From 36b813cafd4fcd745df2eee028bdba1f86ff200d Mon Sep 17 00:00:00 2001 From: liyue Date: Wed, 26 Feb 2025 15:23:34 +0800 Subject: [PATCH 001/268] Fix syntax errors in complex function parameters Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBP2L2 Signed-off-by: liyue Change-Id: I5fb8c8115ac441dd3a666db2fb7daee56977bb5a --- es2panda/parser/parserImpl.cpp | 2 + .../compiler/test-ts-func-param-expected.txt | 2 + .../ts/cases/compiler/test-ts-func-param.ts | 27 + .../parser/ts/test-func-param10-expected.txt | 712 ++++++++++++++++++ es2panda/test/parser/ts/test-func-param10.ts | 27 + .../parser/ts/test-func-param11-expected.txt | 360 +++++++++ es2panda/test/parser/ts/test-func-param11.ts | 19 + 7 files changed, 1149 insertions(+) create mode 100644 es2panda/test/compiler/ts/cases/compiler/test-ts-func-param-expected.txt create mode 100644 es2panda/test/compiler/ts/cases/compiler/test-ts-func-param.ts create mode 100644 es2panda/test/parser/ts/test-func-param10-expected.txt create mode 100644 es2panda/test/parser/ts/test-func-param10.ts create mode 100644 es2panda/test/parser/ts/test-func-param11-expected.txt create mode 100644 es2panda/test/parser/ts/test-func-param11.ts diff --git a/es2panda/parser/parserImpl.cpp b/es2panda/parser/parserImpl.cpp index 5c6a5148cf..270cd2c48a 100644 --- a/es2panda/parser/parserImpl.cpp +++ b/es2panda/parser/parserImpl.cpp @@ -3710,7 +3710,9 @@ ArenaVector ParserImpl::ParseFunctionParams(bool isDeclare, } } + context_.Status() |= ParserStatus::FUNCTION_PARAM; ir::Expression *parameter = ParseFunctionParameter(isDeclare); + context_.Status() &= ~ParserStatus::FUNCTION_PARAM; ValidateFunctionParam(params, parameter, &seenOptional); params.push_back(parameter); diff --git a/es2panda/test/compiler/ts/cases/compiler/test-ts-func-param-expected.txt b/es2panda/test/compiler/ts/cases/compiler/test-ts-func-param-expected.txt new file mode 100644 index 0000000000..25d54ae755 --- /dev/null +++ b/es2panda/test/compiler/ts/cases/compiler/test-ts-func-param-expected.txt @@ -0,0 +1,2 @@ +333 +111 1 diff --git a/es2panda/test/compiler/ts/cases/compiler/test-ts-func-param.ts b/es2panda/test/compiler/ts/cases/compiler/test-ts-func-param.ts new file mode 100644 index 0000000000..717ae2477f --- /dev/null +++ b/es2panda/test/compiler/ts/cases/compiler/test-ts-func-param.ts @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +let a = "111"; +let b = "222"; +let c = true; +function test1() { + print("333") +} +function test2(aa : string = c ? (test1(),a) : (test1(),b), dd:number = 1) { + print(aa, dd); +} + +test2() diff --git a/es2panda/test/parser/ts/test-func-param10-expected.txt b/es2panda/test/parser/ts/test-func-param10-expected.txt new file mode 100644 index 0000000000..2f0ae83bd7 --- /dev/null +++ b/es2panda/test/parser/ts/test-func-param10-expected.txt @@ -0,0 +1,712 @@ +{ + "type": "Program", + "statements": [ + { + "type": "VariableDeclaration", + "declarations": [ + { + "type": "VariableDeclarator", + "id": { + "type": "Identifier", + "name": "a", + "loc": { + "start": { + "line": 17, + "column": 5 + }, + "end": { + "line": 17, + "column": 6 + } + } + }, + "init": { + "type": "StringLiteral", + "value": "111", + "loc": { + "start": { + "line": 17, + "column": 9 + }, + "end": { + "line": 17, + "column": 14 + } + } + }, + "loc": { + "start": { + "line": 17, + "column": 5 + }, + "end": { + "line": 17, + "column": 14 + } + } + } + ], + "kind": "let", + "loc": { + "start": { + "line": 17, + "column": 1 + }, + "end": { + "line": 17, + "column": 15 + } + } + }, + { + "type": "VariableDeclaration", + "declarations": [ + { + "type": "VariableDeclarator", + "id": { + "type": "Identifier", + "name": "b", + "loc": { + "start": { + "line": 18, + "column": 5 + }, + "end": { + "line": 18, + "column": 6 + } + } + }, + "init": { + "type": "StringLiteral", + "value": "222", + "loc": { + "start": { + "line": 18, + "column": 9 + }, + "end": { + "line": 18, + "column": 14 + } + } + }, + "loc": { + "start": { + "line": 18, + "column": 5 + }, + "end": { + "line": 18, + "column": 14 + } + } + } + ], + "kind": "let", + "loc": { + "start": { + "line": 18, + "column": 1 + }, + "end": { + "line": 18, + "column": 15 + } + } + }, + { + "type": "VariableDeclaration", + "declarations": [ + { + "type": "VariableDeclarator", + "id": { + "type": "Identifier", + "name": "c", + "loc": { + "start": { + "line": 19, + "column": 5 + }, + "end": { + "line": 19, + "column": 6 + } + } + }, + "init": { + "type": "BooleanLiteral", + "value": true, + "loc": { + "start": { + "line": 19, + "column": 9 + }, + "end": { + "line": 19, + "column": 13 + } + } + }, + "loc": { + "start": { + "line": 19, + "column": 5 + }, + "end": { + "line": 19, + "column": 13 + } + } + } + ], + "kind": "let", + "loc": { + "start": { + "line": 19, + "column": 1 + }, + "end": { + "line": 19, + "column": 14 + } + } + }, + { + "type": "FunctionDeclaration", + "function": { + "type": "ScriptFunction", + "id": { + "type": "Identifier", + "name": "test1", + "loc": { + "start": { + "line": 20, + "column": 10 + }, + "end": { + "line": 20, + "column": 15 + } + } + }, + "generator": false, + "async": false, + "expression": false, + "params": [], + "body": { + "type": "BlockStatement", + "statements": [ + { + "type": "ExpressionStatement", + "expression": { + "type": "CallExpression", + "callee": { + "type": "Identifier", + "name": "print", + "loc": { + "start": { + "line": 21, + "column": 5 + }, + "end": { + "line": 21, + "column": 10 + } + } + }, + "arguments": [ + { + "type": "StringLiteral", + "value": "333", + "loc": { + "start": { + "line": 21, + "column": 11 + }, + "end": { + "line": 21, + "column": 16 + } + } + } + ], + "optional": false, + "loc": { + "start": { + "line": 21, + "column": 5 + }, + "end": { + "line": 21, + "column": 17 + } + } + }, + "loc": { + "start": { + "line": 21, + "column": 5 + }, + "end": { + "line": 21, + "column": 17 + } + } + } + ], + "loc": { + "start": { + "line": 20, + "column": 18 + }, + "end": { + "line": 22, + "column": 2 + } + } + }, + "loc": { + "start": { + "line": 20, + "column": 1 + }, + "end": { + "line": 22, + "column": 2 + } + } + }, + "loc": { + "start": { + "line": 20, + "column": 1 + }, + "end": { + "line": 22, + "column": 2 + } + } + }, + { + "type": "FunctionDeclaration", + "function": { + "type": "ScriptFunction", + "id": { + "type": "Identifier", + "name": "test2", + "loc": { + "start": { + "line": 23, + "column": 10 + }, + "end": { + "line": 23, + "column": 15 + } + } + }, + "generator": false, + "async": false, + "expression": false, + "params": [ + { + "type": "AssignmentPattern", + "left": { + "type": "Identifier", + "name": "aa", + "typeAnnotation": { + "type": "TSStringKeyword", + "loc": { + "start": { + "line": 23, + "column": 21 + }, + "end": { + "line": 23, + "column": 27 + } + } + }, + "loc": { + "start": { + "line": 23, + "column": 16 + }, + "end": { + "line": 23, + "column": 18 + } + } + }, + "right": { + "type": "ConditionalExpression", + "test": { + "type": "Identifier", + "name": "c", + "loc": { + "start": { + "line": 23, + "column": 30 + }, + "end": { + "line": 23, + "column": 31 + } + } + }, + "consequent": { + "type": "SequenceExpression", + "expressions": [ + { + "type": "CallExpression", + "callee": { + "type": "Identifier", + "name": "test1", + "loc": { + "start": { + "line": 23, + "column": 35 + }, + "end": { + "line": 23, + "column": 40 + } + } + }, + "arguments": [], + "optional": false, + "loc": { + "start": { + "line": 23, + "column": 35 + }, + "end": { + "line": 23, + "column": 42 + } + } + }, + { + "type": "Identifier", + "name": "a", + "loc": { + "start": { + "line": 23, + "column": 43 + }, + "end": { + "line": 23, + "column": 44 + } + } + } + ], + "loc": { + "start": { + "line": 23, + "column": 34 + }, + "end": { + "line": 23, + "column": 45 + } + } + }, + "alternate": { + "type": "SequenceExpression", + "expressions": [ + { + "type": "CallExpression", + "callee": { + "type": "Identifier", + "name": "test1", + "loc": { + "start": { + "line": 23, + "column": 49 + }, + "end": { + "line": 23, + "column": 54 + } + } + }, + "arguments": [], + "optional": false, + "loc": { + "start": { + "line": 23, + "column": 49 + }, + "end": { + "line": 23, + "column": 56 + } + } + }, + { + "type": "Identifier", + "name": "b", + "loc": { + "start": { + "line": 23, + "column": 57 + }, + "end": { + "line": 23, + "column": 58 + } + } + } + ], + "loc": { + "start": { + "line": 23, + "column": 48 + }, + "end": { + "line": 23, + "column": 59 + } + } + }, + "loc": { + "start": { + "line": 23, + "column": 30 + }, + "end": { + "line": 23, + "column": 59 + } + } + }, + "loc": { + "start": { + "line": 23, + "column": 16 + }, + "end": { + "line": 23, + "column": 59 + } + } + }, + { + "type": "AssignmentPattern", + "left": { + "type": "Identifier", + "name": "dd", + "typeAnnotation": { + "type": "TSNumberKeyword", + "loc": { + "start": { + "line": 23, + "column": 64 + }, + "end": { + "line": 23, + "column": 70 + } + } + }, + "loc": { + "start": { + "line": 23, + "column": 61 + }, + "end": { + "line": 23, + "column": 63 + } + } + }, + "right": { + "type": "NumberLiteral", + "value": 1, + "loc": { + "start": { + "line": 23, + "column": 73 + }, + "end": { + "line": 23, + "column": 74 + } + } + }, + "loc": { + "start": { + "line": 23, + "column": 61 + }, + "end": { + "line": 23, + "column": 74 + } + } + } + ], + "body": { + "type": "BlockStatement", + "statements": [ + { + "type": "ExpressionStatement", + "expression": { + "type": "CallExpression", + "callee": { + "type": "Identifier", + "name": "print", + "loc": { + "start": { + "line": 24, + "column": 5 + }, + "end": { + "line": 24, + "column": 10 + } + } + }, + "arguments": [ + { + "type": "Identifier", + "name": "aa", + "loc": { + "start": { + "line": 24, + "column": 11 + }, + "end": { + "line": 24, + "column": 13 + } + } + }, + { + "type": "Identifier", + "name": "dd", + "loc": { + "start": { + "line": 24, + "column": 15 + }, + "end": { + "line": 24, + "column": 17 + } + } + } + ], + "optional": false, + "loc": { + "start": { + "line": 24, + "column": 5 + }, + "end": { + "line": 24, + "column": 18 + } + } + }, + "loc": { + "start": { + "line": 24, + "column": 5 + }, + "end": { + "line": 24, + "column": 19 + } + } + } + ], + "loc": { + "start": { + "line": 23, + "column": 76 + }, + "end": { + "line": 25, + "column": 2 + } + } + }, + "loc": { + "start": { + "line": 23, + "column": 1 + }, + "end": { + "line": 25, + "column": 2 + } + } + }, + "loc": { + "start": { + "line": 23, + "column": 1 + }, + "end": { + "line": 25, + "column": 2 + } + } + }, + { + "type": "ExpressionStatement", + "expression": { + "type": "CallExpression", + "callee": { + "type": "Identifier", + "name": "test2", + "loc": { + "start": { + "line": 27, + "column": 1 + }, + "end": { + "line": 27, + "column": 6 + } + } + }, + "arguments": [], + "optional": false, + "loc": { + "start": { + "line": 27, + "column": 1 + }, + "end": { + "line": 27, + "column": 8 + } + } + }, + "loc": { + "start": { + "line": 27, + "column": 1 + }, + "end": { + "line": 27, + "column": 8 + } + } + } + ], + "loc": { + "start": { + "line": 1, + "column": 1 + }, + "end": { + "line": 28, + "column": 1 + } + } +} diff --git a/es2panda/test/parser/ts/test-func-param10.ts b/es2panda/test/parser/ts/test-func-param10.ts new file mode 100644 index 0000000000..717ae2477f --- /dev/null +++ b/es2panda/test/parser/ts/test-func-param10.ts @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +let a = "111"; +let b = "222"; +let c = true; +function test1() { + print("333") +} +function test2(aa : string = c ? (test1(),a) : (test1(),b), dd:number = 1) { + print(aa, dd); +} + +test2() diff --git a/es2panda/test/parser/ts/test-func-param11-expected.txt b/es2panda/test/parser/ts/test-func-param11-expected.txt new file mode 100644 index 0000000000..610308b8d9 --- /dev/null +++ b/es2panda/test/parser/ts/test-func-param11-expected.txt @@ -0,0 +1,360 @@ +{ + "type": "Program", + "statements": [ + { + "type": "FunctionDeclaration", + "function": { + "type": "ScriptFunction", + "id": { + "type": "Identifier", + "name": "bar", + "loc": { + "start": { + "line": 17, + "column": 10 + }, + "end": { + "line": 17, + "column": 13 + } + } + }, + "generator": false, + "async": false, + "expression": false, + "params": [ + { + "type": "AssignmentPattern", + "left": { + "type": "Identifier", + "name": "fn", + "loc": { + "start": { + "line": 17, + "column": 14 + }, + "end": { + "line": 17, + "column": 16 + } + } + }, + "right": { + "type": "ArrowFunctionExpression", + "function": { + "type": "ScriptFunction", + "id": null, + "generator": false, + "async": false, + "expression": true, + "params": [ + { + "type": "Identifier", + "name": "b", + "typeAnnotation": { + "type": "TSNumberKeyword", + "loc": { + "start": { + "line": 17, + "column": 23 + }, + "end": { + "line": 17, + "column": 29 + } + } + }, + "loc": { + "start": { + "line": 17, + "column": 19 + }, + "end": { + "line": 17, + "column": 30 + } + } + } + ], + "body": { + "type": "BinaryExpression", + "operator": "+", + "left": { + "type": "Identifier", + "name": "b", + "loc": { + "start": { + "line": 17, + "column": 34 + }, + "end": { + "line": 17, + "column": 35 + } + } + }, + "right": { + "type": "NumberLiteral", + "value": 1, + "loc": { + "start": { + "line": 17, + "column": 38 + }, + "end": { + "line": 17, + "column": 39 + } + } + }, + "loc": { + "start": { + "line": 17, + "column": 34 + }, + "end": { + "line": 17, + "column": 39 + } + } + }, + "loc": { + "start": { + "line": 17, + "column": 19 + }, + "end": { + "line": 17, + "column": 39 + } + } + }, + "loc": { + "start": { + "line": 17, + "column": 19 + }, + "end": { + "line": 17, + "column": 39 + } + } + }, + "loc": { + "start": { + "line": 17, + "column": 14 + }, + "end": { + "line": 17, + "column": 39 + } + } + }, + { + "type": "Identifier", + "name": "a", + "typeAnnotation": { + "type": "TSStringKeyword", + "loc": { + "start": { + "line": 17, + "column": 44 + }, + "end": { + "line": 17, + "column": 50 + } + } + }, + "loc": { + "start": { + "line": 17, + "column": 41 + }, + "end": { + "line": 17, + "column": 42 + } + } + } + ], + "body": { + "type": "BlockStatement", + "statements": [ + { + "type": "ExpressionStatement", + "expression": { + "type": "CallExpression", + "callee": { + "type": "MemberExpression", + "object": { + "type": "Identifier", + "name": "console", + "loc": { + "start": { + "line": 18, + "column": 5 + }, + "end": { + "line": 18, + "column": 12 + } + } + }, + "property": { + "type": "Identifier", + "name": "log", + "loc": { + "start": { + "line": 18, + "column": 13 + }, + "end": { + "line": 18, + "column": 16 + } + } + }, + "computed": false, + "optional": false, + "loc": { + "start": { + "line": 18, + "column": 5 + }, + "end": { + "line": 18, + "column": 16 + } + } + }, + "arguments": [ + { + "type": "CallExpression", + "callee": { + "type": "Identifier", + "name": "fn", + "loc": { + "start": { + "line": 18, + "column": 17 + }, + "end": { + "line": 18, + "column": 19 + } + } + }, + "arguments": [ + { + "type": "NumberLiteral", + "value": 5, + "loc": { + "start": { + "line": 18, + "column": 20 + }, + "end": { + "line": 18, + "column": 21 + } + } + } + ], + "optional": false, + "loc": { + "start": { + "line": 18, + "column": 17 + }, + "end": { + "line": 18, + "column": 22 + } + } + }, + { + "type": "Identifier", + "name": "a", + "loc": { + "start": { + "line": 18, + "column": 24 + }, + "end": { + "line": 18, + "column": 25 + } + } + } + ], + "optional": false, + "loc": { + "start": { + "line": 18, + "column": 5 + }, + "end": { + "line": 18, + "column": 26 + } + } + }, + "loc": { + "start": { + "line": 18, + "column": 5 + }, + "end": { + "line": 18, + "column": 27 + } + } + } + ], + "loc": { + "start": { + "line": 17, + "column": 52 + }, + "end": { + "line": 19, + "column": 2 + } + } + }, + "loc": { + "start": { + "line": 17, + "column": 1 + }, + "end": { + "line": 19, + "column": 2 + } + } + }, + "loc": { + "start": { + "line": 17, + "column": 1 + }, + "end": { + "line": 19, + "column": 2 + } + } + } + ], + "loc": { + "start": { + "line": 1, + "column": 1 + }, + "end": { + "line": 20, + "column": 1 + } + } +} diff --git a/es2panda/test/parser/ts/test-func-param11.ts b/es2panda/test/parser/ts/test-func-param11.ts new file mode 100644 index 0000000000..4e36915b21 --- /dev/null +++ b/es2panda/test/parser/ts/test-func-param11.ts @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +function bar(fn = (b: number) => b + 1, a: string) { + console.log(fn(5), a); +} -- Gitee From b76581c291b5c5ff93b447a1b0e29507aa2d60b6 Mon Sep 17 00:00:00 2001 From: hanlong Date: Sat, 15 Mar 2025 15:22:29 +0800 Subject: [PATCH 002/268] DEL KFL 0315 Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBTLIG?from=project-issue Signed-off-by: hanlong --- ...ly_workload-fastverify-qemu-aot-litecg.txt | 38 +------------------ 1 file changed, 1 insertion(+), 37 deletions(-) diff --git a/test/workload/ignored-weekly_workload-fastverify-qemu-aot-litecg.txt b/test/workload/ignored-weekly_workload-fastverify-qemu-aot-litecg.txt index fd0d0c4437..25fdaeede1 100644 --- a/test/workload/ignored-weekly_workload-fastverify-qemu-aot-litecg.txt +++ b/test/workload/ignored-weekly_workload-fastverify-qemu-aot-litecg.txt @@ -1,38 +1,2 @@ -#18546 -air -crypto - -##18863 -json-parse-inspector - -#18745 -json-stringify-inspector - -#21663 -mandreel - -#21456 -crypto-aes -splay-latency -stanford-crypto-pbkdf2 - -##21577 -OfflineAssembler - -##19010 -box2d - -##19398 -raytrace - -##18740 -splay -##21607 -pdfjs - -##19862 -typescript-compiler - -##19216 +#19216 wsl - -- Gitee From 8002b394e6a7e3a2b4a8f3e8242b5940e620c4a0 Mon Sep 17 00:00:00 2001 From: guanmingyue Date: Fri, 21 Mar 2025 15:44:28 +0800 Subject: [PATCH 003/268] Update kfl 0321 Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBVA0E Signed-off-by: guanmingyue --- .../ignored-third_lib_js-fastverify-arm64-aot-litecg.txt | 6 ++++++ .../ignored-third_lib_js-fastverify-arm64-int.txt | 9 +++++++++ .../ignored-third_lib_js-fastverify-arm64-jit.txt | 3 +++ .../ignored-weekly_workload-fastverify-qemu-int.txt | 2 +- 4 files changed, 19 insertions(+), 1 deletion(-) diff --git a/test/workload/ignored-third_lib_js-fastverify-arm64-aot-litecg.txt b/test/workload/ignored-third_lib_js-fastverify-arm64-aot-litecg.txt index 9927aa890d..b191ecdf7f 100644 --- a/test/workload/ignored-third_lib_js-fastverify-arm64-aot-litecg.txt +++ b/test/workload/ignored-third_lib_js-fastverify-arm64-aot-litecg.txt @@ -3,3 +3,9 @@ jsDiff_test #21663 crypto-js_test + +#21251 +validator_test + +#24119 +dayjs_test diff --git a/test/workload/ignored-third_lib_js-fastverify-arm64-int.txt b/test/workload/ignored-third_lib_js-fastverify-arm64-int.txt index 9927aa890d..d1b258aa07 100644 --- a/test/workload/ignored-third_lib_js-fastverify-arm64-int.txt +++ b/test/workload/ignored-third_lib_js-fastverify-arm64-int.txt @@ -3,3 +3,12 @@ jsDiff_test #21663 crypto-js_test + +#21251 +validator_test + +#24119 +dayjs_test + +#23119 +jBox2d_test diff --git a/test/workload/ignored-third_lib_js-fastverify-arm64-jit.txt b/test/workload/ignored-third_lib_js-fastverify-arm64-jit.txt index 663ffbdc59..8b70b6b844 100644 --- a/test/workload/ignored-third_lib_js-fastverify-arm64-jit.txt +++ b/test/workload/ignored-third_lib_js-fastverify-arm64-jit.txt @@ -37,3 +37,6 @@ validator_test #23990 hamcrest_test + +#24119 +dayjs_test diff --git a/test/workload/ignored-weekly_workload-fastverify-qemu-int.txt b/test/workload/ignored-weekly_workload-fastverify-qemu-int.txt index 157cf3e6fb..656e14bbd8 100644 --- a/test/workload/ignored-weekly_workload-fastverify-qemu-int.txt +++ b/test/workload/ignored-weekly_workload-fastverify-qemu-int.txt @@ -4,7 +4,7 @@ float-mm #21131 wsl -#21131 +#23119 stanford-crypto-pbkdf2 ##18863 -- Gitee From ea5abcc364d6f43e85755ef235413938f69682c0 Mon Sep 17 00:00:00 2001 From: liyue Date: Sun, 23 Mar 2025 20:19:30 +0800 Subject: [PATCH 004/268] Fix syntax error with readonly as optional param Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBVLPU Signed-off-by: liyue Change-Id: I652a9ba97f576a9e87d9393c41759b9072712f85 --- es2panda/parser/parserImpl.cpp | 2 +- ...st-readonly-optional-property-expected.txt | 101 ++++++++++++++++++ .../ts/test-readonly-optional-property.ts | 19 ++++ 3 files changed, 121 insertions(+), 1 deletion(-) create mode 100644 es2panda/test/parser/ts/test-readonly-optional-property-expected.txt create mode 100644 es2panda/test/parser/ts/test-readonly-optional-property.ts diff --git a/es2panda/parser/parserImpl.cpp b/es2panda/parser/parserImpl.cpp index 0784e69c5c..f119c8e1ef 100644 --- a/es2panda/parser/parserImpl.cpp +++ b/es2panda/parser/parserImpl.cpp @@ -1488,7 +1488,7 @@ ir::Expression *ParserImpl::ParseTsTypeLiteralOrInterfaceMember() char32_t nextToken = lexer_->Lookahead(); if (lexer_->GetToken().KeywordType() == lexer::TokenType::KEYW_READONLY && nextToken != LEX_CHAR_LEFT_PAREN && nextToken != LEX_CHAR_COLON && nextToken != LEX_CHAR_COMMA && nextToken != LEX_CHAR_LESS_THAN && - nextToken != LEX_CHAR_SEMICOLON) { + nextToken != LEX_CHAR_SEMICOLON && nextToken != LEX_CHAR_QUESTION) { readonly = true; lexer_->NextToken(lexer::LexerNextTokenFlags::KEYWORD_TO_IDENT); } diff --git a/es2panda/test/parser/ts/test-readonly-optional-property-expected.txt b/es2panda/test/parser/ts/test-readonly-optional-property-expected.txt new file mode 100644 index 0000000000..970e539cff --- /dev/null +++ b/es2panda/test/parser/ts/test-readonly-optional-property-expected.txt @@ -0,0 +1,101 @@ +{ + "type": "Program", + "statements": [ + { + "type": "TSInterfaceDeclaration", + "body": { + "type": "TSInterfaceBody", + "body": [ + { + "type": "TSPropertySignature", + "computed": false, + "optional": true, + "readonly": false, + "key": { + "type": "Identifier", + "name": "readonly", + "loc": { + "start": { + "line": 18, + "column": 2 + }, + "end": { + "line": 18, + "column": 10 + } + } + }, + "typeAnnotation": { + "type": "TSNumberKeyword", + "loc": { + "start": { + "line": 18, + "column": 13 + }, + "end": { + "line": 18, + "column": 19 + } + } + }, + "loc": { + "start": { + "line": 18, + "column": 2 + }, + "end": { + "line": 18, + "column": 20 + } + } + } + ], + "loc": { + "start": { + "line": 17, + "column": 16 + }, + "end": { + "line": 19, + "column": 2 + } + } + }, + "id": { + "type": "Identifier", + "name": "test", + "loc": { + "start": { + "line": 17, + "column": 11 + }, + "end": { + "line": 17, + "column": 15 + } + } + }, + "extends": [], + "loc": { + "start": { + "line": 17, + "column": 1 + }, + "end": { + "line": 19, + "column": 2 + } + } + } + ], + "loc": { + "start": { + "line": 1, + "column": 1 + }, + "end": { + "line": 19, + "column": 2 + } + } +} diff --git a/es2panda/test/parser/ts/test-readonly-optional-property.ts b/es2panda/test/parser/ts/test-readonly-optional-property.ts new file mode 100644 index 0000000000..2f9df72f3a --- /dev/null +++ b/es2panda/test/parser/ts/test-readonly-optional-property.ts @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +interface test { + readonly?: number; +} \ No newline at end of file -- Gitee From fcb1e828af66eff9e7aa5a0f3f24ec7a7db10b40 Mon Sep 17 00:00:00 2001 From: hanlong Date: Tue, 25 Mar 2025 14:28:46 +0800 Subject: [PATCH 005/268] Update KFL 0325 Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBW3P6?from=project-issue Signed-off-by: hanlong --- test262/ignored-test262-fastverify-x64-aot-pgo-litecg.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test262/ignored-test262-fastverify-x64-aot-pgo-litecg.txt b/test262/ignored-test262-fastverify-x64-aot-pgo-litecg.txt index 8b13789179..c9e09aa947 100644 --- a/test262/ignored-test262-fastverify-x64-aot-pgo-litecg.txt +++ b/test262/ignored-test262-fastverify-x64-aot-pgo-litecg.txt @@ -1 +1,2 @@ - +#19208 +test262/data/test_es2021/language/module-code/instn-iee-err-circular-as.js -- Gitee From 32603453057e3d02d49d5df5530f4c6e4db72a68 Mon Sep 17 00:00:00 2001 From: hanlong Date: Mon, 24 Mar 2025 15:56:23 +0800 Subject: [PATCH 006/268] DEL KFL Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBRIGN?from=project-issue Signed-off-by: hanlong --- ...ored-third_lib_js-fastverify-arm64-jit.txt | 25 ------------------- ...ed-weekly_workload-fastverify-qemu-int.txt | 6 ++--- 2 files changed, 2 insertions(+), 29 deletions(-) diff --git a/test/workload/ignored-third_lib_js-fastverify-arm64-jit.txt b/test/workload/ignored-third_lib_js-fastverify-arm64-jit.txt index 663ffbdc59..b8701d7ffc 100644 --- a/test/workload/ignored-third_lib_js-fastverify-arm64-jit.txt +++ b/test/workload/ignored-third_lib_js-fastverify-arm64-jit.txt @@ -1,34 +1,9 @@ -# Known failures list for third_lib_js-debug-arm64-jit #21456 -hi-base32_test gson_test -#19231 -jBox2d_test - -#18383 -memory-cache_test - -#18383 -memory-cache_test - -#21456 -js-sha256_test - -#21663 -jsDiff_test -crypto-js_test - #19623 rebound_test -#20374 -base64_test - -#21663 -mathjs_test -pdview_test - #20690 dayjs_test diff --git a/test/workload/ignored-weekly_workload-fastverify-qemu-int.txt b/test/workload/ignored-weekly_workload-fastverify-qemu-int.txt index 157cf3e6fb..a44872b66b 100644 --- a/test/workload/ignored-weekly_workload-fastverify-qemu-int.txt +++ b/test/workload/ignored-weekly_workload-fastverify-qemu-int.txt @@ -1,11 +1,9 @@ #21131 float-mm - -#21131 wsl -#21131 +#23119 stanford-crypto-pbkdf2 -##18863 +#18863 json-parse-inspector -- Gitee From a7c5a8aa3b63c15ecd76a98942ef827d478f48da Mon Sep 17 00:00:00 2001 From: ElevenDuan Date: Tue, 25 Mar 2025 20:35:46 +0800 Subject: [PATCH 007/268] Fix modify pkgName bug Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBW8QP?from=project-issue Change-Id: Iad0763f560715920b4e26549d35294224031b69e Signed-off-by: ElevenDuan --- .../abcinputs/main_hap.txt | 2 + .../abcinputs/sdk_hap.txt | 2 + .../main_hap-expected.pa.txt | 306 ++++++++++++++++++ .../main_hap.ts | 22 ++ .../main_hap_import_file.ts | 19 ++ .../modify_pkg_name.txt | 1 + .../recordnames.txt | 4 + .../sdk_hap.ts | 22 ++ .../sdk_hap_import_file.ts | 19 ++ 9 files changed, 397 insertions(+) create mode 100644 es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/abcinputs/main_hap.txt create mode 100644 es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/abcinputs/sdk_hap.txt create mode 100644 es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/main_hap-expected.pa.txt create mode 100644 es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/main_hap.ts create mode 100644 es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/main_hap_import_file.ts create mode 100644 es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/modify_pkg_name.txt create mode 100644 es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/recordnames.txt create mode 100644 es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/sdk_hap.ts create mode 100644 es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/sdk_hap_import_file.ts diff --git a/es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/abcinputs/main_hap.txt b/es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/abcinputs/main_hap.txt new file mode 100644 index 0000000000..8cf0b55aaa --- /dev/null +++ b/es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/abcinputs/main_hap.txt @@ -0,0 +1,2 @@ +main_hap.ts +main_hap_import_file.ts diff --git a/es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/abcinputs/sdk_hap.txt b/es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/abcinputs/sdk_hap.txt new file mode 100644 index 0000000000..128e160248 --- /dev/null +++ b/es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/abcinputs/sdk_hap.txt @@ -0,0 +1,2 @@ +sdk_hap.ts +sdk_hap_import_file.ts diff --git a/es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/main_hap-expected.pa.txt b/es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/main_hap-expected.pa.txt new file mode 100644 index 0000000000..f8c85e90b8 --- /dev/null +++ b/es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/main_hap-expected.pa.txt @@ -0,0 +1,306 @@ +slotNum = 0x2 +.language ECMAScript +.function any &src_hap_to/main_hap&.#*#main(any a0, any a1, any a2) { + ldexternalmodulevar 0x0 + sta v0 + throw.undefinedifholewithname mainHapAddTest + lda v0 + callarg0 0x0 + returnundefined +} + +slotNum = 0x3 +.language ECMAScript +.function any &src_hap_to/main_hap&.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, &src_hap_to/main_hap&.#*#main, 0x0 + callarg0 0x1 + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &src_hap_to/main_hap&_1084 +------------------------------------ +slot &src_hap_to/main_hap&_1088 +{ + index: 0 + tag: 2 + val: 1 +}, +{ + index: 1 + tag: 5 + val: &src_hap_to/main_hap_import_file& +}, +{ + index: 2 + tag: 2 + val: 1 +}, +{ + index: 3 + tag: 5 + val: mainHapAddTest +}, +{ + index: 4 + tag: 5 + val: mainHapAddTest +}, +{ + index: 5 + tag: 9 + val: 0 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +{ + index: 8 + tag: 2 + val: 0 +}, +{ + index: 9 + tag: 2 + val: 0 +}, +======> strings <====== +"&src_hap_to/main_hap&.#*#main"; "mainHapAddTest"; +slotNum = 0x1 +.language ECMAScript +.function any &src_hap_to/main_hap_import_file&.#*#mainHapAddTest(any a0, any a1, any a2, any a3, any a4) { + lda a4 + add2 0x0, a3 + return +} + +slotNum = 0x1 +.language ECMAScript +.function any &src_hap_to/main_hap_import_file&.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, &src_hap_to/main_hap_import_file&.#*#mainHapAddTest, 0x2 + stmodulevar 0x0 + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &src_hap_to/main_hap_import_file&_1130 +------------------------------------ +slot &src_hap_to/main_hap_import_file&_1134 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 1 +}, +{ + index: 4 + tag: 5 + val: mainHapAddTest +}, +{ + index: 5 + tag: 5 + val: mainHapAddTest +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +======> strings <====== +"&src_hap_to/main_hap_import_file&.#*#mainHapAddTest"; + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x2 +.language ECMAScript +.function any &src_hap_to/sdk_hap&.#*#main(any a0, any a1, any a2) { + ldexternalmodulevar 0x0 + sta v0 + throw.undefinedifholewithname sdkHapAddTest + lda v0 + callarg0 0x0 + returnundefined +} + +slotNum = 0x3 +.language ECMAScript +.function any &src_hap_to/sdk_hap&.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, &src_hap_to/sdk_hap&.#*#main, 0x0 + callarg0 0x1 + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &src_hap_to/sdk_hap&_1051 +------------------------------------ +slot &src_hap_to/sdk_hap&_1055 +{ + index: 0 + tag: 2 + val: 1 +}, +{ + index: 1 + tag: 5 + val: &src_hap/sdk_hap_import_file& +}, +{ + index: 2 + tag: 2 + val: 1 +}, +{ + index: 3 + tag: 5 + val: sdkHapAddTest +}, +{ + index: 4 + tag: 5 + val: sdkHapAddTest +}, +{ + index: 5 + tag: 9 + val: 0 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +{ + index: 8 + tag: 2 + val: 0 +}, +{ + index: 9 + tag: 2 + val: 0 +}, +======> strings <====== +"&src_hap_to/sdk_hap&.#*#main"; "sdkHapAddTest"; +slotNum = 0x1 +.language ECMAScript +.function any &src_hap_to/sdk_hap_import_file&.#*#sdkHapAddTest(any a0, any a1, any a2, any a3, any a4) { + lda a4 + add2 0x0, a3 + return +} + +slotNum = 0x1 +.language ECMAScript +.function any &src_hap_to/sdk_hap_import_file&.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, &src_hap_to/sdk_hap_import_file&.#*#sdkHapAddTest, 0x2 + stmodulevar 0x0 + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &src_hap_to/sdk_hap_import_file&_1097 +------------------------------------ +slot &src_hap_to/sdk_hap_import_file&_1101 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 1 +}, +{ + index: 4 + tag: 5 + val: sdkHapAddTest +}, +{ + index: 5 + tag: 5 + val: sdkHapAddTest +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +======> strings <====== +"&src_hap_to/sdk_hap_import_file&.#*#sdkHapAddTest"; + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + diff --git a/es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/main_hap.ts b/es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/main_hap.ts new file mode 100644 index 0000000000..71370610b2 --- /dev/null +++ b/es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/main_hap.ts @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {mainHapAddTest} from '&src_hap_to/main_hap_import_file&' + +function main(): void { + mainHapAddTest(); +} + +main() diff --git a/es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/main_hap_import_file.ts b/es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/main_hap_import_file.ts new file mode 100644 index 0000000000..b27f3ac054 --- /dev/null +++ b/es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/main_hap_import_file.ts @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export function mainHapAddTest(a: number, b: number): number +{ + return a + b; +} \ No newline at end of file diff --git a/es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/modify_pkg_name.txt b/es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/modify_pkg_name.txt new file mode 100644 index 0000000000..7a945914df --- /dev/null +++ b/es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/modify_pkg_name.txt @@ -0,0 +1 @@ +src_hap:src_hap_to diff --git a/es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/recordnames.txt b/es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/recordnames.txt new file mode 100644 index 0000000000..0fc5ee2821 --- /dev/null +++ b/es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/recordnames.txt @@ -0,0 +1,4 @@ +main_hap:&src_hap_to/main_hap& +main_hap_import_file:&src_hap_to/main_hap_import_file& +sdk_hap:&src_hap/sdk_hap& +sdk_hap_import_file:&src_hap/sdk_hap_import_file& diff --git a/es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/sdk_hap.ts b/es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/sdk_hap.ts new file mode 100644 index 0000000000..8087e36196 --- /dev/null +++ b/es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/sdk_hap.ts @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {sdkHapAddTest} from '&src_hap/sdk_hap_import_file&' + +function main(): void { + sdkHapAddTest(); +} + +main() diff --git a/es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/sdk_hap_import_file.ts b/es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/sdk_hap_import_file.ts new file mode 100644 index 0000000000..041a885320 --- /dev/null +++ b/es2panda/test/compiler/merge_hap/projects/merge_hap_replace_perfix_pkg_name/sdk_hap_import_file.ts @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export function sdkHapAddTest(a: number, b: number): number +{ + return a + b; +} \ No newline at end of file -- Gitee From d74067342309c733e28428346b3395dcaffecc2f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=A9=AC=E5=BF=97=E4=BC=9F?= Date: Wed, 26 Mar 2025 15:02:02 +0800 Subject: [PATCH 008/268] Get off the kfl MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBWFSZ?from=project-issue Signed-off-by: 马志伟 --- .../ignored-third_lib_js-fastverify-x64-aot-litecg.txt | 3 --- 1 file changed, 3 deletions(-) diff --git a/test/workload/ignored-third_lib_js-fastverify-x64-aot-litecg.txt b/test/workload/ignored-third_lib_js-fastverify-x64-aot-litecg.txt index 0297a12cfc..9c0352849e 100644 --- a/test/workload/ignored-third_lib_js-fastverify-x64-aot-litecg.txt +++ b/test/workload/ignored-third_lib_js-fastverify-x64-aot-litecg.txt @@ -1,5 +1,2 @@ #19251 pdfview_test - -#19247 -jsDiff_test -- Gitee From 46d4ff5cab1606e3d0f454f4cae30ae657d726da Mon Sep 17 00:00:00 2001 From: Dmitry Kovalenko Date: Thu, 27 Mar 2025 09:46:01 +0300 Subject: [PATCH 009/268] Add liwentao_uiw to linter reviewers list Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBWQAX Signed-off-by: Dmitry Kovalenko --- ets2panda/REVIEWERS | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ets2panda/REVIEWERS b/ets2panda/REVIEWERS index 8d77d32339..dd6b82d699 100644 --- a/ets2panda/REVIEWERS +++ b/ets2panda/REVIEWERS @@ -36,7 +36,7 @@ /ets2panda/checker/ETSAnalyzer.cpp @akmaevaleksey ^vpukhov ^igelhaus ^Prof1983 /ets2panda/declgen_ets2ts/ @dreamdoomwalker ^trubachevilya ^ivagin ^hufeng20 ^igelhaus ^Prof1983 /ets2panda/driver/ ^trubachevilya @dreamdoomwalker @chenqy930 @hufeng20 ^igelhaus ^Prof1983 -/ets2panda/linter/ @ragnvald @rosinskiyigor @eokolnov1 +/ets2panda/linter/ @ragnvald @rosinskiyigor @eokolnov1 @liwentao_uiw /ets2panda/parser/ETSparser*.* @zelentsovdmitry ^igelhaus ^Prof1983 @chernykhsergey /ets2panda/parser/expressionParser.cpp @zelentsovdmitry ^igelhaus ^Prof1983 @chernykhsergey /ets2panda/parser/parser*.* @zelentsovdmitry ^igelhaus ^Prof1983 @chernykhsergey -- Gitee From 6866cf80d9756139a862697c3a49f11718d90063 Mon Sep 17 00:00:00 2001 From: guanmingyue Date: Fri, 28 Mar 2025 14:35:56 +0800 Subject: [PATCH 010/268] Update kfl 0328 Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBX0UL Signed-off-by: guanmingyue --- ...ored-app_workload-fastverify-qemu-aot-litecg.txt | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/test/workload/ignored-app_workload-fastverify-qemu-aot-litecg.txt b/test/workload/ignored-app_workload-fastverify-qemu-aot-litecg.txt index f1740c568c..8b13789179 100644 --- a/test/workload/ignored-app_workload-fastverify-qemu-aot-litecg.txt +++ b/test/workload/ignored-app_workload-fastverify-qemu-aot-litecg.txt @@ -1,12 +1 @@ -#21456 -sort_pcfilemanager -arkui -bili -tranform_zsyh -bili_kntr -testfileinfo -gaode -OneItems_zsyh -welink -lottie -shimo + -- Gitee From 843610780ec0fa460599b4ac12284f7b30b78c15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Czhuzhihui7=E2=80=9D?= Date: Mon, 24 Mar 2025 19:03:45 +0800 Subject: [PATCH 011/268] Support obfuscation performance metrics fix MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Issue: IBVZ4H Signed-off-by: “zhuzhihui7” --- arkguard/src/ArkObfuscator.ts | 11 ++- .../src/configs/INameObfuscationOption.ts | 8 -- arkguard/src/configs/IOptions.ts | 4 - arkguard/src/initialization/Initializer.ts | 17 +--- arkguard/src/utils/PrinterTimeAndMemUtils.ts | 48 ++++++++--- .../ut/utils/PrinterTimeAndmemUtils.spec.ts | 85 +++++++++++++------ 6 files changed, 107 insertions(+), 66 deletions(-) diff --git a/arkguard/src/ArkObfuscator.ts b/arkguard/src/ArkObfuscator.ts index 708aa9ce89..2c5ee888fb 100644 --- a/arkguard/src/ArkObfuscator.ts +++ b/arkguard/src/ArkObfuscator.ts @@ -74,6 +74,7 @@ import { EventList, TimeAndMemTimeTracker, clearTimeAndMemPrinterData, + disablePrinterTimeAndMemConfig, initPerformanceTimeAndMemPrinter, } from './utils/PrinterTimeAndMemUtils'; @@ -89,9 +90,11 @@ export { } from './utils/PrinterUtils'; export { EventList, + PerfMode, TimeAndMemTimeTracker, - enableTimeAndMemoryPrint, blockTimeAndMemPrinter, + configurePerformancePrinter, + enableTimeAndMemoryPrint, } from './utils/PrinterTimeAndMemUtils'; import { Extension, type ProjectInfo, type FilePathObj } from './common/type'; export { type HvigorErrorInfo } from './common/type'; @@ -111,7 +114,7 @@ export { separateUniversalReservedItem, containWildcards, wildcardTransformer } export type { ReservedNameInfo } from './utils/TransformUtil'; export type { ReseverdSetForArkguard } from './common/ApiReader'; -export { initObfuscationConfig, initPrinterTimeAndMemConfig, printerTimeAndMemConfig, printerTimeAndMemDataConfig } from './initialization/Initializer'; +export { initObfuscationConfig, printerTimeAndMemDataConfig } from './initialization/Initializer'; export { nameCacheMap, unobfuscationNamesObj } from './initialization/CommonObject'; export { collectResevedFileNameInIDEConfig, // For running unit test. @@ -170,6 +173,7 @@ export function clearGlobalCaches(): void { clearUnobfuscationNamesObj(); clearHistoryUnobfuscatedMap(); clearTimeAndMemPrinterData(); + disablePrinterTimeAndMemConfig(); ApiExtractor.mConstructorPropertySet.clear(); ApiExtractor.mEnumMemberSet.clear(); } @@ -360,9 +364,8 @@ export class ArkObfuscator { this.mTransformers = new TransformerManager(this.mCustomProfiles).getTransformers(); initPerformancePrinter(this.mCustomProfiles); - - initPerformanceTimeAndMemPrinter(this.mCustomProfiles); + initPerformanceTimeAndMemPrinter(); if (needReadApiInfo(this.mCustomProfiles)) { // if -enable-property-obfuscation or -enable-export-obfuscation, collect language reserved keywords. let languageSet: Set = new Set(); diff --git a/arkguard/src/configs/INameObfuscationOption.ts b/arkguard/src/configs/INameObfuscationOption.ts index 3056b1f4fc..43efec111d 100644 --- a/arkguard/src/configs/INameObfuscationOption.ts +++ b/arkguard/src/configs/INameObfuscationOption.ts @@ -87,14 +87,6 @@ export interface IPrinterOption { readonly mOutputPath?: string; } -export interface IPrinterTimeAndMemOption { - // Print obfuscation time&memory performance data of files - readonly mFilesPrinter?: boolean; - - // Print obfuscation time&memory performance data of single file - readonly mSingleFilePrinter?: boolean; -} - /** * It records which files cannot be obfuscated (except for file name obfuscation) and their dependent files. * The names and properties exported in the dependent files are put into the whitelist. diff --git a/arkguard/src/configs/IOptions.ts b/arkguard/src/configs/IOptions.ts index 7728824aae..ba4c9f2207 100644 --- a/arkguard/src/configs/IOptions.ts +++ b/arkguard/src/configs/IOptions.ts @@ -16,7 +16,6 @@ import type { IFileNameObfuscationOption, IPrinterOption, - IPrinterTimeAndMemOption, INameObfuscationOption, IKeepSourcePathsAndDependency, IDeclarationCommentOption, @@ -62,9 +61,6 @@ export interface IOptions { // Time&Memory printer option readonly mPerformancePrinter?: IPrinterOption; - // Time&Memory performance printer option - readonly mPerformanceTimeAndMemPrinter?: IPrinterTimeAndMemOption; - // The code of the file is not obfuscated, except for file name obfuscation mKeepFileSourceCode?: IKeepSourcePathsAndDependency diff --git a/arkguard/src/initialization/Initializer.ts b/arkguard/src/initialization/Initializer.ts index f8eef2a751..cb437e847e 100644 --- a/arkguard/src/initialization/Initializer.ts +++ b/arkguard/src/initialization/Initializer.ts @@ -20,7 +20,7 @@ import { ArkObfuscator, blockPrinter, renameIdentifierModule } from '../ArkObfus import { collectResevedFileNameInIDEConfig, MergedConfig, ObConfigResolver, readNameCache } from './ConfigResolver'; import { type IOptions } from '../configs/IOptions'; import type { HvigorErrorInfo } from '../common/type'; -import { getObfuscationCacheDir } from '../utils/PrinterTimeAndMemUtils'; +import { blockTimeAndMemPrinter, getObfuscationCacheDir } from '../utils/PrinterTimeAndMemUtils'; // Record all unobfuscated properties and reasons. export const historyUnobfuscatedPropMap: Map = new Map(); @@ -44,13 +44,6 @@ export const printerConfig = { mOutputPath: '', }; -export const printerTimeAndMemConfig = { - // A sub-switch of mTimeAndMemPrinter used to control the obfuscation performance printing of files - mFilesPrinter: false, - // A sub-switch of mTimeAndMemPrinter used to control the obfuscation performance printing of singlefile - mSingleFilePrinter: false, -}; - export const printerTimeAndMemDataConfig = { // The switch for printing obfuscation performance data and memory data mTimeAndMemPrinter: false, @@ -58,12 +51,6 @@ export const printerTimeAndMemDataConfig = { mMoreTimePrint: false, }; -// Initialize the configuration of the TimeAndMem performance printer -export function initPrinterTimeAndMemConfig() { - printerTimeAndMemConfig.mFilesPrinter = true; - printerTimeAndMemConfig.mSingleFilePrinter = true; - printerTimeAndMemDataConfig.mTimeAndMemPrinter = true; -} export function initObfuscationConfig(projectConfig: any, arkProjectConfig: any, printObfLogger: Function): void { const obConfig: ObConfigResolver = new ObConfigResolver(projectConfig, printObfLogger, true); @@ -72,6 +59,7 @@ export function initObfuscationConfig(projectConfig: any, arkProjectConfig: any, getObfuscationCacheDir(projectConfig); if (mergedObConfig.options.disableObfuscation) { blockPrinter(); + blockTimeAndMemPrinter(); return; } @@ -139,7 +127,6 @@ function initArkGuardConfig( }, mExportObfuscation: mergedObConfig.options.enableExportObfuscation, mPerformancePrinter: printerConfig, - mPerformanceTimeAndMemPrinter: printerTimeAndMemConfig, mKeepFileSourceCode: { mKeepSourceOfPaths: new Set(), mkeepFilesAndDependencies: new Set(), diff --git a/arkguard/src/utils/PrinterTimeAndMemUtils.ts b/arkguard/src/utils/PrinterTimeAndMemUtils.ts index 3d5b31c78f..83d98daadd 100644 --- a/arkguard/src/utils/PrinterTimeAndMemUtils.ts +++ b/arkguard/src/utils/PrinterTimeAndMemUtils.ts @@ -20,6 +20,12 @@ import type { IPrinterOption } from '../configs/INameObfuscationOption'; import { performanceTimeAndMemPrinter } from '../ArkObfuscator'; import { printerTimeAndMemDataConfig } from '../initialization/Initializer'; +// DevEco Studio perf mode +export enum PerfMode { + NORMAL = 0, // Normal mode + ADVANCED = 1, // Advanced mode +}; + export enum EventList { OBFUSCATION_INITIALIZATION = 'Obfuscation initialization', SCAN_SYSTEMAPI = 'Scan system api', @@ -194,21 +200,28 @@ export class TimeAndMemTimeTracker { /** * Initialize performance printer */ -export function initPerformanceTimeAndMemPrinter(mCustomProfiles: IOptions): void { - const printerConfig: IPrinterOption | undefined = mCustomProfiles.mPerformanceTimeAndMemPrinter; - - // If no performance printer configuration is provided, disable the printer and return. - if (!printerConfig) { +export function initPerformanceTimeAndMemPrinter(): void { + if (!printerTimeAndMemDataConfig.mTimeAndMemPrinter) { blockTimeAndMemPrinter(); - return; } +} - // Disable performance printer if no specific printer types (files, single file) are enabled. - const isPrinterDisabled = !(printerConfig.mFilesPrinter || printerConfig.mSingleFilePrinter); +/** + * Configures the performance printer based on the specified performance mode + */ +export function configurePerformancePrinter(perf: number): void { + if (perf === PerfMode.ADVANCED) { + initPrinterTimeAndMemConfig(); - if (isPrinterDisabled) { + // If singleFilePrinter and filesPrinter do not exist, create the corresponding instance + if (!performanceTimeAndMemPrinter.singleFilePrinter) { + performanceTimeAndMemPrinter.singleFilePrinter = new TimeAndMemTimeTracker(); + } + if (!performanceTimeAndMemPrinter.filesPrinter) { + performanceTimeAndMemPrinter.filesPrinter = new TimeAndMemTimeTracker(); + } + } else { blockTimeAndMemPrinter(); - return; } } @@ -216,6 +229,7 @@ export function initPerformanceTimeAndMemPrinter(mCustomProfiles: IOptions): voi * Disable performance printer */ export function blockTimeAndMemPrinter(): void { + disablePrinterTimeAndMemConfig(); performanceTimeAndMemPrinter.filesPrinter = undefined; performanceTimeAndMemPrinter.singleFilePrinter = undefined; } @@ -234,6 +248,20 @@ export function clearTimeAndMemPrinterData(): void { } } +/** + * Initialize the configuration of the TimeAndMem performance printer + */ +export function initPrinterTimeAndMemConfig() { + printerTimeAndMemDataConfig.mTimeAndMemPrinter = true; +} + +/** + * Disable the configuration of the TimeAndMem performance printer + */ +export function disablePrinterTimeAndMemConfig(): void { + printerTimeAndMemDataConfig.mTimeAndMemPrinter = false; +} + /** * Start recording singleFileForMoreTimePrinter event */ diff --git a/arkguard/test/ut/utils/PrinterTimeAndmemUtils.spec.ts b/arkguard/test/ut/utils/PrinterTimeAndmemUtils.spec.ts index 4e7c2ce735..61c4e63316 100644 --- a/arkguard/test/ut/utils/PrinterTimeAndmemUtils.spec.ts +++ b/arkguard/test/ut/utils/PrinterTimeAndmemUtils.spec.ts @@ -16,20 +16,23 @@ import * as fs from 'fs'; import * as path from 'path'; import { + PerfMode, TimeAndMemTimeTracker, clearTimeAndMemPrinterData, + configurePerformancePrinter, + disablePrinterTimeAndMemConfig, enableTimeAndMemoryPrint, endSingleFileForMoreTimeEvent, getObfuscationCacheDir, getMemoryPerformanceData, getTimePerformanceData, initPerformanceTimeAndMemPrinter, + initPrinterTimeAndMemConfig, startSingleFileForMoreTimeEvent, writeTimeAndMemoryPerformanceData, } from '../../../src/utils/PrinterTimeAndMemUtils'; import { expect } from 'chai'; import { performanceTimeAndMemPrinter } from '../../../src/ArkObfuscator'; -import type { IOptions } from '../../../src/configs/IOptions'; import { printerTimeAndMemDataConfig } from '../../../src/initialization/Initializer'; describe('test Cases for .', function () { @@ -67,35 +70,50 @@ describe('test Cases for .', function () { }); describe('Tester Cases for ', () => { - it('Printer config is not set', () => { - const mCustomProfiles: IOptions = {}; - initPerformanceTimeAndMemPrinter(mCustomProfiles); - expect(performanceTimeAndMemPrinter.filesPrinter).to.be.undefined; + it('should block performance printer when mTimeAndMemPrinter is false', () => { + printerTimeAndMemDataConfig.mTimeAndMemPrinter = false; + performanceTimeAndMemPrinter.singleFilePrinter = new TimeAndMemTimeTracker(); + performanceTimeAndMemPrinter.filesPrinter = new TimeAndMemTimeTracker(); + + initPerformanceTimeAndMemPrinter(); + expect(performanceTimeAndMemPrinter.singleFilePrinter).to.be.undefined; - }); - - it('Printer config is set all false', () => { - const mCustomProfiles: IOptions = { - mPerformanceTimeAndMemPrinter: { - mFilesPrinter: false, - mSingleFilePrinter: false, - }, - }; - initPerformanceTimeAndMemPrinter(mCustomProfiles); expect(performanceTimeAndMemPrinter.filesPrinter).to.be.undefined; - expect(performanceTimeAndMemPrinter.singleFilePrinter).to.be.undefined; }); - - it('Printer config is set not all false', () => { - const mCustomProfiles: IOptions = { - mPerformanceTimeAndMemPrinter: { - mFilesPrinter: false, - mSingleFilePrinter: true, - }, - }; - initPerformanceTimeAndMemPrinter(mCustomProfiles); + + it('should not block performance printer when mTimeAndMemPrinter is true', () => { + printerTimeAndMemDataConfig.mTimeAndMemPrinter = true; + performanceTimeAndMemPrinter.singleFilePrinter = new TimeAndMemTimeTracker(); + performanceTimeAndMemPrinter.filesPrinter = new TimeAndMemTimeTracker(); + + initPerformanceTimeAndMemPrinter(); + + expect(performanceTimeAndMemPrinter.singleFilePrinter).to.not.be.undefined; expect(performanceTimeAndMemPrinter.filesPrinter).to.not.be.undefined; + }); + }); + + describe('Tester Cases for ', () => { + it('should configure performance printer for advanced mode', () => { + printerTimeAndMemDataConfig.mTimeAndMemPrinter = false; + performanceTimeAndMemPrinter.singleFilePrinter = undefined; + performanceTimeAndMemPrinter.filesPrinter = undefined; + + configurePerformancePrinter(PerfMode.ADVANCED); + expect(performanceTimeAndMemPrinter.singleFilePrinter).to.not.be.undefined; + expect(performanceTimeAndMemPrinter.filesPrinter).to.not.be.undefined; + expect(printerTimeAndMemDataConfig.mTimeAndMemPrinter).to.be.true; + }); + + it('should block performance printer for normal mode', () => { + performanceTimeAndMemPrinter.singleFilePrinter = new TimeAndMemTimeTracker(); + performanceTimeAndMemPrinter.filesPrinter = new TimeAndMemTimeTracker(); + + configurePerformancePrinter(PerfMode.NORMAL); + + expect(performanceTimeAndMemPrinter.singleFilePrinter).to.be.undefined; + expect(performanceTimeAndMemPrinter.filesPrinter).to.be.undefined; }); }); @@ -149,6 +167,22 @@ describe('test Cases for .', function () { }); }); + describe('Tester Cases for ', () => { + it('start a initPrinterTimeAndMemConfig', () => { + printerTimeAndMemDataConfig.mTimeAndMemPrinter = false; + initPrinterTimeAndMemConfig(); + expect(printerTimeAndMemDataConfig.mTimeAndMemPrinter).to.be.true; + }); + }); + + describe('Tester Cases for ', () => { + it('start a disablePrinterTimeAndMemConfig', () => { + printerTimeAndMemDataConfig.mTimeAndMemPrinter = true; + disablePrinterTimeAndMemConfig(); + expect(printerTimeAndMemDataConfig.mTimeAndMemPrinter).to.be.false; + }); + }); + describe('Tester Cases for ', () => { it('start a singleFile event for more timeEvent when mMoreTimePrint is true', () => { if (!performanceTimeAndMemPrinter.singleFilePrinter) { @@ -273,6 +307,7 @@ describe('test Cases for .', function () { }); await enableTimeAndMemoryPrint(); + await new Promise(resolve => setTimeout(resolve, 100)); expect(fs.existsSync(timePerformanceFilePath)).to.be.true; expect(fs.existsSync(memoryPerformanceFilePath)).to.be.true; -- Gitee From 6c846d209808cf2f6770af45d53e19437b20f090 Mon Sep 17 00:00:00 2001 From: ElevenDuan Date: Sun, 30 Mar 2025 15:51:50 +0800 Subject: [PATCH 012/268] Fix code check 0330 Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBXCHA?from=project-issue Change-Id: I7c038bb3a43e440cd7b142d0d5cdd67b34f9afa7 Signed-off-by: ElevenDuan --- es2panda/binder/binder.cpp | 1 + es2panda/es2panda.cpp | 8 +++----- es2panda/lexer/lexer.cpp | 1 + es2panda/typescript/core/destructuringContext.cpp | 2 ++ es2panda/typescript/types/typeRelation.cpp | 1 + 5 files changed, 8 insertions(+), 5 deletions(-) diff --git a/es2panda/binder/binder.cpp b/es2panda/binder/binder.cpp index 3700382d17..156999be59 100644 --- a/es2panda/binder/binder.cpp +++ b/es2panda/binder/binder.cpp @@ -757,6 +757,7 @@ void Binder::ResolveReference(const ir::AstNode *parent, ir::AstNode *childNode) } case ir::AstNodeType::SUPER_EXPRESSION: { VariableScope *varScope = scope_->EnclosingVariableScope(); + CHECK_NOT_NULL(varScope); varScope->AddFlag(VariableScopeFlags::USE_SUPER); ResolveReferences(childNode); diff --git a/es2panda/es2panda.cpp b/es2panda/es2panda.cpp index 3bb600c038..ddd62b5d9e 100644 --- a/es2panda/es2panda.cpp +++ b/es2panda/es2panda.cpp @@ -223,9 +223,9 @@ void Compiler::DumpAsm(const panda::pandasm::Program *prog) int Compiler::CompileFiles(CompilerOptions &options, std::map &progsInfo, panda::ArenaAllocator *allocator) { - util::SymbolTable *symbolTable = nullptr; + std::unique_ptr symbolTable; if (!options.patchFixOptions.symbolTable.empty() || !options.patchFixOptions.dumpSymbolTable.empty()) { - symbolTable = new util::SymbolTable(options.patchFixOptions.symbolTable, + symbolTable = std::make_unique(options.patchFixOptions.symbolTable, options.patchFixOptions.dumpSymbolTable); if (!symbolTable->Initialize(options.targetApiVersion, options.targetApiSubVersion)) { std::cerr << "Failed to initialize for Hotfix." << std::endl; @@ -236,7 +236,7 @@ int Compiler::CompileFiles(CompilerOptions &options, bool failed = false; std::unordered_set optimizationPendingProgs; auto queue = new compiler::CompileFileQueue(options.fileThreadCount, &options, progsInfo, - optimizationPendingProgs, symbolTable, allocator); + optimizationPendingProgs, symbolTable.get(), allocator); try { queue->Schedule(); @@ -256,8 +256,6 @@ int Compiler::CompileFiles(CompilerOptions &options, if (!options.patchFixOptions.dumpSymbolTable.empty()) { symbolTable->WriteSymbolTable(); } - delete symbolTable; - symbolTable = nullptr; } if (options.requireGlobalOptimization) { diff --git a/es2panda/lexer/lexer.cpp b/es2panda/lexer/lexer.cpp index ff656fe34d..11f965aed9 100644 --- a/es2panda/lexer/lexer.cpp +++ b/es2panda/lexer/lexer.cpp @@ -271,6 +271,7 @@ void Lexer::ScanNumberLeadingZero() case LEX_CHAR_8: case LEX_CHAR_9: { ThrowError("Invalid octal digit"); + break; } default: { break; diff --git a/es2panda/typescript/core/destructuringContext.cpp b/es2panda/typescript/core/destructuringContext.cpp index 2243a62b95..9c84408246 100644 --- a/es2panda/typescript/core/destructuringContext.cpp +++ b/es2panda/typescript/core/destructuringContext.cpp @@ -197,6 +197,7 @@ void DestructuringContext::HandleIdentifierPattern(const ir::AssignmentExpressio void ArrayDestructuringContext::ValidateInferedType() { + CHECK_NOT_NULL(inferedType_); if (!inferedType_->IsArrayType() && !inferedType_->IsUnionType() && (!inferedType_->IsObjectType() || !inferedType_->AsObjectType()->IsTupleType())) { checker_->ThrowTypeError( @@ -521,6 +522,7 @@ void ArrayDestructuringContext::Start() void ObjectDestructuringContext::ValidateInferedType() { + CHECK_NOT_NULL(inferedType_); if (!inferedType_->IsObjectType()) { return; } diff --git a/es2panda/typescript/types/typeRelation.cpp b/es2panda/typescript/types/typeRelation.cpp index b87d32b135..0603f632c4 100644 --- a/es2panda/typescript/types/typeRelation.cpp +++ b/es2panda/typescript/types/typeRelation.cpp @@ -82,6 +82,7 @@ bool TypeRelation::IsIdenticalTo(Type *source, Type *target) CHECK_NOT_NULL(target); result_ = CacheLookup(source, target, checker_->IdenticalResults(), RelationType::IDENTICAL); if (result_ == RelationResult::CACHE_MISS) { + CHECK_NOT_NULL(source); checker_->ResolveStructuredTypeMembers(source); checker_->ResolveStructuredTypeMembers(target); result_ = RelationResult::FALSE; -- Gitee From ec74e8d4cf0d2e61d6b13e29b759974329b96062 Mon Sep 17 00:00:00 2001 From: ElevenDuan Date: Sun, 23 Mar 2025 18:43:32 +0800 Subject: [PATCH 013/268] Compiler performance optimization Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBKYU1 Signed-off-by: ElevenDuan Change-Id: I5f09c74be250f803cc502fb35ed523a6a7abcd22 --- es2panda/aot/emitFiles.cpp | 11 ++++++----- es2panda/aot/emitFiles.h | 12 +++++++----- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/es2panda/aot/emitFiles.cpp b/es2panda/aot/emitFiles.cpp index 10396d7546..121f0824f4 100644 --- a/es2panda/aot/emitFiles.cpp +++ b/es2panda/aot/emitFiles.cpp @@ -49,13 +49,10 @@ void EmitFileQueue::Schedule() { ASSERT(jobsCount_ == 0); std::unique_lock lock(m_); - auto targetApi = options_->CompilerOptions().targetApiVersion; - auto targetSubApi = options_->CompilerOptions().targetApiSubVersion; if (mergeAbc_) { // generate merged abc - auto emitMergedAbcJob = new EmitMergedAbcJob(options_->CompilerOutput(), - options_->CompilerOptions().transformLib, progsInfo_, targetApi, targetSubApi); + auto emitMergedAbcJob = new EmitMergedAbcJob(options_, progsInfo_); // One job should be placed before the jobs on which it depends to prevent blocking jobs_.push_back(emitMergedAbcJob); jobsCount_++; @@ -65,6 +62,8 @@ void EmitFileQueue::Schedule() ScheduleEmitCacheJobs(emitMergedAbcJob); } } else { + auto targetApi = options_->CompilerOptions().targetApiVersion; + auto targetSubApi = options_->CompilerOptions().targetApiSubVersion; for (const auto &info: progsInfo_) { try { // generate multi abcs @@ -109,9 +108,11 @@ void EmitMergedAbcJob::Run() progs.push_back(&(info.second->program)); } + panda::pandasm::EmitterConfig emitConfig {targetApiVersion_, targetApiSubVersion_, + options_->CompilerOptions().isDebug, options_->CompilerOptions().fileThreadCount}; bool success = panda::pandasm::AsmEmitter::EmitPrograms( panda::os::file::File::GetExtendedFilePath(outputFileName_), progs, true, - targetApiVersion_, targetApiSubVersion_); + emitConfig); panda::Timer::timerEnd(panda::EVENT_EMIT_MERGED_PROGRAM, ""); diff --git a/es2panda/aot/emitFiles.h b/es2panda/aot/emitFiles.h index 9a223386c6..f3d3ad2e78 100644 --- a/es2panda/aot/emitFiles.h +++ b/es2panda/aot/emitFiles.h @@ -45,17 +45,19 @@ private: class EmitMergedAbcJob : public util::WorkerJob { public: - explicit EmitMergedAbcJob(const std::string &outputFileName, const std::string &transformLib, - const std::map &progsInfo, - uint8_t targetApi, std::string targetSubApi) - : outputFileName_(outputFileName), transformLib_(transformLib), - progsInfo_(progsInfo), targetApiVersion_(targetApi), targetApiSubVersion_(targetSubApi) {}; + explicit EmitMergedAbcJob(const std::unique_ptr &options, + const std::map &progsInfo) + : options_(options), outputFileName_(options->CompilerOutput()), + transformLib_(options->CompilerOptions().transformLib), + progsInfo_(progsInfo), targetApiVersion_(options->CompilerOptions().targetApiVersion), + targetApiSubVersion_(options->CompilerOptions().targetApiSubVersion) {}; NO_COPY_SEMANTIC(EmitMergedAbcJob); NO_MOVE_SEMANTIC(EmitMergedAbcJob); ~EmitMergedAbcJob() override = default; void Run() override; private: + const std::unique_ptr &options_; std::string outputFileName_; std::string transformLib_; const std::map &progsInfo_; -- Gitee From 61f250e983199ab6989866fc4c79cd53d1061acc Mon Sep 17 00:00:00 2001 From: Daniel Kofanov Date: Mon, 31 Mar 2025 18:32:57 +0800 Subject: [PATCH 014/268] Edit REVIEWERS for ASTVerifier Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBXPMZ?from=project-issue Signed-off-by: Daniel Kofanov --- ets2panda/REVIEWERS | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ets2panda/REVIEWERS b/ets2panda/REVIEWERS index dd6b82d699..aaa24061de 100644 --- a/ets2panda/REVIEWERS +++ b/ets2panda/REVIEWERS @@ -17,7 +17,7 @@ /arkguard/ @zhangchen168 /es2panda/ @gavin1012_hw /ets2panda/ @igelhaus @Prof1983 -/ets2panda/ast_verifier @mbolshov ^igelhaus ^Prof1983 +/ets2panda/ast_verifier @mbolshov @dkofanov ^igelhaus ^Prof1983 /ets2panda/bindings ^igelhaus ^Prof1983 @dreamdoomwalker @Ascnbio ^muhammet-fevzi-bayiroglu @utkugursel /ets2panda/lexer @chernykhsergey @igelhaus ^zelentsovdmitry @Prof1983 /ets2panda/lsp ^igelhaus ^Prof1983 @dreamdoomwalker @Ascnbio ^muhammet-fevzi-bayiroglu @utkugursel @@ -56,6 +56,7 @@ /ets2panda/checker/types/typeFlag.h ^vpukhov ^igelhaus ^Prof1983 @zelentsovdmitry /ets2panda/checker/types/typeRelation.* ^vpukhov ^igelhaus ^Prof1983 @zelentsovdmitry /ets2panda/compiler/core/ @zelentsovdmitry ^vpukhov ^igelhaus ^Prof1983 +/ets2panda/compiler/core/compilerImpl.cpp @dkofanov ^igelhaus ^Prof1983 /ets2panda/test/test-lists/astchecker @chernykhsergey ^igelhaus ^Prof1983 /ets2panda/test/test-lists/declgenets2ts @dreamdoomwalker ^hufeng20 ^igelhaus ^Prof1983 /ets2panda/test/test-lists/parser @chernykhsergey ^igelhaus ^Prof1983 -- Gitee From 97fc9ef06722759432ac2c05b3b8ae5db5408b9d Mon Sep 17 00:00:00 2001 From: zhangkai366 Date: Wed, 19 Mar 2025 10:01:23 +0800 Subject: [PATCH 015/268] Fixed the problem of missing fields in namecache Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBUIG1 Test: ut & test Signed-off-by: zhangkai366 Change-Id: I5b9be74f4955b2d15e9f208e50e79a77b69128db --- arkguard/src/ArkObfuscator.ts | 33 ++++++--- arkguard/src/utils/SourceMapMergingUtil.ts | 5 ++ .../ut/arkobfuscator/ArkObfuscator2.spec.ts | 68 +++++++++++++++++++ 3 files changed, 98 insertions(+), 8 deletions(-) diff --git a/arkguard/src/ArkObfuscator.ts b/arkguard/src/ArkObfuscator.ts index 708aa9ce89..1737fb9e53 100644 --- a/arkguard/src/ArkObfuscator.ts +++ b/arkguard/src/ArkObfuscator.ts @@ -454,27 +454,44 @@ export class ArkObfuscator { updatedCache[newKey] = value; continue; } + + const parts = scopeName.split('#'); + // 1: Get the last word 'zz' in '#xx#yy#zz'. + const lastScopeName: string = parts[parts.length - 1]; + const startPosition: SourceMapSegmentObj | null = sourceMapLink.traceSegment( // 1: The line number in originalCache starts from 1 while in source map starts from 0. Number(oldStartLine) - 1, Number(oldStartColumn) - 1, ''); // Minus 1 to get the correct original position. - if (!startPosition) { - // Do not save methods that do not exist in the source code, e.g. 'build' in ArkUI. + if (!startPosition && lastScopeName === value) { + // Do not save methods that do not exist in the source code and not be obfuscated, e.g. 'build' in ArkUI. continue; } const endPosition: SourceMapSegmentObj | null = sourceMapLink.traceSegment( Number(oldEndLine) - 1, Number(oldEndColumn) - 1, ''); // 1: Same as above. - if (!endPosition) { - // Do not save methods that do not exist in the source code, e.g. 'build' in ArkUI. + if (!endPosition && lastScopeName === value) { + // Do not save methods that do not exist in the source code and not be obfuscated, e.g. 'build' in ArkUI. continue; } - const startLine = startPosition.line + 1; // 1: The final line number in updatedCache should starts from 1. - const endLine = endPosition.line + 1; // 1: Same as above. - newKey = `${scopeName}:${startLine}:${endLine}`; - updatedCache[newKey] = value; + + if (!startPosition || !endPosition) { + updatedCache[scopeName] = value; + } else { + const startLine = startPosition.line + 1; // 1: The final line number in updatedCache should starts from 1. + const endLine = endPosition.line + 1; // 1: Same as above. + newKey = `${scopeName}:${startLine}:${endLine}`; + updatedCache[newKey] = value; + } } return updatedCache; } + public convertLineBasedOnSourceMapForTest( + targetCache: string, + sourceMapLink?: SourceMapLink + ): Map { + return this.convertLineBasedOnSourceMap(targetCache, sourceMapLink); + } + /** * Obfuscate ast of a file. * @param content ast or source code of a source file diff --git a/arkguard/src/utils/SourceMapMergingUtil.ts b/arkguard/src/utils/SourceMapMergingUtil.ts index 266f0d33cc..cb4746226a 100644 --- a/arkguard/src/utils/SourceMapMergingUtil.ts +++ b/arkguard/src/utils/SourceMapMergingUtil.ts @@ -74,6 +74,11 @@ export interface SourceMapSegmentObj { type MappingsNameType = { mappings: readonly SourceMapSegment[][]; names?: readonly string[] }; type TracedMappingsType = { mappings: SourceMapSegment[][]; names: string[]; sources: string[] }; +/** + * Type of the map parameter of the SourceMapLink class. + */ +export type MappingsNameTypeForTest = MappingsNameType; + /** * Provide api tools related to sourcemap. */ diff --git a/arkguard/test/ut/arkobfuscator/ArkObfuscator2.spec.ts b/arkguard/test/ut/arkobfuscator/ArkObfuscator2.spec.ts index 57e552d254..a345d5feb3 100644 --- a/arkguard/test/ut/arkobfuscator/ArkObfuscator2.spec.ts +++ b/arkguard/test/ut/arkobfuscator/ArkObfuscator2.spec.ts @@ -67,6 +67,13 @@ import { SOURCE_FILE_PATHS, projectWhiteListManager } from '../../../src/utils/P import { FilePathObj } from '../../../src/common/type'; import { historyAllUnobfuscatedNamesMap } from '../../../src/initialization/Initializer'; import path from 'path'; +import { nameCache } from '../../../src/transformers/rename/RenameIdentifierTransformer'; +import { + decodeSourcemap, + MappingsNameTypeForTest, + Source, + SourceMapLink +} from '../../../src/utils/SourceMapMergingUtil'; describe('Tester Cases for ', function () { let obfuscator: ArkObfuscator; @@ -524,6 +531,67 @@ export declare function findElement(arr: T[], callback: (item: T) => boolean) }); }); + describe('test for ArkObfuscator.convertLineBasedOnSourceMap', () => { + it('there is no location but the value is obfuscated, it should be recorded in nameacahe', () => { + const identifierCache = new Map([ + ['#Person', 'Person'], + ['obfsucationValue:31:5:35:6', 'h'], + ['getName:75:5:77:6', 'getName'] + ]); + nameCache.set('IdentifierCache', identifierCache); + const source: Source = new Source('utils.ets', null); + const previousStageSourceMap: RawSourceMap = { + version: 3, + file: 'utils.ets', + sourceRoot: '', + sources: [ 'entry/src/main/ets/pages/utils/utils.ets'], + names: [], + mappings: '', + sourcesContent: undefined, + } + const decodedSourceMap = decodeSourcemap(previousStageSourceMap as RawSourceMap); + const sourceMapLink: SourceMapLink = new SourceMapLink(decodedSourceMap as MappingsNameTypeForTest, [source]); + + const result = obfuscator.convertLineBasedOnSourceMapForTest('IdentifierCache', sourceMapLink); + const expectedResult= { + '#Person': 'Person', + 'obfsucationValue': 'h' + }; + const compareResult = JSON.stringify(result) === JSON.stringify(expectedResult); + expect(compareResult).to.be.true; + }); + + it('there is start and end location, it should be recorded in nameacahe', () => { + const identifierCache = new Map([ + ['#Person', 'Person'], + ['#foo:1:1:3:2', 'foo'], + ['getName:75:5:77:6', 'getName'] + ]); + nameCache.set('IdentifierCache', identifierCache); + const source: Source = new Source('file.ts', null); + const previousStageSourceMap: RawSourceMap = { + "version": 3, + "file": "file.ts", + "sources": [ + "entry/src/main/ets/pages/file.ts" + ], + "names": [], + "mappings": "AAAA,MAAM,UAAU,GAAG;IACjB,OAAO,CAAC,CAAC;AACX,CAAC", + "sourceRoot": "" + } + const decodedSourceMap = decodeSourcemap(previousStageSourceMap as RawSourceMap); + const sourceMapLink: SourceMapLink = new SourceMapLink(decodedSourceMap as MappingsNameTypeForTest, [source]); + + const result = obfuscator.convertLineBasedOnSourceMapForTest('IdentifierCache', sourceMapLink); + const expectedResult= { + '#Person': 'Person', + '#foo:1:3': 'foo' + }; + const compareResult = JSON.stringify(result) === JSON.stringify(expectedResult); + expect(compareResult).to.be.true; + }); + }); + describe('test for clearGlobalCaches', () => { beforeEach(() => { PropCollections.globalMangledTable.set('test1', 'obfuscated1'); -- Gitee From 98fcdee2ef6693be5a6d7efbe07975e9abd58c65 Mon Sep 17 00:00:00 2001 From: aakmaev Date: Mon, 7 Apr 2025 15:48:56 +0300 Subject: [PATCH 016/268] Add reviewers to frontend MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [新需求]: Add reviewers to frontend Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBZ6VS Signed-off-by: Akmaev Aleksey --- ets2panda/REVIEWERS | 70 ++++++++++++++++++++++++++++++--------------- 1 file changed, 47 insertions(+), 23 deletions(-) diff --git a/ets2panda/REVIEWERS b/ets2panda/REVIEWERS index aaa24061de..b8a6e01577 100644 --- a/ets2panda/REVIEWERS +++ b/ets2panda/REVIEWERS @@ -17,13 +17,14 @@ /arkguard/ @zhangchen168 /es2panda/ @gavin1012_hw /ets2panda/ @igelhaus @Prof1983 -/ets2panda/ast_verifier @mbolshov @dkofanov ^igelhaus ^Prof1983 +/ets2panda/aot @dkofanov @gavin1012_hw ^igelhaus ^Prof1983 +/ets2panda/ast_verifier @mbolshov @dkofanov ^yyang16 ^igelhaus ^Prof1983 /ets2panda/bindings ^igelhaus ^Prof1983 @dreamdoomwalker @Ascnbio ^muhammet-fevzi-bayiroglu @utkugursel /ets2panda/lexer @chernykhsergey @igelhaus ^zelentsovdmitry @Prof1983 /ets2panda/lsp ^igelhaus ^Prof1983 @dreamdoomwalker @Ascnbio ^muhammet-fevzi-bayiroglu @utkugursel /ets2panda/parser @chernykhsergey ^igelhaus ^Prof1983 -/ets2panda/public @mbolshov ^igelhaus ^Prof1983 -/ets2panda/test ^igelhaus ^Prof1983 +/ets2panda/public @mbolshov @yyang16 ^igelhaus ^Prof1983 +/ets2panda/test @akmaevaleksey ^igelhaus ^Prof1983 /legacy_bin/ @ctw-ian /merge_abc/ @gavin1012_hw /test/ @gavin1012_hw @@ -32,44 +33,67 @@ /test262/*.py @shirunova_viktoria @gavin1012_hw @zhuheng27 /test262/ignored*.txt @shirunova_viktoria @gavin1012_hw @kuchkovairina @zhuheng27 /test_ecma_bcopt/ @gavin1012_hw -/ets2panda/checker/ETS*.* @zelentsovdmitry ^igelhaus ^Prof1983 @chernykhsergey -/ets2panda/checker/ETSAnalyzer.cpp @akmaevaleksey ^vpukhov ^igelhaus ^Prof1983 +/ets2panda/checker/ @akmaevaleksey @zelentsovdmitry ^lirismankarina ^igelhaus ^Prof1983 +/ets2panda/checker/ETS*.* @zelentsovdmitry ^igelhaus ^Prof1983 +/ets2panda/checker/ETSAnalyzer.cpp ^akmaevaleksey @Ekkoruse ^igelhaus ^Prof1983 +/ets2panda/checker/ETSAnalyzerHelpers.* @lirismankarina ^igelhaus ^Prof1983 +/ets2panda/compiler/ @xuxjeeee @gogabr ^igelhaus ^Prof1983 ^zelentsovdmitry /ets2panda/declgen_ets2ts/ @dreamdoomwalker ^trubachevilya ^ivagin ^hufeng20 ^igelhaus ^Prof1983 /ets2panda/driver/ ^trubachevilya @dreamdoomwalker @chenqy930 @hufeng20 ^igelhaus ^Prof1983 -/ets2panda/linter/ @ragnvald @rosinskiyigor @eokolnov1 @liwentao_uiw +/ets2panda/ir/ @ziziziiziziz @gavin1012_hw ^igelhaus ^Prof1983 +/ets2panda/linter/ @ragnvald @rosinskiyigor @eokolnov1 @liwentao_uiw ^utkugursel +/ets2panda/parser/ @zelentsovdmitry ^igelhaus ^Prof1983 ^chernykhsergey /ets2panda/parser/ETSparser*.* @zelentsovdmitry ^igelhaus ^Prof1983 @chernykhsergey /ets2panda/parser/expressionParser.cpp @zelentsovdmitry ^igelhaus ^Prof1983 @chernykhsergey /ets2panda/parser/parser*.* @zelentsovdmitry ^igelhaus ^Prof1983 @chernykhsergey /ets2panda/parser/statementParser.cpp @zelentsovdmitry ^igelhaus ^Prof1983 @chernykhsergey /ets2panda/scripts/*-build.sh @titovatatiana ^igelhaus ^Prof1983 /ets2panda/scripts/arkui* @titovatatiana ^igelhaus ^Prof1983 +/ets2panda/util/ @mkaskov @dkofanov ^igelhaus ^Prof1983 /ets2panda/util/arktsconfig* @dreamdoomwalker ^trubachevilya ^igelhaus ^Prof1983 -/ets2panda/util/diagnostic* @chernykhsergey ^igelhaus ^Prof1983 -/ets2panda/util/importPathManager* @dreamdoomwalker ^trubachevilya ^igelhaus ^Prof1983 +/ets2panda/util/diagnostic* @chernykhsergey @mkaskov ^igelhaus ^Prof1983 +/ets2panda/util/importPathManager* @dreamdoomwalker @trubachevilya ^igelhaus ^Prof1983 +/ets2panda/util/plugin.* @yyang16 @mbolshov ^igelhaus ^Prof1983 +/ets2panda/varbinder/ @lirismankarina @akmaevaleksey ^Ekkoruse ^zelentsovdmitry ^igelhaus ^Prof1983 /test/workload/ignored*.txt @shirunova_viktoria @kuchkovairina @gavin1012_hw @zhuheng27 -/ets2panda/checker/ets/dynamic.cpp @akmaevaleksey ^vpukhov ^igelhaus ^Prof1983 -/ets2panda/checker/ets/function.cpp ^vpukhov @gogabr ^igelhaus ^Prof1983 -/ets2panda/checker/ets/helpers.cpp @zelentsovdmitry ^igelhaus ^Prof1983 -/ets2panda/checker/ets/object.cpp @zelentsovdmitry ^vpukhov ^igelhaus ^Prof1983 +/ets2panda/checker/ets/ @lirismankarina ^igelhaus ^Prof1983 +/ets2panda/checker/ets/dynamic.cpp @lirismankarina @akmaevaleksey ^vpukhov ^igelhaus ^Prof1983 +/ets2panda/checker/ets/function.cpp @lirismankarina @gogabr ^vpukhov ^igelhaus ^Prof1983 +/ets2panda/checker/ets/helpers.cpp @xuxjeeee @zelentsovdmitry ^igelhaus ^Prof1983 +/ets2panda/checker/ets/object.cpp @xuxjeeee @zelentsovdmitry ^vpukhov ^igelhaus ^Prof1983 /ets2panda/checker/types/ets @gogabr ^igelhaus ^Prof1983 @zelentsovdmitry -/ets2panda/checker/types/signature.* ^vpukhov ^igelhaus ^Prof1983 @zelentsovdmitry -/ets2panda/checker/types/typeFlag.h ^vpukhov ^igelhaus ^Prof1983 @zelentsovdmitry -/ets2panda/checker/types/typeRelation.* ^vpukhov ^igelhaus ^Prof1983 @zelentsovdmitry -/ets2panda/compiler/core/ @zelentsovdmitry ^vpukhov ^igelhaus ^Prof1983 -/ets2panda/compiler/core/compilerImpl.cpp @dkofanov ^igelhaus ^Prof1983 +/ets2panda/checker/types/signature.* ^vpukhov ^igelhaus ^Prof1983 @zelentsovdmitry @lirismankarina +/ets2panda/checker/types/typeFlag.h ^vpukhov ^igelhaus ^Prof1983 @zelentsovdmitry @mkaskov +/ets2panda/checker/types/typeRelation.* ^vpukhov ^igelhaus ^Prof1983 @zelentsovdmitry @mkaskov +/ets2panda/compiler/core/ @zelentsovdmitry @xuxjeeee ^vpukhov ^igelhaus ^Prof1983 +/ets2panda/compiler/core/compilerImpl.* @yyang16 @dkofanov ^xuxjeeee ^igelhaus ^Prof1983 +/ets2panda/compiler/lowering/phase.* @yyang16 ^mbolshov ^igelhaus ^Prof1983 +/ets2panda/compiler/lowering/plugin_phase.* @yyang16 ^mbolshov ^igelhaus ^Prof1983 +/ets2panda/compiler/lowering/util.* @yyang16 ^mbolshov ^igelhaus ^Prof1983 +/ets2panda/ir/ets/ @lirismankarina @xuxjeeee ^igelhaus ^Prof1983 +/ets2panda/ir/expressions/ @mkaskov @ziziziiziziz ^igelhaus ^Prof1983 +/ets2panda/ir/statements/ @dkofanov @Ekkoruse ^akmaevaleksey ^igelhaus ^Prof1983 +/ets2panda/ir/statements/annotation* @lirismankarina @xuxjeeee ^igelhaus ^Prof1983 /ets2panda/test/test-lists/astchecker @chernykhsergey ^igelhaus ^Prof1983 /ets2panda/test/test-lists/declgenets2ts @dreamdoomwalker ^hufeng20 ^igelhaus ^Prof1983 /ets2panda/test/test-lists/parser @chernykhsergey ^igelhaus ^Prof1983 /ets2panda/test/unit/lsp ^igelhaus ^Prof1983 @dreamdoomwalker @Ascnbio ^muhammet-fevzi-bayiroglu @utkugursel /ets2panda/checker/types/ets/Nullish.* ^vpukhov @gogabr ^igelhaus ^Prof1983 +/ets2panda/checker/types/ets/etsA* @xuxjeeee ^gogabr ^igelhaus ^Prof1983 /ets2panda/checker/types/ets/etsDynamicType.* ^vpukhov @gogabr ^igelhaus ^Prof1983 +/ets2panda/checker/types/ets/etsE* @ziziziiziziz ^zelentsovdmitry ^igelhaus ^Prof1983 /ets2panda/checker/types/ets/etsFunctionType.* ^vpukhov @gogabr ^igelhaus ^Prof1983 +/ets2panda/checker/types/ets/etsN* @ziziziiziziz ^zelentsovdmitry ^igelhaus ^Prof1983 +/ets2panda/checker/types/ets/etsT* @xuxjeeee ^gogabr ^igelhaus ^Prof1983 /ets2panda/checker/types/ets/etsTypeParameter.* ^vpukhov @gogabr ^igelhaus ^Prof1983 /ets2panda/checker/types/ets/etsUnionType.* @akmaevaleksey ^vpukhov @gogabr ^igelhaus ^Prof1983 /ets2panda/checker/types/ets/wildcardType.* ^vpukhov @gogabr ^igelhaus ^Prof1983 -/ets2panda/compiler/lowering/ets/ @akmaevaleksey ^igelhaus ^Prof1983 ^zelentsovdmitry -/ets2panda/compiler/lowering/ets/lambdaLowering.cpp ^vpukhov @akmaevaleksey @gogabr ^igelhaus ^Prof1983 -/ets2panda/compiler/lowering/ets/localClassLowering.cpp @gogabr ^igelhaus ^Prof1983 -/ets2panda/compiler/lowering/ets/optionalLowering.cpp ^vpukhov @akmaevaleksey ^igelhaus ^Prof1983 -/ets2panda/compiler/lowering/ets/unionLowering.cpp ^vpukhov @akmaevaleksey ^igelhaus ^Prof1983 -/ets2panda/compiler/lowering/ets/topLevelStmts/.* ^vpukhov @akmaevaleksey ^igelhaus ^Prof1983 +/ets2panda/compiler/lowering/ets/ @akmaevaleksey @gogabr ^igelhaus ^Prof1983 ^zelentsovdmitry +/ets2panda/compiler/lowering/ets/const* @ziziziiziziz @lirismankarina ^akmaevaleksey ^igelhaus ^Prof1983 +/ets2panda/compiler/lowering/ets/enum* @ziziziiziziz @dkofanov ^akmaevaleksey ^igelhaus ^Prof1983 +/ets2panda/compiler/lowering/ets/lambdaLowering.cpp @Ekkoruse @gogabr ^vpukhov ^akmaevaleksey ^igelhaus ^Prof1983 +/ets2panda/compiler/lowering/ets/localClassLowering.cpp @gogabr ^akmaevaleksey ^igelhaus ^Prof1983 +/ets2panda/compiler/lowering/ets/optionalLowering.cpp @zelentsovdmitry @akmaevaleksey ^vpukhov ^igelhaus ^Prof1983 +/ets2panda/compiler/lowering/ets/spread* @ziziziiziziz @dkofanov ^akmaevaleksey ^igelhaus ^Prof1983 +/ets2panda/compiler/lowering/ets/unionLowering.cpp @Ekkoruse @akmaevaleksey ^vpukhov ^igelhaus ^Prof1983 +/ets2panda/compiler/lowering/ets/topLevelStmts/.* @lirismankarina @xuxjeeee ^akmaevaleksey ^vpukhov ^igelhaus ^Prof1983 \ No newline at end of file -- Gitee From c694089c6de1c2fe5141ef91b10b3e5a5a3f61f8 Mon Sep 17 00:00:00 2001 From: hanlong Date: Wed, 9 Apr 2025 14:57:42 +0800 Subject: [PATCH 017/268] Update KFL 0409 Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBZQ13?from=project-issue Signed-off-by: hanlong --- test/workload/ignored-third_lib_js-debug-arm64-jit.txt | 4 ++-- .../ignored-third_lib_js-fastverify-arm64-jit.txt | 8 ++++---- test/workload/ignored-third_lib_js-release-arm64-aot.txt | 4 ++-- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/test/workload/ignored-third_lib_js-debug-arm64-jit.txt b/test/workload/ignored-third_lib_js-debug-arm64-jit.txt index 5282f00e57..ff8b0695e0 100644 --- a/test/workload/ignored-third_lib_js-debug-arm64-jit.txt +++ b/test/workload/ignored-third_lib_js-debug-arm64-jit.txt @@ -1,2 +1,2 @@ -# Known failures list for third_lib_js-fastverify-arm64-jit - +#24760 +dayjs_test diff --git a/test/workload/ignored-third_lib_js-fastverify-arm64-jit.txt b/test/workload/ignored-third_lib_js-fastverify-arm64-jit.txt index df5f847a76..f4fe2643a4 100644 --- a/test/workload/ignored-third_lib_js-fastverify-arm64-jit.txt +++ b/test/workload/ignored-third_lib_js-fastverify-arm64-jit.txt @@ -4,14 +4,14 @@ gson_test #19623 rebound_test -#20690 -dayjs_test - #21251 validator_test #23990 hamcrest_test -#24119 +#24760 dayjs_test + +#19247 +jsDiff_test diff --git a/test/workload/ignored-third_lib_js-release-arm64-aot.txt b/test/workload/ignored-third_lib_js-release-arm64-aot.txt index 4fdf6cc547..ff8b0695e0 100644 --- a/test/workload/ignored-third_lib_js-release-arm64-aot.txt +++ b/test/workload/ignored-third_lib_js-release-arm64-aot.txt @@ -1,2 +1,2 @@ -# Known failures list for third_lib_js - release-arm64-aot - +#24760 +dayjs_test -- Gitee From 5b10678307b5f714554546b89dab47444177a7b0 Mon Sep 17 00:00:00 2001 From: zhao1d Date: Thu, 10 Apr 2025 15:04:16 +0800 Subject: [PATCH 018/268] update kfl 0410 Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBZAJ0 Signed-off-by: zhao1d --- test/workload/ignored-third_lib_js-debug-arm64-jit.txt | 2 -- .../ignored-third_lib_js-fastverify-arm64-aot-litecg.txt | 6 ------ test/workload/ignored-third_lib_js-fastverify-arm64-int.txt | 6 ------ test/workload/ignored-third_lib_js-fastverify-arm64-jit.txt | 6 ------ test/workload/ignored-third_lib_js-release-arm64-aot.txt | 2 -- test/workload/workload.properties | 2 +- 6 files changed, 1 insertion(+), 23 deletions(-) diff --git a/test/workload/ignored-third_lib_js-debug-arm64-jit.txt b/test/workload/ignored-third_lib_js-debug-arm64-jit.txt index ff8b0695e0..e69de29bb2 100644 --- a/test/workload/ignored-third_lib_js-debug-arm64-jit.txt +++ b/test/workload/ignored-third_lib_js-debug-arm64-jit.txt @@ -1,2 +0,0 @@ -#24760 -dayjs_test diff --git a/test/workload/ignored-third_lib_js-fastverify-arm64-aot-litecg.txt b/test/workload/ignored-third_lib_js-fastverify-arm64-aot-litecg.txt index b191ecdf7f..9927aa890d 100644 --- a/test/workload/ignored-third_lib_js-fastverify-arm64-aot-litecg.txt +++ b/test/workload/ignored-third_lib_js-fastverify-arm64-aot-litecg.txt @@ -3,9 +3,3 @@ jsDiff_test #21663 crypto-js_test - -#21251 -validator_test - -#24119 -dayjs_test diff --git a/test/workload/ignored-third_lib_js-fastverify-arm64-int.txt b/test/workload/ignored-third_lib_js-fastverify-arm64-int.txt index d1b258aa07..bc8c57f26e 100644 --- a/test/workload/ignored-third_lib_js-fastverify-arm64-int.txt +++ b/test/workload/ignored-third_lib_js-fastverify-arm64-int.txt @@ -4,11 +4,5 @@ jsDiff_test #21663 crypto-js_test -#21251 -validator_test - -#24119 -dayjs_test - #23119 jBox2d_test diff --git a/test/workload/ignored-third_lib_js-fastverify-arm64-jit.txt b/test/workload/ignored-third_lib_js-fastverify-arm64-jit.txt index f4fe2643a4..5a1ff03c90 100644 --- a/test/workload/ignored-third_lib_js-fastverify-arm64-jit.txt +++ b/test/workload/ignored-third_lib_js-fastverify-arm64-jit.txt @@ -4,14 +4,8 @@ gson_test #19623 rebound_test -#21251 -validator_test - #23990 hamcrest_test -#24760 -dayjs_test - #19247 jsDiff_test diff --git a/test/workload/ignored-third_lib_js-release-arm64-aot.txt b/test/workload/ignored-third_lib_js-release-arm64-aot.txt index ff8b0695e0..e69de29bb2 100644 --- a/test/workload/ignored-third_lib_js-release-arm64-aot.txt +++ b/test/workload/ignored-third_lib_js-release-arm64-aot.txt @@ -1,2 +0,0 @@ -#24760 -dayjs_test diff --git a/test/workload/workload.properties b/test/workload/workload.properties index e01ed222fc..b517478780 100644 --- a/test/workload/workload.properties +++ b/test/workload/workload.properties @@ -1,3 +1,3 @@ WORKLOAD_REPO=https://gitee.com/haizaibali/ohcompiler-daily.git WORKLOAD_REPO_BRANCH=workload_all -WORKLOAD_REPO_REVISION=d5075b5a12bc94a0ca305fb4e118390a8ab13620 +WORKLOAD_REPO_REVISION=e632f32071213ba6818f9e2013e8fd43c182deb9 -- Gitee From 5cf13c90509e851fdcbd67f18cb4a9365e8d2b3e Mon Sep 17 00:00:00 2001 From: aakmaev Date: Thu, 10 Apr 2025 17:16:00 +0300 Subject: [PATCH 019/268] Modify reviewers Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC06TU Signed-off-by: Akmaev Aleksey --- ets2panda/REVIEWERS | 36 ++++++++++++++++++++---------------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/ets2panda/REVIEWERS b/ets2panda/REVIEWERS index b8a6e01577..9b3f422a62 100644 --- a/ets2panda/REVIEWERS +++ b/ets2panda/REVIEWERS @@ -24,7 +24,7 @@ /ets2panda/lsp ^igelhaus ^Prof1983 @dreamdoomwalker @Ascnbio ^muhammet-fevzi-bayiroglu @utkugursel /ets2panda/parser @chernykhsergey ^igelhaus ^Prof1983 /ets2panda/public @mbolshov @yyang16 ^igelhaus ^Prof1983 -/ets2panda/test @akmaevaleksey ^igelhaus ^Prof1983 +/ets2panda/test ^akmaevaleksey ^igelhaus ^Prof1983 /legacy_bin/ @ctw-ian /merge_abc/ @gavin1012_hw /test/ @gavin1012_hw @@ -42,13 +42,14 @@ /ets2panda/driver/ ^trubachevilya @dreamdoomwalker @chenqy930 @hufeng20 ^igelhaus ^Prof1983 /ets2panda/ir/ @ziziziiziziz @gavin1012_hw ^igelhaus ^Prof1983 /ets2panda/linter/ @ragnvald @rosinskiyigor @eokolnov1 @liwentao_uiw ^utkugursel -/ets2panda/parser/ @zelentsovdmitry ^igelhaus ^Prof1983 ^chernykhsergey -/ets2panda/parser/ETSparser*.* @zelentsovdmitry ^igelhaus ^Prof1983 @chernykhsergey -/ets2panda/parser/expressionParser.cpp @zelentsovdmitry ^igelhaus ^Prof1983 @chernykhsergey -/ets2panda/parser/parser*.* @zelentsovdmitry ^igelhaus ^Prof1983 @chernykhsergey -/ets2panda/parser/statementParser.cpp @zelentsovdmitry ^igelhaus ^Prof1983 @chernykhsergey +/ets2panda/parser/ @mkaskov ^igelhaus ^Prof1983 ^chernykhsergey ^zelentsovdmitry /ets2panda/scripts/*-build.sh @titovatatiana ^igelhaus ^Prof1983 /ets2panda/scripts/arkui* @titovatatiana ^igelhaus ^Prof1983 +/ets2panda/test/ast @mbolshov ^igelhaus ^Prof1983 +/ets2panda/test/depanalyzer @trubachevilya ^igelhaus ^Prof1983 +/ets2panda/test/srcdump @mbolshov ^igelhaus ^Prof1983 +/ets2panda/test/test-lists @igelhaus ^Prof1983 +/ets2panda/test/utils @mbolshov ^igelhaus ^Prof1983 /ets2panda/util/ @mkaskov @dkofanov ^igelhaus ^Prof1983 /ets2panda/util/arktsconfig* @dreamdoomwalker ^trubachevilya ^igelhaus ^Prof1983 /ets2panda/util/diagnostic* @chernykhsergey @mkaskov ^igelhaus ^Prof1983 @@ -57,14 +58,14 @@ /ets2panda/varbinder/ @lirismankarina @akmaevaleksey ^Ekkoruse ^zelentsovdmitry ^igelhaus ^Prof1983 /test/workload/ignored*.txt @shirunova_viktoria @kuchkovairina @gavin1012_hw @zhuheng27 /ets2panda/checker/ets/ @lirismankarina ^igelhaus ^Prof1983 -/ets2panda/checker/ets/dynamic.cpp @lirismankarina @akmaevaleksey ^vpukhov ^igelhaus ^Prof1983 -/ets2panda/checker/ets/function.cpp @lirismankarina @gogabr ^vpukhov ^igelhaus ^Prof1983 +/ets2panda/checker/ets/dynamic.cpp @lirismankarina ^vpukhov ^igelhaus ^Prof1983 +/ets2panda/checker/ets/function.cpp @gogabr ^vpukhov ^igelhaus ^Prof1983 /ets2panda/checker/ets/helpers.cpp @xuxjeeee @zelentsovdmitry ^igelhaus ^Prof1983 /ets2panda/checker/ets/object.cpp @xuxjeeee @zelentsovdmitry ^vpukhov ^igelhaus ^Prof1983 -/ets2panda/checker/types/ets @gogabr ^igelhaus ^Prof1983 @zelentsovdmitry -/ets2panda/checker/types/signature.* ^vpukhov ^igelhaus ^Prof1983 @zelentsovdmitry @lirismankarina -/ets2panda/checker/types/typeFlag.h ^vpukhov ^igelhaus ^Prof1983 @zelentsovdmitry @mkaskov -/ets2panda/checker/types/typeRelation.* ^vpukhov ^igelhaus ^Prof1983 @zelentsovdmitry @mkaskov +/ets2panda/checker/types/ets @dkofanov ^igelhaus ^Prof1983 +/ets2panda/checker/types/signature.* ^vpukhov ^igelhaus ^Prof1983 @zelentsovdmitry +/ets2panda/checker/types/typeFlag.h ^vpukhov ^igelhaus ^Prof1983 @mkaskov +/ets2panda/checker/types/typeRelation.* ^vpukhov ^igelhaus ^Prof1983 @mkaskov /ets2panda/compiler/core/ @zelentsovdmitry @xuxjeeee ^vpukhov ^igelhaus ^Prof1983 /ets2panda/compiler/core/compilerImpl.* @yyang16 @dkofanov ^xuxjeeee ^igelhaus ^Prof1983 /ets2panda/compiler/lowering/phase.* @yyang16 ^mbolshov ^igelhaus ^Prof1983 @@ -77,7 +78,10 @@ /ets2panda/test/test-lists/astchecker @chernykhsergey ^igelhaus ^Prof1983 /ets2panda/test/test-lists/declgenets2ts @dreamdoomwalker ^hufeng20 ^igelhaus ^Prof1983 /ets2panda/test/test-lists/parser @chernykhsergey ^igelhaus ^Prof1983 -/ets2panda/test/unit/lsp ^igelhaus ^Prof1983 @dreamdoomwalker @Ascnbio ^muhammet-fevzi-bayiroglu @utkugursel +/ets2panda/test/unit/arktsconfig-parser @trubachevilya ^igelhaus ^Prof1983 +/ets2panda/test/unit/lsp @dreamdoomwalker @utkugursel ^igelhaus ^Prof1983 +/ets2panda/test/unit/plugin* @mbolshov ^igelhaus ^Prof1983 +/ets2panda/test/unit/public @mbolshov ^igelhaus ^Prof1983 /ets2panda/checker/types/ets/Nullish.* ^vpukhov @gogabr ^igelhaus ^Prof1983 /ets2panda/checker/types/ets/etsA* @xuxjeeee ^gogabr ^igelhaus ^Prof1983 /ets2panda/checker/types/ets/etsDynamicType.* ^vpukhov @gogabr ^igelhaus ^Prof1983 @@ -86,14 +90,14 @@ /ets2panda/checker/types/ets/etsN* @ziziziiziziz ^zelentsovdmitry ^igelhaus ^Prof1983 /ets2panda/checker/types/ets/etsT* @xuxjeeee ^gogabr ^igelhaus ^Prof1983 /ets2panda/checker/types/ets/etsTypeParameter.* ^vpukhov @gogabr ^igelhaus ^Prof1983 -/ets2panda/checker/types/ets/etsUnionType.* @akmaevaleksey ^vpukhov @gogabr ^igelhaus ^Prof1983 +/ets2panda/checker/types/ets/etsUnionType.* @akmaevaleksey ^vpukhov ^igelhaus ^Prof1983 /ets2panda/checker/types/ets/wildcardType.* ^vpukhov @gogabr ^igelhaus ^Prof1983 -/ets2panda/compiler/lowering/ets/ @akmaevaleksey @gogabr ^igelhaus ^Prof1983 ^zelentsovdmitry +/ets2panda/compiler/lowering/ets/ @gogabr ^igelhaus ^Prof1983 ^zelentsovdmitry /ets2panda/compiler/lowering/ets/const* @ziziziiziziz @lirismankarina ^akmaevaleksey ^igelhaus ^Prof1983 /ets2panda/compiler/lowering/ets/enum* @ziziziiziziz @dkofanov ^akmaevaleksey ^igelhaus ^Prof1983 /ets2panda/compiler/lowering/ets/lambdaLowering.cpp @Ekkoruse @gogabr ^vpukhov ^akmaevaleksey ^igelhaus ^Prof1983 /ets2panda/compiler/lowering/ets/localClassLowering.cpp @gogabr ^akmaevaleksey ^igelhaus ^Prof1983 -/ets2panda/compiler/lowering/ets/optionalLowering.cpp @zelentsovdmitry @akmaevaleksey ^vpukhov ^igelhaus ^Prof1983 +/ets2panda/compiler/lowering/ets/optionalLowering.cpp @akmaevaleksey ^vpukhov ^igelhaus ^Prof1983 /ets2panda/compiler/lowering/ets/spread* @ziziziiziziz @dkofanov ^akmaevaleksey ^igelhaus ^Prof1983 /ets2panda/compiler/lowering/ets/unionLowering.cpp @Ekkoruse @akmaevaleksey ^vpukhov ^igelhaus ^Prof1983 /ets2panda/compiler/lowering/ets/topLevelStmts/.* @lirismankarina @xuxjeeee ^akmaevaleksey ^vpukhov ^igelhaus ^Prof1983 \ No newline at end of file -- Gitee From b5f5eb0a4bbf298cca668ce58eb076b8f627cb2f Mon Sep 17 00:00:00 2001 From: Shimenkov Mikhail Date: Thu, 6 Mar 2025 16:25:38 +0300 Subject: [PATCH 020/268] Support methods in unions * Union member now can be resolved to instance method (ETSFunctionType) * Types constituting union should have only one common signature per method Issue: https://gitee.com/openharmony/arkcompiler_runtime_core/issues/IC0RFB Tests: ./runner.sh --astchecker -v short --build-dir $BUILD --processes all --filter "union_method*" Change-Id: I4cfd8b8795778f90b49fcbab72fdd064741180fc Signed-off-by: Shimenkov Mikhail --- ets2panda/ast_verifier/helpers.cpp | 25 ++++ ets2panda/checker/ETSchecker.h | 5 + ets2panda/checker/ets/helpers.cpp | 28 ++++ ets2panda/compiler/core/ETSCompiler.cpp | 16 ++- ets2panda/compiler/core/ETSGen.h | 11 ++ .../compiler/lowering/ets/lambdaLowering.cpp | 10 ++ .../compiler/lowering/ets/unionLowering.cpp | 120 +++++++++++++++--- ets2panda/compiler/lowering/util.cpp | 17 ++- ets2panda/ir/expressions/memberExpression.cpp | 34 ++++- ets2panda/ir/expressions/memberExpression.h | 3 +- .../test/ast/compiler/ets/union_method.ets | 38 ++++++ .../test/ast/compiler/ets/union_method_2.ets | 27 ++++ .../test/ast/compiler/ets/union_method_3.ets | 30 +++++ .../test/ast/compiler/ets/union_method_4.ets | 37 ++++++ .../test/ast/compiler/ets/union_method_5.ets | 45 +++++++ .../FixedArray/illegal_union_member_exp.ets | 1 - .../parser/ets/illegal_union_member_exp.ets | 1 - ets2panda/util/diagnostic/semantic.yaml | 4 + 18 files changed, 415 insertions(+), 37 deletions(-) create mode 100644 ets2panda/test/ast/compiler/ets/union_method.ets create mode 100644 ets2panda/test/ast/compiler/ets/union_method_2.ets create mode 100644 ets2panda/test/ast/compiler/ets/union_method_3.ets create mode 100644 ets2panda/test/ast/compiler/ets/union_method_4.ets create mode 100644 ets2panda/test/ast/compiler/ets/union_method_5.ets diff --git a/ets2panda/ast_verifier/helpers.cpp b/ets2panda/ast_verifier/helpers.cpp index 2d301294b8..13d55e496c 100644 --- a/ets2panda/ast_verifier/helpers.cpp +++ b/ets2panda/ast_verifier/helpers.cpp @@ -18,6 +18,7 @@ #include "checker/types/typeFlag.h" #include "checker/types/type.h" #include "checker/types/ets/etsObjectType.h" +#include "checker/types/ets/etsUnionType.h" #include "ir/statements/blockStatement.h" #include "ir/ets/etsModule.h" #include "parser/program/program.h" @@ -261,6 +262,22 @@ bool ValidateVariableAccess(const varbinder::LocalVariable *propVar, const ir::M if (propVarDeclNode == nullptr) { return false; } + + // NOTE: need to refactor: type of member expression object can be obtained via + // me->ObjType() or me->Object()->TsType() and they may differ!!!! + if (auto objType = const_cast(ast)->Object()->TsType(); objType->IsETSUnionType()) { + bool res = true; + for (auto type : objType->AsETSUnionType()->ConstituentTypes()) { + const_cast(ast)->SetObjectType(type->AsETSObjectType()); + // Just to skip enclosing if clause checking whether object tsType is ETSUnionType in subsequent recursive + // call + const_cast(ast)->Object()->SetTsType(type->AsETSObjectType()); + } + const_cast(ast)->SetObjectType(ast->ObjType()); + const_cast(ast)->Object()->SetTsType(objType); + return res; + } + auto *objType = ast->ObjType(); if (objType == nullptr) { return false; @@ -285,6 +302,8 @@ bool ValidateVariableAccess(const varbinder::LocalVariable *propVar, const ir::M bool ValidateMethodAccess(const ir::MemberExpression *memberExpression, const ir::CallExpression *ast) { + // NOTE: need to refactor: type of member expression object can be obtained via + // me->ObjType() or me->Object()->TsType() and they may differ!!!! if (memberExpression->Object()->TsType() != nullptr) { // When calling enum methods member expression // object has ETSEnumType instead of ETSObjectType. @@ -292,6 +311,12 @@ bool ValidateMethodAccess(const ir::MemberExpression *memberExpression, const ir if (type->IsETSEnumType()) { return true; } + + // When calling enum methods member expression + // object has ETSUnionType instead of ETSObjectType. + if (type->IsETSUnionType()) { + return true; + } } auto *memberObjType = memberExpression->ObjType(); diff --git a/ets2panda/checker/ETSchecker.h b/ets2panda/checker/ETSchecker.h index 705a5df68c..58efdaa101 100644 --- a/ets2panda/checker/ETSchecker.h +++ b/ets2panda/checker/ETSchecker.h @@ -870,6 +870,11 @@ public: overloadSigContainer_.clear(); } + // This helper finds the intersection of two callSignatures sets + // The result is stored in callSignatures of newly created ETSFunctionType + checker::ETSFunctionType *IntersectSignatureSets(const checker::ETSFunctionType *left, + const checker::ETSFunctionType *right); + private: std::pair GetTargetIdentifierAndType(ir::Identifier *ident); void NotResolvedError(ir::Identifier *const ident, const varbinder::Variable *classVar, diff --git a/ets2panda/checker/ets/helpers.cpp b/ets2panda/checker/ets/helpers.cpp index 6b922f282c..0ecd59533b 100644 --- a/ets2panda/checker/ets/helpers.cpp +++ b/ets2panda/checker/ets/helpers.cpp @@ -3054,4 +3054,32 @@ void ETSChecker::SetPreferredTypeIfPossible(ir::Expression *const expr, Type *co } } +checker::ETSFunctionType *ETSChecker::IntersectSignatureSets(const checker::ETSFunctionType *left, + const checker::ETSFunctionType *right) +{ + auto sameSig = [this](checker::Signature *leftSig, checker::Signature *rightSig) { + auto relation = Relation(); + if (leftSig->Flags() != rightSig->Flags()) { + return false; + } + return relation->SignatureIsIdenticalTo(rightSig, leftSig); + }; + + if (left->CallSignatures().size() > right->CallSignatures().size()) { + std::swap(left, right); + } + + ArenaVector intersection {Allocator()->Adapter()}; + + for (const auto sig : left->CallSignatures()) { + auto found = right->FindSpecificSignature( + [sig, &sameSig](checker::Signature *otherSig) { return sameSig(sig, otherSig); }); + if (found != nullptr) { + intersection.push_back(found); + } + } + + return CreateETSMethodType(left->Name(), std::move(intersection)); +} + } // namespace ark::es2panda::checker diff --git a/ets2panda/compiler/core/ETSCompiler.cpp b/ets2panda/compiler/core/ETSCompiler.cpp index 3246445f6e..273562d68e 100644 --- a/ets2panda/compiler/core/ETSCompiler.cpp +++ b/ets2panda/compiler/core/ETSCompiler.cpp @@ -750,9 +750,19 @@ void ETSCompiler::EmitCall(const ir::CallExpression *expr, compiler::VReg &calle } if (signature->HasSignatureFlag(checker::SignatureFlags::STATIC)) { etsg->CallExact(expr, expr->Signature(), expr->Arguments()); - } else if ((expr->Callee()->IsMemberExpression() && - expr->Callee()->AsMemberExpression()->Object()->IsSuperExpression())) { - etsg->CallExact(expr, signature, calleeReg, expr->Arguments()); + } else if (expr->Callee()->IsMemberExpression()) { + auto me = expr->Callee()->AsMemberExpression(); + auto obj = me->Object(); + if (obj->IsSuperExpression()) { + etsg->CallExact(expr, signature, calleeReg, expr->Arguments()); + // NOTE: need to refactor: type of member expression object can be obtained via + // me->ObjType() or me->Object()->TsType() and they may differ!!!! + } else if (me->ObjType() == etsg->Checker()->GlobalETSObjectType() && + me->Object()->TsType()->IsETSUnionType()) { + etsg->CallByName(expr, signature, calleeReg, expr->Arguments()); + } else { + etsg->CallVirtual(expr, signature, calleeReg, expr->Arguments()); + } } else { etsg->CallVirtual(expr, signature, calleeReg, expr->Arguments()); } diff --git a/ets2panda/compiler/core/ETSGen.h b/ets2panda/compiler/core/ETSGen.h index 0b99a46953..02f2b0a348 100644 --- a/ets2panda/compiler/core/ETSGen.h +++ b/ets2panda/compiler/core/ETSGen.h @@ -350,6 +350,17 @@ public: Ra().Emit(node, name, arg0, arg1, arg2, dummyReg_); } + void CallByName([[maybe_unused]] const ir::AstNode *const node, + [[maybe_unused]] const checker::Signature *signature, [[maybe_unused]] const VReg arg0, + [[maybe_unused]] const ArenaVector &arguments) + { +#ifdef PANDA_WITH_ETS + CallArgStart(node, signature, arg0, arguments); +#else + ES2PANDA_UNREACHABLE(); +#endif + } + void CallVirtual(const ir::AstNode *const node, const checker::Signature *signature, const VReg athis, const ArenaVector &arguments) { diff --git a/ets2panda/compiler/lowering/ets/lambdaLowering.cpp b/ets2panda/compiler/lowering/ets/lambdaLowering.cpp index 7805edd435..546ed9e39f 100644 --- a/ets2panda/compiler/lowering/ets/lambdaLowering.cpp +++ b/ets2panda/compiler/lowering/ets/lambdaLowering.cpp @@ -1044,6 +1044,16 @@ static bool IsFunctionOrMethodCall(ir::CallExpression const *node) return true; } + // NOTE: Skip if invoke pattern Union.() + // Not skip if invoke pattern Union.() where field is of ETSArrowType + if (callee->IsMemberExpression()) { + auto me = callee->AsMemberExpression(); + if (me->Object()->TsType() != nullptr && me->Object()->TsType()->IsETSUnionType() && + me->TsType()->IsETSMethodType()) { + return true; + } + } + varbinder::Variable *var = nullptr; if (callee->IsMemberExpression() && (callee->AsMemberExpression()->Kind() & ir::MemberExpressionKind::PROPERTY_ACCESS) != 0) { diff --git a/ets2panda/compiler/lowering/ets/unionLowering.cpp b/ets2panda/compiler/lowering/ets/unionLowering.cpp index 9fcbc35418..80fe82ec8c 100644 --- a/ets2panda/compiler/lowering/ets/unionLowering.cpp +++ b/ets2panda/compiler/lowering/ets/unionLowering.cpp @@ -13,12 +13,17 @@ * limitations under the License. */ +#include #include "unionLowering.h" +#include "compiler/lowering/scopesInit/scopesInitPhase.h" +#include "compiler/lowering/util.h" #include "varbinder/ETSBinder.h" #include "checker/ETSchecker.h" namespace ark::es2panda::compiler { +static constexpr std::string_view PREFIX = "$NamedAccessMeta-"; + static void ReplaceAll(std::string &str, std::string_view substr, std::string_view replacement) { for (size_t pos = str.find(substr, 0); pos != std::string::npos; pos = str.find(substr, pos)) { @@ -27,13 +32,14 @@ static void ReplaceAll(std::string &str, std::string_view substr, std::string_vi } } -static std::string GetAccessClassName(checker::Type *fieldType) +static std::string GetAccessClassName(const checker::ETSUnionType *unionType) { std::stringstream ss; - ss << "$NamedAccessMeta-"; - fieldType->ToAssemblerTypeWithRank(ss); + ss << PREFIX; + unionType->ToString(ss, false); std::string res(ss.str()); std::replace(res.begin(), res.end(), '.', '-'); + std::replace(res.begin(), res.end(), '|', '_'); ReplaceAll(res, "[]", "[$]$"); return res; } @@ -54,7 +60,7 @@ static ir::ClassDefinition *GetUnionAccessClass(checker::ETSChecker *checker, va auto classCtx = varbinder::LexicalScope(varbinder); auto *classDef = checker->AllocNode(checker->Allocator(), ident, ir::ClassDefinitionModifiers::GLOBAL, - ir::ModifierFlags::FINAL, Language(Language::Id::ETS)); + ir::ModifierFlags::ABSTRACT, Language(Language::Id::ETS)); classDef->SetScope(classCtx.GetScope()); auto *classDecl = checker->AllocNode(classDef, checker->Allocator()); classDef->Scope()->BindNode(classDecl->Definition()); @@ -70,21 +76,67 @@ static ir::ClassDefinition *GetUnionAccessClass(checker::ETSChecker *checker, va return classDef; } -static varbinder::LocalVariable *CreateNamedAccessProperty(checker::ETSChecker *checker, - varbinder::VarBinder *varbinder, checker::Type *fieldType, - const util::StringView &propName) +static std::tuple CreateNamedAccessMethod( + checker::ETSChecker *checker, varbinder::VarBinder *varbinder, ir::MemberExpression *expr) { - auto *const allocator = checker->Allocator(); - auto *const accessClass = GetUnionAccessClass(checker, varbinder, GetAccessClassName(fieldType)); - auto *classScope = accessClass->Scope()->AsClassScope(); + auto allocator = checker->Allocator(); + auto unionType = checker->GetApparentType(checker->GetNonNullishType(expr->Object()->TsType()))->AsETSUnionType(); + auto *const accessClass = GetUnionAccessClass(checker, varbinder, GetAccessClassName(unionType)); + auto methodType = expr->TsType()->AsETSFunctionType(); + auto methodName = methodType->Name(); - // Enter the union filed class instance field scope - auto fieldCtx = varbinder::LexicalScope::Enter(varbinder, classScope->InstanceFieldScope()); + // Create method name for synthetic class + auto *methodIdent = checker->AllocNode(methodName, allocator); - if (auto *var = classScope->FindLocal(propName, varbinder::ResolveBindingOptions::VARIABLES); var != nullptr) { - ES2PANDA_ASSERT(checker->IsTypeIdenticalTo(var->TsType(), fieldType)); - return var->AsLocalVariable(); + // Create the synthetic function node + auto *sig = methodType->CallSignatures().front(); + + ArenaVector params {allocator->Adapter()}; + for (auto param : sig->Function()->Params()) { + params.emplace_back(param->Clone(allocator, nullptr)->AsETSParameterExpression()); } + auto returnTypeAnno = sig->Function()->ReturnTypeAnnotation() != nullptr + ? sig->Function()->ReturnTypeAnnotation()->Clone(allocator, nullptr) + : checker->AllocNode(sig->ReturnType(), allocator); + + auto *func = checker->AllocNode( + allocator, ir::ScriptFunction::ScriptFunctionData { + // CC-OFFNXT(G.FMT.02-CPP) project code style + nullptr, ir::FunctionSignature(nullptr, std::move(params), returnTypeAnno), + // CC-OFFNXT(G.FMT.02-CPP) project code style + ir::ScriptFunctionFlags::METHOD, ir::ModifierFlags::PUBLIC | ir::ModifierFlags::ABSTRACT}); + func->SetIdent(methodIdent->Clone(allocator, nullptr)); + + // Create the synthetic function node + auto *funcExpr = checker->AllocNode(func); + + // Create the synthetic method definition node + auto *method = checker->AllocNode(ir::MethodDefinitionKind::METHOD, methodIdent, funcExpr, + ir::ModifierFlags::PUBLIC | ir::ModifierFlags::ABSTRACT, + allocator, false); + ArenaVector methodDecl {allocator->Adapter()}; + methodDecl.push_back(method); + accessClass->AddProperties(std::move(methodDecl)); + + { + auto clsCtx = + varbinder::LexicalScope::Enter(varbinder, accessClass->Scope()->AsClassScope()); + auto boundCtx = varbinder::BoundContext(varbinder->AsETSBinder()->GetRecordTable(), accessClass, true); + CheckLoweredNode(varbinder->AsETSBinder(), checker, method); + } + + return {method->Id()->Variable()->AsLocalVariable(), + method->TsType()->AsETSFunctionType()->CallSignatures().front()}; +} + +static varbinder::LocalVariable *CreateNamedAccessProperty(checker::ETSChecker *checker, + varbinder::VarBinder *varbinder, ir::MemberExpression *expr) +{ + auto *const allocator = checker->Allocator(); + auto unionType = checker->GetApparentType(checker->GetNonNullishType(expr->Object()->TsType()))->AsETSUnionType(); + auto *const accessClass = GetUnionAccessClass(checker, varbinder, GetAccessClassName(unionType)); + auto propName = expr->Property()->AsIdentifier()->Name(); + auto fieldType = expr->TsType(); // Create field name for synthetic class auto *fieldIdent = checker->AllocNode(propName, allocator); @@ -107,6 +159,39 @@ static varbinder::LocalVariable *CreateNamedAccessProperty(checker::ETSChecker * return var->AsLocalVariable(); } +static varbinder::LocalVariable *CreateNamedAccess(checker::ETSChecker *checker, varbinder::VarBinder *varbinder, + ir::MemberExpression *expr) +{ + auto type = expr->TsType(); + auto name = expr->Property()->AsIdentifier()->Name(); + + auto unionType = checker->GetApparentType(checker->GetNonNullishType(expr->Object()->TsType()))->AsETSUnionType(); + auto *const accessClass = GetUnionAccessClass(checker, varbinder, GetAccessClassName(unionType)); + auto *classScope = accessClass->Scope()->AsClassScope(); + + if (auto *var = classScope->FindLocal(name, varbinder::ResolveBindingOptions::ALL_NON_STATIC); var != nullptr) { + return var->AsLocalVariable(); + } + + // arrow type fields should be processed as property access not method invocation + if (type->IsETSMethodType() && !type->IsETSArrowType()) { + if (type->AsETSFunctionType()->CallSignatures().size() != 1) { + checker->LogError(diagnostic::UNION_METHOD_SIGNATURE, {}, expr->Start()); + } + auto parent = expr->Parent(); + ES2PANDA_ASSERT(parent->IsCallExpression() && parent->AsCallExpression()->Callee() == expr && + parent->AsCallExpression()->Signature()->HasFunction()); + auto [var, sig] = CreateNamedAccessMethod(checker, varbinder, expr); + ES2PANDA_ASSERT(parent->IsCallExpression()); + parent->AsCallExpression()->SetSignature(sig); + return var; + } + + // Enter the union filed class instance field scope + auto fieldCtx = varbinder::LexicalScope::Enter(varbinder, classScope->InstanceFieldScope()); + return CreateNamedAccessProperty(checker, varbinder, expr); +} + static void HandleUnionPropertyAccess(checker::ETSChecker *checker, varbinder::VarBinder *vbind, ir::MemberExpression *expr) { @@ -115,10 +200,7 @@ static void HandleUnionPropertyAccess(checker::ETSChecker *checker, varbinder::V } [[maybe_unused]] auto const *const parent = expr->Parent(); - ES2PANDA_ASSERT(!(parent->IsCallExpression() && parent->AsCallExpression()->Callee() == expr && - !parent->AsCallExpression()->Signature()->HasFunction())); - expr->SetPropVar( - CreateNamedAccessProperty(checker, vbind, expr->TsType(), expr->Property()->AsIdentifier()->Name())); + expr->SetPropVar(CreateNamedAccess(checker, vbind, expr)); ES2PANDA_ASSERT(expr->PropVar() != nullptr); } diff --git a/ets2panda/compiler/lowering/util.cpp b/ets2panda/compiler/lowering/util.cpp index 43f7b3c500..452d7daa97 100644 --- a/ets2panda/compiler/lowering/util.cpp +++ b/ets2panda/compiler/lowering/util.cpp @@ -248,13 +248,22 @@ void CheckLoweredNode(varbinder::ETSBinder *varBinder, checker::ETSChecker *chec auto *scope = NearestScope(node); varBinder->ResolveReferencesForScopeWithContext(node, scope); - auto *containingClass = ContainingClass(node); - checker::CheckerStatus newStatus = - (containingClass == nullptr) ? checker::CheckerStatus::NO_OPTS : checker::CheckerStatus::IN_CLASS; + checker::CheckerStatus newStatus = checker::CheckerStatus::NO_OPTS; + auto *containingClass = util::Helpers::GetContainingClassDefinition(node); + + if (containingClass != nullptr) { + if (containingClass->IsAbstract()) { + newStatus = checker::CheckerStatus::IN_ABSTRACT; + } else { + newStatus = checker::CheckerStatus::IN_CLASS; + } + } + if ((checker->Context().Status() & checker::CheckerStatus::IN_EXTENSION_ACCESSOR_CHECK) != 0) { newStatus |= checker::CheckerStatus::IN_EXTENSION_ACCESSOR_CHECK; } - auto checkerCtx = checker::SavedCheckerContext(checker, newStatus, containingClass); + auto checkerCtx = checker::SavedCheckerContext( + checker, newStatus, containingClass != nullptr ? containingClass->TsType()->AsETSObjectType() : nullptr); auto scopeCtx = checker::ScopeContext(checker, scope); node->Check(checker); diff --git a/ets2panda/ir/expressions/memberExpression.cpp b/ets2panda/ir/expressions/memberExpression.cpp index 551f13d4a9..f5c1ff44e7 100644 --- a/ets2panda/ir/expressions/memberExpression.cpp +++ b/ets2panda/ir/expressions/memberExpression.cpp @@ -189,18 +189,38 @@ std::pair MemberExpression::Resolve } } -checker::Type *MemberExpression::TraverseUnionMember(checker::ETSChecker *checker, checker::ETSUnionType *unionType, - checker::Type *commonPropType) +checker::Type *MemberExpression::TraverseUnionMember(checker::ETSChecker *checker, checker::ETSUnionType *unionType) { + checker::Type *commonPropType = nullptr; + auto const addPropType = [this, checker, &commonPropType](checker::Type *memberType) { - if ((memberType != nullptr && memberType->IsETSMethodType()) || - (commonPropType != nullptr && !checker->IsTypeIdenticalTo(commonPropType, memberType))) { - checker->LogError(diagnostic::MEMBER_TYPE_MISMATCH_ACROSS_UNION, {}, Start()); - } else { + if (commonPropType == nullptr) { commonPropType = memberType; + return; + } + + if (memberType == nullptr) { + checker->LogError(diagnostic::MEMBER_TYPE_MISMATCH_ACROSS_UNION, {}, Start()); + return; + } + + if (!commonPropType->IsETSMethodType() && !memberType->IsETSMethodType()) { + if (!checker->IsTypeIdenticalTo(commonPropType, memberType)) { + checker->LogError(diagnostic::MEMBER_TYPE_MISMATCH_ACROSS_UNION, {}, Start()); + } + return; } + + auto newType = + checker->IntersectSignatureSets(commonPropType->AsETSFunctionType(), memberType->AsETSFunctionType()); + if (newType->AsETSFunctionType()->CallSignatures().empty()) { + checker->LogError(diagnostic::MEMBER_TYPE_MISMATCH_ACROSS_UNION, {}, Start()); + } + + commonPropType = newType; }; + for (auto *const type : unionType->ConstituentTypes()) { auto *const apparent = checker->GetApparentType(type); if (apparent->IsETSObjectType()) { @@ -221,7 +241,7 @@ checker::Type *MemberExpression::CheckUnionMember(checker::ETSChecker *checker, checker->LogTypeError("Static union member expression cannot be interpreted.", Start()); return checker->GlobalTypeError(); } - auto *const commonPropType = TraverseUnionMember(checker, unionType, nullptr); + auto *const commonPropType = TraverseUnionMember(checker, unionType); SetObjectType(checker->GlobalETSObjectType()); return commonPropType; } diff --git a/ets2panda/ir/expressions/memberExpression.h b/ets2panda/ir/expressions/memberExpression.h index 8280c4d60d..2a8ee863c6 100644 --- a/ets2panda/ir/expressions/memberExpression.h +++ b/ets2panda/ir/expressions/memberExpression.h @@ -246,8 +246,7 @@ private: checker::Type *SetAndAdjustType(checker::ETSChecker *checker, checker::ETSObjectType *objectType); checker::Type *CheckComputed(checker::ETSChecker *checker, checker::Type *baseType); checker::Type *CheckUnionMember(checker::ETSChecker *checker, checker::Type *baseType); - checker::Type *TraverseUnionMember(checker::ETSChecker *checker, checker::ETSUnionType *unionType, - checker::Type *commonPropType); + checker::Type *TraverseUnionMember(checker::ETSChecker *checker, checker::ETSUnionType *unionType); bool CheckArrayIndexValue(checker::ETSChecker *checker) const; checker::Type *CheckIndexAccessMethod(checker::ETSChecker *checker); diff --git a/ets2panda/test/ast/compiler/ets/union_method.ets b/ets2panda/test/ast/compiler/ets/union_method.ets new file mode 100644 index 0000000000..8820ee691a --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/union_method.ets @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class A { + short(v: string): void {} + ordinary(a: int, b: int, c: int): void {} + range(a: int, b: int, c: int, d: int, e: int, f: int): void {} +} + +class B { + short(v: string): void {} + ordinary(a: int, b: int, c: int): void {} + range(a: int, b: int, c: int, d: int, e: int, f: int): void {} +} + +function short(x: A|B) { + x.short("123") +} + +function ordinary(x: A|B) { + x.ordinary(1, 2, 3) +} + +function range(x: A|B) { + x.range(1, 2, 3, 4, 5, 6) +} diff --git a/ets2panda/test/ast/compiler/ets/union_method_2.ets b/ets2panda/test/ast/compiler/ets/union_method_2.ets new file mode 100644 index 0000000000..73d2e9bd7e --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/union_method_2.ets @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class A { + foo(v: string): void {} + foo(v: int): void {} +} + +class B { + foo(v: string): void {} +} + +function foo(x: A|B) { + x.foo("123") +} diff --git a/ets2panda/test/ast/compiler/ets/union_method_3.ets b/ets2panda/test/ast/compiler/ets/union_method_3.ets new file mode 100644 index 0000000000..a6c0a9191e --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/union_method_3.ets @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class A { + foo(v: string): void {} + foo(v: int): void {} +} + +class B { + foo(v: string): void {} + foo(v: int): void {} +} + +function foo(x: A|B) { + /* @@ label */x.foo("123") +} + +/* @@@ label Error TypeError: Union constituent types should have only one common method signature. */ diff --git a/ets2panda/test/ast/compiler/ets/union_method_4.ets b/ets2panda/test/ast/compiler/ets/union_method_4.ets new file mode 100644 index 0000000000..ec919acd34 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/union_method_4.ets @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class A { + private foo(v: string): void {} + private bar(v: string): void {} +} + +class B { + foo(v: string): void {} + private bar(v: string): void {} +} + +function foo(x: A|B) { + /* @@ label */x.foo("123") +} + +function bar(x: A|B) { + /* @@ label2 */x.bar("123") +} + +/* @@@ label Error TypeError: Member type must be the same for all union objects. */ +/* @@@ label Error TypeError: No matching call signature */ +/* @@@ label2 Error TypeError: Signature bar(v: String): void is not visible here. */ +/* @@@ label2 Error TypeError: No matching call signature for bar("123") */ diff --git a/ets2panda/test/ast/compiler/ets/union_method_5.ets b/ets2panda/test/ast/compiler/ets/union_method_5.ets new file mode 100644 index 0000000000..53e5d86368 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/union_method_5.ets @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class A { + foo(v: string) { console.log("A:" + v) } +} + +class B extends A { + foo(v: string) { console.log("B:" + v) } +} + +class C { + foo(v: string) { console.log("C:" + v) } +} + +class D extends C {} + +function test1(v: A|C) { + v.foo("123") +} + +function test2(v: B|C) { + v.foo("123") +} + +function test3(v: B|D) { + v.foo("123") +} + +test1(new A()) +test1(new C()) +test2(new B()) +test3(new D()) diff --git a/ets2panda/test/ast/parser/ets/FixedArray/illegal_union_member_exp.ets b/ets2panda/test/ast/parser/ets/FixedArray/illegal_union_member_exp.ets index 5267d9b7a5..ce9fff73c6 100644 --- a/ets2panda/test/ast/parser/ets/FixedArray/illegal_union_member_exp.ets +++ b/ets2panda/test/ast/parser/ets/FixedArray/illegal_union_member_exp.ets @@ -22,5 +22,4 @@ function main(): void { /* @@ label */b.toString(); } -/* @@? 22:19 Error TypeError: Member type must be the same for all union objects. */ /* @@? 22:19 Error TypeError: Type String|int[] is illegal in union member expression. */ diff --git a/ets2panda/test/ast/parser/ets/illegal_union_member_exp.ets b/ets2panda/test/ast/parser/ets/illegal_union_member_exp.ets index ceba1bde64..bb8deca84f 100644 --- a/ets2panda/test/ast/parser/ets/illegal_union_member_exp.ets +++ b/ets2panda/test/ast/parser/ets/illegal_union_member_exp.ets @@ -22,5 +22,4 @@ function main(): void { /* @@ label */b.toString(); } -/* @@@ label Error TypeError: Member type must be the same for all union objects. */ /* @@@ label Error TypeError: Type String|int[] is illegal in union member expression. */ diff --git a/ets2panda/util/diagnostic/semantic.yaml b/ets2panda/util/diagnostic/semantic.yaml index 1ce3c79fce..7462253772 100644 --- a/ets2panda/util/diagnostic/semantic.yaml +++ b/ets2panda/util/diagnostic/semantic.yaml @@ -1106,3 +1106,7 @@ semantic: - name: LOCAL_CLASS_NATIVE_METHOD id: 278 message: "Local class '{}' shouldn't have native methods/constructors" + +- name: UNION_METHOD_SIGNATURE + id: 279 + message: "Union constituent types should have only one common method signature." -- Gitee From 5806f9d7b51161cc86d7dda162212bb9febcd949 Mon Sep 17 00:00:00 2001 From: lijunru Date: Fri, 11 Apr 2025 13:09:44 +0800 Subject: [PATCH 021/268] Fix memory leak Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC0CDF Signed-off-by: lijunru --- ets2panda/bindings/native/src/common.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/ets2panda/bindings/native/src/common.cpp b/ets2panda/bindings/native/src/common.cpp index aac4aec58b..cad9c7d8d6 100644 --- a/ets2panda/bindings/native/src/common.cpp +++ b/ets2panda/bindings/native/src/common.cpp @@ -93,10 +93,15 @@ inline KUInt UnpackUInt(const KByte *bytes) return (bytes[0] | (bytes[1] << 8U) | (bytes[2U] << 16U) | (bytes[3U] << 24U)); } +inline std::string_view GetStringView(KStringPtr &ptr) +{ + return std::string_view(ptr.c_str(), static_cast(ptr.length())); +} + KNativePointer impl_CreateConfig(KInt argc, KStringArray argvPtr, KStringPtr &pandaLibPath) { const std::size_t HEADER_LEN = 4; - g_pandaLibPath = GetStringCopy(pandaLibPath); + g_pandaLibPath = GetStringView(pandaLibPath); const char **argv = new const char *[static_cast(argc)]; std::size_t position = HEADER_LEN; std::size_t strLen; -- Gitee From 1128bab38b9b28f81ef6ecd1ef0083faff1c7ea8 Mon Sep 17 00:00:00 2001 From: yaohaosen Date: Thu, 10 Apr 2025 17:09:39 +0800 Subject: [PATCH 022/268] [LSP API] Completion support extend member Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC04J8 Signed-off-by: yaohaosen --- ets2panda/bindings/src/lsp_helper.ts | 2 +- ets2panda/lsp/include/completions.h | 1 + ets2panda/lsp/src/completions.cpp | 155 +++++++++++++++++--- ets2panda/test/unit/lsp/get_completions.cpp | 143 ++++++++++++++++-- 4 files changed, 266 insertions(+), 35 deletions(-) diff --git a/ets2panda/bindings/src/lsp_helper.ts b/ets2panda/bindings/src/lsp_helper.ts index 0d72468760..edf58c1f21 100644 --- a/ets2panda/bindings/src/lsp_helper.ts +++ b/ets2panda/bindings/src/lsp_helper.ts @@ -289,7 +289,7 @@ export class Lsp { } else { source += wildcard; } - offset += wildcard.length - 1; + offset += wildcard.length; } let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg) PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx) diff --git a/ets2panda/lsp/include/completions.h b/ets2panda/lsp/include/completions.h index df8c4480a1..d776bb06f1 100644 --- a/ets2panda/lsp/include/completions.h +++ b/ets2panda/lsp/include/completions.h @@ -208,6 +208,7 @@ std::optional IsCompletionEntryDataResolved(ark::es2panda::lsp::Completion bool StartsWith(const std::string &str, const std::string &prefix); std::shared_ptr GetArkTsConfigFromFile(const char *fileName); +std::vector GetPropertyCompletions(ir::AstNode *preNode, const std::string &triggerWord); } // namespace ark::es2panda::lsp #endif diff --git a/ets2panda/lsp/src/completions.cpp b/ets2panda/lsp/src/completions.cpp index a4d6d2cdb8..099804f827 100644 --- a/ets2panda/lsp/src/completions.cpp +++ b/ets2panda/lsp/src/completions.cpp @@ -309,10 +309,133 @@ std::vector GetEntriesForEnumDeclaration( return completions; } +ir::AstNode *GetIdentifierFromSuper(ir::AstNode *super) +{ + if (super == nullptr || !super->IsETSTypeReference()) { + return nullptr; + } + auto part = super->AsETSTypeReference()->Part(); + if (part == nullptr || !part->IsETSTypeReferencePart()) { + return nullptr; + } + return part->AsETSTypeReferencePart()->Name(); +} + +std::vector GetCompletionFromClassDefinition(ir::ClassDefinition *decl, const std::string &triggerWord) +{ + // After enum refactoring, enum declaration is transformed to a class declaration + if (compiler::ClassDefinitionIsEnumTransformed(decl)) { + if (decl->AsClassDefinition()->OrigEnumDecl() == nullptr) { + return {}; + } + auto members = decl->AsClassDefinition()->OrigEnumDecl()->AsTSEnumDeclaration()->Members(); + auto qualifiedMembers = FilterFromEnumMember(members, triggerWord); + return GetEntriesForEnumDeclaration(qualifiedMembers); + } + auto bodyNodes = decl->AsClassDefinition()->Body(); + std::vector extendCompletions; + auto super = decl->AsClassDefinition()->Super(); + if (super != nullptr) { + auto ident = GetIdentifierFromSuper(super); + extendCompletions = GetPropertyCompletions(ident, triggerWord); + } + auto propertyNodes = FilterFromBody(bodyNodes, triggerWord); + auto res = GetEntriesForClassDeclaration(propertyNodes); + res.insert(res.end(), extendCompletions.begin(), extendCompletions.end()); + return res; +} + +ir::AstNode *GetIdentifierFromTSInterfaceHeritage(ir::TSInterfaceHeritage *extend) +{ + if (extend == nullptr) { + return nullptr; + } + auto expr = extend->Expr(); + if (expr == nullptr) { + return nullptr; + } + auto part = expr->AsETSTypeReference()->Part(); + if (part == nullptr) { + return nullptr; + } + return part->AsETSTypeReferencePart()->Name(); +} + +std::vector GetCompletionFromTSInterfaceDeclaration(ir::TSInterfaceDeclaration *decl, + const std::string &triggerWord) +{ + std::vector completions; + auto body = decl->AsTSInterfaceDeclaration()->Body(); + if (body == nullptr) { + return {}; + } + auto bodies = body->Body(); + std::vector extendCompletions; + auto extends = decl->AsTSInterfaceDeclaration()->Extends(); + for (auto extend : extends) { + auto ident = GetIdentifierFromTSInterfaceHeritage(extend); + if (ident != nullptr && ident->IsIdentifier()) { + auto extendInterf = compiler::DeclarationFromIdentifier(ident->AsIdentifier()); + auto extendCom = + extendInterf->IsTSInterfaceDeclaration() + ? GetCompletionFromTSInterfaceDeclaration(extendInterf->AsTSInterfaceDeclaration(), triggerWord) + : completions; + extendCompletions.insert(extendCompletions.end(), extendCom.begin(), extendCom.end()); + } + } + auto qualifiedBodies = FilterFromInterfaceBody(bodies, triggerWord); + auto res = GetEntriesForTSInterfaceDeclaration(qualifiedBodies); + res.insert(res.end(), extendCompletions.begin(), extendCompletions.end()); + return res; +} + +std::vector GetCompletionFromMethodDefinition(ir::MethodDefinition *decl, + const std::string &triggerWord) +{ + auto value = decl->AsMethodDefinition()->Value(); + if (value == nullptr && !value->IsFunctionExpression()) { + return {}; + } + auto func = value->AsFunctionExpression()->Function(); + if (func == nullptr && func->ReturnTypeAnnotation() == nullptr) { + return {}; + } + auto returnType = func->ReturnTypeAnnotation(); + if (returnType == nullptr || !returnType->IsETSTypeReference()) { + return {}; + } + auto ident = returnType->AsETSTypeReference()->Part()->Name(); + if (ident == nullptr || !ident->IsIdentifier()) { + return {}; + } + return GetPropertyCompletions(reinterpret_cast(ident), triggerWord); +} + +ir::AstNode *GetIndentifierFromCallExpression(ir::AstNode *node) +{ + if (!node->IsCallExpression()) { + return nullptr; + } + auto callee = node->AsCallExpression()->Callee(); + if (callee != nullptr && callee->IsMemberExpression()) { + auto object = callee->AsMemberExpression()->Object(); + if (object->IsCallExpression()) { + return GetIndentifierFromCallExpression(object); + } + } + return callee; +} + std::vector GetPropertyCompletions(ir::AstNode *preNode, const std::string &triggerWord) { std::vector completions; - if (preNode == nullptr || !preNode->IsIdentifier()) { + if (preNode == nullptr) { + return completions; + } + if (preNode->IsCallExpression()) { + preNode = GetIndentifierFromCallExpression(preNode); + } + if (!preNode->IsIdentifier()) { return completions; } auto decl = compiler::DeclarationFromIdentifier(preNode->AsIdentifier()); @@ -328,29 +451,14 @@ std::vector GetPropertyCompletions(ir::AstNode *preNode, const if (decl == nullptr) { return completions; } + if (decl->IsMethodDefinition()) { + return GetCompletionFromMethodDefinition(decl->AsMethodDefinition(), triggerWord); + } if (decl->IsTSInterfaceDeclaration()) { - auto body = decl->AsTSInterfaceDeclaration()->Body(); - if (body == nullptr) { - return completions; - } - auto bodies = body->Body(); - auto qualifiedBodies = FilterFromInterfaceBody(bodies, triggerWord); - return GetEntriesForTSInterfaceDeclaration(qualifiedBodies); + return GetCompletionFromTSInterfaceDeclaration(decl->AsTSInterfaceDeclaration(), triggerWord); } if (decl->IsClassDefinition()) { - // After enum refactoring, enum declaration is transformed to a class declaration - if (compiler::ClassDefinitionIsEnumTransformed(decl)) { - if (decl->AsClassDefinition()->OrigEnumDecl() == nullptr) { - return completions; - } - auto members = decl->AsClassDefinition()->OrigEnumDecl()->AsTSEnumDeclaration()->Members(); - auto qualifiedMembers = FilterFromEnumMember(members, triggerWord); - completions = GetEntriesForEnumDeclaration(qualifiedMembers); - } else { - auto bodyNodes = decl->AsClassDefinition()->Body(); - auto propertyNodes = FilterFromBody(bodyNodes, triggerWord); - completions = GetEntriesForClassDeclaration(propertyNodes); - } + return GetCompletionFromClassDefinition(decl->AsClassDefinition(), triggerWord); } return completions; } @@ -563,12 +671,11 @@ std::vector GetCompletionsAtPositionImpl(es2panda_Context *cont auto allocator = ctx->allocator; std::string sourceCode(ctx->parserProgram->SourceCode()); // Current GetPrecedingPosition cannot get token of "obj." with position. - auto position = GetPrecedingTokenPosition(sourceCode, pos); - auto precedingToken = FindPrecedingToken(position, ctx->parserProgram->Ast(), allocator); + auto precedingToken = FindPrecedingToken(pos, ctx->parserProgram->Ast(), allocator); if (precedingToken == nullptr) { return {}; } - auto triggerValue = sourceCode.substr(precedingToken->Start().index, pos - precedingToken->Start().index + 1); + auto triggerValue = GetCurrentTokenValueImpl(context, pos); // Unsupported yet because of ast parsing problem if (IsEndWithValidPoint(triggerValue)) { return GetPropertyCompletions(precedingToken, ""); diff --git a/ets2panda/test/unit/lsp/get_completions.cpp b/ets2panda/test/unit/lsp/get_completions.cpp index 6f7319236a..52c94ee42d 100644 --- a/ets2panda/test/unit/lsp/get_completions.cpp +++ b/ets2panda/test/unit/lsp/get_completions.cpp @@ -59,6 +59,129 @@ void AssertCompletionsContainAndNotContainEntries(const std::vector files = {"getCompletionsAtPosition16.ets"}; + std::vector texts = {R"delimiter( +export interface Method { + get(value: number): this; +} +export interface CommonMethod { + width(value: number): this; + height(value: number): this; +} +export interface TextAttribute extends CommonMethod { + font(value: number): this; + fontColor(value: number): this; +} +export declare function Text( + content?: string, + value?: string +): TextAttribute +Text("Hello").font()._WILDCARD +)delimiter"}; + auto filePaths = CreateTempFile(files, texts); + + int const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + + LSPAPI const *lspApi = GetImpl(); + size_t const offset = 385; // after 'j._WILDCARD' + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + auto res = lspApi->getCompletionsAtPosition(ctx, offset); + auto expectedEntries = std::vector { + CompletionEntry("font", ark::es2panda::lsp::CompletionEntryKind::METHOD, std::string(CLASS_MEMBER_SNIPPETS)), + CompletionEntry("fontColor", ark::es2panda::lsp::CompletionEntryKind::METHOD, + std::string(CLASS_MEMBER_SNIPPETS)), + CompletionEntry("width", ark::es2panda::lsp::CompletionEntryKind::METHOD, std::string(CLASS_MEMBER_SNIPPETS)), + CompletionEntry("height", ark::es2panda::lsp::CompletionEntryKind::METHOD, std::string(CLASS_MEMBER_SNIPPETS))}; + AssertCompletionsContainAndNotContainEntries(res.GetEntries(), expectedEntries, {}); + initializer.DestroyContext(ctx); +} + +TEST_F(LSPCompletionsTests, getCompletionsAtPosition14) +{ + std::vector files = {"getCompletionsAtPosition15.ets"}; + std::vector texts = {R"delimiter( +export class MyClass0 { + public property0: string = '0' + public get0() {} +} +export class MyClass extends MyClass0 { + public property: string = '1' + public get() {} +} +export class MySonClass extends MyClass { + public property2: string = '2' +} +let c = new MySonClass() +let p = c._WILDCARD +)delimiter"}; + auto filePaths = CreateTempFile(files, texts); + + int const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + + LSPAPI const *lspApi = GetImpl(); + size_t const offset = 292; // after 'j._WILDCARD' + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + auto res = lspApi->getCompletionsAtPosition(ctx, offset); + auto expectedEntries = std::vector { + CompletionEntry("property", ark::es2panda::lsp::CompletionEntryKind::PROPERTY, + std::string(SUGGESTED_CLASS_MEMBERS)), + CompletionEntry("property", ark::es2panda::lsp::CompletionEntryKind::PROPERTY, + std::string(SUGGESTED_CLASS_MEMBERS)), + CompletionEntry("property2", ark::es2panda::lsp::CompletionEntryKind::PROPERTY, + std::string(SUGGESTED_CLASS_MEMBERS)), + CompletionEntry("get", ark::es2panda::lsp::CompletionEntryKind::METHOD, std::string(CLASS_MEMBER_SNIPPETS)), + CompletionEntry("get0", ark::es2panda::lsp::CompletionEntryKind::METHOD, std::string(CLASS_MEMBER_SNIPPETS))}; + AssertCompletionsContainAndNotContainEntries(res.GetEntries(), expectedEntries, {}); + initializer.DestroyContext(ctx); +} + +TEST_F(LSPCompletionsTests, getCompletionsAtPosition13) +{ + std::vector files = {"getCompletionsAtPosition14.ets"}; + std::vector texts = {R"delimiter( +export interface Method { + get(value: number): this; +} +export interface CommonMethod { + width(value: number): this; + height(value: number): this; +} +export interface TextAttribute extends CommonMethod { + font(value: number): this; + fontColor(value: number): this; +} +export declare function Text( + content?: string, + value?: string +): TextAttribute +Text("Hello")._WILDCARD +)delimiter"}; + auto filePaths = CreateTempFile(files, texts); + + int const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + + LSPAPI const *lspApi = GetImpl(); + size_t const offset = 378; // after 'j._WILDCARD' + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + auto res = lspApi->getCompletionsAtPosition(ctx, offset); + auto expectedEntries = std::vector { + CompletionEntry("font", ark::es2panda::lsp::CompletionEntryKind::METHOD, std::string(CLASS_MEMBER_SNIPPETS)), + CompletionEntry("fontColor", ark::es2panda::lsp::CompletionEntryKind::METHOD, + std::string(CLASS_MEMBER_SNIPPETS)), + CompletionEntry("width", ark::es2panda::lsp::CompletionEntryKind::METHOD, std::string(CLASS_MEMBER_SNIPPETS)), + CompletionEntry("height", ark::es2panda::lsp::CompletionEntryKind::METHOD, std::string(CLASS_MEMBER_SNIPPETS))}; + AssertCompletionsContainAndNotContainEntries(res.GetEntries(), expectedEntries, {}); + initializer.DestroyContext(ctx); +} + TEST_F(LSPCompletionsTests, getCompletionsAtPosition12) { std::vector files = {"getCompletionsAtPosition13.ets"}; @@ -76,7 +199,7 @@ let res = j._WILDCARD ASSERT_EQ(filePaths.size(), expectedFileCount); LSPAPI const *lspApi = GetImpl(); - size_t const offset = 141; // after 'j._WILDCARD' + size_t const offset = 142; // after 'j._WILDCARD' Initializer initializer = Initializer(); auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); auto res = lspApi->getCompletionsAtPosition(ctx, offset); @@ -99,7 +222,7 @@ let a = 1;)delimiter"}; ASSERT_EQ(filePaths.size(), expectedFileCount); LSPAPI const *lspApi = GetImpl(); - size_t const offset = 50; // after 'i.k' + size_t const offset = 51; // after 'i.k' Initializer initializer = Initializer(); auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); auto res = lspApi->getCompletionsAtPosition(ctx, offset); @@ -122,7 +245,7 @@ let a = 1;)delimiter"}; ASSERT_EQ(filePaths.size(), expectedFileCount); LSPAPI const *lspApi = GetImpl(); - size_t const offset = 58; // after 'i._WILDCARD' + size_t const offset = 59; // after 'i._WILDCARD' Initializer initializer = Initializer(); auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); auto res = lspApi->getCompletionsAtPosition(ctx, offset); @@ -148,7 +271,7 @@ let a = 1;)delimiter"}; ASSERT_EQ(filePaths.size(), expectedFileCount); LSPAPI const *lspApi = GetImpl(); - size_t const offset = 120; // after 'obj._WILDCARD' in 'let p = obj._WILDCARD' + size_t const offset = 121; // after 'obj._WILDCARD' in 'let p = obj._WILDCARD' Initializer initializer = Initializer(); auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); auto res = lspApi->getCompletionsAtPosition(ctx, offset); @@ -175,7 +298,7 @@ let myColor: Color = Color._WILDCARD)delimiter"}; ASSERT_EQ(filePaths.size(), expectedFileCount); LSPAPI const *lspApi = GetImpl(); - size_t const offset = 82; // after 'Color._WILDCARD' + size_t const offset = 83; // after 'Color._WILDCARD' Initializer initializer = Initializer(); auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); auto res = lspApi->getCompletionsAtPosition(ctx, offset); @@ -202,7 +325,7 @@ let numOfSpace: space._WILDCARD)delimiter"}; Initializer initializer = Initializer(); auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); LSPAPI const *lspApi = GetImpl(); - const size_t offset = 112; + const size_t offset = 113; auto res = lspApi->getCompletionsAtPosition(ctx, offset); auto entries = res.GetEntries(); std::string propertyName1 = "classInSpace"; @@ -246,7 +369,7 @@ class ASSERT_EQ(filePaths.size(), expectedFileCount); LSPAPI const *lspApi = GetImpl(); - size_t const offset = 5; // after 'n' in 'let a = n' + size_t const offset = 6; // after 'ss' in 'class' Initializer initializer = Initializer(); auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); auto res = lspApi->getCompletionsAtPosition(ctx, offset); @@ -451,7 +574,7 @@ let prop = obj1.yp)delimiter"}; Initializer initializer = Initializer(); auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); LSPAPI const *lspApi = GetImpl(); - const size_t offset = 119; + const size_t offset = 120; auto res = lspApi->getCompletionsAtPosition(ctx, offset); auto entries = res.GetEntries(); ASSERT_TRUE(entries.size() == 1); @@ -479,7 +602,7 @@ let numOfSpace: space.classi)delimiter"}; Initializer initializer = Initializer(); auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); LSPAPI const *lspApi = GetImpl(); - const size_t offset = 109; + const size_t offset = 110; auto res = lspApi->getCompletionsAtPosition(ctx, offset); auto entries = res.GetEntries(); std::string propertyName1 = "classInSpace"; @@ -506,7 +629,7 @@ let myColor: Color = Color.R)delimiter"}; Initializer initializer = Initializer(); auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); LSPAPI const *lspApi = GetImpl(); - const size_t offset = 74; + const size_t offset = 75; auto res = lspApi->getCompletionsAtPosition(ctx, offset); auto entries = res.GetEntries(); ASSERT_TRUE(entries.size() == 1); -- Gitee From 3976b1aec1d7c83f45a37ba2437c862eded8be04 Mon Sep 17 00:00:00 2001 From: yaohaosen Date: Wed, 9 Apr 2025 17:01:11 +0800 Subject: [PATCH 023/268] [LSP] Fix completion inconsistent offset Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBZSD2 Signed-off-by: yaohaosen --- ets2panda/bindings/src/lsp_helper.ts | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/ets2panda/bindings/src/lsp_helper.ts b/ets2panda/bindings/src/lsp_helper.ts index 0d72468760..82f11a7415 100644 --- a/ets2panda/bindings/src/lsp_helper.ts +++ b/ets2panda/bindings/src/lsp_helper.ts @@ -24,17 +24,26 @@ import { PluginDriver, PluginHook } from './ui_plugins_driver' import * as fs from "fs" import * as path from 'path' +function initBuildEnv(): void { + const currentPath: string | undefined = process.env.PATH; + let pandaLibPath: string = path.resolve(__dirname, '../../ets2panda/lib'); + process.env.PATH = `${currentPath}${path.delimiter}${pandaLibPath}`; +} + export class Lsp { private pandaLibPath: string private fileNameToArktsconfig: any // Map private moduleToBuildConfig: any // Map + private getFileContent: (filePath: string) => string; - constructor(projectPath: string) { + constructor(projectPath: string, getContentCallback?: (filePath: string) => string) { + initBuildEnv() this.pandaLibPath = path.resolve(__dirname, '../../ets2panda/lib'); let compileFileInfoPath = path.join(projectPath, '.idea', '.deveco', 'lsp_compileFileInfos.json') this.fileNameToArktsconfig = JSON.parse(fs.readFileSync(compileFileInfoPath, 'utf-8')) let buildConfigPath = path.join(projectPath, '.idea', '.deveco', 'lsp_build_config.json') this.moduleToBuildConfig = JSON.parse(fs.readFileSync(buildConfigPath, 'utf-8')) + this.getFileContent = getContentCallback || ((path) => fs.readFileSync(path, 'utf8')); } getDefinitionAtPosition(filename: String, offset: number): LspDefinitionData { @@ -280,7 +289,7 @@ export class Lsp { let arktsconfig = this.fileNameToArktsconfig[filePath] let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig] let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath) - let source = fs.readFileSync(filePath, 'utf8').toString().replace(/\r\n/g, '\n'); + let source = this.getFileContent(filePath).replace(/\r\n/g, '\n'); // This is a temporary solution to support "obj." with wildcard for better solution in internal issue. if (source[offset - 1] === '.') { const wildcard = "_WILDCARD"; -- Gitee From 346fbee947a5487dc2043a168bb7c29a4618d148 Mon Sep 17 00:00:00 2001 From: dongchao Date: Sat, 12 Apr 2025 20:11:20 +0800 Subject: [PATCH 024/268] Clear driver alarms Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC14LY Signed-off-by: dongchao --- .../build_system/src/build/base_mode.ts | 32 +++++++------ .../build_system/src/build/compile_worker.ts | 5 +- .../src/build/generate_arktsconfig.ts | 22 ++++----- ets2panda/driver/build_system/src/logger.ts | 27 +++++++---- .../src/plugins/plugins_driver.ts | 4 +- ets2panda/driver/build_system/src/types.ts | 48 +++++++++++++++++-- ets2panda/driver/dependency_analyzer/main.cpp | 2 +- 7 files changed, 97 insertions(+), 43 deletions(-) diff --git a/ets2panda/driver/build_system/src/build/base_mode.ts b/ets2panda/driver/build_system/src/build/base_mode.ts index 15bf2c109f..b0f3a57b38 100644 --- a/ets2panda/driver/build_system/src/build/base_mode.ts +++ b/ets2panda/driver/build_system/src/build/base_mode.ts @@ -45,13 +45,15 @@ import { Logger, LogData, LogDataFactory -} from '../logger' -import { ErrorCode } from '../error_code' +} from '../logger'; +import { ErrorCode } from '../error_code'; import { + ArkTS, + ArkTSGlobal, BuildConfig, + CompileFileInfo, DependentModuleConfig, - ModuleInfo, - CompileFileInfo + ModuleInfo } from '../types'; import { ArkTSConfigGenerator } from './generate_arktsconfig'; import { SetupClusterOptions } from '../types'; @@ -121,8 +123,8 @@ export abstract class BaseMode { ); ensurePathExists(declEtsOutputPath); ensurePathExists(etsOutputPath); - let arktsGlobal = this.buildConfig.arktsGlobal as any; - let arkts = this.buildConfig.arkts as any; + let arktsGlobal: ArkTSGlobal = this.buildConfig.arktsGlobal; + let arkts: ArkTS = this.buildConfig.arkts; try { arktsGlobal.filePath = fileInfo.filePath; arktsGlobal.config = arkts.Config.create([ @@ -153,7 +155,7 @@ export abstract class BaseMode { etsOutputPath, false ); // Generate 1.0 declaration files & 1.0 glue code - this.logger.printInfo("declaration files generated"); + this.logger.printInfo('declaration files generated'); } catch (error) { if (error instanceof Error) { const logData: LogData = LogDataFactory.newInstance( @@ -164,6 +166,7 @@ export abstract class BaseMode { this.logger.printError(logData); } } finally { + arktsGlobal.es2panda._DestroyContext(arktsGlobal.compilerContext.peer); arkts.destroyConfig(arktsGlobal.config); } } @@ -187,8 +190,8 @@ export abstract class BaseMode { ets2pandaCmd.push(fileInfo.filePath); this.logger.printInfo('ets2pandaCmd: ' + ets2pandaCmd.join(' ')); - let arktsGlobal = this.buildConfig.arktsGlobal as any; - let arkts = this.buildConfig.arkts as any; + let arktsGlobal = this.buildConfig.arktsGlobal; + let arkts = this.buildConfig.arkts; try { arktsGlobal.filePath = fileInfo.filePath; arktsGlobal.config = arkts.Config.create(ets2pandaCmd).peer; @@ -222,6 +225,7 @@ export abstract class BaseMode { this.logger.printError(logData); } } finally { + arktsGlobal.es2panda._DestroyContext(arktsGlobal.compilerContext.peer); PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); arkts.destroyConfig(arktsGlobal.config); } @@ -232,7 +236,7 @@ export abstract class BaseMode { let linkerInputContent: string = ''; this.abcFiles.forEach((abcFile: string) => { linkerInputContent += abcFile + os.EOL; - }) + }); fs.writeFileSync(linkerInputFile, linkerInputContent); this.abcLinkerCmd.push('--output'); @@ -326,7 +330,7 @@ export abstract class BaseMode { compileFileInfos: [], declgenV1OutPath: this.declgenV1OutPath, declgenBridgeCodePath: this.declgenBridgeCodePath - } + }; this.moduleInfos.set(this.packageName, mainModuleInfo); this.dependentModuleList.forEach((module: DependentModuleConfig) => { if (!module.packageName || !module.modulePath || !module.sourceRoots || !module.entryFile) { @@ -352,7 +356,7 @@ export abstract class BaseMode { language: module.language, declFilesPath: module.declFilesPath, dependencies: module.dependencies - } + }; this.moduleInfos.set(module.packageName, moduleInfo); }); this.collectDepModuleInfos(); @@ -440,7 +444,7 @@ export abstract class BaseMode { this.mergeAbcFiles(); } - private terminateAllWorkers() { + private terminateAllWorkers(): void { Object.values(cluster.workers || {}).forEach(worker => { worker?.kill(); }); @@ -510,7 +514,7 @@ export abstract class BaseMode { await Promise.all(workerExitPromises); } - private setupWorkerMessageHandler(worker: Worker) { + private setupWorkerMessageHandler(worker: Worker): void { worker.on('message', (message: { success: boolean; filePath?: string; diff --git a/ets2panda/driver/build_system/src/build/compile_worker.ts b/ets2panda/driver/build_system/src/build/compile_worker.ts index b94e6d5b2c..b4f7050c27 100644 --- a/ets2panda/driver/build_system/src/build/compile_worker.ts +++ b/ets2panda/driver/build_system/src/build/compile_worker.ts @@ -58,7 +58,9 @@ process.on('message', (message: { '--arktsconfig', fileInfo.arktsConfigFile, '--output', fileInfo.abcFilePath, ]; - if (isDebug) ets2pandaCmd.push('--debug-info'); + if (isDebug) { + ets2pandaCmd.push('--debug-info'); + } ets2pandaCmd.push(fileInfo.filePath); arktsGlobal.filePath = fileInfo.filePath; @@ -89,6 +91,7 @@ process.on('message', (message: { error: 'Compile abc files failed.' }); } finally { + arktsGlobal.es2panda._DestroyContext(arktsGlobal.compilerContext.peer); PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); arkts.destroyConfig(arktsGlobal.config); } diff --git a/ets2panda/driver/build_system/src/build/generate_arktsconfig.ts b/ets2panda/driver/build_system/src/build/generate_arktsconfig.ts index fe7923bafe..e05fec759a 100644 --- a/ets2panda/driver/build_system/src/build/generate_arktsconfig.ts +++ b/ets2panda/driver/build_system/src/build/generate_arktsconfig.ts @@ -20,10 +20,10 @@ import { Logger, LogData, LogDataFactory -} from '../logger' +} from '../logger'; import { ErrorCode -} from '../error_code' +} from '../error_code'; import { changeFileExtension, ensurePathExists @@ -95,7 +95,7 @@ export class ArkTSConfigGenerator { } private generateSystemSdkPathSection(pathSection: Record): void { - function traverse(currentDir: string, relativePath: string = '', isExcludedDir: boolean = false) { + function traverse(currentDir: string, relativePath: string = '', isExcludedDir: boolean = false): void { const items = fs.readdirSync(currentDir); for (const item of items) { const itemPath = path.join(currentDir, item); @@ -133,8 +133,8 @@ export class ArkTSConfigGenerator { return this.pathSection; } - this.pathSection['std'] = [this.stdlibStdPath]; - this.pathSection['escompat'] = [this.stdlibEscompatPath]; + this.pathSection.std = [this.stdlibStdPath]; + this.pathSection.escompat = [this.stdlibEscompatPath]; this.generateSystemSdkPathSection(this.pathSection); @@ -142,7 +142,7 @@ export class ArkTSConfigGenerator { if (moduleInfo.language === LANGUAGE_VERSION.ARKTS_1_2) { this.pathSection[moduleInfo.packageName] = [ path.resolve(moduleInfo.moduleRootPath, moduleInfo.sourceRoots[0]) - ] + ]; } }); @@ -157,13 +157,13 @@ export class ArkTSConfigGenerator { }); } - private getOhmurl(file: string, moduleInfo: ModuleInfo): string{ + private getOhmurl(file: string, moduleInfo: ModuleInfo): string { let unixFilePath: string = file.replace(/\\/g, '/'); let ohmurl: string = moduleInfo.packageName + '/' + unixFilePath; return changeFileExtension(ohmurl, ''); } - private getDynamicPathSection(moduleInfo: ModuleInfo, dynamicPathSection: Record) { + private getDynamicPathSection(moduleInfo: ModuleInfo, dynamicPathSection: Record): void { let depModules: Map = moduleInfo.dynamicDepModuleInfos; depModules.forEach((depModuleInfo: ModuleInfo) => { @@ -176,10 +176,10 @@ export class ArkTSConfigGenerator { Object.keys(declFilesObject.files).forEach((file: string)=> { let ohmurl: string = this.getOhmurl(file, depModuleInfo); dynamicPathSection[ohmurl] = { - language: "js", + language: 'js', declPath: declFilesObject.files[file].declPath, ohmUrl: declFilesObject.files[file].ohmUrl - } + }; let absFilePath: string = path.resolve(depModuleInfo.moduleRootPath, file); let entryFileWithoutExtension: string = changeFileExtension(depModuleInfo.entryFile, ''); @@ -191,7 +191,7 @@ export class ArkTSConfigGenerator { } public writeArkTSConfigFile(moduleInfo: ModuleInfo): void { - if (!moduleInfo.sourceRoots || moduleInfo.sourceRoots.length == 0) { + if (!moduleInfo.sourceRoots || moduleInfo.sourceRoots.length === 0) { const logData: LogData = LogDataFactory.newInstance( ErrorCode.BUILDSYSTEM_SOURCEROOTS_NOT_SET_FAIL, 'SourceRoots not set from hvigor.' diff --git a/ets2panda/driver/build_system/src/logger.ts b/ets2panda/driver/build_system/src/logger.ts index 266837c7b5..542126b022 100644 --- a/ets2panda/driver/build_system/src/logger.ts +++ b/ets2panda/driver/build_system/src/logger.ts @@ -21,7 +21,7 @@ import { export class Logger { private static instance: Logger | undefined; - private loggerMap: { [key in SubsystemCode]?: Object }; + private loggerMap: { [key in SubsystemCode]?: ILogger }; private constructor(projectConfig: BuildConfig) { if (typeof projectConfig.getHvigorConsoleLogger !== 'function') { @@ -48,27 +48,27 @@ export class Logger { } public printInfo(message: string, subsystemCode: SubsystemCode = SubsystemCode.BUILDSYSTEM): void { - const logger = this.getLoggerFromSubsystemCode(subsystemCode) as any; + const logger: ILogger = this.getLoggerFromSubsystemCode(subsystemCode); logger.printInfo(message); } public printWarn(message: string, subsystemCode: SubsystemCode = SubsystemCode.BUILDSYSTEM): void { - const logger = this.getLoggerFromSubsystemCode(subsystemCode) as any; + const logger: ILogger = this.getLoggerFromSubsystemCode(subsystemCode); logger.printWarn(message); } public printDebug(message: string, subsystemCode: SubsystemCode = SubsystemCode.BUILDSYSTEM): void { - const logger = this.getLoggerFromSubsystemCode(subsystemCode) as any; + const logger: ILogger = this.getLoggerFromSubsystemCode(subsystemCode); logger.printDebug(message); } public printError(error: LogData): void { - const logger = this.getLoggerFromErrorCode(error.code) as any; + const logger: ILogger = this.getLoggerFromErrorCode(error.code); logger.printError(error); } public printErrorAndExit(error: LogData): void { - const logger = this.getLoggerFromErrorCode(error.code) as any; + const logger: ILogger = this.getLoggerFromErrorCode(error.code); logger.printErrorAndExit(error); } @@ -76,7 +76,7 @@ export class Logger { return /^\d{8}$/.test(errorCode); } - private getLoggerFromErrorCode(errorCode: ErrorCode): Object { + private getLoggerFromErrorCode(errorCode: ErrorCode): ILogger { if (!this.isValidErrorCode(errorCode)) { throw new Error('Invalid errorCode.'); } @@ -85,14 +85,21 @@ export class Logger { return logger; } - private getLoggerFromSubsystemCode(subsystemCode: SubsystemCode): Object { - if(!this.loggerMap[subsystemCode]) { + private getLoggerFromSubsystemCode(subsystemCode: SubsystemCode): ILogger { + if (!this.loggerMap[subsystemCode]) { throw new Error('Invalid subsystemCode.'); } - return this.loggerMap[subsystemCode] + return this.loggerMap[subsystemCode]; } } +interface ILogger { + printInfo(message: string): void; + printWarn(message: string): void; + printDebug(message: string): void; + printError(error: LogData): void; + printErrorAndExit(error: LogData): void; +} export class LogDataFactory { diff --git a/ets2panda/driver/build_system/src/plugins/plugins_driver.ts b/ets2panda/driver/build_system/src/plugins/plugins_driver.ts index d0905124ed..4184b13b9f 100644 --- a/ets2panda/driver/build_system/src/plugins/plugins_driver.ts +++ b/ets2panda/driver/build_system/src/plugins/plugins_driver.ts @@ -18,7 +18,7 @@ import { LogData, LogDataFactory } from '../logger'; -import { BuildConfig } from '../types' +import { BuildConfig } from '../types'; import { ErrorCode } from '../error_code'; export enum PluginHook { @@ -144,7 +144,7 @@ export class PluginDriver { let pluginObject = require(value as string); let initFunction = Object.values(pluginObject)[0] as PluginInitFunction; if (typeof initFunction !== 'function') { - throw('Failed to load plugin: plugin in wrong format'); + throw ('Failed to load plugin: plugin in wrong format'); } this.logger.printInfo(`Loaded plugin: ', ${key}, ${pluginObject}`); diff --git a/ets2panda/driver/build_system/src/types.ts b/ets2panda/driver/build_system/src/types.ts index c2f238386a..521244be66 100644 --- a/ets2panda/driver/build_system/src/types.ts +++ b/ets2panda/driver/build_system/src/types.ts @@ -22,11 +22,51 @@ export interface BuildBaseConfig { buildType: 'build' | 'preview' | 'hotreload' | 'coldreload'; buildMode: 'Debug' | 'Release'; hasMainModule: boolean; - arkts: object; - arktsGlobal: object; + arkts: ArkTS; + arktsGlobal: ArkTSGlobal; maxWorkers?: number; } +export interface ArkTSGlobal { + filePath: string; + config: object; + compilerContext: { + program: object; + peer: object + }; + es2panda: { + _DestroyContext: Function; + } +} + +export interface ArkTS { + Config: { + create: Function; + }; + Context: { + createFromString: Function; + }; + EtsScript: { + fromContext: Function; + }; + proceedToState: Function; + generateTsDeclarationsFromContext: Function; + destroyConfig: Function; + Es2pandaContextState: typeof Es2pandaContextState; +} + +export enum Es2pandaContextState { + ES2PANDA_STATE_NEW = 0, + ES2PANDA_STATE_PARSED = 1, + ES2PANDA_STATE_SCOPE_INITED = 2, + ES2PANDA_STATE_BOUND = 3, + ES2PANDA_STATE_CHECKED = 4, + ES2PANDA_STATE_LOWERED = 5, + ES2PANDA_STATE_ASM_GENERATED = 6, + ES2PANDA_STATE_BIN_GENERATED = 7, + ES2PANDA_STATE_ERROR = 8 +} + export interface ModuleConfig { packageName: string; moduleType: string; @@ -38,8 +78,8 @@ export interface PathConfig { loaderOutPath: string; cachePath: string; buildSdkPath: string; - pandaSdkPath?: string; // path to panda sdk lib/bin, for local test - pandaStdlibPath?: string; // path to panda sdk stdlib, for local test + pandaSdkPath?: string; // path to panda sdk lib/bin, for local test + pandaStdlibPath?: string; // path to panda sdk stdlib, for local test abcLinkerPath?: string; } diff --git a/ets2panda/driver/dependency_analyzer/main.cpp b/ets2panda/driver/dependency_analyzer/main.cpp index f2dd6eb311..165ea75aea 100644 --- a/ets2panda/driver/dependency_analyzer/main.cpp +++ b/ets2panda/driver/dependency_analyzer/main.cpp @@ -15,7 +15,7 @@ #include "dep_analyzer.h" -void FilterArgs(ark::Span args, int &newArgc, const char **&newArgv) +static void FilterArgs(ark::Span args, int &newArgc, const char **&newArgv) { ASSERT(args.size() > 1); std::vector filteredArgs; -- Gitee From 70fd0d0455c8645fd5262df8109d87fd2d40236d Mon Sep 17 00:00:00 2001 From: lijunru Date: Sun, 13 Apr 2025 00:25:11 +0800 Subject: [PATCH 025/268] Support to build lsp for mac Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC0O83 Signed-off-by: lijunru --- ets2panda/bindings/BUILD.gn | 19 +++++++++++++++++++ ets2panda/bindings/build_bindings.py | 2 +- ets2panda/bindings/native/include/common.h | 2 +- .../bindings/native/include/dynamic-loader.h | 2 +- ets2panda/bindings/native/src/common.cpp | 9 +++++++-- ets2panda/bindings/src/loadLibraries.ts | 7 +++++-- 6 files changed, 34 insertions(+), 7 deletions(-) diff --git a/ets2panda/bindings/BUILD.gn b/ets2panda/bindings/BUILD.gn index a94c16de11..5c3806ebaa 100644 --- a/ets2panda/bindings/BUILD.gn +++ b/ets2panda/bindings/BUILD.gn @@ -161,6 +161,25 @@ shared_library("ts_bindings") { "x86_64-pc-windows-gnu", ] sources += [ "./native/src/win-dynamic-node.cpp" ] + } else if (is_mac) { + cflags_cc = [ + "-std=c++17", + "-Wall", + "-Werror", + "-Wno-unused-variable", + "-fPIC", + ] + + ldflags = [ + "-fPIC", + "-fuse-ld=lld", + "-Wl,--icf=all", + "-Wl,--color-diagnostics", + "-m64", + "-Wl,-undefined,dynamic_lookup", + ] + output_extension = "node" + output_prefix_override = true } } diff --git a/ets2panda/bindings/build_bindings.py b/ets2panda/bindings/build_bindings.py index 4ad6c76874..549b2b5052 100755 --- a/ets2panda/bindings/build_bindings.py +++ b/ets2panda/bindings/build_bindings.py @@ -62,7 +62,7 @@ def copy_output(options): copy_files(os.path.join(options.root_out_dir, 'libts_bindings.dll'), os.path.join(options.output_path, 'ts_bindings.node'), True) - if options.current_os == "linux" : + if options.current_os == "linux" or options.current_os == "mac": copy_files(os.path.join(options.root_out_dir, 'ts_bindings.node'), os.path.join(options.output_path, 'ts_bindings.node'), True) diff --git a/ets2panda/bindings/native/include/common.h b/ets2panda/bindings/native/include/common.h index bb1ba10f3f..b92a49f9f1 100644 --- a/ets2panda/bindings/native/include/common.h +++ b/ets2panda/bindings/native/include/common.h @@ -23,7 +23,7 @@ #include #include "public/es2panda_lib.h" -es2panda_Impl *GetPublicImpl(); +const es2panda_Impl *GetPublicImpl(); // CC-OFFNXT(G.NAM.01) false positive std::string GetString(KStringPtr ptr); diff --git a/ets2panda/bindings/native/include/dynamic-loader.h b/ets2panda/bindings/native/include/dynamic-loader.h index cf3d487aee..d99d7fa19f 100644 --- a/ets2panda/bindings/native/include/dynamic-loader.h +++ b/ets2panda/bindings/native/include/dynamic-loader.h @@ -43,7 +43,7 @@ inline std::string LibName(const char *lib) return std::string(lib) + ".dll"; } -#elif defined(__linux__) +#elif defined(__linux__) || defined(__APPLE__) #include inline void *LoadLibrary(const std::string &libPath) diff --git a/ets2panda/bindings/native/src/common.cpp b/ets2panda/bindings/native/src/common.cpp index cad9c7d8d6..52fc388ace 100644 --- a/ets2panda/bindings/native/src/common.cpp +++ b/ets2panda/bindings/native/src/common.cpp @@ -23,7 +23,7 @@ using std::string, std::cout, std::endl, std::vector; -static es2panda_Impl *impl = nullptr; +static es2panda_Impl const *impl = nullptr; #ifdef _WIN32 #include @@ -61,8 +61,12 @@ void *FindLibrary() return LoadLibrary(libraryName); } -es2panda_Impl *GetPublicImpl() +const es2panda_Impl *GetPublicImpl() { +#ifdef __APPLE__ + impl = es2panda_GetImpl(ES2PANDA_LIB_VERSION); + return impl; +#else if (impl) { return impl; } @@ -76,6 +80,7 @@ es2panda_Impl *GetPublicImpl() } impl = reinterpret_cast(symbol)(ES2PANDA_LIB_VERSION); return impl; +#endif } std::string GetString(KStringPtr ptr) diff --git a/ets2panda/bindings/src/loadLibraries.ts b/ets2panda/bindings/src/loadLibraries.ts index d60bd020e7..fb22a82cba 100644 --- a/ets2panda/bindings/src/loadLibraries.ts +++ b/ets2panda/bindings/src/loadLibraries.ts @@ -22,8 +22,11 @@ export function loadNativeLibrary(name: string): Record { return (globalThis as any).requireNapi(name, true) else { const suffixedName = name.endsWith(".node") ? name : `${name}.node` - const safePath = path.win32.resolve(process.cwd(), `${suffixedName}`).replace(/\\/g, '\\\\') - return eval(`let exports = {}; process.dlopen({ exports }, require.resolve("${safePath.replace(/ /g, '\\ ')}"), 2); exports`) + if (process.platform === 'win32') { + return require(suffixedName) + } else { + return eval(`let exports = {}; process.dlopen({ exports }, require.resolve("${suffixedName}"), 2); exports`); + } } } -- Gitee From c79261b82d31765de3eecd482474834ba33b0c86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Czhuzhihui7=E2=80=9D?= Date: Wed, 9 Apr 2025 16:53:38 +0800 Subject: [PATCH 026/268] Support obfuscation performance tracking fix MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Issue: IBZS9E Signed-off-by: “zhuzhihui7” --- arkguard/src/initialization/Initializer.ts | 2 +- arkguard/src/utils/PrinterTimeAndMemUtils.ts | 16 +++++++++------- .../test/ut/utils/PrinterTimeAndmemUtils.spec.ts | 6 ++++++ arkguard/tools/timesum.py | 11 +++++++++-- 4 files changed, 25 insertions(+), 10 deletions(-) diff --git a/arkguard/src/initialization/Initializer.ts b/arkguard/src/initialization/Initializer.ts index cb437e847e..16b3fc6dd7 100644 --- a/arkguard/src/initialization/Initializer.ts +++ b/arkguard/src/initialization/Initializer.ts @@ -56,12 +56,12 @@ export function initObfuscationConfig(projectConfig: any, arkProjectConfig: any, const obConfig: ObConfigResolver = new ObConfigResolver(projectConfig, printObfLogger, true); const mergedObConfig: MergedConfig = obConfig.resolveObfuscationConfigs(); const isHarCompiled: boolean = projectConfig.compileHar; - getObfuscationCacheDir(projectConfig); if (mergedObConfig.options.disableObfuscation) { blockPrinter(); blockTimeAndMemPrinter(); return; } + getObfuscationCacheDir(projectConfig); if (mergedObConfig.options.enableFileNameObfuscation) { const ohPackagePath = path.join(projectConfig.modulePath, 'oh-package.json5'); diff --git a/arkguard/src/utils/PrinterTimeAndMemUtils.ts b/arkguard/src/utils/PrinterTimeAndMemUtils.ts index 83d98daadd..334f542d89 100644 --- a/arkguard/src/utils/PrinterTimeAndMemUtils.ts +++ b/arkguard/src/utils/PrinterTimeAndMemUtils.ts @@ -117,7 +117,7 @@ const MEMORY_PERFORMANCE_FILE_NAME = 'memoryPerformanceData.json'; // Memory per export const eventListTimeAndMemValues = new Set(Object.values(EventList)); export class TimeAndMemTimeTracker { - static obfuscationCacheDir: string = ''; // Obtain the directory of the obfuscated output file + static obfuscationCacheDir: string | undefined = ''; // Obtain the directory of the obfuscated output file private eventStack: Array<{ eventName: string; data: TimeAndMemInfo }> = []; timeDataArr: TimeInfo[] = []; memoryDataArr: MemInfo[] = []; @@ -251,7 +251,7 @@ export function clearTimeAndMemPrinterData(): void { /** * Initialize the configuration of the TimeAndMem performance printer */ -export function initPrinterTimeAndMemConfig() { +export function initPrinterTimeAndMemConfig(): void { printerTimeAndMemDataConfig.mTimeAndMemPrinter = true; } @@ -315,11 +315,13 @@ export function printMemoryPerformanceData(): void { * Write data of timeAndMemoryPerformance */ export async function writeTimeAndMemoryPerformanceData(data: (TimeInfo | MemInfo)[], fileName: string): Promise { - const filePath: string = path.join(TimeAndMemTimeTracker.obfuscationCacheDir, fileName); - try { - await fs.promises.writeFile(filePath, JSON.stringify(data, null, INDENTATION_SPACES)); - } catch (error) { - throw new Error('Failed to write file: ' + error.message.toString()); + if (TimeAndMemTimeTracker.obfuscationCacheDir) { + const filePath: string = path.join(TimeAndMemTimeTracker.obfuscationCacheDir, fileName); + try { + await fs.promises.writeFile(filePath, JSON.stringify(data, null, INDENTATION_SPACES)); + } catch (error) { + throw new Error('Failed to write file: ' + error.message.toString()); + } } } diff --git a/arkguard/test/ut/utils/PrinterTimeAndmemUtils.spec.ts b/arkguard/test/ut/utils/PrinterTimeAndmemUtils.spec.ts index 61c4e63316..a3675c3287 100644 --- a/arkguard/test/ut/utils/PrinterTimeAndmemUtils.spec.ts +++ b/arkguard/test/ut/utils/PrinterTimeAndmemUtils.spec.ts @@ -316,6 +316,11 @@ describe('test Cases for .', function () { describe('Tester Cases for ', () => { it('Write file error', () => { + const projectConfig = { + obfuscationOptions: { + obfuscationCacheDir: 'test/', + }, + }; const data = [ { 'name': 'BreakpointConstants.ts', @@ -324,6 +329,7 @@ describe('test Cases for .', function () { }, ]; const fileName = ''; + getObfuscationCacheDir(projectConfig); expect(writeTimeAndMemoryPerformanceData(data, fileName)).to.be.throw; }); }); diff --git a/arkguard/tools/timesum.py b/arkguard/tools/timesum.py index 20781a7d79..b75ed50f6b 100644 --- a/arkguard/tools/timesum.py +++ b/arkguard/tools/timesum.py @@ -19,6 +19,8 @@ limitations under the License. from collections import defaultdict import json import logging +import os +import stat # Configure logging to display timestamps and messages logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(message)s") @@ -33,7 +35,8 @@ def gen_parent(data): """ # Sort the data by timestamp (ts) data = sorted(data, key=lambda x: x["ts"]) - for i in range(len(data)): + data_length = len(data) + for i in range(data_length): current = data[i] # Current event current_end = current["ts"] + current["dur"] # End time of the current event for j in range(i - 1, -1, -1): # Candidate parent event @@ -136,7 +139,11 @@ def re_gen_ts_and_dur(data_with_parent): flattened.extend(nodes) # Save the flattened data to a JSON file - with open("data.json", "w") as f: + if os.path.exists('data.json'): + os.remove('data.json') + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL + modes = stat.S_IWUSR | stat.S_IRUSR + with os.fdopen(os.open('data.json', flags, modes), 'w') as f: json.dump(flattened, f, indent=2) return groups -- Gitee From 1d1c7012acab7ea60080f0ae0dfa105fb0841d20 Mon Sep 17 00:00:00 2001 From: hanlong Date: Tue, 15 Apr 2025 15:44:04 +0800 Subject: [PATCH 027/268] Update KFL 0415 Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC1BKR?from=project-issue Signed-off-by: hanlong --- test262/ignored-test262-release-qemu-jit.txt | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/test262/ignored-test262-release-qemu-jit.txt b/test262/ignored-test262-release-qemu-jit.txt index 924dfda25a..43a60883fb 100644 --- a/test262/ignored-test262-release-qemu-jit.txt +++ b/test262/ignored-test262-release-qemu-jit.txt @@ -1,2 +1,6 @@ #21423 test262/data/test_es2021/intl402/String/prototype/toLocaleUpperCase/special_casing_Lithuanian.js + +#19208 +test262/data/test_es2021/language/module-code/instn-iee-err-circular.js +test262/data/test_es2021/language/module-code/instn-iee-err-circular-as.js -- Gitee From df521b20f8208c164c9309b629df0cff355f62db Mon Sep 17 00:00:00 2001 From: hanlong Date: Tue, 15 Apr 2025 15:49:20 +0800 Subject: [PATCH 028/268] DEL KFL 0415 Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC1BSR?from=project-issue Signed-off-by: hanlong --- test/workload/ignored-third_lib_js-release-x64-jit.txt | 6 ------ 1 file changed, 6 deletions(-) diff --git a/test/workload/ignored-third_lib_js-release-x64-jit.txt b/test/workload/ignored-third_lib_js-release-x64-jit.txt index 95ceef636c..573a56debb 100644 --- a/test/workload/ignored-third_lib_js-release-x64-jit.txt +++ b/test/workload/ignored-third_lib_js-release-x64-jit.txt @@ -1,7 +1 @@ # Known failures list for third_lib_js - release-x64-jit -# 21116 -pdfview_test - -#20325 -htmlParser2_test - -- Gitee From cb7d2e9cf44fa4e8b5dea041cb0a58b53e2b7b0f Mon Sep 17 00:00:00 2001 From: xuhangqi Date: Tue, 15 Apr 2025 20:21:51 +0800 Subject: [PATCH 029/268] Remove UI unnecessary import Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC1F8Z Signed-off-by: xuhangqi Change-Id: I69a695699586c832afb76c44bcd4a887ae36522c --- ets2panda/declgen_ets2ts/declgenEts2Ts.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp b/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp index e40c3e5bbf..81a917e4e2 100644 --- a/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp +++ b/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp @@ -1004,6 +1004,9 @@ std::vector TSDeclGen::FilterValidImportSpecifiers(const ArenaVec std::vector importSpecifiers; for (std::size_t i = 0; i < specifiers.size(); i++) { const auto local = specifiers[i]->AsImportSpecifier()->Local()->Name().Mutf8(); + if (specifiers[i]->AsImportSpecifier()->IsRemovable()) { + continue; + } if (importSet_.find(local) != importSet_.end()) { importSpecifiers.push_back(specifiers[i]); } -- Gitee From 0c5b537b28ffef4c5f643ad6ef24d4651dad3257 Mon Sep 17 00:00:00 2001 From: dongchao Date: Wed, 9 Apr 2025 18:07:50 +0800 Subject: [PATCH 030/268] Avoid segmentation fault in declgen_ets2ts Issue: https://gitee.com/openharmony/arkcompiler_runtime_core/issues/IC1FGY Signed-off-by: dongchao Change-Id: I5528d724c507986dc8966d9e1e1e48035a05dccf --- ets2panda/declgen_ets2ts/declgenEts2Ts.cpp | 24 ++++++++++++++----- ets2panda/declgen_ets2ts/declgenEts2Ts.h | 4 ++-- .../declgen_ets2ts/declgen_ets2ts_error.yaml | 3 +++ .../declgen-ets2ts-runtime-ignored.txt | 11 +++++---- 4 files changed, 29 insertions(+), 13 deletions(-) diff --git a/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp b/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp index e40c3e5bbf..34b1e1f1fb 100644 --- a/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp +++ b/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp @@ -43,21 +43,30 @@ static void DebugPrint([[maybe_unused]] const std::string &msg) #endif } -void TSDeclGen::Generate() +bool TSDeclGen::Generate() { - GenGlobalDescriptor(); + if (!GenGlobalDescriptor()) { + return false; + } CollectIndirectExportDependencies(); GenDeclarations(); + return true; } -void TSDeclGen::GenGlobalDescriptor() +bool TSDeclGen::GenGlobalDescriptor() { + if (program_->GlobalClass() == nullptr) { + const auto loc = lexer::SourcePosition(); + LogError(diagnostic::UNSUPPORTED_ENCODING_SPECIFICATIONS, {}, loc); + return false; + } globalDesc_ = checker::ETSObjectType::NameToDescriptor(program_->GlobalClass()->TsType()->AsETSObjectType()->AssemblerName()); OutTs("let ETSGLOBAL = (globalThis as any).Panda.getClass('", globalDesc_, "');"); OutEndlTs(); OutTs("ETSGLOBAL.", compiler::Signatures::INIT_METHOD, "();"); OutEndlTs(); + return true; } void TSDeclGen::CollectIndirectExportDependencies() @@ -531,11 +540,12 @@ void TSDeclGen::ProcessParameterTypeAnnotation(const ir::ETSParameterExpression if (typeAnnotation->IsETSTypeReference()) { auto etsTypeRef = typeAnnotation->AsETSTypeReference(); - if (paramType->IsETSFunctionType()) { + if (paramType->IsETSFunctionType() && etsTypeRef->Part()->Name()->IsIdentifier()) { auto name = etsTypeRef->Part()->Name()->AsIdentifier()->Name(); indirectDependencyObjects_.insert(name.Mutf8()); OutDts(name); - } else if (etsTypeRef->Part()->Name()->IsTSQualifiedName()) { + } else if (etsTypeRef->Part()->Name()->IsTSQualifiedName() && + etsTypeRef->Part()->Name()->AsTSQualifiedName()->Left()->IsIdentifier()) { auto qualifiedName = etsTypeRef->Part()->Name()->AsTSQualifiedName(); auto leftName = qualifiedName->Left()->AsIdentifier()->Name(); auto rightName = qualifiedName->Right()->AsIdentifier()->Name(); @@ -1676,7 +1686,9 @@ bool GenerateTsDeclarations(checker::ETSChecker *checker, const ark::es2panda::p return false; } - declBuilder.Generate(); + if (!declBuilder.Generate()) { + return false; + } std::string outputEts = declBuilder.GetTsOutput(); std::string outputDEts = declBuilder.GetDtsOutput(); diff --git a/ets2panda/declgen_ets2ts/declgenEts2Ts.h b/ets2panda/declgen_ets2ts/declgenEts2Ts.h index 0a259f27bf..e4219fe2c8 100644 --- a/ets2panda/declgen_ets2ts/declgenEts2Ts.h +++ b/ets2panda/declgen_ets2ts/declgenEts2Ts.h @@ -59,7 +59,7 @@ public: return declgenOptions_; } - void Generate(); + bool Generate(); void GenImportDeclarations(); std::string GetDtsOutput() const @@ -149,7 +149,7 @@ private: void GenPartName(std::string &partName); void ProcessIndent(); - void GenGlobalDescriptor(); + bool GenGlobalDescriptor(); void CollectIndirectExportDependencies(); void ProcessTypeAliasDependencies(const ir::TSTypeAliasDeclaration *typeAliasDecl); void ProcessTypeAnnotationDependencies(const ir::TypeNode *typeAnnotation); diff --git a/ets2panda/declgen_ets2ts/declgen_ets2ts_error.yaml b/ets2panda/declgen_ets2ts/declgen_ets2ts_error.yaml index 6f730c1126..392309b9b7 100644 --- a/ets2panda/declgen_ets2ts/declgen_ets2ts_error.yaml +++ b/ets2panda/declgen_ets2ts/declgen_ets2ts_error.yaml @@ -48,3 +48,6 @@ declgen_ets2ts_error: id: 9 message: Imports with local bindings are not supported. +- name: UNSUPPORTED_ENCODING_SPECIFICATIONS + id: 10 + message: The source file does not comply with the encoding specifications. For details, please see the following error information. diff --git a/ets2panda/test/test-lists/declgenets2ts/ets-runtime/declgen-ets2ts-runtime-ignored.txt b/ets2panda/test/test-lists/declgenets2ts/ets-runtime/declgen-ets2ts-runtime-ignored.txt index bbed2b8f56..c78b49ead4 100644 --- a/ets2panda/test/test-lists/declgenets2ts/ets-runtime/declgen-ets2ts-runtime-ignored.txt +++ b/ets2panda/test/test-lists/declgenets2ts/ets-runtime/declgen-ets2ts-runtime-ignored.txt @@ -1,15 +1,15 @@ -#FailKind.SEGFAULT_FAIL - 7 tests: +#FailKind.SEGFAULT_FAIL - 1 tests: +lambda_with_receiver/lambda_with_receiver_generics_return_this.ets +#FailKind.DECLGEN_ETS2TS_FAIL - 6 tests: StringFasta.ets conditionalExpressionGenericLUB.ets funcRefWithRestArguments.ets -lambda_with_receiver/lambda_with_receiver_generics_return_this.ets struct-identifier.ets struct-init2.ets type_param_in_union.ets -#FailKind.ABORT_FAIL - 1 tests: -ArrowFunctionWithNestedNameSpace.ets -#FailKind.TSC_FAIL - 69 tests: +#FailKind.TSC_FAIL - 71 tests: AliasClass.ets +ArrowFunctionWithNestedNameSpace.ets ClassNewInstance.ets Enum7.ets GenericBridges_01.ets @@ -74,6 +74,7 @@ namespace_tests/namespace_execution_statements_test02.ets namespace_tests/namespace_with_annotations.ets override_for_partial_01.ets override_for_partial_02.ets +qualified-type-name.ets readonly_simple_form_pos.ets simple_form_pos.ets static-invoke.ets -- Gitee From 95ef7c7a7f9bf00dfe46f39c96b40cbe1c8f088e Mon Sep 17 00:00:00 2001 From: lijunru Date: Mon, 14 Apr 2025 22:06:10 +0800 Subject: [PATCH 031/268] [LSP] fix segfault on mac Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC14G4 Signed-off-by: lijunru --- ets2panda/bindings/BUILD.gn | 160 +++++++++++++++++- ets2panda/bindings/build_bindings.py | 4 + ets2panda/bindings/native/CMakeLists.txt | 3 - ets2panda/bindings/native/src/bridges.cpp | 8 - ets2panda/bindings/native/src/common.cpp | 5 - ets2panda/bindings/native/src/lsp.cpp | 5 + .../bindings/src/Es2pandaNativeModule.ts | 32 ++++ ets2panda/bindings/src/InteropNativeModule.ts | 16 ++ ets2panda/bindings/src/driver_helper.ts | 10 +- ets2panda/bindings/src/global.ts | 26 ++- ets2panda/bindings/src/lsp_helper.ts | 2 +- ets2panda/bindings/src/types.ts | 27 +-- 12 files changed, 245 insertions(+), 53 deletions(-) diff --git a/ets2panda/bindings/BUILD.gn b/ets2panda/bindings/BUILD.gn index 5c3806ebaa..5db6f1d96d 100644 --- a/ets2panda/bindings/BUILD.gn +++ b/ets2panda/bindings/BUILD.gn @@ -22,12 +22,9 @@ npm_path = "//prebuilts/build-tools/common/nodejs/current/bin/npm" shared_library("ts_bindings") { sources = [ - "./native/src/bridges.cpp", "./native/src/callback-resource.cpp", "./native/src/common-interop.cpp", - "./native/src/common.cpp", "./native/src/convertors-napi.cpp", - "./native/src/generated/bridges.cpp", "./native/src/lsp.cpp", ] configs += [ @@ -183,8 +180,163 @@ shared_library("ts_bindings") { } } +shared_library("public") { + sources = [ + "./native/src/bridges.cpp", + "./native/src/callback-resource.cpp", + "./native/src/common-interop.cpp", + "./native/src/common.cpp", + "./native/src/convertors-napi.cpp", + ] + + configs += [ + "$ark_root/assembler:arkassembler_public_config", + "../:libes2panda_public_config", + "../:libes2panda_config", + "$ark_root/libpandabase:arkbase_public_config", + "$ark_root/libpandafile:arkfile_public_config", + ] + + include_dirs = [ + "./native/include", + "../public/", + "//third_party/node/src", + rebase_path("$root_gen_dir/arkcompiler/ets_frontend/ets2panda/"), + ] + + if (!is_mac) { + deps = [ "../aot:ets2panda" ] + } + + if (ark_standalone_build) { + deps += [ "$ark_third_party_root/bounds_checking_function:libsec_shared" ] + } else { + external_deps = [ sdk_libc_secshared_dep ] + } + + defines = [ + "TS_INTEROP_MODULE=NativeModule", + "INTEROP_LIBRARY_NAME=ts_bindings", + "TS_USE_NODE_VM", + "TS_NAPI", + ] + if (ark_standalone_build) { + configs -= [ "$build_root/config/compiler:compiler" ] + } else { + configs -= [ "//build/config/compiler:compiler" ] + } + + if (is_linux) { + cflags_cc = [ + "-std=c++17", + "-Wall", + "-Werror", + "-Wno-unused-variable", + "-fPIC", + ] + + ldflags = [ + "-Wl,--allow-shlib-undefined", + "-Wl,--fatal-warnings", + "-Wl,--build-id=md5", + "-fPIC", + "-Wl,-z,noexecstack", + "-Wl,-z,now", + "-Wl,-z,relro", + "-Wl,--as-needed", + "-fuse-ld=lld", + "-Wl,--icf=all", + "-Wl,--color-diagnostics", + "-m64", + ] + output_extension = "node" + output_prefix_override = true + } else if (is_mingw) { + output_extension = "dll" + cflags_cc = [ + "-std=c++17", + "-Wall", + "-Werror", + "-Wno-unused-variable", + "-fPIC", + "-Wno-error=deprecated-copy", + "-enable-trivial-auto-var-init-zero-knowing-it-will-be-removed-from-clang", + "-ftrivial-auto-var-init=zero", + "-fcolor-diagnostics", + "-fmerge-all-constants", + "-Xclang", + "-mllvm", + "-Xclang", + "-instcombine-lower-dbg-declare=0", + "-no-canonical-prefixes", + "-static", + "-rtlib=compiler-rt", + "-stdlib=libc++", + "-lunwind", + "-lpthread", + "-Qunused-arguments", + "-fuse-ld=lld", + "-fno-stack-protector", + "-fno-strict-aliasing", + "-Wno-builtin-macro-redefined", + "-fms-extensions", + "-static", + "-rtlib=compiler-rt", + "-stdlib=libc++", + "-std=c++17", + "-lunwind", + "-lpthread", + "-Qunused-arguments", + "-target", + "x86_64-pc-windows-gnu", + "-D__CUSTOM_SECURITY_LIBRARY", + ] + + ldflags = [ + "-Wl,--fatal-warnings", + "-fPIC", + "-Wl,--as-needed", + "-fuse-ld=lld", + "-Wl,--icf=all", + "-m64", + "-static", + "-rtlib=compiler-rt", + "-stdlib=libc++", + "-std=c++17", + "-lunwind", + "-lpthread", + "-Qunused-arguments", + "-target", + "x86_64-pc-windows-gnu", + ] + sources += [ "./native/src/win-dynamic-node.cpp" ] + } else if (is_mac) { + cflags_cc = [ + "-std=c++17", + "-Wall", + "-Werror", + "-Wno-unused-variable", + "-fPIC", + ] + + ldflags = [ + "-fPIC", + "-fuse-ld=lld", + "-Wl,--icf=all", + "-Wl,--color-diagnostics", + "-m64", + "-Wl,-undefined,dynamic_lookup", + ] + output_extension = "node" + output_prefix_override = true + } +} + action("build_bindings") { - deps = [ ":ts_bindings" ] + deps = [ + ":public", + ":ts_bindings", + ] sources = [ "./src/Es2pandaNativeModule.ts", "./src/InteropNativeModule.ts", diff --git a/ets2panda/bindings/build_bindings.py b/ets2panda/bindings/build_bindings.py index 549b2b5052..0754cfa736 100755 --- a/ets2panda/bindings/build_bindings.py +++ b/ets2panda/bindings/build_bindings.py @@ -61,10 +61,14 @@ def copy_output(options): if options.current_os == "mingw" : copy_files(os.path.join(options.root_out_dir, 'libts_bindings.dll'), os.path.join(options.output_path, 'ts_bindings.node'), True) + copy_files(os.path.join(options.root_out_dir, 'libpublic.dll'), + os.path.join(options.output_path, 'public.node'), True) if options.current_os == "linux" or options.current_os == "mac": copy_files(os.path.join(options.root_out_dir, 'ts_bindings.node'), os.path.join(options.output_path, 'ts_bindings.node'), True) + copy_files(os.path.join(options.root_out_dir, 'public.node'), + os.path.join(options.output_path, 'public.node'), True) def parse_args(): diff --git a/ets2panda/bindings/native/CMakeLists.txt b/ets2panda/bindings/native/CMakeLists.txt index b7794eba99..60dcbb51de 100644 --- a/ets2panda/bindings/native/CMakeLists.txt +++ b/ets2panda/bindings/native/CMakeLists.txt @@ -65,12 +65,9 @@ set(NODE_BINARY ${PANDA_ROOT}/third_party/nodejs/node-${NODE_VERSION}-${DISTRO}/ set(NAPI_BINDINGS_LIB "ts_bindings") set(BINDINGS_NAPI_SRC - ./src/bridges.cpp - ./src/common.cpp ./src/common-interop.cpp ./src/convertors-napi.cpp ./src/callback-resource.cpp - ./src/generated/bridges.cpp ./src/lsp.cpp ) diff --git a/ets2panda/bindings/native/src/bridges.cpp b/ets2panda/bindings/native/src/bridges.cpp index f90652abc4..2757d4b9ef 100644 --- a/ets2panda/bindings/native/src/bridges.cpp +++ b/ets2panda/bindings/native/src/bridges.cpp @@ -66,11 +66,3 @@ KNativePointer impl_ContextErrorMessage(KNativePointer contextPtr) return new std::string(GetPublicImpl()->ContextErrorMessage(context)); } TS_INTEROP_1(ContextErrorMessage, KNativePointer, KNativePointer) - -KNativePointer impl_ProgramAst(KNativePointer programPtr) -{ - auto context = reinterpret_cast(programPtr); - auto program = reinterpret_cast(programPtr); - return GetPublicImpl()->ProgramAst(context, program); -} -TS_INTEROP_1(ProgramAst, KNativePointer, KNativePointer) diff --git a/ets2panda/bindings/native/src/common.cpp b/ets2panda/bindings/native/src/common.cpp index 52fc388ace..78f051246e 100644 --- a/ets2panda/bindings/native/src/common.cpp +++ b/ets2panda/bindings/native/src/common.cpp @@ -63,10 +63,6 @@ void *FindLibrary() const es2panda_Impl *GetPublicImpl() { -#ifdef __APPLE__ - impl = es2panda_GetImpl(ES2PANDA_LIB_VERSION); - return impl; -#else if (impl) { return impl; } @@ -80,7 +76,6 @@ const es2panda_Impl *GetPublicImpl() } impl = reinterpret_cast(symbol)(ES2PANDA_LIB_VERSION); return impl; -#endif } std::string GetString(KStringPtr ptr) diff --git a/ets2panda/bindings/native/src/lsp.cpp b/ets2panda/bindings/native/src/lsp.cpp index e7cbd65c47..254eaf869e 100644 --- a/ets2panda/bindings/native/src/lsp.cpp +++ b/ets2panda/bindings/native/src/lsp.cpp @@ -25,6 +25,11 @@ #include #include +char *GetStringCopy(KStringPtr &ptr) +{ + return strdup(ptr.c_str()); +} + KNativePointer impl_getCurrentTokenValue(KNativePointer context, KInt position) { LSPAPI const *ctx = GetImpl(); diff --git a/ets2panda/bindings/src/Es2pandaNativeModule.ts b/ets2panda/bindings/src/Es2pandaNativeModule.ts index 5bcf95113e..7c08204701 100644 --- a/ets2panda/bindings/src/Es2pandaNativeModule.ts +++ b/ets2panda/bindings/src/Es2pandaNativeModule.ts @@ -442,3 +442,35 @@ export function initGeneratedEs2panda(): GeneratedEs2pandaNativeModule { loadNativeModuleLibrary("NativeModule", instance) return instance } + +export function initPublicEs2panda(): Es2pandaNativeModule { + let libPath = process.env.BINDINGS_PATH + if (libPath == undefined) { + libPath = path.resolve(__dirname, "../public.node") + } else { + libPath = path.join(libPath, "public.node") + } + if (!fs.existsSync(libPath)) { + throwError(`Cannot find lib path ${libPath}`) + } + registerNativeModuleLibraryName("NativeModule", libPath) + const instance = new Es2pandaNativeModule() + loadNativeModuleLibrary("NativeModule", instance) + return instance +} + +export function initPublicGeneratedEs2panda(): GeneratedEs2pandaNativeModule { + let libPath = process.env.BINDINGS_PATH + if (libPath == undefined) { + libPath = path.resolve(__dirname, "../public.node") + } else { + libPath = path.join(libPath, "public.node") + } + if (!fs.existsSync(libPath)) { + throwError(`Cannot find lib path ${libPath}`) + } + registerNativeModuleLibraryName("NativeModule", libPath) + const instance = new GeneratedEs2pandaNativeModule() + loadNativeModuleLibrary("NativeModule", instance) + return instance +} diff --git a/ets2panda/bindings/src/InteropNativeModule.ts b/ets2panda/bindings/src/InteropNativeModule.ts index 58281df340..b659368edd 100644 --- a/ets2panda/bindings/src/InteropNativeModule.ts +++ b/ets2panda/bindings/src/InteropNativeModule.ts @@ -73,3 +73,19 @@ export function initInterop(): InteropNativeModule { loadNativeModuleLibrary("InteropNativeModule", instance) return instance } + +export function initPublicInterop(): InteropNativeModule { + let libPath = process.env.BINDINGS_PATH + if (libPath == undefined) { + libPath = path.resolve(__dirname, "../public.node") + } else { + libPath = path.join(libPath, "public.node") + } + if (!fs.existsSync(libPath)) { + throwError(`Cannot find lib path ${libPath}`) + } + registerNativeModuleLibraryName("InteropNativeModule", libPath) + const instance = new InteropNativeModule() + loadNativeModuleLibrary("InteropNativeModule", instance) + return instance +} diff --git a/ets2panda/bindings/src/driver_helper.ts b/ets2panda/bindings/src/driver_helper.ts index 049364575b..2553ce7f96 100644 --- a/ets2panda/bindings/src/driver_helper.ts +++ b/ets2panda/bindings/src/driver_helper.ts @@ -95,14 +95,14 @@ export class LspDriverHelper { if (ctx === undefined) { throwError("Trying to proceed to state while cts is undefined") } - if (state <= global.es2panda._ContextState(ctx)) { + if (state <= global.es2pandaPublic._ContextState(ctx)) { return } try { - global.es2panda._ProceedToState(ctx, state) + global.es2pandaPublic._ProceedToState(ctx, state) } catch (e) { - global.es2panda._DestroyContext(ctx) + global.es2pandaPublic._DestroyContext(ctx) throw e } } @@ -111,13 +111,13 @@ export class LspDriverHelper { if (ctx === undefined) { return } - global.es2panda._DestroyContext(ctx) + global.es2pandaPublic._DestroyContext(ctx) } public destroyConfig(cfg: Config) { if (cfg === undefined) { return } - global.es2panda._DestroyConfig(cfg.peer) + global.es2pandaPublic._DestroyConfig(cfg.peer) } } diff --git a/ets2panda/bindings/src/global.ts b/ets2panda/bindings/src/global.ts index 6af40a7f73..3cf022f996 100644 --- a/ets2panda/bindings/src/global.ts +++ b/ets2panda/bindings/src/global.ts @@ -15,9 +15,9 @@ import { throwError } from "./utils" import { KNativePointer } from "./InteropTypes" -import { initEs2panda, Es2pandaNativeModule, initGeneratedEs2panda } from "./Es2pandaNativeModule" +import { initEs2panda, Es2pandaNativeModule, initGeneratedEs2panda, initPublicEs2panda, initPublicGeneratedEs2panda } from "./Es2pandaNativeModule" import { Es2pandaNativeModule as GeneratedEs2pandaNativeModule } from "./generated/Es2pandaNativeModule" -import { initInterop, InteropNativeModule } from "./InteropNativeModule" +import { initInterop, InteropNativeModule, initPublicInterop } from "./InteropNativeModule" import { Context } from "./types" export class global { @@ -52,6 +52,7 @@ export class global { } private static _es2panda: Es2pandaNativeModule | undefined = undefined + private static _es2pandaPublic: Es2pandaNativeModule | undefined = undefined public static get es2panda(): Es2pandaNativeModule { if (this._es2panda === undefined) { this._es2panda = initEs2panda() @@ -59,7 +60,15 @@ export class global { return this._es2panda } + public static get es2pandaPublic(): Es2pandaNativeModule { + if (this._es2pandaPublic === undefined) { + this._es2pandaPublic = initPublicEs2panda() + } + return this._es2pandaPublic + } + private static _generatedEs2panda: GeneratedEs2pandaNativeModule | undefined = undefined + private static _generatedEs2pandaPublic: GeneratedEs2pandaNativeModule | undefined = undefined public static get generatedEs2panda(): GeneratedEs2pandaNativeModule { if (this._generatedEs2panda === undefined) { this._generatedEs2panda = initGeneratedEs2panda() @@ -67,9 +76,22 @@ export class global { return this._generatedEs2panda } + public static get generatedEs2pandaPublic(): GeneratedEs2pandaNativeModule { + if (this._generatedEs2pandaPublic === undefined) { + this._generatedEs2pandaPublic = initPublicGeneratedEs2panda() + } + return this._generatedEs2pandaPublic + } + private static _interop: InteropNativeModule | undefined = undefined + private static _interopPublic: InteropNativeModule | undefined = undefined public static get interop(): InteropNativeModule { if (this._interop === undefined) this._interop = initInterop() return this._interop } + + public static get interopPublic(): InteropNativeModule { + if (this._interopPublic === undefined) this._interopPublic = initPublicInterop() + return this._interopPublic + } } diff --git a/ets2panda/bindings/src/lsp_helper.ts b/ets2panda/bindings/src/lsp_helper.ts index 819a705d2d..592277606d 100644 --- a/ets2panda/bindings/src/lsp_helper.ts +++ b/ets2panda/bindings/src/lsp_helper.ts @@ -18,7 +18,7 @@ import { global } from "./global" import { LspDefinitionData, LspDiagsNode, LspReferences, LspQuickInfo, LspDocumentHighlightsReferences, LspCompletionInfo, LspReferenceLocationList, LspLineAndCharacter, LspReferenceData } from "./lspNode" import { unpackString } from "./private" import { Es2pandaContextState } from "./generated/Es2pandaEnums" -import { BuildConfig, EtsScript } from './types' +import { BuildConfig } from './types' import { PluginDriver, PluginHook } from './ui_plugins_driver' import * as fs from "fs" diff --git a/ets2panda/bindings/src/types.ts b/ets2panda/bindings/src/types.ts index a9d89f1a91..c67661360c 100644 --- a/ets2panda/bindings/src/types.ts +++ b/ets2panda/bindings/src/types.ts @@ -74,7 +74,7 @@ export class Config extends ArktsObject { input: string[], fpath: string, pandaLibPath: string = '', isEditingMode: boolean = false ): Config { if (isEditingMode) { - let cfg = global.es2panda._CreateConfig(input.length, passStringArray(input), pandaLibPath) + let cfg = global.es2pandaPublic._CreateConfig(input.length, passStringArray(input), pandaLibPath) return new Config(cfg, fpath) } if (!global.configIsInitialized()) { @@ -89,26 +89,6 @@ export class Config extends ArktsObject { } } -export class EtsScript extends Node { - constructor(peer: KPtr) { - super(peer) - } - - static fromContext(ctx: Context): EtsScript { - return new EtsScript(global.es2panda._ProgramAst(global.es2panda._ContextProgram(ctx.peer))) - } -} - -export class Program extends ArktsObject { - constructor(peer: KPtr) { - super(peer) - } - - get astNode(): EtsScript { - return new EtsScript(global.es2panda._ProgramAst(this.peer)); - } -} - export class Context extends ArktsObject { constructor(peer: KPtr) { super(peer) @@ -139,15 +119,12 @@ export class Context extends ArktsObject { if (cfg === undefined) { throwError(`Config not initialized`) } - return global.es2panda._CreateContextFromString( + return global.es2pandaPublic._CreateContextFromString( cfg.peer, passString(source), passString(filePath) ) } - get program(): Program { - return new Program(global.es2panda._ContextProgram(this.peer)); - } } // ProjectConfig begins -- Gitee From dd0462d8165d04bab930c74c7833d9d4f8421ae7 Mon Sep 17 00:00:00 2001 From: Klimentieva Date: Tue, 4 Mar 2025 16:11:35 +0300 Subject: [PATCH 032/268] symlink path in dynamic paths arktsconfig Change-Id: I0707697d677e7e9c88057f61174e1f51f3fd6ccf Signed-off-by: Klimentieva --- ets2panda/test/tsconfig/CMakeLists.txt | 1 + .../test/tsconfig/test-decl/CMakeLists.txt | 32 ++++++++ .../check-decl-path/arktsconfig.in.decl.json | 12 +++ .../test-decl/check-decl-path/expected.json | 4 + .../test-decl/check-decl-path/main.ets | 20 +++++ .../arktsconfig.in.decl.json | 12 +++ .../resolve-dynamic-paths/expected.json | 5 ++ .../resolve-dynamic-paths/js/index.ets | 20 +++++ .../resolve-dynamic-paths/js/index.js | 23 ++++++ .../test-decl/resolve-dynamic-paths/main.ets | 24 ++++++ ets2panda/test/tsconfig/test-decl/test.py | 76 +++++++++++++++++++ ets2panda/util/arktsconfig.cpp | 6 ++ .../util/diagnostic/arktsconfig_error.yaml | 4 + 13 files changed, 239 insertions(+) create mode 100644 ets2panda/test/tsconfig/test-decl/CMakeLists.txt create mode 100644 ets2panda/test/tsconfig/test-decl/check-decl-path/arktsconfig.in.decl.json create mode 100644 ets2panda/test/tsconfig/test-decl/check-decl-path/expected.json create mode 100644 ets2panda/test/tsconfig/test-decl/check-decl-path/main.ets create mode 100644 ets2panda/test/tsconfig/test-decl/resolve-dynamic-paths/arktsconfig.in.decl.json create mode 100644 ets2panda/test/tsconfig/test-decl/resolve-dynamic-paths/expected.json create mode 100644 ets2panda/test/tsconfig/test-decl/resolve-dynamic-paths/js/index.ets create mode 100644 ets2panda/test/tsconfig/test-decl/resolve-dynamic-paths/js/index.js create mode 100644 ets2panda/test/tsconfig/test-decl/resolve-dynamic-paths/main.ets create mode 100644 ets2panda/test/tsconfig/test-decl/test.py diff --git a/ets2panda/test/tsconfig/CMakeLists.txt b/ets2panda/test/tsconfig/CMakeLists.txt index 55190eb980..11f275f856 100644 --- a/ets2panda/test/tsconfig/CMakeLists.txt +++ b/ets2panda/test/tsconfig/CMakeLists.txt @@ -17,3 +17,4 @@ endif() add_subdirectory(test-config) add_subdirectory(test-build) +add_subdirectory(test-decl) diff --git a/ets2panda/test/tsconfig/test-decl/CMakeLists.txt b/ets2panda/test/tsconfig/test-decl/CMakeLists.txt new file mode 100644 index 0000000000..daef19951c --- /dev/null +++ b/ets2panda/test/tsconfig/test-decl/CMakeLists.txt @@ -0,0 +1,32 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +function(add_test project) + set(PROJECT_TARGET_NAME es2panda-tsconfig-test-decl-${project}) + set(ETS_CONFIG_DECL ${CMAKE_CURRENT_BINARY_DIR}/${project}/arktsconfig_decl.json) + configure_file(${CMAKE_CURRENT_SOURCE_DIR}/${project}/arktsconfig.in.decl.json ${ETS_CONFIG_DECL}) + add_custom_target(${PROJECT_TARGET_NAME} + COMMENT "Testing tsconfig for: ${project}" + DEPENDS es2panda + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} + COMMAND python3 test.py + --es2panda '${PANDA_RUN_PREFIX} $' + --arktsconfig ${CMAKE_CURRENT_BINARY_DIR}/${project}/arktsconfig_decl.json + --stdlib ${PANDA_ROOT}/plugins/ets/stdlib + --target ${project}/main.ets + ) + add_dependencies(es2panda_tests ${PROJECT_TARGET_NAME}) +endfunction() + +add_test(resolve-dynamic-paths) +add_test(check-decl-path) \ No newline at end of file diff --git a/ets2panda/test/tsconfig/test-decl/check-decl-path/arktsconfig.in.decl.json b/ets2panda/test/tsconfig/test-decl/check-decl-path/arktsconfig.in.decl.json new file mode 100644 index 0000000000..abc17863c9 --- /dev/null +++ b/ets2panda/test/tsconfig/test-decl/check-decl-path/arktsconfig.in.decl.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "baseUrl": "${CMAKE_CURRENT_SOURCE_DIR}", + "paths": { + "escompat": ["${PANDA_ROOT}/plugins/ets/stdlib/escompat"], + "std": ["${PANDA_ROOT}/plugins/ets/stdlib/std"] + }, + "dynamicPaths": { + "js": { "language": "js", "declPath": "${CMAKE_CURRENT_SOURCE_DIR}/wrong-path/js/index.ets", "ohmUrl": "${CMAKE_CURRENT_SOURCE_DIR}/${project}/js/index" } + } + } +} \ No newline at end of file diff --git a/ets2panda/test/tsconfig/test-decl/check-decl-path/expected.json b/ets2panda/test/tsconfig/test-decl/check-decl-path/expected.json new file mode 100644 index 0000000000..64e8f0d406 --- /dev/null +++ b/ets2panda/test/tsconfig/test-decl/check-decl-path/expected.json @@ -0,0 +1,4 @@ +{ + "returncode": 1, + "stderr": "" +} \ No newline at end of file diff --git a/ets2panda/test/tsconfig/test-decl/check-decl-path/main.ets b/ets2panda/test/tsconfig/test-decl/check-decl-path/main.ets new file mode 100644 index 0000000000..a4d48e61d2 --- /dev/null +++ b/ets2panda/test/tsconfig/test-decl/check-decl-path/main.ets @@ -0,0 +1,20 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { A } from "js" + +function main() : void { + let myclass = new A(); +} \ No newline at end of file diff --git a/ets2panda/test/tsconfig/test-decl/resolve-dynamic-paths/arktsconfig.in.decl.json b/ets2panda/test/tsconfig/test-decl/resolve-dynamic-paths/arktsconfig.in.decl.json new file mode 100644 index 0000000000..3e875c427d --- /dev/null +++ b/ets2panda/test/tsconfig/test-decl/resolve-dynamic-paths/arktsconfig.in.decl.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "baseUrl": "${CMAKE_CURRENT_SOURCE_DIR}", + "paths": { + "escompat": ["${PANDA_ROOT}/plugins/ets/stdlib/escompat"], + "std": ["${PANDA_ROOT}/plugins/ets/stdlib/std"] + }, + "dynamicPaths": { + "js": { "language": "js", "declPath": "${CMAKE_CURRENT_SOURCE_DIR}/${project}/js/index.ets", "ohmUrl": "${CMAKE_CURRENT_SOURCE_DIR}/${project}/js/index" } + } + } +} diff --git a/ets2panda/test/tsconfig/test-decl/resolve-dynamic-paths/expected.json b/ets2panda/test/tsconfig/test-decl/resolve-dynamic-paths/expected.json new file mode 100644 index 0000000000..b494dfffa6 --- /dev/null +++ b/ets2panda/test/tsconfig/test-decl/resolve-dynamic-paths/expected.json @@ -0,0 +1,5 @@ +{ + "returncode": 0, + "stdout": "", + "stderr": "" +} \ No newline at end of file diff --git a/ets2panda/test/tsconfig/test-decl/resolve-dynamic-paths/js/index.ets b/ets2panda/test/tsconfig/test-decl/resolve-dynamic-paths/js/index.ets new file mode 100644 index 0000000000..aca7e89390 --- /dev/null +++ b/ets2panda/test/tsconfig/test-decl/resolve-dynamic-paths/js/index.ets @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export declare class A { + name: string; + age: double; + location: string; +} \ No newline at end of file diff --git a/ets2panda/test/tsconfig/test-decl/resolve-dynamic-paths/js/index.js b/ets2panda/test/tsconfig/test-decl/resolve-dynamic-paths/js/index.js new file mode 100644 index 0000000000..e5251ce711 --- /dev/null +++ b/ets2panda/test/tsconfig/test-decl/resolve-dynamic-paths/js/index.js @@ -0,0 +1,23 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +'use strict'; + +class A { + name; + age; + location; +} + +exports.A = A; diff --git a/ets2panda/test/tsconfig/test-decl/resolve-dynamic-paths/main.ets b/ets2panda/test/tsconfig/test-decl/resolve-dynamic-paths/main.ets new file mode 100644 index 0000000000..3366977426 --- /dev/null +++ b/ets2panda/test/tsconfig/test-decl/resolve-dynamic-paths/main.ets @@ -0,0 +1,24 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { A } from "js" + +function main(): void { + let myclass = new A(); + + console.log(myclass["location"]); +} + + diff --git a/ets2panda/test/tsconfig/test-decl/test.py b/ets2panda/test/tsconfig/test-decl/test.py new file mode 100644 index 0000000000..213042f5b2 --- /dev/null +++ b/ets2panda/test/tsconfig/test-decl/test.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +# coding=utf-8 +# +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +import os +import json +import subprocess + + +def ensure_exists(path): + if not os.path.exists(path): + raise RuntimeError(f'The file {path} cannot be found') + + +def es2panda_command(es2panda_path, stdlib_path, arktsconfig_path, target_path): + return [ + *str(es2panda_path).split(), + '--opt-level=2', + '--thread=0', + '--extension=ets', + '--stdlib', stdlib_path, + '--arktsconfig', arktsconfig_path, + '--ets-unnamed', + target_path + ] + + +def compare_output(lhs, rhs): + for k in rhs: + attr = getattr(lhs, k) + if attr != rhs[k]: + message = "\n".join([f'In {k} field', + f'Expected: {rhs[k]}', + f'Got: {attr}']) + raise RuntimeError(message) + + +parser = argparse.ArgumentParser() +parser.add_argument('--es2panda', required=True, + help='Path to es2panda executable, could be prefixed') +parser.add_argument('--arktsconfig', required=True, help='Path to project arktsconfig') +parser.add_argument('--stdlib', required=True, help='Path to es2panda stdlib') +parser.add_argument('--target', required=True, help='Path to .sts to compile it to .abc') + +args = parser.parse_args() + +project_dir = os.path.dirname(args.target) +expected_path = os.path.join(project_dir, 'expected.json') + +[ensure_exists(f) for f in [ + str(args.es2panda).split()[-1], args.arktsconfig, expected_path]] + +cmd = es2panda_command(args.es2panda, args.stdlib, args.arktsconfig, args.target) + + +actual = subprocess.run(cmd, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + encoding='utf-8') + +with open(expected_path, "r", encoding="utf-8") as expected_file: + expected = json.load(expected_file) + compare_output(actual, expected) diff --git a/ets2panda/util/arktsconfig.cpp b/ets2panda/util/arktsconfig.cpp index c541e534f7..f4d1901fb0 100644 --- a/ets2panda/util/arktsconfig.cpp +++ b/ets2panda/util/arktsconfig.cpp @@ -64,6 +64,9 @@ fs::path NormalizePath(const fs::path &p) result /= part; } } + if (fs::exists(result)) { + return fs::canonical(result); + } return result; } #endif // ARKTSCONFIG_USE_FILESYSTEM @@ -268,6 +271,9 @@ bool ArkTsConfig::ParseDynamicPaths(const JsonObject::JsonObjPointer *options, std::string normalizedDeclPath {}; if (declPathValue != nullptr) { normalizedDeclPath = ark::os::GetAbsolutePath(*declPathValue); + if (!Check(ark::os::IsFileExists(normalizedDeclPath), diagnostic::INVALID_DYNAMIC_PATH, {key})) { + return false; + } } auto res = dynamicPathsMap.insert( {ark::os::NormalizePath(key), ArkTsConfig::DynamicImportData(*lang, normalizedDeclPath, ohmUrlValue)}); diff --git a/ets2panda/util/diagnostic/arktsconfig_error.yaml b/ets2panda/util/diagnostic/arktsconfig_error.yaml index 1f30a289bb..2568bcd284 100644 --- a/ets2panda/util/diagnostic/arktsconfig_error.yaml +++ b/ets2panda/util/diagnostic/arktsconfig_error.yaml @@ -75,3 +75,7 @@ arkts_config_error: - name: INVALID_DESTINATION_FILE id: 16 message: Invalid destination file + +- name: INVALID_DYNAMIC_PATH + id: 17 + message: Invalid dynamic path '{}' -- Gitee From 5ce055648af222e0eb240e0788af08a59fa15164 Mon Sep 17 00:00:00 2001 From: huangyu Date: Wed, 16 Apr 2025 20:18:30 +0800 Subject: [PATCH 033/268] Modify arkguard reviewer Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC1PSI Signed-off-by: huangyu Change-Id: I9866f0c18821eae6ad5d7d4966e84c73033ff55e --- ets2panda/REVIEWERS | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ets2panda/REVIEWERS b/ets2panda/REVIEWERS index 9b3f422a62..1a3d942328 100644 --- a/ets2panda/REVIEWERS +++ b/ets2panda/REVIEWERS @@ -14,7 +14,7 @@ * @gavin1012_hw @zhuoli72 .* @zhuoli72 @Prof1983 @igelhaus -/arkguard/ @zhangchen168 +/arkguard/ @huangyu76 /es2panda/ @gavin1012_hw /ets2panda/ @igelhaus @Prof1983 /ets2panda/aot @dkofanov @gavin1012_hw ^igelhaus ^Prof1983 @@ -100,4 +100,4 @@ /ets2panda/compiler/lowering/ets/optionalLowering.cpp @akmaevaleksey ^vpukhov ^igelhaus ^Prof1983 /ets2panda/compiler/lowering/ets/spread* @ziziziiziziz @dkofanov ^akmaevaleksey ^igelhaus ^Prof1983 /ets2panda/compiler/lowering/ets/unionLowering.cpp @Ekkoruse @akmaevaleksey ^vpukhov ^igelhaus ^Prof1983 -/ets2panda/compiler/lowering/ets/topLevelStmts/.* @lirismankarina @xuxjeeee ^akmaevaleksey ^vpukhov ^igelhaus ^Prof1983 \ No newline at end of file +/ets2panda/compiler/lowering/ets/topLevelStmts/.* @lirismankarina @xuxjeeee ^akmaevaleksey ^vpukhov ^igelhaus ^Prof1983 -- Gitee From 4b3bf90858ec455b115f79e706f84e8b6fbe0984 Mon Sep 17 00:00:00 2001 From: Tao Wu Date: Tue, 15 Apr 2025 18:03:45 +0800 Subject: [PATCH 034/268] Fix build system failure on macOS Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC1PW6 Signed-off-by: Tao Wu Change-Id: I1a0a4fd3aa812ef9b5f5f05322a6448de80cf29a --- ets2panda/driver/build_system/src/build/base_mode.ts | 9 +++++++-- .../driver/build_system/src/init/process_build_config.ts | 3 +++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/ets2panda/driver/build_system/src/build/base_mode.ts b/ets2panda/driver/build_system/src/build/base_mode.ts index b0f3a57b38..7374d81a9d 100644 --- a/ets2panda/driver/build_system/src/build/base_mode.ts +++ b/ets2panda/driver/build_system/src/build/base_mode.ts @@ -35,7 +35,8 @@ import { import { changeFileExtension, ensurePathExists, - isFileExistSync + isFileExistSync, + isMac } from '../utils'; import { PluginDriver, @@ -245,6 +246,10 @@ export abstract class BaseMode { this.abcLinkerCmd.push('@' + '"' + linkerInputFile + '"'); let abcLinkerCmdStr: string = this.abcLinkerCmd.join(' '); + if (isMac()) { + const loadLibrary = "DYLD_LIBRARY_PATH=" + process.env.DYLD_LIBRARY_PATH; + abcLinkerCmdStr = loadLibrary + " " + abcLinkerCmdStr; + } this.logger.printInfo(abcLinkerCmdStr); ensurePathExists(this.mergedAbcFile); @@ -567,4 +572,4 @@ export abstract class BaseMode { execArgv: execArgs, }); } -} \ No newline at end of file +} diff --git a/ets2panda/driver/build_system/src/init/process_build_config.ts b/ets2panda/driver/build_system/src/init/process_build_config.ts index 58900a0dc8..f7b4caa75c 100644 --- a/ets2panda/driver/build_system/src/init/process_build_config.ts +++ b/ets2panda/driver/build_system/src/init/process_build_config.ts @@ -77,6 +77,9 @@ export function initBuildEnv(buildConfig: BuildConfig): void { let pandaLibPath: string = path.resolve(pandaSdkPath, 'lib'); process.env.PATH = `${currentPath}${path.delimiter}${pandaLibPath}`; + if (isMac()) { + process.env.DYLD_LIBRARY_PATH = `${currentPath}${path.delimiter}${pandaLibPath}`; + } logger.printInfo(`Updated PATH: ${process.env.PATH}`); } -- Gitee From eb0bc7f61a8094a6d9c9e6d9691c7a8e3b90d64d Mon Sep 17 00:00:00 2001 From: ozerovnikita Date: Tue, 8 Apr 2025 15:59:07 +0300 Subject: [PATCH 035/268] add "ETSGLOBAL." to global func src dump Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBV3OF Test: ninja es2panda-plugin-test Signed-off-by: ozerovnikita --- ets2panda/compiler/lowering/util.cpp | 13 +-- ets2panda/compiler/lowering/util.h | 3 +- ets2panda/ir/base/classDefinition.cpp | 23 +++++ ets2panda/ir/base/classDefinition.h | 1 + ets2panda/ir/base/classProperty.cpp | 13 ++- ets2panda/ir/base/classProperty.h | 1 + ets2panda/ir/base/methodDefinition.cpp | 11 +++ ets2panda/test/unit/plugin/CMakeLists.txt | 1 + ...ed_to_state_test_global_func_call_dump.cpp | 86 +++++++++++++++++++ .../use_plugin_to_test_export_table.cpp | 2 +- 10 files changed, 146 insertions(+), 8 deletions(-) create mode 100644 ets2panda/test/unit/plugin/plugin_proceed_to_state_test_global_func_call_dump.cpp diff --git a/ets2panda/compiler/lowering/util.cpp b/ets2panda/compiler/lowering/util.cpp index 43f7b3c500..81227a75f1 100644 --- a/ets2panda/compiler/lowering/util.cpp +++ b/ets2panda/compiler/lowering/util.cpp @@ -22,6 +22,12 @@ namespace ark::es2panda::compiler { +bool HasGlobalClassParent(const ir::AstNode *node) +{ + auto parentClass = util::Helpers::FindAncestorGivenByType(node, ir::AstNodeType::CLASS_DEFINITION); + return parentClass != nullptr && parentClass->AsClassDefinition()->IsGlobal(); +} + varbinder::Scope *NearestScope(const ir::AstNode *ast) { while (ast != nullptr && !ast->IsScopeBearer()) { @@ -33,10 +39,7 @@ varbinder::Scope *NearestScope(const ir::AstNode *ast) checker::ETSObjectType const *ContainingClass(const ir::AstNode *ast) { - while (ast != nullptr && !ast->IsClassDefinition()) { - ast = ast->Parent(); - } - + ast = util::Helpers::FindAncestorGivenByType(ast, ir::AstNodeType::CLASS_DEFINITION); return ast == nullptr ? nullptr : ast->AsClassDefinition()->TsType()->AsETSObjectType(); } @@ -228,7 +231,7 @@ void Recheck(PhaseManager *phaseManager, varbinder::ETSBinder *varBinder, checke } // NOTE: used to get the declaration from identifier in Plugin API and LSP -ir::AstNode *DeclarationFromIdentifier(ir::Identifier *node) +ir::AstNode *DeclarationFromIdentifier(const ir::Identifier *node) { auto idVar = node->Variable(); if (idVar == nullptr) { diff --git a/ets2panda/compiler/lowering/util.h b/ets2panda/compiler/lowering/util.h index 7a08db7c00..1d09e6d848 100644 --- a/ets2panda/compiler/lowering/util.h +++ b/ets2panda/compiler/lowering/util.h @@ -25,6 +25,7 @@ class PhaseManager; inline constexpr std::string_view const GENSYM_CORE = "gensym%%_"; inline constexpr std::string_view const DUMMY_ID = "_"; +bool HasGlobalClassParent(const ir::AstNode *node); varbinder::Scope *NearestScope(const ir::AstNode *ast); checker::ETSObjectType const *ContainingClass(const ir::AstNode *ast); ir::Identifier *Gensym(ArenaAllocator *allocator); @@ -40,7 +41,7 @@ void Recheck(PhaseManager *phaseManager, varbinder::ETSBinder *varBinder, checke ir::AstNode *node); // NOTE: used to get the declaration from identifier in Plugin API and LSP -ir::AstNode *DeclarationFromIdentifier(ir::Identifier *node); +ir::AstNode *DeclarationFromIdentifier(const ir::Identifier *node); // Note: run varbinder and checker on the new node generated in lowering phases void CheckLoweredNode(varbinder::ETSBinder *varBinder, checker::ETSChecker *checker, ir::AstNode *node); diff --git a/ets2panda/ir/base/classDefinition.cpp b/ets2panda/ir/base/classDefinition.cpp index 908c71b045..48c03fd0c4 100644 --- a/ets2panda/ir/base/classDefinition.cpp +++ b/ets2panda/ir/base/classDefinition.cpp @@ -184,6 +184,23 @@ void ClassDefinition::Dump(ir::AstDumper *dumper) const {"body", body_, propFilter}}); } +void ClassDefinition::DumpGlobalClass(ir::SrcDumper *dumper) const +{ + ES2PANDA_ASSERT(IsGlobal()); + for (auto elem : body_) { + if (elem->IsClassProperty()) { + elem->Dump(dumper); + dumper->Endl(); + } + } + for (auto elem : body_) { + if (elem->IsMethodDefinition()) { + elem->Dump(dumper); + dumper->Endl(); + } + } +} + // This method is needed by OHOS CI code checker void ClassDefinition::DumpBody(ir::SrcDumper *dumper) const { @@ -208,6 +225,12 @@ void ClassDefinition::Dump(ir::SrcDumper *dumper) const if ((ident_->Name().StartsWith("$dynmodule")) || (ident_->Name().StartsWith("$jscall"))) { return; } + + if (IsGlobal()) { + DumpGlobalClass(dumper); + return; + } + for (auto *anno : Annotations()) { anno->Dump(dumper); } diff --git a/ets2panda/ir/base/classDefinition.h b/ets2panda/ir/base/classDefinition.h index bfff217ba8..43f501035a 100644 --- a/ets2panda/ir/base/classDefinition.h +++ b/ets2panda/ir/base/classDefinition.h @@ -475,6 +475,7 @@ private: // This method is needed by OHOS CI code checker void DumpBody(ir::SrcDumper *dumper) const; + void DumpGlobalClass(ir::SrcDumper *dumper) const; varbinder::LocalScope *scope_ {nullptr}; util::StringView internalName_ {}; diff --git a/ets2panda/ir/base/classProperty.cpp b/ets2panda/ir/base/classProperty.cpp index 77bbb99ba1..2aed95995e 100644 --- a/ets2panda/ir/base/classProperty.cpp +++ b/ets2panda/ir/base/classProperty.cpp @@ -19,6 +19,7 @@ #include "checker/TSchecker.h" #include "compiler/core/ETSGen.h" #include "compiler/core/pandagen.h" +#include "compiler/lowering/util.h" namespace ark::es2panda::ir { void ClassProperty::TransformChildren(const NodeTransformer &cb, std::string_view const transformationName) @@ -95,12 +96,17 @@ void ClassProperty::Dump(ir::AstDumper *dumper) const {"annotations", AstDumper::Optional(Annotations())}}); } -void ClassProperty::Dump(ir::SrcDumper *dumper) const +void ClassProperty::DumpPrefix(ir::SrcDumper *dumper) const { for (auto *anno : Annotations()) { anno->Dump(dumper); } + if (compiler::HasGlobalClassParent(this)) { + dumper->Add("let "); + return; + } + if (Parent() != nullptr && Parent()->IsClassDefinition() && !Parent()->AsClassDefinition()->IsLocal()) { if (IsPrivate()) { dumper->Add("private "); @@ -120,6 +126,11 @@ void ClassProperty::Dump(ir::SrcDumper *dumper) const if (IsReadonly()) { dumper->Add("readonly "); } +} + +void ClassProperty::Dump(ir::SrcDumper *dumper) const +{ + DumpPrefix(dumper); if (key_ != nullptr) { key_->Dump(dumper); diff --git a/ets2panda/ir/base/classProperty.h b/ets2panda/ir/base/classProperty.h index 6327c850d9..eb233d6fb0 100644 --- a/ets2panda/ir/base/classProperty.h +++ b/ets2panda/ir/base/classProperty.h @@ -86,6 +86,7 @@ public: } private: + void DumpPrefix(ir::SrcDumper *dumper) const; TypeNode *typeAnnotation_; bool isDefault_ = false; }; diff --git a/ets2panda/ir/base/methodDefinition.cpp b/ets2panda/ir/base/methodDefinition.cpp index b5c91f95a4..f756c90372 100644 --- a/ets2panda/ir/base/methodDefinition.cpp +++ b/ets2panda/ir/base/methodDefinition.cpp @@ -20,6 +20,7 @@ #include "compiler/core/pandagen.h" #include "classDefinition.h" #include "ir/ts/tsInterfaceBody.h" +#include "compiler/lowering/util.h" namespace ark::es2panda::ir { @@ -160,6 +161,11 @@ void MethodDefinition::Dump(ir::AstDumper *dumper) const void MethodDefinition::DumpPrefix(ir::SrcDumper *dumper) const { + if (compiler::HasGlobalClassParent(this)) { + dumper->Add("function "); + return; + } + if (Parent() != nullptr && Parent()->IsClassDefinition() && !Parent()->AsClassDefinition()->IsLocal()) { if (IsPrivate()) { dumper->Add("private "); @@ -205,6 +211,11 @@ void MethodDefinition::DumpPrefix(ir::SrcDumper *dumper) const void MethodDefinition::Dump(ir::SrcDumper *dumper) const { + if (compiler::HasGlobalClassParent(this) && Id()->Name().Is(compiler::Signatures::INIT_METHOD)) { + Function()->Body()->Dump(dumper); + return; + } + for (auto method : overloads_) { method->Dump(dumper); dumper->Endl(); diff --git a/ets2panda/test/unit/plugin/CMakeLists.txt b/ets2panda/test/unit/plugin/CMakeLists.txt index 86856a0fc2..ca00af5a73 100644 --- a/ets2panda/test/unit/plugin/CMakeLists.txt +++ b/ets2panda/test/unit/plugin/CMakeLists.txt @@ -95,6 +95,7 @@ set(PLUGIN_TESTS "plugin_proceed_to_state_default_access_modifier compile.ets ${COMPILE_MODE} cpp ${EXECUTABLE_PLUGIN}" "plugin_proceed_to_state_assignment_expression_set_result compile.ets ${COMPILE_MODE} cpp ${EXECUTABLE_PLUGIN}" "use_plugin_to_test_export_table compile.ets ${COMPILE_MODE} cpp ${EXECUTABLE_PLUGIN}" + "plugin_proceed_to_state_test_global_func_call_dump compile.ets ${COMPILE_MODE} cpp ${EXECUTABLE_PLUGIN}" ) set(RUNTIME_ARGUMENTS diff --git a/ets2panda/test/unit/plugin/plugin_proceed_to_state_test_global_func_call_dump.cpp b/ets2panda/test/unit/plugin/plugin_proceed_to_state_test_global_func_call_dump.cpp new file mode 100644 index 0000000000..aebb296a91 --- /dev/null +++ b/ets2panda/test/unit/plugin/plugin_proceed_to_state_test_global_func_call_dump.cpp @@ -0,0 +1,86 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include "util.h" +#include "public/es2panda_lib.h" + +// NOLINTBEGIN + +static es2panda_Impl *impl = nullptr; +static constexpr int NUMBER_OF_COMPILATION = 5; + +static std::string source = R"( +function foo() { + main(); +} +let c: number = 2; +function main() { + foo(); + console.log(c); + let b: number = c + 1; + let a: () => void = foo; + let d: number = b + 1; +} +class A { + goo() { + foo(); + } +} +)"; + +int main(int argc, char **argv) +{ + if (argc < MIN_ARGC) { + return 1; + } + + if (GetImpl() == nullptr) { + return NULLPTR_IMPL_ERROR_CODE; + } + impl = GetImpl(); + const char **args = const_cast(&(argv[1])); + es2panda_Config *config; + es2panda_Context *context; + + for (int i = 0; i < NUMBER_OF_COMPILATION; i++) { + config = impl->CreateConfig(argc - 1, args); + context = impl->CreateContextFromString(config, source.data(), argv[argc - 1]); + if (context == nullptr) { + return TEST_ERROR_CODE; + } + + impl->ProceedToState(context, ES2PANDA_STATE_CHECKED); + CheckForErrors("CHECKED", context); + + // Run es2panda on new source(src dump) + source = std::string( + impl->AstNodeDumpEtsSrcConst(context, impl->ProgramAst(context, impl->ContextProgram(context)))); + std::cout << source << std::endl; + impl->ProceedToState(context, ES2PANDA_STATE_BIN_GENERATED); + if (impl->ContextState(context) == ES2PANDA_STATE_ERROR) { + impl->DestroyContext(context); + impl->DestroyConfig(config); + return TEST_ERROR_CODE; + } + impl->DestroyContext(context); + impl->DestroyConfig(config); + } + + return 0; +} + +// NOLINTEND diff --git a/ets2panda/test/unit/plugin/use_plugin_to_test_export_table.cpp b/ets2panda/test/unit/plugin/use_plugin_to_test_export_table.cpp index 855161adab..1bfb5a30ef 100644 --- a/ets2panda/test/unit/plugin/use_plugin_to_test_export_table.cpp +++ b/ets2panda/test/unit/plugin/use_plugin_to_test_export_table.cpp @@ -57,7 +57,7 @@ const std::string SOURCE_CODE = const std::string EXPECTED_CLASS_DEFINITION = "class A {\n public constructor() {}\n \n}\n"; -const std::string EXPECTED_METHOD_DEFINITION = "public static foo(): void {}\n"; +const std::string EXPECTED_METHOD_DEFINITION = "function foo(): void {}\n"; int CheckLiteralValues(ark::es2panda::public_lib::Context *ctx, const ark::pandasm::Program &prog) { -- Gitee From 734774c5b69e8ef7bac0e1915327db25be6dae21 Mon Sep 17 00:00:00 2001 From: Daniel Kofanov Date: Thu, 23 Jan 2025 22:47:34 +0800 Subject: [PATCH 036/268] Fix ASTVerifier 1. Change log level 'error'->'fatal'. 2. Revert enabling verifer-on-each-phase by-default. 3. Remove excessive 'RecursiveInvariant'-mixin. 4. Introduce an ability to specify dependecies between invariants ('RequiredInvariants'). 5. Segregate invariants from it's management under 'invariants' dir. Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBX5LF?from=project-issue Signed-off-by: Daniel Kofanov --- ets2panda/BUILD.gn | 42 +++--- ets2panda/CMakeLists.txt | 40 +++--- ets2panda/ast_verifier/ASTVerifier.cpp | 77 ++++++----- ets2panda/ast_verifier/ASTVerifier.h | 122 +++++------------- .../{checkContext.h => invariantBase.h} | 108 ++++++++++++++-- .../arithmeticOperationValid.cpp | 4 +- .../arithmeticOperationValid.h | 16 +-- .../{ => invariants}/checkAbstractMethod.cpp | 2 +- .../{ => invariants}/checkAbstractMethod.h | 16 +-- .../{ => invariants}/checkConstProperties.cpp | 0 .../{ => invariants}/checkConstProperties.h | 16 +-- .../checkScopeDeclaration.cpp | 2 +- .../{ => invariants}/checkScopeDeclaration.h | 18 +-- .../checkStructDeclaration.cpp | 0 .../{ => invariants}/checkStructDeclaration.h | 14 +- .../everyChildHasValidParent.cpp | 0 .../everyChildHasValidParent.h} | 16 +-- .../everyChildInParentRange.cpp | 2 +- .../invariants/everyChildInParentRange.h | 31 +++++ .../forLoopCorrectlyInitialized.cpp | 2 +- .../forLoopCorrectlyInitialized.h | 18 +-- .../getterSetterValidation.cpp | 0 .../{ => invariants}/getterSetterValidation.h | 18 +-- .../identifierHasVariable.cpp | 0 .../{ => invariants}/identifierHasVariable.h | 15 ++- .../importExportAccessValid.cpp | 2 +- .../importExportAccessValid.h | 17 ++- .../{ => invariants}/modifierAccessValid.cpp | 4 +- .../{ => invariants}/modifierAccessValid.h | 18 +-- .../{ => invariants}/nodeHasParent.cpp | 0 .../{ => invariants}/nodeHasParent.h | 16 +-- .../{ => invariants}/nodeHasSourceRange.cpp | 2 +- .../{ => invariants}/nodeHasSourceRange.h | 16 +-- .../{ => invariants}/nodeHasType.cpp | 113 ++++++++-------- .../{ => invariants}/nodeHasType.h | 34 ++--- .../referenceTypeAnnotationIsNull.cpp | 0 .../referenceTypeAnnotationIsNull.h | 16 +-- .../sequenceExpressionHasLastType.cpp | 0 .../sequenceExpressionHasLastType.h} | 16 +-- .../variableHasEnclosingScope.cpp | 2 +- .../variableHasEnclosingScope.h | 16 +-- .../{ => invariants}/variableHasScope.cpp | 3 +- .../{ => invariants}/variableHasScope.h | 14 +- .../variableNameIdentifierNameSame.cpp | 0 .../variableNameIdentifierNameSame.h | 31 +++++ .../sequenceExpressionHasLastType.h | 31 ----- .../variableNameIdentifierNameSame.h | 32 ----- ets2panda/compiler/core/compilerImpl.cpp | 19 +-- ets2panda/public/CMakeLists.txt | 2 - ..._verifier_private_access_negative_test.cpp | 6 +- ...erifier_protected_access_negative_test.cpp | 6 +- .../unit/public/ast_verifier_short_test.cpp | 21 ++- ets2panda/test/utils/ast_verifier_test.h | 21 ++- ets2panda/util/options.yaml | 2 +- 54 files changed, 544 insertions(+), 495 deletions(-) rename ets2panda/ast_verifier/{checkContext.h => invariantBase.h} (41%) rename ets2panda/ast_verifier/{ => invariants}/arithmeticOperationValid.cpp (97%) rename ets2panda/ast_verifier/{ => invariants}/arithmeticOperationValid.h (62%) rename ets2panda/ast_verifier/{ => invariants}/checkAbstractMethod.cpp (96%) rename ets2panda/ast_verifier/{ => invariants}/checkAbstractMethod.h (62%) rename ets2panda/ast_verifier/{ => invariants}/checkConstProperties.cpp (100%) rename ets2panda/ast_verifier/{ => invariants}/checkConstProperties.h (62%) rename ets2panda/ast_verifier/{ => invariants}/checkScopeDeclaration.cpp (98%) rename ets2panda/ast_verifier/{ => invariants}/checkScopeDeclaration.h (63%) rename ets2panda/ast_verifier/{ => invariants}/checkStructDeclaration.cpp (100%) rename ets2panda/ast_verifier/{ => invariants}/checkStructDeclaration.h (66%) rename ets2panda/ast_verifier/{ => invariants}/everyChildHasValidParent.cpp (100%) rename ets2panda/ast_verifier/{everyChildInParentRange.h => invariants/everyChildHasValidParent.h} (61%) rename ets2panda/ast_verifier/{ => invariants}/everyChildInParentRange.cpp (97%) create mode 100644 ets2panda/ast_verifier/invariants/everyChildInParentRange.h rename ets2panda/ast_verifier/{ => invariants}/forLoopCorrectlyInitialized.cpp (98%) rename ets2panda/ast_verifier/{ => invariants}/forLoopCorrectlyInitialized.h (66%) rename ets2panda/ast_verifier/{ => invariants}/getterSetterValidation.cpp (100%) rename ets2panda/ast_verifier/{ => invariants}/getterSetterValidation.h (65%) rename ets2panda/ast_verifier/{ => invariants}/identifierHasVariable.cpp (100%) rename ets2panda/ast_verifier/{ => invariants}/identifierHasVariable.h (72%) rename ets2panda/ast_verifier/{ => invariants}/importExportAccessValid.cpp (99%) rename ets2panda/ast_verifier/{ => invariants}/importExportAccessValid.h (74%) rename ets2panda/ast_verifier/{ => invariants}/modifierAccessValid.cpp (97%) rename ets2panda/ast_verifier/{ => invariants}/modifierAccessValid.h (65%) rename ets2panda/ast_verifier/{ => invariants}/nodeHasParent.cpp (100%) rename ets2panda/ast_verifier/{ => invariants}/nodeHasParent.h (64%) rename ets2panda/ast_verifier/{ => invariants}/nodeHasSourceRange.cpp (95%) rename ets2panda/ast_verifier/{ => invariants}/nodeHasSourceRange.h (62%) rename ets2panda/ast_verifier/{ => invariants}/nodeHasType.cpp (31%) rename ets2panda/ast_verifier/{ => invariants}/nodeHasType.h (65%) rename ets2panda/ast_verifier/{ => invariants}/referenceTypeAnnotationIsNull.cpp (100%) rename ets2panda/ast_verifier/{ => invariants}/referenceTypeAnnotationIsNull.h (61%) rename ets2panda/ast_verifier/{ => invariants}/sequenceExpressionHasLastType.cpp (100%) rename ets2panda/ast_verifier/{everyChildHasValidParent.h => invariants/sequenceExpressionHasLastType.h} (60%) rename ets2panda/ast_verifier/{ => invariants}/variableHasEnclosingScope.cpp (99%) rename ets2panda/ast_verifier/{ => invariants}/variableHasEnclosingScope.h (66%) rename ets2panda/ast_verifier/{ => invariants}/variableHasScope.cpp (98%) rename ets2panda/ast_verifier/{ => invariants}/variableHasScope.h (71%) rename ets2panda/ast_verifier/{ => invariants}/variableNameIdentifierNameSame.cpp (100%) create mode 100644 ets2panda/ast_verifier/invariants/variableNameIdentifierNameSame.h delete mode 100644 ets2panda/ast_verifier/sequenceExpressionHasLastType.h delete mode 100644 ets2panda/ast_verifier/variableNameIdentifierNameSame.h diff --git a/ets2panda/BUILD.gn b/ets2panda/BUILD.gn index 8636a69d2a..73e0bc965f 100644 --- a/ets2panda/BUILD.gn +++ b/ets2panda/BUILD.gn @@ -33,27 +33,27 @@ config("libes2panda_public_config") { libes2panda_sources = [ "ast_verifier/ASTVerifier.cpp", - "ast_verifier/arithmeticOperationValid.cpp", - "ast_verifier/checkAbstractMethod.cpp", - "ast_verifier/checkConstProperties.cpp", - "ast_verifier/checkScopeDeclaration.cpp", - "ast_verifier/checkStructDeclaration.cpp", - "ast_verifier/everyChildHasValidParent.cpp", - "ast_verifier/everyChildInParentRange.cpp", - "ast_verifier/forLoopCorrectlyInitialized.cpp", - "ast_verifier/getterSetterValidation.cpp", "ast_verifier/helpers.cpp", - "ast_verifier/identifierHasVariable.cpp", - "ast_verifier/importExportAccessValid.cpp", - "ast_verifier/modifierAccessValid.cpp", - "ast_verifier/nodeHasParent.cpp", - "ast_verifier/nodeHasSourceRange.cpp", - "ast_verifier/nodeHasType.cpp", - "ast_verifier/referenceTypeAnnotationIsNull.cpp", - "ast_verifier/sequenceExpressionHasLastType.cpp", - "ast_verifier/variableHasEnclosingScope.cpp", - "ast_verifier/variableHasScope.cpp", - "ast_verifier/variableNameIdentifierNameSame.cpp", + "ast_verifier/invariants/arithmeticOperationValid.cpp", + "ast_verifier/invariants/checkAbstractMethod.cpp", + "ast_verifier/invariants/checkConstProperties.cpp", + "ast_verifier/invariants/checkScopeDeclaration.cpp", + "ast_verifier/invariants/checkStructDeclaration.cpp", + "ast_verifier/invariants/everyChildHasValidParent.cpp", + "ast_verifier/invariants/everyChildInParentRange.cpp", + "ast_verifier/invariants/forLoopCorrectlyInitialized.cpp", + "ast_verifier/invariants/getterSetterValidation.cpp", + "ast_verifier/invariants/identifierHasVariable.cpp", + "ast_verifier/invariants/importExportAccessValid.cpp", + "ast_verifier/invariants/modifierAccessValid.cpp", + "ast_verifier/invariants/nodeHasParent.cpp", + "ast_verifier/invariants/nodeHasSourceRange.cpp", + "ast_verifier/invariants/nodeHasType.cpp", + "ast_verifier/invariants/referenceTypeAnnotationIsNull.cpp", + "ast_verifier/invariants/sequenceExpressionHasLastType.cpp", + "ast_verifier/invariants/variableHasEnclosingScope.cpp", + "ast_verifier/invariants/variableHasScope.cpp", + "ast_verifier/invariants/variableNameIdentifierNameSame.cpp", "checker/ASchecker.cpp", "checker/ETSAnalyzer.cpp", "checker/ETSAnalyzerHelpers.cpp", @@ -756,7 +756,6 @@ HEADERS_TO_BE_PARSED = [ "parser/program/program.h", "es2panda.h", "ast_verifier/ASTVerifier.h", - "ast_verifier/checkContext.h", "util/importPathManager.h", ] @@ -1024,7 +1023,6 @@ ES2PANDA_API_GENERATED = [ "$LIBGEN_DIR/gen/headers/parser/ETSparser.yaml", "$LIBGEN_DIR/gen/headers/parser/program/program.yaml", "$LIBGEN_DIR/gen/headers/ast_verifier/ASTVerifier.yaml", - "$LIBGEN_DIR/gen/headers/ast_verifier/checkContext.yaml", "$LIBGEN_DIR/gen/headers/util/importPathManager.yaml", ] diff --git a/ets2panda/CMakeLists.txt b/ets2panda/CMakeLists.txt index 7931019cfc..7bfb532c91 100644 --- a/ets2panda/CMakeLists.txt +++ b/ets2panda/CMakeLists.txt @@ -166,27 +166,27 @@ panda_gen( set(ES2PANDA_LIB_SRC ast_verifier/ASTVerifier.cpp - ast_verifier/arithmeticOperationValid.cpp - ast_verifier/checkAbstractMethod.cpp - ast_verifier/checkConstProperties.cpp - ast_verifier/checkScopeDeclaration.cpp - ast_verifier/checkStructDeclaration.cpp - ast_verifier/everyChildHasValidParent.cpp - ast_verifier/everyChildInParentRange.cpp - ast_verifier/getterSetterValidation.cpp ast_verifier/helpers.cpp - ast_verifier/identifierHasVariable.cpp - ast_verifier/importExportAccessValid.cpp - ast_verifier/nodeHasParent.cpp - ast_verifier/nodeHasSourceRange.cpp - ast_verifier/nodeHasType.cpp - ast_verifier/referenceTypeAnnotationIsNull.cpp - ast_verifier/forLoopCorrectlyInitialized.cpp - ast_verifier/modifierAccessValid.cpp - ast_verifier/sequenceExpressionHasLastType.cpp - ast_verifier/variableHasEnclosingScope.cpp - ast_verifier/variableHasScope.cpp - ast_verifier/variableNameIdentifierNameSame.cpp + ast_verifier/invariants/arithmeticOperationValid.cpp + ast_verifier/invariants/checkAbstractMethod.cpp + ast_verifier/invariants/checkConstProperties.cpp + ast_verifier/invariants/checkScopeDeclaration.cpp + ast_verifier/invariants/checkStructDeclaration.cpp + ast_verifier/invariants/everyChildHasValidParent.cpp + ast_verifier/invariants/everyChildInParentRange.cpp + ast_verifier/invariants/getterSetterValidation.cpp + ast_verifier/invariants/identifierHasVariable.cpp + ast_verifier/invariants/importExportAccessValid.cpp + ast_verifier/invariants/nodeHasParent.cpp + ast_verifier/invariants/nodeHasSourceRange.cpp + ast_verifier/invariants/nodeHasType.cpp + ast_verifier/invariants/referenceTypeAnnotationIsNull.cpp + ast_verifier/invariants/forLoopCorrectlyInitialized.cpp + ast_verifier/invariants/modifierAccessValid.cpp + ast_verifier/invariants/sequenceExpressionHasLastType.cpp + ast_verifier/invariants/variableHasEnclosingScope.cpp + ast_verifier/invariants/variableHasScope.cpp + ast_verifier/invariants/variableNameIdentifierNameSame.cpp es2panda.cpp varbinder/ASBinder.cpp varbinder/TSBinder.cpp diff --git a/ets2panda/ast_verifier/ASTVerifier.cpp b/ets2panda/ast_verifier/ASTVerifier.cpp index ced6d67138..9854161341 100644 --- a/ets2panda/ast_verifier/ASTVerifier.cpp +++ b/ets2panda/ast_verifier/ASTVerifier.cpp @@ -19,6 +19,16 @@ namespace ark::es2panda::compiler::ast_verifier { using AstToCheck = ArenaMap; +template +auto VerifyNode(Inv *inv, const ir::AstNode *node) +{ + auto [res, action] = (*inv)(node); + if (action == CheckAction::SKIP_SUBTREE) { + LOG_ASTV(DEBUG, Inv::NAME << ": SKIP_SUBTREE"); + } + return CheckResult {res, action}; +} + struct ASTVerifier::SinglePassVerifier { // NOLINTBEGIN(misc-non-private-member-variables-in-classes) ASTVerifier *verifier {nullptr}; @@ -29,28 +39,25 @@ struct ASTVerifier::SinglePassVerifier { { const auto *node = ncnode; auto enabledSave = verifier->enabled_; - LOG_ASTV(DEBUG, "Verify: " << node->DumpJSON()); - - std::apply( - [this, node](auto &...inv) { - InvArray decisions {}; - InvArray actions {}; - ((std::tie(decisions[inv.ID], actions[inv.ID]) = - verifier->NeedCheckInvariant(inv) - ? inv.VerifyNode(node) - : CheckResult {CheckDecision::CORRECT, CheckAction::SKIP_SUBTREE}), - ...); - // Temporaly disable invariant, the value should be restored after node and its childs are visited: - ((verifier->enabled_[inv.ID] &= (actions[inv.ID] == CheckAction::CONTINUE)), ...); - - for (size_t i = 0; i < VerifierInvariants::COUNT; i++) { - LOG_ASTV(DEBUG, (actions[i] == CheckAction::CONTINUE ? "Enabled " : "Disabled ") - << util::gen::ast_verifier::ToString(VerifierInvariants {i})); - } - - (*astCorrect) &= ((decisions[inv.ID] == CheckDecision::CORRECT) && ...); - }, - verifier->invariants_); + LOG_ASTV(DEBUG, "Verify: " << ir::ToString(node->Type())); + + verifier->Apply([this, node](auto &...inv) { + InvArray decisions {}; + InvArray actions {}; + ((std::tie(decisions[inv.ID], actions[inv.ID]) = + verifier->NeedCheckInvariant(inv) ? VerifyNode(&inv, node) + : CheckResult {CheckDecision::CORRECT, CheckAction::SKIP_SUBTREE}), + ...); + // Temporaly disable invariant, the value should be restored after node and its childs are visited: + ((verifier->enabled_[inv.ID] &= (actions[inv.ID] == CheckAction::CONTINUE)), ...); + + for (size_t i = 0; i < VerifierInvariants::COUNT; i++) { + LOG_ASTV(DEBUG, (actions[i] == CheckAction::CONTINUE ? "Enabled " : "Disabled ") + << util::gen::ast_verifier::ToString(VerifierInvariants {i})); + } + + (*astCorrect) &= ((decisions[inv.ID] == CheckDecision::CORRECT) && ...); + }); node->Iterate(*this); verifier->enabled_ = enabledSave; @@ -75,14 +82,19 @@ static auto ExtractAst(const parser::Program &program, bool checkFullProgram) void ASTVerifier::Verify(std::string_view phaseName) { + if (context_.diagnosticEngine->IsAnyError()) { + // NOTE(dkofanov): As for now, the policy is that ASTVerifier doesn't interrupt pipeline if there were errors + // reported. Should be revisited. + Suppress(); + } if (suppressed_) { return; } - auto astToCheck = ExtractAst(program_, options_.IsAstVerifierFullProgram()); + auto astToCheck = ExtractAst(program_, Options().IsAstVerifierFullProgram()); for (const auto &p : astToCheck) { const auto sourceName = p.first; const auto *ast = p.second; - std::apply([](auto &&...inv) { ((inv.Init()), ...); }, invariants_); + Apply([](auto &&...inv) { ((inv.Init()), ...); }); LOG_ASTV(INFO, "Begin traversal (" << sourceName << ')'); @@ -93,18 +105,17 @@ void ASTVerifier::Verify(std::string_view phaseName) auto reporter = [this, sourceName](auto &&inv) { if (inv.HasMessages()) { report_.back().second[sourceName][TreatAsError(inv.ID) ? "errors" : "warnings"][inv.ID] = - std::forward(inv).MoveMessages(); + std::forward(inv).MoveMessages(); (TreatAsError(inv.ID) ? hasErrors_ : hasWarnings_) = true; } }; - ES2PANDA_ASSERT(astCorrect == - std::apply([](const auto &...inv) { return ((!inv.HasMessages()) && ...); }, invariants_)); + ES2PANDA_ASSERT(astCorrect == Apply([](const auto &...inv) { return ((!inv.HasMessages()) && ...); })); if (!astCorrect) { if (report_.empty() || report_.back().first != phaseName) { report_.emplace_back(); report_.back().first = phaseName; } - std::apply([&reporter](auto &...inv) { (reporter(std::move(inv)), ...); }, invariants_); + Apply([&reporter](auto &...inv) { (reporter(std::move(inv)), ...); }); } } } @@ -191,22 +202,22 @@ void DumpLog(const ASTVerifier::GroupedMessages &report) void ASTVerifier::DumpMessages() const { std::string errMsg = "ASTVerifier found broken invariants."; - if (options_.IsAstVerifierJson()) { - DumpJson(report_, options_.GetAstVerifierJsonPath()); - errMsg += " Dumped to '" + std::string(options_.GetAstVerifierJsonPath()) + "'."; + if (Options().IsAstVerifierJson()) { + DumpJson(report_, Options().GetAstVerifierJsonPath()); + errMsg += " Dumped to '" + std::string(Options().GetAstVerifierJsonPath()) + "'."; } else { DumpLog(report_); errMsg += " You may want to pass '--ast-verifier:json' option for more verbose output."; } if (hasErrors_) { - LOG(ERROR, ES2PANDA) << errMsg; + LOG(FATAL, ES2PANDA) << errMsg; } else if (hasWarnings_) { LOG(WARNING, ES2PANDA) << errMsg; } } -void CheckContext::AddCheckMessage(const std::string &cause, const ir::AstNode &node) +void InvariantMessages::AddCheckMessage(const std::string &cause, const ir::AstNode &node) { messages_.emplace_back(cause.data(), &node); } diff --git a/ets2panda/ast_verifier/ASTVerifier.h b/ets2panda/ast_verifier/ASTVerifier.h index 910b753728..9aaa1aecc3 100644 --- a/ets2panda/ast_verifier/ASTVerifier.h +++ b/ets2panda/ast_verifier/ASTVerifier.h @@ -22,27 +22,27 @@ #include #include -#include "ast_verifier/checkContext.h" -#include "ast_verifier/sequenceExpressionHasLastType.h" -#include "ast_verifier/checkAbstractMethod.h" -#include "ast_verifier/everyChildHasValidParent.h" -#include "ast_verifier/everyChildInParentRange.h" -#include "ast_verifier/getterSetterValidation.h" -#include "ast_verifier/identifierHasVariable.h" -#include "ast_verifier/nodeHasParent.h" -#include "ast_verifier/nodeHasSourceRange.h" -#include "ast_verifier/nodeHasType.h" -#include "ast_verifier/referenceTypeAnnotationIsNull.h" -#include "ast_verifier/variableHasScope.h" -#include "ast_verifier/variableHasEnclosingScope.h" -#include "ast_verifier/forLoopCorrectlyInitialized.h" -#include "ast_verifier/modifierAccessValid.h" -#include "ast_verifier/importExportAccessValid.h" -#include "ast_verifier/arithmeticOperationValid.h" -#include "ast_verifier/variableNameIdentifierNameSame.h" -#include "ast_verifier/checkScopeDeclaration.h" -#include "ast_verifier/checkStructDeclaration.h" -#include "ast_verifier/checkConstProperties.h" +#include "ast_verifier/invariantBase.h" +#include "ast_verifier/invariants/sequenceExpressionHasLastType.h" +#include "ast_verifier/invariants/checkAbstractMethod.h" +#include "ast_verifier/invariants/everyChildHasValidParent.h" +#include "ast_verifier/invariants/everyChildInParentRange.h" +#include "ast_verifier/invariants/getterSetterValidation.h" +#include "ast_verifier/invariants/identifierHasVariable.h" +#include "ast_verifier/invariants/nodeHasParent.h" +#include "ast_verifier/invariants/nodeHasSourceRange.h" +#include "ast_verifier/invariants/nodeHasType.h" +#include "ast_verifier/invariants/referenceTypeAnnotationIsNull.h" +#include "ast_verifier/invariants/variableHasScope.h" +#include "ast_verifier/invariants/variableHasEnclosingScope.h" +#include "ast_verifier/invariants/forLoopCorrectlyInitialized.h" +#include "ast_verifier/invariants/modifierAccessValid.h" +#include "ast_verifier/invariants/importExportAccessValid.h" +#include "ast_verifier/invariants/arithmeticOperationValid.h" +#include "ast_verifier/invariants/variableNameIdentifierNameSame.h" +#include "ast_verifier/invariants/checkScopeDeclaration.h" +#include "ast_verifier/invariants/checkStructDeclaration.h" +#include "ast_verifier/invariants/checkConstProperties.h" #include "ir/astNode.h" #include "ir/statements/blockStatement.h" @@ -65,39 +65,6 @@ namespace ark::es2panda::compiler::ast_verifier { -template -class InvariantsRegistryImpl { -public: - using Invariants = std::tuple; - template - using InvariantClass = std::tuple_element_t; - template - using InvArray = std::array; - -private: - template - static constexpr bool CheckRegistry(std::integer_sequence /*unused*/) - { - return ((CheckRegistry()) && ...); - } - - template - static constexpr bool CheckRegistry() - { - static_assert(ORDER_IN_PARAMETER_LIST == DEFINED_ENUM, - "Invariant's `ID` must be equal to" - "index of the invariant in `InvariantsRegistryImpl` parameter-list"); - return true; - } - -protected: - Invariants invariants_ {}; - - static_assert(sizeof...(Invs) == VerifierInvariants::COUNT, - "Parameter-list is inconsistent with invaraints' declararation in 'options.yaml'"); - static_assert(CheckRegistry(std::make_index_sequence {})); -}; - // NOTE(dkofanov) Fix and enable ImportExportAccessValid: using InvariantsRegistry = InvariantsRegistryImploptions} + : program_ {program}, context_ {context} { for (size_t i = VerifierInvariants::BASE_FIRST; i <= VerifierInvariants::BASE_LAST; i++) { allowed_[i] = true; @@ -124,7 +91,7 @@ public: for (size_t i = 0; i < VerifierInvariants::COUNT; i++) { enabled_[i] = TreatAsWarning(VerifierInvariants {i}) || TreatAsError(VerifierInvariants {i}); } - if (options_.IsAstVerifierBeforePhases()) { + if (Options().IsAstVerifierBeforePhases()) { Verify("before"); } } @@ -132,7 +99,7 @@ public: ~ASTVerifier() { if (!suppressed_) { - if (options_.IsAstVerifierAfterPhases()) { + if (Options().IsAstVerifierAfterPhases()) { Verify("after"); } if (HasErrors() || HasWarnings()) { @@ -163,10 +130,10 @@ public: allowed_[i] = true; } // NOTE(dkofanov): This should be called after "NumberLowering" phase: - std::get(invariants_).SetNumberLoweringOccured(); + Get()->SetNumberLoweringOccured(); } if (occurredPhaseName == "UnionLowering") { - std::get(invariants_).SetUnionLoweringOccurred(); + Get()->SetUnionLoweringOccurred(); } } @@ -179,11 +146,11 @@ public: bool TreatAsWarning(VerifierInvariants id) const { - return options_.GetAstVerifierWarnings()[id]; + return Options().GetAstVerifierWarnings()[id]; } bool TreatAsError(VerifierInvariants id) const { - return options_.GetAstVerifierErrors()[id]; + return Options().GetAstVerifierErrors()[id]; } bool HasErrors() const { @@ -195,12 +162,17 @@ public: } private: - template , T>, void *> = nullptr> + template , void *> = nullptr> bool NeedCheckInvariant(const T & /*unused*/) { return enabled_[T::ID] && allowed_[T::ID]; } + const util::Options &Options() const + { + return *context_.config->options; + } + public: using SourcePath = std::string_view; using PhaseName = std::string_view; @@ -211,7 +183,7 @@ public: private: const parser::Program &program_; - const util::Options &options_; + const public_lib::Context &context_; InvArray enabled_ {}; InvArray allowed_ {}; @@ -223,30 +195,6 @@ private: struct SinglePassVerifier; }; -template -CheckResult InvariantBase::VerifyNode(const ir::AstNode *ast) -{ - auto [res, action] = (*static_cast *>(this))(ast); - if (action == CheckAction::SKIP_SUBTREE) { - LOG_ASTV(DEBUG, util::gen::ast_verifier::ToString(ID) << ": SKIP_SUBTREE"); - } - return {res, action}; -} - -template -void RecursiveInvariant::VerifyAst(const ir::AstNode *ast) -{ - std::function aux {}; - aux = [this, &aux](const ir::AstNode *child) -> void { - const auto [_, action] = this->VerifyNode(child); - if (action == CheckAction::SKIP_SUBTREE) { - return; - } - child->Iterate(aux); - }; - aux(ast); -} - } // namespace ark::es2panda::compiler::ast_verifier #endif // ES2PANDA_COMPILER_CORE_ASTVERIFIER_H diff --git a/ets2panda/ast_verifier/checkContext.h b/ets2panda/ast_verifier/invariantBase.h similarity index 41% rename from ets2panda/ast_verifier/checkContext.h rename to ets2panda/ast_verifier/invariantBase.h index ef5d5b2de5..7ce416e98a 100644 --- a/ets2panda/ast_verifier/checkContext.h +++ b/ets2panda/ast_verifier/invariantBase.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_CHECKCONTEXT_H -#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_CHECKCONTEXT_H +#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTBASE_H +#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTBASE_H #include "generated/options.h" #include "ir/astNode.h" @@ -29,6 +29,58 @@ using CheckResult = std::tuple; using VerifierInvariants = util::gen::ast_verifier::Enum; using Enum = VerifierInvariants; +template +class InvariantsRegistryImpl { +public: + InvariantsRegistryImpl() : invariants_ {Invs(this)...} {} + + using Invariants = std::tuple; + template + using InvariantClass = std::tuple_element_t; + template + using InvArray = std::array; + + template + constexpr auto *Get() + { + return Get>(); + } + + template + constexpr auto *Get() + { + return &std::get(invariants_); + } + + template + auto Apply(Func &&f) + { + return std::apply(std::forward(f), invariants_); + } + +private: + Invariants invariants_; + + template + static constexpr bool CheckRegistry(std::integer_sequence /*unused*/) + { + return ((CheckRegistry()) && ...); + } + + template + static constexpr bool CheckRegistry() + { + static_assert(ORDER_IN_PARAMETER_LIST == DEFINED_ENUM, + "Invariant's `ID` must be equal to" + "index of the invariant in `InvariantsRegistryImpl` parameter-list"); + return true; + } + + static_assert(sizeof...(Invs) == VerifierInvariants::COUNT, + "Parameter-list is inconsistent with invaraints' declararation in 'options.yaml'"); + static_assert(CheckRegistry(std::make_index_sequence {})); +}; + class CheckMessage { public: explicit CheckMessage(util::StringView cause, const ir::AstNode *node) : cause_ {cause}, node_ {node} {} @@ -44,8 +96,14 @@ public: std::string ToString() const { - return cause_ + "(AstNodeType::" + std::string(ir::ToString(node_->Type())) + ", line " + - std::to_string(node_->Start().line + 1) + ')'; + auto nodeLocation = std::string(ir::ToString(node_->Type())); + auto parent = node_->Parent(); + while (parent != nullptr) { + nodeLocation = std::string(ir::ToString(parent->Type())).append("->").append(nodeLocation); + parent = parent->Parent(); + } + + return cause_ + "(" + nodeLocation + ", line " + std::to_string(node_->Start().line + 1) + ')'; } const auto &Cause() const @@ -60,7 +118,7 @@ private: using Messages = std::vector; -class CheckContext { +class InvariantMessages { public: void Init() { @@ -88,20 +146,42 @@ private: Messages messages_; }; -template -class InvariantBase : public CheckContext { +template +class RequiredInvariants { public: - constexpr static VerifierInvariants ID = ENUM; - constexpr static std::string_view NAME = util::gen::ast_verifier::ToString(ID); - CheckResult VerifyNode(const ir::AstNode *ast); + template + explicit constexpr RequiredInvariants([[maybe_unused]] InvariantsReg *reg) + : required_ {*reg->template Get()...} + { + } + + const auto &GetRequired() const + { + return required_; + } + +protected: + template + const auto &Get() + { + return std::get(required_); + } + +private: + static_assert(((RequiredInvs::ID < ENUM) && ...), "'Required' invariants should precede the related invariant"); + std::tuple required_; }; -template -class RecursiveInvariant : public InvariantBase { +template +// NOLINTNEXTLINE(fuchsia-multiple-inheritance) +class InvariantBase : public RequiredInvariants, public InvariantMessages { public: - void VerifyAst(const ir::AstNode *ast); + using RequiredInvariants::RequiredInvariants; + using Base = InvariantBase; + constexpr static VerifierInvariants ID = ENUM; + constexpr static std::string_view NAME = util::gen::ast_verifier::ToString(ID); }; } // namespace ark::es2panda::compiler::ast_verifier -#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_CHECKCONTEXT_H +#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTBASE_H diff --git a/ets2panda/ast_verifier/arithmeticOperationValid.cpp b/ets2panda/ast_verifier/invariants/arithmeticOperationValid.cpp similarity index 97% rename from ets2panda/ast_verifier/arithmeticOperationValid.cpp rename to ets2panda/ast_verifier/invariants/arithmeticOperationValid.cpp index ed0794f19e..bb77859aed 100644 --- a/ets2panda/ast_verifier/arithmeticOperationValid.cpp +++ b/ets2panda/ast_verifier/invariants/arithmeticOperationValid.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -19,7 +19,7 @@ #include "ir/ts/tsInterfaceDeclaration.h" #include "ir/ts/tsEnumDeclaration.h" #include "ir/ts/tsInterfaceBody.h" -#include "helpers.h" +#include "../helpers.h" namespace ark::es2panda::compiler::ast_verifier { diff --git a/ets2panda/ast_verifier/arithmeticOperationValid.h b/ets2panda/ast_verifier/invariants/arithmeticOperationValid.h similarity index 62% rename from ets2panda/ast_verifier/arithmeticOperationValid.h rename to ets2panda/ast_verifier/invariants/arithmeticOperationValid.h index c9177b562c..1afed1ea7f 100644 --- a/ets2panda/ast_verifier/arithmeticOperationValid.h +++ b/ets2panda/ast_verifier/invariants/arithmeticOperationValid.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,20 +13,20 @@ * limitations under the License. */ -#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_ARITHMETICOPERATIONVALID_H -#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_ARITHMETICOPERATIONVALID_H +#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_ARITHMETICOPERATIONVALID_H +#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_ARITHMETICOPERATIONVALID_H -#include "checkContext.h" +#include "../invariantBase.h" namespace ark::es2panda::compiler::ast_verifier { -class ArithmeticOperationValid : public RecursiveInvariant { - template - friend class InvariantBase; +class ArithmeticOperationValid : public InvariantBase { +public: + using Base::Base; [[nodiscard]] CheckResult operator()(const ir::AstNode *ast); CheckResult CheckCompound(const ir::AstNode *ast); }; } // namespace ark::es2panda::compiler::ast_verifier -#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_ARITHMETICOPERATIONVALID_H +#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_ARITHMETICOPERATIONVALID_H diff --git a/ets2panda/ast_verifier/checkAbstractMethod.cpp b/ets2panda/ast_verifier/invariants/checkAbstractMethod.cpp similarity index 96% rename from ets2panda/ast_verifier/checkAbstractMethod.cpp rename to ets2panda/ast_verifier/invariants/checkAbstractMethod.cpp index b74f0fd82e..efd25e797c 100644 --- a/ets2panda/ast_verifier/checkAbstractMethod.cpp +++ b/ets2panda/ast_verifier/invariants/checkAbstractMethod.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/ets2panda/ast_verifier/checkAbstractMethod.h b/ets2panda/ast_verifier/invariants/checkAbstractMethod.h similarity index 62% rename from ets2panda/ast_verifier/checkAbstractMethod.h rename to ets2panda/ast_verifier/invariants/checkAbstractMethod.h index 0abd1ab3d9..d2534f5483 100644 --- a/ets2panda/ast_verifier/checkAbstractMethod.h +++ b/ets2panda/ast_verifier/invariants/checkAbstractMethod.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,19 +13,19 @@ * limitations under the License. */ -#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_CHECKABSTRACTMETHOD_H -#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_CHECKABSTRACTMETHOD_H +#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_CHECKABSTRACTMETHOD_H +#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_CHECKABSTRACTMETHOD_H -#include "checkContext.h" +#include "../invariantBase.h" namespace ark::es2panda::compiler::ast_verifier { -class CheckAbstractMethod : public RecursiveInvariant { - template - friend class InvariantBase; +class CheckAbstractMethod : public InvariantBase { +public: + using Base::Base; [[nodiscard]] CheckResult operator()(const ir::AstNode *ast); }; } // namespace ark::es2panda::compiler::ast_verifier -#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_CHECKABSTRACTMETHOD_H +#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_CHECKABSTRACTMETHOD_H diff --git a/ets2panda/ast_verifier/checkConstProperties.cpp b/ets2panda/ast_verifier/invariants/checkConstProperties.cpp similarity index 100% rename from ets2panda/ast_verifier/checkConstProperties.cpp rename to ets2panda/ast_verifier/invariants/checkConstProperties.cpp diff --git a/ets2panda/ast_verifier/checkConstProperties.h b/ets2panda/ast_verifier/invariants/checkConstProperties.h similarity index 62% rename from ets2panda/ast_verifier/checkConstProperties.h rename to ets2panda/ast_verifier/invariants/checkConstProperties.h index e2302d0073..379e446e7a 100644 --- a/ets2panda/ast_verifier/checkConstProperties.h +++ b/ets2panda/ast_verifier/invariants/checkConstProperties.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,19 +13,19 @@ * limitations under the License. */ -#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_CHECKCONSTPROPERTIES_H -#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_CHECKCONSTPROPERTIES_H +#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_CHECKCONSTPROPERTIES_H +#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_CHECKCONSTPROPERTIES_H -#include "checkContext.h" +#include "../invariantBase.h" namespace ark::es2panda::compiler::ast_verifier { -class CheckConstProperties : public RecursiveInvariant { - template - friend class InvariantBase; +class CheckConstProperties : public InvariantBase { +public: + using Base::Base; [[nodiscard]] CheckResult operator()(const ir::AstNode *ast); }; } // namespace ark::es2panda::compiler::ast_verifier -#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_CHECKCONSTPROPERTIES_H +#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_CHECKCONSTPROPERTIES_H diff --git a/ets2panda/ast_verifier/checkScopeDeclaration.cpp b/ets2panda/ast_verifier/invariants/checkScopeDeclaration.cpp similarity index 98% rename from ets2panda/ast_verifier/checkScopeDeclaration.cpp rename to ets2panda/ast_verifier/invariants/checkScopeDeclaration.cpp index aac5ec0141..b76e622e29 100644 --- a/ets2panda/ast_verifier/checkScopeDeclaration.cpp +++ b/ets2panda/ast_verifier/invariants/checkScopeDeclaration.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/ets2panda/ast_verifier/checkScopeDeclaration.h b/ets2panda/ast_verifier/invariants/checkScopeDeclaration.h similarity index 63% rename from ets2panda/ast_verifier/checkScopeDeclaration.h rename to ets2panda/ast_verifier/invariants/checkScopeDeclaration.h index 7b4308d46b..f7766ab0b8 100644 --- a/ets2panda/ast_verifier/checkScopeDeclaration.h +++ b/ets2panda/ast_verifier/invariants/checkScopeDeclaration.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,20 +13,22 @@ * limitations under the License. */ -#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_CHECKSCOPEDECLARATION_H -#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_CHECKSCOPEDECLARATION_H +#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_CHECKSCOPEDECLARATION_H +#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_CHECKSCOPEDECLARATION_H -#include "checkContext.h" +#include "../invariantBase.h" namespace ark::es2panda::compiler::ast_verifier { -class CheckScopeDeclaration : public RecursiveInvariant { - template - friend class InvariantBase; +class CheckScopeDeclaration : public InvariantBase { +public: + using Base::Base; [[nodiscard]] CheckResult operator()(const ir::AstNode *ast); + +private: CheckResult CheckScope(varbinder::Scope const *const scope); }; } // namespace ark::es2panda::compiler::ast_verifier -#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_CHECKSCOPEDECLARATION_H +#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_CHECKSCOPEDECLARATION_H diff --git a/ets2panda/ast_verifier/checkStructDeclaration.cpp b/ets2panda/ast_verifier/invariants/checkStructDeclaration.cpp similarity index 100% rename from ets2panda/ast_verifier/checkStructDeclaration.cpp rename to ets2panda/ast_verifier/invariants/checkStructDeclaration.cpp diff --git a/ets2panda/ast_verifier/checkStructDeclaration.h b/ets2panda/ast_verifier/invariants/checkStructDeclaration.h similarity index 66% rename from ets2panda/ast_verifier/checkStructDeclaration.h rename to ets2panda/ast_verifier/invariants/checkStructDeclaration.h index cfb7f6be08..931279a83c 100644 --- a/ets2panda/ast_verifier/checkStructDeclaration.h +++ b/ets2panda/ast_verifier/invariants/checkStructDeclaration.h @@ -13,19 +13,19 @@ * limitations under the License. */ -#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_CHECKSTRUCTDECLARATION_H -#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_CHECKSTRUCTDECLARATION_H +#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_CHECKSTRUCTDECLARATION_H +#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_CHECKSTRUCTDECLARATION_H -#include "checkContext.h" +#include "../invariantBase.h" namespace ark::es2panda::compiler::ast_verifier { -class CheckStructDeclaration : public RecursiveInvariant { - template - friend class InvariantBase; +class CheckStructDeclaration : public InvariantBase { +public: + using Base::Base; [[nodiscard]] CheckResult operator()(const ir::AstNode *ast); }; } // namespace ark::es2panda::compiler::ast_verifier -#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_NODEHASPARENT_H +#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_NODEHASPARENT_H diff --git a/ets2panda/ast_verifier/everyChildHasValidParent.cpp b/ets2panda/ast_verifier/invariants/everyChildHasValidParent.cpp similarity index 100% rename from ets2panda/ast_verifier/everyChildHasValidParent.cpp rename to ets2panda/ast_verifier/invariants/everyChildHasValidParent.cpp diff --git a/ets2panda/ast_verifier/everyChildInParentRange.h b/ets2panda/ast_verifier/invariants/everyChildHasValidParent.h similarity index 61% rename from ets2panda/ast_verifier/everyChildInParentRange.h rename to ets2panda/ast_verifier/invariants/everyChildHasValidParent.h index b9b976f21a..d18220f781 100644 --- a/ets2panda/ast_verifier/everyChildInParentRange.h +++ b/ets2panda/ast_verifier/invariants/everyChildHasValidParent.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,19 +13,19 @@ * limitations under the License. */ -#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_EVERYCHILDINPARENTRANGE_H -#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_EVERYCHILDINPARENTRANGE_H +#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_EVERYCHILDHASVALIDPARENT_H +#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_EVERYCHILDHASVALIDPARENT_H -#include "checkContext.h" +#include "../invariantBase.h" namespace ark::es2panda::compiler::ast_verifier { -class EveryChildInParentRange : public RecursiveInvariant { - template - friend class InvariantBase; +class EveryChildHasValidParent : public InvariantBase { +public: + using Base::Base; [[nodiscard]] CheckResult operator()(const ir::AstNode *ast); }; } // namespace ark::es2panda::compiler::ast_verifier -#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_EVERYCHILDINPARENTRANGE_H +#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_EVERYCHILDHASVALIDPARENT_H diff --git a/ets2panda/ast_verifier/everyChildInParentRange.cpp b/ets2panda/ast_verifier/invariants/everyChildInParentRange.cpp similarity index 97% rename from ets2panda/ast_verifier/everyChildInParentRange.cpp rename to ets2panda/ast_verifier/invariants/everyChildInParentRange.cpp index 91a6bb9983..397aeb27ea 100644 --- a/ets2panda/ast_verifier/everyChildInParentRange.cpp +++ b/ets2panda/ast_verifier/invariants/everyChildInParentRange.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/ets2panda/ast_verifier/invariants/everyChildInParentRange.h b/ets2panda/ast_verifier/invariants/everyChildInParentRange.h new file mode 100644 index 0000000000..c3406de3e0 --- /dev/null +++ b/ets2panda/ast_verifier/invariants/everyChildInParentRange.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_EVERYCHILDINPARENTRANGE_H +#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_EVERYCHILDINPARENTRANGE_H + +#include "../invariantBase.h" + +namespace ark::es2panda::compiler::ast_verifier { + +class EveryChildInParentRange : public InvariantBase { +public: + using Base::Base; + [[nodiscard]] CheckResult operator()(const ir::AstNode *ast); +}; + +} // namespace ark::es2panda::compiler::ast_verifier + +#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_EVERYCHILDINPARENTRANGE_H diff --git a/ets2panda/ast_verifier/forLoopCorrectlyInitialized.cpp b/ets2panda/ast_verifier/invariants/forLoopCorrectlyInitialized.cpp similarity index 98% rename from ets2panda/ast_verifier/forLoopCorrectlyInitialized.cpp rename to ets2panda/ast_verifier/invariants/forLoopCorrectlyInitialized.cpp index 6c92add48d..9ccb62e969 100644 --- a/ets2panda/ast_verifier/forLoopCorrectlyInitialized.cpp +++ b/ets2panda/ast_verifier/invariants/forLoopCorrectlyInitialized.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/ets2panda/ast_verifier/forLoopCorrectlyInitialized.h b/ets2panda/ast_verifier/invariants/forLoopCorrectlyInitialized.h similarity index 66% rename from ets2panda/ast_verifier/forLoopCorrectlyInitialized.h rename to ets2panda/ast_verifier/invariants/forLoopCorrectlyInitialized.h index 1afe3a0ee0..15c3e45451 100644 --- a/ets2panda/ast_verifier/forLoopCorrectlyInitialized.h +++ b/ets2panda/ast_verifier/invariants/forLoopCorrectlyInitialized.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,17 +13,19 @@ * limitations under the License. */ -#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_FORLOOPCORRECTLYINITIALIZED_H -#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_FORLOOPCORRECTLYINITIALIZED_H +#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_FORLOOPCORRECTLYINITIALIZED_H +#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_FORLOOPCORRECTLYINITIALIZED_H -#include "checkContext.h" +#include "../invariantBase.h" namespace ark::es2panda::compiler::ast_verifier { -class ForLoopCorrectlyInitialized : public RecursiveInvariant { - template - friend class InvariantBase; +class ForLoopCorrectlyInitialized : public InvariantBase { +public: + using Base::Base; [[nodiscard]] CheckResult operator()(const ir::AstNode *ast); + +private: [[nodiscard]] CheckResult HandleForInStatement(const ir::AstNode *ast); [[nodiscard]] CheckResult HandleForOfStatement(const ir::AstNode *ast); [[nodiscard]] CheckResult HandleForUpdateStatement(const ir::AstNode *ast); @@ -31,4 +33,4 @@ class ForLoopCorrectlyInitialized : public RecursiveInvariant { - template - friend class InvariantBase; +class GetterSetterValidation : public InvariantBase { +public: + using Base::Base; [[nodiscard]] CheckResult operator()(const ir::AstNode *ast); + +private: bool ValidateGetter(ir::MethodDefinition const *const method); bool ValidateSetter(ir::MethodDefinition const *const method); }; } // namespace ark::es2panda::compiler::ast_verifier -#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_GETTERSETTERVALIDATION_H +#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_GETTERSETTERVALIDATION_H diff --git a/ets2panda/ast_verifier/identifierHasVariable.cpp b/ets2panda/ast_verifier/invariants/identifierHasVariable.cpp similarity index 100% rename from ets2panda/ast_verifier/identifierHasVariable.cpp rename to ets2panda/ast_verifier/invariants/identifierHasVariable.cpp diff --git a/ets2panda/ast_verifier/identifierHasVariable.h b/ets2panda/ast_verifier/invariants/identifierHasVariable.h similarity index 72% rename from ets2panda/ast_verifier/identifierHasVariable.h rename to ets2panda/ast_verifier/invariants/identifierHasVariable.h index 80939333d6..8fc17ff9bb 100644 --- a/ets2panda/ast_verifier/identifierHasVariable.h +++ b/ets2panda/ast_verifier/invariants/identifierHasVariable.h @@ -13,21 +13,22 @@ * limitations under the License. */ -#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_IDENTIFIERHASVARIABLE_H -#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_IDENTIFIERHASVARIABLE_H +#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_IDENTIFIERHASVARIABLE_H +#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_IDENTIFIERHASVARIABLE_H -#include "checkContext.h" +#include "../invariantBase.h" #include "ir/expressions/identifier.h" namespace ark::es2panda::compiler::ast_verifier { -class IdentifierHasVariable : public RecursiveInvariant { - template - friend class InvariantBase; +class IdentifierHasVariable : public InvariantBase { +public: + using Base::Base; class ExceptionsMatcher; [[nodiscard]] CheckResult operator()(const ir::AstNode *ast); +private: auto UnionLoweringOccurred() const { return unionLoweringOccurred_; @@ -45,4 +46,4 @@ private: } // namespace ark::es2panda::compiler::ast_verifier -#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_IDENTIFIERHASVARIABLE_H +#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_IDENTIFIERHASVARIABLE_H diff --git a/ets2panda/ast_verifier/importExportAccessValid.cpp b/ets2panda/ast_verifier/invariants/importExportAccessValid.cpp similarity index 99% rename from ets2panda/ast_verifier/importExportAccessValid.cpp rename to ets2panda/ast_verifier/invariants/importExportAccessValid.cpp index 8e7ac7e6b7..10a85bbdc0 100644 --- a/ets2panda/ast_verifier/importExportAccessValid.cpp +++ b/ets2panda/ast_verifier/invariants/importExportAccessValid.cpp @@ -14,7 +14,7 @@ */ #include "importExportAccessValid.h" -#include "helpers.h" +#include "../helpers.h" #include "ir/expressions/callExpression.h" #include "checker/types/ets/etsObjectType.h" #include "ir/module/importSpecifier.h" diff --git a/ets2panda/ast_verifier/importExportAccessValid.h b/ets2panda/ast_verifier/invariants/importExportAccessValid.h similarity index 74% rename from ets2panda/ast_verifier/importExportAccessValid.h rename to ets2panda/ast_verifier/invariants/importExportAccessValid.h index 7c539217fc..7977ee3a56 100644 --- a/ets2panda/ast_verifier/importExportAccessValid.h +++ b/ets2panda/ast_verifier/invariants/importExportAccessValid.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,17 +13,16 @@ * limitations under the License. */ -#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_IMPORTEXPORTACCESSVALID_H -#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_IMPORTEXPORTACCESSVALID_H +#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_IMPORTEXPORTACCESSVALID_H +#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_IMPORTEXPORTACCESSVALID_H -#include "checkContext.h" +#include "../invariantBase.h" namespace ark::es2panda::compiler::ast_verifier { -// NOTE(dkofanov) Fix and enable via `RecursiveInvariant` -class ImportExportAccessValid : public RecursiveInvariant { - template - friend class InvariantBase; +// NOTE(dkofanov) Fix and enable via `InvariantBase` +class ImportExportAccessValid : public InvariantBase { +public: [[nodiscard]] CheckResult operator()(const ir::AstNode *ast); bool ValidateExport(const varbinder::Variable *var); bool InvariantImportExportMethod(const std::unordered_set &importedVariables, @@ -38,4 +37,4 @@ class ImportExportAccessValid : public RecursiveInvariant { - template - friend class InvariantBase; +class ModifierAccessValid : public InvariantBase { +public: + using Base::Base; [[nodiscard]] CheckResult operator()(const ir::AstNode *ast); + +private: CheckResult HandleMethodExpression(const ir::AstNode *ast); CheckResult HandleCallExpression(const ir::AstNode *ast); }; } // namespace ark::es2panda::compiler::ast_verifier -#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_MODIFIERACCESSVALID_H +#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_MODIFIERACCESSVALID_H diff --git a/ets2panda/ast_verifier/nodeHasParent.cpp b/ets2panda/ast_verifier/invariants/nodeHasParent.cpp similarity index 100% rename from ets2panda/ast_verifier/nodeHasParent.cpp rename to ets2panda/ast_verifier/invariants/nodeHasParent.cpp diff --git a/ets2panda/ast_verifier/nodeHasParent.h b/ets2panda/ast_verifier/invariants/nodeHasParent.h similarity index 64% rename from ets2panda/ast_verifier/nodeHasParent.h rename to ets2panda/ast_verifier/invariants/nodeHasParent.h index 90d9800b36..c3f583c8d9 100644 --- a/ets2panda/ast_verifier/nodeHasParent.h +++ b/ets2panda/ast_verifier/invariants/nodeHasParent.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,19 +13,19 @@ * limitations under the License. */ -#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_NODEHASPARENT_H -#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_NODEHASPARENT_H +#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_NODEHASPARENT_H +#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_NODEHASPARENT_H -#include "checkContext.h" +#include "../invariantBase.h" namespace ark::es2panda::compiler::ast_verifier { -class NodeHasParent : public RecursiveInvariant { - template - friend class InvariantBase; +class NodeHasParent : public InvariantBase { +public: + using Base::Base; [[nodiscard]] CheckResult operator()(const ir::AstNode *ast); }; } // namespace ark::es2panda::compiler::ast_verifier -#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_NODEHASPARENT_H +#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_NODEHASPARENT_H diff --git a/ets2panda/ast_verifier/nodeHasSourceRange.cpp b/ets2panda/ast_verifier/invariants/nodeHasSourceRange.cpp similarity index 95% rename from ets2panda/ast_verifier/nodeHasSourceRange.cpp rename to ets2panda/ast_verifier/invariants/nodeHasSourceRange.cpp index efb690e4f9..5af7313ec6 100644 --- a/ets2panda/ast_verifier/nodeHasSourceRange.cpp +++ b/ets2panda/ast_verifier/invariants/nodeHasSourceRange.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/ets2panda/ast_verifier/nodeHasSourceRange.h b/ets2panda/ast_verifier/invariants/nodeHasSourceRange.h similarity index 62% rename from ets2panda/ast_verifier/nodeHasSourceRange.h rename to ets2panda/ast_verifier/invariants/nodeHasSourceRange.h index 95f713e47e..fed802ecb7 100644 --- a/ets2panda/ast_verifier/nodeHasSourceRange.h +++ b/ets2panda/ast_verifier/invariants/nodeHasSourceRange.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,19 +13,19 @@ * limitations under the License. */ -#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_NODEHASSOURCERANGE_H -#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_NODEHASSOURCERANGE_H +#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_NODEHASSOURCERANGE_H +#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_NODEHASSOURCERANGE_H -#include "checkContext.h" +#include "../invariantBase.h" namespace ark::es2panda::compiler::ast_verifier { -class NodeHasSourceRange : public RecursiveInvariant { - template - friend class InvariantBase; +class NodeHasSourceRange : public InvariantBase { +public: + using Base::Base; [[nodiscard]] CheckResult operator()(const ir::AstNode *ast); }; } // namespace ark::es2panda::compiler::ast_verifier -#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_NODEHASSOURCERANGE_H +#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_NODEHASSOURCERANGE_H diff --git a/ets2panda/ast_verifier/nodeHasType.cpp b/ets2panda/ast_verifier/invariants/nodeHasType.cpp similarity index 31% rename from ets2panda/ast_verifier/nodeHasType.cpp rename to ets2panda/ast_verifier/invariants/nodeHasType.cpp index 42ff41a036..4cfa95f5ca 100644 --- a/ets2panda/ast_verifier/nodeHasType.cpp +++ b/ets2panda/ast_verifier/invariants/nodeHasType.cpp @@ -13,10 +13,15 @@ * limitations under the License. */ -#include "helpers.h" +#include "../helpers.h" #include "nodeHasType.h" #include "ir/base/classDefinition.h" +#include "ir/base/methodDefinition.h" +#include "ir/base/scriptFunction.h" +#include "ir/base/spreadElement.h" +#include "ir/expressions/functionExpression.h" #include "ir/expressions/identifier.h" +#include "ir/ets/etsParameterExpression.h" #include "ir/statements/annotationDeclaration.h" #include "ir/ts/tsEnumDeclaration.h" #include "ir/ts/tsInterfaceBody.h" @@ -24,71 +29,75 @@ namespace ark::es2panda::compiler::ast_verifier { -CheckResult NodeHasType::operator()(const ir::AstNode *ast) -{ - // NOTE(orlovskymaxim) In TS some ETS constructs are expressions (i.e. class/interface definition) - // Because ETS uses some AST classes from TS this introduces semantical problem - // Solution for now - manually filter expressions that are statements in ETS - if (ast->IsETSPackageDeclaration()) { - return {CheckDecision::CORRECT, CheckAction::SKIP_SUBTREE}; +// NOTE(dkofanov): These exceptions are inadequate and are not actual exceptions. +class NodeHasType::ExceptionsMatcher { +public: + explicit ExceptionsMatcher(const ir::AstNode *ast) : nulltypeNode_(ast) {} + + auto ShouldSkipNode() const + { + return nulltypeNode_->IsIdentifier() || MatchFunctionExpression() || nulltypeNode_->IsTSClassImplements() || + nulltypeNode_->IsSpreadElement() || nulltypeNode_->IsTSThisType() || nulltypeNode_->IsETSNullType() || + nulltypeNode_->IsStringLiteral() || AnyChildStringLiteral(); } - if (IsImportLike(ast)) { - return {CheckDecision::CORRECT, CheckAction::SKIP_SUBTREE}; + + auto ShouldSkipSubtree() const + { + return nulltypeNode_->IsAnnotationUsage() || nulltypeNode_->IsVariableDeclarator() || MatchTypeParameter() || + nulltypeNode_->IsTSEnumDeclaration() || nulltypeNode_->IsTSInterfaceDeclaration() || + nulltypeNode_->IsTSQualifiedName() || nulltypeNode_->IsETSParameterExpression() || + nulltypeNode_->IsETSTypeReference() || MatchImportExport() || nulltypeNode_->IsTryStatement() || + nulltypeNode_->IsAssignmentExpression(); } - if (IsExportLike(ast)) { - return {CheckDecision::CORRECT, CheckAction::SKIP_SUBTREE}; + +private: + bool MatchFunctionExpression() const + { + if (!nulltypeNode_->IsFunctionExpression()) { + return false; + } + auto fe = nulltypeNode_->AsFunctionExpression(); + return (fe->Parent() != nullptr) && (fe->Parent()->IsMethodDefinition() || fe->Parent()->IsClassStaticBlock()); } - if (ast->IsTSTypeAliasDeclaration()) { - return {CheckDecision::CORRECT, CheckAction::SKIP_SUBTREE}; + bool MatchTypeParameter() const + { + return nulltypeNode_->IsTSTypeParameterInstantiation() || nulltypeNode_->IsTSTypeParameterDeclaration(); } - if (auto [decision, action] = CheckCompound(ast); action == CheckAction::SKIP_SUBTREE) { - return {decision, action}; + + bool MatchImportExport() const + { + return nulltypeNode_->IsETSReExportDeclaration() || nulltypeNode_->IsETSImportDeclaration(); } - if (ast->IsTyped() && ast->IsExpression()) { - if (ast->IsClassDefinition() && ast->AsClassDefinition()->Ident()->Name() == Signatures::ETS_GLOBAL) { - return {CheckDecision::CORRECT, CheckAction::SKIP_SUBTREE}; - } - if (ast->IsIdentifier() && ast->AsIdentifier()->Name() == "") { - return {CheckDecision::CORRECT, CheckAction::SKIP_SUBTREE}; - } - const auto *typed = static_cast(ast); - if (typed->TsType() == nullptr) { - AddCheckMessage("NULL_TS_TYPE", *ast); - return {CheckDecision::INCORRECT, CheckAction::CONTINUE}; - } + bool AnyChildStringLiteral() const + { + return nulltypeNode_->IsAnyChild([](auto *child) { return child->IsStringLiteral(); }); } - return {CheckDecision::CORRECT, CheckAction::CONTINUE}; -} -CheckResult NodeHasType::CheckCompound(const ir::AstNode *ast) +private: + const ir::AstNode *nulltypeNode_ {}; +}; + +CheckResult NodeHasType::operator()(const ir::AstNode *ast) { - if (ast->IsTSInterfaceDeclaration()) { - for (const auto &member : ast->AsTSInterfaceDeclaration()->Body()->Body()) { - [[maybe_unused]] auto _ = (*this)(member); - } - return {CheckDecision::CORRECT, CheckAction::SKIP_SUBTREE}; - } - if (ast->IsTSEnumDeclaration()) { - for (const auto &member : ast->AsTSEnumDeclaration()->Members()) { - [[maybe_unused]] auto _ = (*this)(member); - } + type_ = nullptr; + + if (ExceptionsMatcher {ast}.ShouldSkipSubtree()) { return {CheckDecision::CORRECT, CheckAction::SKIP_SUBTREE}; } - if (ast->IsClassDefinition()) { - for (const auto &member : ast->AsClassDefinition()->Body()) { - [[maybe_unused]] auto _ = (*this)(member); - } - return {CheckDecision::CORRECT, CheckAction::SKIP_SUBTREE}; + + if (!ast->IsTyped()) { + return {CheckDecision::CORRECT, CheckAction::CONTINUE}; } - if (ast->IsAnnotationDeclaration()) { - for (const auto &member : ast->AsAnnotationDeclaration()->Properties()) { - [[maybe_unused]] auto _ = (*this)(member); - } - return {CheckDecision::CORRECT, CheckAction::SKIP_SUBTREE}; + + type_ = ast->AsTyped()->TsType(); + if (type_ != nullptr || ExceptionsMatcher {ast}.ShouldSkipNode()) { + return {CheckDecision::CORRECT, CheckAction::CONTINUE}; } - return {CheckDecision::CORRECT, CheckAction::CONTINUE}; + + AddCheckMessage("NULL_TS_TYPE", *ast); + return {CheckDecision::INCORRECT, CheckAction::CONTINUE}; } } // namespace ark::es2panda::compiler::ast_verifier diff --git a/ets2panda/ast_verifier/nodeHasType.h b/ets2panda/ast_verifier/invariants/nodeHasType.h similarity index 65% rename from ets2panda/ast_verifier/nodeHasType.h rename to ets2panda/ast_verifier/invariants/nodeHasType.h index 6d4fe1e360..81769166cf 100644 --- a/ets2panda/ast_verifier/nodeHasType.h +++ b/ets2panda/ast_verifier/invariants/nodeHasType.h @@ -13,24 +13,31 @@ * limitations under the License. */ -#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_NODEHASTYPE_H -#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_NODEHASTYPE_H +#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_NODEHASTYPE_H +#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_NODEHASTYPE_H -#include "checkContext.h" +#include "../invariantBase.h" #include "checker/types/type.h" namespace ark::es2panda::compiler::ast_verifier { -class NodeHasType : public RecursiveInvariant { - template - friend class InvariantBase; +class NodeHasType : public InvariantBase { +public: + using Base::Base; [[nodiscard]] CheckResult operator()(const ir::AstNode *ast); - CheckResult CheckCompound(const ir::AstNode *ast); + +private: + const checker::Type *type_ {}; + + class ExceptionsMatcher; + + friend class NoPrimitiveTypes; }; -// NOTE(dkofanov): explicitly mark as dependent on NodeHasType: -class NoPrimitiveTypes : public RecursiveInvariant { +class NoPrimitiveTypes : public InvariantBase { public: + using Base::Base; + void SetNumberLoweringOccured(bool v = true) { numberLoweringOccurred_ = v; @@ -38,15 +45,10 @@ public: [[nodiscard]] CheckResult operator()(const ir::AstNode *ast) { - if (!ast->IsTyped()) { - return {CheckDecision::CORRECT, CheckAction::CONTINUE}; - } - auto type = ast->AsTyped()->TsType(); + const auto *type = Get().type_; if (type == nullptr) { - // Checked during NodeHasType. return {CheckDecision::CORRECT, CheckAction::CONTINUE}; } - if (!numberLoweringOccurred_ && type->IsETSPrimitiveType()) { AddCheckMessage("PRIMITIVE_BEFORE_LOWERING", *ast); return {CheckDecision::INCORRECT, CheckAction::CONTINUE}; @@ -59,4 +61,4 @@ private: }; } // namespace ark::es2panda::compiler::ast_verifier -#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_NODEHASTYPE_H +#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_NODEHASTYPE_H diff --git a/ets2panda/ast_verifier/referenceTypeAnnotationIsNull.cpp b/ets2panda/ast_verifier/invariants/referenceTypeAnnotationIsNull.cpp similarity index 100% rename from ets2panda/ast_verifier/referenceTypeAnnotationIsNull.cpp rename to ets2panda/ast_verifier/invariants/referenceTypeAnnotationIsNull.cpp diff --git a/ets2panda/ast_verifier/referenceTypeAnnotationIsNull.h b/ets2panda/ast_verifier/invariants/referenceTypeAnnotationIsNull.h similarity index 61% rename from ets2panda/ast_verifier/referenceTypeAnnotationIsNull.h rename to ets2panda/ast_verifier/invariants/referenceTypeAnnotationIsNull.h index c2a887beb8..e0e7bcaf36 100644 --- a/ets2panda/ast_verifier/referenceTypeAnnotationIsNull.h +++ b/ets2panda/ast_verifier/invariants/referenceTypeAnnotationIsNull.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,20 +13,20 @@ * limitations under the License. */ -#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_REFERENCETYPEANNOTATIONISNULL_H -#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_REFERENCETYPEANNOTATIONISNULL_H +#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_REFERENCETYPEANNOTATIONISNULL_H +#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_REFERENCETYPEANNOTATIONISNULL_H -#include "checkContext.h" +#include "../invariantBase.h" namespace ark::es2panda::compiler::ast_verifier { -class ReferenceTypeAnnotationIsNull : public RecursiveInvariant { - template - friend class InvariantBase; +class ReferenceTypeAnnotationIsNull : public InvariantBase { +public: + using Base::Base; [[nodiscard]] CheckResult operator()(const ir::AstNode *ast); bool CheckExceptions(ir::Identifier const *const id) const; }; } // namespace ark::es2panda::compiler::ast_verifier -#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_REFERENCETYPEANNOTATIONISNULL_H +#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_REFERENCETYPEANNOTATIONISNULL_H diff --git a/ets2panda/ast_verifier/sequenceExpressionHasLastType.cpp b/ets2panda/ast_verifier/invariants/sequenceExpressionHasLastType.cpp similarity index 100% rename from ets2panda/ast_verifier/sequenceExpressionHasLastType.cpp rename to ets2panda/ast_verifier/invariants/sequenceExpressionHasLastType.cpp diff --git a/ets2panda/ast_verifier/everyChildHasValidParent.h b/ets2panda/ast_verifier/invariants/sequenceExpressionHasLastType.h similarity index 60% rename from ets2panda/ast_verifier/everyChildHasValidParent.h rename to ets2panda/ast_verifier/invariants/sequenceExpressionHasLastType.h index 8c5b6c1375..c39f505072 100644 --- a/ets2panda/ast_verifier/everyChildHasValidParent.h +++ b/ets2panda/ast_verifier/invariants/sequenceExpressionHasLastType.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,19 +13,19 @@ * limitations under the License. */ -#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_EVERYCHILDHASVALIDPARENT_H -#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_EVERYCHILDHASVALIDPARENT_H +#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_SEQUENCEEXPRESSIONHASLASTTYPE_H +#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_SEQUENCEEXPRESSIONHASLASTTYPE_H -#include "checkContext.h" +#include "../invariantBase.h" namespace ark::es2panda::compiler::ast_verifier { -class EveryChildHasValidParent : public RecursiveInvariant { - template - friend class InvariantBase; +class SequenceExpressionHasLastType : public InvariantBase { +public: + using Base::Base; [[nodiscard]] CheckResult operator()(const ir::AstNode *ast); }; } // namespace ark::es2panda::compiler::ast_verifier -#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_EVERYCHILDHASVALIDPARENT_H +#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_SEQUENCEEXPRESSIONHASLASTTYPE_H diff --git a/ets2panda/ast_verifier/variableHasEnclosingScope.cpp b/ets2panda/ast_verifier/invariants/variableHasEnclosingScope.cpp similarity index 99% rename from ets2panda/ast_verifier/variableHasEnclosingScope.cpp rename to ets2panda/ast_verifier/invariants/variableHasEnclosingScope.cpp index a6946e3fdd..1aa6f1abf0 100644 --- a/ets2panda/ast_verifier/variableHasEnclosingScope.cpp +++ b/ets2panda/ast_verifier/invariants/variableHasEnclosingScope.cpp @@ -15,7 +15,7 @@ #include "variableHasEnclosingScope.h" #include "variableHasScope.h" -#include "helpers.h" +#include "../helpers.h" namespace ark::es2panda::compiler::ast_verifier { diff --git a/ets2panda/ast_verifier/variableHasEnclosingScope.h b/ets2panda/ast_verifier/invariants/variableHasEnclosingScope.h similarity index 66% rename from ets2panda/ast_verifier/variableHasEnclosingScope.h rename to ets2panda/ast_verifier/invariants/variableHasEnclosingScope.h index 3b12cba744..5d0cf63698 100644 --- a/ets2panda/ast_verifier/variableHasEnclosingScope.h +++ b/ets2panda/ast_verifier/invariants/variableHasEnclosingScope.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,16 +13,16 @@ * limitations under the License. */ -#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_VARIABLEHASENCLOSINGSCOPE_H -#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_VARIABLEHASENCLOSINGSCOPE_H +#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_VARIABLEHASENCLOSINGSCOPE_H +#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_VARIABLEHASENCLOSINGSCOPE_H -#include "checkContext.h" +#include "../invariantBase.h" namespace ark::es2panda::compiler::ast_verifier { -class VariableHasEnclosingScope : public RecursiveInvariant { - template - friend class InvariantBase; +class VariableHasEnclosingScope : public InvariantBase { +public: + using Base::Base; [[nodiscard]] CheckResult operator()(const ir::AstNode *ast); bool CheckCatchClause(const ir::AstNode *ast, const ir::AstNode *node) const; bool CheckScopeNodeExceptions(const ir::AstNode *node) const; @@ -31,4 +31,4 @@ class VariableHasEnclosingScope : public RecursiveInvariant { +class VariableHasScope : public InvariantBase { public: - template - friend class InvariantBase; + using Base::Base; [[nodiscard]] CheckResult operator()(const ir::AstNode *ast); +private: bool ScopeEncloseVariable(const varbinder::LocalVariable *var); bool CheckAstExceptions(const ir::AstNode *ast); }; } // namespace ark::es2panda::compiler::ast_verifier -#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_VARIABLEHASSCOPE_H +#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_VARIABLEHASSCOPE_H diff --git a/ets2panda/ast_verifier/variableNameIdentifierNameSame.cpp b/ets2panda/ast_verifier/invariants/variableNameIdentifierNameSame.cpp similarity index 100% rename from ets2panda/ast_verifier/variableNameIdentifierNameSame.cpp rename to ets2panda/ast_verifier/invariants/variableNameIdentifierNameSame.cpp diff --git a/ets2panda/ast_verifier/invariants/variableNameIdentifierNameSame.h b/ets2panda/ast_verifier/invariants/variableNameIdentifierNameSame.h new file mode 100644 index 0000000000..5eb9e85e21 --- /dev/null +++ b/ets2panda/ast_verifier/invariants/variableNameIdentifierNameSame.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_VARIABLENAMEIDENTIFIERNAMESAME_H +#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_VARIABLENAMEIDENTIFIERNAMESAME_H + +#include "../invariantBase.h" + +namespace ark::es2panda::compiler::ast_verifier { + +class VariableNameIdentifierNameSame : public InvariantBase { +public: + using Base::Base; + [[nodiscard]] CheckResult operator()(const ir::AstNode *ast); +}; + +} // namespace ark::es2panda::compiler::ast_verifier + +#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_VARIABLENAMEIDENTIFIERNAMESAME_H diff --git a/ets2panda/ast_verifier/sequenceExpressionHasLastType.h b/ets2panda/ast_verifier/sequenceExpressionHasLastType.h deleted file mode 100644 index 3cf7c53cd5..0000000000 --- a/ets2panda/ast_verifier/sequenceExpressionHasLastType.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2024 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_SEQUENCEEXPRESSIONHASLASTTYPE_H -#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_SEQUENCEEXPRESSIONHASLASTTYPE_H - -#include "checkContext.h" - -namespace ark::es2panda::compiler::ast_verifier { - -class SequenceExpressionHasLastType : public RecursiveInvariant { - template - friend class InvariantBase; - [[nodiscard]] CheckResult operator()(const ir::AstNode *ast); -}; - -} // namespace ark::es2panda::compiler::ast_verifier - -#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_SEQUENCEEXPRESSIONHASLASTTYPE_H diff --git a/ets2panda/ast_verifier/variableNameIdentifierNameSame.h b/ets2panda/ast_verifier/variableNameIdentifierNameSame.h deleted file mode 100644 index f30c6dd563..0000000000 --- a/ets2panda/ast_verifier/variableNameIdentifierNameSame.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2024 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_VARIABLENAMEIDENTIFIERNAMESAME_H -#define ES2PANDA_COMPILER_CORE_AST_VERIFIER_VARIABLENAMEIDENTIFIERNAMESAME_H - -#include "checkContext.h" - -namespace ark::es2panda::compiler::ast_verifier { - -class VariableNameIdentifierNameSame - : public RecursiveInvariant { - template - friend class InvariantBase; - [[nodiscard]] CheckResult operator()(const ir::AstNode *ast); -}; - -} // namespace ark::es2panda::compiler::ast_verifier - -#endif // ES2PANDA_COMPILER_CORE_AST_VERIFIER_VARIABLENAMEIDENTIFIERNAMESAME_H diff --git a/ets2panda/compiler/core/compilerImpl.cpp b/ets2panda/compiler/core/compilerImpl.cpp index 7dcd8a6284..b4a76e4e4e 100644 --- a/ets2panda/compiler/core/compilerImpl.cpp +++ b/ets2panda/compiler/core/compilerImpl.cpp @@ -134,27 +134,18 @@ static bool RunVerifierAndPhases(public_lib::Context &context, parser::Program & continue; } - if (CheckOptionsBeforePhase(options, program, name)) { - return false; - } - - if (!phase->Apply(&context, &program)) { - // Seems that some critical error happened inside lowering and code refactoring required. - // For normal processing this call shouldn't return false! + if (CheckOptionsBeforePhase(options, program, name) || !phase->Apply(&context, &program) || + CheckOptionsAfterPhase(options, program, name)) { return false; } - if (verifierEachPhase || options.HasVerifierPhase(name)) { + if (verifier.IntroduceNewInvariants(phase->Name()); + verifierEachPhase || options.HasVerifierPhase(phase->Name())) { verifier.Verify(phase->Name()); } - verifier.IntroduceNewInvariants(name); - - if (CheckOptionsAfterPhase(options, program, name)) { - return false; - } // Stop lowerings processing after Checker phase if any error happened. - if (name == compiler::CheckerPhase::NAME && context.diagnosticEngine->IsAnyError()) { + if (phase->Name() == compiler::CheckerPhase::NAME && context.diagnosticEngine->IsAnyError()) { return false; } } diff --git a/ets2panda/public/CMakeLists.txt b/ets2panda/public/CMakeLists.txt index a399f4b251..b887bce27e 100644 --- a/ets2panda/public/CMakeLists.txt +++ b/ets2panda/public/CMakeLists.txt @@ -288,7 +288,6 @@ set (HEADERS_TO_BE_PARSED ${ES2PANDA_ROOT}/parser/program/program.h ${ES2PANDA_ROOT}/es2panda.h ${ES2PANDA_ROOT}/ast_verifier/ASTVerifier.h - ${ES2PANDA_ROOT}/ast_verifier/checkContext.h ${ES2PANDA_ROOT}/util/importPathManager.h ) @@ -556,7 +555,6 @@ set (ES2PANDA_API_GENERATED ${LIBGEN_DIR}/gen/headers/parser/ETSparser.yaml ${LIBGEN_DIR}/gen/headers/parser/program/program.yaml ${LIBGEN_DIR}/gen/headers/ast_verifier/ASTVerifier.yaml - ${LIBGEN_DIR}/gen/headers/ast_verifier/checkContext.yaml ${LIBGEN_DIR}/gen/headers/util/importPathManager.yaml ) diff --git a/ets2panda/test/unit/public/ast_verifier_private_access_negative_test.cpp b/ets2panda/test/unit/public/ast_verifier_private_access_negative_test.cpp index 917dc39271..6a7cd71d0a 100644 --- a/ets2panda/test/unit/public/ast_verifier_private_access_negative_test.cpp +++ b/ets2panda/test/unit/public/ast_verifier_private_access_negative_test.cpp @@ -40,8 +40,7 @@ TEST_F(ASTVerifierTest, PrivateAccessTestNegative1) ->AsClassProperty() ->AddModifier(ark::es2panda::ir::ModifierFlags::PRIVATE); - EXPECT_TRUE(Verify( - ExpectVerifierMessage {"PROPERTY_NOT_VISIBLE_HERE(AstNodeType::MEMBER_EXPRESSION, line 6)"})); + EXPECT_TRUE(Verify(ExpectVerifierMessage {"PROPERTY_NOT_VISIBLE_HERE"})); } } @@ -96,8 +95,7 @@ TEST_F(ASTVerifierTest, PrivateAccessTestNegative3) ->AsClassProperty() ->AddModifier(ark::es2panda::ir::ModifierFlags::PRIVATE); - EXPECT_TRUE(Verify( - ExpectVerifierMessage {"PROPERTY_NOT_VISIBLE_HERE(AstNodeType::MEMBER_EXPRESSION, line 8)"})); + EXPECT_TRUE(Verify(ExpectVerifierMessage {"PROPERTY_NOT_VISIBLE_HERE"})); } } diff --git a/ets2panda/test/unit/public/ast_verifier_protected_access_negative_test.cpp b/ets2panda/test/unit/public/ast_verifier_protected_access_negative_test.cpp index b605d4926e..d3204e733f 100644 --- a/ets2panda/test/unit/public/ast_verifier_protected_access_negative_test.cpp +++ b/ets2panda/test/unit/public/ast_verifier_protected_access_negative_test.cpp @@ -41,8 +41,7 @@ TEST_F(ASTVerifierTest, ProtectedAccessTestNegative1) ->AsClassProperty() ->AddModifier(ark::es2panda::ir::ModifierFlags::PROTECTED); - EXPECT_TRUE(Verify( - ExpectVerifierMessage {"PROPERTY_NOT_VISIBLE_HERE(AstNodeType::MEMBER_EXPRESSION, line 7)"})); + EXPECT_TRUE(Verify(ExpectVerifierMessage {"PROPERTY_NOT_VISIBLE_HERE"})); } } @@ -98,8 +97,7 @@ TEST_F(ASTVerifierTest, ProtectedAccessTestNegative3) ->AsClassProperty() ->AddModifier(ark::es2panda::ir::ModifierFlags::PROTECTED); - EXPECT_TRUE(Verify( - ExpectVerifierMessage {"PROPERTY_NOT_VISIBLE_HERE(AstNodeType::MEMBER_EXPRESSION, line 8)"})); + EXPECT_TRUE(Verify(ExpectVerifierMessage {"PROPERTY_NOT_VISIBLE_HERE"})); } } diff --git a/ets2panda/test/unit/public/ast_verifier_short_test.cpp b/ets2panda/test/unit/public/ast_verifier_short_test.cpp index dec7ee7442..214ac89d08 100644 --- a/ets2panda/test/unit/public/ast_verifier_short_test.cpp +++ b/ets2panda/test/unit/public/ast_verifier_short_test.cpp @@ -55,22 +55,20 @@ using ark::es2panda::varbinder::VariableFlags; TEST_F(ASTVerifierTest, NullParent) { StringLiteral emptyNode; - EXPECT_TRUE(VerifyNode(&emptyNode, - ExpectVerifierMessage {"NULL_PARENT(AstNodeType::STRING_LITERAL, line 1)"})); + EXPECT_TRUE(VerifyNode(&emptyNode, ExpectVerifierMessage {"NULL_PARENT"})); } TEST_F(ASTVerifierTest, NullRange) { StringLiteral emptyNode; - EXPECT_TRUE(VerifyNode( - &emptyNode, ExpectVerifierMessage {"NULL_RANGE(AstNodeType::STRING_LITERAL, line 1)"})); + EXPECT_TRUE(VerifyNode(&emptyNode, ExpectVerifierMessage {"NULL_RANGE"})); } -TEST_F(ASTVerifierTest, NullType) +// NOTE(dkofanov): #22355 'NodeHasType' is broken. +TEST_F(ASTVerifierTest, DISABLED_NullType) { StringLiteral emptyNode; - EXPECT_TRUE(VerifyNode(&emptyNode, - ExpectVerifierMessage {"NULL_TS_TYPE(AstNodeType::STRING_LITERAL, line 1)"})); + EXPECT_TRUE(VerifyNode(&emptyNode, ExpectVerifierMessage {"NULL_TS_TYPE"})); } TEST_F(ASTVerifierTest, WithoutScope) @@ -183,9 +181,8 @@ TEST_F(ASTVerifierTest, ArithmeticExpressionNegative2) left.SetTsType(etschecker.GlobalETSStringLiteralType()); right.SetTsType(etschecker.GlobalIntType()); - EXPECT_TRUE(VerifyNode( - arithmeticExpression.AsBinaryExpression(), - ExpectVerifierMessage {"Not a numeric type(AstNodeType::BOOLEAN_LITERAL, line 1)"})); + EXPECT_TRUE(VerifyNode(arithmeticExpression.AsBinaryExpression(), + ExpectVerifierMessage {"Not a numeric type"})); } TEST_F(ASTVerifierTest, PrimitiveType) @@ -197,9 +194,9 @@ TEST_F(ASTVerifierTest, PrimitiveType) ast.SetTsType(etschecker.CreateETSBooleanType(true)); ASSERT_TRUE(VerifyNode(&ast, ExpectVerifierMessage {"PRIMITIVE_BEFORE_LOWERING"})); - std::get(invariants_).SetNumberLoweringOccured(); + Get()->SetNumberLoweringOccured(); ASSERT_TRUE(VerifyNode(&ast)); - std::get(invariants_).SetNumberLoweringOccured(false); + Get()->SetNumberLoweringOccured(false); } TEST_F(ASTVerifierTest, SequenceExpressionType) diff --git a/ets2panda/test/utils/ast_verifier_test.h b/ets2panda/test/utils/ast_verifier_test.h index 180afb419f..68ccb22ecb 100644 --- a/ets2panda/test/utils/ast_verifier_test.h +++ b/ets2panda/test/utils/ast_verifier_test.h @@ -173,18 +173,31 @@ public: [[nodiscard]] auto Verify(ExpectVerifierMessage expected = {}) { ASSERT(ctx_ != nullptr); - auto *inv = &std::get(invariants_); + auto *inv = Get(); inv->Init(); - inv->VerifyAst(GetAst()); + + std::function aux {}; + aux = [inv, &aux](const ir_alias::AstNode *child) -> void { + // Required invariants need to be manually called in tests: + std::apply([child](auto &...requiredInv) { (((void)(requiredInv)(child)), ...); }, inv->GetRequired()); + const auto [_, action] = (*inv)(child); + if (action == verifier_alias::CheckAction::SKIP_SUBTREE) { + return; + } + child->Iterate(aux); + }; + aux(GetAst()); return expected.CheckMessages(inv->ViewMessages()); } template [[nodiscard]] auto VerifyNode(const ir_alias::AstNode *ast, ExpectVerifierMessage expected = {}) { - auto *inv = &std::get(invariants_); + auto *inv = Get(); inv->Init(); - inv->VerifyNode(ast); + // Required invariants need to be manually called in tests: + std::apply([ast](auto &...requiredInv) { (((void)(requiredInv)(ast)), ...); }, inv->GetRequired()); + (void)(*inv)(ast); return expected.CheckMessages(inv->ViewMessages()); } diff --git a/ets2panda/util/options.yaml b/ets2panda/util/options.yaml index 4c5327f7f9..332845801b 100644 --- a/ets2panda/util/options.yaml +++ b/ets2panda/util/options.yaml @@ -277,7 +277,7 @@ options: delimiter: ':' - name: phases type: arg_list_t - default: [ "each" ] + default: [ "after" ] description: > Specify phases to finalize with ASTVerifier. Shortcuts: "before", "each", "after". delimiter: ':' -- Gitee From 36258fadc61fb47524af111766fff3b04eb49c55 Mon Sep 17 00:00:00 2001 From: ozerovnikita Date: Thu, 27 Mar 2025 23:05:50 +0300 Subject: [PATCH 037/268] add mdf flag copy from scrFunc Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBWVZH Test: ninja es2panda-plugin-test Signed-off-by: ozerovnikita --- ets2panda/ir/statements/functionDeclaration.h | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/ets2panda/ir/statements/functionDeclaration.h b/ets2panda/ir/statements/functionDeclaration.h index 34f5058dc3..a88466a32e 100644 --- a/ets2panda/ir/statements/functionDeclaration.h +++ b/ets2panda/ir/statements/functionDeclaration.h @@ -1,5 +1,5 @@ /** - * Copyright (c) 2021-2024 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -19,6 +19,7 @@ #include "ir/annotationAllowed.h" #include "ir/statement.h" #include "ir/statements/annotationUsage.h" +#include "ir/base/scriptFunction.h" namespace ark::es2panda::ir { class ScriptFunction; @@ -33,6 +34,7 @@ public: func_(func), isAnonymous_(isAnonymous) { + flags_ = func->Modifiers(); } explicit FunctionDeclaration(ArenaAllocator *allocator, ScriptFunction *func, bool isAnonymous = false) @@ -41,6 +43,7 @@ public: func_(func), isAnonymous_(isAnonymous) { + flags_ = func->Modifiers(); } ScriptFunction *Function() -- Gitee From 1f18464a41d67e24395039544fb4e2d6143a5f00 Mon Sep 17 00:00:00 2001 From: Denis Silakov Date: Wed, 9 Apr 2025 16:35:30 +0300 Subject: [PATCH 038/268] Ignore check for PRINT_DEBUG macro The G.PRE.01 check has been disabled globally but for some reason it is still occasionally triggered in CI and produces an error on PRINT_DEBUG macro. Let's make it silent. Issue: #IBZV51 Signed-off-by: Denis Silakov --- ets2panda/declgen_ets2ts/declgenEts2Ts.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp b/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp index e40c3e5bbf..cff92782e7 100644 --- a/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp +++ b/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp @@ -32,6 +32,7 @@ #include "ir/ts/tsTypeAliasDeclaration.h" #include "ir/ts/tsTypeParameter.h" +/* CC-OFFNXT(G.PRE.01) Disabled check still occasionally triggered in CI */ #define DEBUG_PRINT 0 namespace ark::es2panda::declgen_ets2ts { -- Gitee From 86b76b544a1d6af5c78365a5d3cd505b46e500c5 Mon Sep 17 00:00:00 2001 From: ozerovnikita Date: Tue, 8 Apr 2025 22:35:46 +0300 Subject: [PATCH 039/268] better way to create plugin tests Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBREDQ Test: ninja es2panda-plugin-test Signed-off-by: ozerovnikita --- ets2panda/test/unit/plugin/CMakeLists.txt | 3 +- ets2panda/test/unit/plugin/export.ets | 7 + ets2panda/test/unit/plugin/import.ets | 2 +- ...ceed_to_state_rerun_scopes_after_check.cpp | 135 ++++-------------- ...roceed_to_state_rerun_scopes_on_import.cpp | 110 ++++++++++++++ ets2panda/test/unit/plugin/util.cpp | 102 ++++++++++++- ets2panda/test/unit/plugin/util.h | 12 ++ 7 files changed, 257 insertions(+), 114 deletions(-) create mode 100644 ets2panda/test/unit/plugin/plugin_proceed_to_state_rerun_scopes_on_import.cpp diff --git a/ets2panda/test/unit/plugin/CMakeLists.txt b/ets2panda/test/unit/plugin/CMakeLists.txt index ca00af5a73..b8836c09e9 100644 --- a/ets2panda/test/unit/plugin/CMakeLists.txt +++ b/ets2panda/test/unit/plugin/CMakeLists.txt @@ -53,7 +53,8 @@ set(PLUGIN_TESTS "plugin_proceed_to_state_find_import_declaration compile.ets ${COMPILE_MODE} cpp ${EXECUTABLE_PLUGIN}" # See #22753. # "plugin_proceed_to_state_test_number_literal compile.ets ${RUNTIME_MODE} cpp ${EXECUTABLE_PLUGIN}" - # "plugin_proceed_to_state_rerun_scopes_after_check compile.ets ${RUNTIME_MODE} cpp ${EXECUTABLE_PLUGIN}" + "plugin_proceed_to_state_rerun_scopes_after_check compile.ets ${RUNTIME_MODE} cpp ${EXECUTABLE_PLUGIN}" + "plugin_proceed_to_state_rerun_scopes_on_import import.ets ${COMPILE_MODE} cpp ${EXECUTABLE_PLUGIN}" # "plugin_proceed_to_state_rerun_scopes_after_lowered compile.ets ${RUNTIME_MODE} cpp ${EXECUTABLE_PLUGIN}" # "plugin_proceed_to_state_run_verifier compile.ets ${COMPILE_MODE} cpp ${EXECUTABLE_PLUGIN}" "plugin_proceed_to_state_ast_node_check compile.ets ${COMPILE_MODE} cpp ${EXECUTABLE_PLUGIN}" diff --git a/ets2panda/test/unit/plugin/export.ets b/ets2panda/test/unit/plugin/export.ets index c37edc0c5e..bd9d256393 100644 --- a/ets2panda/test/unit/plugin/export.ets +++ b/ets2panda/test/unit/plugin/export.ets @@ -23,3 +23,10 @@ export class A { } b: int = 2 } + +export class B { + foo() : int { + return 5; + } + b: int = 5 +} \ No newline at end of file diff --git a/ets2panda/test/unit/plugin/import.ets b/ets2panda/test/unit/plugin/import.ets index ef92074fe3..ee00946ba4 100644 --- a/ets2panda/test/unit/plugin/import.ets +++ b/ets2panda/test/unit/plugin/import.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import {A, foo} from "./export.ets" +import {A, B, foo} from "./export.ets" function main() { let a: A = new A(); diff --git a/ets2panda/test/unit/plugin/plugin_proceed_to_state_rerun_scopes_after_check.cpp b/ets2panda/test/unit/plugin/plugin_proceed_to_state_rerun_scopes_after_check.cpp index 06c7be9a96..d577d30ebd 100644 --- a/ets2panda/test/unit/plugin/plugin_proceed_to_state_rerun_scopes_after_check.cpp +++ b/ets2panda/test/unit/plugin/plugin_proceed_to_state_rerun_scopes_after_check.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include "util.h" #include "public/es2panda_lib.h" @@ -26,31 +27,18 @@ static es2panda_Impl *impl = nullptr; static auto source = std::string("function main() { \nlet a = 5;\n assertEQ(a, 5);\n }"); +constexpr int NUM_OF_CHANGE_IDENTIFIERS = 2; -static es2panda_AstNode *letStatement = nullptr; -static es2panda_AstNode *assertStatement = nullptr; static es2panda_AstNode *mainScriptFunc = nullptr; +static std::vector changeIdentifiers {}; static es2panda_Context *ctx = nullptr; -es2panda_AstNode *parNode; -es2panda_Context *newCtx; - -static void FindLet(es2panda_AstNode *ast) +static void FindChangeIdentifiers(es2panda_AstNode *ast) { - if (!impl->IsVariableDeclaration(ast)) { - impl->AstNodeIterateConst(ctx, ast, FindLet); - return; + if (impl->IsIdentifier(ast) && std::string(impl->IdentifierName(ctx, ast)) == "a") { + changeIdentifiers.emplace_back(ast); } - letStatement = ast; -} - -static void FindAssert(es2panda_AstNode *ast) -{ - if (!IsAssertCall(ast)) { - impl->AstNodeIterateConst(ctx, ast, FindAssert); - return; - } - assertStatement = ast; + impl->AstNodeIterateConst(ctx, ast, FindChangeIdentifiers); } static void FindMainDef(es2panda_AstNode *ast) @@ -68,112 +56,37 @@ static void FindMainDef(es2panda_AstNode *ast) mainScriptFunc = scriptFunc; } -static void changeParent(es2panda_AstNode *child) -{ - impl->AstNodeSetParent(newCtx, child, parNode); -} - -static void SetRightParent(es2panda_AstNode *node, void *arg) +static bool ChangeAst(es2panda_Context *context) { - es2panda_Context *context = static_cast(arg); - newCtx = context; - parNode = node; - impl->AstNodeIterateConst(context, node, changeParent); -} - -static bool ChangeAst(es2panda_Context *context, es2panda_AstNode *ast) -{ - std::cout << impl->AstNodeDumpJSONConst(context, ast) << std::endl; - size_t n = 0; + auto Ast = impl->ProgramAst(context, impl->ContextProgram(context)); ctx = context; - impl->AstNodeIterateConst(context, ast, FindLet); - impl->AstNodeIterateConst(context, ast, FindAssert); - impl->AstNodeIterateConst(context, ast, FindMainDef); - if (mainScriptFunc == nullptr || letStatement == nullptr || assertStatement == nullptr) { + impl->AstNodeIterateConst(context, Ast, FindMainDef); + if (mainScriptFunc == nullptr) { + return false; + } + impl->AstNodeIterateConst(context, mainScriptFunc, FindChangeIdentifiers); + if (changeIdentifiers.size() != NUM_OF_CHANGE_IDENTIFIERS) { return false; } - auto mainFuncBody = impl->ScriptFunctionBody(context, mainScriptFunc); - std::cout << impl->AstNodeDumpJSONConst(context, mainScriptFunc) << std::endl; - auto assertStatementTest = AssertStatementTest(context, assertStatement); - std::cout << impl->AstNodeDumpJSONConst(context, letStatement) << std::endl; - std::cout << impl->AstNodeDumpJSONConst(context, assertStatementTest) << std::endl; std::string className = std::string("b"); auto *memForName = static_cast(impl->AllocMemory(context, className.size() + 1, 1)); std::copy_n(className.c_str(), className.size() + 1, memForName); - auto varIdent = impl->CreateIdentifier1(context, memForName); - auto assertIdent = impl->CreateIdentifier1(context, memForName); - auto declarator = impl->CreateVariableDeclarator1( - context, Es2pandaVariableDeclaratorFlag::VARIABLE_DECLARATOR_FLAG_LET, varIdent, - impl->VariableDeclaratorInit(context, impl->VariableDeclarationDeclaratorsConst(context, letStatement, &n)[0])); - auto declaration = impl->CreateVariableDeclaration( - context, Es2pandaVariableDeclarationKind::VARIABLE_DECLARATION_KIND_LET, &declarator, 1); - - impl->BinaryExpressionSetLeft(context, assertStatementTest, assertIdent); - auto newAssertStatement = CreateAssertStatement(context, assertStatementTest, nullptr); - - es2panda_AstNode *newMainStatements[2] = {declaration, newAssertStatement}; - impl->BlockStatementSetStatements(context, mainFuncBody, newMainStatements, 2U); - impl->AstNodeForEach(ast, SetRightParent, context); - std::cout << impl->AstNodeDumpJSONConst(context, ast) << std::endl; - - impl->AstNodeRecheck(context, declaration); - impl->AstNodeRecheck(context, newAssertStatement); - - std::cout << impl->AstNodeDumpEtsSrcConst(context, ast) << std::endl; + for (auto ident : changeIdentifiers) { + impl->IdentifierSetName(context, ident, memForName); + } + std::cout << impl->AstNodeDumpEtsSrcConst(context, Ast) << std::endl; + impl->AstNodeRecheck(context, Ast); return true; } int main(int argc, char **argv) { - if (argc < MIN_ARGC) { - return INVALID_ARGC_ERROR_CODE; - } - - if (GetImpl() == nullptr) { - return NULLPTR_IMPL_ERROR_CODE; - } - impl = GetImpl(); - std::cout << "LOAD SUCCESS" << std::endl; - const char **args = const_cast(&(argv[1])); - auto config = impl->CreateConfig(argc - 1, args); - auto context = impl->CreateContextFromString(config, source.data(), argv[argc - 1]); - if (context == nullptr) { - std::cerr << "FAILED TO CREATE CONTEXT" << std::endl; - return NULLPTR_CONTEXT_ERROR_CODE; - } - - impl->ProceedToState(context, ES2PANDA_STATE_PARSED); - CheckForErrors("PARSE", context); - - impl->ProceedToState(context, ES2PANDA_STATE_BOUND); - CheckForErrors("BOUND", context); - - impl->ProceedToState(context, ES2PANDA_STATE_CHECKED); - CheckForErrors("CHECKED", context); - - auto ast = impl->ProgramAst(context, impl->ContextProgram(context)); - if (!ChangeAst(context, ast)) { - return TEST_ERROR_CODE; - } - - impl->AstNodeRecheck(context, ast); - - impl->ProceedToState(context, ES2PANDA_STATE_LOWERED); - CheckForErrors("LOWERED", context); - - impl->ProceedToState(context, ES2PANDA_STATE_ASM_GENERATED); - CheckForErrors("ASM", context); - - impl->ProceedToState(context, ES2PANDA_STATE_BIN_GENERATED); - CheckForErrors("BIN", context); - if (impl->ContextState(context) == ES2PANDA_STATE_ERROR) { - return PROCEED_ERROR_CODE; - } - impl->DestroyConfig(config); - - return 0; + std::map>> testFunctions; + testFunctions[ES2PANDA_STATE_CHECKED] = {ChangeAst}; + ProccedToStatePluginTestData data = {argc, argv, &impl, testFunctions, true, source}; + return RunAllStagesWithTestFunction(data); } // NOLINTEND diff --git a/ets2panda/test/unit/plugin/plugin_proceed_to_state_rerun_scopes_on_import.cpp b/ets2panda/test/unit/plugin/plugin_proceed_to_state_rerun_scopes_on_import.cpp new file mode 100644 index 0000000000..5d97f84739 --- /dev/null +++ b/ets2panda/test/unit/plugin/plugin_proceed_to_state_rerun_scopes_on_import.cpp @@ -0,0 +1,110 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include "util.h" +#include "public/es2panda_lib.h" + +// NOLINTBEGIN + +static es2panda_Impl *impl = nullptr; + +static es2panda_AstNode *letStatement = nullptr; +static std::vector *typeRefs = nullptr; +static es2panda_Context *ctx = nullptr; + +es2panda_AstNode *parNode; +es2panda_Context *newCtx; + +static void FindLet(es2panda_AstNode *ast) +{ + if (!impl->IsVariableDeclaration(ast)) { + impl->AstNodeIterateConst(ctx, ast, FindLet); + return; + } + letStatement = ast; +} + +static void FindEtsTypeReferencesInLet(es2panda_AstNode *ast) +{ + if (!impl->IsETSTypeReferencePart(ast)) { + impl->AstNodeIterateConst(ctx, ast, FindEtsTypeReferencesInLet); + return; + } + typeRefs->push_back(ast); + impl->AstNodeIterateConst(ctx, ast, FindEtsTypeReferencesInLet); +} + +static void changeParent(es2panda_AstNode *child) +{ + impl->AstNodeSetParent(newCtx, child, parNode); +} + +static void SetRightParent(es2panda_AstNode *node, void *arg) +{ + es2panda_Context *context = static_cast(arg); + newCtx = context; + parNode = node; + impl->AstNodeIterateConst(context, node, changeParent); +} + +static bool ChangeAst(es2panda_Context *context) +{ + auto Ast = impl->ProgramAst(context, impl->ContextProgram(context)); + ctx = context; + impl->AstNodeIterateConst(context, Ast, FindLet); + if (letStatement == nullptr) { + return false; + } + impl->AstNodeIterateConst(context, letStatement, FindEtsTypeReferencesInLet); + if (typeRefs == nullptr) { + return false; + } + + std::string className = std::string("B"); + auto *memForName = static_cast(impl->AllocMemory(context, className.size() + 1, 1)); + std::copy_n(className.c_str(), className.size() + 1, memForName); + + for (auto typeRef : *typeRefs) { + auto identifier = impl->ETSTypeReferencePartGetIdent(context, typeRef); + impl->IdentifierSetName(context, identifier, memForName); + } + impl->AstNodeForEach(Ast, SetRightParent, context); + impl->AstNodeRecheck(context, Ast); + return true; +} + +int main(int argc, char **argv) +{ + auto recheckTest = [&](es2panda_Context *context) -> bool { + typeRefs = new std::vector(); + auto testResult = ChangeAst(context); + delete typeRefs; + typeRefs = nullptr; + return testResult; + }; + + std::map>> testFunctions; + testFunctions[ES2PANDA_STATE_CHECKED] = {recheckTest}; + ProccedToStatePluginTestData data = {argc, argv, &impl, testFunctions, false, ""}; + return RunAllStagesWithTestFunction(data); +} + +// NOLINTEND diff --git a/ets2panda/test/unit/plugin/util.cpp b/ets2panda/test/unit/plugin/util.cpp index 8bf7274192..adfdf1f81e 100644 --- a/ets2panda/test/unit/plugin/util.cpp +++ b/ets2panda/test/unit/plugin/util.cpp @@ -39,7 +39,7 @@ es2panda_Impl *GetImpl() auto library = std::move(libraryRes.Value()); auto getImpl = ark::os::library_loader::ResolveSymbol(library, "es2panda_GetImpl"); if (!getImpl.HasValue()) { - std::cout << "Error in load func get impl" << std::endl; + std::cout << "Error in load func get g_implPtr" << std::endl; return nullptr; } @@ -100,6 +100,106 @@ void PrependStatementToProgram(es2panda_Context *context, es2panda_AstNode *prog impl->AstNodeSetParent(context, newStatement, program); } +static const char *GetPhaseName(es2panda_ContextState state) +{ + switch (state) { + case ES2PANDA_STATE_NEW: + return "NEW"; + case ES2PANDA_STATE_PARSED: + return "PARSE"; + case ES2PANDA_STATE_SCOPE_INITED: + return "SCOPE_INITED"; + case ES2PANDA_STATE_BOUND: + return "BOUND"; + case ES2PANDA_STATE_CHECKED: + return "CHECKED"; + case ES2PANDA_STATE_LOWERED: + return "LOWERED"; + case ES2PANDA_STATE_ASM_GENERATED: + return "ASM"; + case ES2PANDA_STATE_BIN_GENERATED: + return "BIN"; + case ES2PANDA_STATE_ERROR: + return "ERROR"; + default: + return "NON_VALID_STATE"; + } +} + +static bool IsAllowedStage(es2panda_ContextState state) +{ + switch (state) { + case ES2PANDA_STATE_NEW: + return false; + case ES2PANDA_STATE_SCOPE_INITED: + return false; + case ES2PANDA_STATE_ERROR: + return false; + default: + return true; + } +} + +static void DestroyTest(es2panda_Context *context, es2panda_Config *config) +{ + g_implPtr->DestroyContext(context); + g_implPtr->DestroyConfig(config); +} + +int RunAllStagesWithTestFunction(ProccedToStatePluginTestData &data) +{ + if (data.argc < MIN_ARGC) { + return INVALID_ARGC_ERROR_CODE; + } + + if (GetImpl() == nullptr) { + return NULLPTR_IMPL_ERROR_CODE; + } + *data.impl = GetImpl(); + std::cout << "LOAD SUCCESS" << std::endl; + const char **args = const_cast(&(data.argv[1])); + auto config = g_implPtr->CreateConfig(data.argc - 1, args); + es2panda_Context *context = nullptr; + if (data.fromSource) { + context = g_implPtr->CreateContextFromString(config, data.source.data(), data.argv[data.argc - 1]); + } else { + context = g_implPtr->CreateContextFromFile(config, data.argv[data.argc - 1]); + } + if (context == nullptr) { + std::cerr << "FAILED TO CREATE CONTEXT" << std::endl; + return NULLPTR_CONTEXT_ERROR_CODE; + } + + for (auto [testStage, _] : data.testFunctions) { + if (!IsAllowedStage(testStage)) { + DestroyTest(context, config); + return TEST_ERROR_CODE; + } + } + + for (auto state = ES2PANDA_STATE_PARSED; state <= ES2PANDA_STATE_BIN_GENERATED; + state = static_cast(state + 1)) { + if (!IsAllowedStage(state)) { + continue; + } + g_implPtr->ProceedToState(context, state); + CheckForErrors(GetPhaseName(state), context); + for (auto testFunc : data.testFunctions[state]) { + if (!testFunc(context)) { + DestroyTest(context, config); + return TEST_ERROR_CODE; + } + } + } + + if (g_implPtr->ContextState(context) == ES2PANDA_STATE_ERROR) { + DestroyTest(context, config); + return PROCEED_ERROR_CODE; + } + DestroyTest(context, config); + return 0; +} + int Test(es2panda_Context *context, es2panda_Impl *impl, int stage, std::function handle) { diff --git a/ets2panda/test/unit/plugin/util.h b/ets2panda/test/unit/plugin/util.h index 1fd7c0869a..ba30c32c4d 100644 --- a/ets2panda/test/unit/plugin/util.h +++ b/ets2panda/test/unit/plugin/util.h @@ -19,6 +19,8 @@ #include #include #include +#include +#include #include "os/library_loader.h" @@ -35,10 +37,20 @@ constexpr int NULLPTR_CONTEXT_ERROR_CODE = 6; es2panda_Impl *GetImpl(); +struct ProccedToStatePluginTestData { + int argc; + char **argv; + es2panda_Impl **impl; + std::map>> testFunctions; + bool fromSource; + std::string source; +}; + void CheckForErrors(const std::string &stateName, es2panda_Context *context); bool IsAssertCall(es2panda_AstNode *ast); es2panda_AstNode *CreateAssertStatement(es2panda_Context *context, es2panda_AstNode *test, es2panda_AstNode *second); es2panda_AstNode *AssertStatementTest(es2panda_Context *context, es2panda_AstNode *classInstance); +int RunAllStagesWithTestFunction(ProccedToStatePluginTestData &data); es2panda_AstNode *CreateIdentifierFromString(es2panda_Context *context, const std::string_view &name); -- Gitee From 20e7793412683092ab008fb828ac93e72e92fc38 Mon Sep 17 00:00:00 2001 From: zenghang Date: Wed, 16 Apr 2025 02:01:32 +0800 Subject: [PATCH 040/268] Fix the clean context twice Issue: IC1GA6 Signed-off-by: zenghang Change-Id: Ie4520ac38b8ed86f2ee4538d531cb94dd20bb6c5 --- .../driver/build_system/src/build/base_mode.ts | 14 ++++++++++++-- .../build_system/src/build/compile_worker.ts | 7 ++++++- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/ets2panda/driver/build_system/src/build/base_mode.ts b/ets2panda/driver/build_system/src/build/base_mode.ts index b0f3a57b38..65dac4675e 100644 --- a/ets2panda/driver/build_system/src/build/base_mode.ts +++ b/ets2panda/driver/build_system/src/build/base_mode.ts @@ -125,6 +125,7 @@ export abstract class BaseMode { ensurePathExists(etsOutputPath); let arktsGlobal: ArkTSGlobal = this.buildConfig.arktsGlobal; let arkts: ArkTS = this.buildConfig.arkts; + let errorStatus = false; try { arktsGlobal.filePath = fileInfo.filePath; arktsGlobal.config = arkts.Config.create([ @@ -157,6 +158,7 @@ export abstract class BaseMode { ); // Generate 1.0 declaration files & 1.0 glue code this.logger.printInfo('declaration files generated'); } catch (error) { + errorStatus = true; if (error instanceof Error) { const logData: LogData = LogDataFactory.newInstance( ErrorCode.BUILDSYSTEM_DECLGEN_FAIL, @@ -166,7 +168,10 @@ export abstract class BaseMode { this.logger.printError(logData); } } finally { - arktsGlobal.es2panda._DestroyContext(arktsGlobal.compilerContext.peer); + if (!errorStatus) { + // when error occur,wrapper will destroy context. + arktsGlobal.es2panda._DestroyContext(arktsGlobal.compilerContext.peer); + } arkts.destroyConfig(arktsGlobal.config); } } @@ -192,6 +197,7 @@ export abstract class BaseMode { let arktsGlobal = this.buildConfig.arktsGlobal; let arkts = this.buildConfig.arkts; + let errorStatus = false; try { arktsGlobal.filePath = fileInfo.filePath; arktsGlobal.config = arkts.Config.create(ets2pandaCmd).peer; @@ -216,6 +222,7 @@ export abstract class BaseMode { arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_BIN_GENERATED); this.logger.printInfo('es2panda bin generated'); } catch (error) { + errorStatus = true; if (error instanceof Error) { const logData: LogData = LogDataFactory.newInstance( ErrorCode.BUILDSYSTEM_COMPILE_ABC_FAIL, @@ -225,7 +232,10 @@ export abstract class BaseMode { this.logger.printError(logData); } } finally { - arktsGlobal.es2panda._DestroyContext(arktsGlobal.compilerContext.peer); + if (!errorStatus) { + // when error occur,wrapper will destroy context. + arktsGlobal.es2panda._DestroyContext(arktsGlobal.compilerContext.peer); + } PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); arkts.destroyConfig(arktsGlobal.config); } diff --git a/ets2panda/driver/build_system/src/build/compile_worker.ts b/ets2panda/driver/build_system/src/build/compile_worker.ts index b4f7050c27..4c69a0c8a4 100644 --- a/ets2panda/driver/build_system/src/build/compile_worker.ts +++ b/ets2panda/driver/build_system/src/build/compile_worker.ts @@ -49,6 +49,7 @@ process.on('message', (message: { let { arkts, arktsGlobal } = require(koalaWrapperPath); for (const fileInfo of taskList) { + let errorStatus = false; try { ensurePathExists(fileInfo.abcFilePath); const source = fs.readFileSync(fileInfo.filePath).toString(); @@ -77,6 +78,7 @@ process.on('message', (message: { arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_BIN_GENERATED); } catch (error) { + errorStatus = true; if (error instanceof Error) { const logData: LogData = LogDataFactory.newInstance( ErrorCode.BUILDSYSTEM_COMPILE_ABC_FAIL, @@ -91,7 +93,10 @@ process.on('message', (message: { error: 'Compile abc files failed.' }); } finally { - arktsGlobal.es2panda._DestroyContext(arktsGlobal.compilerContext.peer); + if (!errorStatus) { + // when error occur,wrapper will destroy context. + arktsGlobal.es2panda._DestroyContext(arktsGlobal.compilerContext.peer); + } PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); arkts.destroyConfig(arktsGlobal.config); } -- Gitee From 6ed33504db7ccd59b6757cbe7567f38dc3255417 Mon Sep 17 00:00:00 2001 From: liushitong Date: Fri, 11 Apr 2025 15:49:46 +0800 Subject: [PATCH 041/268] [lsp]: fix code warnning Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC1SFA Signed-off-by: liushitong --- ets2panda/bindings/.prettierignore | 22 + ets2panda/bindings/.prettierrc.json | 10 + .../bindings/native/include/dynamic-loader.h | 3 +- .../bindings/native/src/win-dynamic-node.cpp | 6 +- ets2panda/bindings/package.json | 4 +- .../bindings/src/Es2pandaNativeModule.ts | 302 ++++++------ ets2panda/bindings/src/InteropNativeModule.ts | 61 ++- ets2panda/bindings/src/InteropTypes.ts | 44 +- ets2panda/bindings/src/Platform.ts | 69 ++- ets2panda/bindings/src/Wrapper.ts | 24 +- ets2panda/bindings/src/arktsConfigGenerate.ts | 19 +- ets2panda/bindings/src/arrays.ts | 179 ++++--- ets2panda/bindings/src/build/buildMode.ts | 31 +- .../bindings/src/build/generateArkTSConfig.ts | 59 +-- ets2panda/bindings/src/buildConfigGenerate.ts | 329 +++++++------ ets2panda/bindings/src/driver_helper.ts | 96 ++-- .../src/generated/Es2pandaNativeModule.ts | 32 +- ets2panda/bindings/src/global.ts | 76 +-- ets2panda/bindings/src/index.ts | 21 +- ets2panda/bindings/src/loadLibraries.ts | 29 +- ets2panda/bindings/src/lspNode.ts | 192 ++++---- ets2panda/bindings/src/lsp_helper.ts | 456 +++++++++--------- ets2panda/bindings/src/mainWrapper.ts | 18 +- ets2panda/bindings/src/preDefine.ts | 4 +- ets2panda/bindings/src/private.ts | 32 +- ets2panda/bindings/src/strings.ts | 203 ++++---- ets2panda/bindings/src/ts-reflection.ts | 10 +- ets2panda/bindings/src/types.ts | 132 +++-- ets2panda/bindings/src/ui_plugins_driver.ts | 44 +- ets2panda/bindings/src/utils.ts | 6 +- ets2panda/test/unit/lsp/get_completions.cpp | 6 +- 31 files changed, 1319 insertions(+), 1200 deletions(-) create mode 100644 ets2panda/bindings/.prettierignore create mode 100644 ets2panda/bindings/.prettierrc.json diff --git a/ets2panda/bindings/.prettierignore b/ets2panda/bindings/.prettierignore new file mode 100644 index 0000000000..752fdaad79 --- /dev/null +++ b/ets2panda/bindings/.prettierignore @@ -0,0 +1,22 @@ +# +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +native/ +dist/** +dist-test/** +node_modules/** +**.json +**.js +**.md diff --git a/ets2panda/bindings/.prettierrc.json b/ets2panda/bindings/.prettierrc.json new file mode 100644 index 0000000000..813963a821 --- /dev/null +++ b/ets2panda/bindings/.prettierrc.json @@ -0,0 +1,10 @@ +{ + "singleQuote": true, + "jsxSingleQuote": true, + "arrowParens": "always", + "printWidth": 120, + "tabWidth": 2, + "useTabs": false, + "semi": true, + "trailingComma": "none" +} diff --git a/ets2panda/bindings/native/include/dynamic-loader.h b/ets2panda/bindings/native/include/dynamic-loader.h index d99d7fa19f..ec4fc5077c 100644 --- a/ets2panda/bindings/native/include/dynamic-loader.h +++ b/ets2panda/bindings/native/include/dynamic-loader.h @@ -55,7 +55,8 @@ inline void *LoadLibrary(const std::string &libPath) return handle; } -inline const char *LibraryError() +// NOLINTNEXTLINE(modernize-redundant-void-arg) +inline const char *LibraryError(void) { return dlerror(); } diff --git a/ets2panda/bindings/native/src/win-dynamic-node.cpp b/ets2panda/bindings/native/src/win-dynamic-node.cpp index 5a7a68fc8b..85bb3cb4da 100644 --- a/ets2panda/bindings/native/src/win-dynamic-node.cpp +++ b/ets2panda/bindings/native/src/win-dynamic-node.cpp @@ -66,8 +66,9 @@ bool LoadNapiFunctions() FARPROC fn_addr = GetProcAddress(nodeModule, "napi_module_register"); if (fn_addr == NULL) { nodeModule = GetModuleHandleA("node.dll"); - if (nodeModule == NULL) + if (nodeModule == NULL) { return false; + } fn_addr = GetProcAddress(nodeModule, "napi_module_register"); if (fn_addr == NULL) { return false; @@ -87,8 +88,9 @@ bool LoadNapiFunctions() NAPI_FUNCTIONS(GET_NAPI_IMPL); // If any required APIs failed to load, return false - if (apiLoadFailed) + if (apiLoadFailed) { return false; + } isLoaded = true; diff --git a/ets2panda/bindings/package.json b/ets2panda/bindings/package.json index bd5a42e3f2..193f7b1b8a 100644 --- a/ets2panda/bindings/package.json +++ b/ets2panda/bindings/package.json @@ -5,6 +5,7 @@ "devDependencies": { "@tsconfig/recommended": "^1.0.2", "@types/node": "^18.0.0", + "prettier": "latest", "rimraf": "^6.0.1", "typescript": "4.9.5", "node-api-headers": "^1.4.0" @@ -14,7 +15,8 @@ "test": "echo \"Error: no test specified\" && exit 1", "compile": "tsc --build --verbose tsconfig.json", "clean": "rimraf dist tsconfig.tsbuildinfo package-lock.json", - "run": "npm run clean && npm run compile" + "run": "npm run clean && npm run compile", + "format": "npx prettier --write ." }, "author": "", "license": "ISC", diff --git a/ets2panda/bindings/src/Es2pandaNativeModule.ts b/ets2panda/bindings/src/Es2pandaNativeModule.ts index 7c08204701..89ed6a70f7 100644 --- a/ets2panda/bindings/src/Es2pandaNativeModule.ts +++ b/ets2panda/bindings/src/Es2pandaNativeModule.ts @@ -13,464 +13,478 @@ */ import * as fs from 'fs'; -import * as path from 'path' -import { KNativePointer as KPtr, KInt, KBoolean, KNativePointer, KDouble, KUInt, KStringPtr } from "./InteropTypes" -import { Es2pandaNativeModule as GeneratedEs2pandaNativeModule } from "./generated/Es2pandaNativeModule" -import { loadNativeModuleLibrary, registerNativeModuleLibraryName } from "./loadLibraries" -import { throwError } from "./utils" +import * as path from 'path'; +import { KNativePointer as KPtr, KInt, KBoolean, KNativePointer, KDouble, KUInt, KStringPtr } from './InteropTypes'; +import { Es2pandaNativeModule as GeneratedEs2pandaNativeModule } from './generated/Es2pandaNativeModule'; +import { loadNativeModuleLibrary, registerNativeModuleLibraryName } from './loadLibraries'; +import { throwError } from './utils'; -export type KPtrArray = BigUint64Array +export type KPtrArray = BigUint64Array; export class Es2pandaNativeModule { _ClassDefinitionSuper(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } - _CreateTSInterfaceDeclaration(_context: KPtr, _extends: KPtrArray, _extendsLen: KInt, _id: KPtr, _typeParams: KPtr, _body: KPtr, _isStatic: KBoolean, _isExternal: KBoolean): KPtr { - throw new Error("Not implemented") + _CreateTSInterfaceDeclaration( + _context: KPtr, + _extends: KPtrArray, + _extendsLen: KInt, + _id: KPtr, + _typeParams: KPtr, + _body: KPtr, + _isStatic: KBoolean, + _isExternal: KBoolean + ): KPtr { + throw new Error('Not implemented'); } _ContextState(context: KPtr): KInt { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ContextErrorMessage(context: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _AstNodeDumpModifiers(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CreateAstDumper(context: KPtr, node: KPtr, source: String): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CreateConfig(argc: number, argv: string[] | Uint8Array, pandaLibPath: KStringPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _DestroyConfig(config: KPtr): void { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CreateContextFromString(config: KPtr, source: String, filename: String): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } - _GenerateTsDeclarationsFromContext(config: KPtr, outputDeclEts: String, outputEts: String, exportAll: KBoolean): KPtr { - throw new Error("Not implemented") + _GenerateTsDeclarationsFromContext( + config: KPtr, + outputDeclEts: String, + outputEts: String, + exportAll: KBoolean + ): KPtr { + throw new Error('Not implemented'); } _CreateContextFromFile(config: KPtr, filename: String): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _DestroyContext(context: KPtr): void { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ProceedToState(context: KPtr, state: number): void { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ContextProgram(context: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ProgramAst(program: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CheckerStartChecker(context: KPtr): KBoolean { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _IsProgram(context: KPtr, node: KPtr): KBoolean { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _AstNodeDumpJsonConst(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _AstNodeDumpEtsSrcConst(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _AstNodeUpdateChildren(context: KPtr, node: KPtr): void { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _AstNodeUpdateAll(context: KPtr, node: KPtr): void { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _AstNodeSetOriginalNode(context: KPtr, ast: KPtr, originalNode: KPtr): void { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _AstNodeOriginalNodeConst(context: KPtr, ast: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _VarBinderSetProgram(context: KPtr): void { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _VarBinderSetContext(context: KPtr): void { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getCurrentTokenValue(context: KNativePointer, position: KInt): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getSemanticDiagnostics(context: KNativePointer): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getSyntacticDiagnostics(context: KNativePointer): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getDiags(ptr: KNativePointer): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getDiagMsg(ptr: KNativePointer): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getDiagSource(ptr: KNativePointer): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getDefinitionAtPosition(context: KNativePointer, position: KInt): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getFileNameFromDef(ptr: KNativePointer): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getStartFromDef(ptr: KPtr): KInt { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getLengthFromDef(ptr: KPtr): KInt { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getDiagRange(ptr: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getRangeEnd(ptr: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getRangeStart(ptr: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getPosLine(ptr: KPtr): KInt { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getPosChar(ptr: KPtr): KInt { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getDiagSeverity(ptr: KPtr): KInt { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getDiagCode(ptr: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getDiagCodeDescription(ptr: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getCodeDescriptionHref(ptr: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getDiagTags(ptr: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getDiagData(ptr: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getDiagRelatedInfo(ptr: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getRelatedInfoMsg(ptr: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getRelatedInfoLoc(ptr: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getLocUri(ptr: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getLocRange(ptr: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getImplementationAtPosition(context: KNativePointer, position: KInt): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getReferenceStart(ptr: KPtr): KInt { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getReferenceLength(ptr: KPtr): KInt { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getReferenceFileName(ptr: KNativePointer): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getReferencesFromRefs(ptr: KNativePointer): KPtr[] { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getReferenceInfos(ptr: KNativePointer): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getDeclInfo(context: KNativePointer, position: KInt): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getDeclInfoFileText(declInfo: KNativePointer): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getDeclInfoFileName(declInfo: KNativePointer): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getReferencesAtPosition(context: KNativePointer, declInfo: KNativePointer): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _isPackageModule(context: KNativePointer): boolean { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getFileReferences(filename: String, context: KNativePointer, isPackageModule: boolean): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getSpanOfEnclosingComment(filename: String, position: KInt): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getSuggestionDiagnostics(context: KNativePointer): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getQuickInfoAtPosition(filename: String, context: KNativePointer, position: KInt): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getDisplayPartsText(ptr: KNativePointer): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getDisplayPartsKind(ptr: KNativePointer): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getQuickInfoKind(ptr: KNativePointer): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getQuickInfoKindModifier(ptr: KNativePointer): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getQuickInfoFileName(ptr: KNativePointer): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getSymbolDisplayPart(ptr: KNativePointer): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getTextSpanStart(ptr: KNativePointer): KInt { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getTextSpanLength(ptr: KNativePointer): KInt { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getTextSpan(ptr: KNativePointer): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getHighlightFileName(ptr: KNativePointer): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getHighlightIsInString(ptr: KNativePointer): boolean { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getHighlightKind(ptr: KPtr): KInt { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getHighlightSpanFromHighlights(ptr: KNativePointer): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getDocumentHighlightsFromRef(ptr: KNativePointer): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getDocumentHighlights(context: KNativePointer, position: KInt): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getCompletionAtPosition(context: KNativePointer, position: KInt): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getFileNameFromEntryData(ptr: KNativePointer): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getNamedExportFromEntryData(ptr: KNativePointer): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getImportDeclarationFromEntryData(ptr: KNativePointer): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getStatusFromEntryData(ptr: KPtr): KInt { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getNameFromEntry(ptr: KNativePointer): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getSortTextFromEntry(ptr: KNativePointer): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getInsertTextFromEntry(ptr: KNativePointer): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getKindFromEntry(ptr: KPtr): KInt { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getDataFromEntry(ptr: KNativePointer): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getEntriesFromCompletionInfo(ptr: KNativePointer): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getUriFromLocation(ptr: KNativePointer): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getStartFromLocation(ptr: KNativePointer): KInt { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getEndFromLocation(ptr: KNativePointer): KInt { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getIsDefinitionFromLocation(ptr: KNativePointer): boolean { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getIsImportFromLocation(ptr: KNativePointer): boolean { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getAccessKindFromLocation(ptr: KPtr): KInt { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getLocationFromList(ptr: KNativePointer): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getLine(ptr: KNativePointer): KInt { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getChar(ptr: KNativePointer): KInt { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _toLineColumnOffset(context: KNativePointer, position: KInt): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } } export function initEs2panda(): Es2pandaNativeModule { - let libPath = process.env.BINDINGS_PATH - if (libPath == undefined) { - libPath = path.resolve(__dirname, "../ts_bindings.node") + let libPath = process.env.BINDINGS_PATH; + if (libPath === undefined) { + libPath = path.resolve(__dirname, '../ts_bindings.node'); } else { - libPath = path.join(libPath, "ts_bindings.node") + libPath = path.join(libPath, 'ts_bindings.node'); } if (!fs.existsSync(libPath)) { - throwError(`Cannot find lib path ${libPath}`) + throwError(`Cannot find lib path ${libPath}`); } - registerNativeModuleLibraryName("NativeModule", libPath) - const instance = new Es2pandaNativeModule() - loadNativeModuleLibrary("NativeModule", instance) - return instance + registerNativeModuleLibraryName('NativeModule', libPath); + const instance = new Es2pandaNativeModule(); + loadNativeModuleLibrary('NativeModule', instance); + return instance; } export function initGeneratedEs2panda(): GeneratedEs2pandaNativeModule { - let libPath = process.env.BINDINGS_PATH - if (libPath == undefined) { - libPath = path.resolve(__dirname, "../ts_bindings.node") + let libPath = process.env.BINDINGS_PATH; + if (libPath === undefined) { + libPath = path.resolve(__dirname, '../ts_bindings.node'); } else { - libPath = path.join(libPath, "ts_bindings.node") + libPath = path.join(libPath, 'ts_bindings.node'); } if (!fs.existsSync(libPath)) { - throwError(`Cannot find lib path ${libPath}`) + throwError(`Cannot find lib path ${libPath}`); } - registerNativeModuleLibraryName("NativeModule", libPath) - const instance = new GeneratedEs2pandaNativeModule() - loadNativeModuleLibrary("NativeModule", instance) - return instance + registerNativeModuleLibraryName('NativeModule', libPath); + const instance = new GeneratedEs2pandaNativeModule(); + loadNativeModuleLibrary('NativeModule', instance); + return instance; } export function initPublicEs2panda(): Es2pandaNativeModule { - let libPath = process.env.BINDINGS_PATH + let libPath = process.env.BINDINGS_PATH; if (libPath == undefined) { - libPath = path.resolve(__dirname, "../public.node") + libPath = path.resolve(__dirname, '../public.node'); } else { - libPath = path.join(libPath, "public.node") + libPath = path.join(libPath, 'public.node'); } if (!fs.existsSync(libPath)) { - throwError(`Cannot find lib path ${libPath}`) + throwError(`Cannot find lib path ${libPath}`); } - registerNativeModuleLibraryName("NativeModule", libPath) - const instance = new Es2pandaNativeModule() - loadNativeModuleLibrary("NativeModule", instance) - return instance + registerNativeModuleLibraryName('NativeModule', libPath); + const instance = new Es2pandaNativeModule(); + loadNativeModuleLibrary('NativeModule', instance); + return instance; } export function initPublicGeneratedEs2panda(): GeneratedEs2pandaNativeModule { - let libPath = process.env.BINDINGS_PATH + let libPath = process.env.BINDINGS_PATH; if (libPath == undefined) { - libPath = path.resolve(__dirname, "../public.node") + libPath = path.resolve(__dirname, '../public.node'); } else { - libPath = path.join(libPath, "public.node") + libPath = path.join(libPath, 'public.node'); } if (!fs.existsSync(libPath)) { - throwError(`Cannot find lib path ${libPath}`) + throwError(`Cannot find lib path ${libPath}`); } - registerNativeModuleLibraryName("NativeModule", libPath) - const instance = new GeneratedEs2pandaNativeModule() - loadNativeModuleLibrary("NativeModule", instance) - return instance + registerNativeModuleLibraryName('NativeModule', libPath); + const instance = new GeneratedEs2pandaNativeModule(); + loadNativeModuleLibrary('NativeModule', instance); + return instance; } diff --git a/ets2panda/bindings/src/InteropNativeModule.ts b/ets2panda/bindings/src/InteropNativeModule.ts index b659368edd..3531703067 100644 --- a/ets2panda/bindings/src/InteropNativeModule.ts +++ b/ets2panda/bindings/src/InteropNativeModule.ts @@ -14,78 +14,77 @@ */ import * as fs from 'fs'; -import * as path from 'path' -import { KNativePointer as KPtr, KInt, KUInt } from "./InteropTypes" -import { loadNativeModuleLibrary, registerNativeModuleLibraryName } from "./loadLibraries" -import { throwError } from "./utils" +import * as path from 'path'; +import { KNativePointer as KPtr, KInt, KUInt } from './InteropTypes'; +import { loadNativeModuleLibrary, registerNativeModuleLibraryName } from './loadLibraries'; +import { throwError } from './utils'; export class InteropNativeModule { - _StringLength(ptr: KPtr): KInt { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _StringData(ptr: KPtr, buffer: KPtr, length: KInt): void { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _GetStringFinalizer(): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _InvokeFinalizer(ptr: KPtr, finalizer: KPtr): void { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _GetPtrVectorSize(ptr: KPtr): KInt { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _GetPtrVectorElement(ptr: KPtr, index: KInt): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getTypeOfVariant(ptr: KPtr): KInt { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getIntFromVariant(ptr: KPtr): KInt { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _getStringFromVariant(ptr: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } } export function initInterop(): InteropNativeModule { - let libPath = process.env.BINDINGS_PATH - if (libPath == undefined) { - libPath = path.resolve(__dirname, "../ts_bindings.node") + let libPath = process.env.BINDINGS_PATH; + if (libPath === undefined) { + libPath = path.resolve(__dirname, '../ts_bindings.node'); } else { - libPath = path.join(libPath, "ts_bindings.node") + libPath = path.join(libPath, 'ts_bindings.node'); } if (!fs.existsSync(libPath)) { - throwError(`Cannot find lib path ${libPath}`) + throwError(`Cannot find lib path ${libPath}`); } - registerNativeModuleLibraryName("InteropNativeModule", libPath) - const instance = new InteropNativeModule() - loadNativeModuleLibrary("InteropNativeModule", instance) - return instance + registerNativeModuleLibraryName('InteropNativeModule', libPath); + const instance = new InteropNativeModule(); + loadNativeModuleLibrary('InteropNativeModule', instance); + return instance; } export function initPublicInterop(): InteropNativeModule { - let libPath = process.env.BINDINGS_PATH + let libPath = process.env.BINDINGS_PATH; if (libPath == undefined) { - libPath = path.resolve(__dirname, "../public.node") + libPath = path.resolve(__dirname, '../public.node'); } else { - libPath = path.join(libPath, "public.node") + libPath = path.join(libPath, 'public.node'); } if (!fs.existsSync(libPath)) { - throwError(`Cannot find lib path ${libPath}`) + throwError(`Cannot find lib path ${libPath}`); } - registerNativeModuleLibraryName("InteropNativeModule", libPath) - const instance = new InteropNativeModule() - loadNativeModuleLibrary("InteropNativeModule", instance) - return instance + registerNativeModuleLibraryName('InteropNativeModule', libPath); + const instance = new InteropNativeModule(); + loadNativeModuleLibrary('InteropNativeModule', instance); + return instance; } diff --git a/ets2panda/bindings/src/InteropTypes.ts b/ets2panda/bindings/src/InteropTypes.ts index 3e6d51a5a7..4a3a3d8678 100644 --- a/ets2panda/bindings/src/InteropTypes.ts +++ b/ets2panda/bindings/src/InteropTypes.ts @@ -13,26 +13,26 @@ * limitations under the License. */ -export const nullptr: int | bigint = BigInt(0) -export type int = number -export type int32 = int -export type int64 = int -export type float = number -export type float32 = float -export type float64 = float +export const nullptr: int | bigint = BigInt(0); +export type int = number; +export type int32 = int; +export type int64 = int; +export type float = number; +export type float32 = float; +export type float64 = float; -export type KStringPtr = int32 | string | null -export type KStringArrayPtr = int32 | Uint8Array | null -export type KInt32ArrayPtr = int32 | Int32Array | null -export type KFloat32ArrayPtr = int32 | Float32Array | null -export type KUint8ArrayPtr = int32 | Uint8Array | null -export type KInt = int32 -export type KUInt = int32 -export type KLong = int64 -export type KFloat = float32 -export type KDouble = float64 -export type KBoolean = int32 -export type KPointer = Uint8Array | number | bigint -export type pointer = KPointer -export type KNativePointer = KPointer -export type KNativePointerArray = BigUint64Array +export type KStringPtr = int32 | string | null; +export type KStringArrayPtr = int32 | Uint8Array | null; +export type KInt32ArrayPtr = int32 | Int32Array | null; +export type KFloat32ArrayPtr = int32 | Float32Array | null; +export type KUint8ArrayPtr = int32 | Uint8Array | null; +export type KInt = int32; +export type KUInt = int32; +export type KLong = int64; +export type KFloat = float32; +export type KDouble = float64; +export type KBoolean = int32; +export type KPointer = Uint8Array | number | bigint; +export type pointer = KPointer; +export type KNativePointer = KPointer; +export type KNativePointerArray = BigUint64Array; diff --git a/ets2panda/bindings/src/Platform.ts b/ets2panda/bindings/src/Platform.ts index 805e92003c..37c2159d2e 100644 --- a/ets2panda/bindings/src/Platform.ts +++ b/ets2panda/bindings/src/Platform.ts @@ -13,47 +13,46 @@ * limitations under the License. */ -import { isNullPtr } from "./Wrapper" -import { decodeToString } from "./arrays" -import { Wrapper } from "./mainWrapper" -import { global } from "./global" -import { int32, KPointer, nullptr } from "./InteropTypes" +import { isNullPtr } from './Wrapper'; +import { decodeToString } from './arrays'; +import { Wrapper } from './mainWrapper'; +import { global } from './global'; +import { int32, KInt, KPointer, nullptr } from './InteropTypes'; export abstract class NativeStringBase extends Wrapper { constructor(ptr: KPointer) { - super(ptr) + super(ptr); } - protected abstract bytesLength(): int32 - protected abstract getData(data: Uint8Array): void + protected abstract bytesLength(): int32; + protected abstract getData(data: Uint8Array): void; toString(): string { - let length = this.bytesLength() - let data = new Uint8Array(length) - this.getData(data) - return decodeToString(data) + let length = this.bytesLength(); + let data = new Uint8Array(length); + this.getData(data); + return decodeToString(data); } - abstract close(): void + abstract close(): void; } export abstract class ArrayDecoder { - abstract getArraySize(blob: KPointer): int32 - abstract disposeArray(blob: KPointer): void - abstract getArrayElement(blob: KPointer, index: int32): T + abstract getArraySize(blob: KPointer): int32; + abstract disposeArray(blob: KPointer): void; + abstract getArrayElement(blob: KPointer, index: int32): T; decode(blob: KPointer): Array { - const size = this.getArraySize(blob) - const result = new Array(size) + const size = this.getArraySize(blob); + const result = new Array(size); for (let index = 0; index < size; index++) { - result[index] = this.getArrayElement(blob, index) + result[index] = this.getArrayElement(blob, index); } - this.disposeArray(blob) - return result + this.disposeArray(blob); + return result; } } - // TODO: the semicolons after methods in these interfaces are to // workaround ArkTS compiler parser bug export interface CallbackRegistry { @@ -67,37 +66,37 @@ export interface PlatformDefinedData { } export function withStringResult(ptr: KPointer): string | undefined { - if (isNullPtr(ptr)) return undefined - let managedString = new NativeString(ptr) - let result = managedString?.toString() - managedString?.close() - return result + if (isNullPtr(ptr)) return undefined; + let managedString = new NativeString(ptr); + let result = managedString?.toString(); + managedString?.close(); + return result; } export class NativeString extends NativeStringBase { constructor(ptr: KPointer) { - super(ptr) + super(ptr); } protected bytesLength(): int32 { - return global.interop._StringLength(this.ptr) + return global.interop._StringLength(this.ptr); } protected getData(data: Uint8Array): void { - global.interop._StringData(this.ptr, data, data.length) + global.interop._StringData(this.ptr, data, data.length); } close(): void { - global.interop._InvokeFinalizer(this.ptr, global.interop._GetStringFinalizer()) - this.ptr = nullptr + global.interop._InvokeFinalizer(this.ptr, global.interop._GetStringFinalizer()); + this.ptr = nullptr; } } export class NativePtrDecoder extends ArrayDecoder { - getArraySize(blob: KPointer) { - return global.interop._GetPtrVectorSize(blob) + getArraySize(blob: KPointer): KInt { + return global.interop._GetPtrVectorSize(blob); } disposeArray(blob: KPointer): void { // TODO } getArrayElement(blob: KPointer, index: int32): KPointer { - return global.interop._GetPtrVectorElement(blob, index) + return global.interop._GetPtrVectorElement(blob, index); } } diff --git a/ets2panda/bindings/src/Wrapper.ts b/ets2panda/bindings/src/Wrapper.ts index b5d04420b5..66c17e8918 100644 --- a/ets2panda/bindings/src/Wrapper.ts +++ b/ets2panda/bindings/src/Wrapper.ts @@ -13,30 +13,30 @@ * limitations under the License. */ -import { int32, KPointer, nullptr } from "./InteropTypes" +import { int32, KPointer, nullptr } from './InteropTypes'; export function isNullPtr(value: KPointer): boolean { - return value === nullptr + return value === nullptr; } export function ptrToString(ptr: KPointer) { - return `0x${ptr!.toString(16).padStart(8, "0")}` + return `0x${ptr!.toString(16).padStart(8, '0')}`; } export function isSamePtr(a: KPointer, b: KPointer) { - return (a === b) + return a === b; } export function ptrToBits(ptr: KPointer): Uint32Array | null { - let result = new Uint32Array(2) - let ptrBigInt = ptr as bigint - result[0] = Number(ptrBigInt & BigInt(0xFFFFFFFF)) - result[1] = Number((ptrBigInt >> BigInt(32)) & BigInt(0xFFFFFFFF)) - return result + let result = new Uint32Array(2); + let ptrBigInt = ptr as bigint; + result[0] = Number(ptrBigInt & BigInt(0xffffffff)); + result[1] = Number((ptrBigInt >> BigInt(32)) & BigInt(0xffffffff)); + return result; } export function bitsToPtr(array: Int32Array, offset: int32): KPointer { - let ptrBigInt: bigint = BigInt(array[offset + 1]) & BigInt(0xFFFFFFFF) - ptrBigInt = (ptrBigInt << BigInt(32)) | (BigInt(array[offset]) & BigInt(0xFFFFFFFF)) - return ptrBigInt + let ptrBigInt: bigint = BigInt(array[offset + 1]) & BigInt(0xffffffff); + ptrBigInt = (ptrBigInt << BigInt(32)) | (BigInt(array[offset]) & BigInt(0xffffffff)); + return ptrBigInt; } diff --git a/ets2panda/bindings/src/arktsConfigGenerate.ts b/ets2panda/bindings/src/arktsConfigGenerate.ts index 78a2cfd1d8..56f00052ed 100644 --- a/ets2panda/bindings/src/arktsConfigGenerate.ts +++ b/ets2panda/bindings/src/arktsConfigGenerate.ts @@ -16,9 +16,7 @@ import { BuildMode } from './build/buildMode'; import { BuildConfig } from './types'; import { ModuleDescriptor, generateBuildConfigs } from './buildConfigGenerate'; -import { - PANDA_SDK_PATH_FROM_SDK -} from './preDefine'; +import { PANDA_SDK_PATH_FROM_SDK } from './preDefine'; import * as fs from 'fs'; import * as path from 'path'; @@ -32,15 +30,16 @@ function processBuildConfig(projectConfig: BuildConfig): BuildConfig { return buildConfig; } -export function generateArkTsConfigByModules(buildSdkPath: string, projectRoot: string, modules?: ModuleDescriptor[]) { +export function generateArkTsConfigByModules( + buildSdkPath: string, + projectRoot: string, + modules?: ModuleDescriptor[] +): void { const allBuildConfig = generateBuildConfigs(buildSdkPath, projectRoot, modules); let compileFileInfos: Record = {}; const cacheDir = path.join(projectRoot, '.idea', '.deveco'); - const compileFileInfosPath = path.join( - cacheDir, - 'lsp_compileFileInfos.json' - ) - Object.keys(allBuildConfig).forEach(moduleName => { + const compileFileInfosPath = path.join(cacheDir, 'lsp_compileFileInfos.json'); + Object.keys(allBuildConfig).forEach((moduleName) => { const moduleConfig = allBuildConfig[moduleName] as BuildConfig; const processedConfig = processBuildConfig(moduleConfig); @@ -49,7 +48,7 @@ export function generateArkTsConfigByModules(buildSdkPath: string, projectRoot: }); try { const jsonCompileFileInfos = JSON.stringify(compileFileInfos, null, 2); - if (!fs.existsSync(cacheDir)) { + if (!fs.existsSync(cacheDir)) { fs.mkdirSync(cacheDir, { recursive: true }); } fs.writeFileSync(compileFileInfosPath, jsonCompileFileInfos, 'utf-8'); diff --git a/ets2panda/bindings/src/arrays.ts b/ets2panda/bindings/src/arrays.ts index 9f2ca7629d..54d05cb613 100644 --- a/ets2panda/bindings/src/arrays.ts +++ b/ets2panda/bindings/src/arrays.ts @@ -13,126 +13,155 @@ * limitations under the License. */ -import { KPointer, int32 } from "./InteropTypes" -import { Wrapper } from "./mainWrapper" -import { CustomTextDecoder, CustomTextEncoder } from "./strings" -import { throwError } from "./utils" +import { KPointer, int32 } from './InteropTypes'; +import { Wrapper } from './mainWrapper'; +import { CustomTextDecoder, CustomTextEncoder } from './strings'; +import { throwError } from './utils'; -const encoder = new CustomTextEncoder() -const decoder = new CustomTextDecoder() +const encoder = new CustomTextEncoder(); +const decoder = new CustomTextDecoder(); export function decodeToString(array: Uint8Array): string { - return decoder.decode(array) + return decoder.decode(array); } export function encodeToData(string: string): Uint8Array { - return encoder.encode(string, false) + return encoder.encode(string, false); } export function withString(data: string, exec: Exec): R { - return exec(data) + return exec(data); } export function withStringArray(strings: Array | undefined): Uint8Array { if (strings === undefined || strings.length === 0) { - throwError('Error in strings array') + throwError('Error in strings array'); } - let array = encoder.encodeArray(strings) - return array + let array = encoder.encodeArray(strings); + return array; } -function withArray( - data: C | undefined, - exec: ExecWithLength -): R { - return exec(data ?? null, data?.length ?? 0) +function withArray(data: C | undefined, exec: ExecWithLength): R { + return exec(data ?? null, data?.length ?? 0); } export function withPtrArray(data: BigUint64Array, access: Access, exec: ExecWithLength) { - return exec(data ?? null, data?.length ?? 0) // TODO rethink + return exec(data ?? null, data?.length ?? 0); // TODO rethink } export function toPtrArray(data: Array | undefined): BigUint64Array { - if (data == undefined || data.length === 0) { - return new BigUint64Array(0) - } - const array = new BigUint64Array(data.length) - for (let i = 0; i < data.length; i++) { - let item = data[i] - array[i] = item != undefined ? item.ptr as bigint : nullptr - } - return array + if (data == undefined || data.length === 0) { + return new BigUint64Array(0); + } + const array = new BigUint64Array(data.length); + for (let i = 0; i < data.length; i++) { + let item = data[i]; + array[i] = item != undefined ? (item.ptr as bigint) : nullptr; + } + return array; } -export function fromPtrArray(array: PtrArray, factory: (ptr: KPointer) => T) : Array { - if (array.length === 0) { - return new Array(0) - } - const result = new Array(array.length) - for (let i = 0; i < array.length; i++) { - let ptr = array[i] - if (ptr == nullptr) { - result[i] = undefined - } else { - result[i] = factory(ptr) - } +export function fromPtrArray(array: PtrArray, factory: (ptr: KPointer) => T): Array { + if (array.length === 0) { + return new Array(0); + } + const result = new Array(array.length); + for (let i = 0; i < array.length; i++) { + let ptr = array[i]; + if (ptr == nullptr) { + result[i] = undefined; + } else { + result[i] = factory(ptr); } - return result -} - -export function withUint8Array(data: Uint8Array | undefined, access: Access, exec: ExecWithLength): T { - return withArray(data, exec) -} -export function withInt8Array(data: Int8Array | undefined, access: Access, exec: ExecWithLength) { - return withArray(data, exec) -} -export function withUint16Array(data: Uint16Array | undefined, access: Access, exec: ExecWithLength) { - return withArray(data, exec) -} -export function withInt16Array(data: Int16Array | undefined, access: Access, exec: ExecWithLength) { - return withArray(data, exec) -} -export function withUint32Array(data: Uint32Array | undefined, access: Access, exec: ExecWithLength) { - return withArray(data, exec) -} -export function withInt32Array(data: Int32Array | undefined, access: Access, exec: ExecWithLength) { - return withArray(data, exec) -} -export function withFloat32Array(data: Float32Array | undefined, access: Access, exec: ExecWithLength) { - return withArray(data, exec) -} -export function withFloat64Array(data: Float64Array | undefined, access: Access, exec: ExecWithLength) { - return withArray(data, exec) + } + return result; +} + +export function withUint8Array( + data: Uint8Array | undefined, + access: Access, + exec: ExecWithLength +): T { + return withArray(data, exec); +} +export function withInt8Array( + data: Int8Array | undefined, + access: Access, + exec: ExecWithLength +) { + return withArray(data, exec); +} +export function withUint16Array( + data: Uint16Array | undefined, + access: Access, + exec: ExecWithLength +) { + return withArray(data, exec); +} +export function withInt16Array( + data: Int16Array | undefined, + access: Access, + exec: ExecWithLength +) { + return withArray(data, exec); +} +export function withUint32Array( + data: Uint32Array | undefined, + access: Access, + exec: ExecWithLength +) { + return withArray(data, exec); +} +export function withInt32Array( + data: Int32Array | undefined, + access: Access, + exec: ExecWithLength +) { + return withArray(data, exec); +} +export function withFloat32Array( + data: Float32Array | undefined, + access: Access, + exec: ExecWithLength +) { + return withArray(data, exec); +} +export function withFloat64Array( + data: Float64Array | undefined, + access: Access, + exec: ExecWithLength +) { + return withArray(data, exec); } export function wasmHeap(): ArrayBuffer { - throw new Error("Unused") + throw new Error('Unused'); } export enum Access { READ = 1, // 1 << 0, WRITE = 2, // 1 << 1, - READWRITE = 3, // READ | WRITE + READWRITE = 3 // READ | WRITE } export function isRead(access: Access) { - return access & Access.READ + return access & Access.READ; } export function isWrite(access: Access) { - return access & Access.WRITE + return access & Access.WRITE; } -export type Exec = (pointer: P) => R -export type ExecWithLength = (pointer: P, length: int32) => R +export type Exec = (pointer: P) => R; +export type ExecWithLength = (pointer: P, length: int32) => R; export type TypedArray = - Uint8Array + | Uint8Array | Int8Array | Uint16Array | Int16Array | Uint32Array | Int32Array | Float32Array - | Float64Array + | Float64Array; -export const nullptr: bigint = BigInt(0) -export type PtrArray = Uint32Array | BigUint64Array +export const nullptr: bigint = BigInt(0); +export type PtrArray = Uint32Array | BigUint64Array; diff --git a/ets2panda/bindings/src/build/buildMode.ts b/ets2panda/bindings/src/build/buildMode.ts index 172ac4847f..d1be834b99 100644 --- a/ets2panda/bindings/src/build/buildMode.ts +++ b/ets2panda/bindings/src/build/buildMode.ts @@ -15,20 +15,9 @@ import * as path from 'path'; -import { - ABC_SUFFIX, - ARKTSCONFIG_JSON_FILE, - LANGUAGE_VERSION, -} from '../preDefine'; -import { - changeFileExtension, -} from '../utils'; -import { - BuildConfig, - DependentModuleConfig, - ModuleInfo, - CompileFileInfo -} from '../types'; +import { ABC_SUFFIX, ARKTSCONFIG_JSON_FILE, LANGUAGE_VERSION } from '../preDefine'; +import { changeFileExtension } from '../utils'; +import { BuildConfig, DependentModuleConfig, ModuleInfo, CompileFileInfo } from '../types'; import { ArkTSConfigGenerator } from './generateArkTSConfig'; export class BuildMode { @@ -77,8 +66,9 @@ export class BuildMode { if (module.isMainModule) { return; } - module.language === LANGUAGE_VERSION.ARKTS_1_2 ? - staticDepModules.set(packageName, module) : dynamicDepModules.set(packageName, module); + module.language === LANGUAGE_VERSION.ARKTS_1_2 + ? staticDepModules.set(packageName, module) + : dynamicDepModules.set(packageName, module); }); return [dynamicDepModules, staticDepModules]; } @@ -89,8 +79,9 @@ export class BuildMode { if (!depModuleInfo) { console.error(`Module ${packageName} not found in moduleInfos`); } else { - depModuleInfo.language === LANGUAGE_VERSION.ARKTS_1_2 ? - staticDepModules.set(packageName, depModuleInfo) : dynamicDepModules.set(packageName, depModuleInfo); + depModuleInfo.language === LANGUAGE_VERSION.ARKTS_1_2 + ? staticDepModules.set(packageName, depModuleInfo) + : dynamicDepModules.set(packageName, depModuleInfo); } }); } @@ -132,7 +123,7 @@ export class BuildMode { compileFileInfos: [], declgenV1OutPath: this.declgenV1OutPath, declgenBridgeCodePath: this.declgenBridgeCodePath - } + }; this.moduleInfos.set(this.packageName, mainModuleInfo); this.dependentModuleList.forEach((module: DependentModuleConfig) => { if (!module.packageName || !module.modulePath || !module.sourceRoots || !module.entryFile) { @@ -154,7 +145,7 @@ export class BuildMode { language: module.language, declFilesPath: module.declFilesPath, dependencies: module.dependencies - } + }; this.moduleInfos.set(module.packageName, moduleInfo); }); this.collectDepModuleInfos(); diff --git a/ets2panda/bindings/src/build/generateArkTSConfig.ts b/ets2panda/bindings/src/build/generateArkTSConfig.ts index a981dfb5cd..fe1dc108fc 100644 --- a/ets2panda/bindings/src/build/generateArkTSConfig.ts +++ b/ets2panda/bindings/src/build/generateArkTSConfig.ts @@ -16,35 +16,26 @@ import * as path from 'path'; import * as fs from 'fs'; -import { - changeFileExtension, - ensurePathExists -} from '../utils'; -import { - BuildConfig, - ModuleInfo -} from '../types'; -import { - LANGUAGE_VERSION, - SYSTEM_SDK_PATH_FROM_SDK -} from '../preDefine'; +import { changeFileExtension, ensurePathExists } from '../utils'; +import { BuildConfig, ModuleInfo } from '../types'; +import { LANGUAGE_VERSION, SYSTEM_SDK_PATH_FROM_SDK } from '../preDefine'; interface DynamicPathItem { - language: string, - declPath: string, - runtimeName: string + language: string; + declPath: string; + runtimeName: string; } interface ArkTSConfigObject { compilerOptions: { - package: string, - baseUrl: string, + package: string; + baseUrl: string; paths: Record; dependencies: string[] | undefined; entry: string; dynamicPaths: Record; - } -}; + }; +} export class ArkTSConfigGenerator { private static instance: ArkTSConfigGenerator | undefined; @@ -56,8 +47,8 @@ export class ArkTSConfigGenerator { private pathSection: Record; private constructor(buildConfig: BuildConfig, moduleInfos: Map) { - let pandaStdlibPath: string = buildConfig.pandaStdlibPath ?? - path.resolve(buildConfig.pandaSdkPath!!, 'lib', 'stdlib'); + let pandaStdlibPath: string = + buildConfig.pandaStdlibPath ?? path.resolve(buildConfig.pandaSdkPath!!, 'lib', 'stdlib'); this.stdlibStdPath = path.resolve(pandaStdlibPath, 'std'); this.stdlibEscompatPath = path.resolve(pandaStdlibPath, 'escompat'); this.systemSdkPath = path.resolve(buildConfig.buildSdkPath, SYSTEM_SDK_PATH_FROM_SDK); @@ -69,8 +60,7 @@ export class ArkTSConfigGenerator { public static getInstance(buildConfig?: BuildConfig, moduleInfos?: Map): ArkTSConfigGenerator { if (!ArkTSConfigGenerator.instance) { if (!buildConfig || !moduleInfos) { - throw new Error( - 'buildConfig and moduleInfos is required for the first instantiation of ArkTSConfigGenerator.'); + throw new Error('buildConfig and moduleInfos is required for the first instantiation of ArkTSConfigGenerator.'); } ArkTSConfigGenerator.instance = new ArkTSConfigGenerator(buildConfig, moduleInfos); } @@ -86,7 +76,7 @@ export class ArkTSConfigGenerator { } private generateSystemSdkPathSection(pathSection: Record): void { - function traverse(currentDir: string, relativePath: string = '', isExcludedDir: boolean = false) { + function traverse(currentDir: string, relativePath: string = '', isExcludedDir: boolean = false): void { const items = fs.readdirSync(currentDir); for (const item of items) { const itemPath = path.join(currentDir, item); @@ -94,7 +84,7 @@ export class ArkTSConfigGenerator { if (stat.isFile()) { const basename = path.basename(item, '.d.ets'); - const key = isExcludedDir ? basename : (relativePath ? `${relativePath}.${basename}` : basename); + const key = isExcludedDir ? basename : relativePath ? `${relativePath}.${basename}` : basename; pathSection[key] = [changeFileExtension(itemPath, '', '.d.ets')]; } if (stat.isDirectory()) { @@ -103,7 +93,7 @@ export class ArkTSConfigGenerator { // For arkui files under api dir, // fill path section with `"fileName" = [${absolute_path_to_file}]`. const isCurrentDirExcluded = path.basename(currentDir) === 'arkui' && item === 'runtime-api'; - const newRelativePath = isCurrentDirExcluded ? '' : (relativePath ? `${relativePath}.${item}` : item); + const newRelativePath = isCurrentDirExcluded ? '' : relativePath ? `${relativePath}.${item}` : item; traverse(path.resolve(currentDir, item), newRelativePath, isCurrentDirExcluded || isExcludedDir); } } @@ -124,18 +114,15 @@ export class ArkTSConfigGenerator { return this.pathSection; } - this.pathSection['std'] = [this.stdlibStdPath]; - this.pathSection['escompat'] = [this.stdlibEscompatPath]; + this.pathSection.std = [this.stdlibStdPath]; + this.pathSection.escompat = [this.stdlibEscompatPath]; this.generateSystemSdkPathSection(this.pathSection); this.moduleInfos.forEach((moduleInfo: ModuleInfo, packageName: string) => { if (moduleInfo.language === LANGUAGE_VERSION.ARKTS_1_2) { - this.pathSection[moduleInfo.packageName] = [ - path.resolve(moduleInfo.moduleRootPath, moduleInfo.sourceRoots[0]) - ] + this.pathSection[moduleInfo.packageName] = [path.resolve(moduleInfo.moduleRootPath, moduleInfo.sourceRoots[0])]; } - }); return this.pathSection; @@ -154,7 +141,7 @@ export class ArkTSConfigGenerator { return changeFileExtension(ohmurl, ''); } - private getDynamicPathSection(moduleInfo: ModuleInfo, dynamicPathSection: Record) { + private getDynamicPathSection(moduleInfo: ModuleInfo, dynamicPathSection: Record): void { let depModules: Map = moduleInfo.dynamicDepModuleInfos; depModules.forEach((depModuleInfo: ModuleInfo) => { @@ -167,10 +154,10 @@ export class ArkTSConfigGenerator { Object.keys(declFilesObject.files).forEach((file: string) => { let ohmurl: string = this.getOhmurl(file, depModuleInfo); dynamicPathSection[ohmurl] = { - language: "js", + language: 'js', declPath: declFilesObject.files[file].declPath, runtimeName: declFilesObject.files[file].ohmUrl - } + }; let absFilePath: string = path.resolve(depModuleInfo.moduleRootPath, file); let entryFileWithoutExtension: string = changeFileExtension(depModuleInfo.entryFile, ''); @@ -182,7 +169,7 @@ export class ArkTSConfigGenerator { } public writeArkTSConfigFile(moduleInfo: ModuleInfo): void { - if (!moduleInfo.sourceRoots || moduleInfo.sourceRoots.length == 0) { + if (!moduleInfo.sourceRoots || moduleInfo.sourceRoots.length === 0) { console.error('SourceRoots not set from hvigor.'); } let pathSection = this.getPathSection(); diff --git a/ets2panda/bindings/src/buildConfigGenerate.ts b/ets2panda/bindings/src/buildConfigGenerate.ts index 88d1f1fe11..fa34184ed1 100644 --- a/ets2panda/bindings/src/buildConfigGenerate.ts +++ b/ets2panda/bindings/src/buildConfigGenerate.ts @@ -16,188 +16,215 @@ import * as fs from 'fs'; import * as path from 'path'; import * as JSON5 from 'json5'; +import { BuildConfig } from './types'; export interface ModuleDescriptor { - arktsversion: string; + arktsversion: string; + name: string; + moduleType: string; + srcPath: string; +} + +interface Json5Object { + module?: { + type?: string; + }; + modules?: Array<{ name: string; - moduleType: string; srcPath: string; + arktsversion?: string; + }>; + dependencies?: { + [packageName: string]: string; + }; } function removeTrailingCommas(jsonString: string): string { - return jsonString.replace(/,\s*([}\]])/g, '$1'); + return jsonString.replace(/,\s*([}\]])/g, '$1'); } -function parseJson5(filePath: string) { - try { - const rawContent = fs.readFileSync(filePath, 'utf8'); - const cleanedContent = removeTrailingCommas(rawContent); - return JSON5.parse(cleanedContent); - } catch (error) { - console.error(`Error parsing ${filePath}:`, error); - process.exit(1); - } +function parseJson5(filePath: string): Json5Object { + try { + const rawContent = fs.readFileSync(filePath, 'utf8'); + const cleanedContent = removeTrailingCommas(rawContent); + return JSON5.parse(cleanedContent) as Json5Object; + } catch (error) { + console.error(`Error parsing ${filePath}:`, error); + process.exit(1); + } } function getModuleTypeFromConfig(modulePath: string): string { - const moduleConfigPath = path.join(modulePath, 'src/main/module.json5'); - if (fs.existsSync(moduleConfigPath)) { - try { - const moduleData = parseJson5(moduleConfigPath); - return moduleData.module?.type || "har"; - } catch (error) { - console.error(`Error parsing ${moduleConfigPath}:`, error); - } + const moduleConfigPath = path.join(modulePath, 'src/main/module.json5'); + if (fs.existsSync(moduleConfigPath)) { + try { + const moduleData = parseJson5(moduleConfigPath); + return moduleData.module?.type || 'har'; + } catch (error) { + console.error(`Error parsing ${moduleConfigPath}:`, error); } - return "har"; + } + return 'har'; } function getModulesFromBuildProfile(buildProfilePath: string): ModuleDescriptor[] { - if (!fs.existsSync(buildProfilePath)) { - console.error("Error: build-profile.json5 not found"); - process.exit(1); - } - - const buildProfile = parseJson5(buildProfilePath); - const modules = buildProfile.modules || []; - - return modules.map((module: any) => { - const moduleSrcPath = path.resolve(path.dirname(buildProfilePath), module.srcPath); - const arktsversion = module.arktsversion || "1.1"; - return { - name: module.name, - moduleType: getModuleTypeFromConfig(moduleSrcPath), - srcPath: moduleSrcPath, - arktsversion - }; - }); + if (!fs.existsSync(buildProfilePath)) { + console.error('Error: build-profile.json5 not found'); + process.exit(1); + } + + const buildProfile = parseJson5(buildProfilePath); + const modules = buildProfile.modules || []; + + return modules.map((module: { name: string; srcPath: string; arktsversion?: string }) => { + const moduleSrcPath = path.resolve(path.dirname(buildProfilePath), module.srcPath); + const arktsversion = module.arktsversion || '1.1'; + return { + name: module.name, + moduleType: getModuleTypeFromConfig(moduleSrcPath), + srcPath: moduleSrcPath, + arktsversion + }; + }); } function getEtsFiles(modulePath: string): string[] { - const files: string[] = []; - - const shouldSkipDirectory = (relativePath: string): boolean => { - const testDir1 = `src${path.sep}test`; - const testDir2 = `src${path.sep}ohosTest`; - return relativePath.startsWith(testDir1) || relativePath.startsWith(testDir2); - }; - - const processEntry = (dir: string, entry: fs.Dirent) => { - const fullPath = path.join(dir, entry.name); - const relativePath = path.relative(modulePath, fullPath); - - if (entry.isDirectory()) { - if (shouldSkipDirectory(relativePath)) return; - traverseDir(fullPath); - return; - } + const files: string[] = []; + + const shouldSkipDirectory = (relativePath: string): boolean => { + const testDir1 = `src${path.sep}test`; + const testDir2 = `src${path.sep}ohosTest`; + return relativePath.startsWith(testDir1) || relativePath.startsWith(testDir2); + }; + + const processEntry = (dir: string, entry: fs.Dirent): void => { + const fullPath = path.join(dir, entry.name); + const relativePath = path.relative(modulePath, fullPath); + + if (entry.isDirectory()) { + if (shouldSkipDirectory(relativePath)) { + return; + } + traverseDir(fullPath); + return; + } - if (entry.isFile() && entry.name.endsWith('.ets')) { - files.push(fullPath); - } - }; + if (entry.isFile() && entry.name.endsWith('.ets')) { + files.push(fullPath); + } + }; - const traverseDir = (dir: string) => { - if (!fs.existsSync(dir)) return; + const traverseDir = (dir: string): void => { + if (!fs.existsSync(dir)) { + return; + } - const entries = fs.readdirSync(dir, { withFileTypes: true }); - entries.forEach(entry => processEntry(dir, entry)); - }; + const entries = fs.readdirSync(dir, { withFileTypes: true }); + entries.forEach((entry) => processEntry(dir, entry)); + }; - traverseDir(modulePath); - return files; + traverseDir(modulePath); + return files; } function getModuleDependencies(modulePath: string, visited = new Set()): string[] { - if (visited.has(modulePath)) return []; - visited.add(modulePath); - - const extractDependencies = (): string[] => { - const packageFilePath = path.join(modulePath, 'oh-package.json5'); - if (!fs.existsSync(packageFilePath)) return []; - - try { - const packageData = parseJson5(packageFilePath); - return Object.entries(packageData.dependencies || {}) - .map(([_, depPath]) => (depPath as string).replace('file:', '')) - .map(depPath => path.resolve(modulePath, depPath)); - } catch (error) { - console.error(`Error parsing ${packageFilePath}:`, error); - return []; - } - }; + if (visited.has(modulePath)) { + return []; + } + visited.add(modulePath); + + const extractDependencies = (): string[] => { + const packageFilePath = path.join(modulePath, 'oh-package.json5'); + if (!fs.existsSync(packageFilePath)) { + return []; + } - const resolveNestedDependencies = (deps: string[]): string[] => { - return deps.flatMap(depPath => - visited.has(depPath) ? [] : [depPath, ...getModuleDependencies(depPath, visited)] - ); - }; + try { + const packageData = parseJson5(packageFilePath); + return Object.entries(packageData.dependencies || {}) + .map(([_, depPath]) => (depPath as string).replace('file:', '')) + .map((depPath) => path.resolve(modulePath, depPath)); + } catch (error) { + console.error(`Error parsing ${packageFilePath}:`, error); + return []; + } + }; - const dependencies = extractDependencies(); - const nestedDependencies = resolveNestedDependencies(dependencies); - return Array.from(new Set([...dependencies, ...nestedDependencies])); -} + const resolveNestedDependencies = (deps: string[]): string[] => { + return deps.flatMap((depPath) => + visited.has(depPath) ? [] : [depPath, ...getModuleDependencies(depPath, visited)] + ); + }; -export function generateBuildConfigs(buildSdkPath: string, projectRoot: string, modules?: ModuleDescriptor[]): Record { - const allBuildConfigs: Record = {}; + const dependencies = extractDependencies(); + const nestedDependencies = resolveNestedDependencies(dependencies); + return Array.from(new Set([...dependencies, ...nestedDependencies])); +} - if (!modules) { - const buildProfilePath = path.join(projectRoot, 'build-profile.json5'); - modules = getModulesFromBuildProfile(buildProfilePath); +export function generateBuildConfigs( + buildSdkPath: string, + projectRoot: string, + modules?: ModuleDescriptor[] +): Record { + const allBuildConfigs: Record = {}; + + if (!modules) { + const buildProfilePath = path.join(projectRoot, 'build-profile.json5'); + modules = getModulesFromBuildProfile(buildProfilePath); + } + + const definedModules = modules; + const cacheDir = path.join(projectRoot, '.idea', '.deveco'); + + for (const module of definedModules) { + const modulePath = module.srcPath; + const compileFiles = new Set(getEtsFiles(modulePath)); + + // Get recursive dependencies + const dependencies = getModuleDependencies(modulePath); + for (const depPath of dependencies) { + getEtsFiles(depPath).forEach((file) => compileFiles.add(file)); } - const definedModules = modules; - const cacheDir = path.join(projectRoot, '.idea', '.deveco') - - for (const module of definedModules) { - const modulePath = module.srcPath; - const compileFiles = new Set(getEtsFiles(modulePath)); - - // Get recursive dependencies - const dependencies = getModuleDependencies(modulePath); - for (const depPath of dependencies) { - getEtsFiles(depPath).forEach(file => compileFiles.add(file)); - } - - const buildConfig = { - plugins: { - "ui-plugins": path.join(buildSdkPath, 'build-tools', 'ui-plugins', 'lib', 'ui-plugins', 'index'), - "memo-plugin": path.join(buildSdkPath, 'build-tools', 'ui-plugins', 'lib', 'memo-plugins', 'index') - }, - compileFiles: Array.from(compileFiles), - packageName: module.name, - moduleType: module.moduleType, - buildType: "build", - buildMode: "Debug", - moduleRootPath: modulePath, - sourceRoots: ["./"], - hasMainModule: true, - loaderOutPath: path.join(modulePath, 'build', 'default', 'cache'), - cachePath: cacheDir, - buildSdkPath: buildSdkPath, - enableDeclgenEts2Ts: false, - declgenDtsOutPath: path.join(modulePath, 'build', 'default', 'cache'), - declgenTsOutPath: path.join(modulePath, 'build', 'default', 'cache'), - dependentModuleList: dependencies.map(dep => { - const depModule = definedModules.find(m => m.srcPath === dep); - return { - packageName: path.basename(dep), - moduleName: path.basename(dep), - moduleType: depModule ? depModule.moduleType : "har", - modulePath: dep, - sourceRoots: ["./"], - entryFile: "index.ets", - language: depModule ? depModule.arktsversion : "1.1" - }; - }) + allBuildConfigs[module.name] = { + plugins: { + 'ui-plugins': path.join(buildSdkPath, 'build-tools', 'ui-plugins', 'lib', 'ui-plugins', 'index'), + 'memo-plugin': path.join(buildSdkPath, 'build-tools', 'ui-plugins', 'lib', 'memo-plugins', 'index') + }, + arkts: {}, + arktsGlobal: {}, + compileFiles: Array.from(compileFiles), + packageName: module.name, + moduleType: module.moduleType, + buildType: 'build', + buildMode: 'Debug', + moduleRootPath: modulePath, + sourceRoots: ['./'], + hasMainModule: true, + loaderOutPath: path.join(modulePath, 'build', 'default', 'cache'), + cachePath: cacheDir, + buildSdkPath: buildSdkPath, + enableDeclgenEts2Ts: false, + declgenDtsOutPath: path.join(modulePath, 'build', 'default', 'cache'), + declgenTsOutPath: path.join(modulePath, 'build', 'default', 'cache'), + dependentModuleList: dependencies.map((dep) => { + const depModule = definedModules.find((m) => m.srcPath === dep); + return { + packageName: path.basename(dep), + moduleName: path.basename(dep), + moduleType: depModule ? depModule.moduleType : 'har', + modulePath: dep, + sourceRoots: ['./'], + entryFile: 'index.ets', + language: depModule ? depModule.arktsversion : '1.1' }; - - allBuildConfigs[module.name] = buildConfig; - } - const outputPath = path.join(cacheDir, 'lsp_build_config.json'); - if (!fs.existsSync(cacheDir)) { - fs.mkdirSync(cacheDir, { recursive: true }); - } - fs.writeFileSync(outputPath, JSON.stringify(allBuildConfigs, null, 4)); - return allBuildConfigs; + }) + }; + } + const outputPath = path.join(cacheDir, 'lsp_build_config.json'); + if (!fs.existsSync(cacheDir)) { + fs.mkdirSync(cacheDir, { recursive: true }); + } + fs.writeFileSync(outputPath, JSON.stringify(allBuildConfigs, null, 4)); + return allBuildConfigs; } diff --git a/ets2panda/bindings/src/driver_helper.ts b/ets2panda/bindings/src/driver_helper.ts index 2553ce7f96..29f82f3d01 100644 --- a/ets2panda/bindings/src/driver_helper.ts +++ b/ets2panda/bindings/src/driver_helper.ts @@ -13,111 +13,111 @@ * limitations under the License. */ -import { Context, Config } from "./types" -import { global } from "./global" -import { throwError } from "./utils" -import { Es2pandaContextState } from "./generated/Es2pandaEnums" -import { withStringResult } from "./Platform" -import { KBoolean, KNativePointer, KPointer } from "./InteropTypes" +import { Context, Config } from './types'; +import { global } from './global'; +import { throwError } from './utils'; +import { Es2pandaContextState } from './generated/Es2pandaEnums'; +import { withStringResult } from './Platform'; +import { KBoolean, KNativePointer, KPointer } from './InteropTypes'; export class DriverHelper { constructor(filePath: string, cmd: string[]) { - this._filePath = filePath - global.filePath = this._filePath - this._cfg = Config.create(cmd, filePath) + this._filePath = filePath; + global.filePath = this._filePath; + this._cfg = Config.create(cmd, filePath); } - private _ctx: Context | undefined - private _cfg: Config - private _filePath: string + private _ctx: Context | undefined; + private _cfg: Config; + private _filePath: string; public createCtx(source: string): KPointer { - this._ctx = Context.createFromString(source) - return this._ctx.peer + this._ctx = Context.createFromString(source); + return this._ctx.peer; } public toString(): string { - return `DriverHelper (filepath = ${this._filePath}, config = ${this._cfg}, context = ${this._ctx})` + return `DriverHelper (filepath = ${this._filePath}, config = ${this._cfg}, context = ${this._ctx})`; } - public proceedToState(state: Es2pandaContextState) { + public proceedToState(state: Es2pandaContextState): void { if (this._ctx === undefined) { - throwError("Trying to proceed to state while cts is undefined") + throwError('Trying to proceed to state while cts is undefined'); } if (state <= global.es2panda._ContextState(this._ctx.peer)) { - return + return; } try { - global.es2panda._ProceedToState(this._ctx.peer, state) + global.es2panda._ProceedToState(this._ctx.peer, state); if (global.es2panda._ContextState(this._ctx.peer) === Es2pandaContextState.ES2PANDA_STATE_ERROR) { - const errMsg = withStringResult(global.es2panda._ContextErrorMessage(this._ctx.peer)) + const errMsg = withStringResult(global.es2panda._ContextErrorMessage(this._ctx.peer)); if (errMsg === undefined) { - throwError(`Couldn't get context error msg`) + throwError(`Couldn't get context error msg`); } else { - throwError("Failed proceed to: " + Es2pandaContextState[state] + "\n" + errMsg) + throwError('Failed proceed to: ' + Es2pandaContextState[state] + '\n' + errMsg); } } } catch (e) { - global.es2panda._DestroyContext(this._ctx.peer) - throw e + global.es2panda._DestroyContext(this._ctx.peer); + throw e; } } - public finalize() { + public finalize(): void { if (this._cfg === undefined) { - throwError("Call finalize before initialized config") + throwError('Call finalize before initialized config'); } if (this._ctx === undefined) { - throwError("Call finalize before initialized context") + throwError('Call finalize before initialized context'); } - global.es2panda._DestroyContext(this._ctx.peer) - global.es2panda._DestroyConfig(this._cfg.peer) - this._ctx = undefined - global.destroyCfg() + global.es2panda._DestroyContext(this._ctx.peer); + global.es2panda._DestroyConfig(this._cfg.peer); + this._ctx = undefined; + global.destroyCfg(); } - public generateTsDecl(declOutPath: string, etsOutPath: string, exportAll: boolean) { - let exportAll_: KBoolean = exportAll ? 1 : 0 - global.es2panda._GenerateTsDeclarationsFromContext(this._cfg.peer, declOutPath, etsOutPath, exportAll_) + public generateTsDecl(declOutPath: string, etsOutPath: string, exportAll: boolean): void { + let exportAll_: KBoolean = exportAll ? 1 : 0; + global.es2panda._GenerateTsDeclarationsFromContext(this._cfg.peer, declOutPath, etsOutPath, exportAll_); } } export class LspDriverHelper { public createCfg(cmd: string[], filePath: string, pandaLibPath: string): Config { - return Config.create(cmd, filePath, pandaLibPath, true) + return Config.create(cmd, filePath, pandaLibPath, true); } public createCtx(source: string, filePath: string, cfg: Config): KNativePointer { - return Context.lspCreateFromString(source, filePath, cfg) + return Context.lspCreateFromString(source, filePath, cfg); } - public proceedToState(ctx: KNativePointer, state: Es2pandaContextState) { + public proceedToState(ctx: KNativePointer, state: Es2pandaContextState): void { if (ctx === undefined) { - throwError("Trying to proceed to state while cts is undefined") + throwError('Trying to proceed to state while cts is undefined'); } if (state <= global.es2pandaPublic._ContextState(ctx)) { - return + return; } try { - global.es2pandaPublic._ProceedToState(ctx, state) + global.es2pandaPublic._ProceedToState(ctx, state); } catch (e) { - global.es2pandaPublic._DestroyContext(ctx) - throw e + global.es2pandaPublic._DestroyContext(ctx); + throw e; } } - public destroyContext(ctx: KNativePointer) { + public destroyContext(ctx: KNativePointer): void { if (ctx === undefined) { - return + return; } - global.es2pandaPublic._DestroyContext(ctx) + global.es2pandaPublic._DestroyContext(ctx); } - public destroyConfig(cfg: Config) { + public destroyConfig(cfg: Config): void { if (cfg === undefined) { - return + return; } - global.es2pandaPublic._DestroyConfig(cfg.peer) + global.es2pandaPublic._DestroyConfig(cfg.peer); } } diff --git a/ets2panda/bindings/src/generated/Es2pandaNativeModule.ts b/ets2panda/bindings/src/generated/Es2pandaNativeModule.ts index f83a5db66a..8bd49b74b2 100644 --- a/ets2panda/bindings/src/generated/Es2pandaNativeModule.ts +++ b/ets2panda/bindings/src/generated/Es2pandaNativeModule.ts @@ -13,23 +13,37 @@ * limitations under the License. */ - -import { KBoolean, KInt, KNativePointer } from "../InteropTypes" +import { KBoolean, KInt, KNativePointer } from '../InteropTypes'; export class Es2pandaNativeModule { - _CreateMemberExpression(context: KNativePointer, object_arg: KNativePointer, property: KNativePointer, kind: KInt, computed: KBoolean, optional_arg: KBoolean): KNativePointer { - throw new Error("This methods was not overloaded by native module initialization") + _CreateMemberExpression( + context: KNativePointer, + object_arg: KNativePointer, + property: KNativePointer, + kind: KInt, + computed: KBoolean, + optional_arg: KBoolean + ): KNativePointer { + throw new Error('This methods was not overloaded by native module initialization'); } - _UpdateMemberExpression(context: KNativePointer, original: KNativePointer, object_arg: KNativePointer, property: KNativePointer, kind: KInt, computed: KBoolean, optional_arg: KBoolean): KNativePointer { - throw new Error("This methods was not overloaded by native module initialization") + _UpdateMemberExpression( + context: KNativePointer, + original: KNativePointer, + object_arg: KNativePointer, + property: KNativePointer, + kind: KInt, + computed: KBoolean, + optional_arg: KBoolean + ): KNativePointer { + throw new Error('This methods was not overloaded by native module initialization'); } _MemberExpressionObject(context: KNativePointer, receiver: KNativePointer): KNativePointer { - throw new Error("This methods was not overloaded by native module initialization") + throw new Error('This methods was not overloaded by native module initialization'); } _MemberExpressionProperty(context: KNativePointer, receiver: KNativePointer): KNativePointer { - throw new Error("This methods was not overloaded by native module initialization") + throw new Error('This methods was not overloaded by native module initialization'); } _MemberExpressionKindConst(context: KNativePointer, receiver: KNativePointer): KInt { - throw new Error("This methods was not overloaded by native module initialization") + throw new Error('This methods was not overloaded by native module initialization'); } } diff --git a/ets2panda/bindings/src/global.ts b/ets2panda/bindings/src/global.ts index 3cf022f996..9578770a53 100644 --- a/ets2panda/bindings/src/global.ts +++ b/ets2panda/bindings/src/global.ts @@ -13,85 +13,91 @@ * limitations under the License. */ -import { throwError } from "./utils" -import { KNativePointer } from "./InteropTypes" -import { initEs2panda, Es2pandaNativeModule, initGeneratedEs2panda, initPublicEs2panda, initPublicGeneratedEs2panda } from "./Es2pandaNativeModule" -import { Es2pandaNativeModule as GeneratedEs2pandaNativeModule } from "./generated/Es2pandaNativeModule" -import { initInterop, InteropNativeModule, initPublicInterop } from "./InteropNativeModule" -import { Context } from "./types" +import { throwError } from './utils'; +import { KNativePointer } from './InteropTypes'; +import { + initEs2panda, + Es2pandaNativeModule, + initGeneratedEs2panda, + initPublicEs2panda, + initPublicGeneratedEs2panda +} from './Es2pandaNativeModule'; +import { Es2pandaNativeModule as GeneratedEs2pandaNativeModule } from './generated/Es2pandaNativeModule'; +import { initInterop, InteropNativeModule, initPublicInterop } from './InteropNativeModule'; +import { Context } from './types'; export class global { - public static filePath: string = "./examples/input/main.ets" + public static filePath: string = './examples/input/main.ets'; - private static _config?: KNativePointer + private static _config?: KNativePointer; public static set config(config: KNativePointer) { if (global._config !== undefined) { - throwError('Global.config already initialized') + throwError('Global.config already initialized'); } - global._config = config + global._config = config; } public static get config(): KNativePointer { - return global._config ?? throwError('Global.config not initialized') + return global._config ?? throwError('Global.config not initialized'); } - public static destroyCfg() { - global._config = undefined + public static destroyCfg(): void { + global._config = undefined; } public static configIsInitialized(): boolean { - return global._config !== undefined + return global._config !== undefined; } - private static _context?: KNativePointer + private static _context?: KNativePointer; public static set context(context: KNativePointer) { - global._context = context + global._context = context; } public static get context(): KNativePointer { - return global._context ?? throwError('Global.context not initialized') + return global._context ?? throwError('Global.context not initialized'); } - private static _es2panda: Es2pandaNativeModule | undefined = undefined - private static _es2pandaPublic: Es2pandaNativeModule | undefined = undefined + private static _es2panda: Es2pandaNativeModule | undefined = undefined; + private static _es2pandaPublic: Es2pandaNativeModule | undefined = undefined; public static get es2panda(): Es2pandaNativeModule { if (this._es2panda === undefined) { - this._es2panda = initEs2panda() + this._es2panda = initEs2panda(); } - return this._es2panda + return this._es2panda; } public static get es2pandaPublic(): Es2pandaNativeModule { if (this._es2pandaPublic === undefined) { - this._es2pandaPublic = initPublicEs2panda() + this._es2pandaPublic = initPublicEs2panda(); } - return this._es2pandaPublic + return this._es2pandaPublic; } - private static _generatedEs2panda: GeneratedEs2pandaNativeModule | undefined = undefined - private static _generatedEs2pandaPublic: GeneratedEs2pandaNativeModule | undefined = undefined + private static _generatedEs2panda: GeneratedEs2pandaNativeModule | undefined = undefined; + private static _generatedEs2pandaPublic: GeneratedEs2pandaNativeModule | undefined = undefined; public static get generatedEs2panda(): GeneratedEs2pandaNativeModule { if (this._generatedEs2panda === undefined) { - this._generatedEs2panda = initGeneratedEs2panda() + this._generatedEs2panda = initGeneratedEs2panda(); } - return this._generatedEs2panda + return this._generatedEs2panda; } public static get generatedEs2pandaPublic(): GeneratedEs2pandaNativeModule { if (this._generatedEs2pandaPublic === undefined) { - this._generatedEs2pandaPublic = initPublicGeneratedEs2panda() + this._generatedEs2pandaPublic = initPublicGeneratedEs2panda(); } - return this._generatedEs2pandaPublic + return this._generatedEs2pandaPublic; } - private static _interop: InteropNativeModule | undefined = undefined - private static _interopPublic: InteropNativeModule | undefined = undefined + private static _interop: InteropNativeModule | undefined = undefined; + private static _interopPublic: InteropNativeModule | undefined = undefined; public static get interop(): InteropNativeModule { - if (this._interop === undefined) this._interop = initInterop() - return this._interop + if (this._interop === undefined) this._interop = initInterop(); + return this._interop; } public static get interopPublic(): InteropNativeModule { - if (this._interopPublic === undefined) this._interopPublic = initPublicInterop() - return this._interopPublic + if (this._interopPublic === undefined) this._interopPublic = initPublicInterop(); + return this._interopPublic; } } diff --git a/ets2panda/bindings/src/index.ts b/ets2panda/bindings/src/index.ts index 4b83e7e668..ac1bbaaa34 100644 --- a/ets2panda/bindings/src/index.ts +++ b/ets2panda/bindings/src/index.ts @@ -13,9 +13,18 @@ * limitations under the License. */ -export { Lsp } from "./lsp_helper"; -export { DriverHelper } from "./driver_helper"; -export { Es2pandaContextState } from "./generated/Es2pandaEnums" -export { LspCompletionInfo, LspCompletionEntryKind, LspDefinitionData, LspDiagsNode, LspDiagnosticNode, LspDiagSeverity, LspQuickInfo, LspSymbolDisplayPart } from './lspNode' -export { generateArkTsConfigByModules } from './arktsConfigGenerate' -export { ModuleDescriptor } from './buildConfigGenerate' +export { Lsp } from './lsp_helper'; +export { DriverHelper } from './driver_helper'; +export { Es2pandaContextState } from './generated/Es2pandaEnums'; +export { + LspCompletionInfo, + LspCompletionEntryKind, + LspDefinitionData, + LspDiagsNode, + LspDiagnosticNode, + LspDiagSeverity, + LspQuickInfo, + LspSymbolDisplayPart +} from './lspNode'; +export { generateArkTsConfigByModules } from './arktsConfigGenerate'; +export type { ModuleDescriptor } from './buildConfigGenerate'; diff --git a/ets2panda/bindings/src/loadLibraries.ts b/ets2panda/bindings/src/loadLibraries.ts index fb22a82cba..44e6d1c60e 100644 --- a/ets2panda/bindings/src/loadLibraries.ts +++ b/ets2panda/bindings/src/loadLibraries.ts @@ -13,17 +13,17 @@ * limitations under the License. */ -import * as path from 'path' +import * as path from 'path'; -const nativeModuleLibraries: Map = new Map() +const nativeModuleLibraries: Map = new Map(); export function loadNativeLibrary(name: string): Record { - if ((globalThis as any).requireNapi) - return (globalThis as any).requireNapi(name, true) - else { - const suffixedName = name.endsWith(".node") ? name : `${name}.node` + if ((globalThis as any).requireNapi) { + return (globalThis as any).requireNapi(name, true); + } else { + const suffixedName = name.endsWith('.node') ? name : `${name}.node`; if (process.platform === 'win32') { - return require(suffixedName) + return require(suffixedName); } else { return eval(`let exports = {}; process.dlopen({ exports }, require.resolve("${suffixedName}"), 2); exports`); } @@ -31,16 +31,17 @@ export function loadNativeLibrary(name: string): Record { } export function registerNativeModuleLibraryName(nativeModule: string, libraryName: string) { - nativeModuleLibraries.set(nativeModule, libraryName) + nativeModuleLibraries.set(nativeModule, libraryName); } export function loadNativeModuleLibrary(moduleName: string, module?: object) { - if (!module) - throw new Error(" argument is required and optional only for compatibility with ArkTS") - const library = loadNativeLibrary(nativeModuleLibraries.get(moduleName) ?? moduleName) + if (!module) { + throw new Error(' argument is required and optional only for compatibility with ArkTS'); + } + const library = loadNativeLibrary(nativeModuleLibraries.get(moduleName) ?? moduleName); if (!library || !library[moduleName]) { - console.error(`Failed to load library for module ${moduleName}`) - return + console.error(`Failed to load library for module ${moduleName}`); + return; } - Object.assign(module, library[moduleName]) + Object.assign(module, library[moduleName]); } diff --git a/ets2panda/bindings/src/lspNode.ts b/ets2panda/bindings/src/lspNode.ts index 28e013aa70..4126a58541 100644 --- a/ets2panda/bindings/src/lspNode.ts +++ b/ets2panda/bindings/src/lspNode.ts @@ -13,41 +13,41 @@ * limitations under the License. */ -import { KBoolean, KInt, KNativePointer, KUInt } from "./InteropTypes" -import { unpackString, VariantTypes } from "./private" -import { throwError } from "./utils" -import { isNullPtr } from "./Wrapper" -import { global } from "./global" -import { NativePtrDecoder } from "./Platform" +import { KBoolean, KInt, KNativePointer, KUInt } from './InteropTypes'; +import { unpackString, VariantTypes } from './private'; +import { throwError } from './utils'; +import { isNullPtr } from './Wrapper'; +import { global } from './global'; +import { NativePtrDecoder } from './Platform'; export abstract class LspNode { - readonly peer: KNativePointer + readonly peer: KNativePointer; protected constructor(peer: KNativePointer) { if (isNullPtr(peer)) { - throwError("nullptr from peer in lspnode constuctor") + throwError('nullptr from peer in lspnode constuctor'); } - this.peer = peer + this.peer = peer; } } export class LspPosition extends LspNode { - readonly line: number - readonly character: number + readonly line: number; + readonly character: number; constructor(peer: KNativePointer) { - super(peer) - this.line = global.es2panda._getPosLine(peer) - this.character = global.es2panda._getPosChar(peer) + super(peer); + this.line = global.es2panda._getPosLine(peer); + this.character = global.es2panda._getPosChar(peer); } } export class LspRange extends LspNode { - readonly start: LspPosition - readonly end: LspPosition + readonly start: LspPosition; + readonly end: LspPosition; constructor(peer: KNativePointer) { - super(peer) - this.start = new LspPosition(global.es2panda._getRangeStart(peer)) - this.end = new LspPosition(global.es2panda._getRangeEnd(peer)) + super(peer); + this.start = new LspPosition(global.es2panda._getRangeStart(peer)); + this.end = new LspPosition(global.es2panda._getRangeEnd(peer)); } } @@ -55,102 +55,102 @@ export enum LspDiagSeverity { Error = 1, Warning = 2, Information = 3, - Hint = 4, + Hint = 4 } export enum LspDiagTag { Unnecessary = 1, - Deprecated = 2, + Deprecated = 2 } export class LspLocation extends LspNode { constructor(peer: KNativePointer) { - super(peer) - this.uri = unpackString(global.es2panda._getLocUri(peer)) - this.range = new LspRange(global.es2panda._getLocRange(peer)) + super(peer); + this.uri = unpackString(global.es2panda._getLocUri(peer)); + this.range = new LspRange(global.es2panda._getLocRange(peer)); } - readonly uri: string - readonly range: LspRange + readonly uri: string; + readonly range: LspRange; } export class LspRelatedInfo extends LspNode { constructor(peer: KNativePointer) { - super(peer) - this.message = unpackString(global.es2panda._getRelatedInfoMsg(peer)) - this.location = new LspLocation(global.es2panda._getRelatedInfoLoc(peer)) + super(peer); + this.message = unpackString(global.es2panda._getRelatedInfoMsg(peer)); + this.location = new LspLocation(global.es2panda._getRelatedInfoLoc(peer)); } - readonly message: string - readonly location: LspLocation + readonly message: string; + readonly location: LspLocation; } export class LspCodeDescription extends LspNode { constructor(peer: KNativePointer) { - super(peer) - this.href = unpackString(global.es2panda._getCodeDescriptionHref(peer)) + super(peer); + this.href = unpackString(global.es2panda._getCodeDescriptionHref(peer)); } - readonly href: string + readonly href: string; } export class LspDiagnosticNode extends LspNode { constructor(peer: KNativePointer) { - super(peer) - this.message = unpackString(global.es2panda._getDiagMsg(peer)) - this.source = unpackString(global.es2panda._getDiagSource(peer)) - this.range = new LspRange(global.es2panda._getDiagRange(peer)) + super(peer); + this.message = unpackString(global.es2panda._getDiagMsg(peer)); + this.source = unpackString(global.es2panda._getDiagSource(peer)); + this.range = new LspRange(global.es2panda._getDiagRange(peer)); this.tags = new NativePtrDecoder() .decode(global.es2panda._getDiagTags(peer)) - .map((elPeer: KNativePointer) => elPeer as KInt) + .map((elPeer: KNativePointer) => elPeer as KInt); this.relatedInfo = new NativePtrDecoder() .decode(global.es2panda._getDiagRelatedInfo(peer)) - .map((elPeer: KNativePointer) => new LspRelatedInfo(elPeer)) - let codeVarPtr = global.es2panda._getDiagCode(peer) - if (global.interop._getTypeOfVariant(codeVarPtr) == VariantTypes.VARIANT_INT) { - this.code = global.interop._getIntFromVariant(codeVarPtr) + .map((elPeer: KNativePointer) => new LspRelatedInfo(elPeer)); + let codeVarPtr = global.es2panda._getDiagCode(peer); + if (global.interop._getTypeOfVariant(codeVarPtr) === VariantTypes.VARIANT_INT) { + this.code = global.interop._getIntFromVariant(codeVarPtr); } else { - this.code = unpackString(global.interop._getStringFromVariant(codeVarPtr)) + this.code = unpackString(global.interop._getStringFromVariant(codeVarPtr)); } - let dataPtr = global.es2panda._getDiagData(peer) - if (global.interop._getTypeOfVariant(dataPtr) == VariantTypes.VARIANT_INT) { - this.data = global.interop._getIntFromVariant(dataPtr) + let dataPtr = global.es2panda._getDiagData(peer); + if (global.interop._getTypeOfVariant(dataPtr) === VariantTypes.VARIANT_INT) { + this.data = global.interop._getIntFromVariant(dataPtr); } else { - this.data = unpackString(global.interop._getStringFromVariant(dataPtr)) + this.data = unpackString(global.interop._getStringFromVariant(dataPtr)); } - this.severity = global.es2panda._getDiagSeverity(peer) - this.codeDescription = new LspCodeDescription(global.es2panda._getDiagCodeDescription(peer)) + this.severity = global.es2panda._getDiagSeverity(peer); + this.codeDescription = new LspCodeDescription(global.es2panda._getDiagCodeDescription(peer)); } - readonly source: String - readonly message: String - readonly range: LspRange - readonly codeDescription: LspCodeDescription - readonly severity: LspDiagSeverity - readonly tags: LspDiagTag[] - readonly relatedInfo: LspRelatedInfo[] - readonly code: number | String - readonly data: number | string + readonly source: String; + readonly message: String; + readonly range: LspRange; + readonly codeDescription: LspCodeDescription; + readonly severity: LspDiagSeverity; + readonly tags: LspDiagTag[]; + readonly relatedInfo: LspRelatedInfo[]; + readonly code: number | String; + readonly data: number | string; } export class LspDiagsNode extends LspNode { constructor(peer: KNativePointer) { - super(peer) + super(peer); this.diagnostics = new NativePtrDecoder() .decode(global.es2panda._getDiags(this.peer)) .map((elPeer: KNativePointer) => { - return new LspDiagnosticNode(elPeer) - }) + return new LspDiagnosticNode(elPeer); + }); } - readonly diagnostics: LspDiagnosticNode[] + readonly diagnostics: LspDiagnosticNode[]; } export class LspDefinitionData extends LspNode { constructor(peer: KNativePointer) { - super(peer) - this.fileName = unpackString(global.es2panda._getFileNameFromDef(peer)) - this.start = global.es2panda._getStartFromDef(peer) - this.length = global.es2panda._getLengthFromDef(peer) + super(peer); + this.fileName = unpackString(global.es2panda._getFileNameFromDef(peer)); + this.start = global.es2panda._getStartFromDef(peer); + this.length = global.es2panda._getLengthFromDef(peer); } - readonly fileName: String - readonly start: KInt - readonly length: KInt + readonly fileName: String; + readonly start: KInt; + readonly length: KInt; } export class LspReferenceData extends LspNode { @@ -181,8 +181,8 @@ export class LspReferences extends LspNode { this.referenceInfos = new NativePtrDecoder() .decode(global.es2panda._getReferenceInfos(this.peer)) .map((elPeer: KNativePointer) => { - return new LspReferenceData(elPeer) - }) + return new LspReferenceData(elPeer); + }); } readonly referenceInfos: LspReferenceData[]; } @@ -217,8 +217,8 @@ export class LspQuickInfo extends LspNode { this.displayParts = new NativePtrDecoder() .decode(global.es2panda._getSymbolDisplayPart(peer)) .map((elPeer: KNativePointer) => { - return new LspSymbolDisplayPart(elPeer) - }) + return new LspSymbolDisplayPart(elPeer); + }); } readonly kind: String; readonly kindModifier: String; @@ -228,7 +228,10 @@ export class LspQuickInfo extends LspNode { } export enum LspHighlightSpanKind { - NONE, DEFINITION, REFERENCE, WRITTEN_REFERENCE + NONE, + DEFINITION, + REFERENCE, + WRITTEN_REFERENCE } export class LspHighlightSpan extends LspNode { @@ -237,7 +240,7 @@ export class LspHighlightSpan extends LspNode { this.fileName = unpackString(global.es2panda._getHighlightFileName(peer)); this.textSpan = new LspTextSpan(global.es2panda._getTextSpan(peer)); this.contextSpan = new LspTextSpan(global.es2panda._getTextSpan(peer)); - this.kind = global.es2panda._getHighlightKind(peer) + this.kind = global.es2panda._getHighlightKind(peer); } readonly fileName: String; readonly textSpan: LspTextSpan; @@ -252,8 +255,8 @@ export class LspDocumentHighlights extends LspNode { this.highlightSpans = new NativePtrDecoder() .decode(global.es2panda._getHighlightSpanFromHighlights(peer)) .map((elPeer: KNativePointer) => { - return new LspHighlightSpan(elPeer) - }) + return new LspHighlightSpan(elPeer); + }); } readonly fileName: String; readonly highlightSpans: LspHighlightSpan[]; @@ -265,8 +268,8 @@ export class LspDocumentHighlightsReferences extends LspNode { this.documentHighlights = new NativePtrDecoder() .decode(global.es2panda._getDocumentHighlightsFromRef(peer)) .map((elPeer: KNativePointer) => { - return new LspDocumentHighlights(elPeer) - }) + return new LspDocumentHighlights(elPeer); + }); } readonly documentHighlights: LspDocumentHighlights[]; } @@ -300,7 +303,8 @@ export enum LspCompletionEntryKind { } export enum ResolutionStatus { - RESOLVED, UNRESOLVED + RESOLVED, + UNRESOLVED } export class LspCompletionEntryData extends LspNode { @@ -347,13 +351,17 @@ export class LspCompletionInfo extends LspNode { this.entries = new NativePtrDecoder() .decode(global.es2panda._getEntriesFromCompletionInfo(peer)) .map((elPeer: KNativePointer) => { - return new LspCompletionEntry(elPeer) - }) + return new LspCompletionEntry(elPeer); + }); } readonly entries: LspCompletionEntry[]; } -export enum AccessKind { READ, WRITE, READWRITE }; +export enum AccessKind { + READ, + WRITE, + READWRITE +} export class LspReferenceLocation extends LspNode { constructor(peer: KNativePointer) { @@ -375,18 +383,18 @@ export class LspReferenceLocationList extends LspNode { this.entries = new NativePtrDecoder() .decode(global.es2panda._getLocationFromList(peer)) .map((elPeer: KNativePointer) => { - return new LspReferenceLocation(elPeer) - }) + return new LspReferenceLocation(elPeer); + }); } readonly entries: LspReferenceLocation[]; } export class LspLineAndCharacter extends LspNode { - readonly line: number - readonly character: number + readonly line: number; + readonly character: number; constructor(peer: KNativePointer) { - super(peer) - this.line = global.es2panda._getLine(peer) - this.character = global.es2panda._getChar(peer) + super(peer); + this.line = global.es2panda._getLine(peer); + this.character = global.es2panda._getChar(peer); } -} \ No newline at end of file +} diff --git a/ets2panda/bindings/src/lsp_helper.ts b/ets2panda/bindings/src/lsp_helper.ts index 592277606d..b9224e4b29 100644 --- a/ets2panda/bindings/src/lsp_helper.ts +++ b/ets2panda/bindings/src/lsp_helper.ts @@ -13,16 +13,26 @@ * limitations under the License. */ -import { LspDriverHelper } from "./driver_helper" -import { global } from "./global" -import { LspDefinitionData, LspDiagsNode, LspReferences, LspQuickInfo, LspDocumentHighlightsReferences, LspCompletionInfo, LspReferenceLocationList, LspLineAndCharacter, LspReferenceData } from "./lspNode" -import { unpackString } from "./private" -import { Es2pandaContextState } from "./generated/Es2pandaEnums" -import { BuildConfig } from './types' -import { PluginDriver, PluginHook } from './ui_plugins_driver' +import { LspDriverHelper } from './driver_helper'; +import { global } from './global'; +import { + LspDefinitionData, + LspDiagsNode, + LspReferences, + LspQuickInfo, + LspDocumentHighlightsReferences, + LspCompletionInfo, + LspReferenceLocationList, + LspLineAndCharacter, + LspReferenceData +} from './lspNode'; +import { unpackString } from './private'; +import { Es2pandaContextState } from './generated/Es2pandaEnums'; +import { BuildConfig } from './types'; +import { PluginDriver, PluginHook } from './ui_plugins_driver'; -import * as fs from "fs" -import * as path from 'path' +import * as fs from 'fs'; +import * as path from 'path'; function initBuildEnv(): void { const currentPath: string | undefined = process.env.PATH; @@ -31,268 +41,268 @@ function initBuildEnv(): void { } export class Lsp { - private pandaLibPath: string - private fileNameToArktsconfig: any // Map - private moduleToBuildConfig: any // Map + private pandaLibPath: string; + private fileNameToArktsconfig: Record; // Map + private moduleToBuildConfig: Record; // Map private getFileContent: (filePath: string) => string; constructor(projectPath: string, getContentCallback?: (filePath: string) => string) { - initBuildEnv() + initBuildEnv(); this.pandaLibPath = path.resolve(__dirname, '../../ets2panda/lib'); - let compileFileInfoPath = path.join(projectPath, '.idea', '.deveco', 'lsp_compileFileInfos.json') - this.fileNameToArktsconfig = JSON.parse(fs.readFileSync(compileFileInfoPath, 'utf-8')) - let buildConfigPath = path.join(projectPath, '.idea', '.deveco', 'lsp_build_config.json') - this.moduleToBuildConfig = JSON.parse(fs.readFileSync(buildConfigPath, 'utf-8')) + let compileFileInfoPath = path.join(projectPath, '.idea', '.deveco', 'lsp_compileFileInfos.json'); + this.fileNameToArktsconfig = JSON.parse(fs.readFileSync(compileFileInfoPath, 'utf-8')); + let buildConfigPath = path.join(projectPath, '.idea', '.deveco', 'lsp_build_config.json'); + this.moduleToBuildConfig = JSON.parse(fs.readFileSync(buildConfigPath, 'utf-8')); this.getFileContent = getContentCallback || ((path) => fs.readFileSync(path, 'utf8')); } getDefinitionAtPosition(filename: String, offset: number): LspDefinitionData { - let lspDriverHelper = new LspDriverHelper() - let filePath = path.resolve(filename.valueOf()) - let arktsconfig = this.fileNameToArktsconfig[filePath] - let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig] - let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath) + let lspDriverHelper = new LspDriverHelper(); + let filePath = path.resolve(filename.valueOf()); + let arktsconfig = this.fileNameToArktsconfig[filePath]; + let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; + let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); const source = fs.readFileSync(filePath, 'utf8').toString().replace(/\r\n/g, '\n'); - let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg) - PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx) - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED) - PluginDriver.getInstance().runPluginHook(PluginHook.PARSED) - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED) - let ptr = global.es2panda._getDefinitionAtPosition(localCtx, offset) - PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN) + let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); + PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); + lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); + PluginDriver.getInstance().runPluginHook(PluginHook.PARSED); + lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED); + let ptr = global.es2panda._getDefinitionAtPosition(localCtx, offset); + PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); lspDriverHelper.destroyContext(localCtx); lspDriverHelper.destroyConfig(localCfg); - return new LspDefinitionData(ptr) + return new LspDefinitionData(ptr); } getSemanticDiagnostics(filename: String): LspDiagsNode { - let lspDriverHelper = new LspDriverHelper() - let filePath = path.resolve(filename.valueOf()) - let arktsconfig = this.fileNameToArktsconfig[filePath] - let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig] + let lspDriverHelper = new LspDriverHelper(); + let filePath = path.resolve(filename.valueOf()); + let arktsconfig = this.fileNameToArktsconfig[filePath]; + let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; let pandaLibPath: string = path.resolve(__dirname, '../../ets2panda/lib'); - let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, pandaLibPath) + let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, pandaLibPath); const source = fs.readFileSync(filePath, 'utf8').toString().replace(/\r\n/g, '\n'); - let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg) - PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx) - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED) - PluginDriver.getInstance().runPluginHook(PluginHook.PARSED) - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED) - let ptr = global.es2panda._getSemanticDiagnostics(localCtx) - PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN) + let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); + PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); + lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); + PluginDriver.getInstance().runPluginHook(PluginHook.PARSED); + lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED); + let ptr = global.es2panda._getSemanticDiagnostics(localCtx); + PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); lspDriverHelper.destroyContext(localCtx); lspDriverHelper.destroyConfig(localCfg); - return new LspDiagsNode(ptr) + return new LspDiagsNode(ptr); } getCurrentTokenValue(filename: String, offset: number): string { - let lspDriverHelper = new LspDriverHelper() - let filePath = path.resolve(filename.valueOf()) - let arktsconfig = this.fileNameToArktsconfig[filePath] - let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig] - let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath) + let lspDriverHelper = new LspDriverHelper(); + let filePath = path.resolve(filename.valueOf()); + let arktsconfig = this.fileNameToArktsconfig[filePath]; + let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; + let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); const source = fs.readFileSync(filePath, 'utf8').toString().replace(/\r\n/g, '\n'); - let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg) - PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx) - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED) - PluginDriver.getInstance().runPluginHook(PluginHook.PARSED) - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED) - let ptr = global.es2panda._getCurrentTokenValue(localCtx, offset) - PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN) + let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); + PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); + lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); + PluginDriver.getInstance().runPluginHook(PluginHook.PARSED); + lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED); + let ptr = global.es2panda._getCurrentTokenValue(localCtx, offset); + PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); lspDriverHelper.destroyContext(localCtx); lspDriverHelper.destroyConfig(localCfg); - return unpackString(ptr) + return unpackString(ptr); } getImplementationAtPosition(filename: String, offset: number): LspDefinitionData { - let lspDriverHelper = new LspDriverHelper() - let filePath = path.resolve(filename.valueOf()) - let arktsconfig = this.fileNameToArktsconfig[filePath] - let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig] - let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath) + let lspDriverHelper = new LspDriverHelper(); + let filePath = path.resolve(filename.valueOf()); + let arktsconfig = this.fileNameToArktsconfig[filePath]; + let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; + let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); const source = fs.readFileSync(filePath, 'utf8').toString().replace(/\r\n/g, '\n'); - let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg) - PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx) - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED) - PluginDriver.getInstance().runPluginHook(PluginHook.PARSED) - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED) - let ptr = global.es2panda._getImplementationAtPosition(localCtx, offset) - PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN) + let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); + PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); + lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); + PluginDriver.getInstance().runPluginHook(PluginHook.PARSED); + lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED); + let ptr = global.es2panda._getImplementationAtPosition(localCtx, offset); + PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); lspDriverHelper.destroyContext(localCtx); lspDriverHelper.destroyConfig(localCfg); - return new LspDefinitionData(ptr) + return new LspDefinitionData(ptr); } getFileReferences(filename: String): LspReferenceData[] { - let lspDriverHelper = new LspDriverHelper() - let filePath = path.resolve(filename.valueOf()) - let arktsconfig = this.fileNameToArktsconfig[filePath] - let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig] - let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath) + let lspDriverHelper = new LspDriverHelper(); + let filePath = path.resolve(filename.valueOf()); + let arktsconfig = this.fileNameToArktsconfig[filePath]; + let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; + let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); const source = fs.readFileSync(filePath, 'utf8').toString().replace(/\r\n/g, '\n'); - let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg) - PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx) - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED) - PluginDriver.getInstance().runPluginHook(PluginHook.PARSED) - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED) - let isPackageModule = global.es2panda._isPackageModule(localCtx) - PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN) + let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); + PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); + lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); + PluginDriver.getInstance().runPluginHook(PluginHook.PARSED); + lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED); + let isPackageModule = global.es2panda._isPackageModule(localCtx); + PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); lspDriverHelper.destroyContext(localCtx); lspDriverHelper.destroyConfig(localCfg); - let result: LspReferenceData[] = [] - let moduleName = path.basename(path.dirname(arktsconfig)) - let buildConfig: BuildConfig = this.moduleToBuildConfig[moduleName] + let result: LspReferenceData[] = []; + let moduleName = path.basename(path.dirname(arktsconfig)); + let buildConfig: BuildConfig = this.moduleToBuildConfig[moduleName]; for (let i = 0; i < buildConfig.compileFiles.length; i++) { - let filePath = path.resolve(buildConfig.compileFiles[i]) - let arktsconfig = this.fileNameToArktsconfig[filePath] - let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig] - let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath) + let filePath = path.resolve(buildConfig.compileFiles[i]); + let arktsconfig = this.fileNameToArktsconfig[filePath]; + let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; + let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); const source = fs.readFileSync(filePath, 'utf8').toString().replace(/\r\n/g, '\n'); - let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg) - PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx) - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED) - PluginDriver.getInstance().runPluginHook(PluginHook.PARSED) - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED) - let ptr = global.es2panda._getFileReferences(filePath, localCtx, isPackageModule) - let refs = new LspReferences(ptr) - PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN) - lspDriverHelper.destroyContext(localCtx) - lspDriverHelper.destroyConfig(localCfg) + let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); + PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); + lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); + PluginDriver.getInstance().runPluginHook(PluginHook.PARSED); + lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED); + let ptr = global.es2panda._getFileReferences(filePath, localCtx, isPackageModule); + let refs = new LspReferences(ptr); + PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); + lspDriverHelper.destroyContext(localCtx); + lspDriverHelper.destroyConfig(localCfg); for (let j = 0; j < refs.referenceInfos.length; j++) { if (refs.referenceInfos[j].fileName !== '') { - result.push(refs.referenceInfos[j]) + result.push(refs.referenceInfos[j]); } } } - return result + return result; } getReferencesAtPosition(filename: String, offset: number): LspReferenceData[] { - let lspDriverHelper = new LspDriverHelper() - let filePath = path.resolve(filename.valueOf()) - let arktsconfig = this.fileNameToArktsconfig[filePath] - let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig] - let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath) + let lspDriverHelper = new LspDriverHelper(); + let filePath = path.resolve(filename.valueOf()); + let arktsconfig = this.fileNameToArktsconfig[filePath]; + let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; + let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); const source = fs.readFileSync(filePath, 'utf8').toString().replace(/\r\n/g, '\n'); - let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg) - PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx) - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED) - PluginDriver.getInstance().runPluginHook(PluginHook.PARSED) - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED) - let declInfo = global.es2panda._getDeclInfo(localCtx, offset) - PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN) - lspDriverHelper.destroyContext(localCtx) - lspDriverHelper.destroyConfig(localCfg) - let result: LspReferenceData[] = [] - let moduleName = path.basename(path.dirname(arktsconfig)) - let buildConfig: BuildConfig = this.moduleToBuildConfig[moduleName] + let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); + PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); + lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); + PluginDriver.getInstance().runPluginHook(PluginHook.PARSED); + lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED); + let declInfo = global.es2panda._getDeclInfo(localCtx, offset); + PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); + lspDriverHelper.destroyContext(localCtx); + lspDriverHelper.destroyConfig(localCfg); + let result: LspReferenceData[] = []; + let moduleName = path.basename(path.dirname(arktsconfig)); + let buildConfig: BuildConfig = this.moduleToBuildConfig[moduleName]; for (let i = 0; i < buildConfig.compileFiles.length; i++) { - let filePath = path.resolve(buildConfig.compileFiles[i]) - let arktsconfig = this.fileNameToArktsconfig[filePath] - let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig] - let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath) + let filePath = path.resolve(buildConfig.compileFiles[i]); + let arktsconfig = this.fileNameToArktsconfig[filePath]; + let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; + let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); const source = fs.readFileSync(filePath, 'utf8').toString().replace(/\r\n/g, '\n'); - let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg) - PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx) - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED) - PluginDriver.getInstance().runPluginHook(PluginHook.PARSED) - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED) - let ptr = global.es2panda._getReferencesAtPosition(localCtx, declInfo) - PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN) - lspDriverHelper.destroyContext(localCtx) - lspDriverHelper.destroyConfig(localCfg) - let refs = new LspReferences(ptr) - result.push(...refs.referenceInfos) + let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); + PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); + lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); + PluginDriver.getInstance().runPluginHook(PluginHook.PARSED); + lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED); + let ptr = global.es2panda._getReferencesAtPosition(localCtx, declInfo); + PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); + lspDriverHelper.destroyContext(localCtx); + lspDriverHelper.destroyConfig(localCfg); + let refs = new LspReferences(ptr); + result.push(...refs.referenceInfos); } return Array.from(new Set(result)); } getSyntacticDiagnostics(filename: String): LspDiagsNode { - let lspDriverHelper = new LspDriverHelper() - let filePath = path.resolve(filename.valueOf()) - let arktsconfig = this.fileNameToArktsconfig[filePath] - let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig] - let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath) + let lspDriverHelper = new LspDriverHelper(); + let filePath = path.resolve(filename.valueOf()); + let arktsconfig = this.fileNameToArktsconfig[filePath]; + let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; + let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); const source = fs.readFileSync(filePath, 'utf8').toString().replace(/\r\n/g, '\n'); - let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg) - PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx) - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED) - PluginDriver.getInstance().runPluginHook(PluginHook.PARSED) - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED) - let ptr = global.es2panda._getSyntacticDiagnostics(localCtx) - PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN) - lspDriverHelper.destroyContext(localCtx) - lspDriverHelper.destroyConfig(localCfg) - return new LspDiagsNode(ptr) + let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); + PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); + lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); + PluginDriver.getInstance().runPluginHook(PluginHook.PARSED); + lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED); + let ptr = global.es2panda._getSyntacticDiagnostics(localCtx); + PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); + lspDriverHelper.destroyContext(localCtx); + lspDriverHelper.destroyConfig(localCfg); + return new LspDiagsNode(ptr); } getSuggestionDiagnostics(filename: String): LspDiagsNode { - let lspDriverHelper = new LspDriverHelper() - let filePath = path.resolve(filename.valueOf()) - let arktsconfig = this.fileNameToArktsconfig[filePath] - let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig] - let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath) + let lspDriverHelper = new LspDriverHelper(); + let filePath = path.resolve(filename.valueOf()); + let arktsconfig = this.fileNameToArktsconfig[filePath]; + let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; + let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); const source = fs.readFileSync(filePath, 'utf8').toString().replace(/\r\n/g, '\n'); - let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg) - PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx) - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED) - PluginDriver.getInstance().runPluginHook(PluginHook.PARSED) - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED) - let ptr = global.es2panda._getSuggestionDiagnostics(localCtx) - PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN) - lspDriverHelper.destroyContext(localCtx) - lspDriverHelper.destroyConfig(localCfg) - return new LspDiagsNode(ptr) + let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); + PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); + lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); + PluginDriver.getInstance().runPluginHook(PluginHook.PARSED); + lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED); + let ptr = global.es2panda._getSuggestionDiagnostics(localCtx); + PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); + lspDriverHelper.destroyContext(localCtx); + lspDriverHelper.destroyConfig(localCfg); + return new LspDiagsNode(ptr); } getQuickInfoAtPosition(filename: String, offset: number): LspQuickInfo { - let lspDriverHelper = new LspDriverHelper() - let filePath = path.resolve(filename.valueOf()) - let arktsconfig = this.fileNameToArktsconfig[filePath] - let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig] - let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath) + let lspDriverHelper = new LspDriverHelper(); + let filePath = path.resolve(filename.valueOf()); + let arktsconfig = this.fileNameToArktsconfig[filePath]; + let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; + let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); const source = fs.readFileSync(filePath, 'utf8').toString().replace(/\r\n/g, '\n'); - let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg) - PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx) - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED) - PluginDriver.getInstance().runPluginHook(PluginHook.PARSED) - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED) - let ptr = global.es2panda._getQuickInfoAtPosition(filename, localCtx, offset) - PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN) - lspDriverHelper.destroyContext(localCtx) - lspDriverHelper.destroyConfig(localCfg) - return new LspQuickInfo(ptr) + let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); + PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); + lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); + PluginDriver.getInstance().runPluginHook(PluginHook.PARSED); + lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED); + let ptr = global.es2panda._getQuickInfoAtPosition(filename, localCtx, offset); + PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); + lspDriverHelper.destroyContext(localCtx); + lspDriverHelper.destroyConfig(localCfg); + return new LspQuickInfo(ptr); } getDocumentHighlights(filename: String, offset: number): LspDocumentHighlightsReferences { - let lspDriverHelper = new LspDriverHelper() - let filePath = path.resolve(filename.valueOf()) - let arktsconfig = this.fileNameToArktsconfig[filePath] - let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig] - let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath) + let lspDriverHelper = new LspDriverHelper(); + let filePath = path.resolve(filename.valueOf()); + let arktsconfig = this.fileNameToArktsconfig[filePath]; + let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; + let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); const source = fs.readFileSync(filePath, 'utf8').toString().replace(/\r\n/g, '\n'); - let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg) - PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx) - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED) - PluginDriver.getInstance().runPluginHook(PluginHook.PARSED) - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED) - let ptr = global.es2panda._getDocumentHighlights(localCtx, offset) - PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN) - lspDriverHelper.destroyContext(localCtx) - lspDriverHelper.destroyConfig(localCfg) - return new LspDocumentHighlightsReferences(ptr) + let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); + PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); + lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); + PluginDriver.getInstance().runPluginHook(PluginHook.PARSED); + lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED); + let ptr = global.es2panda._getDocumentHighlights(localCtx, offset); + PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); + lspDriverHelper.destroyContext(localCtx); + lspDriverHelper.destroyConfig(localCfg); + return new LspDocumentHighlightsReferences(ptr); } getCompletionAtPosition(filename: String, offset: number): LspCompletionInfo { - let lspDriverHelper = new LspDriverHelper() - let filePath = path.resolve(filename.valueOf()) - let arktsconfig = this.fileNameToArktsconfig[filePath] - let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig] - let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath) + let lspDriverHelper = new LspDriverHelper(); + let filePath = path.resolve(filename.valueOf()); + let arktsconfig = this.fileNameToArktsconfig[filePath]; + let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; + let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); let source = this.getFileContent(filePath).replace(/\r\n/g, '\n'); // This is a temporary solution to support "obj." with wildcard for better solution in internal issue. if (source[offset - 1] === '.') { - const wildcard = "_WILDCARD"; + const wildcard = '_WILDCARD'; if (offset < source.length + 1) { source = source.slice(0, offset) + wildcard + source.slice(offset); } else { @@ -300,34 +310,34 @@ export class Lsp { } offset += wildcard.length; } - let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg) - PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx) - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED) - PluginDriver.getInstance().runPluginHook(PluginHook.PARSED) - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED) - let ptr = global.es2panda._getCompletionAtPosition(localCtx, offset) - PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN) - lspDriverHelper.destroyContext(localCtx) - lspDriverHelper.destroyConfig(localCfg) - return new LspCompletionInfo(ptr) + let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); + PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); + lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); + PluginDriver.getInstance().runPluginHook(PluginHook.PARSED); + lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED); + let ptr = global.es2panda._getCompletionAtPosition(localCtx, offset); + PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); + lspDriverHelper.destroyContext(localCtx); + lspDriverHelper.destroyConfig(localCfg); + return new LspCompletionInfo(ptr); } toLineColumnOffset(filename: String, offset: number): LspLineAndCharacter { - let lspDriverHelper = new LspDriverHelper() - let filePath = path.resolve(filename.valueOf()) - let arktsconfig = this.fileNameToArktsconfig[filePath] - let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig] - let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath) + let lspDriverHelper = new LspDriverHelper(); + let filePath = path.resolve(filename.valueOf()); + let arktsconfig = this.fileNameToArktsconfig[filePath]; + let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; + let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); const source = fs.readFileSync(filePath, 'utf8').toString().replace(/\r\n/g, '\n'); - let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg) - PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx) - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED) - PluginDriver.getInstance().runPluginHook(PluginHook.PARSED) - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED) - let ptr = global.es2panda._toLineColumnOffset(localCtx, offset) - PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN) - lspDriverHelper.destroyContext(localCtx) - lspDriverHelper.destroyConfig(localCfg) - return new LspLineAndCharacter(ptr) + let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); + PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); + lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); + PluginDriver.getInstance().runPluginHook(PluginHook.PARSED); + lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED); + let ptr = global.es2panda._toLineColumnOffset(localCtx, offset); + PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); + lspDriverHelper.destroyContext(localCtx); + lspDriverHelper.destroyConfig(localCfg); + return new LspLineAndCharacter(ptr); } } diff --git a/ets2panda/bindings/src/mainWrapper.ts b/ets2panda/bindings/src/mainWrapper.ts index 2b62690d2e..6d3139b200 100644 --- a/ets2panda/bindings/src/mainWrapper.ts +++ b/ets2panda/bindings/src/mainWrapper.ts @@ -13,22 +13,22 @@ * limitations under the License. */ -import { KPointer } from "./InteropTypes" -import { ptrToString } from "./Wrapper" -import { className } from "./ts-reflection" +import { KPointer } from './InteropTypes'; +import { ptrToString } from './Wrapper'; +import { className } from './ts-reflection'; /** * An object holding reference to the native pointer. */ export class Wrapper { - ptr: KPointer + ptr: KPointer; constructor(ptr: KPointer) { - if (ptr == null) - throw new Error(`Init <${className(this)}> with null native peer`) - this.ptr = ptr + if (ptr == null) { + throw new Error(`Init <${className(this)}> with null native peer`); + } + this.ptr = ptr; } toString(): string { - return `[native object <${className(this)}> at ${ptrToString(this.ptr)}]` + return `[native object <${className(this)}> at ${ptrToString(this.ptr)}]`; } } - diff --git a/ets2panda/bindings/src/preDefine.ts b/ets2panda/bindings/src/preDefine.ts index 79b1c27022..b0dc4d7f85 100644 --- a/ets2panda/bindings/src/preDefine.ts +++ b/ets2panda/bindings/src/preDefine.ts @@ -20,8 +20,8 @@ export const ABC_SUFFIX: string = '.abc'; export enum LANGUAGE_VERSION { ARKTS_1_2 = '1.2', ARKTS_1_1 = '1.1', - ARKTS_HYBRID = 'hybrid', -}; + ARKTS_HYBRID = 'hybrid' +} export const PANDA_SDK_PATH_FROM_SDK: string = './build-tools/ets2panda'; export const SYSTEM_SDK_PATH_FROM_SDK: string = './'; diff --git a/ets2panda/bindings/src/private.ts b/ets2panda/bindings/src/private.ts index fa3a1cf5c4..0392b1006c 100644 --- a/ets2panda/bindings/src/private.ts +++ b/ets2panda/bindings/src/private.ts @@ -13,14 +13,14 @@ * limitations under the License. */ -import { throwError } from "./utils" -import { KNativePointer, nullptr } from "./InteropTypes" -import { withString, withStringArray } from "./arrays" -import { NativePtrDecoder, withStringResult } from "./Platform" -import { LspDiagsNode, LspNode } from "./lspNode"; +import { throwError } from './utils'; +import { KNativePointer, nullptr } from './InteropTypes'; +import { withString, withStringArray } from './arrays'; +import { NativePtrDecoder, withStringResult } from './Platform'; +import { LspDiagsNode, LspNode } from './lspNode'; export function lspData(peer: KNativePointer): LspNode { - return new LspDiagsNode(peer) + return new LspDiagsNode(peer); } export enum VariantTypes { @@ -30,37 +30,35 @@ export enum VariantTypes { export function unpackNonNullableNode(peer: KNativePointer): T { if (peer === nullptr) { - throwError('peer is NULLPTR (maybe you should use unpackNode)') + throwError('peer is NULLPTR (maybe you should use unpackNode)'); } - return lspData(peer) as T + return lspData(peer) as T; } export function unpackNode(peer: KNativePointer): T | undefined { if (peer === nullptr) { - return undefined + return undefined; } } export function unpackNodeArray(nodesPtr: KNativePointer): readonly T[] { if (nodesPtr === nullptr) { - throwError('nodesPtr is NULLPTR (maybe you should use unpackNodeArray)') + throwError('nodesPtr is NULLPTR (maybe you should use unpackNodeArray)'); } - return (new NativePtrDecoder()) - .decode(nodesPtr) - .map((peer: KNativePointer) => unpackNonNullableNode(peer)) + return new NativePtrDecoder().decode(nodesPtr).map((peer: KNativePointer) => unpackNonNullableNode(peer)); } export function unpackString(peer: KNativePointer): string { - return withStringResult(peer) ?? throwError(`failed to unpack (peer shouldn't be NULLPTR)`) + return withStringResult(peer) ?? throwError(`failed to unpack (peer shouldn't be NULLPTR)`); } export function passString(str: string | undefined): string { if (str === undefined) { - return "" + return ''; } - return withString(str, (it: string) => it) + return withString(str, (it: string) => it); } export function passStringArray(strings: string[]): Uint8Array { - return withStringArray(strings) + return withStringArray(strings); } diff --git a/ets2panda/bindings/src/strings.ts b/ets2panda/bindings/src/strings.ts index 0f6cf4ad34..cf3cac9e86 100644 --- a/ets2panda/bindings/src/strings.ts +++ b/ets2panda/bindings/src/strings.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -import { int32 } from "./InteropTypes" +import { int32 } from './InteropTypes'; interface SystemTextEncoder { encode(input?: string): Uint8Array; @@ -25,181 +25,186 @@ interface WithStreamOption { } interface SystemTextDecoder { - decode( - input?: ArrayBuffer | null | Uint8Array, - options?: WithStreamOption - ): string; + decode(input?: ArrayBuffer | null | Uint8Array, options?: WithStreamOption): string; } export class CustomTextEncoder { - static readonly HeaderLen: int32 = Int32Array.BYTES_PER_ELEMENT + static readonly HeaderLen: int32 = Int32Array.BYTES_PER_ELEMENT; - constructor(encoder: SystemTextEncoder | undefined = ((typeof TextEncoder != "undefined") ? new TextEncoder() : undefined)) { - this.encoder = encoder + constructor( + encoder: SystemTextEncoder | undefined = typeof TextEncoder != 'undefined' ? new TextEncoder() : undefined + ) { + this.encoder = encoder; } - private readonly encoder: SystemTextEncoder | undefined + private readonly encoder: SystemTextEncoder | undefined; public static stringLength(input: string): int32 { - let length = 0 + let length = 0; for (let i = 0; i < input.length; i++) { - length++ - let cp = input.codePointAt(i)! + length++; + let cp = input.codePointAt(i)!; if (cp >= 0x10000) { - i++ + i++; } } - return length + return length; } encodedLength(input: string): int32 { - let length = 0 + let length = 0; for (let i = 0; i < input.length; i++) { - let cp = input.codePointAt(i)! + let cp = input.codePointAt(i)!; if (cp < 0x80) { - length += 1 + length += 1; } else if (cp < 0x800) { - length += 2 + length += 2; } else if (cp < 0x10000) { - length += 3 + length += 3; } else { - length += 4 - i++ + length += 4; + i++; } } - return length + return length; } private addLength(array: Uint8Array, offset: int32, len: int32): void { - array[offset] = (len & 0xff) - array[offset + 1] = ((len >> 8) & 0xff) - array[offset + 2] = ((len >> 16) & 0xff) - array[offset + 3] = ((len >> 24) & 0xff) + array[offset] = len & 0xff; + array[offset + 1] = (len >> 8) & 0xff; + array[offset + 2] = (len >> 16) & 0xff; + array[offset + 3] = (len >> 24) & 0xff; } static getHeaderLength(array: Uint8Array, offset: int32 = 0): int32 { - return (array[offset] | (array[offset + 1] << 8) | (array[offset + 2] << 16) | (array[offset + 3] << 24)) + return array[offset] | (array[offset + 1] << 8) | (array[offset + 2] << 16) | (array[offset + 3] << 24); } // Produces array of bytes with encoded string headed by 4 bytes (little endian) size information: // [s0][s1][s2][s3] [c_0] ... [c_size-1] encode(input: string | undefined, addLength: boolean = true): Uint8Array { - let headerLen = addLength ? CustomTextEncoder.HeaderLen : 0 - let result: Uint8Array + let headerLen = addLength ? CustomTextEncoder.HeaderLen : 0; + let result: Uint8Array; if (!input) { - result = new Uint8Array(headerLen) + result = new Uint8Array(headerLen); } else if (this.encoder !== undefined) { - result = this.encoder!.encode('s'.repeat(headerLen) + input) + result = this.encoder!.encode('s'.repeat(headerLen) + input); } else { - let length = this.encodedLength(input) - result = new Uint8Array(length + headerLen) - this.encodeInto(input, result, headerLen) + let length = this.encodedLength(input); + result = new Uint8Array(length + headerLen); + this.encodeInto(input, result, headerLen); } if (addLength) { - this.addLength(result, 0, result.length - headerLen) + this.addLength(result, 0, result.length - headerLen); } - return result + return result; } // Produces encoded array of strings with size information. encodeArray(strings: Array): Uint8Array { - let totalBytes = CustomTextEncoder.HeaderLen - let lengths = new Int32Array(strings.length) + let totalBytes = CustomTextEncoder.HeaderLen; + let lengths = new Int32Array(strings.length); for (let i = 0; i < lengths.length; i++) { - let len = this.encodedLength(strings[i]) - lengths[i] = len - totalBytes += len + CustomTextEncoder.HeaderLen + let len = this.encodedLength(strings[i]); + lengths[i] = len; + totalBytes += len + CustomTextEncoder.HeaderLen; } - let array = new Uint8Array(totalBytes) - let position = 0 - this.addLength(array, position, lengths.length) - position += CustomTextEncoder.HeaderLen + let array = new Uint8Array(totalBytes); + let position = 0; + this.addLength(array, position, lengths.length); + position += CustomTextEncoder.HeaderLen; for (let i = 0; i < lengths.length; i++) { - this.addLength(array, position, lengths[i]) - position += CustomTextEncoder.HeaderLen - this.encodeInto(strings[i], array, position) - position += lengths[i] + this.addLength(array, position, lengths[i]); + position += CustomTextEncoder.HeaderLen; + this.encodeInto(strings[i], array, position); + position += lengths[i]; } - return array + return array; } encodeInto(input: string, result: Uint8Array, position: int32): Uint8Array { if (this.encoder !== undefined) { - this.encoder!.encodeInto(input, result.subarray(position, result.length)) - return result + this.encoder!.encodeInto(input, result.subarray(position, result.length)); + return result; } - let index = position + let index = position; for (let stringPosition = 0; stringPosition < input.length; stringPosition++) { - let cp = input.codePointAt(stringPosition)! + let cp = input.codePointAt(stringPosition)!; if (cp < 0x80) { - result[index++] = (cp | 0) + result[index++] = cp | 0; } else if (cp < 0x800) { - result[index++] = ((cp >> 6) | 0xc0) - result[index++] = ((cp & 0x3f) | 0x80) + result[index++] = (cp >> 6) | 0xc0; + result[index++] = (cp & 0x3f) | 0x80; } else if (cp < 0x10000) { - result[index++] = ((cp >> 12) | 0xe0) - result[index++] = (((cp >> 6) & 0x3f) | 0x80) - result[index++] = ((cp & 0x3f) | 0x80) + result[index++] = (cp >> 12) | 0xe0; + result[index++] = ((cp >> 6) & 0x3f) | 0x80; + result[index++] = (cp & 0x3f) | 0x80; } else { - result[index++] = ((cp >> 18) | 0xf0) - result[index++] = (((cp >> 12) & 0x3f) | 0x80) - result[index++] = (((cp >> 6) & 0x3f) | 0x80) - result[index++] = ((cp & 0x3f) | 0x80) - stringPosition++ + result[index++] = (cp >> 18) | 0xf0; + result[index++] = ((cp >> 12) & 0x3f) | 0x80; + result[index++] = ((cp >> 6) & 0x3f) | 0x80; + result[index++] = (cp & 0x3f) | 0x80; + stringPosition++; } } - result[index] = 0 - return result + result[index] = 0; + return result; } } export class CustomTextDecoder { - static cpArrayMaxSize = 128 - constructor(decoder: SystemTextDecoder | TextDecoder | undefined = ((typeof TextDecoder != "undefined") ? new TextDecoder() : undefined)) { - this.decoder = decoder + static cpArrayMaxSize = 128; + constructor( + decoder: SystemTextDecoder | TextDecoder | undefined = typeof TextDecoder !== 'undefined' + ? new TextDecoder() + : undefined + ) { + this.decoder = decoder; } - private readonly decoder: SystemTextDecoder | TextDecoder | undefined + private readonly decoder: SystemTextDecoder | TextDecoder | undefined; decode(input: Uint8Array): string { if (this.decoder !== undefined) { - return this.decoder!.decode(input) + return this.decoder!.decode(input); } - const cpSize = Math.min(CustomTextDecoder.cpArrayMaxSize, input.length) - let codePoints = new Int32Array(cpSize) + const cpSize = Math.min(CustomTextDecoder.cpArrayMaxSize, input.length); + let codePoints = new Int32Array(cpSize); let cpIndex = 0; - let index = 0 - let result = "" + let index = 0; + let result = ''; while (index < input.length) { - let elem = input[index] - let lead = elem & 0xff - let count = 0 - let value = 0 + let elem = input[index]; + let lead = elem & 0xff; + let count = 0; + let value = 0; if (lead < 0x80) { - count = 1 - value = elem - } else if ((lead >> 5) == 0x6) { - value = ((elem << 6) & 0x7ff) + (input[index + 1] & 0x3f) - count = 2 - } else if ((lead >> 4) == 0xe) { - value = ((elem << 12) & 0xffff) + ((input[index + 1] << 6) & 0xfff) + - (input[index + 2] & 0x3f) - count = 3 - } else if ((lead >> 3) == 0x1e) { - value = ((elem << 18) & 0x1fffff) + ((input[index + 1] << 12) & 0x3ffff) + - ((input[index + 2] << 6) & 0xfff) + (input[index + 3] & 0x3f) - count = 4 + count = 1; + value = elem; + } else if (lead >> 5 == 0x6) { + value = ((elem << 6) & 0x7ff) + (input[index + 1] & 0x3f); + count = 2; + } else if (lead >> 4 == 0xe) { + value = ((elem << 12) & 0xffff) + ((input[index + 1] << 6) & 0xfff) + (input[index + 2] & 0x3f); + count = 3; + } else if (lead >> 3 == 0x1e) { + value = + ((elem << 18) & 0x1fffff) + + ((input[index + 1] << 12) & 0x3ffff) + + ((input[index + 2] << 6) & 0xfff) + + (input[index + 3] & 0x3f); + count = 4; } - codePoints[cpIndex++] = value + codePoints[cpIndex++] = value; if (cpIndex == cpSize) { - cpIndex = 0 - result += String.fromCodePoint(...codePoints) + cpIndex = 0; + result += String.fromCodePoint(...codePoints); } - index += count + index += count; } if (cpIndex > 0) { - result += String.fromCodePoint(...codePoints.slice(0, cpIndex)) + result += String.fromCodePoint(...codePoints.slice(0, cpIndex)); } - return result + return result; } } diff --git a/ets2panda/bindings/src/ts-reflection.ts b/ets2panda/bindings/src/ts-reflection.ts index 48a8ed37b5..b5bca76260 100644 --- a/ets2panda/bindings/src/ts-reflection.ts +++ b/ets2panda/bindings/src/ts-reflection.ts @@ -14,22 +14,22 @@ */ export function className(object?: Object): string { - return object?.constructor.name ?? "" + return object?.constructor.name ?? ''; } export function isFunction(object?: Object): boolean { - return typeof object === 'function' + return typeof object === 'function'; } // TODO: this is to match arkts counterpart export function functionOverValue(value: Value | (() => Value)): boolean { - return typeof value === 'function' + return typeof value === 'function'; } export function refEqual(a: Value, b: Value): boolean { - return a === b + return a === b; } export function isNotPrimitive(value: Object): boolean { - return true + return true; } diff --git a/ets2panda/bindings/src/types.ts b/ets2panda/bindings/src/types.ts index c67661360c..2a34d968b7 100644 --- a/ets2panda/bindings/src/types.ts +++ b/ets2panda/bindings/src/types.ts @@ -13,117 +13,101 @@ * limitations under the License. */ -import { KNativePointer as KPtr } from "./InteropTypes" -import { global } from "./global" -import { throwError } from "./utils" -import { passString, passStringArray, unpackString } from "./private" -import { isNullPtr } from "./Wrapper" +import { KNativePointer as KPtr } from './InteropTypes'; +import { global } from './global'; +import { throwError } from './utils'; +import { passString, passStringArray, unpackString } from './private'; +import { isNullPtr } from './Wrapper'; -export const arrayOfNullptr = new BigUint64Array([BigInt(0)]) +export const arrayOfNullptr = new BigUint64Array([BigInt(0)]); export abstract class ArktsObject { protected constructor(peer: KPtr) { - this.peer = peer + this.peer = peer; } - readonly peer: KPtr + readonly peer: KPtr; } export abstract class Node extends ArktsObject { protected constructor(peer: KPtr) { if (isNullPtr(peer)) { - throw new Error('trying to create new Node on NULLPTR') + throw new Error('trying to create new Node on NULLPTR'); } - super(peer) + super(peer); } public get originalPeer(): KPtr { - return global.es2panda._AstNodeOriginalNodeConst(global.context, this.peer) + return global.es2panda._AstNodeOriginalNodeConst(global.context, this.peer); } public set originalPeer(peer: KPtr) { - global.es2panda._AstNodeSetOriginalNode(global.context, this.peer, peer) + global.es2panda._AstNodeSetOriginalNode(global.context, this.peer, peer); } protected dumpMessage(): string { - return `` + return ``; } public dumpJson(): string { - return unpackString(global.es2panda._AstNodeDumpJsonConst(global.context, this.peer)) + return unpackString(global.es2panda._AstNodeDumpJsonConst(global.context, this.peer)); } public dumpSrc(): string { - return unpackString(global.es2panda._AstNodeDumpEtsSrcConst(global.context, this.peer)) + return unpackString(global.es2panda._AstNodeDumpEtsSrcConst(global.context, this.peer)); } } export class Config extends ArktsObject { - readonly path: string + readonly path: string; constructor(peer: KPtr, fpath: string) { - super(peer) + super(peer); // TODO: wait for getter from api - this.path = fpath + this.path = fpath; } public toString(): string { - return `Config (peer = ${this.peer}, path = ${this.path})` + return `Config (peer = ${this.peer}, path = ${this.path})`; } - static create( - input: string[], fpath: string, pandaLibPath: string = '', isEditingMode: boolean = false - ): Config { + static create(input: string[], fpath: string, pandaLibPath: string = '', isEditingMode: boolean = false): Config { if (isEditingMode) { - let cfg = global.es2pandaPublic._CreateConfig(input.length, passStringArray(input), pandaLibPath) - return new Config(cfg, fpath) + let cfg = global.es2pandaPublic._CreateConfig(input.length, passStringArray(input), pandaLibPath); + return new Config(cfg, fpath); } if (!global.configIsInitialized()) { - let cfg = global.es2panda._CreateConfig(input.length, passStringArray(input), pandaLibPath) - global.config = cfg - return new Config( - cfg, fpath - ) + let cfg = global.es2panda._CreateConfig(input.length, passStringArray(input), pandaLibPath); + global.config = cfg; + return new Config(cfg, fpath); } else { - return new Config(global.config, fpath) + return new Config(global.config, fpath); } } } export class Context extends ArktsObject { constructor(peer: KPtr) { - super(peer) + super(peer); } public toString(): string { - return `Context (peer = ${this.peer})` + return `Context (peer = ${this.peer})`; } - static createFromString( - source: string - ): Context { + static createFromString(source: string): Context { if (!global.configIsInitialized()) { - throwError(`Config not initialized`) + throwError(`Config not initialized`); } return new Context( - global.es2panda._CreateContextFromString( - global.config, - passString(source), - passString(global.filePath) - ) - ) + global.es2panda._CreateContextFromString(global.config, passString(source), passString(global.filePath)) + ); } - static lspCreateFromString( - source: string, filePath: string, cfg: Config - ): KPtr { + static lspCreateFromString(source: string, filePath: string, cfg: Config): KPtr { if (cfg === undefined) { - throwError(`Config not initialized`) + throwError(`Config not initialized`); } - return global.es2pandaPublic._CreateContextFromString( - cfg.peer, - passString(source), - passString(filePath) - ) + return global.es2pandaPublic._CreateContextFromString(cfg.peer, passString(source), passString(filePath)); } } @@ -149,10 +133,12 @@ export interface ModuleConfig { export interface PathConfig { loaderOutPath: string; + declgenDtsOutPath: string; + declgenTsOutPath: string; cachePath: string; buildSdkPath: string; - pandaSdkPath?: string; // path to panda sdk lib/bin, for local test - pandaStdlibPath?: string; // path to panda sdk stdlib, for local test + pandaSdkPath?: string; // path to panda sdk lib/bin, for local test + pandaStdlibPath?: string; // path to panda sdk stdlib, for local test abcLinkerPath?: string; } @@ -173,9 +159,9 @@ export interface DependentModuleConfig { modulePath: string; sourceRoots: string[]; entryFile: string; - language: string, - declFilesPath?: string, - dependencies?: string[] + language: string; + declFilesPath?: string; + dependencies?: string[]; } export interface BuildConfig extends BuildBaseConfig, DeclgenConfig, LoggerConfig, ModuleConfig, PathConfig { @@ -186,25 +172,25 @@ export interface BuildConfig extends BuildBaseConfig, DeclgenConfig, LoggerConfi // ProjectConfig ends export interface CompileFileInfo { - filePath: string, - dependentFiles: string[], - abcFilePath: string, - arktsConfigFile: string, - packageName: string, -}; + filePath: string; + dependentFiles: string[]; + abcFilePath: string; + arktsConfigFile: string; + packageName: string; +} export interface ModuleInfo { - isMainModule: boolean, - packageName: string, - moduleRootPath: string, - moduleType: string, - sourceRoots: string[], - entryFile: string, - arktsConfigFile: string, - compileFileInfos: CompileFileInfo[], - declgenV1OutPath: string | undefined, - declgenBridgeCodePath: string | undefined, - dependencies?: string[] + isMainModule: boolean; + packageName: string; + moduleRootPath: string; + moduleType: string; + sourceRoots: string[]; + entryFile: string; + arktsConfigFile: string; + compileFileInfos: CompileFileInfo[]; + declgenV1OutPath: string | undefined; + declgenBridgeCodePath: string | undefined; + dependencies?: string[]; staticDepModuleInfos: Map; dynamicDepModuleInfos: Map; language?: string; diff --git a/ets2panda/bindings/src/ui_plugins_driver.ts b/ets2panda/bindings/src/ui_plugins_driver.ts index b880392f7e..1d30fb9803 100644 --- a/ets2panda/bindings/src/ui_plugins_driver.ts +++ b/ets2panda/bindings/src/ui_plugins_driver.ts @@ -13,8 +13,8 @@ * limitations under the License. */ -import { KNativePointer } from "./InteropTypes"; -import { BuildConfig } from "./types"; +import { KNativePointer } from './InteropTypes'; +import { BuildConfig } from './types'; export enum PluginHook { NEW = 'afterNew', @@ -24,40 +24,40 @@ export enum PluginHook { LOWERED = 'lowered', ASM_GENERATED = 'asmGenerated', BIN_GENERATED = 'binGenerated', - CLEAN = 'clean', -}; + CLEAN = 'clean' +} type PluginHandlerFunction = () => void; type PluginHandlerObject = { - order: 'pre' | 'post' | undefined - handler: PluginHandlerFunction + order: 'pre' | 'post' | undefined; + handler: PluginHandlerFunction; }; type PluginHandler = PluginHandlerFunction | PluginHandlerObject; interface Plugins { - name: string, - afterNew?: PluginHandler, - parsed?: PluginHandler, - scopeInited?: PluginHandler, - checked?: PluginHandler, - lowered?: PluginHandler, - asmGenerated?: PluginHandler, - binGenerated?: PluginHandler, - clean?: PluginHandler, + name: string; + afterNew?: PluginHandler; + parsed?: PluginHandler; + scopeInited?: PluginHandler; + checked?: PluginHandler; + lowered?: PluginHandler; + asmGenerated?: PluginHandler; + binGenerated?: PluginHandler; + clean?: PluginHandler; } type PluginExecutor = { - name: string - handler: PluginHandler + name: string; + handler: PluginHandler; }; type PluginInitFunction = () => Plugins; type RawPlugins = { - name: string, - init: PluginInitFunction | undefined + name: string; + init: PluginInitFunction | undefined; }; class PluginContext { @@ -98,11 +98,11 @@ class PluginContext { } public setContextPtr(ptr: KNativePointer): void { - this.contextPtr = ptr + this.contextPtr = ptr; } public getContextPtr(): KNativePointer | undefined { - return this.contextPtr + return this.contextPtr; } } @@ -167,7 +167,7 @@ export class PluginDriver { let post: PluginExecutor[] = []; this.allPlugins.forEach((pluginObject: Plugins, name: string) => { - if (!(pluginObject[hook])) { + if (!pluginObject[hook]) { return; } diff --git a/ets2panda/bindings/src/utils.ts b/ets2panda/bindings/src/utils.ts index b767be2e7a..5e21866cc6 100644 --- a/ets2panda/bindings/src/utils.ts +++ b/ets2panda/bindings/src/utils.ts @@ -17,12 +17,12 @@ import * as fs from 'fs'; import * as path from 'path'; export function throwError(error: string): never { - throw new Error(error) + throw new Error(error); } export function withWarning(value: T, message: string): T { - console.warn(message) - return value + console.warn(message); + return value; } export function changeFileExtension(file: string, targetExt: string, originExt = ''): string { diff --git a/ets2panda/test/unit/lsp/get_completions.cpp b/ets2panda/test/unit/lsp/get_completions.cpp index 52c94ee42d..cac0c5a820 100644 --- a/ets2panda/test/unit/lsp/get_completions.cpp +++ b/ets2panda/test/unit/lsp/get_completions.cpp @@ -27,9 +27,9 @@ using ark::es2panda::lsp::sort_text::GLOBALS_OR_KEYWORDS; using ark::es2panda::lsp::sort_text::MEMBER_DECLARED_BY_SPREAD_ASSIGNMENT; using ark::es2panda::lsp::sort_text::SUGGESTED_CLASS_MEMBERS; -void AssertCompletionsContainAndNotContainEntries(const std::vector &entries, - const std::vector &expectedEntries, - const std::vector &unexpectedEntries) +static void AssertCompletionsContainAndNotContainEntries(const std::vector &entries, + const std::vector &expectedEntries, + const std::vector &unexpectedEntries) { auto emptyCheck = expectedEntries.empty() && !entries.empty(); ASSERT_FALSE(emptyCheck) << "Expected empty but the result is not. Actual account: " << entries.size(); -- Gitee From b030bb23589824c0cae3b3dc4a06d5790196721f Mon Sep 17 00:00:00 2001 From: Tao Wu Date: Thu, 17 Apr 2025 14:06:54 +0800 Subject: [PATCH 042/268] [cherry-pick] Fix build system failure on macOS Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC1X64 Signed-off-by: Tao Wu --- ets2panda/driver/build_system/src/build/base_mode.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ets2panda/driver/build_system/src/build/base_mode.ts b/ets2panda/driver/build_system/src/build/base_mode.ts index 7374d81a9d..921da50393 100644 --- a/ets2panda/driver/build_system/src/build/base_mode.ts +++ b/ets2panda/driver/build_system/src/build/base_mode.ts @@ -247,8 +247,8 @@ export abstract class BaseMode { let abcLinkerCmdStr: string = this.abcLinkerCmd.join(' '); if (isMac()) { - const loadLibrary = "DYLD_LIBRARY_PATH=" + process.env.DYLD_LIBRARY_PATH; - abcLinkerCmdStr = loadLibrary + " " + abcLinkerCmdStr; + const loadLibrary = 'DYLD_LIBRARY_PATH=' + '"' + process.env.DYLD_LIBRARY_PATH + '"'; + abcLinkerCmdStr = loadLibrary + ' ' + abcLinkerCmdStr; } this.logger.printInfo(abcLinkerCmdStr); -- Gitee From 5110730c614ab694a52737e0d6fcaa104841b3a4 Mon Sep 17 00:00:00 2001 From: Okolnov Evgeniy Date: Thu, 10 Apr 2025 22:24:14 +0300 Subject: [PATCH 043/268] Fix crashing for `destructuring parameter` case Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC077R Test scenarios: new tests added to the linter Change-Id: Ic7fd5e89e130178f8c9734751154cc724e499103 Signed-off-by: Okolnov Evgeniy --- ets2panda/linter/src/lib/TypeScriptLinter.ts | 12 +- .../linter/src/lib/autofixes/Autofixer.ts | 30 +- .../src/lib/utils/functions/ArrayUtils.ts | 4 +- .../LibraryTypeCallDiagnosticChecker.ts | 3 +- .../test/main/destructuring_parameters.ets | 2 + .../destructuring_parameters.ets.args.json | 19 ++ .../destructuring_parameters.ets.autofix.json | 304 ++++++++++++++++++ .../main/destructuring_parameters.ets.json | 100 +++--- 8 files changed, 397 insertions(+), 77 deletions(-) create mode 100644 ets2panda/linter/test/main/destructuring_parameters.ets.args.json create mode 100644 ets2panda/linter/test/main/destructuring_parameters.ets.autofix.json diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index 8985c35bb7..2476d0e806 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -1816,7 +1816,9 @@ export class TypeScriptLinter { private handleDeclarationDestructuring(decl: ts.VariableDeclaration | ts.ParameterDeclaration): void { const faultId = ts.isVariableDeclaration(decl) ? FaultID.DestructuringDeclaration : FaultID.DestructuringParameter; if (ts.isObjectBindingPattern(decl.name)) { - const autofix = this.autofixer?.fixObjectBindingPatternDeclarations(decl, faultId); + const autofix = ts.isVariableDeclaration(decl) ? + this.autofixer?.fixObjectBindingPatternDeclarations(decl) : + undefined; this.incrementCounters(decl, faultId, autofix); } else if (ts.isArrayBindingPattern(decl.name)) { // Array destructuring is allowed only for Arrays/Tuples and without spread operator. @@ -1833,7 +1835,9 @@ export class TypeScriptLinter { hasNestedObjectDestructuring || TsUtils.destructuringDeclarationHasSpreadOperator(decl.name) ) { - const autofix = this.autofixer?.fixArrayBindingPatternDeclarations(decl, isArrayOrTuple); + const autofix = ts.isVariableDeclaration(decl) ? + this.autofixer?.fixArrayBindingPatternDeclarations(decl, isArrayOrTuple) : + undefined; this.incrementCounters(decl, faultId, autofix); } } @@ -4163,7 +4167,7 @@ export class TypeScriptLinter { } const typeString = this.tsTypeChecker.typeToString(type); - return (typeString === 'String' || typeString === 'int'); + return typeString === 'String' || typeString === 'int'; } private static isValidNumber(value: number): boolean { @@ -4206,7 +4210,7 @@ export class TypeScriptLinter { } return null; } - + private handleLimitedLiteralType(literalTypeNode: ts.LiteralTypeNode): void { if (!this.options.arkts2 || !literalTypeNode) { return; diff --git a/ets2panda/linter/src/lib/autofixes/Autofixer.ts b/ets2panda/linter/src/lib/autofixes/Autofixer.ts index bfef893582..e7a5f6cf02 100644 --- a/ets2panda/linter/src/lib/autofixes/Autofixer.ts +++ b/ets2panda/linter/src/lib/autofixes/Autofixer.ts @@ -15,7 +15,6 @@ import * as ts from 'typescript'; import { TsUtils } from '../utils/TsUtils'; -import { FaultID } from '../Problems'; import { scopeContainsThis } from '../utils/functions/ContainsThis'; import { forEachNodeInSubtree } from '../utils/functions/ForEachNodeInSubtree'; import { NameGenerator } from '../utils/functions/NameGenerator'; @@ -159,13 +158,13 @@ export class Autofixer { /** * Creates autofix suggestions for destructuring assignment. - * @param variableDeclaration - The variable or parameter declaration to fix. + * @param variableDeclaration - The variable declaration to fix. * @param newObjectName - Name of the new object to use for destructuring. * @param destructElementText - Generated text for destructuring elements. * @returns Array of autofix suggestions or undefined. */ private static genAutofixForObjDecls( - variableDeclaration: ts.VariableDeclaration | ts.ParameterDeclaration, + variableDeclaration: ts.VariableDeclaration, newObjectName: string | undefined, destructElementText: string, isIdentifier: boolean @@ -207,13 +206,9 @@ export class Autofixer { * @param variableDeclaration - The variable or parameter declaration to check for boundary conditions. * @returns A boolean indicating if the declaration passes the boundary checks. */ - private static passBoundaryCheckForObjDecls( - faultId: number, - variableDeclaration: ts.VariableDeclaration | ts.ParameterDeclaration - ): boolean { + private static passBoundaryCheckForObjDecls(variableDeclaration: ts.VariableDeclaration): boolean { // Check if the fault ID is for a destructuring parameter or if the declaration has a spread operator if ( - faultId === FaultID.DestructuringParameter || TsUtils.destructuringDeclarationHasSpreadOperator(variableDeclaration.name as ts.BindingPattern) || TsUtils.destructuringDeclarationHasDefaultValue(variableDeclaration.name as ts.BindingPattern) ) { @@ -235,15 +230,12 @@ export class Autofixer { /** ** Fixes object binding pattern declarations by generating appropriate autofix suggestions. - * @param variableDeclaration - The variable or parameter declaration to fix. + * @param variableDeclaration - The variable declaration to fix. * @param faultId - The fault ID indicating the type of check to perform. * @returns Array of autofix suggestions or undefined. */ - fixObjectBindingPatternDeclarations( - variableDeclaration: ts.VariableDeclaration | ts.ParameterDeclaration, - faultId: number - ): Autofix[] | undefined { - if (!Autofixer.passBoundaryCheckForObjDecls(faultId, variableDeclaration)) { + fixObjectBindingPatternDeclarations(variableDeclaration: ts.VariableDeclaration): Autofix[] | undefined { + if (!Autofixer.passBoundaryCheckForObjDecls(variableDeclaration)) { return undefined; } // Map to hold variable names and their corresponding property names @@ -336,13 +328,13 @@ export class Autofixer { /** * Creates autofix suggestions for array destructuring assignment. - * @param variableDeclaration - The variable or parameter declaration to fix. + * @param variableDeclaration - The variable declaration to fix. * @param newArrayName - Name of the new array to use for destructuring. * @param destructElementText - Generated text for destructuring elements. * @returns Array of autofix suggestions. */ private static genAutofixForArrayDecls( - variableDeclaration: ts.VariableDeclaration | ts.ParameterDeclaration, + variableDeclaration: ts.VariableDeclaration, newArrayName: string | undefined, destructElementText: string, isIdentifierOrElementAccess: boolean @@ -385,7 +377,7 @@ export class Autofixer { * @returns A boolean indicating if the declaration passes the boundary checks. */ private static passBoundaryCheckForArrayDecls( - variableDeclaration: ts.VariableDeclaration | ts.ParameterDeclaration, + variableDeclaration: ts.VariableDeclaration, isArrayOrTuple: boolean ): boolean { // If it's not an array/tuple or the declaration has a spread operator in destructuring @@ -416,12 +408,12 @@ export class Autofixer { /** * Fixes array binding pattern declarations by generating appropriate autofix suggestions. * - * @param variableDeclaration - The variable or parameter declaration to fix. + * @param variableDeclaration - The variable declaration to fix. * @param isArrayOrTuple - Flag indicating if the declaration is for an array or tuple. * @returns Array of autofix suggestions or undefined. */ fixArrayBindingPatternDeclarations( - variableDeclaration: ts.VariableDeclaration | ts.ParameterDeclaration, + variableDeclaration: ts.VariableDeclaration, isArrayOrTuple: boolean ): Autofix[] | undefined { if (!Autofixer.passBoundaryCheckForArrayDecls(variableDeclaration, isArrayOrTuple)) { diff --git a/ets2panda/linter/src/lib/utils/functions/ArrayUtils.ts b/ets2panda/linter/src/lib/utils/functions/ArrayUtils.ts index 60bb8d6c96..ffd5a98fa4 100644 --- a/ets2panda/linter/src/lib/utils/functions/ArrayUtils.ts +++ b/ets2panda/linter/src/lib/utils/functions/ArrayUtils.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2024 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -23,7 +23,7 @@ export default class ArrayUtils { list: readonly T[], deferChecker: (value: T, index: number, array: readonly T[]) => boolean, callbackfn: (value: T, index: number, array: readonly T[]) => void, - thisArg?: Object + thisArg?: object ): void { if (!list.length) { return; diff --git a/ets2panda/linter/src/lib/utils/functions/LibraryTypeCallDiagnosticChecker.ts b/ets2panda/linter/src/lib/utils/functions/LibraryTypeCallDiagnosticChecker.ts index 3401707156..9d38e6e663 100644 --- a/ets2panda/linter/src/lib/utils/functions/LibraryTypeCallDiagnosticChecker.ts +++ b/ets2panda/linter/src/lib/utils/functions/LibraryTypeCallDiagnosticChecker.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2024 Huawei Device Co., Ltd. + * Copyright (c) 2023-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -133,7 +133,6 @@ export class LibraryTypeCallDiagnosticChecker { }); } - // eslint-disable-next-line max-lines-per-function filterDiagnostics( tscDiagnostics: readonly ts.Diagnostic[], expr: ts.CallExpression | ts.NewExpression, diff --git a/ets2panda/linter/test/main/destructuring_parameters.ets b/ets2panda/linter/test/main/destructuring_parameters.ets index 0c4fdc6492..fca184f731 100644 --- a/ets2panda/linter/test/main/destructuring_parameters.ets +++ b/ets2panda/linter/test/main/destructuring_parameters.ets @@ -13,6 +13,8 @@ * limitations under the License. */ +// issue: 24982: Enable 'autofix' mode for this test to ensure it finishes without crashing + function drawText({ text = '', position: [x, y] = [0, 0] }): void { // NOT OK // Draw text } diff --git a/ets2panda/linter/test/main/destructuring_parameters.ets.args.json b/ets2panda/linter/test/main/destructuring_parameters.ets.args.json new file mode 100644 index 0000000000..4ce1a4c45c --- /dev/null +++ b/ets2panda/linter/test/main/destructuring_parameters.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "autofix": "" + } +} diff --git a/ets2panda/linter/test/main/destructuring_parameters.ets.autofix.json b/ets2panda/linter/test/main/destructuring_parameters.ets.autofix.json new file mode 100644 index 0000000000..3783eb3180 --- /dev/null +++ b/ets2panda/linter/test/main/destructuring_parameters.ets.autofix.json @@ -0,0 +1,304 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 19, + "endLine": 18, + "endColumn": 59, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 10, + "endLine": 21, + "endColumn": 11, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 16, + "endLine": 29, + "endColumn": 2, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 4, + "endLine": 26, + "endColumn": 5, + "problem": "ObjectTypeLiteral", + "autofix": [ + { + "start": 846, + "end": 846, + "replacementText": "interface GeneratedTypeLiteralInterface_1 {\n firstName: string;\n lastName: string;\n}\n" + }, + { + "start": 901, + "end": 945, + "replacementText": "GeneratedTypeLiteralInterface_1" + } + ], + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 19, + "endLine": 30, + "endColumn": 20, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 16, + "endLine": 32, + "endColumn": 17, + "problem": "ObjectLiteralNoContextType", + "autofix": [ + { + "start": 1055, + "end": 1055, + "replacementText": "interface GeneratedObjectLiteralInterface_1 {\n firstName: string;\n lastName: string;\n}\n" + }, + { + "start": 1067, + "end": 1067, + "replacementText": ": GeneratedObjectLiteralInterface_1" + } + ], + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 13, + "endLine": 39, + "endColumn": 23, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 43, + "column": 13, + "endLine": 43, + "endColumn": 33, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 43, + "column": 22, + "endLine": 43, + "endColumn": 23, + "problem": "ObjectTypeLiteral", + "autofix": [ + { + "start": 1219, + "end": 1219, + "replacementText": "interface GeneratedTypeLiteralInterface_2 {\n d: number;\n}\n" + }, + { + "start": 1240, + "end": 1251, + "replacementText": "GeneratedTypeLiteralInterface_2" + } + ], + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 4, + "endLine": 45, + "endColumn": 5, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 47, + "column": 13, + "endLine": 47, + "endColumn": 22, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 46, + "endLine": 49, + "endColumn": 50, + "problem": "PropertyAccessByIndex", + "suggest": "", + "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", + "severity": "ERROR" + }, + { + "line": 51, + "column": 4, + "endLine": 51, + "endColumn": 5, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 53, + "column": 13, + "endLine": 53, + "endColumn": 19, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 58, + "column": 13, + "endLine": 58, + "endColumn": 29, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 63, + "column": 13, + "endLine": 63, + "endColumn": 24, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 68, + "column": 13, + "endLine": 68, + "endColumn": 25, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 13, + "endLine": 73, + "endColumn": 30, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 78, + "column": 13, + "endLine": 78, + "endColumn": 24, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 81, + "column": 4, + "endLine": 81, + "endColumn": 21, + "problem": "ArrayLiteralNoContextType", + "suggest": "", + "rule": "Array literals must contain elements of only inferrable types (arkts-no-noninferrable-arr-literals)", + "severity": "ERROR" + }, + { + "line": 81, + "column": 8, + "endLine": 81, + "endColumn": 9, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 83, + "column": 14, + "endLine": 83, + "endColumn": 36, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 86, + "column": 9, + "endLine": 86, + "endColumn": 27, + "problem": "ArrayLiteralNoContextType", + "suggest": "", + "rule": "Array literals must contain elements of only inferrable types (arkts-no-noninferrable-arr-literals)", + "severity": "ERROR" + }, + { + "line": 86, + "column": 13, + "endLine": 86, + "endColumn": 14, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 88, + "column": 14, + "endLine": 88, + "endColumn": 33, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/destructuring_parameters.ets.json b/ets2panda/linter/test/main/destructuring_parameters.ets.json index ba3275b467..eadaa87a97 100644 --- a/ets2panda/linter/test/main/destructuring_parameters.ets.json +++ b/ets2panda/linter/test/main/destructuring_parameters.ets.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 16, + "line": 18, "column": 19, - "endLine": 16, + "endLine": 18, "endColumn": 59, "problem": "DestructuringParameter", "suggest": "", @@ -25,9 +25,9 @@ "severity": "ERROR" }, { - "line": 19, + "line": 21, "column": 10, - "endLine": 19, + "endLine": 21, "endColumn": 11, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -35,9 +35,9 @@ "severity": "ERROR" }, { - "line": 21, + "line": 23, "column": 16, - "endLine": 27, + "endLine": 29, "endColumn": 2, "problem": "DestructuringParameter", "suggest": "", @@ -45,9 +45,9 @@ "severity": "ERROR" }, { - "line": 24, + "line": 26, "column": 4, - "endLine": 24, + "endLine": 26, "endColumn": 5, "problem": "ObjectTypeLiteral", "suggest": "", @@ -55,9 +55,9 @@ "severity": "ERROR" }, { - "line": 28, + "line": 30, "column": 19, - "endLine": 28, + "endLine": 30, "endColumn": 20, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -65,9 +65,9 @@ "severity": "ERROR" }, { - "line": 30, + "line": 32, "column": 16, - "endLine": 30, + "endLine": 32, "endColumn": 17, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -75,9 +75,9 @@ "severity": "ERROR" }, { - "line": 37, + "line": 39, "column": 13, - "endLine": 37, + "endLine": 39, "endColumn": 23, "problem": "DestructuringParameter", "suggest": "", @@ -85,9 +85,9 @@ "severity": "ERROR" }, { - "line": 41, + "line": 43, "column": 13, - "endLine": 41, + "endLine": 43, "endColumn": 33, "problem": "DestructuringParameter", "suggest": "", @@ -95,9 +95,9 @@ "severity": "ERROR" }, { - "line": 41, + "line": 43, "column": 22, - "endLine": 41, + "endLine": 43, "endColumn": 23, "problem": "ObjectTypeLiteral", "suggest": "", @@ -105,9 +105,9 @@ "severity": "ERROR" }, { - "line": 43, + "line": 45, "column": 4, - "endLine": 43, + "endLine": 45, "endColumn": 5, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -115,9 +115,9 @@ "severity": "ERROR" }, { - "line": 45, + "line": 47, "column": 13, - "endLine": 45, + "endLine": 47, "endColumn": 22, "problem": "DestructuringParameter", "suggest": "", @@ -125,9 +125,9 @@ "severity": "ERROR" }, { - "line": 47, + "line": 49, "column": 46, - "endLine": 47, + "endLine": 49, "endColumn": 50, "problem": "PropertyAccessByIndex", "suggest": "", @@ -135,9 +135,9 @@ "severity": "ERROR" }, { - "line": 49, + "line": 51, "column": 4, - "endLine": 49, + "endLine": 51, "endColumn": 5, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -145,9 +145,9 @@ "severity": "ERROR" }, { - "line": 51, + "line": 53, "column": 13, - "endLine": 51, + "endLine": 53, "endColumn": 19, "problem": "DestructuringParameter", "suggest": "", @@ -155,9 +155,9 @@ "severity": "ERROR" }, { - "line": 56, + "line": 58, "column": 13, - "endLine": 56, + "endLine": 58, "endColumn": 29, "problem": "DestructuringParameter", "suggest": "", @@ -165,9 +165,9 @@ "severity": "ERROR" }, { - "line": 61, + "line": 63, "column": 13, - "endLine": 61, + "endLine": 63, "endColumn": 24, "problem": "DestructuringParameter", "suggest": "", @@ -175,9 +175,9 @@ "severity": "ERROR" }, { - "line": 66, + "line": 68, "column": 13, - "endLine": 66, + "endLine": 68, "endColumn": 25, "problem": "DestructuringParameter", "suggest": "", @@ -185,9 +185,9 @@ "severity": "ERROR" }, { - "line": 71, + "line": 73, "column": 13, - "endLine": 71, + "endLine": 73, "endColumn": 30, "problem": "DestructuringParameter", "suggest": "", @@ -195,9 +195,9 @@ "severity": "ERROR" }, { - "line": 76, + "line": 78, "column": 13, - "endLine": 76, + "endLine": 78, "endColumn": 24, "problem": "DestructuringParameter", "suggest": "", @@ -205,9 +205,9 @@ "severity": "ERROR" }, { - "line": 79, + "line": 81, "column": 4, - "endLine": 79, + "endLine": 81, "endColumn": 21, "problem": "ArrayLiteralNoContextType", "suggest": "", @@ -215,9 +215,9 @@ "severity": "ERROR" }, { - "line": 79, + "line": 81, "column": 8, - "endLine": 79, + "endLine": 81, "endColumn": 9, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -225,9 +225,9 @@ "severity": "ERROR" }, { - "line": 81, + "line": 83, "column": 14, - "endLine": 81, + "endLine": 83, "endColumn": 36, "problem": "DestructuringParameter", "suggest": "", @@ -235,9 +235,9 @@ "severity": "ERROR" }, { - "line": 84, + "line": 86, "column": 9, - "endLine": 84, + "endLine": 86, "endColumn": 27, "problem": "ArrayLiteralNoContextType", "suggest": "", @@ -245,9 +245,9 @@ "severity": "ERROR" }, { - "line": 84, + "line": 86, "column": 13, - "endLine": 84, + "endLine": 86, "endColumn": 14, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -255,9 +255,9 @@ "severity": "ERROR" }, { - "line": 86, + "line": 88, "column": 14, - "endLine": 86, + "endLine": 88, "endColumn": 33, "problem": "DestructuringParameter", "suggest": "", -- Gitee From 703a07956267288fa10ad93b50766d150d75a80f Mon Sep 17 00:00:00 2001 From: ZhongNing Date: Fri, 11 Apr 2025 14:16:52 +0800 Subject: [PATCH 044/268] fix issue for arkts-numeric-semantic Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBZQ7T Test scenarios: new tests added to the linter Signed-off-by: ZhongNing --- ets2panda/linter/src/lib/TypeScriptLinter.ts | 55 ++++++++++++++++++- .../linter/src/lib/autofixes/Autofixer.ts | 35 ++++++++++++ .../src/lib/utils/consts/StringLiteral.ts | 1 + .../linter/test/main/numeric_semantics.ets | 2 + .../main/numeric_semantics.ets.arkts2.json | 30 ++++++++++ .../main/numeric_semantics.ets.autofix.json | 39 ++++++++++++- .../test/main/numeric_semantics.ets.json | 10 ++++ 7 files changed, 169 insertions(+), 3 deletions(-) diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index 8985c35bb7..b770a39de8 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -30,7 +30,12 @@ import { SYMBOL, SYMBOL_CONSTRUCTOR, TsUtils } from './utils/TsUtils'; import { FUNCTION_HAS_NO_RETURN_ERROR_CODE } from './utils/consts/FunctionHasNoReturnErrorCode'; import { LIMITED_STANDARD_UTILITY_TYPES } from './utils/consts/LimitedStandardUtilityTypes'; import { LIKE_FUNCTION } from './utils/consts/LikeFunction'; -import { STRINGLITERAL_NUMBER, STRINGLITERAL_STRING, STRINGLITERAL_INT } from './utils/consts/StringLiteral'; +import { + STRINGLITERAL_NUMBER, + STRINGLITERAL_STRING, + STRINGLITERAL_INT, + STRINGLITERAL_ANY +} from './utils/consts/StringLiteral'; import { NON_INITIALIZABLE_PROPERTY_CLASS_DECORATORS, NON_INITIALIZABLE_PROPERTY_DECORATORS, @@ -2822,6 +2827,52 @@ export class TypeScriptLinter { } this.checkArkTSObjectInterop(tsCallExpr); + this.handleAppStorageCallExpression(tsCallExpr); + } + + private handleAppStorageCallExpression(tsCallExpr: ts.CallExpression): void { + if (!this.options.arkts2 || !tsCallExpr) { + return; + } + if ( + !ts.isBinaryExpression(tsCallExpr.parent) || + tsCallExpr.parent.operatorToken.kind !== ts.SyntaxKind.QuestionQuestionToken + ) { + return; + } + + const varDecl = tsCallExpr.parent.parent; + if (!ts.isVariableDeclaration(varDecl)) { + return; + } + + if (varDecl.type && ts.isTypeReferenceNode(varDecl.type)) { + if (varDecl.type.typeName.getText() === STRINGLITERAL_ANY) { + return; + } + } + + const callReturnType = this.tsTypeChecker.getTypeAtLocation(tsCallExpr); + const isNumberReturnType = callReturnType.flags & ts.TypeFlags.Number; + const isNumberGeneric = ((): boolean => { + if (tsCallExpr.typeArguments?.length !== 1) { + return false; + } + const typeArg = tsCallExpr.typeArguments[0]; + if (typeArg.kind === ts.SyntaxKind.NumberKeyword) { + return true; + } + + if (ts.isTypeReferenceNode(typeArg)) { + return ts.isIdentifier(typeArg.typeName) && typeArg.typeName.text === STRINGLITERAL_NUMBER; + } + return typeArg.getText().trim() === STRINGLITERAL_NUMBER; + })(); + + if (isNumberGeneric && !isNumberReturnType) { + const autofix = this.autofixer?.fixAppStorageCallExpression(tsCallExpr); + this.incrementCounters(tsCallExpr, FaultID.NumericSemantics, autofix); + } } private handleInteropForCallExpression(tsCallExpr: ts.CallExpression): void { @@ -4206,7 +4257,7 @@ export class TypeScriptLinter { } return null; } - + private handleLimitedLiteralType(literalTypeNode: ts.LiteralTypeNode): void { if (!this.options.arkts2 || !literalTypeNode) { return; diff --git a/ets2panda/linter/src/lib/autofixes/Autofixer.ts b/ets2panda/linter/src/lib/autofixes/Autofixer.ts index bfef893582..03ef9a004d 100644 --- a/ets2panda/linter/src/lib/autofixes/Autofixer.ts +++ b/ets2panda/linter/src/lib/autofixes/Autofixer.ts @@ -2912,4 +2912,39 @@ export class Autofixer { return [{ start: binaryExpr.getStart(), end: binaryExpr.getEnd(), replacementText }]; } + + fixAppStorageCallExpression(callExpr: ts.CallExpression): Autofix[] | undefined { + const varDecl = Autofixer.findParentVariableDeclaration(callExpr); + if (!varDecl || varDecl.type) { + return undefined; + } + + const updatedVarDecl = ts.factory.updateVariableDeclaration( + varDecl, + varDecl.name, + undefined, + ts.factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword), + varDecl.initializer + ); + + const replacementText = this.printer.printNode(ts.EmitHint.Unspecified, updatedVarDecl, varDecl.getSourceFile()); + + return [ + { + replacementText, + start: varDecl.getStart(), + end: varDecl.getEnd() + } + ]; + } + + private static findParentVariableDeclaration(node: ts.Node): ts.VariableDeclaration | undefined { + while (node) { + if (ts.isVariableDeclaration(node)) { + return node; + } + node = node.parent; + } + return undefined; + } } diff --git a/ets2panda/linter/src/lib/utils/consts/StringLiteral.ts b/ets2panda/linter/src/lib/utils/consts/StringLiteral.ts index 0f40d6a2d0..27a4b2412d 100644 --- a/ets2panda/linter/src/lib/utils/consts/StringLiteral.ts +++ b/ets2panda/linter/src/lib/utils/consts/StringLiteral.ts @@ -17,3 +17,4 @@ export const STRINGLITERAL_NUMBER = 'number'; export const STRINGLITERAL_NUMBER_ARRAY = 'number[]'; export const STRINGLITERAL_STRING = 'string'; export const STRINGLITERAL_INT = 'int'; +export const STRINGLITERAL_ANY = 'ANY'; diff --git a/ets2panda/linter/test/main/numeric_semantics.ets b/ets2panda/linter/test/main/numeric_semantics.ets index fc52f50758..34a471161c 100755 --- a/ets2panda/linter/test/main/numeric_semantics.ets +++ b/ets2panda/linter/test/main/numeric_semantics.ets @@ -139,3 +139,5 @@ const c1 = 1; export class G{ readonly a5 = 4; } + +const fingerprintPositionY = AppStorage.get(FingerprintConstants.COORDINATE_Y_OF_FINGERPRINT_UD_SCREEN_IN_PX) ?? 0; \ No newline at end of file diff --git a/ets2panda/linter/test/main/numeric_semantics.ets.arkts2.json b/ets2panda/linter/test/main/numeric_semantics.ets.arkts2.json index 78a139f722..60878c95bd 100755 --- a/ets2panda/linter/test/main/numeric_semantics.ets.arkts2.json +++ b/ets2panda/linter/test/main/numeric_semantics.ets.arkts2.json @@ -444,6 +444,26 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 143, + "column": 7, + "endLine": 143, + "endColumn": 123, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 143, + "column": 30, + "endLine": 143, + "endColumn": 118, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { "line": 117, "column": 2, @@ -493,6 +513,16 @@ "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" + }, + { + "line": 143, + "column": 30, + "endLine": 143, + "endColumn": 40, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/numeric_semantics.ets.autofix.json b/ets2panda/linter/test/main/numeric_semantics.ets.autofix.json index 2eb4bebd6e..9593057bff 100755 --- a/ets2panda/linter/test/main/numeric_semantics.ets.autofix.json +++ b/ets2panda/linter/test/main/numeric_semantics.ets.autofix.json @@ -702,6 +702,33 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 143, + "column": 7, + "endLine": 143, + "endColumn": 123, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 143, + "column": 30, + "endLine": 143, + "endColumn": 118, + "problem": "NumericSemantics", + "autofix": [ + { + "replacementText": "fingerprintPositionY: number = AppStorage.get(FingerprintConstants.COORDINATE_Y_OF_FINGERPRINT_UD_SCREEN_IN_PX) ?? 0", + "start": 2952, + "end": 3068 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { "line": 117, "column": 2, @@ -748,11 +775,21 @@ "endLine": 130, "endColumn": 11, "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 143, + "column": 30, + "endLine": 143, + "endColumn": 40, + "problem": "UIInterfaceImport", "autofix": [ { "start": 738, "end": 738, - "replacementText": "\n\nimport { Entry, Component, State, RelativeContainer, Text } from '@kits.ArkUI';\n" + "replacementText": "\n\nimport { Entry, Component, State, RelativeContainer, Text, AppStorage } from '@kits.ArkUI';\n" } ], "suggest": "", diff --git a/ets2panda/linter/test/main/numeric_semantics.ets.json b/ets2panda/linter/test/main/numeric_semantics.ets.json index 35c82b1f9d..95cc38ecce 100755 --- a/ets2panda/linter/test/main/numeric_semantics.ets.json +++ b/ets2panda/linter/test/main/numeric_semantics.ets.json @@ -23,6 +23,16 @@ "suggest": "", "rule": "Definite assignment assertions are not supported (arkts-no-definite-assignment)", "severity": "WARNING" + }, + { + "line": 143, + "column": 7, + "endLine": 143, + "endColumn": 123, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" } ] } \ No newline at end of file -- Gitee From c66e716b7d00c3df5fba1a10f7fc7d3369a289db Mon Sep 17 00:00:00 2001 From: Utku Enes GURSEL Date: Fri, 11 Apr 2025 10:39:37 +0300 Subject: [PATCH 045/268] bug fix for isStringType method Issue:IC0F6N Description: bug fix where if the type we are checking does not have a symbol the cli crashes. Signed-off-by: Utku Enes GURSEL --- ets2panda/linter/src/lib/TypeScriptLinter.ts | 2 +- ets2panda/linter/src/lib/utils/TsUtils.ts | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index b770a39de8..83f581dcc2 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -4214,7 +4214,7 @@ export class TypeScriptLinter { } const typeString = this.tsTypeChecker.typeToString(type); - return (typeString === 'String' || typeString === 'int'); + return typeString === 'String' || typeString === 'int'; } private static isValidNumber(value: number): boolean { diff --git a/ets2panda/linter/src/lib/utils/TsUtils.ts b/ets2panda/linter/src/lib/utils/TsUtils.ts index 555d4d98c2..cb488165e4 100644 --- a/ets2panda/linter/src/lib/utils/TsUtils.ts +++ b/ets2panda/linter/src/lib/utils/TsUtils.ts @@ -2841,6 +2841,9 @@ export class TsUtils { } const symbol = tsType.symbol; + if (symbol === undefined) { + return false; + } const name = this.tsTypeChecker.getFullyQualifiedName(symbol); return name === 'String' && this.isGlobalSymbol(symbol); } -- Gitee From c205239ac30c5a3b160eeecea91919ea15f79db0 Mon Sep 17 00:00:00 2001 From: Okolnov Evgeniy Date: Thu, 10 Apr 2025 22:24:14 +0300 Subject: [PATCH 046/268] Fix crashing for `destructuring parameter` case Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC077R Test scenarios: new tests added to the linter Signed-off-by: Okolnov Evgeniy --- ets2panda/linter/src/lib/TypeScriptLinter.ts | 8 +- .../linter/src/lib/autofixes/Autofixer.ts | 30 +- .../src/lib/utils/functions/ArrayUtils.ts | 2 +- .../LibraryTypeCallDiagnosticChecker.ts | 1 - .../test/main/destructuring_parameters.ets | 2 + .../destructuring_parameters.ets.args.json | 19 ++ .../destructuring_parameters.ets.autofix.json | 304 ++++++++++++++++++ .../main/destructuring_parameters.ets.json | 100 +++--- 8 files changed, 393 insertions(+), 73 deletions(-) create mode 100644 ets2panda/linter/test/main/destructuring_parameters.ets.args.json create mode 100644 ets2panda/linter/test/main/destructuring_parameters.ets.autofix.json diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index 83f581dcc2..839532d2d8 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -1821,7 +1821,9 @@ export class TypeScriptLinter { private handleDeclarationDestructuring(decl: ts.VariableDeclaration | ts.ParameterDeclaration): void { const faultId = ts.isVariableDeclaration(decl) ? FaultID.DestructuringDeclaration : FaultID.DestructuringParameter; if (ts.isObjectBindingPattern(decl.name)) { - const autofix = this.autofixer?.fixObjectBindingPatternDeclarations(decl, faultId); + const autofix = ts.isVariableDeclaration(decl) ? + this.autofixer?.fixObjectBindingPatternDeclarations(decl) : + undefined; this.incrementCounters(decl, faultId, autofix); } else if (ts.isArrayBindingPattern(decl.name)) { // Array destructuring is allowed only for Arrays/Tuples and without spread operator. @@ -1838,7 +1840,9 @@ export class TypeScriptLinter { hasNestedObjectDestructuring || TsUtils.destructuringDeclarationHasSpreadOperator(decl.name) ) { - const autofix = this.autofixer?.fixArrayBindingPatternDeclarations(decl, isArrayOrTuple); + const autofix = ts.isVariableDeclaration(decl) ? + this.autofixer?.fixArrayBindingPatternDeclarations(decl, isArrayOrTuple) : + undefined; this.incrementCounters(decl, faultId, autofix); } } diff --git a/ets2panda/linter/src/lib/autofixes/Autofixer.ts b/ets2panda/linter/src/lib/autofixes/Autofixer.ts index 03ef9a004d..d4c25ff2a5 100644 --- a/ets2panda/linter/src/lib/autofixes/Autofixer.ts +++ b/ets2panda/linter/src/lib/autofixes/Autofixer.ts @@ -15,7 +15,6 @@ import * as ts from 'typescript'; import { TsUtils } from '../utils/TsUtils'; -import { FaultID } from '../Problems'; import { scopeContainsThis } from '../utils/functions/ContainsThis'; import { forEachNodeInSubtree } from '../utils/functions/ForEachNodeInSubtree'; import { NameGenerator } from '../utils/functions/NameGenerator'; @@ -159,13 +158,13 @@ export class Autofixer { /** * Creates autofix suggestions for destructuring assignment. - * @param variableDeclaration - The variable or parameter declaration to fix. + * @param variableDeclaration - The variable declaration to fix. * @param newObjectName - Name of the new object to use for destructuring. * @param destructElementText - Generated text for destructuring elements. * @returns Array of autofix suggestions or undefined. */ private static genAutofixForObjDecls( - variableDeclaration: ts.VariableDeclaration | ts.ParameterDeclaration, + variableDeclaration: ts.VariableDeclaration, newObjectName: string | undefined, destructElementText: string, isIdentifier: boolean @@ -207,13 +206,9 @@ export class Autofixer { * @param variableDeclaration - The variable or parameter declaration to check for boundary conditions. * @returns A boolean indicating if the declaration passes the boundary checks. */ - private static passBoundaryCheckForObjDecls( - faultId: number, - variableDeclaration: ts.VariableDeclaration | ts.ParameterDeclaration - ): boolean { + private static passBoundaryCheckForObjDecls(variableDeclaration: ts.VariableDeclaration): boolean { // Check if the fault ID is for a destructuring parameter or if the declaration has a spread operator if ( - faultId === FaultID.DestructuringParameter || TsUtils.destructuringDeclarationHasSpreadOperator(variableDeclaration.name as ts.BindingPattern) || TsUtils.destructuringDeclarationHasDefaultValue(variableDeclaration.name as ts.BindingPattern) ) { @@ -235,15 +230,12 @@ export class Autofixer { /** ** Fixes object binding pattern declarations by generating appropriate autofix suggestions. - * @param variableDeclaration - The variable or parameter declaration to fix. + * @param variableDeclaration - The variable declaration to fix. * @param faultId - The fault ID indicating the type of check to perform. * @returns Array of autofix suggestions or undefined. */ - fixObjectBindingPatternDeclarations( - variableDeclaration: ts.VariableDeclaration | ts.ParameterDeclaration, - faultId: number - ): Autofix[] | undefined { - if (!Autofixer.passBoundaryCheckForObjDecls(faultId, variableDeclaration)) { + fixObjectBindingPatternDeclarations(variableDeclaration: ts.VariableDeclaration): Autofix[] | undefined { + if (!Autofixer.passBoundaryCheckForObjDecls(variableDeclaration)) { return undefined; } // Map to hold variable names and their corresponding property names @@ -336,13 +328,13 @@ export class Autofixer { /** * Creates autofix suggestions for array destructuring assignment. - * @param variableDeclaration - The variable or parameter declaration to fix. + * @param variableDeclaration - The variable declaration to fix. * @param newArrayName - Name of the new array to use for destructuring. * @param destructElementText - Generated text for destructuring elements. * @returns Array of autofix suggestions. */ private static genAutofixForArrayDecls( - variableDeclaration: ts.VariableDeclaration | ts.ParameterDeclaration, + variableDeclaration: ts.VariableDeclaration, newArrayName: string | undefined, destructElementText: string, isIdentifierOrElementAccess: boolean @@ -385,7 +377,7 @@ export class Autofixer { * @returns A boolean indicating if the declaration passes the boundary checks. */ private static passBoundaryCheckForArrayDecls( - variableDeclaration: ts.VariableDeclaration | ts.ParameterDeclaration, + variableDeclaration: ts.VariableDeclaration, isArrayOrTuple: boolean ): boolean { // If it's not an array/tuple or the declaration has a spread operator in destructuring @@ -416,12 +408,12 @@ export class Autofixer { /** * Fixes array binding pattern declarations by generating appropriate autofix suggestions. * - * @param variableDeclaration - The variable or parameter declaration to fix. + * @param variableDeclaration - The variable declaration to fix. * @param isArrayOrTuple - Flag indicating if the declaration is for an array or tuple. * @returns Array of autofix suggestions or undefined. */ fixArrayBindingPatternDeclarations( - variableDeclaration: ts.VariableDeclaration | ts.ParameterDeclaration, + variableDeclaration: ts.VariableDeclaration, isArrayOrTuple: boolean ): Autofix[] | undefined { if (!Autofixer.passBoundaryCheckForArrayDecls(variableDeclaration, isArrayOrTuple)) { diff --git a/ets2panda/linter/src/lib/utils/functions/ArrayUtils.ts b/ets2panda/linter/src/lib/utils/functions/ArrayUtils.ts index 60bb8d6c96..83a75ea2ce 100644 --- a/ets2panda/linter/src/lib/utils/functions/ArrayUtils.ts +++ b/ets2panda/linter/src/lib/utils/functions/ArrayUtils.ts @@ -23,7 +23,7 @@ export default class ArrayUtils { list: readonly T[], deferChecker: (value: T, index: number, array: readonly T[]) => boolean, callbackfn: (value: T, index: number, array: readonly T[]) => void, - thisArg?: Object + thisArg?: object ): void { if (!list.length) { return; diff --git a/ets2panda/linter/src/lib/utils/functions/LibraryTypeCallDiagnosticChecker.ts b/ets2panda/linter/src/lib/utils/functions/LibraryTypeCallDiagnosticChecker.ts index 3401707156..453f5f7e9a 100644 --- a/ets2panda/linter/src/lib/utils/functions/LibraryTypeCallDiagnosticChecker.ts +++ b/ets2panda/linter/src/lib/utils/functions/LibraryTypeCallDiagnosticChecker.ts @@ -133,7 +133,6 @@ export class LibraryTypeCallDiagnosticChecker { }); } - // eslint-disable-next-line max-lines-per-function filterDiagnostics( tscDiagnostics: readonly ts.Diagnostic[], expr: ts.CallExpression | ts.NewExpression, diff --git a/ets2panda/linter/test/main/destructuring_parameters.ets b/ets2panda/linter/test/main/destructuring_parameters.ets index 0c4fdc6492..fca184f731 100644 --- a/ets2panda/linter/test/main/destructuring_parameters.ets +++ b/ets2panda/linter/test/main/destructuring_parameters.ets @@ -13,6 +13,8 @@ * limitations under the License. */ +// issue: 24982: Enable 'autofix' mode for this test to ensure it finishes without crashing + function drawText({ text = '', position: [x, y] = [0, 0] }): void { // NOT OK // Draw text } diff --git a/ets2panda/linter/test/main/destructuring_parameters.ets.args.json b/ets2panda/linter/test/main/destructuring_parameters.ets.args.json new file mode 100644 index 0000000000..4ce1a4c45c --- /dev/null +++ b/ets2panda/linter/test/main/destructuring_parameters.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "autofix": "" + } +} diff --git a/ets2panda/linter/test/main/destructuring_parameters.ets.autofix.json b/ets2panda/linter/test/main/destructuring_parameters.ets.autofix.json new file mode 100644 index 0000000000..3783eb3180 --- /dev/null +++ b/ets2panda/linter/test/main/destructuring_parameters.ets.autofix.json @@ -0,0 +1,304 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 19, + "endLine": 18, + "endColumn": 59, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 10, + "endLine": 21, + "endColumn": 11, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 16, + "endLine": 29, + "endColumn": 2, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 4, + "endLine": 26, + "endColumn": 5, + "problem": "ObjectTypeLiteral", + "autofix": [ + { + "start": 846, + "end": 846, + "replacementText": "interface GeneratedTypeLiteralInterface_1 {\n firstName: string;\n lastName: string;\n}\n" + }, + { + "start": 901, + "end": 945, + "replacementText": "GeneratedTypeLiteralInterface_1" + } + ], + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 19, + "endLine": 30, + "endColumn": 20, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 16, + "endLine": 32, + "endColumn": 17, + "problem": "ObjectLiteralNoContextType", + "autofix": [ + { + "start": 1055, + "end": 1055, + "replacementText": "interface GeneratedObjectLiteralInterface_1 {\n firstName: string;\n lastName: string;\n}\n" + }, + { + "start": 1067, + "end": 1067, + "replacementText": ": GeneratedObjectLiteralInterface_1" + } + ], + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 13, + "endLine": 39, + "endColumn": 23, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 43, + "column": 13, + "endLine": 43, + "endColumn": 33, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 43, + "column": 22, + "endLine": 43, + "endColumn": 23, + "problem": "ObjectTypeLiteral", + "autofix": [ + { + "start": 1219, + "end": 1219, + "replacementText": "interface GeneratedTypeLiteralInterface_2 {\n d: number;\n}\n" + }, + { + "start": 1240, + "end": 1251, + "replacementText": "GeneratedTypeLiteralInterface_2" + } + ], + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 4, + "endLine": 45, + "endColumn": 5, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 47, + "column": 13, + "endLine": 47, + "endColumn": 22, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 46, + "endLine": 49, + "endColumn": 50, + "problem": "PropertyAccessByIndex", + "suggest": "", + "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", + "severity": "ERROR" + }, + { + "line": 51, + "column": 4, + "endLine": 51, + "endColumn": 5, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 53, + "column": 13, + "endLine": 53, + "endColumn": 19, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 58, + "column": 13, + "endLine": 58, + "endColumn": 29, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 63, + "column": 13, + "endLine": 63, + "endColumn": 24, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 68, + "column": 13, + "endLine": 68, + "endColumn": 25, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 13, + "endLine": 73, + "endColumn": 30, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 78, + "column": 13, + "endLine": 78, + "endColumn": 24, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 81, + "column": 4, + "endLine": 81, + "endColumn": 21, + "problem": "ArrayLiteralNoContextType", + "suggest": "", + "rule": "Array literals must contain elements of only inferrable types (arkts-no-noninferrable-arr-literals)", + "severity": "ERROR" + }, + { + "line": 81, + "column": 8, + "endLine": 81, + "endColumn": 9, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 83, + "column": 14, + "endLine": 83, + "endColumn": 36, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 86, + "column": 9, + "endLine": 86, + "endColumn": 27, + "problem": "ArrayLiteralNoContextType", + "suggest": "", + "rule": "Array literals must contain elements of only inferrable types (arkts-no-noninferrable-arr-literals)", + "severity": "ERROR" + }, + { + "line": 86, + "column": 13, + "endLine": 86, + "endColumn": 14, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 88, + "column": 14, + "endLine": 88, + "endColumn": 33, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/destructuring_parameters.ets.json b/ets2panda/linter/test/main/destructuring_parameters.ets.json index ba3275b467..eadaa87a97 100644 --- a/ets2panda/linter/test/main/destructuring_parameters.ets.json +++ b/ets2panda/linter/test/main/destructuring_parameters.ets.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 16, + "line": 18, "column": 19, - "endLine": 16, + "endLine": 18, "endColumn": 59, "problem": "DestructuringParameter", "suggest": "", @@ -25,9 +25,9 @@ "severity": "ERROR" }, { - "line": 19, + "line": 21, "column": 10, - "endLine": 19, + "endLine": 21, "endColumn": 11, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -35,9 +35,9 @@ "severity": "ERROR" }, { - "line": 21, + "line": 23, "column": 16, - "endLine": 27, + "endLine": 29, "endColumn": 2, "problem": "DestructuringParameter", "suggest": "", @@ -45,9 +45,9 @@ "severity": "ERROR" }, { - "line": 24, + "line": 26, "column": 4, - "endLine": 24, + "endLine": 26, "endColumn": 5, "problem": "ObjectTypeLiteral", "suggest": "", @@ -55,9 +55,9 @@ "severity": "ERROR" }, { - "line": 28, + "line": 30, "column": 19, - "endLine": 28, + "endLine": 30, "endColumn": 20, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -65,9 +65,9 @@ "severity": "ERROR" }, { - "line": 30, + "line": 32, "column": 16, - "endLine": 30, + "endLine": 32, "endColumn": 17, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -75,9 +75,9 @@ "severity": "ERROR" }, { - "line": 37, + "line": 39, "column": 13, - "endLine": 37, + "endLine": 39, "endColumn": 23, "problem": "DestructuringParameter", "suggest": "", @@ -85,9 +85,9 @@ "severity": "ERROR" }, { - "line": 41, + "line": 43, "column": 13, - "endLine": 41, + "endLine": 43, "endColumn": 33, "problem": "DestructuringParameter", "suggest": "", @@ -95,9 +95,9 @@ "severity": "ERROR" }, { - "line": 41, + "line": 43, "column": 22, - "endLine": 41, + "endLine": 43, "endColumn": 23, "problem": "ObjectTypeLiteral", "suggest": "", @@ -105,9 +105,9 @@ "severity": "ERROR" }, { - "line": 43, + "line": 45, "column": 4, - "endLine": 43, + "endLine": 45, "endColumn": 5, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -115,9 +115,9 @@ "severity": "ERROR" }, { - "line": 45, + "line": 47, "column": 13, - "endLine": 45, + "endLine": 47, "endColumn": 22, "problem": "DestructuringParameter", "suggest": "", @@ -125,9 +125,9 @@ "severity": "ERROR" }, { - "line": 47, + "line": 49, "column": 46, - "endLine": 47, + "endLine": 49, "endColumn": 50, "problem": "PropertyAccessByIndex", "suggest": "", @@ -135,9 +135,9 @@ "severity": "ERROR" }, { - "line": 49, + "line": 51, "column": 4, - "endLine": 49, + "endLine": 51, "endColumn": 5, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -145,9 +145,9 @@ "severity": "ERROR" }, { - "line": 51, + "line": 53, "column": 13, - "endLine": 51, + "endLine": 53, "endColumn": 19, "problem": "DestructuringParameter", "suggest": "", @@ -155,9 +155,9 @@ "severity": "ERROR" }, { - "line": 56, + "line": 58, "column": 13, - "endLine": 56, + "endLine": 58, "endColumn": 29, "problem": "DestructuringParameter", "suggest": "", @@ -165,9 +165,9 @@ "severity": "ERROR" }, { - "line": 61, + "line": 63, "column": 13, - "endLine": 61, + "endLine": 63, "endColumn": 24, "problem": "DestructuringParameter", "suggest": "", @@ -175,9 +175,9 @@ "severity": "ERROR" }, { - "line": 66, + "line": 68, "column": 13, - "endLine": 66, + "endLine": 68, "endColumn": 25, "problem": "DestructuringParameter", "suggest": "", @@ -185,9 +185,9 @@ "severity": "ERROR" }, { - "line": 71, + "line": 73, "column": 13, - "endLine": 71, + "endLine": 73, "endColumn": 30, "problem": "DestructuringParameter", "suggest": "", @@ -195,9 +195,9 @@ "severity": "ERROR" }, { - "line": 76, + "line": 78, "column": 13, - "endLine": 76, + "endLine": 78, "endColumn": 24, "problem": "DestructuringParameter", "suggest": "", @@ -205,9 +205,9 @@ "severity": "ERROR" }, { - "line": 79, + "line": 81, "column": 4, - "endLine": 79, + "endLine": 81, "endColumn": 21, "problem": "ArrayLiteralNoContextType", "suggest": "", @@ -215,9 +215,9 @@ "severity": "ERROR" }, { - "line": 79, + "line": 81, "column": 8, - "endLine": 79, + "endLine": 81, "endColumn": 9, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -225,9 +225,9 @@ "severity": "ERROR" }, { - "line": 81, + "line": 83, "column": 14, - "endLine": 81, + "endLine": 83, "endColumn": 36, "problem": "DestructuringParameter", "suggest": "", @@ -235,9 +235,9 @@ "severity": "ERROR" }, { - "line": 84, + "line": 86, "column": 9, - "endLine": 84, + "endLine": 86, "endColumn": 27, "problem": "ArrayLiteralNoContextType", "suggest": "", @@ -245,9 +245,9 @@ "severity": "ERROR" }, { - "line": 84, + "line": 86, "column": 13, - "endLine": 84, + "endLine": 86, "endColumn": 14, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -255,9 +255,9 @@ "severity": "ERROR" }, { - "line": 86, + "line": 88, "column": 14, - "endLine": 86, + "endLine": 88, "endColumn": 33, "problem": "DestructuringParameter", "suggest": "", -- Gitee From 276f6dd7e5c01d5ba2f54772e8cda578f6c90502 Mon Sep 17 00:00:00 2001 From: cihatfurkaneken Date: Fri, 11 Apr 2025 18:59:07 +0300 Subject: [PATCH 047/268] change check for worker symbol Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC0JFU Signed-off-by: cihatfurkaneken --- ets2panda/linter/src/lib/TypeScriptLinter.ts | 35 +++--- .../test/main/oh_modules/@kit.ArkTS.d.ets | 16 --- .../test/main/oh_modules/@ohos.worker.d.ets | 28 ----- ets2panda/linter/test/main/worker_module.ets | 26 +--- .../test/main/worker_module.ets.arkts2.json | 114 ++---------------- 5 files changed, 30 insertions(+), 189 deletions(-) delete mode 100644 ets2panda/linter/test/main/oh_modules/@kit.ArkTS.d.ets delete mode 100644 ets2panda/linter/test/main/oh_modules/@ohos.worker.d.ets diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index 839532d2d8..8508d969ae 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -769,6 +769,7 @@ export class TypeScriptLinter { // handle no side effect import in sendable module this.handleSharedModuleNoSideEffectImport(importDeclNode); this.handleInvalidIdentifier(importDeclNode); + this.checkWorkerImport(importDeclNode); } private handleImportModule(importDeclNode: ts.ImportDeclaration): void { @@ -2403,10 +2404,6 @@ export class TypeScriptLinter { if (isArkTs2 && this.tsTypeChecker.isArgumentsSymbol(tsIdentSym)) { this.incrementCounters(node, FaultID.ArgumentsObject); } - - if (isArkTs2) { - this.checkWorkerSymbol(tsIdentSym, node); - } if (isArkTs2 && tsIdentifier.text === LIKE_FUNCTION && isStdLibrarySymbol(tsIdentSym)) { this.incrementCounters(node, FaultID.ExplicitFunctionType); } @@ -4707,21 +4704,25 @@ export class TypeScriptLinter { } } - private checkWorkerSymbol(symbol: ts.Symbol, node: ts.Node): void { - if (symbol.name === WORKER_TEXT) { - const decl = TsUtils.getDeclaration(symbol); + private checkWorkerImport(node: ts.ImportDeclaration): void { + if (!this.options.arkts2) { + return; + } + const moduleSpecifier = (node.moduleSpecifier as ts.StringLiteral).text; + if (!WORKER_MODULES.includes(moduleSpecifier)) { + return; + } - if (!decl) { - return; - } - const sourceFile = decl.getSourceFile(); - const fileName = path.basename(sourceFile.fileName); - if ( - WORKER_MODULES.some((moduleName) => { - return fileName.startsWith(moduleName); - }) - ) { + const namedBindings = node.importClause?.namedBindings; + if (!namedBindings || namedBindings.kind !== ts.SyntaxKind.NamedImports) { + return; + } + const elements = namedBindings.elements; + for (const el of elements) { + const importedName = el.propertyName?.text ?? el.name.text; + if (importedName === WORKER_TEXT) { this.incrementCounters(node, FaultID.LimitedStdLibApi); + return; } } } diff --git a/ets2panda/linter/test/main/oh_modules/@kit.ArkTS.d.ets b/ets2panda/linter/test/main/oh_modules/@kit.ArkTS.d.ets deleted file mode 100644 index ed88cb6a2d..0000000000 --- a/ets2panda/linter/test/main/oh_modules/@kit.ArkTS.d.ets +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -export { worker } from '../oh_modules/@ohos.worker'; \ No newline at end of file diff --git a/ets2panda/linter/test/main/oh_modules/@ohos.worker.d.ets b/ets2panda/linter/test/main/oh_modules/@ohos.worker.d.ets deleted file mode 100644 index 74748df41d..0000000000 --- a/ets2panda/linter/test/main/oh_modules/@ohos.worker.d.ets +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -export namespace worker { - export class ThreadWorker { - constructor(scriptURL: string, options?: WorkerOptions); - postMessage(message: any, transfer?: Transferable[]): void; - terminate(): void; - on(type: string, listener: (data: any) => void): void; - } - - export interface WorkerOptions { - type?: "classic" | "module"; - name?: string; - } -} \ No newline at end of file diff --git a/ets2panda/linter/test/main/worker_module.ets b/ets2panda/linter/test/main/worker_module.ets index dc6f082a9f..5eb608bafe 100644 --- a/ets2panda/linter/test/main/worker_module.ets +++ b/ets2panda/linter/test/main/worker_module.ets @@ -13,28 +13,12 @@ * limitations under the License. */ -import { worker } from './oh_modules/@ohos.worker'; +import { worker, MessageEvents } from '@kit.ArkTS'; -import { worker as workerAlias } from './oh_modules/@ohos.worker'; +import { process } from '@kit.ArkTS'; //legal -import { worker as kitWorker } from './oh_modules/@kit.ArkTS'; +import { worker as workerAlias } from '@ohos.worker'; -import { worker as definedWorker } from 'user_defined_worker'; //legal - -export { worker } from './oh_modules/@ohos.worker'; - -function testWorkerUsage() { - - const worker1: worker.ThreadWorker = new worker.ThreadWorker('script.js'); - - const worker2 = new workerAlias.ThreadWorker('script.js'); +import { worker as kitWorker } from '@kit.ArkTS'; - const worker3 = new kitWorker.ThreadWorker('script.js'); - - let worker4: workerAlias.ThreadWorker('script.js'); - - const worker5: workerAlias.ThreadWorker = new workerAlias.ThreadWorker('script.js'); - - let worker6: definedWorker.ThreadWorker('script.js'); // legal - -} \ No newline at end of file +import { worker as definedWorker } from 'user_defined_worker'; //legal diff --git a/ets2panda/linter/test/main/worker_module.ets.arkts2.json b/ets2panda/linter/test/main/worker_module.ets.arkts2.json index e041799b6c..9dea915ba6 100644 --- a/ets2panda/linter/test/main/worker_module.ets.arkts2.json +++ b/ets2panda/linter/test/main/worker_module.ets.arkts2.json @@ -16,29 +16,9 @@ "result": [ { "line": 16, - "column": 10, + "column": 1, "endLine": 16, - "endColumn": 16, - "problem": "LimitedStdLibApi", - "suggest": "", - "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", - "severity": "ERROR" - }, - { - "line": 18, - "column": 10, - "endLine": 18, - "endColumn": 16, - "problem": "LimitedStdLibApi", - "suggest": "", - "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", - "severity": "ERROR" - }, - { - "line": 18, - "column": 20, - "endLine": 18, - "endColumn": 31, + "endColumn": 52, "problem": "LimitedStdLibApi", "suggest": "", "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", @@ -46,103 +26,23 @@ }, { "line": 20, - "column": 10, + "column": 1, "endLine": 20, - "endColumn": 16, - "problem": "LimitedStdLibApi", - "suggest": "", - "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", - "severity": "ERROR" - }, - { - "line": 20, - "column": 20, - "endLine": 20, - "endColumn": 29, - "problem": "LimitedStdLibApi", - "suggest": "", - "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", - "severity": "ERROR" - }, - { - "line": 24, - "column": 10, - "endLine": 24, - "endColumn": 16, - "problem": "LimitedStdLibApi", - "suggest": "", - "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", - "severity": "ERROR" - }, - { - "line": 28, - "column": 18, - "endLine": 28, - "endColumn": 24, + "endColumn": 54, "problem": "LimitedStdLibApi", "suggest": "", "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", "severity": "ERROR" }, { - "line": 28, - "column": 44, - "endLine": 28, + "line": 22, + "column": 1, + "endLine": 22, "endColumn": 50, "problem": "LimitedStdLibApi", "suggest": "", "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", "severity": "ERROR" - }, - { - "line": 30, - "column": 23, - "endLine": 30, - "endColumn": 34, - "problem": "LimitedStdLibApi", - "suggest": "", - "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", - "severity": "ERROR" - }, - { - "line": 32, - "column": 23, - "endLine": 32, - "endColumn": 32, - "problem": "LimitedStdLibApi", - "suggest": "", - "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", - "severity": "ERROR" - }, - { - "line": 34, - "column": 16, - "endLine": 34, - "endColumn": 27, - "problem": "LimitedStdLibApi", - "suggest": "", - "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", - "severity": "ERROR" - }, - { - "line": 36, - "column": 18, - "endLine": 36, - "endColumn": 29, - "problem": "LimitedStdLibApi", - "suggest": "", - "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", - "severity": "ERROR" - }, - { - "line": 36, - "column": 49, - "endLine": 36, - "endColumn": 60, - "problem": "LimitedStdLibApi", - "suggest": "", - "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", - "severity": "ERROR" } ] } \ No newline at end of file -- Gitee From 61443fcb84f064c6383b7d41cd955dd776483a1b Mon Sep 17 00:00:00 2001 From: zhongning Date: Tue, 8 Apr 2025 17:49:16 +0800 Subject: [PATCH 048/268] fix issue for arkts-no-ts-overload Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBYX0U Test scenarios:fix issues Signed-off-by:zhongning --- ets2panda/linter/src/lib/TypeScriptLinter.ts | 17 ++++++++++++----- .../property_decl_on_function.ets.arkts2.json | 10 ---------- ets2panda/linter/test/main/ts_overload.ets | 7 ++++++- .../test/main/ts_overload.ets.arkts2.json | 10 ++++++++++ 4 files changed, 28 insertions(+), 16 deletions(-) diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index 8508d969ae..83c1e38ab9 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -4108,11 +4108,18 @@ export class TypeScriptLinter { } if (decl.name) { const symbol = this.tsTypeChecker.getSymbolAtLocation(decl.name); - if (symbol) { - const declarations = symbol.getDeclarations(); - if (declarations && declarations.length > 1) { - this.incrementCounters(decl, FaultID.TsOverload); - } + if (!symbol) { + return; + } + const declarations = symbol.getDeclarations(); + if (!declarations) { + return; + } + const filterDecl = declarations.filter((name) => { + return ts.isFunctionDeclaration(name) || ts.isMethodDeclaration(name); + }); + if (filterDecl.length > 1) { + this.incrementCounters(decl, FaultID.TsOverload); } } else if (ts.isConstructorDeclaration(decl)) { const parent = decl.parent; diff --git a/ets2panda/linter/test/main/property_decl_on_function.ets.arkts2.json b/ets2panda/linter/test/main/property_decl_on_function.ets.arkts2.json index 75c1cb8679..f7836beb52 100644 --- a/ets2panda/linter/test/main/property_decl_on_function.ets.arkts2.json +++ b/ets2panda/linter/test/main/property_decl_on_function.ets.arkts2.json @@ -14,16 +14,6 @@ "limitations under the License." ], "result": [ - { - "line": 16, - "column": 1, - "endLine": 18, - "endColumn": 2, - "problem": "TsOverload", - "suggest": "", - "rule": "Class TS overloading is not supported(arkts-no-ts-overload)", - "severity": "ERROR" - }, { "line": 20, "column": 1, diff --git a/ets2panda/linter/test/main/ts_overload.ets b/ets2panda/linter/test/main/ts_overload.ets index 25e7ed30ea..40fc4f8024 100644 --- a/ets2panda/linter/test/main/ts_overload.ets +++ b/ets2panda/linter/test/main/ts_overload.ets @@ -54,4 +54,9 @@ abstract class absClass { constructor(...args: number[]) { /* ... */ } -} \ No newline at end of file +} +function func(){ + console.log("ArkTs foo4") +} + +func.val = "0xff"; \ No newline at end of file diff --git a/ets2panda/linter/test/main/ts_overload.ets.arkts2.json b/ets2panda/linter/test/main/ts_overload.ets.arkts2.json index 191fb8f526..4c34eae345 100644 --- a/ets2panda/linter/test/main/ts_overload.ets.arkts2.json +++ b/ets2panda/linter/test/main/ts_overload.ets.arkts2.json @@ -163,6 +163,16 @@ "suggest": "", "rule": "Class TS overloading is not supported(arkts-no-ts-overload)", "severity": "ERROR" + }, + { + "line": 62, + "column": 1, + "endLine": 62, + "endColumn": 5, + "problem": "PropertyDeclOnFunction", + "suggest": "", + "rule": "Declaring properties on functions is not supported (arkts-no-func-props)", + "severity": "ERROR" } ] } \ No newline at end of file -- Gitee From 88d46f1b132fdffe30ec2f0331df719c6d57eca4 Mon Sep 17 00:00:00 2001 From: wangjiaqiang Date: Wed, 9 Apr 2025 16:43:51 +0800 Subject: [PATCH 049/268] Fix arkts-invalid-identifier for interface Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBYWXC Signed-off-by: wangjiaqiang --- ets2panda/linter/src/lib/TypeScriptLinter.ts | 6 + .../linter/test/main/invalid_identifier.ets | 10 + .../main/invalid_identifier.ets.arkts2.json | 216 ++++++++++-------- 3 files changed, 134 insertions(+), 98 deletions(-) diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index 83c1e38ab9..e8e20b111a 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -665,6 +665,11 @@ export class TypeScriptLinter { this.options.cancellationToken?.throwIfCancellationRequested(); const interfaceNode = node as ts.InterfaceDeclaration; + + if (this.options.arkts2) { + this.handleInvalidIdentifier(interfaceNode); + } + const iSymbol = this.tsUtils.trueSymbolAtLocation(interfaceNode.name); const iDecls = iSymbol ? iSymbol.getDeclarations() : null; if (iDecls) { @@ -4608,6 +4613,7 @@ export class TypeScriptLinter { | ts.EnumDeclaration | ts.EnumMember | ts.ModuleDeclaration + | ts.InterfaceDeclaration ): void { if (!this.options.arkts2) { return; diff --git a/ets2panda/linter/test/main/invalid_identifier.ets b/ets2panda/linter/test/main/invalid_identifier.ets index 0b9bba4864..ade4397a20 100755 --- a/ets2panda/linter/test/main/invalid_identifier.ets +++ b/ets2panda/linter/test/main/invalid_identifier.ets @@ -208,4 +208,14 @@ enum char { namespace char { let number : number +} + +namespace quarantine { + interface int { + test: short + } + + interface test { + int: int + } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/invalid_identifier.ets.arkts2.json b/ets2panda/linter/test/main/invalid_identifier.ets.arkts2.json index 15d99566df..f25f62f469 100755 --- a/ets2panda/linter/test/main/invalid_identifier.ets.arkts2.json +++ b/ets2panda/linter/test/main/invalid_identifier.ets.arkts2.json @@ -665,104 +665,124 @@ "severity": "ERROR" }, { - "line": 204, - "column": 3, - "endLine": 204, - "endColumn": 8, - "problem": "InvalidIdentifier", - "suggest": "", - "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", - "severity": "ERROR" - }, - { - "line": 205, - "column": 3, - "endLine": 205, - "endColumn": 9, - "problem": "InvalidIdentifier", - "suggest": "", - "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", - "severity": "ERROR" - }, - { - "line": 206, - "column": 3, - "endLine": 206, - "endColumn": 6, - "problem": "InvalidIdentifier", - "suggest": "", - "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", - "severity": "ERROR" - }, - { - "line": 209, - "column": 11, - "endLine": 209, - "endColumn": 15, - "problem": "InvalidIdentifier", - "suggest": "", - "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", - "severity": "ERROR" - }, - { - "line": 210, - "column": 9, - "endLine": 210, - "endColumn": 15, - "problem": "InvalidIdentifier", - "suggest": "", - "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", - "severity": "ERROR" - }, - { - "line": 172, - "column": 2, - "endLine": 172, - "endColumn": 7, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 173, - "column": 2, - "endLine": 173, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 175, - "column": 4, - "endLine": 175, - "endColumn": 9, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 181, - "column": 5, - "endLine": 181, - "endColumn": 22, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 182, - "column": 7, - "endLine": 182, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" + "line": 204, + "column": 3, + "endLine": 204, + "endColumn": 8, + "problem": "InvalidIdentifier", + "suggest": "", + "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", + "severity": "ERROR" + }, + { + "line": 205, + "column": 3, + "endLine": 205, + "endColumn": 9, + "problem": "InvalidIdentifier", + "suggest": "", + "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", + "severity": "ERROR" + }, + { + "line": 206, + "column": 3, + "endLine": 206, + "endColumn": 6, + "problem": "InvalidIdentifier", + "suggest": "", + "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", + "severity": "ERROR" + }, + { + "line": 209, + "column": 11, + "endLine": 209, + "endColumn": 15, + "problem": "InvalidIdentifier", + "suggest": "", + "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", + "severity": "ERROR" + }, + { + "line": 210, + "column": 9, + "endLine": 210, + "endColumn": 15, + "problem": "InvalidIdentifier", + "suggest": "", + "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", + "severity": "ERROR" + }, + { + "line": 214, + "column": 13, + "endLine": 214, + "endColumn": 16, + "problem": "InvalidIdentifier", + "suggest": "", + "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", + "severity": "ERROR" + }, + { + "line": 219, + "column": 7, + "endLine": 219, + "endColumn": 10, + "problem": "InvalidIdentifier", + "suggest": "", + "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", + "severity": "ERROR" + }, + { + "line": 172, + "column": 2, + "endLine": 172, + "endColumn": 7, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 173, + "column": 2, + "endLine": 173, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 175, + "column": 4, + "endLine": 175, + "endColumn": 9, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 181, + "column": 5, + "endLine": 181, + "endColumn": 22, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 182, + "column": 7, + "endLine": 182, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" } ] } \ No newline at end of file -- Gitee From 5eaf86328a40d8a7bfffc68abede6f8066292066 Mon Sep 17 00:00:00 2001 From: lizhonghan Date: Thu, 10 Apr 2025 12:14:20 +0800 Subject: [PATCH 050/268] add sdk whitelist 1. add sdk whitelist 2. update eslint allow json ext Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBZJ7M Change-Id: Ic9b42caec741fe13ac9b5b43ab24294e515c8ed3 Signed-off-by: lizhonghan --- ets2panda/linter/eslint.config.mjs | 2 +- ets2panda/linter/package.json | 2 +- ets2panda/linter/src/lib/CookBookMsg.ts | 3 +- ets2panda/linter/src/lib/FaultAttrs.ts | 1 + ets2panda/linter/src/lib/FaultDesc.ts | 2 + ets2panda/linter/src/lib/LinterRunner.ts | 3 + ets2panda/linter/src/lib/Problems.ts | 1 + ets2panda/linter/src/lib/TypeScriptLinter.ts | 123 ++++++++++++++++++ .../linter/src/lib/data/SdkWhitelist.json | 54 ++++++++ .../src/lib/utils/consts/ArkTS2Rules.ts | 3 +- .../src/lib/utils/consts/SdkWhitelist.ts | 97 ++++++++++++++ .../test/sdkwhite/ComputedPropertyName.ets | 32 +++++ .../ComputedPropertyName.ets.arkts2.json | 19 +++ .../sdkwhite/ComputedPropertyName.ets.json | 118 +++++++++++++++++ .../linter/test/sdkwhite/ConstructorFuncs.ets | 109 ++++++++++++++++ .../sdkwhite/ConstructorFuncs.ets.arkts2.json | 19 +++ .../test/sdkwhite/ConstructorFuncs.ets.json | 108 +++++++++++++++ .../test/sdkwhite/ConstructorIface4.ets | 21 +++ .../ConstructorIface4.ets.arkts2.json | 19 +++ .../test/sdkwhite/ConstructorIface4.ets.json | 17 +++ .../test/sdkwhite/DeclWithDuplicateName5.ets | 23 ++++ .../DeclWithDuplicateName5.ets.arkts2.json | 19 +++ .../sdkwhite/DeclWithDuplicateName5.ets.json | 17 +++ .../sdkwhite/GlobalThisError&TypeQuery.ets | 16 +++ .../GlobalThisError&TypeQuery.ets.arkts2.json | 19 +++ .../GlobalThisError&TypeQuery.ets.json | 17 +++ .../test/sdkwhite/IndexedAccessType.ets | 25 ++++ .../IndexedAccessType.ets.arkts2.json | 19 +++ .../test/sdkwhite/IndexedAccessType.ets.json | 17 +++ .../test/sdkwhite/InterfaceExtendsClass.ets | 20 +++ .../InterfaceExtendsClass.ets.arkts2.json | 19 +++ .../sdkwhite/InterfaceExtendsClass.ets.json | 17 +++ .../linter/test/sdkwhite/LimitedVoidType3.ets | 27 ++++ .../sdkwhite/LimitedVoidType3.ets.arkts2.json | 19 +++ .../test/sdkwhite/LimitedVoidType3.ets.json | 28 ++++ .../test/sdkwhite/LiteralAsPropertyName2.ets | 30 +++++ .../LiteralAsPropertyName2.ets.arkts2.json | 19 +++ .../sdkwhite/LiteralAsPropertyName2.ets.json | 17 +++ .../linter/test/sdkwhite/OptionalMethod1.ets | 68 ++++++++++ .../sdkwhite/OptionalMethod1.ets.arkts2.json | 19 +++ .../test/sdkwhite/OptionalMethod1.ets.json | 17 +++ .../linter/test/sdkwhite/SendablePropType.ets | 16 +++ .../sdkwhite/SendablePropType.ets.arkts2.json | 19 +++ .../test/sdkwhite/SendablePropType.ets.json | 17 +++ .../test/sdkwhite/limit_void_type_sdk.ets | 26 ++++ .../limit_void_type_sdk.ets.args.json | 19 +++ .../limit_void_type_sdk.ets.arkts2.json | 48 +++++++ .../sdkwhite/limit_void_type_sdk.ets.json | 19 +++ .../test/sdkwhite/limit_void_type_sdk2.ets | 25 ++++ .../limit_void_type_sdk2.ets.args.json | 19 +++ .../limit_void_type_sdk2.ets.arkts2.json | 48 +++++++ .../sdkwhite/limit_void_type_sdk2.ets.json | 28 ++++ ets2panda/linter/tsconfig.json | 3 +- 53 files changed, 1507 insertions(+), 5 deletions(-) create mode 100644 ets2panda/linter/src/lib/data/SdkWhitelist.json create mode 100644 ets2panda/linter/src/lib/utils/consts/SdkWhitelist.ts create mode 100644 ets2panda/linter/test/sdkwhite/ComputedPropertyName.ets create mode 100644 ets2panda/linter/test/sdkwhite/ComputedPropertyName.ets.arkts2.json create mode 100644 ets2panda/linter/test/sdkwhite/ComputedPropertyName.ets.json create mode 100644 ets2panda/linter/test/sdkwhite/ConstructorFuncs.ets create mode 100644 ets2panda/linter/test/sdkwhite/ConstructorFuncs.ets.arkts2.json create mode 100644 ets2panda/linter/test/sdkwhite/ConstructorFuncs.ets.json create mode 100644 ets2panda/linter/test/sdkwhite/ConstructorIface4.ets create mode 100644 ets2panda/linter/test/sdkwhite/ConstructorIface4.ets.arkts2.json create mode 100644 ets2panda/linter/test/sdkwhite/ConstructorIface4.ets.json create mode 100644 ets2panda/linter/test/sdkwhite/DeclWithDuplicateName5.ets create mode 100644 ets2panda/linter/test/sdkwhite/DeclWithDuplicateName5.ets.arkts2.json create mode 100644 ets2panda/linter/test/sdkwhite/DeclWithDuplicateName5.ets.json create mode 100644 ets2panda/linter/test/sdkwhite/GlobalThisError&TypeQuery.ets create mode 100644 ets2panda/linter/test/sdkwhite/GlobalThisError&TypeQuery.ets.arkts2.json create mode 100644 ets2panda/linter/test/sdkwhite/GlobalThisError&TypeQuery.ets.json create mode 100644 ets2panda/linter/test/sdkwhite/IndexedAccessType.ets create mode 100644 ets2panda/linter/test/sdkwhite/IndexedAccessType.ets.arkts2.json create mode 100644 ets2panda/linter/test/sdkwhite/IndexedAccessType.ets.json create mode 100644 ets2panda/linter/test/sdkwhite/InterfaceExtendsClass.ets create mode 100644 ets2panda/linter/test/sdkwhite/InterfaceExtendsClass.ets.arkts2.json create mode 100644 ets2panda/linter/test/sdkwhite/InterfaceExtendsClass.ets.json create mode 100644 ets2panda/linter/test/sdkwhite/LimitedVoidType3.ets create mode 100644 ets2panda/linter/test/sdkwhite/LimitedVoidType3.ets.arkts2.json create mode 100644 ets2panda/linter/test/sdkwhite/LimitedVoidType3.ets.json create mode 100644 ets2panda/linter/test/sdkwhite/LiteralAsPropertyName2.ets create mode 100644 ets2panda/linter/test/sdkwhite/LiteralAsPropertyName2.ets.arkts2.json create mode 100644 ets2panda/linter/test/sdkwhite/LiteralAsPropertyName2.ets.json create mode 100644 ets2panda/linter/test/sdkwhite/OptionalMethod1.ets create mode 100644 ets2panda/linter/test/sdkwhite/OptionalMethod1.ets.arkts2.json create mode 100644 ets2panda/linter/test/sdkwhite/OptionalMethod1.ets.json create mode 100644 ets2panda/linter/test/sdkwhite/SendablePropType.ets create mode 100644 ets2panda/linter/test/sdkwhite/SendablePropType.ets.arkts2.json create mode 100644 ets2panda/linter/test/sdkwhite/SendablePropType.ets.json create mode 100644 ets2panda/linter/test/sdkwhite/limit_void_type_sdk.ets create mode 100644 ets2panda/linter/test/sdkwhite/limit_void_type_sdk.ets.args.json create mode 100644 ets2panda/linter/test/sdkwhite/limit_void_type_sdk.ets.arkts2.json create mode 100644 ets2panda/linter/test/sdkwhite/limit_void_type_sdk.ets.json create mode 100644 ets2panda/linter/test/sdkwhite/limit_void_type_sdk2.ets create mode 100644 ets2panda/linter/test/sdkwhite/limit_void_type_sdk2.ets.args.json create mode 100644 ets2panda/linter/test/sdkwhite/limit_void_type_sdk2.ets.arkts2.json create mode 100644 ets2panda/linter/test/sdkwhite/limit_void_type_sdk2.ets.json diff --git a/ets2panda/linter/eslint.config.mjs b/ets2panda/linter/eslint.config.mjs index c803d799b2..ab024a62fd 100644 --- a/ets2panda/linter/eslint.config.mjs +++ b/ets2panda/linter/eslint.config.mjs @@ -98,7 +98,7 @@ export default tseslint.config( // imports 'import/no-absolute-path': 'error', - 'n/file-extension-in-import': ['error', 'never'], + 'n/file-extension-in-import': ['error', 'never', { '.json': 'always' }], // style '@stylistic/array-bracket-newline': ['error', 'consistent'], diff --git a/ets2panda/linter/package.json b/ets2panda/linter/package.json index 6b88208578..e93784e047 100644 --- a/ets2panda/linter/package.json +++ b/ets2panda/linter/package.json @@ -20,7 +20,7 @@ "pack:linter": "rimraf bundle && mkdir bundle && npm pack --pack-destination bundle", "pretest": " npm run fix", "test": "npm run test_all && npm run test_ts_import_ets", - "test_all": "npm run testrunner -- -d test/main,test/rules,test/regression,test/extended_features,test/ohmurl,test/interop", + "test_all": "npm run testrunner -- -d test/main,test/rules,test/regression,test/extended_features,test/ohmurl,test/interop,test/sdkwhite", "test_main": "npm run testrunner -- -d test/main", "test_ohmurl": "npm run testrunner -- -d test/ohmurl", "test_interop": "npm run testrunner -- -d test/interop", diff --git a/ets2panda/linter/src/lib/CookBookMsg.ts b/ets2panda/linter/src/lib/CookBookMsg.ts index 2f93d27e5b..cd18f4ebd1 100644 --- a/ets2panda/linter/src/lib/CookBookMsg.ts +++ b/ets2panda/linter/src/lib/CookBookMsg.ts @@ -16,7 +16,7 @@ export const cookBookMsg: string[] = []; export const cookBookTag: string[] = []; -for (let i = 0; i <= 300; i++) { +for (let i = 0; i <= 308; i++) { cookBookMsg[i] = ''; } @@ -274,3 +274,4 @@ cookBookTag[304] = 'Duplicate function name in namespace are not allowed (arkts- cookBookTag[305] = 'Typescript class decorators are not allowed (arkts-interop-no-decorators)'; cookBookTag[306] = 'Cannot access typescript types directly (arkts-interop-access-ts-types)'; cookBookTag[307] = 'Cannot invoke functions implemented in TypeScript (arkts-interop-ts-function)'; +cookBookTag[308] = 'Type "void" has no instances.(arkts-sdk-limited-void-type)'; diff --git a/ets2panda/linter/src/lib/FaultAttrs.ts b/ets2panda/linter/src/lib/FaultAttrs.ts index f2e4a80688..88c49cf845 100644 --- a/ets2panda/linter/src/lib/FaultAttrs.ts +++ b/ets2panda/linter/src/lib/FaultAttrs.ts @@ -186,3 +186,4 @@ faultsAttrs[FaultID.NoDuplicateFunctionName] = new FaultAttributes(304); faultsAttrs[FaultID.InteropNoDecorators] = new FaultAttributes(305); faultsAttrs[FaultID.InteropDirectAccessToTSTypes] = new FaultAttributes(306); faultsAttrs[FaultID.InteropTSFunctionInvoke] = new FaultAttributes(307); +faultsAttrs[FaultID.LimitedVoidTypeFromSdk] = new FaultAttributes(308); diff --git a/ets2panda/linter/src/lib/FaultDesc.ts b/ets2panda/linter/src/lib/FaultDesc.ts index 2d98c1f0d3..cb2ec2ec4e 100644 --- a/ets2panda/linter/src/lib/FaultDesc.ts +++ b/ets2panda/linter/src/lib/FaultDesc.ts @@ -174,3 +174,5 @@ faultDesc[FaultID.InteropCallObjectParam] = 'Interop call with "Object" paramete faultDesc[FaultID.InteropNoDecorators] = 'Interop decorators not supported'; faultDesc[FaultID.InteropDirectAccessToTSTypes] = 'TS Types Access'; faultDesc[FaultID.InteropTSFunctionInvoke] = 'TS Function Invoke'; +faultDesc[FaultID.LimitedVoidTypeFromSdk] = 'Limited void type from sdk'; + diff --git a/ets2panda/linter/src/lib/LinterRunner.ts b/ets2panda/linter/src/lib/LinterRunner.ts index 3e05015802..d7950d10d9 100644 --- a/ets2panda/linter/src/lib/LinterRunner.ts +++ b/ets2panda/linter/src/lib/LinterRunner.ts @@ -174,6 +174,9 @@ function lintFiles(srcFiles: ts.SourceFile[], linter: TypeScriptLinter | Interop const problemsInfos: Map = new Map(); for (const srcFile of srcFiles) { + if (linter instanceof TypeScriptLinter) { + linter.initSdkInfo(); + } const prevVisitedNodes = linter.totalVisitedNodes; const prevErrorLines = linter.totalErrorLines; const prevWarningLines = linter.totalWarningLines; diff --git a/ets2panda/linter/src/lib/Problems.ts b/ets2panda/linter/src/lib/Problems.ts index 0db76ca07a..31eb4cdd93 100644 --- a/ets2panda/linter/src/lib/Problems.ts +++ b/ets2panda/linter/src/lib/Problems.ts @@ -175,6 +175,7 @@ export enum FaultID { InteropNoDecorators, InteropDirectAccessToTSTypes, InteropTSFunctionInvoke, + LimitedVoidTypeFromSdk, // this should always be last enum LAST_ID } diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index e8e20b111a..823ccf7e5a 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -89,6 +89,9 @@ import { arkuiImportList } from './utils/consts/ArkuiImportList'; import { REFLECT_PROPERTIES, USE_STATIC } from './utils/consts/InteropAPI'; import { EXTNAME_TS, EXTNAME_D_TS } from './utils/consts/ExtensionName'; import { ARKTS_IGNORE_DIRS_OH_MODULES } from './utils/consts/ArktsIgnorePaths'; +import type { ApiInfo } from './utils/consts/SdkWhitelist'; +import { ApiList } from './utils/consts/SdkWhitelist'; +import * as apiWhiteList from './data/SdkWhitelist.json'; export class TypeScriptLinter { totalVisitedNodes: number = 0; @@ -117,10 +120,19 @@ export class TypeScriptLinter { private static sharedModulesCache: Map; static nameSpaceFunctionCache: Map>; private readonly constVariableInitCache: Map = new Map(); + private funcMap: Map> = new Map>(); + private interfaceMap: Map> = new Map>(); + static pathMap: Map>; static initGlobals(): void { TypeScriptLinter.sharedModulesCache = new Map(); TypeScriptLinter.nameSpaceFunctionCache = new Map>(); + TypeScriptLinter.pathMap = new Map>(); + } + + initSdkInfo(): void { + this.funcMap = new Map>(); + this.interfaceMap = new Map>(); } private initEtsHandlers(): void { @@ -142,6 +154,29 @@ export class TypeScriptLinter { } } + private static initSdkWhitelist(): void { + const list: ApiList = new ApiList(apiWhiteList); + if (list?.api_list?.length > 0) { + for (const item of list.api_list) { + item.file_path.forEach((path) => { + TypeScriptLinter.addOrUpdateData(TypeScriptLinter.pathMap, `'${path}'`, item.api_info); + }); + item.import_path.forEach((path) => { + TypeScriptLinter.addOrUpdateData(TypeScriptLinter.pathMap, `'${path}'`, item.api_info); + }); + } + } + } + + private static addOrUpdateData(map: Map>, path: string, data: ApiInfo): void { + let apiInfos = map.get(path); + if (!apiInfos) { + apiInfos = new Set(); + map.set(path, apiInfos); + } + apiInfos.add(data); + } + constructor( private readonly tsTypeChecker: ts.TypeChecker, readonly options: LinterOptions, @@ -155,6 +190,7 @@ export class TypeScriptLinter { this.compatibleSdkVersionStage = options.compatibleSdkVersionStage || DEFAULT_COMPATIBLE_SDK_VERSION_STAGE; this.initEtsHandlers(); this.initCounters(); + TypeScriptLinter.initSdkWhitelist(); } readonly handlersMap = new Map([ @@ -743,6 +779,19 @@ export class TypeScriptLinter { this.checkForLoopDestructuring(tsForOfInit); } + private updateDataSdkJsonInfo(importDeclNode: ts.ImportDeclaration, importClause: ts.ImportClause): void { + const sdkInfo = TypeScriptLinter.pathMap.get(importDeclNode.moduleSpecifier.getText()); + if (sdkInfo && importClause.namedBindings) { + const namedImports = importClause.namedBindings as ts.NamedImports; + namedImports.elements.forEach((element) => { + const elementName = element.name.getText(); + sdkInfo.forEach((info) => { + TypeScriptLinter.addOrUpdateData(this.interfaceMap, elementName, info); + }); + }); + } + } + private handleImportDeclaration(node: ts.Node): void { // early exit via exception if cancellation was requested this.options.cancellationToken?.throwIfCancellationRequested(); @@ -752,6 +801,8 @@ export class TypeScriptLinter { const importClause = importDeclNode.importClause; if (!importClause || !importClause.name && !importClause.namedBindings) { this.incrementCounters(node, FaultID.NoSideEffectImport); + } else { + this.updateDataSdkJsonInfo(importDeclNode, importClause); } } for (const stmt of importDeclNode.parent.statements) { @@ -1998,6 +2049,78 @@ export class TypeScriptLinter { this.processClassStaticBlocks(tsClassDecl); this.handleInvalidIdentifier(tsClassDecl); + this.handleSdkMethod(tsClassDecl); + } + + private static findFinalExpression(typeNode: ts.TypeNode): ts.Node { + let currentNode = typeNode; + while ((currentNode as any).expression) { + currentNode = (currentNode as any).expression; + } + return currentNode; + } + + private processSdkMethodClauseTypes(tsClassDecl: ts.ClassDeclaration, heritageClause: ts.HeritageClause): void { + for (const type of heritageClause.types) { + const fullTypeName = TypeScriptLinter.findFinalExpression(type).getText(); + const sdkInfos = this.interfaceMap.get(fullTypeName); + if (!sdkInfos || sdkInfos.size === 0) { + continue; + } + + for (const sdkInfo of sdkInfos) { + if (sdkInfo.api_type !== 'MethodSignature') { + continue; + } + this.processSdkInfoWithMembers(sdkInfo, tsClassDecl.members); + } + } + } + + private handleSdkMethod(tsClassDecl: ts.ClassDeclaration): void { + if ( + !this.options.arkts2 || + !tsClassDecl.heritageClauses || + tsClassDecl.heritageClauses.length === 0 || + !tsClassDecl.members || + tsClassDecl.members.length === 0 + ) { + return; + } + + for (const heritageClause of tsClassDecl.heritageClauses) { + if (!heritageClause.types || heritageClause.types.length === 0) { + continue; + } + this.processSdkMethodClauseTypes(tsClassDecl, heritageClause); + } + } + + private processSdkInfoWithMembers(sdkInfo: ApiInfo, members: ts.NodeArray): void { + for (const member of members) { + if (!ts.isMethodDeclaration(member)) { + continue; + } + + const memberName = member.name?.getText(); + if (sdkInfo.api_name === memberName && sdkInfo.api_func_args.length === member.parameters.length) { + if (TypeScriptLinter.areParametersEqual(sdkInfo.api_func_args, member.parameters)) { + this.incrementCounters(member, FaultID.LimitedVoidTypeFromSdk); + } + } + } + } + + private static areParametersEqual( + sdkFuncArgs: { name: string; type: string }[], + memberParams: ts.NodeArray + ): boolean { + for (let i = 0; i < sdkFuncArgs.length; i++) { + if (sdkFuncArgs[i].type !== memberParams[i].type?.getText()) { + return false; + } + } + return true; } private handleNotSupportCustomDecorators(decorator: ts.Decorator): void { diff --git a/ets2panda/linter/src/lib/data/SdkWhitelist.json b/ets2panda/linter/src/lib/data/SdkWhitelist.json new file mode 100644 index 0000000000..6ad29180ae --- /dev/null +++ b/ets2panda/linter/src/lib/data/SdkWhitelist.json @@ -0,0 +1,54 @@ +{ + "api_list": [ + { + "import_path": ["@ohos.arkui.Prefetcher", "@kit.ArkUI"], + "file_path": ["api/@ohos.arkui.Prefetcher.d.ts"], + "is_global": false, + "api_info": { + "problem": "", + "api_name": "prefetch", + "api_type": "MethodSignature", + "api_optional": false, + "api_auto_fix": false, + "api_auto_fix_context": "", + "target_type": "", + "api_func_args": [{ "name": "index", "type": "number", "is_optional": false, "hasDefault": false }], + "parent_api": [ + { + "api_name": "IDataSourcePrefetching", + "api_type": "InterfaceDeclaration" + } + ], + "methd_return_type": "void | Promise", + "codeKind": 173 + } + }, + { + "import_path": ["@hms.collaboration.rcp", "@kit.RemoteCommunicationKit"], + "file_path": ["api/@hms.collaboration.rcp.d.ts"], + "is_global": false, + "api_info": { + "problem": "LimitiedVoidType", + "api_name": "write", + "api_type": "MethodSignature", + "api_optional": false, + "api_auto_fix": false, + "api_auto_fix_context": "", + "target_type": "", + "api_func_args": [{ "name": "buffer", "type": "ArrayBuffer", "is_optional": false, "hasDefault": false }], + "parent_api": [ + { + "api_name": "WriteFile", + "api_type": "InterfaceDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "methd_return_type": "void | Promise", + "codeKind": 115 + } + } + ] +} diff --git a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts index 6487992e66..f1fb4bbe4a 100644 --- a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts +++ b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts @@ -66,5 +66,6 @@ export const arkts2Rules: number[] = [ 304, 305, 306, - 307 + 307, + 308 ]; diff --git a/ets2panda/linter/src/lib/utils/consts/SdkWhitelist.ts b/ets2panda/linter/src/lib/utils/consts/SdkWhitelist.ts new file mode 100644 index 0000000000..cddc6d0964 --- /dev/null +++ b/ets2panda/linter/src/lib/utils/consts/SdkWhitelist.ts @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Define function argument class +export class ApiFuncArg { + name: string; + type: string; + is_optional: boolean; + + constructor(data: Partial) { + this.name = data.name || ''; + this.type = data.type || ''; + this.is_optional = data.is_optional || false; + } +} + +// Define the parent API class (recursive structure) +export class ParentApi { + api_name: string; + api_type: string; + + constructor(data: Partial) { + this.api_name = data.api_name || ''; + this.api_type = data.api_type || ''; + } +} + +// Define the API information class +export class ApiInfo { + problem: string; + api_name: string; + api_type: string; + api_optional: boolean; + api_auto_fix: boolean; + api_auto_fix_context: string; + target_type: string; + api_func_args: ApiFuncArg[]; + parent_api: ParentApi[]; + methd_return_type: string; + codeKind: number; + + constructor(data: Partial) { + this.problem = data.problem || ''; + this.api_name = data.api_name || ''; + this.api_type = data.api_type || ''; + this.api_optional = data.api_optional || false; + this.api_auto_fix = data.api_auto_fix || false; + this.api_auto_fix_context = data.api_auto_fix_context || ''; + this.target_type = data.target_type || ''; + this.api_func_args = (data.api_func_args || []).map((arg) => { + return new ApiFuncArg(arg); + }); + this.parent_api = (data.parent_api || []).map((parent) => { + return new ParentApi(parent); + }); + this.methd_return_type = data.methd_return_type || ''; + this.codeKind = data.codeKind || 0; + } +} + +// Define the API list item class +export class ApiListItem { + import_path: string[]; + file_path: string[]; + api_info: ApiInfo; + is_global: boolean; + + constructor(data: Partial) { + this.import_path = data.import_path || []; + this.file_path = data.file_path || []; + this.api_info = new ApiInfo(data.api_info || {}); + this.is_global = data.is_global || false; + } +} + +// Define the top-level API list class +export class ApiList { + api_list: ApiListItem[]; + + constructor(data: Partial) { + this.api_list = (data.api_list || []).map((item) => { + return new ApiListItem(item); + }); + } +} diff --git a/ets2panda/linter/test/sdkwhite/ComputedPropertyName.ets b/ets2panda/linter/test/sdkwhite/ComputedPropertyName.ets new file mode 100644 index 0000000000..ea2407ae1b --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/ComputedPropertyName.ets @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +const styleMap: ProgressStyleMap = { + 1: { // Error + strokeWidth: 1, + }, + 2: { // Error + strokeWidth: 1, + }, + 3: { // Error + strokeWidth: 1, + }, + 4: { // Error + strokeWidth: 1, + }, + 0: { // Error + + } +}; diff --git a/ets2panda/linter/test/sdkwhite/ComputedPropertyName.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/ComputedPropertyName.ets.arkts2.json new file mode 100644 index 0000000000..5e75d5b3e7 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/ComputedPropertyName.ets.arkts2.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/ComputedPropertyName.ets.json b/ets2panda/linter/test/sdkwhite/ComputedPropertyName.ets.json new file mode 100644 index 0000000000..4d9df55e45 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/ComputedPropertyName.ets.json @@ -0,0 +1,118 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 3, + "endLine": 17, + "endColumn": 4, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 6, + "endLine": 17, + "endColumn": 7, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 3, + "endLine": 20, + "endColumn": 4, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 6, + "endLine": 20, + "endColumn": 7, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 3, + "endLine": 23, + "endColumn": 4, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 6, + "endLine": 23, + "endColumn": 7, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 3, + "endLine": 26, + "endColumn": 4, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 6, + "endLine": 26, + "endColumn": 7, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 3, + "endLine": 29, + "endColumn": 4, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 6, + "endLine": 29, + "endColumn": 7, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/ConstructorFuncs.ets b/ets2panda/linter/test/sdkwhite/ConstructorFuncs.ets new file mode 100644 index 0000000000..81cb6eeb8b --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/ConstructorFuncs.ets @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// 1. First, define the DatabaseObject base class and several entity classes + +// Base database object interface +interface DatabaseObject { + id: number; + save(): Promise; +} + +// User entity class +class User implements DatabaseObject { + id: number; + username: string; + email: string; + + constructor() { + this.id = 0; + this.username = ''; + this.email = ''; + } + + async save(): Promise { + console.log(`Saving user ${this.username}`); + // Actual saving logic... + } +} + +// Product entity class +class Product implements DatabaseObject { + id: number; + name: string; + price: number; + + constructor() { + this.id = 0; + this.name = ''; + this.price = 0; + } + + async save(): Promise { + console.log(`Saving product ${this.name}`); + // Actual saving logic... + } +} + +// 2. Implement the DatabaseQuery class +class DatabaseQuery { + private entityClass: new () => T; + + constructor(entityClass: new () => T) { + this.entityClass = entityClass; + } + + // Example query method + async findById(id: number): Promise { + const entity = new this.entityClass(); + // Simulate database query + console.log(`Querying ${entity.constructor.name} with id ${id}`); + // Actual query logic... + return {...entity, id}; // Return simulated data + } + + // Another example query method + async findAll(): Promise { + const entity = new this.entityClass(); + console.log(`Querying all ${entity.constructor.name} records`); + // Actual query logic... + return [{...entity, id: 1}]; // Return simulated data + } +} + +// 3. Usage example + +// Create a user query instance +const userQuery = new DatabaseQuery(User); // Error occurs + +// Use the query methods +(async () => { + const user = await userQuery.findById(1); + if (user) { + console.log(`Found user: ${user.username}`); + user.username = "newUsername"; + await user.save(); + } + + const allUsers = await userQuery.findAll(); + console.log(`Found ${allUsers.length} users`); + + // Create a product query instance + const productQuery = new DatabaseQuery(Product); // Error occurs + const product = await productQuery.findById(5); + if (product) { + console.log(`Found product: ${product.name} ($${product.price})`); + } +})(); \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/ConstructorFuncs.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/ConstructorFuncs.ets.arkts2.json new file mode 100644 index 0000000000..5e75d5b3e7 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/ConstructorFuncs.ets.arkts2.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/ConstructorFuncs.ets.json b/ets2panda/linter/test/sdkwhite/ConstructorFuncs.ets.json new file mode 100644 index 0000000000..d16c4619db --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/ConstructorFuncs.ets.json @@ -0,0 +1,108 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 62, + "column": 24, + "endLine": 62, + "endColumn": 35, + "problem": "ConstructorFuncs", + "suggest": "", + "rule": "Constructor function type is not supported (arkts-no-ctor-signatures-funcs)", + "severity": "ERROR" + }, + { + "line": 64, + "column": 28, + "endLine": 64, + "endColumn": 39, + "problem": "ConstructorFuncs", + "suggest": "", + "rule": "Constructor function type is not supported (arkts-no-ctor-signatures-funcs)", + "severity": "ERROR" + }, + { + "line": 74, + "column": 12, + "endLine": 74, + "endColumn": 13, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 74, + "column": 13, + "endLine": 74, + "endColumn": 22, + "problem": "SpreadOperator", + "suggest": "", + "rule": "It is possible to spread only arrays or classes derived from arrays into the rest parameter or array literals (arkts-no-spread)", + "severity": "ERROR" + }, + { + "line": 82, + "column": 12, + "endLine": 82, + "endColumn": 32, + "problem": "ArrayLiteralNoContextType", + "suggest": "", + "rule": "Array literals must contain elements of only inferrable types (arkts-no-noninferrable-arr-literals)", + "severity": "ERROR" + }, + { + "line": 82, + "column": 13, + "endLine": 82, + "endColumn": 14, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 82, + "column": 14, + "endLine": 82, + "endColumn": 23, + "problem": "SpreadOperator", + "suggest": "", + "rule": "It is possible to spread only arrays or classes derived from arrays into the rest parameter or array literals (arkts-no-spread)", + "severity": "ERROR" + }, + { + "line": 89, + "column": 37, + "endLine": 89, + "endColumn": 41, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 104, + "column": 42, + "endLine": 104, + "endColumn": 49, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/ConstructorIface4.ets b/ets2panda/linter/test/sdkwhite/ConstructorIface4.ets new file mode 100644 index 0000000000..1f6135015a --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/ConstructorIface4.ets @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { rcp } from '@kit.RemoteCommunicationKit'; + + +const MyNetworkOutputQueueConstructor: rcp.NetworkOutputQueueConstructor = rcp.NetworkOutputQueue; // Error + + diff --git a/ets2panda/linter/test/sdkwhite/ConstructorIface4.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/ConstructorIface4.ets.arkts2.json new file mode 100644 index 0000000000..5e75d5b3e7 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/ConstructorIface4.ets.arkts2.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/ConstructorIface4.ets.json b/ets2panda/linter/test/sdkwhite/ConstructorIface4.ets.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/ConstructorIface4.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/DeclWithDuplicateName5.ets b/ets2panda/linter/test/sdkwhite/DeclWithDuplicateName5.ets new file mode 100644 index 0000000000..fb83e2bfe2 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/DeclWithDuplicateName5.ets @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@Entry +@Component +struct Index { + fontStyleAttr1: TextStyle = new TextStyle({ fontColor: Color.Blue }); // Error + build() { + Text() + } +} diff --git a/ets2panda/linter/test/sdkwhite/DeclWithDuplicateName5.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/DeclWithDuplicateName5.ets.arkts2.json new file mode 100644 index 0000000000..5e75d5b3e7 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/DeclWithDuplicateName5.ets.arkts2.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/DeclWithDuplicateName5.ets.json b/ets2panda/linter/test/sdkwhite/DeclWithDuplicateName5.ets.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/DeclWithDuplicateName5.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/GlobalThisError&TypeQuery.ets b/ets2panda/linter/test/sdkwhite/GlobalThisError&TypeQuery.ets new file mode 100644 index 0000000000..359249a5ec --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/GlobalThisError&TypeQuery.ets @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { worker } from '@kit.ArkTS'; // Error \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/GlobalThisError&TypeQuery.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/GlobalThisError&TypeQuery.ets.arkts2.json new file mode 100644 index 0000000000..5e75d5b3e7 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/GlobalThisError&TypeQuery.ets.arkts2.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/GlobalThisError&TypeQuery.ets.json b/ets2panda/linter/test/sdkwhite/GlobalThisError&TypeQuery.ets.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/GlobalThisError&TypeQuery.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/IndexedAccessType.ets b/ets2panda/linter/test/sdkwhite/IndexedAccessType.ets new file mode 100644 index 0000000000..ab5be3eefd --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/IndexedAccessType.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Does not support index access +// todo Unsupported syntax: Can developers use this API? +import { AccessibilityElement, + AccessibilityExtensionAbility, ElementAttributeKeys } from '@kit.AccessibilityKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + + + + + diff --git a/ets2panda/linter/test/sdkwhite/IndexedAccessType.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/IndexedAccessType.ets.arkts2.json new file mode 100644 index 0000000000..5e75d5b3e7 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/IndexedAccessType.ets.arkts2.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/IndexedAccessType.ets.json b/ets2panda/linter/test/sdkwhite/IndexedAccessType.ets.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/IndexedAccessType.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/InterfaceExtendsClass.ets b/ets2panda/linter/test/sdkwhite/InterfaceExtendsClass.ets new file mode 100644 index 0000000000..6606e1f3b9 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/InterfaceExtendsClass.ets @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { TypedFrameNode } from '@kit.ArkUI'; + +class nodes implements TypedFrameNode{ // Error + +} diff --git a/ets2panda/linter/test/sdkwhite/InterfaceExtendsClass.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/InterfaceExtendsClass.ets.arkts2.json new file mode 100644 index 0000000000..5e75d5b3e7 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/InterfaceExtendsClass.ets.arkts2.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/InterfaceExtendsClass.ets.json b/ets2panda/linter/test/sdkwhite/InterfaceExtendsClass.ets.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/InterfaceExtendsClass.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/LimitedVoidType3.ets b/ets2panda/linter/test/sdkwhite/LimitedVoidType3.ets new file mode 100644 index 0000000000..e3c4c6107c --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/LimitedVoidType3.ets @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { rcp } from '@kit.RemoteCommunicationKit'; +class LI implements rcp.WriteFile{ + write(buffer: ArrayBuffer): Promise { // Error + throw new Error('Method not implemented.'); + } +} + + +const simpleDataHandler: rcp.IncomingDataCallback = (incomingData) => { + console.log(`Received ${incomingData.byteLength} bytes of data`); + // Error +}; \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/LimitedVoidType3.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/LimitedVoidType3.ets.arkts2.json new file mode 100644 index 0000000000..5e75d5b3e7 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/LimitedVoidType3.ets.arkts2.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/LimitedVoidType3.ets.json b/ets2panda/linter/test/sdkwhite/LimitedVoidType3.ets.json new file mode 100644 index 0000000000..266fcc7d89 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/LimitedVoidType3.ets.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 24, + "column": 54, + "endLine": 24, + "endColumn": 66, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/LiteralAsPropertyName2.ets b/ets2panda/linter/test/sdkwhite/LiteralAsPropertyName2.ets new file mode 100644 index 0000000000..3afff7ad6d --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/LiteralAsPropertyName2.ets @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { rcp } from '@kit.RemoteCommunicationKit'; +const basicHeaders: rcp.RequestHeaders = { + 'authorization': 'Bearer abc123', // Error + 'content-type': 'application/json' // Error +}; + +function createHeaders(authToken?: string): rcp.RequestHeaders { + return { + 'authorization': authToken ? `Bearer ${authToken}` : undefined, // Error + 'accept': 'application/json', // Error + 'cache-control': 'no-cache', // Error + 'user-agent': 'MyApp/2.0' // Error + }; +} + diff --git a/ets2panda/linter/test/sdkwhite/LiteralAsPropertyName2.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/LiteralAsPropertyName2.ets.arkts2.json new file mode 100644 index 0000000000..5e75d5b3e7 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/LiteralAsPropertyName2.ets.arkts2.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/LiteralAsPropertyName2.ets.json b/ets2panda/linter/test/sdkwhite/LiteralAsPropertyName2.ets.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/LiteralAsPropertyName2.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/OptionalMethod1.ets b/ets2panda/linter/test/sdkwhite/OptionalMethod1.ets new file mode 100644 index 0000000000..128f882768 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/OptionalMethod1.ets @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { webview } from '@kit.ArkWeb'; + +class OptionalMethod implements webview.NativeMediaPlayerBridge { + updateRect(x: number, y: number, width: number, height: number): void { + throw new Error('Method not implemented.'); + } + + play(): void { + throw new Error('Method not implemented.'); + } + + pause(): void { + throw new Error('Method not implemented.'); + } + + seek(targetTime: number): void { + throw new Error('Method not implemented.'); + } + + setVolume(volume: number): void { + throw new Error('Method not implemented.'); + } + + setMuted(muted: boolean): void { + throw new Error('Method not implemented.'); + } + + setPlaybackRate(playbackRate: number): void { + throw new Error('Method not implemented.'); + } + + release(): void { + throw new Error('Method not implemented.'); + } + + enterFullscreen(): void { + throw new Error('Method not implemented.'); + } + + exitFullscreen(): void { + throw new Error('Method not implemented.'); + } + + resumePlayer?(): void { // Error + throw new Error('Method not implemented.'); + } + + suspendPlayer?(type: webview.SuspendType): void { // Error + throw new Error('Method not implemented.'); + } +} + + diff --git a/ets2panda/linter/test/sdkwhite/OptionalMethod1.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/OptionalMethod1.ets.arkts2.json new file mode 100644 index 0000000000..5e75d5b3e7 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/OptionalMethod1.ets.arkts2.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/OptionalMethod1.ets.json b/ets2panda/linter/test/sdkwhite/OptionalMethod1.ets.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/OptionalMethod1.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/SendablePropType.ets b/ets2panda/linter/test/sdkwhite/SendablePropType.ets new file mode 100644 index 0000000000..02860a5f30 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/SendablePropType.ets @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import sendablePhotoAccessHelper from "@ohos.file.sendablePhotoAccessHelper" // Error diff --git a/ets2panda/linter/test/sdkwhite/SendablePropType.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/SendablePropType.ets.arkts2.json new file mode 100644 index 0000000000..5e75d5b3e7 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/SendablePropType.ets.arkts2.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/SendablePropType.ets.json b/ets2panda/linter/test/sdkwhite/SendablePropType.ets.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/SendablePropType.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/limit_void_type_sdk.ets b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk.ets new file mode 100644 index 0000000000..82bf1e5c60 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk.ets @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {IDataSourcePrefetching} from '@ohos.arkui.Prefetcher' + +class C implements IDataSourcePrefetching { + prefetch(index: number): void | Promise { + + } + + prefetch2(index: number): void | Promise { + + } +} diff --git a/ets2panda/linter/test/sdkwhite/limit_void_type_sdk.ets.args.json b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk.ets.args.json new file mode 100644 index 0000000000..948b846fe0 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} diff --git a/ets2panda/linter/test/sdkwhite/limit_void_type_sdk.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk.ets.arkts2.json new file mode 100644 index 0000000000..f65500d7d1 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk.ets.arkts2.json @@ -0,0 +1,48 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 19, + "column": 3, + "endLine": 21, + "endColumn": 4, + "problem": "LimitedVoidTypeFromSdk", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-sdk-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 28, + "endLine": 19, + "endColumn": 32, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 29, + "endLine": 23, + "endColumn": 33, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/limit_void_type_sdk.ets.json b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk.ets.json new file mode 100644 index 0000000000..5e75d5b3e7 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk.ets.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/limit_void_type_sdk2.ets b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk2.ets new file mode 100644 index 0000000000..e768ba911c --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk2.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { rcp } from '@kit.RemoteCommunicationKit'; +class LI implements rcp.WriteFile { + write(buffer: ArrayBuffer): Promise { + throw new Error() + } +} + +const sp:rcp.IncomingDataCallback = (incomingData) => { + console.log(''); +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/limit_void_type_sdk2.ets.args.json b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk2.ets.args.json new file mode 100644 index 0000000000..948b846fe0 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk2.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} diff --git a/ets2panda/linter/test/sdkwhite/limit_void_type_sdk2.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk2.ets.arkts2.json new file mode 100644 index 0000000000..07e4765956 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk2.ets.arkts2.json @@ -0,0 +1,48 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 3, + "endLine": 20, + "endColumn": 4, + "problem": "LimitedVoidTypeFromSdk", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-sdk-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 48, + "endLine": 18, + "endColumn": 52, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 38, + "endLine": 23, + "endColumn": 50, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/limit_void_type_sdk2.ets.json b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk2.ets.json new file mode 100644 index 0000000000..67fe0d197f --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk2.ets.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 23, + "column": 38, + "endLine": 23, + "endColumn": 50, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/tsconfig.json b/ets2panda/linter/tsconfig.json index 17e27ba6f7..2dece78605 100644 --- a/ets2panda/linter/tsconfig.json +++ b/ets2panda/linter/tsconfig.json @@ -9,7 +9,8 @@ "preserveConstEnums": true, "sourceMap": true, "outDir": "build", - "strict": true + "strict": true, + "resolveJsonModule": true }, "include": ["src/**/*"] -- Gitee From 7471d598e691b6bb1a989867e74302a5aa90d36a Mon Sep 17 00:00:00 2001 From: ZhongNing Date: Thu, 10 Apr 2025 13:50:41 +0800 Subject: [PATCH 051/268] fix issue for arkts-no-extends-expression Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBWGWF Test scenarios: fix issue for arkts-no-extends-expression Signed-off-by: ZhongNing --- ets2panda/linter/src/lib/TypeScriptLinter.ts | 6 ++- .../linter/test/main/extends_expression.ets | 32 +++++++++++- .../main/extends_expression.ets.arkts2.json | 50 +++++++++++++++++++ .../test/main/extends_expression.ets.json | 20 ++++++++ 4 files changed, 106 insertions(+), 2 deletions(-) diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index 823ccf7e5a..7e02247bf1 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -4768,9 +4768,13 @@ export class TypeScriptLinter { if (!this.options.arkts2) { return; } - if (node.token === ts.SyntaxKind.ExtendsKeyword) { + if (node.token === ts.SyntaxKind.ExtendsKeyword || node.token === ts.SyntaxKind.ImplementsKeyword) { node.types.forEach((type) => { const expr = type.expression; + if (ts.isCallExpression(expr)) { + this.incrementCounters(expr, FaultID.ExtendsExpression); + return; + } if ( ts.isIdentifier(expr) && this.isVariableReference(expr) && diff --git a/ets2panda/linter/test/main/extends_expression.ets b/ets2panda/linter/test/main/extends_expression.ets index b7236fae81..d95b96aee4 100755 --- a/ets2panda/linter/test/main/extends_expression.ets +++ b/ets2panda/linter/test/main/extends_expression.ets @@ -54,4 +54,34 @@ class C4 implements E { export declare class Bar { constructor(arg: { new(): T }); -} \ No newline at end of file +} + +function getBaseClass(isAdmin: boolean) { + class A{ + adminMethod() { + console.log('这是管理员方法'); + } + } + class B{ + adminMethod() { + console.log('这是用户方法'); + } + } + if (isAdmin) { + return A; + } else { + return B; + } +} + +class User extends getBaseClass(false) { + commonMethod() { + console.log('这是通用方法'); + } +} + +class Admin extends getBaseClass(true) { + commonMethod() { + console.log('这是通用方法'); + } +} diff --git a/ets2panda/linter/test/main/extends_expression.ets.arkts2.json b/ets2panda/linter/test/main/extends_expression.ets.arkts2.json index 408c287bcd..b347754475 100755 --- a/ets2panda/linter/test/main/extends_expression.ets.arkts2.json +++ b/ets2panda/linter/test/main/extends_expression.ets.arkts2.json @@ -73,6 +73,56 @@ "suggest": "", "rule": "Use \"class\" instead of a type with constructor signature (arkts-no-ctor-signatures-type)", "severity": "ERROR" + }, + { + "line": 59, + "column": 10, + "endLine": 59, + "endColumn": 22, + "problem": "LimitedReturnTypeInference", + "suggest": "", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 12, + "endLine": 71, + "endColumn": 13, + "problem": "ClassAsObjectError", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 12, + "endLine": 73, + "endColumn": 13, + "problem": "ClassAsObjectError", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "ERROR" + }, + { + "line": 77, + "column": 20, + "endLine": 77, + "endColumn": 39, + "problem": "ExtendsExpression", + "suggest": "", + "rule": "Extends or implemetns expression are not supported(arkts-no-extends-expression)", + "severity": "ERROR" + }, + { + "line": 83, + "column": 21, + "endLine": 83, + "endColumn": 39, + "problem": "ExtendsExpression", + "suggest": "", + "rule": "Extends or implemetns expression are not supported(arkts-no-extends-expression)", + "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/extends_expression.ets.json b/ets2panda/linter/test/main/extends_expression.ets.json index c1f183fffb..d8afa3d8c8 100644 --- a/ets2panda/linter/test/main/extends_expression.ets.json +++ b/ets2panda/linter/test/main/extends_expression.ets.json @@ -63,6 +63,26 @@ "suggest": "", "rule": "Use \"class\" instead of a type with constructor signature (arkts-no-ctor-signatures-type)", "severity": "ERROR" + }, + { + "line": 71, + "column": 12, + "endLine": 71, + "endColumn": 13, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 73, + "column": 12, + "endLine": 73, + "endColumn": 13, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" } ] } \ No newline at end of file -- Gitee From b7ac650252e1e6a35563b1cd9cd09814cd6550c3 Mon Sep 17 00:00:00 2001 From: openharmony_ci <120357966@qq.com> Date: Mon, 14 Apr 2025 21:44:14 +0000 Subject: [PATCH 052/268] !4733 [cherry-pick 0411] Fix Return Type This Issue: #IC23EF Description: Merge pull request !4733 from furkanocalan/WrongReturnTypeThis Signed-off-by: furkanocalan --- ets2panda/checker/ETSchecker.h | 2 + ets2panda/checker/ets/function.cpp | 12 ++++++ ets2panda/checker/ets/typeCheckingHelpers.cpp | 43 +++++++++++++++++++ .../extension_function_return_this_neg2.ets | 1 + .../extension_function_return_this_union.ets | 2 +- .../extension_function_return_this_union2.ets | 1 + .../extension_function_return_this_union3.ets | 1 + ets2panda/util/diagnostic/semantic.yaml | 16 +++++++ ets2panda/util/diagnostic/syntax.yaml | 2 +- 9 files changed, 78 insertions(+), 2 deletions(-) diff --git a/ets2panda/checker/ETSchecker.h b/ets2panda/checker/ETSchecker.h index 58efdaa101..44ed5a9c1c 100644 --- a/ets2panda/checker/ETSchecker.h +++ b/ets2panda/checker/ETSchecker.h @@ -550,6 +550,8 @@ public: void CheckFunctionSignatureAnnotations(const ArenaVector ¶ms, ir::TSTypeParameterDeclaration *typeParams, ir::TypeNode *returnTypeAnnotation); + bool CheckAndLogInvalidThisUsage(const ir::TypeNode *type, const diagnostic::DiagnosticKind &diagnostic); + void ValidateThisUsage(const ir::TypeNode *returnTypeAnnotation); void CheckAnnotations(const ArenaVector &annotations); void CheckAmbientAnnotation(ir::AnnotationDeclaration *annoImpl, ir::AnnotationDeclaration *annoDecl); bool CheckAmbientAnnotationFieldInitializerValue(ir::Expression *init, ir::Expression *expected); diff --git a/ets2panda/checker/ets/function.cpp b/ets2panda/checker/ets/function.cpp index 139cc5e82e..63f1e8aa74 100644 --- a/ets2panda/checker/ets/function.cpp +++ b/ets2panda/checker/ets/function.cpp @@ -1736,6 +1736,18 @@ bool ETSChecker::IsReturnTypeSubstitutable(Signature *const s1, Signature *const return Relation()->IsIdenticalTo(r2, r1); } + auto const hasThisReturnType = [](Signature *s) { + auto *retAnn = s->Function()->ReturnTypeAnnotation(); + return retAnn != nullptr && retAnn->IsTSThisType(); + }; + // - If S2 is a 'this' type(polymorphic) and S1 must be also 'this' + // If the overridden method (s2) has a 'this' return type, then the overriding method (s1) must also have it. + bool s1HasThisType = hasThisReturnType(s1); + bool s2HasThisType = hasThisReturnType(s2); + if (s1HasThisType != s2HasThisType) { + return false; + } + // - If R1 is a reference type then R1, adapted to the type parameters of d2 (link to generic methods), is a // subtype of R2. ES2PANDA_ASSERT(IsReferenceType(r1)); diff --git a/ets2panda/checker/ets/typeCheckingHelpers.cpp b/ets2panda/checker/ets/typeCheckingHelpers.cpp index 5a806d5a79..3ad56e644b 100644 --- a/ets2panda/checker/ets/typeCheckingHelpers.cpp +++ b/ets2panda/checker/ets/typeCheckingHelpers.cpp @@ -36,6 +36,7 @@ #include "ir/ts/tsEnumMember.h" #include "ir/ts/tsTypeParameter.h" #include "ir/ets/etsUnionType.h" +#include "ir/ets/etsTuple.h" #include "varbinder/declaration.h" #include "checker/ETSchecker.h" #include "varbinder/ETSBinder.h" @@ -904,10 +905,52 @@ void ETSChecker::CheckFunctionSignatureAnnotations(const ArenaVectorAnnotations()); } } +bool ETSChecker::CheckAndLogInvalidThisUsage(const ir::TypeNode *type, const diagnostic::DiagnosticKind &diagnostic) +{ + if (type->IsTSThisType()) { + LogError(diagnostic, {}, type->Start()); + return true; + } + return false; +} + +void ETSChecker::ValidateThisUsage(const ir::TypeNode *returnTypeAnnotation) +{ + if (returnTypeAnnotation->IsETSUnionType()) { + auto types = returnTypeAnnotation->AsETSUnionType()->Types(); + for (auto type : types) { + if (CheckAndLogInvalidThisUsage(type, diagnostic::NOT_ALLOWED_THIS_IN_UNION_TYPE)) { + return; + } + ValidateThisUsage(type); + } + return; + } + if (returnTypeAnnotation->IsETSTuple()) { + auto types = returnTypeAnnotation->AsETSTuple()->GetTupleTypeAnnotationsList(); + for (auto type : types) { + if (CheckAndLogInvalidThisUsage(type, diagnostic::NOT_ALLOWED_THIS_IN_TUPLE_TYPE)) { + return; + } + ValidateThisUsage(type); + } + return; + } + if (returnTypeAnnotation->IsTSArrayType()) { + auto elementType = returnTypeAnnotation->AsTSArrayType()->ElementType(); + if (CheckAndLogInvalidThisUsage(elementType, diagnostic::NOT_ALLOWED_THIS_IN_ARRAY_TYPE)) { + return; + } + ValidateThisUsage(elementType); + return; + } +} + void ETSChecker::CheckAnnotations(const ArenaVector &annotations) { if (annotations.empty()) { diff --git a/ets2panda/test/ast/compiler/ets/extension_function_tests/extension_function_return_this_neg2.ets b/ets2panda/test/ast/compiler/ets/extension_function_tests/extension_function_return_this_neg2.ets index 852e0b732e..b3862bbc5b 100644 --- a/ets2panda/test/ast/compiler/ets/extension_function_tests/extension_function_return_this_neg2.ets +++ b/ets2panda/test/ast/compiler/ets/extension_function_tests/extension_function_return_this_neg2.ets @@ -21,4 +21,5 @@ function f1(this : B): /* @@ label*/this[] { } /* @@@ label Error SyntaxError: A 'this' type is available only as return type in a non-static method of a class or struct and extension functions. */ +/* @@? 19:37 Error TypeError: A 'this' cannot be used as type of array. */ /* @@? 20:12 Error TypeError: Type 'B' is not compatible with the enclosing method's return type 'ETSGLOBAL[]' */ diff --git a/ets2panda/test/ast/compiler/ets/extension_function_tests/extension_function_return_this_union.ets b/ets2panda/test/ast/compiler/ets/extension_function_tests/extension_function_return_this_union.ets index 227c44ca6e..c3776e2b05 100644 --- a/ets2panda/test/ast/compiler/ets/extension_function_tests/extension_function_return_this_union.ets +++ b/ets2panda/test/ast/compiler/ets/extension_function_tests/extension_function_return_this_union.ets @@ -20,5 +20,5 @@ function f1(this : B): /* @@ label*/this | A { return this; } /* @@@ label Error SyntaxError: A 'this' type is available only as return type in a non-static method of a class or struct and extension functions. */ +/* @@? 19:37 Error TypeError: A 'this' cannot be used as a part of union type. */ /* @@? 20:12 Error TypeError: Type 'B' is not compatible with the enclosing method's return type 'ETSGLOBAL|A' */ - diff --git a/ets2panda/test/ast/compiler/ets/extension_function_tests/extension_function_return_this_union2.ets b/ets2panda/test/ast/compiler/ets/extension_function_tests/extension_function_return_this_union2.ets index 05f4e6b1cf..05f1930cee 100644 --- a/ets2panda/test/ast/compiler/ets/extension_function_tests/extension_function_return_this_union2.ets +++ b/ets2panda/test/ast/compiler/ets/extension_function_tests/extension_function_return_this_union2.ets @@ -19,3 +19,4 @@ function f1(this : B): /* @@ label*/this | B { return this; } /* @@@ label Error SyntaxError: A 'this' type is available only as return type in a non-static method of a class or struct and extension functions. */ +/* @@? 18:37 Error TypeError: A 'this' cannot be used as a part of union type. */ diff --git a/ets2panda/test/ast/compiler/ets/extension_function_tests/extension_function_return_this_union3.ets b/ets2panda/test/ast/compiler/ets/extension_function_tests/extension_function_return_this_union3.ets index cb304e0bbf..404e72c9c8 100644 --- a/ets2panda/test/ast/compiler/ets/extension_function_tests/extension_function_return_this_union3.ets +++ b/ets2panda/test/ast/compiler/ets/extension_function_tests/extension_function_return_this_union3.ets @@ -21,4 +21,5 @@ function f1(this : B): A | /* @@ label*/this { } /* @@@ label Error SyntaxError: A 'this' type is available only as return type in a non-static method of a class or struct and extension functions. */ +/* @@? 19:41 Error TypeError: A 'this' cannot be used as a part of union type. */ /* @@? 20:12 Error TypeError: Type 'B' is not compatible with the enclosing method's return type 'A|ETSGLOBAL' */ diff --git a/ets2panda/util/diagnostic/semantic.yaml b/ets2panda/util/diagnostic/semantic.yaml index 7462253772..34150bda7d 100644 --- a/ets2panda/util/diagnostic/semantic.yaml +++ b/ets2panda/util/diagnostic/semantic.yaml @@ -1110,3 +1110,19 @@ semantic: - name: UNION_METHOD_SIGNATURE id: 279 message: "Union constituent types should have only one common method signature." + +- name: TUPLEN_NOT_IMPLEMENTED + id: 280 + message: "Tuple types with arity >16 are not yet implemented" + +- name: NOT_ALLOWED_THIS_IN_UNION_TYPE + id: 281 + message: "A 'this' cannot be used as a part of union type." + +- name: NOT_ALLOWED_THIS_IN_TUPLE_TYPE + id: 282 + message: "A 'this' cannot be used as a part of tuple type." + +- name: NOT_ALLOWED_THIS_IN_ARRAY_TYPE + id: 283 + message: "A 'this' cannot be used as type of array." diff --git a/ets2panda/util/diagnostic/syntax.yaml b/ets2panda/util/diagnostic/syntax.yaml index c66b45870b..421782b176 100644 --- a/ets2panda/util/diagnostic/syntax.yaml +++ b/ets2panda/util/diagnostic/syntax.yaml @@ -1155,7 +1155,7 @@ syntax: - name: INVALID_SHORTHAND_PROPERTY_INITIALIZER id: 286 message: "Invalid shorthand property initializer." - + - name: RETURN_WITH_VALUE id: 287 message: "Unexpected return value." -- Gitee From 8d4849299239639d65346a13690744690596af55 Mon Sep 17 00:00:00 2001 From: sd_wu Date: Thu, 27 Mar 2025 16:32:17 +0800 Subject: [PATCH 053/268] add entry and provide annotation autofix rules Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBWDRG Signed-off-by: sd_wu --- ets2panda/linter/src/lib/CookBookMsg.ts | 2 + ets2panda/linter/src/lib/FaultAttrs.ts | 2 + ets2panda/linter/src/lib/FaultDesc.ts | 2 + ets2panda/linter/src/lib/Problems.ts | 2 + ets2panda/linter/src/lib/TypeScriptLinter.ts | 74 ++++++++- .../linter/src/lib/autofixes/AutofixTitles.ts | 4 +- .../linter/src/lib/autofixes/Autofixer.ts | 146 +++++++++++++++++- .../src/lib/utils/consts/ArkTS2Rules.ts | 2 + .../src/lib/utils/consts/ArkuiConstants.ts | 9 ++ .../test/main/entry_annotation_test10_1.ets | 25 +++ .../entry_annotation_test10_1.ets.args.json | 20 +++ .../entry_annotation_test10_1.ets.arkts2.json | 28 ++++ ...entry_annotation_test10_1.ets.autofix.json | 35 +++++ .../main/entry_annotation_test10_1.ets.json | 17 ++ .../test/main/entry_annotation_test10_2.ets | 26 ++++ .../entry_annotation_test10_2.ets.args.json | 20 +++ .../entry_annotation_test10_2.ets.arkts2.json | 17 ++ ...entry_annotation_test10_2.ets.autofix.json | 17 ++ .../main/entry_annotation_test10_2.ets.json | 17 ++ .../test/main/entry_annotation_test1_1.ets | 24 +++ .../entry_annotation_test1_1.ets.args.json | 20 +++ .../entry_annotation_test1_1.ets.arkts2.json | 17 ++ .../entry_annotation_test1_1.ets.autofix.json | 17 ++ .../main/entry_annotation_test1_1.ets.json | 17 ++ .../test/main/entry_annotation_test1_2.ets | 24 +++ .../entry_annotation_test1_2.ets.args.json | 20 +++ .../entry_annotation_test1_2.ets.arkts2.json | 17 ++ .../entry_annotation_test1_2.ets.autofix.json | 17 ++ .../main/entry_annotation_test1_2.ets.json | 17 ++ .../test/main/entry_annotation_test2_1.ets | 25 +++ .../entry_annotation_test2_1.ets.args.json | 20 +++ .../entry_annotation_test2_1.ets.arkts2.json | 48 ++++++ .../entry_annotation_test2_1.ets.autofix.json | 55 +++++++ .../main/entry_annotation_test2_1.ets.json | 28 ++++ .../test/main/entry_annotation_test2_2.ets | 25 +++ .../entry_annotation_test2_2.ets.args.json | 20 +++ .../entry_annotation_test2_2.ets.arkts2.json | 38 +++++ .../entry_annotation_test2_2.ets.autofix.json | 38 +++++ .../main/entry_annotation_test2_2.ets.json | 28 ++++ .../test/main/entry_annotation_test3_1.ets | 24 +++ .../entry_annotation_test3_1.ets.args.json | 20 +++ .../entry_annotation_test3_1.ets.arkts2.json | 38 +++++ .../entry_annotation_test3_1.ets.autofix.json | 45 ++++++ .../main/entry_annotation_test3_1.ets.json | 17 ++ .../test/main/entry_annotation_test3_2.ets | 25 +++ .../entry_annotation_test3_2.ets.args.json | 20 +++ .../entry_annotation_test3_2.ets.arkts2.json | 28 ++++ .../entry_annotation_test3_2.ets.autofix.json | 28 ++++ .../main/entry_annotation_test3_2.ets.json | 17 ++ .../test/main/entry_annotation_test4_1.ets | 24 +++ .../entry_annotation_test4_1.ets.args.json | 20 +++ .../entry_annotation_test4_1.ets.arkts2.json | 28 ++++ .../entry_annotation_test4_1.ets.autofix.json | 35 +++++ .../main/entry_annotation_test4_1.ets.json | 17 ++ .../test/main/entry_annotation_test4_2.ets | 25 +++ .../entry_annotation_test4_2.ets.args.json | 20 +++ .../entry_annotation_test4_2.ets.arkts2.json | 17 ++ .../entry_annotation_test4_2.ets.autofix.json | 17 ++ .../main/entry_annotation_test4_2.ets.json | 17 ++ .../test/main/entry_annotation_test5_1.ets | 25 +++ .../entry_annotation_test5_1.ets.args.json | 20 +++ .../entry_annotation_test5_1.ets.arkts2.json | 48 ++++++ .../entry_annotation_test5_1.ets.autofix.json | 55 +++++++ .../main/entry_annotation_test5_1.ets.json | 28 ++++ .../test/main/entry_annotation_test5_2.ets | 25 +++ .../entry_annotation_test5_2.ets.args.json | 20 +++ .../entry_annotation_test5_2.ets.arkts2.json | 38 +++++ .../entry_annotation_test5_2.ets.autofix.json | 38 +++++ .../main/entry_annotation_test5_2.ets.json | 28 ++++ .../test/main/entry_annotation_test6_1.ets | 24 +++ .../entry_annotation_test6_1.ets.args.json | 20 +++ .../entry_annotation_test6_1.ets.arkts2.json | 38 +++++ .../entry_annotation_test6_1.ets.autofix.json | 45 ++++++ .../main/entry_annotation_test6_1.ets.json | 17 ++ .../test/main/entry_annotation_test6_2.ets | 25 +++ .../entry_annotation_test6_2.ets.args.json | 20 +++ .../entry_annotation_test6_2.ets.arkts2.json | 28 ++++ .../entry_annotation_test6_2.ets.autofix.json | 28 ++++ .../main/entry_annotation_test6_2.ets.json | 17 ++ .../test/main/entry_annotation_test7_1.ets | 24 +++ .../entry_annotation_test7_1.ets.args.json | 20 +++ .../entry_annotation_test7_1.ets.arkts2.json | 28 ++++ .../entry_annotation_test7_1.ets.autofix.json | 35 +++++ .../main/entry_annotation_test7_1.ets.json | 17 ++ .../test/main/entry_annotation_test7_2.ets | 25 +++ .../entry_annotation_test7_2.ets.args.json | 20 +++ .../entry_annotation_test7_2.ets.arkts2.json | 17 ++ .../entry_annotation_test7_2.ets.autofix.json | 17 ++ .../main/entry_annotation_test7_2.ets.json | 17 ++ .../test/main/entry_annotation_test8_1.ets | 25 +++ .../entry_annotation_test8_1.ets.args.json | 20 +++ .../entry_annotation_test8_1.ets.arkts2.json | 38 +++++ .../entry_annotation_test8_1.ets.autofix.json | 52 +++++++ .../main/entry_annotation_test8_1.ets.json | 28 ++++ .../test/main/entry_annotation_test8_2.ets | 26 ++++ .../entry_annotation_test8_2.ets.args.json | 20 +++ .../entry_annotation_test8_2.ets.arkts2.json | 28 ++++ .../entry_annotation_test8_2.ets.autofix.json | 35 +++++ .../main/entry_annotation_test8_2.ets.json | 28 ++++ .../test/main/entry_annotation_test9_1.ets | 24 +++ .../entry_annotation_test9_1.ets.args.json | 20 +++ .../entry_annotation_test9_1.ets.arkts2.json | 38 +++++ .../entry_annotation_test9_1.ets.autofix.json | 52 +++++++ .../main/entry_annotation_test9_1.ets.json | 28 ++++ .../test/main/entry_annotation_test9_2.ets | 25 +++ .../entry_annotation_test9_2.ets.args.json | 20 +++ .../entry_annotation_test9_2.ets.arkts2.json | 28 ++++ .../entry_annotation_test9_2.ets.autofix.json | 35 +++++ .../main/entry_annotation_test9_2.ets.json | 28 ++++ .../linter/test/main/provide_annotation_1.ets | 44 ++++++ .../main/provide_annotation_1.ets.args.json | 20 +++ .../main/provide_annotation_1.ets.arkts2.json | 98 ++++++++++++ .../provide_annotation_1.ets.autofix.json | 119 ++++++++++++++ .../test/main/provide_annotation_1.ets.json | 48 ++++++ .../linter/test/main/provide_annotation_2.ets | 44 ++++++ .../main/provide_annotation_2.ets.args.json | 20 +++ .../main/provide_annotation_2.ets.arkts2.json | 78 ++++++++++ .../provide_annotation_2.ets.autofix.json | 85 ++++++++++ .../test/main/provide_annotation_2.ets.json | 48 ++++++ 119 files changed, 3468 insertions(+), 3 deletions(-) create mode 100644 ets2panda/linter/test/main/entry_annotation_test10_1.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test10_1.ets.args.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test10_1.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test10_1.ets.autofix.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test10_1.ets.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test10_2.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test10_2.ets.args.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test10_2.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test10_2.ets.autofix.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test10_2.ets.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test1_1.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test1_1.ets.args.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test1_1.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test1_1.ets.autofix.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test1_1.ets.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test1_2.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test1_2.ets.args.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test1_2.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test1_2.ets.autofix.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test1_2.ets.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test2_1.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test2_1.ets.args.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test2_1.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test2_1.ets.autofix.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test2_1.ets.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test2_2.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test2_2.ets.args.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test2_2.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test2_2.ets.autofix.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test2_2.ets.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test3_1.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test3_1.ets.args.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test3_1.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test3_1.ets.autofix.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test3_1.ets.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test3_2.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test3_2.ets.args.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test3_2.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test3_2.ets.autofix.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test3_2.ets.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test4_1.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test4_1.ets.args.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test4_1.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test4_1.ets.autofix.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test4_1.ets.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test4_2.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test4_2.ets.args.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test4_2.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test4_2.ets.autofix.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test4_2.ets.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test5_1.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test5_1.ets.args.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test5_1.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test5_1.ets.autofix.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test5_1.ets.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test5_2.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test5_2.ets.args.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test5_2.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test5_2.ets.autofix.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test5_2.ets.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test6_1.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test6_1.ets.args.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test6_1.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test6_1.ets.autofix.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test6_1.ets.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test6_2.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test6_2.ets.args.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test6_2.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test6_2.ets.autofix.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test6_2.ets.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test7_1.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test7_1.ets.args.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test7_1.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test7_1.ets.autofix.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test7_1.ets.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test7_2.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test7_2.ets.args.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test7_2.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test7_2.ets.autofix.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test7_2.ets.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test8_1.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test8_1.ets.args.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test8_1.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test8_1.ets.autofix.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test8_1.ets.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test8_2.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test8_2.ets.args.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test8_2.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test8_2.ets.autofix.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test8_2.ets.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test9_1.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test9_1.ets.args.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test9_1.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test9_1.ets.autofix.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test9_1.ets.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test9_2.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test9_2.ets.args.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test9_2.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test9_2.ets.autofix.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test9_2.ets.json create mode 100644 ets2panda/linter/test/main/provide_annotation_1.ets create mode 100644 ets2panda/linter/test/main/provide_annotation_1.ets.args.json create mode 100644 ets2panda/linter/test/main/provide_annotation_1.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/provide_annotation_1.ets.autofix.json create mode 100644 ets2panda/linter/test/main/provide_annotation_1.ets.json create mode 100644 ets2panda/linter/test/main/provide_annotation_2.ets create mode 100644 ets2panda/linter/test/main/provide_annotation_2.ets.args.json create mode 100644 ets2panda/linter/test/main/provide_annotation_2.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/provide_annotation_2.ets.autofix.json create mode 100644 ets2panda/linter/test/main/provide_annotation_2.ets.json diff --git a/ets2panda/linter/src/lib/CookBookMsg.ts b/ets2panda/linter/src/lib/CookBookMsg.ts index cd18f4ebd1..33dff6b05c 100644 --- a/ets2panda/linter/src/lib/CookBookMsg.ts +++ b/ets2panda/linter/src/lib/CookBookMsg.ts @@ -264,6 +264,8 @@ cookBookTag[257] = '"@AnimatableExtend" decorator should be transformed to use receiver (arkui-animatableextend-use-receiver)'; cookBookTag[258] = 'Data observation needs to add "@Observed" (arkui-data-observation)'; cookBookTag[259] = 'ArkUI interface should be imported before using (arkui-modular-interface)'; +cookBookTag[260] = 'The "@Entry" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)'; +cookBookTag[263] = 'The "@Provide" annotation does not support dynamic parameters (arkui-provide-annotation-parameters)'; cookBookTag[300] = 'The function type should be explicit (arkts-no-ts-like-function)'; cookBookTag[301] = 'Importing from "oh module" requires specifying full path (arkts-ohmurl-full-path)'; cookBookTag[302] = diff --git a/ets2panda/linter/src/lib/FaultAttrs.ts b/ets2panda/linter/src/lib/FaultAttrs.ts index 88c49cf845..e9d415f6b9 100644 --- a/ets2panda/linter/src/lib/FaultAttrs.ts +++ b/ets2panda/linter/src/lib/FaultAttrs.ts @@ -178,6 +178,8 @@ faultsAttrs[FaultID.StylesDecoratorNotSupported] = new FaultAttributes(256); faultsAttrs[FaultID.AnimatableExtendDecoratorTransform] = new FaultAttributes(257); faultsAttrs[FaultID.DataObservation] = new FaultAttributes(258); faultsAttrs[FaultID.UIInterfaceImport] = new FaultAttributes(259); +faultsAttrs[FaultID.EntryAnnotation] = new FaultAttributes(260); +faultsAttrs[FaultID.ProvideAnnotation] = new FaultAttributes(263); faultsAttrs[FaultID.ExplicitFunctionType] = new FaultAttributes(300); faultsAttrs[FaultID.OhmUrlFullPath] = new FaultAttributes(301); faultsAttrs[FaultID.InteropCallObjectParam] = new FaultAttributes(302); diff --git a/ets2panda/linter/src/lib/FaultDesc.ts b/ets2panda/linter/src/lib/FaultDesc.ts index cb2ec2ec4e..8c92fa9689 100644 --- a/ets2panda/linter/src/lib/FaultDesc.ts +++ b/ets2panda/linter/src/lib/FaultDesc.ts @@ -175,4 +175,6 @@ faultDesc[FaultID.InteropNoDecorators] = 'Interop decorators not supported'; faultDesc[FaultID.InteropDirectAccessToTSTypes] = 'TS Types Access'; faultDesc[FaultID.InteropTSFunctionInvoke] = 'TS Function Invoke'; faultDesc[FaultID.LimitedVoidTypeFromSdk] = 'Limited void type from sdk'; +faultDesc[FaultID.EntryAnnotation] = '"@Entry" decorator parameter'; +faultDesc[FaultID.ProvideAnnotation] = '"@Provide" decorator parameter'; diff --git a/ets2panda/linter/src/lib/Problems.ts b/ets2panda/linter/src/lib/Problems.ts index 31eb4cdd93..459e9d2a6c 100644 --- a/ets2panda/linter/src/lib/Problems.ts +++ b/ets2panda/linter/src/lib/Problems.ts @@ -176,6 +176,8 @@ export enum FaultID { InteropDirectAccessToTSTypes, InteropTSFunctionInvoke, LimitedVoidTypeFromSdk, + EntryAnnotation, + ProvideAnnotation, // this should always be last enum LAST_ID } diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index 7e02247bf1..58d43f92fe 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -83,7 +83,10 @@ import { STATE_STYLES, CustomDecoratorName, observedDecoratorName, - skipImportDecoratorName + skipImportDecoratorName, + ENTRY_DECORATOR_NAME, + PROVIDE_DECORATOR_NAME, + PROVIDE_ALLOW_OVERRIDE_PROPERTY_NAME } from './utils/consts/ArkuiConstants'; import { arkuiImportList } from './utils/consts/ArkuiImportList'; import { REFLECT_PROPERTIES, USE_STATIC } from './utils/consts/InteropAPI'; @@ -4107,6 +4110,8 @@ export class TypeScriptLinter { private handleDecorator(node: ts.Node): void { this.handleExtendDecorator(node); + this.handleEntryDecorator(node); + this.handleProvideDecorator(node); const decorator: ts.Decorator = node as ts.Decorator; this.handleSendableDecorator(decorator); @@ -4123,6 +4128,41 @@ export class TypeScriptLinter { this.handleNotSupportCustomDecorators(decorator); } + private handleProvideDecorator(node: ts.Node): void { + if (!this.options.arkts2) { + return; + } + + if (!ts.isDecorator(node)) { + return; + } + + if (ts.isCallExpression(node.expression) && ts.isIdentifier(node.expression.expression)) { + if (node.expression.expression.text !== PROVIDE_DECORATOR_NAME || node.expression.arguments.length !== 1) { + return; + } + const arg = node.expression.arguments[0]; + if (!ts.isStringLiteral(arg) && !ts.isObjectLiteralExpression(arg)) { + return; + } + if (ts.isObjectLiteralExpression(arg)) { + const properties = arg.properties; + if (properties.length !== 1) { + return; + } + const property = properties[0] as ts.PropertyAssignment; + if (!ts.isIdentifier(property.name) || !ts.isStringLiteral(property.initializer)) { + return; + } + if (property.name.escapedText !== PROVIDE_ALLOW_OVERRIDE_PROPERTY_NAME) { + return; + } + } + const autofix = this.autofixer?.fixProvideDecorator(node); + this.incrementCounters(node.parent, FaultID.ProvideAnnotation, autofix); + } + } + private isSendableDecoratorValid(decl: ts.FunctionDeclaration | ts.TypeAliasDeclaration): boolean { if ( this.compatibleSdkVersion > SENDBALE_FUNCTION_START_VERSION || @@ -4696,6 +4736,38 @@ export class TypeScriptLinter { } } + private handleEntryDecorator(node: ts.Node): void { + if (!this.options.arkts2) { + return; + } + + if (!ts.isDecorator(node)) { + return; + } + + if (ts.isCallExpression(node.expression) && ts.isIdentifier(node.expression.expression)) { + if (node.expression.expression.escapedText !== ENTRY_DECORATOR_NAME || node.expression.arguments.length !== 1) { + return; + } + const arg = node.expression.arguments[0]; + if (ts.isObjectLiteralExpression(arg)) { + const properties = arg.properties; + if (properties.length !== 1) { + return; + } + if (!ts.isPropertyAssignment(properties[0])) { + return; + } + const property = properties[0]; + if (ts.isStringLiteral(property.initializer)) { + return; + } + } + const autofix = this.autofixer?.fixEntryDecorator(node); + this.incrementCounters(node, FaultID.EntryAnnotation, autofix); + } + } + private handleStructPropertyDecl(propDecl: ts.PropertyDeclaration): void { if (!this.options.arkts2) { return; diff --git a/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts b/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts index 54c5dee7dd..f750480c16 100644 --- a/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts +++ b/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts @@ -46,5 +46,7 @@ export const cookBookRefToFixTitle: Map = new Map([ [256, '"@Styles" transform to function with receiver'], [257, '"@AnimatableExtend" transform to function with receiver'], [258, 'Add "@Observed" decorator'], - [259, 'Add UI Interface Import'] + [259, 'Add UI Interface Import'], + [260, '"@Entry" annotaion fixed'], + [263, '"@Provide" annotation fixed'] ]); diff --git a/ets2panda/linter/src/lib/autofixes/Autofixer.ts b/ets2panda/linter/src/lib/autofixes/Autofixer.ts index d4c25ff2a5..a3495a0bf0 100644 --- a/ets2panda/linter/src/lib/autofixes/Autofixer.ts +++ b/ets2panda/linter/src/lib/autofixes/Autofixer.ts @@ -33,7 +33,14 @@ import { CustomDecoratorName, ARKUI_PACKAGE_NAME, VALUE_IDENTIFIER, - INDENT_STEP + INDENT_STEP, + ENTRY_DECORATOR_NAME, + ENTRY_STORAGE_PROPERITY, + LOCAL_STORAGE_TYPE_NAME, + GET_LOCAL_STORAGE_FUNC_NAME, + PROVIDE_DECORATOR_NAME, + PROVIDE_ALIAS_PROPERTY_NAME, + PROVIDE_ALLOW_OVERRIDE_PROPERTY_NAME } from '../utils/consts/ArkuiConstants'; const UNDEFINED_NAME = 'undefined'; @@ -2359,6 +2366,143 @@ export class Autofixer { return [{ start: funcDecl.getStart(), end: funcDecl.getEnd(), replacementText: text }]; } + fixEntryDecorator(entryDecorator: ts.Decorator): Autofix[] | undefined { + if (!ts.isCallExpression(entryDecorator.expression)) { + return undefined; + } + + const args = entryDecorator.expression.arguments; + if (args.length !== 1) { + return undefined; + } + + const parentNode = entryDecorator.parent; + const arg = args[0]; + let getLocalStorageStatement: ts.VariableStatement | undefined; + + if (ts.isIdentifier(arg) || ts.isNewExpression(arg) || ts.isCallExpression(arg)) { + getLocalStorageStatement = Autofixer.createGetLocalStorageLambdaStatement(arg); + } else if (ts.isObjectLiteralExpression(arg)) { + getLocalStorageStatement = Autofixer.processEntryAnnotationObjectLiteralExpression(arg); + } + + if (getLocalStorageStatement !== undefined) { + let text = this.printer.printNode(ts.EmitHint.Unspecified, getLocalStorageStatement, parentNode.getSourceFile()); + const fixedEntryDecorator = Autofixer.createFixedEntryDecorator(); + const fixedEntryDecoratorText = this.printer.printNode( + ts.EmitHint.Unspecified, + fixedEntryDecorator, + parentNode.getSourceFile() + ); + text = text + '\n' + fixedEntryDecoratorText; + return [{ start: entryDecorator.getStart(), end: entryDecorator.getEnd(), replacementText: text }]; + } + return undefined; + } + + private static createFixedEntryDecorator(): ts.Decorator { + const storageProperty = ts.factory.createPropertyAssignment( + ts.factory.createIdentifier(ENTRY_STORAGE_PROPERITY), + ts.factory.createStringLiteral(GET_LOCAL_STORAGE_FUNC_NAME) + ); + const objectLiteralExpr = ts.factory.createObjectLiteralExpression([storageProperty], false); + const callExpr = ts.factory.createCallExpression(ts.factory.createIdentifier(ENTRY_DECORATOR_NAME), undefined, [ + objectLiteralExpr + ]); + return ts.factory.createDecorator(callExpr); + } + + private static processEntryAnnotationObjectLiteralExpression( + expression: ts.ObjectLiteralExpression + ): ts.VariableStatement | undefined { + const objectProperties = expression.properties; + if (objectProperties.length !== 1) { + return undefined; + } + const objectProperty = objectProperties[0]; + if (!ts.isPropertyAssignment(objectProperty)) { + return undefined; + } + if (ts.isIdentifier(objectProperty.name)) { + if (objectProperty.name.escapedText !== ENTRY_STORAGE_PROPERITY) { + return undefined; + } + const properityInitializer = objectProperty.initializer; + if ( + ts.isIdentifier(properityInitializer) || + ts.isNewExpression(properityInitializer) || + ts.isCallExpression(properityInitializer) || + ts.isPropertyAccessExpression(properityInitializer) + ) { + return Autofixer.createGetLocalStorageLambdaStatement(properityInitializer); + } + } + return undefined; + } + + private static createGetLocalStorageLambdaStatement(expression: ts.Expression): ts.VariableStatement { + const variable = ts.factory.createVariableDeclaration( + ts.factory.createIdentifier(GET_LOCAL_STORAGE_FUNC_NAME), + undefined, + undefined, + ts.factory.createArrowFunction( + undefined, + undefined, + [], + ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(LOCAL_STORAGE_TYPE_NAME), undefined), + ts.factory.createToken(ts.SyntaxKind.EqualsGreaterThanToken), + expression + ) + ); + const declarationList = ts.factory.createVariableDeclarationList([variable], ts.NodeFlags.Const); + return ts.factory.createVariableStatement(undefined, declarationList); + } + + fixProvideDecorator(provideDecorator: ts.Decorator): Autofix[] | undefined { + const callExpr = provideDecorator.expression as ts.CallExpression; + const args = callExpr.arguments; + const parentNode = provideDecorator.parent; + const arg = args[0]; + let provideAnnotationFixed: ts.Decorator | undefined; + if (ts.isStringLiteral(arg)) { + provideAnnotationFixed = Autofixer.createProvideDecorator(arg); + } + if (ts.isObjectLiteralExpression(arg)) { + const properties = arg.properties; + const property = properties[0] as ts.PropertyAssignment; + const propertyInitializer = property.initializer as ts.StringLiteral; + provideAnnotationFixed = Autofixer.createProvideDecorator(propertyInitializer, true); + } + if (provideAnnotationFixed !== undefined) { + const text = this.printer.printNode(ts.EmitHint.Unspecified, provideAnnotationFixed, parentNode.getSourceFile()); + return [{ start: provideDecorator.getStart(), end: provideDecorator.getEnd(), replacementText: text }]; + } + return undefined; + } + + private static createProvideDecorator( + alias: ts.StringLiteral, + allowOverride: boolean | undefined = undefined + ): ts.Decorator { + const properties: ts.PropertyAssignment[] = []; + properties.push( + ts.factory.createPropertyAssignment(ts.factory.createIdentifier(PROVIDE_ALIAS_PROPERTY_NAME), alias) + ); + if (allowOverride !== undefined && allowOverride) { + properties.push( + ts.factory.createPropertyAssignment( + ts.factory.createIdentifier(PROVIDE_ALLOW_OVERRIDE_PROPERTY_NAME), + ts.factory.createTrue() + ) + ); + } + const objectLiteralExpr = ts.factory.createObjectLiteralExpression(properties, false); + const callExpr = ts.factory.createCallExpression(ts.factory.createIdentifier(PROVIDE_DECORATOR_NAME), undefined, [ + objectLiteralExpr + ]); + return ts.factory.createDecorator(callExpr); + } + private static createFunctionDeclaration( funcDecl: ts.FunctionDeclaration, typeParameters: ts.TypeParameterDeclaration[] | undefined, diff --git a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts index f1fb4bbe4a..7d2be8a961 100644 --- a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts +++ b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts @@ -60,6 +60,8 @@ export const arkts2Rules: number[] = [ 257, 258, 259, + 260, + 263, 301, 302, 303, diff --git a/ets2panda/linter/src/lib/utils/consts/ArkuiConstants.ts b/ets2panda/linter/src/lib/utils/consts/ArkuiConstants.ts index 9e4f4e88dc..633b4e5ef1 100644 --- a/ets2panda/linter/src/lib/utils/consts/ArkuiConstants.ts +++ b/ets2panda/linter/src/lib/utils/consts/ArkuiConstants.ts @@ -46,3 +46,12 @@ export const observedDecoratorName: Set = new Set([ ]); export const skipImportDecoratorName: Set = new Set(['Extend', 'Styles', 'Sendable', 'Concurrent']); + +export const ENTRY_DECORATOR_NAME = 'Entry'; +export const ENTRY_STORAGE_PROPERITY = 'storage'; +export const LOCAL_STORAGE_TYPE_NAME = 'LocalStorage'; +export const GET_LOCAL_STORAGE_FUNC_NAME = '__get_local_storage__'; + +export const PROVIDE_DECORATOR_NAME = 'Provide'; +export const PROVIDE_ALIAS_PROPERTY_NAME = 'alias'; +export const PROVIDE_ALLOW_OVERRIDE_PROPERTY_NAME = 'allowOverride'; \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test10_1.ets b/ets2panda/linter/test/main/entry_annotation_test10_1.ets new file mode 100644 index 0000000000..898d571593 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test10_1.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; +import { getLocalStorage } from './storage-manager'; + +@Entry({storage: getLocalStorage(1)}) +@Component +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test10_1.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test10_1.ets.args.json new file mode 100644 index 0000000000..66e8f07a19 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test10_1.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test10_1.ets.arkts2.json b/ets2panda/linter/test/main/entry_annotation_test10_1.ets.arkts2.json new file mode 100644 index 0000000000..32c8ce210a --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test10_1.ets.arkts2.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 38, + "problem": "EntryAnnotation", + "suggest": "", + "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test10_1.ets.autofix.json b/ets2panda/linter/test/main/entry_annotation_test10_1.ets.autofix.json new file mode 100644 index 0000000000..e47b36f325 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test10_1.ets.autofix.json @@ -0,0 +1,35 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 38, + "problem": "EntryAnnotation", + "autofix": [ + { + "start": 756, + "end": 793, + "replacementText": "const __get_local_storage__ = (): LocalStorage => getLocalStorage(1);\n@Entry({ storage: \"__get_local_storage__\" })" + } + ], + "suggest": "", + "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test10_1.ets.json b/ets2panda/linter/test/main/entry_annotation_test10_1.ets.json new file mode 100644 index 0000000000..8227167def --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test10_1.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test10_2.ets b/ets2panda/linter/test/main/entry_annotation_test10_2.ets new file mode 100644 index 0000000000..b6345be4c3 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test10_2.ets @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; +import { getLocalStorage } from './storage-manager'; + +const __get_local_storage__ = (): LocalStorage => getLocalStorage(1); +@Entry({storage: "__get_local_storage__"}) +@Component +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test10_2.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test10_2.ets.args.json new file mode 100644 index 0000000000..66e8f07a19 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test10_2.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test10_2.ets.arkts2.json b/ets2panda/linter/test/main/entry_annotation_test10_2.ets.arkts2.json new file mode 100644 index 0000000000..8227167def --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test10_2.ets.arkts2.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test10_2.ets.autofix.json b/ets2panda/linter/test/main/entry_annotation_test10_2.ets.autofix.json new file mode 100644 index 0000000000..8227167def --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test10_2.ets.autofix.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test10_2.ets.json b/ets2panda/linter/test/main/entry_annotation_test10_2.ets.json new file mode 100644 index 0000000000..8227167def --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test10_2.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test1_1.ets b/ets2panda/linter/test/main/entry_annotation_test1_1.ets new file mode 100644 index 0000000000..e62f535cac --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test1_1.ets @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text } from '@ohos.arkui.components'; + +@Entry +@Component +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test1_1.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test1_1.ets.args.json new file mode 100644 index 0000000000..66e8f07a19 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test1_1.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test1_1.ets.arkts2.json b/ets2panda/linter/test/main/entry_annotation_test1_1.ets.arkts2.json new file mode 100644 index 0000000000..8227167def --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test1_1.ets.arkts2.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test1_1.ets.autofix.json b/ets2panda/linter/test/main/entry_annotation_test1_1.ets.autofix.json new file mode 100644 index 0000000000..8227167def --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test1_1.ets.autofix.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test1_1.ets.json b/ets2panda/linter/test/main/entry_annotation_test1_1.ets.json new file mode 100644 index 0000000000..8227167def --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test1_1.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test1_2.ets b/ets2panda/linter/test/main/entry_annotation_test1_2.ets new file mode 100644 index 0000000000..e62f535cac --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test1_2.ets @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text } from '@ohos.arkui.components'; + +@Entry +@Component +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test1_2.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test1_2.ets.args.json new file mode 100644 index 0000000000..66e8f07a19 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test1_2.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test1_2.ets.arkts2.json b/ets2panda/linter/test/main/entry_annotation_test1_2.ets.arkts2.json new file mode 100644 index 0000000000..8227167def --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test1_2.ets.arkts2.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test1_2.ets.autofix.json b/ets2panda/linter/test/main/entry_annotation_test1_2.ets.autofix.json new file mode 100644 index 0000000000..8227167def --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test1_2.ets.autofix.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test1_2.ets.json b/ets2panda/linter/test/main/entry_annotation_test1_2.ets.json new file mode 100644 index 0000000000..8227167def --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test1_2.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test2_1.ets b/ets2panda/linter/test/main/entry_annotation_test2_1.ets new file mode 100644 index 0000000000..09b330e06c --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test2_1.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const storage = new LocalStorage(); +@Entry(storage) +@Component +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test2_1.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test2_1.ets.args.json new file mode 100644 index 0000000000..66e8f07a19 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test2_1.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test2_1.ets.arkts2.json b/ets2panda/linter/test/main/entry_annotation_test2_1.ets.arkts2.json new file mode 100644 index 0000000000..350f552e39 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test2_1.ets.arkts2.json @@ -0,0 +1,48 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 7, + "endLine": 18, + "endColumn": 35, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 21, + "endLine": 18, + "endColumn": 33, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 16, + "problem": "EntryAnnotation", + "suggest": "", + "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test2_1.ets.autofix.json b/ets2panda/linter/test/main/entry_annotation_test2_1.ets.autofix.json new file mode 100644 index 0000000000..5fcc9d49f5 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test2_1.ets.autofix.json @@ -0,0 +1,55 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 7, + "endLine": 18, + "endColumn": 35, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 21, + "endLine": 18, + "endColumn": 33, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 16, + "problem": "EntryAnnotation", + "autofix": [ + { + "start": 739, + "end": 754, + "replacementText": "const __get_local_storage__ = (): LocalStorage => storage;\n@Entry({ storage: \"__get_local_storage__\" })" + } + ], + "suggest": "", + "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test2_1.ets.json b/ets2panda/linter/test/main/entry_annotation_test2_1.ets.json new file mode 100644 index 0000000000..a39b2863ef --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test2_1.ets.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 7, + "endLine": 18, + "endColumn": 35, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test2_2.ets b/ets2panda/linter/test/main/entry_annotation_test2_2.ets new file mode 100644 index 0000000000..52bd3e4f78 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test2_2.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const storage = new LocalStorage(); +const __get_local_storage__ = (): LocalStorage => storage; +@Entry({storage: "__get_local_storage__"}) +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test2_2.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test2_2.ets.args.json new file mode 100644 index 0000000000..66e8f07a19 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test2_2.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test2_2.ets.arkts2.json b/ets2panda/linter/test/main/entry_annotation_test2_2.ets.arkts2.json new file mode 100644 index 0000000000..bc6a0db58e --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test2_2.ets.arkts2.json @@ -0,0 +1,38 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 7, + "endLine": 18, + "endColumn": 35, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 21, + "endLine": 18, + "endColumn": 33, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test2_2.ets.autofix.json b/ets2panda/linter/test/main/entry_annotation_test2_2.ets.autofix.json new file mode 100644 index 0000000000..bc6a0db58e --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test2_2.ets.autofix.json @@ -0,0 +1,38 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 7, + "endLine": 18, + "endColumn": 35, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 21, + "endLine": 18, + "endColumn": 33, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test2_2.ets.json b/ets2panda/linter/test/main/entry_annotation_test2_2.ets.json new file mode 100644 index 0000000000..a39b2863ef --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test2_2.ets.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 7, + "endLine": 18, + "endColumn": 35, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test3_1.ets b/ets2panda/linter/test/main/entry_annotation_test3_1.ets new file mode 100644 index 0000000000..6dbca25bda --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test3_1.ets @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +@Entry(new LocalStorage()) +@Component +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test3_1.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test3_1.ets.args.json new file mode 100644 index 0000000000..66e8f07a19 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test3_1.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test3_1.ets.arkts2.json b/ets2panda/linter/test/main/entry_annotation_test3_1.ets.arkts2.json new file mode 100644 index 0000000000..aa442606c5 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test3_1.ets.arkts2.json @@ -0,0 +1,38 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 27, + "problem": "EntryAnnotation", + "suggest": "", + "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 12, + "endLine": 18, + "endColumn": 24, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test3_1.ets.autofix.json b/ets2panda/linter/test/main/entry_annotation_test3_1.ets.autofix.json new file mode 100644 index 0000000000..b61a99047a --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test3_1.ets.autofix.json @@ -0,0 +1,45 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 27, + "problem": "EntryAnnotation", + "autofix": [ + { + "start": 702, + "end": 728, + "replacementText": "const __get_local_storage__ = (): LocalStorage => new LocalStorage();\n@Entry({ storage: \"__get_local_storage__\" })" + } + ], + "suggest": "", + "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 12, + "endLine": 18, + "endColumn": 24, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test3_1.ets.json b/ets2panda/linter/test/main/entry_annotation_test3_1.ets.json new file mode 100644 index 0000000000..8227167def --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test3_1.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test3_2.ets b/ets2panda/linter/test/main/entry_annotation_test3_2.ets new file mode 100644 index 0000000000..5d9cf9c567 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test3_2.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const __get_local_storage__ = (): LocalStorage => new LocalStorage(); +@Entry({storage: "__get_local_storage__"}) +@Component +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test3_2.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test3_2.ets.args.json new file mode 100644 index 0000000000..66e8f07a19 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test3_2.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test3_2.ets.arkts2.json b/ets2panda/linter/test/main/entry_annotation_test3_2.ets.arkts2.json new file mode 100644 index 0000000000..daadd31517 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test3_2.ets.arkts2.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 55, + "endLine": 18, + "endColumn": 67, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test3_2.ets.autofix.json b/ets2panda/linter/test/main/entry_annotation_test3_2.ets.autofix.json new file mode 100644 index 0000000000..daadd31517 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test3_2.ets.autofix.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 55, + "endLine": 18, + "endColumn": 67, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test3_2.ets.json b/ets2panda/linter/test/main/entry_annotation_test3_2.ets.json new file mode 100644 index 0000000000..8227167def --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test3_2.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test4_1.ets b/ets2panda/linter/test/main/entry_annotation_test4_1.ets new file mode 100644 index 0000000000..c6c4d34956 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test4_1.ets @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +@Entry(LocalStorage.getShared()) +@Component +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test4_1.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test4_1.ets.args.json new file mode 100644 index 0000000000..66e8f07a19 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test4_1.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test4_1.ets.arkts2.json b/ets2panda/linter/test/main/entry_annotation_test4_1.ets.arkts2.json new file mode 100644 index 0000000000..6055f15b89 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test4_1.ets.arkts2.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 33, + "problem": "EntryAnnotation", + "suggest": "", + "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test4_1.ets.autofix.json b/ets2panda/linter/test/main/entry_annotation_test4_1.ets.autofix.json new file mode 100644 index 0000000000..e765741f4c --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test4_1.ets.autofix.json @@ -0,0 +1,35 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 33, + "problem": "EntryAnnotation", + "autofix": [ + { + "start": 702, + "end": 734, + "replacementText": "const __get_local_storage__ = (): LocalStorage => LocalStorage.getShared();\n@Entry({ storage: \"__get_local_storage__\" })" + } + ], + "suggest": "", + "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test4_1.ets.json b/ets2panda/linter/test/main/entry_annotation_test4_1.ets.json new file mode 100644 index 0000000000..8227167def --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test4_1.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test4_2.ets b/ets2panda/linter/test/main/entry_annotation_test4_2.ets new file mode 100644 index 0000000000..6638d8b755 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test4_2.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const __get_local_storage__ = (): LocalStorage => LocalStorage.getShared(); +@Entry({storage: "__get_local_storage__"}) +@Component +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test4_2.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test4_2.ets.args.json new file mode 100644 index 0000000000..66e8f07a19 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test4_2.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test4_2.ets.arkts2.json b/ets2panda/linter/test/main/entry_annotation_test4_2.ets.arkts2.json new file mode 100644 index 0000000000..8227167def --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test4_2.ets.arkts2.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test4_2.ets.autofix.json b/ets2panda/linter/test/main/entry_annotation_test4_2.ets.autofix.json new file mode 100644 index 0000000000..8227167def --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test4_2.ets.autofix.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test4_2.ets.json b/ets2panda/linter/test/main/entry_annotation_test4_2.ets.json new file mode 100644 index 0000000000..8227167def --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test4_2.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test5_1.ets b/ets2panda/linter/test/main/entry_annotation_test5_1.ets new file mode 100644 index 0000000000..7bea704097 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test5_1.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const storage = new LocalStorage(); +@Entry({storage: storage}) +@Component +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test5_1.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test5_1.ets.args.json new file mode 100644 index 0000000000..66e8f07a19 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test5_1.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test5_1.ets.arkts2.json b/ets2panda/linter/test/main/entry_annotation_test5_1.ets.arkts2.json new file mode 100644 index 0000000000..723aac826a --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test5_1.ets.arkts2.json @@ -0,0 +1,48 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 7, + "endLine": 18, + "endColumn": 35, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 21, + "endLine": 18, + "endColumn": 33, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 27, + "problem": "EntryAnnotation", + "suggest": "", + "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test5_1.ets.autofix.json b/ets2panda/linter/test/main/entry_annotation_test5_1.ets.autofix.json new file mode 100644 index 0000000000..f6c124af23 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test5_1.ets.autofix.json @@ -0,0 +1,55 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 7, + "endLine": 18, + "endColumn": 35, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 21, + "endLine": 18, + "endColumn": 33, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 27, + "problem": "EntryAnnotation", + "autofix": [ + { + "start": 739, + "end": 765, + "replacementText": "const __get_local_storage__ = (): LocalStorage => storage;\n@Entry({ storage: \"__get_local_storage__\" })" + } + ], + "suggest": "", + "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test5_1.ets.json b/ets2panda/linter/test/main/entry_annotation_test5_1.ets.json new file mode 100644 index 0000000000..a39b2863ef --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test5_1.ets.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 7, + "endLine": 18, + "endColumn": 35, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test5_2.ets b/ets2panda/linter/test/main/entry_annotation_test5_2.ets new file mode 100644 index 0000000000..52bd3e4f78 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test5_2.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const storage = new LocalStorage(); +const __get_local_storage__ = (): LocalStorage => storage; +@Entry({storage: "__get_local_storage__"}) +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test5_2.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test5_2.ets.args.json new file mode 100644 index 0000000000..66e8f07a19 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test5_2.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test5_2.ets.arkts2.json b/ets2panda/linter/test/main/entry_annotation_test5_2.ets.arkts2.json new file mode 100644 index 0000000000..bc6a0db58e --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test5_2.ets.arkts2.json @@ -0,0 +1,38 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 7, + "endLine": 18, + "endColumn": 35, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 21, + "endLine": 18, + "endColumn": 33, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test5_2.ets.autofix.json b/ets2panda/linter/test/main/entry_annotation_test5_2.ets.autofix.json new file mode 100644 index 0000000000..bc6a0db58e --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test5_2.ets.autofix.json @@ -0,0 +1,38 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 7, + "endLine": 18, + "endColumn": 35, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 21, + "endLine": 18, + "endColumn": 33, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test5_2.ets.json b/ets2panda/linter/test/main/entry_annotation_test5_2.ets.json new file mode 100644 index 0000000000..a39b2863ef --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test5_2.ets.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 7, + "endLine": 18, + "endColumn": 35, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test6_1.ets b/ets2panda/linter/test/main/entry_annotation_test6_1.ets new file mode 100644 index 0000000000..e17333cbff --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test6_1.ets @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +@Entry({storage: new LocalStorage()}) +@Component +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test6_1.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test6_1.ets.args.json new file mode 100644 index 0000000000..66e8f07a19 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test6_1.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test6_1.ets.arkts2.json b/ets2panda/linter/test/main/entry_annotation_test6_1.ets.arkts2.json new file mode 100644 index 0000000000..ad567bc81c --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test6_1.ets.arkts2.json @@ -0,0 +1,38 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 38, + "problem": "EntryAnnotation", + "suggest": "", + "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 22, + "endLine": 18, + "endColumn": 34, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test6_1.ets.autofix.json b/ets2panda/linter/test/main/entry_annotation_test6_1.ets.autofix.json new file mode 100644 index 0000000000..0c300530e8 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test6_1.ets.autofix.json @@ -0,0 +1,45 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 38, + "problem": "EntryAnnotation", + "autofix": [ + { + "start": 702, + "end": 739, + "replacementText": "const __get_local_storage__ = (): LocalStorage => new LocalStorage();\n@Entry({ storage: \"__get_local_storage__\" })" + } + ], + "suggest": "", + "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 22, + "endLine": 18, + "endColumn": 34, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test6_1.ets.json b/ets2panda/linter/test/main/entry_annotation_test6_1.ets.json new file mode 100644 index 0000000000..8227167def --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test6_1.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test6_2.ets b/ets2panda/linter/test/main/entry_annotation_test6_2.ets new file mode 100644 index 0000000000..5d9cf9c567 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test6_2.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const __get_local_storage__ = (): LocalStorage => new LocalStorage(); +@Entry({storage: "__get_local_storage__"}) +@Component +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test6_2.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test6_2.ets.args.json new file mode 100644 index 0000000000..66e8f07a19 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test6_2.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test6_2.ets.arkts2.json b/ets2panda/linter/test/main/entry_annotation_test6_2.ets.arkts2.json new file mode 100644 index 0000000000..daadd31517 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test6_2.ets.arkts2.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 55, + "endLine": 18, + "endColumn": 67, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test6_2.ets.autofix.json b/ets2panda/linter/test/main/entry_annotation_test6_2.ets.autofix.json new file mode 100644 index 0000000000..daadd31517 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test6_2.ets.autofix.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 55, + "endLine": 18, + "endColumn": 67, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test6_2.ets.json b/ets2panda/linter/test/main/entry_annotation_test6_2.ets.json new file mode 100644 index 0000000000..8227167def --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test6_2.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test7_1.ets b/ets2panda/linter/test/main/entry_annotation_test7_1.ets new file mode 100644 index 0000000000..5de5fc213a --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test7_1.ets @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +@Entry({storage: LocalStorage.getShared()}) +@Component +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test7_1.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test7_1.ets.args.json new file mode 100644 index 0000000000..66e8f07a19 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test7_1.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test7_1.ets.arkts2.json b/ets2panda/linter/test/main/entry_annotation_test7_1.ets.arkts2.json new file mode 100644 index 0000000000..2b7950ceb8 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test7_1.ets.arkts2.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 44, + "problem": "EntryAnnotation", + "suggest": "", + "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test7_1.ets.autofix.json b/ets2panda/linter/test/main/entry_annotation_test7_1.ets.autofix.json new file mode 100644 index 0000000000..655059a71d --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test7_1.ets.autofix.json @@ -0,0 +1,35 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 44, + "problem": "EntryAnnotation", + "autofix": [ + { + "start": 702, + "end": 745, + "replacementText": "const __get_local_storage__ = (): LocalStorage => LocalStorage.getShared();\n@Entry({ storage: \"__get_local_storage__\" })" + } + ], + "suggest": "", + "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test7_1.ets.json b/ets2panda/linter/test/main/entry_annotation_test7_1.ets.json new file mode 100644 index 0000000000..8227167def --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test7_1.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test7_2.ets b/ets2panda/linter/test/main/entry_annotation_test7_2.ets new file mode 100644 index 0000000000..6638d8b755 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test7_2.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const __get_local_storage__ = (): LocalStorage => LocalStorage.getShared(); +@Entry({storage: "__get_local_storage__"}) +@Component +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test7_2.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test7_2.ets.args.json new file mode 100644 index 0000000000..66e8f07a19 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test7_2.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test7_2.ets.arkts2.json b/ets2panda/linter/test/main/entry_annotation_test7_2.ets.arkts2.json new file mode 100644 index 0000000000..8227167def --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test7_2.ets.arkts2.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test7_2.ets.autofix.json b/ets2panda/linter/test/main/entry_annotation_test7_2.ets.autofix.json new file mode 100644 index 0000000000..8227167def --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test7_2.ets.autofix.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test7_2.ets.json b/ets2panda/linter/test/main/entry_annotation_test7_2.ets.json new file mode 100644 index 0000000000..8227167def --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test7_2.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test8_1.ets b/ets2panda/linter/test/main/entry_annotation_test8_1.ets new file mode 100644 index 0000000000..f5895dae8c --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test8_1.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const source = globalThis.localStorage; +@Entry({storage: source}) +@Component +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test8_1.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test8_1.ets.args.json new file mode 100644 index 0000000000..66e8f07a19 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test8_1.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test8_1.ets.arkts2.json b/ets2panda/linter/test/main/entry_annotation_test8_1.ets.arkts2.json new file mode 100644 index 0000000000..1845256104 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test8_1.ets.arkts2.json @@ -0,0 +1,38 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 16, + "endLine": 18, + "endColumn": 39, + "problem": "GlobalThisError", + "suggest": "", + "rule": "\"globalThis\" is not supported (arkts-no-globalthis)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 26, + "problem": "EntryAnnotation", + "suggest": "", + "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test8_1.ets.autofix.json b/ets2panda/linter/test/main/entry_annotation_test8_1.ets.autofix.json new file mode 100644 index 0000000000..9f9ef341aa --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test8_1.ets.autofix.json @@ -0,0 +1,52 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 16, + "endLine": 18, + "endColumn": 39, + "problem": "GlobalThisError", + "autofix": [ + { + "start": 717, + "end": 740, + "replacementText": "specialAutofixLib.globalThis.get(\"localStorage\")" + } + ], + "suggest": "", + "rule": "\"globalThis\" is not supported (arkts-no-globalthis)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 26, + "problem": "EntryAnnotation", + "autofix": [ + { + "start": 743, + "end": 768, + "replacementText": "const __get_local_storage__ = (): LocalStorage => source;\n@Entry({ storage: \"__get_local_storage__\" })" + } + ], + "suggest": "", + "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test8_1.ets.json b/ets2panda/linter/test/main/entry_annotation_test8_1.ets.json new file mode 100644 index 0000000000..b9bcd106e5 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test8_1.ets.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 16, + "endLine": 18, + "endColumn": 26, + "problem": "GlobalThis", + "suggest": "", + "rule": "\"globalThis\" is not supported (arkts-no-globalthis)", + "severity": "WARNING" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test8_2.ets b/ets2panda/linter/test/main/entry_annotation_test8_2.ets new file mode 100644 index 0000000000..1120a5a860 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test8_2.ets @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const source = globalThis.localStorage; +const __get_local_storage__ = (): LocalStorage => source; +@Entry({storage: "__get_local_storage__"}) +@Component +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test8_2.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test8_2.ets.args.json new file mode 100644 index 0000000000..66e8f07a19 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test8_2.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test8_2.ets.arkts2.json b/ets2panda/linter/test/main/entry_annotation_test8_2.ets.arkts2.json new file mode 100644 index 0000000000..9dc9dd7879 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test8_2.ets.arkts2.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 16, + "endLine": 18, + "endColumn": 39, + "problem": "GlobalThisError", + "suggest": "", + "rule": "\"globalThis\" is not supported (arkts-no-globalthis)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test8_2.ets.autofix.json b/ets2panda/linter/test/main/entry_annotation_test8_2.ets.autofix.json new file mode 100644 index 0000000000..e111a09d28 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test8_2.ets.autofix.json @@ -0,0 +1,35 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 16, + "endLine": 18, + "endColumn": 39, + "problem": "GlobalThisError", + "autofix": [ + { + "start": 717, + "end": 740, + "replacementText": "specialAutofixLib.globalThis.get(\"localStorage\")" + } + ], + "suggest": "", + "rule": "\"globalThis\" is not supported (arkts-no-globalthis)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test8_2.ets.json b/ets2panda/linter/test/main/entry_annotation_test8_2.ets.json new file mode 100644 index 0000000000..b9bcd106e5 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test8_2.ets.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 16, + "endLine": 18, + "endColumn": 26, + "problem": "GlobalThis", + "suggest": "", + "rule": "\"globalThis\" is not supported (arkts-no-globalthis)", + "severity": "WARNING" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test9_1.ets b/ets2panda/linter/test/main/entry_annotation_test9_1.ets new file mode 100644 index 0000000000..6d77c4401b --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test9_1.ets @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +@Entry({storage: globalThis.localStorage}) +@Component +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test9_1.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test9_1.ets.args.json new file mode 100644 index 0000000000..66e8f07a19 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test9_1.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test9_1.ets.arkts2.json b/ets2panda/linter/test/main/entry_annotation_test9_1.ets.arkts2.json new file mode 100644 index 0000000000..13bf251571 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test9_1.ets.arkts2.json @@ -0,0 +1,38 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 43, + "problem": "EntryAnnotation", + "suggest": "", + "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 18, + "endLine": 18, + "endColumn": 41, + "problem": "GlobalThisError", + "suggest": "", + "rule": "\"globalThis\" is not supported (arkts-no-globalthis)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test9_1.ets.autofix.json b/ets2panda/linter/test/main/entry_annotation_test9_1.ets.autofix.json new file mode 100644 index 0000000000..b2105691ce --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test9_1.ets.autofix.json @@ -0,0 +1,52 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 43, + "problem": "EntryAnnotation", + "autofix": [ + { + "start": 702, + "end": 744, + "replacementText": "const __get_local_storage__ = (): LocalStorage => globalThis.localStorage;\n@Entry({ storage: \"__get_local_storage__\" })" + } + ], + "suggest": "", + "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 18, + "endLine": 18, + "endColumn": 41, + "problem": "GlobalThisError", + "autofix": [ + { + "start": 719, + "end": 742, + "replacementText": "specialAutofixLib.globalThis.get(\"localStorage\")" + } + ], + "suggest": "", + "rule": "\"globalThis\" is not supported (arkts-no-globalthis)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test9_1.ets.json b/ets2panda/linter/test/main/entry_annotation_test9_1.ets.json new file mode 100644 index 0000000000..87514dc7ed --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test9_1.ets.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 18, + "endLine": 18, + "endColumn": 28, + "problem": "GlobalThis", + "suggest": "", + "rule": "\"globalThis\" is not supported (arkts-no-globalthis)", + "severity": "WARNING" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test9_2.ets b/ets2panda/linter/test/main/entry_annotation_test9_2.ets new file mode 100644 index 0000000000..f6f5bf039f --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test9_2.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const __get_local_storage__ = (): LocalStorage => globalThis.localStorage; +@Entry({storage: "__get_local_storage__"}) +@Component +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test9_2.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test9_2.ets.args.json new file mode 100644 index 0000000000..66e8f07a19 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test9_2.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test9_2.ets.arkts2.json b/ets2panda/linter/test/main/entry_annotation_test9_2.ets.arkts2.json new file mode 100644 index 0000000000..08d96edc08 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test9_2.ets.arkts2.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 51, + "endLine": 18, + "endColumn": 74, + "problem": "GlobalThisError", + "suggest": "", + "rule": "\"globalThis\" is not supported (arkts-no-globalthis)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test9_2.ets.autofix.json b/ets2panda/linter/test/main/entry_annotation_test9_2.ets.autofix.json new file mode 100644 index 0000000000..0727f2fce6 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test9_2.ets.autofix.json @@ -0,0 +1,35 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 51, + "endLine": 18, + "endColumn": 74, + "problem": "GlobalThisError", + "autofix": [ + { + "start": 752, + "end": 775, + "replacementText": "specialAutofixLib.globalThis.get(\"localStorage\")" + } + ], + "suggest": "", + "rule": "\"globalThis\" is not supported (arkts-no-globalthis)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test9_2.ets.json b/ets2panda/linter/test/main/entry_annotation_test9_2.ets.json new file mode 100644 index 0000000000..c259d2121e --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test9_2.ets.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 51, + "endLine": 18, + "endColumn": 61, + "problem": "GlobalThis", + "suggest": "", + "rule": "\"globalThis\" is not supported (arkts-no-globalthis)", + "severity": "WARNING" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/provide_annotation_1.ets b/ets2panda/linter/test/main/provide_annotation_1.ets new file mode 100644 index 0000000000..6eebfb8e65 --- /dev/null +++ b/ets2panda/linter/test/main/provide_annotation_1.ets @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@Component +struct Index { + @Provide + value: number; + build() { + Column() { + } + } +} + +@Component +struct Index { + @Provide("value") + value: number; + build() { + Column() { + } + } +} + +@Component +struct Index { + @Provide({allowOverride: "value"}) + value: number; + build() { + Column() { + } + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/provide_annotation_1.ets.args.json b/ets2panda/linter/test/main/provide_annotation_1.ets.args.json new file mode 100644 index 0000000000..40bac500e3 --- /dev/null +++ b/ets2panda/linter/test/main/provide_annotation_1.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2" + } + } \ No newline at end of file diff --git a/ets2panda/linter/test/main/provide_annotation_1.ets.arkts2.json b/ets2panda/linter/test/main/provide_annotation_1.ets.arkts2.json new file mode 100644 index 0000000000..1111f1a6e8 --- /dev/null +++ b/ets2panda/linter/test/main/provide_annotation_1.ets.arkts2.json @@ -0,0 +1,98 @@ +{ + "copyright": [ + "Copyright (c) 2023-2024 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 28, + "column": 3, + "endLine": 29, + "endColumn": 17, + "problem": "ProvideAnnotation", + "suggest": "", + "rule": "The \"@Provide\" annotation does not support dynamic parameters (arkui-provide-annotation-parameters)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 3, + "endLine": 39, + "endColumn": 17, + "problem": "ProvideAnnotation", + "suggest": "", + "rule": "The \"@Provide\" annotation does not support dynamic parameters (arkui-provide-annotation-parameters)", + "severity": "ERROR" + }, + { + "line": 16, + "column": 2, + "endLine": 16, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 4, + "endLine": 18, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 5, + "endLine": 21, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 3, + "endLine": 19, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 29, + "column": 3, + "endLine": 29, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 39, + "column": 3, + "endLine": 39, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/provide_annotation_1.ets.autofix.json b/ets2panda/linter/test/main/provide_annotation_1.ets.autofix.json new file mode 100644 index 0000000000..0aa483a8a8 --- /dev/null +++ b/ets2panda/linter/test/main/provide_annotation_1.ets.autofix.json @@ -0,0 +1,119 @@ +{ + "copyright": [ + "Copyright (c) 2023-2024 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 28, + "column": 3, + "endLine": 29, + "endColumn": 17, + "problem": "ProvideAnnotation", + "autofix": [ + { + "start": 754, + "end": 771, + "replacementText": "@Provide({ alias: \"value\" })" + } + ], + "suggest": "", + "rule": "The \"@Provide\" annotation does not support dynamic parameters (arkui-provide-annotation-parameters)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 3, + "endLine": 39, + "endColumn": 17, + "problem": "ProvideAnnotation", + "autofix": [ + { + "start": 867, + "end": 901, + "replacementText": "@Provide({ alias: \"value\", allowOverride: true })" + } + ], + "suggest": "", + "rule": "The \"@Provide\" annotation does not support dynamic parameters (arkui-provide-annotation-parameters)", + "severity": "ERROR" + }, + { + "line": 16, + "column": 2, + "endLine": 16, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 4, + "endLine": 18, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 5, + "endLine": 21, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 616, + "end": 616, + "replacementText": "\n\nimport { Component, Provide, Column } from '@kits.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 3, + "endLine": 19, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 29, + "column": 3, + "endLine": 29, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 39, + "column": 3, + "endLine": 39, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/provide_annotation_1.ets.json b/ets2panda/linter/test/main/provide_annotation_1.ets.json new file mode 100644 index 0000000000..23189d668f --- /dev/null +++ b/ets2panda/linter/test/main/provide_annotation_1.ets.json @@ -0,0 +1,48 @@ +{ + "copyright": [ + "Copyright (c) 2023-2024 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 19, + "column": 3, + "endLine": 19, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 29, + "column": 3, + "endLine": 29, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 39, + "column": 3, + "endLine": 39, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/provide_annotation_2.ets b/ets2panda/linter/test/main/provide_annotation_2.ets new file mode 100644 index 0000000000..a3d3e3bb35 --- /dev/null +++ b/ets2panda/linter/test/main/provide_annotation_2.ets @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@Component +struct Index { + @Provide + value: number; + build() { + Column() { + } + } +} + +@Component +struct Index { + @Provide({ alias: "value" }) + value: number; + build() { + Column() { + } + } +} + +@Component +struct Index { + @Provide({ alias: "value", allowOverride: true }) + value: number; + build() { + Column() { + } + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/provide_annotation_2.ets.args.json b/ets2panda/linter/test/main/provide_annotation_2.ets.args.json new file mode 100644 index 0000000000..40bac500e3 --- /dev/null +++ b/ets2panda/linter/test/main/provide_annotation_2.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2" + } + } \ No newline at end of file diff --git a/ets2panda/linter/test/main/provide_annotation_2.ets.arkts2.json b/ets2panda/linter/test/main/provide_annotation_2.ets.arkts2.json new file mode 100644 index 0000000000..d5f43e0789 --- /dev/null +++ b/ets2panda/linter/test/main/provide_annotation_2.ets.arkts2.json @@ -0,0 +1,78 @@ +{ + "copyright": [ + "Copyright (c) 2023-2024 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 2, + "endLine": 16, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 4, + "endLine": 18, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 5, + "endLine": 21, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 3, + "endLine": 19, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 29, + "column": 3, + "endLine": 29, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 39, + "column": 3, + "endLine": 39, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/provide_annotation_2.ets.autofix.json b/ets2panda/linter/test/main/provide_annotation_2.ets.autofix.json new file mode 100644 index 0000000000..7f9665e664 --- /dev/null +++ b/ets2panda/linter/test/main/provide_annotation_2.ets.autofix.json @@ -0,0 +1,85 @@ +{ + "copyright": [ + "Copyright (c) 2023-2024 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 2, + "endLine": 16, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 4, + "endLine": 18, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 5, + "endLine": 21, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 616, + "end": 616, + "replacementText": "\n\nimport { Component, Provide, Column } from '@kits.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 3, + "endLine": 19, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 29, + "column": 3, + "endLine": 29, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 39, + "column": 3, + "endLine": 39, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/provide_annotation_2.ets.json b/ets2panda/linter/test/main/provide_annotation_2.ets.json new file mode 100644 index 0000000000..23189d668f --- /dev/null +++ b/ets2panda/linter/test/main/provide_annotation_2.ets.json @@ -0,0 +1,48 @@ +{ + "copyright": [ + "Copyright (c) 2023-2024 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 19, + "column": 3, + "endLine": 19, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 29, + "column": 3, + "endLine": 29, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 39, + "column": 3, + "endLine": 39, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + } + ] +} \ No newline at end of file -- Gitee From 5fa63f69416ce75d7157fe6f59a77d748fe42b2c Mon Sep 17 00:00:00 2001 From: ZhongNing Date: Sat, 12 Apr 2025 15:40:34 +0800 Subject: [PATCH 054/268] fix issue for arkts-identifiers-as-prop-names Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBZWTD Test scenarios: fix issue for arkts-identifiers-as-prop-names Signed-off-by: ZhongNing --- ets2panda/linter/src/lib/TypeScriptLinter.ts | 19 +- .../linter/src/lib/autofixes/Autofixer.ts | 65 +---- ets2panda/linter/src/lib/utils/TsUtils.ts | 31 ++- .../main/interface_literal_prop_name.ets.json | 20 -- .../test/main/literals_as_prop_names.ets | 22 ++ .../main/literals_as_prop_names.ets.args.json | 2 +- .../literals_as_prop_names.ets.arkts2.json | 120 ++++++--- .../literals_as_prop_names.ets.autofix.json | 246 +++++++++++------- .../test/main/literals_as_prop_names.ets.json | 22 +- .../test/main/type_literals.ets.autofix.json | 20 -- .../linter/test/main/type_literals.ets.json | 20 -- .../linter/test/main/types.ets.autofix.json | 32 --- ets2panda/linter/test/main/types.ets.json | 20 -- 13 files changed, 286 insertions(+), 353 deletions(-) diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index 58d43f92fe..863f533f08 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -1016,7 +1016,7 @@ export class TypeScriptLinter { } } - private handleLiteralAsPropertyName(node: ts.PropertyDeclaration): void { + private handleLiteralAsPropertyName(node: ts.PropertyDeclaration | ts.PropertySignature): void { const propName = node.name; if (!!propName && (ts.isNumericLiteral(propName) || this.options.arkts2 && ts.isStringLiteral(propName))) { const autofix = this.autofixer?.fixLiteralAsPropertyNamePropertyName(propName); @@ -1027,10 +1027,6 @@ export class TypeScriptLinter { private handlePropertyDeclaration(node: ts.PropertyDeclaration): void { this.handleDataObservation(node); const propName = node.name; - if (!!propName && (ts.isNumericLiteral(propName) || this.options.arkts2 && ts.isStringLiteral(propName))) { - const autofix = this.autofixer?.fixLiteralAsPropertyNamePropertyName(propName); - this.incrementCounters(node.name, FaultID.LiteralAsPropertyName, autofix); - } this.handleLiteralAsPropertyName(node); const decorators = ts.getDecorators(node); this.filterOutDecoratorsDiagnostics( @@ -1136,16 +1132,8 @@ export class TypeScriptLinter { } private handlePropertySignature(node: ts.PropertySignature): void { - const propName = node.name; this.handleInterfaceProperty(node); - if (!!propName && (ts.isNumericLiteral(propName) || this.options.arkts2 && ts.isStringLiteral(propName))) { - const autofix = this.autofixer?.fixLiteralAsPropertyNamePropertyName(propName); - this.incrementCounters(node.name, FaultID.LiteralAsPropertyName, autofix); - } - if (!!propName && (ts.isNumericLiteral(propName) || this.options.arkts2 && ts.isStringLiteral(propName))) { - const autofix = this.autofixer?.fixLiteralAsPropertyNamePropertyName(propName); - this.incrementCounters(node.name, FaultID.LiteralAsPropertyName, autofix); - } + this.handleLiteralAsPropertyName(node); this.handleSendableInterfaceProperty(node); this.handleInvalidIdentifier(node); } @@ -2854,8 +2842,7 @@ export class TypeScriptLinter { tsEnumMemberName: ts.StringLiteral, node: ts.Node ): void { - const autofix = this.autofixer?.fixLiteralAsPropertyNamePropertyName(tsEnumMemberName); - this.autofixer?.checkEnumMemberNameConflict(tsEnumMember, autofix); + const autofix = this.autofixer?.fixLiteralAsPropertyNamePropertyName(tsEnumMemberName, tsEnumMember); this.incrementCounters(node, FaultID.LiteralAsPropertyName, autofix); } diff --git a/ets2panda/linter/src/lib/autofixes/Autofixer.ts b/ets2panda/linter/src/lib/autofixes/Autofixer.ts index a3495a0bf0..622173177c 100644 --- a/ets2panda/linter/src/lib/autofixes/Autofixer.ts +++ b/ets2panda/linter/src/lib/autofixes/Autofixer.ts @@ -871,13 +871,13 @@ export class Autofixer { return this.renameSymbolAsIdentifier(symbol); } - fixLiteralAsPropertyNamePropertyName(node: ts.PropertyName): Autofix[] | undefined { + fixLiteralAsPropertyNamePropertyName(node: ts.PropertyName, enumMember?: ts.EnumMember): Autofix[] | undefined { const symbol = this.typeChecker.getSymbolAtLocation(node); if (symbol === undefined) { return undefined; } - return this.renameSymbolAsIdentifier(symbol); + return this.renameSymbolAsIdentifier(symbol, enumMember); } fixPropertyAccessByIndex(node: ts.ElementAccessExpression): Autofix[] | undefined { @@ -889,7 +889,7 @@ export class Autofixer { return this.renameSymbolAsIdentifier(symbol); } - private renameSymbolAsIdentifier(symbol: ts.Symbol): Autofix[] | undefined { + private renameSymbolAsIdentifier(symbol: ts.Symbol, enumMember?: ts.EnumMember): Autofix[] | undefined { if (this.renameSymbolAsIdentifierCache.has(symbol)) { return this.renameSymbolAsIdentifierCache.get(symbol); } @@ -899,7 +899,7 @@ export class Autofixer { return undefined; } - const newName = this.utils.findIdentifierNameForSymbol(symbol); + const newName = this.utils.findIdentifierNameForSymbol(symbol, enumMember); if (newName === undefined) { this.renameSymbolAsIdentifierCache.set(symbol, undefined); return undefined; @@ -2742,63 +2742,6 @@ export class Autofixer { ]; } - checkEnumMemberNameConflict(tsEnumMember: ts.EnumMember, autofix: Autofix[] | undefined): void { - if (!autofix?.length) { - return; - } - - const parentEnum = tsEnumMember.parent; - if (!this.hasNameConflict(parentEnum, tsEnumMember, autofix)) { - return; - } - - const existingNames = this.collectExistingNames(parentEnum, tsEnumMember); - this.adjustAutofixNames(autofix, existingNames); - } - - hasNameConflict(parentEnum: ts.EnumDeclaration, tsEnumMember: ts.EnumMember, autofix: Autofix[]): boolean { - void this; - return parentEnum.members.some((member) => { - return ( - member !== tsEnumMember && - (ts.isStringLiteral(member.name) || member.name.getText() === autofix[0].replacementText) - ); - }); - } - - collectExistingNames(parentEnum: ts.EnumDeclaration, tsEnumMember: ts.EnumMember): Set { - void this; - return new Set( - parentEnum.members. - filter((m) => { - return m !== tsEnumMember; - }). - map((m) => { - const nameNode = m.name; - if (ts.isStringLiteral(nameNode)) { - const fix = this.fixLiteralAsPropertyNamePropertyName(nameNode); - return fix?.[0]?.replacementText || nameNode.text; - } - return nameNode.getText(); - }) - ); - } - - adjustAutofixNames(autofix: Autofix[], existingNames: Set): void { - void this; - const baseName = autofix[0].replacementText; - let newName = baseName; - let counter = 1; - - while (existingNames.has(newName)) { - newName = `${baseName}_${counter++}`; - } - - autofix.forEach((fix) => { - fix.replacementText = newName; - }); - } - fixSingleImport( interfacesNeedToImport: Set, importedInterfaces: Set, diff --git a/ets2panda/linter/src/lib/utils/TsUtils.ts b/ets2panda/linter/src/lib/utils/TsUtils.ts index cb488165e4..2dce4b6fec 100644 --- a/ets2panda/linter/src/lib/utils/TsUtils.ts +++ b/ets2panda/linter/src/lib/utils/TsUtils.ts @@ -2718,17 +2718,22 @@ export class TsUtils { return false; } - findIdentifierNameForSymbol(symbol: ts.Symbol): string | undefined { + findIdentifierNameForSymbol(symbol: ts.Symbol, enumMember?: ts.EnumMember): string | undefined { let name = TsUtils.getIdentifierNameFromString(symbol.name); if (name === undefined || name === symbol.name) { return name; } + const enumExpress = enumMember?.parent; const parentType = this.getTypeByProperty(symbol); if (parentType === undefined) { return undefined; } - + if (enumExpress) { + while (this.findEnumMember(enumExpress, name)) { + name = '_' + name; + } + } while (this.findProperty(parentType, name) !== undefined) { name = '_' + name; } @@ -3406,4 +3411,26 @@ export class TsUtils { } return false; } + + findEnumMember(enumDecl: ts.EnumDeclaration | undefined, name: string): ts.Symbol | undefined { + if (!enumDecl) { + return undefined; + } + + const syms: ts.Symbol[] = []; + for (const enumMember of enumDecl.members) { + const sym = this.trueSymbolAtLocation(enumMember.name); + if (sym) { + syms.push(sym); + } + } + + for (const sym of syms) { + if (sym.name === name) { + return sym; + } + } + + return undefined; + } } diff --git a/ets2panda/linter/test/main/interface_literal_prop_name.ets.json b/ets2panda/linter/test/main/interface_literal_prop_name.ets.json index 9df6f8b541..6f68e19f77 100644 --- a/ets2panda/linter/test/main/interface_literal_prop_name.ets.json +++ b/ets2panda/linter/test/main/interface_literal_prop_name.ets.json @@ -14,16 +14,6 @@ "limitations under the License." ], "result": [ - { - "line": 23, - "column": 3, - "endLine": 23, - "endColumn": 4, - "problem": "LiteralAsPropertyName", - "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", - "severity": "ERROR" - }, { "line": 23, "column": 3, @@ -64,16 +54,6 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, - { - "line": 43, - "column": 10, - "endLine": 43, - "endColumn": 11, - "problem": "LiteralAsPropertyName", - "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", - "severity": "ERROR" - }, { "line": 50, "column": 3, diff --git a/ets2panda/linter/test/main/literals_as_prop_names.ets b/ets2panda/linter/test/main/literals_as_prop_names.ets index 53d450b13a..3c736bdefb 100755 --- a/ets2panda/linter/test/main/literals_as_prop_names.ets +++ b/ets2panda/linter/test/main/literals_as_prop_names.ets @@ -97,3 +97,25 @@ const enum Direction16 { "\\" = 1, "__x5c" = 1, } + +const enum Direction17 { + "\\" = 1, + "__x5c" = 1, +} +let case17 = Direction17["\\"] +let case172 = Direction17["__x5c"] + +const enum Direction11 { +"!!" = 1, +} +const enum Direction23 { +"aaa" = 1, +} +// ArkUI +@Component +struct Index { +@State message: string = 'Hello World'; +private case11 = Direction11["!!"] +build() { +} +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/literals_as_prop_names.ets.args.json b/ets2panda/linter/test/main/literals_as_prop_names.ets.args.json index 52b03ab984..4e9dc628f7 100644 --- a/ets2panda/linter/test/main/literals_as_prop_names.ets.args.json +++ b/ets2panda/linter/test/main/literals_as_prop_names.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", diff --git a/ets2panda/linter/test/main/literals_as_prop_names.ets.arkts2.json b/ets2panda/linter/test/main/literals_as_prop_names.ets.arkts2.json index 8520a5f1b6..bc8e2bf232 100755 --- a/ets2panda/linter/test/main/literals_as_prop_names.ets.arkts2.json +++ b/ets2panda/linter/test/main/literals_as_prop_names.ets.arkts2.json @@ -34,26 +34,6 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, - { - "line": 26, - "column": 11, - "endLine": 26, - "endColumn": 12, - "problem": "LiteralAsPropertyName", - "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", - "severity": "ERROR" - }, - { - "line": 27, - "column": 3, - "endLine": 27, - "endColumn": 8, - "problem": "LiteralAsPropertyName", - "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", - "severity": "ERROR" - }, { "line": 27, "column": 3, @@ -204,26 +184,6 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, - { - "line": 75, - "column": 3, - "endLine": 75, - "endColumn": 4, - "problem": "LiteralAsPropertyName", - "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", - "severity": "ERROR" - }, - { - "line": 76, - "column": 3, - "endLine": 76, - "endColumn": 8, - "problem": "LiteralAsPropertyName", - "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", - "severity": "ERROR" - }, { "line": 76, "column": 3, @@ -324,6 +284,86 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, + { + "line": 102, + "column": 3, + "endLine": 102, + "endColumn": 11, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 103, + "column": 3, + "endLine": 103, + "endColumn": 14, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 105, + "column": 5, + "endLine": 105, + "endColumn": 31, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 106, + "column": 5, + "endLine": 106, + "endColumn": 35, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 109, + "column": 1, + "endLine": 109, + "endColumn": 9, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 112, + "column": 1, + "endLine": 112, + "endColumn": 10, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 115, + "column": 2, + "endLine": 115, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 117, + "column": 2, + "endLine": 117, + "endColumn": 7, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, { "line": 42, "column": 11, diff --git a/ets2panda/linter/test/main/literals_as_prop_names.ets.autofix.json b/ets2panda/linter/test/main/literals_as_prop_names.ets.autofix.json index 0eabd752ac..3706ab2eee 100644 --- a/ets2panda/linter/test/main/literals_as_prop_names.ets.autofix.json +++ b/ets2panda/linter/test/main/literals_as_prop_names.ets.autofix.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2023-2024 Huawei Device Co., Ltd.", + "Copyright (c) 2023-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -63,60 +63,6 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, - { - "line": 26, - "column": 11, - "endLine": 26, - "endColumn": 12, - "problem": "LiteralAsPropertyName", - "autofix": [ - { - "replacementText": "__2", - "start": 836, - "end": 837 - }, - { - "replacementText": "__2", - "start": 928, - "end": 929 - }, - { - "replacementText": "litAsPropName.__2", - "start": 1001, - "end": 1017 - } - ], - "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", - "severity": "ERROR" - }, - { - "line": 27, - "column": 3, - "endLine": 27, - "endColumn": 8, - "problem": "LiteralAsPropertyName", - "autofix": [ - { - "replacementText": "Two", - "start": 849, - "end": 854 - }, - { - "replacementText": "Two", - "start": 940, - "end": 945 - }, - { - "replacementText": "litAsPropName.Two", - "start": 1032, - "end": 1052 - } - ], - "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", - "severity": "ERROR" - }, { "line": 27, "column": 3, @@ -378,50 +324,6 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, - { - "line": 75, - "column": 3, - "endLine": 75, - "endColumn": 4, - "problem": "LiteralAsPropertyName", - "autofix": [ - { - "replacementText": "___2", - "start": 1726, - "end": 1727 - }, - { - "replacementText": "___2", - "start": 1808, - "end": 1809 - } - ], - "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", - "severity": "ERROR" - }, - { - "line": 76, - "column": 3, - "endLine": 76, - "endColumn": 8, - "problem": "LiteralAsPropertyName", - "autofix": [ - { - "replacementText": "__2", - "start": 1739, - "end": 1744 - }, - { - "replacementText": "__2", - "start": 1824, - "end": 1829 - } - ], - "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", - "severity": "ERROR" - }, { "line": 76, "column": 3, @@ -541,7 +443,7 @@ "problem": "LiteralAsPropertyName", "autofix": [ { - "replacementText": "__x5c_1", + "replacementText": "___x5c", "start": 2033, "end": 2037 } @@ -567,6 +469,150 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, + { + "line": 102, + "column": 3, + "endLine": 102, + "endColumn": 11, + "problem": "LiteralAsPropertyName", + "autofix": [ + { + "replacementText": "___x5c", + "start": 2088, + "end": 2092 + }, + { + "replacementText": "Direction17.___x5c", + "start": 2128, + "end": 2145 + } + ], + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 103, + "column": 3, + "endLine": 103, + "endColumn": 14, + "problem": "LiteralAsPropertyName", + "autofix": [ + { + "replacementText": "__x5c", + "start": 2100, + "end": 2107 + }, + { + "replacementText": "Direction17.__x5c", + "start": 2160, + "end": 2180 + } + ], + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 105, + "column": 5, + "endLine": 105, + "endColumn": 31, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2119, + "end": 2145, + "replacementText": "case17: number = Direction17[\"\\\\\"]" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 106, + "column": 5, + "endLine": 106, + "endColumn": 35, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2150, + "end": 2180, + "replacementText": "case172: number = Direction17[\"__x5c\"]" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 109, + "column": 1, + "endLine": 109, + "endColumn": 9, + "problem": "LiteralAsPropertyName", + "autofix": [ + { + "replacementText": "__x21x21", + "start": 2207, + "end": 2211 + }, + { + "replacementText": "Direction11.__x21x21", + "start": 2349, + "end": 2366 + } + ], + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 112, + "column": 1, + "endLine": 112, + "endColumn": 10, + "problem": "LiteralAsPropertyName", + "autofix": [ + { + "replacementText": "aaa", + "start": 2244, + "end": 2249 + } + ], + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 115, + "column": 2, + "endLine": 115, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 117, + "column": 2, + "endLine": 117, + "endColumn": 7, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 608, + "end": 608, + "replacementText": "\n\nimport { Component, State } from '@kits.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, { "line": 42, "column": 11, diff --git a/ets2panda/linter/test/main/literals_as_prop_names.ets.json b/ets2panda/linter/test/main/literals_as_prop_names.ets.json index bf6df5f5a3..7e721f74f1 100644 --- a/ets2panda/linter/test/main/literals_as_prop_names.ets.json +++ b/ets2panda/linter/test/main/literals_as_prop_names.ets.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2023-2024 Huawei Device Co., Ltd.", + "Copyright (c) 2023-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,16 +14,6 @@ "limitations under the License." ], "result": [ - { - "line": 26, - "column": 11, - "endLine": 26, - "endColumn": 12, - "problem": "LiteralAsPropertyName", - "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", - "severity": "ERROR" - }, { "line": 26, "column": 11, @@ -134,16 +124,6 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, - { - "line": 75, - "column": 3, - "endLine": 75, - "endColumn": 4, - "problem": "LiteralAsPropertyName", - "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", - "severity": "ERROR" - }, { "line": 80, "column": 3, diff --git a/ets2panda/linter/test/main/type_literals.ets.autofix.json b/ets2panda/linter/test/main/type_literals.ets.autofix.json index 8d8dc62efe..16726b33b2 100644 --- a/ets2panda/linter/test/main/type_literals.ets.autofix.json +++ b/ets2panda/linter/test/main/type_literals.ets.autofix.json @@ -700,16 +700,6 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, - { - "line": 85, - "column": 3, - "endLine": 85, - "endColumn": 4, - "problem": "LiteralAsPropertyName", - "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", - "severity": "ERROR" - }, { "line": 93, "column": 3, @@ -782,16 +772,6 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, - { - "line": 101, - "column": 3, - "endLine": 101, - "endColumn": 4, - "problem": "LiteralAsPropertyName", - "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", - "severity": "ERROR" - }, { "line": 109, "column": 3, diff --git a/ets2panda/linter/test/main/type_literals.ets.json b/ets2panda/linter/test/main/type_literals.ets.json index 45014a1517..fe85abf706 100644 --- a/ets2panda/linter/test/main/type_literals.ets.json +++ b/ets2panda/linter/test/main/type_literals.ets.json @@ -394,16 +394,6 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, - { - "line": 85, - "column": 3, - "endLine": 85, - "endColumn": 4, - "problem": "LiteralAsPropertyName", - "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", - "severity": "ERROR" - }, { "line": 93, "column": 3, @@ -464,16 +454,6 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, - { - "line": 101, - "column": 3, - "endLine": 101, - "endColumn": 4, - "problem": "LiteralAsPropertyName", - "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", - "severity": "ERROR" - }, { "line": 109, "column": 3, diff --git a/ets2panda/linter/test/main/types.ets.autofix.json b/ets2panda/linter/test/main/types.ets.autofix.json index f0175f233b..7eb21c4bca 100644 --- a/ets2panda/linter/test/main/types.ets.autofix.json +++ b/ets2panda/linter/test/main/types.ets.autofix.json @@ -177,16 +177,6 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, - { - "line": 56, - "column": 3, - "endLine": 56, - "endColumn": 4, - "problem": "LiteralAsPropertyName", - "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", - "severity": "ERROR" - }, { "line": 57, "column": 3, @@ -229,28 +219,6 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, - { - "line": 62, - "column": 3, - "endLine": 62, - "endColumn": 4, - "problem": "LiteralAsPropertyName", - "autofix": [ - { - "replacementText": "__2", - "start": 1604, - "end": 1605 - }, - { - "replacementText": "__2", - "start": 1684, - "end": 1685 - } - ], - "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", - "severity": "ERROR" - }, { "line": 67, "column": 3, diff --git a/ets2panda/linter/test/main/types.ets.json b/ets2panda/linter/test/main/types.ets.json index 0e14ef4cbd..9daadb68bf 100644 --- a/ets2panda/linter/test/main/types.ets.json +++ b/ets2panda/linter/test/main/types.ets.json @@ -144,16 +144,6 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, - { - "line": 56, - "column": 3, - "endLine": 56, - "endColumn": 4, - "problem": "LiteralAsPropertyName", - "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", - "severity": "ERROR" - }, { "line": 57, "column": 3, @@ -184,16 +174,6 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, - { - "line": 62, - "column": 3, - "endLine": 62, - "endColumn": 4, - "problem": "LiteralAsPropertyName", - "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", - "severity": "ERROR" - }, { "line": 67, "column": 3, -- Gitee From 77d3906998d31af709548cff7b450c63cd5663a4 Mon Sep 17 00:00:00 2001 From: Utku Enes GURSEL Date: Sat, 12 Apr 2025 16:51:28 +0300 Subject: [PATCH 055/268] extend checking Sendable and Concurrent decorator Issue: IBYPEQ Description: Instead of checking specific use cases for Sendable and Concurrent decorators, now extended the check we raising problems for every usage of these after mentioned Decorators and deleting them with autofix functionality. Signed-off-by: Utku Enes GURSEL --- ets2panda/linter/src/lib/TypeScriptLinter.ts | 33 ++++--------------- .../linter/src/lib/autofixes/Autofixer.ts | 4 +-- 2 files changed, 9 insertions(+), 28 deletions(-) diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index 863f533f08..233a77b40d 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -2633,8 +2633,7 @@ export class TypeScriptLinter { } if ( - (tsIdentSym.flags & illegalValues) === 0 && - !(this.options.arkts2 && this.isStdlibClassVarDecl(tsIdentifier, tsIdentSym)) || + (tsIdentSym.flags & illegalValues) === 0 && !this.isStdlibClassVarDecl(tsIdentifier, tsIdentSym) || isStruct(tsIdentSym) || !identiferUseInValueContext(tsIdentifier, tsIdentSym) ) { @@ -4101,14 +4100,13 @@ export class TypeScriptLinter { this.handleProvideDecorator(node); const decorator: ts.Decorator = node as ts.Decorator; - this.handleSendableDecorator(decorator); - this.handleConcurrentDecorator(decorator); + this.checkSendableAndConcurrentDecorator(decorator); this.handleStylesDecorator(decorator); this.handleTypescriptDecorators(decorator); if (TsUtils.getDecoratorName(decorator) === SENDABLE_DECORATOR) { const parent: ts.Node = decorator.parent; if (!parent || !SENDABLE_DECORATOR_NODES.includes(parent.kind)) { - const autofix = this.autofixer?.removeDecorator(decorator); + const autofix = this.autofixer?.removeNode(decorator); this.incrementCounters(decorator, FaultID.SendableDecoratorLimited, autofix); } } @@ -4850,30 +4848,13 @@ export class TypeScriptLinter { return !!symbol && (symbol.flags & ts.SymbolFlags.Variable) !== 0; } - private handleSendableDecorator(decorator: ts.Decorator): void { + private checkSendableAndConcurrentDecorator(decorator: ts.Decorator): void { if (!this.options.arkts2) { return; } - if (TsUtils.getDecoratorName(decorator) === SENDABLE_DECORATOR) { - const parent: ts.Node = decorator.parent; - if (parent && parent.kind !== ts.SyntaxKind.ClassDeclaration) { - return; - } - const autofix = this.autofixer?.removeDecorator(decorator); - this.incrementCounters(decorator, FaultID.LimitedStdLibApi, autofix); - } - } - - private handleConcurrentDecorator(decorator: ts.Decorator): void { - if (!this.options.arkts2) { - return; - } - if (TsUtils.getDecoratorName(decorator) === CONCURRENT_DECORATOR) { - const parent: ts.Node = decorator.parent; - if (parent && parent.kind !== ts.SyntaxKind.FunctionDeclaration) { - return; - } - const autofix = this.autofixer?.removeDecorator(decorator); + const decoratorName = TsUtils.getDecoratorName(decorator); + if (decoratorName === SENDABLE_DECORATOR || decoratorName === CONCURRENT_DECORATOR) { + const autofix = this.autofixer?.removeNode(decorator); this.incrementCounters(decorator, FaultID.LimitedStdLibApi, autofix); } } diff --git a/ets2panda/linter/src/lib/autofixes/Autofixer.ts b/ets2panda/linter/src/lib/autofixes/Autofixer.ts index 622173177c..60bed5f883 100644 --- a/ets2panda/linter/src/lib/autofixes/Autofixer.ts +++ b/ets2panda/linter/src/lib/autofixes/Autofixer.ts @@ -2004,9 +2004,9 @@ export class Autofixer { return found; } - removeDecorator(decorator: ts.Decorator): Autofix[] { + removeNode(node: ts.Node): Autofix[] { void this; - return [{ start: decorator.getStart(), end: decorator.getEnd(), replacementText: '' }]; + return [{ start: node.getStart(), end: node.getEnd(), replacementText: '' }]; } fixSendableExplicitFieldType(node: ts.PropertyDeclaration): Autofix[] | undefined { -- Gitee From 84e5361ed449f330a92054ba225133029fad4c08 Mon Sep 17 00:00:00 2001 From: xudan16 Date: Mon, 7 Apr 2025 19:14:25 +0800 Subject: [PATCH 056/268] add homecheck and its dependency arkanalyzer Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC0J1R Signed-off-by: xudan16 Change-Id: Ifd134cf6686b32a49c7c45430da011cfd0d0ef0c --- .gitignore | 2 + codecheck_ignore.json | 2 + ets2panda/linter/arkanalyzer/.prettierrc | 10 + ets2panda/linter/arkanalyzer/LICENSE | 201 ++ ets2panda/linter/arkanalyzer/OAT.xml | 25 + .../arkanalyzer/config/arkanalyzer.json | 20 + ets2panda/linter/arkanalyzer/package.json | 33 + .../typescriptCollectionDefinitionCopy.ts | 56 + ets2panda/linter/arkanalyzer/src/Config.ts | 273 +++ ets2panda/linter/arkanalyzer/src/Scene.ts | 1438 +++++++++++++ ets2panda/linter/arkanalyzer/src/VFG/DVFG.ts | 111 + .../src/VFG/builder/DVFGBuilder.ts | 122 ++ .../callgraph/algorithm/AbstractAnalysis.ts | 161 ++ .../algorithm/ClassHierarchyAnalysis.ts | 91 + .../callgraph/algorithm/RapidTypeAnalysis.ts | 156 ++ .../src/callgraph/common/Statistics.ts | 226 +++ .../src/callgraph/model/CallGraph.ts | 462 +++++ .../model/builder/CallGraphBuilder.ts | 122 ++ .../src/callgraph/pointerAnalysis/Context.ts | 181 ++ .../pointerAnalysis/DummyCallCreator.ts | 101 + .../src/callgraph/pointerAnalysis/PTAUtils.ts | 45 + .../src/callgraph/pointerAnalysis/Pag.ts | 1032 ++++++++++ .../callgraph/pointerAnalysis/PagBuilder.ts | 1780 ++++++++++++++++ .../pointerAnalysis/PointerAnalysis.ts | 672 +++++++ .../pointerAnalysis/PointerAnalysisConfig.ts | 84 + .../src/callgraph/pointerAnalysis/PtsDS.ts | 363 ++++ .../arkanalyzer/src/core/base/Constant.ts | 120 ++ .../arkanalyzer/src/core/base/Decorator.ts | 44 + .../arkanalyzer/src/core/base/DefUseChain.ts | 28 + .../linter/arkanalyzer/src/core/base/Expr.ts | 1140 +++++++++++ .../linter/arkanalyzer/src/core/base/Local.ts | 208 ++ .../arkanalyzer/src/core/base/Position.ts | 150 ++ .../linter/arkanalyzer/src/core/base/Ref.ts | 411 ++++ .../linter/arkanalyzer/src/core/base/Stmt.ts | 603 ++++++ .../linter/arkanalyzer/src/core/base/Trap.ts | 34 + .../linter/arkanalyzer/src/core/base/Type.ts | 794 ++++++++ .../arkanalyzer/src/core/base/TypeExpr.ts | 178 ++ .../linter/arkanalyzer/src/core/base/Value.ts | 49 + .../arkanalyzer/src/core/common/ArkError.ts | 30 + .../src/core/common/ArkIRTransformer.ts | 869 ++++++++ .../src/core/common/ArkValueTransformer.ts | 1789 +++++++++++++++++ .../arkanalyzer/src/core/common/Builtin.ts | 93 + .../arkanalyzer/src/core/common/Const.ts | 48 + .../src/core/common/DummyMainCreater.ts | 342 ++++ .../arkanalyzer/src/core/common/EtsConst.ts | 1030 ++++++++++ .../src/core/common/ExprUseReplacer.ts | 142 ++ .../src/core/common/IRInference.ts | 809 ++++++++ .../arkanalyzer/src/core/common/IRUtils.ts | 162 ++ .../arkanalyzer/src/core/common/ModelUtils.ts | 756 +++++++ .../src/core/common/RefUseReplacer.ts | 55 + .../arkanalyzer/src/core/common/SdkUtils.ts | 127 ++ .../src/core/common/StmtDefReplacer.ts | 46 + .../src/core/common/StmtUseReplacer.ts | 111 + .../arkanalyzer/src/core/common/TSConst.ts | 42 + .../src/core/common/TypeInference.ts | 854 ++++++++ .../arkanalyzer/src/core/common/ValueUtil.ts | 71 + .../src/core/common/VisibleValue.ts | 208 ++ .../src/core/dataflow/DataflowProblem.ts | 55 + .../src/core/dataflow/DataflowResult.ts | 25 + .../src/core/dataflow/DataflowSolver.ts | 353 ++++ .../arkanalyzer/src/core/dataflow/Edge.ts | 36 + .../arkanalyzer/src/core/dataflow/Fact.ts | 22 + .../src/core/dataflow/GenericDataFlow.ts | 232 +++ .../src/core/dataflow/ReachingDef.ts | 205 ++ .../src/core/dataflow/UndefinedVariable.ts | 263 +++ .../arkanalyzer/src/core/dataflow/Util.ts | 66 + .../src/core/graph/BaseExplicitGraph.ts | 205 ++ .../src/core/graph/BaseImplicitGraph.ts | 140 ++ .../arkanalyzer/src/core/graph/BasicBlock.ts | 286 +++ .../linter/arkanalyzer/src/core/graph/Cfg.ts | 291 +++ .../src/core/graph/DependsGraph.ts | 119 ++ .../src/core/graph/DominanceFinder.ts | 130 ++ .../src/core/graph/DominanceTree.ts | 75 + .../arkanalyzer/src/core/graph/GraphTraits.ts | 23 + .../linter/arkanalyzer/src/core/graph/Scc.ts | 278 +++ .../arkanalyzer/src/core/graph/ViewTree.ts | 140 ++ .../src/core/graph/builder/CfgBuilder.ts | 1260 ++++++++++++ .../core/graph/builder/ConditionBuilder.ts | 314 +++ .../src/core/graph/builder/LoopBuilder.ts | 342 ++++ .../src/core/graph/builder/SwitchBuilder.ts | 148 ++ .../src/core/graph/builder/TrapBuilder.ts | 281 +++ .../src/core/graph/builder/ViewTreeBuilder.ts | 1285 ++++++++++++ .../src/core/model/ArkBaseModel.ts | 283 +++ .../arkanalyzer/src/core/model/ArkBody.ts | 85 + .../arkanalyzer/src/core/model/ArkClass.ts | 535 +++++ .../arkanalyzer/src/core/model/ArkExport.ts | 208 ++ .../arkanalyzer/src/core/model/ArkField.ts | 163 ++ .../arkanalyzer/src/core/model/ArkFile.ts | 341 ++++ .../arkanalyzer/src/core/model/ArkImport.ts | 141 ++ .../arkanalyzer/src/core/model/ArkMetadata.ts | 66 + .../arkanalyzer/src/core/model/ArkMethod.ts | 694 +++++++ .../src/core/model/ArkNamespace.ts | 273 +++ .../src/core/model/ArkSignature.ts | 498 +++++ .../src/core/model/builder/ArkClassBuilder.ts | 522 +++++ .../core/model/builder/ArkExportBuilder.ts | 212 ++ .../src/core/model/builder/ArkFieldBuilder.ts | 175 ++ .../src/core/model/builder/ArkFileBuilder.ts | 173 ++ .../core/model/builder/ArkImportBuilder.ts | 133 ++ .../core/model/builder/ArkMethodBuilder.ts | 516 +++++ .../core/model/builder/ArkNamespaceBuilder.ts | 196 ++ .../core/model/builder/ArkSignatureBuilder.ts | 44 + .../src/core/model/builder/BodyBuilder.ts | 601 ++++++ .../src/core/model/builder/builderUtils.ts | 579 ++++++ ets2panda/linter/arkanalyzer/src/index.ts | 127 ++ .../linter/arkanalyzer/src/save/ArkStream.ts | 97 + .../linter/arkanalyzer/src/save/DotPrinter.ts | 205 ++ .../arkanalyzer/src/save/GraphPrinter.ts | 153 ++ .../arkanalyzer/src/save/JsonPrinter.ts | 620 ++++++ .../linter/arkanalyzer/src/save/Printer.ts | 32 + .../arkanalyzer/src/save/PrinterBuilder.ts | 172 ++ .../arkanalyzer/src/save/ViewTreePrinter.ts | 166 ++ .../src/save/arkir/ArkIRClassPrinter.ts | 112 ++ .../src/save/arkir/ArkIRFieldPrinter.ts | 68 + .../src/save/arkir/ArkIRFilePrinter.ts | 61 + .../src/save/arkir/ArkIRMethodPrinter.ts | 175 ++ .../src/save/arkir/ArkIRNamespacePrinter.ts | 76 + .../arkanalyzer/src/save/base/BasePrinter.ts | 88 + .../src/save/base/ExportPrinter.ts | 71 + .../src/save/base/ImportPrinter.ts | 98 + .../arkanalyzer/src/save/base/PrinterUtils.ts | 232 +++ .../arkanalyzer/src/save/serializeArkIR.ts | 316 +++ .../arkanalyzer/src/save/source/SourceBase.ts | 85 + .../arkanalyzer/src/save/source/SourceBody.ts | 331 +++ .../src/save/source/SourceClass.ts | 214 ++ .../src/save/source/SourceField.ts | 80 + .../src/save/source/SourceFilePrinter.ts | 100 + .../src/save/source/SourceMethod.ts | 227 +++ .../src/save/source/SourceNamespace.ts | 94 + .../arkanalyzer/src/save/source/SourceStmt.ts | 974 +++++++++ .../src/save/source/SourceTransformer.ts | 563 ++++++ .../src/transformer/FunctionTransformer.ts | 19 + .../src/transformer/SceneTransformer.ts | 19 + .../StaticSingleAssignmentFormer.ts | 311 +++ .../src/transformer/Transformer.ts | 24 + .../arkanalyzer/src/utils/AstTreeUtils.ts | 31 + .../src/utils/CfgStructualAnalysis.ts | 1497 ++++++++++++++ .../linter/arkanalyzer/src/utils/FileUtils.ts | 135 ++ .../arkanalyzer/src/utils/SparseBitVector.ts | 544 +++++ .../arkanalyzer/src/utils/callGraphUtils.ts | 224 +++ .../arkanalyzer/src/utils/crypto_utils.ts | 35 + .../arkanalyzer/src/utils/entryMethodUtils.ts | 123 ++ .../arkanalyzer/src/utils/getAllFiles.ts | 71 + .../arkanalyzer/src/utils/json5parser.ts | 121 ++ .../linter/arkanalyzer/src/utils/logger.ts | 99 + .../arkanalyzer/src/utils/pathTransfer.ts | 28 + ets2panda/linter/arkanalyzer/tsconfig.json | 12 + .../linter/arkanalyzer/tsconfig.main.json | 101 + .../linter/arkanalyzer/tsconfig.prod.json | 9 + ets2panda/linter/arkanalyzer/typedoc.json | 21 + ets2panda/linter/arkanalyzer/vitest.config.ts | 25 + ets2panda/linter/build_linter.py | 66 +- ets2panda/linter/eslint.config.mjs | 4 +- ets2panda/linter/homecheck/LICENSE | 201 ++ ets2panda/linter/homecheck/OAT.xml | 25 + .../homecheck/config/projectConfig.json | 23 + .../linter/homecheck/config/ruleConfig.json | 21 + ets2panda/linter/homecheck/package.json | 32 + .../resources/internalSdk/@internal/es5.d.ts | 56 + .../linter/homecheck/resources/sdkConfig.json | 24 + .../@hview/moment/index.d.ts | 25 + .../@ohos/gif-drawable/index.ets | 16 + .../components/gif/display/GIFComponent.ets | 26 + .../components/gif/display/GIFComponentV2.ets | 26 + .../thirdPartyModules/@ohos/lottie/index.d.ts | 17 + ets2panda/linter/homecheck/ruleSet.json | 207 ++ .../homecheck/scripts/install_arkanalyzer.sh | 33 + .../linter/homecheck/scripts/run_ci_ut.sh | 71 + ets2panda/linter/homecheck/src/Index.ts | 45 + ets2panda/linter/homecheck/src/Main.ts | 61 + .../homecheck/src/checker/BaseChecker.ts | 37 + .../checker/migration/AppStorageGetCheck.ts | 146 ++ .../checker/migration/CustomBuilderCheck.ts | 136 ++ .../checker/migration/ModifyStateVarCheck.ts | 121 ++ .../migration/NoMethodOverridingFieldCheck.ts | 62 + .../migration/NoOptionalMethodCheck.ts | 73 + .../checker/migration/ObjectLiteralCheck.ts | 185 ++ .../migration/ObservedDecoratorCheck.ts | 155 ++ .../src/checker/migration/ThisBindCheck.ts | 159 ++ .../linter/homecheck/src/codeFix/FixEngine.ts | 33 + .../src/codeFix/engines/AIFixEngine.ts | 28 + .../src/codeFix/engines/EsLintFixEngine.ts | 145 ++ .../src/codeFix/engines/HomeCheckFixEngine.ts | 80 + .../linter/homecheck/src/matcher/Matchers.ts | 227 +++ .../src/matcher/matcherAdapter/matchClass.ts | 40 + .../src/matcher/matcherAdapter/matchFields.ts | 46 + .../src/matcher/matcherAdapter/matchFiles.ts | 25 + .../matcher/matcherAdapter/matchMethods.ts | 46 + .../matcher/matcherAdapter/matchNameSpaces.ts | 30 + .../linter/homecheck/src/model/Defects.ts | 72 + .../linter/homecheck/src/model/Engine.ts | 28 + .../linter/homecheck/src/model/File2Check.ts | 117 ++ ets2panda/linter/homecheck/src/model/Fix.ts | 55 + .../linter/homecheck/src/model/Interfaces.ts | 35 + .../linter/homecheck/src/model/Message.ts | 77 + .../linter/homecheck/src/model/NumberValue.ts | 29 + .../homecheck/src/model/Project2Check.ts | 179 ++ .../homecheck/src/model/ProjectConfig.ts | 72 + ets2panda/linter/homecheck/src/model/Rule.ts | 42 + .../linter/homecheck/src/model/RuleConfig.ts | 56 + ets2panda/linter/homecheck/src/model/Scope.ts | 61 + .../homecheck/src/model/SparseArrayValue.ts | 44 + .../linter/homecheck/src/model/StmtExt.ts | 23 + .../linter/homecheck/src/model/VarInfo.ts | 26 + .../linter/homecheck/src/model/Variable.ts | 32 + ets2panda/linter/homecheck/src/run.ts | 18 + ets2panda/linter/homecheck/src/runTool.ts | 35 + .../homecheck/src/tools/BuildModuleChains.ts | 585 ++++++ .../homecheck/src/tools/depGraph/builder.ts | 82 + .../src/tools/depGraph/fileComponent.ts | 95 + .../homecheck/src/tools/depGraph/fileDeps.ts | 87 + .../src/tools/depGraph/moduleComponent.ts | 83 + .../src/tools/depGraph/moduleDeps.ts | 106 + .../homecheck/src/tools/depGraph/utils.ts | 54 + .../src/tools/migrationTool/ExportIssue.ts | 62 + .../src/tools/migrationTool/MigrationTool.ts | 72 + .../linter/homecheck/src/tools/toolEntry.ts | 136 ++ .../linter/homecheck/src/tools/toolRun.ts | 22 + .../src/utils/checker/AbilityInterface.ts | 86 + .../homecheck/src/utils/checker/BytesUtils.ts | 104 + .../src/utils/checker/CheckerUtils.ts | 178 ++ .../homecheck/src/utils/checker/ImageUtils.ts | 99 + .../src/utils/checker/NumberUtils.ts | 343 ++++ .../src/utils/checker/StringUtils.ts | 178 ++ .../homecheck/src/utils/checker/TypeUtils.ts | 193 ++ .../src/utils/checker/ViewTreeTool.ts | 40 + .../src/utils/checker/imageFormat/bmp.ts | 25 + .../src/utils/checker/imageFormat/jpg.ts | 115 ++ .../src/utils/checker/imageFormat/png.ts | 50 + .../src/utils/checker/imageFormat/svg.ts | 100 + .../src/utils/checker/imageFormat/webp.ts | 68 + .../homecheck/src/utils/common/AfterCheck.ts | 34 + .../src/utils/common/CheckBuilder.ts | 51 + .../homecheck/src/utils/common/CheckEntry.ts | 281 +++ .../src/utils/common/CheckerFactory.ts | 28 + .../src/utils/common/CheckerIndex.ts | 54 + .../src/utils/common/CheckerStorage.ts | 83 + .../homecheck/src/utils/common/ConfigUtils.ts | 275 +++ .../homecheck/src/utils/common/DefectsList.ts | 54 + .../homecheck/src/utils/common/Disable.ts | 47 + .../src/utils/common/FileRuleMapping.ts | 153 ++ .../homecheck/src/utils/common/FileUtils.ts | 289 +++ .../homecheck/src/utils/common/FixUtils.ts | 84 + .../src/utils/common/GeneratingJsonFile.ts | 151 ++ .../homecheck/src/utils/common/GlobMatch.ts | 56 + .../homecheck/src/utils/common/Json5parser.ts | 130 ++ .../homecheck/src/utils/common/ScopeHelper.ts | 273 +++ .../homecheck/src/utils/common/Utils.ts | 80 + ets2panda/linter/homecheck/tsconfig.json | 10 + ets2panda/linter/homecheck/tsconfig.main.json | 19 + ets2panda/linter/homecheck/tsconfig.prod.json | 9 + ets2panda/linter/homecheck/typedoc.json | 9 + ets2panda/linter/homecheck/vitest.config.ts | 26 + ets2panda/linter/package.json | 6 +- ...install-ohos-typescript-and-homecheck.mjs} | 58 +- ets2panda/linter/src/cli/CommandLineParser.ts | 4 + ets2panda/linter/src/cli/LinterCLI.ts | 29 +- .../linter/src/lib/CommandLineOptions.ts | 1 + ets2panda/linter/src/lib/HomeCheck.ts | 57 + ets2panda/linter/tsconfig.json | 4 +- 259 files changed, 50172 insertions(+), 10 deletions(-) create mode 100644 ets2panda/linter/arkanalyzer/.prettierrc create mode 100644 ets2panda/linter/arkanalyzer/LICENSE create mode 100644 ets2panda/linter/arkanalyzer/OAT.xml create mode 100644 ets2panda/linter/arkanalyzer/config/arkanalyzer.json create mode 100644 ets2panda/linter/arkanalyzer/package.json create mode 100644 ets2panda/linter/arkanalyzer/script/typescriptCollectionDefinitionCopy.ts create mode 100644 ets2panda/linter/arkanalyzer/src/Config.ts create mode 100644 ets2panda/linter/arkanalyzer/src/Scene.ts create mode 100644 ets2panda/linter/arkanalyzer/src/VFG/DVFG.ts create mode 100644 ets2panda/linter/arkanalyzer/src/VFG/builder/DVFGBuilder.ts create mode 100644 ets2panda/linter/arkanalyzer/src/callgraph/algorithm/AbstractAnalysis.ts create mode 100644 ets2panda/linter/arkanalyzer/src/callgraph/algorithm/ClassHierarchyAnalysis.ts create mode 100644 ets2panda/linter/arkanalyzer/src/callgraph/algorithm/RapidTypeAnalysis.ts create mode 100644 ets2panda/linter/arkanalyzer/src/callgraph/common/Statistics.ts create mode 100644 ets2panda/linter/arkanalyzer/src/callgraph/model/CallGraph.ts create mode 100644 ets2panda/linter/arkanalyzer/src/callgraph/model/builder/CallGraphBuilder.ts create mode 100644 ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/Context.ts create mode 100644 ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/DummyCallCreator.ts create mode 100644 ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PTAUtils.ts create mode 100644 ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/Pag.ts create mode 100644 ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PagBuilder.ts create mode 100644 ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PointerAnalysis.ts create mode 100644 ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PointerAnalysisConfig.ts create mode 100644 ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PtsDS.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/base/Constant.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/base/Decorator.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/base/DefUseChain.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/base/Expr.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/base/Local.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/base/Position.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/base/Ref.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/base/Stmt.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/base/Trap.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/base/Type.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/base/TypeExpr.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/base/Value.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/common/ArkError.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/common/ArkIRTransformer.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/common/ArkValueTransformer.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/common/Builtin.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/common/Const.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/common/DummyMainCreater.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/common/EtsConst.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/common/ExprUseReplacer.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/common/IRInference.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/common/IRUtils.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/common/ModelUtils.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/common/RefUseReplacer.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/common/SdkUtils.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/common/StmtDefReplacer.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/common/StmtUseReplacer.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/common/TSConst.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/common/TypeInference.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/common/ValueUtil.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/common/VisibleValue.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/dataflow/DataflowProblem.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/dataflow/DataflowResult.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/dataflow/DataflowSolver.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/dataflow/Edge.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/dataflow/Fact.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/dataflow/GenericDataFlow.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/dataflow/ReachingDef.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/dataflow/UndefinedVariable.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/dataflow/Util.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/graph/BaseExplicitGraph.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/graph/BaseImplicitGraph.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/graph/BasicBlock.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/graph/Cfg.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/graph/DependsGraph.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/graph/DominanceFinder.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/graph/DominanceTree.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/graph/GraphTraits.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/graph/Scc.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/graph/ViewTree.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/graph/builder/CfgBuilder.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/graph/builder/ConditionBuilder.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/graph/builder/LoopBuilder.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/graph/builder/SwitchBuilder.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/graph/builder/TrapBuilder.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/graph/builder/ViewTreeBuilder.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/model/ArkBaseModel.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/model/ArkBody.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/model/ArkClass.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/model/ArkExport.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/model/ArkField.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/model/ArkFile.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/model/ArkImport.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/model/ArkMetadata.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/model/ArkMethod.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/model/ArkNamespace.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/model/ArkSignature.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/model/builder/ArkClassBuilder.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/model/builder/ArkExportBuilder.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/model/builder/ArkFieldBuilder.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/model/builder/ArkFileBuilder.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/model/builder/ArkImportBuilder.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/model/builder/ArkMethodBuilder.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/model/builder/ArkNamespaceBuilder.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/model/builder/ArkSignatureBuilder.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/model/builder/BodyBuilder.ts create mode 100644 ets2panda/linter/arkanalyzer/src/core/model/builder/builderUtils.ts create mode 100644 ets2panda/linter/arkanalyzer/src/index.ts create mode 100644 ets2panda/linter/arkanalyzer/src/save/ArkStream.ts create mode 100644 ets2panda/linter/arkanalyzer/src/save/DotPrinter.ts create mode 100644 ets2panda/linter/arkanalyzer/src/save/GraphPrinter.ts create mode 100644 ets2panda/linter/arkanalyzer/src/save/JsonPrinter.ts create mode 100644 ets2panda/linter/arkanalyzer/src/save/Printer.ts create mode 100644 ets2panda/linter/arkanalyzer/src/save/PrinterBuilder.ts create mode 100644 ets2panda/linter/arkanalyzer/src/save/ViewTreePrinter.ts create mode 100644 ets2panda/linter/arkanalyzer/src/save/arkir/ArkIRClassPrinter.ts create mode 100644 ets2panda/linter/arkanalyzer/src/save/arkir/ArkIRFieldPrinter.ts create mode 100644 ets2panda/linter/arkanalyzer/src/save/arkir/ArkIRFilePrinter.ts create mode 100644 ets2panda/linter/arkanalyzer/src/save/arkir/ArkIRMethodPrinter.ts create mode 100644 ets2panda/linter/arkanalyzer/src/save/arkir/ArkIRNamespacePrinter.ts create mode 100644 ets2panda/linter/arkanalyzer/src/save/base/BasePrinter.ts create mode 100644 ets2panda/linter/arkanalyzer/src/save/base/ExportPrinter.ts create mode 100644 ets2panda/linter/arkanalyzer/src/save/base/ImportPrinter.ts create mode 100644 ets2panda/linter/arkanalyzer/src/save/base/PrinterUtils.ts create mode 100644 ets2panda/linter/arkanalyzer/src/save/serializeArkIR.ts create mode 100644 ets2panda/linter/arkanalyzer/src/save/source/SourceBase.ts create mode 100644 ets2panda/linter/arkanalyzer/src/save/source/SourceBody.ts create mode 100644 ets2panda/linter/arkanalyzer/src/save/source/SourceClass.ts create mode 100644 ets2panda/linter/arkanalyzer/src/save/source/SourceField.ts create mode 100644 ets2panda/linter/arkanalyzer/src/save/source/SourceFilePrinter.ts create mode 100644 ets2panda/linter/arkanalyzer/src/save/source/SourceMethod.ts create mode 100644 ets2panda/linter/arkanalyzer/src/save/source/SourceNamespace.ts create mode 100644 ets2panda/linter/arkanalyzer/src/save/source/SourceStmt.ts create mode 100644 ets2panda/linter/arkanalyzer/src/save/source/SourceTransformer.ts create mode 100644 ets2panda/linter/arkanalyzer/src/transformer/FunctionTransformer.ts create mode 100644 ets2panda/linter/arkanalyzer/src/transformer/SceneTransformer.ts create mode 100644 ets2panda/linter/arkanalyzer/src/transformer/StaticSingleAssignmentFormer.ts create mode 100644 ets2panda/linter/arkanalyzer/src/transformer/Transformer.ts create mode 100644 ets2panda/linter/arkanalyzer/src/utils/AstTreeUtils.ts create mode 100644 ets2panda/linter/arkanalyzer/src/utils/CfgStructualAnalysis.ts create mode 100644 ets2panda/linter/arkanalyzer/src/utils/FileUtils.ts create mode 100644 ets2panda/linter/arkanalyzer/src/utils/SparseBitVector.ts create mode 100644 ets2panda/linter/arkanalyzer/src/utils/callGraphUtils.ts create mode 100644 ets2panda/linter/arkanalyzer/src/utils/crypto_utils.ts create mode 100644 ets2panda/linter/arkanalyzer/src/utils/entryMethodUtils.ts create mode 100644 ets2panda/linter/arkanalyzer/src/utils/getAllFiles.ts create mode 100644 ets2panda/linter/arkanalyzer/src/utils/json5parser.ts create mode 100644 ets2panda/linter/arkanalyzer/src/utils/logger.ts create mode 100644 ets2panda/linter/arkanalyzer/src/utils/pathTransfer.ts create mode 100644 ets2panda/linter/arkanalyzer/tsconfig.json create mode 100644 ets2panda/linter/arkanalyzer/tsconfig.main.json create mode 100644 ets2panda/linter/arkanalyzer/tsconfig.prod.json create mode 100644 ets2panda/linter/arkanalyzer/typedoc.json create mode 100644 ets2panda/linter/arkanalyzer/vitest.config.ts create mode 100644 ets2panda/linter/homecheck/LICENSE create mode 100644 ets2panda/linter/homecheck/OAT.xml create mode 100644 ets2panda/linter/homecheck/config/projectConfig.json create mode 100644 ets2panda/linter/homecheck/config/ruleConfig.json create mode 100644 ets2panda/linter/homecheck/package.json create mode 100644 ets2panda/linter/homecheck/resources/internalSdk/@internal/es5.d.ts create mode 100644 ets2panda/linter/homecheck/resources/sdkConfig.json create mode 100644 ets2panda/linter/homecheck/resources/thirdPartyModules/@hview/moment/index.d.ts create mode 100644 ets2panda/linter/homecheck/resources/thirdPartyModules/@ohos/gif-drawable/index.ets create mode 100644 ets2panda/linter/homecheck/resources/thirdPartyModules/@ohos/gif-drawable/src/main/ets/components/gif/display/GIFComponent.ets create mode 100644 ets2panda/linter/homecheck/resources/thirdPartyModules/@ohos/gif-drawable/src/main/ets/components/gif/display/GIFComponentV2.ets create mode 100644 ets2panda/linter/homecheck/resources/thirdPartyModules/@ohos/lottie/index.d.ts create mode 100644 ets2panda/linter/homecheck/ruleSet.json create mode 100644 ets2panda/linter/homecheck/scripts/install_arkanalyzer.sh create mode 100644 ets2panda/linter/homecheck/scripts/run_ci_ut.sh create mode 100644 ets2panda/linter/homecheck/src/Index.ts create mode 100644 ets2panda/linter/homecheck/src/Main.ts create mode 100644 ets2panda/linter/homecheck/src/checker/BaseChecker.ts create mode 100644 ets2panda/linter/homecheck/src/checker/migration/AppStorageGetCheck.ts create mode 100644 ets2panda/linter/homecheck/src/checker/migration/CustomBuilderCheck.ts create mode 100644 ets2panda/linter/homecheck/src/checker/migration/ModifyStateVarCheck.ts create mode 100644 ets2panda/linter/homecheck/src/checker/migration/NoMethodOverridingFieldCheck.ts create mode 100644 ets2panda/linter/homecheck/src/checker/migration/NoOptionalMethodCheck.ts create mode 100644 ets2panda/linter/homecheck/src/checker/migration/ObjectLiteralCheck.ts create mode 100644 ets2panda/linter/homecheck/src/checker/migration/ObservedDecoratorCheck.ts create mode 100644 ets2panda/linter/homecheck/src/checker/migration/ThisBindCheck.ts create mode 100644 ets2panda/linter/homecheck/src/codeFix/FixEngine.ts create mode 100644 ets2panda/linter/homecheck/src/codeFix/engines/AIFixEngine.ts create mode 100644 ets2panda/linter/homecheck/src/codeFix/engines/EsLintFixEngine.ts create mode 100644 ets2panda/linter/homecheck/src/codeFix/engines/HomeCheckFixEngine.ts create mode 100644 ets2panda/linter/homecheck/src/matcher/Matchers.ts create mode 100644 ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchClass.ts create mode 100644 ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchFields.ts create mode 100644 ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchFiles.ts create mode 100644 ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchMethods.ts create mode 100644 ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchNameSpaces.ts create mode 100644 ets2panda/linter/homecheck/src/model/Defects.ts create mode 100644 ets2panda/linter/homecheck/src/model/Engine.ts create mode 100644 ets2panda/linter/homecheck/src/model/File2Check.ts create mode 100644 ets2panda/linter/homecheck/src/model/Fix.ts create mode 100644 ets2panda/linter/homecheck/src/model/Interfaces.ts create mode 100644 ets2panda/linter/homecheck/src/model/Message.ts create mode 100644 ets2panda/linter/homecheck/src/model/NumberValue.ts create mode 100644 ets2panda/linter/homecheck/src/model/Project2Check.ts create mode 100644 ets2panda/linter/homecheck/src/model/ProjectConfig.ts create mode 100644 ets2panda/linter/homecheck/src/model/Rule.ts create mode 100644 ets2panda/linter/homecheck/src/model/RuleConfig.ts create mode 100644 ets2panda/linter/homecheck/src/model/Scope.ts create mode 100644 ets2panda/linter/homecheck/src/model/SparseArrayValue.ts create mode 100644 ets2panda/linter/homecheck/src/model/StmtExt.ts create mode 100644 ets2panda/linter/homecheck/src/model/VarInfo.ts create mode 100644 ets2panda/linter/homecheck/src/model/Variable.ts create mode 100644 ets2panda/linter/homecheck/src/run.ts create mode 100644 ets2panda/linter/homecheck/src/runTool.ts create mode 100644 ets2panda/linter/homecheck/src/tools/BuildModuleChains.ts create mode 100644 ets2panda/linter/homecheck/src/tools/depGraph/builder.ts create mode 100644 ets2panda/linter/homecheck/src/tools/depGraph/fileComponent.ts create mode 100644 ets2panda/linter/homecheck/src/tools/depGraph/fileDeps.ts create mode 100644 ets2panda/linter/homecheck/src/tools/depGraph/moduleComponent.ts create mode 100644 ets2panda/linter/homecheck/src/tools/depGraph/moduleDeps.ts create mode 100644 ets2panda/linter/homecheck/src/tools/depGraph/utils.ts create mode 100644 ets2panda/linter/homecheck/src/tools/migrationTool/ExportIssue.ts create mode 100644 ets2panda/linter/homecheck/src/tools/migrationTool/MigrationTool.ts create mode 100644 ets2panda/linter/homecheck/src/tools/toolEntry.ts create mode 100644 ets2panda/linter/homecheck/src/tools/toolRun.ts create mode 100644 ets2panda/linter/homecheck/src/utils/checker/AbilityInterface.ts create mode 100644 ets2panda/linter/homecheck/src/utils/checker/BytesUtils.ts create mode 100644 ets2panda/linter/homecheck/src/utils/checker/CheckerUtils.ts create mode 100644 ets2panda/linter/homecheck/src/utils/checker/ImageUtils.ts create mode 100644 ets2panda/linter/homecheck/src/utils/checker/NumberUtils.ts create mode 100644 ets2panda/linter/homecheck/src/utils/checker/StringUtils.ts create mode 100644 ets2panda/linter/homecheck/src/utils/checker/TypeUtils.ts create mode 100644 ets2panda/linter/homecheck/src/utils/checker/ViewTreeTool.ts create mode 100644 ets2panda/linter/homecheck/src/utils/checker/imageFormat/bmp.ts create mode 100644 ets2panda/linter/homecheck/src/utils/checker/imageFormat/jpg.ts create mode 100644 ets2panda/linter/homecheck/src/utils/checker/imageFormat/png.ts create mode 100644 ets2panda/linter/homecheck/src/utils/checker/imageFormat/svg.ts create mode 100644 ets2panda/linter/homecheck/src/utils/checker/imageFormat/webp.ts create mode 100644 ets2panda/linter/homecheck/src/utils/common/AfterCheck.ts create mode 100644 ets2panda/linter/homecheck/src/utils/common/CheckBuilder.ts create mode 100644 ets2panda/linter/homecheck/src/utils/common/CheckEntry.ts create mode 100644 ets2panda/linter/homecheck/src/utils/common/CheckerFactory.ts create mode 100644 ets2panda/linter/homecheck/src/utils/common/CheckerIndex.ts create mode 100644 ets2panda/linter/homecheck/src/utils/common/CheckerStorage.ts create mode 100644 ets2panda/linter/homecheck/src/utils/common/ConfigUtils.ts create mode 100644 ets2panda/linter/homecheck/src/utils/common/DefectsList.ts create mode 100644 ets2panda/linter/homecheck/src/utils/common/Disable.ts create mode 100644 ets2panda/linter/homecheck/src/utils/common/FileRuleMapping.ts create mode 100644 ets2panda/linter/homecheck/src/utils/common/FileUtils.ts create mode 100644 ets2panda/linter/homecheck/src/utils/common/FixUtils.ts create mode 100644 ets2panda/linter/homecheck/src/utils/common/GeneratingJsonFile.ts create mode 100644 ets2panda/linter/homecheck/src/utils/common/GlobMatch.ts create mode 100644 ets2panda/linter/homecheck/src/utils/common/Json5parser.ts create mode 100644 ets2panda/linter/homecheck/src/utils/common/ScopeHelper.ts create mode 100644 ets2panda/linter/homecheck/src/utils/common/Utils.ts create mode 100644 ets2panda/linter/homecheck/tsconfig.json create mode 100644 ets2panda/linter/homecheck/tsconfig.main.json create mode 100644 ets2panda/linter/homecheck/tsconfig.prod.json create mode 100644 ets2panda/linter/homecheck/typedoc.json create mode 100644 ets2panda/linter/homecheck/vitest.config.ts rename ets2panda/linter/scripts/{install-ohos-typescript.mjs => install-ohos-typescript-and-homecheck.mjs} (63%) create mode 100644 ets2panda/linter/src/lib/HomeCheck.ts diff --git a/.gitignore b/.gitignore index 7e3b942d7a..257077ee45 100644 --- a/.gitignore +++ b/.gitignore @@ -17,6 +17,8 @@ ets2panda/linter*/test_rules/**/results ets2panda/linter*/test_regression/**/results ets2panda/linter*/test_extended_features/**/results ets2panda/linter*/**/package-lock.json +ets2panda/linter*/arkanalyzer/**/lib +ets2panda/linter*/homecheck/**/lib **/compile_commands.json .cache .vscode diff --git a/codecheck_ignore.json b/codecheck_ignore.json index c0c4e5df78..775d3e8774 100755 --- a/codecheck_ignore.json +++ b/codecheck_ignore.json @@ -9,6 +9,8 @@ "legacy_bin": "*", "merge_abc": "*", "ets2panda/public/headers_parser": "*", + "ets2panda/linter/arkanalyzer": "*", + "ets2panda/linter/homecheck": "*", "*": ["G.CMT.03", "G.FMT.11", "G.NAM.03", "huge_headerfile", "huge_non_headerfile", "bc-30001"] } diff --git a/ets2panda/linter/arkanalyzer/.prettierrc b/ets2panda/linter/arkanalyzer/.prettierrc new file mode 100644 index 0000000000..2e3d95a2a6 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/.prettierrc @@ -0,0 +1,10 @@ +{ + "trailingComma": "es5", + "tabWidth": 4, + "useTabs": false, + "semi": true, + "singleQuote": true, + "printWidth": 120, + "quoteProps": "as-needed", + "arrowParens": "always" +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/LICENSE b/ets2panda/linter/arkanalyzer/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/ets2panda/linter/arkanalyzer/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/ets2panda/linter/arkanalyzer/OAT.xml b/ets2panda/linter/arkanalyzer/OAT.xml new file mode 100644 index 0000000000..6420939360 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/OAT.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/config/arkanalyzer.json b/ets2panda/linter/arkanalyzer/config/arkanalyzer.json new file mode 100644 index 0000000000..26c5953b47 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/config/arkanalyzer.json @@ -0,0 +1,20 @@ +{ + "supportFileExts": [ + ".ets", + ".ts", + ".d.ets", + ".d.ts" + ], + "enableLeadingComments": false, + "ignoreFileNames": [ + "oh_modules", + "node_modules", + "hvigorfile.ts", + "build-tools" + ], + "sdkGlobalFolders": [ + "component", + "@internal" + ], + "tsconfig": "tsconfig.json" +} diff --git a/ets2panda/linter/arkanalyzer/package.json b/ets2panda/linter/arkanalyzer/package.json new file mode 100644 index 0000000000..902be5d33d --- /dev/null +++ b/ets2panda/linter/arkanalyzer/package.json @@ -0,0 +1,33 @@ +{ + "name": "arkanalyzer", + "version": "1.0.8", + "files": [ + "docs", + "lib", + "config" + ], + "main": "lib/index.js", + "scripts": { + "build": "tsc", + "compile": "tsc -p ./tsconfig.prod.json", + "test": "npm run copyCollectionDefintion && vitest", + "testonce": "npm run copyCollectionDefintion && vitest --no-color run", + "coverage": "npm run copyCollectionDefintion && vitest run --coverage", + "heapdump": "npm run build && node --expose-gc out/tests/HeapDumpTest.js", + "gendoc": "npx typedoc", + "copyCollectionDefintion": "ts-node script/typescriptCollectionDefinitionCopy.ts" + }, + "dependencies": { + "commander": "11.0.0", + "log4js": "6.7.1" + }, + "bundleDependencies": [ + "ohos-typescript" + ], + "devDependencies": { + "@vitest/coverage-v8": "^1.5.0", + "ts-node": "^10.9.1", + "typedoc": "^0.25.13", + "vitest": "^1.5.0" + } +} diff --git a/ets2panda/linter/arkanalyzer/script/typescriptCollectionDefinitionCopy.ts b/ets2panda/linter/arkanalyzer/script/typescriptCollectionDefinitionCopy.ts new file mode 100644 index 0000000000..eb4d3476e3 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/script/typescriptCollectionDefinitionCopy.ts @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as fs from 'fs'; +import * as path from 'path'; + +const targetDir = './builtIn/typescript'; + +function emptyDir(dir: string): void { + if (fs.existsSync(dir)) { + fs.readdirSync(dir).forEach(file => { + const filePath = path.join(dir, file); + if (fs.statSync(filePath).isFile()) { + fs.unlinkSync(filePath); + } else if (fs.statSync(filePath).isDirectory()) { + emptyDir(filePath); + fs.rmdirSync(filePath); + } + }); + } +} + +if (!fs.existsSync(targetDir)) { + fs.mkdirSync(targetDir, { recursive: true }); +} else { + emptyDir(targetDir); +} + +fs.mkdirSync(path.join(targetDir, 'api')); +fs.mkdirSync(path.join(targetDir, 'api/@internal')); + +const sourceFile1 = './node_modules/typescript/lib/lib.es2015.collection.d.ts'; +const sourceFile2 = './node_modules/typescript/lib/lib.es5.d.ts'; + +function copyFile(source: string, destination: string): void { + if (fs.existsSync(source)) { + fs.copyFileSync(source, destination); + } else { + console.log('Error copy typescript collection definition file'); + } +} + +copyFile(sourceFile1, path.join(targetDir, 'api/@internal', 'lib.es2015.collection.d.ts')); +copyFile(sourceFile2, path.join(targetDir, 'api/@internal', 'lib.es5.d.ts')); \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/Config.ts b/ets2panda/linter/arkanalyzer/src/Config.ts new file mode 100644 index 0000000000..24178d2b5b --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/Config.ts @@ -0,0 +1,273 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import fs from 'fs'; +import path from 'path'; +import Logger, { LOG_MODULE_TYPE } from './utils/logger'; +import { getAllFiles } from './utils/getAllFiles'; +import { Language } from './core/model/ArkFile'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'Config'); + +export interface Sdk { + name: string; + path: string; + moduleName: string; +} + +export interface TsConfig { + extends?: string; + compilerOptions?: { + baseUrl?: string; + paths?: { + [key: string]: string[]; + }; + }; + +} + +export type SceneOptionsValue = string | number | boolean | (string | number)[] | string[] | null | undefined; +export interface SceneOptions { + supportFileExts?: string[]; + ignoreFileNames?: string[]; + enableLeadingComments?: boolean; + enableTrailingComments?:boolean + tsconfig?: string; + isScanAbc?: boolean; + sdkGlobalFolders?: string[]; + [option: string]: SceneOptionsValue; +} +const CONFIG_FILENAME = 'arkanalyzer.json'; +const DEFAULT_CONFIG_FILE = path.join(__dirname, '../config', CONFIG_FILENAME); + +export class SceneConfig { + private targetProjectName: string = ''; + private targetProjectDirectory: string = ''; + + private etsSdkPath: string = ''; + private sdksObj: Sdk[] = []; + + private sdkFiles: string[] = []; + private sdkFilesMap: Map = new Map(); + + private projectFiles: string[] = []; + private fileLanguages: Map = new Map(); + + private options: SceneOptions; + + constructor(options?: SceneOptions) { + this.options = { supportFileExts: ['.ets', '.ts'] }; + this.loadDefaultConfig(options); + } + + public getOptions(): SceneOptions { + return this.options; + } + + /** + * Set the scene's config, + * such as the target project's name, the used sdks and the full path. + * @param targetProjectName - the target project's name. + * @param targetProjectDirectory - the target project's directory. + * @param sdks - sdks used in this scene. + * @param fullFilePath - the full file path. + */ + public buildConfig( + targetProjectName: string, + targetProjectDirectory: string, + sdks: Sdk[], + fullFilePath?: string[] + ) { + this.targetProjectName = targetProjectName; + this.targetProjectDirectory = targetProjectDirectory; + this.sdksObj = sdks; + if (fullFilePath) { + this.projectFiles.push(...fullFilePath); + } + } + + /** + * Create a sceneConfig object for a specified project path and set the target project directory to the + * targetProjectDirectory property of the sceneConfig object. + * @param targetProjectDirectory - the target project directory, such as xxx/xxx/xxx, started from project + * directory. + * @example + * 1. build a sceneConfig object. + ```typescript + const projectDir = 'xxx/xxx/xxx'; + const sceneConfig: SceneConfig = new SceneConfig(); + sceneConfig.buildFromProjectDir(projectDir); + ``` + */ + public buildFromProjectDir(targetProjectDirectory: string) { + this.targetProjectDirectory = targetProjectDirectory; + this.targetProjectName = path.basename(targetProjectDirectory); + this.projectFiles = getAllFiles( + targetProjectDirectory, + this.options.supportFileExts!, + this.options.ignoreFileNames + ); + } + + public buildFromProjectFiles(projectName: string, projectDir: string, filesAndDirectorys: string[], sdks?: Sdk[], + languageTags?: Map): void { + if (sdks) { + this.sdksObj = sdks; + } + this.targetProjectDirectory = projectDir; + this.targetProjectName = projectName; + if (filesAndDirectorys.length === 0) { + logger.error('no files for build scene!'); + return; + } + filesAndDirectorys.forEach(fileOrDirectory => this.processFilePaths(fileOrDirectory, projectDir)); + languageTags?.forEach((languageTag, fileOrDirectory) => { + this.setLanguageTagForFiles(fileOrDirectory, projectDir, languageTag); + }); + } + + private processFilePaths(fileOrDirectory: string, projectDir: string): void { + let absoluteFilePath = ''; + if (fileOrDirectory.includes(projectDir)) { + absoluteFilePath = fileOrDirectory; + } else { + absoluteFilePath = path.join(projectDir, fileOrDirectory); + } + if (fs.statSync(absoluteFilePath).isDirectory()) { + getAllFiles(absoluteFilePath, this.getOptions().supportFileExts!, this.options.ignoreFileNames).forEach((filePath) => { + if (!this.projectFiles.includes(filePath)) { + this.projectFiles.push(filePath); + } + }); + } else { + this.projectFiles.push(absoluteFilePath); + } + } + + private setLanguageTagForFiles(fileOrDirectory: string, projectDir: string, languageTag: Language): void { + let absoluteFilePath = ''; + if (fileOrDirectory.includes(projectDir)) { + absoluteFilePath = fileOrDirectory; + } else { + absoluteFilePath = path.join(projectDir, fileOrDirectory); + } + if (fs.statSync(absoluteFilePath).isDirectory()) { + getAllFiles(absoluteFilePath, this.getOptions().supportFileExts!, this.options.ignoreFileNames) + .forEach((filePath) => { + this.fileLanguages.set(filePath, languageTag); + }); + } else { + this.fileLanguages.set(absoluteFilePath, languageTag); + } + } + + public buildFromJson(configJsonPath: string) { + if (fs.existsSync(configJsonPath)) { + let configurationsText: string; + try { + configurationsText = fs.readFileSync(configJsonPath, 'utf-8'); + } catch (error) { + logger.error(`Error reading file: ${error}`); + return; + } + + logger.info(configurationsText); + let configurations: any; + try { + configurations = JSON.parse(configurationsText); + } catch (error) { + logger.error(`Error parsing JSON: ${error}`); + return; + } + + const targetProjectName: string = configurations.targetProjectName ? configurations.targetProjectName : ''; + const targetProjectDirectory: string = configurations.targetProjectDirectory + ? configurations.targetProjectDirectory + : ''; + const sdks: Sdk[] = configurations.sdks ? configurations.sdks : []; + + if (configurations.options) { + this.options = { ...this.options, ...configurations.options }; + } + + this.buildConfig(targetProjectName, targetProjectDirectory, sdks); + } else { + logger.error(`Your configJsonPath: "${configJsonPath}" is not exist.`); + } + } + + public getTargetProjectName() { + return this.targetProjectName; + } + + public getTargetProjectDirectory() { + return this.targetProjectDirectory; + } + + public getProjectFiles() { + return this.projectFiles; + } + + public getFileLanguages(): Map { + return this.fileLanguages; + } + + public getSdkFiles() { + return this.sdkFiles; + } + + public getSdkFilesMap() { + return this.sdkFilesMap; + } + + public getEtsSdkPath() { + return this.etsSdkPath; + } + + public getSdksObj() { + return this.sdksObj; + } + + private getDefaultConfigPath(): string { + try { + const moduleRoot = path.dirname(path.dirname(require.resolve('arkanalyzer'))); + return path.join(moduleRoot, 'config', CONFIG_FILENAME); + } catch (e) { + logger.info(`Failed to resolve default config file from dependency path with error: ${e}`); + let configFile = DEFAULT_CONFIG_FILE; + if (!fs.existsSync(configFile)) { + logger.debug(`default config file '${DEFAULT_CONFIG_FILE}' not found.`); + configFile = path.join(__dirname, 'config', CONFIG_FILENAME); + logger.debug(`use new config file '${configFile}'.`); + } else { + logger.debug(`default config file '${DEFAULT_CONFIG_FILE}' found, use it.`); + } + return configFile; + } + } + + private loadDefaultConfig(options?: SceneOptions): void { + const configFile = this.getDefaultConfigPath(); + logger.debug(`try to parse config file ${configFile}`); + try { + this.options = { ...this.options, ...JSON.parse(fs.readFileSync(configFile, 'utf-8')) }; + } catch (error) { + logger.error(`Failed to parse config file with error: ${error}`); + } + if (options) { + this.options = { ...this.options, ...options }; + } + } +} diff --git a/ets2panda/linter/arkanalyzer/src/Scene.ts b/ets2panda/linter/arkanalyzer/src/Scene.ts new file mode 100644 index 0000000000..02e26abc46 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/Scene.ts @@ -0,0 +1,1438 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import fs from 'fs'; +import path from 'path'; + +import { SceneConfig, SceneOptions, Sdk, TsConfig } from './Config'; +import { initModulePathMap, ModelUtils } from './core/common/ModelUtils'; +import { TypeInference } from './core/common/TypeInference'; +import { VisibleValue } from './core/common/VisibleValue'; +import { ArkClass } from './core/model/ArkClass'; +import { ArkFile, Language } from './core/model/ArkFile'; +import { ArkMethod } from './core/model/ArkMethod'; +import { ArkNamespace } from './core/model/ArkNamespace'; +import { ClassSignature, FileSignature, MethodSignature, NamespaceSignature } from './core/model/ArkSignature'; +import Logger, { LOG_MODULE_TYPE } from './utils/logger'; +import { Local } from './core/base/Local'; +import { buildArkFileFromFile } from './core/model/builder/ArkFileBuilder'; +import { fetchDependenciesFromFile, parseJsonText } from './utils/json5parser'; +import { getAllFiles } from './utils/getAllFiles'; +import { FileUtils, getFileRecursively } from './utils/FileUtils'; +import { ArkExport, ExportInfo, ExportType } from './core/model/ArkExport'; +import { addInitInConstructor, buildDefaultConstructor } from './core/model/builder/ArkMethodBuilder'; +import { DEFAULT_ARK_CLASS_NAME, STATIC_INIT_METHOD_NAME } from './core/common/Const'; +import { CallGraph } from './callgraph/model/CallGraph'; +import { CallGraphBuilder } from './callgraph/model/builder/CallGraphBuilder'; +import { IRInference } from './core/common/IRInference'; +import { ImportInfo } from './core/model/ArkImport'; +import { ALL, CONSTRUCTOR_NAME, TSCONFIG_JSON } from './core/common/TSConst'; +import { BUILD_PROFILE_JSON5, OH_PACKAGE_JSON5 } from './core/common/EtsConst'; +import { SdkUtils } from './core/common/SdkUtils'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'Scene'); + +enum SceneBuildStage { + BUILD_INIT, + CLASS_DONE, + METHOD_DONE, + CLASS_COLLECTED, + METHOD_COLLECTED, + SDK_INFERRED, + TYPE_INFERRED +}; + +/** + * The Scene class includes everything in the analyzed project. + * We should be able to re-generate the project's code based on this class. + */ +export class Scene { + private projectName: string = ''; + private projectFiles: string[] = []; + private realProjectDir: string = ''; + + private moduleScenesMap: Map = new Map(); + private modulePath2NameMap: Map = new Map(); + + private moduleSdkMap: Map = new Map(); + private projectSdkMap: Map = new Map(); + + // values that are visible in curr scope + private visibleValue: VisibleValue = new VisibleValue(); + + // signature string to model + private filesMap: Map = new Map(); + private namespacesMap: Map = new Map(); + private classesMap: Map = new Map(); + private methodsMap: Map = new Map(); + // TODO: type of key should be signature object + private sdkArkFilesMap: Map = new Map(); + private sdkGlobalMap: Map = new Map(); + private ohPkgContentMap: Map = new Map(); + private ohPkgFilePath: string = ''; + private ohPkgContent: { [k: string]: unknown } = {}; + private overRides: Map = new Map(); + private overRideDependencyMap: Map = new Map(); + private globalModule2PathMapping?: { [k: string]: string[]; } | undefined; + private baseUrl?: string | undefined; + + private buildStage: SceneBuildStage = SceneBuildStage.BUILD_INIT; + private fileLanguages: Map = new Map(); + + private options!: SceneOptions; + private indexPathArray = ['Index.ets', 'Index.ts', 'Index.d.ets', 'Index.d.ts', 'index.ets', 'index.ts', 'index.d.ets', 'index.d.ts']; + + private unhandledFilePaths: string[] = []; + private unhandledSdkFilePaths: string[] = []; + + constructor() { + } + + public getOptions(): SceneOptions { + return this.options; + } + + public getOverRides(): Map { + return this.overRides; + } + + public getOverRideDependencyMap(): Map { + return this.overRideDependencyMap; + } + + public clear(): void { + this.projectFiles = []; + + this.moduleScenesMap.clear(); + this.modulePath2NameMap.clear(); + + this.moduleSdkMap.clear(); + this.projectSdkMap.clear(); + + this.filesMap.clear(); + this.namespacesMap.clear(); + this.classesMap.clear(); + this.methodsMap.clear(); + + this.sdkArkFilesMap.clear(); + this.sdkGlobalMap.clear(); + this.ohPkgContentMap.clear(); + this.ohPkgContent = {}; + } + + public getStage(): SceneBuildStage { + return this.buildStage; + } + + /** + * Build scene object according to the {@link SceneConfig}. This API implements 3 functions. + * First is to build scene object from {@link SceneConfig}, second is to generate {@link ArkFile}s, + * and the last is to collect project import infomation. + * @param sceneConfig - a sceneConfig object, which is usally defined by user or Json file. + * @example + * 1. Build Scene object from scene config + + ```typescript + // build config + const projectDir = ... ...; + const sceneConfig = new SceneConfig(); + sceneConfig.buildFromProjectDir(projectDir); + + // build scene + const scene = new Scene(); + scene.buildSceneFromProjectDir(sceneConfig); + ``` + */ + public buildSceneFromProjectDir(sceneConfig: SceneConfig) { + this.buildBasicInfo(sceneConfig); + this.genArkFiles(); + } + + public buildSceneFromFiles(sceneConfig: SceneConfig): void { + this.buildBasicInfo(sceneConfig); + this.buildOhPkgContentMap(); + initModulePathMap(this.ohPkgContentMap); + this.getFilesOrderByDependency(); + } + + /** + * Set the basic information of the scene using a config, + * such as the project's name, real path and files. + * @param sceneConfig - the config used to set the basic information of scene. + */ + public buildBasicInfo(sceneConfig: SceneConfig): void { + this.options = sceneConfig.getOptions(); + this.projectName = sceneConfig.getTargetProjectName(); + this.realProjectDir = fs.realpathSync(sceneConfig.getTargetProjectDirectory()); + this.projectFiles = sceneConfig.getProjectFiles(); + + this.parseBuildProfile(); + + this.parseOhPackage(); + let tsConfigFilePath; + if (this.options.tsconfig) { + tsConfigFilePath = path.join(sceneConfig.getTargetProjectDirectory(), this.options.tsconfig); + } else { + tsConfigFilePath = path.join(sceneConfig.getTargetProjectDirectory(), TSCONFIG_JSON); + } + if (fs.existsSync(tsConfigFilePath)) { + const tsConfigObj: TsConfig = fetchDependenciesFromFile(tsConfigFilePath); + this.findTsConfigInfoDeeply(tsConfigObj, tsConfigFilePath); + } else { + logger.warn('This project has no tsconfig.json!'); + } + + // handle sdks + sceneConfig.getSdksObj()?.forEach((sdk) => { + if (!sdk.moduleName) { + this.buildSdk(sdk.name, sdk.path); + this.projectSdkMap.set(sdk.name, sdk); + } else { + let moduleSdks = this.moduleSdkMap.get(sdk.moduleName); + if (moduleSdks) { + moduleSdks.push(sdk); + } else { + this.moduleSdkMap.set(sdk.moduleName, [sdk]); + } + } + }); + + this.fileLanguages = sceneConfig.getFileLanguages(); + } + + private parseBuildProfile(): void { + const buildProfile = path.join(this.realProjectDir, BUILD_PROFILE_JSON5); + if (fs.existsSync(buildProfile)) { + let configurationsText: string; + try { + configurationsText = fs.readFileSync(buildProfile, 'utf-8'); + } catch (error) { + logger.error(`Error reading file: ${error}`); + return; + } + const buildProfileJson = parseJsonText(configurationsText); + const modules = buildProfileJson.modules; + if (modules instanceof Array) { + modules.forEach((module) => { + this.modulePath2NameMap.set(path.resolve(this.realProjectDir, path.join(module.srcPath)), module.name); + }); + } + } else { + logger.warn('There is no build-profile.json5 for this project.'); + } + } + + private parseOhPackage(): void { + const OhPkgFilePath = path.join(this.realProjectDir, OH_PACKAGE_JSON5); + if (fs.existsSync(OhPkgFilePath)) { + this.ohPkgFilePath = OhPkgFilePath; + this.ohPkgContent = fetchDependenciesFromFile(this.ohPkgFilePath); + this.ohPkgContentMap.set(OhPkgFilePath, this.ohPkgContent); + if (this.ohPkgContent.overrides) { + let overRides = this.ohPkgContent.overrides as { [k: string]: unknown }; + for (const [key, value] of Object.entries(overRides)) { + this.overRides.set(key, value as string); + } + } + if (this.ohPkgContent.overrideDependencyMap) { + let globalOverRideDependencyMap = this.ohPkgContent.overrideDependencyMap as { [k: string]: unknown }; + for (const [key, value] of Object.entries(globalOverRideDependencyMap)) { + let globalDependency = fetchDependenciesFromFile(value as string); + this.overRideDependencyMap.set(key, globalDependency); + } + } + + } else { + logger.warn('This project has no oh-package.json5!'); + } + } + + private findTsConfigInfoDeeply(tsConfigObj: TsConfig, tsConfigFilePath: string): void { + if (tsConfigObj.extends) { + const extTsConfigObj: TsConfig = fetchDependenciesFromFile(path.join(path.dirname(tsConfigFilePath), tsConfigObj.extends)); + this.findTsConfigInfoDeeply(extTsConfigObj, tsConfigFilePath); + if (!this.baseUrl && !this.globalModule2PathMapping) { + this.addTsConfigInfo(extTsConfigObj); + } + } + if (!this.baseUrl && !this.globalModule2PathMapping) { + this.addTsConfigInfo(tsConfigObj); + } + } + + private addTsConfigInfo(tsConfigObj: TsConfig): void { + if (tsConfigObj.compilerOptions && tsConfigObj.compilerOptions.paths) { + const paths = tsConfigObj.compilerOptions.paths; + if (paths) { + this.globalModule2PathMapping = paths; + } + } + if (tsConfigObj.compilerOptions && tsConfigObj.compilerOptions.baseUrl) { + this.baseUrl = tsConfigObj.compilerOptions.baseUrl; + } + } + + private addDefaultConstructors(): void { + for (const file of this.getFiles()) { + for (const cls of ModelUtils.getAllClassesInFile(file)) { + buildDefaultConstructor(cls); + const constructor = cls.getMethodWithName(CONSTRUCTOR_NAME); + if (constructor !== null) { + addInitInConstructor(constructor); + } + } + } + } + + private buildAllMethodBody(): void { + this.buildStage = SceneBuildStage.CLASS_DONE; + for (const file of this.getFiles()) { + for (const cls of file.getClasses()) { + for (const method of cls.getMethods(true)) { + method.buildBody(); + method.freeBodyBuilder(); + } + } + } + for (const namespace of this.getNamespacesMap().values()) { + for (const cls of namespace.getClasses()) { + for (const method of cls.getMethods(true)) { + method.buildBody(); + method.freeBodyBuilder(); + } + } + } + + this.buildStage = SceneBuildStage.METHOD_DONE; + } + + private genArkFiles() { + this.projectFiles.forEach((file) => { + logger.info('=== parse file:', file); + try { + const arkFile: ArkFile = new ArkFile(FileUtils.getFileLanguage(file, this.fileLanguages)); + arkFile.setScene(this); + buildArkFileFromFile(file, this.realProjectDir, arkFile, this.projectName); + this.filesMap.set(arkFile.getFileSignature().toMapKey(), arkFile); + } catch (error) { + logger.error('Error parsing file:', file, error); + this.unhandledFilePaths.push(file); + return; + } + }); + this.buildAllMethodBody(); + this.addDefaultConstructors(); + } + + private getFilesOrderByDependency(): void { + for (const projectFile of this.projectFiles) { + this.getDependencyFilesDeeply(projectFile); + } + this.buildAllMethodBody(); + this.addDefaultConstructors(); + } + + private getDependencyFilesDeeply(projectFile: string): void { + if (!this.options.supportFileExts!.includes(path.extname(projectFile))) { + return; + } + const fileSignature = new FileSignature(this.getProjectName(), path.relative(this.getRealProjectDir(), projectFile)); + if (this.filesMap.has(fileSignature.toMapKey()) || this.isRepeatBuildFile(projectFile)) { + return; + } + try { + const arkFile = new ArkFile(FileUtils.getFileLanguage(projectFile, this.fileLanguages)); + arkFile.setScene(this); + buildArkFileFromFile(projectFile, this.getRealProjectDir(), arkFile, this.getProjectName()); + for (const [modulePath, moduleName] of this.modulePath2NameMap) { + if (arkFile.getFilePath().startsWith(modulePath)) { + this.addArkFile2ModuleScene(modulePath, moduleName, arkFile); + break; + } + } + this.filesMap.set(arkFile.getFileSignature().toMapKey(), arkFile); + const importInfos = arkFile.getImportInfos(); + const repeatFroms: string[] = []; + this.findDependencyFiles(importInfos, arkFile, repeatFroms); + + const exportInfos = arkFile.getExportInfos(); + this.findDependencyFiles(exportInfos, arkFile, repeatFroms); + } catch (error) { + logger.error('Error parsing file:', projectFile, error); + this.unhandledFilePaths.push(projectFile); + return; + } + } + + private isRepeatBuildFile(projectFile: string): boolean { + for (const [key, file] of this.filesMap) { + if (key && file.getFilePath().toLowerCase() === projectFile.toLowerCase()) { + return true; + } + } + return false; + } + + private addArkFile2ModuleScene(modulePath: string, moduleName: string, arkFile: ArkFile): void { + if (this.moduleScenesMap.has(moduleName)) { + let curModuleScene = this.moduleScenesMap.get(moduleName); + if (curModuleScene) { + curModuleScene.addArkFile(arkFile); + arkFile.setModuleScene(curModuleScene); + } + } else { + let moduleScene = new ModuleScene(this); + moduleScene.ModuleScenePartiallyBuilder(moduleName, modulePath); + moduleScene.addArkFile(arkFile); + this.moduleScenesMap.set(moduleName, moduleScene); + arkFile.setModuleScene(moduleScene); + } + } + + private findDependencyFiles(importOrExportInfos: ImportInfo[] | ExportInfo[], arkFile: ArkFile, repeatFroms: string[]): void { + for (const importOrExportInfo of importOrExportInfos) { + const from = importOrExportInfo.getFrom(); + if (from && !repeatFroms.includes(from)) { + this.parseFrom(from, arkFile); + repeatFroms.push(from); + } + } + } + + private parseFrom(from: string, arkFile: ArkFile): void { + if (/^@[a-z|\-]+?\/?/.test(from)) { + for (const [ohPkgContentPath, ohPkgContent] of this.ohPkgContentMap) { + this.findDependenciesByOhPkg(ohPkgContentPath, ohPkgContent, from, arkFile); + } + } else if (/^([^@]*\/)([^\/]*)$/.test(from) || /^[\.\./|\.\.]+$/.test(from)) { + this.findRelativeDependenciesByOhPkg(from, arkFile); + } else if (/^[@a-zA-Z0-9]+(\/[a-zA-Z0-9]+)*$/.test(from)) { + this.findDependenciesByTsConfig(from, arkFile); + } + } + + private findDependenciesByTsConfig(from: string, arkFile: ArkFile): void { + if (this.globalModule2PathMapping) { + const paths: { [k: string]: string[] } = this.globalModule2PathMapping; + Object.keys(paths).forEach((key) => this.parseTsConfigParms(paths, key, from, arkFile)); + } + } + + private parseTsConfigParms(paths: { [k: string]: string[] }, key: string, from: string, arkFile: ArkFile): void { + const module2pathMapping = paths[key]; + if (key.includes(ALL)) { + this.processFuzzyMapping(key, from, module2pathMapping, arkFile); + } else if (from.startsWith(key)) { + let tail = from.substring(key.length, from.length); + module2pathMapping.forEach((pathMapping) => { + let originPath = path.join(this.getRealProjectDir(), pathMapping, tail); + if (this.baseUrl) { + originPath = path.resolve(this.baseUrl, originPath); + } + this.findDependenciesByRule(originPath, arkFile); + }); + } + } + + private processFuzzyMapping(key: string, from: string, module2pathMapping: string[], arkFile: ArkFile): void { + key = key.substring(0, key.indexOf(ALL) - 1); + if (from.substring(0, key.indexOf(ALL) - 1) === key) { + let tail = from.substring(key.indexOf(ALL) - 1, from.length); + module2pathMapping.forEach((pathMapping) => { + pathMapping = pathMapping.substring(0, pathMapping.indexOf(ALL) - 1); + let originPath = path.join(this.getRealProjectDir(), pathMapping, tail); + if (this.baseUrl) { + originPath = path.join(this.baseUrl, originPath); + } + this.findDependenciesByRule(originPath, arkFile); + }); + } + } + + private findDependenciesByRule(originPath: string, arkFile: ArkFile): void { + const extNameArray = ['.ets', '.ts', '.d.ets', '.d.ts']; + if (!this.findFilesByPathArray(originPath, this.indexPathArray, arkFile) && !this.findFilesByExtNameArray(originPath, extNameArray, arkFile)) { + logger.info(originPath + 'module mapperInfo is not found!'); + } + } + + private findFilesByPathArray(originPath: string, pathArray: string[], arkFile: ArkFile): boolean { + for (const pathInfo of pathArray) { + const curPath = path.join(originPath, pathInfo); + if (fs.existsSync(curPath) && !this.isRepeatBuildFile(curPath)) { + this.addFileNode2DependencyGrap(curPath, arkFile); + return true; + } + } + return false; + } + + private findFilesByExtNameArray(originPath: string, pathArray: string[], arkFile: ArkFile): boolean { + for (const pathInfo of pathArray) { + const curPath = originPath + pathInfo; + if (fs.existsSync(curPath) && !this.isRepeatBuildFile(curPath)) { + this.addFileNode2DependencyGrap(curPath, arkFile); + return true; + } + } + return false; + } + + + private findRelativeDependenciesByOhPkg(from: string, arkFile: ArkFile): void { + //relative path ../from ./from + //order + //1. ../from/oh-package.json5 -> [[name]] -> overRides/overRideDependencyMap? -> + //[[main]] -> file path ->dependencies(priority)+devDependencies? dynamicDependencies(not support) -> + //key overRides/overRideDependencyMap? + //2. ../from/index.ets(ts) + //3. ../from/index.d.ets(ts) + //4. ../from.ets(ts) + //5. ../from.d.ets(ts) + //2.3.4.5 random order + let originPath = this.getOriginPath(from, arkFile); + if (fs.existsSync(path.join(originPath, OH_PACKAGE_JSON5))) { + for (const [ohPkgContentPath, ohPkgContent] of this.ohPkgContentMap) { + this.findDependenciesByOhPkg(ohPkgContentPath, ohPkgContent, from, arkFile); + } + } + this.findDependenciesByRule(originPath, arkFile); + } + + private findDependenciesByOhPkg(ohPkgContentPath: string, ohPkgContentInfo: { + [k: string]: unknown + }, from: string, arkFile: ArkFile): void { + //module name @ohos/from + const ohPkgContent: { [k: string]: unknown } | undefined = ohPkgContentInfo; + //module main name is must be + if (ohPkgContent && ohPkgContent.name && from.startsWith(ohPkgContent.name.toString())) { + let originPath = ohPkgContentPath.toString().replace(OH_PACKAGE_JSON5, ''); + if (ohPkgContent.main) { + originPath = path.join(ohPkgContentPath.toString().replace(OH_PACKAGE_JSON5, ''), ohPkgContent.main.toString()); + if (ohPkgContent.dependencies) { + this.getDependenciesMapping(ohPkgContent.dependencies, ohPkgContentPath, from, arkFile); + } else if (ohPkgContent.devDependencies) { + this.getDependenciesMapping(ohPkgContent.devDependencies, ohPkgContentPath, from, arkFile); + } else if (ohPkgContent.dynamicDependencies) { + // dynamicDependencies not support + } + this.addFileNode2DependencyGrap(originPath, arkFile); + } + if (!this.findFilesByPathArray(originPath, this.indexPathArray, arkFile)) { + logger.info(originPath + 'module mapperInfo is not found!'); + } + } + } + + private getDependenciesMapping(dependencies: object, ohPkgContentPath: string, from: string, arkFile: ArkFile): void { + for (let [moduleName, modulePath] of Object.entries(dependencies)) { + logger.debug('dependencies:' + moduleName); + if (modulePath.startsWith('file:')) { + modulePath = modulePath.replace(/^file:/, ''); + } + const innerOhpackagePath = path.join(ohPkgContentPath.replace(OH_PACKAGE_JSON5, ''), modulePath.toString(), OH_PACKAGE_JSON5); + if (!this.ohPkgContentMap.has(innerOhpackagePath)) { + const innerModuleOhPkgContent = fetchDependenciesFromFile(innerOhpackagePath); + this.findDependenciesByOhPkg(innerOhpackagePath, innerModuleOhPkgContent, from, arkFile); + } + } + } + + private getOriginPath(from: string, arkFile: ArkFile): string { + const parentPath = /^\.{1,2}\//.test(from) ? path.dirname(arkFile.getFilePath()) : arkFile.getProjectDir(); + return path.resolve(parentPath, from); + } + + private addFileNode2DependencyGrap(filePath: string, arkFile: ArkFile): void { + this.getDependencyFilesDeeply(filePath); + this.filesMap.set(arkFile.getFileSignature().toMapKey(), arkFile); + } + + private buildSdk(sdkName: string, sdkPath: string) { + const allFiles = getAllFiles(sdkPath, this.options.supportFileExts!, this.options.ignoreFileNames); + allFiles.forEach((file) => { + logger.info('=== parse sdk file:', file); + try { + const arkFile: ArkFile = new ArkFile(FileUtils.getFileLanguage(file, this.fileLanguages)); + arkFile.setScene(this); + buildArkFileFromFile(file, path.normalize(sdkPath), arkFile, sdkName); + ModelUtils.getAllClassesInFile(arkFile).forEach(cls => { + cls.getDefaultArkMethod()?.buildBody(); + cls.getDefaultArkMethod()?.freeBodyBuilder(); + }); + const fileSig = arkFile.getFileSignature().toMapKey(); + this.sdkArkFilesMap.set(fileSig, arkFile); + SdkUtils.buildGlobalMap(arkFile, this.sdkGlobalMap); + } catch (error) { + logger.error('Error parsing file:', file, error); + this.unhandledSdkFilePaths.push(file); + return; + } + }); + } + + /** + * Build the scene for harmony project. It resolves the file path of the project first, and then fetches + * dependencies from this file. Next, build a `ModuleScene` for this project to generate {@link ArkFile}. Finally, + * it build bodies of all methods, generate extended classes, and add DefaultConstructors. + */ + public buildScene4HarmonyProject() { + this.buildOhPkgContentMap(); + this.modulePath2NameMap.forEach((value, key) => { + let moduleScene = new ModuleScene(this); + moduleScene.ModuleSceneBuilder(value, key, this.options.supportFileExts!); + this.moduleScenesMap.set(value, moduleScene); + }); + initModulePathMap(this.ohPkgContentMap); + this.buildAllMethodBody(); + this.addDefaultConstructors(); + } + + private buildOhPkgContentMap(): void { + this.modulePath2NameMap.forEach((value, key) => { + const moduleOhPkgFilePath = path.resolve(key, OH_PACKAGE_JSON5); + if (fs.existsSync(moduleOhPkgFilePath)) { + const moduleOhPkgContent = fetchDependenciesFromFile(moduleOhPkgFilePath); + this.ohPkgContentMap.set(moduleOhPkgFilePath, moduleOhPkgContent); + } + }); + } + + public buildModuleScene(moduleName: string, modulePath: string, supportFileExts: string[]) { + if (this.moduleScenesMap.get(moduleName)) { + return; + } + + // get oh-package.json5 + const moduleOhPkgFilePath = path.resolve(this.realProjectDir, path.join(modulePath, OH_PACKAGE_JSON5)); + if (fs.existsSync(moduleOhPkgFilePath)) { + const moduleOhPkgContent = fetchDependenciesFromFile(moduleOhPkgFilePath); + this.ohPkgContentMap.set(moduleOhPkgFilePath, moduleOhPkgContent); + } else { + logger.warn('Module: ', moduleName, 'has no oh-package.json5.'); + } + + // parse moduleOhPkgContent, get dependencies and build dependent module + const moduleOhPkgContent = this.ohPkgContentMap.get(moduleOhPkgFilePath); + if (moduleOhPkgContent) { + if (moduleOhPkgContent.dependencies instanceof Object) { + this.processModuleOhPkgContent(moduleOhPkgContent.dependencies, moduleOhPkgFilePath, supportFileExts); + } + } + + let moduleScene = new ModuleScene(this); + moduleScene.ModuleSceneBuilder(moduleName, modulePath, supportFileExts); + this.moduleScenesMap.set(moduleName, moduleScene); + + this.buildAllMethodBody(); + } + + private processModuleOhPkgContent(dependencies: Object, moduleOhPkgFilePath: string, supportFileExts: string[]): void { + Object.entries(dependencies).forEach(([k, v]) => { + const pattern = new RegExp('^(\\.\\.\\/\|\\.\\/)'); + if (typeof (v) === 'string') { + let dependencyModulePath: string = ''; + if (pattern.test(v)) { + dependencyModulePath = path.join(moduleOhPkgFilePath, v); + } else if (v.startsWith('file:')) { + const dependencyFilePath = path.join(moduleOhPkgFilePath, v.replace(/^file:/, '')); + const dependencyOhPkgPath = getFileRecursively(path.dirname(dependencyFilePath), OH_PACKAGE_JSON5); + dependencyModulePath = path.dirname(dependencyOhPkgPath); + } + const dependencyModuleName = this.modulePath2NameMap.get(dependencyModulePath); + if (dependencyModuleName) { + this.buildModuleScene(dependencyModuleName, dependencyModulePath, supportFileExts); + } + } + }); + } + + /** + * Get the absolute path of current project. + * @returns The real project's directiory. + * @example + * 1. get real project directory, such as: + ```typescript + let projectDir = projectScene.getRealProjectDir(); + ``` + */ + public getRealProjectDir(): string { + return this.realProjectDir; + } + + /** + * Returns the **string** name of the project. + * @returns The name of the project. + */ + public getProjectName(): string { + return this.projectName; + } + + public getProjectFiles() { + return this.projectFiles; + } + + public getSdkGlobal(globalName: string): ArkExport | null { + return this.sdkGlobalMap.get(globalName) || null; + } + + /** + * Returns the file based on its signature. + * If no file can be found according to the input signature, **null** will be returned. + * A typical {@link ArkFile} contains: file's name (i.e., its relative path), project's name, + * project's dir, file's signature etc. + * @param fileSignature - the signature of file. + * @returns a file defined by ArkAnalyzer. **null** will be returned if no file could be found. + * @example + * 1. get ArkFile based on file signature. + + ```typescript + if (...) { + const fromSignature = new FileSignature(); + fromSignature.setProjectName(im.getDeclaringArkFile().getProjectName()); + fromSignature.setFileName(fileName); + return scene.getFile(fromSignature); + } + ``` + */ + public getFile(fileSignature: FileSignature): ArkFile | null { + if (this.projectName === fileSignature.getProjectName()) { + return this.filesMap.get(fileSignature.toMapKey()) || null; + } else { + return this.sdkArkFilesMap.get(fileSignature.toMapKey()) || null; + } + } + + /* + * Returns the absolute file paths that cannot be handled currently. + */ + public getUnhandledFilePaths(): string[] { + return this.unhandledFilePaths; + } + + /* + * Returns the absolute sdk file paths that cannot be handled currently. + */ + public getUnhandledSdkFilePaths(): string[] { + return this.unhandledSdkFilePaths; + } + + public setFile(file: ArkFile): void { + this.filesMap.set(file.getFileSignature().toMapKey(), file); + } + + public hasSdkFile(fileSignature: FileSignature): boolean { + return this.sdkArkFilesMap.has(fileSignature.toMapKey()); + } + + /** + * Get files of a {@link Scene}. Generally, a project includes several ets/ts files that define the different + * class. We need to generate {@link ArkFile} objects from these ets/ts files. + * @returns The array of {@link ArkFile} from `scene.filesMap.values()`. + * @example + * 1. In inferSimpleTypes() to check arkClass and arkMethod. + * ```typescript + * public inferSimpleTypes() { + * for (let arkFile of this.getFiles()) { + * for (let arkClass of arkFile.getClasses()) { + * for (let arkMethod of arkClass.getMethods()) { + * // ... ...; + * } + * } + * } + * } + * ``` + * 2. To iterate each method + * ```typescript + * for (const file of this.getFiles()) { + * for (const cls of file.getClasses()) { + * for (const method of cls.getMethods()) { + * // ... ... + * } + * } + * } + *``` + */ + public getFiles(): ArkFile[] { + return Array.from(this.filesMap.values()); + } + + public getFileLanguages(): Map { + return this.fileLanguages; + } + + public getSdkArkFiles(): ArkFile[] { + return Array.from(this.sdkArkFilesMap.values()); + } + + public getModuleSdkMap() { + return this.moduleSdkMap; + } + + public getProjectSdkMap() { + return this.projectSdkMap; + } + + public getNamespace(namespaceSignature: NamespaceSignature): ArkNamespace | null { + const isProject = this.projectName === namespaceSignature.getDeclaringFileSignature().getProjectName(); + let namespace; + if (isProject) { + namespace = this.namespacesMap.get(namespaceSignature.toMapKey()); + } + if (namespace) { + return namespace; + } + namespace = this.getNamespaceBySignature(namespaceSignature); + if (isProject && namespace) { + this.namespacesMap.set(namespaceSignature.toMapKey(), namespace); + } + return namespace || null; + } + + private getNamespaceBySignature(signature: NamespaceSignature): ArkNamespace | null { + const parentSignature = signature.getDeclaringNamespaceSignature(); + if (parentSignature) { + const parentNamespace = this.getNamespaceBySignature(parentSignature); + return parentNamespace?.getNamespace(signature) || null; + } else { + const arkFile = this.getFile(signature.getDeclaringFileSignature()); + return arkFile?.getNamespace(signature) || null; + } + } + + private getNamespacesMap(): Map { + if (this.buildStage === SceneBuildStage.CLASS_DONE) { + for (const file of this.getFiles()) { + ModelUtils.getAllNamespacesInFile(file).forEach((namespace) => { + this.namespacesMap.set(namespace.getNamespaceSignature().toMapKey(), namespace); + }); + } + } + return this.namespacesMap; + } + + public getNamespaces(): ArkNamespace[] { + return Array.from(this.getNamespacesMap().values()); + } + + /** + * Returns the class according to the input class signature. + * @param classSignature - signature of the class to be obtained. + * @returns A class. + */ + public getClass(classSignature: ClassSignature): ArkClass | null { + const isProject = this.projectName === classSignature.getDeclaringFileSignature().getProjectName(); + let arkClass; + if (isProject) { + arkClass = this.classesMap.get(classSignature.toMapKey()); + } + if (arkClass) { + return arkClass; + } + const namespaceSignature = classSignature.getDeclaringNamespaceSignature(); + if (namespaceSignature) { + arkClass = this.getNamespaceBySignature(namespaceSignature)?.getClass(classSignature) || null; + } else { + const arkFile = this.getFile(classSignature.getDeclaringFileSignature()); + arkClass = arkFile?.getClass(classSignature); + } + if (isProject && arkClass) { + this.classesMap.set(classSignature.toMapKey(), arkClass); + } + return arkClass || null; + } + + private getClassesMap(refresh?: boolean): Map { + if (refresh || this.buildStage === SceneBuildStage.METHOD_DONE) { + this.classesMap.clear(); + for (const file of this.getFiles()) { + for (const cls of file.getClasses()) { + this.classesMap.set(cls.getSignature().toMapKey(), cls); + } + } + for (const namespace of this.getNamespacesMap().values()) { + for (const cls of namespace.getClasses()) { + this.classesMap.set(cls.getSignature().toMapKey(), cls); + } + } + if (this.buildStage < SceneBuildStage.CLASS_COLLECTED) { + this.buildStage = SceneBuildStage.CLASS_COLLECTED; + } + } + return this.classesMap; + } + + public getClasses(): ArkClass[] { + return Array.from(this.getClassesMap().values()); + } + + public getMethod(methodSignature: MethodSignature, refresh?: boolean): ArkMethod | null { + const isProject = this.projectName === methodSignature.getDeclaringClassSignature().getDeclaringFileSignature().getProjectName(); + let arkMethod; + if (isProject) { + arkMethod = this.methodsMap.get(methodSignature.toMapKey()); + } + if (arkMethod) { + return arkMethod; + } + arkMethod = this.getClass(methodSignature.getDeclaringClassSignature())?.getMethod(methodSignature); + if (isProject && arkMethod) { + this.methodsMap.set(methodSignature.toMapKey(), arkMethod); + } + return arkMethod || null; + } + + private getMethodsMap(refresh?: boolean): Map { + if (refresh || (this.buildStage >= SceneBuildStage.METHOD_DONE && this.buildStage < SceneBuildStage.METHOD_COLLECTED)) { + this.methodsMap.clear(); + for (const cls of this.getClassesMap(refresh).values()) { + for (const method of cls.getMethods(true)) { + this.methodsMap.set(method.getSignature().toMapKey(), method); + } + } + if (this.buildStage < SceneBuildStage.METHOD_COLLECTED) { + this.buildStage = SceneBuildStage.METHOD_COLLECTED; + } + } + return this.methodsMap; + } + + /** + * Returns the method associated with the method signature. + * If no method is associated with this signature, **null** will be returned. + * An {@link ArkMethod} includes: + * - Name: the **string** name of method. + * - Code: the **string** code of the method. + * - Line: a **number** indicating the line location, initialized as -1. + * - Column: a **number** indicating the column location, initialized as -1. + * - Parameters & Types of parameters: the parameters of method and their types. + * - View tree: the view tree of the method. + * - ... + * + * @param methodSignature - the signature of method. + * @returns The method associated with the method signature. + * @example + * 1. get method from getMethod. + + ```typescript + const methodSignatures = this.CHA.resolveCall(xxx, yyy); + for (const methodSignature of methodSignatures) { + const method = this.scene.getMethod(methodSignature); + ... ... + } + ``` + */ + public getMethods(): ArkMethod[] { + return Array.from(this.getMethodsMap().values()); + } + + public addToMethodsMap(method: ArkMethod): void { + this.methodsMap.set(method.getSignature().toMapKey(), method); + } + + public removeMethod(method: ArkMethod): boolean { + return this.methodsMap.delete(method.getSignature().toMapKey()); + } + + public removeClass(arkClass: ArkClass): boolean { + return this.classesMap.delete(arkClass.getSignature().toMapKey()); + } + + public removeNamespace(namespace: ArkNamespace): boolean { + return this.namespacesMap.delete(namespace.getSignature().toMapKey()); + } + + public removeFile(file: ArkFile): boolean { + return this.filesMap.delete(file.getFileSignature().toMapKey()); + } + + public hasMainMethod(): boolean { + return false; + } + + //Get the set of entry points that are used to build the call graph. + public getEntryPoints() { + return []; + } + + /** get values that is visible in curr scope */ + public getVisibleValue(): VisibleValue { + return this.visibleValue; + } + + public getOhPkgContent() { + return this.ohPkgContent; + } + + public getOhPkgContentMap() { + return this.ohPkgContentMap; + } + + public getOhPkgFilePath() { + return this.ohPkgFilePath; + } + + public makeCallGraphCHA(entryPoints: MethodSignature[]): CallGraph { + let callGraph = new CallGraph(this); + let callGraphBuilder = new CallGraphBuilder(callGraph, this); + callGraphBuilder.buildClassHierarchyCallGraph(entryPoints); + return callGraph; + } + + public makeCallGraphRTA(entryPoints: MethodSignature[]): CallGraph { + let callGraph = new CallGraph(this); + let callGraphBuilder = new CallGraphBuilder(callGraph, this); + callGraphBuilder.buildRapidTypeCallGraph(entryPoints); + return callGraph; + } + + /** + * Infer type for each non-default method. It infers the type of each field/local/reference. + * For example, the statement `let b = 5;`, the type of local `b` is `NumberType`; and for the statement `let s = + * 'hello';`, the type of local `s` is `StringType`. The detailed types are defined in the Type.ts file. + * @example + * 1. Infer the type of each class field and method field. + ```typescript + const scene = new Scene(); + scene.buildSceneFromProjectDir(sceneConfig); + scene.inferTypes(); + ``` + */ + public inferTypes() { + if (this.buildStage < SceneBuildStage.SDK_INFERRED) { + this.sdkArkFilesMap.forEach(file => IRInference.inferFile(file)); + this.buildStage = SceneBuildStage.SDK_INFERRED; + } + this.filesMap.forEach(file => IRInference.inferFile(file)); + if (this.buildStage < SceneBuildStage.TYPE_INFERRED) { + this.getMethodsMap(true); + this.buildStage = SceneBuildStage.TYPE_INFERRED; + } + } + + /** + * Iterate all assignment statements in methods, + * and set the type of left operand based on the type of right operand + * if the left operand is a local variable as well as an unknown. + * @Deprecated + * @example + * 1. Infer simple type when scene building. + + ```typescript + let scene = new Scene(); + scene.buildSceneFromProjectDir(config); + scene.inferSimpleTypes(); + ``` + */ + public inferSimpleTypes() { + + for (let arkFile of this.getFiles()) { + for (let arkClass of arkFile.getClasses()) { + for (let arkMethod of arkClass.getMethods()) { + TypeInference.inferSimpleTypeInMethod(arkMethod); + } + } + } + } + + private addNSClasses(namespaceStack: ArkNamespace[], finalNamespaces: ArkNamespace[], + classMap: Map, + parentMap: Map): void { + while (namespaceStack.length > 0) { + const ns = namespaceStack.shift()!; + const nsClass: ArkClass[] = []; + for (const arkClass of ns.getClasses()) { + nsClass.push(arkClass); + } + classMap.set(ns.getNamespaceSignature(), nsClass); + if (ns.getNamespaces().length === 0) { + finalNamespaces.push(ns); + } else { + for (const nsns of ns.getNamespaces()) { + namespaceStack.push(nsns); + parentMap.set(nsns, ns); + } + } + } + } + + private addNSExportedClasses(finalNamespaces: ArkNamespace[], + classMap: Map, + parentMap: Map): void { + while (finalNamespaces.length > 0) { + const finalNS = finalNamespaces.shift()!; + const exportClass = []; + for (const arkClass of finalNS.getClasses()) { + if (arkClass.isExported()) { + exportClass.push(arkClass); + } + } + const parent = parentMap.get(finalNS)!; + if (parent instanceof ArkNamespace) { + classMap.get(parent.getNamespaceSignature())?.push(...exportClass); + } else if (parent instanceof ArkFile) { + classMap.get(parent.getFileSignature())?.push(...exportClass); + } + let p = finalNS; + while (!(parentMap.get(p) instanceof ArkFile) && p.isExported()) { + const grandParent = parentMap.get(parentMap.get(p)! as ArkNamespace); + if (grandParent instanceof ArkNamespace) { + classMap.get(grandParent.getNamespaceSignature())?.push(...exportClass); + p = parentMap.get(p)! as ArkNamespace; + } else if (grandParent instanceof ArkFile) { + classMap.get(grandParent.getFileSignature())?.push(...exportClass); + break; + } + } + if (parent instanceof ArkNamespace && !finalNamespaces.includes(parent)) { + finalNamespaces.push(parent); + } + } + } + + private addFileImportedClasses(file: ArkFile, classMap: Map): void { + const importClasses: ArkClass[] = []; + const importNameSpaces: ArkNamespace[] = []; + for (const importInfo of file.getImportInfos()) { + const importClass = ModelUtils.getClassInImportInfoWithName(importInfo.getImportClauseName(), file); + if (importClass && !importClasses.includes(importClass)) { + importClasses.push(importClass); + continue; + } + const importNameSpace = ModelUtils.getNamespaceInImportInfoWithName(importInfo.getImportClauseName(), file); + if (importNameSpace && !importNameSpaces.includes(importNameSpace)) { + try { + // 遗留问题:只统计了项目文件的namespace,没统计sdk文件内部的引入 + const importNameSpaceClasses = classMap.get(importNameSpace.getNamespaceSignature())!; + importClasses.push(...importNameSpaceClasses.filter(c => !importClasses.includes(c) && c.getName() !== DEFAULT_ARK_CLASS_NAME)); + } catch { + } + + } + } + const fileClasses = classMap.get(file.getFileSignature())!; + fileClasses.push(...importClasses.filter(c => !fileClasses.includes(c))); + // 子节点加上父节点的class + const namespaceStack = [...file.getNamespaces()]; + for (const ns of namespaceStack) { + const nsClasses = classMap.get(ns.getNamespaceSignature())!; + nsClasses.push(...fileClasses.filter(c => !nsClasses.includes(c) && c.getName() !== DEFAULT_ARK_CLASS_NAME)); + } + while (namespaceStack.length > 0) { + const ns = namespaceStack.shift()!; + const nsClasses = classMap.get(ns.getNamespaceSignature())!; + for (const nsns of ns.getNamespaces()) { + const nsnsClasses = classMap.get(nsns.getNamespaceSignature())!; + nsnsClasses.push(...nsClasses.filter(c => !nsnsClasses.includes(c) && c.getName() !== DEFAULT_ARK_CLASS_NAME)); + namespaceStack.push(nsns); + } + } + } + + public getClassMap(): Map { + const classMap: Map = new Map(); + for (const file of this.getFiles()) { + const fileClass: ArkClass[] = []; + const namespaceStack: ArkNamespace[] = []; + const parentMap: Map = new Map(); + const finalNamespaces: ArkNamespace[] = []; + for (const arkClass of file.getClasses()) { + fileClass.push(arkClass); + } + for (const ns of file.getNamespaces()) { + namespaceStack.push(ns); + parentMap.set(ns, file); + } + + classMap.set(file.getFileSignature(), fileClass); + // 第一轮遍历,加上每个namespace自己的class + this.addNSClasses(namespaceStack, finalNamespaces, classMap, parentMap); + + // 第二轮遍历,父节点加上子节点的export的class + this.addNSExportedClasses(finalNamespaces, classMap, parentMap); + } + + for (const file of this.getFiles()) { + // 文件加上import的class,包括ns的 + this.addFileImportedClasses(file, classMap); + } + return classMap; + } + + private addNSLocals(namespaceStack: ArkNamespace[], finalNamespaces: ArkNamespace[], + parentMap: Map, + globalVariableMap: Map): void { + while (namespaceStack.length > 0) { + const ns = namespaceStack.shift()!; + const nsGlobalLocals: Local[] = []; + ns.getDefaultClass().getDefaultArkMethod()!.getBody()?.getLocals().forEach(local => { + if (local.getDeclaringStmt() && local.getName() !== 'this' && local.getName()[0] !== '$') { + nsGlobalLocals.push(local); + } + }); + globalVariableMap.set(ns.getNamespaceSignature(), nsGlobalLocals); + if (ns.getNamespaces().length === 0) { + finalNamespaces.push(ns); + } else { + for (const nsns of ns.getNamespaces()) { + namespaceStack.push(nsns); + parentMap.set(nsns, ns); + } + } + } + } + + private addNSExportedLocals(finalNamespaces: ArkNamespace[], + globalVariableMap: Map, + parentMap: Map): void { + while (finalNamespaces.length > 0) { + const finalNS = finalNamespaces.shift()!; + const exportLocal = []; + for (const exportInfo of finalNS.getExportInfos()) { + if (exportInfo.getExportClauseType() === ExportType.LOCAL && exportInfo.getArkExport()) { + exportLocal.push(exportInfo.getArkExport() as Local); + } + } + const parent = parentMap.get(finalNS)!; + if (parent instanceof ArkNamespace) { + globalVariableMap.get(parent.getNamespaceSignature())?.push(...exportLocal); + } else if (parent instanceof ArkFile) { + globalVariableMap.get(parent.getFileSignature())?.push(...exportLocal); + } + let p = finalNS; + while (!(parentMap.get(p) instanceof ArkFile) && p.isExported()) { + const grandParent = parentMap.get(parentMap.get(p)! as ArkNamespace); + if (grandParent instanceof ArkNamespace) { + globalVariableMap.get(grandParent.getNamespaceSignature())?.push(...exportLocal); + p = parentMap.get(p)! as ArkNamespace; + } else if (grandParent instanceof ArkFile) { + globalVariableMap.get(grandParent.getFileSignature())?.push(...exportLocal); + break; + } + } + if (parent instanceof ArkNamespace && !finalNamespaces.includes(parent)) { + finalNamespaces.push(parent); + } + } + } + + private addFileImportLocals(file: ArkFile, globalVariableMap: Map): void { + const importLocals: Local[] = []; + const importNameSpaces: ArkNamespace[] = []; + for (const importInfo of file.getImportInfos()) { + const importLocal = ModelUtils.getLocalInImportInfoWithName(importInfo.getImportClauseName(), file); + if (importLocal && !importLocals.includes(importLocal)) { + importLocals.push(importLocal); + } + const importNameSpace = ModelUtils.getNamespaceInImportInfoWithName(importInfo.getImportClauseName(), file); + if (importNameSpace && !importNameSpaces.includes(importNameSpace)) { + try { + // 遗留问题:只统计了项目文件,没统计sdk文件内部的引入 + const importNameSpaceClasses = globalVariableMap.get(importNameSpace.getNamespaceSignature())!; + importLocals.push(...importNameSpaceClasses.filter(c => !importLocals.includes(c) && c.getName() !== DEFAULT_ARK_CLASS_NAME)); + } catch { + } + + } + } + const fileLocals = globalVariableMap.get(file.getFileSignature())!; + fileLocals.push(...importLocals.filter(c => !fileLocals.includes(c))); + // 子节点加上父节点的local + const namespaceStack = [...file.getNamespaces()]; + for (const ns of namespaceStack) { + const nsLocals = globalVariableMap.get(ns.getNamespaceSignature())!; + const nsLocalNameSet = new Set(nsLocals.map(item => item.getName())); + for (const local of fileLocals) { + if (!nsLocalNameSet.has(local.getName())) { + nsLocals.push(local); + } + } + } + while (namespaceStack.length > 0) { + const ns = namespaceStack.shift()!; + const nsLocals = globalVariableMap.get(ns.getNamespaceSignature())!; + for (const nsns of ns.getNamespaces()) { + this.handleNestedNSLocals(nsns, nsLocals, globalVariableMap); + namespaceStack.push(nsns); + } + } + } + + private handleNestedNSLocals(nsns: ArkNamespace, nsLocals: Local[], + globalVariableMap: Map): void { + const nsnsLocals = globalVariableMap.get(nsns.getNamespaceSignature())!; + const nsnsLocalNameSet = new Set(nsnsLocals.map(item => item.getName())); + for (const local of nsLocals) { + if (!nsnsLocalNameSet.has(local.getName())) { + nsnsLocals.push(local); + } + } + } + + public getGlobalVariableMap(): Map { + const globalVariableMap: Map = new Map(); + for (const file of this.getFiles()) { + const namespaceStack: ArkNamespace[] = []; + const parentMap: Map = new Map(); + const finalNamespaces: ArkNamespace[] = []; + const globalLocals: Local[] = []; + file.getDefaultClass()?.getDefaultArkMethod()!.getBody()?.getLocals().forEach(local => { + if (local.getDeclaringStmt() && local.getName() !== 'this' && local.getName()[0] !== '$') { + globalLocals.push(local); + } + }); + globalVariableMap.set(file.getFileSignature(), globalLocals); + for (const ns of file.getNamespaces()) { + namespaceStack.push(ns); + parentMap.set(ns, file); + } + // 第一轮遍历,加上每个namespace自己的local + this.addNSLocals(namespaceStack, finalNamespaces, parentMap, globalVariableMap); + + // 第二轮遍历,父节点加上子节点的export的local + this.addNSExportedLocals(finalNamespaces, globalVariableMap, parentMap); + } + + for (const file of this.getFiles()) { + // 文件加上import的local,包括ns的 + this.addFileImportLocals(file, globalVariableMap); + } + return globalVariableMap; + } + + public getStaticInitMethods(): ArkMethod[] { + const staticInitMethods: ArkMethod[] = []; + for (const method of Array.from(this.getMethodsMap(true).values())) { + if (method.getName() === STATIC_INIT_METHOD_NAME) { + staticInitMethods.push(method); + } + } + return staticInitMethods; + } + + public buildClassDone(): boolean { + return this.buildStage >= SceneBuildStage.CLASS_DONE; + } + + public getModuleScene(moduleName: string) { + return this.moduleScenesMap.get(moduleName); + } + + public getModuleSceneMap(): Map { + return this.moduleScenesMap; + } + + public getGlobalModule2PathMapping(): { [k: string]: string[]; } | undefined { + return this.globalModule2PathMapping; + } + + public getbaseUrl(): string | undefined { + return this.baseUrl; + } +} + +export class ModuleScene { + private projectScene: Scene; + private moduleName: string = ''; + private modulePath: string = ''; + private moduleFileMap: Map = new Map(); + + private moduleOhPkgFilePath: string = ''; + private ohPkgContent: { [k: string]: unknown } = {}; + + constructor(projectScene: Scene) { + this.projectScene = projectScene; + } + + public ModuleSceneBuilder(moduleName: string, modulePath: string, supportFileExts: string[], recursively: boolean = false): void { + this.moduleName = moduleName; + this.modulePath = modulePath; + + this.getModuleOhPkgFilePath(); + + if (this.moduleOhPkgFilePath) { + this.ohPkgContent = fetchDependenciesFromFile(this.moduleOhPkgFilePath); + } else { + logger.warn('This module has no oh-package.json5!'); + } + this.genArkFiles(supportFileExts); + } + + public ModuleScenePartiallyBuilder(moduleName: string, modulePath: string): void { + this.moduleName = moduleName; + this.modulePath = modulePath; + if (this.moduleOhPkgFilePath) { + this.ohPkgContent = fetchDependenciesFromFile(this.moduleOhPkgFilePath); + } else { + logger.warn('This module has no oh-package.json5!'); + } + } + + /** + * get oh-package.json5 + */ + private getModuleOhPkgFilePath() { + const moduleOhPkgFilePath = path.resolve(this.projectScene.getRealProjectDir(), path.join(this.modulePath, OH_PACKAGE_JSON5)); + if (fs.existsSync(moduleOhPkgFilePath)) { + this.moduleOhPkgFilePath = moduleOhPkgFilePath; + } + } + + /** + * get nodule name + * @returns return module name + */ + public getModuleName(): string { + return this.moduleName; + } + + public getModulePath(): string { + return this.modulePath; + } + + public getOhPkgFilePath() { + return this.moduleOhPkgFilePath; + } + + public getOhPkgContent() { + return this.ohPkgContent; + } + + public getModuleFilesMap(): Map { + return this.moduleFileMap; + } + + public addArkFile(arkFile: ArkFile): void { + this.moduleFileMap.set(arkFile.getFileSignature().toMapKey(), arkFile); + } + + private genArkFiles(supportFileExts: string[]) { + getAllFiles(this.modulePath, supportFileExts, this.projectScene.getOptions().ignoreFileNames).forEach((file) => { + logger.info('=== parse file:', file); + try { + const arkFile: ArkFile = new ArkFile(FileUtils.getFileLanguage(file, this.projectScene.getFileLanguages())); + arkFile.setScene(this.projectScene); + arkFile.setModuleScene(this); + buildArkFileFromFile(file, this.projectScene.getRealProjectDir(), arkFile, + this.projectScene.getProjectName()); + this.projectScene.setFile(arkFile); + } catch (error) { + logger.error('Error parsing file:', file, error); + this.projectScene.getUnhandledFilePaths().push(file); + return; + } + }); + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/VFG/DVFG.ts b/ets2panda/linter/arkanalyzer/src/VFG/DVFG.ts new file mode 100644 index 0000000000..cdf1b3ee10 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/VFG/DVFG.ts @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BaseEdge, BaseExplicitGraph, BaseNode, NodeID } from '../core/graph/BaseExplicitGraph'; +import { CallGraph } from '../callgraph/model/CallGraph'; +import { ArkAssignStmt, Stmt } from '../core/base/Stmt'; +import { GraphPrinter } from '../save/GraphPrinter'; +import { PrinterBuilder } from '../save/PrinterBuilder'; + +/** + * Direct value flow graph + * Consist of stmt(node) and direct Def-Use edge + * Is basic of VFG. And VFG is building on DVFG + */ +export class DVFG extends BaseExplicitGraph { + private cg: CallGraph; + private stmtToVFGMap: Map; + constructor(cg: CallGraph) { + super(); + this.cg = cg; + this.stmtToVFGMap = new Map(); + } + + public getCG(): CallGraph { + return this.cg; + } + + public getGraphName(): string { + return 'Direct-VFG'; + } + + public getOrNewDVFGNode(stmt: Stmt): DVFGNode { + let node = this.stmtToVFGMap.get(stmt); + if (node) { + return this.getNode(node)! as DVFGNode; + } + + let kind: DVFGNodeKind = DVFGNodeKind.normal; + if (stmt instanceof ArkAssignStmt) { + //TODO: split assign to copy, write, load + kind = DVFGNodeKind.assign; + } else { + // TODO: handle other type of stmt + } + + return this.addDVFGNode(stmt, kind); + } + + public addDVFGNode(stmt: Stmt, kind: DVFGNodeKind): DVFGNode { + let id: NodeID = this.nodeNum; + let dvfgNode = new DVFGNode(id, kind, stmt); + + this.addNode(dvfgNode); + this.stmtToVFGMap.set(stmt, dvfgNode.getID()); + return dvfgNode; + } + + public addDVFGEdge(src: DVFGNode, dst: DVFGNode): boolean { + let kind = 0; //common kind + let edge = new DVFGEdge(src, dst, kind); + if (this.ifEdgeExisting(edge)) { + return false; + } + + src.addOutgoingEdge(edge); + dst.addIncomingEdge(edge); + + return true; + } + + public dump(name: string): void { + let printer = new GraphPrinter(this); + PrinterBuilder.dump(printer, name); + } +} + +export enum DVFGNodeKind { + assign, copy, write, load, addr, if, actualParm, formalParm, actualRet, + formalRet, unary, binary, normal +} + +export class DVFGNode extends BaseNode { + private stmt: Stmt; + + constructor(i: NodeID, k: DVFGNodeKind, s: Stmt) { + super(i, k); + this.stmt = s; + } + + public getDotLabel(): string { + let label: string = 'ID: ' + this.getID() + '\n'; + label = label + this.stmt.toString(); + return label; + } + + public getStmt(): Stmt { + return this.stmt; + } +} + +export class DVFGEdge extends BaseEdge {} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/VFG/builder/DVFGBuilder.ts b/ets2panda/linter/arkanalyzer/src/VFG/builder/DVFGBuilder.ts new file mode 100644 index 0000000000..51bb4fb007 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/VFG/builder/DVFGBuilder.ts @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Constant } from '../../core/base/Constant'; +import { AbstractExpr, AbstractInvokeExpr } from '../../core/base/Expr'; +import { AbstractFieldRef } from '../../core/base/Ref'; +import { ArkAssignStmt, ArkInvokeStmt, ArkIfStmt, ArkReturnStmt, ArkThrowStmt, Stmt, ArkReturnVoidStmt, ArkAliasTypeDefineStmt } from '../../core/base/Stmt'; +import { Value } from '../../core/base/Value'; +import { DummyStmt } from '../../core/common/ArkIRTransformer'; +import { MFPDataFlowSolver } from '../../core/dataflow/GenericDataFlow'; +import { ReachingDefProblem } from '../../core/dataflow/ReachingDef'; +import { NodeID } from '../../core/graph/BaseExplicitGraph'; +import { ArkMethod } from '../../core/model/ArkMethod'; +import { FieldSignature } from '../../core/model/ArkSignature'; +import { Scene } from '../../Scene'; +import { DVFG } from '../DVFG'; + +export class DVFGBuilder { + private dvfg: DVFG; + private scene: Scene; + + constructor(dvfg: DVFG, s: Scene) { + this.dvfg = dvfg; + this.scene = s; + } + + public build() { + this.scene.getMethods().forEach(m => { if (m.getCfg()) { this.buildForSingleMethod(m) } }); + } + + public buildForSingleMethod(m: ArkMethod) { + let problem = new ReachingDefProblem(m); + let solver = new MFPDataFlowSolver(); + let solution = solver.calculateMopSolutionForwards(problem); + + let defMap = new Map>(); + m.getCfg()!.getStmts().forEach((s) => { + let def: Value | FieldSignature | null = s.getDef(); + if (def != null) { + if (def instanceof AbstractFieldRef) { + def = def.getFieldSignature(); + } + let defStmts = defMap.get(def) ?? new Set(); + defStmts.add(s); + defMap.set(def, defStmts); + } + }); + + solution.in.forEach((defs, reach) => { + let addNewNodes = (defId: NodeID, def: Stmt, reach: Stmt): void => { + if (defs.test(defId)) { + let srcNode = this.dvfg.getOrNewDVFGNode(def); + let dstNode = this.dvfg.getOrNewDVFGNode(reach); + this.dvfg.addDVFGEdge(srcNode, dstNode); + } + }; + + const reachStmt = problem.flowGraph.getNode(reach); + this.getStmtUsedValues(reachStmt).forEach(use => { + let target: Value | FieldSignature = use; + if (target instanceof AbstractFieldRef) { + target = target.getFieldSignature(); + } + defMap.get(target)?.forEach((defStmt) => { + let defId = problem.flowGraph.getNodeID(defStmt); + addNewNodes(defId, defStmt, reachStmt); + }); + }); + }); + } + + private getStmtUsedValues(stmt: Stmt): Value[] { + if (stmt instanceof ArkAssignStmt) { + return this.getUsedValues(stmt.getRightOp()); + } else if (stmt instanceof ArkInvokeStmt) { + return this.getUsedValues(stmt.getInvokeExpr()); + } else if (stmt instanceof ArkIfStmt) { + return this.getUsedValues(stmt.getConditionExpr()); + } else if (stmt instanceof ArkReturnStmt) { + return this.getUsedValues(stmt.getOp()); + } else if (stmt instanceof ArkThrowStmt) { + return this.getUsedValues(stmt.getOp()); + } else if (stmt instanceof ArkReturnVoidStmt || stmt instanceof ArkAliasTypeDefineStmt || stmt instanceof DummyStmt) { + return []; + } else { + throw new Error('unsupported stmt'); + } + } + + private getUsedValues(val: Value): Value[] { + if (val instanceof AbstractExpr) { + if (val instanceof AbstractInvokeExpr) { + return val.getArgs().flatMap((current) => { return this.getUsedValues(current) }, []); + } else { + return val.getUses().flatMap((current) => { return this.getUsedValues(current) }, []); + } + } + if (val instanceof Constant) { + return []; + } + return [val]; + } + + public getOrNewDVFGNode(stmt: Stmt) { + return this.dvfg.getOrNewDVFGNode(stmt); + } + + public addDVFGNodes(): void { } + + public addDVFGEdges(): void { } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/algorithm/AbstractAnalysis.ts b/ets2panda/linter/arkanalyzer/src/callgraph/algorithm/AbstractAnalysis.ts new file mode 100644 index 0000000000..5c543b1c49 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/callgraph/algorithm/AbstractAnalysis.ts @@ -0,0 +1,161 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Scene } from '../../Scene'; +import { AbstractInvokeExpr } from '../../core/base/Expr'; +import { Stmt } from '../../core/base/Stmt'; +import { FunctionType } from '../../core/base/Type'; +import { ArkClass } from '../../core/model/ArkClass'; +import { ArkMethod } from '../../core/model/ArkMethod'; +import { MethodSignature } from '../../core/model/ArkSignature'; +import Logger, { LOG_MODULE_TYPE } from '../../utils/logger'; +import { NodeID } from '../../core/graph/BaseExplicitGraph'; +import { CallGraph, FuncID, CallSite, CallGraphNode } from '../model/CallGraph'; +import { CallGraphBuilder } from '../model/builder/CallGraphBuilder'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'CG'); + +export abstract class AbstractAnalysis { + protected scene: Scene; + protected cg!: CallGraph; + protected cgBuilder!: CallGraphBuilder; + protected workList: FuncID[] = []; + protected processedMethod!: Set; + + constructor(s: Scene) { + this.scene = s; + } + + public getScene(): Scene { + return this.scene; + } + + public getCallGraph(): CallGraph { + return this.cg; + } + + protected abstract resolveCall(sourceMethod: NodeID, invokeStmt: Stmt): CallSite[]; + protected abstract preProcessMethod(funcID: FuncID): CallSite[]; + + public resolveInvokeExpr(invokeExpr: AbstractInvokeExpr): ArkMethod | undefined { + const method = this.scene.getMethod(invokeExpr.getMethodSignature()); + if (method != null) { + return method; + } + } + + public getClassHierarchy(arkClass: ArkClass): ArkClass[] { + // TODO: remove abstract class + let classWorkList: ArkClass[] = [arkClass]; + // TODO: check class with no super Class + let classHierarchy: ArkClass[] = []; + + while (classWorkList.length > 0) { + // TODO: no dumplicated check, TS doesn't allow multi extend + let tempClass = classWorkList.shift()!; + classWorkList.push(...tempClass.getExtendedClasses().values()); + classHierarchy.push(tempClass); + } + + return classHierarchy; + } + + public start(displayGeneratedMethod: boolean): void { + this.init(); + while (this.workList.length !== 0) { + const method = this.workList.shift() as FuncID; + const cgNode = this.cg.getNode(method) as CallGraphNode; + + if (this.processedMethod.has(method) || cgNode.isSdkMethod()) { + continue; + } + + // pre process for RTA only + this.preProcessMethod(method).forEach((cs: CallSite) => { + this.workList.push(cs.calleeFuncID); + }) + + this.processMethod(method).forEach((cs: CallSite) => { + let me = this.cg.getArkMethodByFuncID(cs.calleeFuncID); + + this.addCallGraphEdge(method, me, cs, displayGeneratedMethod); + + if (!this.processedMethod.has(cs.calleeFuncID)) { + this.workList.push(cs.calleeFuncID); + logger.info(`New workList item ${cs.calleeFuncID}: ${this.cg.getArkMethodByFuncID(cs.calleeFuncID)?.getSignature().toString()}`); + + this.processedMethod.add(cs.callerFuncID); + } + }) + } + } + + protected init(): void { + this.processedMethod = new Set(); + this.cg.getEntries().forEach((entryFunc) => { + this.workList.push(entryFunc); + }) + } + + protected processMethod(methodID: FuncID): CallSite[] { + let cgNode = this.cg.getNode(methodID) as CallGraphNode; + let arkMethod = this.scene.getMethod(cgNode.getMethod(), true); + let calleeMethods: CallSite[] = []; + + if (!arkMethod) { + throw new Error("can not find method"); + } + + const cfg = arkMethod.getCfg(); + if (!cfg) { + return []; + } + cfg.getStmts().forEach((stmt) => { + if (stmt.containsInvokeExpr()) { + this.resolveCall(cgNode.getID(), stmt).forEach((callSite) => { + calleeMethods.push(callSite); + this.cg.addStmtToCallSiteMap(stmt, callSite); + this.cg.addMethodToCallSiteMap(callSite.calleeFuncID, callSite); + }); + } + }) + + return calleeMethods; + } + + protected getParamAnonymousMethod(invokeExpr: AbstractInvokeExpr): MethodSignature[] { + let paramMethod: MethodSignature[] = []; + + invokeExpr.getArgs().forEach((args) => { + let argsType = args.getType(); + if (argsType instanceof FunctionType) { + paramMethod.push(argsType.getMethodSignature()); + } + }); + + return paramMethod; + } + + protected addCallGraphEdge(caller: FuncID, callee: ArkMethod | null, cs: CallSite, displayGeneratedMethod: boolean): void { + // check if need to display generated method + if (!callee) { + logger.error(`FuncID has no method ${cs.calleeFuncID}`); + } else { + if (displayGeneratedMethod || !(callee?.isGenerated())) { + this.cg.addDynamicCallEdge(caller, cs.calleeFuncID, cs.callStmt); + } + } + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/algorithm/ClassHierarchyAnalysis.ts b/ets2panda/linter/arkanalyzer/src/callgraph/algorithm/ClassHierarchyAnalysis.ts new file mode 100644 index 0000000000..f086c8267d --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/callgraph/algorithm/ClassHierarchyAnalysis.ts @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkStaticInvokeExpr } from '../../core/base/Expr'; +import { Scene } from '../../Scene'; +import { Stmt } from '../../core/base/Stmt'; +import { ArkClass } from '../../core/model/ArkClass'; +import { NodeID } from '../../core/graph/BaseExplicitGraph'; +import { CallGraph, CallSite } from '../model/CallGraph'; +import { AbstractAnalysis } from './AbstractAnalysis'; + +export class ClassHierarchyAnalysis extends AbstractAnalysis { + + constructor(scene: Scene, cg: CallGraph) { + super(scene); + this.cg = cg; + } + + public resolveCall(callerMethod: NodeID, invokeStmt: Stmt): CallSite[] { + let invokeExpr = invokeStmt.getInvokeExpr(); + let resolveResult: CallSite[] = []; + + if (!invokeExpr) { + return []; + } + + // process anonymous method call + this.getParamAnonymousMethod(invokeExpr).forEach(method => { + resolveResult.push( + new CallSite(invokeStmt, undefined, + this.cg.getCallGraphNodeByMethod(method).getID(), callerMethod + ) + ); + }); + + let calleeMethod = this.resolveInvokeExpr(invokeExpr); + if (!calleeMethod) { + return resolveResult; + } + if (invokeExpr instanceof ArkStaticInvokeExpr) { + // get specific method + resolveResult.push(new CallSite(invokeStmt, undefined, + this.cg.getCallGraphNodeByMethod(calleeMethod!.getSignature()).getID(), + callerMethod!)); + } else { + let declareClass = calleeMethod.getDeclaringArkClass(); + // TODO: super class method should be placed at the end + this.getClassHierarchy(declareClass).forEach((arkClass: ArkClass) => { + if (arkClass.isAbstract()) { + return; + } + + let possibleCalleeMethod = arkClass.getMethodWithName(calleeMethod!.getName()); + + if (possibleCalleeMethod && possibleCalleeMethod.isGenerated() && + arkClass.getSignature().toString() !== declareClass.getSignature().toString()) { + // remove the generated method in extended classes + return; + } + + if (possibleCalleeMethod && !possibleCalleeMethod.isAbstract()) { + resolveResult.push( + new CallSite(invokeStmt, undefined, + this.cg.getCallGraphNodeByMethod(possibleCalleeMethod.getSignature()).getID(), + callerMethod + ) + ); + } + }); + } + + return resolveResult; + } + + protected preProcessMethod(): CallSite[] { + // do nothing + return []; + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/algorithm/RapidTypeAnalysis.ts b/ets2panda/linter/arkanalyzer/src/callgraph/algorithm/RapidTypeAnalysis.ts new file mode 100644 index 0000000000..1e447e6dcc --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/callgraph/algorithm/RapidTypeAnalysis.ts @@ -0,0 +1,156 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkNewExpr, ArkStaticInvokeExpr } from '../../core/base/Expr'; +import { Scene } from '../../Scene'; +import { Stmt } from '../../core/base/Stmt'; +import { ArkClass } from '../../core/model/ArkClass'; +import { ClassSignature } from '../../core/model/ArkSignature'; +import { NodeID } from '../../core/graph/BaseExplicitGraph'; +import { CallGraph, CallSite, FuncID } from '../model/CallGraph'; +import { AbstractAnalysis } from './AbstractAnalysis'; +import Logger, { LOG_MODULE_TYPE } from '../../utils/logger'; +import { ClassType } from '../../core/base/Type'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'RTA'); + +export class RapidTypeAnalysis extends AbstractAnalysis { + // TODO: signature duplicated check + private instancedClasses: Set = new Set(); + // TODO: Set duplicated check + private ignoredCalls: Map> = new Map(); + + constructor(scene: Scene, cg: CallGraph) { + super(scene); + this.cg = cg; + } + + public resolveCall(callerMethod: NodeID, invokeStmt: Stmt): CallSite[] { + let invokeExpr = invokeStmt.getInvokeExpr(); + let resolveResult: CallSite[] = []; + + if (!invokeExpr) { + return []; + } + + // process anonymous method call + this.getParamAnonymousMethod(invokeExpr).forEach(method => { + resolveResult.push(new CallSite(invokeStmt, undefined, + this.cg.getCallGraphNodeByMethod(method).getID(), callerMethod) + ); + }); + + let calleeMethod = this.resolveInvokeExpr(invokeExpr); + if (!calleeMethod) { + return resolveResult; + } + + if (invokeExpr instanceof ArkStaticInvokeExpr) { + // get specific method + resolveResult.push(new CallSite(invokeStmt, undefined, + this.cg.getCallGraphNodeByMethod(calleeMethod.getSignature()).getID(), callerMethod) + ); + } else { + let declareClass = calleeMethod!.getDeclaringArkClass(); + // TODO: super class method should be placed at the end + this.getClassHierarchy(declareClass).forEach((arkClass: ArkClass) => { + if (arkClass.isAbstract()) { + return; + } + + let possibleCalleeMethod = arkClass.getMethodWithName(calleeMethod!.getName()); + + if (possibleCalleeMethod && possibleCalleeMethod.isGenerated() && + arkClass.getSignature().toString() !== declareClass.getSignature().toString()) { + // remove the generated method in extended classes + return; + } + + if (!(possibleCalleeMethod && !possibleCalleeMethod.isAbstract())) { + return; + } + + if (!this.instancedClasses.has(arkClass.getSignature())) { + this.addIgnoredCalls(arkClass.getSignature(), callerMethod, + this.cg.getCallGraphNodeByMethod(possibleCalleeMethod.getSignature()).getID(), + invokeStmt + ); + } else { + resolveResult.push(new CallSite(invokeStmt, undefined, + this.cg.getCallGraphNodeByMethod(possibleCalleeMethod.getSignature()).getID(), + callerMethod) + ); + } + }); + } + + return resolveResult; + } + + protected preProcessMethod(funcID: FuncID): CallSite[] { + let newCallSites: CallSite[] = []; + let instancedClasses: Set = this.collectInstancedClassesInMethod(funcID); + let newlyInstancedClasses = new Set( + Array.from(instancedClasses).filter(item => !this.instancedClasses.has(item)) + ); + + newlyInstancedClasses.forEach(sig => { + let ignoredCalls = this.ignoredCalls.get(sig) + if (ignoredCalls) { + ignoredCalls.forEach((call) => { + this.cg.addDynamicCallEdge(call.caller, call.callee, call.callStmt); + newCallSites.push(new CallSite(call.callStmt, undefined, call.callee, call.caller)); + }); + } + this.instancedClasses.add(sig); + this.ignoredCalls.delete(sig); + }); + return newCallSites; + } + + private collectInstancedClassesInMethod(funcID: FuncID) { + let instancedClasses: Set = new Set(); + let arkMethod = this.cg.getArkMethodByFuncID(funcID); + + if (!arkMethod) { + logger.error(`can not find arkMethod by funcID`); + return instancedClasses; + } + + let cfg = arkMethod!.getCfg(); + if (!cfg) { + logger.error(`arkMethod ${arkMethod.getSignature().toString()} has no cfg`); + return instancedClasses; + } + + for (let stmt of cfg!.getStmts()) { + let stmtExpr = stmt.getExprs()[0]; + if (stmtExpr instanceof ArkNewExpr) { + let classSig: ClassSignature = (stmtExpr.getType() as ClassType).getClassSignature(); + if (classSig != null) { + // TODO: need to check if different stmt has single sig + instancedClasses.add(classSig); + } + } + } + return instancedClasses; + } + + public addIgnoredCalls(arkClass: ClassSignature, callerID: FuncID, calleeID: FuncID, invokeStmt: Stmt) { + let classMap = this.ignoredCalls.get(arkClass) ?? new Set(); + classMap.add({ caller: callerID, callee: calleeID, callStmt: invokeStmt }); + this.ignoredCalls.set(arkClass, classMap); + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/common/Statistics.ts b/ets2panda/linter/arkanalyzer/src/callgraph/common/Statistics.ts new file mode 100644 index 0000000000..e3b41aeaa9 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/callgraph/common/Statistics.ts @@ -0,0 +1,226 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkAssignStmt, Stmt } from "../../core/base/Stmt"; +import { UnknownType } from "../../core/base/Type"; +import { CallGraphNode, CallGraphNodeKind } from "../model/CallGraph"; +import { PointerAnalysis } from "../pointerAnalysis/PointerAnalysis"; +import Logger, { LOG_MODULE_TYPE } from "../../utils/logger"; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'PTA'); + +abstract class StatTraits { + public getStat(): string { + return ''; + } + + public printStat(): void { + logger.trace(this.getStat()); + } +} + +export class PTAStat implements StatTraits { + pta: PointerAnalysis; + numProcessedAddr: number = 0; + numProcessedCopy: number = 0; + numProcessedLoad: number = 0; + numProcessedWrite: number = 0; + numProcessedThis: number = 0; + numRealWrite: number = 0; + numRealLoad: number = 0; + + numUnhandledFun: number = 0; + numTotalValuesInHandedFun: number = 0; + numTotalHandledValue: number = 0; + + // Original type is UnknownType but inferred by PTA + numInferedUnknownValue: number = 0; + // Original type is not UnknownType and inferred with different type by PTA + numInferedDiffTypeValue: number = 0; + // Total number of values in the functions visited by PTA + totalValuesInVisitedFunc: number = 0; + // Original type is UnkonwnType and not inferred by PTA as well + numNotInferedUnknownValue: number = 0; + numUnhandledFunc: number = 0; + + iterTimes: number = 0; + TotalTime: number = 0; + + startTime: number = 0; + endTime: number = 0; + + startMemUsage: any; + endMemUsage: any; + rssUsed: number = 0; + heapUsed: number = 0; + + constructor(pta: PointerAnalysis) { + this.pta = pta; + } + + public startStat(): void { + this.startTime = this.getNow(); + this.startMemUsage = process.memoryUsage(); + } + + public endStat(): void { + this.endTime = this.getNow(); + this.endMemUsage = process.memoryUsage(); + this.TotalTime = (this.endTime - this.startTime) / 1000; + this.rssUsed = Number(this.endMemUsage.rss - this.startMemUsage.rss) / Number(1024 * 1024); + this.heapUsed = Number(this.endMemUsage.heapTotal - this.startMemUsage.heapTotal) / Number(1024 * 1024); + this.getInferedStat(); + this.getUnhandledFuncStat(); + } + + public getNow(): number { + return new Date().getTime(); + } + + private getInferedStat(): void { + let stmtStat = (s: Stmt): void => { + if (!(s instanceof ArkAssignStmt)) { + return; + } + + let lop = s.getLeftOp(); + if (visited.has(lop)) { + return; + } + visited.add(lop); + + if (inferred.includes(lop)) { + if (lop.getType() instanceof UnknownType) { + this.numInferedUnknownValue++; + } else { + this.numInferedDiffTypeValue++; + } + } else { + if (lop.getType() instanceof UnknownType) { + this.numNotInferedUnknownValue++; + } + } + this.totalValuesInVisitedFunc++; + }; + + let inferred = Array.from(this.pta.getTypeDiffMap().keys()); + let visited = new Set(); + + let cg = this.pta.getCallGraph(); + this.pta.getHandledFuncs().forEach(funcID => { + let f = cg.getArkMethodByFuncID(funcID); + f?.getCfg()?.getStmts().forEach(s => stmtStat(s)); + }); + } + + private getUnhandledFuncStat(): void { + let cg = this.pta.getCallGraph(); + this.pta.getUnhandledFuncs().forEach(funcID => { + let cgNode = cg.getNode(funcID); + if ((cgNode as CallGraphNode).isSdkMethod()) { + return; + } + + let f = cg.getArkMethodByFuncID(funcID); + if (f) { + this.numUnhandledFun++; + } + }); + } + + public getStat(): string { + // TODO: get PAG stat and CG stat + let output: string; + output = '==== Pointer analysis Statictics: ====\n' + output = output + `Processed address\t${this.numProcessedAddr}\n` + output = output + `Processed copy\t\t${this.numProcessedCopy}\n` + output = output + `Processed load\t\t${this.numProcessedLoad}\n` + output = output + `Processed write\t\t${this.numProcessedWrite}\n` + output = output + `Real write\t\t${this.numRealWrite}\n` + output = output + `Real load\t\t${this.numRealLoad}\n` + output = output + `Processed This\t\t${this.numProcessedThis}\n\n` + output = output + `Unhandled function\t${this.numUnhandledFun}\n` + output = output + `Total values in visited function\t${this.totalValuesInVisitedFunc}\n` + output = output + `Infered Value unknown+different type\t${this.numInferedUnknownValue}+${this.numInferedDiffTypeValue}\n\n` + output = output + `Total Time\t\t${this.TotalTime} S\n` + output = output + `Total iterator Times\t${this.iterTimes}\n` + output = output + `RSS used\t\t${this.rssUsed.toFixed(3)} Mb\n` + output = output + `Heap used\t\t${this.heapUsed.toFixed(3)} Mb\n` + return output; + + } + + public printStat(): void { + logger.trace(this.getStat()); + } +} + +export class PAGStat implements StatTraits { + numDynamicCall: number = 0; + numTotalFunction: number = 0; + numTotalNode: number = 0; + + public getStat(): string { + let output: string; + output = '==== PAG Statictics: ====\n' + output = output + `Dynamic call\t\t${this.numDynamicCall}\n` + output = output + `Total function handled\t${this.numTotalFunction}\n` + output = output + `Total PAG Nodes\t\t${this.numTotalNode}\n` + return output; + } + + public printStat(): void { + logger.trace(this.getStat()); + } +} + +export class CGStat extends StatTraits { + //real, vitual, intrinsic, constructor + numTotalNode: number = 0; + numReal: number = 0; + numVirtual: number = 0; + numIntrinsic: number = 0; + numConstructor: number = 0; + + public addNodeStat(kind: CallGraphNodeKind): void { + switch(kind) { + case CallGraphNodeKind.real: + this.numReal++; + break; + case CallGraphNodeKind.vitual: + this.numVirtual++; + break; + case CallGraphNodeKind.constructor: + this.numConstructor++; + break; + case CallGraphNodeKind.intrinsic: + this.numIntrinsic++; + break; + default: + } + this.numTotalNode++; + } + + public getStat(): string { + let output: string; + output = '==== CG Statictics: ====\n' + output = output + `Real function\t\t${this.numReal}\n` + output = output + `Intrinsic function\t${this.numIntrinsic}\n` + output = output + `Constructor function\t${this.numConstructor}\n` + output = output + `Blank function\t\t${this.numVirtual}\n` + output = output + `Total\t\t\t${this.numTotalNode}\n` + return output; + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/model/CallGraph.ts b/ets2panda/linter/arkanalyzer/src/callgraph/model/CallGraph.ts new file mode 100644 index 0000000000..78b2892088 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/callgraph/model/CallGraph.ts @@ -0,0 +1,462 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { MethodSignature } from '../../core/model/ArkSignature' +import { Stmt } from '../../core/base/Stmt' +import { Value } from '../../core/base/Value' +import { Scene } from '../../Scene'; +import { ArkMethod } from '../../core/model/ArkMethod'; +import { GraphPrinter } from '../../save/GraphPrinter'; +import { PrinterBuilder } from '../../save/PrinterBuilder'; +import { BaseEdge, BaseNode, BaseExplicitGraph, NodeID } from '../../core/graph/BaseExplicitGraph'; +import { CGStat } from '../common/Statistics'; +import { ContextID } from '../pointerAnalysis/Context'; +import { UNKNOWN_FILE_NAME } from '../../core/common/Const'; + +export type Method = MethodSignature; +export type CallSiteID = number; +export type FuncID = number; +type StmtSet = Set; + +export enum CallGraphNodeKind { + real, vitual, intrinsic, constructor +} + +export class CallSite { + public callStmt: Stmt; + public args: Value[] | undefined; + public calleeFuncID: FuncID; + public callerFuncID: FuncID; + + constructor(s: Stmt, a: Value[] | undefined, ce: FuncID, cr: FuncID) { + this.callStmt = s; + this.args = a; + this.calleeFuncID = ce; + this.callerFuncID = cr; + } +} + +export class DynCallSite { + public callerFuncID: FuncID; + public callStmt: Stmt; + public args: Value[] | undefined; + public protentialCalleeFuncID: FuncID | undefined; + + constructor(caller: FuncID, s: Stmt, a: Value[] | undefined, ptcCallee: FuncID | undefined) { + this.callerFuncID = caller; + this.callStmt = s; + this.args = a; + this.protentialCalleeFuncID = ptcCallee; + } +} + +export class CSCallSite extends CallSite { + public cid: ContextID; + + constructor(id: ContextID, cs: CallSite) { + super(cs.callStmt, cs.args, cs.calleeFuncID, cs.callerFuncID); + this.cid = id; + } +} + +export class CallGraphEdge extends BaseEdge { + private directCalls: StmtSet = new Set(); + private specialCalls: StmtSet = new Set(); + private indirectCalls: StmtSet = new Set(); + // private callSiteID: CallSiteID; + + constructor(src: CallGraphNode, dst: CallGraphNode) { + super(src, dst, 0); + } + + public addDirectCallSite(stmt: Stmt) { + this.directCalls.add(stmt); + } + + public addSpecialCallSite(stmt: Stmt) { + this.specialCalls.add(stmt); + } + + public addInDirectCallSite(stmt: Stmt) { + this.indirectCalls.add(stmt); + } + + public getDotAttr(): string { + const indirectCallNums: number = this.indirectCalls.size; + const directCallNums: number = this.directCalls.size; + const specialCallNums: number = this.specialCalls.size; + if ([CallGraphNodeKind.intrinsic, CallGraphNodeKind.constructor].includes(this.getDstNode().getKind())) { + return '' + } + + if (indirectCallNums !== 0 && directCallNums === 0) { + return "color=red"; + } else if (specialCallNums !== 0) { + return "color=yellow"; + } else if (indirectCallNums === 0 && directCallNums !== 0) { + return "color=black"; + } else { + return "color=black"; + } + } +} + +export class CallGraphNode extends BaseNode { + private method: Method; + private ifSdkMethod: boolean = false; + private isBlank: boolean = false; + + constructor(id: number, m: Method, k: CallGraphNodeKind = CallGraphNodeKind.real) { + super(id, k); + this.method = m; + } + + public getMethod(): Method { + return this.method; + } + + public setSdkMethod(v: boolean): void { + this.ifSdkMethod = v; + } + + public isSdkMethod(): boolean { + return this.ifSdkMethod + } + + public get isBlankMethod(): boolean { + return this.isBlank; + } + + public set isBlankMethod(is: boolean) { + this.isBlank = is; + } + + public getDotAttr(): string { + if ([CallGraphNodeKind.intrinsic, CallGraphNodeKind.constructor].includes(this.getKind())) { + return ''; + } + return 'shape=box'; + } + + public getDotLabel(): string { + let label: string = 'ID: ' + this.getID() + '\n'; + label = label + this.getMethod().toString(); + return label; + } +} + +export class CallGraph extends BaseExplicitGraph { + private scene: Scene; + private idToCallSiteMap: Map = new Map(); + private callSiteToIdMap: Map = new Map(); + private stmtToCallSitemap: Map = new Map(); + private stmtToDynCallSitemap: Map = new Map(); + private methodToCGNodeMap: Map = new Map(); + private callPairToEdgeMap: Map = new Map(); + private methodToCallSiteMap: Map> = new Map(); + private callSiteNum: number = 0; + private entries!: NodeID[]; + private cgStat: CGStat; + private dummyMainMethodID: FuncID | undefined; + + constructor(s: Scene) { + super(); + this.scene = s; + this.cgStat = new CGStat(); + } + + private getCallPairString(srcID: NodeID, dstID: NodeID): string { + return `${srcID}-${dstID}`; + } + + public getCallEdgeByPair(srcID: NodeID, dstID: NodeID): CallGraphEdge | undefined { + let key: string = this.getCallPairString(srcID, dstID); + return this.callPairToEdgeMap.get(key); + } + + public addCallGraphNode(method: Method, kind: CallGraphNodeKind = CallGraphNodeKind.real): CallGraphNode { + let id: NodeID = this.nodeNum; + let cgNode = new CallGraphNode(id, method, kind); + // check if sdk method + cgNode.setSdkMethod(this.scene.hasSdkFile( + method.getDeclaringClassSignature().getDeclaringFileSignature() + )); + + let arkMethod = this.scene.getMethod(method); + if (!arkMethod || !arkMethod.getCfg()) { + cgNode.isBlankMethod = true; + } + + this.addNode(cgNode); + this.methodToCGNodeMap.set(method.toString(), cgNode.getID()); + this.cgStat.addNodeStat(kind); + return cgNode; + } + + public removeCallGraphNode(nodeID: NodeID) { + // remove edge relate to node first + this.removeCallGraphEdge(nodeID); + let node = this.getNode(nodeID) as CallGraphNode; + // remove node itself + this.removeNode(nodeID); + this.methodToCGNodeMap.delete(node.getMethod().toString()); + } + + public getCallGraphNodeByMethod(method: Method): CallGraphNode { + if (!method) { + throw new Error(); + } + let n = this.methodToCGNodeMap.get(method.toString()); + if (n === undefined) { + // The method can't be found + // means the method has no implementation, or base type is unclear to find it + // Create a virtual CG Node + // TODO: this virtual CG Node need be remove once the base type is clear + return this.addCallGraphNode(method, CallGraphNodeKind.vitual); + } + + return this.getNode(n) as CallGraphNode; + } + + public addDirectOrSpecialCallEdge(caller: Method, callee: Method, callStmt: Stmt, isDirectCall: boolean = true): void { + let callerNode = this.getCallGraphNodeByMethod(caller) as CallGraphNode; + let calleeNode = this.getCallGraphNodeByMethod(callee) as CallGraphNode; + let args = callStmt.getInvokeExpr()?.getArgs(); + + let cs: CallSite = new CallSite(callStmt, args, calleeNode.getID(), callerNode.getID()); + let csID: CallSiteID; + if (!this.callSiteToIdMap.has(cs)) { + csID = this.callSiteNum++; + this.idToCallSiteMap.set(csID, cs); + this.callSiteToIdMap.set(cs, csID); + } else { + csID = this.callSiteToIdMap.get(cs) as CallSiteID; + } + + if (this.addStmtToCallSiteMap(callStmt, cs)) { + // TODO: check stmt exists + } + + // TODO: check if edge exists + let callEdge = this.getCallEdgeByPair(callerNode.getID(), calleeNode.getID()); + if (callEdge === undefined) { + callEdge = new CallGraphEdge(callerNode, calleeNode); + callEdge.getSrcNode().addOutgoingEdge(callEdge); + callEdge.getDstNode().addIncomingEdge(callEdge); + this.callPairToEdgeMap.set(this.getCallPairString(callerNode.getID(), calleeNode.getID()), callEdge); + } + if (isDirectCall) { + callEdge.addDirectCallSite(callStmt); + } else { + callEdge.addSpecialCallSite(callStmt); + } + } + + public removeCallGraphEdge(nodeID: NodeID) { + let node = this.getNode(nodeID) as CallGraphNode; + + for (const inEdge of node.getIncomingEdge()) { + node.removeIncomingEdge(inEdge); + } + + for (const outEdge of node.getOutgoingEdges()) { + node.removeIncomingEdge(outEdge); + } + } + + public addDynamicCallInfo(callStmt: Stmt, caller: Method, protentialCallee?: Method): void { + let callerNode = this.getCallGraphNodeByMethod(caller) as CallGraphNode; + let calleeNode; + if (protentialCallee) { + calleeNode = this.getCallGraphNodeByMethod(protentialCallee) as CallGraphNode; + } + let args = callStmt.getInvokeExpr()?.getArgs(); + + let cs = new DynCallSite(callerNode.getID(), callStmt, args, calleeNode?.getID()) + this.stmtToDynCallSitemap.set(callStmt, cs); + } + + public addDynamicCallEdge(callerID: NodeID, calleeID: NodeID, callStmt: Stmt) { + let callerNode = this.getNode(callerID) as CallGraphNode; + let calleeNode = this.getNode(calleeID) as CallGraphNode; + + let callEdge = this.getCallEdgeByPair(callerNode.getID(), calleeNode.getID()); + if (callEdge === undefined) { + callEdge = new CallGraphEdge(callerNode, calleeNode); + callEdge.getSrcNode().addOutgoingEdge(callEdge); + callEdge.getDstNode().addIncomingEdge(callEdge); + this.callPairToEdgeMap.set(this.getCallPairString(callerNode.getID(), calleeNode.getID()), callEdge); + } + callEdge.addInDirectCallSite(callStmt); + } + + public getDynCallsiteByStmt(stmt: Stmt): DynCallSite | undefined { + return this.stmtToDynCallSitemap.get(stmt); + } + + public addStmtToCallSiteMap(stmt: Stmt, cs: CallSite): boolean { + if (this.stmtToCallSitemap.has(stmt)) { + let callSites = this.stmtToCallSitemap.get(stmt) ?? []; + this.stmtToCallSitemap.set(stmt, [...callSites, cs]); + return false; + } + this.stmtToCallSitemap.set(stmt, [cs]); + return true; + } + + public getCallSiteByStmt(stmt: Stmt): CallSite[] { + return this.stmtToCallSitemap.get(stmt) ?? []; + } + + public addMethodToCallSiteMap(funcID: FuncID, cs: CallSite): void { + if (this.methodToCallSiteMap.has(funcID)) { + this.methodToCallSiteMap.get(funcID)!.add(cs); + } else { + this.methodToCallSiteMap.set(funcID, new Set([cs])); + } + } + + public getCallSitesByMethod(func: FuncID | MethodSignature): Set { + let funcID: FuncID; + if (func instanceof MethodSignature) { + funcID = this.getCallGraphNodeByMethod(func).getID(); + } else { + funcID = func; + } + + return this.methodToCallSiteMap.get(funcID) ?? new Set(); + } + + public getInvokeStmtByMethod(func: FuncID | MethodSignature): Stmt[] { + let callSites = this.getCallSitesByMethod(func); + let invokeStmts: Stmt[] = []; + callSites.forEach((cs) => { + invokeStmts.push(cs.callStmt); + }); + + return invokeStmts; + } + + public getDynEdges(): Map> { + let callMap: Map> = new Map(); + this.callPairToEdgeMap.forEach((edge: CallGraphEdge) => { + let srcMethod = (edge.getSrcNode() as CallGraphNode).getMethod(); + let dstMethod = (edge.getDstNode() as CallGraphNode).getMethod(); + + let dstSet: Set; + if (callMap.has(srcMethod)) { + dstSet = callMap.get(srcMethod)!; + } else { + dstSet = new Set(); + } + callMap.set(srcMethod, dstSet.add(dstMethod)); + }); + + return callMap; + } + + public getMethodByFuncID(id: FuncID): Method | null { + let node = this.getNode(id); + if (node !== undefined) { + return (node as CallGraphNode).getMethod(); + } + //return undefined; + return null; + } + + public getArkMethodByFuncID(id: FuncID): ArkMethod | null { + let method = this.getMethodByFuncID(id); + if (method != null) { + // TODO: SDK Method search + return this.scene.getMethod(method); + } + + return null; + } + + public getEntries(): FuncID[] { + return this.entries; + } + + public setEntries(n: NodeID[]): void { + this.entries = n; + } + + public dump(name: string, entry?: FuncID): void { + let printer = new GraphPrinter(this); + if (entry) { + printer.setStartID(entry); + } + PrinterBuilder.dump(printer, name); + } + + public detectReachable(fromID: FuncID, dstID: FuncID): boolean { + let dWorklist: FuncID[] = []; + let travserdFuncs = new Set(); + + dWorklist.push(fromID); + + while (dWorklist.length > 0) { + let nodeID = dWorklist.shift()!; + if (travserdFuncs.has(nodeID)) { + continue; + } + travserdFuncs.add(nodeID); + + let node = this.getNode(nodeID)!; + for (let e of node.getOutgoingEdges()) { + let dst = e.getDstID(); + if (dst === dstID) { + return true; + } + dWorklist.push(dst); + } + } + + return false; + } + + public printStat(): void { + this.cgStat.printStat(); + } + + public getStat(): string { + return this.cgStat.getStat(); + } + + public setDummyMainFuncID(dummyMainMethodID: number): void { + this.dummyMainMethodID = dummyMainMethodID; + } + + public getDummyMainFuncID(): FuncID | undefined { + return this.dummyMainMethodID; + } + + public isUnknownMethod(funcID: FuncID): boolean { + let method = this.getMethodByFuncID(funcID); + + if (method) { + if (!(method.getDeclaringClassSignature().getDeclaringFileSignature().getFileName() === UNKNOWN_FILE_NAME)) { + return false; + } + } + + return true; + } + + public getGraphName(): string { + return 'CG'; + } +} diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/model/builder/CallGraphBuilder.ts b/ets2panda/linter/arkanalyzer/src/callgraph/model/builder/CallGraphBuilder.ts new file mode 100644 index 0000000000..88076a8eaf --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/callgraph/model/builder/CallGraphBuilder.ts @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { CallGraph, CallGraphNode, CallGraphNodeKind, Method } from '../CallGraph'; +import { Scene } from '../../../Scene'; +import { AbstractInvokeExpr, ArkInstanceInvokeExpr, ArkStaticInvokeExpr } from "../../../core/base/Expr"; +import { NodeID } from '../../../core/graph/BaseExplicitGraph'; +import { ClassHierarchyAnalysis } from '../../algorithm/ClassHierarchyAnalysis'; +import { RapidTypeAnalysis } from '../../algorithm/RapidTypeAnalysis'; +import { ArkMethod } from '../../../core/model/ArkMethod'; + +export class CallGraphBuilder { + private cg: CallGraph; + private scene: Scene; + + constructor(c: CallGraph, s: Scene) { + this.cg = c; + this.scene = s; + } + + + public buildDirectCallGraphForScene(): void { + const methods = this.scene.getMethods(); + this.buildDirectCallGraph(methods); + + // set entries at end + this.setEntries(); + } + + public buildDirectCallGraph(methods: ArkMethod[]): void { + for (const method of methods) { + let m = method.getSignature(); + let kind = CallGraphNodeKind.real; + if (method.isGenerated()) { + kind = CallGraphNodeKind.intrinsic; + } + if (method.getName() === 'constructor') { + kind = CallGraphNodeKind.constructor; + } + + this.cg.addCallGraphNode(m, kind); + } + + for (const method of methods) { + let cfg = method.getCfg(); + if (cfg === undefined) { + // abstract method cfg is undefined + continue; + } + let stmts = cfg.getStmts(); + for (const stmt of stmts) { + let invokeExpr = stmt.getInvokeExpr(); + if (invokeExpr === undefined) { + continue; + } + + let callee: Method | undefined = this.getDCCallee(invokeExpr); + // abstract method will also be added into direct cg + if (callee && invokeExpr instanceof ArkStaticInvokeExpr) { + this.cg.addDirectOrSpecialCallEdge(method.getSignature(), callee, stmt); + } else if (callee && (invokeExpr instanceof ArkInstanceInvokeExpr && ( + this.isConstructor(callee) || this.scene.getMethod(callee)?.isGenerated()))) { + this.cg.addDirectOrSpecialCallEdge(method.getSignature(), callee, stmt, false); + } else { + this.cg.addDynamicCallInfo(stmt, method.getSignature(), callee); + } + } + } + } + + public buildClassHierarchyCallGraph(entries: Method[], displayGeneratedMethod: boolean = false): void { + let cgEntries: NodeID[] = []; + entries.forEach((entry: Method) => { + cgEntries.push(this.cg.getCallGraphNodeByMethod(entry).getID()); + }) + this.cg.setEntries(cgEntries); + + let classHierarchyAnalysis: ClassHierarchyAnalysis = new ClassHierarchyAnalysis(this.scene, this.cg); + classHierarchyAnalysis.start(displayGeneratedMethod); + } + + public buildRapidTypeCallGraph(entries: Method[], displayGeneratedMethod: boolean = false): void { + let cgEntries: NodeID[] = []; + entries.forEach((entry: Method) => { + cgEntries.push(this.cg.getCallGraphNodeByMethod(entry).getID()); + }) + this.cg.setEntries(cgEntries); + + let rapidTypeAnalysis: RapidTypeAnalysis = new RapidTypeAnalysis(this.scene, this.cg); + rapidTypeAnalysis.start(displayGeneratedMethod); + } + + /// Get direct call callee + private getDCCallee(invokeExpr: AbstractInvokeExpr): Method | undefined { + return invokeExpr.getMethodSignature(); + } + + private isConstructor(m: Method): boolean { + return m.getMethodSubSignature().getMethodName() === 'constructor'; + } + + public setEntries(): void { + let nodesIter = this.cg.getNodesIter(); + let entries = Array.from(nodesIter) + .filter(node => !node.hasIncomingEdges() && node.getKind() === CallGraphNodeKind.real + && !(node as CallGraphNode).isBlankMethod) + .map(node => node.getID()); + this.cg.setEntries(entries); + } +} diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/Context.ts b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/Context.ts new file mode 100644 index 0000000000..e8affe8adb --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/Context.ts @@ -0,0 +1,181 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {FuncID} from '../model/CallGraph' + +export type ContextID = number +export const DUMMY_CID = 0 + +class Context { + private contextElems: number[]; + static sEmptyCtx: Context = new Context([]); + + constructor(contextElems: number[] = []) { + this.contextElems = contextElems; + } + + static newEmpty(): Context { + return new Context(); + } + + static new(contextElems: number[]): Context { + return new Context(contextElems); + } + + // use old context and a new element to create a new k-limited Context + static newKLimitedContext(oldCtx: Context, elem: number, k: number): Context { + let elems: number[] = []; + if (k > 0) { + elems.push(elem); + if (oldCtx.contextElems.length < k) { + elems = elems.concat(oldCtx.contextElems); + } else { + elems = elems.concat(oldCtx.contextElems.slice(0, k - 1)); + } + } + return new Context(elems); + } + + static kLimitedContext(ctx: Context, k:number): Context { + if (ctx.length() <= k) { + return new Context(ctx.contextElems); + } else { + const elems = ctx.contextElems.slice(0, k); + return new Context(elems); + } + } + + public length(): number { + return this.contextElems.length; + } + + public get(index: number): number { + if (index < 0 || index >= this.contextElems.length) { + throw new Error('Index out of bounds'); + } + return this.contextElems[index]; + } + + public toString(): String { + return this.contextElems.join('-') + } +} + +class ContextCache { + private contextList: Context[] = []; + private contextToIDMap: Map = new Map(); + + constructor() { + this.contextList = []; + this.contextToIDMap = new Map(); + } + + public getOrNewContextID(context: Context): ContextID { + let cStr = context.toString(); + if (this.contextToIDMap.has(cStr)) { + return this.contextToIDMap.get(cStr) as ContextID; + } else { + // real cid start from 1 + const id = this.contextList.length; + this.contextList.push(context); + this.contextToIDMap.set(cStr, id); + return id; + } + } + + public updateContext(id: ContextID, newContext: Context, oldContext: Context): boolean { + if(this.contextList.length < id) { + return false; + } + this.contextList[id] = newContext; + let oldCStr = oldContext.toString(); + let newCStr = newContext.toString(); + this.contextToIDMap.delete(oldCStr); + this.contextToIDMap.set(newCStr, id); + return true; + } + + public getContextID(context: Context): ContextID | undefined { + let cStr = context.toString(); + if (this.contextToIDMap.has(cStr)) { + return this.contextToIDMap.get(cStr) as ContextID; + } + + return undefined; + } + + public getContext(id: number): Context | undefined { + if (id > this.contextList.length) { + return undefined; + } + return this.contextList[id]; + } + + public getContextList(): Context[] { + return this.contextList; + } +} + +export class KLimitedContextSensitive { + k: number; + ctxCache: ContextCache; + + constructor(k: number) { + this.k = k; + this.ctxCache = new ContextCache(); + // put dummy cid + this.getEmptyContextID(); + } + + public emptyContext(): Context { + return new Context([]); + } + + public getEmptyContextID(): ContextID{ + return this.getContextID(Context.newEmpty()); + } + + public getContextID(context: Context): ContextID{ + return this.ctxCache.getOrNewContextID(context); + } + + public getContextByID(context_id: number): Context | undefined { + return this.ctxCache.getContext(context_id); + } + + public getNewContextID(callerFuncId: FuncID): ContextID { + return this.ctxCache.getOrNewContextID(Context.new([callerFuncId])); + } + + public getOrNewContext(callerCid: ContextID, calleeFuncId: FuncID, findCalleeAsTop: boolean = false): ContextID { + const callerCtx = this.ctxCache.getContext(callerCid); + if (!callerCtx) { + throw new Error(`Context with id ${callerCid} not found.`); + } + + const calleeNewCtx = Context.newKLimitedContext(callerCtx, calleeFuncId, this.k); + if (findCalleeAsTop){ + const calleeAsTopCtx = Context.newKLimitedContext(Context.sEmptyCtx, calleeFuncId, this.k); + let topID = this.ctxCache.getContextID(calleeAsTopCtx); + if (topID) { + this.ctxCache.updateContext(topID, calleeNewCtx, calleeAsTopCtx); + return topID; + } + } + + const calleeCid = this.ctxCache.getOrNewContextID(calleeNewCtx); + return calleeCid; + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/DummyCallCreator.ts b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/DummyCallCreator.ts new file mode 100644 index 0000000000..3708605bdf --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/DummyCallCreator.ts @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +import { ArkInstanceInvokeExpr } from '../../core/base/Expr'; +import { Local } from '../../core/base/Local'; +import { Stmt, ArkInvokeStmt } from '../../core/base/Stmt'; +import { ArkMethod } from '../../core/model/ArkMethod'; +import { ClassSignature } from '../../core/model/ArkSignature'; +import { Scene } from '../../Scene'; +import { COMPONENT_LIFECYCLE_METHOD_NAME } from '../../utils/entryMethodUtils'; +import Logger, { LOG_MODULE_TYPE } from '../../utils/logger'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'Dummy Call'); + +/** + * TODO: constructor pointer and cid + */ +export class DummyCallCreator { + private scene: Scene; + private pageMap; + // TODO: classSig -> str ? + private componentMap: Map>; + + constructor(scene: Scene) { + this.scene = scene; + this.componentMap = new Map(); + this.pageMap = new Map(); + } + + public getDummyCallByPage(classSig: ClassSignature, basePage: Local): Set { + let dummyCallStmts = this.pageMap.get(classSig); + if (dummyCallStmts) { + return dummyCallStmts; + } + + dummyCallStmts = this.buildDummyCallBody(classSig, basePage); + + this.pageMap.set(classSig, dummyCallStmts); + return dummyCallStmts; + } + + public getDummyCallByComponent(classSig: ClassSignature, baseComponent: Local): Set { + let dummyCallStmts = this.componentMap.get(classSig); + if (dummyCallStmts) { + return dummyCallStmts; + } + + dummyCallStmts = this.buildDummyCallBody(classSig, baseComponent); + + this.componentMap.set(classSig, dummyCallStmts); + return dummyCallStmts; + } + + /** + * build dummy call edge with class signature, including a class new expr and call back function invokes + * @param classSig class signature + * @returns dummy call edges + */ + private buildDummyCallBody(classSig: ClassSignature, baseComponent: Local): Set { + let dummyCallStmts: Set = new Set(); + + this.getComponentCallStmts(classSig, baseComponent).forEach(stmt => dummyCallStmts.add(stmt)); + + return dummyCallStmts; + } + + private getComponentCallStmts(classSig: ClassSignature, base: Local): Stmt[] { + let componentClass = this.scene.getClass(classSig); + if (!componentClass) { + logger.error(`can not find class ${classSig.toString()}`); + return []; + } + + let callStmts: Stmt[] = []; + // filter callback method + componentClass.getMethods().filter(method => COMPONENT_LIFECYCLE_METHOD_NAME.includes(method.getName())) + .forEach((method: ArkMethod) => { + // TODO: args pointer ? + if (method.getParameters().length === 0) { + callStmts.push(new ArkInvokeStmt(new ArkInstanceInvokeExpr(base, method.getSignature(), []))); + } else { + logger.warn(`parameters in callback function hasn't been processed: ${method.getSignature().toString()}`); + } + }); + + return callStmts; + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PTAUtils.ts b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PTAUtils.ts new file mode 100644 index 0000000000..04b07551c9 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PTAUtils.ts @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ClassSignature, MethodSignature } from '../../core/model/ArkSignature'; + +export function IsCollectionClass(classSignature: ClassSignature): boolean { + if (classSignature.toString().endsWith('lib.es2015.collection.d.ts: Set') || + classSignature.toString().endsWith('lib.es2015.collection.d.ts: Map')) { + return true; + } + return false; +} + +export function IsCollectionAPI(method: MethodSignature): boolean { + if (IsCollectionSetAdd(method) || IsCollectionMapSet(method)) { + return true; + } + return false; +} + +export function IsCollectionSetAdd(method: MethodSignature): boolean { + if (method.toString().endsWith('lib.es2015.collection.d.ts: Set.add(T)')) { + return true; + } + return false; +} + +export function IsCollectionMapSet(method: MethodSignature): boolean { + if (method.toString().endsWith('lib.es2015.collection.d.ts: Map.set(K, V)')) { + return true; + } + return false; +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/Pag.ts b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/Pag.ts new file mode 100644 index 0000000000..6da4c6c9ac --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/Pag.ts @@ -0,0 +1,1032 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { NodeID, BaseEdge, BaseExplicitGraph, BaseNode, Kind } from '../../core/graph/BaseExplicitGraph'; +import { CallGraph, CallSite, DynCallSite } from '../model/CallGraph'; +import { Value } from '../../core/base/Value'; +import { ArkAssignStmt, ArkReturnStmt, Stmt } from '../../core/base/Stmt'; +import { AbstractExpr, ArkNewArrayExpr, ArkNewExpr } from '../../core/base/Expr'; +import { AbstractFieldRef, ArkArrayRef, ArkInstanceFieldRef, ArkParameterRef, ArkStaticFieldRef, ArkThisRef } from '../../core/base/Ref'; +import { Local } from '../../core/base/Local'; +import { GraphPrinter } from '../../save/GraphPrinter'; +import { PrinterBuilder } from '../../save/PrinterBuilder'; +import { Constant } from '../../core/base/Constant'; +import { FunctionType, UnclearReferenceType } from '../../core/base/Type'; +import { ClassSignature, FieldSignature, FileSignature, MethodSignature } from '../../core/model/ArkSignature'; +import { ContextID } from './Context'; +import Logger, { LOG_MODULE_TYPE } from '../../utils/logger'; +import { GLOBAL_THIS_NAME } from '../../core/common/TSConst'; +import { ExportInfo } from '../../core/model/ArkExport'; +import { IsCollectionClass } from './PTAUtils'; +import { IPtsCollection } from './PtsDS'; +import { PointerAnalysisConfig } from './PointerAnalysisConfig'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'PTA'); +export type PagNodeType = Value; + +/* + * Implementation of pointer-to assignment graph for pointer analysis + */ + +const DUMMY_PAG_NODE_ID = -1 + +export enum PagEdgeKind { + Address, Copy, Load, Write, This, Unknown, InterProceduralCopy +}; + +export enum StorageType { + APP_STORAGE, LOCAL_STORAGE, Undefined +}; + +export enum StorageLinkEdgeType { + Property2Local, + Local2Property, + TwoWay +} + +export class PagEdge extends BaseEdge { + private stmt: Stmt | undefined; + + constructor(n: PagNode, d: PagNode, k: PagEdgeKind, s?: Stmt) { + super(n, d, k); + this.stmt = s; + }; + + public getDotAttr(): string { + switch (this.getKind()) { + case PagEdgeKind.Address: + return "color=green"; + case PagEdgeKind.Copy: + if (this.stmt?.getInvokeExpr() !== undefined || this.stmt instanceof ArkReturnStmt) { + return "color=black,style=dotted"; + } + return "color=black"; + case PagEdgeKind.Load: + return "color=red"; + case PagEdgeKind.Write: + return "color=blue" + case PagEdgeKind.This: + return "color=orange" + case PagEdgeKind.InterProceduralCopy: + return "color=purple,style=dashed"; + default: + return "color=black"; + } + } +} + +export class AddrPagEdge extends PagEdge { + constructor(n: PagNode, d: PagNode, s: Stmt) { + super(n, d, PagEdgeKind.Address, s); + }; +} + +export class CopyPagEdge extends PagEdge { + constructor(n: PagNode, d: PagNode, s: Stmt) { + super(n, d, PagEdgeKind.Copy, s); + }; +} + +export class LoadPagEdge extends PagEdge { + constructor(n: PagNode, d: PagNode, s: Stmt) { + super(n, d, PagEdgeKind.Copy, s); + }; +} + +export class WritePagEdge extends PagEdge { + constructor(n: PagNode, d: PagNode, s: Stmt) { + super(n, d, PagEdgeKind.Write, s); + }; +} + +export class ThisPagEdge extends PagEdge { + constructor(n: PagNode, d: PagNode, s: Stmt) { + super(n, d, PagEdgeKind.This, s); + }; +} + +type PagEdgeSet = Set; + +export enum PagNodeKind { HeapObj, LocalVar, RefVar, Param, ThisRef, Function, GlobalThis, ExportInfo } +export class PagNode extends BaseNode { + private cid: ContextID | undefined; + private value: Value; + private stmt: Stmt | undefined; // stmt is just used for graph print + private pointTo: IPtsCollection; + + private addressInEdges!: PagEdgeSet; + private addressOutEdges!: PagEdgeSet; + private copyInEdges!: PagEdgeSet; + private copyOutEdges!: PagEdgeSet; + private loadInEdges!: PagEdgeSet; + private loadOutEdges!: PagEdgeSet; + private writeInEdges!: PagEdgeSet; + private writeOutEdges!: PagEdgeSet; + private thisInEdges!: PagEdgeSet; + private thisOutEdges!: PagEdgeSet; + + // Point-to node of base class + // Only PagInstanceRefNode has this field + // Define in base class is for dot print + protected basePt!: NodeID; + protected clonedFrom!: NodeID; + + constructor(id: NodeID, cid: ContextID | undefined = undefined, value: Value, k: Kind, s?: Stmt) { + super(id, k); + this.cid = cid; + this.value = value; + this.stmt = s; + let ptaConfig = PointerAnalysisConfig.getInstance(); + this.pointTo = new ptaConfig.ptsCollectionCtor(); + } + + public getBasePt(): NodeID { + return this.basePt; + } + + public setBasePt(pt: NodeID) { + this.basePt = pt; + } + + public getCid(): ContextID { + if (this.cid === undefined) { + throw new Error('cid is undefine') + } + return this.cid; + } + + public setCid(cid: ContextID) { + this.cid = cid; + } + + public setStmt(s: Stmt) { + this.stmt = s; + } + + public getStmt(): Stmt | undefined { + return this.stmt; + } + + public hasOutgoingCopyEdge(): boolean { + return (this.copyOutEdges.size !== 0); + } + + public getOutgoingCopyEdges(): PagEdgeSet { + return this.copyOutEdges; + } + + public getIncomingCopyEdges(): PagEdgeSet { + return this.copyInEdges; + } + + public getOutgoingLoadEdges(): PagEdgeSet { + return this.loadOutEdges; + } + + public getOutgoingWriteEdges(): PagEdgeSet { + return this.writeOutEdges; + } + + public getIncomingWriteEdges(): PagEdgeSet { + return this.writeInEdges; + } + + public getOutgoingThisEdges(): PagEdgeSet { + return this.thisOutEdges; + } + + public getIncomingThisEdges(): PagEdgeSet { + return this.thisInEdges; + } + + public addAddressInEdge(e: AddrPagEdge): void { + this.addressInEdges === undefined ? this.addressInEdges = new Set() : undefined; + this.addressInEdges.add(e); + this.addIncomingEdge(e); + } + + public addAddressOutEdge(e: AddrPagEdge): void { + this.addressOutEdges === undefined ? this.addressOutEdges = new Set() : undefined; + this.addressOutEdges.add(e); + this.addOutgoingEdge(e); + } + + public addCopyInEdge(e: CopyPagEdge): void { + this.copyInEdges === undefined ? this.copyInEdges = new Set() : undefined; + this.copyInEdges.add(e); + this.addIncomingEdge(e); + } + + public addCopyOutEdge(e: CopyPagEdge): void { + this.copyOutEdges === undefined ? this.copyOutEdges = new Set() : undefined; + + this.copyOutEdges.add(e); + this.addOutgoingEdge(e); + } + + public addLoadInEdge(e: LoadPagEdge): void { + this.loadInEdges === undefined ? this.loadInEdges = new Set() : undefined; + this.loadInEdges.add(e); + this.addIncomingEdge(e); + } + + public addLoadOutEdge(e: LoadPagEdge): void { + this.loadOutEdges === undefined ? this.loadOutEdges = new Set() : undefined; + this.loadOutEdges.add(e); + this.addOutgoingEdge(e); + } + + public addWriteInEdge(e: WritePagEdge): void { + this.writeInEdges = this.writeInEdges ?? new Set(); + this.writeInEdges.add(e); + this.addIncomingEdge(e); + } + + public addWriteOutEdge(e: LoadPagEdge): void { + this.writeOutEdges = this.writeOutEdges ?? new Set(); + this.writeOutEdges.add(e); + this.addOutgoingEdge(e); + } + + public addThisInEdge(e: ThisPagEdge): void { + this.thisInEdges = this.thisInEdges ?? new Set(); + this.thisInEdges.add(e); + this.addIncomingEdge(e); + } + + public addThisOutEdge(e: ThisPagEdge): void { + this.thisOutEdges = this.thisOutEdges ?? new Set(); + this.thisOutEdges.add(e); + this.addOutgoingEdge(e); + } + + public getValue(): Value { + return this.value; + } + + public getPointTo(): IPtsCollection { + return this.pointTo; + } + + public addPointToElement(node: NodeID) { + this.pointTo.insert(node); + } + + public setPointTo(pts: IPtsCollection): void { + this.pointTo = pts; + } + + public getOutEdges() { + return { + AddressEdge: this.addressOutEdges, + CopyEdge: this.copyOutEdges, + LoadEdge: this.loadOutEdges, + WriteEdge: this.writeOutEdges + } + } + + public getClonedFrom(): NodeID { + return this.clonedFrom; + } + + public setClonedFrom(id: NodeID): void { + this.clonedFrom = id; + } + + public getDotAttr(): string { + switch (this.getKind()) { + case PagNodeKind.HeapObj: + case PagNodeKind.Function: + case PagNodeKind.GlobalThis: + return 'shape=box3d'; + case PagNodeKind.LocalVar: + return 'shape=box'; + case PagNodeKind.RefVar: + return 'shape=component'; + case PagNodeKind.Param: + return 'shape=box'; + case PagNodeKind.ExportInfo: + return 'shape=tab,color=purple'; + case PagNodeKind.ThisRef: + return 'shape=box,color=orange' + default: + return 'shape=box'; + } + } + + public getDotLabel(): string { + let label: string; + let param: ArkParameterRef; + + label = PagNodeKind[this.getKind()]; + label = label + ` ID: ${this.getID()} Ctx: ${this.cid}`; + if (this.basePt) { + label = label + ` base:{${this.basePt}}`; + } + label = label + ` pts:{${Array.from(this.pointTo).join(',')}}` + + if (this.getKind() === PagNodeKind.Param) { + param = this.value as ArkParameterRef; + label = label + `\nParam#${param.getIndex()} ${param.toString()}`; + } + + if (this.getKind() === PagNodeKind.ThisRef) { + label = label + `\n${(this.value as ArkThisRef).toString()}`; + } + + if (this.stmt) { + label = label + `\n${this.stmt.toString()}`; + let method = this.stmt.getCfg()?.getDeclaringMethod().getSubSignature().toString(); + if (method) { + label = label + '\n' + method; + } + label = label + ' ln: ' + this.stmt.getOriginPositionInfo().getLineNo(); + } else if (this.value) { + label += `\n${this.value.toString()}`; + } + + return label; + } +} + +export class PagLocalNode extends PagNode { + private relatedDynamicCallSite?: Set; + private relatedUnknownCallSite?: Set; + private storageLinked: boolean = false; + private storageType?: StorageType; + private propertyName?: string; + + private sdkParam: boolean = false; + + constructor(id: NodeID, cid: ContextID | undefined = undefined, value: Local, stmt?: Stmt) { + super(id, cid, value, PagNodeKind.LocalVar, stmt) + } + + public addRelatedDynCallSite(cs: DynCallSite) { + this.relatedDynamicCallSite = this.relatedDynamicCallSite ?? new Set() + + this.relatedDynamicCallSite.add(cs) + } + + public getRelatedDynCallSites(): Set { + return this.relatedDynamicCallSite ?? new Set(); + } + + public addRelatedUnknownCallSite(cs: CallSite) { + this.relatedUnknownCallSite = this.relatedUnknownCallSite ?? new Set(); + + this.relatedUnknownCallSite.add(cs); + } + + public getRelatedUnknownCallSites(): Set { + return this.relatedUnknownCallSite ?? new Set(); + } + + public setStorageLink(storageType: StorageType, propertyName: string): void { + this.storageLinked = true; + this.storageType = storageType; + this.propertyName = propertyName; + } + + public getStorage(): { StorageType: StorageType, PropertyName: string } { + return { + StorageType: this.storageType!, + PropertyName: this.propertyName! + }; + } + + public isStorageLinked(): boolean { + return this.storageLinked; + } + + public setSdkParam(): void { + this.sdkParam = true; + } + + public isSdkParam(): boolean { + return this.sdkParam; + } +} + +export class PagInstanceFieldNode extends PagNode { + constructor(id: NodeID, cid: ContextID | undefined = undefined, instanceFieldRef: ArkInstanceFieldRef, stmt?: Stmt) { + super(id, cid, instanceFieldRef, PagNodeKind.RefVar, stmt) + } + +} + +export class PagStaticFieldNode extends PagNode { + constructor(id: NodeID, cid: ContextID | undefined = undefined, staticFieldRef: ArkStaticFieldRef, stmt?: Stmt) { + super(id, cid, staticFieldRef, PagNodeKind.RefVar, stmt) + } +} + +export class PagThisRefNode extends PagNode { + pointToNode: NodeID[]; + constructor(id: NodeID, thisRef: ArkThisRef) { + super(id, DUMMY_PAG_NODE_ID, thisRef, PagNodeKind.ThisRef); + this.pointToNode = []; + } + + public getThisPTNode(): NodeID[] { + return this.pointToNode; + } + + public addPTNode(ptNode: NodeID) { + this.pointToNode.push(ptNode) + } +} + +export class PagArrayNode extends PagNode { + base: Value; + + constructor(id: NodeID, cid: ContextID | undefined = undefined, expr: ArkArrayRef, stmt?: Stmt) { + super(id, cid, expr, PagNodeKind.LocalVar, stmt); + this.base = expr.getBase(); + } +} + + +/** + * below is heapObj like Node + */ +export class PagNewExprNode extends PagNode { + // store the cloned field node + fieldNodes!: Map + + constructor(id: NodeID, cid: ContextID | undefined = undefined, expr: AbstractExpr, stmt?: Stmt) { + super(id, cid, expr, PagNodeKind.HeapObj, stmt) + } + + public addFieldNode(fieldSignature: AbstractFieldRef, nodeID: NodeID): boolean { + if (!this.fieldNodes) { + this.fieldNodes = new Map() + } + if (this.fieldNodes.has(fieldSignature.getFieldSignature().toString())) { + return false + } + this.fieldNodes.set(fieldSignature.getFieldSignature().toString(), nodeID); + return true + } + + public getFieldNode(fieldSignature: AbstractFieldRef): NodeID | undefined { + if (!this.fieldNodes) { + return undefined + } + return this.fieldNodes.get(fieldSignature.getFieldSignature().toString()) + } + + public getFieldNodes(): Map | undefined { + if (!this.fieldNodes) { + return undefined + } + return this.fieldNodes + } +} + +export class PagNewContainerExprNode extends PagNode { + // store the cloned array ref node + elementNode: NodeID | undefined; + + constructor(id: NodeID, cid: ContextID | undefined = undefined, expr: Value, stmt?: Stmt) { + super(id, cid, expr, PagNodeKind.HeapObj, stmt); + } + + public addElementNode(nodeID: NodeID): boolean { + if (!this.elementNode) { + this.elementNode = nodeID; + } + + return true; + } + + public getElementNode(): NodeID | undefined { + if (this.elementNode) { + return this.elementNode; + } + return undefined; + } +} + +export class PagParamNode extends PagNode { + constructor(id: NodeID, cid: ContextID | undefined = undefined, r: ArkParameterRef, stmt?: Stmt) { + super(id, cid, r, PagNodeKind.Param, stmt) + } +} + +export class PagFuncNode extends PagNode { + private methodSignature!: MethodSignature + // TODO: may add obj interface + + constructor(id: NodeID, cid: ContextID | undefined = undefined, r: Value, stmt?: Stmt, method?: MethodSignature) { + super(id, cid, r, PagNodeKind.Function, stmt) + if (method) { + this.methodSignature = method; + } + } + + public setMethod(method: MethodSignature) { + this.methodSignature = method + } + + public getMethod(): MethodSignature { + return this.methodSignature + } +} + +/** + * almost same as PagNewExprNode, used only for globalThis and its field reference + */ +export class PagGlobalThisNode extends PagNode { + fieldNodes: Map + + constructor(id: NodeID, cid: ContextID | undefined = undefined, r: Value, stmt?: Stmt) { + super(id, cid, r, PagNodeKind.GlobalThis, stmt) + this.fieldNodes = new Map() + } + + public addFieldNode(fieldSignature: AbstractFieldRef, nodeID: NodeID): boolean { + if (this.fieldNodes.has(fieldSignature.getFieldSignature().toString())) { + return false + } + this.fieldNodes.set(fieldSignature.getFieldSignature().toString(), nodeID); + return true + } + + public getFieldNode(fieldSignature: AbstractFieldRef): NodeID | undefined { + return this.fieldNodes.get(fieldSignature.getFieldSignature().toString()) + } + + public getFieldNodes(): Map | undefined { + return this.fieldNodes + } +} + +export class Pag extends BaseExplicitGraph { + + private cg!: CallGraph; + private contextValueToIdMap: Map> = new Map(); + private ExportInfoToIdMap?: Map; + // contextBaseToIdMap will only be used in instance field + // Value: instance field base value, NodeID: abstract nodes + private contextBaseToIdMap: Map> = new Map(); + // for reanalyze, will return new addr edges + private stashAddrEdge: PagEdgeSet = new Set(); + private addrEdge: PagEdgeSet = new Set(); + private clonedNodeMap: Map> = new Map(); + + public getCG(): CallGraph { + return this.cg; + } + + /* + * Clone a PagNode with same cid/value/stmt, + * but different Node ID + */ + public getOrClonePagNode(src: PagNode, basePt: NodeID): PagNode { + if (src.getBasePt() !== undefined) { + throw new Error('This is a cloned ref node, can not be cloned again'); + } + + let cloneSet = this.clonedNodeMap.get(src.getID()); + if (!cloneSet) { + cloneSet = new Map(); + this.clonedNodeMap.set(src.getID(), cloneSet); + } else { + let nodeID = cloneSet.get(basePt); + if (nodeID) { + return this.getNode(nodeID) as PagNode; + } + } + + // Not found + let cloneNode = this.addPagNode(src.getCid(), src.getValue(), src.getStmt(), false) + cloneNode.setClonedFrom(src.getID()); + cloneSet.set(basePt, cloneNode.getID()); + return cloneNode; + } + + public getOrClonePagFieldNode(src: PagInstanceFieldNode, basePt: NodeID): PagInstanceFieldNode | undefined { + let baseNode = this.getNode(basePt) + if (baseNode instanceof PagNewExprNode || baseNode instanceof PagGlobalThisNode) { + // check if real field node has been created with basePT, using FieldSignature as key + let existedNode = baseNode.getFieldNode(src.getValue() as ArkInstanceFieldRef) + if (existedNode) { + return this.getNode(existedNode) as PagInstanceFieldNode + } + + let fieldNode = this.getOrClonePagNode(src, basePt) + baseNode.addFieldNode(src.getValue() as ArkInstanceFieldRef, fieldNode.getID()) + fieldNode.setBasePt(basePt) + return fieldNode + } else { + logger.error(`Error clone field node ${src.getValue()}`) + return undefined; + } + } + + public getOrClonePagContainerFieldNode(basePt: NodeID, src?: PagArrayNode, base?: Local): PagInstanceFieldNode | undefined { + let baseNode = this.getNode(basePt) as PagNode; + if (baseNode instanceof PagNewContainerExprNode) { + // check if Array Ref real node has been created or not, if not: create a real Array Ref node + let existedNode = baseNode.getElementNode(); + let fieldNode!: PagNode; + if (existedNode) { + return this.getNode(existedNode) as PagInstanceFieldNode; + } + + if (src) { + fieldNode = this.getOrClonePagNode(src, basePt); + } else if (base) { + const containerFieldSignature = new FieldSignature('field', + new ClassSignature('container', new FileSignature('container', 'lib.es2015.collection.d.ts')), + new UnclearReferenceType('')); + fieldNode = this.getOrClonePagNode( + // TODO: cid check + this.addPagNode(0, new ArkInstanceFieldRef(base, containerFieldSignature)), basePt + ); + } + + baseNode.addElementNode(fieldNode.getID()); + fieldNode.setBasePt(basePt); + return fieldNode; + } else if (baseNode instanceof PagNewExprNode) { + // In some cases, the value of a variable of array type may not be an explicit array object. + // For example, it could be a return value of a function (assuming that the call depth has + // exceeded the k-limit). + // In such situation, the `baseNode` will be a PagNewExprNode instead of a PagNewContainerExprNode, + // and a warning will be raised. + logger.warn(`[PTA]: Trying to clone an array from a PagNewExprNode instead of a PagNewContainerExprNode`); + } else { + throw new Error(`Error clone array field node ${baseNode.getValue()}`); + } + return undefined; + } + + public addPagNode(cid: ContextID, value: PagNodeType, stmt?: Stmt, refresh: boolean = true): PagNode { + let id: NodeID = this.nodeNum + 1; + let pagNode: PagNode; + + if (value instanceof Local) { + pagNode = this.handleLocalNode(id, cid, value, stmt); + } else if (value instanceof ArkInstanceFieldRef) { + pagNode = this.handleInstanceFieldNode(id, cid, value, stmt); + } else if (value instanceof ArkStaticFieldRef) { + pagNode = this.handleStaticFieldNode(id, cid, value, stmt); + } else if (value instanceof ArkArrayRef) { + pagNode = new PagArrayNode(id, cid, value, stmt); + } else if (value instanceof ArkNewExpr) { + pagNode = this.handleNewExprNode(id, cid, value, stmt); + } else if (value instanceof ArkNewArrayExpr) { + pagNode = new PagNewContainerExprNode(id, cid, value, stmt); + } else if (value instanceof ArkParameterRef) { + pagNode = new PagParamNode(id, cid, value, stmt); + } else if (value instanceof ArkThisRef) { + throw new Error('This Node needs to use addThisNode method'); + } else { + throw new Error('unsupported Value type ' + value.getType().toString()); + } + + this.addNode(pagNode!); + this.addContextOrExportInfoMap(refresh, cid, id, value, pagNode, stmt); + + return pagNode!; + } + + private handleLocalNode(id: NodeID, cid: ContextID, value: Local, stmt?: Stmt): PagNode { + const valueType = value.getType(); + if (valueType instanceof FunctionType && value.getDeclaringStmt() === null) { + return new PagFuncNode(id, cid, value, stmt, valueType.getMethodSignature()); + } else if (value.getName() === GLOBAL_THIS_NAME && value.getDeclaringStmt() == null) { + return new PagGlobalThisNode(id, -1, value); + } else { + return new PagLocalNode(id, cid, value, stmt); + } + } + + private handleInstanceFieldNode(id: NodeID, cid: ContextID, value: ArkInstanceFieldRef, stmt?: Stmt): PagNode { + return this.createFieldNode(id, cid, value, stmt); + } + + private handleStaticFieldNode(id: NodeID, cid: ContextID, value: ArkStaticFieldRef, stmt?: Stmt): PagNode { + return this.createFieldNode(id, cid, value, stmt); + } + + private createFieldNode(id: NodeID, cid: ContextID, value: any, stmt?: Stmt): PagNode { + if (value.getType() instanceof FunctionType) { + return new PagFuncNode(id, cid, value, stmt, (value.getType() as FunctionType).getMethodSignature()); + } else { + return value instanceof ArkStaticFieldRef ? new PagStaticFieldNode(id, cid, value, stmt) : new PagInstanceFieldNode(id, cid, value, stmt); + } + } + + private handleNewExprNode(id: NodeID, cid: ContextID, value: ArkNewExpr, stmt?: Stmt): PagNode { + const classSignature = value.getClassType().getClassSignature(); + if (IsCollectionClass(classSignature)) { + return new PagNewContainerExprNode(id, cid, value, stmt); + } else { + return new PagNewExprNode(id, cid, value, stmt); + } + } + + private addContextOrExportInfoMap(refresh: boolean, cid: ContextID, id: NodeID, + value: PagNodeType, pagNode: PagNode, stmt?: Stmt): void { + if (!(value instanceof ExportInfo)) { + this.addContextMap(refresh, cid, id, value, stmt!, pagNode!); + } else { + this.addExportInfoMap(id, value); + } + } + + private addExportInfoMap(id: NodeID, v: ExportInfo): void { + this.ExportInfoToIdMap = this.ExportInfoToIdMap ?? new Map(); + this.ExportInfoToIdMap.set(v, id); + } + + private addContextMap(refresh: boolean, cid: ContextID, id: NodeID, value: Value, stmt: Stmt, pagNode: PagNode): void { + if (!refresh) { + return; + } + + let ctx2NdMap = this.contextValueToIdMap.get(value); + if (!ctx2NdMap) { + ctx2NdMap = new Map(); + this.contextValueToIdMap.set(value, ctx2NdMap); + } + ctx2NdMap.set(cid, id); + + if (!(value instanceof ArkInstanceFieldRef || value instanceof ArkArrayRef)) { + return; + } + + let base = value.getBase(); + //TODO: remove below once this Local is not uniq in %instInit is fix + if (base instanceof Local && base.getName() === 'this') { + stmt?.getCfg() ?.getStmts() .forEach((s) => { + if (s instanceof ArkAssignStmt && s.getLeftOp() instanceof Local && + (s.getLeftOp() as Local).getName() === 'this') { + base = s.getLeftOp() as Local; + return; + } + }); + } + let ctxMap = this.contextBaseToIdMap.get(base); + if (ctxMap === undefined) { + ctxMap = new Map(); + ctxMap.set(cid, [pagNode.getID()]); + } else { + let nodes = ctxMap.get(cid); + if (nodes === undefined) { + nodes = [pagNode.getID()]; + } else { + nodes.push(pagNode.getID()); + } + ctxMap.set(cid, nodes); + } + this.contextBaseToIdMap.set(base, ctxMap); + } + + /* + * This node has no context info + * but point to node info + */ + public addPagThisRefNode(value: ArkThisRef): PagNode { + let id: NodeID = this.nodeNum + 1; + let pagNode = new PagThisRefNode(id, value); + this.addNode(pagNode); + + return pagNode; + } + + public addPagThisLocalNode(ptNode: NodeID, value: Local): PagNode { + let id: NodeID = this.nodeNum + 1; + let pagNode = new PagLocalNode(id, ptNode, value); + this.addNode(pagNode); + + return pagNode; + } + + public getOrNewThisRefNode(thisRefNodeID: NodeID, value: ArkThisRef): PagNode { + if (thisRefNodeID !== -1) { + return this.getNode(thisRefNodeID) as PagNode + } + + let thisRefNode = this.addPagThisRefNode(value) + return thisRefNode + } + + public getOrNewThisLocalNode(cid: ContextID, ptNode: NodeID, value: Local, s?: Stmt): PagNode { + if (ptNode !== -1) { + return this.getNode(ptNode) as PagNode; + } else { + return this.getOrNewNode(cid, value, s); + } + } + + public hasExportNode(v: ExportInfo): NodeID | undefined { + this.ExportInfoToIdMap = this.ExportInfoToIdMap ?? new Map(); + return this.ExportInfoToIdMap.get(v); + } + + public hasCtxNode(cid: ContextID, v: Value): NodeID | undefined { + let ctx2nd = this.contextValueToIdMap.get(v); + if (!ctx2nd) { + return undefined; + } + + let ndId = ctx2nd.get(cid); + if (!ndId) { + return undefined; + } + + return ndId; + } + + public hasCtxRetNode(cid: ContextID, v: Value): NodeID | undefined { + let ctx2nd = this.contextValueToIdMap.get(v); + if (!ctx2nd) { + return undefined; + } + + let ndId = ctx2nd.get(cid); + if (!ndId) { + return undefined; + } + + return ndId; + } + public getOrNewNode(cid: ContextID, v: PagNodeType, s?: Stmt): PagNode { + let nodeId; + // Value + if (!(v instanceof ExportInfo)) { + nodeId = this.hasCtxNode(cid, v); + } else { + // ExportInfo + nodeId = this.hasExportNode(v); + } + + if (nodeId !== undefined) { + return this.getNode(nodeId) as PagNode; + } + + return this.addPagNode(cid, v, s); + } + + public getNodesByValue(v: Value): Map | undefined { + return this.contextValueToIdMap.get(v); + } + + public getNodesByBaseValue(v: Value): Map | undefined { + return this.contextBaseToIdMap.get(v); + } + + public addPagEdge(src: PagNode, dst: PagNode, kind: PagEdgeKind, stmt?: Stmt): boolean { + // TODO: check if the edge already existing + let edge = new PagEdge(src, dst, kind, stmt); + if (this.ifEdgeExisting(edge)) { + return false; + } + + switch (kind) { + case PagEdgeKind.Copy: + case PagEdgeKind.InterProceduralCopy: + src.addCopyOutEdge(edge); + dst.addCopyInEdge(edge); + if (src instanceof PagFuncNode || + src instanceof PagGlobalThisNode || + src instanceof PagNewExprNode || + src instanceof PagNewContainerExprNode + ) { + this.addrEdge.add(edge); + this.stashAddrEdge.add(edge); + } + break; + case PagEdgeKind.Address: + src.addAddressOutEdge(edge); + dst.addAddressInEdge(edge); + this.addrEdge.add(edge); + this.stashAddrEdge.add(edge); + break; + case PagEdgeKind.Write: + src.addWriteOutEdge(edge); + dst.addWriteInEdge(edge); + break; + case PagEdgeKind.Load: + src.addLoadOutEdge(edge); + dst.addLoadInEdge(edge); + break; + case PagEdgeKind.This: + src.addThisOutEdge(edge); + dst.addThisInEdge(edge); + break; + default: + ; + } + return true; + } + + public getAddrEdges(): PagEdgeSet { + return this.stashAddrEdge; + } + + public resetAddrEdges() { + this.stashAddrEdge.clear(); + } + + public getGraphName(): string { + return 'PAG'; + } + + public dump(name: string): void { + let printer = new GraphPrinter(this); + PrinterBuilder.dump(printer, name); + } +} + +export type InterProceduralSrcType = Local; +export type IntraProceduralEdge = { src: Value, dst: Value, kind: PagEdgeKind, stmt: Stmt } +export type InterProceduralEdge = { src: InterProceduralSrcType, dst: Value, kind: PagEdgeKind } + +export class FuncPag { + private internalEdges!: Set; + private normalCallSites!: Set; + private dynamicCallSites!: Set; + private unknownCallSites!: Set; + + public getInternalEdges(): Set | undefined { + return this.internalEdges; + } + + public addNormalCallSite(cs: CallSite): void { + this.normalCallSites = this.normalCallSites ?? new Set(); + this.normalCallSites.add(cs); + } + + public getNormalCallSites(): Set { + this.normalCallSites = this.normalCallSites ?? new Set(); + return this.normalCallSites; + } + + public addDynamicCallSite(cs: DynCallSite): void { + this.dynamicCallSites = this.dynamicCallSites ?? new Set(); + this.dynamicCallSites.add(cs); + } + + public getDynamicCallSites(): Set { + this.dynamicCallSites = this.dynamicCallSites ?? new Set(); + return this.dynamicCallSites; + } + + public addUnknownCallSite(cs: CallSite): void { + this.unknownCallSites = this.unknownCallSites ?? new Set(); + this.unknownCallSites.add(cs); + } + + public getUnknownCallSites(): Set { + this.unknownCallSites = this.unknownCallSites ?? new Set(); + return this.unknownCallSites; + } + + public addInternalEdge(stmt: ArkAssignStmt, k: PagEdgeKind): boolean { + this.internalEdges === undefined ? this.internalEdges = new Set() : undefined; + let lhOp = stmt.getLeftOp(); + let rhOp = stmt.getRightOp(); + + if (rhOp instanceof Constant) { + return false; + } + + let iEdge: IntraProceduralEdge = { src: rhOp, dst: lhOp, kind: k, stmt: stmt }; + this.internalEdges.add(iEdge); + + return true; + } +} + +export class InterFuncPag { + private interFuncEdges: Set; + + constructor() { + this.interFuncEdges = new Set(); + } + + public getInterProceduralEdges(): Set { + return this.interFuncEdges; + } + + public addToInterProceduralEdgeSet(e: InterProceduralEdge): void { + this.interFuncEdges.add(e); + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PagBuilder.ts b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PagBuilder.ts new file mode 100644 index 0000000000..98abe7e584 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PagBuilder.ts @@ -0,0 +1,1780 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { CallGraph, CallGraphNode, CallGraphNodeKind, CallSite, DynCallSite, FuncID } from '../model/CallGraph'; +import { Scene } from '../../Scene' +import { ArkAssignStmt, ArkInvokeStmt, ArkReturnStmt, Stmt } from '../../core/base/Stmt' +import { + AbstractExpr, + AbstractInvokeExpr, + ArkInstanceInvokeExpr, + ArkNewArrayExpr, + ArkNewExpr, + ArkPtrInvokeExpr, + ArkStaticInvokeExpr +} from '../../core/base/Expr'; +import { + AbstractFieldRef, + ArkArrayRef, + ArkInstanceFieldRef, + ArkParameterRef, + ArkStaticFieldRef, + ArkThisRef +} from '../../core/base/Ref'; +import { Value } from '../../core/base/Value'; +import { ArkMethod } from '../../core/model/ArkMethod'; +import Logger, { LOG_MODULE_TYPE } from "../../utils/logger"; +import { Local } from '../../core/base/Local'; +import { NodeID } from '../../core/graph/BaseExplicitGraph'; +import { ClassSignature } from '../../core/model/ArkSignature'; +import { ArkClass } from '../../core/model/ArkClass'; +import { ClassType, FunctionType, StringType } from '../../core/base/Type'; +import { Constant } from '../../core/base/Constant'; +import { PAGStat } from '../common/Statistics'; +import { ContextID, DUMMY_CID, KLimitedContextSensitive } from './Context'; +import { + FuncPag, + InterFuncPag, + InterProceduralEdge, + IntraProceduralEdge, + Pag, + PagEdgeKind, + PagFuncNode, + PagGlobalThisNode, + PagLocalNode, + PagNewContainerExprNode, + PagNode, + PagNodeType, + PagThisRefNode, + StorageLinkEdgeType, + StorageType +} from './Pag'; +import { GLOBAL_THIS_NAME } from '../../core/common/TSConst'; +import { IPtsCollection } from './PtsDS'; +import { UNKNOWN_FILE_NAME } from '../../core/common/Const'; +import { IsCollectionAPI, IsCollectionMapSet, IsCollectionSetAdd } from './PTAUtils'; +import { PointerAnalysisConfig, PtaAnalysisScale } from './PointerAnalysisConfig'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'PTA'); + +export class CSFuncID { + public cid: ContextID; + public funcID: FuncID; + + constructor(cid: ContextID, fid: FuncID) { + this.cid = cid; + this.funcID = fid; + } +} + +export class PagBuilder { + private pag: Pag; + private cg: CallGraph; + private scale: PtaAnalysisScale; + private funcPags: Map; + private interFuncPags?: Map; + private handledFunc: Set = new Set() + private ctx: KLimitedContextSensitive; + private scene: Scene; + private worklist: CSFuncID[] = []; + private pagStat: PAGStat; + // TODO: change string to hash value + private staticField2UniqInstanceMap: Map = new Map(); + private instanceField2UniqInstanceMap: Map = new Map(); + private cid2ThisRefPtMap: Map = new Map(); + private cid2ThisRefMap: Map = new Map(); + private cid2ThisLocalMap: Map = new Map(); + private sdkMethodReturnValueMap: Map> = new Map(); + // record the SDK API param, and create fake Values + private methodParamValueMap: Map> = new Map(); + private fakeSdkMethodParamDeclaringStmt: Stmt = new ArkAssignStmt(new Local(""), new Local("")); + private funcHandledThisRound: Set = new Set(); + private updatedNodesThisRound: Map> = new Map() + private singletonFuncMap: Map = new Map(); + private globalThisValue: Local = new Local(GLOBAL_THIS_NAME); + private globalThisPagNode?: PagGlobalThisNode; + private storagePropertyMap: Map> = new Map(); + private externalScopeVariableMap: Map = new Map(); + + constructor(p: Pag, cg: CallGraph, s: Scene, kLimit: number, scale: PtaAnalysisScale) { + this.pag = p; + this.cg = cg; + this.scale = scale; + this.funcPags = new Map; + this.ctx = new KLimitedContextSensitive(kLimit); + this.scene = s; + this.pagStat = new PAGStat(); + } + + private buildFuncPagAndAddToWorklist(cs: CSFuncID): CSFuncID { + if (this.worklist.includes(cs)) { + return cs; + } + + this.buildFuncPag(cs.funcID); + if (this.isSingletonFunction(cs.funcID)) { + cs.cid = DUMMY_CID; + } + + this.worklist.push(cs); + return cs + } + + private addToFuncHandledListThisRound(id: FuncID) { + if (this.funcHandledThisRound.has(id)) { + return; + } + + this.funcHandledThisRound.add(id) + } + + public buildForEntries(funcIDs: FuncID[]): void { + this.worklist = []; + funcIDs.forEach(funcID => { + let cid = this.ctx.getNewContextID(funcID); + let csFuncID = new CSFuncID(cid, funcID); + this.buildFuncPagAndAddToWorklist(csFuncID); + }); + + this.handleReachable(); + this.globalThisPagNode = this.getOrNewGlobalThisNode(-1) as PagGlobalThisNode; + this.pag.addPagEdge(this.globalThisPagNode, this.globalThisPagNode, PagEdgeKind.Copy); + } + + public handleReachable(): boolean { + if (this.worklist.length === 0) { + return false; + } + this.funcHandledThisRound.clear(); + + while (this.worklist.length > 0) { + let csFunc = this.worklist.shift() as CSFuncID; + this.buildPagFromFuncPag(csFunc.funcID, csFunc.cid); + this.addToFuncHandledListThisRound(csFunc.funcID); + } + + return true; + } + + public build(): void { + for (let funcID of this.cg.getEntries()) { + let cid = this.ctx.getNewContextID(funcID); + let csFuncID = new CSFuncID(cid, funcID); + this.buildFuncPagAndAddToWorklist(csFuncID); + + this.handleReachable(); + } + } + + public buildFuncPag(funcID: FuncID): boolean { + if (this.funcPags.has(funcID)) { + return false; + } + + let arkMethod = this.cg.getArkMethodByFuncID(funcID); + if (arkMethod == null) { + return false; + } + + let cfg = arkMethod.getCfg() + if (!cfg) { + this.buildSDKFuncPag(funcID); + return false + } + + logger.trace(`[build FuncPag] ${arkMethod.getSignature().toString()}`) + + let fpag = new FuncPag(); + for (let stmt of cfg.getStmts()) { + if (stmt instanceof ArkAssignStmt) { + stmt.getRightOp().getUses().forEach((v) => { + this.handleValueFromExternalScope(v, funcID); + }); + // Add non-call edges + let kind = this.getEdgeKindForAssignStmt(stmt); + if (kind !== PagEdgeKind.Unknown) { + fpag.addInternalEdge(stmt, kind); + continue; + } + + // handle call + this.buildInvokeExprInAssignStmt(stmt, fpag); + } else if (stmt instanceof ArkInvokeStmt && this.scale === PtaAnalysisScale.WholeProgram) { + this.buildInvokeExprInInvokeStmt(stmt, fpag); + } else { + // TODO: need handle other type of stmt? + } + } + + this.funcPags.set(funcID, fpag); + this.pagStat.numTotalFunction++; + return true; + } + + private buildInvokeExprInAssignStmt(stmt: ArkAssignStmt, fpag: FuncPag): void { + let ivkExpr = stmt.getInvokeExpr()!; + if (ivkExpr instanceof ArkStaticInvokeExpr) { + let callSites = this.cg.getCallSiteByStmt(stmt); + if (callSites.length !== 0) { + // direct call is already existing in CG + // TODO: API Invoke stmt has anonymous method param, how to add these param into callee + callSites.forEach((cs) => { + this.addFuncPagCallSite(fpag, cs, ivkExpr); + }); + } else { + throw new Error('Can not find static callsite'); + } + } else if (ivkExpr instanceof ArkInstanceInvokeExpr || ivkExpr instanceof ArkPtrInvokeExpr) { + let ptcs = this.cg.getDynCallsiteByStmt(stmt); + if (ptcs) { + this.addToDynamicCallSite(fpag, ptcs); + } + } + } + + private addFuncPagCallSite(fpag: FuncPag, cs: CallSite, ivkExpr: AbstractInvokeExpr): void { + if (ivkExpr instanceof ArkStaticInvokeExpr) { + if (ivkExpr.getMethodSignature().getDeclaringClassSignature() + .getDeclaringFileSignature().getFileName() === UNKNOWN_FILE_NAME) { + fpag.addUnknownCallSite(cs); + } else { + fpag.addNormalCallSite(cs); + } + } + } + + private buildInvokeExprInInvokeStmt(stmt: ArkInvokeStmt, fpag: FuncPag): void { + // TODO: discuss if we need a invokeStmt + + let callSites = this.cg.getCallSiteByStmt(stmt); + if (callSites.length !== 0) { + // direct call or constructor call is already existing in CG + // TODO: some ptr invoke stmt is recognized as Static invoke in tests/resources/callgraph/funPtrTest1/fnPtrTest4.ts + // TODO: instance invoke(ptr invoke) + callSites.forEach((cs) => { + if (this.cg.isUnknownMethod(cs.calleeFuncID)) { + fpag.addUnknownCallSite(cs); + } else { + fpag.addNormalCallSite(cs); + } + }); + + return; + } + + let dycs = this.cg.getDynCallsiteByStmt(stmt); + if (dycs) { + this.addToDynamicCallSite(fpag, dycs); + } else { + throw new Error('Can not find callsite by stmt'); + } + } + + /** + * will not create real funcPag, only create param values + */ + private buildSDKFuncPag(funcID: FuncID): void { + // check if SDK method + let cgNode = this.cg.getNode(funcID) as CallGraphNode; + if (!cgNode.isSdkMethod()) { + return; + } + let paramArr: Map = this.createDummyParamValue(funcID); + + this.methodParamValueMap.set(funcID, paramArr); + } + + private createDummyParamValue(funcID: FuncID, type: number = 1): Map { + let arkMethod = this.cg.getArkMethodByFuncID(funcID); + if (!arkMethod) { + return new Map(); + } + + let args = arkMethod.getParameters(); + if (!args) { + return new Map(); + } + + let paramArr: Map = new Map(); + + if (type === 0) { + // heapObj + args.forEach((arg, index) => { + let paramType = arg.getType(); + if (!(paramType instanceof ClassType)) { + return; + // TODO: support more type + } + + let argInstance: ArkNewExpr = new ArkNewExpr(paramType); + paramArr.set(index, argInstance); + }); + } else if (type === 1) { + // Local + args.forEach((arg, index) => { + let argInstance: Local = new Local(arg.getName(), arg.getType()); + argInstance.setDeclaringStmt(this.fakeSdkMethodParamDeclaringStmt); + paramArr.set(index, argInstance); + }); + } + + return paramArr; + } + + private createDummyParamPagNodes(value: Map, funcID: FuncID): Map { + let paramPagNodes: Map = new Map(); + let method = this.cg.getArkMethodByFuncID(funcID)!; + if (!method || !method.getCfg()) { + return paramPagNodes; + } + + value.forEach((v, index) => { + let paramArkExprNode = this.pag.getOrNewNode(DUMMY_CID, v, this.fakeSdkMethodParamDeclaringStmt); + paramPagNodes.set(index, paramArkExprNode.getID()); + }); + + return paramPagNodes; + } + + public buildPagFromFuncPag(funcID: FuncID, cid: ContextID) { + let funcPag = this.funcPags.get(funcID); + if (funcPag === undefined) { + return; + } + if (this.handledFunc.has(`${cid}-${funcID}`)) { + return; + } + + this.addEdgesFromFuncPag(funcPag, cid, funcID); + let interFuncPag = this.interFuncPags?.get(funcID); + if (interFuncPag) { + this.addEdgesFromInterFuncPag(interFuncPag, cid); + } + + this.addCallsEdgesFromFuncPag(funcPag, cid); + this.addDynamicCallSite(funcPag, funcID); + this.addUnknownCallSite(funcPag, funcID); + this.handledFunc.add(`${cid}-${funcID}`); + } + + /// Add Pag Nodes and Edges in function + public addEdgesFromFuncPag(funcPag: FuncPag, cid: ContextID, funcID: FuncID): boolean { + let inEdges = funcPag.getInternalEdges(); + if (inEdges === undefined) { + return false; + } + let paramNodes; + let paramRefIndex = 0; + if (this.scale === PtaAnalysisScale.MethodLevel) { + paramNodes = this.createDummyParamPagNodes(this.createDummyParamValue(funcID, 0), funcID); + } + + for (let e of inEdges) { + let srcPagNode = this.getOrNewPagNode(cid, e.src, e.stmt); + let dstPagNode = this.getOrNewPagNode(cid, e.dst, e.stmt); + + this.pag.addPagEdge(srcPagNode, dstPagNode, e.kind, e.stmt); + + // Take place of the real stmt for return + if (dstPagNode.getStmt() instanceof ArkReturnStmt) { + dstPagNode.setStmt(e.stmt); + } + + // for demand-driven analysis, add fake parameter heapObj nodes + if (e.src instanceof ArkParameterRef && this.scale === PtaAnalysisScale.MethodLevel) { + let paramObjNodeID = paramNodes?.get(paramRefIndex ++); + if (!paramObjNodeID) { + continue; + } + + this.pag.addPagEdge(this.pag.getNode(paramObjNodeID) as PagNode, srcPagNode, PagEdgeKind.Address); + } + } + + return true; + } + + /// add Copy edges interprocedural + public addCallsEdgesFromFuncPag(funcPag: FuncPag, cid: ContextID): boolean { + for (let cs of funcPag.getNormalCallSites()) { + let ivkExpr = cs.callStmt.getInvokeExpr(); + let calleeCid = this.ctx.getOrNewContext(cid, cs.calleeFuncID, true); + + let calleeCGNode = this.cg.getNode(cs.calleeFuncID) as CallGraphNode; + + if (this.scale === PtaAnalysisScale.MethodLevel) { + this.addStaticPagCallReturnEdge(cs, cid, calleeCid); + } + + // process the Storage API(Static) + if (!this.processStorage(cs, calleeCGNode, cid)) { + // If not Storage API, process normal edge + this.addStaticPagCallEdge(cs, cid, calleeCid); + } + + // Add edge to thisRef for special calls + if (calleeCGNode.getKind() === CallGraphNodeKind.constructor || + calleeCGNode.getKind() === CallGraphNodeKind.intrinsic) { + let callee = this.scene.getMethod(this.cg.getMethodByFuncID(cs.calleeFuncID)!)! + if (ivkExpr instanceof ArkInstanceInvokeExpr) { + let baseNode = this.getOrNewPagNode(cid, ivkExpr.getBase()) + let baseNodeID = baseNode.getID(); + + this.addThisRefCallEdge(baseNodeID, cid, ivkExpr, callee, calleeCid, cs.callerFuncID); + } else { + logger.error(`constructor or intrinsic func is static ${ivkExpr!.toString()}`); + } + } + } + + return true; + } + + /** + * process Storage API + * @returns boolean: check if the cs represent a Storage API, no matter the API will success or fail + */ + private processStorage(cs: CallSite | DynCallSite, calleeCGNode: CallGraphNode, cid: ContextID): boolean { + let storageName = calleeCGNode.getMethod().getDeclaringClassSignature().getClassName(); + let storageType: StorageType = this.getStorageType(storageName, cs, cid); + + // TODO: add other storages + if (storageType === StorageType.APP_STORAGE) { + let calleeName = calleeCGNode.getMethod().getMethodSubSignature().getMethodName(); + + // TODO: complete AppStorage API + if (calleeName === 'setOrCreate') { + this.processStorageSetOrCreate(cs, cid); + } else if (calleeName === 'link') { + this.processStorageLink(cs, cid); + } else if (calleeName === 'prop') { + this.processStorageProp(cs, cid); + } else if (calleeName === 'set') { + this.processStorageSet(cs, cid); + } else if (calleeName === 'get') { + this.processStorageGet(cs, cid); + } + return true; + } else if (storageType === StorageType.LOCAL_STORAGE) { + // TODO: LocalStorage is not Static + } + + return false; + } + + private processStorageSetOrCreate(cs: CallSite | DynCallSite, cid: ContextID): void { + let propertyStr = this.getPropertyName(cs.args![0]); + if (!propertyStr) { + return; + } + + let propertyName = propertyStr; + let propertyNode = this.getOrNewPropertyNode(StorageType.APP_STORAGE, propertyName, cs.callStmt); + let storageObj = cs.args![1]; + + this.addPropertyLinkEdge(propertyNode, storageObj, cid, cs.callStmt, StorageLinkEdgeType.Local2Property); + } + + private processStorageLink(cs: CallSite | DynCallSite, cid: ContextID): void { + let propertyStr = this.getPropertyName(cs.args![0]); + if (!propertyStr) { + return; + } + + let propertyName = propertyStr; + let propertyNode = this.getOrNewPropertyNode(StorageType.APP_STORAGE, propertyName, cs.callStmt); + let leftOp = (cs.callStmt as ArkAssignStmt).getLeftOp() as Local; + let linkedOpNode = this.pag.getOrNewNode(cid, leftOp) as PagNode; + if (linkedOpNode instanceof PagLocalNode) { + linkedOpNode.setStorageLink(StorageType.APP_STORAGE, propertyName); + } + + this.pag.addPagEdge(propertyNode, linkedOpNode, PagEdgeKind.Copy); + this.pag.addPagEdge(linkedOpNode, propertyNode, PagEdgeKind.Copy); + } + + private processStorageProp(cs: CallSite | DynCallSite, cid: ContextID): void { + let propertyStr = this.getPropertyName(cs.args![0]); + if (!propertyStr) { + return; + } + + let propertyName = propertyStr; + let propertyNode = this.getOrNewPropertyNode(StorageType.APP_STORAGE, propertyName, cs.callStmt); + let leftOp = (cs.callStmt as ArkAssignStmt).getLeftOp() as Local; + let linkedOpNode = this.pag.getOrNewNode(cid, leftOp) as PagNode; + if (linkedOpNode instanceof PagLocalNode) { + linkedOpNode.setStorageLink(StorageType.APP_STORAGE, propertyName); + } + + this.pag.addPagEdge(propertyNode, linkedOpNode, PagEdgeKind.Copy); + } + + private processStorageSet(cs: CallSite | DynCallSite, cid: ContextID): void { + let ivkExpr: AbstractInvokeExpr = cs.callStmt.getInvokeExpr()!; + if (ivkExpr instanceof ArkInstanceInvokeExpr) { + let base = ivkExpr.getBase(); + let baseNode = this.pag.getOrNewNode(cid, base) as PagLocalNode; + + if (baseNode.isStorageLinked()) { + let argsNode = this.pag.getOrNewNode(cid, cs.args![0]) as PagNode; + + this.pag.addPagEdge(argsNode, baseNode, PagEdgeKind.Copy); + } + } else if (ivkExpr instanceof ArkStaticInvokeExpr) { + // TODO: process AppStorage.set() + } + } + + private processStorageGet(cs: CallSite | DynCallSite, cid: ContextID): void { + if (!(cs.callStmt instanceof ArkAssignStmt)) { + return; + } + let leftOp = (cs.callStmt as ArkAssignStmt).getLeftOp() as Local; + let ivkExpr = cs.callStmt.getInvokeExpr(); + let propertyName!: string; + if (ivkExpr instanceof ArkStaticInvokeExpr) { + let propertyStr = this.getPropertyName(cs.args![0]); + if (propertyStr) { + propertyName = propertyStr; + } + } else if (ivkExpr instanceof ArkInstanceInvokeExpr) { + let baseNode = this.pag.getOrNewNode(cid, ivkExpr.getBase()) as PagLocalNode; + if (baseNode.isStorageLinked()) { + propertyName = baseNode.getStorage().PropertyName!; + } + } + + let propertyNode = this.getPropertyNode(StorageType.APP_STORAGE, propertyName, cs.callStmt); + if (!propertyNode) { + return; + } + + this.pag.addPagEdge( + propertyNode, this.pag.getOrNewNode(cid, leftOp, cs.callStmt), + PagEdgeKind.Copy, cs.callStmt + ); + } + + private getPropertyName(value: Value): string | undefined { + if (value instanceof Local) { + let type = value.getType(); + if (type instanceof StringType) { + return type.getName(); + } + } else if (value instanceof Constant) { + return value.getValue(); + } + + return undefined; + } + + public addDynamicCallSite(funcPag: FuncPag, funcID: FuncID) { + // add dyn callsite in funcpag to base node + for (let cs of funcPag.getDynamicCallSites()) { + let invokeExpr: AbstractInvokeExpr = cs.callStmt.getInvokeExpr()!; + let base!: Local; + if (invokeExpr instanceof ArkInstanceInvokeExpr) { + base = invokeExpr.getBase(); + } else if (invokeExpr instanceof ArkPtrInvokeExpr && invokeExpr.getFuncPtrLocal() instanceof Local) { + base = invokeExpr.getFuncPtrLocal() as Local; + } + // TODO: check base under different cid + let baseNodeIDs = this.pag.getNodesByValue(base); + if (!baseNodeIDs) { + // bind the call site to export base + let interProceduralLocal = this.getSourceValueFromExternalScope(base, funcID); + if (interProceduralLocal) { + baseNodeIDs = this.pag.getNodesByValue(interProceduralLocal); + } + } + + if (!baseNodeIDs) { + logger.warn(`[build dynamic call site] can not handle call site with base ${base.toString()}`); + continue; + } + + for (let nodeID of baseNodeIDs!.values()) { + let node = this.pag.getNode(nodeID); + if (!(node instanceof PagLocalNode)) { + continue; + } + + node.addRelatedDynCallSite(cs); + } + } + } + + public addUnknownCallSite(funcPag: FuncPag, funcID: FuncID): void { + let method = this.cg.getArkMethodByFuncID(funcID); + + if (!method) { + throw new Error(`can not find ArkMethod by FuncID ${funcID}`); + } + + let locals = method.getBody()?.getLocals()!; + + funcPag.getUnknownCallSites().forEach((unknownCallSite) => { + let calleeName = unknownCallSite.callStmt.getInvokeExpr()?.getMethodSignature() + .getMethodSubSignature().getMethodName()!; + + let base = locals.get(calleeName); + if (!base) { + return; + } + let baseNodeIDs = this.pag.getNodesByValue(base); + if (!baseNodeIDs) { + logger.warn(`[build dynamic call site] can not handle call site with base ${base.toString()}`); + return; + } + for (let nodeID of baseNodeIDs!.values()) { + let node = this.pag.getNode(nodeID); + if (!(node instanceof PagLocalNode)) { + continue; + } + + node.addRelatedUnknownCallSite(unknownCallSite); + } + }) + } + + public addDynamicCallEdge(cs: DynCallSite | CallSite, baseClassPTNode: NodeID, cid: ContextID): NodeID[] { + let srcNodes: NodeID[] = []; + let ivkExpr = cs.callStmt.getInvokeExpr(); + + let ptNode = this.pag.getNode(baseClassPTNode) as PagNode; + let value = (ptNode as PagNode).getValue(); + let callees: ArkMethod[] = this.getDynamicCallee(ptNode, value, ivkExpr!, cs); + + for (let callee of callees) { + if (!callee) { + continue; + } + // get caller and callee CG node, add param and return value PAG edge + let dstCGNode = this.cg.getCallGraphNodeByMethod(callee.getSignature()); + let callerNode = this.cg.getNode(cs.callerFuncID) as CallGraphNode; + if (!callerNode) { + throw new Error("Can not get caller method node"); + } + // update call graph + // TODO: movo to cgbuilder + this.cg.addDynamicCallEdge(callerNode.getID(), dstCGNode.getID(), cs.callStmt); + if (!this.cg.detectReachable(dstCGNode.getID(), callerNode.getID())) { + let calleeCid = this.ctx.getOrNewContext(cid, dstCGNode.getID(), true); + let staticCS = new CallSite(cs.callStmt, cs.args, dstCGNode.getID(), cs.callerFuncID); + + if (this.scale === PtaAnalysisScale.MethodLevel) { + srcNodes.push(...this.addStaticPagCallReturnEdge(staticCS, baseClassPTNode, calleeCid)); + continue; + } + srcNodes.push(...this.processContainerPagCallEdge(staticCS, cid, baseClassPTNode)); + srcNodes.push(...this.addStaticPagCallEdge(staticCS, cid, calleeCid)); + + // Pass base's pts to callee's this pointer + if (!dstCGNode.isSdkMethod() && ivkExpr instanceof ArkInstanceInvokeExpr) { + let srcBaseNode = this.addThisRefCallEdge(baseClassPTNode, cid, ivkExpr, callee!, calleeCid, cs.callerFuncID); + srcNodes.push(srcBaseNode); + } + } + } + + return srcNodes; + } + + private getDynamicCallee(ptNode: PagNode, value: Value, ivkExpr: AbstractInvokeExpr, cs: DynCallSite | CallSite): ArkMethod[] { + let callee: ArkMethod[] = []; + + if (ptNode instanceof PagFuncNode) { + // function ptr invoke + let tempCallee = this.scene.getMethod(ptNode.getMethod()); + + if (!callee) { + return callee; + } + callee.push(tempCallee!); + return callee; + } + //else branch + let calleeName = ivkExpr!.getMethodSignature().getMethodSubSignature().getMethodName(); + // instance method invoke + if (!(value instanceof ArkNewExpr || value instanceof ArkNewArrayExpr)) { + return callee; + } + let tempCallee; + + // try to get callee by MethodSignature + if (value instanceof ArkNewExpr) { + // get class signature + let clsSig = (value.getType() as ClassType).getClassSignature() as ClassSignature; + let cls; + + cls = this.scene.getClass(clsSig) as ArkClass; + + while (!tempCallee && cls) { + tempCallee = cls.getMethodWithName(calleeName); + cls = cls.getSuperClass(); + } + + if (!tempCallee) { + tempCallee = this.scene.getMethod(ivkExpr!.getMethodSignature()); + } + } + + if (!tempCallee && cs.args) { + // while pts has {o_1, o_2} and invoke expr represents a method that only {o_1} has + // return empty node when {o_2} come in + // try to get callee by anonymous method in param + for (let arg of cs.args) { + // TODO: anonymous method param and return value pointer pass + let argType = arg.getType(); + if (argType instanceof FunctionType) { + callee.push(this.scene.getMethod(argType.getMethodSignature())!); + } + } + } else if (tempCallee) { + callee.push(tempCallee); + } + + return callee; + } + + public addUpdatedNode(nodeID: NodeID, diffPT: IPtsCollection) { + let ptaConfig = PointerAnalysisConfig.getInstance(); + let updatedNode = this.updatedNodesThisRound.get(nodeID) ?? new ptaConfig.ptsCollectionCtor(); + updatedNode.union(diffPT); + this.updatedNodesThisRound.set(nodeID, updatedNode); + } + + public getUpdatedNodes() { + return this.updatedNodesThisRound; + } + + public resetUpdatedNodes() { + this.updatedNodesThisRound.clear(); + } + + public handleUnkownDynamicCall(cs: DynCallSite, cid: ContextID): NodeID[] { + let srcNodes: NodeID[] = []; + let callerNode = this.cg.getNode(cs.callerFuncID) as CallGraphNode; + let ivkExpr = cs.callStmt.getInvokeExpr() as AbstractInvokeExpr; + logger.warn("Handling unknown dyn call site : \n " + callerNode.getMethod().toString() + + '\n --> ' + ivkExpr.toString() + '\n CID: ' + cid); + + let callees: ArkMethod[] = [] + let callee: ArkMethod | null = null; + callee = this.scene.getMethod(ivkExpr.getMethodSignature()); + if (!callee) { + cs.args?.forEach(arg => { + if (!(arg.getType() instanceof FunctionType)) { + return; + } + + callee = this.scene.getMethod((arg.getType() as FunctionType).getMethodSignature()); + if (callee) { + callees.push(callee); + } + }) + } else { + callees.push(callee); + } + + if (callees.length === 0) { + return srcNodes; + } + + callees.forEach(callee => { + let dstCGNode = this.cg.getCallGraphNodeByMethod(callee.getSignature()); + if (!callerNode) { + throw new Error("Can not get caller method node"); + } + + if (this.processStorage(cs, dstCGNode, cid)) { + if (ivkExpr.getArgs().length !== 0) { + // for AppStorage.set() instance invoke, add obj to reanalyze list + let argsNode = this.pag.getOrNewNode(cid, cs.args![0]); + srcNodes.push(argsNode.getID()); + } + } + + logger.warn(`\tAdd call edge of unknown call ${callee.getSignature().toString()}`) + this.cg.addDynamicCallEdge(callerNode.getID(), dstCGNode.getID(), cs.callStmt); + if (!this.cg.detectReachable(dstCGNode.getID(), callerNode.getID())) { + let calleeCid = this.ctx.getOrNewContext(cid, dstCGNode.getID(), true); + let staticCS = new CallSite(cs.callStmt, cs.args, dstCGNode.getID(), cs.callerFuncID); + let staticSrcNodes = this.addStaticPagCallEdge(staticCS, cid, calleeCid); + srcNodes.push(...staticSrcNodes); + } + }) + return srcNodes; + } + + public handleUnprocessedCallSites(processedCallSites: Set): NodeID[] { + let reAnalyzeNodes: NodeID[] = []; + for (let funcID of this.funcHandledThisRound) { + let funcPag = this.funcPags.get(funcID) + if (!funcPag) { + logger.error(`can not find funcPag of handled func ${funcID}`) + continue + } + let callSites = funcPag.getDynamicCallSites() + + const diffCallSites = new Set(Array.from(callSites).filter(item => !processedCallSites.has(item))) + diffCallSites.forEach((cs) => { + let ivkExpr = cs.callStmt.getInvokeExpr(); + if (!(ivkExpr instanceof ArkInstanceInvokeExpr)) { + return; + } + // Get local of base class + let base = ivkExpr.getBase(); + // TODO: remove this after multiple this local fixed + base = this.getRealThisLocal(base, cs.callerFuncID) + // Get PAG nodes for this base's local + let ctx2NdMap = this.pag.getNodesByValue(base); + if (!ctx2NdMap) { + return; + } + + for (let [cid] of ctx2NdMap.entries()) { + reAnalyzeNodes.push(...this.handleUnkownDynamicCall(cs, cid)); + } + }) + } + + return reAnalyzeNodes; + } + + private addThisRefCallEdge(baseClassPTNode: NodeID, cid: ContextID, + ivkExpr: ArkInstanceInvokeExpr, callee: ArkMethod, calleeCid: ContextID, callerFunID: FuncID): NodeID { + + if (!callee || !callee.getCfg()) { + logger.error(`callee is null`); + return -1; + } + let thisAssignStmt = callee.getCfg()?.getStmts().filter(s => + s instanceof ArkAssignStmt && s.getRightOp() instanceof ArkThisRef); + let thisPtr = (thisAssignStmt?.at(0) as ArkAssignStmt).getRightOp() as ArkThisRef; + if (!thisPtr) { + throw new Error('Can not get this ptr'); + } + + // IMPORTANT: set cid 2 base Pt info firstly + this.cid2ThisRefPtMap.set(calleeCid, baseClassPTNode); + let thisRefNode = this.getOrNewThisRefNode(calleeCid, thisPtr) as PagThisRefNode; + thisRefNode.addPTNode(baseClassPTNode); + let srcBaseLocal = ivkExpr.getBase(); + srcBaseLocal = this.getRealThisLocal(srcBaseLocal, callerFunID); + let srcNodeId = this.pag.hasCtxNode(cid, srcBaseLocal); + if (!srcNodeId) { + // this check is for export local and closure use + // replace the invoke base, because its origin base has no pag node + let interProceduralLocal = this.getSourceValueFromExternalScope(srcBaseLocal, callerFunID); + if (interProceduralLocal) { + srcNodeId = this.pag.hasCtxNode(cid, interProceduralLocal); + } + } + + if (!srcNodeId) { + throw new Error('Can not get base node'); + } + + this.pag.addPagEdge(this.pag.getNode(srcNodeId) as PagNode, thisRefNode, PagEdgeKind.This); + return srcNodeId; + } + + /* + * Add copy edges from arguments to parameters + * ret edges from return values to callsite + * Return src node + */ + public addStaticPagCallEdge(cs: CallSite, callerCid: ContextID, calleeCid?: ContextID): NodeID[] { + if (!calleeCid) { + calleeCid = this.ctx.getOrNewContext(callerCid, cs.calleeFuncID, true); + } + + let srcNodes: NodeID[] = [] + // Add reachable + + let calleeNode = this.cg.getNode(cs.calleeFuncID) as CallGraphNode; + let calleeMethod: ArkMethod | null = this.scene.getMethod(calleeNode.getMethod()); + if (!calleeMethod) { + // TODO: check if nodes need to delete + return srcNodes; + } + if (calleeNode.isSdkMethod()) { + srcNodes.push(...this.addSDKMethodPagCallEdge(cs, callerCid, calleeCid)); + return srcNodes; + } + + if (!calleeMethod.getCfg()) { + // method have no cfg body + return srcNodes; + } + + let calleeCS = this.buildFuncPagAndAddToWorklist(new CSFuncID(calleeCid, cs.calleeFuncID)); + // callee cid will updated if callee is singleton + calleeCid = calleeCS.cid + + // TODO: getParameterInstances's performance is not good. Need to refactor + let params = calleeMethod.getCfg()!.getStmts() + .filter(stmt => stmt instanceof ArkAssignStmt && stmt.getRightOp() instanceof ArkParameterRef) + .map(stmt => (stmt as ArkAssignStmt).getRightOp()); + + srcNodes.push(...this.addCallParamPagEdge(params, cs, callerCid, calleeCid)); + + // add ret to caller edges + let retStmts = calleeMethod.getReturnStmt(); + // TODO: call statement must be a assignment state + if (cs.callStmt instanceof ArkAssignStmt) { + let retDst = cs.callStmt.getLeftOp(); + for (let retStmt of retStmts) { + let retValue = (retStmt as ArkReturnStmt).getOp(); + if (retValue instanceof Local) { + let srcPagNode = this.getOrNewPagNode(calleeCid, retValue, retStmt); + let dstPagNode = this.getOrNewPagNode(callerCid, retDst, cs.callStmt); + + this.pag.addPagEdge(srcPagNode, dstPagNode, PagEdgeKind.Copy, retStmt); + } else if (retValue instanceof Constant) { + continue; + } else if (retValue instanceof AbstractExpr) { + logger.debug(retValue); + continue; + } else { + throw new Error('return dst not a local or constant, but: ' + retValue.getType().toString()) + } + } + } + + return srcNodes; + } + + public addStaticPagCallReturnEdge(cs: CallSite, callerCid: ContextID, calleeCid: ContextID): NodeID[] { + if (!calleeCid) { + calleeCid = this.ctx.getOrNewContext(callerCid, cs.calleeFuncID, true); + } + + let srcNodes: NodeID[] = []; + // Add reachable + + let calleeNode = this.cg.getNode(cs.calleeFuncID) as CallGraphNode; + let calleeMethod: ArkMethod | null = this.scene.getMethod(calleeNode.getMethod()); + if (!calleeMethod) { + // TODO: check if nodes need to delete + return srcNodes; + } + srcNodes.push(...this.addSDKMethodReturnPagEdge(cs, callerCid, calleeCid, calleeMethod)); + return srcNodes; + } + + public addCallParamPagEdge(params: Value[], cs: CallSite, callerCid: ContextID, calleeCid: ContextID): NodeID[] { + let srcNodes: NodeID[] = []; + let argNum = cs.args?.length; + if (argNum === params.length) { + // add args to parameters edges + for (let i = 0; i < argNum; i++) { + let arg = cs.args?.at(i); + let param = params.at(i); + if (!arg || !param) { + return srcNodes; + } + + if (arg instanceof Constant || arg instanceof AbstractExpr) { + // TODO: handle AbstractExpr + continue; + } + + // Get or create new PAG node for argument and parameter + let srcPagNode = this.getOrNewPagNode(callerCid, arg, cs.callStmt); + let dstPagNode = this.getOrNewPagNode(calleeCid, param, cs.callStmt); + + this.pag.addPagEdge(srcPagNode, dstPagNode, PagEdgeKind.Copy, cs.callStmt); + srcNodes.push(srcPagNode.getID()); + // TODO: handle other types of parmeters + } + } else { + /** + * process foreach situation + * e.g. arr.forEach((item) => { ... }) + * cs.args is anonymous method local, will have only 1 parameter + * but inside foreach will have >= 1 parameters + */ + if (!(cs.callStmt.getInvokeExpr()?.getMethodSignature().getMethodSubSignature().getMethodName() === 'forEach')) { + return srcNodes; + } + // container value is the base value of callstmt, its points-to is PagNewContainerExprNode + let containerValue = (cs.callStmt.getInvokeExpr() as ArkInstanceInvokeExpr).getBase(); + let param = params.at(0); + if (!containerValue || !param) { + return srcNodes; + } + + let basePagNode = this.getOrNewPagNode(callerCid, containerValue, cs.callStmt); + let dstPagNode = this.getOrNewPagNode(calleeCid, param, cs.callStmt); + + for (let pt of basePagNode.getPointTo()) { + let newContainerExprPagNode = this.pag.getNode(pt) as PagNewContainerExprNode; + + // PagNewContainerExprNode's points-to is the element node + if (!newContainerExprPagNode || !newContainerExprPagNode.getElementNode()) { + continue; + } + let srcPagNode = this.pag.getNode(newContainerExprPagNode.getElementNode()!) as PagNode; + + // connect the element node with the value inside foreach + this.pag.addPagEdge(srcPagNode, dstPagNode, PagEdgeKind.Copy, cs.callStmt); + srcNodes.push(srcPagNode.getID()); + } + } + return srcNodes; + } + + private addSDKMethodPagCallEdge(cs: CallSite, callerCid: ContextID, calleeCid: ContextID): NodeID[] { + let srcNodes: NodeID[] = []; + let calleeNode = this.cg.getNode(cs.calleeFuncID) as CallGraphNode; + let calleeMethod: ArkMethod | null = this.scene.getMethod(calleeNode.getMethod()); + + if (!calleeMethod) { + return srcNodes; + } + + // block the container SDK + if (IsCollectionAPI(calleeMethod.getSignature())) { + return srcNodes; + } + + if (!this.methodParamValueMap.has(calleeNode.getID())) { + this.buildSDKFuncPag(calleeNode.getID()); + } + + srcNodes.push(...this.addSDKMethodReturnPagEdge(cs, callerCid, calleeCid, calleeMethod)); + srcNodes.push(...this.addSDKMethodParamPagEdge(cs, callerCid, calleeCid, calleeNode.getID())); + return srcNodes + } + + private addSDKMethodReturnPagEdge(cs: CallSite, callerCid: ContextID, calleeCid: ContextID, calleeMethod: ArkMethod): NodeID[] { + let srcNodes: NodeID[] = []; + let returnType = calleeMethod.getReturnType(); + if (!(returnType instanceof ClassType) || !(cs.callStmt instanceof ArkAssignStmt)) { + return srcNodes; + } + + // check fake heap object exists or not + let cidMap = this.sdkMethodReturnValueMap.get(calleeMethod) + if (!cidMap) { + cidMap = new Map() + } + let newExpr = cidMap.get(calleeCid) + if (!newExpr) { + if (returnType instanceof ClassType) { + newExpr = new ArkNewExpr(returnType) + } + } + cidMap.set(calleeCid, newExpr!) + this.sdkMethodReturnValueMap.set(calleeMethod, cidMap) + + let srcPagNode = this.getOrNewPagNode(calleeCid, newExpr!) + let dstPagNode = this.getOrNewPagNode(callerCid, cs.callStmt.getLeftOp(), cs.callStmt); + + this.pag.addPagEdge(srcPagNode, dstPagNode, PagEdgeKind.Address, cs.callStmt); + srcNodes.push(srcPagNode.getID()); + return srcNodes; + } + + private addSDKMethodParamPagEdge(cs: CallSite, callerCid: ContextID, calleeCid: ContextID, funcID: FuncID): NodeID[] { + let argNum = cs.args?.length; + let srcNodes: NodeID[] = []; + + if (!argNum) { + return srcNodes; + } + + // add args to parameters edges + for (let i = 0; i < argNum; i++) { + let arg = cs.args?.at(i); + let paramValue; + + if (arg instanceof Local && arg.getType() instanceof FunctionType) { + // TODO: cannot find value + paramValue = this.methodParamValueMap.get(funcID)!.get(i); + } else { + continue; + } + + if (!(arg && paramValue)) { + continue; + } + + // Get or create new PAG node for argument and parameter + let srcPagNode = this.getOrNewPagNode(callerCid, arg, cs.callStmt); + let dstPagNode = this.getOrNewPagNode(calleeCid, paramValue, cs.callStmt); + + if (dstPagNode instanceof PagLocalNode) { + // set the fake param Value in PagLocalNode + /** + * TODO: !!! + * some API param is in the form of anonymous method: + * component/common.d.ts + * declare function animateTo(value: AnimateParam, event: () => void): void; + * + * this param fake Value will create PagFuncNode rather than PagLocalNode + * when this API is called, the anonymous method pointer will not be able to pass into the fake Value PagNode + */ + dstPagNode.setSdkParam(); + let sdkParamInvokeStmt = new ArkInvokeStmt( + new ArkPtrInvokeExpr((arg.getType() as FunctionType).getMethodSignature(), paramValue as Local, []) + ); + + // create new DynCallSite + let sdkParamCallSite = new DynCallSite(funcID, sdkParamInvokeStmt, undefined, undefined); + dstPagNode.addRelatedDynCallSite(sdkParamCallSite); + } + + this.pag.addPagEdge(srcPagNode, dstPagNode, PagEdgeKind.Copy, cs.callStmt); + srcNodes.push(srcPagNode.getID()); + } + + return srcNodes; + } + + private processContainerPagCallEdge(cs: CallSite, cid: ContextID, baseClassPTNode: NodeID): NodeID[] { + let srcNodes: NodeID[] = []; + let calleeNode = this.cg.getNode(cs.calleeFuncID) as CallGraphNode; + let calleeMethod: ArkMethod | null = this.scene.getMethod(calleeNode.getMethod()); + let ptNode = this.pag.getNode(baseClassPTNode) as PagNode; + + if (!calleeMethod || !(ptNode instanceof PagNewContainerExprNode)) { + return srcNodes; + } + + let containerValue = (cs.callStmt.getInvokeExpr() as ArkInstanceInvokeExpr).getBase(); + + const containerValueProcess = (argIndex: number): void => { + let srcNode = this.pag.getOrNewNode(cid, cs.args![argIndex], cs.callStmt); + let realContainerFieldPagNode = this.pag.getOrClonePagContainerFieldNode(baseClassPTNode, undefined, containerValue); + + if (realContainerFieldPagNode) { + // In some cases, the value of a variable of array type may not be an explicit array object, + // and the value of `realContainerFieldPagNode` will be undefined. + this.pag.addPagEdge(srcNode, realContainerFieldPagNode, PagEdgeKind.Copy, cs.callStmt); + srcNodes.push(srcNode.getID()); + } + }; + + if (IsCollectionSetAdd(calleeMethod.getSignature())) { + containerValueProcess(0); + } else if (IsCollectionMapSet(calleeMethod.getSignature())) { + containerValueProcess(1); + } + + return srcNodes; + } + + public getOrNewPagNode(cid: ContextID, v: PagNodeType, s?: Stmt): PagNode { + if (v instanceof ArkThisRef) { + return this.getOrNewThisRefNode(cid, v as ArkThisRef); + } + + // this local is also not uniq!!! + // remove below block once this issue fixed + + // globalThis process can not be removed while all `globalThis` ref is the same Value + if (v instanceof Local) { + if (v.getName() === "this") { + return this.getOrNewThisLoalNode(cid, v as Local, s); + } else if (v.getName() === GLOBAL_THIS_NAME && v.getDeclaringStmt() == null) { + // globalThis node has no cid + return this.getOrNewGlobalThisNode(-1) + } + } + + if (v instanceof ArkInstanceFieldRef || v instanceof ArkStaticFieldRef) { + v = this.getRealInstanceRef(v); + } + + return this.pag.getOrNewNode(cid, v, s); + } + + /** + * return ThisRef PAG node according to cid, a cid has a unique ThisRef node + * @param cid: current contextID + */ + public getOrNewThisRefNode(cid: ContextID, v: ArkThisRef): PagNode { + let thisRefNodeID = this.cid2ThisRefMap.get(cid) + if (!thisRefNodeID) { + thisRefNodeID = -1; + } + + let thisRefNode = this.pag.getOrNewThisRefNode(thisRefNodeID, v) + this.cid2ThisRefMap.set(cid, thisRefNode.getID()) + return thisRefNode + } + + // TODO: remove it once this local not uniq issue is fixed + public getOrNewThisLoalNode(cid: ContextID, v: Local, s?: Stmt): PagNode { + let thisLocalNodeID = this.cid2ThisLocalMap.get(cid) + if (thisLocalNodeID) { + return this.pag.getNode(thisLocalNodeID) as PagNode; + } + + let thisNode = this.pag.getOrNewNode(cid, v, s); + this.cid2ThisLocalMap.set(cid, thisNode.getID()); + return thisNode; + } + + public getOrNewGlobalThisNode(cid: ContextID): PagNode { + return this.pag.getOrNewNode(cid, this.getGlobalThisValue()); + } + + public getUniqThisLocalNode(cid: ContextID): NodeID | undefined { + return this.cid2ThisLocalMap.get(cid); + } + + /** + * search the storage map to get propertyNode with given storage and propertyFieldName + * @param storage storage type: AppStorage, LocalStorage etc. + * @param propertyName string property key + * @returns propertyNode: PagLocalNode + */ + public getOrNewPropertyNode(storage: StorageType, propertyName: string, stmt: Stmt): PagNode { + let propertyNode = this.getPropertyNode(storage, propertyName, stmt); + + if (propertyNode) { + return propertyNode; + } + + let storageMap = this.storagePropertyMap.get(storage)!; + let propertyLocal = new Local(propertyName); + storageMap.set(propertyName, propertyLocal); + this.storagePropertyMap.set(storage, storageMap); + + return this.getOrNewPagNode(-1, propertyLocal, stmt); + } + + public getPropertyNode(storage: StorageType, propertyName: string, stmt: Stmt): PagNode | undefined { + let storageMap = this.storagePropertyMap.get(storage); + let propertyLocal: Local | undefined; + + if (!storageMap) { + storageMap = new Map(); + this.storagePropertyMap.set(storage, storageMap); + } + + if (storageMap.has(propertyName)) { + propertyLocal = storageMap.get(propertyName)!; + } + + + if (propertyLocal) { + return this.getOrNewPagNode(-1, propertyLocal, stmt); + } + return undefined; + } + + /** + * add PagEdge + * @param edgeKind: edge kind differs from API + * @param propertyNode: PAG node created by protpertyName + * @param obj: heapObj stored with Storage API + */ + public addPropertyLinkEdge(propertyNode: PagNode, storageObj: Value, cid: ContextID, stmt: Stmt, edgeKind: number): boolean { + if (!(storageObj.getType() instanceof ClassType)) { + return false; + } + + if (edgeKind === StorageLinkEdgeType.Property2Local) { + // propertyNode --> objNode + this.pag.addPagEdge(propertyNode, this.pag.getOrNewNode(cid, storageObj), PagEdgeKind.Copy, stmt); + } else if (edgeKind === StorageLinkEdgeType.Local2Property) { + // propertyNode <-- objNode + this.pag.addPagEdge(this.pag.getOrNewNode(cid, storageObj), propertyNode, PagEdgeKind.Copy, stmt); + } else if (edgeKind === StorageLinkEdgeType.TwoWay) { + // propertyNode <-> objNode + this.pag.addPagEdge(propertyNode, this.pag.getOrNewNode(cid, storageObj), PagEdgeKind.Copy, stmt); + this.pag.addPagEdge(this.pag.getOrNewNode(cid, storageObj), propertyNode, PagEdgeKind.Copy, stmt); + } + return true; + } + + /* + * In ArkIR, ArkField has multiple instances for each stmt which use it + * But the unique one is needed for pointer analysis + * This is a temp solution to use a ArkField->(first instance) + * as the unique instance + * + * node merge condition: + * instance field: value and ArkField + * static field: ArkField + */ + public getRealInstanceRef(v: Value): Value { + if (!(v instanceof ArkInstanceFieldRef || v instanceof ArkStaticFieldRef)) { + return v; + } + + let sig = v.getFieldSignature(); + let sigStr = sig.toString() + let base: Local; + let real: Value | undefined; + + if (v instanceof ArkInstanceFieldRef) { + base = (v as ArkInstanceFieldRef).getBase() + if (base instanceof Local && base.getName() === GLOBAL_THIS_NAME && base.getDeclaringStmt() == null) { + // replace the base in fieldRef + base = this.getGlobalThisValue(); + (v as ArkInstanceFieldRef).setBase(base as Local) + } + let key = `${base.getSignature()}-${sigStr}` + + real = this.instanceField2UniqInstanceMap.get(key); + if (!real) { + this.instanceField2UniqInstanceMap.set(key, v); + real = v; + } + } else { + real = this.staticField2UniqInstanceMap.get(sigStr); + if (!real) { + this.staticField2UniqInstanceMap.set(sigStr, v); + real = v; + } + } + return real; + } + + /** + * check if a method is singleton function + * rule: static method, assign heap obj to global var or static field, return the receiver + */ + public isSingletonFunction(funcID: FuncID): boolean { + if (this.singletonFuncMap.has(funcID)) { + return this.singletonFuncMap.get(funcID)!; + } + + let arkMethod = this.cg.getArkMethodByFuncID(funcID); + if (!arkMethod) { + this.singletonFuncMap.set(funcID, false); + return false; + } + + if (!arkMethod.isStatic()) { + this.singletonFuncMap.set(funcID, false); + return false; + } + + let funcPag = this.funcPags.get(funcID)!; + let heapObjects = [...funcPag.getInternalEdges()!] + .filter(edge => edge.kind === PagEdgeKind.Address) + .map(edge => edge.dst); + + let returnValues = arkMethod.getReturnValues(); + + let result = this.isValueConnected([...funcPag.getInternalEdges()!], heapObjects, returnValues); + this.singletonFuncMap.set(funcID, result); + if (result) { + logger.info(`function ${funcID} is marked as singleton function`); + } + return result; + } + + private isValueConnected(edges: IntraProceduralEdge[], leftNodes: Value[], targetNodes: Value[]): boolean { + // build funcPag graph + const graph = new Map(); + let hasStaticFieldOrGlobalVar: boolean = false; + + for (const edge of edges) { + let dst = this.getRealInstanceRef(edge.dst); + let src = this.getRealInstanceRef(edge.src); + if (!graph.has(dst)) { + graph.set(dst, []); + } + if (!graph.has(src)) { + graph.set(src, []); + } + + if (dst instanceof ArkStaticFieldRef || src instanceof ArkStaticFieldRef) { + hasStaticFieldOrGlobalVar = true; + } + + graph.get(src)!.push(dst); + } + + if (!hasStaticFieldOrGlobalVar) { + return false; + } + + for (const targetNode of targetNodes) { + for (const leftNode of leftNodes) { + const visited = new Set(); + let meetStaticField = false; + if (this.funcPagDfs(graph, visited, leftNode, targetNode, meetStaticField)) { + return true; // a value pair that satisfy condition + } + + if (!meetStaticField) { + break; // heap obj will not deal any more + } + } + } + + return false; + } + + private funcPagDfs(graph: Map, visited: Set, currentNode: Value, targetNode: Value, + staticFieldFound: boolean): boolean { + if (currentNode === targetNode) { + return staticFieldFound; + } + + visited.add(currentNode); + + for (const neighbor of graph.get(currentNode) || []) { + // TODO: add global variable + const isSpecialNode = neighbor instanceof ArkStaticFieldRef; + + if (!visited.has(neighbor)) { + if (isSpecialNode) { + staticFieldFound = true; + } + + if (this.funcPagDfs(graph, visited, neighbor, targetNode, staticFieldFound)) { + return true; + } + } + } + + return false; + } + + public getGlobalThisValue(): Local { + return this.globalThisValue; + } + + private getEdgeKindForAssignStmt(stmt: ArkAssignStmt): PagEdgeKind { + if (this.stmtIsCreateAddressObj(stmt)) { + return PagEdgeKind.Address; + } + + if (this.stmtIsCopyKind(stmt)) { + return PagEdgeKind.Copy; + } + + if (this.stmtIsReadKind(stmt)) { + return PagEdgeKind.Load; + } + + if (this.stmtIsWriteKind(stmt)) { + return PagEdgeKind.Write; + } + + return PagEdgeKind.Unknown; + } + + /** + * get storageType enum with method's Declaring ClassName + * + * @param storageName ClassName that method belongs to, currently support AppStorage and SubscribedAbstractProperty + * SubscribedAbstractProperty: in following listing, `link1` is infered as ClassType `SubscribedAbstractProperty`, + * it needs to get PAG node to check the StorageType + * let link1: SubscribedAbstractProperty = AppStorage.link('PropA'); + * link1.set(a); + * @param cs: for search PAG node in SubscribedAbstractProperty + * @param cid: for search PAG node in SubscribedAbstractProperty + * @returns StorageType enum + */ + private getStorageType(storageName: string, cs: CallSite | DynCallSite, cid: ContextID): StorageType { + switch (storageName) { + case 'AppStorage': + return StorageType.APP_STORAGE; + case 'SubscribedAbstractProperty': { + let calleeBaseLocal = (cs.callStmt.getInvokeExpr() as ArkInstanceInvokeExpr).getBase(); + let calleeBaseLocalNode = this.pag.getOrNewNode(cid, calleeBaseLocal) as PagLocalNode; + if (calleeBaseLocalNode.isStorageLinked()) { + let storage = calleeBaseLocalNode.getStorage(); + + return storage.StorageType!; + } + return StorageType.Undefined; + } + default: + return StorageType.Undefined; + } + } + + /**\ + * ArkNewExpr, ArkNewArrayExpr, function ptr, globalThis + */ + private stmtIsCreateAddressObj(stmt: ArkAssignStmt): boolean { + let lhOp = stmt.getLeftOp(); + let rhOp = stmt.getRightOp(); + if ((rhOp instanceof ArkNewExpr || rhOp instanceof ArkNewArrayExpr) || + (lhOp instanceof Local && ( + (rhOp instanceof Local && rhOp.getType() instanceof FunctionType && + rhOp.getDeclaringStmt() === null) || + (rhOp instanceof AbstractFieldRef && rhOp.getType() instanceof FunctionType))) || + (rhOp instanceof Local && rhOp.getName() === GLOBAL_THIS_NAME && rhOp.getDeclaringStmt() == null) + ) { + return true; + } + + // TODO: add other Address Obj creation + // like static object + return false; + } + + private stmtIsCopyKind(stmt: ArkAssignStmt): boolean { + let lhOp = stmt.getLeftOp(); + let rhOp = stmt.getRightOp(); + + let condition: boolean = + (lhOp instanceof Local && ( + rhOp instanceof Local || rhOp instanceof ArkParameterRef || + rhOp instanceof ArkThisRef || rhOp instanceof ArkStaticFieldRef)) || + (lhOp instanceof ArkStaticFieldRef && rhOp instanceof Local) + + if (condition) { + return true; + } + return false; + } + + private stmtIsWriteKind(stmt: ArkAssignStmt): boolean { + let lhOp = stmt.getLeftOp(); + let rhOp = stmt.getRightOp(); + + if (rhOp instanceof Local && + (lhOp instanceof ArkInstanceFieldRef || lhOp instanceof ArkArrayRef)) { + return true; + } + return false; + } + + private stmtIsReadKind(stmt: ArkAssignStmt): boolean { + let lhOp = stmt.getLeftOp(); + let rhOp = stmt.getRightOp(); + + if (lhOp instanceof Local && + (rhOp instanceof ArkInstanceFieldRef || rhOp instanceof ArkArrayRef)) { + return true; + } + return false; + } + + public addToDynamicCallSite(funcPag: FuncPag, cs: DynCallSite): void { + funcPag.addDynamicCallSite(cs); + this.pagStat.numDynamicCall++; + + logger.trace("[add dynamic callsite] " + cs.callStmt.toString() + ": " + cs.callStmt.getCfg()?.getDeclaringMethod().getSignature().toString()); + } + + public setPtForNode(node: NodeID, pts: IPtsCollection | undefined): void { + if (!pts) { + return; + } + + (this.pag.getNode(node) as PagNode).setPointTo(pts); + } + + public getRealThisLocal(input: Local, funcId: FuncID): Local { + if (input.getName() !== 'this') + return input; + let real = input; + + let f = this.cg.getArkMethodByFuncID(funcId); + f?.getCfg()?.getStmts().forEach(s => { + if (s instanceof ArkAssignStmt && s.getLeftOp() instanceof Local) { + if ((s.getLeftOp() as Local).getName() === 'this') { + real = s.getLeftOp() as Local; + return; + } + } + }) + return real; + } + + public doStat(): void { + this.pagStat.numTotalNode = this.pag.getNodeNum(); + } + + public printStat(): void { + this.pagStat.printStat(); + } + + public getStat(): string { + return this.pagStat.getStat(); + } + + public getUnhandledFuncs(): FuncID[] { + let handledFuncs = this.getHandledFuncs(); + let unhandleFuncs = Array.from(this.cg.getNodesIter()) + .filter(f => !handledFuncs.includes(f.getID())) + .map(f => f.getID()); + return unhandleFuncs; + } + + public getHandledFuncs(): FuncID[] { + return Array.from(this.funcPags.keys()); + } + + /** + * build export edge in internal func pag + * @param value: Value that need to check if it is from import/export + * @param originValue: if Value if InstanceFieldRef, the base will be passed to `value` recursively, + * fieldRef will be passed to `originValue` + */ + private handleValueFromExternalScope(value: Value, funcID: FuncID, originValue?: Value): void { + if (value instanceof Local) { + if (value.getDeclaringStmt()) { + // not from external scope + return; + } + + if (!value.getType()) { + return; + } + + let srcLocal = this.getSourceValueFromExternalScope(value, funcID); + + if (srcLocal) { + // if `value` is from field base, use origin value(fieldRef) instead + this.addInterFuncEdge(srcLocal, originValue ?? value, funcID); + } + } else if (value instanceof ArkInstanceFieldRef) { + let base = value.getBase(); + if (base) { + this.handleValueFromExternalScope(base, funcID, value); + } + } + } + + private addInterFuncEdge(src: Local, dst: Value, funcID: FuncID): void { + this.interFuncPags = this.interFuncPags ?? new Map(); + let interFuncPag = this.interFuncPags.get(funcID) ?? new InterFuncPag(); + // Export a local + // Add a InterProcedural edge + if (dst instanceof Local) { + let e: InterProceduralEdge = { src: src, dst: dst, kind: PagEdgeKind.InterProceduralCopy }; + interFuncPag.addToInterProceduralEdgeSet(e); + this.addExportVariableMap(src, dst as Local); + } else if (dst instanceof ArkInstanceFieldRef) { + // record the export base use + this.addExportVariableMap(src, dst.getBase()); + } + this.interFuncPags.set(funcID, interFuncPag); + + // Put the function which the src belongs to to worklist + let srcFunc = src.getDeclaringStmt()?.getCfg().getDeclaringMethod(); + if (srcFunc) { + let srcFuncID = this.cg.getCallGraphNodeByMethod(srcFunc.getSignature()).getID(); + let cid = this.ctx.getNewContextID(srcFuncID); + let csFuncID = new CSFuncID(cid, srcFuncID); + this.buildFuncPagAndAddToWorklist(csFuncID); + } + // Extend other types of src here + } + + private getSourceValueFromExternalScope(value: Local, funcID: FuncID): Local | undefined { + let sourceValue; + // TODO: first from default method + sourceValue = this.getDefaultMethodSourceValue(value, funcID); + if (!sourceValue) { + sourceValue = this.getExportSourceValue(value, funcID); + } + + return sourceValue; + } + + private getDefaultMethodSourceValue(value: Local, funcID: FuncID): Local | undefined { + // namespace check + let arkMethod = this.cg.getArkMethodByFuncID(funcID); + if (!arkMethod) { + return; + } + + let declaringNameSpace = arkMethod.getDeclaringArkClass().getDeclaringArkNamespace(); + while (declaringNameSpace) { + let nameSpaceLocals = declaringNameSpace.getDefaultClass() + .getDefaultArkMethod()?.getBody()?.getLocals() ?? new Map(); + if (nameSpaceLocals.has(value.getName())) { + return nameSpaceLocals.get(value.getName()); + } + + declaringNameSpace = declaringNameSpace.getDeclaringArkNamespace() ?? undefined; + } + + // file check + let declaringFile = arkMethod.getDeclaringArkFile(); + let fileLocals = declaringFile.getDefaultClass() + .getDefaultArkMethod()?.getBody()?.getLocals() ?? new Map(); + if (!fileLocals.has(value.getName())) { + return; + } + + return fileLocals.get(value.getName()); + } + + private getExportSourceValue(value: Local, funcID: FuncID): Local | undefined { + let curMethod = this.cg.getArkMethodByFuncID(funcID); + if (!curMethod) { + return; + } + + let curFile = curMethod.getDeclaringArkFile(); + let impInfo = curFile.getImportInfoBy(value.getName()); + if (!impInfo) { + return; + } + + let exportSource = impInfo.getLazyExportInfo(); + if (!exportSource) { + return; + } + + let exportSouceValue = exportSource.getArkExport(); + if (exportSouceValue instanceof Local) { + return exportSouceValue; + } + } + + private addExportVariableMap(src: Local, dst: Local): void { + let exportMap: Local[] = this.externalScopeVariableMap.get(src) ?? []; + if (!exportMap.includes(dst)) { + exportMap.push(dst); + this.externalScopeVariableMap.set(src, exportMap); + } + } + + public getExportVariableMap(src: Local): Local[] { + return this.externalScopeVariableMap.get(src) ?? []; + } + + /// Add inter-procedural Pag Nodes and Edges + public addEdgesFromInterFuncPag(interFuncPag: InterFuncPag, cid: ContextID): boolean { + let edges = interFuncPag.getInterProceduralEdges(); + if (edges.size === 0) { + return false; + } + + for (let e of edges) { + // Existing local exported nodes -> ExportNode + let exportLocal = e.src; + let dstPagNode = this.getOrNewPagNode(cid, e.dst); + + // get export local node in all cid + let existingNodes = this.pag.getNodesByValue(exportLocal); + existingNodes?.forEach(n => { + this.pag.addPagEdge(this.pag.getNode(n)! as PagNode, dstPagNode, e.kind); + }); + } + + return true; + } +} diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PointerAnalysis.ts b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PointerAnalysis.ts new file mode 100644 index 0000000000..9dca84f638 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PointerAnalysis.ts @@ -0,0 +1,672 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Scene } from '../../Scene'; +import { Value } from '../../core/base/Value'; +import { NodeID } from '../../core/graph/BaseExplicitGraph'; +import path from 'path'; +import * as fs from 'fs'; +import { CallGraph, CallGraphNode, CallSite, DynCallSite, FuncID } from '../model/CallGraph'; +import { AbstractAnalysis } from '../algorithm/AbstractAnalysis'; +import { ClassType, Type, UnknownType } from '../../core/base/Type'; +import { CallGraphBuilder } from '../model/builder/CallGraphBuilder'; +import { Stmt } from '../../core/base/Stmt'; +import Logger, { LOG_MODULE_TYPE } from '../../utils/logger'; +import { DummyMainCreater } from '../../core/common/DummyMainCreater'; +import { PTAStat } from '../common/Statistics'; +import { Pag, PagNode, PagEdgeKind, PagEdge, PagLocalNode, PagGlobalThisNode, PagArrayNode } from './Pag'; +import { PagBuilder } from './PagBuilder'; +import { PointerAnalysisConfig, PtaAnalysisScale } from './PointerAnalysisConfig'; +import { DiffPTData, IPtsCollection } from './PtsDS'; +import { Local } from '../../core/base/Local'; +import { ArkMethod } from '../../core/model/ArkMethod'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'PTA'); + +export class PointerAnalysis extends AbstractAnalysis { + private pag: Pag; + private pagBuilder: PagBuilder; + private ptd: DiffPTData>; + private entries!: FuncID[]; + private worklist!: NodeID[]; + // record all updated nodes + private ptaStat: PTAStat; + private typeDiffMap!: Map>; + private config: PointerAnalysisConfig; + + constructor(p: Pag, cg: CallGraph, s: Scene, config: PointerAnalysisConfig) { + super(s) + this.pag = p; + this.cg = cg; + this.ptd = new DiffPTData>(config.ptsCollectionCtor); + this.pagBuilder = new PagBuilder(this.pag, this.cg, s, config.kLimit, config.analysisScale); + this.cgBuilder = new CallGraphBuilder(this.cg, s); + this.ptaStat = new PTAStat(this); + this.config = config; + } + + static pointerAnalysisForWholeProject(projectScene: Scene, config?: PointerAnalysisConfig): PointerAnalysis { + let cg = new CallGraph(projectScene); + let cgBuilder = new CallGraphBuilder(cg, projectScene); + cgBuilder.buildDirectCallGraphForScene(); + let pag = new Pag(); + if (!config) { + config = PointerAnalysisConfig.create(1, 'out/', false, false); + } + + const dummyMainCreator = new DummyMainCreater(projectScene); + dummyMainCreator.createDummyMain(); + const dummyMainMethod = dummyMainCreator.getDummyMain(); + cgBuilder.buildDirectCallGraph([dummyMainMethod]); + + let dummyMainMethodID = cg.getCallGraphNodeByMethod(dummyMainMethod.getSignature()).getID(); + cg.setDummyMainFuncID(dummyMainMethodID); + + let pta = new PointerAnalysis(pag, cg, projectScene, config); + pta.setEntries([dummyMainMethodID]); + pta.start(); + return pta; + } + + static pointerAnalysisForMethod(s: Scene, method: ArkMethod, config?: PointerAnalysisConfig): PointerAnalysis { + let cg = new CallGraph(s); + let cgBuilder = new CallGraphBuilder(cg, s); + cgBuilder.buildDirectCallGraphForScene(); + let pag = new Pag(); + if (!config) { + config = PointerAnalysisConfig.create(1, 'out/', false, false); + } + + let entryMethodID = cg.getCallGraphNodeByMethod(method.getSignature()).getID(); + let pta = new PointerAnalysis(pag, cg, s, config); + pta.setEntries([entryMethodID]); + pta.start(); + return pta; + } + + protected init() { + logger.warn(`========== Init Pointer Analysis ==========`); + // start statistics + this.ptaStat.startStat(); + // build funcPag with entries + this.pagBuilder.buildForEntries(this.entries); + if (this.config.dotDump) { + this.pag.dump(path.join(this.config.outputDirectory, 'ptaInit_pag.dot')); + this.cg.dump(path.join(this.config.outputDirectory, 'cg_init.dot')); + } + } + + public start() { + this.init(); + this.solveConstraint(); + this.postProcess(); + } + + private postProcess() { + this.ptaStat.endStat(); + this.pagBuilder.doStat(); + this.cg.printStat(); + this.pagBuilder.printStat(); + this.ptaStat.printStat(); + if (this.config.dotDump) { + this.pag.dump(path.join(this.config.outputDirectory, 'ptaEnd_pag.dot')); + this.cg.dump(path.join(this.config.outputDirectory, 'cgEnd.dot')); + } + + if (this.config.unhandledFuncDump) { + this.dumpUnhandledFunctions(); + } + } + + public getPTD(): DiffPTData> { + return this.ptd; + } + + public getStat(): string { + let ret: string = this.cg.getStat(); + ret += '\n' + this.pagBuilder.getStat(); + ret += '\n' + this.ptaStat.getStat(); + + return ret; + } + + protected preProcessMethod(funcID: FuncID): CallSite[] { + // do nothing + return []; + } + + public setEntries(fIds: FuncID[]) { + this.entries = fIds; + } + + private solveConstraint() { + this.worklist = []; + logger.warn(`========== Pointer Analysis Start ==========`); + this.initWorklist(); + let reanalyzer: boolean = true; + + while (reanalyzer) { + this.ptaStat.iterTimes++; + logger.warn(`========== Pointer Analysis Round ${this.ptaStat.iterTimes} ==========`); + + // do pointer transfer + this.solveWorklist(); + // process dynamic call + if (this.config.analysisScale === PtaAnalysisScale.WholeProgram || this.ptaStat.iterTimes === 1 ) { + reanalyzer = this.onTheFlyDynamicCallSolve(); + } else { + reanalyzer = false; + } + if (this.config.dotDump) { + this.pag.dump(path.join(this.config.outputDirectory, `pta_pag_itor#${this.ptaStat.iterTimes}.dot`)); + } + } + } + + /** + * get newly added Address Edge, and add them to initial WorkList + */ + private initWorklist(): boolean { + let changed: boolean = false; + for (let e of this.pag.getAddrEdges()) { + this.ptaStat.numProcessedAddr++; + + let { src, dst } = e.getEndPoints(); + this.ptd.addPts(dst, src); + if (this.pag.getNode(src) instanceof PagGlobalThisNode) { + // readd globalThis heapObj into workList + this.ptd.addPts(src, src); + this.worklist.push(src); + } + + this.worklist.push(dst); + changed = true; + } + this.pag.resetAddrEdges(); + return changed; + } + + private solveWorklist(): boolean { + while (this.worklist.length > 0) { + let node = this.worklist.shift() as NodeID; + this.processNode(node); + } + + return true; + } + + private processNode(nodeId: NodeID): boolean { + this.handleThis(nodeId); + this.handleLoadWrite(nodeId); + this.handleCopy(nodeId); + this.handlePt(nodeId); + + this.detectTypeDiff(nodeId); + return true; + } + + private handleCopy(nodeID: NodeID): boolean { + let node = this.pag.getNode(nodeID) as PagNode; + node.getOutgoingCopyEdges()?.forEach(copyEdge => { + this.propagate(copyEdge); + this.ptaStat.numProcessedCopy++; + }); + + return true; + } + + private handleLoadWrite(nodeID: NodeID): boolean { + let node = this.pag.getNode(nodeID) as PagNode; + let nodeValue = node.getValue(); + let diffPts = this.ptd.getDiffPts(nodeID); + if (!diffPts || diffPts.count() === 0) { + return false; + } + + // get related field node with current node's value + let instanceFieldNodeMap = this.pag.getNodesByBaseValue(nodeValue) ?? new Map(); + // get intra procedural field node by exportMap + let intraProceduralFieldNodeMap = new Map(); + + if (nodeValue instanceof Local) { + this.pagBuilder.getExportVariableMap(nodeValue).forEach((dst) => { + let temp = this.pag.getNodesByBaseValue(dst) ?? new Map(); + intraProceduralFieldNodeMap = this.mergeInstanceFieldMap(instanceFieldNodeMap, temp); + }) + } + + instanceFieldNodeMap!.forEach((nodeIDs, cid) => { + // TODO: check cid + // cid === -1 will escape the check, mainly for globalThis + let baseCid = node.getCid(); + if (baseCid !== -1 && cid !== baseCid) { + return; + } + nodeIDs.forEach((nodeID: number) => { + // get abstract field node + let fieldNode = this.pag.getNode(nodeID) as PagNode; + + this.handleFieldInEdges(fieldNode, diffPts!); + this.handleFieldOutEdges(fieldNode, diffPts!); + }) + }) + + // without cid check, because closure and export is under different cid + intraProceduralFieldNodeMap!.forEach((nodeIDs) => { + nodeIDs.forEach((nodeID: number) => { + // get abstract field node + let fieldNode = this.pag.getNode(nodeID) as PagNode; + + this.handleFieldInEdges(fieldNode, diffPts!); + this.handleFieldOutEdges(fieldNode, diffPts!); + }) + }) + + return true; + } + + private handleFieldInEdges(fieldNode: PagNode, diffPts: IPtsCollection): void { + fieldNode.getIncomingEdge().forEach((edge) => { + if (edge.getKind() !== PagEdgeKind.Write) { + return; + } + let srcNode = edge.getSrcNode() as PagNode; + this.ptaStat.numProcessedWrite++; + for (let pt of diffPts!) { + // filter pt + // clone the real field node with abstract field node + let dstNode; + if (fieldNode instanceof PagArrayNode) { + dstNode = this.pag.getOrClonePagContainerFieldNode(pt, fieldNode); + } else { + dstNode = this.pag.getOrClonePagFieldNode(fieldNode, pt); + } + if (!(dstNode && this.pag.addPagEdge(srcNode, dstNode!, PagEdgeKind.Copy))) { + continue; + } + + this.ptaStat.numRealWrite++; + + if (this.ptd.resetElem(srcNode.getID())) { + this.worklist.push(srcNode.getID()); + } + } + }); + } + + private handleFieldOutEdges(fieldNode: PagNode, diffPts: IPtsCollection): void { + fieldNode.getOutgoingEdges().forEach((edge) => { + if (edge.getKind() !== PagEdgeKind.Load) { + return; + } + let dstNode = edge.getDstNode() as PagNode; + this.ptaStat.numProcessedLoad++; + for (let pt of diffPts!) { + let srcNode; + if (fieldNode instanceof PagArrayNode) { + srcNode = this.pag.getOrClonePagContainerFieldNode(pt, fieldNode); + } else { + srcNode = this.pag.getOrClonePagFieldNode(fieldNode, pt); + } + if (!(srcNode && this.pag.addPagEdge(srcNode!, dstNode, PagEdgeKind.Copy))) { + continue; + } + + this.ptaStat.numRealLoad++; + + // TODO: if field is used before initialzed, newSrc node has no diff pts + if (this.ptd.resetElem(srcNode.getID())) { + this.worklist.push(srcNode.getID()); + } + } + }); + } + + /** + * If current node is a base of a called method, pointer in this node will be transfered into `this` Local in method + */ + private handleThis(nodeID: NodeID): boolean { + let node = this.pag.getNode(nodeID) as PagNode; + node.getOutgoingThisEdges()?.forEach(thisEdge => { + this.propagate(thisEdge); + this.ptaStat.numProcessedThis++; + }); + + return true; + } + + private handlePt(nodeID: NodeID) { + let realDiff = this.ptd.calculateDiff(nodeID, nodeID); + + if (realDiff.count() !== 0) { + // record the updated nodes + this.pagBuilder.addUpdatedNode(nodeID, realDiff); + } + this.ptd.flush(nodeID); + this.pagBuilder.setPtForNode(nodeID, this.ptd.getPropaPts(nodeID)); + } + + private propagate(edge: PagEdge): boolean { + let changed: boolean = false; + let { src, dst } = edge.getEndPoints(); + let diffPts = this.ptd.getDiffPts(src); + if (!diffPts) { + return changed; + } + let realDiffPts = this.ptd.calculateDiff(src, dst); + + for (let pt of realDiffPts) { + changed = this.ptd.addPts(dst, pt) || changed; + } + + if (changed) { + this.worklist.push(dst); + } + + return changed; + } + + /** + * 1. 记录被更新的节点(记录cid, nodeid) + * 2. ( PAGLocalNode记录callsite(cid, value唯一)),通过1种的nodeID查询Node,拿到Callsite + * 3. 在addDynamicCall里对传入指针过滤(已处理指针和未处理指针) + */ + private onTheFlyDynamicCallSolve(): boolean { + let changed: boolean = false; + let processedCallSites: Set = new Set(); + this.pagBuilder.getUpdatedNodes().forEach((pts, nodeID) => { + let node = this.pag.getNode(nodeID) as PagNode; + + if (!(node instanceof PagLocalNode)) { + logger.warn(`node ${nodeID} is not local node, value: ${node.getValue()}`); + return; + } + + changed = this.processDynCallSite(node, pts, processedCallSites) || changed; + changed = this.processUnknownCallSite(node, pts) || changed; + }) + this.pagBuilder.resetUpdatedNodes(); + let srcNodes = this.pagBuilder.handleUnprocessedCallSites(processedCallSites); + changed = this.addToReanalyze(srcNodes) || changed; + + changed = this.pagBuilder.handleReachable() || changed; + changed = this.initWorklist() || changed; + return changed; + } + + private processDynCallSite(node: PagLocalNode, pts: IPtsCollection, processedCallSites: Set): boolean { + let changed: boolean = false; + let dynCallSites = node.getRelatedDynCallSites(); + + if (!dynCallSites && !node.isSdkParam()) { + logger.warn(`node ${node.getID()} has no related dynamic call site`); + return changed; + } + + logger.info(`[process dynamic callsite] node ${node.getID()}`); + dynCallSites.forEach((dynCallsite) => { + for (let pt of pts) { + let srcNodes = this.pagBuilder.addDynamicCallEdge(dynCallsite, pt, node.getCid()); + changed = this.addToReanalyze(srcNodes) || changed; + } + processedCallSites.add(dynCallsite); + }) + + return changed; + } + + private processUnknownCallSite(node: PagLocalNode, pts: IPtsCollection): boolean { + let changed: boolean = false; + let unknownCallSites = node.getRelatedUnknownCallSites(); + + if (!unknownCallSites) { + logger.warn(`node ${node.getID()} has no related unknown call site`); + return changed; + } + + logger.info(`[process unknown callsite] node ${node.getID()}`); + unknownCallSites.forEach((unknownCallSite) => { + for (let pt of pts) { + let srcNodes = this.pagBuilder.addDynamicCallEdge(unknownCallSite, pt, node.getCid()); + changed = this.addToReanalyze(srcNodes) || changed; + } + }) + + return changed; + } + + private addToReanalyze(startNodes: NodeID[]): boolean { + let flag = false; + for (let node of startNodes) { + if (!this.worklist.includes(node) && this.ptd.resetElem(node)) { + this.worklist.push(node); + flag = true; + } + } + return flag; + } + + /** + * compare interface + */ + public noAlias(leftValue: Value, rightValue: Value): boolean { + let leftValueNodes = this.pag.getNodesByValue(leftValue)?.values()!; + let rightValueNodes = this.pag.getNodesByValue(rightValue)?.values()!; + + let leftValuePts: Set = new Set(); + let rightValuePts: Set = new Set(); + + for (let nodeID of leftValueNodes) { + let node = this.pag.getNode(nodeID) as PagNode; + for (let pt of node.getPointTo()) { + leftValuePts.add(pt); + } + } + + for (let nodeID of rightValueNodes) { + let node = this.pag.getNode(nodeID) as PagNode; + for (let pt of node.getPointTo()) { + rightValuePts.add(pt); + } + } + + if (leftValuePts.size > rightValuePts.size) { + [leftValuePts, rightValuePts] = [rightValuePts, leftValuePts]; + } + + for (const elem of leftValuePts) { + if (rightValuePts.has(elem)) { + return false; + } + } + + // no alias + return true; + } + + public mayAlias(leftValue: Value, rightValue: Value): boolean { + return !this.noAlias(leftValue, rightValue); + } + + public getRelatedNodes(value: Value): Set { + let valueNodes = this.pag.getNodesByValue(value); + let relatedAllNodes: Set = new Set(); + let workListNodes: NodeID[] = []; + let processedNodes: Set = new Set(); + + if (valueNodes) { + for (const nodeID of valueNodes.values()) { + workListNodes.push(nodeID); + } + } + + while (workListNodes.length !== 0) { + let valueNodeID: NodeID = workListNodes.shift()!; + if (processedNodes.has(valueNodeID)) { + continue; + } + + this.processRelatedNode(valueNodeID, workListNodes, processedNodes); + } + + processedNodes.forEach(nodeID => { + let valueNode = this.pag.getNode(nodeID) as PagNode; + relatedAllNodes.add(valueNode.getValue()); + }) + + return relatedAllNodes; + } + + private processRelatedNode(valueNodeID: NodeID, workListNodes: NodeID[], processedNodes: Set): void { + let valueNode = this.pag.getNode(valueNodeID) as PagNode; + + this.addIncomingEdgesToWorkList(valueNode, workListNodes, processedNodes); + this.addOutgoingEdgesToWorkList(valueNode, workListNodes, processedNodes); + + processedNodes.add(valueNodeID); + } + + private addIncomingEdgesToWorkList(valueNode: PagNode, workListNodes: NodeID[], processedNodes: Set): void { + let inCopyEdges = valueNode.getIncomingCopyEdges(); + let inThisEdges = valueNode.getIncomingThisEdges(); + let combinedEdges = new Set([...inCopyEdges ?? [], ...inThisEdges ?? []]); + if (combinedEdges) { + combinedEdges.forEach(edge => { + let srcID = edge.getSrcID(); + if (!processedNodes.has(srcID)) { + workListNodes.push(srcID); + } + }); + } + } + + private addOutgoingEdgesToWorkList(valueNode: PagNode, workListNodes: NodeID[], processedNodes: Set): void { + let outCopyEdges = valueNode.getOutgoingCopyEdges(); + let outThisEdges = valueNode.getOutgoingThisEdges(); + let combinedEdges = new Set([...outCopyEdges ?? [], ...outThisEdges ?? []]); + if (combinedEdges) { + combinedEdges.forEach(edge => { + let dstID = edge.getDstID(); + if (!processedNodes.has(dstID)) { + workListNodes.push(dstID); + } + }); + } + } + + private detectTypeDiff(nodeId: NodeID): void { + if (this.config.detectTypeDiff === false) { + return; + } + + this.typeDiffMap = this.typeDiffMap ?? new Map(); + let node = this.pag.getNode(nodeId) as PagNode; + + let value = node.getValue(); + let origType = node.getValue().getType(); + // TODO: union type + if (!(origType instanceof ClassType || origType instanceof UnknownType)) { + return; + } + + let findSameType = false; + let pts = node.getPointTo(); + if (pts.count() === 0) { + return; + } + + for (let pt of pts) { + let ptNode = this.pag.getNode(pt) as PagNode; + let type = ptNode.getValue().getType(); + if (type.toString() !== origType.toString()) { + let diffSet = this.typeDiffMap.get(value) ?? new Set(); + this.typeDiffMap.set(value, diffSet); + if (!diffSet.has(type)) { + diffSet.add(type); + } + } else { + findSameType = true; + } + } + + // If find pts to original type, + // need add original type back since it is a correct type + let diffSet = this.typeDiffMap.get(value); + if (diffSet && findSameType) { + diffSet.add(origType); + } + } + + public getTypeDiffMap(): Map> { + return this.typeDiffMap ?? new Map(); + } + + protected resolveCall(sourceMethod: NodeID, invokeStmt: Stmt): CallSite[] { + return []; + } + + public getUnhandledFuncs(): FuncID[] { + return this.pagBuilder.getUnhandledFuncs(); + } + + public getHandledFuncs(): FuncID[] { + return this.pagBuilder.getHandledFuncs(); + } + + public getPTAConfig(): PointerAnalysisConfig { + return this.config; + } + + private dumpUnhandledFunctions(): void { + const filePath = path.join(this.config.outputDirectory, 'PtaUnhandledFunctionList.txt'); + fs.access(filePath, fs.constants.F_OK, (err) => { + if (!err) { + fs.truncate(filePath, 0, (err) => { + err && logger.error('Error to truncate file ', err); + }); + } + + let updatedContent: string = ''; + this.getUnhandledFuncs().forEach(funcID => { + let cgNode = this.cg.getNode(funcID); + if ((cgNode as CallGraphNode).isSdkMethod()) { + return; + } + + let f = this.cg.getArkMethodByFuncID(funcID); + if (f) { + updatedContent += f.getSignature().toString() + '\n'; + } + }); + + fs.writeFile(filePath, updatedContent, 'utf8', (err) => { + if (err) { + logger.error('Error to write file', err); + } + }); + }); + } + + public mergeInstanceFieldMap(src: Map, dst: Map): Map { + dst.forEach((value, key) => { + if (src.has(key)) { + src.set(key, [...src.get(key)!, ...value]); + } else { + src.set(key, value); + } + }); + return src; + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PointerAnalysisConfig.ts b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PointerAnalysisConfig.ts new file mode 100644 index 0000000000..9dcde376dd --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PointerAnalysisConfig.ts @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as fs from 'fs'; +import { createPtsCollectionCtor, IPtsCollection, PtsCollectionType } from './PtsDS'; +import { NodeID } from '../../core/graph/BaseExplicitGraph'; + +export enum PtaAnalysisScale { + WholeProgram = 0, + MethodLevel = 1 +} + +export class PointerAnalysisConfig { + private static instance: PointerAnalysisConfig; + + public kLimit: number; + public outputDirectory: string; + public detectTypeDiff: boolean; + public dotDump: boolean; + public unhandledFuncDump: boolean; + public analysisScale: PtaAnalysisScale; + public ptsCollectionType: PtsCollectionType; + public ptsCollectionCtor: new () => IPtsCollection; + + /* + * Note: DO NOT use `new PointerAnalysisConfig` to initialize ptaconfig + * Use PointerAnalysisConfig.create() for singleton pattern + */ + constructor(kLimit: number, outputDirectory: string, detectTypeDiff: boolean = false, + dotDump: boolean = false, unhandledFuncDump: boolean = false, + analysisScale: PtaAnalysisScale = PtaAnalysisScale.WholeProgram, ptsCoType = PtsCollectionType.Set) { + if (kLimit > 5) { + throw new Error('K Limit too large'); + } + this.kLimit = kLimit; + this.outputDirectory = outputDirectory; + this.detectTypeDiff = detectTypeDiff; + this.dotDump = dotDump; + this.unhandledFuncDump = unhandledFuncDump; + this.analysisScale = analysisScale; + this.ptsCollectionType = ptsCoType; + this.ptsCollectionCtor = createPtsCollectionCtor(ptsCoType); + + if (!fs.existsSync(outputDirectory)) { + fs.mkdirSync(outputDirectory, { recursive: true }); + } + } + + + /* + * Create Singleton instance + * The instance can be created multi-times and be overwrited + */ + public static create(kLimit: number, outputDirectory: string, detectTypeDiff: boolean = false, + dotDump: boolean = false, unhandledFuncDump: boolean = false, + analysisScale: PtaAnalysisScale = PtaAnalysisScale.WholeProgram, ptsCoType = PtsCollectionType.Set): PointerAnalysisConfig { + PointerAnalysisConfig.instance = new PointerAnalysisConfig( + kLimit, outputDirectory, detectTypeDiff, dotDump, unhandledFuncDump, analysisScale, ptsCoType + ); + return PointerAnalysisConfig.instance; + } + + /* + * Get Singleton instance + */ + public static getInstance(): PointerAnalysisConfig { + if (!PointerAnalysisConfig.instance) { + throw new Error('PTA config: instance is not existing'); + } + return PointerAnalysisConfig.instance; + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PtsDS.ts b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PtsDS.ts new file mode 100644 index 0000000000..3b7c3baf81 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PtsDS.ts @@ -0,0 +1,363 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { SparseBitVector } from '../../utils/SparseBitVector'; + +type Idx = number; +export interface IPtsCollection { + contains(elem: T): boolean; + insert(elem: T): boolean; + remove(elem: T): boolean; + clone(): this; + union(other: this): boolean; + subtract(other: this): boolean; + clear(): void; + count(): number; + isEmpty(): boolean; + superset(other: this): boolean; + intersect(other: this): boolean; + getProtoPtsSet(): any; + [Symbol.iterator](): IterableIterator; +} + +/* + * Return PtsSet or PtsBV 's constructor by input type + */ +export function createPtsCollectionCtor(type: PtsCollectionType): new () => IPtsCollection { + if (type === PtsCollectionType.Set) { + return PtsSet; + } else if (type === PtsCollectionType.BitVector) { + return PtsBV; + } + throw new Error(`Unsupported pts collection type: ${type}`); +} + +/* + * A simple set to store pts data + */ +export class PtsSet implements IPtsCollection { + pts: Set; + + constructor() { + this.pts = new Set(); + } + + contains(elem: T): boolean { + return this.pts.has(elem); + } + + insert(elem: T): boolean { + if (this.pts.has(elem)) { + return false; + } + this.pts.add(elem); + return true; + } + + remove(elem: T): boolean { + if (!this.pts.has(elem)) { + return false; + } + this.pts.delete(elem); + return true; + } + + clone(): this { + let clonedSet = new PtsSet(); + clonedSet.pts = new Set(this.pts); + // TODO: need validate + return clonedSet as this; + } + + union(other: this): boolean { + let changed = false; + for (const elem of other.pts) { + changed = this.insert(elem) || changed; + } + return changed; + } + + subtract(other: this): boolean { + let changed = false; + for (const elem of other.pts) { + changed = this.remove(elem) || changed; + } + + return changed; + } + + clear(): void { + this.pts.clear(); + } + + count(): number { + return this.pts.size; + } + + isEmpty(): boolean { + return this.pts.size === 0; + } + + // If current collection is a super set of other + superset(other: this): boolean { + for (const elem of other.pts) { + if (!this.pts.has(elem)) { + return false; + } + } + return true; + } + + // If current collection is intersect with other + intersect(other: this): boolean { + for (const elem of other.pts) { + if (this.pts.has(elem)) { + return true; + } + } + return false; + } + + getProtoPtsSet(): Set { + return this.pts; + } + + [Symbol.iterator](): IterableIterator { + return this.pts[Symbol.iterator](); + } +} + +export class PtsBV implements IPtsCollection { + pts: SparseBitVector; + + constructor() { + this.pts = new SparseBitVector(); + } + + contains(elem: T): boolean { + return this.pts.test(elem); + } + + insert(elem: T): boolean { + this.pts.set(elem); + return true; + } + + remove(elem: T): boolean { + this.pts.reset(elem); + return true; + } + + clone(): this { + let cloned = new PtsBV(); + cloned.pts = this.pts.clone(); + return cloned as this; + } + + union(other: this): boolean { + return this.pts.unionWith(other.pts); + } + + subtract(other: this): boolean { + return this.pts.subtractWith(other.pts); + } + + clear(): void { + this.pts.clear(); + } + + count(): number { + return this.pts.count(); + } + + isEmpty(): boolean { + return this.pts.isEmpty(); + } + + // If current collection is a super set of other + superset(other: this): boolean { + for (const elem of other.pts) { + if (!this.pts.test(elem)) { + return false; + } + } + return true; + } + + // If current collection is intersect with other + intersect(other: this): boolean { + for (const elem of other.pts) { + if (this.pts.test(elem)) { + return true; + } + } + return false; + } + + getProtoPtsSet(): SparseBitVector { + return this.pts; + } + + [Symbol.iterator](): IterableIterator { + return this.pts[Symbol.iterator]() as IterableIterator; + } +} + +export enum PtsCollectionType { Set, BitVector }; +export class DiffPTData> { + private diffPtsMap: Map; + private propaPtsMap: Map; + + constructor(private DSCreator: (new () => DS)) { + this.diffPtsMap = new Map(); + this.propaPtsMap = new Map(); + } + + clear(): void { + this.diffPtsMap.clear(); + this.propaPtsMap.clear(); + } + + addPts(v: K, elem: D): boolean { + let propa = this.propaPtsMap.get(v); + if (propa && propa.contains(elem)) { + return false; + } + let diff = this.diffPtsMap.get(v) || new this.DSCreator(); + this.diffPtsMap.set(v, diff); + return diff.insert(elem); + } + + resetElem(v: K): boolean { + let propa = this.propaPtsMap.get(v); + if (propa) { + this.diffPtsMap.set(v, propa.clone()); + return true; + } + return false; + } + + unionDiffPts(dstv: K, srcv: K): boolean { + if (dstv === srcv) { + return false; + } + let changed = false; + let diff = this.diffPtsMap.get(srcv); + if (diff) { + let srcDs = diff.clone(); + changed = this.unionPtsTo(dstv, srcDs); + } + return changed; + } + + unionPts(dstv: K, srcv: K): boolean { + if (dstv === srcv) { + return false; + } + let changed = false; + let diff = this.diffPtsMap.get(srcv); + if (diff) { + let srcDs = diff.clone(); + changed = this.unionPtsTo(dstv, srcDs); + } + let propa = this.propaPtsMap.get(srcv); + if (propa) { + let srcDs = propa.clone(); + changed = this.unionPtsTo(dstv, srcDs) || changed; + } + return changed; + } + + unionPtsTo(dstv: K, srcDs: DS): boolean { + let diff = this.diffPtsMap.get(dstv) || new this.DSCreator(); + let propa = this.propaPtsMap.get(dstv) || new this.DSCreator(); + let newSet = srcDs.clone(); + newSet.subtract(propa); + let changed = diff.union(newSet); + this.diffPtsMap.set(dstv, diff); + return changed; + } + + removePtsElem(v: K, elem: D): boolean { + let removedFromDiff = this.diffPtsMap.get(v)?.remove(elem) ?? false; + let removedFromPropa = this.propaPtsMap.get(v)?.remove(elem) ?? false; + return removedFromDiff || removedFromPropa; + } + + getDiffPts(v: K): DS | undefined { + return this.diffPtsMap.get(v); + } + + getMutDiffPts(v: K): DS | undefined { + if (!this.diffPtsMap.has(v)) { + this.diffPtsMap.set(v, new this.DSCreator()); + } + return this.diffPtsMap.get(v); + } + + getPropaPts(v: K): DS | undefined { + return this.propaPtsMap.get(v); + } + + getAllPropaPts(): Map { + return this.propaPtsMap; + } + + getPropaPtsMut(v: K): DS { + if (!this.propaPtsMap.has(v)) { + this.propaPtsMap.set(v, new this.DSCreator()); + } + return this.propaPtsMap.get(v)!; + } + + flush(v: K): void { + if (!this.diffPtsMap.has(v)) return; + let diff = this.diffPtsMap.get(v)!; + let propa = this.getPropaPtsMut(v); + // do not clear origin propa, only copy the pt and add it to diff + propa.union(diff); + diff.clear(); + } + + clearPts(v: K): void { + let diff = this.diffPtsMap.get(v); + if (diff) diff.clear(); + let propa = this.propaPtsMap.get(v); + if (propa) propa.clear(); + } + + clearDiffPts(v: K): void { + let diff = this.diffPtsMap.get(v); + if (diff) diff.clear(); + } + + clearPropaPts(v: K): void { + let propa = this.propaPtsMap.get(v); + if (propa) propa.clear(); + } + + calculateDiff(src: K, dst: K): DS { + let srcDiff = this.diffPtsMap.get(src)!; + let dstPropa = this.propaPtsMap.get(dst); + if (!dstPropa) { + return srcDiff.clone(); + } + + let result = srcDiff.clone(); + + result.subtract(dstPropa); + return result; + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/base/Constant.ts b/ets2panda/linter/arkanalyzer/src/core/base/Constant.ts new file mode 100644 index 0000000000..d6541f1cb1 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/base/Constant.ts @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { BigIntType, BooleanType, NullType, NumberType, StringType, Type, UndefinedType } from './Type'; +import { Value } from './Value'; +import { NULL_KEYWORD, UNDEFINED_KEYWORD } from '../common/TSConst'; + +/** + * @category core/base + */ +export class Constant implements Value { + private readonly value: string; + private readonly type: Type; + + constructor(value: string, type: Type) { + this.value = value; + this.type = type; + } + + /** + * Returns the constant's value as a **string**. + * @returns The constant's value. + */ + public getValue(): string { + return this.value; + } + + public getUses(): Value[] { + return []; + } + + /** + * Returns the type of this constant. + * @returns The type of this constant. + */ + public getType(): Type { + return this.type; + } + + /** + * Get a string of constant value in Constant. + * @returns The string of constant value. + */ + public toString(): string { + let str = ''; + if (this.type instanceof StringType) { + str = '\'' + this.value + '\''; + } else { + str = this.value; + } + return str; + } +} + +export class BooleanConstant extends Constant { + private static readonly FALSE = new BooleanConstant(false); + private static readonly TRUE = new BooleanConstant(true); + + constructor(value: boolean) { + super(value.toString(), BooleanType.getInstance()); + } + + public static getInstance(value: boolean): NullConstant { + return value ? this.TRUE : this.FALSE; + } +} + +export class NumberConstant extends Constant { + constructor(value: number) { + super(value.toString(), NumberType.getInstance()); + } +} + +export class BigIntConstant extends Constant { + constructor(value: bigint) { + super(value.toString(), BigIntType.getInstance()); + } +} + +export class StringConstant extends Constant { + constructor(value: string) { + super(value.toString(), StringType.getInstance()); + } +} + +export class NullConstant extends Constant { + private static readonly INSTANCE = new NullConstant(); + + constructor() { + super(NULL_KEYWORD, NullType.getInstance()); + } + + public static getInstance(): NullConstant { + return this.INSTANCE; + } +} + +export class UndefinedConstant extends Constant { + private static readonly INSTANCE = new UndefinedConstant(); + + constructor() { + super(UNDEFINED_KEYWORD, UndefinedType.getInstance()); + } + + public static getInstance(): UndefinedConstant { + return this.INSTANCE; + } +} diff --git a/ets2panda/linter/arkanalyzer/src/core/base/Decorator.ts b/ets2panda/linter/arkanalyzer/src/core/base/Decorator.ts new file mode 100644 index 0000000000..8c98790ff9 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/base/Decorator.ts @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @category core/base + */ +export class Decorator { + kind: string; + content: string = ''; + param: string = ''; + constructor(name: string) { + this.kind = name; + } + public getKind(): string { + return this.kind; + } + public setContent(content: string): void { + this.content = content; + } + public getContent(): string { + return this.content; + } + public setParam(param: string): void { + this.param = param; + } + public getParam(): string { + return this.param; + } + public toString(): string { + return `@${this.content}`; + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/base/DefUseChain.ts b/ets2panda/linter/arkanalyzer/src/core/base/DefUseChain.ts new file mode 100644 index 0000000000..669bc74f27 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/base/DefUseChain.ts @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Value } from './Value'; +import { Stmt } from './Stmt'; + +export class DefUseChain{ + value:Value; + def:Stmt; + use:Stmt; + constructor(value:Value,def:Stmt,use:Stmt){ + this.value=value; + this.def=def; + this.use=use; + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/base/Expr.ts b/ets2panda/linter/arkanalyzer/src/core/base/Expr.ts new file mode 100644 index 0000000000..96a499d5a5 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/base/Expr.ts @@ -0,0 +1,1140 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { TypeInference } from '../common/TypeInference'; +import { BasicBlock } from '../graph/BasicBlock'; +import { MethodSignature } from '../model/ArkSignature'; +import { Local } from './Local'; +import { + AliasType, + ArrayType, BigIntType, + BooleanType, + ClassType, + FunctionType, + NullType, + NumberType, + StringType, + Type, + UnclearReferenceType, + UndefinedType, + UnionType, + UnknownType, +} from './Type'; +import { Value } from './Value'; +import { AbstractFieldRef, AbstractRef, ArkInstanceFieldRef, ArkStaticFieldRef } from './Ref'; +import { EMPTY_STRING, ValueUtil } from '../common/ValueUtil'; +import { ArkMethod } from '../model/ArkMethod'; +import { UNKNOWN_FILE_NAME } from '../common/Const'; +import { IRInference } from '../common/IRInference'; +import { ImportInfo } from '../model/ArkImport'; +import { ArkClass } from '../model/ArkClass'; +import { ArkField } from '../model/ArkField'; + +/** + * @category core/base/expr + */ +export abstract class AbstractExpr implements Value { + abstract getUses(): Value[]; + + abstract getType(): Type; + + abstract toString(): string; + + public inferType(arkMethod: ArkMethod): AbstractExpr { + return this; + } +} + +export abstract class AbstractInvokeExpr extends AbstractExpr { + private methodSignature: MethodSignature; + private args: Value[]; + private realGenericTypes?: Type[];//新增 + + constructor(methodSignature: MethodSignature, args: Value[], realGenericTypes?: Type[]) { + super(); + this.methodSignature = methodSignature; + this.args = args; + this.realGenericTypes = realGenericTypes; + } + + /** + * Get method Signature. The method signature is consist of ClassSignature and MethodSubSignature. + * It is the unique flag of a method. It is usually used to compose a expression string in ArkIRTransformer. + * @returns The class method signature, such as ArkStaticInvokeExpr. + * @example + * 1. 3AC information composed of getMethodSignature (). + + ```typescript + let strs: string[] = []; + strs.push('staticinvoke <'); + strs.push(this.getMethodSignature().toString()); + strs.push('>('); + ``` + */ + public getMethodSignature(): MethodSignature { + return this.methodSignature; + } + + public setMethodSignature(newMethodSignature: MethodSignature): void { + this.methodSignature = newMethodSignature; + } + + /** + * Returns an argument used in the expression according to its index. + * @param index - the index of the argument. + * @returns An argument used in the expression. + */ + public getArg(index: number): Value { + return this.args[index]; + } + + /** + * Returns an **array** of arguments used in the expression. + * @returns An **array** of arguments used in the expression. + * @example + * 1. get args number. + + ```typescript + const argsNum = expr.getArgs().length; + if (argsNum < 5) { + ... ... + } + ``` + + 2. iterate arg based on expression + + ```typescript + for (const arg of this.getArgs()) { + strs.push(arg.toString()); + strs.push(', '); + } + ``` + */ + public getArgs(): Value[] { + return this.args; + } + + public setArgs(newArgs: Value[]): void { + this.args = newArgs; + } + + public getType(): Type { + const type = this.methodSignature.getType(); + if (this.realGenericTypes) { + return TypeInference.replaceTypeWithReal(type, this.realGenericTypes); + } + return type; + } + + public getRealGenericTypes(): Type[] | undefined { + return this.realGenericTypes; + } + + public setRealGenericTypes(realTypes: Type[] | undefined): void { + if (realTypes) { + this.realGenericTypes = realTypes; + } + } + + public getUses(): Value[] { + let uses: Value[] = []; + uses.push(...this.args); + for (const arg of this.args) { + uses.push(...arg.getUses()); + } + return uses; + } +} + +export class ArkInstanceInvokeExpr extends AbstractInvokeExpr { + private base: Local; + + constructor(base: Local, methodSignature: MethodSignature, args: Value[], realGenericTypes?: Type[]) { + super(methodSignature, args, realGenericTypes); + this.base = base; + } + + /** + * Returns the local of the instance of invoke expression. + * @returns The local of the invoke expression's instance.. + */ + public getBase(): Local { + return this.base; + } + + public setBase(newBase: Local): void { + this.base = newBase; + } + + /** + * Returns an **array** of values used in this invoke expression, + * including all arguments and values each arguments used. + * For {@link ArkInstanceInvokeExpr}, the return also contains the caller base and uses of base. + * @returns An **array** of arguments used in the invoke expression. + */ + public getUses(): Value[] { + let uses: Value[] = []; + uses.push(this.base); + uses.push(...this.base.getUses()); + uses.push(...this.getArgs()); + for (const arg of this.getArgs()) { + uses.push(...arg.getUses()); + } + return uses; + } + + public toString(): string { + let strs: string[] = []; + strs.push('instanceinvoke '); + strs.push(this.base.toString()); + strs.push('.<'); + strs.push(this.getMethodSignature().toString()); + strs.push('>('); + if (this.getArgs().length > 0) { + for (const arg of this.getArgs()) { + strs.push(arg.toString()); + strs.push(', '); + } + strs.pop(); + } + strs.push(')'); + return strs.join(''); + } + + public inferType(arkMethod: ArkMethod): AbstractInvokeExpr { + return IRInference.inferInstanceInvokeExpr(this, arkMethod); + } + +} + +export class ArkStaticInvokeExpr extends AbstractInvokeExpr { + constructor(methodSignature: MethodSignature, args: Value[], realGenericTypes?: Type[]) { + super(methodSignature, args, realGenericTypes); + } + + public toString(): string { + let strs: string[] = []; + strs.push('staticinvoke <'); + strs.push(this.getMethodSignature().toString()); + strs.push('>('); + if (this.getArgs().length > 0) { + for (const arg of this.getArgs()) { + strs.push(arg.toString()); + strs.push(', '); + } + strs.pop(); + } + strs.push(')'); + return strs.join(''); + } + + public inferType(arkMethod: ArkMethod): AbstractInvokeExpr { + return IRInference.inferStaticInvokeExpr(this, arkMethod); + } + +} + +/** + * 1. Local PtrInvokeExpr + * + * ```typescript + * func foo():void { + * } + * let ptr = foo; + * ptr(); + * ``` + * 2. FieldRef PtrInvokeExpr + * + * ```typescript + * class A { + * b:()=> void() + * } + * new A().b() + * ``` + */ +export class ArkPtrInvokeExpr extends AbstractInvokeExpr { + private funPtr: Local | AbstractFieldRef; + + constructor(methodSignature: MethodSignature, ptr: Local | AbstractFieldRef, args: Value[], realGenericTypes?: Type[]) { + super(methodSignature, args, realGenericTypes); + this.funPtr = ptr; + } + + public setFunPtrLocal(ptr: Local | AbstractFieldRef): void { + this.funPtr = ptr; + } + + public getFuncPtrLocal(): Local | AbstractFieldRef { + return this.funPtr; + } + + public toString(): string { + let strs: string[] = []; + strs.push('ptrinvoke <'); + let ptrName: string = ''; + if (this.funPtr instanceof Local) { + ptrName = this.funPtr.getName(); + } else if (this.funPtr instanceof ArkInstanceFieldRef) { + ptrName = this.funPtr.getBase().getName() + '.' + this.funPtr.getFieldName(); + } else if (this.funPtr instanceof ArkStaticFieldRef) { + ptrName = this.funPtr.getFieldName(); + } + strs.push(this.getMethodSignature().toString(ptrName)); + strs.push('>('); + if (this.getArgs().length > 0) { + for (const arg of this.getArgs()) { + strs.push(arg.toString()); + strs.push(', '); + } + strs.pop(); + } + strs.push(')'); + return strs.join(''); + } + + public getUses(): Value[] { + let uses: Value[] = []; + uses.push(this.getFuncPtrLocal()); + uses.push(...this.getArgs()); + for (const arg of this.getArgs()) { + uses.push(...arg.getUses()); + } + return uses; + } +} + +export class ArkNewExpr extends AbstractExpr { + private classType: ClassType; + + constructor(classType: ClassType) { + super(); + this.classType = classType; + } + + public getClassType(): ClassType { + return this.classType; + } + + public getUses(): Value[] { + return []; + } + + public getType(): Type { + return this.classType; + } + + public toString(): string { + return 'new ' + this.classType; + } + + public inferType(arkMethod: ArkMethod): ArkNewExpr { + const classSignature = this.classType.getClassSignature(); + if (classSignature.getDeclaringFileSignature().getFileName() === UNKNOWN_FILE_NAME) { + const className = classSignature.getClassName(); + let type = TypeInference.inferUnclearRefName(className, arkMethod.getDeclaringArkClass()); + if (type && type instanceof ClassType) { + let realGenericTypes = this.classType.getRealGenericTypes(); + this.classType = realGenericTypes ? new ClassType(type.getClassSignature(), realGenericTypes) : type; + } + } + return this; + } +} + +export class ArkNewArrayExpr extends AbstractExpr { + private baseType: Type; + private size: Value; + + private fromLiteral: boolean; + + constructor(baseType: Type, size: Value, fromLiteral: boolean = false) { + super(); + this.baseType = baseType; + this.size = size; + this.fromLiteral = fromLiteral; + } + + public getSize(): Value { + return this.size; + } + + public setSize(newSize: Value): void { + this.size = newSize; + } + + public getType(): ArrayType { + return new ArrayType(this.baseType, 1); + } + + public getBaseType(): Type { + return this.baseType; + } + + public setBaseType(newType: Type): void { + this.baseType = newType; + } + + public isFromLiteral(): boolean { + return this.fromLiteral; + } + + public inferType(arkMethod: ArkMethod): ArkNewArrayExpr { + const type = TypeInference.inferUnclearedType(this.baseType, arkMethod.getDeclaringArkClass()); + if (type) { + this.baseType = type; + } + return this; + } + + public getUses(): Value[] { + let uses: Value[] = [this.size]; + uses.push(...this.size.getUses()); + return uses; + } + + public toString(): string { + return 'newarray (' + this.baseType + ')[' + this.size + ']'; + } +} + +export class ArkDeleteExpr extends AbstractExpr { + private field: AbstractFieldRef; + + constructor(field: AbstractFieldRef) { + super(); + this.field = field; + } + + public getField(): AbstractFieldRef { + return this.field; + } + + public setField(newField: AbstractFieldRef): void { + this.field = newField; + } + + public getType(): Type { + return BooleanType.getInstance(); + } + + public getUses(): Value[] { + const uses: Value[] = []; + uses.push(this.field); + uses.push(...this.field.getUses()); + return uses; + } + + public toString(): string { + return 'delete ' + this.field; + } + +} + +export class ArkAwaitExpr extends AbstractExpr { + private promise: Value; + + constructor(promise: Value) { + super(); + this.promise = promise; + } + + public getPromise(): Value { + return this.promise; + } + + public setPromise(newPromise: Value): void { + this.promise = newPromise; + } + + public getType(): Type { + const type = this.promise.getType(); + if (type instanceof UnclearReferenceType) { + return type.getGenericTypes()[0]; + } else if (type instanceof ClassType) { + return type.getRealGenericTypes()?.[0] ?? type; + } + return type; + } + + public inferType(arkMethod: ArkMethod): ArkAwaitExpr { + TypeInference.inferValueType(this.promise, arkMethod); + return this; + } + + public getUses(): Value[] { + const uses: Value[] = []; + uses.push(this.promise); + uses.push(...this.promise.getUses()); + return uses; + } + + public toString(): string { + const str = 'await ' + this.promise; + return str; + } +} + +export class ArkYieldExpr extends AbstractExpr { + private yieldValue: Value; + + constructor(yieldValue: Value) { + super(); + this.yieldValue = yieldValue; + } + + public getYieldValue(): Value { + return this.yieldValue; + } + + public setYieldValue(newYieldValue: Value): void { + this.yieldValue = newYieldValue; + } + + public getType(): Type { + return this.yieldValue.getType(); + } + + public getUses(): Value[] { + const uses: Value[] = []; + uses.push(this.yieldValue); + uses.push(...this.yieldValue.getUses()); + return uses; + } + + public toString(): string { + const str = 'yield ' + this.yieldValue; + return str; + } +} + +export enum NormalBinaryOperator { + // TODO: unfold it + NullishCoalescing = '??', + + // arithmetic + Exponentiation = '**', + Division = '/', + Addition = '+', + Subtraction = '-', + Multiplication = '*', + Remainder = '%', + + // shift + LeftShift = '<<', + RightShift = '>>', + UnsignedRightShift = '>>>', + + // Bitwise + BitwiseAnd = '&', + BitwiseOr = '|', + BitwiseXor = '^', + + // Logical + LogicalAnd = '&&', + LogicalOr = '||', +} + +export enum RelationalBinaryOperator { + LessThan = '<', + LessThanOrEqual = '<=', + GreaterThan = '>', + GreaterThanOrEqual = '>=', + Equality = '==', + InEquality = '!=', + StrictEquality = '===', + StrictInequality = '!==', + isPropertyOf = 'in', +} + +export type BinaryOperator = NormalBinaryOperator | RelationalBinaryOperator; + +// 二元运算表达式 +export abstract class AbstractBinopExpr extends AbstractExpr { + protected op1: Value; + protected op2: Value; + protected operator: BinaryOperator; + + protected type!: Type; + + constructor(op1: Value, op2: Value, operator: BinaryOperator) { + super(); + this.op1 = op1; + this.op2 = op2; + this.operator = operator; + } + + /** + * Returns the first operand in the binary operation expression. + * For example, the first operand in `a + b;` is `a`. + * @returns The first operand in the binary operation expression. + */ + public getOp1(): Value { + return this.op1; + } + + public setOp1(newOp1: Value): void { + this.op1 = newOp1; + } + + /** + * Returns the second operand in the binary operation expression. + * For example, the second operand in `a + b;` is `b`. + * @returns The second operand in the binary operation expression. + */ + public getOp2(): Value { + return this.op2; + } + + public setOp2(newOp2: Value): void { + this.op2 = newOp2; + } + + /** + * Get the binary operator from the statement. + * The binary operator can be divided into two categories, + * one is the normal binary operator and the other is relational binary operator. + * @returns The binary operator from the statement. + * @example + ```typescript + if (expr instanceof AbstractBinopExpr) { + let op1: Value = expr.getOp1(); + let op2: Value = expr.getOp2(); + let operator: string = expr.getOperator(); + ... ... + } + ``` + */ + public getOperator(): BinaryOperator { + return this.operator; + } + + public getType(): Type { + if (!this.type) { + this.setType(); + } + return this.type; + } + + public getUses(): Value[] { + let uses: Value[] = []; + uses.push(this.op1); + uses.push(...this.op1.getUses()); + uses.push(this.op2); + uses.push(...this.op2.getUses()); + return uses; + } + + public toString(): string { + return this.op1 + ' ' + this.operator + ' ' + this.op2; + } + + protected inferOpType(op: Value, arkMethod: ArkMethod) { + if (op instanceof AbstractExpr || op instanceof AbstractRef) { + TypeInference.inferValueType(op, arkMethod); + } + } + + protected setType() { + let op1Type = this.op1.getType(); + let op2Type = this.op2.getType(); + if (op1Type instanceof UnionType) { + op1Type = op1Type.getCurrType(); + } + if (op2Type instanceof UnionType) { + op2Type = op2Type.getCurrType(); + } + let type = UnknownType.getInstance(); + switch (this.operator) { + case '+': + if (op1Type === StringType.getInstance() || op2Type === StringType.getInstance()) { + type = StringType.getInstance(); + } + if (op1Type === NumberType.getInstance() && op2Type === NumberType.getInstance()) { + type = NumberType.getInstance(); + } + if (op1Type === BigIntType.getInstance() && op2Type === BigIntType.getInstance()) { + type = BigIntType.getInstance(); + } + break; + case '-': + case '*': + case '/': + case '%': + if (op1Type === NumberType.getInstance() && op2Type === NumberType.getInstance()) { + type = NumberType.getInstance(); + } + if (op1Type === BigIntType.getInstance() && op2Type === BigIntType.getInstance()) { + type = BigIntType.getInstance(); + } + break; + case '!=': + case '!==': + case '<': + case '>': + case '<=': + case '>=': + case '&&': + case '||': + case '==': + case '===': + case 'in': + type = BooleanType.getInstance(); + break; + case '&': + case '|': + case '^': + case '<<': + case '>>': + if (op1Type === BigIntType.getInstance() && op2Type === BigIntType.getInstance()) { + type = BigIntType.getInstance(); + } + case '>>>': + if (op1Type === NumberType.getInstance() && op2Type === NumberType.getInstance()) { + type = NumberType.getInstance(); + } + break; + case '??': + if (op1Type === UnknownType.getInstance() || op1Type === UndefinedType.getInstance() + || op1Type === NullType.getInstance()) { + type = op2Type; + } else { + type = op1Type; + } + break; + default: + ; + } + this.type = type; + } + + public inferType(arkMethod: ArkMethod): AbstractBinopExpr { + this.inferOpType(this.op1, arkMethod); + this.inferOpType(this.op2, arkMethod); + this.setType(); + return this; + } +} + +export class ArkConditionExpr extends AbstractBinopExpr { + constructor(op1: Value, op2: Value, operator: RelationalBinaryOperator) { + super(op1, op2, operator); + } + + public inferType(arkMethod: ArkMethod): ArkConditionExpr { + this.inferOpType(this.op1, arkMethod); + const op1Type = this.op1.getType(); + if (this.operator === RelationalBinaryOperator.InEquality && this.op2 === ValueUtil.getOrCreateNumberConst(0)) { + if (op1Type instanceof StringType) { + this.op2 = ValueUtil.createStringConst(EMPTY_STRING); + } else if (op1Type instanceof BooleanType) { + this.op2 = ValueUtil.getBooleanConstant(false); + } else if (op1Type instanceof ClassType) { + this.op2 = ValueUtil.getUndefinedConst(); + } + } else { + this.inferOpType(this.getOp2(), arkMethod); + } + this.type = BooleanType.getInstance(); + return this; + } +} + +export class ArkNormalBinopExpr extends AbstractBinopExpr { + constructor(op1: Value, op2: Value, operator: NormalBinaryOperator) { + super(op1, op2, operator); + } +} + +export class ArkTypeOfExpr extends AbstractExpr { + private op: Value; + + constructor(op: Value) { + super(); + this.op = op; + } + + public getOp(): Value { + return this.op; + } + + public setOp(newOp: Value): void { + this.op = newOp; + } + + public getUses(): Value[] { + let uses: Value[] = []; + uses.push(this.op); + uses.push(...this.op.getUses()); + return uses; + } + + public getType(): Type { + return this.op.getType(); + } + + public toString(): string { + return 'typeof ' + this.op; + } + + public inferType(arkMethod: ArkMethod): AbstractExpr { + if (this.op instanceof AbstractRef || this.op instanceof AbstractExpr) { + this.op.inferType(arkMethod); + } + return this; + } +} + +export class ArkInstanceOfExpr extends AbstractExpr { + private op: Value; + private checkType: Type; + + constructor(op: Value, checkType: Type) { + super(); + this.op = op; + this.checkType = checkType; + } + + public getOp(): Value { + return this.op; + } + + public setOp(newOp: Value): void { + this.op = newOp; + } + + public getCheckType(): Type { + return this.checkType; + } + + public getType(): Type { + return BooleanType.getInstance(); + } + + public getUses(): Value[] { + let uses: Value[] = []; + uses.push(this.op); + uses.push(...this.op.getUses()); + return uses; + } + + public toString(): string { + return this.op + ' instanceof ' + this.checkType; + } + + public inferType(arkMethod: ArkMethod): AbstractExpr { + TypeInference.inferValueType(this.op, arkMethod); + if (TypeInference.isUnclearType(this.checkType)) { + const newType = TypeInference.inferUnclearedType(this.checkType, arkMethod.getDeclaringArkClass()); + if (newType) { + this.checkType = newType; + } + } + return this; + } +} + +// 类型转换 +export class ArkCastExpr extends AbstractExpr { + private op: Value; + private type: Type; + + constructor(op: Value, type: Type) { + super(); + this.op = op; + this.type = type; + } + + public getOp(): Value { + return this.op; + } + + public setOp(newOp: Value): void { + this.op = newOp; + } + + public getUses(): Value[] { + let uses: Value[] = []; + uses.push(this.op); + uses.push(...this.op.getUses()); + return uses; + } + + public getType(): Type { + return this.type; + } + + public inferType(arkMethod: ArkMethod): AbstractExpr { + if (TypeInference.isUnclearType(this.getType())) { + const type = TypeInference.inferUnclearedType(this.type, arkMethod.getDeclaringArkClass()) ?? this.op.getType(); + if (type !== undefined && !TypeInference.isUnclearType(type)) { + this.type = type; + IRInference.inferRightWithSdkType(type, this.op.getType(), arkMethod.getDeclaringArkClass()); + } + } + return this; + } + + public toString(): string { + return '<' + this.type + '>' + this.op; + } +} + +export class ArkPhiExpr extends AbstractExpr { + private args: Local[]; + private argToBlock: Map; + + constructor() { + super(); + this.args = []; + this.argToBlock = new Map(); + } + + public getUses(): Value[] { + let uses: Value[] = []; + uses.push(...this.args); + return uses; + } + + public getArgs(): Local[] { + return this.args; + } + + public setArgs(args: Local[]): void { + this.args = args; + } + + public getArgToBlock(): Map { + return this.argToBlock; + } + + public setArgToBlock(argToBlock: Map): void { + this.argToBlock = argToBlock; + } + + public getType(): Type { + return this.args[0].getType(); + } + + public toString(): string { + let strs: string[] = []; + strs.push('phi('); + if (this.args.length > 0) { + for (const arg of this.args) { + strs.push(arg.toString()); + strs.push(', '); + } + strs.pop(); + } + strs.push(')'); + return strs.join(''); + } +} + +export enum UnaryOperator { + Neg = '-', + BitwiseNot = '~', + LogicalNot = '!' +} + +// unary operation expression +export class ArkUnopExpr extends AbstractExpr { + private op: Value; + private operator: UnaryOperator; + + constructor(op: Value, operator: UnaryOperator) { + super(); + this.op = op; + this.operator = operator; + } + + public getUses(): Value[] { + let uses: Value[] = []; + uses.push(this.op); + uses.push(...this.op.getUses()); + return uses; + } + + public getOp(): Value { + return this.op; + } + + public setOp(newOp: Value): void { + this.op = newOp; + } + + public getType(): Type { + return this.op.getType(); + } + + /** + * Get the unary operator from the statement, such as `-`,`~`,`!`. + * @returns the unary operator of a statement. + */ + public getOperator(): UnaryOperator { + return this.operator; + } + + public toString(): string { + return this.operator + this.op; + } +} + +export type AliasTypeOriginalModel = Type | ImportInfo | Local | ArkClass | ArkMethod | ArkField; + +/** + * Expression of the right hand of the type alias definition statement. + * @category core/base/expr + * @extends AbstractExpr + * @example + ```typescript + let a: number = 123; + type ABC = typeof a; + ``` + * The AliasTypeExpr of the previous statement is with local 'a' as the 'originalObject' and 'transferWithTypeOf' is true. + * + * The Following case: import type with no clause name is not supported now, + * whose 'originalObject' is {@link ImportInfo} with 'null' 'lazyExportInfo'. + ```typescript + let a = typeof import('./abc'); + ``` + */ +export class AliasTypeExpr extends AbstractExpr { + private originalObject: AliasTypeOriginalModel; + private readonly transferWithTypeOf: boolean = false; + private realGenericTypes?: Type[]; + + constructor(originalObject: AliasTypeOriginalModel, transferWithTypeOf?: boolean) { + super(); + this.originalObject = originalObject; + if (transferWithTypeOf !== undefined) { + this.transferWithTypeOf = transferWithTypeOf; + } + } + + public getOriginalObject(): AliasTypeOriginalModel { + return this.originalObject; + } + + public setOriginalObject(object: AliasTypeOriginalModel): void { + this.originalObject = object; + } + + public getTransferWithTypeOf(): boolean { + return this.transferWithTypeOf; + } + + public setRealGenericTypes(realGenericTypes: Type[]): void { + this.realGenericTypes = realGenericTypes; + } + + public getRealGenericTypes(): Type[] | undefined { + return this.realGenericTypes; + } + + public getType(): Type { + function getTypeOfImportInfo(importInfo: ImportInfo): Type { + const arkExport = importInfo.getLazyExportInfo()?.getArkExport(); + if (arkExport) { + return TypeInference.parseArkExport2Type(arkExport) ?? UnknownType.getInstance(); + } + return UnknownType.getInstance(); + } + + const operator = this.getOriginalObject(); + if (!this.getTransferWithTypeOf()) { + if (operator instanceof Type) { + return TypeInference.replaceTypeWithReal(operator, this.getRealGenericTypes()); + } + if (operator instanceof ImportInfo) { + return getTypeOfImportInfo(operator); + } + if (operator instanceof ArkClass) { + return TypeInference.replaceTypeWithReal(new ClassType(operator.getSignature(), operator.getGenericsTypes()), this.getRealGenericTypes()); + } + return UnknownType.getInstance(); + } + + if (operator instanceof ImportInfo) { + return getTypeOfImportInfo(operator); + } + if (operator instanceof Local || operator instanceof ArkField) { + return operator.getType(); + } + if (operator instanceof ArkClass) { + return TypeInference.replaceTypeWithReal(new ClassType(operator.getSignature(), operator.getGenericsTypes()), this.getRealGenericTypes()); + } + if (operator instanceof ArkMethod) { + return TypeInference.replaceTypeWithReal(new FunctionType(operator.getSignature(), operator.getGenericTypes()), this.getRealGenericTypes()); + } + return UnknownType.getInstance(); + } + + public inferType(arkMethod: ArkMethod): AbstractExpr { + return IRInference.inferAliasTypeExpr(this, arkMethod); + } + + /** + * Returns all used values which mainly used for def-use chain analysis. + * @returns Always returns empty array because her is the alias type definition which has no relationship with value flow. + */ + public getUses(): Value[] { + return []; + } + + public toString(): string { + let typeOf = ''; + if (this.getTransferWithTypeOf()) { + typeOf = 'typeof '; + } + + const typeObject = this.getOriginalObject(); + if (typeObject instanceof AliasType && this.getRealGenericTypes()) { + return `${typeOf}${typeObject.getSignature().toString()}<${this.getRealGenericTypes()!.join(',')}>`; + } + if (typeObject instanceof Type) { + return `${typeOf}${typeObject.getTypeString()}`; + } + if (typeObject instanceof ImportInfo) { + let res = `${typeOf}import('${typeObject.getFrom()}')`; + if (typeObject.getImportClauseName() !== '') { + res = `${res}.${typeObject.getImportClauseName()}`; + } + return res; + } + if (typeObject instanceof Local) { + return `${typeOf}${typeObject.toString()}`; + } + if (typeObject instanceof ArkClass || typeObject instanceof ArkMethod) { + let res = `${typeOf}${typeObject.getSignature().toString()}`; + if (this.getRealGenericTypes() && typeObject instanceof ArkClass) { + res += `<${this.getRealGenericTypes()!.join(',')}>`; + } else if (this.getRealGenericTypes() && typeObject instanceof ArkMethod) { + const genericTypes = this.getRealGenericTypes()!.join(','); + res = res.replace('(', `<${genericTypes}>(`).replace(/\([^)]*\)/g, `(${genericTypes})`); + } + return res + } + return `${typeOf}${typeObject.getName()}`; + } + + public static isAliasTypeOriginalModel(object: any): object is AliasTypeOriginalModel { + return object instanceof Type || + object instanceof ImportInfo || + object instanceof Local || + object instanceof ArkClass || + object instanceof ArkMethod || + object instanceof ArkField; + } +} diff --git a/ets2panda/linter/arkanalyzer/src/core/base/Local.ts b/ets2panda/linter/arkanalyzer/src/core/base/Local.ts new file mode 100644 index 0000000000..b018725ccb --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/base/Local.ts @@ -0,0 +1,208 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Stmt } from './Stmt'; +import { Type, UnknownType } from './Type'; +import { Value } from './Value'; +import { TypeInference } from '../common/TypeInference'; +import { ArkExport, ExportType } from '../model/ArkExport'; +import { ClassSignature, LocalSignature, MethodSignature } from '../model/ArkSignature'; +import { ArkSignatureBuilder } from '../model/builder/ArkSignatureBuilder'; +import { UNKNOWN_METHOD_NAME } from '../common/Const'; +import { ModifierType } from '../model/ArkBaseModel'; +import { ArkMethod } from '../model/ArkMethod'; +import { ModelUtils } from '../common/ModelUtils'; + +/** + * @category core/base + */ +export class Local implements Value, ArkExport { + private name: string; + private type: Type; + + private originalValue: Value | null; + + private declaringStmt: Stmt | null; + private usedStmts: Stmt[]; + private signature?: LocalSignature; + private constFlag?: boolean; + + constructor(name: string, type: Type = UnknownType.getInstance()) { + this.name = name; + this.type = type; + + this.originalValue = null; + this.declaringStmt = null; + this.usedStmts = []; + } + + public inferType(arkMethod: ArkMethod): Local { + if (TypeInference.isUnclearType(this.type)) { + const type = TypeInference.inferUnclearRefName(this.name, arkMethod.getDeclaringArkClass()) ?? + ModelUtils.findDeclaredLocal(this, arkMethod)?.getType(); + if (type) { + this.type = type; + } + } + return this; + } + + /** + * Returns the name of local value. + * @returns The name of local value. + * @example + * 1. get the name of local value. + + ```typescript + arkClass.getDefaultArkMethod()?.getBody().getLocals().forEach(local => { + const arkField = new ArkField(); + arkField.setFieldType(ArkField.DEFAULT_ARK_Field); + arkField.setDeclaringClass(defaultClass); + arkField.setType(local.getType()); + arkField.setName(local.getName()); + arkField.genSignature(); + defaultClass.addField(arkField); + }); + ``` + */ + public getName(): string { + return this.name; + } + + public setName(name: string): void { + this.name = name; + } + + /** + * Returns the type of this local. + * @returns The type of this local. + */ + public getType(): Type { + return this.type; + } + + public setType(newType: Type): void { + this.type = newType; + } + + public getOriginalValue(): Value | null { + return this.originalValue; + } + + public setOriginalValue(originalValue: Value): void { + this.originalValue = originalValue; + } + + /** + * Returns the declaring statement, which may also be a **null**. + * For example, if the code snippet in a function is `let dd = cc + 5;` where `cc` is a **number** + * and `dd` is not defined before, then the declaring statemet of local `dd`: + * - its **string** text is "dd = cc + 5". + * - the **strings** of right operand and left operand are "cc + 5" and "dd", respectively. + * - three values are used in this statement: `cc + 5` (i.e., a normal binary operation expression), `cc` (a local), and `5` (a constant), respectively. + * @returns The declaring statement (maybe a **null**) of the local. + * @example + * 1. get the statement that defines the local for the first time. + + ```typescript + let stmt = local.getDeclaringStmt(); + if (stmt !== null) { + ... + } + ``` + */ + public getDeclaringStmt(): Stmt | null { + return this.declaringStmt; + } + + public setDeclaringStmt(declaringStmt: Stmt) { + this.declaringStmt = declaringStmt; + } + + /** + * Returns an **array** of values which are contained in this local. + * @returns An **array** of values used by this local. + */ + public getUses(): Value[] { + return []; + } + + public addUsedStmt(usedStmt: Stmt) { + this.usedStmts.push(usedStmt); + } + + /** + * Returns an array of statements used by the local, i.e., the statements in which the local participate. + * For example, if the code snippet is `let dd = cc + 5;` where `cc` is a local and `cc` only appears once, + * then the length of **array** returned is 1 and `Stmts[0]` will be same as the example described + * in the `Local.getDeclaringStmt()`. + * @returns An array of statements used by the local. + */ + public getUsedStmts(): Stmt[] { + return this.usedStmts; + } + + /** + * Get a string of local name in Local + * @returns The string of local name. + * @example + * 1. get a name string. + + ```typescript + for (const value of stmt.getUses()) { + const name = value.toString(); + ... + } + ``` + */ + public toString(): string { + return this.getName(); + } + + public getExportType(): ExportType { + return ExportType.LOCAL; + } + + public getModifiers(): number { + return 0; + } + + public containsModifier(modifierType: ModifierType): boolean { + if (modifierType === ModifierType.CONST) { + return this.getConstFlag(); + } + return false; + } + + public getSignature(): LocalSignature { + return this.signature ?? new LocalSignature(this.name, new MethodSignature(ClassSignature.DEFAULT, + ArkSignatureBuilder.buildMethodSubSignatureFromMethodName(UNKNOWN_METHOD_NAME))); + } + + public setSignature(signature: LocalSignature): void { + this.signature = signature; + } + + public getConstFlag(): boolean { + if (!this.constFlag) { + return false; + } + return this.constFlag; + } + + public setConstFlag(newConstFlag: boolean): void { + this.constFlag = newConstFlag; + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/base/Position.ts b/ets2panda/linter/arkanalyzer/src/core/base/Position.ts new file mode 100644 index 0000000000..9ae747dac9 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/base/Position.ts @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import ts from 'ohos-typescript'; + +import Logger, { LOG_MODULE_TYPE } from '../../utils/logger'; +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'Position'); + +const LOW_BITS_SIZE = 16; +const LOW_BITS_MASK = 0xffff; +const HIGH_BITS_MASK = 0xffff0000; +const MIN_NUMBER = 0; +const MAX_NUMBER = 0xffff; +const INVALID_LINE = -1; + +export type LineCol = number; + +export function setLine(lineCol: LineCol, lineNo: number): LineCol { + if (lineNo < MIN_NUMBER) { + lineNo = MIN_NUMBER; + } + if (lineNo > MAX_NUMBER) { + logger.warn(`setLine overflow ${lineNo}`); + lineNo = MAX_NUMBER; + } + + return (lineNo << LOW_BITS_SIZE) | (lineCol & LOW_BITS_MASK); +} + +export function setCol(lineCol: LineCol, colNo: number): LineCol { + if (colNo < MIN_NUMBER) { + colNo = MIN_NUMBER; + } + if (colNo > MAX_NUMBER) { + logger.warn(`setCol overflow ${colNo}`); + colNo = MAX_NUMBER; + } + + return (lineCol & HIGH_BITS_MASK) | colNo; +} + +export function setLineCol(lineNo: number, colNo: number): LineCol { + let lineCol: LineCol = 0; + lineCol = setLine(lineCol, lineNo); + lineCol = setCol(lineCol, colNo); + return lineCol; +} + +export function getLineNo(lineCol: LineCol): number { + let line = lineCol >>> LOW_BITS_SIZE; + if (line === MIN_NUMBER) { + return INVALID_LINE; + } + return line; +} + +export function getColNo(lineCol: LineCol): number { + let col = lineCol & LOW_BITS_MASK; + if (col === MIN_NUMBER) { + return INVALID_LINE; + } + return col; +} + +/** + * @category core/base + */ +export class LineColPosition { + private readonly lineCol: LineCol; + + public static readonly DEFAULT: LineColPosition = new LineColPosition(INVALID_LINE, INVALID_LINE); + + constructor(lineNo: number, colNo: number) { + this.lineCol = setLineCol(lineNo, colNo); + } + + public getLineNo(): number { + return getLineNo(this.lineCol); + } + + public getColNo(): number { + return getColNo(this.lineCol); + } + + public static buildFromNode(node: ts.Node, sourceFile: ts.SourceFile) { + let { line, character } = ts.getLineAndCharacterOfPosition(sourceFile, node.getStart(sourceFile)); + // line start from 1. + return new LineColPosition(line + 1, character + 1); + } +} + +export class FullPosition { + private readonly first: LineCol; + private readonly last: LineCol; + + public static readonly DEFAULT: FullPosition = new FullPosition(INVALID_LINE, INVALID_LINE, INVALID_LINE, INVALID_LINE); + + constructor(firstLine: number, firstCol: number, lastLine: number, lastCol: number) { + this.first = setLineCol(firstLine, firstCol); + this.last = setLineCol(lastLine, lastCol); + } + + public getFirstLine(): number { + return getLineNo(this.first); + } + + public getLastLine(): number { + return getLineNo(this.last); + } + + public getFirstCol(): number { + return getColNo(this.first); + } + + public getLastCol(): number { + return getColNo(this.last); + } + + public static buildFromNode(node: ts.Node, sourceFile: ts.SourceFile): FullPosition { + const { line: startLine, character: startCharacter } = ts.getLineAndCharacterOfPosition( + sourceFile, + node.getStart(sourceFile) + ); + const { line: endLine, character: endCharacter } = ts.getLineAndCharacterOfPosition(sourceFile, node.getEnd()); + + // line start from 1 + return new FullPosition(startLine + 1, startCharacter + 1, endLine + 1, endCharacter + 1); + } + + public static merge(leftMostPosition: FullPosition, rightMostPosition: FullPosition): FullPosition { + return new FullPosition( + leftMostPosition.getFirstLine(), + leftMostPosition.getFirstCol(), + rightMostPosition.getLastLine(), + rightMostPosition.getLastCol() + ); + } +} diff --git a/ets2panda/linter/arkanalyzer/src/core/base/Ref.ts b/ets2panda/linter/arkanalyzer/src/core/base/Ref.ts new file mode 100644 index 0000000000..612b0e3371 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/base/Ref.ts @@ -0,0 +1,411 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Logger, { LOG_MODULE_TYPE } from '../../utils/logger'; +import { FieldSignature } from '../model/ArkSignature'; +import { Local } from './Local'; +import { ArrayType, ClassType, LexicalEnvType, Type, UnknownType } from './Type'; +import { Value } from './Value'; +import { TypeInference } from '../common/TypeInference'; +import { ArkMethod } from '../model/ArkMethod'; +import { Stmt } from './Stmt'; +import { IRInference } from '../common/IRInference'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'Ref'); + +/** + * @category core/base/ref + */ +export abstract class AbstractRef implements Value { + abstract getUses(): Value[]; + + abstract getType(): Type; + + public inferType(arkMethod: ArkMethod): AbstractRef { + return this; + } +} + +export class ArkArrayRef extends AbstractRef { + private base: Local; // 数组变量 + private index: Value; // 索引 + + constructor(base: Local, index: Value) { + super(); + this.base = base; + this.index = index; + } + + /** + * Returns the base of this array reference. Array reference refers to access to array elements. + * Array references usually consist of an local variable and an index. + * For example, `a[i]` is a typical array reference, where `a` is the base (i.e., local variable) + * pointing to the actual memory location where the array is stored + * and `i` is the index indicating access to the `i-th` element from array `a`. + * @returns the base of this array reference. + * @example + * 1. Get the base and the specific elements. + + ```typescript + // Create an array + let myArray: number[] = [10, 20, 30, 40]; + // Create an ArrayRef object representing a reference to myArray[2] + let arrayRef = new ArkArrayRef(myArray, 2); + // Use the getBase() method to get the base of the array + let baseArray = arrayRef.getBase(); + + console.log("Base array:", baseArray); // Output: Base array: [10, 20, 30, 40] + + // Use baseArray and obeject index of ArrayRef to access to specific array elements + let element = baseArray[arrayRef.index]; + console.log("Element at index", arrayRef.index, ":", element); // Output: Element at index 2 : 30 + ``` + */ + public getBase(): Local { + return this.base; + } + + public setBase(newBase: Local): void { + this.base = newBase; + } + + /** + * Returns the index of this array reference. + * In TypeScript, an array reference means that the variable stores + * the memory address of the array rather than the actual data of the array. + * @returns The index of this array reference. + */ + public getIndex(): Value { + return this.index; + } + + public setIndex(newIndex: Value): void { + this.index = newIndex; + } + + public getType(): Type { + let baseType = TypeInference.replaceTypeWithReal(this.base.getType()); + if (baseType instanceof ArrayType) { + return baseType.getBaseType(); + } else { + logger.warn(`the type of base in ArrayRef is not ArrayType`); + return UnknownType.getInstance(); + } + } + + public getUses(): Value[] { + let uses: Value[] = []; + uses.push(this.base); + uses.push(...this.base.getUses()); + uses.push(this.index); + uses.push(...this.index.getUses()); + return uses; + } + + public toString(): string { + return this.base + '[' + this.index + ']'; + } +} + +export abstract class AbstractFieldRef extends AbstractRef { + private fieldSignature: FieldSignature; + + constructor(fieldSignature: FieldSignature) { + super(); + this.fieldSignature = fieldSignature; + } + + /** + * Returns the the field name as a **string**. + * @returns The the field name. + */ + public getFieldName(): string { + return this.fieldSignature.getFieldName(); + } + + /** + * Returns a field signature, which consists of a class signature, + * a **string** field name, and a **boolean** label indicating whether it is static or not. + * @returns The field signature. + * @example + * 1. Compare two Fields + + ```typescript + const fieldSignature = new FieldSignature(); + fieldSignature.setFieldName(...); + const fieldRef = new ArkInstanceFieldRef(baseValue as Local, fieldSignature); + ... + if (fieldRef.getFieldSignature().getFieldName() === + targetField.getFieldSignature().getFieldName()) { + ... + } + ``` + */ + public getFieldSignature(): FieldSignature { + return this.fieldSignature; + } + + public setFieldSignature(newFieldSignature: FieldSignature): void { + this.fieldSignature = newFieldSignature; + } + + public getType(): Type { + return this.fieldSignature.getType(); + } +} + +export class ArkInstanceFieldRef extends AbstractFieldRef { + private base: Local; // which obj this field belong to + + constructor(base: Local, fieldSignature: FieldSignature) { + super(fieldSignature); + this.base = base; + } + + /** + * Returns the local of field, showing which object this field belongs to. + * A {@link Local} consists of : + * - Name: the **string** name of local value, e.g., "$temp0". + * - Type: the type of value. + * @returns The object that the field belongs to. + * @example + * 1. Get a base. + + ```typescript + if (expr instanceof ArkInstanceFieldRef) { + ... + let base = expr.getBase(); + if (base.getName() == 'this') { + ... + } + ... + } + ``` + */ + public getBase(): Local { + return this.base; + } + + public setBase(newBase: Local): void { + this.base = newBase; + } + + public getUses(): Value[] { + let uses: Value[] = []; + uses.push(this.base); + uses.push(...this.base.getUses()); + return uses; + } + + public toString(): string { + return this.base.toString() + '.<' + this.getFieldSignature() + '>'; + } + + public inferType(arkMethod: ArkMethod): AbstractRef { + return IRInference.inferFieldRef(this, arkMethod); + } + +} + +export class ArkStaticFieldRef extends AbstractFieldRef { + constructor(fieldSignature: FieldSignature) { + super(fieldSignature); + } + + public getUses(): Value[] { + return []; + } + + public toString(): string { + return this.getFieldSignature().toString(); + } +} + +export class ArkParameterRef extends AbstractRef { + private index: number; + private paramType: Type; + + constructor(index: number, paramType: Type) { + super(); + this.index = index; + this.paramType = paramType; + } + + public getIndex(): number { + return this.index; + } + + public setIndex(index: number): void { + this.index = index; + } + + public getType(): Type { + return this.paramType; + } + + public setType(newType: Type): void { + this.paramType = newType; + } + + public inferType(arkMethod: ArkMethod): AbstractRef { + return IRInference.inferParameterRef(this, arkMethod); + } + + public getUses(): Value[] { + return []; + } + + public toString(): string { + return 'parameter' + this.index + ': ' + this.paramType; + } +} + + +export class ArkThisRef extends AbstractRef { + private type: ClassType; + + constructor(type: ClassType) { + super(); + this.type = type; + } + + public getType(): ClassType { + return this.type; + } + + public getUses(): Value[] { + return []; + } + + public toString(): string { + return 'this: ' + this.type; + } +} + +export class ArkCaughtExceptionRef extends AbstractRef { + private type: Type; + + constructor(type: Type) { + super(); + this.type = type; + } + + public getType(): Type { + return this.type; + } + + public getUses(): Value[] { + return []; + } + + public toString(): string { + return 'caughtexception: ' + this.type; + } +} + +export class GlobalRef extends AbstractRef { + private name: string; + private ref: Value | null; + private usedStmts: Stmt[]; + + constructor(name: string, ref?: Value) { + super(); + this.name = name; + this.ref = ref ?? null; + this.usedStmts = []; + } + + public getName(): string { + return this.name; + } + + public getUses(): Value[] { + return this.ref?.getUses() || []; + } + + public getType(): Type { + return this.ref?.getType() || UnknownType.getInstance(); + } + + public getRef(): Value | null { + return this.ref || null; + } + + public setRef(value: Value): void { + this.ref = value; + } + + public getUsedStmts(): Stmt[] { + return this.usedStmts; + } + + public addUsedStmts(usedStmts: Stmt | Stmt[]): void { + if (usedStmts instanceof Stmt) { + this.usedStmts.push(usedStmts); + } else { + usedStmts.forEach(stmt => this.usedStmts.push(stmt)); + } + } + + public toString(): string { + return this.getName(); + } +} + +export class ClosureFieldRef extends AbstractRef { + private base: Local; + private fieldName: string; + private type: Type; + + constructor(base: Local, fieldName: string, type: Type) { + super(); + this.base = base; + this.fieldName = fieldName; + this.type = type; + } + + public getUses(): Value[] { + return []; + } + + public getBase(): Local { + return this.base; + } + + public getType(): Type { + return this.type; + } + + public getFieldName(): string { + return this.fieldName; + } + + public toString(): string { + return this.base.toString() + '.' + this.getFieldName(); + } + + public inferType(arkMethod: ArkMethod): AbstractRef { + if (TypeInference.isUnclearType(this.type)) { + let type: Type | undefined = this.base.getType(); + if (type instanceof LexicalEnvType) { + type = type.getClosures().find(c => c.getName() === this.fieldName)?.getType(); + } + if (type && !TypeInference.isUnclearType(type)) { + this.type = type; + } + } + return this; + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/base/Stmt.ts b/ets2panda/linter/arkanalyzer/src/core/base/Stmt.ts new file mode 100644 index 0000000000..914bf73043 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/base/Stmt.ts @@ -0,0 +1,603 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { StmtUseReplacer } from '../common/StmtUseReplacer'; +import { Cfg } from '../graph/Cfg'; +import { AbstractExpr, AbstractInvokeExpr, AliasTypeExpr, ArkConditionExpr } from './Expr'; +import { AbstractFieldRef, ArkArrayRef } from './Ref'; +import { Value } from './Value'; +import { FullPosition, LineColPosition } from './Position'; +import { ArkMetadata, ArkMetadataKind, ArkMetadataType } from '../model/ArkMetadata'; +import { StmtDefReplacer } from '../common/StmtDefReplacer'; +import { IRUtils } from '../common/IRUtils'; +import { AliasType, ArrayType, IntersectionType, TupleType, Type, UnionType } from './Type'; +import { ModifierType } from '../model/ArkBaseModel'; +import { AbstractTypeExpr } from './TypeExpr'; + +/** + * @category core/base/stmt + */ +export abstract class Stmt { + protected text?: string; // just for debug + protected originalText?: string; + protected originalPosition: LineColPosition = LineColPosition.DEFAULT; + protected cfg!: Cfg; + protected operandOriginalPositions?: FullPosition[]; // operandOriginalPositions correspond with + // def and uses one by one + metadata?: ArkMetadata; + + public getMetadata(kind: ArkMetadataKind): ArkMetadataType | undefined { + return this.metadata?.getMetadata(kind); + } + + public setMetadata(kind: ArkMetadataKind, value: ArkMetadataType): void { + if (!this.metadata) { + this.metadata = new ArkMetadata(); + } + return this.metadata?.setMetadata(kind, value); + } + + /** Return a list of values which are uesd in this statement */ + public getUses(): Value[] { + return []; + } + + public replaceUse(oldUse: Value, newUse: Value): void { + const stmtUseReplacer = new StmtUseReplacer(oldUse, newUse); + stmtUseReplacer.caseStmt(this); + } + + /** + * Return the definition which is uesd in this statement. Generally, the definition is the left value of `=` in + * 3AC. For example, the definition in 3AC of `value = parameter0: @project-1/sample-1.ets: AnonymousClass-0` is + * `value`, and the definition in `$temp0 = staticinvoke <@_ProjectName/_FileName: xxx.create()>()` is `\$temp0`. + * @returns The definition in 3AC (may be a **null**). + * @example + * 1. get the def in stmt. + ```typescript + for (const block of this.blocks) { + for (const stmt of block.getStmts()) { + const defValue = stmt.getDef(); + ... + } + } + ``` + */ + public getDef(): Value | null { + return null; + } + + public replaceDef(oldDef: Value, newDef: Value): void { + const stmtDefReplacer = new StmtDefReplacer(oldDef, newDef); + stmtDefReplacer.caseStmt(this); + } + + public getDefAndUses(): Value[] { + const defAndUses: Value[] = []; + const def = this.getDef(); + if (def) { + defAndUses.push(def); + } + defAndUses.push(...this.getUses()); + return defAndUses; + } + + /** + * Get the CFG (i.e., control flow graph) of an {@link ArkBody} in which the statement is. + * A CFG contains a set of basic blocks and statements corresponding to each basic block. + * Note that, "source code" and "three-address" are two types of {@link Stmt} in ArkAnalyzer. + * Source code {@link Stmt} represents the statement of ets/ts source code, while three-address code {@link Stmt} + * represents the statement after it has been converted into three-address code. Since the source code {@link + * Stmt} does not save its CFG reference, it returns **null**, while the `getCfg()` of the third address code + * {@link Stmt} will return its CFG reference. + * @returns The CFG (i.e., control flow graph) of an {@link ArkBody} in which the statement is. + * @example + * 1. get the ArkFile based on stmt. + ```typescript + const arkFile = stmt.getCfg()?.getDeclaringMethod().getDeclaringArkFile(); + ``` + 2. get the ArkMethod based on stmt. + ```typescript + let sourceMethod: ArkMethod = stmt.getCfg()?.getDeclaringMethod(); + ``` + */ + public getCfg(): Cfg { + return this.cfg; + } + + public setCfg(cfg: Cfg): void { + this.cfg = cfg; + } + + /** + * Return true if the following statement may not execute after this statement. + * The ArkIfStmt and ArkGotoStmt will return true. + */ + public isBranch(): boolean { + return false; + } + + /** Return the number of statements which this statement may go to */ + public getExpectedSuccessorCount(): number { + return 1; + } + + public containsInvokeExpr(): boolean { + for (const use of this.getUses()) { + if (use instanceof AbstractInvokeExpr) { + return true; + } + } + return false; + } + + /** + * Returns the method's invocation expression (including method signature and its arguments) + * in the current statement. An **undefined** will be returned if there is no method used in this statement. + * @returns the method's invocation expression from the statement. An **undefined** will be returned if there is + * no method can be found in this statement. + * @example + * 1. get invoke expr based on stmt. + ```typescript + let invoke = stmt.getInvokeExpr(); + ``` + */ + public getInvokeExpr(): AbstractInvokeExpr | undefined { + for (const use of this.getUses()) { + if (use instanceof AbstractInvokeExpr) { + return use as AbstractInvokeExpr; + } + } + return undefined; + } + + /** + * Returns an array of expressions in the statement. + * @returns An array of expressions in the statement. + * @example + * 1. Traverse expression of statement. + + ```typescript + for (const expr of stmt.getExprs()) { + ... + } + ``` + */ + public getExprs(): AbstractExpr[] { + let exprs: AbstractExpr[] = []; + for (const use of this.getUses()) { + if (use instanceof AbstractExpr) { + exprs.push(use); + } + } + return exprs; + } + + public getTypeExprs(): AbstractTypeExpr[] { + let typeExprs: AbstractTypeExpr[] = []; + for (const value of this.getDefAndUses()) { + const valueType = value.getType(); + if (valueType instanceof AbstractTypeExpr) { + typeExprs.push(valueType); + } + } + return typeExprs; + } + + public containsArrayRef(): boolean { + for (const use of this.getUses()) { + if (use instanceof ArkArrayRef) { + return true; + } + } + if (this.getDef() instanceof ArkArrayRef) { + return true; + } + return false; + } + + public getArrayRef(): ArkArrayRef | undefined { + for (const use of this.getUses()) { + if (use instanceof ArkArrayRef) { + return use as ArkArrayRef; + } + } + + if (this.getDef() instanceof ArkArrayRef) { + return undefined; + } + + return undefined; + } + + public containsFieldRef(): boolean { + for (const use of this.getUses()) { + if (use instanceof AbstractFieldRef) { + return true; + } + } + + if (this.getDef() instanceof AbstractFieldRef) { + return true; + } + return false; + } + + public getFieldRef(): AbstractFieldRef | undefined { + for (const use of this.getUses()) { + if (use instanceof AbstractFieldRef) { + return use as AbstractFieldRef; + } + } + if (this.getDef() instanceof AbstractFieldRef) { + return undefined; + } + return undefined; + } + + public setOriginPositionInfo(originPositionInfo: LineColPosition): void { + this.originalPosition = originPositionInfo; + } + + /** + * Returns the original position of the statement. + * The position consists of two parts: line number and column number. + * In the source file, the former (i.e., line number) indicates which line the statement is in, + * and the latter (i.e., column number) indicates the position of the statement in the line. + * The position is described as `LineColPosition(lineNo,colNum)` in ArkAnalyzer, + * and its default value is LineColPosition(-1,-1). + * @returns The original location of the statement. + * @example + * 1. Get the stmt position info to make some condition judgements. + ```typescript + for (const stmt of stmts) { + if (stmt.getOriginPositionInfo().getLineNo() === -1) { + stmt.setOriginPositionInfo(originalStmt.getOriginPositionInfo()); + this.stmtToOriginalStmt.set(stmt, originalStmt); + } + } + ``` + */ + public getOriginPositionInfo(): LineColPosition { + return this.originalPosition; + } + + abstract toString(): string ; + + public setText(text: string): void { + this.text = text; + } + + public setOriginalText(originalText: string): void { + this.originalText = originalText; + } + + public getOriginalText(): string | undefined { + return this.originalText; + } + + public setOperandOriginalPositions(operandOriginalPositions: FullPosition[]): void { + this.operandOriginalPositions = operandOriginalPositions; + }; + + public getOperandOriginalPositions(): FullPosition[] | undefined { + return this.operandOriginalPositions; + }; + + public getOperandOriginalPosition(indexOrOperand: number | Value): FullPosition | null { + let index:number = -1; + if (typeof indexOrOperand !== 'number') { + index = IRUtils.findOperandIdx(this, indexOrOperand); + } else { + index = indexOrOperand; + } + + if (!this.operandOriginalPositions || index < 0 || index > this.operandOriginalPositions.length) { + return null; + } + return this.operandOriginalPositions[index]; + }; +} + +export class ArkAssignStmt extends Stmt { + private leftOp: Value; + private rightOp: Value; + + constructor(leftOp: Value, rightOp: Value) { + super(); + this.leftOp = leftOp; + this.rightOp = rightOp; + } + + /** + * Returns the left operand of the assigning statement. + * @returns The left operand of the assigning statement. + * @example + * 1. If the statement is `a=b;`, the right operand is `a`; if the statement is `dd = cc + 5;`, the right operand + * is `cc`. + */ + public getLeftOp(): Value { + return this.leftOp; + } + + public setLeftOp(newLeftOp: Value): void { + this.leftOp = newLeftOp; + } + + /** + * Returns the right operand of the assigning statement. + * @returns The right operand of the assigning statement. + * @example + * 1. If the statement is `a=b;`, the right operand is `b`; if the statement is `dd = cc + 5;`, the right operand + * is `cc + 5`. + * 2. Get the rightOp from stmt. + ```typescript + const rightOp = stmt.getRightOp(); + ``` + */ + public getRightOp(): Value { + return this.rightOp; + } + + public setRightOp(rightOp: Value): void { + this.rightOp = rightOp; + } + + public toString(): string { + const str = this.getLeftOp() + ' = ' + this.getRightOp(); + return str; + } + + public getDef(): Value | null { + return this.leftOp; + } + + public getUses(): Value[] { + let uses: Value[] = []; + uses.push(...this.leftOp.getUses()); + uses.push(this.rightOp); + uses.push(...this.rightOp.getUses()); + return uses; + } +} + +export class ArkInvokeStmt extends Stmt { + private invokeExpr: AbstractInvokeExpr; + + constructor(invokeExpr: AbstractInvokeExpr) { + super(); + this.invokeExpr = invokeExpr; + } + + public replaceInvokeExpr(newExpr: AbstractInvokeExpr) { + this.invokeExpr = newExpr; + } + + public getInvokeExpr() { + return this.invokeExpr; + } + + public toString(): string { + const str = this.invokeExpr.toString(); + return str; + } + + public getUses(): Value[] { + let uses: Value[] = []; + uses.push(this.invokeExpr); + uses.push(...this.invokeExpr.getUses()); + return uses; + } +} + +export class ArkIfStmt extends Stmt { + private conditionExpr: ArkConditionExpr; + + constructor(conditionExpr: ArkConditionExpr) { + super(); + this.conditionExpr = conditionExpr; + } + + /** + * The condition expression consisit of two values as operands and one binary operator as operator. + * The operator can indicate the relation between the two values, e.g., `<`, `<=`,`>`, `>=`, `==`, `!=`, `===`, + * `!==`. + * @returns a condition expression. + * @example + * 1. When a statement is `if (a > b)`, the operands are `a` and `b`, the operator is `<`. Therefore, the condition + * expression is `a > b`. + * 2. get a conditon expr from a condition statement. + ```typescript + let expr = (this.original as ArkIfStmt).getConditionExpr(); + ``` + */ + public getConditionExpr(): ArkConditionExpr { + return this.conditionExpr; + } + + public setConditionExpr(newConditionExpr: ArkConditionExpr): void { + this.conditionExpr = newConditionExpr; + } + + public isBranch(): boolean { + return true; + } + + public getExpectedSuccessorCount(): number { + return 2; + } + + public toString(): string { + const str = 'if ' + this.conditionExpr; + return str; + } + + public getUses(): Value[] { + let uses: Value[] = []; + uses.push(this.conditionExpr); + uses.push(...this.conditionExpr.getUses()); + return uses; + } +} + +export class ArkReturnStmt extends Stmt { + private op: Value; + + constructor(op: Value) { + super(); + this.op = op; + } + + public getExpectedSuccessorCount(): number { + return 0; + } + + public getOp(): Value { + return this.op; + } + + public setReturnValue(returnValue: Value): void { + this.op = returnValue; + } + + public toString(): string { + const str = 'return ' + this.op; + return str; + } + + public getUses(): Value[] { + let uses: Value[] = []; + uses.push(this.op); + uses.push(...this.op.getUses()); + return uses; + } +} + +export class ArkReturnVoidStmt extends Stmt { + constructor() { + super(); + } + + public getExpectedSuccessorCount(): number { + return 0; + } + + public toString(): string { + const str = 'return'; + return str; + } +} + +export class ArkThrowStmt extends Stmt { + private op: Value; + + constructor(op: Value) { + super(); + this.op = op; + } + + public getOp(): Value { + return this.op; + } + + public setOp(newOp: Value): void { + this.op = newOp; + } + + public toString(): string { + const str = 'throw ' + this.op; + return str; + } + + public getUses(): Value[] { + let uses: Value[] = []; + uses.push(this.op); + uses.push(...this.op.getUses()); + return uses; + } +} + +/** + * Statement of type alias definition combines with the left hand as {@link AliasType} and right hand as {@link AliasTypeExpr}. + * @category core/base/stmt + * @extends Stmt + * @example + ```typescript + type A = string; + type B = import('./abc').TypeB; + + let c = 123; + declare type C = typeof c; + ``` + */ +export class ArkAliasTypeDefineStmt extends Stmt { + private aliasType: AliasType; + private aliasTypeExpr: AliasTypeExpr; + + constructor(aliasType: AliasType, typeAliasExpr: AliasTypeExpr) { + super(); + this.aliasType = aliasType; + this.aliasTypeExpr = typeAliasExpr; + } + + public getAliasType(): AliasType { + return this.aliasType; + } + + public getAliasTypeExpr(): AliasTypeExpr { + return this.aliasTypeExpr; + } + + public getAliasName(): string { + return this.getAliasType().getName(); + } + + public toString(): string { + let str = `type ${this.getAliasType().toString()} = ${this.getAliasTypeExpr().toString()}`; + if (this.getAliasType().containsModifier(ModifierType.DECLARE)) { + str = 'declare ' + str; + } + if (this.getAliasType().containsModifier(ModifierType.EXPORT)) { + str = 'export ' + str; + } + return str; + } + + public getExprs(): AliasTypeExpr[] { + return [this.getAliasTypeExpr()]; + } + + public getTypeExprs(): AbstractTypeExpr[] { + function getTypeExprsInType(originalObject: Type): AbstractTypeExpr[] { + let typeExprs: AbstractTypeExpr[] = []; + if (originalObject instanceof AbstractTypeExpr) { + typeExprs.push(originalObject); + } else if (originalObject instanceof ArrayType) { + typeExprs.push(...getTypeExprsInType(originalObject.getBaseType())); + } else if (originalObject instanceof UnionType || originalObject instanceof IntersectionType || originalObject instanceof TupleType) { + for (const member of originalObject.getTypes()) { + typeExprs.push(...getTypeExprsInType(member)); + } + } + return typeExprs; + } + + const originalObject = this.getAliasTypeExpr().getOriginalObject(); + if (originalObject instanceof Type) { + return getTypeExprsInType(originalObject); + } + return []; + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/base/Trap.ts b/ets2panda/linter/arkanalyzer/src/core/base/Trap.ts new file mode 100644 index 0000000000..b5e22d7594 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/base/Trap.ts @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { BasicBlock } from '../graph/BasicBlock'; + +export class Trap { + private readonly tryBlocks: BasicBlock[]; + private readonly catchBlocks: BasicBlock[]; + + constructor(tryBlocks: BasicBlock[], catchBlocks: BasicBlock[]) { + this.tryBlocks = tryBlocks; + this.catchBlocks = catchBlocks; + } + + public getTryBlocks(): BasicBlock[] { + return this.tryBlocks; + } + + public getCatchBlocks(): BasicBlock[] { + return this.catchBlocks; + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/base/Type.ts b/ets2panda/linter/arkanalyzer/src/core/base/Type.ts new file mode 100644 index 0000000000..18a85c32fc --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/base/Type.ts @@ -0,0 +1,794 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { AliasTypeSignature, ClassSignature, MethodSignature, NamespaceSignature, } from '../model/ArkSignature'; +import { ArkExport, ExportType } from '../model/ArkExport'; +import { MODIFIER_TYPE_MASK, ModifierType } from '../model/ArkBaseModel'; +import { + ANY_KEYWORD, + BIGINT_KEYWORD, + BOOLEAN_KEYWORD, + NEVER_KEYWORD, + NULL_KEYWORD, + NUMBER_KEYWORD, + STRING_KEYWORD, + UNDEFINED_KEYWORD, + UNKNOWN_KEYWORD, + VOID_KEYWORD, +} from '../common/TSConst'; +import { Local } from './Local'; + +/** + * @category core/base/type + */ +export abstract class Type { + toString(): string { + return this.getTypeString(); + } + + abstract getTypeString(): string; +} + +/** + * any type + * @category core/base/type + */ +export class AnyType extends Type { + private static readonly INSTANCE = new AnyType(); + + public static getInstance(): AnyType { + return this.INSTANCE; + } + + private constructor() { + super(); + } + + public getTypeString(): string { + return ANY_KEYWORD; + } +} + +/** + * unknown type + * @category core/base/type + */ +export class UnknownType extends Type { + private static readonly INSTANCE = new UnknownType(); + + public static getInstance(): UnknownType { + return this.INSTANCE; + } + + private constructor() { + super(); + } + + public getTypeString(): string { + return UNKNOWN_KEYWORD; + } +} + +/** + * unclear type + * @category core/base/type + */ +export class UnclearReferenceType extends Type { + private name: string; + private genericTypes: Type[]; + + constructor(name: string, genericTypes: Type[] = []) { + super(); + this.name = name; + this.genericTypes = genericTypes; + } + + public getName() { + return this.name; + } + + public getGenericTypes(): Type[] { + return this.genericTypes; + } + + public getTypeString(): string { + let str = this.name; + if (this.genericTypes.length > 0) { + str += '<' + this.genericTypes.join(',') + '>'; + } + return str; + } +} + +/** + * primitive type + * @category core/base/type + */ +export abstract class PrimitiveType extends Type { + private name: string; + + constructor(name: string) { + super(); + this.name = name; + } + + public getName() { + return this.name; + } + + public getTypeString(): string { + return this.name; + } +} + +export class BooleanType extends PrimitiveType { + private static readonly INSTANCE = new BooleanType(); + + private constructor() { + super(BOOLEAN_KEYWORD); + } + + public static getInstance() { + return this.INSTANCE; + } +} + +export class NumberType extends PrimitiveType { + private static readonly INSTANCE = new NumberType(); + + private constructor() { + super(NUMBER_KEYWORD); + } + + public static getInstance() { + return this.INSTANCE; + } +} + +/** + * bigint type + * @category core/base/type + */ +export class BigIntType extends PrimitiveType { + private static readonly INSTANCE = new BigIntType(); + + private constructor() { + super(BIGINT_KEYWORD); + } + + public static getInstance() { + return this.INSTANCE; + } +} + +export class StringType extends PrimitiveType { + private static readonly INSTANCE = new StringType(); + + private constructor() { + super(STRING_KEYWORD); + } + + public static getInstance() { + return this.INSTANCE; + } +} + +/** + * null type + * @category core/base/type + */ +export class NullType extends PrimitiveType { + private static readonly INSTANCE = new NullType(); + + public static getInstance(): NullType { + return this.INSTANCE; + } + + private constructor() { + super(NULL_KEYWORD); + } +} + +/** + * undefined type + * @category core/base/type + */ +export class UndefinedType extends PrimitiveType { + private static readonly INSTANCE = new UndefinedType(); + + public static getInstance(): UndefinedType { + return this.INSTANCE; + } + + private constructor() { + super(UNDEFINED_KEYWORD); + } +} + +/** + * literal type + * @category core/base/type + */ +export class LiteralType extends PrimitiveType { + public static readonly TRUE = new LiteralType(true); + public static readonly FALSE = new LiteralType(false); + + private literalName: string | number | boolean; + + constructor(literalName: string | number | boolean) { + super('literal'); + this.literalName = literalName; + } + + public getLiteralName(): string | number | boolean { + return this.literalName; + } + + public getTypeString(): string { + return this.literalName.toString(); + } +} + +/** + * union type + * @category core/base/type + */ +export class UnionType extends Type { + private types: Type[]; + private currType: Type; // The true type of the value at this time + constructor(types: Type[], currType: Type = UnknownType.getInstance()) { + super(); + this.types = [...types]; + this.currType = currType; + } + + public getTypes(): Type[] { + return this.types; + } + + public getCurrType(): Type { + return this.currType; + } + + public setCurrType(newType: Type): void { + this.currType = newType; + } + + public getTypeString(): string { + let typesString: string[] = []; + this.getTypes().forEach((t) => { + if (t instanceof UnionType || t instanceof IntersectionType) { + typesString.push(`(${t.toString()})`); + } else { + typesString.push(t.toString()); + } + }); + return typesString.join('|'); + } + + // TODO: Need to remove this function because of IntersectionType has been added. + public flatType(): Type[] { + const result: Type[] = []; + this.types.forEach(t => { + if (t instanceof UnionType) { + t.flatType().forEach(e => result.push(e)); + } else { + result.push(t); + } + }); + return result; + } +} + +/** + * intersection type + * @category core/base/type + */ +export class IntersectionType extends Type { + private types: Type[]; + + constructor(types: Type[]) { + super(); + this.types = [...types]; + } + + public getTypes(): Type[] { + return this.types; + } + + public getTypeString(): string { + let typesString: string[] = []; + this.getTypes().forEach((t) => { + if (t instanceof UnionType || t instanceof IntersectionType) { + typesString.push(`(${t.toString()})`); + } else { + typesString.push(t.toString()); + } + }); + return typesString.join('&'); + } +} + +/** + * types for function void return type + * @category core/base/type + */ +export class VoidType extends Type { + private static readonly INSTANCE = new VoidType(); + + public static getInstance(): VoidType { + return this.INSTANCE; + } + + private constructor() { + super(); + } + + public getTypeString(): string { + return VOID_KEYWORD; + } +} + +export class NeverType extends Type { + private static readonly INSTANCE = new NeverType(); + + public static getInstance(): NeverType { + return this.INSTANCE; + } + + private constructor() { + super(); + } + + public getTypeString(): string { + return NEVER_KEYWORD; + } +} + +/** + * function type + * @category core/base/type + */ +export class FunctionType extends Type { + private methodSignature: MethodSignature; + private realGenericTypes?: Type[]; + + constructor(methodSignature: MethodSignature, realGenericTypes?: Type[]) { + super(); + this.methodSignature = methodSignature; + this.realGenericTypes = realGenericTypes; + } + + public getMethodSignature(): MethodSignature { + return this.methodSignature; + } + + public getRealGenericTypes(): Type[] | undefined { + return this.realGenericTypes; + } + + public getTypeString(): string { + return this.methodSignature.toString(); + } +} + +/** + * types for closures which is a special FunctionType with a lexical env + * @category core/base/type + */ +export class ClosureType extends FunctionType { + private lexicalEnv: LexicalEnvType; + + constructor(lexicalEnv: LexicalEnvType, methodSignature: MethodSignature, realGenericTypes?: Type[]) { + super(methodSignature, realGenericTypes); + this.lexicalEnv = lexicalEnv; + } + + public getLexicalEnv(): LexicalEnvType { + return this.lexicalEnv; + } + + public getTypeString(): string { + return 'closures: ' + super.getTypeString(); + } +} + +/** + * type of an object + * @category core/base/type + */ +export class ClassType extends Type { + private classSignature: ClassSignature; + private realGenericTypes?: Type[]; + + constructor(classSignature: ClassSignature, realGenericTypes?: Type[]) { + super(); + this.classSignature = classSignature; + this.realGenericTypes = realGenericTypes; + } + + public getClassSignature(): ClassSignature { + return this.classSignature; + } + + public setClassSignature(newClassSignature: ClassSignature): void { + this.classSignature = newClassSignature; + } + + public getRealGenericTypes(): Type[] | undefined { + return this.realGenericTypes; + } + + public setRealGenericTypes(types: Type[] | undefined): void { + this.realGenericTypes = types; + } + + public getTypeString(): string { + let temp = this.classSignature.toString(); + let generic = this.realGenericTypes?.join(','); + if (generic) { + temp += `<${generic}>`; + } + return temp; + } +} + +/** + * Array type + * @category core/base/type + * @extends Type + * @example + ```typescript + // baseType is number, dimension is 1, readonlyFlag is true + let a: readonly number[] = [1, 2, 3]; + + // baseType is number, dimension is 1, readonlyFlag is undefined + let a: number[] = [1, 2, 3]; + ``` + */ +export class ArrayType extends Type { + private baseType: Type; + private dimension: number; + private readonlyFlag?: boolean; + + constructor(baseType: Type, dimension: number) { + super(); + this.baseType = baseType; + this.dimension = dimension; + } + + /** + * Returns the base type of this array, such as `Any`, `Unknown`, `TypeParameter`, etc. + * @returns The base type of array. + */ + public getBaseType(): Type { + return this.baseType; + } + + public setBaseType(newType: Type): void { + this.baseType = newType; + } + + public getDimension(): number { + return this.dimension; + } + + public setReadonlyFlag(readonlyFlag: boolean): void { + this.readonlyFlag = readonlyFlag; + } + + public getReadonlyFlag(): boolean | undefined { + return this.readonlyFlag; + } + + public getTypeString(): string { + const strs: string[] = []; + if (this.getReadonlyFlag()) { + strs.push('readonly '); + } + if (this.baseType instanceof UnionType || this.baseType instanceof IntersectionType) { + strs.push('(' + this.baseType.toString() + ')'); + } else if (this.baseType) { + strs.push(this.baseType.toString()); + } + for (let i = 0; i < this.dimension; i++) { + strs.push('[]'); + } + return strs.join(''); + } +} + +/** + * Tuple type + * @category core/base/type + * @extends Type + * @example + ```typescript + // types are number and string, dimension is 1, readonlyFlag is true + let a: readonly number[] = [1, 2, 3]; + + // baseType is number, dimension is 1, readonlyFlag is undefined + let a: number[] = [1, 2, 3]; + ``` + */ +export class TupleType extends Type { + private types: Type[]; + private readonlyFlag?: boolean; + + constructor(types: Type[]) { + super(); + this.types = types; + } + + public getTypes(): Type[] { + return this.types; + } + + public setReadonlyFlag(readonlyFlag: boolean): void { + this.readonlyFlag = readonlyFlag; + } + + public getReadonlyFlag(): boolean | undefined { + return this.readonlyFlag; + } + + public getTypeString(): string { + if (this.getReadonlyFlag()) { + return 'readonly [' + this.types.join(', ') + ']'; + } + return '[' + this.types.join(', ') + ']'; + } +} + +/** + * alias type + * @category core/base/type + * @extends Type + * @example + ```typescript + // alias type A is defined without any genericTypes (undefined) or realGenericTypes (undefined) + type A = number; + + // alias type B is defined with genericTypes but not instance with realGenericTypes (undefined) + type B = T[]; + + // alias type could also be defined with another instance generic type such as aliaType, FunctionType and ClassType + // genericTypes and realGenericTypes of C are both undefined + // originalType of C is an instance of B with genericTypes [T] and realGenericTypes [numberType] + type C = B; + ``` + */ +export class AliasType extends Type implements ArkExport { + private originalType: Type; + private name: string; + private signature: AliasTypeSignature; + protected modifiers?: number; + private genericTypes?: GenericType[]; + private realGenericTypes?: Type[]; + + constructor(name: string, originalType: Type, signature: AliasTypeSignature, genericTypes?: GenericType[]) { + super(); + this.name = name; + this.originalType = originalType; + this.signature = signature; + this.genericTypes = genericTypes; + } + + public getName(): string { + return this.name; + } + + public setOriginalType(type: Type): void { + this.originalType = type; + } + + public getOriginalType(): Type { + return this.originalType; + } + + public getTypeString(): string { + let res = this.getSignature().toString(); + let generic = this.getRealGenericTypes()?.join(',') ?? this.getGenericTypes()?.join(','); + if (generic) { + res += `<${generic}>`; + } + return res; + } + + public getExportType(): ExportType { + return ExportType.TYPE; + } + + public getModifiers(): number { + if (!this.modifiers) { + return 0; + } + return this.modifiers; + } + + public containsModifier(modifierType: ModifierType): boolean { + if (!this.modifiers) { + return false; + } + + return (this.modifiers & modifierType) === modifierType; + } + + public setModifiers(modifiers: number): void { + if (modifiers !== 0) { + this.modifiers = modifiers; + } + } + + public addModifier(modifier: ModifierType | number): void { + this.modifiers = this.getModifiers() | modifier; + } + + public removeModifier(modifier: ModifierType): void { + if (!this.modifiers) { + return; + } + this.modifiers &= MODIFIER_TYPE_MASK ^ modifier; + } + + public getSignature(): AliasTypeSignature { + return this.signature; + } + + public setGenericTypes(genericTypes: GenericType[]): void { + this.genericTypes = genericTypes; + } + + public getGenericTypes(): GenericType[] | undefined { + return this.genericTypes; + } + + public setRealGenericTypes(realGenericTypes: Type[]): void { + this.realGenericTypes = realGenericTypes; + } + + public getRealGenericTypes(): Type[] | undefined { + return this.realGenericTypes; + } +} + +export class GenericType extends Type { + private name: string; + private defaultType?: Type; + private constraint?: Type; + private index: number = 0; + + constructor(name: string, defaultType?: Type, constraint?: Type) { + super(); + this.name = name; + this.defaultType = defaultType; + this.constraint = constraint; + } + + public getName(): string { + return this.name; + } + + public getDefaultType(): Type | undefined { + return this.defaultType; + } + + public setDefaultType(type: Type): void { + this.defaultType = type; + } + + public getConstraint(): Type | undefined { + return this.constraint; + } + + public setConstraint(type: Type): void { + this.constraint = type; + } + + public setIndex(index: number) { + this.index = index; + } + + public getIndex(): number { + return this.index ?? 0; + } + + public getTypeString(): string { + let str = this.name; + if (this.constraint) { + str += ' extends ' + this.constraint.toString(); + } + if (this.defaultType) { + str += ' = ' + this.defaultType.toString(); + } + return str; + } +} + +export abstract class AnnotationType extends Type { + private originType: string; + + protected constructor(originType: string) { + super(); + this.originType = originType; + } + + public getOriginType(): string { + return this.originType; + } + + public getTypeString(): string { + return this.originType; + } +} + +export class AnnotationNamespaceType extends AnnotationType { + private namespaceSignature: NamespaceSignature = NamespaceSignature.DEFAULT; + + public static getInstance(signature: NamespaceSignature): AnnotationNamespaceType { + const type = new AnnotationNamespaceType(signature.getNamespaceName()); + type.setNamespaceSignature(signature); + return type; + } + + public getNamespaceSignature(): NamespaceSignature { + return this.namespaceSignature; + } + + public setNamespaceSignature(signature: NamespaceSignature): void { + this.namespaceSignature = signature; + } + + constructor(originType: string) { + super(originType); + } + + public getOriginType(): string { + return super.getOriginType(); + } +} + +export class AnnotationTypeQueryType extends AnnotationType { + constructor(originType: string) { + super(originType); + } +} + +export class LexicalEnvType extends Type { + private nestedMethodSignature: MethodSignature; + private closures: Local[] = []; + + constructor(nestedMethod: MethodSignature, closures?: Local[]) { + super(); + this.nestedMethodSignature = nestedMethod; + this.closures = closures ?? this.closures; + } + + public getNestedMethod(): MethodSignature { + return this.nestedMethodSignature; + } + + public getClosures(): Local[] { + return this.closures; + } + + public addClosure(closure: Local): void { + this.closures.push(closure); + } + + public getTypeString(): string { + return `[${this.getClosures().join(', ')}]`; + } +} diff --git a/ets2panda/linter/arkanalyzer/src/core/base/TypeExpr.ts b/ets2panda/linter/arkanalyzer/src/core/base/TypeExpr.ts new file mode 100644 index 0000000000..c390f3ce5b --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/base/TypeExpr.ts @@ -0,0 +1,178 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Value } from './Value'; +import { ArkMethod } from '../model/ArkMethod'; +import { IntersectionType, Type, UnionType, UnknownType } from './Type'; +import { IRInference } from '../common/IRInference'; +import { ArkBaseModel } from '../model/ArkBaseModel'; +import { ModelUtils } from '../common/ModelUtils'; +import { ArkClass } from '../model/ArkClass'; + +/** + * abstract type expr represents the type operations of types or values. + * AbstractTypeExpr is different from AbstractExpr. + * @category core/base/typeExpr + * @extends Type + * @example + * ```typescript + * let a = number; + * type A = typeof a; + * let b: keyof typeof a; + * ``` + */ +export abstract class AbstractTypeExpr extends Type { + abstract getUses(): Value[]; + + abstract getType(): Type; + + public inferType(arkMethod: ArkMethod): void { + return; + } +} + +/** + * typeQuery type expr represents the get type of value with typeof. + * @category core/base/typeExpr + * @extends AbstractTypeExpr + * @example + ```typescript + // opValue is a and type A is number + let a = number; + type A = typeof a; + ``` + */ + +export class TypeQueryExpr extends AbstractTypeExpr { + private opValue: Value | ArkBaseModel; + private genericTypes?: Type[]; + + constructor(opValue: Value | ArkBaseModel, generateTypes?: Type[]) { + super(); + this.opValue = opValue; + this.genericTypes = generateTypes; + } + + public setOpValue(opValue: Value | ArkBaseModel): void { + this.opValue = opValue; + } + + public getOpValue(): Value | ArkBaseModel { + return this.opValue; + } + + public setGenerateTypes(types: Type[]): void { + this.genericTypes = types; + } + + public getGenerateTypes(): Type[] | undefined { + return this.genericTypes; + } + + public addGenericType(gType: Type): void { + if (!this.genericTypes) { + this.genericTypes = []; + } + this.genericTypes.push(gType); + } + + public getUses(): Value[] { + const opValue = this.getOpValue(); + if (opValue instanceof ArkBaseModel) { + return []; + } + let uses: Value[] = []; + uses.push(opValue); + uses.push(...opValue.getUses()); + return uses; + } + + public getType(): Type { + const opValue = this.getOpValue(); + if (opValue instanceof ArkBaseModel) { + return ModelUtils.parseArkBaseModel2Type(opValue) ?? UnknownType.getInstance(); + } + return opValue.getType(); + } + + public getTypeString(): string { + const opValue = this.getOpValue(); + const gTypes = this.getGenerateTypes(); + const genericStr = gTypes && gTypes.length > 0 ? `<${gTypes.join(',')}>` : ''; + if (opValue instanceof ArkClass || opValue instanceof ArkMethod) { + return `typeof ${opValue.getSignature().toString()}${genericStr}`; + } + return `typeof ${opValue.toString()}${genericStr}`; + } + + public inferType(arkMethod: ArkMethod): void { + IRInference.inferTypeQueryExpr(this, arkMethod); + } +} + +/** + * keyof type expr represents the type operator with keyof. + * It should be an internal expr. + * the final type should be transferred to union type, unless it cannot find out all types within the union type. + * @category core/base/typeExpr + * @extends AbstractTypeExpr + * @example + ```typescript + // opType is {a: 1, b: 2} and type of A is KeyofTypeExpr, which can be transferred to union type {'a', 'b'} + type A = keyof {a: 1, b: 2}; + + // opType is number and type of B is KeyofTypeExpr, which can be transferred to union type "toString" | "toFixed" | "toExponential" | ... + type B = keyof number; + ``` + */ +export class KeyofTypeExpr extends AbstractTypeExpr { + private opType: Type; + + constructor(opType: Type) { + super(); + this.opType = opType; + } + + public getOpType(): Type { + return this.opType; + } + + public setOpType(opType: Type): void { + this.opType = opType; + } + + public getUses(): Value[] { + let uses: Value[] = []; + if (this.getOpType() instanceof TypeQueryExpr) { + uses.push(...(this.getOpType() as TypeQueryExpr).getUses()); + } + return uses; + } + + public getType(): Type { + return this; + } + + public getTypeString(): string { + if (this.getOpType() instanceof UnionType || this.getOpType() instanceof IntersectionType) { + return `keyof (${this.getOpType().toString()})`; + } + return `keyof ${this.getOpType().toString()}`; + } + + public inferType(arkMethod: ArkMethod): void { + IRInference.inferKeyofTypeExpr(this, arkMethod); + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/base/Value.ts b/ets2panda/linter/arkanalyzer/src/core/base/Value.ts new file mode 100644 index 0000000000..89ed31ee51 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/base/Value.ts @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Type } from './Type'; + +/** + * @category core/base + */ +export interface Value { + /** + * Return a list of values which are contained in this {@link Value}. + * Value is a core interface in ArkAnalyzer, which may represent any value or expression. + * @returns An **array** of values used by this value. + */ + getUses(): Value[]; + + /** + * Return the type of this value. The interface is encapsulated in {@link Value}. + * The `Type` is defined in type.ts, such as **Any**, **Unknown**, **TypeParameter**, + * **UnclearReference**, **Primitive**, **Number**, **String**, etc. + * @returns The type of this value. + * @example + * 1. In the declaration statement, determine the left-value type and right-value type. + + ```typescript + let leftValue:Value; + let rightValue:Value; + ... + if (leftValue.getType() instanceof UnknownType && + !(rightValue.getType() instanceof UnknownType) && + !(rightValue.getType() instanceof UndefinedType)) { + ... + } + ``` + */ + getType():Type; +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/common/ArkError.ts b/ets2panda/linter/arkanalyzer/src/core/common/ArkError.ts new file mode 100644 index 0000000000..be9fa839a1 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/common/ArkError.ts @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export enum ArkErrorCode { + OK = 0, + CLASS_INSTANCE_FIELD_UNDEFINDED = -1, + BB_MORE_THAN_ONE_BRANCH_RET_STMT = -2, + BB_BRANCH_RET_STMT_NOT_AT_END = -3, + CFG_NOT_FOUND_START_BLOCK = -4, + CFG_HAS_UNREACHABLE_BLOCK = -5, + METHOD_SIGNATURE_UNDEFINED = -6, + METHOD_SIGNATURE_LINE_UNMATCHED = -7, +} + +export interface ArkError { + errCode: ArkErrorCode; + errMsg?: string; +} diff --git a/ets2panda/linter/arkanalyzer/src/core/common/ArkIRTransformer.ts b/ets2panda/linter/arkanalyzer/src/core/common/ArkIRTransformer.ts new file mode 100644 index 0000000000..ab15671794 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/common/ArkIRTransformer.ts @@ -0,0 +1,869 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + AbstractInvokeExpr, + AliasTypeExpr, + ArkCastExpr, + ArkConditionExpr, + ArkInstanceInvokeExpr, + ArkStaticInvokeExpr, + BinaryOperator, + NormalBinaryOperator, + RelationalBinaryOperator, + UnaryOperator, +} from '../base/Expr'; +import { ArkCaughtExceptionRef, ArkInstanceFieldRef, ArkParameterRef, ArkThisRef, GlobalRef } from '../base/Ref'; +import { Value } from '../base/Value'; +import * as ts from 'ohos-typescript'; +import { Local } from '../base/Local'; +import { + ArkAliasTypeDefineStmt, + ArkAssignStmt, + ArkIfStmt, + ArkInvokeStmt, + ArkReturnStmt, + ArkReturnVoidStmt, + ArkThrowStmt, + Stmt, +} from '../base/Stmt'; +import { AliasType, BooleanType, ClassType, Type, UnclearReferenceType, UnknownType, VoidType } from '../base/Type'; +import { ValueUtil } from './ValueUtil'; +import { + AliasTypeSignature, + ClassSignature, + FieldSignature, + MethodSignature, + MethodSubSignature, +} from '../model/ArkSignature'; + +import { IRUtils } from './IRUtils'; +import { ArkMethod } from '../model/ArkMethod'; +import { buildArkMethodFromArkClass } from '../model/builder/ArkMethodBuilder'; +import { ArkSignatureBuilder } from '../model/builder/ArkSignatureBuilder'; +import { + COMPONENT_BRANCH_FUNCTION, + COMPONENT_CREATE_FUNCTION, + COMPONENT_IF, + COMPONENT_POP_FUNCTION, + COMPONENT_REPEAT, +} from './EtsConst'; +import { FullPosition, LineColPosition } from '../base/Position'; +import { ModelUtils } from './ModelUtils'; +import { Builtin } from './Builtin'; +import { DEFAULT, PROMISE } from './TSConst'; +import { buildGenericType, buildModifiers, buildTypeParameters } from '../model/builder/builderUtils'; +import { ArkValueTransformer } from './ArkValueTransformer'; +import { ImportInfo } from '../model/ArkImport'; +import { TypeInference } from './TypeInference'; +import { AbstractTypeExpr } from '../base/TypeExpr'; +import { buildNormalArkClassFromArkMethod } from '../model/builder/ArkClassBuilder'; +import { ArkClass } from '../model/ArkClass'; +import { ModifierType } from '../model/ArkBaseModel'; + +export type ValueAndStmts = { + value: Value, + valueOriginalPositions: FullPosition[], // original positions of value and its uses + stmts: Stmt[] +}; + +export class DummyStmt extends Stmt { + constructor(text: string) { + super(); + this.text = text; + } + + public toString(): string { + return this.text!; + } +} + +export class ArkIRTransformer { + public static readonly DUMMY_LOOP_INITIALIZER_STMT = 'LoopInitializer'; + public static readonly DUMMY_CONDITIONAL_OPERATOR = 'ConditionalOperator'; + public static readonly DUMMY_CONDITIONAL_OPERATOR_IF_TRUE_STMT = ArkIRTransformer.DUMMY_CONDITIONAL_OPERATOR + 'IfTrue'; + public static readonly DUMMY_CONDITIONAL_OPERATOR_IF_FALSE_STMT = ArkIRTransformer.DUMMY_CONDITIONAL_OPERATOR + 'IfFalse'; + public static readonly DUMMY_CONDITIONAL_OPERATOR_END_STMT = ArkIRTransformer.DUMMY_CONDITIONAL_OPERATOR + 'End'; + + private sourceFile: ts.SourceFile; + private declaringMethod: ArkMethod; + private inBuilderMethod = false; + private builderMethodContextFlag = false; + private stmtsHaveOriginalText: Set = new Set(); + private arkValueTransformer: ArkValueTransformer; + + constructor(sourceFile: ts.SourceFile, declaringMethod: ArkMethod) { + this.sourceFile = sourceFile; + this.declaringMethod = declaringMethod; + this.inBuilderMethod = ModelUtils.isArkUIBuilderMethod(declaringMethod); + this.arkValueTransformer = new ArkValueTransformer(this, sourceFile, this.declaringMethod); + } + + public getLocals(): Set { + return this.arkValueTransformer.getLocals(); + } + + public getGlobals(): Map | null { + return this.arkValueTransformer.getGlobals(); + } + + public getThisLocal(): Local { + return this.arkValueTransformer.getThisLocal(); + } + + public getAliasTypeMap(): Map { + return this.arkValueTransformer.getAliasTypeMap(); + } + + public prebuildStmts(): Stmt[] { + const stmts: Stmt[] = []; + let index = 0; + for (const methodParameter of this.declaringMethod.getParameters()) { + const parameterRef = new ArkParameterRef(index, methodParameter.getType()); + stmts.push(new ArkAssignStmt( + this.arkValueTransformer.addNewLocal(methodParameter.getName(), parameterRef.getType()), + parameterRef)); + index++; + } + + const thisRef = new ArkThisRef(this.arkValueTransformer.getThisLocal().getType() as ClassType); + stmts.push(new ArkAssignStmt(this.arkValueTransformer.getThisLocal(), thisRef)); + return stmts; + } + + public tsNodeToStmts(node: ts.Node): Stmt[] { + let stmts: Stmt[] = []; + if (ts.isExpressionStatement(node)) { + stmts = this.expressionStatementToStmts(node); + } else if (ts.isTypeAliasDeclaration(node)) { + stmts = this.typeAliasDeclarationToStmts(node); + } else if (ts.isBlock(node)) { + stmts = this.blockToStmts(node); + } else if (ts.isForStatement(node)) { + stmts = this.forStatementToStmts(node); + } else if (ts.isForInStatement(node) || ts.isForOfStatement(node)) { + stmts = this.rangeForStatementToStmts(node); + } else if (ts.isWhileStatement(node)) { + stmts = this.whileStatementToStmts(node); + } else if (ts.isDoStatement(node)) { + stmts = this.doStatementToStmts(node); + } else if (ts.isVariableStatement(node)) { + stmts = this.variableStatementToStmts(node); + } else if (ts.isVariableDeclarationList(node)) { + stmts = this.variableDeclarationListToStmts(node); + } else if (ts.isIfStatement(node)) { + stmts = this.ifStatementToStmts(node); + } else if (ts.isBreakStatement(node) || ts.isContinueStatement(node)) { + stmts = this.gotoStatementToStmts(node); + } else if (ts.isThrowStatement(node)) { + stmts = this.throwStatementToStmts(node); + } else if (ts.isCatchClause(node)) { + stmts = this.catchClauseToStmts(node); + } else if (ts.isReturnStatement(node)) { + stmts = this.returnStatementToStmts(node); + } else if (ts.isFunctionDeclaration(node)) { + stmts = this.functionDeclarationToStmts(node); + } else if (ts.isExportAssignment(node)) { + stmts = this.expressionInExportToStmts(node.expression); + } else if (ts.isClassDeclaration(node)) { + stmts = this.classDeclarationToStmts(node); + } + + this.mapStmtsToTsStmt(stmts, node); + if (stmts.length > 0) { + IRUtils.setComments(stmts[0], node, this.sourceFile, this.declaringMethod.getDeclaringArkFile().getScene().getOptions()); + } + return stmts; + } + + public tsNodeToValueAndStmts(node: ts.Node): ValueAndStmts { + return this.arkValueTransformer.tsNodeToValueAndStmts(node); + } + + private functionDeclarationToStmts(functionDeclarationNode: ts.FunctionDeclaration): Stmt[] { + const declaringClass = this.declaringMethod.getDeclaringArkClass(); + const arkMethod = new ArkMethod(); + if (this.builderMethodContextFlag) { + ModelUtils.implicitArkUIBuilderMethods.add(arkMethod); + } + buildArkMethodFromArkClass(functionDeclarationNode, declaringClass, arkMethod, this.sourceFile, this.declaringMethod); + return []; + } + + private classDeclarationToStmts(node: ts.ClassDeclaration): Stmt[] { + const cls = new ArkClass(); + const declaringArkNamespace = this.declaringMethod.getDeclaringArkClass().getDeclaringArkNamespace(); + if (declaringArkNamespace) { + cls.setDeclaringArkNamespace(declaringArkNamespace); + } + cls.setDeclaringArkFile(this.declaringMethod.getDeclaringArkFile()); + buildNormalArkClassFromArkMethod(node, cls, this.sourceFile, this.declaringMethod); + return []; + } + + private returnStatementToStmts(returnStatement: ts.ReturnStatement): Stmt[] { + const stmts: Stmt[] = []; + if (returnStatement.expression) { + let { + value: exprValue, + valueOriginalPositions: exprPositions, + stmts: exprStmts, + } = this.tsNodeToValueAndStmts(returnStatement.expression); + exprStmts.forEach(stmt => stmts.push(stmt)); + if (IRUtils.moreThanOneAddress(exprValue)) { + ({ + value: exprValue, + valueOriginalPositions: exprPositions, + stmts: exprStmts, + } = this.generateAssignStmtForValue(exprValue, exprPositions)); + exprStmts.forEach(stmt => stmts.push(stmt)); + } + const returnStmt = new ArkReturnStmt(exprValue); + returnStmt.setOperandOriginalPositions(exprPositions); + stmts.push(returnStmt); + if (this.declaringMethod.getSubSignature().getReturnType() instanceof UnknownType) { + this.declaringMethod.getSubSignature().setReturnType(exprValue.getType()); + } + return stmts; + } + stmts.push(new ArkReturnVoidStmt()); + if (this.declaringMethod.getSubSignature().getReturnType() instanceof UnknownType) { + if (this.declaringMethod.containsModifier(ModifierType.ASYNC)) { + const promise = this.declaringMethod.getDeclaringArkFile().getScene().getSdkGlobal(PROMISE); + if (promise instanceof ArkClass) { + this.declaringMethod.getSubSignature().setReturnType(new ClassType(promise.getSignature())); + } else { + this.declaringMethod.getSubSignature().setReturnType(new UnclearReferenceType(PROMISE, [VoidType.getInstance()])); + } + } else { + this.declaringMethod.getSubSignature().setReturnType(VoidType.getInstance()); + } + } + return stmts; + } + + private blockToStmts(block: ts.Block): Stmt[] { + const stmts: Stmt[] = []; + for (const statement of block.statements) { + this.tsNodeToStmts(statement).forEach(stmt => stmts.push(stmt)); + } + return stmts; + } + + private expressionStatementToStmts(expressionStatement: ts.ExpressionStatement): Stmt[] { + const exprNode = expressionStatement.expression; + const { + value: exprValue, + valueOriginalPositions: exprPositions, + stmts: stmts, + } = this.tsNodeToValueAndStmts(exprNode); + if (exprValue instanceof AbstractInvokeExpr) { + this.addInvokeStmts(exprValue, exprPositions, stmts); + } else if (this.shouldGenerateExtraAssignStmt(exprNode)) { + const { stmts: exprStmts } = this.generateAssignStmtForValue(exprValue, exprPositions); + exprStmts.forEach(stmt => stmts.push(stmt)); + } + return stmts; + } + + private addInvokeStmts(invokeExpr: AbstractInvokeExpr, exprPositions: FullPosition[], stmts: Stmt[]): void { + const invokeStmt = new ArkInvokeStmt(invokeExpr); + invokeStmt.setOperandOriginalPositions(exprPositions); + stmts.push(invokeStmt); + + let hasRepeat: boolean = false; + for (const stmt of stmts) { + if ((stmt instanceof ArkAssignStmt) && (stmt.getRightOp() instanceof ArkStaticInvokeExpr)) { + const rightOp = stmt.getRightOp() as ArkStaticInvokeExpr; + if (rightOp.getMethodSignature().getMethodSubSignature().getMethodName() === COMPONENT_REPEAT) { + const createMethodSignature = + ArkSignatureBuilder.buildMethodSignatureFromClassNameAndMethodName(COMPONENT_REPEAT, COMPONENT_CREATE_FUNCTION); + const createInvokeExpr = new ArkStaticInvokeExpr(createMethodSignature, rightOp.getArgs()); + stmt.setRightOp(createInvokeExpr); + hasRepeat = true; + } + } + } + if (hasRepeat) { + const popMethodSignature = ArkSignatureBuilder.buildMethodSignatureFromClassNameAndMethodName(COMPONENT_REPEAT, COMPONENT_POP_FUNCTION); + const popInvokeExpr = new ArkStaticInvokeExpr(popMethodSignature, []); + const popInvokeStmt = new ArkInvokeStmt(popInvokeExpr); + stmts.push(popInvokeStmt); + } + } + + private shouldGenerateExtraAssignStmt(expression: ts.Expression): boolean { + if (ts.isParenthesizedExpression(expression)) { + return this.shouldGenerateExtraAssignStmt(expression.expression); + } + if ((ts.isBinaryExpression(expression) && (expression.operatorToken.kind === ts.SyntaxKind.FirstAssignment || + ArkValueTransformer.isCompoundAssignmentOperator(expression.operatorToken.kind))) || + ts.isEtsComponentExpression(expression) || ts.isVoidExpression(expression) || + ts.isNewExpression(expression) || ts.isCallExpression(expression) || + (ts.isPrefixUnaryExpression(expression) && + (expression.operator === ts.SyntaxKind.PlusPlusToken || + expression.operator === ts.SyntaxKind.MinusMinusToken)) || + (ts.isPostfixUnaryExpression(expression) && + (expression.operator === ts.SyntaxKind.PlusPlusToken || + expression.operator === ts.SyntaxKind.MinusMinusToken))) { + return false; + } + + return true; + } + + private typeAliasDeclarationToStmts(typeAliasDeclaration: ts.TypeAliasDeclaration): Stmt[] { + const aliasName = typeAliasDeclaration.name.text; + const rightOp = typeAliasDeclaration.type; + let rightType = this.arkValueTransformer.resolveTypeNode(rightOp); + if (rightType instanceof AbstractTypeExpr) { + rightType = rightType.getType(); + } + + const aliasType = new AliasType(aliasName, rightType, new AliasTypeSignature(aliasName, this.declaringMethod.getSignature())); + if (typeAliasDeclaration.typeParameters) { + const genericTypes = buildTypeParameters(typeAliasDeclaration.typeParameters, this.sourceFile, this.declaringMethod); + aliasType.setGenericTypes(genericTypes); + aliasType.setOriginalType(buildGenericType(rightType, aliasType)); + rightType = aliasType.getOriginalType(); + } + + let expr = this.generateAliasTypeExpr(rightOp, aliasType); + + if ((ts.isTypeQueryNode(rightOp) || ts.isTypeReferenceNode(rightOp)) && rightOp.typeArguments) { + let realGenericTypes: Type[] = []; + rightOp.typeArguments.forEach(typeArgument => { + realGenericTypes.push(this.arkValueTransformer.resolveTypeNode(typeArgument)); + }); + expr.setRealGenericTypes(realGenericTypes); + } + + const modifiers = typeAliasDeclaration.modifiers ? buildModifiers(typeAliasDeclaration) : 0; + aliasType.setModifiers(modifiers); + + const aliasTypeDefineStmt = new ArkAliasTypeDefineStmt(aliasType, expr); + const leftPosition = FullPosition.buildFromNode(typeAliasDeclaration.name, this.sourceFile); + const rightPosition = FullPosition.buildFromNode(rightOp, this.sourceFile); + const operandOriginalPositions = [leftPosition, rightPosition]; + aliasTypeDefineStmt.setOperandOriginalPositions(operandOriginalPositions); + + this.getAliasTypeMap().set(aliasName, [aliasType, aliasTypeDefineStmt]); + + return [aliasTypeDefineStmt]; + } + + private generateAliasTypeExpr(rightOp: ts.TypeNode, aliasType: AliasType): AliasTypeExpr { + let rightType = aliasType.getOriginalType(); + let expr: AliasTypeExpr; + if (ts.isImportTypeNode(rightOp)) { + expr = this.resolveImportTypeNode(rightOp); + const typeObject = expr.getOriginalObject(); + if (typeObject instanceof ImportInfo && typeObject.getLazyExportInfo() !== null) { + const arkExport = typeObject.getLazyExportInfo()!.getArkExport(); + rightType = TypeInference.parseArkExport2Type(arkExport) ?? UnknownType.getInstance(); + aliasType.setOriginalType(rightType); + } + } else if (ts.isTypeQueryNode(rightOp)) { + const localName = rightOp.exprName.getText(this.sourceFile); + const originalLocal = Array.from(this.arkValueTransformer.getLocals()).find(local => + local.getName() === localName); + if (originalLocal === undefined || rightType instanceof UnclearReferenceType) { + expr = new AliasTypeExpr(new Local(localName, rightType), true); + } else { + expr = new AliasTypeExpr(originalLocal, true); + } + } else if (ts.isTypeReferenceNode(rightOp)) { + // For type A = B stmt and B is also an alias type with the same scope of A, + // rightType here is AliasType with real generic type number. + // The originalObject in expr should be the object without real generic type, so try to find it in this scope. + if (rightType instanceof AliasType) { + const existAliasType = this.getAliasTypeMap().get(rightType.getName()); + if (existAliasType) { + expr = new AliasTypeExpr(existAliasType[0], false); + } else { + expr = new AliasTypeExpr(rightType, false); + } + } else { + expr = new AliasTypeExpr(rightType, false); + } + } else { + expr = new AliasTypeExpr(rightType, false); + + // 对于type A = {x:1, y:2}语句,当前阶段即可精确获取ClassType类型,需找到对应的ArkClass作为originalObject + // 对于其他情况此处为UnclearReferenceTye并由类型推导进行查找和处理 + if (rightType instanceof ClassType) { + const classObject = ModelUtils.getClassWithName(rightType.getClassSignature().getClassName(), this.declaringMethod.getDeclaringArkClass()); + if (classObject) { + expr.setOriginalObject(classObject); + } + } + } + return expr; + } + + private resolveImportTypeNode(importTypeNode: ts.ImportTypeNode): AliasTypeExpr { + const importType = 'typeAliasDefine'; + let importFrom = ''; + let importClauseName = ''; + + if (ts.isLiteralTypeNode(importTypeNode.argument)) { + if (ts.isStringLiteral(importTypeNode.argument.literal)) { + importFrom = importTypeNode.argument.literal.text; + } + } + + const importQualifier = importTypeNode.qualifier; + if (importQualifier !== undefined) { + importClauseName = importQualifier.getText(this.sourceFile); + } + + let importInfo = new ImportInfo(); + importInfo.build(importClauseName, importType, importFrom, LineColPosition.buildFromNode(importTypeNode, this.sourceFile), 0); + importInfo.setDeclaringArkFile(this.declaringMethod.getDeclaringArkFile()); + + // Function getLazyExportInfo will automatically try to infer the export info if it's undefined at the beginning. + importInfo.getLazyExportInfo(); + return new AliasTypeExpr(importInfo, importTypeNode.isTypeOf); + } + + public switchStatementToValueAndStmts(switchStatement: ts.SwitchStatement): ValueAndStmts[] { + const valueAndStmtsOfSwitchAndCases: ValueAndStmts[] = []; + const exprStmts: Stmt[] = []; + let { + value: exprValue, + valueOriginalPositions: exprPositions, + stmts: exprTempStmts, + } = this.tsNodeToValueAndStmts(switchStatement.expression); + exprTempStmts.forEach(stmt => exprStmts.push(stmt)); + if (IRUtils.moreThanOneAddress(exprValue)) { + ({ value: exprValue, valueOriginalPositions: exprPositions, stmts: exprTempStmts } = + this.generateAssignStmtForValue(exprValue, exprPositions)); + exprTempStmts.forEach(stmt => exprStmts.push(stmt)); + } + valueAndStmtsOfSwitchAndCases.push( + { value: exprValue, valueOriginalPositions: exprPositions, stmts: exprStmts }); + + for (const clause of switchStatement.caseBlock.clauses) { + if (ts.isCaseClause(clause)) { + const clauseStmts: Stmt[] = []; + let { + value: clauseValue, + valueOriginalPositions: clausePositions, + stmts: clauseTempStmts, + } = this.tsNodeToValueAndStmts(clause.expression); + clauseTempStmts.forEach(stmt => clauseStmts.push(stmt)); + if (IRUtils.moreThanOneAddress(clauseValue)) { + ({ + value: clauseValue, + valueOriginalPositions: clausePositions, + stmts: clauseTempStmts, + } = this.generateAssignStmtForValue(clauseValue, clausePositions)); + clauseTempStmts.forEach(stmt => clauseStmts.push(stmt)); + } + valueAndStmtsOfSwitchAndCases.push( + { value: clauseValue, valueOriginalPositions: clausePositions, stmts: clauseStmts }); + } + } + return valueAndStmtsOfSwitchAndCases; + } + + private forStatementToStmts(forStatement: ts.ForStatement): Stmt[] { + const stmts: Stmt[] = []; + if (forStatement.initializer) { + this.tsNodeToValueAndStmts(forStatement.initializer).stmts.forEach(stmt => stmts.push(stmt)); + } + const dummyInitializerStmt = new DummyStmt(ArkIRTransformer.DUMMY_LOOP_INITIALIZER_STMT); + stmts.push(dummyInitializerStmt); + + if (forStatement.condition) { + const { + value: conditionValue, + stmts: conditionStmts, + } = this.arkValueTransformer.conditionToValueAndStmts(forStatement.condition); + conditionStmts.forEach(stmt => stmts.push(stmt)); + stmts.push(new ArkIfStmt(conditionValue as ArkConditionExpr)); + } else { + // The omitted condition always evaluates to true. + const trueConstant = ValueUtil.getBooleanConstant(true); + const conditionExpr = new ArkConditionExpr(trueConstant, trueConstant, RelationalBinaryOperator.Equality); + stmts.push(new ArkIfStmt(conditionExpr)); + } + if (forStatement.incrementor) { + this.tsNodeToValueAndStmts(forStatement.incrementor).stmts.forEach(stmt => stmts.push(stmt)); + } + return stmts; + } + + private rangeForStatementToStmts(forOfStatement: ts.ForOfStatement | ts.ForInStatement): Stmt[] { + const stmts: Stmt[] = []; + let { + value: iterableValue, + valueOriginalPositions: iterablePositions, + stmts: iterableStmts, + } = this.tsNodeToValueAndStmts(forOfStatement.expression); + iterableStmts.forEach(stmt => stmts.push(stmt)); + if (!(iterableValue instanceof Local)) { + ({ value: iterableValue, valueOriginalPositions: iterablePositions, stmts: iterableStmts } = + this.generateAssignStmtForValue(iterableValue, iterablePositions)); + iterableStmts.forEach(stmt => stmts.push(stmt)); + } + const iteratorMethodSubSignature = new MethodSubSignature(Builtin.ITERATOR_FUNCTION, [], + Builtin.ITERATOR_CLASS_TYPE); + const iteratorMethodSignature = new MethodSignature(ClassSignature.DEFAULT, iteratorMethodSubSignature); + const iteratorInvokeExpr = new ArkInstanceInvokeExpr(iterableValue as Local, iteratorMethodSignature, []); + const iteratorInvokeExprPositions = [iterablePositions[0], ...iterablePositions]; + const { + value: iterator, + valueOriginalPositions: iteratorPositions, + stmts: iteratorStmts, + } = this.generateAssignStmtForValue(iteratorInvokeExpr, iteratorInvokeExprPositions); + iteratorStmts.forEach(stmt => stmts.push(stmt)); + (iterator as Local).setType(Builtin.ITERATOR_CLASS_TYPE); + + const nextMethodSubSignature = new MethodSubSignature(Builtin.ITERATOR_NEXT, [], + Builtin.ITERATOR_RESULT_CLASS_TYPE); + const nextMethodSignature = new MethodSignature(ClassSignature.DEFAULT, nextMethodSubSignature); + const iteratorNextInvokeExpr = new ArkInstanceInvokeExpr(iterator as Local, nextMethodSignature, []); + const iteratorNextInvokeExprPositions = [iteratorPositions[0], ...iteratorPositions]; + const { + value: iteratorResult, + valueOriginalPositions: iteratorResultPositions, + stmts: iteratorResultStmts, + } = this.generateAssignStmtForValue(iteratorNextInvokeExpr, + iteratorNextInvokeExprPositions); + iteratorResultStmts.forEach(stmt => stmts.push(stmt)); + (iteratorResult as Local).setType(Builtin.ITERATOR_RESULT_CLASS_TYPE); + const doneFieldSignature = new FieldSignature(Builtin.ITERATOR_RESULT_DONE, + Builtin.ITERATOR_RESULT_CLASS_SIGNATURE, BooleanType.getInstance(), false); + const doneFieldRef = new ArkInstanceFieldRef(iteratorResult as Local, doneFieldSignature); + const doneFieldRefPositions = [iteratorResultPositions[0], ...iteratorResultPositions]; + const { + value: doneFlag, + valueOriginalPositions: doneFlagPositions, + stmts: doneFlagStmts, + } = this.generateAssignStmtForValue(doneFieldRef, doneFieldRefPositions); + doneFlagStmts.forEach(stmt => stmts.push(stmt)); + (doneFlag as Local).setType(BooleanType.getInstance()); + const conditionExpr = new ArkConditionExpr(doneFlag, ValueUtil.getBooleanConstant(true), RelationalBinaryOperator.Equality); + const conditionExprPositions = [doneFlagPositions[0], ...doneFlagPositions, FullPosition.DEFAULT]; + const ifStmt = new ArkIfStmt(conditionExpr); + ifStmt.setOperandOriginalPositions(conditionExprPositions); + stmts.push(ifStmt); + + const valueFieldSignature = new FieldSignature(Builtin.ITERATOR_RESULT_VALUE, + Builtin.ITERATOR_RESULT_CLASS_SIGNATURE, UnknownType.getInstance(), false); + const valueFieldRef = new ArkInstanceFieldRef(iteratorResult as Local, valueFieldSignature); + const valueFieldRefPositions = [iteratorResultPositions[0], ...iteratorResultPositions]; + const { + value: yieldValue, + valueOriginalPositions: yieldValuePositions, + stmts: yieldValueStmts, + } = this.generateAssignStmtForValue(valueFieldRef, valueFieldRefPositions); + yieldValueStmts.forEach(stmt => stmts.push(stmt)); + + const castExpr = new ArkCastExpr(yieldValue, UnknownType.getInstance()); + const castExprPositions = [yieldValuePositions[0], ...yieldValuePositions]; + const initializerNode = forOfStatement.initializer; + if (ts.isVariableDeclarationList(initializerNode)) { + const isConst = (initializerNode.flags & ts.NodeFlags.Const) !== 0; + const { + value: initValue, valueOriginalPositions: initOriPos, stmts: initStmts, + } = this.arkValueTransformer.variableDeclarationToValueAndStmts(initializerNode.declarations[0], isConst, + false); + const assignStmt = new ArkAssignStmt(initValue, castExpr); + assignStmt.setOperandOriginalPositions([...initOriPos, ...castExprPositions]); + stmts.push(assignStmt); + initStmts.forEach(stmt => stmts.push(stmt)); + } else { // initializer maybe an expression + const { + value: initValue, valueOriginalPositions: initOriPos, stmts: initStmts, + } = this.tsNodeToValueAndStmts(initializerNode); + const assignStmt = new ArkAssignStmt(initValue, castExpr); + assignStmt.setOperandOriginalPositions([...initOriPos, ...castExprPositions]); + initStmts.forEach(stmt => stmts.push(stmt)); + stmts.push(assignStmt); + } + return stmts; + } + + private whileStatementToStmts(whileStatement: ts.WhileStatement): Stmt[] { + const stmts: Stmt[] = []; + const dummyInitializerStmt = new DummyStmt(ArkIRTransformer.DUMMY_LOOP_INITIALIZER_STMT); + stmts.push(dummyInitializerStmt); + + const { + value: conditionExpr, + stmts: conditionStmts, + } = this.arkValueTransformer.conditionToValueAndStmts(whileStatement.expression); + conditionStmts.forEach(stmt => stmts.push(stmt)); + stmts.push(new ArkIfStmt(conditionExpr as ArkConditionExpr)); + return stmts; + } + + private doStatementToStmts(doStatement: ts.DoStatement): Stmt[] { + const stmts: Stmt[] = []; + const { + value: conditionExpr, + stmts: conditionStmts, + } = this.arkValueTransformer.conditionToValueAndStmts(doStatement.expression); + conditionStmts.forEach(stmt => stmts.push(stmt)); + stmts.push(new ArkIfStmt(conditionExpr as ArkConditionExpr)); + return stmts; + } + + private variableStatementToStmts(variableStatement: ts.VariableStatement): Stmt[] { + return this.variableDeclarationListToStmts(variableStatement.declarationList); + } + + private variableDeclarationListToStmts(variableDeclarationList: ts.VariableDeclarationList): Stmt[] { + return this.arkValueTransformer.variableDeclarationListToValueAndStmts(variableDeclarationList).stmts; + } + + private ifStatementToStmts(ifStatement: ts.IfStatement): Stmt[] { + const stmts: Stmt[] = []; + if (this.inBuilderMethod) { + const { + value: conditionExpr, + valueOriginalPositions: conditionExprPositions, + stmts: conditionStmts, + } = this.arkValueTransformer.conditionToValueAndStmts(ifStatement.expression); + conditionStmts.forEach(stmt => stmts.push(stmt)); + const createMethodSignature = ArkSignatureBuilder.buildMethodSignatureFromClassNameAndMethodName(COMPONENT_IF, COMPONENT_CREATE_FUNCTION); + const { + value: conditionLocal, + valueOriginalPositions: conditionLocalPositions, + stmts: assignConditionStmts + } = this.generateAssignStmtForValue(conditionExpr, conditionExprPositions); + assignConditionStmts.forEach(stmt => stmts.push(stmt)); + const createInvokeExpr = new ArkStaticInvokeExpr(createMethodSignature, [conditionLocal]); + const createInvokeExprPositions = [conditionLocalPositions[0], ...conditionLocalPositions]; + const { stmts: createStmts } = this.generateAssignStmtForValue(createInvokeExpr, + createInvokeExprPositions); + createStmts.forEach(stmt => stmts.push(stmt)); + const branchMethodSignature = ArkSignatureBuilder.buildMethodSignatureFromClassNameAndMethodName(COMPONENT_IF, COMPONENT_BRANCH_FUNCTION); + const branchInvokeExpr = new ArkStaticInvokeExpr(branchMethodSignature, [ValueUtil.getOrCreateNumberConst(0)]); + const branchInvokeExprPositions = [conditionLocalPositions[0], FullPosition.DEFAULT]; + const branchInvokeStmt = new ArkInvokeStmt(branchInvokeExpr); + branchInvokeStmt.setOperandOriginalPositions(branchInvokeExprPositions); + stmts.push(branchInvokeStmt); + this.tsNodeToStmts(ifStatement.thenStatement).forEach(stmt => stmts.push(stmt)); + if (ifStatement.elseStatement) { + const branchElseMethodSignature = ArkSignatureBuilder.buildMethodSignatureFromClassNameAndMethodName(COMPONENT_IF, COMPONENT_BRANCH_FUNCTION); + const branchElseInvokeExpr = new ArkStaticInvokeExpr(branchElseMethodSignature, [ValueUtil.getOrCreateNumberConst(1)]); + const branchElseInvokeExprPositions = [FullPosition.buildFromNode(ifStatement.elseStatement, + this.sourceFile), FullPosition.DEFAULT]; + const branchElseInvokeStmt = new ArkInvokeStmt(branchElseInvokeExpr); + branchElseInvokeStmt.setOperandOriginalPositions(branchElseInvokeExprPositions); + stmts.push(branchElseInvokeStmt); + + this.tsNodeToStmts(ifStatement.elseStatement).forEach(stmt => stmts.push(stmt)); + } + const popMethodSignature = ArkSignatureBuilder.buildMethodSignatureFromClassNameAndMethodName(COMPONENT_IF, COMPONENT_POP_FUNCTION); + const popInvokeExpr = new ArkStaticInvokeExpr(popMethodSignature, []); + const popInvokeStmt = new ArkInvokeStmt(popInvokeExpr); + stmts.push(popInvokeStmt); + } else { + const { + value: conditionExpr, + valueOriginalPositions: conditionExprPositions, + stmts: conditionStmts, + } = this.arkValueTransformer.conditionToValueAndStmts(ifStatement.expression); + conditionStmts.forEach(stmt => stmts.push(stmt)); + const ifStmt = new ArkIfStmt(conditionExpr as ArkConditionExpr); + ifStmt.setOperandOriginalPositions(conditionExprPositions); + stmts.push(ifStmt); + } + return stmts; + } + + private gotoStatementToStmts(gotoStatement: ts.BreakStatement | ts.ContinueStatement): Stmt[] { + return []; + } + + private throwStatementToStmts(throwStatement: ts.ThrowStatement): Stmt[] { + const stmts: Stmt[] = []; + const { + value: throwValue, + valueOriginalPositions: throwValuePositions, + stmts: throwStmts, + } = this.tsNodeToValueAndStmts(throwStatement.expression); + throwStmts.forEach(stmt => stmts.push(stmt)); + const throwStmt = new ArkThrowStmt(throwValue); + throwStmt.setOperandOriginalPositions(throwValuePositions); + stmts.push(throwStmt); + return stmts; + } + + private catchClauseToStmts(catchClause: ts.CatchClause): Stmt[] { + const stmts: Stmt[] = []; + if (catchClause.variableDeclaration) { + const { + value: catchValue, valueOriginalPositions: catchOriPos, stmts: catchStmts, + } = this.arkValueTransformer.variableDeclarationToValueAndStmts(catchClause.variableDeclaration, false, + false); + const caughtExceptionRef = new ArkCaughtExceptionRef(UnknownType.getInstance()); + const assignStmt = new ArkAssignStmt(catchValue, caughtExceptionRef); + assignStmt.setOperandOriginalPositions(catchOriPos); + stmts.push(assignStmt); + catchStmts.forEach(stmt => stmts.push(stmt)); + } + return stmts; + } + + private expressionInExportToStmts(expression: ts.Node): Stmt[] { + if (ts.isNewExpression(expression) || ts.isObjectLiteralExpression(expression)) { + return this.newClassInExportToStmts(expression); + } + return []; + } + + private newClassInExportToStmts(expression: ts.NewExpression | ts.ObjectLiteralExpression): Stmt[] { + let stmts: Stmt[] = []; + let { + value: rightValue, + valueOriginalPositions: rightPositions, + stmts: rightStmts, + } = this.tsNodeToValueAndStmts(expression); + rightStmts.forEach(stmt => stmts.push(stmt)); + let leftValue = this.arkValueTransformer.addNewLocal(DEFAULT); + let leftPositions = rightPositions; + const assignStmt = new ArkAssignStmt(leftValue, rightValue); + assignStmt.setOperandOriginalPositions([...leftPositions, ...rightPositions]); + stmts.push(assignStmt); + return stmts; + } + + public mapStmtsToTsStmt(stmts: Stmt[], node: ts.Node): void { + for (const stmt of stmts) { + if (!this.stmtsHaveOriginalText.has(stmt)) { + this.stmtsHaveOriginalText.add(stmt); + stmt.setOriginPositionInfo(LineColPosition.buildFromNode(node, this.sourceFile)); + stmt.setOriginalText(node.getText(this.sourceFile)); + } + } + } + + public static tokenToUnaryOperator(token: ts.SyntaxKind): UnaryOperator | null { + switch (token) { + case ts.SyntaxKind.MinusToken: + return UnaryOperator.Neg; + case ts.SyntaxKind.TildeToken: + return UnaryOperator.BitwiseNot; + case ts.SyntaxKind.ExclamationToken: + return UnaryOperator.LogicalNot; + default: + ; + } + return null; + } + + public static tokenToBinaryOperator(token: ts.SyntaxKind): BinaryOperator | null { + switch (token) { + case ts.SyntaxKind.QuestionQuestionToken: + return NormalBinaryOperator.NullishCoalescing; + case ts.SyntaxKind.AsteriskAsteriskToken: + return NormalBinaryOperator.Exponentiation; + case ts.SyntaxKind.SlashToken: + return NormalBinaryOperator.Division; + case ts.SyntaxKind.PlusToken: + return NormalBinaryOperator.Addition; + case ts.SyntaxKind.MinusToken: + return NormalBinaryOperator.Subtraction; + case ts.SyntaxKind.AsteriskToken: + return NormalBinaryOperator.Multiplication; + case ts.SyntaxKind.PercentToken: + return NormalBinaryOperator.Remainder; + case ts.SyntaxKind.LessThanLessThanToken: + return NormalBinaryOperator.LeftShift; + case ts.SyntaxKind.GreaterThanGreaterThanToken: + return NormalBinaryOperator.RightShift; + case ts.SyntaxKind.GreaterThanGreaterThanGreaterThanToken: + return NormalBinaryOperator.UnsignedRightShift; + case ts.SyntaxKind.AmpersandToken: + return NormalBinaryOperator.BitwiseAnd; + case ts.SyntaxKind.BarToken: + return NormalBinaryOperator.BitwiseOr; + case ts.SyntaxKind.CaretToken: + return NormalBinaryOperator.BitwiseXor; + case ts.SyntaxKind.AmpersandAmpersandToken: + return NormalBinaryOperator.LogicalAnd; + case ts.SyntaxKind.BarBarToken: + return NormalBinaryOperator.LogicalOr; + case ts.SyntaxKind.LessThanToken: + return RelationalBinaryOperator.LessThan; + case ts.SyntaxKind.LessThanEqualsToken: + return RelationalBinaryOperator.LessThanOrEqual; + case ts.SyntaxKind.GreaterThanToken: + return RelationalBinaryOperator.GreaterThan; + case ts.SyntaxKind.GreaterThanEqualsToken: + return RelationalBinaryOperator.GreaterThanOrEqual; + case ts.SyntaxKind.EqualsEqualsToken: + return RelationalBinaryOperator.Equality; + case ts.SyntaxKind.ExclamationEqualsToken: + return RelationalBinaryOperator.InEquality; + case ts.SyntaxKind.EqualsEqualsEqualsToken: + return RelationalBinaryOperator.StrictEquality; + case ts.SyntaxKind.ExclamationEqualsEqualsToken: + return RelationalBinaryOperator.StrictInequality; + default: + ; + } + return null; + } + + public generateAssignStmtForValue(value: Value, valueOriginalPositions: FullPosition[]): ValueAndStmts { + const leftOp = this.arkValueTransformer.generateTempLocal(value.getType()); + const leftOpPosition = valueOriginalPositions[0]; + const assignStmt = new ArkAssignStmt(leftOp, value); + assignStmt.setOperandOriginalPositions([leftOpPosition, ...valueOriginalPositions]); + return { value: leftOp, valueOriginalPositions: [leftOpPosition], stmts: [assignStmt] }; + } + + public generateIfStmtForValues(leftValue: Value, leftOpOriginalPositions: FullPosition[], rightValue: Value, + rightOpOriginalPositions: FullPosition[]): Stmt[] { + const stmts: Stmt[] = []; + if (IRUtils.moreThanOneAddress(leftValue)) { + const { + value: tempLeftValue, + valueOriginalPositions: tempLeftPositions, + stmts: leftStmts, + } = this.generateAssignStmtForValue(leftValue, leftOpOriginalPositions); + leftStmts.forEach(stmt => stmts.push(stmt)); + leftValue = tempLeftValue; + leftOpOriginalPositions = tempLeftPositions; + } + if (IRUtils.moreThanOneAddress(rightValue)) { + const { + value: tempRightValue, + valueOriginalPositions: tempRightPositions, + stmts: rightStmts, + } = this.generateAssignStmtForValue(rightValue, rightOpOriginalPositions); + rightStmts.forEach(stmt => stmts.push(stmt)); + rightValue = tempRightValue; + rightOpOriginalPositions = tempRightPositions; + } + + const conditionExpr = new ArkConditionExpr(leftValue, rightValue, RelationalBinaryOperator.Equality); + const conditionPositions = [...leftOpOriginalPositions, ...rightOpOriginalPositions]; + const ifStmt = new ArkIfStmt(conditionExpr); + ifStmt.setOperandOriginalPositions([...conditionPositions]); + stmts.push(ifStmt); + return stmts; + } + + public setBuilderMethodContextFlag(builderMethodContextFlag: boolean): void { + this.builderMethodContextFlag = builderMethodContextFlag; + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/common/ArkValueTransformer.ts b/ets2panda/linter/arkanalyzer/src/core/common/ArkValueTransformer.ts new file mode 100644 index 0000000000..1e22c774d4 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/common/ArkValueTransformer.ts @@ -0,0 +1,1789 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as ts from 'ohos-typescript'; +import { Local } from '../base/Local'; +import { FullPosition } from '../base/Position'; +import { ArkAliasTypeDefineStmt, ArkAssignStmt, ArkIfStmt, ArkInvokeStmt, Stmt } from '../base/Stmt'; +import { + AbstractBinopExpr, + ArkAwaitExpr, + ArkCastExpr, + ArkConditionExpr, + ArkDeleteExpr, + ArkInstanceInvokeExpr, + ArkInstanceOfExpr, + ArkNewArrayExpr, + ArkNewExpr, + ArkNormalBinopExpr, + ArkPtrInvokeExpr, + ArkStaticInvokeExpr, + ArkTypeOfExpr, + ArkUnopExpr, + ArkYieldExpr, + BinaryOperator, + NormalBinaryOperator, + RelationalBinaryOperator, +} from '../base/Expr'; +import { ArkClass } from '../model/ArkClass'; +import { buildNormalArkClassFromArkFile, buildNormalArkClassFromArkNamespace } from '../model/builder/ArkClassBuilder'; +import { + AliasType, + AnyType, + ArrayType, + BigIntType, + BooleanType, + ClassType, + FunctionType, + IntersectionType, + LiteralType, + NeverType, + NullType, + NumberType, + StringType, + TupleType, + Type, + UnclearReferenceType, + UndefinedType, + UnionType, + UnknownType, + VoidType, +} from '../base/Type'; +import { ArkSignatureBuilder } from '../model/builder/ArkSignatureBuilder'; +import { CONSTRUCTOR_NAME, THIS_NAME } from './TSConst'; +import { ClassSignature, FieldSignature, MethodSignature } from '../model/ArkSignature'; +import { Value } from '../base/Value'; +import { + COMPONENT_CREATE_FUNCTION, + COMPONENT_CUSTOMVIEW, + COMPONENT_FOR_EACH, + COMPONENT_LAZY_FOR_EACH, + COMPONENT_POP_FUNCTION, + isEtsSystemComponent, +} from './EtsConst'; +import { ValueUtil } from './ValueUtil'; +import { IRUtils } from './IRUtils'; +import { AbstractFieldRef, ArkArrayRef, ArkInstanceFieldRef, ArkStaticFieldRef, GlobalRef } from '../base/Ref'; +import { ModelUtils } from './ModelUtils'; +import { ArkMethod } from '../model/ArkMethod'; +import { buildArkMethodFromArkClass } from '../model/builder/ArkMethodBuilder'; +import { Builtin } from './Builtin'; +import { Constant } from '../base/Constant'; +import { TEMP_LOCAL_PREFIX } from './Const'; +import { ArkIRTransformer, DummyStmt, ValueAndStmts } from './ArkIRTransformer'; +import Logger, { LOG_MODULE_TYPE } from '../../utils/logger'; +import { TypeInference } from './TypeInference'; +import { KeyofTypeExpr, TypeQueryExpr } from '../base/TypeExpr'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'ArkValueTransformer'); + +export class ArkValueTransformer { + private conditionalOperatorNo: number = 0; + private tempLocalNo: number = 0; + private sourceFile: ts.SourceFile; + private locals: Map = new Map(); + private globals?: Map; + private thisLocal: Local; + private declaringMethod: ArkMethod; + private arkIRTransformer: ArkIRTransformer; + private aliasTypeMap: Map = new Map(); + private builderMethodContextFlag = false; + + constructor(arkIRTransformer: ArkIRTransformer, sourceFile: ts.SourceFile, declaringMethod: ArkMethod) { + this.arkIRTransformer = arkIRTransformer; + this.sourceFile = sourceFile; + this.thisLocal = new Local(THIS_NAME, declaringMethod.getDeclaringArkClass().getSignature().getType()); + this.locals.set(this.thisLocal.getName(), this.thisLocal); + this.declaringMethod = declaringMethod; + } + + public getLocals(): Set { + return new Set(this.locals.values()); + } + + public getThisLocal(): Local { + return this.thisLocal; + } + + public getAliasTypeMap(): Map { + return this.aliasTypeMap; + } + + public addNewLocal(localName: string, localType: Type = UnknownType.getInstance()): Local { + let local = new Local(localName, localType); + this.locals.set(localName, local); + return local; + } + + public getGlobals(): Map | null { + return this.globals ?? null; + } + + private addNewGlobal(name: string, ref?: Value): GlobalRef { + let globalRef = new GlobalRef(name, ref); + this.globals = this.globals ?? new Map(); + this.globals.set(name, globalRef); + return globalRef; + } + + public tsNodeToValueAndStmts(node: ts.Node): ValueAndStmts { + if (ts.isBinaryExpression(node)) { + return this.binaryExpressionToValueAndStmts(node); + } else if (ts.isCallExpression(node)) { + return this.callExpressionToValueAndStmts(node); + } else if (ts.isVariableDeclarationList(node)) { + return this.variableDeclarationListToValueAndStmts(node); + } else if (ts.isIdentifier(node)) { + return this.identifierToValueAndStmts(node); + } else if (ts.isPropertyAccessExpression(node)) { + return this.propertyAccessExpressionToValue(node); + } else if (ts.isPrefixUnaryExpression(node)) { + return this.prefixUnaryExpressionToValueAndStmts(node); + } else if (ts.isPostfixUnaryExpression(node)) { + return this.postfixUnaryExpressionToValueAndStmts(node); + } else if (ts.isTemplateExpression(node)) { + return this.templateExpressionToValueAndStmts(node); + } else if (ts.isTaggedTemplateExpression(node)) { + return this.taggedTemplateExpressionToValueAndStmts(node); + } else if (ts.isAwaitExpression(node)) { + return this.awaitExpressionToValueAndStmts(node); + } else if (ts.isYieldExpression(node)) { + return this.yieldExpressionToValueAndStmts(node); + } else if (ts.isDeleteExpression(node)) { + return this.deleteExpressionToValueAndStmts(node); + } else if (ts.isVoidExpression(node)) { + return this.voidExpressionToValueAndStmts(node); + } else if (ts.isElementAccessExpression(node)) { + return this.elementAccessExpressionToValueAndStmts(node); + } else if (ts.isNewExpression(node)) { + return this.newExpressionToValueAndStmts(node); + } else if (ts.isParenthesizedExpression(node)) { + return this.parenthesizedExpressionToValueAndStmts(node); + } else if (ts.isAsExpression(node)) { + return this.asExpressionToValueAndStmts(node); + } else if (ts.isNonNullExpression(node)) { + return this.nonNullExpressionToValueAndStmts(node); + } else if (ts.isTypeAssertionExpression(node)) { + return this.typeAssertionToValueAndStmts(node); + } else if (ts.isTypeOfExpression(node)) { + return this.typeOfExpressionToValueAndStmts(node); + } else if (ts.isArrayLiteralExpression(node)) { + return this.arrayLiteralExpressionToValueAndStmts(node); + } else if (this.isLiteralNode(node)) { + return this.literalNodeToValueAndStmts(node) as ValueAndStmts; + } else if (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) { + return this.callableNodeToValueAndStmts(node); + } else if (ts.isClassExpression(node)) { + return this.classExpressionToValueAndStmts(node); + } else if (ts.isEtsComponentExpression(node)) { + return this.etsComponentExpressionToValueAndStmts(node); + } else if (ts.isObjectLiteralExpression(node)) { + return this.objectLiteralExpresionToValueAndStmts(node); + } else if (node.kind === ts.SyntaxKind.ThisKeyword) { + return this.thisExpressionToValueAndStmts(node as ts.ThisExpression); + } else if (ts.isConditionalExpression(node)) { + return this.conditionalExpressionToValueAndStmts(node); + } + + return { + value: new Local(node.getText(this.sourceFile)), + valueOriginalPositions: [FullPosition.buildFromNode(node, this.sourceFile)], + stmts: [], + }; + } + + private tsNodeToSingleAddressValueAndStmts(node: ts.Node): ValueAndStmts { + const allStmts: Stmt[] = []; + let { value, valueOriginalPositions, stmts } = this.tsNodeToValueAndStmts(node); + stmts.forEach(stmt => allStmts.push(stmt)); + if (IRUtils.moreThanOneAddress(value)) { + ({ value, valueOriginalPositions, stmts } = + this.arkIRTransformer.generateAssignStmtForValue(value, valueOriginalPositions)); + stmts.forEach(stmt => allStmts.push(stmt)); + } + return { value, valueOriginalPositions, stmts: allStmts }; + } + + private thisExpressionToValueAndStmts(thisExpression: ts.ThisExpression): ValueAndStmts { + return { + value: this.getThisLocal(), + valueOriginalPositions: [FullPosition.buildFromNode(thisExpression, this.sourceFile)], + stmts: [], + }; + } + + private conditionalExpressionToValueAndStmts(conditionalExpression: ts.ConditionalExpression): ValueAndStmts { + const stmts: Stmt[] = []; + const currConditionalOperatorIndex = this.conditionalOperatorNo++; + const { + value: conditionValue, + valueOriginalPositions: conditionPositions, + stmts: conditionStmts, + } = this.conditionToValueAndStmts(conditionalExpression.condition); + conditionStmts.forEach(stmt => stmts.push(stmt)); + const ifStmt = new ArkIfStmt(conditionValue as ArkConditionExpr); + ifStmt.setOperandOriginalPositions(conditionPositions); + stmts.push(ifStmt); + + stmts.push( + new DummyStmt(ArkIRTransformer.DUMMY_CONDITIONAL_OPERATOR_IF_TRUE_STMT + currConditionalOperatorIndex)); + const { + value: whenTrueValue, + valueOriginalPositions: whenTruePositions, + stmts: whenTrueStmts, + } = this.tsNodeToValueAndStmts(conditionalExpression.whenTrue); + whenTrueStmts.forEach(stmt => stmts.push(stmt)); + const resultLocal = this.generateTempLocal(); + const assignStmtWhenTrue = new ArkAssignStmt(resultLocal, whenTrueValue); + const resultLocalPosition: FullPosition[] = [whenTruePositions[0]]; + assignStmtWhenTrue.setOperandOriginalPositions([...resultLocalPosition, ...whenTruePositions]); + stmts.push(assignStmtWhenTrue); + + stmts.push( + new DummyStmt(ArkIRTransformer.DUMMY_CONDITIONAL_OPERATOR_IF_FALSE_STMT + currConditionalOperatorIndex)); + const { + value: whenFalseValue, + valueOriginalPositions: whenFalsePositions, + stmts: whenFalseStmts, + } = this.tsNodeToValueAndStmts(conditionalExpression.whenFalse); + whenFalseStmts.forEach(stmt => stmts.push(stmt)); + const assignStmt = new ArkAssignStmt(resultLocal, whenFalseValue); + assignStmt.setOperandOriginalPositions([...resultLocalPosition, ...whenFalsePositions]); + stmts.push(assignStmt); + stmts.push( + new DummyStmt(ArkIRTransformer.DUMMY_CONDITIONAL_OPERATOR_END_STMT + currConditionalOperatorIndex)); + return { value: resultLocal, valueOriginalPositions: resultLocalPosition, stmts: stmts }; + } + + private objectLiteralExpresionToValueAndStmts(objectLiteralExpression: ts.ObjectLiteralExpression): ValueAndStmts { + const declaringArkClass = this.declaringMethod.getDeclaringArkClass(); + const declaringArkNamespace = declaringArkClass.getDeclaringArkNamespace(); + const anonymousClass = new ArkClass(); + if (declaringArkNamespace) { + buildNormalArkClassFromArkNamespace(objectLiteralExpression, declaringArkNamespace, anonymousClass, + this.sourceFile, this.declaringMethod); + declaringArkNamespace.addArkClass(anonymousClass); + } else { + const declaringArkFile = declaringArkClass.getDeclaringArkFile(); + buildNormalArkClassFromArkFile(objectLiteralExpression, declaringArkFile, anonymousClass, this.sourceFile, + this.declaringMethod); + declaringArkFile.addArkClass(anonymousClass); + } + + const objectLiteralExpressionPosition = FullPosition.buildFromNode(objectLiteralExpression, this.sourceFile); + const stmts: Stmt[] = []; + const anonymousClassSignature = anonymousClass.getSignature(); + const anonymousClassType = new ClassType(anonymousClassSignature); + const newExpr = new ArkNewExpr(anonymousClassType); + const { + value: newExprLocal, + valueOriginalPositions: newExprLocalPositions, + stmts: newExprStmts, + } = this.arkIRTransformer.generateAssignStmtForValue(newExpr, [objectLiteralExpressionPosition]); + newExprStmts.forEach(stmt => stmts.push(stmt)); + + const constructorMethodSubSignature = ArkSignatureBuilder.buildMethodSubSignatureFromMethodName( + CONSTRUCTOR_NAME); + const constructorMethodSignature = new MethodSignature(anonymousClassSignature, constructorMethodSubSignature); + const constructorInvokeExpr = new ArkInstanceInvokeExpr(newExprLocal as Local, constructorMethodSignature, []); + const constructorInvokeExprPositions = [objectLiteralExpressionPosition, ...newExprLocalPositions]; + const constructorInvokeStmt = new ArkInvokeStmt(constructorInvokeExpr); + constructorInvokeStmt.setOperandOriginalPositions(constructorInvokeExprPositions); + stmts.push(constructorInvokeStmt); + return { value: newExprLocal, valueOriginalPositions: newExprLocalPositions, stmts: stmts }; + } + + private generateSystemComponentStmt(componentName: string, args: Value[], argPositionsAllFlat: FullPosition[], + componentExpression: ts.EtsComponentExpression | ts.CallExpression, + currStmts: Stmt[]): ValueAndStmts { + const stmts: Stmt[] = [...currStmts]; + const componentExpressionPosition = FullPosition.buildFromNode(componentExpression, this.sourceFile); + const { + value: componentValue, valueOriginalPositions: componentPositions, stmts: componentStmts, + } = this.generateComponentCreationStmts(componentName, args, componentExpressionPosition, argPositionsAllFlat); + componentStmts.forEach(stmt => stmts.push(stmt)); + + if (ts.isEtsComponentExpression(componentExpression) && componentExpression.body) { + for (const statement of componentExpression.body.statements) { + this.arkIRTransformer.tsNodeToStmts(statement).forEach(stmt => stmts.push(stmt)); + } + } + stmts.push(this.generateComponentPopStmts(componentName, componentExpressionPosition)); + return { value: componentValue, valueOriginalPositions: componentPositions, stmts: stmts }; + } + + private generateCustomViewStmt(componentName: string, args: Value[], argPositionsAllFlat: FullPosition[], + componentExpression: ts.EtsComponentExpression | ts.CallExpression, + currStmts: Stmt[]): ValueAndStmts { + const stmts: Stmt[] = [...currStmts]; + const componentExpressionPosition = FullPosition.buildFromNode(componentExpression, this.sourceFile); + const classSignature = ArkSignatureBuilder.buildClassSignatureFromClassName(componentName); + const classType = new ClassType(classSignature); + const newExpr = new ArkNewExpr(classType); + const { + value: newExprLocal, + valueOriginalPositions: newExprPositions, + stmts: newExprStmts, + } = this.arkIRTransformer.generateAssignStmtForValue(newExpr, [componentExpressionPosition]); + newExprStmts.forEach(stmt => stmts.push(stmt)); + const constructorMethodSubSignature = ArkSignatureBuilder.buildMethodSubSignatureFromMethodName( + CONSTRUCTOR_NAME); + const constructorMethodSignature = new MethodSignature(classSignature, constructorMethodSubSignature); + const instanceInvokeExpr = new ArkInstanceInvokeExpr(newExprLocal as Local, constructorMethodSignature, args); + const instanceInvokeExprPositions = [componentExpressionPosition, ...newExprPositions, ...argPositionsAllFlat]; + const instanceInvokeStmt = new ArkInvokeStmt(instanceInvokeExpr); + instanceInvokeStmt.setOperandOriginalPositions(instanceInvokeExprPositions); + stmts.push(instanceInvokeStmt); + const createViewArgs = [newExprLocal]; + const createViewArgPositionsAll = [newExprPositions]; + if (ts.isEtsComponentExpression(componentExpression) && componentExpression.body) { + const anonymous = ts.factory.createArrowFunction([], [], [], undefined, undefined, + componentExpression.body); + // @ts-expect-error: add pos info for the created ArrowFunction + anonymous.pos = componentExpression.body.pos; + // @ts-expect-error: add end info for the created ArrowFunction + anonymous.end = componentExpression.body.end; + const { + value: builderMethod, + valueOriginalPositions: builderMethodPositions, + } = this.callableNodeToValueAndStmts(anonymous); + createViewArgs.push(builderMethod); + createViewArgPositionsAll.push(builderMethodPositions); + } + const { + value: componentValue, valueOriginalPositions: componentPositions, stmts: componentStmts, + } = this.generateComponentCreationStmts(COMPONENT_CUSTOMVIEW, createViewArgs, componentExpressionPosition, + createViewArgPositionsAll.flat()); + componentStmts.forEach(stmt => stmts.push(stmt)); + stmts.push(this.generateComponentPopStmts(COMPONENT_CUSTOMVIEW, componentExpressionPosition)); + return { value: componentValue, valueOriginalPositions: componentPositions, stmts: stmts }; + } + + private generateComponentCreationStmts(componentName: string, createArgs: Value[], + componentExpressionPosition: FullPosition, + createArgsPositionsAllFlat: FullPosition[]): ValueAndStmts { + const createMethodSignature = ArkSignatureBuilder.buildMethodSignatureFromClassNameAndMethodName( + componentName, COMPONENT_CREATE_FUNCTION); + const createInvokeExpr = new ArkStaticInvokeExpr(createMethodSignature, createArgs); + const createInvokeExprPositions = [componentExpressionPosition, ...createArgsPositionsAllFlat]; + const { + value: componentValue, valueOriginalPositions: componentPositions, stmts: componentStmts, + } = this.arkIRTransformer.generateAssignStmtForValue(createInvokeExpr, createInvokeExprPositions); + return { value: componentValue, valueOriginalPositions: componentPositions, stmts: componentStmts }; + } + + private generateComponentPopStmts(componentName: string, componentExpressionPosition: FullPosition): Stmt { + const popMethodSignature = ArkSignatureBuilder.buildMethodSignatureFromClassNameAndMethodName( + componentName, COMPONENT_POP_FUNCTION); + const popInvokeExpr = new ArkStaticInvokeExpr(popMethodSignature, []); + const popInvokeExprPositions = [componentExpressionPosition]; + const popInvokeStmt = new ArkInvokeStmt(popInvokeExpr); + popInvokeStmt.setOperandOriginalPositions(popInvokeExprPositions); + return popInvokeStmt; + } + + private etsComponentExpressionToValueAndStmts(etsComponentExpression: ts.EtsComponentExpression): ValueAndStmts { + const stmts: Stmt[] = []; + const componentName = (etsComponentExpression.expression as ts.Identifier).text; + const { args: args, argPositions: argPositions } = this.parseArguments(stmts, + etsComponentExpression.arguments); + if (isEtsSystemComponent(componentName)) { + return this.generateSystemComponentStmt(componentName, args, argPositions, etsComponentExpression, + stmts); + } + return this.generateCustomViewStmt(componentName, args, argPositions, etsComponentExpression, stmts); + } + + private classExpressionToValueAndStmts(classExpression: ts.ClassExpression): ValueAndStmts { + const declaringArkClass = this.declaringMethod.getDeclaringArkClass(); + const declaringArkNamespace = declaringArkClass.getDeclaringArkNamespace(); + const newClass = new ArkClass(); + if (declaringArkNamespace) { + buildNormalArkClassFromArkNamespace(classExpression, declaringArkNamespace, newClass, this.sourceFile, + this.declaringMethod); + declaringArkNamespace.addArkClass(newClass); + } else { + const declaringArkFile = declaringArkClass.getDeclaringArkFile(); + buildNormalArkClassFromArkFile(classExpression, declaringArkFile, newClass, this.sourceFile, + this.declaringMethod); + declaringArkFile.addArkClass(newClass); + } + const classValue = this.addNewLocal(newClass.getName(), new ClassType(newClass.getSignature())); + return { + value: classValue, + valueOriginalPositions: [FullPosition.buildFromNode(classExpression, this.sourceFile)], + stmts: [], + }; + } + + private templateExpressionToValueAndStmts(templateExpression: ts.TemplateExpression): ValueAndStmts { + const { stmts, stringTextValues, placeholderValues, stringTextPositions, placeholderPositions } = + this.collectTemplateValues(templateExpression); + + const { placeholderStringLocals, placeholderStringLocalPositions, newStmts } = + this.processTemplatePlaceholders(placeholderValues, placeholderPositions, stmts); + + return this.combineTemplateParts(stringTextValues, stringTextPositions, placeholderStringLocals, placeholderStringLocalPositions, newStmts); + } + + private processTemplatePlaceholders(placeholderValues: Value[], placeholderPositions: FullPosition[], currStmts: Stmt[]): { + placeholderStringLocals: Local[], placeholderStringLocalPositions: FullPosition[], newStmts: Stmt[] + } { + const placeholderStringLocals: Local[] = []; + const placeholderStringLocalPositions: FullPosition[] = []; + const newStmts: Stmt[] = [...currStmts]; + + for (let i = 0; i < placeholderValues.length; i++) { + let placeholderValue = placeholderValues[i]; + let placeholderPosition: FullPosition[] = [placeholderPositions[i]]; + let placeholderStmts: Stmt[] = []; + + if (!(placeholderValue instanceof Local)) { + ({ value: placeholderValue, valueOriginalPositions: placeholderPosition, stmts: placeholderStmts } = + this.arkIRTransformer.generateAssignStmtForValue(placeholderValue, placeholderPosition)); + } + + placeholderStmts.forEach(stmt => newStmts.push(stmt)); + const toStringExpr = new ArkInstanceInvokeExpr(placeholderValue as Local, Builtin.TO_STRING_METHOD_SIGNATURE, []); + const toStringExprPosition: FullPosition[] = [placeholderPosition[0], placeholderPosition[0]]; + const { + value: placeholderStringLocal, valueOriginalPositions: placeholderStringPositions, stmts: toStringStmts, + } = this.arkIRTransformer.generateAssignStmtForValue(toStringExpr, toStringExprPosition); + placeholderStringLocals.push(placeholderStringLocal as Local); + placeholderStringLocalPositions.push(placeholderStringPositions[0]); + toStringStmts.forEach(stmt => newStmts.push(stmt)); + } + + return { placeholderStringLocals, placeholderStringLocalPositions, newStmts }; + } + + private combineTemplateParts(stringTextValues: Value[], stringTextPositions: FullPosition[], + placeholderStringLocals: Local[], placeholderStringLocalPositions: FullPosition[], + currStmts: Stmt[]): ValueAndStmts { + const templateParts: Value[] = []; + const templatePartPositions: FullPosition[] = []; + + for (let i = 0; i < placeholderStringLocals.length; i++) { + if (stringTextValues[i] !== ValueUtil.EMPTY_STRING_CONSTANT) { + templateParts.push(stringTextValues[i]); + templatePartPositions.push(stringTextPositions[i]); + } + templateParts.push(placeholderStringLocals[i]); + templatePartPositions.push(placeholderStringLocalPositions[i]); + } + + if (stringTextValues[stringTextValues.length - 1] !== ValueUtil.EMPTY_STRING_CONSTANT) { + templateParts.push(stringTextValues[stringTextValues.length - 1]); + templatePartPositions.push(stringTextPositions[stringTextPositions.length - 1]); + } + + let currTemplateResult: Value = templateParts[0]; + let currTemplateResultPosition: FullPosition = templatePartPositions[0]; + const finalStmts: Stmt[] = [...currStmts]; + + for (let i = 1; i < templateParts.length; i++) { + const nextTemplatePartPosition = templatePartPositions[i]; + const normalBinopExpr = new ArkNormalBinopExpr(currTemplateResult, templateParts[i], NormalBinaryOperator.Addition); + const normalBinopExprPositions = [FullPosition.merge(currTemplateResultPosition, nextTemplatePartPosition), + currTemplateResultPosition, nextTemplatePartPosition]; + const { + value: combinationValue, valueOriginalPositions: combinationValuePositions, stmts: combinationStmts, + } = this.arkIRTransformer.generateAssignStmtForValue(normalBinopExpr, normalBinopExprPositions); + combinationStmts.forEach(stmt => finalStmts.push(stmt)); + currTemplateResult = combinationValue; + currTemplateResultPosition = combinationValuePositions[0]; + } + + return { value: currTemplateResult, valueOriginalPositions: [currTemplateResultPosition], stmts: finalStmts }; + } + + private taggedTemplateExpressionToValueAndStmts(taggedTemplateExpression: ts.TaggedTemplateExpression): ValueAndStmts { + const { + stmts, stringTextValues, placeholderValues, stringTextPositions, placeholderPositions, + } = this.collectTemplateValues(taggedTemplateExpression.template); + const stringTextBaseType = StringType.getInstance(); + const stringTextArrayLen = stringTextValues.length; + const stringTextArrayLenValue = ValueUtil.getOrCreateNumberConst(stringTextArrayLen); + const stringTextArrayLenPosition = FullPosition.DEFAULT; + const { + value: templateObjectLocal, valueOriginalPositions: templateObjectLocalPositions, + stmts: templateObjectStmts, + } = this.generateArrayExprAndStmts(stringTextBaseType, stringTextArrayLenValue, stringTextArrayLenPosition, + stringTextArrayLen, stringTextValues, stringTextPositions, stmts, FullPosition.DEFAULT, true); + + const placeholderBaseType = AnyType.getInstance(); + const placeholdersArrayLen = placeholderValues.length; + const placeholdersArrayLenValue = ValueUtil.getOrCreateNumberConst(placeholdersArrayLen); + const placeholdersArrayLenPosition = FullPosition.DEFAULT; + const { + value: placeholdersLocal, valueOriginalPositions: placeholdersLocalPositions, + stmts: placeholdersStmts, + } = this.generateArrayExprAndStmts(placeholderBaseType, placeholdersArrayLenValue, placeholdersArrayLenPosition, + placeholdersArrayLen, placeholderValues, placeholderPositions, templateObjectStmts, FullPosition.DEFAULT, true); + + const taggedFuncArgus = { + realGenericTypes: undefined, args: [templateObjectLocal, placeholdersLocal], + argPositions: [templateObjectLocalPositions[0], placeholdersLocalPositions[0]], + }; + return this.generateInvokeValueAndStmts(taggedTemplateExpression.tag, taggedFuncArgus, placeholdersStmts, taggedTemplateExpression); + } + + private collectTemplateValues(templateLiteral: ts.TemplateLiteral): + { + stmts: Stmt[], stringTextValues: Value[], placeholderValues: Value[], stringTextPositions: FullPosition[], + placeholderPositions: FullPosition[] + } { + const stmts: Stmt[] = []; + if (ts.isNoSubstitutionTemplateLiteral(templateLiteral)) { + const templateLiteralString = templateLiteral.getText(this.sourceFile); + return { + stmts: [], stringTextValues: [ValueUtil.createStringConst(templateLiteralString)], + placeholderValues: [], + stringTextPositions: [FullPosition.buildFromNode(templateLiteral, this.sourceFile)], + placeholderPositions: [], + }; + } + const head = templateLiteral.head; + const stringTextValues: Value[] = [ValueUtil.createStringConst(head.rawText || '')]; + const placeholderValues: Value[] = []; + const stringTextPositions: FullPosition[] = [FullPosition.buildFromNode(head, this.sourceFile)]; + const placeholderPositions: FullPosition[] = []; + for (const templateSpan of templateLiteral.templateSpans) { + let { + value: exprValue, valueOriginalPositions: exprPositions, stmts: exprStmts, + } = this.tsNodeToValueAndStmts(templateSpan.expression); + exprStmts.forEach(stmt => stmts.push(stmt)); + if (IRUtils.moreThanOneAddress(exprValue)) { + ({ value: exprValue, valueOriginalPositions: exprPositions, stmts: exprStmts } = + this.arkIRTransformer.generateAssignStmtForValue(exprValue, exprPositions)); + exprStmts.forEach(stmt => stmts.push(stmt)); + } + placeholderValues.push(exprValue); + placeholderPositions.push(exprPositions[0]); + stringTextPositions.push(FullPosition.buildFromNode(templateSpan.literal, this.sourceFile)); + stringTextValues.push(ValueUtil.createStringConst(templateSpan.literal.rawText || '')); + } + return { stmts, stringTextValues, placeholderValues, stringTextPositions, placeholderPositions }; + } + + private identifierToValueAndStmts(identifier: ts.Identifier, variableDefFlag: boolean = false): ValueAndStmts { + let identifierValue: Value; + let identifierPositions = [FullPosition.buildFromNode(identifier, this.sourceFile)]; + if (identifier.text === UndefinedType.getInstance().getName()) { + identifierValue = ValueUtil.getUndefinedConst(); + } else { + if (variableDefFlag) { + identifierValue = this.addNewLocal(identifier.text); + } else { + identifierValue = this.getOrCreateLocal(identifier.text); + } + } + return { value: identifierValue, valueOriginalPositions: identifierPositions, stmts: [] }; + } + + private propertyAccessExpressionToValue(propertyAccessExpression: ts.PropertyAccessExpression): ValueAndStmts { + const stmts: Stmt[] = []; + let { + value: baseValue, + valueOriginalPositions: basePositions, + stmts: baseStmts, + } = this.tsNodeToValueAndStmts(propertyAccessExpression.expression); + baseStmts.forEach(stmt => stmts.push(stmt)); + if (IRUtils.moreThanOneAddress(baseValue)) { + ({ value: baseValue, valueOriginalPositions: basePositions, stmts: baseStmts } = + this.arkIRTransformer.generateAssignStmtForValue(baseValue, basePositions)); + baseStmts.forEach(stmt => stmts.push(stmt)); + } + if (!(baseValue instanceof Local)) { + ({ value: baseValue, valueOriginalPositions: basePositions, stmts: baseStmts } = + this.arkIRTransformer.generateAssignStmtForValue(baseValue, basePositions)); + baseStmts.forEach(stmt => stmts.push(stmt)); + } + + const fieldRefPositions = [FullPosition.buildFromNode(propertyAccessExpression, this.sourceFile), ...basePositions]; + + // this if for the case: const obj: Object = Object.create(Object.prototype); + if (baseValue instanceof Local && baseValue.getName() === Builtin.OBJECT) { + this.locals.delete(baseValue.getName()); + const fieldSignature = new FieldSignature(propertyAccessExpression.name.getText(this.sourceFile), + Builtin.OBJECT_CLASS_SIGNATURE, UnknownType.getInstance(), true); + const fieldRef = new ArkStaticFieldRef(fieldSignature); + return { value: fieldRef, valueOriginalPositions: fieldRefPositions, stmts: stmts }; + } + + let fieldSignature: FieldSignature; + if (baseValue instanceof Local && baseValue.getType() instanceof ClassType) { + fieldSignature = new FieldSignature(propertyAccessExpression.name.getText(this.sourceFile), + (baseValue.getType() as ClassType).getClassSignature(), UnknownType.getInstance()); + } else { + fieldSignature = ArkSignatureBuilder.buildFieldSignatureFromFieldName(propertyAccessExpression.name.getText(this.sourceFile)); + } + const fieldRef = new ArkInstanceFieldRef(baseValue as Local, fieldSignature); + + return { value: fieldRef, valueOriginalPositions: fieldRefPositions, stmts: stmts }; + } + + private elementAccessExpressionToValueAndStmts(elementAccessExpression: ts.ElementAccessExpression): ValueAndStmts { + const stmts: Stmt[] = []; + let { value: baseValue, valueOriginalPositions: basePositions, stmts: baseStmts } = this.tsNodeToValueAndStmts( + elementAccessExpression.expression); + baseStmts.forEach(stmt => stmts.push(stmt)); + if (!(baseValue instanceof Local)) { + ({ value: baseValue, valueOriginalPositions: basePositions, stmts: baseStmts } = + this.arkIRTransformer.generateAssignStmtForValue(baseValue, basePositions)); + baseStmts.forEach(stmt => stmts.push(stmt)); + } + let { + value: argumentValue, + valueOriginalPositions: arguPositions, + stmts: argumentStmts, + } = this.tsNodeToValueAndStmts(elementAccessExpression.argumentExpression); + argumentStmts.forEach(stmt => stmts.push(stmt)); + if (IRUtils.moreThanOneAddress(argumentValue)) { + ({ value: argumentValue, valueOriginalPositions: arguPositions, stmts: argumentStmts } = + this.arkIRTransformer.generateAssignStmtForValue(argumentValue, arguPositions)); + argumentStmts.forEach(stmt => stmts.push(stmt)); + } + + let elementAccessExpr: Value; + if (baseValue.getType() instanceof ArrayType) { + elementAccessExpr = new ArkArrayRef(baseValue as Local, argumentValue); + } else { + // TODO: deal with ArkStaticFieldRef + const fieldSignature = ArkSignatureBuilder.buildFieldSignatureFromFieldName(argumentValue.toString()); + elementAccessExpr = new ArkInstanceFieldRef(baseValue as Local, fieldSignature); + } + // reserve positions for field name + const exprPositions = [FullPosition.buildFromNode(elementAccessExpression, this.sourceFile), ...basePositions, + ...arguPositions]; + return { value: elementAccessExpr, valueOriginalPositions: exprPositions, stmts: stmts }; + } + + private callExpressionToValueAndStmts(callExpression: ts.CallExpression): ValueAndStmts { + const stmts: Stmt[] = []; + const argus = this.parseArgumentsOfCallExpression(stmts, callExpression); + return this.generateInvokeValueAndStmts(callExpression.expression, argus, stmts, callExpression); + } + + private generateInvokeValueAndStmts(functionNameNode: ts.LeftHandSideExpression, argus: { + realGenericTypes: Type[] | undefined, + args: Value[], + argPositions: FullPosition[] + }, currStmts: Stmt[], callExpression: ts.CallExpression | ts.TaggedTemplateExpression): ValueAndStmts { + const stmts: Stmt[] = [...currStmts]; + let { + value: callerValue, + valueOriginalPositions: callerPositions, + stmts: callerStmts, + } = this.tsNodeToValueAndStmts(functionNameNode); + callerStmts.forEach(stmt => stmts.push(stmt)); + + let invokeValue: Value; + let invokeValuePositions: FullPosition[] = [FullPosition.buildFromNode(callExpression, this.sourceFile)]; + const { args, argPositions, realGenericTypes } = argus; + if (callerValue instanceof AbstractFieldRef) { + let methodSignature: MethodSignature; + const declareSignature = callerValue.getFieldSignature().getDeclaringSignature(); + if (declareSignature instanceof ClassSignature) { + methodSignature = new MethodSignature(declareSignature, ArkSignatureBuilder.buildMethodSubSignatureFromMethodName(callerValue.getFieldName())); + } else { + methodSignature = ArkSignatureBuilder.buildMethodSignatureFromMethodName(callerValue.getFieldName()); + } + if (callerValue instanceof ArkInstanceFieldRef) { + invokeValue = new ArkInstanceInvokeExpr(callerValue.getBase(), methodSignature, args, realGenericTypes); + invokeValuePositions.push(...callerPositions.slice(1)); + } else { + invokeValue = new ArkStaticInvokeExpr(methodSignature, args, realGenericTypes); + } + } else if (callerValue instanceof Local) { + const callerName = callerValue.getName(); + let classSignature = ArkSignatureBuilder.buildClassSignatureFromClassName(callerName); + let cls = ModelUtils.getClass(this.declaringMethod, classSignature); + if (cls?.hasComponentDecorator() && ts.isCallExpression(callExpression)) { + return this.generateCustomViewStmt(callerName, args, argPositions, callExpression, stmts); + } else if ((callerName === COMPONENT_FOR_EACH || callerName === COMPONENT_LAZY_FOR_EACH) && ts.isCallExpression(callExpression)) { + // foreach/lazyforeach will be parsed as ts.callExpression + return this.generateSystemComponentStmt(callerName, args, argPositions, callExpression, stmts); + } + const methodSignature = ArkSignatureBuilder.buildMethodSignatureFromMethodName(callerName); + if (callerValue.getType() instanceof FunctionType) { + invokeValue = new ArkPtrInvokeExpr(methodSignature, callerValue, args, realGenericTypes); + } else { + invokeValue = new ArkStaticInvokeExpr(methodSignature, args, realGenericTypes); + } + } else { + ({ value: callerValue, valueOriginalPositions: callerPositions, stmts: callerStmts } = + this.arkIRTransformer.generateAssignStmtForValue(callerValue, callerPositions)); + callerStmts.forEach(stmt => stmts.push(stmt)); + const methodSignature = ArkSignatureBuilder.buildMethodSignatureFromMethodName((callerValue as Local).getName()); + invokeValue = new ArkStaticInvokeExpr(methodSignature, args, realGenericTypes); + } + invokeValuePositions.push(...argPositions); + return { value: invokeValue, valueOriginalPositions: invokeValuePositions, stmts: stmts }; + } + + private parseArgumentsOfCallExpression(currStmts: Stmt[], callExpression: ts.CallExpression): { + realGenericTypes: Type[] | undefined, + args: Value[], + argPositions: FullPosition[] + } { + let realGenericTypes: Type[] | undefined; + if (callExpression.typeArguments) { + realGenericTypes = []; + callExpression.typeArguments.forEach(typeArgument => { + realGenericTypes!.push(this.resolveTypeNode(typeArgument)); + }); + } + + let builderMethodIndexes: Set | undefined; + if (ts.isIdentifier(callExpression.expression)) { + const callerName = callExpression.expression.text; + if (callerName === COMPONENT_FOR_EACH || callerName === COMPONENT_LAZY_FOR_EACH) { + builderMethodIndexes = new Set([1]); + } + } + const { args: args, argPositions: argPositions } = this.parseArguments(currStmts, + callExpression.arguments, builderMethodIndexes); + return { realGenericTypes: realGenericTypes, args: args, argPositions: argPositions }; + } + + private parseArguments(currStmts: Stmt[], argumentNodes?: ts.NodeArray, + builderMethodIndexes?: Set): { + args: Value[], + argPositions: FullPosition[] + } { + const args: Value[] = []; + const argPositions: FullPosition[] = []; + if (argumentNodes) { + for (let i = 0; i < argumentNodes.length; i++) { + const argument = argumentNodes[i]; + const prevBuilderMethodContextFlag = this.builderMethodContextFlag; + if (builderMethodIndexes?.has(i)) { + this.builderMethodContextFlag = true; + this.arkIRTransformer.setBuilderMethodContextFlag(true); + } + let { + value: argValue, + valueOriginalPositions: argPositionsSingle, + stmts: argStmts, + } = this.tsNodeToValueAndStmts(argument); + this.builderMethodContextFlag = prevBuilderMethodContextFlag; + this.arkIRTransformer.setBuilderMethodContextFlag(prevBuilderMethodContextFlag); + argStmts.forEach(s => currStmts.push(s)); + if (IRUtils.moreThanOneAddress(argValue)) { + ({ value: argValue, valueOriginalPositions: argPositionsSingle, stmts: argStmts } = + this.arkIRTransformer.generateAssignStmtForValue(argValue, argPositionsSingle)); + argStmts.forEach(s => currStmts.push(s)); + } + args.push(argValue); + argPositions.push(argPositionsSingle[0]); + } + } + return { args: args, argPositions: argPositions }; + } + + private callableNodeToValueAndStmts(callableNode: ts.ArrowFunction | ts.FunctionExpression): ValueAndStmts { + const declaringClass = this.declaringMethod.getDeclaringArkClass(); + const arrowArkMethod = new ArkMethod(); + if (this.builderMethodContextFlag) { + ModelUtils.implicitArkUIBuilderMethods.add(arrowArkMethod); + } + buildArkMethodFromArkClass(callableNode, declaringClass, arrowArkMethod, this.sourceFile, this.declaringMethod); + + const callableType = new FunctionType(arrowArkMethod.getSignature()); + const callableValue = this.addNewLocal(arrowArkMethod.getName(), callableType); + return { + value: callableValue, + valueOriginalPositions: [FullPosition.buildFromNode(callableNode, this.sourceFile)], + stmts: [], + }; + } + + private newExpressionToValueAndStmts(newExpression: ts.NewExpression): ValueAndStmts { + let className = ''; + if (ts.isClassExpression(newExpression.expression) && newExpression.expression.name) { + className = newExpression.expression.name.text; + } else { + className = newExpression.expression.getText(this.sourceFile); + } + if (className === Builtin.ARRAY) { + return this.newArrayExpressionToValueAndStmts(newExpression); + } + + const stmts: Stmt[] = []; + let realGenericTypes: Type[] | undefined; + if (newExpression.typeArguments) { + realGenericTypes = []; + newExpression.typeArguments.forEach(typeArgument => { + realGenericTypes!.push(this.resolveTypeNode(typeArgument)); + }); + } + + let classSignature = ArkSignatureBuilder.buildClassSignatureFromClassName(className); + let classType = new ClassType(classSignature, realGenericTypes); + if (className === Builtin.OBJECT) { + classSignature = Builtin.OBJECT_CLASS_SIGNATURE; + classType = Builtin.OBJECT_CLASS_TYPE; + } + + const newExpr = new ArkNewExpr(classType); + const { + value: newLocal, + valueOriginalPositions: newLocalPositions, + stmts: newExprStmts, + } = this.arkIRTransformer.generateAssignStmtForValue(newExpr, + [FullPosition.buildFromNode(newExpression, this.sourceFile)]); + newExprStmts.forEach(stmt => stmts.push(stmt)); + + const constructorMethodSubSignature = ArkSignatureBuilder.buildMethodSubSignatureFromMethodName( + CONSTRUCTOR_NAME); + const constructorMethodSignature = new MethodSignature(classSignature, constructorMethodSubSignature); + + const { args: argValues, argPositions: argPositions } = this.parseArguments(stmts, + newExpression.arguments); + const instanceInvokeExpr = new ArkInstanceInvokeExpr(newLocal as Local, constructorMethodSignature, + argValues); + const instanceInvokeExprPositions = [newLocalPositions[0], ...newLocalPositions, ...argPositions]; + const invokeStmt = new ArkInvokeStmt(instanceInvokeExpr); + invokeStmt.setOperandOriginalPositions(instanceInvokeExprPositions); + stmts.push(invokeStmt); + return { value: newLocal, valueOriginalPositions: newLocalPositions, stmts: stmts }; + } + + private newArrayExpressionToValueAndStmts(newArrayExpression: ts.NewExpression): ValueAndStmts { + let baseType: Type = UnknownType.getInstance(); + if (newArrayExpression.typeArguments && newArrayExpression.typeArguments.length > 0) { + const argumentType = this.resolveTypeNode(newArrayExpression.typeArguments[0]); + if (!(argumentType instanceof AnyType || argumentType instanceof UnknownType)) { + baseType = argumentType; + } + } + const stmts: Stmt[] = []; + const { args: argumentValues, argPositions: argPositions } = this.parseArguments(stmts, + newArrayExpression.arguments); + let argumentsLength = newArrayExpression.arguments ? newArrayExpression.arguments.length : 0; + let arrayLengthValue: Value; + let arrayLength = -1; + let arrayLengthPosition = FullPosition.DEFAULT; + if ((argumentsLength === 1) && + ((argumentValues[0].getType() instanceof NumberType) || argumentValues[0].getType() instanceof + UnknownType)) { + arrayLengthValue = argumentValues[0]; + arrayLengthPosition = argPositions[0]; + } else { + arrayLengthValue = ValueUtil.getOrCreateNumberConst(argumentsLength); + arrayLength = argumentsLength; + } + if (baseType instanceof UnknownType) { + if ((argumentsLength > 1) && !(argumentValues[0].getType() instanceof UnknownType)) { + baseType = argumentValues[0].getType(); + } else { + baseType = AnyType.getInstance(); + } + } + const newArrayExprPosition = FullPosition.buildFromNode(newArrayExpression, this.sourceFile); + return this.generateArrayExprAndStmts(baseType, arrayLengthValue, arrayLengthPosition, arrayLength, + argumentValues, argPositions, stmts, newArrayExprPosition, false); + } + + private arrayLiteralExpressionToValueAndStmts(arrayLiteralExpression: ts.ArrayLiteralExpression): ValueAndStmts { + const stmts: Stmt[] = []; + const elementTypes: Set = new Set(); + const elementValues: Value[] = []; + const elementPositions: FullPosition[] = []; + const arrayLength = arrayLiteralExpression.elements.length; + for (const element of arrayLiteralExpression.elements) { + let { + value: elementValue, + valueOriginalPositions: elementPosition, + stmts: elementStmts, + } = this.tsNodeToValueAndStmts(element); + elementStmts.forEach(stmt => stmts.push(stmt)); + if (IRUtils.moreThanOneAddress(elementValue)) { + ({ value: elementValue, valueOriginalPositions: elementPosition, stmts: elementStmts } = + this.arkIRTransformer.generateAssignStmtForValue(elementValue, elementPosition)); + elementStmts.forEach(stmt => stmts.push(stmt)); + } + elementValues.push(elementValue); + elementTypes.add(elementValue.getType()); + elementPositions.push(elementPosition[0]); + } + + let baseType: Type = AnyType.getInstance(); + if (elementTypes.size === 1) { + baseType = elementTypes.keys().next().value as Type; + } else if (elementTypes.size > 1) { + baseType = new UnionType(Array.from(elementTypes)); + } + const newArrayExprPosition = FullPosition.buildFromNode(arrayLiteralExpression, this.sourceFile); + return this.generateArrayExprAndStmts(baseType, ValueUtil.getOrCreateNumberConst(arrayLength), FullPosition.DEFAULT, + arrayLength, elementValues, elementPositions, stmts, newArrayExprPosition, true); + } + + private generateArrayExprAndStmts(baseType: Type, arrayLengthValue: Value, arrayLengthPosition: FullPosition, + arrayLength: number, initializerValues: Value[], + initializerPositions: FullPosition[], + currStmts: Stmt[], + newArrayExprPosition: FullPosition, fromLiteral: boolean): ValueAndStmts { + const stmts: Stmt[] = [...currStmts]; + const newArrayExpr = new ArkNewArrayExpr(baseType, arrayLengthValue, fromLiteral); + const newArrayExprPositions = [newArrayExprPosition, arrayLengthPosition]; + const { + value: arrayLocal, + valueOriginalPositions: arrayLocalPositions, + stmts: arrayStmts, + } = this.arkIRTransformer.generateAssignStmtForValue(newArrayExpr, newArrayExprPositions); + arrayStmts.forEach(stmt => stmts.push(stmt)); + for (let i = 0; i < arrayLength; i++) { + const indexValue = ValueUtil.getOrCreateNumberConst(i); + const arrayRef = new ArkArrayRef(arrayLocal as Local, indexValue); + const arrayRefPositions = [arrayLocalPositions[0], ...arrayLocalPositions, FullPosition.DEFAULT]; + const assignStmt = new ArkAssignStmt(arrayRef, initializerValues[i]); + assignStmt.setOperandOriginalPositions([...arrayRefPositions, initializerPositions[i]]); + stmts.push(assignStmt); + } + return { value: arrayLocal, valueOriginalPositions: arrayLocalPositions, stmts: stmts }; + } + + + private prefixUnaryExpressionToValueAndStmts(prefixUnaryExpression: ts.PrefixUnaryExpression): ValueAndStmts { + const stmts: Stmt[] = []; + let { + value: operandValue, + valueOriginalPositions: operandPositions, + stmts: operandStmts, + } = this.tsNodeToValueAndStmts(prefixUnaryExpression.operand); + operandStmts.forEach(stmt => stmts.push(stmt)); + if (IRUtils.moreThanOneAddress(operandValue)) { + ({ value: operandValue, valueOriginalPositions: operandPositions, stmts: operandStmts } = + this.arkIRTransformer.generateAssignStmtForValue(operandValue, operandPositions)); + operandStmts.forEach(stmt => stmts.push(stmt)); + } + + const operatorToken = prefixUnaryExpression.operator; + let exprPositions = [FullPosition.buildFromNode(prefixUnaryExpression, this.sourceFile)]; + if (operatorToken === ts.SyntaxKind.PlusPlusToken || operatorToken === ts.SyntaxKind.MinusMinusToken) { + const binaryOperator = operatorToken === ts.SyntaxKind.PlusPlusToken ? NormalBinaryOperator.Addition : NormalBinaryOperator.Subtraction; + const binopExpr = new ArkNormalBinopExpr(operandValue, ValueUtil.getOrCreateNumberConst(1), binaryOperator); + exprPositions.push(...operandPositions, FullPosition.DEFAULT); + const assignStmt = new ArkAssignStmt(operandValue, binopExpr); + assignStmt.setOperandOriginalPositions([...operandPositions, ...exprPositions]); + stmts.push(assignStmt); + return { value: operandValue, valueOriginalPositions: operandPositions, stmts: stmts }; + } else if (operatorToken === ts.SyntaxKind.PlusToken) { + return { value: operandValue, valueOriginalPositions: operandPositions, stmts: stmts }; + } else { + let unopExpr: Value; + const operator = ArkIRTransformer.tokenToUnaryOperator(operatorToken); + if (operator) { + unopExpr = new ArkUnopExpr(operandValue, operator); + exprPositions.push(...operandPositions); + } else { + unopExpr = ValueUtil.getUndefinedConst(); + exprPositions = [FullPosition.DEFAULT]; + } + return { value: unopExpr, valueOriginalPositions: exprPositions, stmts: stmts }; + } + } + + private postfixUnaryExpressionToValueAndStmts(postfixUnaryExpression: ts.PostfixUnaryExpression): ValueAndStmts { + const stmts: Stmt[] = []; + let { + value: operandValue, + valueOriginalPositions: operandPositions, + stmts: exprStmts, + } = this.tsNodeToValueAndStmts(postfixUnaryExpression.operand); + exprStmts.forEach(stmt => stmts.push(stmt)); + if (IRUtils.moreThanOneAddress(operandValue)) { + ({ value: operandValue, valueOriginalPositions: operandPositions, stmts: exprStmts } = + this.arkIRTransformer.generateAssignStmtForValue(operandValue, operandPositions)); + exprStmts.forEach(stmt => stmts.push(stmt)); + } + + let value: Value; + let exprPositions = [FullPosition.buildFromNode(postfixUnaryExpression, this.sourceFile)]; + const operatorToken = postfixUnaryExpression.operator; + if (operatorToken === ts.SyntaxKind.PlusPlusToken || operatorToken === ts.SyntaxKind.MinusMinusToken) { + const binaryOperator = operatorToken === ts.SyntaxKind.PlusPlusToken ? NormalBinaryOperator.Addition : NormalBinaryOperator.Subtraction; + const binopExpr = new ArkNormalBinopExpr(operandValue, ValueUtil.getOrCreateNumberConst(1), binaryOperator); + exprPositions.push(...operandPositions, FullPosition.DEFAULT); + const assignStmt = new ArkAssignStmt(operandValue, binopExpr); + assignStmt.setOperandOriginalPositions([...operandPositions, ...exprPositions]); + stmts.push(assignStmt); + value = operandValue; + } else { + value = ValueUtil.getUndefinedConst(); + exprPositions = [FullPosition.DEFAULT]; + } + + return { value: value, valueOriginalPositions: exprPositions, stmts: stmts }; + } + + private awaitExpressionToValueAndStmts(awaitExpression: ts.AwaitExpression): ValueAndStmts { + const stmts: Stmt[] = []; + let { + value: promiseValue, + valueOriginalPositions: promisePositions, + stmts: promiseStmts, + } = this.tsNodeToValueAndStmts(awaitExpression.expression); + promiseStmts.forEach(stmt => stmts.push(stmt)); + if (IRUtils.moreThanOneAddress(promiseValue)) { + ({ value: promiseValue, valueOriginalPositions: promisePositions, stmts: promiseStmts } = + this.arkIRTransformer.generateAssignStmtForValue(promiseValue, promisePositions)); + promiseStmts.forEach(stmt => stmts.push(stmt)); + } + const awaitExpr = new ArkAwaitExpr(promiseValue); + const awaitExprPositions = [FullPosition.buildFromNode(awaitExpression, this.sourceFile), ...promisePositions]; + return { value: awaitExpr, valueOriginalPositions: awaitExprPositions, stmts: stmts }; + } + + private yieldExpressionToValueAndStmts(yieldExpression: ts.YieldExpression): ValueAndStmts { + let yieldValue: Value = ValueUtil.getUndefinedConst(); + let yieldPositions = [FullPosition.DEFAULT]; + let stmts: Stmt[] = []; + if (yieldExpression.expression) { + ({ value: yieldValue, valueOriginalPositions: yieldPositions, stmts: stmts } = + this.tsNodeToValueAndStmts(yieldExpression.expression)); + } + + const yieldExpr = new ArkYieldExpr(yieldValue); + const yieldExprPositions = [FullPosition.buildFromNode(yieldExpression, this.sourceFile), ...yieldPositions]; + return { value: yieldExpr, valueOriginalPositions: yieldExprPositions, stmts: stmts }; + } + + private deleteExpressionToValueAndStmts(deleteExpression: ts.DeleteExpression): ValueAndStmts { + const { value: exprValue, valueOriginalPositions: exprPositions, stmts: stmts } = this.tsNodeToValueAndStmts( + deleteExpression.expression); + const deleteExpr = new ArkDeleteExpr(exprValue as AbstractFieldRef); + const deleteExprPositions = [FullPosition.buildFromNode(deleteExpression, this.sourceFile), + ...exprPositions]; + return { value: deleteExpr, valueOriginalPositions: deleteExprPositions, stmts: stmts }; + } + + private voidExpressionToValueAndStmts(voidExpression: ts.VoidExpression): ValueAndStmts { + const { value: exprValue, valueOriginalPositions: exprPositions, stmts: stmts } = this.tsNodeToValueAndStmts( + voidExpression.expression); + const { stmts: exprStmts } = this.arkIRTransformer.generateAssignStmtForValue(exprValue, exprPositions); + exprStmts.forEach(stmt => stmts.push(stmt)); + return { value: ValueUtil.getUndefinedConst(), valueOriginalPositions: [FullPosition.DEFAULT], stmts: stmts }; + } + + private nonNullExpressionToValueAndStmts(nonNullExpression: ts.NonNullExpression): ValueAndStmts { + return this.tsNodeToValueAndStmts(nonNullExpression.expression); + } + + private parenthesizedExpressionToValueAndStmts(parenthesizedExpression: ts.ParenthesizedExpression): ValueAndStmts { + return this.tsNodeToValueAndStmts(parenthesizedExpression.expression); + } + + private typeOfExpressionToValueAndStmts(typeOfExpression: ts.TypeOfExpression): ValueAndStmts { + const { + value: exprValue, + valueOriginalPositions: exprPositions, + stmts: exprStmts, + } = this.tsNodeToValueAndStmts(typeOfExpression.expression); + const typeOfExpr = new ArkTypeOfExpr(exprValue); + const typeOfExprPositions = [FullPosition.buildFromNode(typeOfExpression, this.sourceFile), ...exprPositions]; + return { value: typeOfExpr, valueOriginalPositions: typeOfExprPositions, stmts: exprStmts }; + } + + private asExpressionToValueAndStmts(asExpression: ts.AsExpression): ValueAndStmts { + const stmts: Stmt[] = []; + let { value: exprValue, valueOriginalPositions: exprPositions, stmts: exprStmts } = this.tsNodeToValueAndStmts( + asExpression.expression); + exprStmts.forEach(stmt => stmts.push(stmt)); + if (IRUtils.moreThanOneAddress(exprValue)) { + ({ value: exprValue, valueOriginalPositions: exprPositions, stmts: exprStmts } = + this.arkIRTransformer.generateAssignStmtForValue(exprValue, exprPositions)); + exprStmts.forEach(stmt => stmts.push(stmt)); + } + const castExpr = new ArkCastExpr(exprValue, this.resolveTypeNode(asExpression.type)); + const castExprPositions = [FullPosition.buildFromNode(asExpression, this.sourceFile), ...exprPositions]; + return { value: castExpr, valueOriginalPositions: castExprPositions, stmts: stmts }; + } + + private typeAssertionToValueAndStmts(typeAssertion: ts.TypeAssertion): ValueAndStmts { + const { + value: exprValue, + valueOriginalPositions: exprPositions, + stmts: exprStmts, + } = this.tsNodeToValueAndStmts(typeAssertion.expression); + const castExpr = new ArkCastExpr(exprValue, this.resolveTypeNode(typeAssertion.type)); + const castExprPositions = [FullPosition.buildFromNode(typeAssertion, this.sourceFile), ...exprPositions]; + return { value: castExpr, valueOriginalPositions: castExprPositions, stmts: exprStmts }; + } + + public variableDeclarationListToValueAndStmts(variableDeclarationList: ts.VariableDeclarationList): ValueAndStmts { + const stmts: Stmt[] = []; + const isConst = (variableDeclarationList.flags & ts.NodeFlags.Const) !== 0; + for (const declaration of variableDeclarationList.declarations) { + const { stmts: declaredStmts } = this.variableDeclarationToValueAndStmts(declaration, isConst); + declaredStmts.forEach(s => stmts.push(s)); + } + return { value: ValueUtil.getUndefinedConst(), valueOriginalPositions: [FullPosition.DEFAULT], stmts: stmts }; + } + + public variableDeclarationToValueAndStmts(variableDeclaration: ts.VariableDeclaration, + isConst: boolean, needRightOp: boolean = true): ValueAndStmts { + const leftOpNode = variableDeclaration.name; + const rightOpNode = variableDeclaration.initializer; + const declarationType = variableDeclaration.type ? this.resolveTypeNode( + variableDeclaration.type) : UnknownType.getInstance(); + return this.assignmentToValueAndStmts(leftOpNode, rightOpNode, true, isConst, declarationType, needRightOp); + } + + private assignmentToValueAndStmts(leftOpNode: ts.Node, rightOpNode: ts.Node | undefined, variableDefFlag: boolean, + isConst: boolean, declarationType: Type, + needRightOp: boolean = true): ValueAndStmts { + let leftValueAndStmts: ValueAndStmts; + if (ts.isIdentifier(leftOpNode)) { + leftValueAndStmts = this.identifierToValueAndStmts(leftOpNode, variableDefFlag); + } else if (ts.isArrayBindingPattern(leftOpNode) || ts.isArrayLiteralExpression(leftOpNode)) { + leftValueAndStmts = this.arrayDestructuringToValueAndStmts(leftOpNode, isConst); + } else if (ts.isObjectBindingPattern(leftOpNode) || ts.isObjectLiteralExpression(leftOpNode)) { + leftValueAndStmts = this.objectDestructuringToValueAndStmts(leftOpNode, isConst); + } else { + leftValueAndStmts = this.tsNodeToValueAndStmts(leftOpNode); + } + const { value: leftValue, valueOriginalPositions: leftPositions, stmts: leftStmts } = leftValueAndStmts; + + let stmts: Stmt[] = []; + if (needRightOp) { + const { + value: rightValue, valueOriginalPositions: rightPositions, stmts: rightStmts, + } = this.assignmentRightOpToValueAndStmts(rightOpNode, leftValue); + if (leftValue instanceof Local) { + if (variableDefFlag) { + leftValue.setConstFlag(isConst); + leftValue.setType(declarationType); + } + if (leftValue.getType() instanceof UnknownType && !(rightValue.getType() instanceof UnknownType) && + !(rightValue.getType() instanceof UndefinedType)) { + leftValue.setType(rightValue.getType()); + } + } + const assignStmt = new ArkAssignStmt(leftValue, rightValue); + assignStmt.setOperandOriginalPositions([...leftPositions, ...rightPositions]); + if (ts.isArrayBindingPattern(leftOpNode) || ts.isArrayLiteralExpression(leftOpNode) || + ts.isObjectBindingPattern(leftOpNode) || ts.isObjectLiteralExpression(leftOpNode)) { + rightStmts.forEach(stmt => stmts.push(stmt)); + stmts.push(assignStmt); + leftStmts.forEach(stmt => stmts.push(stmt)); + } else { + rightStmts.forEach(stmt => stmts.push(stmt)); + leftStmts.forEach(stmt => stmts.push(stmt)); + stmts.push(assignStmt); + } + } else { + stmts = leftStmts; + } + return { value: leftValue, valueOriginalPositions: leftPositions, stmts: stmts }; + } + + private assignmentRightOpToValueAndStmts(rightOpNode: ts.Node | undefined, leftValue: Value): ValueAndStmts { + let rightValue: Value; + let rightPositions: FullPosition[]; + let tempRightStmts: Stmt[] = []; + const rightStmts: Stmt[] = []; + if (rightOpNode) { + ({ value: rightValue, valueOriginalPositions: rightPositions, stmts: tempRightStmts } = + this.tsNodeToValueAndStmts(rightOpNode)); + tempRightStmts.forEach(stmt => rightStmts.push(stmt)); + } else { + rightValue = ValueUtil.getUndefinedConst(); + rightPositions = [FullPosition.DEFAULT]; + } + if (IRUtils.moreThanOneAddress(leftValue) && IRUtils.moreThanOneAddress(rightValue)) { + ({ value: rightValue, valueOriginalPositions: rightPositions, stmts: tempRightStmts } = + this.arkIRTransformer.generateAssignStmtForValue(rightValue, rightPositions)); + tempRightStmts.forEach(stmt => rightStmts.push(stmt)); + } + return { value: rightValue, valueOriginalPositions: rightPositions, stmts: rightStmts }; + } + + // In assignment patterns, the left operand will be an array literal expression + private arrayDestructuringToValueAndStmts(arrayDestructuring: ts.ArrayBindingPattern | ts.ArrayLiteralExpression, + isConst: boolean = false): ValueAndStmts { + const stmts: Stmt[] = []; + const arrayTempLocal = this.generateTempLocal(); + const leftOriginalPosition = FullPosition.buildFromNode(arrayDestructuring, this.sourceFile); + const elements = arrayDestructuring.elements; + const isArrayBindingPattern = ts.isArrayBindingPattern(arrayDestructuring); + let index = 0; + for (const element of elements) { + const arrayRef = new ArkArrayRef(arrayTempLocal, ValueUtil.getOrCreateNumberConst(index)); + const arrayRefPositions = [leftOriginalPosition, leftOriginalPosition, FullPosition.DEFAULT]; + const itemName = element.getText(this.sourceFile); + const targetLocal = isArrayBindingPattern ? this.addNewLocal(itemName) : this.getOrCreateLocal(itemName); + const targetLocalPosition = FullPosition.buildFromNode(element, this.sourceFile); + isArrayBindingPattern && targetLocal.setConstFlag(isConst); + const assignStmt = new ArkAssignStmt(targetLocal, arrayRef); + assignStmt.setOperandOriginalPositions([targetLocalPosition, ...arrayRefPositions]); + stmts.push(assignStmt); + index++; + } + return { value: arrayTempLocal, valueOriginalPositions: [leftOriginalPosition], stmts: stmts }; + } + + // In assignment patterns, the left operand will be an object literal expression + private objectDestructuringToValueAndStmts(objectDestructuring: ts.ObjectBindingPattern | ts.ObjectLiteralExpression, + isConst: boolean = false): ValueAndStmts { + const stmts: Stmt[] = []; + const objectTempLocal = this.generateTempLocal(); + const leftOriginalPosition = FullPosition.buildFromNode(objectDestructuring, this.sourceFile); + const isObjectBindingPattern = ts.isObjectBindingPattern(objectDestructuring); + const elements = isObjectBindingPattern ? objectDestructuring.elements : objectDestructuring.properties; + for (const element of elements) { + let fieldName = ''; + let targetName = ''; + if (ts.isBindingElement(element)) { + fieldName = element.propertyName ? element.propertyName.getText(this.sourceFile) : element.name.getText( + this.sourceFile); + targetName = element.name.getText(this.sourceFile); + } else if (ts.isPropertyAssignment(element)) { + fieldName = element.name.getText(this.sourceFile); + targetName = element.initializer.getText(this.sourceFile); + } else if (ts.isShorthandPropertyAssignment(element)) { + fieldName = element.name.getText(this.sourceFile); + targetName = fieldName; + } else { + continue; + } + + const fieldSignature = ArkSignatureBuilder.buildFieldSignatureFromFieldName(fieldName); + const fieldRef = new ArkInstanceFieldRef(objectTempLocal, fieldSignature); + const fieldRefPositions = [leftOriginalPosition, leftOriginalPosition]; + const targetLocal = isObjectBindingPattern ? this.addNewLocal(targetName) : this.getOrCreateLocal( + targetName); + isObjectBindingPattern && targetLocal.setConstFlag(isConst); + const targetLocalPosition = FullPosition.buildFromNode(element, this.sourceFile); + const assignStmt = new ArkAssignStmt(targetLocal, fieldRef); + assignStmt.setOperandOriginalPositions([targetLocalPosition, ...fieldRefPositions]); + stmts.push(assignStmt); + } + return { value: objectTempLocal, valueOriginalPositions: [leftOriginalPosition], stmts: stmts }; + } + + private binaryExpressionToValueAndStmts(binaryExpression: ts.BinaryExpression): ValueAndStmts { + const operatorToken = binaryExpression.operatorToken; + if (operatorToken.kind === ts.SyntaxKind.FirstAssignment) { + const leftOpNode = binaryExpression.left; + const rightOpNode = binaryExpression.right; + const declarationType = UnknownType.getInstance(); + return this.assignmentToValueAndStmts(leftOpNode, rightOpNode, false, false, declarationType, true); + } else if (ArkValueTransformer.isCompoundAssignmentOperator(operatorToken.kind)) { + return this.compoundAssignmentToValueAndStmts(binaryExpression); + } + const stmts: Stmt[] = []; + const binaryExpressionPosition = FullPosition.buildFromNode(binaryExpression, this.sourceFile); + const { + value: opValue1, + valueOriginalPositions: opPositions1, + stmts: opStmts1, + } = this.tsNodeToSingleAddressValueAndStmts(binaryExpression.left); + opStmts1.forEach(stmt => stmts.push(stmt)); + + if (operatorToken.kind === ts.SyntaxKind.InstanceOfKeyword) { + const instanceOfExpr = new ArkInstanceOfExpr(opValue1, + new UnclearReferenceType(binaryExpression.right.getText(this.sourceFile))); + const instanceOfExprPositions = [binaryExpressionPosition, ...opPositions1]; + const { + value: instanceofRes, + valueOriginalPositions: instanceofPos, + stmts: instanceofStmt, + } = this.arkIRTransformer.generateAssignStmtForValue(instanceOfExpr, instanceOfExprPositions); + instanceofStmt.forEach(stmt => stmts.push(stmt)); + return { value: instanceofRes, valueOriginalPositions: instanceofPos, stmts: stmts }; + } + + const { + value: opValue2, + valueOriginalPositions: opPositions2, + stmts: opStmts2, + } = this.tsNodeToSingleAddressValueAndStmts(binaryExpression.right); + opStmts2.forEach(stmt => stmts.push(stmt)); + let exprValue: Value; + let exprValuePositions = [binaryExpressionPosition]; + if (operatorToken.kind === ts.SyntaxKind.CommaToken) { + exprValue = opValue2; + } else { + const operator = ArkIRTransformer.tokenToBinaryOperator(operatorToken.kind); + if (operator) { + if (this.isRelationalOperator(operator)) { + exprValue = new ArkConditionExpr(opValue1, opValue2, operator as RelationalBinaryOperator); + } else { + exprValue = new ArkNormalBinopExpr(opValue1, opValue2, operator as NormalBinaryOperator); + } + exprValuePositions.push(...opPositions1, ...opPositions2); + } else { + exprValue = ValueUtil.getUndefinedConst(); + exprValuePositions.push(binaryExpressionPosition); + } + } + return { value: exprValue, valueOriginalPositions: exprValuePositions, stmts: stmts }; + } + + private compoundAssignmentToValueAndStmts(binaryExpression: ts.BinaryExpression): ValueAndStmts { + const stmts: Stmt[] = []; + let { + value: leftValue, + valueOriginalPositions: leftPositions, + stmts: leftStmts, + } = this.tsNodeToValueAndStmts(binaryExpression.left); + leftStmts.forEach(stmt => stmts.push(stmt)); + let { + value: rightValue, + valueOriginalPositions: rightPositions, + stmts: rightStmts, + } = this.tsNodeToValueAndStmts(binaryExpression.right); + rightStmts.forEach(stmt => stmts.push(stmt)); + if (IRUtils.moreThanOneAddress(leftValue) && IRUtils.moreThanOneAddress(rightValue)) { + const { + value: newRightValue, + valueOriginalPositions: newRightPositions, + stmts: rightStmts, + } = this.arkIRTransformer.generateAssignStmtForValue(rightValue, rightPositions); + rightValue = newRightValue; + rightPositions = newRightPositions; + rightStmts.forEach(stmt => stmts.push(stmt)); + } + + let leftOpValue: Value; + let leftOpPositions: FullPosition[]; + const operator = this.compoundAssignmentTokenToBinaryOperator(binaryExpression.operatorToken.kind); + if (operator) { + const exprValue = new ArkNormalBinopExpr(leftValue, rightValue, operator); + const exprValuePosition = FullPosition.buildFromNode(binaryExpression, this.sourceFile); + const assignStmt = new ArkAssignStmt(leftValue, exprValue); + assignStmt.setOperandOriginalPositions( + [...leftPositions, exprValuePosition, ...leftPositions, ...rightPositions]); + stmts.push(assignStmt); + leftOpValue = leftValue; + leftOpPositions = leftPositions; + } else { + leftOpValue = ValueUtil.getUndefinedConst(); + leftOpPositions = [leftPositions[0]]; + } + return { value: leftOpValue, valueOriginalPositions: leftOpPositions, stmts: stmts }; + } + + private compoundAssignmentTokenToBinaryOperator(token: ts.SyntaxKind): NormalBinaryOperator | null { + switch (token) { + case ts.SyntaxKind.QuestionQuestionEqualsToken: + return NormalBinaryOperator.NullishCoalescing; + case ts.SyntaxKind.AsteriskAsteriskEqualsToken: + return NormalBinaryOperator.Exponentiation; + case ts.SyntaxKind.SlashEqualsToken: + return NormalBinaryOperator.Division; + case ts.SyntaxKind.PlusEqualsToken: + return NormalBinaryOperator.Addition; + case ts.SyntaxKind.MinusEqualsToken: + return NormalBinaryOperator.Subtraction; + case ts.SyntaxKind.AsteriskEqualsToken: + return NormalBinaryOperator.Multiplication; + case ts.SyntaxKind.PercentEqualsToken: + return NormalBinaryOperator.Remainder; + case ts.SyntaxKind.LessThanLessThanEqualsToken: + return NormalBinaryOperator.LeftShift; + case ts.SyntaxKind.GreaterThanGreaterThanEqualsToken: + return NormalBinaryOperator.RightShift; + case ts.SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken: + return NormalBinaryOperator.UnsignedRightShift; + case ts.SyntaxKind.AmpersandEqualsToken: + return NormalBinaryOperator.BitwiseAnd; + case ts.SyntaxKind.BarEqualsToken: + return NormalBinaryOperator.BitwiseOr; + case ts.SyntaxKind.CaretEqualsToken: + return NormalBinaryOperator.BitwiseXor; + case ts.SyntaxKind.AmpersandAmpersandEqualsToken: + return NormalBinaryOperator.LogicalAnd; + case ts.SyntaxKind.BarBarEqualsToken: + return NormalBinaryOperator.LogicalOr; + default: + ; + } + return null; + } + + public conditionToValueAndStmts(condition: ts.Expression): ValueAndStmts { + const stmts: Stmt[] = []; + let { + value: conditionValue, + valueOriginalPositions: conditionPositions, + stmts: conditionStmts, + } = this.tsNodeToValueAndStmts(condition); + conditionStmts.forEach(stmt => stmts.push(stmt)); + let conditionExpr: ArkConditionExpr; + if ((conditionValue instanceof AbstractBinopExpr) && this.isRelationalOperator(conditionValue.getOperator())) { + const operator = conditionValue.getOperator() as RelationalBinaryOperator; + conditionExpr = new ArkConditionExpr(conditionValue.getOp1(), conditionValue.getOp2(), operator); + } else { + if (IRUtils.moreThanOneAddress(conditionValue)) { + ({ + value: conditionValue, + valueOriginalPositions: conditionPositions, + stmts: conditionStmts, + } = this.arkIRTransformer.generateAssignStmtForValue(conditionValue, conditionPositions)); + conditionStmts.forEach(stmt => stmts.push(stmt)); + } + conditionExpr = new ArkConditionExpr(conditionValue, ValueUtil.getOrCreateNumberConst(0), + RelationalBinaryOperator.InEquality); + conditionPositions = [conditionPositions[0], ...conditionPositions, FullPosition.DEFAULT]; + } + return { value: conditionExpr, valueOriginalPositions: conditionPositions, stmts: stmts }; + } + + private literalNodeToValueAndStmts(literalNode: ts.Node): ValueAndStmts | null { + const syntaxKind = literalNode.kind; + let constant: Constant | null = null; + switch (syntaxKind) { + case ts.SyntaxKind.NumericLiteral: + constant = ValueUtil.getOrCreateNumberConst(parseFloat((literalNode as ts.NumericLiteral).text)); + break; + case ts.SyntaxKind.BigIntLiteral: + constant = ValueUtil.createBigIntConst(BigInt((literalNode as ts.BigIntLiteral).text.slice(0, -1))); + break; + case ts.SyntaxKind.StringLiteral: + constant = ValueUtil.createStringConst((literalNode as ts.StringLiteral).text); + break; + case ts.SyntaxKind.RegularExpressionLiteral: + constant = new Constant((literalNode as ts.RegularExpressionLiteral).text, Builtin.REGEXP_CLASS_TYPE); + break; + case ts.SyntaxKind.NoSubstitutionTemplateLiteral: + constant = ValueUtil.createStringConst((literalNode as ts.NoSubstitutionTemplateLiteral).text); + break; + case ts.SyntaxKind.NullKeyword: + constant = ValueUtil.getNullConstant(); + break; + case ts.SyntaxKind.UndefinedKeyword: + constant = ValueUtil.getUndefinedConst(); + break; + case ts.SyntaxKind.TrueKeyword: + constant = ValueUtil.getBooleanConstant(true); + break; + case ts.SyntaxKind.FalseKeyword: + constant = ValueUtil.getBooleanConstant(false); + break; + default: + logger.warn(`ast node's syntaxKind is ${ts.SyntaxKind[literalNode.kind]}, not literalNode`); + } + + if (constant === null) { + return null; + } + return { + value: constant, + valueOriginalPositions: [FullPosition.buildFromNode(literalNode, this.sourceFile)], + stmts: [], + }; + } + + private getOrCreateLocal(localName: string, localType: Type = UnknownType.getInstance()): Local { + let local = this.locals.get(localName); + if (local !== undefined) { + return local; + } + local = this.addNewLocal(localName, localType); + this.addNewGlobal(localName); + return local; + } + + public generateTempLocal(localType: Type = UnknownType.getInstance()): Local { + const tempLocalName = TEMP_LOCAL_PREFIX + this.tempLocalNo; + this.tempLocalNo++; + const tempLocal: Local = new Local(tempLocalName, localType); + this.locals.set(tempLocalName, tempLocal); + return tempLocal; + } + + private isRelationalOperator(operator: BinaryOperator): boolean { + return operator === RelationalBinaryOperator.LessThan || + operator === RelationalBinaryOperator.LessThanOrEqual || + operator === RelationalBinaryOperator.GreaterThan || + operator === RelationalBinaryOperator.GreaterThanOrEqual || + operator === RelationalBinaryOperator.Equality || + operator === RelationalBinaryOperator.InEquality || + operator === RelationalBinaryOperator.StrictEquality || + operator === RelationalBinaryOperator.StrictInequality; + } + + private isLiteralNode(node: ts.Node): boolean { + if (ts.isStringLiteral(node) || + ts.isNumericLiteral(node) || + ts.isBigIntLiteral(node) || + ts.isRegularExpressionLiteral(node) || + ts.isNoSubstitutionTemplateLiteral(node) || + node.kind === ts.SyntaxKind.NullKeyword || + node.kind === ts.SyntaxKind.TrueKeyword || + node.kind === ts.SyntaxKind.FalseKeyword || + node.kind === ts.SyntaxKind.UndefinedKeyword) { + return true; + } + return false; + } + + public resolveTypeNode(type: ts.TypeNode): Type { + const kind = type.kind; + switch (kind) { + case ts.SyntaxKind.BooleanKeyword: + return BooleanType.getInstance(); + case ts.SyntaxKind.NumberKeyword: + return NumberType.getInstance(); + case ts.SyntaxKind.StringKeyword: + return StringType.getInstance(); + case ts.SyntaxKind.UndefinedKeyword: + return UndefinedType.getInstance(); + case ts.SyntaxKind.AnyKeyword: + return AnyType.getInstance(); + case ts.SyntaxKind.VoidKeyword: + return VoidType.getInstance(); + case ts.SyntaxKind.NeverKeyword: + return NeverType.getInstance(); + case ts.SyntaxKind.BigIntKeyword: + return BigIntType.getInstance(); + case ts.SyntaxKind.TypeReference: + return this.resolveTypeReferenceNode(type as ts.TypeReferenceNode); + case ts.SyntaxKind.ArrayType: + return new ArrayType(this.resolveTypeNode((type as ts.ArrayTypeNode).elementType), 1); + case ts.SyntaxKind.UnionType: { + const mayTypes: Type[] = []; + (type as ts.UnionTypeNode).types.forEach(t => mayTypes.push(this.resolveTypeNode(t))); + return new UnionType(mayTypes); + } + case ts.SyntaxKind.IntersectionType: { + const intersectionTypes: Type[] = []; + (type as ts.IntersectionTypeNode).types.forEach(t => intersectionTypes.push(this.resolveTypeNode(t))); + return new IntersectionType(intersectionTypes); + } + case ts.SyntaxKind.TupleType: { + const types: Type[] = []; + (type as ts.TupleTypeNode).elements.forEach(element => { + types.push(this.resolveTypeNode(element)); + }); + return new TupleType(types); + } + case ts.SyntaxKind.NamedTupleMember: + return this.resolveTypeNode((type as ts.NamedTupleMember).type); + case ts.SyntaxKind.LiteralType: + return ArkValueTransformer.resolveLiteralTypeNode(type as ts.LiteralTypeNode, this.sourceFile); + case ts.SyntaxKind.TemplateLiteralType: + return this.resolveTemplateLiteralTypeNode(type as ts.TemplateLiteralTypeNode); + case ts.SyntaxKind.TypeLiteral: + return this.resolveTypeLiteralNode(type as ts.TypeLiteralNode); + case ts.SyntaxKind.FunctionType: + return this.resolveFunctionTypeNode(type as ts.FunctionTypeNode); + case ts.SyntaxKind.ImportType: + return UnknownType.getInstance(); + case ts.SyntaxKind.TypeQuery: + return this.resolveTypeQueryNode(type as ts.TypeQueryNode); + case ts.SyntaxKind.ParenthesizedType: + return this.resolveTypeNode((type as ts.ParenthesizedTypeNode).type); + case ts.SyntaxKind.TypeOperator: + return this.resolveTypeOperatorNode(type as ts.TypeOperatorNode); + default: + return UnknownType.getInstance(); + } + } + + private resolveTypeQueryNode(typeQueryNode: ts.TypeQueryNode): Type { + const genericTypes: Type[] = []; + if (typeQueryNode.typeArguments) { + for (const typeArgument of typeQueryNode.typeArguments) { + genericTypes.push(this.resolveTypeNode(typeArgument)); + } + } + + const exprNameNode = typeQueryNode.exprName; + let opValue: Value; + if (ts.isQualifiedName(exprNameNode)) { + if (exprNameNode.left.getText(this.sourceFile) === THIS_NAME) { + const fieldName = exprNameNode.right.getText(this.sourceFile); + const fieldSignature = this.declaringMethod.getDeclaringArkClass().getFieldWithName(fieldName)?.getSignature() ?? + ArkSignatureBuilder.buildFieldSignatureFromFieldName(fieldName); + const baseLocal = this.locals.get(THIS_NAME) ?? + new Local(THIS_NAME, new ClassType(this.declaringMethod.getDeclaringArkClass().getSignature(), genericTypes)); + opValue = new ArkInstanceFieldRef(baseLocal, fieldSignature); + } else { + const exprName = exprNameNode.getText(this.sourceFile); + opValue = new Local(exprName, UnknownType.getInstance()); + } + } else { + const exprName = exprNameNode.escapedText.toString(); + opValue = this.locals.get(exprName) ?? this.globals?.get(exprName) ?? new Local(exprName, UnknownType.getInstance()); + } + + return new TypeQueryExpr(opValue, genericTypes); + } + + private resolveTypeOperatorNode(typeOperatorNode: ts.TypeOperatorNode): Type { + let type = this.resolveTypeNode(typeOperatorNode.type); + + switch (typeOperatorNode.operator) { + case ts.SyntaxKind.ReadonlyKeyword: { + if (type instanceof ArrayType || type instanceof TupleType) { + type.setReadonlyFlag(true); + } + return type; + } + case ts.SyntaxKind.KeyOfKeyword: { + return new KeyofTypeExpr(type); + } + case ts.SyntaxKind.UniqueKeyword: { + return UnknownType.getInstance(); + } + default: + return UnknownType.getInstance(); + } + } + + public static resolveLiteralTypeNode(literalTypeNode: ts.LiteralTypeNode, sourceFile: ts.SourceFile): Type { + const literal = literalTypeNode.literal; + const kind = literal.kind; + switch (kind) { + case ts.SyntaxKind.NullKeyword: + return NullType.getInstance(); + case ts.SyntaxKind.TrueKeyword: + return LiteralType.TRUE; + case ts.SyntaxKind.FalseKeyword: + return LiteralType.FALSE; + case ts.SyntaxKind.NumericLiteral: + return new LiteralType(parseFloat((literal as ts.NumericLiteral).text)); + case ts.SyntaxKind.PrefixUnaryExpression: + return new LiteralType(parseFloat(literal.getText(sourceFile))); + default: + ; + } + return new LiteralType(literal.getText(sourceFile)); + } + + private resolveTemplateLiteralTypeNode(templateLiteralTypeNode: ts.TemplateLiteralTypeNode): Type { + let stringLiterals: string[] = ['']; + const headString = templateLiteralTypeNode.head.rawText || ''; + let newStringLiterals: string[] = []; + for (const stringLiteral of stringLiterals) { + newStringLiterals.push(stringLiteral + headString); + } + stringLiterals = newStringLiterals; + newStringLiterals = []; + + for (const templateSpan of templateLiteralTypeNode.templateSpans) { + const templateType = this.resolveTypeNode(templateSpan.type); + const unfoldTemplateTypes: Type[] = []; + if (templateType instanceof UnionType) { + unfoldTemplateTypes.push(...templateType.getTypes()); + } else { + unfoldTemplateTypes.push(templateType); + } + const unfoldTemplateTypeStrs: string[] = []; + for (const unfoldTemplateType of unfoldTemplateTypes) { + unfoldTemplateTypeStrs.push( + unfoldTemplateType instanceof AliasType ? unfoldTemplateType.getOriginalType() + .toString() : unfoldTemplateType.toString()); + } + + const templateSpanString = templateSpan.literal.rawText || ''; + for (const stringLiteral of stringLiterals) { + for (const unfoldTemplateTypeStr of unfoldTemplateTypeStrs) { + newStringLiterals.push(stringLiteral + unfoldTemplateTypeStr + templateSpanString); + } + } + stringLiterals = newStringLiterals; + newStringLiterals = []; + } + + const templateTypes: Type[] = []; + for (const stringLiteral of stringLiterals) { + templateTypes.push(new LiteralType(stringLiteral)); + } + if (templateTypes.length > 0) { + return new UnionType(templateTypes); + } + return templateTypes[0]; + } + + private resolveTypeReferenceNode(typeReferenceNode: ts.TypeReferenceNode): Type { + const typeReferenceFullName = typeReferenceNode.typeName.getText(this.sourceFile); + if (typeReferenceFullName === Builtin.OBJECT) { + return Builtin.OBJECT_CLASS_TYPE; + } + const aliasTypeAndStmt = this.aliasTypeMap.get(typeReferenceFullName); + + const genericTypes: Type[] = []; + if (typeReferenceNode.typeArguments) { + for (const typeArgument of typeReferenceNode.typeArguments) { + genericTypes.push(this.resolveTypeNode(typeArgument)); + } + } + + if (!aliasTypeAndStmt) { + const typeName = typeReferenceNode.typeName.getText(this.sourceFile); + const local = this.locals.get(typeName); + if (local !== undefined) { + return local.getType(); + } + return new UnclearReferenceType(typeName, genericTypes); + } else { + if (genericTypes.length > 0) { + const oldAlias = aliasTypeAndStmt[0]; + let alias = new AliasType(oldAlias.getName(), TypeInference.replaceTypeWithReal(oldAlias.getOriginalType(), genericTypes), + oldAlias.getSignature(), oldAlias.getGenericTypes()); + alias.setRealGenericTypes(genericTypes); + return alias; + } + return aliasTypeAndStmt[0]; + } + } + + private resolveTypeLiteralNode(typeLiteralNode: ts.TypeLiteralNode): Type { + const anonymousClass = new ArkClass(); + const declaringClass = this.declaringMethod.getDeclaringArkClass(); + const declaringNamespace = declaringClass.getDeclaringArkNamespace(); + if (declaringNamespace) { + buildNormalArkClassFromArkNamespace(typeLiteralNode, declaringNamespace, anonymousClass, this.sourceFile); + } else { + buildNormalArkClassFromArkFile(typeLiteralNode, declaringClass.getDeclaringArkFile(), anonymousClass, + this.sourceFile); + } + return new ClassType(anonymousClass.getSignature()); + } + + private resolveFunctionTypeNode(functionTypeNode: ts.FunctionTypeNode): Type { + const anonymousMethod = new ArkMethod(); + const declaringClass = this.declaringMethod.getDeclaringArkClass(); + buildArkMethodFromArkClass(functionTypeNode, declaringClass, anonymousMethod, this.sourceFile); + return new FunctionType(anonymousMethod.getSignature()); + } + + public static isCompoundAssignmentOperator(operator: ts.SyntaxKind): boolean { + const compoundAssignmentOperators = [ + ts.SyntaxKind.PlusEqualsToken, + ts.SyntaxKind.MinusEqualsToken, + ts.SyntaxKind.AsteriskAsteriskEqualsToken, + ts.SyntaxKind.AsteriskEqualsToken, + ts.SyntaxKind.SlashEqualsToken, + ts.SyntaxKind.PercentEqualsToken, + ts.SyntaxKind.AmpersandEqualsToken, + ts.SyntaxKind.BarEqualsToken, + ts.SyntaxKind.CaretEqualsToken, + ts.SyntaxKind.LessThanLessThanEqualsToken, + ts.SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken, + ts.SyntaxKind.GreaterThanGreaterThanEqualsToken, + ts.SyntaxKind.BarBarEqualsToken, + ts.SyntaxKind.AmpersandAmpersandEqualsToken, + ts.SyntaxKind.QuestionQuestionEqualsToken, + ]; + return compoundAssignmentOperators.includes(operator); + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/common/Builtin.ts b/ets2panda/linter/arkanalyzer/src/core/common/Builtin.ts new file mode 100644 index 0000000000..87cd5981a2 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/common/Builtin.ts @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ClassSignature, FileSignature, MethodSignature, MethodSubSignature } from '../model/ArkSignature'; +import { ClassType, GenericType, StringType } from '../base/Type'; + +export class Builtin { + // built-in classes + // TODO: Automatically obtain from the standard library + public static OBJECT = 'Object'; + public static ARRAY = 'Array'; + public static SET = 'Set'; + public static MAP = 'Map'; + public static REGEXP = 'RegExp'; + + public static BUILT_IN_CLASSES = this.buildBuiltInClasses(); + + // signature for built-in class + public static DUMMY_PROJECT_NAME = 'ES2015'; + public static DUMMY_FILE_NAME = 'BuiltinClass'; + + public static BUILT_IN_CLASSES_FILE_SIGNATURE = Builtin.buildBuiltInClassesFileSignature(); + public static OBJECT_CLASS_SIGNATURE = this.buildBuiltInClassSignature(this.OBJECT); + public static OBJECT_CLASS_TYPE = new ClassType(this.OBJECT_CLASS_SIGNATURE); + public static ARRAY_CLASS_SIGNATURE = this.buildBuiltInClassSignature(this.ARRAY); + public static SET_CLASS_SIGNATURE = this.buildBuiltInClassSignature(this.SET); + public static MAP_CLASS_SIGNATURE = this.buildBuiltInClassSignature(this.MAP); + public static REGEXP_CLASS_SIGNATURE = this.buildBuiltInClassSignature(this.REGEXP); + public static REGEXP_CLASS_TYPE = new ClassType(this.REGEXP_CLASS_SIGNATURE); + public static BUILT_IN_CLASS_SIGNATURE_MAP = this.buildBuiltInClassSignatureMap(); + + // constants for iterator + public static ITERATOR_FUNCTION = 'iterator'; + public static ITERATOR = 'Iterator'; + public static ITERATOR_NEXT = 'next'; + public static ITERATOR_RESULT = 'IteratorResult'; + public static ITERATOR_RESULT_DONE = 'done'; + public static ITERATOR_RESULT_VALUE = 'value'; + + public static ITERATOR_CLASS_SIGNATURE = this.buildBuiltInClassSignature(this.ITERATOR); + public static ITERATOR_RESULT_CLASS_SIGNATURE = this.buildBuiltInClassSignature(this.ITERATOR_RESULT); + public static ITERATOR_CLASS_TYPE = new ClassType(this.ITERATOR_CLASS_SIGNATURE, [new GenericType('T')]); + public static ITERATOR_RESULT_CLASS_TYPE = new ClassType(this.ITERATOR_RESULT_CLASS_SIGNATURE, [new GenericType('T')]); + + // constants for string + public static TO_STRING = 'toString'; + public static TO_STRING_METHOD_SIGNATURE = new MethodSignature(ClassSignature.DEFAULT, + new MethodSubSignature(this.TO_STRING, [], StringType.getInstance(), false)); + + private static buildBuiltInClasses(): Set { + const builtInClasses = new Set(); + builtInClasses.add(this.OBJECT); + builtInClasses.add(this.ARRAY); + builtInClasses.add(this.SET); + builtInClasses.add(this.MAP); + builtInClasses.add(this.REGEXP); + return builtInClasses; + } + + private static buildBuiltInClassesFileSignature(): FileSignature { + return new FileSignature(this.DUMMY_PROJECT_NAME, this.DUMMY_FILE_NAME); + } + + public static buildBuiltInClassSignature(className: string): ClassSignature { + return new ClassSignature(className, this.BUILT_IN_CLASSES_FILE_SIGNATURE); + } + + private static buildBuiltInClassSignatureMap(): Map { + const builtInClassSignatureMap = new Map(); + builtInClassSignatureMap.set(this.OBJECT, this.OBJECT_CLASS_SIGNATURE); + builtInClassSignatureMap.set(this.ARRAY, this.ARRAY_CLASS_SIGNATURE); + builtInClassSignatureMap.set(this.SET, this.SET_CLASS_SIGNATURE); + builtInClassSignatureMap.set(this.MAP, this.MAP_CLASS_SIGNATURE); + builtInClassSignatureMap.set(this.REGEXP, this.REGEXP_CLASS_SIGNATURE); + return builtInClassSignatureMap; + } + + public static isBuiltinClass(className: string): boolean { + return this.BUILT_IN_CLASSES.has(className); + } +} diff --git a/ets2panda/linter/arkanalyzer/src/core/common/Const.ts b/ets2panda/linter/arkanalyzer/src/core/common/Const.ts new file mode 100644 index 0000000000..3edd6f6cc0 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/common/Const.ts @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// names +export const NAME_DELIMITER = '$'; +export const NAME_PREFIX = '%'; +export const UNKNOWN_NAME = 'unk'; +export const DEFAULT_NAME = 'dflt'; + +// ArkClass const +export const DEFAULT_ARK_CLASS_NAME = NAME_PREFIX + DEFAULT_NAME; +export const ANONYMOUS_CLASS_PREFIX = NAME_PREFIX + 'AC'; +export const ANONYMOUS_CLASS_DELIMITER = NAME_DELIMITER; + +// ArkMethod const +export const DEFAULT_ARK_METHOD_NAME = NAME_PREFIX + DEFAULT_NAME; +export const INSTANCE_INIT_METHOD_NAME = NAME_PREFIX + 'instInit'; +export const STATIC_INIT_METHOD_NAME = NAME_PREFIX + 'statInit'; +export const STATIC_BLOCK_METHOD_NAME_PREFIX = NAME_PREFIX + 'statBlock'; +export const ANONYMOUS_METHOD_PREFIX = NAME_PREFIX + 'AM'; +export const CALL_SIGNATURE_NAME = 'create'; + +// ArkSignature const +export const UNKNOWN_PROJECT_NAME = NAME_PREFIX + UNKNOWN_NAME; +export const UNKNOWN_FILE_NAME = NAME_PREFIX + UNKNOWN_NAME; +export const UNKNOWN_NAMESPACE_NAME = NAME_PREFIX + UNKNOWN_NAME; +export const UNKNOWN_CLASS_NAME = ''; // temp for being compatible with existing type inference +export const UNKNOWN_FIELD_NAME = ''; // temp for being compatible with existing type inference +export const UNKNOWN_METHOD_NAME = ''; // temp for being compatible with existing type inference + +// IR const +export const TEMP_LOCAL_PREFIX = NAME_PREFIX; +export const LEXICAL_ENV_NAME_PREFIX = TEMP_LOCAL_PREFIX + 'closures'; + +// ArkTS version +export const ARKTS_STATIC_MARK = 'use static'; \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/common/DummyMainCreater.ts b/ets2panda/linter/arkanalyzer/src/core/common/DummyMainCreater.ts new file mode 100644 index 0000000000..479cb2f76c --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/common/DummyMainCreater.ts @@ -0,0 +1,342 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Scene } from '../../Scene'; +import { COMPONENT_LIFECYCLE_METHOD_NAME, getCallbackMethodFromStmt, LIFECYCLE_METHOD_NAME } from '../../utils/entryMethodUtils'; +import { Constant } from '../base/Constant'; +import { + AbstractInvokeExpr, + ArkConditionExpr, + ArkInstanceInvokeExpr, + ArkNewExpr, + ArkStaticInvokeExpr, + RelationalBinaryOperator, +} from '../base/Expr'; +import { Local } from '../base/Local'; +import { ArkAssignStmt, ArkIfStmt, ArkInvokeStmt, ArkReturnVoidStmt } from '../base/Stmt'; +import { ClassType, NumberType, Type } from '../base/Type'; +import { BasicBlock } from '../graph/BasicBlock'; +import { Cfg } from '../graph/Cfg'; +import { ArkBody } from '../model/ArkBody'; +import { ArkClass } from '../model/ArkClass'; +import { ArkFile, Language } from '../model/ArkFile'; +import { ArkMethod } from '../model/ArkMethod'; +import { ClassSignature, FileSignature, MethodSignature } from '../model/ArkSignature'; +import { ArkSignatureBuilder } from '../model/builder/ArkSignatureBuilder'; +import { CONSTRUCTOR_NAME } from './TSConst'; +import { checkAndUpdateMethod } from '../model/builder/ArkMethodBuilder'; +import { ValueUtil } from './ValueUtil'; + + +/** +收集所有的onCreate,onStart等函数,构造一个虚拟函数,具体为: +%statInit() +... +count = 0 +while (true) { + if (count === 1) { + temp1 = new ability + temp2 = new want + temp1.onCreate(temp2) + } + if (count === 2) { + onDestroy() + } + ... + if (count === *) { + callbackMethod1() + } + ... +} +return +如果是instanceInvoke还要先实例化对象,如果是其他文件的类或者方法还要添加import信息 + */ + +export class DummyMainCreater { + + private entryMethods: ArkMethod[] = []; + private classLocalMap: Map = new Map(); + private dummyMain: ArkMethod = new ArkMethod(); + private scene: Scene; + private tempLocalIndex: number = 0; + + constructor(scene: Scene) { + this.scene = scene; + // Currently get entries from module.json5 can't visit all of abilities + // Todo: handle ablity/component jump, then get entries from module.json5 + this.entryMethods = this.getMethodsFromAllAbilities(); + this.entryMethods.push(...this.getEntryMethodsFromComponents()); + this.entryMethods.push(...this.getCallbackMethods()); + } + + + public setEntryMethods(methods: ArkMethod[]): void { + this.entryMethods = methods; + } + + public createDummyMain(): void { + const dummyMainFile = new ArkFile(Language.UNKNOWN); + dummyMainFile.setScene(this.scene); + const dummyMainFileSignature = new FileSignature(this.scene.getProjectName(), '@dummyFile') + dummyMainFile.setFileSignature(dummyMainFileSignature) + this.scene.setFile(dummyMainFile); + const dummyMainClass = new ArkClass(); + dummyMainClass.setDeclaringArkFile(dummyMainFile); + const dummyMainClassSignature = new ClassSignature('@dummyClass', + dummyMainClass.getDeclaringArkFile().getFileSignature(), dummyMainClass.getDeclaringArkNamespace()?.getSignature() || null); + dummyMainClass.setSignature(dummyMainClassSignature); + dummyMainFile.addArkClass(dummyMainClass); + + this.dummyMain = new ArkMethod(); + this.dummyMain.setDeclaringArkClass(dummyMainClass); + const methodSubSignature = ArkSignatureBuilder.buildMethodSubSignatureFromMethodName('@dummyMain'); + const methodSignature = new MethodSignature(this.dummyMain.getDeclaringArkClass().getSignature(), + methodSubSignature); + this.dummyMain.setImplementationSignature(methodSignature); + this.dummyMain.setLineCol(0); + checkAndUpdateMethod(this.dummyMain, dummyMainClass); + dummyMainClass.addMethod(this.dummyMain); + + let defaultMethods: ArkMethod[] = []; + for (const method of this.entryMethods) { + if (method.getDeclaringArkClass().isDefaultArkClass() || method.isStatic()) { + defaultMethods.push(method); + continue; + } + const declaringArkClass = method.getDeclaringArkClass(); + let newLocal: Local | null = null; + for (const local of this.classLocalMap.values()) { + if ((local?.getType() as ClassType).getClassSignature() === declaringArkClass.getSignature()) { + newLocal = local; + break; + } + } + if (!newLocal) { + newLocal = new Local('%' + this.tempLocalIndex, new ClassType(declaringArkClass.getSignature())); + this.tempLocalIndex++; + } + this.classLocalMap.set(method, newLocal); + } + for (const defaultMethod of defaultMethods) { + this.classLocalMap.set(defaultMethod, null); + } + const localSet = new Set(Array.from(this.classLocalMap.values()).filter((value): value is Local => value !== null)); + const dummyBody = new ArkBody(localSet, this.createDummyMainCfg()); + this.dummyMain.setBody(dummyBody) + this.addCfg2Stmt() + this.scene.addToMethodsMap(this.dummyMain); + } + + private addStaticInit(dummyCfg: Cfg, firstBlock: BasicBlock): void { + let isStartingStmt = true; + for (const method of this.scene.getStaticInitMethods()) { + const staticInvokeExpr = new ArkStaticInvokeExpr(method.getSignature(), []); + const invokeStmt = new ArkInvokeStmt(staticInvokeExpr); + if (isStartingStmt) { + dummyCfg.setStartingStmt(invokeStmt); + isStartingStmt = false; + } + firstBlock.addStmt(invokeStmt); + } + } + + private addClassInit(firstBlock: BasicBlock): void { + const locals = Array.from(new Set(this.classLocalMap.values())); + for (const local of locals) { + if (!local) { + continue; + } + let clsType = local.getType() as ClassType; + let cls = this.scene.getClass(clsType.getClassSignature())!; + const assStmt = new ArkAssignStmt(local!, new ArkNewExpr(clsType)); + firstBlock.addStmt(assStmt); + local.setDeclaringStmt(assStmt); + let consMtd = cls.getMethodWithName(CONSTRUCTOR_NAME); + if (consMtd) { + let ivkExpr = new ArkInstanceInvokeExpr(local, consMtd.getSignature(), []); + let ivkStmt = new ArkInvokeStmt(ivkExpr); + firstBlock.addStmt(ivkStmt); + } + } + } + + private addParamInit(method: ArkMethod, paramLocals: Local[], invokeBlock: BasicBlock): void { + let paramIdx = 0; + for (const param of method.getParameters()) { + let paramType: Type | undefined = param.getType(); + // In ArkIR from abc scenario, param type is undefined in some cases + // Then try to get it from super class(SDK) + // TODO - need handle method overload to get the correct method + if (!paramType) { + let superCls = method.getDeclaringArkClass().getSuperClass(); + let methodInSuperCls = superCls?.getMethodWithName(method.getName()); + if (methodInSuperCls) { + paramType = methodInSuperCls.getParameters().at(paramIdx)?.getType(); + method = methodInSuperCls; + } + } + const paramLocal = new Local('%' + this.tempLocalIndex++, paramType); + paramLocals.push(paramLocal); + if (paramType instanceof ClassType) { + const assStmt = new ArkAssignStmt(paramLocal, new ArkNewExpr(paramType)); + invokeBlock.addStmt(assStmt); + } + paramIdx++; + } + } + + private addBranches(whileBlock: BasicBlock, countLocal: Local, dummyCfg: Cfg): void { + let lastBlocks: BasicBlock[] = [whileBlock]; + let count = 0; + for (let method of this.entryMethods) { + count++; + const condition = new ArkConditionExpr(countLocal, new Constant(count.toString(), NumberType.getInstance()), RelationalBinaryOperator.Equality); + const ifStmt = new ArkIfStmt(condition); + const ifBlock = new BasicBlock(); + ifBlock.addStmt(ifStmt); + dummyCfg.addBlock(ifBlock); + for (const block of lastBlocks) { + ifBlock.addPredecessorBlock(block); + block.addSuccessorBlock(ifBlock); + } + const invokeBlock = new BasicBlock(); + const paramLocals: Local[] = []; + this.addParamInit(method, paramLocals, invokeBlock); + const local = this.classLocalMap.get(method); + let invokeExpr: AbstractInvokeExpr; + if (local) { + invokeExpr = new ArkInstanceInvokeExpr(local, method.getSignature(), paramLocals); + } else { + invokeExpr = new ArkStaticInvokeExpr(method.getSignature(), paramLocals); + } + const invokeStmt = new ArkInvokeStmt(invokeExpr); + invokeBlock.addStmt(invokeStmt); + dummyCfg.addBlock(invokeBlock); + ifBlock.addSuccessorBlock(invokeBlock); + invokeBlock.addPredecessorBlock(ifBlock); + lastBlocks = [ifBlock, invokeBlock]; + } + for (const block of lastBlocks) { + block.addSuccessorBlock(whileBlock); + whileBlock.addPredecessorBlock(block); + } + } + + private createDummyMainCfg(): Cfg { + const dummyCfg = new Cfg(); + dummyCfg.setDeclaringMethod(this.dummyMain); + const firstBlock = new BasicBlock(); + this.addStaticInit(dummyCfg, firstBlock); + this.addClassInit(firstBlock); + const countLocal = new Local('count', NumberType.getInstance()); + const zero = ValueUtil.getOrCreateNumberConst(0); + const countAssignStmt = new ArkAssignStmt(countLocal, zero); + const truE = ValueUtil.getBooleanConstant(true); + const conditionTrue = new ArkConditionExpr(truE, zero, RelationalBinaryOperator.Equality); + const whileStmt = new ArkIfStmt(conditionTrue); + firstBlock.addStmt(countAssignStmt); + dummyCfg.addBlock(firstBlock); + dummyCfg.setStartingStmt(firstBlock.getStmts()[0]); + const whileBlock = new BasicBlock(); + whileBlock.addStmt(whileStmt); + dummyCfg.addBlock(whileBlock); + firstBlock.addSuccessorBlock(whileBlock); + whileBlock.addPredecessorBlock(firstBlock); + this.addBranches(whileBlock, countLocal, dummyCfg); + const returnStmt = new ArkReturnVoidStmt(); + const returnBlock = new BasicBlock(); + returnBlock.addStmt(returnStmt); + dummyCfg.addBlock(returnBlock); + whileBlock.addSuccessorBlock(returnBlock); + returnBlock.addPredecessorBlock(whileBlock); + return dummyCfg; + } + + private addCfg2Stmt() { + const cfg = this.dummyMain.getCfg(); + if (!cfg) { + return; + } + for (const block of cfg.getBlocks()) { + for (const stmt of block.getStmts()) { + stmt.setCfg(cfg); + } + } + } + + public getDummyMain(): ArkMethod { + return this.dummyMain; + } + + private getEntryMethodsFromComponents(): ArkMethod[] { + const COMPONENT_BASE_CLASSES = ['CustomComponent', 'ViewPU']; + let methods: ArkMethod[] = []; + this.scene.getClasses() + .filter(cls => { + if (COMPONENT_BASE_CLASSES.includes(cls.getSuperClassName())) { + return true; + } + if (cls.hasDecorator('Component')) { + return true; + } + return false; + }) + .forEach(cls => { + methods.push(...cls.getMethods().filter(mtd => COMPONENT_LIFECYCLE_METHOD_NAME.includes(mtd.getName()))); + }); + return methods; + } + + private classInheritsAbility(arkClass: ArkClass): boolean { + const ABILITY_BASE_CLASSES = ['UIExtensionAbility', 'Ability', 'FormExtensionAbility', 'UIAbility', 'BackupExtensionAbility']; + if (ABILITY_BASE_CLASSES.includes(arkClass.getSuperClassName())) { + return true; + } + let superClass = arkClass.getSuperClass(); + while (superClass) { + if (ABILITY_BASE_CLASSES.includes(superClass.getSuperClassName())) { + return true; + } + superClass = superClass.getSuperClass(); + } + return false; + } + + public getMethodsFromAllAbilities(): ArkMethod[] { + let methods: ArkMethod[] = []; + this.scene.getClasses() + .filter(cls => this.classInheritsAbility(cls)) + .forEach(cls => { + methods.push(...cls.getMethods().filter(mtd => LIFECYCLE_METHOD_NAME.includes(mtd.getName()))); + }); + return methods; + } + + public getCallbackMethods(): ArkMethod[] { + const callbackMethods: ArkMethod[] = []; + this.scene.getMethods().forEach(method => { + if (!method.getCfg()) { + return; + } + method.getCfg()!.getStmts().forEach(stmt => { + const cbMethod = getCallbackMethodFromStmt(stmt, this.scene); + if (cbMethod && !callbackMethods.includes(cbMethod)) { + callbackMethods.push(cbMethod); + } + }); + }); + return callbackMethods; + } +} diff --git a/ets2panda/linter/arkanalyzer/src/core/common/EtsConst.ts b/ets2panda/linter/arkanalyzer/src/core/common/EtsConst.ts new file mode 100644 index 0000000000..3d4c1a5161 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/common/EtsConst.ts @@ -0,0 +1,1030 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const ETS_COMPILER_OPTIONS = { + ets: { + emitDecorators: [ + { + name: 'Entry', + emitParameters: true, + }, + { + name: 'Component', + emitParameters: false, + }, + { + name: 'Reusable', + emitParameters: false, + }, + { + name: 'CustomDialog', + emitParameters: false, + }, + { + name: 'Consume', + emitParameters: true, + }, + { + name: 'Link', + emitParameters: false, + }, + { + name: 'LocalStorageLink', + emitParameters: true, + }, + { + name: 'LocalStorageProp', + emitParameters: true, + }, + { + name: 'ObjectLink', + emitParameters: false, + }, + { + name: 'Prop', + emitParameters: false, + }, + { + name: 'Provide', + emitParameters: true, + }, + { + name: 'State', + emitParameters: false, + }, + { + name: 'StorageLink', + emitParameters: true, + }, + { + name: 'StorageProp', + emitParameters: true, + }, + { + name: 'Builder', + emitParameters: false, + }, + { + name: 'LocalBuilder', + emitParameters: false, + }, + { + name: 'BuilderParam', + emitParameters: false, + }, + { + name: 'Observed', + emitParameters: false, + }, + { + name: 'Require', + emitParameters: false, + }, + { + name: 'Sendable', + emitParameters: false, + }, + { + name: 'Track', + emitParameters: false, + }, + { + name: 'ComponentV2', + emitParameters: true, + }, + { + name: 'ObservedV2', + emitParameters: false, + }, + { + name: 'Trace', + emitParameters: false, + }, + { + name: 'Local', + emitParameters: false, + }, + { + name: 'Param', + emitParameters: false, + }, + { + name: 'Once', + emitParameters: false, + }, + { + name: 'Event', + emitParameters: false, + }, + { + name: 'Monitor', + emitParameters: true, + }, + { + name: 'Provider', + emitParameters: true, + }, + { + name: 'Consumer', + emitParameters: true, + }, + { + name: 'Computed', + emitParameters: false, + }, + { + name: 'Type', + emitParameters: true, + }, + ], + propertyDecorators: [ + { + name: 'Link', + needInitialization: false, + }, + { + name: 'Prop', + needInitialization: false, + }, + { + name: 'ObjectLink', + needInitialization: false, + }, + { + name: 'Consume', + needInitialization: false, + }, + ], + render: { + method: ['build', 'pageTransition'], + decorator: ['LocalBuilder', 'Builder'], + }, + components: [ + 'AbilityComponent', + 'AlphabetIndexer', + 'Animator', + 'Badge', + 'Blank', + 'Button', + 'Calendar', + 'CalendarPicker', + 'Camera', + 'Canvas', + 'Checkbox', + 'CheckboxGroup', + 'Circle', + 'ColorPicker', + 'ColorPickerDialog', + 'Column', + 'ColumnSplit', + 'ContentSlot', + 'Counter', + 'DataPanel', + 'DatePicker', + 'Divider', + 'EffectComponent', + 'Ellipse', + 'EmbeddedComponent', + 'Flex', + 'FolderStack', + 'FormComponent', + 'FormLink', + 'Gauge', + 'GeometryView', + 'Grid', + 'GridItem', + 'GridContainer', + 'Hyperlink', + 'Image', + 'ImageAnimator', + 'Line', + 'List', + 'ListItem', + 'ListItemGroup', + 'LoadingProgress', + 'Marquee', + 'MediaCachedImage', + 'Menu', + 'MenuItem', + 'MenuItemGroup', + 'MovingPhotoView', + 'NavDestination', + 'NavRouter', + 'Navigation', + 'Navigator', + 'NodeContainer', + 'Option', + 'PageTransitionEnter', + 'PageTransitionExit', + 'Panel', + 'Particle', + 'Path', + 'PatternLock', + 'Piece', + 'PluginComponent', + 'Polygon', + 'Polyline', + 'Progress', + 'QRCode', + 'Radio', + 'Rating', + 'Rect', + 'Refresh', + 'RelativeContainer', + 'RemoteWindow', + 'RootScene', + 'Row', + 'RowSplit', + 'RichText', + 'Screen', + 'Scroll', + 'ScrollBar', + 'Search', + 'Section', + 'Select', + 'Shape', + 'Sheet', + 'SideBarContainer', + 'Slider', + 'Span', + 'Stack', + 'Stepper', + 'StepperItem', + 'Swiper', + 'SymbolGlyph', + 'SymbolSpan', + 'TabContent', + 'Tabs', + 'Text', + 'TextPicker', + 'TextClock', + 'TextArea', + 'TextInput', + 'TextTimer', + 'TimePicker', + 'Toggle', + 'Video', + 'Web', + 'WindowScene', + 'WithTheme', + 'XComponent', + 'GridRow', + 'GridCol', + 'WaterFlow', + 'FlowItem', + 'ImageSpan', + 'LocationButton', + 'PasteButton', + 'SaveButton', + 'UIExtensionComponent', + 'IsolatedComponent', + 'RichEditor', + 'Component3D', + 'ContainerSpan', + ], + extend: { + decorator: ['Extend', 'AnimatableExtend'], + components: [ + { + name: 'AbilityComponent', + type: 'AbilityComponentAttribute', + instance: 'AbilityComponentInstance', + }, + { + name: 'AlphabetIndexer', + type: 'AlphabetIndexerAttribute', + instance: 'AlphabetIndexerInstance', + }, + { + name: 'Animator', + type: 'AnimatorAttribute', + instance: 'AnimatorInstance', + }, + { + name: 'Badge', + type: 'BadgeAttribute', + instance: 'BadgeInstance', + }, + { + name: 'Blank', + type: 'BlankAttribute', + instance: 'BlankInstance', + }, + { + name: 'Button', + type: 'ButtonAttribute', + instance: 'ButtonInstance', + }, + { + name: 'Calendar', + type: 'CalendarAttribute', + instance: 'CalendarInstance', + }, + { + name: 'CalendarPicker', + type: 'CalendarPickerAttribute', + instance: 'CalendarPickerInstance', + }, + { + name: 'Camera', + type: 'CameraAttribute', + instance: 'CameraInstance', + }, + { + name: 'Canvas', + type: 'CanvasAttribute', + instance: 'CanvasInstance', + }, + { + name: 'Checkbox', + type: 'CheckboxAttribute', + instance: 'CheckboxInstance', + }, + { + name: 'CheckboxGroup', + type: 'CheckboxGroupAttribute', + instance: 'CheckboxGroupInstance', + }, + { + name: 'Circle', + type: 'CircleAttribute', + instance: 'CircleInstance', + }, + { + name: 'ColorPicker', + type: 'ColorPickerAttribute', + instance: 'ColorPickerInstance', + }, + { + name: 'ColorPickerDialog', + type: 'ColorPickerDialogAttribute', + instance: 'ColorPickerDialogInstance', + }, + { + name: 'Column', + type: 'ColumnAttribute', + instance: 'ColumnInstance', + }, + { + name: 'ColumnSplit', + type: 'ColumnSplitAttribute', + instance: 'ColumnSplitInstance', + }, + { + name: 'Counter', + type: 'CounterAttribute', + instance: 'CounterInstance', + }, + { + name: 'DataPanel', + type: 'DataPanelAttribute', + instance: 'DataPanelInstance', + }, + { + name: 'DatePicker', + type: 'DatePickerAttribute', + instance: 'DatePickerInstance', + }, + { + name: 'Divider', + type: 'DividerAttribute', + instance: 'DividerInstance', + }, + { + name: 'EffectComponent', + type: 'EffectComponentAttribute', + instance: 'EffectComponentInstance', + }, + { + name: 'Ellipse', + type: 'EllipseAttribute', + instance: 'EllipseInstance', + }, + { + name: 'EmbeddedComponent', + type: 'EmbeddedComponentAttribute', + instance: 'EmbeddedComponentInstance', + }, + { + name: 'Flex', + type: 'FlexAttribute', + instance: 'FlexInstance', + }, + { + name: 'FolderStack', + type: 'FolderStackAttribute', + instance: 'FolderStackInstance', + }, + { + name: 'FormComponent', + type: 'FormComponentAttribute', + instance: 'FormComponentInstance', + }, + { + name: 'FormLink', + type: 'FormLinkAttribute', + instance: 'FormLinkInstance', + }, + { + name: 'Gauge', + type: 'GaugeAttribute', + instance: 'GaugeInstance', + }, + { + name: 'GeometryView', + type: 'GeometryViewAttribute', + instance: 'GeometryViewInstance', + }, + { + name: 'Grid', + type: 'GridAttribute', + instance: 'GridInstance', + }, + { + name: 'GridItem', + type: 'GridItemAttribute', + instance: 'GridItemInstance', + }, + { + name: 'GridContainer', + type: 'GridContainerAttribute', + instance: 'GridContainerInstance', + }, + { + name: 'Hyperlink', + type: 'HyperlinkAttribute', + instance: 'HyperlinkInstance', + }, + { + name: 'Image', + type: 'ImageAttribute', + instance: 'ImageInstance', + }, + { + name: 'ImageAnimator', + type: 'ImageAnimatorAttribute', + instance: 'ImageAnimatorInstance', + }, + { + name: 'Line', + type: 'LineAttribute', + instance: 'LineInstance', + }, + { + name: 'List', + type: 'ListAttribute', + instance: 'ListInstance', + }, + { + name: 'ListItem', + type: 'ListItemAttribute', + instance: 'ListItemInstance', + }, + { + name: 'ListItemGroup', + type: 'ListItemGroupAttribute', + instance: 'ListItemGroupInstance', + }, + { + name: 'LoadingProgress', + type: 'LoadingProgressAttribute', + instance: 'LoadingProgressInstance', + }, + { + name: 'Marquee', + type: 'MarqueeAttribute', + instance: 'MarqueeInstance', + }, + { + name: 'MediaCachedImage', + type: 'MediaCachedImageAttribute', + instance: 'MediaCachedImageInstance', + }, + { + name: 'Menu', + type: 'MenuAttribute', + instance: 'MenuInstance', + }, + { + name: 'MenuItem', + type: 'MenuItemAttribute', + instance: 'MenuItemInstance', + }, + { + name: 'MenuItemGroup', + type: 'MenuItemGroupAttribute', + instance: 'MenuItemGroupInstance', + }, + { + name: 'MovingPhotoView', + type: 'MovingPhotoViewAttribute', + instance: 'MovingPhotoViewInstance', + }, + { + name: 'NavDestination', + type: 'NavDestinationAttribute', + instance: 'NavDestinationInstance', + }, + { + name: 'NavRouter', + type: 'NavRouterAttribute', + instance: 'NavRouterInstance', + }, + { + name: 'Navigation', + type: 'NavigationAttribute', + instance: 'NavigationInstance', + }, + { + name: 'Navigator', + type: 'NavigatorAttribute', + instance: 'NavigatorInstance', + }, + { + name: 'NodeContainer', + type: 'NodeContainerAttribute', + instance: 'NodeContainerInstance', + }, + { + name: 'Option', + type: 'OptionAttribute', + instance: 'OptionInstance', + }, + { + name: 'PageTransitionEnter', + type: 'PageTransitionEnterAttribute', + instance: 'PageTransitionEnterInstance', + }, + { + name: 'PageTransitionExit', + type: 'PageTransitionExitAttribute', + instance: 'PageTransitionExitInstance', + }, + { + name: 'Panel', + type: 'PanelAttribute', + instance: 'PanelInstance', + }, + { + name: 'Particle', + type: 'ParticleAttribute', + instance: 'ParticleInstance', + }, + { + name: 'Path', + type: 'PathAttribute', + instance: 'PathInstance', + }, + { + name: 'PatternLock', + type: 'PatternLockAttribute', + instance: 'PatternLockInstance', + }, + { + name: 'Piece', + type: 'PieceAttribute', + instance: 'PieceInstance', + }, + { + name: 'PluginComponent', + type: 'PluginComponentAttribute', + instance: 'PluginComponentInstance', + }, + { + name: 'Polygon', + type: 'PolygonAttribute', + instance: 'PolygonInstance', + }, + { + name: 'Polyline', + type: 'PolylineAttribute', + instance: 'PolylineInstance', + }, + { + name: 'Progress', + type: 'ProgressAttribute', + instance: 'ProgressInstance', + }, + { + name: 'QRCode', + type: 'QRCodeAttribute', + instance: 'QRCodeInstance', + }, + { + name: 'Radio', + type: 'RadioAttribute', + instance: 'RadioInstance', + }, + { + name: 'Rating', + type: 'RatingAttribute', + instance: 'RatingInstance', + }, + { + name: 'Rect', + type: 'RectAttribute', + instance: 'RectInstance', + }, + { + name: 'RelativeContainer', + type: 'RelativeContainerAttribute', + instance: 'RelativeContainerInstance', + }, + { + name: 'Refresh', + type: 'RefreshAttribute', + instance: 'RefreshInstance', + }, + { + name: 'RemoteWindow', + type: 'RemoteWindowAttribute', + instance: 'RemoteWindowInstance', + }, + { + name: 'RootScene', + type: 'RootSceneAttribute', + instance: 'RootSceneInstance', + }, + { + name: 'Row', + type: 'RowAttribute', + instance: 'RowInstance', + }, + { + name: 'RowSplit', + type: 'RowSplitAttribute', + instance: 'RowSplitInstance', + }, + { + name: 'RichText', + type: 'RichTextAttribute', + instance: 'RichTextInstance', + }, + { + name: 'Screen', + type: 'ScreenAttribute', + instance: 'ScreenInstance', + }, + { + name: 'Scroll', + type: 'ScrollAttribute', + instance: 'ScrollInstance', + }, + { + name: 'ScrollBar', + type: 'ScrollBarAttribute', + instance: 'ScrollBarInstance', + }, + { + name: 'Search', + type: 'SearchAttribute', + instance: 'SearchInstance', + }, + { + name: 'Section', + type: 'SectionAttribute', + instance: 'SectionInstance', + }, + { + name: 'Select', + type: 'SelectAttribute', + instance: 'SelectInstance', + }, + { + name: 'Shape', + type: 'ShapeAttribute', + instance: 'ShapeInstance', + }, + { + name: 'Sheet', + type: 'SheetAttribute', + instance: 'SheetInstance', + }, + { + name: 'SideBarContainer', + type: 'SideBarContainerAttribute', + instance: 'SideBarContainerInstance', + }, + { + name: 'Slider', + type: 'SliderAttribute', + instance: 'SliderInstance', + }, + { + name: 'Span', + type: 'SpanAttribute', + instance: 'SpanInstance', + }, + { + name: 'Stack', + type: 'StackAttribute', + instance: 'StackInstance', + }, + { + name: 'Stepper', + type: 'StepperAttribute', + instance: 'StepperInstance', + }, + { + name: 'StepperItem', + type: 'StepperItemAttribute', + instance: 'StepperItemInstance', + }, + { + name: 'Swiper', + type: 'SwiperAttribute', + instance: 'SwiperInstance', + }, + { + name: 'SymbolGlyph', + type: 'SymbolGlyphAttribute', + instance: 'SymbolGlyphInstance', + }, + { + name: 'SymbolSpan', + type: 'SymbolSpanAttribute', + instance: 'SymbolSpanInstance', + }, + { + name: 'TabContent', + type: 'TabContentAttribute', + instance: 'TabContentInstance', + }, + { + name: 'Tabs', + type: 'TabsAttribute', + instance: 'TabsInstance', + }, + { + name: 'Text', + type: 'TextAttribute', + instance: 'TextInstance', + }, + { + name: 'TextPicker', + type: 'TextPickerAttribute', + instance: 'TextPickerInstance', + }, + { + name: 'TextClock', + type: 'TextClockAttribute', + instance: 'TextClockInstance', + }, + { + name: 'TextArea', + type: 'TextAreaAttribute', + instance: 'TextAreaInstance', + }, + { + name: 'TextInput', + type: 'TextInputAttribute', + instance: 'TextInputInstance', + }, + { + name: 'TextTimer', + type: 'TextTimerAttribute', + instance: 'TextTimerInstance', + }, + { + name: 'TimePicker', + type: 'TimePickerAttribute', + instance: 'TimePickerInstance', + }, + { + name: 'Toggle', + type: 'ToggleAttribute', + instance: 'ToggleInstance', + }, + { + name: 'Video', + type: 'VideoAttribute', + instance: 'VideoInstance', + }, + { + name: 'Web', + type: 'WebAttribute', + instance: 'WebInstance', + }, + { + name: 'WindowScene', + type: 'WindowSceneAttribute', + instance: 'WindowSceneInstance', + }, + { + name: 'XComponent', + type: 'XComponentAttribute', + instance: 'XComponentInstance', + }, + { + name: 'GridRow', + type: 'GridRowAttribute', + instance: 'GridRowInstance', + }, + { + name: 'GridCol', + type: 'GridColAttribute', + instance: 'GridColInstance', + }, + { + name: 'WaterFlow', + type: 'WaterFlowAttribute', + instance: 'WaterFlowInstance', + }, + { + name: 'FlowItem', + type: 'FlowItemAttribute', + instance: 'FlowItemInstance', + }, + { + name: 'ImageSpan', + type: 'ImageSpanAttribute', + instance: 'ImageSpanInstance', + }, + { + name: 'LocationButton', + type: 'LocationButtonAttribute', + instance: 'LocationButtonInstance', + }, + { + name: 'PasteButton', + type: 'PasteButtonAttribute', + instance: 'PasteButtonInstance', + }, + { + name: 'SaveButton', + type: 'SaveButtonAttribute', + instance: 'SaveButtonInstance', + }, + { + name: 'UIExtensionComponent', + type: 'UIExtensionComponentAttribute', + instance: 'UIExtensionComponentInstance', + }, + { + name: 'IsolatedComponent', + type: 'IsolatedComponentAttribute', + instance: 'IsolatedComponentInstance', + }, + { + name: 'RichEditor', + type: 'RichEditorAttribute', + instance: 'RichEditorInstance', + }, + { + name: 'Component3D', + type: 'Component3DAttribute', + instance: 'Component3DInstance', + }, + { + name: 'ContainerSpan', + type: 'ContainerSpanAttribute', + instance: 'ContainerSpanInstance', + }, + ], + }, + styles: { + decorator: 'Styles', + component: { + name: 'Common', + type: 'T', + instance: 'CommonInstance', + }, + property: 'stateStyles', + }, + concurrent: { + decorator: 'Concurrent', + }, + customComponent: 'CustomComponent', + syntaxComponents: { + paramsUICallback: ['ForEach', 'LazyForEach'], + attrUICallback: [ + { + name: 'Repeat', + attributes: ['each', 'template'], + }, + ], + }, + libs: [], + }, +}; + +export const COMPONENT_FOR_EACH: string = 'ForEach'; +export const COMPONENT_LAZY_FOR_EACH: string = 'LazyForEach'; + +export const BUILDIN_SYSTEM_COMPONENT: Set = new Set([ + ...ETS_COMPILER_OPTIONS.ets.components, + COMPONENT_FOR_EACH, + COMPONENT_LAZY_FOR_EACH, +]); + +export const BUILDIN_ATOMIC_COMPONENT: Set = new Set([ + 'AbilityComponent', + 'AlphabetIndexer', + 'Animator', + 'Blank', + 'CalendarPicker', + 'Camera', + 'Circle', + 'Component3D', + 'ContentSlot', + 'Divider', + 'Ellipse', + 'EmbeddedComponent', + 'FormComponent', + 'FrictionMotion', + 'GeometryView', + 'Image', + 'ImageAnimator', + 'ImageSpan', + 'Line', + 'LoadingProgress', + 'LocationButton', + 'Marquee', + 'MediaCachedImage', + 'NodeContainer', + 'PageTransitionEnter', + 'PageTransitionExit', + 'Particle', + 'PasteButton', + 'Path', + 'PatternLock', + 'Polygon', + 'Polyline', + 'Progress', + 'Radio', + 'Rect', + 'RemoteWindow', + 'RichEditor', + 'RichText', + 'SaveButton', + 'ScrollMotion', + 'Search', + 'Slider', + 'Span', + 'SpringMotion', + 'SpringProp', + 'SymbolSpan', + 'SymbolGlyph', + 'TextArea', + 'TextInput', + 'UIExtensionComponent', + 'Video', + 'Web', +]); + +export const COMPONENT_DECORATOR: Set = new Set(['Reusable', 'Component', 'ComponentV2', 'CustomDialog']); +export const ENTRY_DECORATOR: string = 'Entry'; +export const BUILDER_DECORATOR: string = 'Builder'; +export const BUILDER_PARAM_DECORATOR: string = 'BuilderParam'; + +export function isEtsAtomicComponent(name: string): boolean { + return BUILDIN_ATOMIC_COMPONENT.has(name); +} + +export function isEtsSystemComponent(name: string): boolean { + return BUILDIN_SYSTEM_COMPONENT.has(name); +} + +export function isEtsContainerComponent(name: string): boolean { + return isEtsSystemComponent(name) && !isEtsAtomicComponent(name); +} + +export const COMPONENT_CREATE_FUNCTION: string = 'create'; +export const COMPONENT_POP_FUNCTION: string = 'pop'; +export const COMPONENT_CUSTOMVIEW: string = 'View'; +export const COMPONENT_REPEAT: string = 'Repeat'; + +export const COMPONENT_IF: string = 'If'; +export const COMPONENT_IF_BRANCH: string = 'IfBranch'; +export const COMPONENT_BRANCH_FUNCTION: string = 'branch'; +export const COMPONENT_BUILD_FUNCTION: string = 'build'; + +export const SPECIAL_CONTAINER_COMPONENT: Set = new Set([ + COMPONENT_IF, + COMPONENT_IF_BRANCH, + COMPONENT_CUSTOMVIEW, + COMPONENT_REPEAT, +]); + + +export const COMPONENT_COMMON: string = 'Common'; +export const COMPONENT_INSTANCE: string = 'Instance'; + +export const COMPONENT_ATTRIBUTE: string = 'Attribute'; +export const CALL_BACK: string = 'Callback'; +export const ON_OFF: Set = new Set(['on', 'off']); + +export const OH_PACKAGE_JSON5 = 'oh-package.json5'; +export const BUILD_PROFILE_JSON5 = 'build-profile.json5'; \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/common/ExprUseReplacer.ts b/ets2panda/linter/arkanalyzer/src/core/common/ExprUseReplacer.ts new file mode 100644 index 0000000000..3603b3bc51 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/common/ExprUseReplacer.ts @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + AbstractBinopExpr, + AbstractExpr, + AbstractInvokeExpr, + ArkAwaitExpr, + ArkCastExpr, + ArkDeleteExpr, + ArkInstanceInvokeExpr, + ArkInstanceOfExpr, + ArkNewArrayExpr, + ArkPtrInvokeExpr, + ArkTypeOfExpr, + ArkUnopExpr, + ArkYieldExpr, +} from '../base/Expr'; +import { Local } from '../base/Local'; +import { Value } from '../base/Value'; +import { AbstractFieldRef } from '../base/Ref'; + +/** + * Replace old use of a Expr inplace + */ +export class ExprUseReplacer { + private oldUse: Value; + private newUse: Value; + + constructor(oldUse: Value, newUse: Value) { + this.oldUse = oldUse + this.newUse = newUse; + } + + public caseExpr(expr: AbstractExpr): void { + if (expr instanceof AbstractBinopExpr) { + this.caseBinopExpr(expr); + } else if (expr instanceof AbstractInvokeExpr) { + this.caseInvokeExpr(expr); + } else if (expr instanceof ArkNewArrayExpr) { + this.caseNewArrayExpr(expr); + } else if (expr instanceof ArkTypeOfExpr) { + this.caseTypeOfExpr(expr); + } else if (expr instanceof ArkInstanceOfExpr) { + this.caseInstanceOfExpr(expr); + } else if (expr instanceof ArkCastExpr) { + this.caseCastExpr(expr); + } else if (expr instanceof ArkAwaitExpr) { + this.caseAwaitExpr(expr); + } else if (expr instanceof ArkYieldExpr) { + this.caseYieldExpr(expr); + } else if (expr instanceof ArkDeleteExpr) { + this.caseDeleteExpr(expr); + } else if (expr instanceof ArkUnopExpr) { + this.caseUnopExpr(expr); + } + } + + private caseBinopExpr(expr: AbstractBinopExpr): void { + if (expr.getOp1() === this.oldUse) { + expr.setOp1(this.newUse); + } + if (expr.getOp2() === this.oldUse) { + expr.setOp2(this.newUse); + } + } + + private caseInvokeExpr(expr: AbstractInvokeExpr): void { + let args = expr.getArgs(); + for (let i = 0; i < args.length; i++) { + if (args[i] === this.oldUse) { + args[i] = this.newUse; + } + } + + if (expr instanceof ArkInstanceInvokeExpr && expr.getBase() === this.oldUse) { + expr.setBase(this.newUse); + } else if (expr instanceof ArkPtrInvokeExpr && expr.getFuncPtrLocal() === this.oldUse && this.newUse instanceof Local) { + expr.setFunPtrLocal(this.newUse); + } + } + + private caseNewArrayExpr(expr: ArkNewArrayExpr): void { + if (expr.getSize() === this.oldUse) { + expr.setSize(this.newUse); + } + } + + private caseTypeOfExpr(expr: ArkTypeOfExpr): void { + if (expr.getOp() === this.oldUse) { + expr.setOp(this.newUse); + } + } + + private caseInstanceOfExpr(expr: ArkInstanceOfExpr): void { + if (expr.getOp() === this.oldUse) { + expr.setOp(this.newUse); + } + } + + private caseCastExpr(expr: ArkCastExpr): void { + if (expr.getOp() === this.oldUse) { + expr.setOp(this.newUse); + } + } + + private caseAwaitExpr(expr: ArkAwaitExpr): void { + if (expr.getPromise() === this.oldUse) { + expr.setPromise(this.newUse); + } + } + + private caseDeleteExpr(expr: ArkDeleteExpr): void { + if (expr.getField() === this.oldUse && this.newUse instanceof AbstractFieldRef) { + expr.setField(this.newUse); + } + } + + private caseYieldExpr(expr: ArkYieldExpr): void { + if (expr.getYieldValue() === this.oldUse) { + expr.setYieldValue(this.newUse); + } + } + + private caseUnopExpr(expr: ArkUnopExpr): void { + if (expr.getOp() === this.oldUse) { + expr.setOp(this.newUse); + } + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/common/IRInference.ts b/ets2panda/linter/arkanalyzer/src/core/common/IRInference.ts new file mode 100644 index 0000000000..44f222faa0 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/common/IRInference.ts @@ -0,0 +1,809 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ArkMethod } from '../model/ArkMethod'; +import { + AliasType, + AnnotationNamespaceType, + AnyType, + ArrayType, + ClassType, + FunctionType, + GenericType, + LexicalEnvType, + NullType, + Type, + UnclearReferenceType, + UndefinedType, + UnionType, + UnknownType, +} from '../base/Type'; +import { Local } from '../base/Local'; +import { TypeInference } from './TypeInference'; +import { + AbstractExpr, + AbstractInvokeExpr, + AliasTypeExpr, + ArkInstanceInvokeExpr, + ArkPtrInvokeExpr, + ArkStaticInvokeExpr +} from '../base/Expr'; +import Logger, { LOG_MODULE_TYPE } from '../../utils/logger'; +import { Scene } from '../../Scene'; +import { ArkClass } from '../model/ArkClass'; +import { findArkExport, ModelUtils } from './ModelUtils'; +import { ArkField } from '../model/ArkField'; +import { CALL_BACK } from './EtsConst'; +import { + AliasClassSignature, + BaseSignature, + ClassSignature, + FieldSignature, + MethodSignature, + MethodSubSignature +} from '../model/ArkSignature'; +import { CONSTRUCTOR_NAME, FUNCTION, IMPORT, SUPER_NAME, THIS_NAME } from './TSConst'; +import { Builtin } from './Builtin'; +import { ArkBody } from '../model/ArkBody'; +import { ArkAssignStmt, ArkInvokeStmt } from '../base/Stmt'; +import { + AbstractFieldRef, + AbstractRef, + ArkArrayRef, + ArkInstanceFieldRef, + ArkParameterRef, + ArkStaticFieldRef +} from '../base/Ref'; +import { Value } from '../base/Value'; +import { Constant } from '../base/Constant'; +import { + ANONYMOUS_CLASS_PREFIX, + CALL_SIGNATURE_NAME, + DEFAULT_ARK_CLASS_NAME, + NAME_DELIMITER, + NAME_PREFIX, + UNKNOWN_CLASS_NAME +} from './Const'; +import { ValueUtil } from './ValueUtil'; +import { ArkFile } from '../model/ArkFile'; +import { AbstractTypeExpr, KeyofTypeExpr, TypeQueryExpr } from '../base/TypeExpr'; +import { ArkBaseModel } from '../model/ArkBaseModel'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'IRInference'); + +export class IRInference { + + private static inferExportInfos(file: ArkFile): void { + file.getExportInfos().forEach(exportInfo => { + if (exportInfo.getArkExport() === undefined) { + let arkExport = findArkExport(exportInfo); + exportInfo.setArkExport(arkExport); + if (arkExport) { + exportInfo.setExportClauseType(arkExport.getExportType()); + } + } + }); + } + + private static inferImportInfos(file: ArkFile): void { + file.getImportInfos().forEach(importInfo => { + importInfo.getLazyExportInfo(); + }); + } + + public static inferFile(file: ArkFile): void { + this.inferImportInfos(file); + ModelUtils.getAllClassesInFile(file).forEach(arkClass => { + TypeInference.inferGenericType(arkClass.getGenericsTypes(), arkClass); + const defaultArkMethod = arkClass.getDefaultArkMethod(); + if (defaultArkMethod) { + TypeInference.inferTypeInMethod(defaultArkMethod); + } + arkClass.getFields().forEach(arkField => TypeInference.inferTypeInArkField(arkField)); + const methods = arkClass.getMethods().sort((a, b) => { + const name = a.getName().split(NAME_DELIMITER).reverse().join(); + const anotherName = b.getName().split(NAME_DELIMITER).reverse().join(); + if (name.startsWith(anotherName)) { + return 1; + } else if (anotherName.startsWith(name)) { + return -1; + } + return 0; + }); + methods.forEach(arkMethod => TypeInference.inferTypeInMethod(arkMethod)); + }); + this.inferExportInfos(file); + } + + public static inferStaticInvokeExpr(expr: ArkStaticInvokeExpr, arkMethod: ArkMethod): AbstractInvokeExpr { + const arkClass = arkMethod.getDeclaringArkClass(); + const methodName = expr.getMethodSignature().getMethodSubSignature().getMethodName(); + if (methodName === IMPORT) { + const arg = expr.getArg(0); + let type; + if (arg instanceof Constant) { + type = TypeInference.inferDynamicImportType(arg.getValue(), arkClass); + } + if (type) { + expr.getMethodSignature().getMethodSubSignature().setReturnType(type); + } + return expr; + } + expr.getArgs().forEach(arg => TypeInference.inferValueType(arg, arkMethod)); + if (methodName === SUPER_NAME) { + const superClass = arkClass.getSuperClass(); + if (superClass !== null) { + const newMethodSignature = new MethodSignature(superClass.getSignature(), expr.getMethodSignature().getMethodSubSignature()); + expr.setMethodSignature(newMethodSignature); + } + return expr; + } + const className = expr.getMethodSignature().getDeclaringClassSignature().getClassName(); + if (className && className !== UNKNOWN_CLASS_NAME) { + const baseType = TypeInference.inferUnclearRefName(className, arkClass); + if (baseType) { + let result = this.inferInvokeExpr(expr, baseType, methodName, arkClass.getDeclaringArkFile().getScene()); + if (result) { + this.inferArgs(result, arkMethod); + return result; + } + } + return expr; + } + return this.inferStaticInvokeExprByMethodName(methodName, arkMethod, expr); + } + + private static inferStaticInvokeExprByMethodName(methodName: string, arkMethod: ArkMethod, expr: AbstractInvokeExpr): AbstractInvokeExpr { + const arkClass = arkMethod.getDeclaringArkClass(); + const arkExport = ModelUtils.getStaticMethodWithName(methodName, arkClass) ?? + arkMethod.getFunctionLocal(methodName) ?? + ModelUtils.findDeclaredLocal(new Local(methodName), arkMethod) ?? + ModelUtils.getArkExportInImportInfoWithName(methodName, arkClass.getDeclaringArkFile()) ?? + arkClass.getDeclaringArkFile().getScene().getSdkGlobal(methodName); + let method; + let signature; + if (arkExport instanceof ArkMethod) { + method = arkExport; + } else if (arkExport instanceof ArkClass) { + method = arkExport.getMethodWithName(CONSTRUCTOR_NAME); + } else if (arkExport instanceof Local) { + const type = arkExport.getType(); + if (type instanceof ClassType) { + const cls = arkClass.getDeclaringArkFile().getScene().getClass(type.getClassSignature()); + method = cls?.getMethodWithName(CONSTRUCTOR_NAME) ?? cls?.getMethodWithName(CALL_SIGNATURE_NAME); + } else if (type instanceof FunctionType) { + signature = type.getMethodSignature(); + } + } else if (arkExport instanceof AliasType && arkExport.getOriginalType() instanceof FunctionType) { + signature = (arkExport.getOriginalType() as FunctionType).getMethodSignature(); + } + if (method) { + signature = method.matchMethodSignature(expr.getArgs()); + TypeInference.inferSignatureReturnType(signature, method); + } + if (signature) { + if (arkExport instanceof Local) { + expr = new ArkPtrInvokeExpr(signature, arkExport, expr.getArgs(), expr.getRealGenericTypes()); + } else { + expr.setMethodSignature(signature); + } + this.inferArgs(expr, arkMethod); + } + return expr; + } + + public static inferInstanceInvokeExpr(expr: ArkInstanceInvokeExpr, arkMethod: ArkMethod): AbstractInvokeExpr { + const arkClass = arkMethod.getDeclaringArkClass(); + TypeInference.inferRealGenericTypes(expr.getRealGenericTypes(), arkClass); + this.inferBase(expr, arkMethod); + + const baseType: Type = TypeInference.replaceAliasType(expr.getBase().getType()); + let methodName = expr.getMethodSignature().getMethodSubSignature().getMethodName(); + if (methodName.startsWith(NAME_PREFIX)) { + const declaringStmt = arkMethod.getBody()?.getLocals().get(methodName)?.getDeclaringStmt(); + if (declaringStmt instanceof ArkAssignStmt && declaringStmt.getRightOp() instanceof ArkInstanceFieldRef) { + const rightOp = declaringStmt.getRightOp() as ArkInstanceFieldRef; + methodName = rightOp.getBase().getName() + '.' + rightOp.getFieldName(); + } + } + const scene = arkClass.getDeclaringArkFile().getScene(); + if ((methodName === 'forEach') && (baseType instanceof ArrayType)) { + this.processForEach(expr.getArg(0), baseType, scene); + return expr; + } + expr.getArgs().forEach(arg => TypeInference.inferValueType(arg, arkMethod)); + let result = this.inferInvokeExpr(expr, baseType, methodName, scene) ?? + this.processExtendFunc(expr, arkMethod, methodName); + if (result) { + this.inferArgs(result, arkMethod); + return result; + } + logger.warn('invoke ArkInstanceInvokeExpr MethodSignature type fail: ', expr.toString()); + return expr; + } + + /** + * process arkUI function with Annotation @Extend @Styles @AnimatableExtend + * @param expr + * @param arkMethod + * @param methodName + */ + private static processExtendFunc(expr: AbstractInvokeExpr, arkMethod: ArkMethod, methodName: string): AbstractInvokeExpr | null { + const type = TypeInference.inferBaseType(methodName, arkMethod.getDeclaringArkClass()); + if (type instanceof FunctionType) { + const methodSignature = type.getMethodSignature(); + // because of last stmt is ArkReturnVoidStmt, the ArkInvokeStmt at -2 before ArkReturnVoidStmt. + const endIndex = -2; + const endStmt = arkMethod.getDeclaringArkFile().getScene().getMethod(methodSignature)?.getCfg()?.getStmts().at(endIndex); + if (endStmt instanceof ArkInvokeStmt) { + methodSignature.getMethodSubSignature().setReturnType(endStmt.getInvokeExpr().getType()); + } + expr.setMethodSignature(methodSignature); + return expr; + } + return null; + } + + public static inferFieldRef(ref: ArkInstanceFieldRef, arkMethod: ArkMethod): AbstractRef { + this.inferBase(ref, arkMethod); + const baseType: Type = TypeInference.replaceAliasType(ref.getBase().getType()); + if (baseType instanceof ArrayType && ref.getFieldName() !== 'length') { + return new ArkArrayRef(ref.getBase(), ValueUtil.createConst(ref.getFieldName())); + } + + let newFieldSignature = this.generateNewFieldSignature(ref, arkMethod.getDeclaringArkClass(), baseType); + if (newFieldSignature) { + if (newFieldSignature.isStatic()) { + return new ArkStaticFieldRef(newFieldSignature); + } + ref.setFieldSignature(newFieldSignature); + } + return ref; + } + + private static inferBase(instance: ArkInstanceFieldRef | ArkInstanceInvokeExpr, arkMethod: ArkMethod): void { + const base = instance.getBase(); + if (base.getName() === THIS_NAME) { + let newBase = this.inferThisLocal(arkMethod); + if (newBase) { + instance.setBase(newBase); + } + } else { + this.inferLocal(instance.getBase(), arkMethod); + } + } + + public static inferThisLocal(arkMethod: ArkMethod): Local | null { + const arkClass = arkMethod.getDeclaringArkClass(); + if (!arkClass.isAnonymousClass()) { + return null; + } + + const value = arkMethod.getBody()?.getUsedGlobals()?.get(THIS_NAME); + if (value instanceof Local) { + return value; + } else { + const thisType = TypeInference.inferBaseType(arkClass.getSignature().getDeclaringClassName(), arkClass); + if (thisType instanceof ClassType) { + const newBase = new Local(THIS_NAME, thisType); + let usedGlobals = arkMethod.getBody()?.getUsedGlobals(); + if (!usedGlobals) { + usedGlobals = new Map(); + arkMethod.getBody()?.setUsedGlobals(usedGlobals); + } + usedGlobals.set(THIS_NAME, newBase); + return newBase; + } + } + return null; + } + + private static inferArgs(expr: AbstractInvokeExpr, arkMethod: ArkMethod): void { + const scene = arkMethod.getDeclaringArkFile().getScene(); + const parameters = expr.getMethodSignature().getMethodSubSignature().getParameters(); + let realTypes: Type[] = []; + const len = expr.getArgs().length; + for (let index = 0; index < len; index++) { + const arg = expr.getArg(index); + if (index >= parameters.length) { + break; + } + const argType = arg.getType(); + const paramType = parameters[index].getType(); + this.inferArg(expr, argType, paramType, scene, realTypes); + } + if (realTypes.length > 0 && !expr.getRealGenericTypes()) { + expr.setRealGenericTypes(realTypes); + } + } + + private static inferArg(expr: AbstractInvokeExpr, argType: Type, paramType: Type, scene: Scene, realTypes: Type[]): void { + if (paramType instanceof UnionType) { + paramType.getTypes().forEach(t => this.inferArg(expr, argType, t, scene, realTypes)); + } else if (paramType instanceof AliasType) { + this.inferArg(expr, argType, paramType.getOriginalType(), scene, realTypes); + } else if (paramType instanceof ArrayType && argType instanceof ArrayType) { + this.inferArg(expr, argType.getBaseType(), paramType.getBaseType(), scene, realTypes); + } else if (expr instanceof ArkInstanceInvokeExpr && expr.getBase().getType() instanceof ArrayType) { + if (paramType instanceof ArrayType && paramType.getBaseType() instanceof GenericType) { + this.inferArg(expr, argType, (expr.getBase().getType() as ArrayType).getBaseType(), scene, realTypes); + } + } + + if (paramType instanceof ClassType && scene.getProjectSdkMap().has(paramType.getClassSignature() + .getDeclaringFileSignature().getProjectName())) { + this.inferArgTypeWithSdk(paramType, scene, argType); + } else if (paramType instanceof GenericType || paramType instanceof AnyType) { + realTypes.push(argType); + } else if (paramType instanceof FunctionType && argType instanceof FunctionType) { + const method = scene.getMethod(argType.getMethodSignature()); + if (method) { + TypeInference.inferTypeInMethod(method); + } + const realTypes = expr.getRealGenericTypes(); + TypeInference.inferFunctionType(argType, paramType.getMethodSignature().getMethodSubSignature(), realTypes); + } + } + + public static inferRightWithSdkType(leftType: Type, rightType: Type, ackClass: ArkClass): void { + if (leftType instanceof AliasType) { + this.inferRightWithSdkType(TypeInference.replaceAliasType(leftType), rightType, ackClass); + } else if (leftType instanceof UnionType) { + leftType.getTypes().forEach(t => this.inferRightWithSdkType(t, rightType, ackClass)); + } else if (leftType instanceof ClassType) { + IRInference.inferArgTypeWithSdk(leftType, ackClass.getDeclaringArkFile().getScene(), rightType); + } else if (rightType instanceof ArrayType && leftType instanceof ArrayType) { + const baseType = TypeInference.replaceAliasType(leftType.getBaseType()); + if (baseType instanceof ClassType) { + IRInference.inferArgTypeWithSdk(baseType, ackClass.getDeclaringArkFile().getScene(), rightType.getBaseType()); + } + } + } + + public static inferArgTypeWithSdk(sdkType: ClassType, scene: Scene, argType: Type): void { + if (!scene.getProjectSdkMap().has(sdkType.getClassSignature().getDeclaringFileSignature().getProjectName())) { + return; + } + if (argType instanceof UnionType) { + argType.getTypes().forEach(t => this.inferArgTypeWithSdk(sdkType, scene, t)); + } else if (argType instanceof ClassType && argType.getClassSignature().getClassName().startsWith(ANONYMOUS_CLASS_PREFIX)) { + this.inferAnonymousClass(scene.getClass(argType.getClassSignature()), sdkType.getClassSignature()); + } else if (argType instanceof FunctionType) { + const param = scene.getClass(sdkType.getClassSignature()) + ?.getMethodWithName(CALL_SIGNATURE_NAME)?.getSignature().getMethodSubSignature(); + const realTypes = sdkType.getRealGenericTypes(); + TypeInference.inferFunctionType(argType, param, realTypes); + } + } + + + private static inferInvokeExpr(expr: AbstractInvokeExpr, baseType: Type, methodName: string, scene: Scene): AbstractInvokeExpr | null { + if (baseType instanceof AliasType) { + return this.inferInvokeExpr(expr, baseType.getOriginalType(), methodName, scene); + } else if (baseType instanceof UnionType) { + for (let type of baseType.flatType()) { + if (type instanceof UndefinedType || type instanceof NullType) { + continue; + } + let result = this.inferInvokeExpr(expr, type, methodName, scene); + if (result) { + return result; + } + } + } + if (baseType instanceof ClassType) { + return this.inferInvokeExprWithDeclaredClass(expr, baseType, methodName, scene); + } else if (baseType instanceof AnnotationNamespaceType) { + const namespace = scene.getNamespace(baseType.getNamespaceSignature()); + if (namespace) { + const foundMethod = ModelUtils.findPropertyInNamespace(methodName, namespace); + if (foundMethod instanceof ArkMethod) { + let signature = foundMethod.matchMethodSignature(expr.getArgs()); + TypeInference.inferSignatureReturnType(signature, foundMethod); + expr.setMethodSignature(signature); + return expr instanceof ArkInstanceInvokeExpr ? + new ArkStaticInvokeExpr(signature, expr.getArgs(), expr.getRealGenericTypes()) : expr; + } + } + } else if (baseType instanceof FunctionType) { + return IRInference.inferInvokeExprWithFunction(methodName, expr, baseType, scene); + } else if (baseType instanceof ArrayType) { + return IRInference.inferInvokeExprWithArray(methodName, expr, baseType, scene); + } + return null; + } + + private static inferInvokeExprWithArray(methodName: string, expr: AbstractInvokeExpr, baseType: ArrayType, scene: Scene): AbstractInvokeExpr | null { + if (methodName === Builtin.ITERATOR_FUNCTION) { + const returnType = expr.getMethodSignature().getMethodSubSignature().getReturnType(); + if (returnType instanceof ClassType && returnType.getClassSignature().getDeclaringFileSignature() + .getProjectName() === Builtin.DUMMY_PROJECT_NAME) { + expr.setRealGenericTypes([baseType.getBaseType()]); + return expr; + } + } else { + const arrayInterface = scene.getSdkGlobal(Builtin.ARRAY); + if (arrayInterface instanceof ArkClass) { + return this.inferInvokeExpr(expr, new ClassType(arrayInterface.getSignature(), [baseType.getBaseType()]), methodName, scene); + } + } + return null; + } + + private static inferInvokeExprWithFunction(methodName: string, expr: AbstractInvokeExpr, baseType: FunctionType, scene: Scene): AbstractInvokeExpr | null { + if (methodName === CALL_SIGNATURE_NAME) { + expr.setMethodSignature(baseType.getMethodSignature()); + return expr; + } + const funcInterface = scene.getSdkGlobal(FUNCTION); + if (funcInterface instanceof ArkClass) { + const method = ModelUtils.findPropertyInClass(methodName, funcInterface); + if (method instanceof ArkMethod) { + expr.setRealGenericTypes([baseType]); + expr.setMethodSignature(method.getSignature()); + return expr; + } + } + return null; + } + + private static inferInvokeExprWithDeclaredClass(expr: AbstractInvokeExpr, baseType: ClassType, methodName: string, + scene: Scene): AbstractInvokeExpr | null { + if (Builtin.isBuiltinClass(baseType.getClassSignature().getClassName())) { + expr.setMethodSignature(new MethodSignature(baseType.getClassSignature(), expr.getMethodSignature().getMethodSubSignature())); + } + let declaredClass = scene.getClass(baseType.getClassSignature()); + if (!declaredClass) { + const globalClass = scene.getSdkGlobal(baseType.getClassSignature().getClassName()); + if (globalClass instanceof ArkClass) { + declaredClass = globalClass; + } + } + const method = declaredClass ? ModelUtils.findPropertyInClass(methodName, declaredClass) : null; + if (method instanceof ArkMethod) { + const methodSignature = method.matchMethodSignature(expr.getArgs()); + TypeInference.inferSignatureReturnType(methodSignature, method); + expr.setMethodSignature(this.replaceMethodSignature(expr.getMethodSignature(), methodSignature)); + expr.setRealGenericTypes(IRInference.getRealTypes(method, declaredClass, baseType)); + if (method.isStatic() && expr instanceof ArkInstanceInvokeExpr) { + return new ArkStaticInvokeExpr(methodSignature, expr.getArgs(), expr.getRealGenericTypes()); + } + return expr; + } else if (method instanceof ArkField) { + const type = method.getType(); + let methodSignature; + if (type instanceof FunctionType) { + methodSignature = type.getMethodSignature(); + } else if (type instanceof ClassType && type.getClassSignature().getClassName().endsWith(CALL_BACK)) { + const callback = scene.getClass(type.getClassSignature())?.getMethodWithName(CALL_SIGNATURE_NAME); + if (callback) { + methodSignature = callback.getSignature(); + } + } + if (methodSignature) { + const ptr = expr instanceof ArkInstanceInvokeExpr ? + new ArkInstanceFieldRef(expr.getBase(), method.getSignature()) : new ArkStaticFieldRef(method.getSignature()); + expr = new ArkPtrInvokeExpr(methodSignature, ptr, expr.getArgs(), expr.getRealGenericTypes()); + } + return expr; + } else if (methodName === CONSTRUCTOR_NAME) { //sdk隐式构造 + const subSignature = new MethodSubSignature(methodName, [], new ClassType(baseType.getClassSignature())); + expr.setMethodSignature(new MethodSignature(baseType.getClassSignature(), subSignature)); + return expr; + } else if (methodName === Builtin.ITERATOR_NEXT) { //sdk隐式构造 + const returnType = expr.getMethodSignature().getMethodSubSignature().getReturnType(); + if (returnType instanceof ClassType && returnType.getClassSignature().getDeclaringFileSignature().getProjectName() === Builtin.DUMMY_PROJECT_NAME) { + returnType.setRealGenericTypes(baseType.getRealGenericTypes()); + return expr; + } + } + return null; + } + + private static getRealTypes(method: ArkMethod, declaredClass: ArkClass | null, baseType: ClassType): Type[] | undefined { + let realTypes; + if (method.getDeclaringArkClass() === declaredClass) { + realTypes = baseType.getRealGenericTypes(); + } else if (declaredClass?.getRealTypes()) { + realTypes = declaredClass?.getRealTypes(); + } else if (declaredClass?.hasComponentDecorator()) { + realTypes = [new ClassType(declaredClass?.getSignature())]; + } + return realTypes; + } + + public static replaceMethodSignature(init: MethodSignature, declared: MethodSignature): MethodSignature { + const className = init.getDeclaringClassSignature().getClassName(); + let classSignature; + if (declared.getDeclaringClassSignature().getClassName().endsWith('Interface')) { + classSignature = new AliasClassSignature(className, declared.getDeclaringClassSignature()); + } + let newSubSignature; + if (classSignature || newSubSignature) { + return new MethodSignature(classSignature ?? declared.getDeclaringClassSignature(), + newSubSignature ?? declared.getMethodSubSignature()); + } + return declared; + } + + private static processForEach(arg: Value, baseType: ArrayType, scene: Scene): void { + const argType = arg.getType(); + if (argType instanceof FunctionType) { + const argMethodSignature = argType.getMethodSignature(); + const argMethod = scene.getMethod(argMethodSignature); + if (argMethod != null && argMethod.getBody()) { + const body = argMethod.getBody() as ArkBody; + const firstStmt = body.getCfg().getStartingStmt(); + if ((firstStmt instanceof ArkAssignStmt) && (firstStmt.getRightOp() instanceof ArkParameterRef)) { + const parameterRef = firstStmt.getRightOp() as ArkParameterRef; + parameterRef.setType(baseType.getBaseType()); + const argMethodParams = argMethod.getSignature().getMethodSubSignature().getParameters(); + const actualParam = argMethodParams[argMethodParams.length - 1]; + actualParam.setType(baseType.getBaseType()); + } + TypeInference.inferTypeInMethod(argMethod); + } + } else { + logger.warn(`arg of forEach must be callable`); + } + } + + public static inferLocal(base: Local, arkMethod: ArkMethod): void { + const arkClass = arkMethod.getDeclaringArkClass(); + let baseType: Type | null | undefined = base.getType(); + if (baseType instanceof UnclearReferenceType) { + baseType = TypeInference.inferUnclearRefName(baseType.getName(), arkClass); + } else if (TypeInference.isUnclearType(baseType)) { + const declaringStmt = base.getDeclaringStmt(); + if (!declaringStmt || !declaringStmt.getOriginalText() || declaringStmt.getOriginalText()?.startsWith(base.getName())) { + baseType = ModelUtils.findDeclaredLocal(base, arkMethod)?.getType() ?? TypeInference.inferBaseType(base.getName(), arkClass); + } + } + if (baseType instanceof UnionType || (baseType && !TypeInference.isUnclearType(baseType))) { + base.setType(baseType); + } + } + + private static generateNewFieldSignature(ref: AbstractFieldRef, arkClass: ArkClass, baseType: Type): FieldSignature | null { + if (baseType instanceof UnionType) { + for (let type of baseType.flatType()) { + if (type instanceof UndefinedType || type instanceof NullType) { + continue; + } + let newFieldSignature = this.generateNewFieldSignature(ref, arkClass, type); + if (!TypeInference.isUnclearType(newFieldSignature?.getType())) { + return newFieldSignature; + } + } + return null; + } else if (baseType instanceof AliasType) { + return this.generateNewFieldSignature(ref, arkClass, baseType.getOriginalType()); + } + const fieldName = ref.getFieldName().replace(/[\"|\']/g, ''); + const propertyAndType = TypeInference.inferFieldType(baseType, fieldName, arkClass); + let propertyType = propertyAndType?.[1]; + if (!propertyType) { + const newType = TypeInference.inferUnclearRefName(fieldName, arkClass); + if (newType) { + propertyType = newType; + } + } else if (TypeInference.isUnclearType(propertyType)) { + const newType = TypeInference.inferUnclearedType(propertyType, arkClass); + if (newType) { + propertyType = newType; + } + } + let staticFlag: boolean; + let signature: BaseSignature; + if (baseType instanceof ClassType) { + const property = propertyAndType?.[0]; + if (property instanceof ArkField) { + return property.getSignature(); + } + staticFlag = baseType.getClassSignature().getClassName() === DEFAULT_ARK_CLASS_NAME || + (property instanceof ArkMethod && property.isStatic()); + signature = property instanceof ArkMethod ? property.getSignature().getDeclaringClassSignature() : baseType.getClassSignature(); + } else if (baseType instanceof AnnotationNamespaceType) { + staticFlag = true; + signature = baseType.getNamespaceSignature(); + } else { + return null; + } + return new FieldSignature(fieldName, signature, propertyType ?? ref.getType(), staticFlag); + } + + + public static inferAnonymousClass(anon: ArkClass | null, declaredSignature: ClassSignature, set: Set = new Set()): void { + if (!anon) { + return; + } + const key = anon.getSignature().toString(); + if (set.has(key)) { + return; + } else { + set.add(key); + } + const scene = anon.getDeclaringArkFile().getScene(); + const declaredClass = scene.getClass(declaredSignature); + if (!declaredClass) { + return; + } + for (const anonField of anon.getFields()) { + const property = ModelUtils.findPropertyInClass(anonField.getName(), declaredClass); + if (property instanceof ArkField) { + this.assignAnonField(property, anonField, scene, set); + } else if (property instanceof ArkMethod) { + const type = anonField.getType(); + if (type instanceof FunctionType) { + this.assignAnonMethod(scene.getMethod(type.getMethodSignature()), property); + } + anonField.setSignature(new FieldSignature(anonField.getName(), + property.getDeclaringArkClass().getSignature(), new FunctionType(property.getSignature()))); + } + } + for (const anonMethod of anon.getMethods()) { + this.assignAnonMethod(anonMethod, declaredClass.getMethodWithName(anonMethod.getName())); + } + } + + + private static assignAnonMethod(anonMethod: ArkMethod | null, declaredMethod: ArkMethod | null): void { + if (declaredMethod && anonMethod) { + anonMethod.setImplementationSignature(declaredMethod.matchMethodSignature(anonMethod.getSubSignature().getParameters())); + } + } + + private static assignAnonField(property: ArkField, anonField: ArkField, scene: Scene, set: Set): void { + function deepInfer(anonType: Type, declaredSignature: ClassSignature): void { + if (anonType instanceof ClassType && anonType.getClassSignature().getClassName().startsWith(ANONYMOUS_CLASS_PREFIX)) { + IRInference.inferAnonymousClass(scene.getClass(anonType.getClassSignature()), declaredSignature, set); + } + } + + const type = property.getSignature().getType(); + const lastStmt = anonField.getInitializer().at(-1); + if (lastStmt instanceof ArkAssignStmt) { + const rightType = lastStmt.getRightOp().getType(); + if (type instanceof ClassType) { + deepInfer(rightType, type.getClassSignature()); + } else if (type instanceof ArrayType && type.getBaseType() instanceof ClassType && + rightType instanceof ArrayType) { + const baseType = rightType.getBaseType(); + const classSignature = (type.getBaseType() as ClassType).getClassSignature(); + if (baseType instanceof UnionType) { + baseType.getTypes().forEach(t => deepInfer(t, classSignature)); + } else { + deepInfer(rightType.getBaseType(), classSignature); + } + } else if (type instanceof FunctionType && rightType instanceof FunctionType) { + TypeInference.inferFunctionType(rightType, type.getMethodSignature().getMethodSubSignature(), type.getRealGenericTypes()); + } + const leftOp = lastStmt.getLeftOp(); + if (leftOp instanceof AbstractFieldRef) { + leftOp.setFieldSignature(property.getSignature()); + } + } + anonField.setSignature(property.getSignature()); + } + + public static inferAliasTypeExpr(expr: AliasTypeExpr, arkMethod: ArkMethod): AbstractExpr { + const originalObject = expr.getOriginalObject(); + let model; + if (originalObject instanceof Local) { + model = ModelUtils.findArkModelByRefName(originalObject.getName(), arkMethod.getDeclaringArkClass()); + } else if (originalObject instanceof AbstractTypeExpr) { + originalObject.inferType(arkMethod); + model = originalObject; + } else if (originalObject instanceof Type) { + const type = TypeInference.inferUnclearedType(originalObject, arkMethod.getDeclaringArkClass()); + + // If original Object is ClassType, AliasType or UnclearReferenceType with real generic types, + // the type after infer should be revert back to the object itself. + if (type instanceof ClassType) { + const scene = arkMethod.getDeclaringArkFile().getScene(); + model = ModelUtils.findArkModelBySignature(type.getClassSignature(), scene); + } else if (type instanceof AliasType) { + const scene = arkMethod.getDeclaringArkFile().getScene(); + model = ModelUtils.findArkModelBySignature(type.getSignature(), scene); + } else if (type) { + model = type; + } + if (expr.getRealGenericTypes() !== undefined && originalObject instanceof UnclearReferenceType) { + expr.setRealGenericTypes(originalObject.getGenericTypes()); + } + } + + if (AliasTypeExpr.isAliasTypeOriginalModel(model)) { + expr.setOriginalObject(model); + } + return expr; + } + + public static inferTypeQueryExpr(expr: TypeQueryExpr, arkMethod: ArkMethod): void { + let gTypes = expr.getGenerateTypes(); + if (gTypes) { + for (let i = 0; i < gTypes.length; i++) { + const newType = TypeInference.inferUnclearedType(gTypes[i], arkMethod.getDeclaringArkClass()); + if (newType) { + gTypes[i] = newType; + } + } + } + + const opValue = expr.getOpValue(); + let opValueType; + if (opValue instanceof ArkBaseModel) { + opValueType = ModelUtils.parseArkBaseModel2Type(opValue) ?? UnknownType.getInstance(); + } else { + opValueType = opValue.getType(); + } + + if (!TypeInference.isUnclearType(opValueType)) { + return; + } + if (opValue instanceof Local) { + const newOpValueType = TypeInference.inferUnclearRefName(opValue.getName(), arkMethod.getDeclaringArkClass()); + const scene = arkMethod.getDeclaringArkFile().getScene(); + if (newOpValueType instanceof ClassType) { + const newOpValue = ModelUtils.findArkModelBySignature(newOpValueType.getClassSignature(), scene); + if (newOpValue instanceof ArkBaseModel) { + expr.setOpValue(newOpValue); + } + } else if (newOpValueType instanceof FunctionType) { + const newOpValue = ModelUtils.findArkModelBySignature(newOpValueType.getMethodSignature(), scene); + if (newOpValue instanceof ArkBaseModel) { + expr.setOpValue(newOpValue); + } + } else { + this.inferLocal(opValue, arkMethod); + } + } else if (opValue instanceof AbstractRef || opValue instanceof AbstractExpr) { + expr.setOpValue(opValue.inferType(arkMethod)); + } + } + + public static inferKeyofTypeExpr(expr: KeyofTypeExpr, arkMethod: ArkMethod): void { + const opType = expr.getOpType(); + if (TypeInference.isUnclearType(opType)) { + if (opType instanceof TypeQueryExpr) { + this.inferTypeQueryExpr(opType, arkMethod); + } else { + const type = TypeInference.inferUnclearedType(opType, arkMethod.getDeclaringArkClass()); + if (type) { + expr.setOpType(type); + } + } + } + } + + public static inferParameterRef(ref: ArkParameterRef, arkMethod: ArkMethod): AbstractRef { + const paramType = ref.getType(); + if (paramType instanceof UnknownType || paramType instanceof UnclearReferenceType) { + const type1 = arkMethod.getSignature().getMethodSubSignature().getParameters()[ref.getIndex()]?.getType(); + if (!TypeInference.isUnclearType(type1)) { + ref.setType(type1); + return ref; + } + } else if (paramType instanceof LexicalEnvType) { + paramType.getClosures().filter(c => TypeInference.isUnclearType(c.getType())) + .forEach(e => this.inferLocal(e, arkMethod)); + return ref; + } + let type = TypeInference.inferUnclearedType(paramType, arkMethod.getDeclaringArkClass()); + if (type) { + ref.setType(type); + } + return ref; + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/common/IRUtils.ts b/ets2panda/linter/arkanalyzer/src/core/common/IRUtils.ts new file mode 100644 index 0000000000..9af148f93b --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/common/IRUtils.ts @@ -0,0 +1,162 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { AbstractBinopExpr, AbstractInvokeExpr, ArkCastExpr, ArkUnopExpr } from '../base/Expr'; +import { AbstractFieldRef, AbstractRef, ArkArrayRef, ArkInstanceFieldRef, ArkStaticFieldRef } from '../base/Ref'; +import { Value } from '../base/Value'; +import { Scene } from '../../Scene'; +import ts from 'ohos-typescript'; +import { SceneOptions } from '../../Config'; +import { ArkMetadataKind, CommentItem, CommentsMetadata } from '../model/ArkMetadata'; +import { Stmt } from '../base/Stmt'; +import { ArkBaseModel } from '../model/ArkBaseModel'; +import { FullPosition } from '../base/Position'; +import { Local } from '../base/Local'; +import { NAME_PREFIX } from './Const'; + +export class IRUtils { + public static moreThanOneAddress(value: Value): boolean { + if ( + value instanceof AbstractBinopExpr || + value instanceof AbstractInvokeExpr || + value instanceof AbstractFieldRef || + value instanceof ArkArrayRef || + value instanceof ArkCastExpr || + value instanceof ArkUnopExpr + ) { + return true; + } + return false; + } + + public static generateTextForStmt(scene: Scene): void { + for (const method of scene.getMethods()) { + const cfg = method.getCfg(); + if (cfg) { + for (const stmt of cfg.getStmts()) { + stmt.setText(stmt.toString()); + } + } + } + } + + public static setComments(metadata: Stmt | ArkBaseModel, + node: ts.Node, + sourceFile: ts.SourceFile, + options: SceneOptions): void { + const leadingCommentsMetadata = this.getCommentsMetadata(node, sourceFile, options, true); + if (leadingCommentsMetadata.getComments().length > 0) { + metadata.setMetadata(ArkMetadataKind.LEADING_COMMENTS, leadingCommentsMetadata); + } + + const trailingCommentsMetadata = this.getCommentsMetadata(node, sourceFile, options, false); + if (trailingCommentsMetadata.getComments().length > 0) { + metadata.setMetadata(ArkMetadataKind.TRAILING_COMMENTS, trailingCommentsMetadata); + } + } + + public static getCommentsMetadata(node: ts.Node, sourceFile: ts.SourceFile, options: SceneOptions, + isLeading: boolean): CommentsMetadata { + const comments: CommentItem[] = []; + if ((isLeading && !options.enableLeadingComments) || (!isLeading && !options.enableTrailingComments)) { + return new CommentsMetadata(comments); + } + + const commentRanges = (isLeading ? ts.getLeadingCommentRanges(sourceFile.text, node.pos) + : ts.getTrailingCommentRanges(sourceFile.text, node.end)) || []; // node.pos is the start position of + // leading comment, while node.end is the + // end position of the statement + const getPosition = (pos: number, end: number): FullPosition => { + const start = ts.getLineAndCharacterOfPosition(sourceFile, pos); + const endPos = ts.getLineAndCharacterOfPosition(sourceFile, end); + return new FullPosition(start.line + 1, start.character + 1, endPos.line + 1, endPos.character + 1); + }; + + for (const range of commentRanges) { + comments.push({ + content: sourceFile.text.substring(range.pos, range.end).replace(/\r\n/g, '\n'), + position: getPosition(range.pos, range.end), + }); + } + + return new CommentsMetadata(comments); + } + + public static isTempLocal(value: Value): boolean { + return value instanceof Local && value.getName().startsWith(NAME_PREFIX); + } + + public static findOperandIdx(stmt: Stmt, operand: Value): number { + let index: number = -1; + const operands = stmt.getDefAndUses(); + for (let i = 0; i < operands.length; i++) { + if (operands[i] === operand) { + index = i; + break; + } + } + return index; + } + + public static adjustOperandOriginalPositions(stmt: Stmt, oldValue: Value, newValue: Value): void { + const operandOriginalPositions = stmt.getOperandOriginalPositions(); + if (!operandOriginalPositions) { + return; + } + const operandOriginalPositionSize = operandOriginalPositions.length; + const defUseSize = stmt.getDefAndUses().length; + const oldValueUseSize = oldValue.getUses().length; + const newValueUseSize = newValue.getUses().length; + const oldValueIdx = IRUtils.findOperandIdx(stmt, oldValue); + const baseValueOffset = 1; + const fieldValueOffset = 2; + + if (oldValue instanceof AbstractRef && newValue instanceof AbstractRef) { + if (newValue instanceof ArkStaticFieldRef) { + operandOriginalPositions.splice(oldValueIdx + baseValueOffset, + oldValueUseSize - newValueUseSize); + } else if (oldValue instanceof ArkStaticFieldRef) { + operandOriginalPositions.splice(oldValueIdx + baseValueOffset, 0, + ...IRUtils.generateDefaultPositions( + newValueUseSize - oldValueUseSize)); + } + + if (oldValue instanceof ArkInstanceFieldRef && newValue instanceof ArkArrayRef) { + if (operandOriginalPositionSize === defUseSize) { // may not reserve positions for field name + operandOriginalPositions.splice(oldValueIdx + fieldValueOffset, 0, + ...IRUtils.generateDefaultPositions( + newValueUseSize - oldValueUseSize)); + } + } else if (oldValue instanceof ArkArrayRef && newValue instanceof ArkInstanceFieldRef) { + operandOriginalPositions.splice(oldValueIdx + fieldValueOffset, + oldValueUseSize - newValueUseSize); + } + } else if (oldValue instanceof AbstractInvokeExpr && newValue instanceof AbstractInvokeExpr) { + if (oldValueUseSize === newValueUseSize + 1) { + operandOriginalPositions.splice(oldValueIdx + baseValueOffset, 1); + } else if (oldValueUseSize === newValueUseSize - 1) { + operandOriginalPositions.splice(oldValueIdx + baseValueOffset, 0, FullPosition.DEFAULT); + } + } + } + + public static generateDefaultPositions(count: number): FullPosition[] { + const defaultPositions: FullPosition[] = []; + for (let i = 0; i < count; i++) { + defaultPositions.push(FullPosition.DEFAULT); + } + return defaultPositions; + } +} diff --git a/ets2panda/linter/arkanalyzer/src/core/common/ModelUtils.ts b/ets2panda/linter/arkanalyzer/src/core/common/ModelUtils.ts new file mode 100644 index 0000000000..9e3f335317 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/common/ModelUtils.ts @@ -0,0 +1,756 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Local } from '../base/Local'; +import { ArkClass } from '../model/ArkClass'; +import { ArkFile } from '../model/ArkFile'; +import { ArkMethod } from '../model/ArkMethod'; +import { ArkNamespace } from '../model/ArkNamespace'; +import { + AliasTypeSignature, + ClassSignature, + FieldSignature, + FileSignature, + fileSignatureCompare, + LocalSignature, + MethodSignature, + NamespaceSignature, + Signature +} from '../model/ArkSignature'; +import { ArkExport, ExportInfo, ExportType, FromInfo } from '../model/ArkExport'; +import { ArkField } from '../model/ArkField'; +import Logger, { LOG_MODULE_TYPE } from '../../utils/logger'; +import { FileUtils, ModulePath } from '../../utils/FileUtils'; +import path from 'path'; +import { Sdk } from '../../Config'; +import { ALL, DEFAULT, THIS_NAME } from './TSConst'; +import { buildDefaultExportInfo } from '../model/builder/ArkExportBuilder'; +import { + AnnotationNamespaceType, + ClassType, + FunctionType, + Type, + UnclearReferenceType, + UnknownType +} from '../base/Type'; +import { Scene } from '../../Scene'; +import { DEFAULT_ARK_CLASS_NAME, DEFAULT_ARK_METHOD_NAME, NAME_DELIMITER, TEMP_LOCAL_PREFIX } from './Const'; +import { EMPTY_STRING } from './ValueUtil'; +import { ArkBaseModel } from '../model/ArkBaseModel'; +import { ArkAssignStmt } from '../base/Stmt'; +import { ClosureFieldRef } from '../base/Ref'; + +export class ModelUtils { + public static implicitArkUIBuilderMethods: Set = new Set(); + + public static getMethodSignatureFromArkClass(arkClass: ArkClass, methodName: string): MethodSignature | null { + for (const arkMethod of arkClass.getMethods()) { + if (arkMethod.getName() === methodName) { + return arkMethod.getSignature(); + } + } + return null; + } + + public static getClassWithNameInNamespaceRecursively(className: string, ns: ArkNamespace): ArkClass | null { + if (className === '') { + return null; + } + let res: ArkClass | null = null; + res = ns.getClassWithName(className); + if (res == null) { + let declaringNs = ns.getDeclaringArkNamespace(); + if (declaringNs != null) { + res = this.getClassWithNameInNamespaceRecursively(className, declaringNs); + } else { + res = this.getClassInFileWithName(className, ns.getDeclaringArkFile()); + } + } + return res; + } + + public static getClassWithNameFromClass(className: string, startFrom: ArkClass): ArkClass | null { + if (!className.includes('.')) { + let res: ArkClass | null = null; + const arkNamespace = startFrom.getDeclaringArkNamespace(); + if (arkNamespace) { + res = this.getClassWithNameInNamespaceRecursively(className, arkNamespace); + } else { + res = this.getClassInFileWithName(className, startFrom.getDeclaringArkFile()); + } + return res; + } else { + const names = className.split('.'); + let nameSpace = this.getNamespaceWithNameFromClass(names[0], startFrom); + for (let i = 1; i < names.length - 1; i++) { + if (nameSpace) + nameSpace = nameSpace.getNamespaceWithName(names[i]); + } + if (nameSpace) { + return nameSpace.getClassWithName(names[names.length - 1]); + } + } + return null; + } + + /** + * search class within the file that contain the given method + */ + public static getClassWithName(className: string, thisClass: ArkClass): ArkClass | null { + if (thisClass.getName() === className) { + return thisClass; + } + let classSearched = thisClass.getDeclaringArkNamespace()?.getClassWithName(className); + if (!classSearched) { + classSearched = thisClass.getDeclaringArkFile().getClassWithName(className); + } + return classSearched; + } + + /** search class within the given file */ + public static getClassInFileWithName(className: string, arkFile: ArkFile): ArkClass | null { + let classSearched = arkFile.getClassWithName(className); + if (classSearched != null) { + return classSearched; + } + return null; + } + + public static getClassInImportInfoWithName(className: string, arkFile: ArkFile): ArkClass | null { + let arkExport = this.getArkExportInImportInfoWithName(className, arkFile); + if (arkExport instanceof ArkClass) { + return arkExport; + } + return null; + } + + /** search type within the given file import infos */ + public static getArkExportInImportInfoWithName(name: string, arkFile: ArkFile): ArkExport | null { + return arkFile.getImportInfoBy(name)?.getLazyExportInfo()?.getArkExport() ?? null; + } + + /** search method within the file that contain the given method */ + public static getMethodWithName(methodName: string, startFrom: ArkMethod): ArkMethod | null { + if (!methodName.includes('.')) { + if (startFrom.getName() === methodName) { + return startFrom; + } + + const thisClass = startFrom.getDeclaringArkClass(); + let methodSearched: ArkMethod | null = thisClass.getMethodWithName(methodName); + if (!methodSearched) { + methodSearched = thisClass.getStaticMethodWithName(methodName); + } + return methodSearched; + } else { + const names = methodName.split('.'); + let nameSpace = this.getNamespaceWithName(names[0], startFrom.getDeclaringArkClass()); + for (let i = 1; i < names.length - 1; i++) { + if (nameSpace) { + nameSpace = nameSpace.getNamespaceWithName(names[i]); + } + } + if (nameSpace) { + return nameSpace.getDefaultClass().getMethodWithName(names[names.length - 1]); + } + } + return null; + } + + public static getNamespaceWithNameFromClass(namespaceName: string, startFrom: ArkClass): ArkNamespace | null { + const thisNamespace = startFrom.getDeclaringArkNamespace(); + let namespaceSearched: ArkNamespace | null = null; + if (thisNamespace) { + namespaceSearched = thisNamespace.getNamespaceWithName(namespaceName); + if (namespaceSearched) { + return namespaceSearched; + } + } + const thisFile = startFrom.getDeclaringArkFile(); + namespaceSearched = this.getNamespaceInFileWithName(namespaceName, thisFile); + return namespaceSearched; + } + + public static getNamespaceWithName(namespaceName: string, thisClass: ArkClass): ArkNamespace | null { + let thisNamespace: ArkNamespace | null | undefined = thisClass.getDeclaringArkNamespace(); + let namespaceSearched: ArkNamespace | null = null; + while (!namespaceSearched && thisNamespace) { + namespaceSearched = thisNamespace.getNamespaceWithName(namespaceName); + thisNamespace = thisNamespace.getDeclaringArkNamespace(); + } + if (!namespaceSearched) { + namespaceSearched = thisClass.getDeclaringArkFile().getNamespaceWithName(namespaceName); + } + return namespaceSearched; + } + + public static getNamespaceInFileWithName(namespaceName: string, arkFile: ArkFile): ArkNamespace | null { + let namespaceSearched = arkFile.getNamespaceWithName(namespaceName); + if (namespaceSearched) { + return namespaceSearched; + } + + return null; + } + + public static getNamespaceInImportInfoWithName(namespaceName: string, arkFile: ArkFile): ArkNamespace | null { + let arkExport = this.getArkExportInImportInfoWithName(namespaceName, arkFile); + if (arkExport instanceof ArkNamespace) { + return arkExport; + } + return null; + } + + public static getStaticMethodWithName(methodName: string, thisClass: ArkClass): ArkMethod | null { + + const thisNamespace = thisClass.getDeclaringArkNamespace(); + if (thisNamespace) { + const defaultClass = thisNamespace.getClassWithName(DEFAULT_ARK_CLASS_NAME); + if (defaultClass) { + const method = defaultClass.getMethodWithName(methodName); + if (method) { + return method; + } + } + } + return this.getStaticMethodInFileWithName(methodName, thisClass.getDeclaringArkFile()); + } + + public static getStaticMethodInFileWithName(methodName: string, arkFile: ArkFile): ArkMethod | null { + const defaultClass = arkFile.getClasses().find(cls => cls.getName() === DEFAULT_ARK_CLASS_NAME) || null; + if (defaultClass) { + let method = defaultClass.getMethodWithName(methodName); + if (method) { + return method; + } + } + return null; + } + + public static getStaticMethodInImportInfoWithName(methodName: string, arkFile: ArkFile): ArkMethod | null { + let arkExport = this.getArkExportInImportInfoWithName(methodName, arkFile); + if (arkExport instanceof ArkMethod) { + return arkExport; + } + return null; + } + + public static getLocalInImportInfoWithName(localName: string, arkFile: ArkFile): Local | null { + let arkExport = this.getArkExportInImportInfoWithName(localName, arkFile); + if (arkExport instanceof Local) { + return arkExport; + } + return null; + } + + /* get nested namespaces in a file */ + public static getAllNamespacesInFile(arkFile: ArkFile): ArkNamespace[] { + const arkNamespaces: ArkNamespace[] = arkFile.getNamespaces(); + for (const arkNamespace of arkFile.getNamespaces()) { + this.getAllNamespacesInNamespace(arkNamespace, arkNamespaces); + } + return arkNamespaces; + } + + /* get nested namespaces in a namespace */ + public static getAllNamespacesInNamespace(arkNamespace: ArkNamespace, allNamespaces: ArkNamespace[]): void { + allNamespaces.push(...arkNamespace.getNamespaces()); + for (const nestedNamespace of arkNamespace.getNamespaces()) { + this.getAllNamespacesInNamespace(nestedNamespace, allNamespaces); + } + } + + public static getAllClassesInFile(arkFile: ArkFile): ArkClass[] { + const allClasses = arkFile.getClasses(); + this.getAllNamespacesInFile(arkFile).forEach((namespace) => { + allClasses.push(...namespace.getClasses()); + }); + return allClasses; + } + + public static getAllMethodsInFile(arkFile: ArkFile): ArkMethod[] { + const allMethods: ArkMethod[] = []; + this.getAllClassesInFile(arkFile).forEach((cls) => { + allMethods.push(...cls.getMethods()); + }); + return allMethods; + } + + public static isArkUIBuilderMethod(arkMethod: ArkMethod): boolean { + let isArkUIBuilderMethod = arkMethod.hasBuilderDecorator() || this.implicitArkUIBuilderMethods.has(arkMethod); + + if ( + !isArkUIBuilderMethod && + arkMethod.getName() === 'build' && + arkMethod.getDeclaringArkClass().hasComponentDecorator() && + !arkMethod.isStatic() + ) { + const fileName = arkMethod.getDeclaringArkClass().getDeclaringArkFile().getName(); + if (fileName.endsWith('.ets')) { + isArkUIBuilderMethod = true; + } + } + return isArkUIBuilderMethod; + } + + public static getArkClassInBuild(scene: Scene, classType: ClassType): ArkClass | null { + const classSignature = classType.getClassSignature(); + const file = scene.getFile(classSignature.getDeclaringFileSignature()); + const namespaceSignature = classSignature.getDeclaringNamespaceSignature(); + if (namespaceSignature) { + return file?.getNamespace(namespaceSignature)?.getClass(classSignature) || null; + } + return file?.getClassWithName(classSignature.getClassName()) || null; + } + + public static getDefaultClass(arkClass: ArkClass): ArkClass | null { + return arkClass.getDeclaringArkNamespace()?.getDefaultClass() ?? arkClass.getDeclaringArkFile().getDefaultClass(); + } + + public static getClass(method: ArkMethod, signature: ClassSignature): ArkClass | null { + let cls: ArkClass | undefined | null = method.getDeclaringArkFile().getScene().getClass(signature); + if (cls) { + return cls; + } + let importInfo = method.getDeclaringArkFile().getImportInfoBy(signature.getClassName()); + let exportInfo = importInfo ? findExportInfo(importInfo) : null; + let arkExport = exportInfo?.getArkExport(); + if (arkExport instanceof ArkClass) { + return arkExport; + } + + cls = method.getDeclaringArkClass().getDeclaringArkNamespace()?.getClassWithName(signature.getClassName()); + if (cls) { + return cls; + } + + for (const ns of method.getDeclaringArkFile().getAllNamespacesUnderThisFile()) { + cls = ns.getClassWithName(signature.getClassName()); + if (cls) { + return cls; + } + } + + return method.getDeclaringArkFile().getClassWithName(signature.getClassName()); + } + + public static findPropertyInNamespace(name: string, namespace: ArkNamespace): ArkExport | undefined { + return namespace.getDefaultClass()?.getMethodWithName(name) + ?? findArkExport(namespace.getExportInfoBy(name)) + ?? namespace.getClassWithName(name) + ?? namespace.getNamespaceWithName(name) + ?? namespace.getDefaultClass()?.getDefaultArkMethod()?.getBody()?.getAliasTypeByName(name) + ?? namespace.getDefaultClass()?.getDefaultArkMethod()?.getBody()?.getLocals()?.get(name); + } + + public static findPropertyInClass(name: string, arkClass: ArkClass): ArkExport | ArkField | null { + let property: ArkExport | ArkField | null = arkClass.getMethodWithName(name) + ?? arkClass.getStaticMethodWithName(name) ?? arkClass.getFieldWithName(name) + ?? arkClass.getStaticFieldWithName(name); + if (property) { + return property; + } + if (arkClass.isDefaultArkClass()) { + return findArkExport(arkClass.getDeclaringArkFile().getExportInfoBy(name)); + } + for (const heritage of arkClass.getAllHeritageClasses()) { + property = this.findPropertyInClass(name, heritage); + if (property) { + return property; + } + } + return null; + } + + public static findDeclaredLocal(local: Local, arkMethod: ArkMethod, times: number = 0): Local | null { + if (arkMethod.getDeclaringArkFile().getScene().getOptions().isScanAbc) { + return null; + } + const name: string = local.getName(); + if (name === THIS_NAME || name.startsWith(TEMP_LOCAL_PREFIX)) { + return null; + } + const parameter = arkMethod.getParameters().find(p => p.getName() === name); + if (parameter) { + return new Local(parameter.getName(), parameter.getType()); + } + if (times > 0) { + const declaredLocal = arkMethod.getBody()?.getLocals().get(name); + if (declaredLocal && declaredLocal.getDeclaringStmt() instanceof ArkAssignStmt && + !((declaredLocal.getDeclaringStmt() as ArkAssignStmt).getRightOp() instanceof ClosureFieldRef)) { + return declaredLocal; + } + } + let parentName = arkMethod.getName(); + if (parentName === DEFAULT_ARK_METHOD_NAME) { + return null; + } + let invokeMethod: ArkMethod | null | undefined = arkMethod.getOuterMethod(); + if (!invokeMethod) { + const className = arkMethod.getDeclaringArkClass().getName(); + const outerStart = className.indexOf(NAME_DELIMITER); + const outerEnd = className.lastIndexOf('.'); + if (outerStart > -1 && outerEnd > -1) { + invokeMethod = arkMethod.getDeclaringArkFile().getClassWithName(className.substring(outerStart + 1, outerEnd)) + ?.getMethodWithName(className.substring(outerEnd + 1)); + } else { + const cls = arkMethod.getDeclaringArkClass(); + invokeMethod = cls.getDefaultArkMethod() ?? cls.getDeclaringArkFile().getDefaultClass()?.getDefaultArkMethod(); + } + } + if (invokeMethod) { + return this.findDeclaredLocal(local, invokeMethod, ++times); + } + return null; + } + + public static findArkModel(baseName: string, arkClass: ArkClass): ArkExport | ArkField | null { + let arkModel: ArkExport | ArkField | null = arkClass.getMethodWithName(baseName) ?? + arkClass.getStaticMethodWithName(baseName) ?? arkClass.getFieldWithName(baseName) ?? + arkClass.getStaticFieldWithName(baseName); + if (arkModel) { + return arkModel; + } + arkModel = ModelUtils.getDefaultClass(arkClass)?.getDefaultArkMethod()?.getBody()?.getLocals()?.get(baseName) ?? + ModelUtils.getClassWithName(baseName, arkClass) ?? + ModelUtils.getNamespaceWithName(baseName, arkClass) ?? + ModelUtils.getDefaultClass(arkClass)?.getMethodWithName(baseName) ?? + ModelUtils.getDefaultClass(arkClass)?.getDefaultArkMethod()?.getBody()?.getAliasTypeByName(baseName) ?? + ModelUtils.getArkExportInImportInfoWithName(baseName, arkClass.getDeclaringArkFile()); + if (!arkModel && !arkClass.getDeclaringArkFile().getImportInfoBy(baseName)) { + arkModel = arkClass.getDeclaringArkFile().getScene().getSdkGlobal(baseName); + } + return arkModel; + } + + public static findArkModelByRefName(refName: string, arkClass: ArkClass): ArkExport | ArkField | null { + const singleNames = refName.split('.'); + let model = null; + for (let i = 0; i < singleNames.length; i++) { + if (model instanceof Local || model instanceof ArkField) { + const type = model.getType(); + if (type instanceof ClassType) { + model = arkClass.getDeclaringArkFile().getScene().getClass(type.getClassSignature()); + } else if (type instanceof AnnotationNamespaceType) { + model = arkClass.getDeclaringArkFile().getScene().getNamespace(type.getNamespaceSignature()); + } + } + const name = singleNames[i].replace(/<(\w+)>/, EMPTY_STRING); + if (i === 0) { + model = this.findArkModel(name, arkClass); + } else if (model instanceof ArkClass) { + model = this.findPropertyInClass(name, model); + } else if (model instanceof ArkNamespace) { + model = this.findPropertyInNamespace(name, model); + } + if (!model) { + return null; + } + + } + return model; + } + + public static findArkModelBySignature(signature: Signature, scene: Scene): ArkExport | ArkField | null { + if (signature instanceof ClassSignature) { + return scene.getClass(signature); + } else if (signature instanceof NamespaceSignature) { + return scene.getNamespace(signature); + } else if (signature instanceof MethodSignature) { + return scene.getMethod(signature); + } else if (signature instanceof FieldSignature) { + const declare = this.findArkModelBySignature(signature.getDeclaringSignature(), scene); + if (declare instanceof ArkClass) { + return this.findPropertyInClass(signature.getFieldName(), declare); + } else if (declare instanceof ArkNamespace) { + return this.findPropertyInNamespace(signature.getFieldName(), declare) || null; + } + return null; + } else if (signature instanceof LocalSignature) { + const declare = scene.getMethod(signature.getDeclaringMethodSignature()); + return declare?.getBody()?.getLocals().get(signature.getName()) ?? declare?.getBody()?.getAliasTypeByName(signature.getName()) ?? null; + } else if (signature instanceof AliasTypeSignature) { + const declare = scene.getMethod(signature.getDeclaringMethodSignature()); + return declare?.getBody()?.getAliasTypeByName(signature.getName()) ?? null; + } + return null; + } + + public static parseArkBaseModel2Type(arkBaseModel: ArkBaseModel): Type | null { + if (arkBaseModel instanceof ArkClass) { + return new ClassType(arkBaseModel.getSignature(), arkBaseModel.getGenericsTypes()); + } else if (arkBaseModel instanceof ArkNamespace) { + return AnnotationNamespaceType.getInstance(arkBaseModel.getSignature()); + } else if (arkBaseModel instanceof ArkMethod) { + return new FunctionType(arkBaseModel.getSignature()); + } else if (arkBaseModel instanceof ArkField) { + if (arkBaseModel.getType() instanceof UnknownType || arkBaseModel.getType() instanceof UnclearReferenceType) { + return null; + } + return arkBaseModel.getType(); + } + return null; + } +} + + +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'ModelUtils'); +let moduleMap: Map | undefined; +export const sdkImportMap: Map = new Map(); + +/** + * find arkFile by from info + * export xx from '../xx' + * import xx from '@ohos/xx' + * import xx from '@ohos.xx' + * @param im importInfo or exportInfo + */ +export function getArkFile(im: FromInfo): ArkFile | null | undefined { + const from = im.getFrom(); + if (!from) { + return null; + } + if (/^([^@]*\/)([^\/]*)$/.test(from)) { //relative path + const parentPath = /^\.{1,2}\//.test(from) ? path.dirname(im.getDeclaringArkFile().getFilePath()) + : im.getDeclaringArkFile().getProjectDir(); + const originPath = path.resolve(parentPath, from); + return getArkFileFromScene(im, originPath); + } else if (/^@[a-z|\-]+?\//.test(from)) { //module path + const arkFile = getArkFileFromOtherModule(im); + if (arkFile) { + return arkFile; + } + } + + //sdk path + const file = sdkImportMap.get(from); + if (file) { + return file; + } + const scene = im.getDeclaringArkFile().getScene(); + for (const sdk of scene.getProjectSdkMap().values()) { + const arkFile = getArkFileFormMap(sdk.name, processSdkPath(sdk, from), scene); + if (arkFile) { + return arkFile; + } + } +} + +/** + * find from info's export + * @param fromInfo importInfo or exportInfo + */ +export function findExportInfo(fromInfo: FromInfo): ExportInfo | null { + let file = getArkFile(fromInfo); + if (!file) { + logger.warn(`${fromInfo.getOriginName()} ${fromInfo.getFrom()} file not found: + ${fromInfo.getDeclaringArkFile()?.getFileSignature()?.toString()}`); + return null; + } + if (fileSignatureCompare(file.getFileSignature(), fromInfo.getDeclaringArkFile().getFileSignature())) { + for (let exportInfo of file.getExportInfos()) { + if (exportInfo.getOriginName() === fromInfo.getOriginName()) { + exportInfo.setArkExport(file.getDefaultClass()); + return exportInfo; + } + } + return null; + } + let exportInfo = findExportInfoInfile(fromInfo, file) || null; + if (exportInfo === null) { + logger.warn('export info not found, ' + fromInfo.getFrom() + ' in file: ' + + fromInfo.getDeclaringArkFile().getFileSignature().toString()); + return null; + } + const arkExport = findArkExport(exportInfo); + exportInfo.setArkExport(arkExport); + if (arkExport) { + exportInfo.setExportClauseType(arkExport.getExportType()); + } + return exportInfo; +} + +export function findArkExport(exportInfo: ExportInfo | undefined): ArkExport | null { + if (!exportInfo) { + return null; + } + let arkExport = exportInfo.getArkExport(); + if (arkExport || arkExport === null) { + return arkExport; + } + if (!exportInfo.getFrom()) { + const name = exportInfo.getOriginName(); + if (exportInfo.getExportClauseType() === ExportType.LOCAL) { + arkExport = exportInfo.getDeclaringArkFile().getDefaultClass().getDefaultArkMethod()?.getBody()?.getLocals().get(name) || null; + } else if (exportInfo.getExportClauseType() === ExportType.TYPE) { + arkExport = exportInfo.getDeclaringArkFile().getDefaultClass().getDefaultArkMethod()?.getBody()?.getAliasTypeByName(name) || null; + } else { + arkExport = findArkExportInFile(name, exportInfo.getDeclaringArkFile()); + } + } else if (exportInfo.getExportClauseType() === ExportType.UNKNOWN) { + const result = findExportInfo(exportInfo); + if (result) { + arkExport = result.getArkExport() || null; + } + } + if (!arkExport) { + logger.warn(`${exportInfo.getExportClauseName()} get arkExport fail from ${exportInfo.getFrom()} at + ${exportInfo.getDeclaringArkFile().getFileSignature().toString()}`); + } + return arkExport || null; +} + +export function findArkExportInFile(name: string, declaringArkFile: ArkFile): ArkExport | null { + let arkExport: ArkExport | undefined | null = declaringArkFile.getNamespaceWithName(name) + ?? declaringArkFile.getDefaultClass().getDefaultArkMethod()?.getBody()?.getAliasTypeByName(name) + ?? declaringArkFile.getClassWithName(name) + ?? declaringArkFile.getDefaultClass().getMethodWithName(name) + ?? declaringArkFile.getDefaultClass().getDefaultArkMethod()?.getBody()?.getLocals().get(name); + + if (!arkExport) { + const importInfo = declaringArkFile.getImportInfoBy(name); + if (importInfo) { + const result = findExportInfo(importInfo); + if (result) { + arkExport = result.getArkExport(); + } + } + } + return arkExport || null; +} + +function processSdkPath(sdk: Sdk, formPath: string): string { + let originPath = path.join(sdk.path, formPath); + if (FileUtils.isDirectory(originPath)) { + formPath = path.join(formPath, FileUtils.getIndexFileName(originPath)); + } + return `${formPath}`; +} + +function getArkFileFromScene(im: FromInfo, originPath: string) { + if (FileUtils.isDirectory(originPath)) { + originPath = path.join(originPath, FileUtils.getIndexFileName(originPath)); + } + const fileName = path.relative(im.getDeclaringArkFile().getProjectDir(), originPath); + const scene = im.getDeclaringArkFile().getScene(); + if (/\.e?ts$/.test(originPath)) { + const fromSignature = new FileSignature(im.getDeclaringArkFile().getProjectName(), fileName); + return scene.getFile(fromSignature); + } + const projectName = im.getDeclaringArkFile().getProjectName(); + return getArkFileFormMap(projectName, fileName, scene); +} + +function getArkFileFormMap(projectName: string, filePath: string, scene: Scene): ArkFile | null { + if (/\.e?ts$/.test(filePath)) { + return scene.getFile(new FileSignature(projectName, filePath)); + } + const fileSuffixArray = scene.getOptions().supportFileExts; + if (!fileSuffixArray) { + return null; + } + for (const suffix of fileSuffixArray) { + const arkFile = scene.getFile(new FileSignature(projectName, filePath + suffix)); + if (arkFile) { + return arkFile; + } + } + return null; +} + + +function findExportInfoInfile(fromInfo: FromInfo, file: ArkFile) { + const exportName = fromInfo.isDefault() ? DEFAULT : fromInfo.getOriginName(); + let exportInfo = file.getExportInfoBy(exportName); + if (exportInfo) { + return exportInfo; + } + + if (exportName === DEFAULT) { + exportInfo = file.getExportInfos().find(p => p.isDefault()); + if (exportInfo) { + file.addExportInfo(exportInfo, DEFAULT); + return exportInfo; + } + } + + if (fromInfo.getOriginName() === ALL) { + exportInfo = buildDefaultExportInfo(fromInfo, file); + file.addExportInfo(exportInfo, ALL); + } else if (/\.d\.e?ts$/.test(file.getName())) { + let declare = exportName === DEFAULT ? undefined + : findArkExportInFile(fromInfo.getOriginName(), file) || undefined; + exportInfo = buildDefaultExportInfo(fromInfo, file, declare); + } + + return exportInfo; +} + +export function initModulePathMap(ohPkgContentMap: Map): void { + if (moduleMap) { + moduleMap.clear(); + } + moduleMap = FileUtils.generateModuleMap(ohPkgContentMap); +} + + +function getArkFileFromOtherModule(fromInfo: FromInfo) { + if (!moduleMap || moduleMap.size === 0) { + return; + } + const from = fromInfo.getFrom()!; + let index: number; + let file; + let modulePath; + //find file by given from like '@ohos/module/src/xxx' '@ohos/module/index' + if ((index = from.indexOf('src')) > 0 || (index = from.indexOf('Index')) > 0 || (index = from.indexOf('index')) > 0) { + modulePath = moduleMap.get(from.substring(0, index).replace(/\/*$/, '')); + file = findFileInModule(fromInfo, modulePath, from.substring(index)); + } + if (file) { + return file; + } + modulePath = modulePath ?? moduleMap.get(from); + if (!modulePath) { + return file; + } + //find file in module json main path + if (modulePath.main) { + file = getArkFileFromScene(fromInfo, modulePath.main); + } + //find file in module path Index.ts + if (!file && FileUtils.isDirectory(modulePath.path)) { + file = findFileInModule(fromInfo, modulePath, FileUtils.getIndexFileName(modulePath.path)); + } + //find file in module path/src/main/ets/TsIndex.ts + if (!file) { + file = findFileInModule(fromInfo, modulePath, '/src/main/ets/TsIndex.ts'); + } + return file; +} + +function findFileInModule(fromInfo: FromInfo, modulePath: ModulePath | undefined, contentPath: string) { + if (!modulePath) { + return; + } + const originPath = path.join(modulePath.path, contentPath); + let file; + if (originPath !== modulePath.main) { + file = getArkFileFromScene(fromInfo, originPath); + } + if (file && findExportInfoInfile(fromInfo, file)) { + return file; + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/common/RefUseReplacer.ts b/ets2panda/linter/arkanalyzer/src/core/common/RefUseReplacer.ts new file mode 100644 index 0000000000..db98473ef6 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/common/RefUseReplacer.ts @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Local } from '../base/Local'; +import { AbstractRef, ArkArrayRef, ArkInstanceFieldRef } from '../base/Ref'; +import { Value } from '../base/Value'; + +/** + * Replace old use of a Ref inplace + */ +export class RefUseReplacer { + private oldUse: Value; + private newUse: Value; + + constructor(oldUse: Value, newUse: Value) { + this.oldUse = oldUse + this.newUse = newUse; + } + + public caseRef(ref: AbstractRef): void { + if (ref instanceof ArkInstanceFieldRef) { + this.caseFieldRef(ref); + } else if (ref instanceof ArkArrayRef) { + this.caseArrayRef(ref); + } + } + + private caseFieldRef(ref: ArkInstanceFieldRef): void { + if (ref.getBase() === this.oldUse && this.newUse instanceof Local) { + ref.setBase(this.newUse); + } + } + + private caseArrayRef(ref: ArkArrayRef): void { + if (ref.getBase() === this.oldUse) { + if (this.newUse instanceof Local) { + ref.setBase(this.newUse); + } + } else if (ref.getIndex() === this.oldUse) { + ref.setIndex(this.newUse); + } + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/common/SdkUtils.ts b/ets2panda/linter/arkanalyzer/src/core/common/SdkUtils.ts new file mode 100644 index 0000000000..d5e9e87b46 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/common/SdkUtils.ts @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkFile } from '../model/ArkFile'; +import { ArkExport, ExportInfo } from '../model/ArkExport'; +import { COMPONENT_ATTRIBUTE } from './EtsConst'; +import { GLOBAL_THIS_NAME, THIS_NAME } from './TSConst'; +import { TEMP_LOCAL_PREFIX } from './Const'; +import { ArkClass, ClassCategory } from '../model/ArkClass'; +import { LocalSignature } from '../model/ArkSignature'; +import { ModelUtils, sdkImportMap } from './ModelUtils'; +import { Local } from '../base/Local'; +import { ArkMethod } from '../model/ArkMethod'; +import path from 'path'; +import { IRInference } from './IRInference'; +import { ClassType } from '../base/Type'; +import { AbstractFieldRef } from '../base/Ref'; +import { ArkNamespace } from '../model/ArkNamespace'; + +export class SdkUtils { + + public static buildGlobalMap(file: ArkFile, globalMap: Map): void { + const fileName = path.basename(file.getName()); + if (fileName.startsWith('@')) { + sdkImportMap.set(fileName.replace(/\.d\.e?ts$/, ''), file); + } + + const isGlobalPath = file.getScene().getOptions().sdkGlobalFolders + ?.find(x => file.getFilePath().includes(path.sep + x + path.sep)); + if (!isGlobalPath) { + return; + } + IRInference.inferFile(file); + ModelUtils.getAllClassesInFile(file).forEach(cls => { + if (!cls.isAnonymousClass() && !cls.isDefaultArkClass()) { + SdkUtils.loadClass(globalMap, cls); + } + if (cls.isDefaultArkClass()) { + cls.getMethods() + .filter(mtd => !mtd.isDefaultArkMethod() && !mtd.isAnonymousMethod()) + .forEach(mtd => globalMap.set(mtd.getName(), mtd)); + } + }); + const defaultArkMethod = file.getDefaultClass().getDefaultArkMethod(); + defaultArkMethod?.getBody()?.getLocals().forEach(local => { + const name = local.getName(); + if (name !== THIS_NAME && !name.startsWith(TEMP_LOCAL_PREFIX)) { + this.loadGlobalLocal(local, defaultArkMethod, globalMap); + } + }); + defaultArkMethod?.getBody()?.getAliasTypeMap()?.forEach(a => globalMap.set(a[0].getName(), a[0])); + ModelUtils.getAllNamespacesInFile(file).forEach(ns => globalMap.set(ns.getName(), ns)); + } + + private static loadClass(globalMap: Map, cls: ArkClass): void { + const old = globalMap.get(cls.getName()); + if (old instanceof ArkClass) { + if (old.getCategory() === ClassCategory.CLASS) { + this.copyMethod(cls, old); + } else { + this.copyMethod(old, cls); + globalMap.delete(cls.getName()); + globalMap.set(cls.getName(), cls); + } + } else if (!old) { + globalMap.set(cls.getName(), cls); + } + } + + private static loadGlobalLocal(local: Local, defaultArkMethod: ArkMethod, globalMap: Map): void { + const name = local.getName(); + local.setSignature(new LocalSignature(name, defaultArkMethod.getSignature())); + const scene = defaultArkMethod.getDeclaringArkFile().getScene(); + if (scene.getOptions().isScanAbc) { + const instance = globalMap.get(name + 'Interface'); + const attr = globalMap.get(name + COMPONENT_ATTRIBUTE); + if (attr instanceof ArkClass && instance instanceof ArkClass) { + instance.getMethods().filter(m => !attr.getMethodWithName(m.getName())).forEach(m => attr.addMethod(m)); + globalMap.set(name, attr); + return; + } + + } + const old = globalMap.get(name); + if (!old) { + globalMap.set(name, local); + } else if (old instanceof ArkClass && local.getType() instanceof ClassType) { + const localConstructor = scene.getClass((local.getType() as ClassType).getClassSignature()); + if (localConstructor) { + localConstructor.getMethods().filter(m => !old.getMethodWithName(m.getName())).forEach(m => old.addMethod(m)); + } + } + } + + private static copyMethod(from: ArkClass, to: ArkClass): void { + from.getMethods().forEach(method => { + const dist = method.isStatic() ? to.getStaticMethodWithName(method.getName()) : to.getMethodWithName(method.getName()); + const distSignatures = dist?.getDeclareSignatures(); + if (distSignatures) { + method.getDeclareSignatures()?.forEach(x => distSignatures.push(x)); + } else { + to.addMethod(method); + } + }); + } + + public static computeGlobalThis(leftOp: AbstractFieldRef, arkMethod: ArkMethod): void { + const globalThis = arkMethod.getDeclaringArkFile().getScene().getSdkGlobal(GLOBAL_THIS_NAME); + if (globalThis instanceof ArkNamespace) { + const exportInfo = new ExportInfo.Builder().exportClauseName(leftOp.getFieldName()) + .arkExport(new Local(leftOp.getFieldName(), leftOp.getType())).build(); + globalThis.addExportInfo(exportInfo); + } + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/common/StmtDefReplacer.ts b/ets2panda/linter/arkanalyzer/src/core/common/StmtDefReplacer.ts new file mode 100644 index 0000000000..e746072a67 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/common/StmtDefReplacer.ts @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Value } from '../base/Value'; +import { ArkAssignStmt, Stmt } from '../base/Stmt'; +import { IRUtils } from './IRUtils'; + +/** + * Replace old def(Value) of a Stmt inplace + */ +export class StmtDefReplacer { + private oldDef: Value; + private newDef: Value; + + constructor(oldDef: Value, newDef: Value) { + this.oldDef = oldDef; + this.newDef = newDef; + } + + public caseStmt(stmt: Stmt): void { + if (stmt instanceof ArkAssignStmt) { + this.caseAssignStmt(stmt); + } + } + + private caseAssignStmt(stmt: ArkAssignStmt): void { + const lValue = stmt.getLeftOp(); + if (lValue === this.oldDef) { + IRUtils.adjustOperandOriginalPositions(stmt, this.oldDef, this.newDef); + stmt.setLeftOp(this.newDef); + } + } + +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/common/StmtUseReplacer.ts b/ets2panda/linter/arkanalyzer/src/core/common/StmtUseReplacer.ts new file mode 100644 index 0000000000..051192098e --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/common/StmtUseReplacer.ts @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { AbstractExpr, AbstractInvokeExpr, ArkConditionExpr } from '../base/Expr'; +import { AbstractRef } from '../base/Ref'; +import { ArkAssignStmt, ArkIfStmt, ArkInvokeStmt, ArkReturnStmt, ArkThrowStmt, Stmt } from '../base/Stmt'; +import { Value } from '../base/Value'; +import { ExprUseReplacer } from './ExprUseReplacer'; +import { RefUseReplacer } from './RefUseReplacer'; +import { IRUtils } from './IRUtils'; + +/** + * Replace old use(Value) of a Stmt inplace + */ +export class StmtUseReplacer { + private oldUse: Value; + private newUse: Value; + + constructor(oldUse: Value, newUse: Value) { + this.oldUse = oldUse + this.newUse = newUse; + } + + public caseStmt(stmt: Stmt): void { + if (stmt instanceof ArkAssignStmt) { + this.caseAssignStmt(stmt); + } else if (stmt instanceof ArkInvokeStmt) { + this.caseInvokeStmt(stmt); + } else if (stmt instanceof ArkReturnStmt) { + this.caseReturnStmt(stmt); + } else if (stmt instanceof ArkIfStmt) { + this.caseIfStmt(stmt); + } else if (stmt instanceof ArkThrowStmt) { + this.caseThrowStmt(stmt); + } + } + + private caseAssignStmt(stmt: ArkAssignStmt): void { + const lValue = stmt.getLeftOp(); + if (lValue instanceof AbstractRef) { + const refUseReplacer = new RefUseReplacer(this.oldUse, this.newUse); + refUseReplacer.caseRef(lValue); + } + + const rValue = stmt.getRightOp(); + if (rValue === this.oldUse) { + IRUtils.adjustOperandOriginalPositions(stmt, this.oldUse, this.newUse); + stmt.setRightOp(this.newUse); + } else if (rValue instanceof AbstractRef) { + const refUseReplacer = new RefUseReplacer(this.oldUse, this.newUse); + refUseReplacer.caseRef(rValue); + } else if (rValue instanceof AbstractExpr) { + const exprUseReplacer = new ExprUseReplacer(this.oldUse, this.newUse); + exprUseReplacer.caseExpr(rValue); + } + } + + private caseInvokeStmt(stmt: ArkInvokeStmt): void { + const invokeExpr = stmt.getInvokeExpr(); + if (invokeExpr === this.oldUse) { + if (this.newUse instanceof AbstractInvokeExpr) { + IRUtils.adjustOperandOriginalPositions(stmt, this.oldUse, this.newUse); + stmt.replaceInvokeExpr(this.newUse); + } + } else { + let exprUseReplacer = new ExprUseReplacer(this.oldUse, this.newUse); + exprUseReplacer.caseExpr(stmt.getInvokeExpr()); + } + } + + private caseReturnStmt(stmt: ArkReturnStmt): void { + if (stmt.getOp() === this.oldUse) { + IRUtils.adjustOperandOriginalPositions(stmt, this.oldUse, this.newUse); + stmt.setReturnValue(this.newUse); + } + } + + private caseIfStmt(stmt: ArkIfStmt): void { + const conditionExpr = stmt.getConditionExpr(); + if (conditionExpr === this.oldUse) { + if (this.newUse instanceof ArkConditionExpr) { + IRUtils.adjustOperandOriginalPositions(stmt, this.oldUse, this.newUse); + stmt.setConditionExpr(this.newUse); + } + } else { + let exprUseReplacer = new ExprUseReplacer(this.oldUse, this.newUse); + exprUseReplacer.caseExpr(stmt.getConditionExpr()); + } + } + + private caseThrowStmt(stmt: ArkThrowStmt): void { + if (stmt.getOp() === this.oldUse) { + IRUtils.adjustOperandOriginalPositions(stmt, this.oldUse, this.newUse); + stmt.setOp(this.newUse); + } + } + + +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/common/TSConst.ts b/ets2panda/linter/arkanalyzer/src/core/common/TSConst.ts new file mode 100644 index 0000000000..269c4107da --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/common/TSConst.ts @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const CONSTRUCTOR_NAME = 'constructor'; +export const SUPER_NAME = 'super'; +export const THIS_NAME = 'this'; +export const GLOBAL_THIS_NAME: string = 'globalThis' + +export const DEFAULT = 'default'; + +export const ALL = '*'; + +export const IMPORT = 'import'; +export const PROMISE = 'Promise'; +export const FUNCTION = 'Function'; + +// ast const +export const DECLARE_KEYWORD = 'DeclareKeyword'; +export const NULL_KEYWORD = 'null'; +export const UNDEFINED_KEYWORD = 'undefined'; +export const ANY_KEYWORD = 'any'; +export const UNKNOWN_KEYWORD = 'unknown'; +export const BOOLEAN_KEYWORD = 'boolean'; +export const NUMBER_KEYWORD = 'number'; +export const STRING_KEYWORD = 'string'; +export const VOID_KEYWORD = 'void'; +export const NEVER_KEYWORD = 'never'; +export const BIGINT_KEYWORD = 'bigint'; +export const TSCONFIG_JSON = 'tsconfig.json'; + diff --git a/ets2panda/linter/arkanalyzer/src/core/common/TypeInference.ts b/ets2panda/linter/arkanalyzer/src/core/common/TypeInference.ts new file mode 100644 index 0000000000..44a3d0136f --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/common/TypeInference.ts @@ -0,0 +1,854 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Logger, { LOG_MODULE_TYPE } from '../../utils/logger'; +import { AbstractExpr, ArkInstanceInvokeExpr, ArkPtrInvokeExpr, ArkStaticInvokeExpr } from '../base/Expr'; +import { Local } from '../base/Local'; +import { + AbstractFieldRef, + AbstractRef, + ArkArrayRef, + ArkInstanceFieldRef, + ArkParameterRef, + ArkStaticFieldRef, +} from '../base/Ref'; +import { ArkAliasTypeDefineStmt, ArkAssignStmt, ArkReturnStmt, Stmt } from '../base/Stmt'; +import { + AliasType, + AnnotationNamespaceType, + AnyType, + ArrayType, + BigIntType, + BooleanType, + ClassType, + FunctionType, + GenericType, + IntersectionType, + NeverType, + NullType, + NumberType, + StringType, + TupleType, + Type, + UnclearReferenceType, + UndefinedType, + UnionType, + UnknownType, + VoidType, +} from '../base/Type'; +import { ArkMethod } from '../model/ArkMethod'; +import { ArkExport } from '../model/ArkExport'; +import { ArkClass } from '../model/ArkClass'; +import { ArkField } from '../model/ArkField'; +import { Value } from '../base/Value'; +import { Constant } from '../base/Constant'; +import { ArkNamespace } from '../model/ArkNamespace'; +import { + ALL, + ANY_KEYWORD, + BIGINT_KEYWORD, + BOOLEAN_KEYWORD, + CONSTRUCTOR_NAME, + GLOBAL_THIS_NAME, + NEVER_KEYWORD, + NULL_KEYWORD, + NUMBER_KEYWORD, + PROMISE, + STRING_KEYWORD, + SUPER_NAME, + THIS_NAME, + UNDEFINED_KEYWORD, + VOID_KEYWORD, +} from './TSConst'; +import { ModelUtils } from './ModelUtils'; +import { Builtin } from './Builtin'; +import { MethodSignature, MethodSubSignature, NamespaceSignature } from '../model/ArkSignature'; +import { INSTANCE_INIT_METHOD_NAME, LEXICAL_ENV_NAME_PREFIX, UNKNOWN_FILE_NAME } from './Const'; +import { EMPTY_STRING } from './ValueUtil'; +import { ImportInfo } from '../model/ArkImport'; +import { MethodParameter } from '../model/builder/ArkMethodBuilder'; +import { IRInference } from './IRInference'; +import { AbstractTypeExpr, KeyofTypeExpr, TypeQueryExpr } from '../base/TypeExpr'; +import { SdkUtils } from './SdkUtils'; +import { ModifierType } from '../model/ArkBaseModel'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'TypeInference'); + + +export class TypeInference { + + public static inferTypeInArkField(arkField: ArkField): void { + const arkClass = arkField.getDeclaringArkClass(); + const stmts = arkField.getInitializer(); + const method = arkClass.getMethodWithName(INSTANCE_INIT_METHOD_NAME) ?? + arkClass.getMethodWithName(CONSTRUCTOR_NAME); + for (const stmt of stmts) { + if (method) { + this.resolveStmt(stmt, method); + } + } + const beforeType = arkField.getType(); + if (!this.isUnclearType(beforeType)) { + return; + } + let rightType: Type | undefined; + let fieldRef: ArkInstanceFieldRef | undefined; + const lastStmt = stmts[stmts.length - 1]; + if (lastStmt instanceof ArkAssignStmt) { + rightType = lastStmt.getRightOp().getType(); + if (lastStmt.getLeftOp() instanceof ArkInstanceFieldRef) { + fieldRef = lastStmt.getLeftOp() as ArkInstanceFieldRef; + } + } + let fieldType; + if (beforeType) { + fieldType = this.inferUnclearedType(beforeType, arkClass); + } + if (fieldType) { + arkField.getSignature().setType(fieldType); + fieldRef?.setFieldSignature(arkField.getSignature()); + } else if (rightType && this.isUnclearType(beforeType) && !this.isUnclearType(rightType)) { + arkField.getSignature().setType(rightType); + fieldRef?.setFieldSignature(arkField.getSignature()); + } + } + + /** + * Infer type for a given unclear type. + * It returns an array with 2 items, original object and original type. + * The original object is null if there is no object, or it failed to find the object. + * The original type is null if failed to infer the type. + * @param leftOpType + * @param declaringArkClass + * @param visited + * @returns + */ + public static inferUnclearedType(leftOpType: Type, declaringArkClass: ArkClass, visited: Set = new Set()): Type | null | undefined { + if (visited.has(leftOpType)) { + return leftOpType; + } else { + visited.add(leftOpType); + } + let type; + if (leftOpType instanceof ClassType && + leftOpType.getClassSignature().getDeclaringFileSignature().getFileName() === UNKNOWN_FILE_NAME) { + type = TypeInference.inferUnclearRefName(leftOpType.getClassSignature().getClassName(), declaringArkClass); + } else if (leftOpType instanceof UnionType || leftOpType instanceof IntersectionType || leftOpType instanceof TupleType) { + let types = leftOpType.getTypes(); + for (let i = 0; i < types.length; i++) { + let newType = this.inferUnclearedType(types[i], declaringArkClass, visited); + if (newType) { + types[i] = newType; + } + } + type = leftOpType; + } else if (leftOpType instanceof ArrayType) { + let baseType = this.inferUnclearedType(leftOpType.getBaseType(), declaringArkClass, visited); + if (baseType) { + leftOpType.setBaseType(baseType); + type = leftOpType; + } + } else if (leftOpType instanceof AliasType) { + let baseType = this.inferUnclearedType(leftOpType.getOriginalType(), declaringArkClass, visited); + if (baseType) { + leftOpType.setOriginalType(baseType); + type = leftOpType; + } + } else if (leftOpType instanceof AnnotationNamespaceType) { + type = this.inferUnclearRefName(leftOpType.getOriginType(), declaringArkClass); + } else if (leftOpType instanceof UnclearReferenceType) { + type = this.inferUnclearRefType(leftOpType, declaringArkClass); + } + return type; + } + + public static inferTypeInMethod(arkMethod: ArkMethod): void { + const arkClass = arkMethod.getDeclaringArkClass(); + this.inferGenericType(arkMethod.getGenericTypes(), arkClass); + const signatures: MethodSignature[] = []; + arkMethod.getDeclareSignatures()?.forEach(m => signatures.push(m)); + const impl = arkMethod.getImplementationSignature(); + if (impl) { + signatures.push(impl); + } + signatures.forEach(s => { + s.getMethodSubSignature().getParameters().forEach(p => { + this.inferParameterType(p, arkMethod); + }); + }); + const body = arkMethod.getBody(); + if (!body) { + signatures.forEach(s => this.inferSignatureReturnType(s, arkMethod)); + return; + } + const cfg = body.getCfg(); + for (const block of cfg.getBlocks()) { + for (const stmt of block.getStmts()) { + this.resolveStmt(stmt, arkMethod); + } + } + signatures.forEach(s => this.inferSignatureReturnType(s, arkMethod)); + } + + private static resolveStmt(stmt: Stmt, arkMethod: ArkMethod): void { + try { + this.resolveTypeExprsInStmt(stmt, arkMethod); + this.resolveExprsInStmt(stmt, arkMethod); + this.resolveFieldRefsInStmt(stmt, arkMethod); + this.resolveArkAssignStmt(stmt, arkMethod); + this.resolveArkReturnStmt(stmt, arkMethod); + } catch (e) { + logger.warn('stmt is not correct: ' + stmt.toString()); + } + } + + /** + * @Deprecated + * @param arkMethod + */ + public static inferSimpleTypeInMethod(arkMethod: ArkMethod): void { + const body = arkMethod.getBody(); + if (!body) { + logger.warn('empty body'); + return; + } + const cfg = body.getCfg(); + for (const block of cfg.getBlocks()) { + for (const stmt of block.getStmts()) { + TypeInference.inferSimpleTypeInStmt(stmt); + } + } + } + + /** + * infer type for Exprs in stmt which invoke method. + * such as ArkInstanceInvokeExpr ArkStaticInvokeExpr ArkNewExpr + */ + private static resolveExprsInStmt(stmt: Stmt, arkMethod: ArkMethod): void { + for (const expr of stmt.getExprs()) { + const newExpr = expr.inferType(arkMethod); + if (stmt.containsInvokeExpr() && ((expr instanceof ArkInstanceInvokeExpr && newExpr instanceof ArkStaticInvokeExpr) || + newExpr instanceof ArkPtrInvokeExpr)) { + stmt.replaceUse(expr, newExpr); + } + } + if (stmt instanceof ArkAliasTypeDefineStmt && this.isUnclearType(stmt.getAliasType().getOriginalType())) { + stmt.getAliasType().setOriginalType(stmt.getAliasTypeExpr().getType()); + } + } + + /** + * infer value type for TypeExprs in stmt which specify the type such as TypeQueryExpr + */ + private static resolveTypeExprsInStmt(stmt: Stmt, arkMethod: ArkMethod): void { + for (let typeExpr of stmt.getTypeExprs()) { + typeExpr.inferType(arkMethod); + } + } + + /** + * infer type for fieldRefs in stmt. + */ + private static resolveFieldRefsInStmt(stmt: Stmt, arkMethod: ArkMethod): void { + for (const use of stmt.getUses()) { + if (use instanceof AbstractRef) { + this.processRef(use, stmt, arkMethod); + } + } + const stmtDef = stmt.getDef(); + if (stmtDef && stmtDef instanceof AbstractRef) { + if (arkMethod.getName() === INSTANCE_INIT_METHOD_NAME && stmtDef instanceof ArkInstanceFieldRef && + stmtDef.getBase().getName() === THIS_NAME && arkMethod.getDeclaringArkClass().isAnonymousClass()) { + return; + } + const fieldRef = stmtDef.inferType(arkMethod); + stmt.replaceDef(stmtDef, fieldRef); + } + } + + private static processRef(use: AbstractRef | ArkInstanceFieldRef, stmt: Stmt, arkMethod: ArkMethod): void { + const fieldRef = use.inferType(arkMethod); + if (fieldRef instanceof ArkStaticFieldRef && stmt instanceof ArkAssignStmt) { + stmt.replaceUse(use, fieldRef); + } else if (use instanceof ArkInstanceFieldRef && fieldRef instanceof ArkArrayRef && stmt instanceof ArkAssignStmt) { + const index = fieldRef.getIndex(); + if (index instanceof Constant && index.getType() instanceof StringType) { + const local = arkMethod?.getBody()?.getLocals().get(index.getValue()); + if (local) { + fieldRef.setIndex(local); + } + } + stmt.replaceUse(use, fieldRef); + } + } + + public static parseArkExport2Type(arkExport: ArkExport | undefined | null): Type | null { + if (!arkExport) { + return null; + } + if (arkExport instanceof ArkClass) { + return new ClassType(arkExport.getSignature(), arkExport.getGenericsTypes()); + } else if (arkExport instanceof ArkNamespace) { + return AnnotationNamespaceType.getInstance(arkExport.getSignature()); + } else if (arkExport instanceof ArkMethod) { + return new FunctionType(arkExport.getSignature()); + } else if (arkExport instanceof Local) { + if (arkExport.getType() instanceof UnknownType || arkExport.getType() instanceof UnclearReferenceType) { + return null; + } + return arkExport.getType(); + } else if (arkExport instanceof AliasType) { + return arkExport; + } else { + return null; + } + } + + /** + * infer and pass type for ArkAssignStmt right and left + * @param stmt + * @param arkMethod + */ + public static resolveArkAssignStmt(stmt: Stmt, arkMethod: ArkMethod): void { + if (!(stmt instanceof ArkAssignStmt)) { + return; + } + const arkClass = arkMethod.getDeclaringArkClass(); + const rightOp = stmt.getRightOp(); + if (rightOp instanceof Local && rightOp.getType() instanceof UnknownType) { + IRInference.inferLocal(rightOp, arkMethod); + } + let rightType: Type | null | undefined = rightOp.getType(); + if (this.isUnclearType(rightType)) { + rightType = this.inferUnclearedType(rightType, arkClass); + if (rightType) { + this.setValueType(rightOp, rightType); + } + } + TypeInference.resolveLeftOp(stmt, arkClass, rightType, arkMethod); + } + + private static resolveLeftOp(stmt: ArkAssignStmt, arkClass: ArkClass, rightType: Type | null | undefined, arkMethod: ArkMethod): void { + const leftOp = stmt.getLeftOp(); + let leftType: Type | null | undefined = leftOp.getType(); + if (this.isUnclearType(leftType)) { + const newLeftType = this.inferUnclearedType(leftType, arkClass); + if (!newLeftType && !this.isUnclearType(rightType)) { + leftType = rightType; + } else if (newLeftType) { + leftType = newLeftType; + } + } else if (leftOp instanceof Local && leftOp.getName() === THIS_NAME) { + const thisLocal = IRInference.inferThisLocal(arkMethod); + if (thisLocal) { + stmt.setLeftOp(thisLocal); + } else { + leftType = rightType; + } + } + if (leftType && !this.isUnclearType(leftType)) { + this.setValueType(leftOp, leftType); + if (leftOp instanceof Local && stmt.getOriginalText()?.startsWith(leftOp.getName())) { + let localDef = ModelUtils.findDeclaredLocal(leftOp, arkMethod); + if (localDef && this.isUnclearType(localDef.getType())) { + localDef.setType(leftType); + } + } + if (rightType) { + IRInference.inferRightWithSdkType(leftType, rightType, arkClass); + } + if (leftOp instanceof AbstractFieldRef) { + const declaringSignature = leftOp.getFieldSignature().getDeclaringSignature(); + if (declaringSignature instanceof NamespaceSignature && declaringSignature.getNamespaceName() === GLOBAL_THIS_NAME) { + SdkUtils.computeGlobalThis(leftOp, arkMethod); + } + } + } + } + + private static setValueType(value: Value, type: Type): void { + if (value instanceof Local || value instanceof ArkParameterRef) { + value.setType(type); + } else if (value instanceof AbstractFieldRef) { + value.getFieldSignature().setType(type); + } + } + + public static isUnclearType(type: Type | null | undefined): boolean { + // TODO: For UnionType, IntersectionType and TupleType, it should recurse check every item of them. + if (!type || type instanceof UnknownType || type instanceof UnclearReferenceType + || type instanceof NullType || type instanceof UndefinedType) { + return true; + } else if (type instanceof ClassType && (type.getClassSignature().getDeclaringFileSignature().getFileName() === UNKNOWN_FILE_NAME || + (type.getClassSignature().getDeclaringFileSignature().getFileName() === Builtin.DUMMY_FILE_NAME && + type.getRealGenericTypes()?.find(t => t instanceof GenericType)))) { + return true; + } else if (type instanceof UnionType || type instanceof IntersectionType || type instanceof TupleType) { + return !!type.getTypes().find(t => this.hasUnclearReferenceType(t)); + } else if (type instanceof ArrayType) { + const baseType = type.getBaseType(); + return this.hasUnclearReferenceType(baseType) || baseType instanceof GenericType; + } else if (type instanceof AliasType) { + return this.isUnclearType(type.getOriginalType()); + } else if (type instanceof KeyofTypeExpr) { + return this.isUnclearType(type.getOpType()); + } else if (type instanceof TypeQueryExpr) { + return this.isUnclearType(type.getType()); + } + return false; + } + + // This is the temporal function to check unclearReferenceType recursively and can be removed after typeInfer supports multiple candidate types. + private static hasUnclearReferenceType(type: Type, visited: Set = new Set()): boolean { + if (visited.has(type)) { + return false; + } else { + visited.add(type); + } + if (type instanceof UnclearReferenceType) { + return true; + } else if (type instanceof UnionType || type instanceof IntersectionType || type instanceof TupleType) { + return !!type.getTypes().find(t => this.hasUnclearReferenceType(t, visited)); + } else if (type instanceof ArrayType) { + return this.hasUnclearReferenceType(type.getBaseType(), visited); + } else if (type instanceof AliasType) { + return this.hasUnclearReferenceType(type.getOriginalType(), visited); + } else if (type instanceof KeyofTypeExpr) { + return this.hasUnclearReferenceType(type.getOpType(), visited); + } else if (type instanceof TypeQueryExpr) { + return this.hasUnclearReferenceType(type.getType(), visited); + } + return false; + } + + public static inferSimpleTypeInStmt(stmt: Stmt): void { + if (stmt instanceof ArkAssignStmt) { + const leftOp = stmt.getLeftOp(); + if (leftOp instanceof Local) { + const leftOpType = leftOp.getType(); + if (leftOpType instanceof UnknownType) { + const rightOp = stmt.getRightOp(); + leftOp.setType(rightOp.getType()); + } + } + } + } + + // Deal only with simple situations + public static buildTypeFromStr(typeStr: string): Type { + switch (typeStr) { + case BOOLEAN_KEYWORD: + return BooleanType.getInstance(); + case NUMBER_KEYWORD: + return NumberType.getInstance(); + case STRING_KEYWORD: + return StringType.getInstance(); + case UNDEFINED_KEYWORD: + return UndefinedType.getInstance(); + case NULL_KEYWORD: + return NullType.getInstance(); + case ANY_KEYWORD: + return AnyType.getInstance(); + case VOID_KEYWORD: + return VoidType.getInstance(); + case NEVER_KEYWORD: + return NeverType.getInstance(); + case BIGINT_KEYWORD: + return BigIntType.getInstance(); + case 'RegularExpression': { + const classSignature = Builtin.REGEXP_CLASS_SIGNATURE; + return new ClassType(classSignature); + } + default: + return new UnclearReferenceType(typeStr); + } + } + + public static inferValueType(value: Value, arkMethod: ArkMethod): Type | null { + if (value instanceof ArkInstanceFieldRef || value instanceof ArkInstanceInvokeExpr) { + this.inferValueType(value.getBase(), arkMethod); + } + if (value instanceof AbstractRef || value instanceof AbstractExpr || value instanceof Local) { + value.inferType(arkMethod); + } + return value.getType(); + } + + private static inferParameterType(param: MethodParameter, arkMethod: ArkMethod): void { + let pType = param.getType(); + const arkClass = arkMethod.getDeclaringArkClass(); + let type; + if (pType instanceof AbstractTypeExpr) { + pType.inferType(arkMethod); + } else if (param.getName() === 'value' && arkClass.hasComponentDecorator() && arkMethod.getName() === CONSTRUCTOR_NAME) { + type = this.parseArkExport2Type(arkClass); + } else { + type = TypeInference.inferUnclearedType(pType, arkClass); + } + if (type) { + param.setType(type); + } + } + + public static inferSignatureReturnType(oldSignature: MethodSignature, arkMethod: ArkMethod): void { + if (oldSignature.getMethodSubSignature().getMethodName() === CONSTRUCTOR_NAME) { + const newReturnType = new ClassType(oldSignature.getDeclaringClassSignature()); + oldSignature.getMethodSubSignature().setReturnType(newReturnType); + return; + } + const currReturnType = oldSignature.getType(); + if (!this.isUnclearType(currReturnType)) { + return; + } + + if (currReturnType instanceof AbstractTypeExpr) { + currReturnType.inferType(arkMethod); + return; + } + + if (currReturnType instanceof ArrayType && currReturnType.getBaseType() instanceof AbstractTypeExpr) { + (currReturnType.getBaseType() as AbstractTypeExpr).inferType(arkMethod); + return; + } + + const newReturnType = this.inferUnclearedType(currReturnType, arkMethod.getDeclaringArkClass()); + if (newReturnType) { + oldSignature.getMethodSubSignature().setReturnType(newReturnType); + } else if (arkMethod.getBody()) { + const returnType = TypeInference.inferReturnType(arkMethod); + if (returnType) { + oldSignature.getMethodSubSignature().setReturnType(returnType); + } + } + } + + private static inferReturnType(arkMethod: ArkMethod): Type | null { + const typeMap: Map = new Map(); + for (let returnValue of arkMethod.getReturnValues()) { + const type = returnValue.getType(); + if (type instanceof UnionType) { + type.flatType().filter(t => !TypeInference.isUnclearType(t)).forEach(t => typeMap.set(t.toString(), t)); + } else if (!TypeInference.isUnclearType(type)) { + typeMap.set(type.toString(), type); + } + } + if (typeMap.size > 0) { + const types: Type[] = Array.from(typeMap.values()); + let returnType = types.length === 1 ? types[0] : new UnionType(types); + if (arkMethod.containsModifier(ModifierType.ASYNC)) { + const promise = arkMethod.getDeclaringArkFile().getScene().getSdkGlobal(PROMISE); + if (promise instanceof ArkClass) { + returnType = new ClassType(promise.getSignature(), [returnType]); + } + } + return returnType; + } + return null; + } + + public static inferGenericType(types: GenericType[] | undefined, arkClass: ArkClass) { + types?.forEach(type => { + const defaultType = type.getDefaultType(); + if (defaultType instanceof UnclearReferenceType) { + const newDefaultType = TypeInference.inferUnclearRefName(defaultType.getName(), arkClass); + if (newDefaultType) { + type.setDefaultType(this.replaceTypeWithReal(newDefaultType)); + } + } + const constraint = type.getConstraint(); + if (constraint instanceof UnclearReferenceType) { + const newConstraint = TypeInference.inferUnclearRefName(constraint.getName(), arkClass); + if (newConstraint) { + type.setConstraint(this.replaceTypeWithReal(newConstraint)); + } + } + }); + } + + /** + * Infer type for a given {@link UnclearReferenceType} type. + * It returns original type. + * The original type is null if it failed to infer the type. + * @param urType + * @param arkClass + * @returns + */ + public static inferUnclearRefType(urType: UnclearReferenceType, arkClass: ArkClass): Type | null { + const realTypes = urType.getGenericTypes(); + this.inferRealGenericTypes(realTypes, arkClass); + if (urType.getName() === Builtin.ARRAY) { + return new ArrayType(realTypes[0] ?? AnyType.getInstance(), 1); + } + const type = this.inferUnclearRefName(urType.getName(), arkClass); + return type ? this.replaceTypeWithReal(type, realTypes) : null; + } + + /** + * Find out the original object and type for a given unclear reference type name. + * It returns original type. + * The original type is null if it failed to infer the type. + * @param refName + * @param arkClass + * @returns + */ + public static inferUnclearRefName(refName: string, arkClass: ArkClass): Type | null { + if (!refName) { + return null; + } + //split and iterate to infer each type + const singleNames = refName.split('.'); + let type = null; + for (let i = 0; i < singleNames.length; i++) { + let genericName: string = EMPTY_STRING; + const name = singleNames[i].replace(/<(\w+)>/, (match, group1) => { + genericName = group1; + return EMPTY_STRING; + }); + if (i === 0) { + type = this.inferBaseType(name, arkClass); + } else if (type) { + type = this.inferFieldType(type, name, arkClass)?.[1]; + } + if (!type) { + return null; + } + if (genericName) { + const realTypes = genericName.split(',').map(generic => { + const realType = this.inferBaseType(generic, arkClass); + return realType ?? new UnclearReferenceType(generic); + }); + if (type instanceof ClassType) { + type = new ClassType(type.getClassSignature(), realTypes); + } else if (type instanceof FunctionType) { + type = new FunctionType(type.getMethodSignature(), realTypes); + } + } + } + return type; + } + + /** + * Find out the original object and type for a given base type and the field name. + * It returns an array with 2 items, original object and original type. + * The original object is null if there is no object, or it failed to find the object. + * The original type is null if it failed to infer the type. + * @param baseType + * @param fieldName + * @param declareClass + * @returns + */ + public static inferFieldType(baseType: Type, fieldName: string, declareClass: ArkClass): [any, Type] | null { + if (baseType instanceof AliasType) { + baseType = baseType.getOriginalType(); + } else if (baseType instanceof UnionType && baseType.getCurrType()) { + baseType = baseType.getCurrType(); + } + let propertyAndType: [any, Type] | null = null; + if (baseType instanceof ClassType) { + if (fieldName === Builtin.ITERATOR_RESULT_VALUE && baseType.getClassSignature() + .getDeclaringFileSignature().getProjectName() === Builtin.DUMMY_PROJECT_NAME) { + const types = baseType.getRealGenericTypes(); + if (types && types.length > 0) { + return [null, types[0]]; + } + return null; + } + propertyAndType = this.inferClassFieldType(declareClass, baseType, fieldName); + } else if (baseType instanceof AnnotationNamespaceType) { + const namespace = declareClass.getDeclaringArkFile().getScene().getNamespace(baseType.getNamespaceSignature()); + if (namespace) { + const property = ModelUtils.findPropertyInNamespace(fieldName, namespace); + const propertyType = this.parseArkExport2Type(property); + if (propertyType) { + propertyAndType = [property, propertyType]; + } + } + } else { + logger.warn('infer unclear reference type fail: ' + fieldName); + } + return propertyAndType; + } + + private static inferClassFieldType(declareClass: ArkClass, baseType: ClassType, fieldName: string): [any, Type] | null { + const arkClass = declareClass.getDeclaringArkFile().getScene().getClass(baseType.getClassSignature()); + if (!arkClass) { + return null; + } + const property = ModelUtils.findPropertyInClass(fieldName, arkClass); + let propertyType: Type | null = null; + if (property instanceof ArkField) { + propertyType = property.getType(); + } else if (property) { + propertyType = this.parseArkExport2Type(property); + } + if (propertyType) { + return [property, propertyType]; + } else if (arkClass.isAnonymousClass()) { + const fieldType = this.inferUnclearRefName(fieldName, arkClass); + return fieldType ? [null, fieldType] : null; + } + return null; + } + + /** + * Find out the original object and type for a given base name. + * It returns original type. + * The original type is null if failed to infer the type. + * @param baseName + * @param arkClass + * @returns + */ + public static inferBaseType(baseName: string, arkClass: ArkClass): Type | null { + if (SUPER_NAME === baseName) { + return this.parseArkExport2Type(arkClass.getSuperClass()); + } + const field = ModelUtils.getDefaultClass(arkClass)?.getDefaultArkMethod() + ?.getBody()?.getLocals()?.get(baseName); + if (field && !this.isUnclearType(field.getType())) { + return field.getType(); + } + let arkExport: ArkExport | null = ModelUtils.getClassWithName(baseName, arkClass) + ?? ModelUtils.getDefaultClass(arkClass)?.getDefaultArkMethod()?.getBody()?.getAliasTypeByName(baseName) + ?? ModelUtils.getNamespaceWithName(baseName, arkClass) + ?? ModelUtils.getDefaultClass(arkClass)?.getMethodWithName(baseName) + ?? ModelUtils.getArkExportInImportInfoWithName(baseName, arkClass.getDeclaringArkFile()); + if (!arkExport && !arkClass.getDeclaringArkFile().getImportInfoBy(baseName)) { + arkExport = arkClass.getDeclaringArkFile().getScene().getSdkGlobal(baseName); + } + return this.parseArkExport2Type(arkExport); + } + + public static inferRealGenericTypes(realTypes: Type[] | undefined, arkClass: ArkClass): void { + if (!realTypes) { + return; + } + for (let i = 0; i < realTypes.length; i++) { + const mayType = realTypes[i]; + if (this.isUnclearType(mayType)) { + const newType = this.inferUnclearedType(mayType, arkClass); + if (newType) { + realTypes[i] = newType; + } + } + } + } + + + public static inferDynamicImportType(from: string, arkClass: ArkClass): Type | null { + const importInfo = new ImportInfo(); + importInfo.setNameBeforeAs(ALL); + importInfo.setImportClauseName(ALL); + importInfo.setImportFrom(from); + importInfo.setDeclaringArkFile(arkClass.getDeclaringArkFile()); + return TypeInference.parseArkExport2Type(importInfo.getLazyExportInfo()?.getArkExport()); + } + + + public static replaceTypeWithReal(type: Type, realTypes?: Type[], visited: Set = new Set()): Type { + if (visited.has(type)) { + return type; + } else { + visited.add(type); + } + if (type instanceof GenericType) { + const realType = realTypes?.[type.getIndex()] ?? type.getDefaultType() ?? type.getConstraint(); + return realType ?? type; + } else if (type instanceof AnyType) { + const realType = realTypes?.[0]; + return realType ?? type; + } + return this.replaceRecursiveType(type, visited, realTypes); + } + + public static replaceRecursiveType(type: Type, visited: Set, realTypes?: Type[]): Type { + if (type instanceof ClassType) { + const replacedTypes = type.getRealGenericTypes()?.map(g => this.replaceTypeWithReal(g, realTypes, visited)) ?? realTypes; + return replacedTypes && replacedTypes.length > 0 ? new ClassType(type.getClassSignature(), replacedTypes) : type; + } else if (type instanceof FunctionType) { + const replacedTypes = type.getRealGenericTypes()?.map(g => this.replaceTypeWithReal(g, realTypes, visited)) ?? realTypes; + return replacedTypes && replacedTypes.length > 0 ? new FunctionType(type.getMethodSignature(), replacedTypes) : type; + } else if (type instanceof AliasType && realTypes) { + const newObjectType = this.replaceTypeWithReal(type.getOriginalType(), realTypes, visited); + const replacedTypes = type.getRealGenericTypes()?.map(g => this.replaceTypeWithReal(g, realTypes, visited)) ?? realTypes; + if (replacedTypes.length > 0) { + const newAliasType = new AliasType(type.getName(), newObjectType, type.getSignature(), type.getGenericTypes()); + newAliasType.setRealGenericTypes(replacedTypes); + return newAliasType; + } + } else if (type instanceof UnionType && realTypes) { + const types: Type[] = []; + type.flatType().forEach(t => types.push(this.replaceTypeWithReal(t, realTypes, visited))); + return new UnionType(types, this.replaceTypeWithReal(type.getCurrType(), realTypes, visited)); + } else if (type instanceof IntersectionType && realTypes) { + const types: Type[] = []; + type.getTypes().forEach(t => types.push(this.replaceTypeWithReal(t, realTypes, visited))); + return new IntersectionType(types); + } else if (type instanceof ArrayType && realTypes) { + const replacedBaseType = this.replaceTypeWithReal(type.getBaseType(), realTypes, visited); + return new ArrayType(replacedBaseType, type.getDimension()); + } else if (type instanceof TupleType && realTypes) { + let replacedTypes: Type[] = []; + type.getTypes().forEach(t => replacedTypes.push(this.replaceTypeWithReal(t, realTypes, visited))); + return new TupleType(replacedTypes); + } + return type; + } + + public static replaceAliasType(type: Type): Type { + let aliasType = type; + while (aliasType instanceof AliasType) { + aliasType = aliasType.getOriginalType(); + } + return aliasType; + } + + + public static inferFunctionType(argType: FunctionType, paramSubSignature: MethodSubSignature | undefined, realTypes: Type[] | undefined): void { + const returnType = argType.getMethodSignature().getMethodSubSignature().getReturnType(); + const declareType = paramSubSignature?.getReturnType(); + if (declareType instanceof GenericType && realTypes && !this.isUnclearType(returnType) && !(returnType instanceof VoidType)) { + realTypes[declareType.getIndex()] = returnType; + } + const params = paramSubSignature?.getParameters(); + if (!params) { + return; + } + argType.getMethodSignature().getMethodSubSignature().getParameters() + .filter(p => !p.getName().startsWith(LEXICAL_ENV_NAME_PREFIX)) + .forEach((p, i) => { + let type = params?.[i]?.getType(); + if (type instanceof GenericType && realTypes) { + type = realTypes?.[type.getIndex()]; + } + if (type) { + p.setType(type); + } + }); + } + + private static resolveArkReturnStmt(stmt: Stmt, arkMethod: ArkMethod): void { + if (!(stmt instanceof ArkReturnStmt)) { + return; + } + let returnType: Type | undefined = arkMethod.getSignature().getType(); + if (returnType instanceof ClassType && returnType.getClassSignature().getClassName() === PROMISE) { + returnType = returnType.getRealGenericTypes()?.at(0); + } + if (returnType) { + IRInference.inferRightWithSdkType(returnType, stmt.getOp().getType(), arkMethod.getDeclaringArkClass()); + } + } + +} diff --git a/ets2panda/linter/arkanalyzer/src/core/common/ValueUtil.ts b/ets2panda/linter/arkanalyzer/src/core/common/ValueUtil.ts new file mode 100644 index 0000000000..9247f8f4db --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/common/ValueUtil.ts @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + BigIntConstant, + BooleanConstant, + Constant, + NullConstant, + NumberConstant, + StringConstant, + UndefinedConstant, +} from '../base/Constant'; + +export const EMPTY_STRING = ''; + +export class ValueUtil { + private static readonly NumberConstantCache: Map = new Map(); + public static readonly EMPTY_STRING_CONSTANT = new StringConstant(EMPTY_STRING); + + public static getOrCreateNumberConst(n: number): Constant { + let constant = this.NumberConstantCache.get(n); + if (constant === undefined) { + constant = new NumberConstant(n); + this.NumberConstantCache.set(n, constant); + } + return constant; + } + + public static createBigIntConst(bigInt: bigint): BigIntConstant { + return new BigIntConstant(bigInt); + } + + public static createStringConst(str: string): Constant { + if (str === EMPTY_STRING) { + return this.EMPTY_STRING_CONSTANT; + } + return new StringConstant(str); + } + + public static createConst(str: string): Constant { + const n = Number(str); + if (!isNaN(n)) { + return this.getOrCreateNumberConst(n); + } + return new StringConstant(str); + } + + public static getUndefinedConst(): Constant { + return UndefinedConstant.getInstance(); + } + + public static getNullConstant(): Constant { + return NullConstant.getInstance(); + } + + public static getBooleanConstant(value: boolean): Constant { + return BooleanConstant.getInstance(value); + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/common/VisibleValue.ts b/ets2panda/linter/arkanalyzer/src/core/common/VisibleValue.ts new file mode 100644 index 0000000000..6580426810 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/common/VisibleValue.ts @@ -0,0 +1,208 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Logger, { LOG_MODULE_TYPE } from '../../utils/logger'; +import { Local } from '../base/Local'; +import { ArkInstanceFieldRef, ArkStaticFieldRef } from '../base/Ref'; +import { ArkAssignStmt } from '../base/Stmt'; +import { ClassType } from '../base/Type'; +import { Value } from '../base/Value'; +import { BasicBlock } from '../graph/BasicBlock'; +import { ArkClass } from '../model/ArkClass'; +import { ArkFile } from '../model/ArkFile'; +import { ArkMethod } from '../model/ArkMethod'; +import { ArkNamespace } from '../model/ArkNamespace'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'VisibleValue'); + +export class VisibleValue { + private scopeChain: Scope[]; // 不包含currScope + private currScope: Scope; + private currVisibleValues: Value[]; + + constructor() { + // TODO:填充全局变量 + this.currScope = new Scope([], 0); + this.scopeChain = [this.currScope]; + this.currVisibleValues = [...this.currScope.values]; + } + + /** get values that is visible in curr scope */ + public getCurrVisibleValues(): Value[] { + return this.currVisibleValues; + } + + public getScopeChain(): Scope[] { + return this.scopeChain; + } + + /** udpate visible values after entered a scope, only support step by step */ + public updateIntoScope(model: ArkModel): void { + let name = ''; + if (model instanceof BasicBlock) { + name = 'block: ' + model.toString(); + } else { + name = model.getName(); + } + logger.info('---- into scope:{', name, '}'); + + + // get values in this scope + let values: Value[] = []; + if (model instanceof ArkFile || model instanceof ArkNamespace) { + values = this.getVisibleValuesIntoFileOrNameSpace(model); + } else if (model instanceof ArkClass) { + values = this.getVisibleValuesIntoClass(model); + } else if (model instanceof ArkMethod) { + values = this.getVisibleValuesIntoMethod(model); + } else if (model instanceof BasicBlock) { + values = this.getVisibleValuesIntoBasicBlock(model); + } + + // handle scope chain + const targetDepth = this.getTargetDepth(model); + this.addScope(values, targetDepth, model); + } + + /** udpate visible values after left a scope, only support step by step */ + public updateOutScope(): void { + const currModel = this.currScope.arkModel as ArkModel; + + let name = ''; + if (currModel instanceof BasicBlock) { + name = 'block: ' + currModel.toString(); + } else { + name = currModel.getName(); + } + logger.info('---- out scope:{', name, '}'); + + let targetDepth = this.currScope.depth; + if (currModel instanceof BasicBlock) { + const successorsCnt = currModel.getSuccessors().length; + // if successorsCnt <= 0, unchange + if (successorsCnt > 1) { + targetDepth += 1; // goto inner scope + } + } + this.deleteScope(targetDepth); + } + + + /** clear up previous scope */ + private deleteScope(targetDepth: number): void { + const prevDepth = this.currScope.depth; + if (targetDepth > prevDepth) { + return; + } + + let popScopeValuesCnt = 0; + let popScopeCnt = 0; + for (let i = this.scopeChain.length - 1; i >= 0; i--) { + if (this.scopeChain[i].depth < targetDepth) { + break; + } + popScopeCnt += 1; + popScopeValuesCnt += this.scopeChain[i].values.length; + } + + this.scopeChain.splice(this.scopeChain.length - popScopeCnt, popScopeCnt)[0]; // popScopeCnt >= 1 + this.currScope = this.scopeChain[this.scopeChain.length - 1] + const totalValuesCnt = this.currVisibleValues.length; + this.currVisibleValues.splice(totalValuesCnt - popScopeValuesCnt, popScopeValuesCnt); + } + + /** add this scope to scope chain and update visible values */ + private addScope(values: Value[], targetDepth: number, model: ArkModel): void { + const newScope = new Scope(values, targetDepth, model); + this.currScope = newScope; + this.scopeChain.push(this.currScope); + this.currVisibleValues.push(...this.currScope.values); + } + + // TODO:构造嵌套关系树 + private getTargetDepth(model: ArkModel): number { + const prevDepth = this.currScope.depth; + const prevModel = this.currScope.arkModel; + let targetDepth = prevDepth + 1; + if (model instanceof BasicBlock) { + const predecessorsCnt = model.getPredecessors().length; + if (predecessorsCnt <= 1) { + targetDepth = prevDepth + 1; + } else { + targetDepth = prevDepth; + } + } else if ((model instanceof ArkFile) && (prevModel instanceof ArkFile)) { + targetDepth = prevDepth; + } else if ((model instanceof ArkNamespace) && (prevModel instanceof ArkNamespace)) { + targetDepth = prevDepth; + } else if ((model instanceof ArkClass) && (prevModel instanceof ArkClass)) { + targetDepth = prevDepth; + } else if ((model instanceof ArkMethod) && (prevModel instanceof ArkMethod)) { + targetDepth = prevDepth; + } + return targetDepth; + } + + private getVisibleValuesIntoFileOrNameSpace(fileOrNameSpace: ArkFile | ArkNamespace): Value[] { + let values: Value[] = []; + return values; + } + + + private getVisibleValuesIntoClass(cls: ArkClass): Value[] { + const values: Value[] = []; + const fields = cls.getFields(); + const classSignature = cls.getSignature(); + for (const field of fields) { + if (field.isStatic()) { + const staticFieldRef = new ArkStaticFieldRef(field.getSignature()); + values.push(staticFieldRef); + } else { + const instanceFieldRef = new ArkInstanceFieldRef(new Local('this', new ClassType(classSignature)), field.getSignature()); + values.push(instanceFieldRef); + } + } + return values; + } + + private getVisibleValuesIntoMethod(method: ArkMethod): Value[] { + let visibleValues: Value[] = []; + return visibleValues; + } + + private getVisibleValuesIntoBasicBlock(basiceBlock: BasicBlock): Value[] { + const visibleValues: Value[] = []; + for (const stmt of basiceBlock.getStmts()) { + if (stmt instanceof ArkAssignStmt) { + visibleValues.push(stmt.getLeftOp()); + } + } + return visibleValues; + } +} + + +type ArkModel = ArkFile | ArkNamespace | ArkClass | ArkMethod | BasicBlock; + +export class Scope { + public values: Value[]; + public depth: number; + public arkModel: ArkModel | null; + constructor(values: Value[], depth: number = -1, arkModel: ArkModel | null = null) { + this.values = values; + this.depth = depth; + this.arkModel = arkModel; + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/dataflow/DataflowProblem.ts b/ets2panda/linter/arkanalyzer/src/core/dataflow/DataflowProblem.ts new file mode 100644 index 0000000000..b18d1efe48 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/dataflow/DataflowProblem.ts @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Stmt } from '../base/Stmt'; +import { ArkMethod } from '../model/ArkMethod'; + +export abstract class DataflowProblem { + + /** + * Transfer the outFact of srcStmt to the inFact of tgtStmt + * + * Return true if keeping progagation (i.e., tgtStmt will be added to the WorkList for further analysis) + */ + /* + abstract transferNormalEdge(srcStmt: Stmt, tgtStmt: Stmt, result: DataflowResult): boolean; + + abstract transferCallToReturnEdge(srcStmt: Stmt, tgtStmt: Stmt, result: DataflowResult): boolean; + + abstract transferCallEdge(srcStmt: Stmt, tgtStmt: Stmt, result: DataflowResult): boolean; + + abstract transferReturnEdge(srcStmt: Stmt, tgtStmt: Stmt, result: DataflowResult): boolean; + */ + + abstract getNormalFlowFunction(srcStmt:Stmt, tgtStmt:Stmt) : FlowFunction; + + abstract getCallFlowFunction(srcStmt:Stmt, method:ArkMethod) : FlowFunction; + + abstract getExitToReturnFlowFunction(srcStmt:Stmt, tgtStmt:Stmt, callStmt:Stmt) : FlowFunction; + + abstract getCallToReturnFlowFunction(srcStmt:Stmt, tgtStmt:Stmt) : FlowFunction; + + abstract createZeroValue() : D; + + abstract getEntryPoint() : Stmt; + + abstract getEntryMethod() : ArkMethod; + + abstract factEqual(d1: D, d2: D): boolean; +} + +export interface FlowFunction { + getDataFacts(d:D) : Set; +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/dataflow/DataflowResult.ts b/ets2panda/linter/arkanalyzer/src/core/dataflow/DataflowResult.ts new file mode 100644 index 0000000000..6a26568ddf --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/dataflow/DataflowResult.ts @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Stmt } from '../base/Stmt'; +import { Fact } from './Fact'; + +export class DataflowResult { + stmt2InFacts: Map = new Map(); + stmt2OutFacts: Map = new Map(); + + //should we specifically keep global facts or just embedding them into the two maps above + globalFacts: Set = new Set(); +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/dataflow/DataflowSolver.ts b/ets2panda/linter/arkanalyzer/src/core/dataflow/DataflowSolver.ts new file mode 100644 index 0000000000..ef55d3354c --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/dataflow/DataflowSolver.ts @@ -0,0 +1,353 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Scene } from '../../Scene'; +import { AbstractInvokeExpr } from '../base/Expr'; +import { ArkInvokeStmt, ArkReturnStmt, ArkReturnVoidStmt, Stmt } from '../base/Stmt'; +import { ArkMethod } from '../model/ArkMethod'; +import { DataflowProblem, FlowFunction } from './DataflowProblem'; +import { PathEdge, PathEdgePoint } from './Edge'; +import { BasicBlock } from '../graph/BasicBlock'; +import { CallGraph } from '../../callgraph/model/CallGraph'; +import { ClassHierarchyAnalysis } from '../../callgraph/algorithm/ClassHierarchyAnalysis'; +import { addCfg2Stmt } from '../../utils/entryMethodUtils'; +import { getRecallMethodInParam } from './Util'; + +/* +this program is roughly an implementation of the paper: Practical Extensions to the IFDS Algorithm. +compare to the original ifds paper : Precise Interprocedural Dataflow Analysis via Graph Reachability, +it have several improvments: +1. construct supergraph on demand(implement in this program); +2. use endSummary and incoming tables to speed up the program(implement in this program) +3. handle ssa form(not implement) +4. handle data facts which subsume another(not implement) +*/ +type CallToReturnCacheEdge = PathEdge; + +export abstract class DataflowSolver { + + protected problem: DataflowProblem; + protected workList: Array>; + protected pathEdgeSet: Set>; + protected zeroFact: D; + protected inComing: Map, Set>>; + protected endSummary: Map, Set>>; + protected summaryEdge: Set>; // summaryEdge不是加速一个函数内多次调用同一个函数,而是加速多次调用同一个函数f时,f内的函数调用 + protected scene: Scene; + protected CHA!: ClassHierarchyAnalysis; + protected stmtNexts: Map>; + protected laterEdges: Set> = new Set(); + + constructor(problem: DataflowProblem, scene: Scene) { + this.problem = problem; + this.scene = scene; + scene.inferTypes(); + this.zeroFact = problem.createZeroValue(); + this.workList = new Array>(); + this.pathEdgeSet = new Set>(); + this.inComing = new Map, Set>>(); + this.endSummary = new Map, Set>>(); + this.summaryEdge = new Set>(); + this.stmtNexts = new Map(); + } + + public solve() { + this.init(); + this.doSolve(); + } + + protected computeResult(stmt: Stmt, d: D): boolean { + for (let pathEdge of this.pathEdgeSet) { + if (pathEdge.edgeEnd.node === stmt && pathEdge.edgeEnd.fact === d) { + return true; + } + } + return false; + } + + protected getChildren(stmt: Stmt): Stmt[] { + return Array.from(this.stmtNexts.get(stmt) || []); + } + + protected init() { + let edgePoint: PathEdgePoint = new PathEdgePoint(this.problem.getEntryPoint(), this.zeroFact); + let edge: PathEdge = new PathEdge(edgePoint, edgePoint); + this.workList.push(edge); + this.pathEdgeSet.add(edge); + + // build CHA + let cg = new CallGraph(this.scene) + this.CHA = new ClassHierarchyAnalysis(this.scene, cg) + this.buildStmtMapInClass(); + this.setCfg4AllStmt(); + return; + } + + protected buildStmtMapInClass() { + const methods = this.scene.getMethods(); + methods.push(this.problem.getEntryMethod()); + for (const method of methods) { + const cfg = method.getCfg(); + const blocks: BasicBlock[] = []; + if (cfg) { + blocks.push(...cfg.getBlocks()); + } + for (const block of blocks) { + this.buildStmtMapInBlock(block); + } + } + } + + protected buildStmtMapInBlock(block: BasicBlock): void { + const stmts = block.getStmts(); + for (let stmtIndex = 0; stmtIndex < stmts.length; stmtIndex++) { + const stmt = stmts[stmtIndex]; + if (stmtIndex !== stmts.length - 1) { + this.stmtNexts.set(stmt, new Set([stmts[stmtIndex + 1]])); + } else { + const set: Set = new Set(); + for (const successor of block.getSuccessors()) { + set.add(successor.getStmts()[0]); + } + this.stmtNexts.set(stmt, set); + } + } + } + + protected setCfg4AllStmt() { + for (const cls of this.scene.getClasses()) { + for (const mtd of cls.getMethods(true)) { + addCfg2Stmt(mtd); + } + } + } + + protected getAllCalleeMethods(callNode: ArkInvokeStmt): Set { + const callSites = this.CHA.resolveCall( + this.CHA.getCallGraph().getCallGraphNodeByMethod(this.problem.getEntryMethod().getSignature()).getID(), callNode); + const methods: Set = new Set(); + for (const callSite of callSites) { + const method = this.scene.getMethod(this.CHA.getCallGraph().getMethodByFuncID(callSite.calleeFuncID)!); + if (method) { + methods.add(method); + } + } + return methods; + } + + protected getReturnSiteOfCall(call: Stmt): Stmt { + return [...this.stmtNexts.get(call)!][0]; + } + + protected getStartOfCallerMethod(call: Stmt): Stmt { + const cfg = call.getCfg()!; + const paraNum = cfg.getDeclaringMethod().getParameters().length; + return [...cfg.getBlocks()][0].getStmts()[paraNum]; + } + + protected pathEdgeSetHasEdge(edge: PathEdge) { + for (const path of this.pathEdgeSet) { + this.problem.factEqual(path.edgeEnd.fact, edge.edgeEnd.fact); + if (path.edgeEnd.node === edge.edgeEnd.node && this.problem.factEqual(path.edgeEnd.fact, edge.edgeEnd.fact) && + path.edgeStart.node === edge.edgeStart.node && this.problem.factEqual(path.edgeStart.fact, edge.edgeStart.fact)) { + return true; + } + } + return false; + } + + protected propagate(edge: PathEdge) { + if (!this.pathEdgeSetHasEdge(edge)) { + let index = this.workList.length; + for (let i = 0; i < this.workList.length; i++) { + if (this.laterEdges.has(this.workList[i])) { + index = i; + break; + } + } + this.workList.splice(index, 0, edge); + this.pathEdgeSet.add(edge); + } + } + + protected processExitNode(edge: PathEdge) { + let startEdgePoint: PathEdgePoint = edge.edgeStart; + let exitEdgePoint: PathEdgePoint = edge.edgeEnd; + const summary = this.endSummary.get(startEdgePoint); + if (summary === undefined) { + this.endSummary.set(startEdgePoint, new Set([exitEdgePoint])); + } else { + summary.add(exitEdgePoint); + } + const callEdgePoints = this.inComing.get(startEdgePoint); + if (callEdgePoints === undefined) { + if (startEdgePoint.node.getCfg()!.getDeclaringMethod() === this.problem.getEntryMethod()) { + return; + } + throw new Error('incoming does not have ' + startEdgePoint.node.getCfg()?.getDeclaringMethod().toString()); + } + for (let callEdgePoint of callEdgePoints) { + let returnSite: Stmt = this.getReturnSiteOfCall(callEdgePoint.node); + let returnFlowFunc: FlowFunction = this.problem.getExitToReturnFlowFunction(exitEdgePoint.node, returnSite, callEdgePoint.node); + this.handleFacts(returnFlowFunc, returnSite, exitEdgePoint, callEdgePoint); + } + } + + private handleFacts(returnFlowFunc: FlowFunction, returnSite: Stmt, + exitEdgePoint: PathEdgePoint, callEdgePoint: PathEdgePoint): void { + for (let fact of returnFlowFunc.getDataFacts(exitEdgePoint.fact)) { + let returnSitePoint: PathEdgePoint = new PathEdgePoint(returnSite, fact); + let cacheEdge: CallToReturnCacheEdge = new PathEdge(callEdgePoint, returnSitePoint); + let summaryEdgeHasCacheEdge = false; + for (const sEdge of this.summaryEdge) { + if (sEdge.edgeStart === callEdgePoint && sEdge.edgeEnd.node === returnSite && sEdge.edgeEnd.fact === fact) { + summaryEdgeHasCacheEdge = true; + break; + } + } + if (summaryEdgeHasCacheEdge) { + continue; + } + this.summaryEdge.add(cacheEdge); + let startOfCaller: Stmt = this.getStartOfCallerMethod(callEdgePoint.node); + for (let pathEdge of this.pathEdgeSet) { + if (pathEdge.edgeStart.node === startOfCaller && pathEdge.edgeEnd === callEdgePoint) { + this.propagate(new PathEdge(pathEdge.edgeStart, returnSitePoint)); + } + } + } + } + + protected processNormalNode(edge: PathEdge) { + let start: PathEdgePoint = edge.edgeStart; + let end: PathEdgePoint = edge.edgeEnd; + let stmts: Stmt[] = [...this.getChildren(end.node)].reverse(); + for (let stmt of stmts) { + let flowFunction: FlowFunction = this.problem.getNormalFlowFunction(end.node, stmt); + let set: Set = flowFunction.getDataFacts(end.fact); + for (let fact of set) { + let edgePoint: PathEdgePoint = new PathEdgePoint(stmt, fact); + const edge = new PathEdge(start, edgePoint) + this.propagate(edge); + this.laterEdges.add(edge); + } + } + } + + protected processCallNode(edge: PathEdge) { + let start: PathEdgePoint = edge.edgeStart; + let callEdgePoint: PathEdgePoint = edge.edgeEnd; + const invokeStmt = callEdgePoint.node as ArkInvokeStmt; + let callees: Set; + if (this.scene.getFile(invokeStmt.getInvokeExpr().getMethodSignature().getDeclaringClassSignature().getDeclaringFileSignature())) { + callees = this.getAllCalleeMethods(callEdgePoint.node as ArkInvokeStmt); + } else { + callees = new Set([getRecallMethodInParam(invokeStmt)!]); + } + let returnSite: Stmt = this.getReturnSiteOfCall(callEdgePoint.node); + for (let callee of callees) { + let callFlowFunc: FlowFunction = this.problem.getCallFlowFunction(invokeStmt, callee); + if (!callee.getCfg()) { + continue; + } + let firstStmt: Stmt = [...callee.getCfg()!.getBlocks()][0].getStmts()[callee.getParameters().length]; + let facts: Set = callFlowFunc.getDataFacts(callEdgePoint.fact); + for (let fact of facts) { + this.callNodeFactPropagate(edge, firstStmt, fact, returnSite); + } + } + let callToReturnflowFunc: FlowFunction = this.problem.getCallToReturnFlowFunction(edge.edgeEnd.node, returnSite); + let set: Set = callToReturnflowFunc.getDataFacts(callEdgePoint.fact); + for (let fact of set) { + this.propagate(new PathEdge(start, new PathEdgePoint(returnSite, fact))); + } + for (let cacheEdge of this.summaryEdge) { + if (cacheEdge.edgeStart === edge.edgeEnd && cacheEdge.edgeEnd.node === returnSite) { + this.propagate(new PathEdge(start, cacheEdge.edgeEnd)); + } + } + } + + protected callNodeFactPropagate(edge: PathEdge, firstStmt: Stmt, fact: D, returnSite: Stmt): void { + let callEdgePoint: PathEdgePoint = edge.edgeEnd; + // method start loop path edge + let startEdgePoint: PathEdgePoint = new PathEdgePoint(firstStmt, fact); + this.propagate(new PathEdge(startEdgePoint, startEdgePoint)); + //add callEdgePoint in inComing.get(startEdgePoint) + let coming: Set> | undefined; + for (const incoming of this.inComing.keys()) { + if (incoming.fact === startEdgePoint.fact && incoming.node === startEdgePoint.node) { + coming = this.inComing.get(incoming); + break; + } + } + if (coming === undefined) { + this.inComing.set(startEdgePoint, new Set([callEdgePoint])); + } else { + coming.add(callEdgePoint); + } + let exitEdgePoints: Set> = new Set(); + for (const end of Array.from(this.endSummary.keys())) { + if (end.fact === fact && end.node === firstStmt) { + exitEdgePoints = this.endSummary.get(end)!; + } + } + for (let exitEdgePoint of exitEdgePoints) { + let returnFlowFunc = this.problem.getExitToReturnFlowFunction(exitEdgePoint.node, returnSite, callEdgePoint.node); + for (let returnFact of returnFlowFunc.getDataFacts(exitEdgePoint.fact)) { + this.summaryEdge.add(new PathEdge(edge.edgeEnd, new PathEdgePoint(returnSite, returnFact))); + } + } + } + + protected doSolve() { + while (this.workList.length !== 0) { + let pathEdge: PathEdge = this.workList.shift()!; + if (this.laterEdges.has(pathEdge)) { + this.laterEdges.delete(pathEdge); + } + let targetStmt: Stmt = pathEdge.edgeEnd.node; + if (this.isCallStatement(targetStmt)) { + this.processCallNode(pathEdge); + } else if (this.isExitStatement(targetStmt)) { + this.processExitNode(pathEdge); + } else { + this.processNormalNode(pathEdge); + } + } + } + + protected isCallStatement(stmt: Stmt): boolean { + for (const expr of stmt.getExprs()) { + if (expr instanceof AbstractInvokeExpr) { + if (this.scene.getFile(expr.getMethodSignature().getDeclaringClassSignature().getDeclaringFileSignature())) { + return true; + } + if (stmt instanceof ArkInvokeStmt && getRecallMethodInParam(stmt)) { + return true; + } + } + } + return false; + } + + protected isExitStatement(stmt: Stmt): boolean { + return stmt instanceof ArkReturnStmt || stmt instanceof ArkReturnVoidStmt; + } + + public getPathEdgeSet(): Set> { + return this.pathEdgeSet; + } +} diff --git a/ets2panda/linter/arkanalyzer/src/core/dataflow/Edge.ts b/ets2panda/linter/arkanalyzer/src/core/dataflow/Edge.ts new file mode 100644 index 0000000000..c758713bcb --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/dataflow/Edge.ts @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Stmt } from '../base/Stmt'; + +export class PathEdgePoint { + public node:Stmt; + public fact:D; + + constructor(node:Stmt, fact:D){ + this.node = node; + this.fact = fact; + } +} + +export class PathEdge { + public edgeStart:PathEdgePoint; + public edgeEnd:PathEdgePoint; + + constructor(start:PathEdgePoint, end:PathEdgePoint) { + this.edgeStart=start; + this.edgeEnd=end; + } +} diff --git a/ets2panda/linter/arkanalyzer/src/core/dataflow/Fact.ts b/ets2panda/linter/arkanalyzer/src/core/dataflow/Fact.ts new file mode 100644 index 0000000000..0e8eea6ca0 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/dataflow/Fact.ts @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Value } from '../base/Value'; +import { Stmt } from '../base/Stmt'; + +export class Fact { + values: Set = new Set(); + valueMap: Map = new Map(); // 用最近的def代表value的值 +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/dataflow/GenericDataFlow.ts b/ets2panda/linter/arkanalyzer/src/core/dataflow/GenericDataFlow.ts new file mode 100644 index 0000000000..1c92187866 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/dataflow/GenericDataFlow.ts @@ -0,0 +1,232 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Generic Data Flow Analysis Framework + * + * This module provides a generic framework for implementing data flow analyses, + * such as Reaching Definitions, Live Variables, and Available Expressions. + * The framework is designed to be flexible and extensible, allowing users to + * define custom flow graphs, transfer functions, and meet operations. + * + * Design Notes: + * - The framework is designed to be generic and reusable, allowing users to + * implement custom data flow analyses by defining appropriate transfer functions + * and meet operations. + * - The solver uses a worklist algorithm to efficiently compute the MFP solution. + * - The analysis can be configured as either forward or backward, depending on + * the problem requirements. + * + */ + +/** + * Represents a flow graph for data flow analysis. + * Provides access to nodes in post-order and reverse post-order, as well as + * methods to retrieve successors and predecessors of a given node. + * + * @template T - The type of nodes in the graph (e.g., node IDs or node objects). + */ +export interface FlowGraph { + // Nodes in reverse post-order, which is useful for backward data flow analysis. + nodesInReversePostOrder?: T[]; + // Nodes in post-order, which is useful for forward data flow analysis. + nodesInPostOrder: T[]; + // Get precessors of Node t. + pred(t: T): T[]; + // Get successors of Node t. + succ(t: T): T[]; +} + +/** + * DS (Data Set) is an interface that defines the basic operations for a data set. + * It requires the data set to be iterable, comparable, and countable. + */ +interface DS { + /** + * Returns an iterator that allows iterating over the elements of the data set. + * @returns An iterable iterator over the elements of the data set. + */ + [Symbol.iterator](): IterableIterator; + + /** + * Checks whether the current data set is equal to another data set. + */ + equals(d: DS): boolean; + + /** + * Counts the number of elements in the data set. + */ + count(): number; +} + +/** + * Represents the transfer function used in data flow analysis. + * The transfer function computes the output value (out set) of a node + * based on its input value (in set) and the node's properties. + * + * @template Node - The type of nodes in the graph. + * @template V - The type of data flow values (e.g., sets, bit vectors). + */ +export interface TransferFunction { + /** + * Computes the output value for a node based on its input value. + * + * @param n - The node for which the output value is computed. + * @param x - The input value (in set) for the node. + * @returns The output value (out set) for the node. + */ + apply(n: Node, x: V): V; +} + +/** + * Represents a data flow problem, encapsulating all the necessary components + * for performing data flow analysis, such as the flow graph, transfer function, + * meet operation, and initialization configuration. + * + * @template Node - The type of nodes in the graph. + * @template V - The type of data flow values. + */ +export interface DataFlowProblem { + /** + * The flow graph for the data flow analysis. + */ + flowGraph: FlowGraph; + /** + * The transfer function used to compute out sets from in sets. + */ + transferFunction: TransferFunction; + /** + * The meet operation used to combine values from multiple paths (e.g., union or intersection). + */ + meet: (a: V, b: V) => V; + /** + * The initialization configuration for in and out sets. + */ + initIn: Map; + initOut: Map; + /** + * Indicates whether the analysis is forward (true) or backward (false). + */ + forward: boolean; + /** + * The empty value used to initialize in and out sets (e.g., an empty set). + */ + empty: V; +} + +/** + * Represents the result of a data flow analysis. + * Contains the in and out sets for each node, as well as the corresponding data flow problem. + * + * @template Node - The type of nodes in the graph. + * @template V - The type of data flow values. + */ +export class Solution { + in: Map; + out: Map; + problem: DataFlowProblem; + + constructor(i: Map, out: Map, problem: DataFlowProblem) { + this.in = i; + this.out = out; + this.problem = problem; + } +} + +/** + * A solver for data flow analysis problems. + * Implements forward and backward data flow analysis using a worklist algorithm. + * The solver computes the Maximum Fixed Point (MFP) solution, which is a safe + * over-approximation of the ideal Meet-Over-All-Paths (MOP) solution. + */ +export class MFPDataFlowSolver { + /** + * Computes the MFP solution for a forward data flow analysis problem. + * + * @template Node - The type of nodes in the graph. + * @template V - The type of data flow values. + * @param problem - The data flow problem to solve. + * @returns The solution containing the in and out sets for all nodes. + */ + calculateMopSolutionForwards(problem: DataFlowProblem): Solution { + let _out: Map = problem.initOut; + let _in: Map = problem.initIn; + let workList: Node[] = problem.flowGraph.nodesInPostOrder; + let newEntries: Set = new Set(); + + while (workList.length > 0) { + newEntries.clear(); + workList.forEach((n) => { + let inSet: V | undefined; + const predecessors = problem.flowGraph.pred(n); + if (predecessors && predecessors.length > 0) { + const predecessorOuts = predecessors.map((pred) => _out.get(pred)); + inSet = predecessorOuts.reduce((acc, cur) => problem.meet(acc!, cur!), problem.empty); + } else { + inSet = problem.empty; + } + + _in.set(n, inSet!); + let old: V | undefined = _out.get(n); + let newSet: V = problem.transferFunction.apply(n, inSet!); + + if (!old || old.count() === 0 || !old.equals(newSet)) { + _out.set(n, newSet); + problem.flowGraph.succ(n).forEach((succ) => newEntries.add(succ)); + } + }); + + workList = [...newEntries]; + } + + return new Solution(_in, _out, problem); + } + + /** + * Computes the MFP solution for a backward data flow analysis problem. + * + * @template Node - The type of nodes in the graph. + * @template V - The type of data flow values. + * @param problem - The data flow problem to solve. + * @returns The solution containing the in and out sets for all nodes. + */ + calculateMopSolutionBackwards(problem: DataFlowProblem): Solution { + let _out: Map = problem.initOut; + let _in: Map = problem.initIn; + let workList: Node[] = problem.flowGraph.nodesInPostOrder; + let newEntries: Set = new Set(); + + while (workList.length > 0) { + newEntries.clear(); + workList.forEach((n) => { + let outSet: T = problem.flowGraph.succ(n).reduce((acc, curr) => { + return problem.meet(acc, _in.get(curr)!); + }, problem.empty); + + _out.set(n, outSet); + let old: T | undefined = _in.get(n); + let newSet: T = problem.transferFunction.apply(n, outSet); + if (!old || !old.equals(newSet)) { + _in.set(n, newSet); + problem.flowGraph.pred(n).forEach((pred) => newEntries.add(pred)); + } + }); + + workList = [...newEntries]; + } + + return new Solution(_in, _out, problem); + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/dataflow/ReachingDef.ts b/ets2panda/linter/arkanalyzer/src/core/dataflow/ReachingDef.ts new file mode 100644 index 0000000000..da681fd845 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/dataflow/ReachingDef.ts @@ -0,0 +1,205 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Reaching Definitions Data Flow Analysis + * + * This module implements the Reaching Definitions data flow analysis algorithm. + * Reaching Definitions is a forward data flow analysis that determines, for each + * program point, the set of variable definitions (assignments) that may reach + * that point without being overwritten. + * + * Key Components: + * 1. **Transfer Function**: + * - Computes the out set for each node based on its in set. + * - Uses gen and kill sets to model the effects of assignments: + * - **gen**: The set of definitions generated by the current node. + * - **kill**: The set of definitions killed (overwritten) by the current node. + * + * 2. **Meet Operation**: + * - Combines data flow values from multiple paths (e.g., union for reaching definitions). + * - Ensures that the analysis is conservative (safe) by over-approximating the result. + * + * The analysis is forward, meaning it propagates information from predecessors to successors. + * + */ + +import { ArkAssignStmt, Stmt } from '../base/Stmt'; +import { Value } from '../base/Value'; +import { BaseImplicitGraph, NodeID } from '../graph/BaseImplicitGraph'; +import { ArkMethod } from '../model/ArkMethod'; +import { DataFlowProblem, TransferFunction, FlowGraph } from './GenericDataFlow'; +import { SparseBitVector } from '../../utils/SparseBitVector'; +import { Cfg } from '../graph/Cfg'; + +type RDNode = Stmt; +type DFNodeCollection = SparseBitVector; +let coCtor: new (s: number) => SparseBitVector = SparseBitVector; +const BV_SIZE = 32; + +export class ReachingDefProblem implements DataFlowProblem { + flowGraph: ReachingDefFlowGraph; + transferFunction: ReachingDefTransferFunction; + meet: (a: DFNodeCollection, b: DFNodeCollection) => DFNodeCollection; + initIn: Map; + initOut: Map; + forward: boolean; + empty: DFNodeCollection = new coCtor(BV_SIZE); + + constructor(method: ArkMethod, forward: boolean = true) { + this.flowGraph = new ReachingDefFlowGraph(method); + this.transferFunction = new ReachingDefTransferFunction(this.flowGraph); + this.meet = (x: DFNodeCollection, y: DFNodeCollection): DFNodeCollection => { + let r = x.clone(); + r.unionWith(y); + return r; + }; + this.initIn = new Map(this.flowGraph.nodesInPostOrder.map((i) => [i, new coCtor(BV_SIZE)])); + this.initOut = new Map(this.flowGraph.nodesInPostOrder.map((i) => [i, new coCtor(BV_SIZE)])); + this.forward = forward; + } +} + +/** + * Represents the control flow graph (CFG) for reaching definitions analysis. + * This class implements the FlowGraph interface and provides methods to retrieve + * successors and predecessors of nodes, as well as topological orderings of nodes. + */ +class ReachingDefFlowGraph extends BaseImplicitGraph implements FlowGraph { + nodesInPostOrder: NodeID[]; + + constructor(method: ArkMethod) { + super(); + const cfg = method.getCfg(); + if (!cfg) { + throw new Error('CFG not found'); + } + + const nodes = cfg.getStmts(); + this.nodeToIdMap = new Map(nodes.map((x, i) => [x, i])); + this.idToNodeMap = new Map(nodes.map((x, i) => [i, x])); + this.nodesInPostOrder = nodes.map((_, i) => i); + + this.initSuccPred(nodes, cfg); + } + + getGraphName(): string { + return 'Reaching Definition Flow Graph'; + } + + dumpNodes(): void { + this.nodeToIdMap?.forEach((id, node) => console.log(id + ': ' + node.toString())); + } + + private initSuccPred(nodes: RDNode[], cfg: Cfg): void { + this.succMap = new Map(); + this.predMap = new Map(); + + cfg.getBlocks().forEach((bb) => { + let stmts = bb.getStmts(); + if (stmts.length === 0) { + return; + } + + for (let i = 0; i < stmts.length - 1; i++) { + let c = this.nodeToIdMap!.get(stmts[i])!; + let n = this.nodeToIdMap!.get(stmts[i + 1])!; + if (c === undefined || n === undefined) { + continue; + } + this.succMap.set(c, [n]); + this.predMap.set(n, [c]); + } + + let terminate = bb.getTail(); + if (!terminate) { + throw new Error('cfg has no terminal'); + } + + bb.getSuccessors().forEach((succBB) => { + let head = succBB.getHead(); + if (!head) { + return; + } + let t = this.nodeToIdMap?.get(terminate!)!; + let h = this.nodeToIdMap?.get(head)!; + if (t === undefined || h === undefined) { + return; + } + // Terminate's succ + let succ = this.succMap.get(t) ?? []; + succ.push(h); + this.succMap.set(t, succ); + + // Head's pred + let pred = this.predMap.get(h) ?? []; + pred.push(t); + this.predMap.set(h, pred); + }); + }); + } +} + +/** + * Represents the transfer function for reaching definitions analysis. + */ +export class ReachingDefTransferFunction implements TransferFunction { + gen: DFNodeCollection; + kill: Map; + + constructor(flowGraph: ReachingDefFlowGraph) { + this.gen = new coCtor(BV_SIZE); + this.kill = new Map(); + this.initGenKill(flowGraph); + } + + apply(n: NodeID, x: DFNodeCollection): DFNodeCollection { + const result = x.clone(); + if (this.gen.test(n)) { + result.set(n); + } + + const killSet = this.kill.get(n); + if (killSet) { + for (const item of killSet) { + result.reset(item); + } + } + return result; + } + + private initGenKill(g: ReachingDefFlowGraph): void { + let genValue2Nodes: Map = new Map(); + // Init Gen + g.getNodeToIdMap().forEach((id, node) => { + if (node instanceof ArkAssignStmt) { + let lop = node.getLeftOp(); + let genNodes = genValue2Nodes.get(lop) ?? new coCtor(BV_SIZE); + genNodes.set(id); + genValue2Nodes.set(lop, genNodes); + this.gen.set(id); + } + }); + + // Init Kill + genValue2Nodes.forEach((defNodes, v) => { + for (const i of defNodes) { + const killSet = defNodes.clone(); + killSet.reset(i); + this.kill.set(i, killSet); + } + }); + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/dataflow/UndefinedVariable.ts b/ets2panda/linter/arkanalyzer/src/core/dataflow/UndefinedVariable.ts new file mode 100644 index 0000000000..8d1512ec72 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/dataflow/UndefinedVariable.ts @@ -0,0 +1,263 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Scene } from '../../Scene'; +import { DataflowProblem, FlowFunction } from './DataflowProblem'; +import { Local } from '../base/Local'; +import { Value } from '../base/Value'; +import { ClassType, UndefinedType } from '../base/Type'; +import { ArkAssignStmt, ArkInvokeStmt, Stmt } from '../base/Stmt'; +import { ArkMethod } from '../model/ArkMethod'; +import { Constant } from '../base/Constant'; +import { AbstractRef, ArkInstanceFieldRef, ArkStaticFieldRef } from '../base/Ref'; +import { DataflowSolver } from './DataflowSolver'; +import { ArkInstanceInvokeExpr, ArkStaticInvokeExpr } from '../base/Expr'; +import { FileSignature, NamespaceSignature } from '../model/ArkSignature'; +import { ArkClass } from '../model/ArkClass'; +import { LocalEqual, RefEqual } from './Util'; +import { INSTANCE_INIT_METHOD_NAME, STATIC_INIT_METHOD_NAME } from '../common/Const'; +import { ArkField } from '../model/ArkField'; +import Logger, { LOG_MODULE_TYPE } from '../../utils/logger'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'Scene'); + +export class UndefinedVariableChecker extends DataflowProblem { + zeroValue: Constant = new Constant('undefined', UndefinedType.getInstance()); + entryPoint: Stmt; + entryMethod: ArkMethod; + scene: Scene; + classMap: Map; + globalVariableMap: Map; + outcomes: Outcome[] = []; + constructor(stmt: Stmt, method: ArkMethod){ + super(); + this.entryPoint = stmt; + this.entryMethod = method; + this.scene = method.getDeclaringArkFile().getScene(); + this.classMap = this.scene.getClassMap(); + this.globalVariableMap = this.scene.getGlobalVariableMap(); + } + + getEntryPoint(): Stmt { + return this.entryPoint; + } + + getEntryMethod(): ArkMethod { + return this.entryMethod; + } + + private isUndefined(val: Value): boolean { + if (val instanceof Constant) { + let constant: Constant = val as Constant; + if (constant.getType() instanceof UndefinedType) { + return true; + } + } + return false; + } + + getNormalFlowFunction(srcStmt:Stmt, tgtStmt:Stmt): FlowFunction { + let checkerInstance: UndefinedVariableChecker = this; + return new class implements FlowFunction { + getDataFacts(dataFact: Value): Set { + let ret: Set = new Set(); + if (checkerInstance.getEntryPoint() === srcStmt && checkerInstance.getZeroValue() === dataFact) { + ret.add(checkerInstance.getZeroValue()); + return ret; + } + if (srcStmt instanceof ArkAssignStmt ) { + checkerInstance.insideNormalFlowFunction(ret, srcStmt, dataFact); + } + return ret; + } + } + } + + insideNormalFlowFunction(ret: Set, srcStmt: ArkAssignStmt, dataFact: Value): void { + if (!this.factEqual(srcStmt.getDef()!, dataFact)) { + if (!(dataFact instanceof Local && dataFact.getName() === srcStmt.getDef()!.toString())) { + ret.add(dataFact); + } + } + let ass: ArkAssignStmt = (srcStmt as ArkAssignStmt); + let assigned: Value = ass.getLeftOp(); + let rightOp: Value = ass.getRightOp(); + if (this.getZeroValue() === dataFact) { + if (this.isUndefined(rightOp)) { + ret.add(assigned); + } + } else if (this.factEqual(rightOp, dataFact) || rightOp.getType() instanceof UndefinedType) { + ret.add(assigned); + } else if (rightOp instanceof ArkInstanceFieldRef) { + const base = rightOp.getBase(); + if (base === dataFact || !base.getDeclaringStmt() && base.getName() === dataFact.toString()) { + this.outcomes.push(new Outcome(rightOp, ass)); + logger.info('undefined base'); + logger.info(srcStmt.toString()); + logger.info(srcStmt.getOriginPositionInfo().toString()); + } + } else if (dataFact instanceof ArkInstanceFieldRef && rightOp === dataFact.getBase()) { + const field = new ArkInstanceFieldRef(srcStmt.getLeftOp() as Local, dataFact.getFieldSignature()); + ret.add(field); + } + } + + getCallFlowFunction(srcStmt:Stmt, method:ArkMethod): FlowFunction { + let checkerInstance: UndefinedVariableChecker = this; + return new class implements FlowFunction { + getDataFacts(dataFact: Value): Set { + const ret: Set = new Set(); + if (checkerInstance.getZeroValue() === dataFact) { + checkerInstance.insideCallFlowFunction(ret, method); + } else { + const callExpr = srcStmt.getExprs()[0]; + if (callExpr instanceof ArkInstanceInvokeExpr && dataFact instanceof ArkInstanceFieldRef && callExpr.getBase().getName() === dataFact.getBase().getName()) { + // todo:base转this + const thisRef = new ArkInstanceFieldRef(new Local('this', new ClassType(method.getDeclaringArkClass().getSignature())), dataFact.getFieldSignature()); + ret.add(thisRef); + } else if (callExpr instanceof ArkStaticInvokeExpr && dataFact instanceof ArkStaticFieldRef && callExpr.getMethodSignature().getDeclaringClassSignature() === dataFact.getFieldSignature().getDeclaringSignature()) { + ret.add(dataFact); + } + } + checkerInstance.addParameters(srcStmt, dataFact, method, ret); + return ret; + } + } + } + + insideCallFlowFunction(ret: Set, method: ArkMethod): void { + ret.add(this.getZeroValue()); + // 加上调用函数能访问到的所有静态变量,如果不考虑多线程,加上所有变量,考虑则要统计之前已经处理过的变量并排除 + for (const field of method.getDeclaringArkClass().getStaticFields(this.classMap)) { + if (field.getInitializer() === undefined) { + ret.add(new ArkStaticFieldRef(field.getSignature())); + } + } + for (const local of method.getDeclaringArkClass().getGlobalVariable(this.globalVariableMap)) { + ret.add(local); + } + // 加上所有未定义初始值的属性 + if (method.getName() === INSTANCE_INIT_METHOD_NAME || method.getName() === STATIC_INIT_METHOD_NAME) { + for (const field of method.getDeclaringArkClass().getFields()) { + this.addUndefinedField(field, method, ret); + } + } + } + + addUndefinedField(field: ArkField, method: ArkMethod, ret: Set): void { + let defined = false; + for (const stmt of method.getCfg()!.getStmts()) { + const def = stmt.getDef(); + if (def instanceof ArkInstanceFieldRef && def.getFieldSignature() === field.getSignature()) { + defined = true; + break; + } + } + if (!defined) { + const fieldRef = new ArkInstanceFieldRef(new Local('this', new ClassType(method.getDeclaringArkClass().getSignature())), field.getSignature()); + ret.add(fieldRef); + } + } + + addParameters(srcStmt: Stmt, dataFact: Value, method: ArkMethod, ret: Set): void { + const callStmt = srcStmt as ArkInvokeStmt; + const args = callStmt.getInvokeExpr().getArgs(); + for (let i = 0; i < args.length; i++) { + if (args[i] === dataFact || this.isUndefined(args[i]) && this.getZeroValue() === dataFact) { + const realParameter = [...method.getCfg()!.getBlocks()][0].getStmts()[i].getDef(); + if (realParameter) { + ret.add(realParameter); + } + } else if (dataFact instanceof ArkInstanceFieldRef && dataFact.getBase().getName() === args[i].toString()) { + const realParameter = [...method.getCfg()!.getBlocks()][0].getStmts()[i].getDef(); + if (realParameter) { + const retRef = new ArkInstanceFieldRef(realParameter as Local, dataFact.getFieldSignature()); + ret.add(retRef); + } + } + } + } + + getExitToReturnFlowFunction(srcStmt:Stmt, tgtStmt:Stmt, callStmt:Stmt): FlowFunction { + let checkerInstance: UndefinedVariableChecker = this; + return new class implements FlowFunction { + getDataFacts(dataFact: Value): Set { + let ret: Set = new Set(); + if (dataFact === checkerInstance.getZeroValue()) { + ret.add(checkerInstance.getZeroValue()); + } + return ret; + } + + } + } + + getCallToReturnFlowFunction(srcStmt:Stmt, tgtStmt:Stmt): FlowFunction { + let checkerInstance: UndefinedVariableChecker = this; + return new class implements FlowFunction { + getDataFacts(dataFact: Value): Set { + const ret:Set = new Set(); + if (checkerInstance.getZeroValue() === dataFact) { + ret.add(checkerInstance.getZeroValue()); + } + const defValue = srcStmt.getDef(); + if (!(defValue && defValue === dataFact)) { + ret.add(dataFact); + } + return ret; + } + + } + } + + createZeroValue(): Value { + return this.zeroValue; + } + + getZeroValue(): Value { + return this.zeroValue; + } + + factEqual(d1: Value, d2: Value): boolean { + if (d1 instanceof Constant && d2 instanceof Constant) { + return d1 === d2; + } else if (d1 instanceof Local && d2 instanceof Local) { + return LocalEqual(d1, d2); + } else if (d1 instanceof AbstractRef && d2 instanceof AbstractRef) { + return RefEqual(d1, d2); + } + return false; + } + + public getOutcomes(): Outcome[] { + return this.outcomes; + } +} + +export class UndefinedVariableSolver extends DataflowSolver { + constructor(problem: UndefinedVariableChecker, scene: Scene){ + super(problem, scene); + } +} + + +class Outcome { + value: Value; + stmt: Stmt; + constructor(v: Value, s: Stmt) { + this.value = v; + this.stmt = s; + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/dataflow/Util.ts b/ets2panda/linter/arkanalyzer/src/core/dataflow/Util.ts new file mode 100644 index 0000000000..8bb2346eb6 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/dataflow/Util.ts @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkInvokeStmt } from "../base/Stmt"; +import { FunctionType } from "../base/Type"; +import { ArkMethod } from "../model/ArkMethod"; +import { Local } from "../base/Local"; +import { AbstractRef, ArkStaticFieldRef, ArkInstanceFieldRef } from "../base/Ref"; + + +export const INTERNAL_PARAMETER_SOURCE: string[] = [ + '@ohos.app.ability.Want.d.ts: Want' +] + +export const INTERNAL_SINK_METHOD: string[] = [ + 'console.<@%unk/%unk: .log()>', + 'console.<@%unk/%unk: .error()>', + 'console.<@%unk/%unk: .info()>', + 'console.<@%unk/%unk: .warn()>', + 'console.<@%unk/%unk: .assert()>' +] + +export function getRecallMethodInParam(stmt: ArkInvokeStmt): ArkMethod | null { + for (const param of stmt.getInvokeExpr().getArgs()) { + if (param.getType() instanceof FunctionType) { + const methodSignature = (param.getType() as FunctionType).getMethodSignature(); + const method = stmt.getCfg()?.getDeclaringMethod().getDeclaringArkClass().getMethod(methodSignature); + if (method) { + return method; + } + } + } + return null; +} + + +export function LocalEqual(local1: Local, local2: Local): boolean { + if (local1.getName() === 'this' && local2.getName() === 'this') { + return true; + } + const method1 = local1.getDeclaringStmt()?.getCfg()?.getDeclaringMethod(); + const method2 = local2.getDeclaringStmt()?.getCfg()?.getDeclaringMethod(); + const nameEqual = local1.getName() === local2.getName(); + return method1 === method2 && nameEqual; +} + +export function RefEqual(ref1: AbstractRef, ref2: AbstractRef): boolean { + if (ref1 instanceof ArkStaticFieldRef && ref2 instanceof ArkStaticFieldRef) { + return ref1.getFieldSignature().toString() === ref2.getFieldSignature().toString(); + } else if (ref1 instanceof ArkInstanceFieldRef && ref2 instanceof ArkInstanceFieldRef) { + return LocalEqual(ref1.getBase(), ref2.getBase()) && ref1.getFieldSignature().toString() === ref2.getFieldSignature().toString(); + } + return false; +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/graph/BaseExplicitGraph.ts b/ets2panda/linter/arkanalyzer/src/core/graph/BaseExplicitGraph.ts new file mode 100644 index 0000000000..5823fec536 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/graph/BaseExplicitGraph.ts @@ -0,0 +1,205 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Kind, NodeID, GraphTraits } from './GraphTraits'; + +export {Kind, NodeID}; +export abstract class BaseEdge { + private src: BaseNode; + private dst: BaseNode; + protected kind: Kind; + + constructor(s: BaseNode, d: BaseNode, k: Kind) { + this.src = s; + this.dst = d; + this.kind = k; + } + + public getSrcID(): NodeID { + return this.src.getID(); + } + + public getDstID(): NodeID { + return this.dst.getID(); + } + + public getSrcNode(): BaseNode { + return this.src; + } + + public getDstNode(): BaseNode { + return this.dst; + } + + public getKind(): Kind { + return this.kind; + } + + public setKind(kind: Kind): void { + this.kind = kind; + } + + public getEndPoints(): { src: NodeID; dst: NodeID } { + return { + src: this.src.getID(), + dst: this.dst.getID(), + }; + } + + public getDotAttr(): string { + return 'color=black'; + } +} + +export abstract class BaseNode { + private id: NodeID; + protected kind: Kind; + private inEdges: Set = new Set(); + private outEdges: Set = new Set(); + + constructor(id: NodeID, k: Kind) { + this.id = id; + this.kind = k; + } + + public getID(): NodeID { + return this.id; + } + + public getKind(): Kind { + return this.kind; + } + + public setKind(kind: Kind): void { + this.kind = kind; + } + + public hasIncomingEdges(): boolean { + return this.inEdges.size !== 0; + } + + public hasOutgoingEdges(): boolean { + return this.outEdges.size === 0; + } + + public hasIncomingEdge(e: BaseEdge): boolean { + return this.inEdges.has(e); + } + + public hasOutgoingEdge(e: BaseEdge): boolean { + return this.outEdges.has(e); + } + + public addIncomingEdge(e: BaseEdge): void { + this.inEdges.add(e); + } + + public addOutgoingEdge(e: BaseEdge): void { + this.outEdges.add(e); + } + + public removeIncomingEdge(e: BaseEdge): boolean { + return this.inEdges.delete(e); + } + + public removeOutgoingEdge(e: BaseEdge): boolean { + return this.outEdges.delete(e); + } + + public getIncomingEdge(): Set { + return this.inEdges; + } + + public getOutgoingEdges(): Set { + return this.outEdges; + } + + public getDotAttr(): string { + return 'shape=box'; + } + + public abstract getDotLabel(): string; +} + +export abstract class BaseExplicitGraph implements GraphTraits { + protected edgeNum: number = 0; + protected nodeNum: number = 0; + protected idToNodeMap: Map; + protected edgeMarkSet: Set; + + constructor() { + this.idToNodeMap = new Map(); + this.edgeMarkSet = new Set(); + } + + public getNodeNum(): number { + return this.nodeNum; + } + + public nodesItor(): IterableIterator { + return this.idToNodeMap.values(); + } + + public addNode(n: BaseNode): void { + this.idToNodeMap.set(n.getID(), n); + this.nodeNum++; + } + + public getNode(id: NodeID): BaseNode | undefined { + if (!this.idToNodeMap.has(id)) { + throw new Error(`Can find Node # ${id}`); + } + + return this.idToNodeMap.get(id); + } + + public hasNode(id: NodeID): boolean { + return this.idToNodeMap.has(id); + } + + public removeNode(id: NodeID): boolean { + if (this.idToNodeMap.delete(id)) { + this.nodeNum--; + return true; + } + return false; + } + + public hasEdge(src: BaseNode, dst: BaseNode): boolean { + for (let e of src.getOutgoingEdges()) { + if (e.getDstNode() === dst) { + return true; + } + } + + return false; + } + + public ifEdgeExisting(edge: BaseEdge): boolean { + let edgeMark: string = `${edge.getSrcID()}-${edge.getDstID()}:${edge.getKind()}`; + if (this.edgeMarkSet.has(edgeMark)) { + return true; + } + + this.edgeMarkSet.add(edgeMark); + return false; + } + + public getNodesIter(): IterableIterator { + return this.idToNodeMap.values(); + } + + public abstract getGraphName(): string; +} diff --git a/ets2panda/linter/arkanalyzer/src/core/graph/BaseImplicitGraph.ts b/ets2panda/linter/arkanalyzer/src/core/graph/BaseImplicitGraph.ts new file mode 100644 index 0000000000..671b642c4c --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/graph/BaseImplicitGraph.ts @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { NodeID, GraphTraits } from './GraphTraits'; + +export { NodeID }; + +/** + * BaseImplicitGraph is an abstract class that represents an implicit graph. + * An implicit graph is a graph representation where node and edge information is implicitly stored using maps. + * This class implements the GraphTraits interface and provides basic graph operations. + */ +export abstract class BaseImplicitGraph implements GraphTraits { + /** + * idToNodeMap is an optional map that maps node IDs (NodeID) to node objects (Node). + * If not initialized, calling related methods will throw an error. + */ + protected idToNodeMap?: Map; + + /** + * nodeToIdMap is a map that maps node objects (Node) to node IDs (NodeID). + * This map must be initialized in the subclass. + */ + protected nodeToIdMap!: Map; + + /** + * succMap is a map that stores the successors of each node. + * The key is a node ID (NodeID), and the value is an array of successor node IDs. + */ + succMap!: Map; + + /** + * predMap is a map that stores the predecessors of each node. + * The key is a node ID (NodeID), and the value is an array of predecessor node IDs. + */ + predMap!: Map; + + constructor() {} + + /** + * Gets the number of nodes in the graph. + * @returns The number of nodes in the graph. + */ + public getNodeNum(): number { + return this.nodeToIdMap.size; + } + + /** + * Returns an iterator for all nodes in the graph. + * @returns An iterator for traversing all nodes in the graph. + */ + public nodesItor(): IterableIterator { + return this.nodeToIdMap.keys(); + } + + /** + * Gets the node object corresponding to a given node ID. + * @param id The node ID. + * @returns The corresponding node object. + * @throws Throws an error if idToNodeMap is not initialized or if the node is not found. + */ + public getNode(id: NodeID): Node { + if (!this.idToNodeMap) { + throw new Error(`initialize this.idToNodeMap first`); + } + + if (!this.idToNodeMap.has(id)) { + throw new Error(`Can find Node # ${id}`); + } + + return this.idToNodeMap.get(id)!; + } + + public getNodeID(s: Node): NodeID { + if (!this.nodeToIdMap.has(s)) { + throw new Error(`Can find Node # ${s}`); + } + + return this.nodeToIdMap.get(s)!; + + } + + /** + * Checks whether the graph contains a specific node ID. + * @param id The node ID. + * @returns Returns true if the node ID exists in the graph; otherwise, returns false. + * @throws Throws an error if idToNodeMap is not initialized. + */ + public hasNode(id: NodeID): boolean { + if (!this.idToNodeMap) { + throw new Error(`initialize this.idToNodeMap first`); + } + + return this.idToNodeMap.has(id); + } + + /** + * Gets the list of successor node IDs for a given node. + * @param id The node ID. + * @returns An array of successor node IDs. Returns an empty array if no successors are found. + */ + public succ(id: NodeID): NodeID[] { + return this.succMap.get(id) ?? []; + } + + /** + * Gets the list of predecessor node IDs for a given node. + * @param id The node ID. + * @returns An array of predecessor node IDs. Returns an empty array if no predecessors are found. + */ + public pred(id: NodeID): NodeID[] { + return this.predMap.get(id) ?? []; + } + + /** + * Gets the nodeToIdMap, which maps node objects to node IDs. + * @returns The nodeToIdMap. + */ + public getNodeToIdMap(): Map { + return this.nodeToIdMap; + } + + /** + * Abstract method to get the name of the graph. + * Subclasses must implement this method. + * @returns The name of the graph. + */ + public abstract getGraphName(): string; +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/graph/BasicBlock.ts b/ets2panda/linter/arkanalyzer/src/core/graph/BasicBlock.ts new file mode 100644 index 0000000000..dd9ee3b6d8 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/graph/BasicBlock.ts @@ -0,0 +1,286 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkIfStmt, ArkReturnStmt, ArkReturnVoidStmt, Stmt } from '../base/Stmt'; +import { ArkError, ArkErrorCode } from '../common/ArkError'; +import Logger, { LOG_MODULE_TYPE } from '../../utils/logger'; +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'BasicBlock'); + +/** + * @category core/graph + * A `BasicBlock` is composed of: + * - ID: a **number** that uniquely identify the basic block, initialized as -1. + * - Statements: an **array** of statements in the basic block. + * - Predecessors: an **array** of basic blocks in front of the current basic block. More accurately, these basic + * blocks can reach the current block through edges. + * - Successors: an **array** of basic blocks after the current basic block. More accurately, the current block can + * reach these basic blocks through edges. + */ +export class BasicBlock { + private id: number = -1; + private stmts: Stmt[] = []; + private predecessorBlocks: BasicBlock[] = []; + private successorBlocks: BasicBlock[] = []; + private exceptionalSuccessorBlocks?: BasicBlock[]; + + constructor() {} + + public getId(): number { + return this.id; + } + + public setId(id: number): void { + this.id = id; + } + + /** + * Returns an array of the statements in a basic block. + * @returns An array of statements in a basic block. + */ + public getStmts(): Stmt[] { + return this.stmts; + } + + public addStmt(stmt: Stmt): void { + this.stmts.push(stmt); + } + + /** + * Adds the given stmt at the beginning of the basic block. + * @param stmt + */ + public addHead(stmt: Stmt | Stmt[]): void { + if (stmt instanceof Stmt) { + this.stmts.unshift(stmt); + } else { + this.stmts.unshift(...stmt); + } + } + + /** + * Adds the given stmt at the end of the basic block. + * @param stmt + */ + public addTail(stmt: Stmt | Stmt[]): void { + if (stmt instanceof Stmt) { + this.stmts.push(stmt); + } else { + stmt.forEach(stmt => this.stmts.push(stmt)); + } + } + + /** + * Inserts toInsert in the basic block after point. + * @param toInsert + * @param point + * @returns The number of successfully inserted statements + */ + public insertAfter(toInsert: Stmt | Stmt[], point: Stmt): number { + let index = this.stmts.indexOf(point); + if (index < 0) { + return 0; + } + return this.insertPos(index + 1, toInsert); + } + + /** + * Inserts toInsert in the basic block befor point. + * @param toInsert + * @param point + * @returns The number of successfully inserted statements + */ + public insertBefore(toInsert: Stmt | Stmt[], point: Stmt): number { + let index = this.stmts.indexOf(point); + if (index < 0) { + return 0; + } + return this.insertPos(index, toInsert); + } + + /** + * Removes the given stmt from this basic block. + * @param stmt + * @returns + */ + public remove(stmt: Stmt): void { + let index = this.stmts.indexOf(stmt); + if (index < 0) { + return; + } + this.stmts.splice(index, 1); + } + + /** + * Removes the first stmt from this basic block. + */ + public removeHead(): void { + this.stmts.splice(0, 1); + } + + /** + * Removes the last stmt from this basic block. + */ + public removeTail(): void { + this.stmts.splice(this.stmts.length - 1, 1); + } + + public getHead(): Stmt | null { + if (this.stmts.length === 0) { + return null; + } + return this.stmts[0]; + } + + public getTail(): Stmt | null { + let size = this.stmts.length; + if (size === 0) { + return null; + } + return this.stmts[size - 1]; + } + + /** + * Returns successors of the current basic block, whose types are also basic blocks (i.e.{@link BasicBlock}). + * @returns Successors of the current basic block. + * @example + * 1. get block successors. + + ```typescript + const body = arkMethod.getBody(); + const blocks = [...body.getCfg().getBlocks()] + for (let i = 0; i < blocks.length; i++) { + const block = blocks[i] + ... + for (const next of block.getSuccessors()) { + ... + } + } + ``` + */ + public getSuccessors(): BasicBlock[] { + return this.successorBlocks; + } + + /** + * Returns predecessors of the current basic block, whose types are also basic blocks. + * @returns An array of basic blocks. + */ + public getPredecessors(): BasicBlock[] { + return this.predecessorBlocks; + } + + public addPredecessorBlock(block: BasicBlock): void { + this.predecessorBlocks.push(block); + } + + public setPredecessorBlock(idx: number, block: BasicBlock): boolean { + if (idx < this.predecessorBlocks.length) { + this.predecessorBlocks[idx] = block; + return true; + } + return false; + } + + public setSuccessorBlock(idx: number, block: BasicBlock): boolean { + if (idx < this.successorBlocks.length) { + this.successorBlocks[idx] = block; + return true; + } + return false; + } + + // Temp just for SSA + public addStmtToFirst(stmt: Stmt) { + this.addHead(stmt); + } + + // Temp just for SSA + public addSuccessorBlock(block: BasicBlock): void { + this.successorBlocks.push(block); + } + + public removePredecessorBlock(block: BasicBlock): boolean { + let index = this.predecessorBlocks.indexOf(block); + if (index < 0) { + return false; + } + this.predecessorBlocks.splice(index, 1); + return true; + } + + public removeSuccessorBlock(block: BasicBlock): boolean { + let index = this.successorBlocks.indexOf(block); + if (index < 0) { + return false; + } + this.successorBlocks.splice(index, 1); + return true; + } + + public toString(): string { + let strs: string[] = []; + for (const stmt of this.stmts) { + strs.push(stmt.toString() + '\n'); + } + return strs.join(''); + } + + public validate(): ArkError { + let branchStmts: Stmt[] = []; + for (const stmt of this.stmts) { + if ( + stmt instanceof ArkIfStmt || + stmt instanceof ArkReturnStmt || + stmt instanceof ArkReturnVoidStmt + ) { + branchStmts.push(stmt); + } + } + + if (branchStmts.length > 1) { + let errMsg = `More than one branch or return stmts in the block: ${branchStmts.map((value) => value.toString()).join('\n')}`; + logger.error(errMsg); + return {errCode: ArkErrorCode.BB_MORE_THAN_ONE_BRANCH_RET_STMT, errMsg: errMsg }; + } + + if (branchStmts.length === 1 && branchStmts[0] !== this.stmts[this.stmts.length - 1]) { + let errMsg = `${branchStmts[0].toString()} not at the end of block.`; + logger.error(errMsg); + return {errCode: ArkErrorCode.BB_BRANCH_RET_STMT_NOT_AT_END, errMsg: errMsg}; + } + + return {errCode: ArkErrorCode.OK}; + } + + private insertPos(index: number, toInsert: Stmt | Stmt[]): number { + if (toInsert instanceof Stmt) { + this.stmts.splice(index, 0, toInsert); + return 1; + } + this.stmts.splice(index, 0, ...toInsert); + return toInsert.length; + } + + public getExceptionalSuccessorBlocks(): BasicBlock[] | undefined { + return this.exceptionalSuccessorBlocks; + } + + public addExceptionalSuccessorBlock(block: BasicBlock): void { + if (!this.exceptionalSuccessorBlocks) { + this.exceptionalSuccessorBlocks = []; + } + this.exceptionalSuccessorBlocks.push(block); + } +} diff --git a/ets2panda/linter/arkanalyzer/src/core/graph/Cfg.ts b/ets2panda/linter/arkanalyzer/src/core/graph/Cfg.ts new file mode 100644 index 0000000000..3470793463 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/graph/Cfg.ts @@ -0,0 +1,291 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { DefUseChain } from '../base/DefUseChain'; +import { Local } from '../base/Local'; +import { Stmt } from '../base/Stmt'; +import { ArkError, ArkErrorCode } from '../common/ArkError'; +import { ArkMethod } from '../model/ArkMethod'; +import { BasicBlock } from './BasicBlock'; +import Logger, { LOG_MODULE_TYPE } from '../../utils/logger'; +import { ArkStaticInvokeExpr } from '../base/Expr'; +import { Value } from '../base/Value'; +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'BasicBlock'); + +/** + * @category core/graph + */ +export class Cfg { + private blocks: Set = new Set(); + private stmtToBlock: Map = new Map(); + private startingStmt!: Stmt; + + private defUseChains: DefUseChain[] = []; + private declaringMethod: ArkMethod = new ArkMethod(); + + constructor() {} + + public getStmts(): Stmt[] { + let stmts = new Array(); + for (const block of this.blocks) { + block.getStmts().forEach(s => stmts.push(s)); + } + return stmts; + } + + /** + * Inserts toInsert in the basic block in CFG after point. + * @param toInsert + * @param point + * @returns The number of successfully inserted statements + */ + public insertAfter(toInsert: Stmt | Stmt[], point: Stmt): number { + const block = this.stmtToBlock.get(point); + if (!block) { + return 0; + } + + this.updateStmt2BlockMap(block, toInsert); + return block.insertAfter(toInsert, point); + } + + /** + * Inserts toInsert in the basic block in CFG befor point. + * @param toInsert + * @param point + * @returns The number of successfully inserted statements + */ + public insertBefore(toInsert: Stmt | Stmt[], point: Stmt): number { + const block = this.stmtToBlock.get(point); + if (!block) { + return 0; + } + + this.updateStmt2BlockMap(block, toInsert); + return block.insertBefore(toInsert, point); + } + + /** + * Removes the given stmt from the basic block in CFG. + * @param stmt + * @returns + */ + public remove(stmt: Stmt): void { + const block = this.stmtToBlock.get(stmt); + if (!block) { + return; + } + this.stmtToBlock.delete(stmt); + block.remove(stmt); + } + + /** + * Update stmtToBlock Map + * @param block + * @param changed + */ + public updateStmt2BlockMap(block: BasicBlock, changed?: Stmt | Stmt[]): void { + if (!changed) { + for (const stmt of block.getStmts()) { + this.stmtToBlock.set(stmt, block); + } + } else if (changed instanceof Stmt) { + this.stmtToBlock.set(changed, block); + } else { + for (const insert of changed) { + this.stmtToBlock.set(insert, block); + } + } + } + + // TODO: 添加block之间的边 + public addBlock(block: BasicBlock): void { + this.blocks.add(block); + + for (const stmt of block.getStmts()) { + this.stmtToBlock.set(stmt, block); + } + } + + public getBlocks(): Set { + return this.blocks; + } + + public getStartingBlock(): BasicBlock | undefined { + return this.stmtToBlock.get(this.startingStmt); + } + + public getStartingStmt(): Stmt { + return this.startingStmt; + } + + public setStartingStmt(newStartingStmt: Stmt): void { + this.startingStmt = newStartingStmt; + } + + public getDeclaringMethod(): ArkMethod { + return this.declaringMethod; + } + + public setDeclaringMethod(method: ArkMethod) { + this.declaringMethod = method; + } + + public getDefUseChains(): DefUseChain[] { + return this.defUseChains; + } + + // TODO: 整理成类似jimple的输出 + public toString(): string { + return 'cfg'; + } + + public buildDefUseStmt(locals: Set): void { + for (const block of this.blocks) { + for (const stmt of block.getStmts()) { + const defValue = stmt.getDef(); + if (defValue && defValue instanceof Local && defValue.getDeclaringStmt() === null) { + defValue.setDeclaringStmt(stmt); + } + for (const value of stmt.getUses()) { + this.buildUseStmt(value, locals, stmt); + } + } + } + } + + private buildUseStmt(value: Value, locals: Set, stmt: Stmt): void { + if (value instanceof Local) { + value.addUsedStmt(stmt); + } else if (value instanceof ArkStaticInvokeExpr) { + for (let local of locals) { + if (local.getName() === value.getMethodSignature().getMethodSubSignature().getMethodName()) { + local.addUsedStmt(stmt); + return; + } + } + } + } + + private handleDefUseForValue(value: Value, block: BasicBlock, stmt: Stmt, stmtIndex: number): void { + const name = value.toString(); + const defStmts: Stmt[] = []; + // 判断本block之前有无对应def + for (let i = stmtIndex - 1; i >= 0; i--) { + const beforeStmt = block.getStmts()[i]; + if (beforeStmt.getDef() && beforeStmt.getDef()?.toString() === name) { + defStmts.push(beforeStmt); + break; + } + } + // 本block有对应def直接结束,否则找所有的前序block + if (defStmts.length !== 0) { + this.defUseChains.push(new DefUseChain(value, defStmts[0], stmt)); + return; + } + const needWalkBlocks: BasicBlock[] = [...block.getPredecessors()]; + const walkedBlocks = new Set(); + while (needWalkBlocks.length > 0) { + const predecessor = needWalkBlocks.pop(); + if (!predecessor) { + return; + } + const predecessorStmts = predecessor.getStmts(); + let predecessorHasDef = false; + for (let i = predecessorStmts.length - 1; i >= 0; i--) { + const beforeStmt = predecessorStmts[i]; + if (beforeStmt.getDef() && beforeStmt.getDef()?.toString() === name) { + defStmts.push(beforeStmt); + predecessorHasDef = true; + break; + } + } + walkedBlocks.add(predecessor); + if (predecessorHasDef) { + continue; + } + for (const morePredecessor of predecessor.getPredecessors()) { + if (!walkedBlocks.has(morePredecessor) && !needWalkBlocks.includes(morePredecessor)) { + needWalkBlocks.unshift(morePredecessor); + } + } + } + for (const def of defStmts) { + this.defUseChains.push(new DefUseChain(value, def, stmt)); + } + } + + public buildDefUseChain(): void { + for (const block of this.blocks) { + for (let stmtIndex = 0; stmtIndex < block.getStmts().length; stmtIndex++) { + const stmt = block.getStmts()[stmtIndex]; + for (const value of stmt.getUses()) { + this.handleDefUseForValue(value, block, stmt, stmtIndex); + } + } + } + } + + public getUnreachableBlocks(): Set { + let unreachable = new Set(); + let startBB = this.getStartingBlock(); + if (!startBB) { + return unreachable; + } + let postOrder = this.dfsPostOrder(startBB); + for (const bb of this.blocks) { + if (!postOrder.has(bb)) { + unreachable.add(bb); + } + } + return unreachable; + } + + public validate(): ArkError { + let startBB = this.getStartingBlock(); + if (!startBB) { + let errMsg = `Not found starting block}`; + logger.error(errMsg); + return { errCode: ArkErrorCode.CFG_NOT_FOUND_START_BLOCK, errMsg: errMsg }; + } + + let unreachable = this.getUnreachableBlocks(); + if (unreachable.size !== 0) { + let errMsg = `Unreachable blocks: ${Array.from(unreachable) + .map((value) => value.toString()) + .join('\n')}`; + logger.error(errMsg); + return { errCode: ArkErrorCode.CFG_HAS_UNREACHABLE_BLOCK, errMsg: errMsg }; + } + + return { errCode: ArkErrorCode.OK }; + } + + private dfsPostOrder( + node: BasicBlock, + visitor: Set = new Set(), + postOrder: Set = new Set() + ): Set { + visitor.add(node); + for (const succ of node.getSuccessors()) { + if (visitor.has(succ)) { + continue; + } + this.dfsPostOrder(succ, visitor, postOrder); + } + postOrder.add(node); + return postOrder; + } +} diff --git a/ets2panda/linter/arkanalyzer/src/core/graph/DependsGraph.ts b/ets2panda/linter/arkanalyzer/src/core/graph/DependsGraph.ts new file mode 100644 index 0000000000..e4cab5ac97 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/graph/DependsGraph.ts @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { BaseEdge, BaseExplicitGraph, BaseNode, Kind, NodeID } from './BaseExplicitGraph'; +interface Attributes { + [name: string]: any; +} + +interface NodeAttributes extends Attributes { + name: string; + kind: Kind; +} + +interface EdgeAttributes extends Attributes { + kind: Kind; +} + +export class DependsNode extends BaseNode { + private attr: NodeAttr; + + public constructor(id: NodeID, attr: NodeAttr) { + super(id, attr.kind); + this.attr = attr; + } + + public getNodeAttr(): NodeAttr { + return this.attr; + } + + public setNodeAttr(attr: NodeAttr): void { + this.attr = attr; + } + + public getDotLabel(): string { + return this.attr.name; + } +} + +export class DependsEdge extends BaseEdge { + private attr: EdgeAttr; + + public constructor(s: DependsNode, d: DependsNode, attr: EdgeAttr) { + super(s, d, attr.kind); + this.attr = attr; + } + + public getEdgeAttr(): EdgeAttr { + return this.attr; + } + + public setEdgeAttr(attr: EdgeAttr): void { + this.attr = attr; + } + + public getKey(): string { + return `${this.getSrcID()}-${this.getDstID()}-${this.getKind()}`; + } +} + +export class DependsGraph extends BaseExplicitGraph { + protected depsMap: Map; + protected edgesMap: Map>; + + constructor() { + super(); + this.depsMap = new Map(); + this.edgesMap = new Map(); + } + + public hasDepsNode(key: string): boolean { + return this.depsMap.has(key); + } + + public addDepsNode(key: string, attr: NodeAttr): DependsNode { + if (this.depsMap.has(key)) { + // update attr + let node = this.getNode(this.depsMap.get(key)!) as DependsNode; + node.setNodeAttr(attr); + return node; + } + + let node = new DependsNode(this.getNodeNum(), attr); + this.depsMap.set(key, node.getID()); + this.addNode(node); + return node; + } + + public addEdge( + src: DependsNode, + dst: DependsNode, + attr: EdgeAttr + ): DependsEdge { + let edge = new DependsEdge(src, dst, attr); + let key = edge.getKey(); + if (this.edgesMap.has(key)) { + return this.edgesMap.get(key)!; + } + this.edgesMap.set(key, edge); + src.addOutgoingEdge(edge); + dst.addIncomingEdge(edge); + return edge; + } + + public getGraphName(): string { + return 'DependsGraph'; + } +} diff --git a/ets2panda/linter/arkanalyzer/src/core/graph/DominanceFinder.ts b/ets2panda/linter/arkanalyzer/src/core/graph/DominanceFinder.ts new file mode 100644 index 0000000000..a3cd26a236 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/graph/DominanceFinder.ts @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { BasicBlock } from './BasicBlock'; +import { Cfg } from './Cfg'; + +export class DominanceFinder { + private blocks: BasicBlock[] = []; + private blockToIdx = new Map; + private idoms: number[] = []; + private domFrontiers: number[][] = []; + + constructor(cfg: Cfg) { + this.blocks = Array.from(cfg.getBlocks()); + for (let i = 0; i < this.blocks.length; i++) { + let block = this.blocks[i]; + this.blockToIdx.set(block, i); + } + const startingBlock = cfg.getStartingBlock(); + + // calculate immediate dominator for each block + this.idoms = new Array(this.blocks.length); + this.idoms[0] = 0; + for (let i = 1; i < this.idoms.length; i++) { + this.idoms[i] = -1; + } + let isChanged = true; + while (isChanged) { + isChanged = false; + for (const block of this.blocks) { + if (block === startingBlock) { + continue; + } + let blockIdx = this.blockToIdx.get(block) as number; + let preds = Array.from(block.getPredecessors()); + let newIdom = this.getFirstDefinedBlockPredIdx(preds); + if (preds.length <= 0 || newIdom === -1) { + continue; + } + for (const pred of preds) { + let predIdx = this.blockToIdx.get(pred) as number; + this.idoms[predIdx] !== -1 ? newIdom = this.intersect(newIdom, predIdx) : null; + } + if (this.idoms[blockIdx] !== newIdom) { + this.idoms[blockIdx] = newIdom; + isChanged = true; + } + } + } + + // calculate dominance frontiers for each block + this.domFrontiers = new Array(this.blocks.length); + for (let i = 0; i < this.domFrontiers.length; i++) { + this.domFrontiers[i] = new Array(); + } + for (const block of this.blocks) { + let preds = Array.from(block.getPredecessors()); + if (preds.length <= 1) { + continue; + } + let blockIdx = this.blockToIdx.get(block) as number; + for (const pred of preds) { + let predIdx = this.blockToIdx.get(pred) as number; + while (predIdx !== this.idoms[blockIdx]) { + this.domFrontiers[predIdx].push(blockIdx); + predIdx = this.idoms[predIdx]; + } + } + } + } + + public getDominanceFrontiers(block: BasicBlock): Set { + if (!this.blockToIdx.has(block)) { + throw new Error("The given block: " + block + " is not in Cfg!") + } + let idx = this.blockToIdx.get(block) as number; + let dfs = new Set(); + let dfsIdx = this.domFrontiers[idx]; + for (const dfIdx of dfsIdx) { + dfs.add(this.blocks[dfIdx]); + } + return dfs; + } + + public getBlocks(): BasicBlock[] { + return this.blocks; + } + + public getBlockToIdx(): Map { + return this.blockToIdx; + } + + public getImmediateDominators(): number[] { + return this.idoms; + } + + + private getFirstDefinedBlockPredIdx(preds: BasicBlock[]): number { + for (const block of preds) { + let idx = this.blockToIdx.get(block) as number; + if (this.idoms[idx] !== -1) { + return idx; + } + } + return -1; + } + + private intersect(a: number, b: number): number { + while (a !== b) { + if (a > b) { + a = this.idoms[a]; + } else { + b = this.idoms[b]; + } + } + return a; + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/graph/DominanceTree.ts b/ets2panda/linter/arkanalyzer/src/core/graph/DominanceTree.ts new file mode 100644 index 0000000000..b0cf79915c --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/graph/DominanceTree.ts @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { BasicBlock } from './BasicBlock'; +import { DominanceFinder } from './DominanceFinder'; + +export class DominanceTree { + private blocks: BasicBlock[] = []; + private blockToIdx = new Map(); + private children: number[][] = []; + private parents: number[] = []; + + constructor(dominanceFinder: DominanceFinder) { + this.blocks = dominanceFinder.getBlocks(); + this.blockToIdx = dominanceFinder.getBlockToIdx(); + let idoms = dominanceFinder.getImmediateDominators(); + + // build the tree + let treeSize = this.blocks.length; + this.children = new Array(treeSize); + this.parents = new Array(treeSize); + for (let i = 0; i < treeSize; i++) { + this.children[i] = []; + this.parents[i] = -1; + } + for (let i = 0; i < treeSize; i++) { + if (idoms[i] !== i) { + this.parents[i] = idoms[i]; + this.children[idoms[i]].push(i); + } + } + } + + public getAllNodesDFS(): BasicBlock[] { + let dfsBlocks = new Array(); + let queue = new Array(); + queue.push(this.getRoot()); + while (queue.length !== 0) { + let curr = queue.splice(0, 1)[0]; + dfsBlocks.push(curr); + let childList = this.getChildren(curr); + if (childList.length !== 0) { + for (let i = childList.length - 1; i >= 0; i--) { + queue.splice(0, 0, childList[i]); + } + } + } + return dfsBlocks; + } + + public getChildren(block: BasicBlock): BasicBlock[] { + let childList = new Array(); + let idx = this.blockToIdx.get(block) as number; + for (const i of this.children[idx]) { + childList.push(this.blocks[i]); + } + return childList; + } + + public getRoot(): BasicBlock { + return this.blocks[0]; + } +} diff --git a/ets2panda/linter/arkanalyzer/src/core/graph/GraphTraits.ts b/ets2panda/linter/arkanalyzer/src/core/graph/GraphTraits.ts new file mode 100644 index 0000000000..cf2b89a3db --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/graph/GraphTraits.ts @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export type NodeID = number; +export type Kind = number; + +export interface GraphTraits { + nodesItor(): IterableIterator; + getGraphName(): string; + getNode(id: NodeID): Node | undefined; +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/graph/Scc.ts b/ets2panda/linter/arkanalyzer/src/core/graph/Scc.ts new file mode 100644 index 0000000000..3370659347 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/graph/Scc.ts @@ -0,0 +1,278 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { BaseNode } from './BaseExplicitGraph'; +import { NodeID, GraphTraits } from './GraphTraits'; + +type NodeSet = Set; +type NodeStack = NodeID[]; +type Node2RepSCCInfoMap = Map; +type Node2NodeMap = Map; + +/** + * Basic SCC info for a single node + */ +class NodeSCCInfo { + private _rep: NodeID; + private _subNodes: NodeSet; + + constructor() { + this._rep = Number.MAX_SAFE_INTEGER; + this._subNodes = new Set(); + } + + get rep(): NodeID { + return this._rep; + } + + set rep(n: NodeID) { + this._rep = n; + } + + addSubNodes(n: NodeID): void { + this._subNodes.add(n); + } + + get subNodes(): NodeSet { + return this._subNodes; + } +} + +/** + * Detect strongly connected components in a directed graph + * A topological graph is an extra product from this algorithm + * Advanced Nuutila’s algorithm which come from the following paper: + * Wave Propagation and Deep Propagation for pointer Analysis + * CGO 2009 + */ +export class SCCDetection> { + // graph G = (V, E) + private _G: Graph; + // counter + private _I: number; + // map of V to {1, . . . , |V |} ∪ ⊥, associates the + // nodes in V to the order in which they are visited by + // Nuutila’s algorithm. Initially, D(v) = ⊥. + private _D: Node2NodeMap; + // map of V to V , associates each node in a cycle to + // the representative of that cycle. Initially R(v) = v. + private _R: Node2RepSCCInfoMap; + // stack of V, holds the nodes that are in a cycle, but + // have not yet been inserted into C. Initially empty + private _S: NodeStack; + // stack of V , holds the nodes of V that are represenatives + // of strongly connected components. T keeps the + // nodes in topological order, that is, the top node has no + // predecessors. Initially empty + private _T: NodeStack; + private repNodes: NodeSet; + private visitedNodes: Set; + private inSCCNodes: Set; + + constructor(GT: Graph) { + this._G = GT; + this._I = 0; + this._D = new Map(); + this._S = new Array(); + this._T = new Array(); + this.repNodes = new Set(); + this._R = new Map(); + this.visitedNodes = new Set(); + this.inSCCNodes = new Set(); + } + + private isVisited(n: NodeID): boolean { + return this.visitedNodes.has(n); + } + + private inSCC(n: NodeID): boolean { + return this.inSCCNodes.has(n); + } + + private setVisited(n: NodeID): void { + this.visitedNodes.add(n); + } + + private setInSCC(n: NodeID): void { + this.inSCCNodes.add(n); + } + + private setRep(n: NodeID, r: NodeID): void { + let sccIn = this._R.get(n); + if (!sccIn) { + sccIn = new NodeSCCInfo(); + this._R.set(n, sccIn); + } + sccIn.rep = r; + + let rInfo = this._R.get(r); + if (!rInfo) { + rInfo = new NodeSCCInfo(); + this._R.set(r, rInfo); + } + rInfo.addSubNodes(n); + if (n !== r) { + sccIn.subNodes.clear(); + this.repNodes.add(r); + } + } + + private getRep(n: NodeID): NodeID { + let info = this._R.get(n); + if (!info) { + info = new NodeSCCInfo(); + this._R.set(n, info); + } + return info.rep; + } + + private getNode(id: NodeID): BaseNode { + let n = this._G.getNode(id); + if (!n) { + throw new Error('Node is not found'); + } + return n; + } + + private visit(v: NodeID): void { + this._I += 1; + this._D.set(v, this._I); + this.setRep(v, v); + this.setVisited(v); + + let node = this.getNode(v); + node.getOutgoingEdges().forEach((e) => { + let w: NodeID = e.getDstID(); + if (!this.isVisited(w)) { + this.visit(w); + } + + if (!this.inSCC(w)) { + let repV = this.getRep(v); + let repW = this.getRep(w); + if (!this._D.has(repV) || !this._D.has(repW)) { + throw new Error('Error happening in SCC detection'); + } + let rep = this._D.get(repV)! < this._D.get(repW)! ? repV : repW; + this.setRep(v, rep); + } + }); + + if (this.getRep(v) === v) { + this.setInSCC(v); + while (this._S.length > 0) { + let w = this._S.at(this._S.length - 1)!; + if (this._D.get(w)! <= this._D.get(v)!) { + break; + } else { + this._S.pop(); + this.setInSCC(w); + this.setRep(w, v); + } + } + this._T.push(v); + } else { + this._S.push(v); + } + } + + private clear(): void { + this._R.clear(); + this._I = 0; + this._D.clear(); + this.repNodes.clear(); + this._S.length = 0; + this._T.length = 0; + this.inSCCNodes.clear(); + this.visitedNodes.clear(); + } + + /** + * Get the rep node + * If not found return itself + */ + public getRepNode(n: NodeID): NodeID { + const it = this._R.get(n); + if (!it) { + throw new Error('scc rep not found'); + } + const rep = it.rep; + return rep !== Number.MAX_SAFE_INTEGER ? rep : n; + } + + /** + * Start to detect and collapse SCC + */ + public find(): void { + this.clear(); + let nodeIt = this._G.nodesItor(); + for (let node of nodeIt) { + const nodeId: NodeID = node.getID(); + if (!this.isVisited(nodeId) && !this._D.has(nodeId)) { + this.visit(nodeId); + } + } + } + + public getTopoAndCollapsedNodeStack(): NodeStack { + return this._T; + } + + public getNode2SCCInfoMap(): Node2RepSCCInfoMap { + return this._R; + } + + // whether the node is in a cycle + public nodeIsInCycle(n: NodeID): boolean { + const rep = this.getRepNode(n); + const subNodesCount = this.getSubNodes(rep).size; + // multi-node cycle + if (subNodesCount > 1) { + return true; + } + // self-cycle: a call a + let repNode = this._G.getNode(rep)!; + for (const e of repNode?.getOutgoingEdges()) { + if (e.getDstID() === rep) { + return true; + } + } + return false; + } + + public getMySCCNodes(n: NodeID): NodeSet { + const rep = this.getRepNode(n); + return this.getSubNodes(rep); + } + + // get all subnodes in one scc + public getSubNodes(n: NodeID): NodeSet { + const it = this._R.get(n); + if (!it) { + throw new Error('sccInfo not found for a node'); + } + let sub = it.subNodes; + if (sub.size === 0) { + sub.add(n); + } + + return sub; + } + + // get all representative nodes + public getRepNodes(): NodeSet { + return this.repNodes; + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/graph/ViewTree.ts b/ets2panda/linter/arkanalyzer/src/core/graph/ViewTree.ts new file mode 100644 index 0000000000..5324873ac4 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/graph/ViewTree.ts @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Constant } from '../base/Constant'; +import { Decorator } from '../base/Decorator'; +import { ArkInstanceFieldRef } from '../base/Ref'; +import { Stmt } from '../base/Stmt'; +import { Type } from '../base/Type'; +import { ArkField } from '../model/ArkField'; +import { ArkMethod } from '../model/ArkMethod'; +import { ClassSignature, MethodSignature } from '../model/ArkSignature'; + +/** + * @category core/graph + */ +export interface ViewTreeNode { + /** Component node name */ + name: string; + /** @deprecated Use {@link attributes} instead. */ + stmts: Map; + /** Component attribute stmts, key is attribute name, value is [Stmt, [Uses Values]]. */ + attributes: Map; + /** Used state values. */ + stateValues: Set; + /** Node's parent, CustomComponent and root node no parent. */ + parent: ViewTreeNode | null; + /** Node's children. */ + children: ViewTreeNode[]; + /** @deprecated Use {@link signature} instead. */ + classSignature?: ClassSignature | MethodSignature; + /** CustomComponent class signature or Builder method signature. */ + signature?: ClassSignature | MethodSignature; + + /** + * Custom component value transfer + * - key: ArkField, child custom component class stateValue field. + * - value: ArkField | ArkMethod, parent component transfer value. + * key is BuilderParam, the value is Builder ArkMethod. + * Others, the value is parent class stateValue field. + */ + stateValuesTransfer?: Map; + + /** BuilderParam placeholders ArkField. */ + builderParam?: ArkField; + + /** builderParam bind builder method signature. */ + builder?: MethodSignature; + + /** + * walk node and node's children + * @param selector Node selector function, return true skipping the follow-up nodes. + * @returns + * - true: There are nodes that meet the selector. + * - false: does not exist. + */ + walk(selector: (item: ViewTreeNode) => boolean): boolean; + + /** + * Whether the node type is Builder. + * @returns true: node is Builder, false others. + */ + isBuilder(): boolean; + + /** + * Whether the node type is custom component. + * @returns true: node is custom component, false others. + */ + isCustomComponent(): boolean; +} + +/** + * ArkUI Component Tree + * @example + * // Component Class get ViewTree + * let arkClas: ArkClass = ...; + * let viewtree = arkClas.getViewTree(); + * + * // get viewtree root node + * let root: ViewTreeNode = viewtree.getRoot(); + * + * // get viewtree stateValues Map + * let stateValues: Map> = viewtree.getStateValues(); + * + * // walk all nodes + * root.walk((node) => { + * // check node is builder + * if (node.isBuilder()) { + * xx + * } + * + * // check node is sub CustomComponent + * if (node.isCustomComponent()) { + * xx + * } + * + * if (xxx) { + * // Skip the remaining nodes and end the traversal + * return true; + * } + * + * return false; + * }) + * + * @category core/graph + */ +export interface ViewTree { + /** + * @deprecated Use {@link getStateValues} instead. + */ + isClassField(name: string): boolean; + + /** + * @deprecated Use {@link getStateValues} instead. + */ + getClassFieldType(name: string): Decorator | Type | undefined; + + /** + * Map of the component controlled by the state variable + * @returns + */ + getStateValues(): Map>; + + /** + * ViewTree root node. + * @returns root node + */ + getRoot(): ViewTreeNode | null; +} diff --git a/ets2panda/linter/arkanalyzer/src/core/graph/builder/CfgBuilder.ts b/ets2panda/linter/arkanalyzer/src/core/graph/builder/CfgBuilder.ts new file mode 100644 index 0000000000..61742e133c --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/graph/builder/CfgBuilder.ts @@ -0,0 +1,1260 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as ts from 'ohos-typescript'; +import { Local } from '../../base/Local'; +import { ArkAliasTypeDefineStmt, ArkReturnStmt, ArkReturnVoidStmt, Stmt } from '../../base/Stmt'; +import { BasicBlock } from '../BasicBlock'; +import { Cfg } from '../Cfg'; +import { ArkClass } from '../../model/ArkClass'; +import { ArkMethod } from '../../model/ArkMethod'; +import { ArkIRTransformer, ValueAndStmts } from '../../common/ArkIRTransformer'; +import { ModelUtils } from '../../common/ModelUtils'; +import { IRUtils } from '../../common/IRUtils'; +import { AliasType, ClassType, UnclearReferenceType, UnknownType, VoidType } from '../../base/Type'; +import { Trap } from '../../base/Trap'; +import { GlobalRef } from '../../base/Ref'; +import { LoopBuilder } from './LoopBuilder'; +import { SwitchBuilder } from './SwitchBuilder'; +import { ConditionBuilder } from './ConditionBuilder'; +import { TrapBuilder } from './TrapBuilder'; +import { CONSTRUCTOR_NAME, PROMISE } from '../../common/TSConst'; +import { ModifierType } from '../../model/ArkBaseModel'; + +class StatementBuilder { + type: string; + //节点对应源代码 + code: string; + next: StatementBuilder | null; + lasts: Set; + walked: boolean; + index: number; + // TODO:以下两个属性需要获取 + line: number;//行号//ast节点存了一个start值为这段代码的起始地址,可以从start开始往回查原文有几个换行符确定行号 + column: number; // 列 + astNode: ts.Node | null;//ast节点对象 + scopeID: number; + addressCode3: string[] = []; + block: BlockBuilder | null; + ifExitPass: boolean; + passTmies: number = 0; + numOfIdentifier: number = 0; + isDoWhile: boolean = false; + + constructor(type: string, code: string, astNode: ts.Node | null, scopeID: number) { + this.type = type; + this.code = code; + this.next = null; + this.lasts = new Set(); + this.walked = false; + this.index = 0; + this.line = -1; + this.column = -1; + this.astNode = astNode; + this.scopeID = scopeID; + this.block = null; + this.ifExitPass = false; + } +} + +class ConditionStatementBuilder extends StatementBuilder { + nextT: StatementBuilder | null; + nextF: StatementBuilder | null; + loopBlock: BlockBuilder | null; + condition: string; + doStatement: StatementBuilder | null = null; + + constructor(type: string, code: string, astNode: ts.Node, scopeID: number) { + super(type, code, astNode, scopeID); + this.nextT = null; + this.nextF = null; + this.loopBlock = null; + this.condition = ''; + } +} + +export class SwitchStatementBuilder extends StatementBuilder { + nexts: StatementBuilder[]; + cases: Case[] = []; + default: StatementBuilder | null = null; + afterSwitch: StatementBuilder | null = null; + + constructor(type: string, code: string, astNode: ts.Node, scopeID: number) { + super(type, code, astNode, scopeID); + this.nexts = []; + } +} + +export class TryStatementBuilder extends StatementBuilder { + tryFirst: StatementBuilder | null = null; + tryExit: StatementBuilder | null = null; + catchStatement: StatementBuilder | null = null; + catchError: string = ''; + finallyStatement: StatementBuilder | null = null; + afterFinal: StatementBuilder | null = null; + + constructor(type: string, code: string, astNode: ts.Node, scopeID: number) { + super(type, code, astNode, scopeID); + } +} + +class Case { + value: string; + stmt: StatementBuilder; + valueNode!: ts.Node; + + constructor(value: string, stmt: StatementBuilder) { + this.value = value; + this.stmt = stmt; + } +} + +class DefUseChain { + def: StatementBuilder; + use: StatementBuilder; + + constructor(def: StatementBuilder, use: StatementBuilder) { + this.def = def; + this.use = use; + } +} + +class Variable { + name: string; + lastDef: StatementBuilder; + defUse: DefUseChain[]; + properties: Variable[] = []; + propOf: Variable | null = null; + + constructor(name: string, lastDef: StatementBuilder) { + this.name = name; + this.lastDef = lastDef; + this.defUse = []; + } +} + +class Scope { + id: number; + + constructor(id: number) { + this.id = id; + } +} + +export class BlockBuilder { + id: number; + stmts: StatementBuilder[]; + nexts: BlockBuilder[] = []; + lasts: BlockBuilder[] = []; + walked: boolean = false; + + constructor(id: number, stmts: StatementBuilder[]) { + this.id = id; + this.stmts = stmts; + } +} + +class Catch { + errorName: string; + from: number; + to: number; + withLabel: number; + + constructor(errorName: string, from: number, to: number, withLabel: number) { + this.errorName = errorName; + this.from = from; + this.to = to; + this.withLabel = withLabel; + } +} + +class TextError extends Error { + constructor(message: string) { + // 调用父类的构造函数,并传入错误消息 + super(message); + + // 设置错误类型的名称 + this.name = 'TextError'; + } +} + +export class CfgBuilder { + name: string; + astRoot: ts.Node; + entry: StatementBuilder; + exit: StatementBuilder; + loopStack: ConditionStatementBuilder[]; + switchExitStack: StatementBuilder[]; + functions: CfgBuilder[]; + breakin: string; + statementArray: StatementBuilder[]; + dotEdges: number[][]; + scopes: Scope[]; + tempVariableNum: number; + current3ACstm: StatementBuilder; + blocks: BlockBuilder[]; + currentDeclarationKeyword: string; + variables: Variable[]; + declaringClass: ArkClass; + importFromPath: string[]; + catches: Catch[]; + exits: StatementBuilder[] = []; + emptyBody: boolean = false; + arrowFunctionWithoutBlock: boolean = false; + + private sourceFile: ts.SourceFile; + private declaringMethod: ArkMethod; + + constructor(ast: ts.Node, name: string, declaringMethod: ArkMethod, sourceFile: ts.SourceFile) { + this.name = name; + this.astRoot = ast; + this.declaringMethod = declaringMethod; + this.declaringClass = declaringMethod.getDeclaringArkClass(); + this.entry = new StatementBuilder('entry', '', ast, 0); + this.loopStack = []; + this.switchExitStack = []; + this.functions = []; + this.breakin = ''; + this.statementArray = []; + this.dotEdges = []; + this.exit = new StatementBuilder('exit', 'return;', null, 0); + this.scopes = []; + this.tempVariableNum = 0; + this.current3ACstm = this.entry; + this.blocks = []; + this.currentDeclarationKeyword = ''; + this.variables = []; + this.importFromPath = []; + this.catches = []; + this.sourceFile = sourceFile; + this.arrowFunctionWithoutBlock = true; + } + + public getDeclaringMethod(): ArkMethod { + return this.declaringMethod; + } + + judgeLastType(s: StatementBuilder, lastStatement: StatementBuilder): void { + if (lastStatement.type === 'ifStatement') { + let lastIf = lastStatement as ConditionStatementBuilder; + if (lastIf.nextT == null) { + lastIf.nextT = s; + s.lasts.add(lastIf); + } else { + lastIf.nextF = s; + s.lasts.add(lastIf); + } + } else if (lastStatement.type === 'loopStatement') { + let lastLoop = lastStatement as ConditionStatementBuilder; + lastLoop.nextT = s; + s.lasts.add(lastLoop); + } else if (lastStatement.type === 'catchOrNot') { + let lastLoop = lastStatement as ConditionStatementBuilder; + lastLoop.nextT = s; + s.lasts.add(lastLoop); + } else { + lastStatement.next = s; + s.lasts.add(lastStatement); + } + + } + + ASTNodeBreakStatement(c: ts.Node, lastStatement: StatementBuilder): void { + let p: ts.Node | null = c; + while (p && p !== this.astRoot) { + if (ts.isWhileStatement(p) || ts.isDoStatement(p) || ts.isForStatement(p) || ts.isForInStatement(p) || ts.isForOfStatement(p)) { + const lastLoopNextF = this.loopStack[this.loopStack.length - 1].nextF!; + this.judgeLastType(lastLoopNextF, lastStatement); + lastLoopNextF.lasts.add(lastStatement); + return; + } + if (ts.isCaseClause(p) || ts.isDefaultClause(p)) { + const lastSwitchExit = this.switchExitStack[this.switchExitStack.length - 1]; + this.judgeLastType(lastSwitchExit, lastStatement); + lastSwitchExit.lasts.add(lastStatement); + return; + } + p = p.parent; + } + } + + ASTNodeIfStatement(c: ts.IfStatement, lastStatement: StatementBuilder, scopeID: number): StatementBuilder { + let ifstm: ConditionStatementBuilder = new ConditionStatementBuilder('ifStatement', '', c, scopeID); + this.judgeLastType(ifstm, lastStatement); + let ifexit: StatementBuilder = new StatementBuilder('ifExit', '', c, scopeID); + this.exits.push(ifexit); + ifstm.condition = c.expression.getText(this.sourceFile); + ifstm.code = 'if (' + ifstm.condition + ')'; + if (ts.isBlock(c.thenStatement)) { + this.walkAST(ifstm, ifexit, [...c.thenStatement.statements]); + } else { + this.walkAST(ifstm, ifexit, [c.thenStatement]); + } + if (c.elseStatement) { + if (ts.isBlock(c.elseStatement)) { + this.walkAST(ifstm, ifexit, [...c.elseStatement.statements]); + } else { + this.walkAST(ifstm, ifexit, [c.elseStatement]); + } + } + if (!ifstm.nextT) { + ifstm.nextT = ifexit; + ifexit.lasts.add(ifstm); + } + if (!ifstm.nextF) { + ifstm.nextF = ifexit; + ifexit.lasts.add(ifstm); + } + return ifexit; + } + + ASTNodeWhileStatement(c: ts.WhileStatement, lastStatement: StatementBuilder, scopeID: number): StatementBuilder { + this.breakin = 'loop'; + let loopstm = new ConditionStatementBuilder('loopStatement', '', c, scopeID); + this.loopStack.push(loopstm); + this.judgeLastType(loopstm, lastStatement); + let loopExit = new StatementBuilder('loopExit', '', c, scopeID); + this.exits.push(loopExit); + loopstm.nextF = loopExit; + loopExit.lasts.add(loopstm); + loopstm.condition = c.expression.getText(this.sourceFile); + loopstm.code = 'while (' + loopstm.condition + ')'; + if (ts.isBlock(c.statement)) { + this.walkAST(loopstm, loopstm, [...c.statement.statements]); + } else { + this.walkAST(loopstm, loopstm, [c.statement]); + } + if (!loopstm.nextF) { + loopstm.nextF = loopExit; + loopExit.lasts.add(loopstm); + } + if (!loopstm.nextT) { + loopstm.nextT = loopExit; + loopExit.lasts.add(loopstm); + } + this.loopStack.pop(); + return loopExit; + } + + ASTNodeForStatement(c: ts.ForInOrOfStatement | ts.ForStatement, lastStatement: StatementBuilder, scopeID: number): StatementBuilder { + this.breakin = 'loop'; + let loopstm = new ConditionStatementBuilder('loopStatement', '', c, scopeID); + this.loopStack.push(loopstm); + this.judgeLastType(loopstm, lastStatement); + let loopExit = new StatementBuilder('loopExit', '', c, scopeID); + this.exits.push(loopExit); + loopstm.nextF = loopExit; + loopExit.lasts.add(loopstm); + loopstm.code = 'for ('; + if (ts.isForStatement(c)) { + loopstm.code += c.initializer?.getText(this.sourceFile) + '; ' + c.condition?.getText(this.sourceFile) + '; ' + c.incrementor?.getText(this.sourceFile); + } else if (ts.isForOfStatement(c)) { + loopstm.code += c.initializer?.getText(this.sourceFile) + ' of ' + c.expression.getText(this.sourceFile); + } else { + loopstm.code += c.initializer?.getText(this.sourceFile) + ' in ' + c.expression.getText(this.sourceFile); + } + loopstm.code += ')'; + if (ts.isBlock(c.statement)) { + this.walkAST(loopstm, loopstm, [...c.statement.statements]); + } else { + this.walkAST(loopstm, loopstm, [c.statement]); + } + if (!loopstm.nextF) { + loopstm.nextF = loopExit; + loopExit.lasts.add(loopstm); + } + if (!loopstm.nextT) { + loopstm.nextT = loopExit; + loopExit.lasts.add(loopstm); + } + this.loopStack.pop(); + return loopExit; + } + + ASTNodeDoStatement(c: ts.DoStatement, lastStatement: StatementBuilder, scopeID: number): StatementBuilder { + this.breakin = 'loop'; + let loopstm = new ConditionStatementBuilder('loopStatement', '', c, scopeID); + this.loopStack.push(loopstm); + let loopExit = new StatementBuilder('loopExit', '', c, scopeID); + this.exits.push(loopExit); + loopstm.nextF = loopExit; + loopExit.lasts.add(loopstm); + loopstm.condition = c.expression.getText(this.sourceFile); + loopstm.code = 'while (' + loopstm.condition + ')'; + loopstm.isDoWhile = true; + if (ts.isBlock(c.statement)) { + this.walkAST(lastStatement, loopstm, [...c.statement.statements]); + } else { + this.walkAST(lastStatement, loopstm, [c.statement]); + } + let lastType = lastStatement.type; + if (lastType === 'ifStatement' || lastType === 'loopStatement') { + let lastCondition = lastStatement as ConditionStatementBuilder; + loopstm.nextT = lastCondition.nextT; + lastCondition.nextT?.lasts.add(loopstm); + } else { + loopstm.nextT = lastStatement.next; + lastStatement.next?.lasts.add(loopstm); + } + if (loopstm.nextT && loopstm.nextT !== loopstm) { + loopstm.nextT.isDoWhile = true; + loopstm.doStatement = loopstm.nextT; + } + this.loopStack.pop(); + return loopExit; + } + + ASTNodeSwitchStatement(c: ts.SwitchStatement, lastStatement: StatementBuilder, scopeID: number): StatementBuilder { + this.breakin = 'switch'; + let switchstm = new SwitchStatementBuilder('switchStatement', '', c, scopeID); + this.judgeLastType(switchstm, lastStatement); + let switchExit = new StatementBuilder('switchExit', '', null, scopeID); + this.exits.push(switchExit); + this.switchExitStack.push(switchExit); + switchExit.lasts.add(switchstm); + switchstm.code = 'switch (' + c.expression + ')'; + let lastCaseExit: StatementBuilder | null = null; + for (let i = 0; i < c.caseBlock.clauses.length; i++) { + const clause = c.caseBlock.clauses[i]; + let casestm: StatementBuilder; + if (ts.isCaseClause(clause)) { + casestm = new StatementBuilder('statement', 'case ' + clause.expression.getText(this.sourceFile) + ':', clause, scopeID); + } else { + casestm = new StatementBuilder('statement', 'default:', clause, scopeID); + } + switchstm.nexts.push(casestm); + casestm.lasts.add(switchstm); + let caseExit = new StatementBuilder('caseExit', '', null, scopeID); + this.exits.push(caseExit); + this.walkAST(casestm, caseExit, [...clause.statements]); + if (ts.isCaseClause(clause)) { + const cas = new Case(casestm.code, casestm.next!); + switchstm.cases.push(cas); + } else { + switchstm.default = casestm.next; + } + switchstm.nexts[switchstm.nexts.length - 1] = casestm.next!; + for (const stmt of [...casestm.lasts]) { + casestm.next!.lasts.add(stmt); + } + casestm.next!.lasts.delete(casestm); + + if (lastCaseExit) { + lastCaseExit.next = casestm.next; + casestm.next?.lasts.add(lastCaseExit); + } + lastCaseExit = caseExit; + if (i === c.caseBlock.clauses.length - 1) { + caseExit.next = switchExit; + switchExit.lasts.add(caseExit); + } + } + this.switchExitStack.pop(); + return switchExit; + } + + ASTNodeTryStatement(c: ts.TryStatement, lastStatement: StatementBuilder, scopeID: number): StatementBuilder { + let trystm = new TryStatementBuilder('tryStatement', 'try', c, scopeID); + this.judgeLastType(trystm, lastStatement); + let tryExit = new StatementBuilder('tryExit', '', c, scopeID); + this.exits.push(tryExit); + trystm.tryExit = tryExit; + this.walkAST(trystm, tryExit, [...c.tryBlock.statements]); + trystm.tryFirst = trystm.next; + trystm.next?.lasts.add(trystm); + if (c.catchClause) { + let text = 'catch'; + if (c.catchClause.variableDeclaration) { + text += '(' + c.catchClause.variableDeclaration.getText(this.sourceFile) + ')'; + } + let catchOrNot = new ConditionStatementBuilder('catchOrNot', text, c, scopeID); + let catchExit = new StatementBuilder('catch exit', '', c, scopeID); + catchOrNot.nextF = catchExit; + catchExit.lasts.add(catchOrNot); + this.walkAST(catchOrNot, catchExit, [...c.catchClause.block.statements]); + if (!catchOrNot.nextT) { + catchOrNot.nextT = catchExit; + catchExit.lasts.add(catchOrNot); + } + const catchStatement = new StatementBuilder('statement', catchOrNot.code, c.catchClause, catchOrNot.nextT.scopeID); + catchStatement.next = catchOrNot.nextT; + trystm.catchStatement = catchStatement; + catchStatement.lasts.add(trystm); + if (c.catchClause.variableDeclaration) { + trystm.catchError = c.catchClause.variableDeclaration.getText(this.sourceFile); + } else { + trystm.catchError = 'Error'; + } + + } + let final = new StatementBuilder('statement', 'finally', c, scopeID); + let finalExit = new StatementBuilder('finallyExit', '', c, scopeID); + this.exits.push(finalExit); + if (c.finallyBlock && c.finallyBlock.statements.length > 0) { + this.walkAST(final, finalExit, [...c.finallyBlock.statements]); + } else { + let dummyFinally = new StatementBuilder('statement', 'dummyFinally', c, (new Scope(this.scopes.length)).id); + final.next = dummyFinally; + dummyFinally.lasts.add(final); + dummyFinally.next = finalExit; + finalExit.lasts.add(dummyFinally); + } + trystm.finallyStatement = final.next; + tryExit.next = final.next; + final.next?.lasts.add(tryExit); + + trystm.next = finalExit; + finalExit.lasts.add(trystm); + return finalExit; + } + + walkAST(lastStatement: StatementBuilder, nextStatement: StatementBuilder, nodes: ts.Node[]): void { + let scope = new Scope(this.scopes.length); + this.scopes.push(scope); + for (let i = 0; i < nodes.length; i++) { + let c = nodes[i]; + if (ts.isVariableStatement(c) || ts.isExpressionStatement(c) || ts.isThrowStatement(c) || ts.isTypeAliasDeclaration(c)) { + let s = new StatementBuilder('statement', c.getText(this.sourceFile), c, scope.id); + this.judgeLastType(s, lastStatement); + lastStatement = s; + } else if (!this.declaringMethod.isDefaultArkMethod() && ts.isFunctionDeclaration(c)) { + let s = new StatementBuilder('functionDeclarationStatement', c.getText(this.sourceFile), c, scope.id); + this.judgeLastType(s, lastStatement); + lastStatement = s; + } else if (!this.declaringMethod.isDefaultArkMethod() && ts.isClassDeclaration(c)) { + let s = new StatementBuilder('classDeclarationStatement', c.getText(this.sourceFile), c, scope.id); + this.judgeLastType(s, lastStatement); + lastStatement = s; + } else if (ts.isReturnStatement(c)) { + let s = new StatementBuilder('returnStatement', c.getText(this.sourceFile), c, scope.id); + this.judgeLastType(s, lastStatement); + lastStatement = s; + break; + } else if (ts.isBreakStatement(c)) { + this.ASTNodeBreakStatement(c, lastStatement); + return; + } else if (ts.isContinueStatement(c)) { + const lastLoop = this.loopStack[this.loopStack.length - 1]; + this.judgeLastType(lastLoop, lastStatement); + lastLoop.lasts.add(lastStatement); + return; + } else if (ts.isIfStatement(c)) { + lastStatement = this.ASTNodeIfStatement(c, lastStatement, scope.id); + } else if (ts.isWhileStatement(c)) { + lastStatement = this.ASTNodeWhileStatement(c, lastStatement, scope.id); + } + if (ts.isForStatement(c) || ts.isForInStatement(c) || ts.isForOfStatement(c)) { + lastStatement = this.ASTNodeForStatement(c, lastStatement, scope.id); + } else if (ts.isDoStatement(c)) { + lastStatement = this.ASTNodeDoStatement(c, lastStatement, scope.id); + } else if (ts.isSwitchStatement(c)) { + lastStatement = this.ASTNodeSwitchStatement(c, lastStatement, scope.id); + } else if (ts.isBlock(c)) { + let blockExit = new StatementBuilder('blockExit', '', c, scope.id); + this.exits.push(blockExit); + this.walkAST(lastStatement, blockExit, c.getChildren(this.sourceFile)[1].getChildren(this.sourceFile)); + lastStatement = blockExit; + } else if (ts.isTryStatement(c)) { + lastStatement = this.ASTNodeTryStatement(c, lastStatement, scope.id); + } else if (ts.isExportAssignment(c)) { + if (ts.isNewExpression(c.expression) || ts.isObjectLiteralExpression(c.expression)) { + let s = new StatementBuilder('statement', c.getText(this.sourceFile), c, scope.id); + this.judgeLastType(s, lastStatement); + lastStatement = s; + } + } + } + if (lastStatement.type !== 'breakStatement' && lastStatement.type !== 'continueStatement' && lastStatement.type !== 'returnStatement') { + lastStatement.next = nextStatement; + nextStatement.lasts.add(lastStatement); + } + } + + addReturnInEmptyMethod(): void { + if (this.entry.next === this.exit) { + const ret = new StatementBuilder('returnStatement', 'return;', null, this.entry.scopeID); + this.entry.next = ret; + ret.lasts.add(this.entry); + ret.next = this.exit; + this.exit.lasts = new Set([ret]); + } + } + + deleteExitAfterCondition(last: ConditionStatementBuilder, exit: StatementBuilder): void { + if (last.nextT === exit) { + last.nextT = exit.next; + const lasts = exit.next!.lasts; + lasts.delete(exit); + lasts.add(last); + } else if (last.nextF === exit) { + last.nextF = exit.next; + const lasts = exit.next!.lasts; + lasts.delete(exit); + lasts.add(last); + } + } + + deleteExitAfterSwitch(last: SwitchStatementBuilder, exit: StatementBuilder): void { + if (exit.type === 'switchExit') { + last.afterSwitch = exit.next; + } + exit.next!.lasts.delete(exit); + last.nexts = last.nexts.filter(item => item !== exit); + if (last.nexts.length === 0) { + last.next = exit.next; + exit.next?.lasts.add(last); + } + } + + deleteExit(): void { + for (const exit of this.exits) { + const lasts = [...exit.lasts]; + for (const last of lasts) { + if (last instanceof ConditionStatementBuilder) { + this.deleteExitAfterCondition(last, exit); + } else if (last instanceof SwitchStatementBuilder) { + this.deleteExitAfterSwitch(last, exit); + } else if (last instanceof TryStatementBuilder && exit.type === 'finallyExit') { + last.afterFinal = exit.next; + last.next = last.tryFirst; + exit.lasts.delete(last); + } else { + last.next = exit.next; + const lasts = exit.next!.lasts; + lasts.delete(exit); + lasts.add(last); + } + } + } + // 部分语句例如return后面的exit语句的next无法在上面清除 + for (const exit of this.exits) { + if (exit.next && exit.next.lasts.has(exit)) { + exit.next.lasts.delete(exit); + } + } + } + + addStmt2BlockStmtQueueInSpecialCase(stmt: StatementBuilder, stmtQueue: StatementBuilder[]): StatementBuilder | null { + if (stmt.next) { + if ((stmt.type === 'continueStatement' || stmt.next.type === 'loopStatement') && stmt.next.block || stmt.next.type.includes('exit')) { + return null; + } + stmt.next.passTmies++; + if (stmt.next.passTmies === stmt.next.lasts.size || stmt.next.type === 'loopStatement' || stmt.next.isDoWhile) { + if (stmt.next.scopeID !== stmt.scopeID && !(stmt.next instanceof ConditionStatementBuilder && stmt.next.doStatement) && + !(ts.isCaseClause(stmt.astNode!) || ts.isDefaultClause(stmt.astNode!))) { + stmtQueue.push(stmt.next); + return null; + } + return stmt.next; + } + } + return null; + } + + addStmt2BlockStmtQueue(stmt: StatementBuilder, stmtQueue: StatementBuilder[]): StatementBuilder | null { + if (stmt instanceof ConditionStatementBuilder) { + stmtQueue.push(stmt.nextF!); + stmtQueue.push(stmt.nextT!); + } else if (stmt instanceof SwitchStatementBuilder) { + if (stmt.nexts.length === 0) { + stmtQueue.push(stmt.afterSwitch!); + } + for (let i = stmt.nexts.length - 1; i >= 0; i--) { + stmtQueue.push(stmt.nexts[i]); + } + } else if (stmt instanceof TryStatementBuilder) { + if (stmt.finallyStatement) { + stmtQueue.push(stmt.finallyStatement); + } + if (stmt.catchStatement) { + stmtQueue.push(stmt.catchStatement); + } + if (stmt.tryFirst) { + stmtQueue.push(stmt.tryFirst); + } + } else if (stmt.next) { + return this.addStmt2BlockStmtQueueInSpecialCase(stmt, stmtQueue); + } + return null; + } + + buildBlocks(): void { + const stmtQueue = [this.entry]; + const handledStmts: Set = new Set(); + while (stmtQueue.length > 0) { + let stmt = stmtQueue.pop()!; + if (stmt.type.includes('exit')) { + continue; + } + if (handledStmts.has(stmt)) { + continue; + } + const block = new BlockBuilder(this.blocks.length, []); + this.blocks.push(block); + while (stmt && !handledStmts.has(stmt)) { + if (stmt.type === 'loopStatement' && block.stmts.length > 0 && !stmt.isDoWhile) { + stmtQueue.push(stmt); + break; + } + if (stmt.type.includes('Exit')) { + break; + } + block.stmts.push(stmt); + stmt.block = block; + handledStmts.add(stmt); + const addRet = this.addStmt2BlockStmtQueue(stmt, stmtQueue); + if (addRet instanceof StatementBuilder) { + stmt = addRet; + } else { + break; + } + } + } + } + + buildConditionNextBlocks(originStatement: ConditionStatementBuilder, block: BlockBuilder, + isLastStatement: boolean): void { + let nextT = originStatement.nextT?.block; + if (nextT && (isLastStatement || nextT !== block) && !originStatement.nextT?.type.includes(' exit')) { + block.nexts.push(nextT); + nextT.lasts.push(block); + } + let nextF = originStatement.nextF?.block; + if (nextF && (isLastStatement || nextF !== block) && !originStatement.nextF?.type.includes(' exit')) { + block.nexts.push(nextF); + nextF.lasts.push(block); + } + } + + buildSwitchNextBlocks(originStatement: SwitchStatementBuilder, block: BlockBuilder, + isLastStatement: boolean): void { + if (originStatement.nexts.length === 0) { + const nextBlock = originStatement.afterSwitch!.block; + if (nextBlock && (isLastStatement || nextBlock !== block)) { + block.nexts.push(nextBlock); + nextBlock.lasts.push(block); + } + } + for (const next of originStatement.nexts) { + const nextBlock = next.block; + if (nextBlock && (isLastStatement || nextBlock !== block)) { + block.nexts.push(nextBlock); + nextBlock.lasts.push(block); + } + } + } + + buildNormalNextBlocks(originStatement: StatementBuilder, block: BlockBuilder, isLastStatement: boolean): void { + let next = originStatement.next?.block; + if (next && (isLastStatement || next !== block) && !originStatement.next?.type.includes(' exit')) { + block.nexts.push(next); + next.lasts.push(block); + } + } + + buildBlocksNextLast(): void { + for (let block of this.blocks) { + for (let originStatement of block.stmts) { + let isLastStatement = (block.stmts.indexOf(originStatement) === block.stmts.length - 1); + if (originStatement instanceof ConditionStatementBuilder) { + this.buildConditionNextBlocks(originStatement, block, isLastStatement); + } else if (originStatement instanceof SwitchStatementBuilder) { + this.buildSwitchNextBlocks(originStatement, block, isLastStatement); + } else { + this.buildNormalNextBlocks(originStatement, block, isLastStatement); + } + } + } + } + + addReturnBlock(returnStatement: StatementBuilder, notReturnStmts: StatementBuilder[]): void { + let returnBlock = new BlockBuilder(this.blocks.length, [returnStatement]); + returnStatement.block = returnBlock; + this.blocks.push(returnBlock); + for (const notReturnStmt of notReturnStmts) { + if (notReturnStmt instanceof ConditionStatementBuilder) { + if (this.exit === notReturnStmt.nextT) { + notReturnStmt.nextT = returnStatement; + notReturnStmt.block?.nexts.splice(0, 0, returnBlock); + } else if (this.exit === notReturnStmt.nextF) { + notReturnStmt.nextF = returnStatement; + notReturnStmt.block?.nexts.push(returnBlock); + } + } else { + notReturnStmt.next = returnStatement; + notReturnStmt.block?.nexts.push(returnBlock); + } + returnStatement.lasts.add(notReturnStmt); + returnStatement.next = this.exit; + const lasts = [...this.exit.lasts]; + lasts[lasts.indexOf(notReturnStmt)] = returnStatement; + this.exit.lasts = new Set(lasts); + returnBlock.lasts.push(notReturnStmt.block!); + } + this.exit.block = returnBlock; + } + + addReturnStmt(): void { + let notReturnStmts: StatementBuilder[] = []; + for (let stmt of [...this.exit.lasts]) { + if (stmt.type !== 'returnStatement') { + notReturnStmts.push(stmt); + } + } + if (notReturnStmts.length < 1) { + return; + } + const returnStatement = new StatementBuilder('returnStatement', 'return;', null, this.exit.scopeID); + let TryOrSwitchExit = false; + if (notReturnStmts.length === 1 && notReturnStmts[0].block) { + let p: ts.Node | null = notReturnStmts[0].astNode; + while (p && p !== this.astRoot) { + if (ts.isTryStatement(p) || ts.isSwitchStatement(p)) { + TryOrSwitchExit = true; + break; + } + p = p.parent; + } + } + if (notReturnStmts.length === 1 && !(notReturnStmts[0] instanceof ConditionStatementBuilder) && !TryOrSwitchExit) { + const notReturnStmt = notReturnStmts[0]; + notReturnStmt.next = returnStatement; + returnStatement.lasts = new Set([notReturnStmt]); + returnStatement.next = this.exit; + const lasts = [...this.exit.lasts]; + lasts[lasts.indexOf(notReturnStmt)] = returnStatement; + this.exit.lasts = new Set(lasts); + notReturnStmt.block?.stmts.push(returnStatement); + returnStatement.block = notReturnStmt.block; + } else { + this.addReturnBlock(returnStatement, notReturnStmts); + } + } + + resetWalked(): void { + for (let stmt of this.statementArray) { + stmt.walked = false; + } + } + + addStmtBuilderPosition(): void { + for (const stmt of this.statementArray) { + if (stmt.astNode) { + const { line, character } = ts.getLineAndCharacterOfPosition( + this.sourceFile, + stmt.astNode.getStart(this.sourceFile), + ); + stmt.line = line + 1; + stmt.column = character + 1; + } + } + } + + CfgBuilder2Array(stmt: StatementBuilder): void { + + if (stmt.walked) { + return; + } + stmt.walked = true; + stmt.index = this.statementArray.length; + if (!stmt.type.includes(' exit')) { + this.statementArray.push(stmt); + } + if (stmt.type === 'ifStatement' || stmt.type === 'loopStatement' || stmt.type === 'catchOrNot') { + let cstm = stmt as ConditionStatementBuilder; + if (cstm.nextT == null || cstm.nextF == null) { + this.errorTest(cstm); + return; + } + this.CfgBuilder2Array(cstm.nextF); + this.CfgBuilder2Array(cstm.nextT); + } else if (stmt.type === 'switchStatement') { + let sstm = stmt as SwitchStatementBuilder; + for (let ss of sstm.nexts) { + this.CfgBuilder2Array(ss); + } + } else if (stmt.type === 'tryStatement') { + let trystm = stmt as TryStatementBuilder; + if (trystm.tryFirst) { + this.CfgBuilder2Array(trystm.tryFirst); + } + if (trystm.catchStatement) { + this.CfgBuilder2Array(trystm.catchStatement); + } + if (trystm.finallyStatement) { + this.CfgBuilder2Array(trystm.finallyStatement); + } + if (trystm.next) { + this.CfgBuilder2Array(trystm.next); + } + } else { + if (stmt.next != null) { + this.CfgBuilder2Array(stmt.next); + } + } + } + + getDotEdges(stmt: StatementBuilder): void { + if (this.statementArray.length === 0) { + this.CfgBuilder2Array(this.entry); + } + if (stmt.walked) { + return; + } + stmt.walked = true; + if (stmt.type === 'ifStatement' || stmt.type === 'loopStatement' || stmt.type === 'catchOrNot') { + let cstm = stmt as ConditionStatementBuilder; + if (cstm.nextT == null || cstm.nextF == null) { + this.errorTest(cstm); + return; + } + let edge = [cstm.index, cstm.nextF.index]; + this.dotEdges.push(edge); + edge = [cstm.index, cstm.nextT.index]; + this.dotEdges.push(edge); + this.getDotEdges(cstm.nextF); + this.getDotEdges(cstm.nextT); + } else if (stmt.type === 'switchStatement') { + let sstm = stmt as SwitchStatementBuilder; + for (let ss of sstm.nexts) { + let edge = [sstm.index, ss.index]; + this.dotEdges.push(edge); + this.getDotEdges(ss); + } + } else { + if (stmt.next != null) { + let edge = [stmt.index, stmt.next.index]; + this.dotEdges.push(edge); + this.getDotEdges(stmt.next); + } + } + } + + errorTest(stmt: StatementBuilder): void { + let mes = 'ifnext error '; + if (this.declaringClass?.getDeclaringArkFile()) { + mes += this.declaringClass?.getDeclaringArkFile().getName() + '.' + this.declaringClass.getName() + '.' + this.name; + } + mes += '\n' + stmt.code; + throw new TextError(mes); + } + + buildStatementBuilder4ArrowFunction(stmt: ts.Node): void { + let s = new StatementBuilder('statement', stmt.getText(this.sourceFile), stmt, 0); + this.entry.next = s; + s.lasts = new Set([this.entry]); + s.next = this.exit; + this.exit.lasts = new Set([s]); + } + + buildCfgBuilder(): void { + let stmts: ts.Node[] = []; + if (ts.isSourceFile(this.astRoot)) { + stmts = [...this.astRoot.statements]; + } else if (ts.isFunctionDeclaration(this.astRoot) || ts.isMethodDeclaration(this.astRoot) || + ts.isConstructorDeclaration(this.astRoot) || ts.isGetAccessorDeclaration(this.astRoot) || + ts.isSetAccessorDeclaration(this.astRoot) || ts.isFunctionExpression(this.astRoot) || + ts.isClassStaticBlockDeclaration(this.astRoot)) { + if (this.astRoot.body) { + stmts = [...this.astRoot.body.statements]; + } else { + this.emptyBody = true; + } + } else if (ts.isArrowFunction(this.astRoot)) { + if (ts.isBlock(this.astRoot.body)) { + stmts = [...this.astRoot.body.statements]; + } + } else if (ts.isMethodSignature(this.astRoot) || ts.isConstructSignatureDeclaration(this.astRoot) || + ts.isCallSignatureDeclaration(this.astRoot) || ts.isFunctionTypeNode(this.astRoot)) { + this.emptyBody = true; + } else if (ts.isModuleDeclaration(this.astRoot) && ts.isModuleBlock(this.astRoot.body!)) { + stmts = [...this.astRoot.body.statements]; + } + if (!ModelUtils.isArkUIBuilderMethod(this.declaringMethod)) { + this.walkAST(this.entry, this.exit, stmts); + } else { + this.handleBuilder(stmts); + } + if (ts.isArrowFunction(this.astRoot) && !ts.isBlock(this.astRoot.body)) { + this.buildStatementBuilder4ArrowFunction(this.astRoot.body); + } + this.addReturnInEmptyMethod(); + this.deleteExit(); + this.CfgBuilder2Array(this.entry); + this.addStmtBuilderPosition(); + this.buildBlocks(); + this.blocks = this.blocks.filter((b) => b.stmts.length !== 0); + this.buildBlocksNextLast(); + this.addReturnStmt(); + } + + private handleBuilder(stmts: ts.Node[]): void { + let lastStmt = this.entry; + for (const stmt of stmts) { + const stmtBuilder = new StatementBuilder('statement', stmt.getText(this.sourceFile), stmt, 0); + lastStmt.next = stmtBuilder; + stmtBuilder.lasts.add(lastStmt); + lastStmt = stmtBuilder; + } + lastStmt.next = this.exit; + this.exit.lasts.add(lastStmt); + } + + public isBodyEmpty(): boolean { + return this.emptyBody; + } + + public buildCfg(): { + cfg: Cfg, + locals: Set, + globals: Map | null, + aliasTypeMap: Map, + traps: Trap[], + } { + if (ts.isArrowFunction(this.astRoot) && !ts.isBlock(this.astRoot.body)) { + return this.buildCfgForSimpleArrowFunction(); + } + + return this.buildNormalCfg(); + } + + public buildCfgForSimpleArrowFunction(): { + cfg: Cfg, + locals: Set, + globals: Map | null, + aliasTypeMap: Map, + traps: Trap[], + } { + const stmts: Stmt[] = []; + const arkIRTransformer = new ArkIRTransformer(this.sourceFile, this.declaringMethod); + arkIRTransformer.prebuildStmts().forEach(stmt => stmts.push(stmt)); + const expressionBodyNode = (this.astRoot as ts.ArrowFunction).body as ts.Expression; + const expressionBodyStmts: Stmt[] = []; + let { + value: expressionBodyValue, + valueOriginalPositions: expressionBodyPositions, + stmts: tempStmts, + } = arkIRTransformer.tsNodeToValueAndStmts(expressionBodyNode); + tempStmts.forEach(stmt => expressionBodyStmts.push(stmt)); + if (IRUtils.moreThanOneAddress(expressionBodyValue)) { + ({ + value: expressionBodyValue, + valueOriginalPositions: expressionBodyPositions, + stmts: tempStmts, + } = arkIRTransformer.generateAssignStmtForValue(expressionBodyValue, expressionBodyPositions)); + tempStmts.forEach(stmt => expressionBodyStmts.push(stmt)); + } + const returnStmt = new ArkReturnStmt(expressionBodyValue); + returnStmt.setOperandOriginalPositions([expressionBodyPositions[0], ...expressionBodyPositions]); + expressionBodyStmts.push(returnStmt); + arkIRTransformer.mapStmtsToTsStmt(expressionBodyStmts, expressionBodyNode); + expressionBodyStmts.forEach(stmt => stmts.push(stmt)); + const cfg = new Cfg(); + const blockInCfg = new BasicBlock(); + blockInCfg.setId(0); + stmts.forEach(stmt => { + blockInCfg.addStmt(stmt); + stmt.setCfg(cfg); + }); + cfg.addBlock(blockInCfg); + cfg.setStartingStmt(stmts[0]); + return { + cfg: cfg, + locals: arkIRTransformer.getLocals(), + globals: arkIRTransformer.getGlobals(), + aliasTypeMap: arkIRTransformer.getAliasTypeMap(), + traps: [], + }; + } + + public buildNormalCfg(): { + cfg: Cfg, + locals: Set, + globals: Map | null, + aliasTypeMap: Map, + traps: Trap[], + } { + const { blockBuilderToCfgBlock, basicBlockSet, arkIRTransformer } = this.initializeBuild(); + const { + blocksContainLoopCondition, blockBuildersBeforeTry, blockBuildersContainSwitch, + valueAndStmtsOfSwitchAndCasesAll, + } = this.processBlocks(blockBuilderToCfgBlock, basicBlockSet, arkIRTransformer); + + const currBlockId = this.blocks.length; + this.linkBasicBlocks(blockBuilderToCfgBlock); + this.adjustBlocks(blockBuilderToCfgBlock, blocksContainLoopCondition, basicBlockSet, blockBuildersContainSwitch, + valueAndStmtsOfSwitchAndCasesAll, arkIRTransformer); + + const trapBuilder = new TrapBuilder(); + const traps = trapBuilder.buildTraps(blockBuilderToCfgBlock, blockBuildersBeforeTry, arkIRTransformer, basicBlockSet); + + const cfg = this.createCfg(blockBuilderToCfgBlock, basicBlockSet, currBlockId); + return { + cfg, + locals: arkIRTransformer.getLocals(), + globals: arkIRTransformer.getGlobals(), + aliasTypeMap: arkIRTransformer.getAliasTypeMap(), + traps, + }; + } + + private initializeBuild(): { + blockBuilderToCfgBlock: Map, + basicBlockSet: Set, + arkIRTransformer: ArkIRTransformer, + } { + const blockBuilderToCfgBlock = new Map(); + const basicBlockSet = new Set(); + const arkIRTransformer = new ArkIRTransformer(this.sourceFile, this.declaringMethod); + return { blockBuilderToCfgBlock, basicBlockSet, arkIRTransformer }; + } + + private processBlocks( + blockBuilderToCfgBlock: Map, + basicBlockSet: Set, + arkIRTransformer: ArkIRTransformer, + ): { + blocksContainLoopCondition: Set, + blockBuildersBeforeTry: Set, + blockBuildersContainSwitch: BlockBuilder[], + valueAndStmtsOfSwitchAndCasesAll: ValueAndStmts[][], + } { + const blocksContainLoopCondition = new Set(); + const blockBuildersBeforeTry = new Set(); + const blockBuildersContainSwitch: BlockBuilder[] = []; + const valueAndStmtsOfSwitchAndCasesAll: ValueAndStmts[][] = []; + for (let i = 0; i < this.blocks.length; i++) { + const stmtsInBlock: Stmt[] = []; + if (i === 0) { + arkIRTransformer.prebuildStmts().forEach(stmt => stmtsInBlock.push(stmt)); + } + const stmtsCnt = this.blocks[i].stmts.length; + if (this.blocks[i].stmts[stmtsCnt - 1].type === 'tryStatement') { + blockBuildersBeforeTry.add(this.blocks[i]); + } + for (const statementBuilder of this.blocks[i].stmts) { + if (statementBuilder.type === 'loopStatement') { + blocksContainLoopCondition.add(this.blocks[i]); + } else if (statementBuilder instanceof SwitchStatementBuilder) { + blockBuildersContainSwitch.push(this.blocks[i]); + const valueAndStmtsOfSwitchAndCases = arkIRTransformer.switchStatementToValueAndStmts( + statementBuilder.astNode as ts.SwitchStatement); + valueAndStmtsOfSwitchAndCasesAll.push(valueAndStmtsOfSwitchAndCases); + continue; + } + if (statementBuilder.astNode && statementBuilder.code !== '') { + arkIRTransformer.tsNodeToStmts(statementBuilder.astNode).forEach(s => stmtsInBlock.push(s)); + } else if (statementBuilder.code.startsWith('return')) { + stmtsInBlock.push(this.generateReturnStmt(arkIRTransformer)); + } + } + const blockInCfg = new BasicBlock(); + blockInCfg.setId(this.blocks[i].id); + for (const stmt of stmtsInBlock) { + blockInCfg.addStmt(stmt); + } + basicBlockSet.add(blockInCfg); + blockBuilderToCfgBlock.set(this.blocks[i], blockInCfg); + } + return { + blocksContainLoopCondition, blockBuildersBeforeTry, blockBuildersContainSwitch, + valueAndStmtsOfSwitchAndCasesAll, + }; + } + + private generateReturnStmt(arkIRTransformer: ArkIRTransformer): Stmt { + if (this.name === CONSTRUCTOR_NAME) { + this.declaringMethod.getSubSignature().setReturnType(arkIRTransformer.getThisLocal().getType()); + return new ArkReturnStmt(arkIRTransformer.getThisLocal()); + } + if (this.declaringMethod.getSubSignature().getReturnType() instanceof UnknownType && !this.declaringMethod.getAsteriskToken()) { + if (this.declaringMethod.containsModifier(ModifierType.ASYNC)) { + const promise = this.declaringMethod.getDeclaringArkFile().getScene().getSdkGlobal(PROMISE); + if (promise instanceof ArkClass) { + this.declaringMethod.getSubSignature().setReturnType(new ClassType(promise.getSignature())); + } else { + this.declaringMethod.getSubSignature().setReturnType(new UnclearReferenceType(PROMISE, [VoidType.getInstance()])); + } + } else { + this.declaringMethod.getSubSignature().setReturnType(VoidType.getInstance()); + } + } + return new ArkReturnVoidStmt(); + } + + private adjustBlocks( + blockBuilderToCfgBlock: Map, + blocksContainLoopCondition: Set, + basicBlockSet: Set, + blockBuildersContainSwitch: BlockBuilder[], + valueAndStmtsOfSwitchAndCasesAll: ValueAndStmts[][], + arkIRTransformer: ArkIRTransformer, + ): void { + const loopBuilder = new LoopBuilder(); + loopBuilder.rebuildBlocksInLoop(blockBuilderToCfgBlock, blocksContainLoopCondition, basicBlockSet, this.blocks); + const switchBuilder = new SwitchBuilder(); + switchBuilder.buildSwitch(blockBuilderToCfgBlock, blockBuildersContainSwitch, + valueAndStmtsOfSwitchAndCasesAll, arkIRTransformer, basicBlockSet); + const conditionalBuilder = new ConditionBuilder(); + conditionalBuilder.rebuildBlocksContainConditionalOperator(basicBlockSet, ModelUtils.isArkUIBuilderMethod(this.declaringMethod)); + } + + private createCfg( + blockBuilderToCfgBlock: Map, + basicBlockSet: Set, prevBlockId: number, + ): Cfg { + let currBlockId = prevBlockId; + for (const blockBuilder of this.blocks) { + if (blockBuilder.id === -1) { + blockBuilder.id = currBlockId++; + const block = blockBuilderToCfgBlock.get(blockBuilder) as BasicBlock; + block.setId(blockBuilder.id); + } + } + + const cfg = new Cfg(); + const startingBasicBlock = blockBuilderToCfgBlock.get(this.blocks[0])!; + cfg.setStartingStmt(startingBasicBlock.getStmts()[0]); + currBlockId = 0; + for (const basicBlock of basicBlockSet) { + basicBlock.setId(currBlockId++); + cfg.addBlock(basicBlock); + } + for (const stmt of cfg.getStmts()) { + stmt.setCfg(cfg); + } + return cfg; + } + + private linkBasicBlocks(blockBuilderToCfgBlock: Map): void { + for (const [blockBuilder, cfgBlock] of blockBuilderToCfgBlock) { + for (const successorBlockBuilder of blockBuilder.nexts) { + if (!blockBuilderToCfgBlock.get(successorBlockBuilder)) { + continue; + } + const successorBlock = blockBuilderToCfgBlock.get(successorBlockBuilder) as BasicBlock; + cfgBlock.addSuccessorBlock(successorBlock); + } + for (const predecessorBlockBuilder of blockBuilder.lasts) { + if (!blockBuilderToCfgBlock.get(predecessorBlockBuilder)) { + continue; + } + const predecessorBlock = blockBuilderToCfgBlock.get(predecessorBlockBuilder) as BasicBlock; + cfgBlock.addPredecessorBlock(predecessorBlock); + } + } + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/graph/builder/ConditionBuilder.ts b/ets2panda/linter/arkanalyzer/src/core/graph/builder/ConditionBuilder.ts new file mode 100644 index 0000000000..8faaad123c --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/graph/builder/ConditionBuilder.ts @@ -0,0 +1,314 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { BasicBlock } from '../BasicBlock'; +import { ArkIRTransformer, DummyStmt } from '../../common/ArkIRTransformer'; +import { ArkAssignStmt, Stmt } from '../../base/Stmt'; +import { Local } from '../../base/Local'; +import { IRUtils } from '../../common/IRUtils'; + +/** + * Builder for condition in CFG + */ +export class ConditionBuilder { + public rebuildBlocksContainConditionalOperator(basicBlockSet: Set, isArkUIBuilder: boolean): void { + if (isArkUIBuilder) { + this.deleteDummyConditionalOperatorStmt(basicBlockSet); + return; + } + + const currBasicBlocks = Array.from(basicBlockSet); + for (const currBasicBlock of currBasicBlocks) { + const stmtsInCurrBasicBlock = Array.from(currBasicBlock.getStmts()); + const stmtsCnt = stmtsInCurrBasicBlock.length; + let conditionalOperatorEndPos = -1; + for (let i = stmtsCnt - 1; i >= 0; i--) { + const stmt = stmtsInCurrBasicBlock[i]; + if (stmt instanceof DummyStmt && stmt.toString() + ?.startsWith(ArkIRTransformer.DUMMY_CONDITIONAL_OPERATOR_END_STMT)) { + conditionalOperatorEndPos = i; + break; + } + } + if (conditionalOperatorEndPos === -1) { + continue; + } + + let { + generatedTopBlock: generatedTopBlock, + generatedBottomBlocks: generatedBottomBlocks, + } = this.generateBlocksContainConditionalOperatorGroup( + stmtsInCurrBasicBlock.slice(0, conditionalOperatorEndPos + 1), basicBlockSet); + + if (conditionalOperatorEndPos !== stmtsCnt - 1) { // need create a new basic block for rest statements + const { + generatedTopBlock: extraBlock, + } = this.generateBlockWithoutConditionalOperator( + stmtsInCurrBasicBlock.slice(conditionalOperatorEndPos + 1)); + generatedBottomBlocks.forEach(generatedBottomBlock => { + generatedBottomBlock.addSuccessorBlock(extraBlock); + extraBlock.addPredecessorBlock(generatedBottomBlock); + }); + basicBlockSet.add(extraBlock); + generatedBottomBlocks = this.removeUnnecessaryBlocksInConditionalOperator(extraBlock, basicBlockSet); + } + this.relinkPrevAndSuccOfBlockContainConditionalOperator(currBasicBlock, generatedTopBlock, generatedBottomBlocks); + basicBlockSet.delete(currBasicBlock); + } + } + + private relinkPrevAndSuccOfBlockContainConditionalOperator(currBasicBlock: BasicBlock, + generatedTopBlock: BasicBlock, + generatedBottomBlocks: BasicBlock[]): void { + const predecessorsOfCurrBasicBlock = Array.from(currBasicBlock.getPredecessors()); + predecessorsOfCurrBasicBlock.forEach(predecessor => { + predecessor.removeSuccessorBlock(currBasicBlock); + currBasicBlock.removePredecessorBlock(predecessor); + generatedTopBlock.addPredecessorBlock(predecessor); + predecessor.addSuccessorBlock(generatedTopBlock); + }); + const successorsOfCurrBasicBlock = Array.from(currBasicBlock.getSuccessors()); + successorsOfCurrBasicBlock.forEach(successor => { + successor.removePredecessorBlock(currBasicBlock); + currBasicBlock.removeSuccessorBlock(successor); + generatedBottomBlocks.forEach(generatedBottomBlock => { + generatedBottomBlock.addSuccessorBlock(successor); + successor.addPredecessorBlock(generatedBottomBlock); + }); + }); + } + + private generateBlocksContainConditionalOperatorGroup(sourceStmts: Stmt[], basicBlockSet: Set): { + generatedTopBlock: BasicBlock, + generatedBottomBlocks: BasicBlock[], + } { + const { firstEndPos: firstEndPos } = this.findFirstConditionalOperator(sourceStmts); + if (firstEndPos === -1) { + return this.generateBlockWithoutConditionalOperator(sourceStmts); + } + const { + generatedTopBlock: firstGeneratedTopBlock, + generatedBottomBlocks: firstGeneratedBottomBlocks, + generatedAllBlocks: firstGeneratedAllBlocks, + } = this.generateBlocksContainSingleConditionalOperator(sourceStmts.slice(0, firstEndPos + 1)); + const generatedTopBlock = firstGeneratedTopBlock; + let generatedBottomBlocks = firstGeneratedBottomBlocks; + firstGeneratedAllBlocks.forEach(block => basicBlockSet.add(block)); + const stmtsCnt = sourceStmts.length; + if (firstEndPos !== stmtsCnt - 1) { // need handle other conditional operators + const { + generatedTopBlock: restGeneratedTopBlock, + generatedBottomBlocks: restGeneratedBottomBlocks, + } = this.generateBlocksContainConditionalOperatorGroup( + sourceStmts.slice(firstEndPos + 1, stmtsCnt), basicBlockSet); + firstGeneratedBottomBlocks.forEach(firstGeneratedBottomBlock => { + firstGeneratedBottomBlock.addSuccessorBlock(restGeneratedTopBlock); + restGeneratedTopBlock.addPredecessorBlock(firstGeneratedBottomBlock); + }); + restGeneratedBottomBlocks.forEach(block => basicBlockSet.add(block)); + this.removeUnnecessaryBlocksInConditionalOperator(restGeneratedTopBlock, basicBlockSet); + generatedBottomBlocks = restGeneratedBottomBlocks; + } + return { generatedTopBlock, generatedBottomBlocks }; + } + + private generateBlocksContainSingleConditionalOperator(sourceStmts: Stmt[]): { + generatedTopBlock: BasicBlock, + generatedBottomBlocks: BasicBlock[], + generatedAllBlocks: BasicBlock[], + } { + const { + firstIfTruePos: ifTruePos, + firstIfFalsePos: ifFalsePos, + firstEndPos: endPos, + } = this.findFirstConditionalOperator(sourceStmts); + if (endPos === -1) { + return this.generateBlockWithoutConditionalOperator(sourceStmts); + } + const { + generatedTopBlock: generatedTopBlock, + generatedAllBlocks: generatedAllBlocks, + } = this.generateBlockWithoutConditionalOperator(sourceStmts.slice(0, ifTruePos)); + let generatedBottomBlocks: BasicBlock[] = []; + const { + generatedTopBlock: generatedTopBlockOfTrueBranch, + generatedBottomBlocks: generatedBottomBlocksOfTrueBranch, + generatedAllBlocks: generatedAllBlocksOfTrueBranch, + } = this.generateBlocksContainSingleConditionalOperator(sourceStmts.slice(ifTruePos + 1, ifFalsePos)); + generatedBottomBlocks.push(...generatedBottomBlocksOfTrueBranch); + generatedAllBlocks.push(...generatedAllBlocksOfTrueBranch); + const { + generatedTopBlock: generatedTopBlockOfFalseBranch, + generatedBottomBlocks: generatedBottomBlocksOfFalseBranch, + generatedAllBlocks: generatedAllBlocksOfFalseBranch, + } = this.generateBlocksContainSingleConditionalOperator(sourceStmts.slice(ifFalsePos + 1, endPos)); + generatedBottomBlocks.push(...generatedBottomBlocksOfFalseBranch); + generatedAllBlocks.push(...generatedAllBlocksOfFalseBranch); + + generatedTopBlock.addSuccessorBlock(generatedTopBlockOfTrueBranch); + generatedTopBlockOfTrueBranch.addPredecessorBlock(generatedTopBlock); + generatedTopBlock.addSuccessorBlock(generatedTopBlockOfFalseBranch); + generatedTopBlockOfFalseBranch.addPredecessorBlock(generatedTopBlock); + const stmtsCnt = sourceStmts.length; + if (endPos !== stmtsCnt - 1) { // need create a new basic block for rest statements + const { + generatedTopBlock: extraBlock, + } = this.generateBlockWithoutConditionalOperator(sourceStmts.slice(endPos + 1)); + generatedBottomBlocks.forEach(generatedBottomBlock => { + generatedBottomBlock.addSuccessorBlock(extraBlock); + extraBlock.addPredecessorBlock(generatedBottomBlock); + }); + generatedBottomBlocks = [extraBlock]; + generatedAllBlocks.push(extraBlock); + } + return { generatedTopBlock, generatedBottomBlocks, generatedAllBlocks }; + } + + private generateBlockWithoutConditionalOperator(sourceStmts: Stmt[]): { + generatedTopBlock: BasicBlock, + generatedBottomBlocks: BasicBlock[], + generatedAllBlocks: BasicBlock[], + } { + const generatedBlock = new BasicBlock(); + sourceStmts.forEach(stmt => generatedBlock.addStmt(stmt)); + return { + generatedTopBlock: generatedBlock, + generatedBottomBlocks: [generatedBlock], + generatedAllBlocks: [generatedBlock], + }; + } + + private deleteDummyConditionalOperatorStmt(basicBlockSet: Set): void { + for (const basicBlock of basicBlockSet) { + const stmts = Array.from(basicBlock.getStmts()); + for (const stmt of stmts) { + if (stmt instanceof DummyStmt && stmt.toString() + ?.startsWith(ArkIRTransformer.DUMMY_CONDITIONAL_OPERATOR)) { + basicBlock.remove(stmt); + } + } + } + } + + private findFirstConditionalOperator(stmts: Stmt[]): { + firstIfTruePos: number, firstIfFalsePos: number, firstEndPos: number, + } { + let firstIfTruePos = -1; + let firstIfFalsePos = -1; + let firstEndPos = -1; + let firstConditionalOperatorNo = ''; + for (let i = 0; i < stmts.length; i++) { + const stmt = stmts[i]; + if (stmt instanceof DummyStmt) { + if (stmt.toString() + .startsWith(ArkIRTransformer.DUMMY_CONDITIONAL_OPERATOR_IF_TRUE_STMT) && firstIfTruePos === + -1) { + firstIfTruePos = i; + firstConditionalOperatorNo = + stmt.toString().replace(ArkIRTransformer.DUMMY_CONDITIONAL_OPERATOR_IF_TRUE_STMT, ''); + } else if (stmt.toString() === ArkIRTransformer.DUMMY_CONDITIONAL_OPERATOR_IF_FALSE_STMT + + firstConditionalOperatorNo) { + firstIfFalsePos = i; + } else if (stmt.toString() === ArkIRTransformer.DUMMY_CONDITIONAL_OPERATOR_END_STMT + + firstConditionalOperatorNo) { + firstEndPos = i; + } + } + } + return { firstIfTruePos, firstIfFalsePos, firstEndPos }; + } + + private removeUnnecessaryBlocksInConditionalOperator(bottomBlock: BasicBlock, + allBlocks: Set): BasicBlock[] { + const firstStmtInBottom = bottomBlock.getStmts()[0]; + if (!(firstStmtInBottom instanceof ArkAssignStmt)) { + return [bottomBlock]; + } + + const targetValue = firstStmtInBottom.getLeftOp(); + const tempResultValue = firstStmtInBottom.getRightOp(); + if (!(targetValue instanceof Local && IRUtils.isTempLocal(tempResultValue))) { + return [bottomBlock]; + } + const oldPredecessors = Array.from(bottomBlock.getPredecessors()); + const newPredecessors: BasicBlock[] = []; + for (const predecessor of oldPredecessors) { + predecessor.removeSuccessorBlock(bottomBlock); + newPredecessors.push( + ...this.replaceTempRecursively(predecessor, targetValue as Local, tempResultValue as Local, + allBlocks)); + } + + bottomBlock.remove(firstStmtInBottom); + if (bottomBlock.getStmts().length === 0) { // must be a new block without successors + allBlocks.delete(bottomBlock); + return newPredecessors; + } + + oldPredecessors.forEach((oldPredecessor) => { + bottomBlock.removePredecessorBlock(oldPredecessor); + }); + newPredecessors.forEach((newPredecessor) => { + bottomBlock.addPredecessorBlock(newPredecessor); + newPredecessor.addSuccessorBlock(bottomBlock); + }); + return [bottomBlock]; + } + + private replaceTempRecursively(currBottomBlock: BasicBlock, targetLocal: Local, + tempResultLocal: Local, allBlocks: Set): BasicBlock[] { + const stmts = currBottomBlock.getStmts(); + const stmtsCnt = stmts.length; + let tempResultReassignStmt: Stmt | null = null; + for (let i = stmtsCnt - 1; i >= 0; i--) { + const stmt = stmts[i]; + if (stmt instanceof ArkAssignStmt && stmt.getLeftOp() === tempResultLocal) { + if (IRUtils.isTempLocal(stmt.getRightOp())) { + tempResultReassignStmt = stmt; + } else { + stmt.setLeftOp(targetLocal); + } + } + } + + let newBottomBlocks: BasicBlock[] = []; + if (tempResultReassignStmt) { + const oldPredecessors = currBottomBlock.getPredecessors(); + const newPredecessors: BasicBlock[] = []; + const prevTempResultLocal = (tempResultReassignStmt as ArkAssignStmt).getRightOp() as Local; + for (const predecessor of oldPredecessors) { + predecessor.removeSuccessorBlock(currBottomBlock); + newPredecessors.push( + ...this.replaceTempRecursively(predecessor, targetLocal, prevTempResultLocal, allBlocks)); + } + + currBottomBlock.remove(tempResultReassignStmt); + if (currBottomBlock.getStmts().length === 0) { + // remove this block + newBottomBlocks = newPredecessors; + allBlocks.delete(currBottomBlock); + } else { + currBottomBlock.getPredecessors().splice(0, oldPredecessors.length, ...newPredecessors); + newPredecessors.forEach((newPredecessor) => { + newPredecessor.addSuccessorBlock(currBottomBlock); + }); + newBottomBlocks = [currBottomBlock]; + } + } else { + newBottomBlocks = [currBottomBlock]; + } + return newBottomBlocks; + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/graph/builder/LoopBuilder.ts b/ets2panda/linter/arkanalyzer/src/core/graph/builder/LoopBuilder.ts new file mode 100644 index 0000000000..df6d7cbad7 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/graph/builder/LoopBuilder.ts @@ -0,0 +1,342 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { BasicBlock } from '../BasicBlock'; +import { ArkAssignStmt, ArkIfStmt, Stmt } from '../../base/Stmt'; +import { AbstractInvokeExpr } from '../../base/Expr'; +import { Builtin } from '../../common/Builtin'; +import { ArkIRTransformer } from '../../common/ArkIRTransformer'; +import { BlockBuilder } from './CfgBuilder'; + +/** + * Builder for loop in CFG + */ +export class LoopBuilder { + public rebuildBlocksInLoop(blockBuilderToCfgBlock: Map, + blocksContainLoopCondition: Set, + basicBlockSet: Set, blockBuilders: BlockBuilder[]): void { + for (const blockBuilder of blocksContainLoopCondition) { + if (!blockBuilderToCfgBlock.get(blockBuilder)) { + continue; + } + const block = blockBuilderToCfgBlock.get(blockBuilder) as BasicBlock; + + const blockId = block.getId(); + const stmts = block.getStmts(); + const stmtsCnt = stmts.length; + const { ifStmtIdx, iteratorNextStmtIdx, dummyInitializerStmtIdx } = this.findIteratorIdx(stmts); + if (iteratorNextStmtIdx !== -1 || dummyInitializerStmtIdx !== -1) { + const lastStmtIdxBeforeCondition = iteratorNextStmtIdx !== + -1 ? iteratorNextStmtIdx : dummyInitializerStmtIdx; + const stmtsInsertBeforeCondition = stmts.slice(0, lastStmtIdxBeforeCondition); + + // If the loop body is empty, the loop conditional block should contain its own + const emptyLoopBody = blockBuilder.nexts.length === 1; + if (emptyLoopBody) { + blockBuilder.nexts.splice(0, 0, blockBuilder); + blockBuilder.lasts.push(blockBuilder); + block.getSuccessors().splice(0, 0, block); + block.addPredecessorBlock(block); + } + + let prevBlockBuilderContainsLoop = this.doesPrevBlockBuilderContainLoop(blockBuilder, blockId, + blocksContainLoopCondition); + if (prevBlockBuilderContainsLoop) { + // should create an extra block when previous block contains loop condition + this.insertBeforeConditionBlockBuilder(blockBuilderToCfgBlock, blockBuilder, + stmtsInsertBeforeCondition, false, basicBlockSet, blockBuilders); + } else { + const blockBuilderBeforeCondition = blockBuilder.lasts[0]; + const blockBeforeCondition = blockBuilderToCfgBlock.get(blockBuilderBeforeCondition) as BasicBlock; + stmtsInsertBeforeCondition.forEach(stmt => blockBeforeCondition?.getStmts().push(stmt)); + } + if (dummyInitializerStmtIdx !== -1 && ifStmtIdx !== stmtsCnt - 1) { + // put incrementor statements into block which reenters condition + this.adjustIncrementorStmts(stmts, ifStmtIdx, blockBuilder, blockId, blockBuilderToCfgBlock, + blocksContainLoopCondition, basicBlockSet, emptyLoopBody, blockBuilders); + } else if (iteratorNextStmtIdx !== -1) { + // put statements which get value of iterator into block after condition + const blockBuilderAfterCondition = blockBuilder.nexts[0]; + const blockAfterCondition = blockBuilderToCfgBlock.get(blockBuilderAfterCondition) as BasicBlock; + const stmtsAfterCondition = stmts.slice(ifStmtIdx + 1); + blockAfterCondition?.getStmts().splice(0, 0, ...stmtsAfterCondition); + } + // remove statements which should not in condition + const firstStmtIdxInCondition = iteratorNextStmtIdx !== + -1 ? iteratorNextStmtIdx : dummyInitializerStmtIdx + 1; + stmts.splice(0, firstStmtIdxInCondition); + stmts.splice(ifStmtIdx - firstStmtIdxInCondition + 1); + } + } + } + + private doesPrevBlockBuilderContainLoop(currBlockBuilder: BlockBuilder, currBlockId: number, + blocksContainLoopCondition: Set): boolean { + let prevBlockBuilderContainsLoop = false; + for (const prevBlockBuilder of currBlockBuilder.lasts) { + if (prevBlockBuilder.id < currBlockId && blocksContainLoopCondition.has(prevBlockBuilder)) { + prevBlockBuilderContainsLoop = true; + break; + } + } + return prevBlockBuilderContainsLoop; + } + + private insertBeforeConditionBlockBuilder( + blockBuilderToCfgBlock: Map, + conditionBlockBuilder: BlockBuilder, + stmtsInsertBeforeCondition: Stmt[], + collectReenter: Boolean, + basicBlockSet: Set, + blockBuilders: BlockBuilder[], + ): void { + if (stmtsInsertBeforeCondition.length === 0) { + return; + } + const blockId = conditionBlockBuilder.id; + const block = this.getBlockFromMap(blockBuilderToCfgBlock, conditionBlockBuilder); + const { + blockBuildersBeforeCondition, blocksBeforeCondition, blockBuildersReenterCondition, blocksReenterCondition, + } = this.collectBlocksBeforeAndReenter(blockBuilderToCfgBlock, conditionBlockBuilder, blockId); + + const { + collectedBlockBuilders, collectedBlocks, + } = this.getCollectedBlocks(collectReenter, blockBuildersBeforeCondition, blocksBeforeCondition, + blockBuildersReenterCondition, blocksReenterCondition); + + const { blockBuilderInsertBeforeCondition, blockInsertBeforeCondition } = this.createAndLinkBlocks( + collectedBlockBuilders, collectedBlocks, conditionBlockBuilder, stmtsInsertBeforeCondition, block); + + this.updatePredecessors(collectedBlockBuilders, blockBuilderToCfgBlock, conditionBlockBuilder, + blockBuilderInsertBeforeCondition, blockInsertBeforeCondition); + + const { newPrevBlockBuildersBeforeCondition, newPrevBlocksBeforeCondition } = this.getNewPrevBlocks( + collectReenter, blockBuildersBeforeCondition, blocksBeforeCondition, blockBuilderInsertBeforeCondition, + blockInsertBeforeCondition, blockBuildersReenterCondition, blocksReenterCondition); + + this.updateConditionBlockBuilder(conditionBlockBuilder, newPrevBlockBuildersBeforeCondition, block, newPrevBlocksBeforeCondition); + + this.finalizeInsertion(blockBuilderInsertBeforeCondition, blockInsertBeforeCondition, basicBlockSet, blockBuilderToCfgBlock, blockBuilders); + } + + private getBlockFromMap(blockBuilderToCfgBlock: Map, + conditionBlockBuilder: BlockBuilder): BasicBlock { + return blockBuilderToCfgBlock.get(conditionBlockBuilder) as BasicBlock; + } + + private collectBlocksBeforeAndReenter( + blockBuilderToCfgBlock: Map, + conditionBlockBuilder: BlockBuilder, + blockId: number, + ): { + blockBuildersBeforeCondition: BlockBuilder[], blocksBeforeCondition: BasicBlock[], + blockBuildersReenterCondition: BlockBuilder[], blocksReenterCondition: BasicBlock[] + } { + const blockBuildersBeforeCondition: BlockBuilder[] = []; + const blocksBeforeCondition: BasicBlock[] = []; + const blockBuildersReenterCondition: BlockBuilder[] = []; + const blocksReenterCondition: BasicBlock[] = []; + for (const prevBlockBuilder of conditionBlockBuilder.lasts) { + const prevBlock = blockBuilderToCfgBlock.get(prevBlockBuilder) as BasicBlock; + if (prevBlock.getId() < blockId) { + blockBuildersBeforeCondition.push(prevBlockBuilder); + blocksBeforeCondition.push(prevBlock); + } else { + blockBuildersReenterCondition.push(prevBlockBuilder); + blocksReenterCondition.push(prevBlock); + } + } + return { + blockBuildersBeforeCondition, blocksBeforeCondition, blockBuildersReenterCondition, blocksReenterCondition, + }; + } + + private getCollectedBlocks( + collectReenter: Boolean, + blockBuildersBeforeCondition: BlockBuilder[], + blocksBeforeCondition: BasicBlock[], + blockBuildersReenterCondition: BlockBuilder[], + blocksReenterCondition: BasicBlock[], + ): { collectedBlockBuilders: BlockBuilder[], collectedBlocks: BasicBlock[] } { + let collectedBlockBuilders: BlockBuilder[] = []; + let collectedBlocks: BasicBlock[] = []; + if (collectReenter) { + collectedBlockBuilders = blockBuildersReenterCondition; + collectedBlocks = blocksReenterCondition; + } else { + collectedBlockBuilders = blockBuildersBeforeCondition; + collectedBlocks = blocksBeforeCondition; + } + return { collectedBlockBuilders, collectedBlocks }; + } + + private createAndLinkBlocks( + collectedBlockBuilders: BlockBuilder[], + collectedBlocks: BasicBlock[], + conditionBlockBuilder: BlockBuilder, + stmtsInsertBeforeCondition: Stmt[], + block: BasicBlock, + ): { blockBuilderInsertBeforeCondition: BlockBuilder, blockInsertBeforeCondition: BasicBlock } { + const blockBuilderInsertBeforeCondition = new BlockBuilder(-1, []); + blockBuilderInsertBeforeCondition.lasts.push(...collectedBlockBuilders); + blockBuilderInsertBeforeCondition.nexts.push(conditionBlockBuilder); + const blockInsertBeforeCondition = new BasicBlock(); + stmtsInsertBeforeCondition.forEach(stmt => blockInsertBeforeCondition.getStmts().push(stmt)); + blockInsertBeforeCondition.getPredecessors().push(...collectedBlocks); + blockInsertBeforeCondition.addSuccessorBlock(block); + return { blockBuilderInsertBeforeCondition, blockInsertBeforeCondition }; + } + + private updatePredecessors( + collectedBlockBuilders: BlockBuilder[], + blockBuilderToCfgBlock: Map, + conditionBlockBuilder: BlockBuilder, + blockBuilderInsertBeforeCondition: BlockBuilder, + blockInsertBeforeCondition: BasicBlock, + ): void { + for (const prevBlockBuilder of collectedBlockBuilders) { + const prevBlock = blockBuilderToCfgBlock.get(prevBlockBuilder) as BasicBlock; + for (let j = 0; j < prevBlockBuilder.nexts.length; j++) { + if (prevBlockBuilder.nexts[j] === conditionBlockBuilder) { + prevBlockBuilder.nexts[j] = blockBuilderInsertBeforeCondition; + prevBlock.setSuccessorBlock(j, blockInsertBeforeCondition); + break; + } + } + } + } + + private getNewPrevBlocks( + collectReenter: Boolean, + blockBuildersBeforeCondition: BlockBuilder[], + blocksBeforeCondition: BasicBlock[], + blockBuilderInsertBeforeCondition: BlockBuilder, + blockInsertBeforeCondition: BasicBlock, + blockBuildersReenterCondition: BlockBuilder[], + blocksReenterCondition: BasicBlock[], + ): { newPrevBlockBuildersBeforeCondition: BlockBuilder[], newPrevBlocksBeforeCondition: BasicBlock[] } { + let newPrevBlockBuildersBeforeCondition: BlockBuilder[] = []; + let newPrevBlocksBeforeCondition: BasicBlock[] = []; + if (collectReenter) { + newPrevBlockBuildersBeforeCondition = [...blockBuildersBeforeCondition, blockBuilderInsertBeforeCondition]; + newPrevBlocksBeforeCondition = [...blocksBeforeCondition, blockInsertBeforeCondition]; + } else { + newPrevBlockBuildersBeforeCondition = [blockBuilderInsertBeforeCondition, ...blockBuildersReenterCondition]; + newPrevBlocksBeforeCondition = [blockInsertBeforeCondition, ...blocksReenterCondition]; + } + return { newPrevBlockBuildersBeforeCondition, newPrevBlocksBeforeCondition }; + } + + private updateConditionBlockBuilder( + conditionBlockBuilder: BlockBuilder, + newPrevBlockBuildersBeforeCondition: BlockBuilder[], + block: BasicBlock, + newPrevBlocksBeforeCondition: BasicBlock[], + ): void { + conditionBlockBuilder.lasts = newPrevBlockBuildersBeforeCondition; + const predecessorsCnt = block.getPredecessors().length; + block.getPredecessors().splice(0, predecessorsCnt, ...newPrevBlocksBeforeCondition); + } + + private finalizeInsertion( + blockBuilderInsertBeforeCondition: BlockBuilder, + blockInsertBeforeCondition: BasicBlock, + basicBlockSet: Set, + blockBuilderToCfgBlock: Map, + blockBuilders: BlockBuilder[], + ): void { + blockBuilders.push(blockBuilderInsertBeforeCondition); + basicBlockSet.add(blockInsertBeforeCondition); + blockBuilderToCfgBlock.set(blockBuilderInsertBeforeCondition, blockInsertBeforeCondition); + } + + private findIteratorIdx(stmts: Stmt[]): { + ifStmtIdx: number, iteratorNextStmtIdx: number, dummyInitializerStmtIdx: number + } { + let ifStmtIdx = -1; + let iteratorNextStmtIdx = -1; + let dummyInitializerStmtIdx = -1; + const stmtsCnt = stmts.length; + for (let i = 0; i < stmtsCnt; i++) { + const stmt = stmts[i]; + if (stmt instanceof ArkAssignStmt && stmt.getRightOp() instanceof AbstractInvokeExpr) { + const invokeExpr = stmt.getRightOp() as AbstractInvokeExpr; + if (invokeExpr.getMethodSignature().getMethodSubSignature() + .getMethodName() === Builtin.ITERATOR_NEXT) { + iteratorNextStmtIdx = i; + continue; + } + } + if (stmt.toString() === ArkIRTransformer.DUMMY_LOOP_INITIALIZER_STMT) { + dummyInitializerStmtIdx = i; + continue; + } + if (stmt instanceof ArkIfStmt) { + ifStmtIdx = i; + break; + } + } + return { + ifStmtIdx: ifStmtIdx, + iteratorNextStmtIdx: iteratorNextStmtIdx, + dummyInitializerStmtIdx: dummyInitializerStmtIdx, + }; + } + + private adjustIncrementorStmts(stmts: Stmt[], ifStmtIdx: number, currBlockBuilder: BlockBuilder, + currBlockId: number, blockBuilderToCfgBlock: Map, + blocksContainLoopCondition: Set, basicBlockSet: Set, + emptyLoopBody: boolean, blockBuilders: BlockBuilder[]): void { + const stmtsReenterCondition = stmts.slice(ifStmtIdx + 1); + if (emptyLoopBody) { + const incrementorBlockBuilder = new BlockBuilder(-1, []); + incrementorBlockBuilder.lasts.push(currBlockBuilder); + currBlockBuilder.nexts[0] = incrementorBlockBuilder; + incrementorBlockBuilder.nexts.push(currBlockBuilder); + currBlockBuilder.lasts[1] = incrementorBlockBuilder; + const incrementorBlock = new BasicBlock(); + blockBuilderToCfgBlock.set(incrementorBlockBuilder, incrementorBlock); + stmtsReenterCondition.forEach(stmt => incrementorBlock.getStmts().push(stmt)); + const currBlock = blockBuilderToCfgBlock.get(currBlockBuilder) as BasicBlock; + incrementorBlock.getPredecessors().push(currBlock); + currBlock.setPredecessorBlock(1, incrementorBlock); + incrementorBlock.addSuccessorBlock(currBlock); + currBlock.setSuccessorBlock(0, incrementorBlock); + basicBlockSet.add(incrementorBlock); + return; + } + + const blockBuildersReenterCondition: BlockBuilder[] = []; + for (const prevBlockBuilder of currBlockBuilder.lasts) { + const prevBlock = blockBuilderToCfgBlock.get(prevBlockBuilder) as BasicBlock; + + if (prevBlock.getId() > currBlockId) { + blockBuildersReenterCondition.push(prevBlockBuilder); + } + } + + if (blockBuildersReenterCondition.length > 1 || blocksContainLoopCondition.has( + blockBuildersReenterCondition[0])) { + // put incrementor statements into an extra block + this.insertBeforeConditionBlockBuilder(blockBuilderToCfgBlock, currBlockBuilder, + stmtsReenterCondition, true, basicBlockSet, blockBuilders); + } else { + // put incrementor statements into prev reenter block + const blockReenterCondition = blockBuilderToCfgBlock.get( + blockBuildersReenterCondition[0]) as BasicBlock; + stmtsReenterCondition.forEach(stmt => blockReenterCondition?.getStmts().push(stmt)); + } + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/graph/builder/SwitchBuilder.ts b/ets2panda/linter/arkanalyzer/src/core/graph/builder/SwitchBuilder.ts new file mode 100644 index 0000000000..60a231c2c2 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/graph/builder/SwitchBuilder.ts @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { BasicBlock } from '../BasicBlock'; +import { ArkIRTransformer, ValueAndStmts } from '../../common/ArkIRTransformer'; +import { Stmt } from '../../base/Stmt'; +import { BlockBuilder, SwitchStatementBuilder } from './CfgBuilder'; +import Logger, { LOG_MODULE_TYPE } from '../../../utils/logger'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'SwitchBuilder'); + +/** + * Builder for switch statement in CFG + */ +export class SwitchBuilder { + public buildSwitch(blockBuilderToCfgBlock: Map, + blockBuildersContainSwitch: BlockBuilder[], + valueAndStmtsOfSwitchAndCasesAll: ValueAndStmts[][], arkIRTransformer: ArkIRTransformer, + basicBlockSet: Set): void { + for (let i = 0; i < blockBuildersContainSwitch.length; i++) { + const blockBuilderContainSwitch = blockBuildersContainSwitch[i]; + + if (!blockBuilderToCfgBlock.has(blockBuilderContainSwitch)) { + logger.error( + `can't find basicBlock corresponding to the blockBuilder.`); + continue; + } + + const blockContainSwitch = blockBuilderToCfgBlock.get(blockBuilderContainSwitch)!; + const valueAndStmtsOfSwitch = valueAndStmtsOfSwitchAndCasesAll[i][0]; + const stmtsOfSwitch = valueAndStmtsOfSwitch.stmts; + stmtsOfSwitch.forEach((stmt: Stmt) => { + blockContainSwitch.addStmt(stmt); + }); + + const stmtsCnt = blockBuilderContainSwitch.stmts.length; + const switchStmtBuilder = blockBuilderContainSwitch.stmts[stmtsCnt - 1] as SwitchStatementBuilder; + const cases = switchStmtBuilder.cases; + let nonEmptyCaseCnt = 0; + for (const currCase of cases) { + if (currCase.stmt.block) { // there are stmts after this case + nonEmptyCaseCnt++; + } + } + if (nonEmptyCaseCnt === 0) { + continue; + } + + const caseCnt = cases.length; + const caseIfBlocks = this.generateIfBlocksForCases(valueAndStmtsOfSwitchAndCasesAll[i], caseCnt, + blockContainSwitch, basicBlockSet, arkIRTransformer); + this.linkIfBlockAndCaseBlock(blockContainSwitch, caseIfBlocks, switchStmtBuilder, + blockBuilderToCfgBlock); + } + } + + private generateIfBlocksForCases(valueAndStmtsOfSwitchAndCases: ValueAndStmts[], caseCnt: number, + blockContainSwitch: BasicBlock, basicBlockSet: Set, + arkIRTransformer: ArkIRTransformer): BasicBlock[] { + const valueAndStmtsOfSwitch = valueAndStmtsOfSwitchAndCases[0]; + const valueOfSwitch = valueAndStmtsOfSwitch.value; + const caseIfBlocks: BasicBlock[] = []; + + for (let j = 0; j < caseCnt; j++) { + let caseIfBlock: BasicBlock; + if (j === 0) { + caseIfBlock = blockContainSwitch; + } else { + caseIfBlock = new BasicBlock(); + basicBlockSet.add(caseIfBlock); + } + caseIfBlocks.push(caseIfBlock); + + const caseValueAndStmts = valueAndStmtsOfSwitchAndCases[j + 1]; + const caseValue = caseValueAndStmts.value; + const caseStmts = caseValueAndStmts.stmts; + caseStmts.forEach((stmt: Stmt) => { + caseIfBlock.addStmt(stmt); + }); + const caseIfStmts = arkIRTransformer.generateIfStmtForValues(valueOfSwitch, + valueAndStmtsOfSwitch.valueOriginalPositions, caseValue, + caseValueAndStmts.valueOriginalPositions); + caseIfStmts.forEach((stmt: Stmt) => { + caseIfBlock.addStmt(stmt); + }); + } + return caseIfBlocks; + } + + private linkIfBlockAndCaseBlock(blockContainSwitch: BasicBlock, caseIfBlocks: BasicBlock[], + switchStmtBuilder: SwitchStatementBuilder, + blockBuilderToCfgBlock: Map): boolean { + const successorsOfBlockContainSwitch = Array.from(blockContainSwitch.getSuccessors()); + const expectedSuccessorsOfCaseIfBlock: BasicBlock[] = []; + const defaultStmtBuilder = switchStmtBuilder.default; + if (defaultStmtBuilder && defaultStmtBuilder.block) { + expectedSuccessorsOfCaseIfBlock.push(...successorsOfBlockContainSwitch.splice(-1, 1)); + } else { + const afterSwitchStmtBuilder = switchStmtBuilder.afterSwitch; + const afterSwitchBlockBuilder = afterSwitchStmtBuilder?.block; + if (!afterSwitchBlockBuilder || !blockBuilderToCfgBlock.has(afterSwitchBlockBuilder)) { + logger.error(`can't find basicBlock corresponding to the blockBuilder.`); + return false; + } + expectedSuccessorsOfCaseIfBlock.push(blockBuilderToCfgBlock.get(afterSwitchBlockBuilder)!); + } + const caseCnt = switchStmtBuilder.cases.length; + for (let i = caseCnt - 1; i >= 0; i--) { + const currCase = switchStmtBuilder.cases[i]; + if (currCase.stmt.block) { + expectedSuccessorsOfCaseIfBlock.push(...successorsOfBlockContainSwitch.splice(-1, 1)); + } else { // if there are no stmts after this case, reuse the successor of the next case + expectedSuccessorsOfCaseIfBlock.push(...expectedSuccessorsOfCaseIfBlock.slice(-1)); + } + } + expectedSuccessorsOfCaseIfBlock.reverse(); + + blockContainSwitch.getSuccessors().forEach((successor) => { + successor.getPredecessors().splice(0, 1); + }); + blockContainSwitch.getSuccessors().splice(0); + for (let j = 0; j < caseCnt; j++) { + const caseIfBlock = caseIfBlocks[j]; + caseIfBlock.addSuccessorBlock(expectedSuccessorsOfCaseIfBlock[j]); + expectedSuccessorsOfCaseIfBlock[j].addPredecessorBlock(caseIfBlock); + if (j === caseCnt - 1) { // the false branch of last case should be default or block after switch statement + caseIfBlock.addSuccessorBlock(expectedSuccessorsOfCaseIfBlock[j + 1]); + expectedSuccessorsOfCaseIfBlock[j + 1].addPredecessorBlock(caseIfBlock); + } else { + caseIfBlock.addSuccessorBlock(caseIfBlocks[j + 1]); + caseIfBlocks[j + 1].addPredecessorBlock(caseIfBlock); + } + } + return true; + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/graph/builder/TrapBuilder.ts b/ets2panda/linter/arkanalyzer/src/core/graph/builder/TrapBuilder.ts new file mode 100644 index 0000000000..fdb4689601 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/graph/builder/TrapBuilder.ts @@ -0,0 +1,281 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { BasicBlock } from '../BasicBlock'; +import { ArkIRTransformer } from '../../common/ArkIRTransformer'; +import { Trap } from '../../base/Trap'; +import { ArkCaughtExceptionRef } from '../../base/Ref'; +import { UnknownType } from '../../base/Type'; +import { FullPosition } from '../../base/Position'; +import { + ArkAssignStmt, + ArkIfStmt, + ArkInvokeStmt, + ArkReturnStmt, + ArkReturnVoidStmt, + ArkThrowStmt, + Stmt, +} from '../../base/Stmt'; +import { BlockBuilder, TryStatementBuilder } from './CfgBuilder'; +import Logger, { LOG_MODULE_TYPE } from '../../../utils/logger'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'TrapBuilder'); + +/** + * Builder for traps from try...catch + */ +export class TrapBuilder { + public buildTraps(blockBuilderToCfgBlock: Map, blockBuildersBeforeTry: Set, + arkIRTransformer: ArkIRTransformer, basicBlockSet: Set): Trap[] { + const traps: Trap[] = []; + for (const blockBuilderBeforeTry of blockBuildersBeforeTry) { + if (blockBuilderBeforeTry.nexts.length === 0) { + logger.error(`can't find try block.`); + continue; + } + const blockBuilderContainTry = blockBuilderBeforeTry.nexts[0]; + const stmtsCnt = blockBuilderBeforeTry.stmts.length; + const tryStmtBuilder = blockBuilderBeforeTry.stmts[stmtsCnt - 1] as TryStatementBuilder; + const finallyBlockBuilder = tryStmtBuilder.finallyStatement?.block; + if (!finallyBlockBuilder) { + logger.error(`can't find finally block or dummy finally block.`); + continue; + } + const { bfsBlocks: tryBfsBlocks, tailBlocks: tryTailBlocks } = this.getAllBlocksBFS(blockBuilderToCfgBlock, + blockBuilderContainTry, finallyBlockBuilder); + let catchBfsBlocks: BasicBlock[] = []; + let catchTailBlocks: BasicBlock[] = []; + const catchBlockBuilder = tryStmtBuilder.catchStatement?.block; + if (catchBlockBuilder) { + ({ bfsBlocks: catchBfsBlocks, tailBlocks: catchTailBlocks } = this.getAllBlocksBFS( + blockBuilderToCfgBlock, catchBlockBuilder)); + } + const finallyStmts = finallyBlockBuilder.stmts; + const blockBuilderAfterFinally = tryStmtBuilder.afterFinal?.block; + if (!blockBuilderAfterFinally) { + logger.error(`can't find block after try...catch.`); + continue; + } + if (finallyStmts.length === 1 && finallyStmts[0].code === 'dummyFinally') { // no finally block + const trapsIfNoFinally = this.buildTrapsIfNoFinally(tryBfsBlocks, tryTailBlocks, catchBfsBlocks, + catchTailBlocks, + finallyBlockBuilder, blockBuilderAfterFinally, basicBlockSet, blockBuilderToCfgBlock); + if (trapsIfNoFinally) { + traps.push(...trapsIfNoFinally); + } + } else { + const trapsIfFinallyExist = this.buildTrapsIfFinallyExist(tryBfsBlocks, tryTailBlocks, catchBfsBlocks, + catchTailBlocks, finallyBlockBuilder, blockBuilderAfterFinally, basicBlockSet, arkIRTransformer, + blockBuilderToCfgBlock); + traps.push(...trapsIfFinallyExist); + } + } + return traps; + } + + private buildTrapsIfNoFinally(tryBfsBlocks: BasicBlock[], tryTailBlocks: BasicBlock[], catchBfsBlocks: BasicBlock[], + catchTailBlocks: BasicBlock[], finallyBlockBuilder: BlockBuilder, + blockBuilderAfterFinally: BlockBuilder, basicBlockSet: Set, + blockBuilderToCfgBlock: Map): Trap[] | null { + if (catchBfsBlocks.length === 0) { + logger.error(`catch block expected.`); + return null; + } + if (!blockBuilderToCfgBlock.has(blockBuilderAfterFinally)) { + logger.error(`can't find basicBlock corresponding to the blockBuilder.`); + return null; + } + let blockAfterFinally: BasicBlock = blockBuilderToCfgBlock.get(blockBuilderAfterFinally)!; + if (!blockBuilderToCfgBlock.has(finallyBlockBuilder)) { + logger.error(`can't find basicBlock corresponding to the blockBuilder.`); + return null; + } + const finallyBlock = blockBuilderToCfgBlock.get(finallyBlockBuilder)!; + let dummyFinallyIdxInPredecessors = -1; + for (let i = 0; i < blockAfterFinally.getPredecessors().length; i++) { + if (blockAfterFinally.getPredecessors()[i] === finallyBlock) { + dummyFinallyIdxInPredecessors = i; + break; + } + } + if (dummyFinallyIdxInPredecessors === -1) { + return null; + } + blockAfterFinally.getPredecessors().splice(dummyFinallyIdxInPredecessors, 1); + for (const tryTailBlock of tryTailBlocks) { + tryTailBlock.setSuccessorBlock(0, blockAfterFinally); + blockAfterFinally.addPredecessorBlock(tryTailBlock); + } + basicBlockSet.delete(finallyBlock); + + for (const catchTailBlock of catchTailBlocks) { + catchTailBlock.addSuccessorBlock(blockAfterFinally); + blockAfterFinally.addPredecessorBlock(catchTailBlock); + } + for (const tryTailBlock of tryTailBlocks) { + tryTailBlock.addExceptionalSuccessorBlock(catchBfsBlocks[0]); + } + return [new Trap(tryBfsBlocks, catchBfsBlocks)]; + } + + private buildTrapsIfFinallyExist(tryBfsBlocks: BasicBlock[], tryTailBlocks: BasicBlock[], + catchBfsBlocks: BasicBlock[], catchTailBlocks: BasicBlock[], + finallyBlockBuilder: BlockBuilder, blockBuilderAfterFinally: BlockBuilder, + basicBlockSet: Set, arkIRTransformer: ArkIRTransformer, + blockBuilderToCfgBlock: Map): Trap[] { + const { bfsBlocks: finallyBfsBlocks, tailBlocks: finallyTailBlocks } = this.getAllBlocksBFS( + blockBuilderToCfgBlock, + finallyBlockBuilder, blockBuilderAfterFinally); + const copyFinallyBfsBlocks = this.copyFinallyBlocks(finallyBfsBlocks, finallyTailBlocks, basicBlockSet, + arkIRTransformer, blockBuilderToCfgBlock); + const traps: Trap[] = []; + if (catchBfsBlocks.length !== 0) { + for (const catchTailBlock of catchTailBlocks) { + catchTailBlock.addSuccessorBlock(finallyBfsBlocks[0]); + finallyBfsBlocks[0].addPredecessorBlock(catchTailBlock); + } + // try -> catch trap + for (const tryTailBlock of tryTailBlocks) { + tryTailBlock.addExceptionalSuccessorBlock(catchBfsBlocks[0]); + } + traps.push(new Trap(tryBfsBlocks, catchBfsBlocks)); + // catch -> finally trap + for (const catchTailBlock of catchTailBlocks) { + catchTailBlock.addExceptionalSuccessorBlock(copyFinallyBfsBlocks[0]); + } + traps.push(new Trap(catchBfsBlocks, copyFinallyBfsBlocks)); + } else { + // try -> finally trap + for (const tryTailBlock of tryTailBlocks) { + tryTailBlock.addExceptionalSuccessorBlock(copyFinallyBfsBlocks[0]); + } + traps.push(new Trap(tryBfsBlocks, copyFinallyBfsBlocks)); + } + return traps; + } + + private getAllBlocksBFS(blockBuilderToCfgBlock: Map, startBlockBuilder: BlockBuilder, + endBlockBuilder?: BlockBuilder): { bfsBlocks: BasicBlock[], tailBlocks: BasicBlock[] } { + const bfsBlocks: BasicBlock[] = []; + const tailBlocks: BasicBlock[] = []; + const queue: BlockBuilder[] = []; + const visitedBlockBuilders = new Set(); + queue.push(startBlockBuilder); + while (queue.length !== 0) { + const currBlockBuilder = queue.splice(0, 1)[0]; + if (visitedBlockBuilders.has(currBlockBuilder)) { + continue; + } + visitedBlockBuilders.add(currBlockBuilder); + if (!blockBuilderToCfgBlock.has(currBlockBuilder)) { + logger.error(`can't find basicBlock corresponding to the blockBuilder.`); + continue; + } + const currBlock = blockBuilderToCfgBlock.get(currBlockBuilder)!; + bfsBlocks.push(currBlock); + + const childList = currBlockBuilder.nexts; + if (childList.length === 0 || (childList.length !== 0 && (childList[0] === endBlockBuilder))) { + if (childList[0] === endBlockBuilder) { + tailBlocks.push(currBlock); + continue; + } + } + if (childList.length !== 0) { + for (const child of childList) { + queue.push(child); + } + } + } + return { bfsBlocks, tailBlocks }; + } + + private copyFinallyBlocks(finallyBfsBlocks: BasicBlock[], finallyTailBlocks: BasicBlock[], + basicBlockSet: Set, arkIRTransformer: ArkIRTransformer, + blockBuilderToCfgBlock: Map): BasicBlock[] { + const copyFinallyBfsBlocks = this.copyBlocks(finallyBfsBlocks); + const caughtExceptionRef = new ArkCaughtExceptionRef(UnknownType.getInstance()); + const { + value: exceptionValue, + stmts: exceptionAssignStmts, + } = arkIRTransformer.generateAssignStmtForValue(caughtExceptionRef, [FullPosition.DEFAULT]); + copyFinallyBfsBlocks[0].addHead(exceptionAssignStmts); + const finallyPredecessorsCnt = copyFinallyBfsBlocks[0].getPredecessors().length; + copyFinallyBfsBlocks[0].getPredecessors().splice(0, finallyPredecessorsCnt); + const throwStmt = new ArkThrowStmt(exceptionValue); + let copyFinallyTailBlocks = copyFinallyBfsBlocks.splice( + copyFinallyBfsBlocks.length - finallyTailBlocks.length, finallyTailBlocks.length); + copyFinallyTailBlocks.forEach((copyFinallyTailBlock: BasicBlock) => { + const successorsCnt = copyFinallyTailBlock.getSuccessors().length; + copyFinallyTailBlock.getSuccessors().splice(0, successorsCnt); + }); + if (copyFinallyTailBlocks.length > 1) { + const newCopyFinallyTailBlock = new BasicBlock(); + copyFinallyTailBlocks.forEach((copyFinallyTailBlock: BasicBlock) => { + copyFinallyTailBlock.addSuccessorBlock(newCopyFinallyTailBlock); + newCopyFinallyTailBlock.addPredecessorBlock(copyFinallyTailBlock); + }); + copyFinallyTailBlocks = [newCopyFinallyTailBlock]; + } + copyFinallyTailBlocks[0]?.addStmt(throwStmt); + copyFinallyBfsBlocks.push(...copyFinallyTailBlocks); + copyFinallyBfsBlocks.forEach((copyFinallyBfsBlock: BasicBlock) => { + basicBlockSet.add(copyFinallyBfsBlock); + }); + return copyFinallyBfsBlocks; + } + + private copyBlocks(sourceBlocks: BasicBlock[]): BasicBlock[] { + const sourceToTarget = new Map(); + const targetBlocks: BasicBlock[] = []; + for (const sourceBlock of sourceBlocks) { + const targetBlock = new BasicBlock(); + for (const stmt of sourceBlock.getStmts()) { + targetBlock.addStmt(this.copyStmt(stmt)!); + } + sourceToTarget.set(sourceBlock, targetBlock); + targetBlocks.push(targetBlock); + } + for (const sourceBlock of sourceBlocks) { + const targetBlock = sourceToTarget.get(sourceBlock)!; + for (const predecessor of sourceBlock.getPredecessors()) { + const targetPredecessor = sourceToTarget.get(predecessor)!; + targetBlock.addPredecessorBlock(targetPredecessor); + } + for (const successor of sourceBlock.getSuccessors()) { + const targetSuccessor = sourceToTarget.get(successor)!; + targetBlock.addSuccessorBlock(targetSuccessor); + } + } + return targetBlocks; + } + + private copyStmt(sourceStmt: Stmt): Stmt | null { + if (sourceStmt instanceof ArkAssignStmt) { + return new ArkAssignStmt(sourceStmt.getLeftOp(), sourceStmt.getRightOp()); + } else if (sourceStmt instanceof ArkInvokeStmt) { + return new ArkInvokeStmt(sourceStmt.getInvokeExpr()); + } else if (sourceStmt instanceof ArkIfStmt) { + return new ArkIfStmt(sourceStmt.getConditionExpr()); + } else if (sourceStmt instanceof ArkReturnStmt) { + return new ArkReturnStmt(sourceStmt.getOp()); + } else if (sourceStmt instanceof ArkReturnVoidStmt) { + return new ArkReturnVoidStmt(); + } else if (sourceStmt instanceof ArkThrowStmt) { + return new ArkThrowStmt(sourceStmt.getOp()); + } + return null; + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/graph/builder/ViewTreeBuilder.ts b/ets2panda/linter/arkanalyzer/src/core/graph/builder/ViewTreeBuilder.ts new file mode 100644 index 0000000000..a0c37d94bb --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/graph/builder/ViewTreeBuilder.ts @@ -0,0 +1,1285 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Constant } from '../../base/Constant'; +import { Decorator } from '../../base/Decorator'; +import { + AbstractInvokeExpr, + ArkConditionExpr, + ArkInstanceInvokeExpr, + ArkNewExpr, + ArkNormalBinopExpr, + ArkPtrInvokeExpr, + ArkStaticInvokeExpr, +} from '../../base/Expr'; +import { Local } from '../../base/Local'; +import { ArkArrayRef, ArkInstanceFieldRef, ArkThisRef } from '../../base/Ref'; +import { ArkAssignStmt, ArkInvokeStmt, Stmt } from '../../base/Stmt'; +import { ClassType, FunctionType, Type } from '../../base/Type'; +import { Value } from '../../base/Value'; +import { + BUILDER_DECORATOR, + BUILDER_PARAM_DECORATOR, + COMPONENT_BRANCH_FUNCTION, + COMPONENT_CREATE_FUNCTION, + COMPONENT_CUSTOMVIEW, + COMPONENT_FOR_EACH, + COMPONENT_IF, + COMPONENT_IF_BRANCH, + COMPONENT_LAZY_FOR_EACH, + COMPONENT_POP_FUNCTION, + COMPONENT_REPEAT, + isEtsContainerComponent, + SPECIAL_CONTAINER_COMPONENT, +} from '../../common/EtsConst'; +import { ArkClass, ClassCategory } from '../../model/ArkClass'; +import { ArkField } from '../../model/ArkField'; +import { ArkMethod } from '../../model/ArkMethod'; +import { ClassSignature, MethodSignature } from '../../model/ArkSignature'; +import { Cfg } from '../Cfg'; +import Logger, { LOG_MODULE_TYPE } from '../../../utils/logger'; +import { ViewTree, ViewTreeNode } from '../ViewTree'; +import { ModelUtils } from '../../common/ModelUtils'; +import { Scene } from '../../../Scene'; +import { TEMP_LOCAL_PREFIX } from '../../common/Const'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'ViewTreeBuilder'); +const COMPONENT_CREATE_FUNCTIONS: Set = new Set([COMPONENT_CREATE_FUNCTION, COMPONENT_BRANCH_FUNCTION]); + +function backtraceLocalInitValue(value: Local): Local | Value { + let stmt = value.getDeclaringStmt(); + if (stmt instanceof ArkAssignStmt) { + let rightOp = stmt.getRightOp(); + if (rightOp instanceof Local) { + return backtraceLocalInitValue(rightOp); + } else if (rightOp instanceof ArkInstanceFieldRef && rightOp.getBase().getName().startsWith(TEMP_LOCAL_PREFIX)) { + return backtraceLocalInitValue(rightOp.getBase()); + } else if (rightOp instanceof ArkArrayRef) { + return backtraceLocalInitValue(rightOp.getBase()); + } + return rightOp; + } + return value; +} + +type ObjectLiteralMap = Map; + +function parseObjectLiteral(objectLiteralCls: ArkClass | null, scene: Scene): ObjectLiteralMap { + let map: ObjectLiteralMap = new Map(); + if (objectLiteralCls?.getCategory() !== ClassCategory.OBJECT) { + return map; + } + objectLiteralCls?.getFields().forEach((field) => { + let stmts = field.getInitializer(); + if (stmts.length === 0) { + return; + } + + let assignStmt = stmts[stmts.length - 1]; + if (!(assignStmt instanceof ArkAssignStmt)) { + return; + } + + let value = assignStmt.getRightOp(); + if (value instanceof Local) { + value = backtraceLocalInitValue(value); + } + + map.set(field, value); + if (value instanceof ArkNewExpr) { + let subCls = ModelUtils.getArkClassInBuild(scene, value.getClassType()); + let childMap = parseObjectLiteral(subCls, scene); + if (childMap) { + map.set(field, childMap); + } + } + }); + + return map; +} + +class StateValuesUtils { + private declaringArkClass: ArkClass; + + constructor(declaringArkClass: ArkClass) { + this.declaringArkClass = declaringArkClass; + } + + public static getInstance(declaringArkClass: ArkClass): StateValuesUtils { + return new StateValuesUtils(declaringArkClass); + } + + public parseStmtUsesStateValues( + stmt: Stmt, + uses: Set = new Set(), + wholeMethod: boolean = false, + visitor: Set = new Set() + ): Set { + if (visitor.has(stmt)) { + return uses; + } + visitor.add(stmt); + let values = stmt.getUses(); + if (stmt instanceof ArkAssignStmt) { + values.push(stmt.getLeftOp()); + } + + for (const v of values) { + this.parseValueUsesStateValues(v, uses, wholeMethod, visitor); + } + return uses; + } + + private objectLiteralMapUsedStateValues(uses: Set, map: ObjectLiteralMap): void { + for (const [_, value] of map) { + if (value instanceof ArkInstanceFieldRef) { + let srcField = this.declaringArkClass.getFieldWithName(value.getFieldName()); + let decorators = srcField?.getStateDecorators(); + if (srcField && decorators && decorators.length > 0) { + uses.add(srcField); + } + } else if (value instanceof Map) { + this.objectLiteralMapUsedStateValues(uses, value); + } else if (value instanceof ArkNormalBinopExpr || value instanceof ArkConditionExpr) { + this.parseValueUsesStateValues(value.getOp1(), uses); + this.parseValueUsesStateValues(value.getOp2(), uses); + } + } + } + + public parseObjectUsedStateValues(type: Type, uses: Set = new Set()): Set { + if (!(type instanceof ClassType)) { + return uses; + } + let cls = ModelUtils.getArkClassInBuild(this.declaringArkClass.getDeclaringArkFile().getScene(), type); + let map = parseObjectLiteral(cls, this.declaringArkClass.getDeclaringArkFile().getScene()); + this.objectLiteralMapUsedStateValues(uses, map); + return uses; + } + + private parseMethodUsesStateValues( + methodSignature: MethodSignature, + uses: Set, + visitor: Set = new Set() + ): void { + if (visitor.has(methodSignature)) { + return; + } + visitor.add(methodSignature); + let method = this.declaringArkClass.getDeclaringArkFile().getScene().getMethod(methodSignature); + if (!method) { + return; + } + let stmts = method.getCfg()?.getStmts(); + if (!stmts) { + return; + } + for (const stmt of stmts) { + this.parseStmtUsesStateValues(stmt, uses, true, visitor); + } + } + + private parseValueUsesStateValues( + v: Value, + uses: Set = new Set(), + wholeMethod: boolean = false, + visitor: Set = new Set() + ): Set { + if (v instanceof ArkInstanceFieldRef) { + let field = this.declaringArkClass.getField(v.getFieldSignature()); + let decorators = field?.getStateDecorators(); + if (field && decorators && decorators.length > 0) { + uses.add(field); + } + } else if (v instanceof ArkInstanceInvokeExpr) { + this.parseMethodUsesStateValues(v.getMethodSignature(), uses, visitor); + } else if (v instanceof Local) { + if (v.getName() === 'this') { + return uses; + } + let type = v.getType(); + if (type instanceof FunctionType) { + this.parseMethodUsesStateValues(type.getMethodSignature(), uses, visitor); + return uses; + } + this.parseObjectUsedStateValues(type, uses); + let declaringStmt = v.getDeclaringStmt(); + if (!wholeMethod && declaringStmt) { + this.parseStmtUsesStateValues(declaringStmt, uses, wholeMethod, visitor); + } + } + + return uses; + } +} + +enum ViewTreeNodeType { + SystemComponent, + CustomComponent, + Builder, + BuilderParam, +} + +class ViewTreeNodeImpl implements ViewTreeNode { + name: string; + stmts: Map; + attributes: Map; + stateValues: Set; + parent: ViewTreeNode | null; + children: ViewTreeNodeImpl[]; + classSignature?: MethodSignature | ClassSignature | undefined; + signature?: MethodSignature | ClassSignature | undefined; + stateValuesTransfer?: Map | undefined; + builderParam?: ArkField | undefined; + builder?: MethodSignature | undefined; + private type: ViewTreeNodeType; + + constructor(name: string) { + this.name = name; + this.attributes = new Map(); + this.stmts = this.attributes; + this.stateValues = new Set(); + this.parent = null; + this.children = []; + this.type = ViewTreeNodeType.SystemComponent; + } + + /** + * Whether the node type is Builder. + * @returns true: node is Builder, false others. + */ + public isBuilder(): boolean { + return this.type === ViewTreeNodeType.Builder; + } + + /** + * @internal + */ + public isBuilderParam(): boolean { + return this.type === ViewTreeNodeType.BuilderParam; + } + + /** + * Whether the node type is custom component. + * @returns true: node is custom component, false others. + */ + public isCustomComponent(): boolean { + return this.type === ViewTreeNodeType.CustomComponent; + } + + /** + * walk node and node's children + * @param selector Node selector function, return true skipping the follow-up nodes. + * @returns + * - true: There are nodes that meet the selector. + * - false: does not exist. + */ + public walk(selector: (item: ViewTreeNode) => boolean, visitor: Set = new Set()): boolean { + if (visitor.has(this)) { + return false; + } + + let ret: boolean = selector(this); + visitor.add(this); + + for (const child of this.children) { + ret = ret || child.walk(selector, visitor); + if (ret) { + break; + } + } + return ret; + } + + public static createCustomComponent(): ViewTreeNodeImpl { + let instance = new ViewTreeNodeImpl(COMPONENT_CUSTOMVIEW); + instance.type = ViewTreeNodeType.CustomComponent; + return instance; + } + + public static createBuilderNode(): ViewTreeNodeImpl { + let instance = new ViewTreeNodeImpl(BUILDER_DECORATOR); + instance.type = ViewTreeNodeType.Builder; + return instance; + } + + public static createBuilderParamNode(): ViewTreeNodeImpl { + let instance = new ViewTreeNodeImpl(BUILDER_PARAM_DECORATOR); + instance.type = ViewTreeNodeType.BuilderParam; + return instance; + } + + public changeBuilderParam2BuilderNode(builder: ArkMethod): void { + this.name = BUILDER_DECORATOR; + this.type = ViewTreeNodeType.Builder; + this.signature = builder.getSignature(); + this.classSignature = this.signature; + const root = builder.getViewTree()?.getRoot(); + if (root) { + for (let child of root.children) { + this.children.push(child as ViewTreeNodeImpl); + } + } else { + logger.error( + `ViewTree->changeBuilderParam2BuilderNode ${builder.getSignature().toString()} @Builder viewtree fail.` + ); + } + } + + public hasBuilderParam(): boolean { + return this.walk((item) => { + return (item as ViewTreeNodeImpl).isBuilderParam(); + }); + } + + public clone(parent: ViewTreeNodeImpl, map: Map = new Map()): ViewTreeNodeImpl { + let newNode = new ViewTreeNodeImpl(this.name); + newNode.attributes = this.attributes; + newNode.stmts = newNode.attributes; + newNode.stateValues = this.stateValues; + newNode.parent = parent; + newNode.type = this.type; + newNode.signature = this.signature; + newNode.classSignature = newNode.signature; + newNode.builderParam = this.builderParam; + newNode.builder = this.builder; + map.set(this, newNode); + + for (const child of this.children) { + if (map.has(child)) { + newNode.children.push(map.get(child)!); + } else { + newNode.children.push(child.clone(newNode, map)); + } + } + + return newNode; + } + + public addStmt(tree: ViewTreeImpl, stmt: Stmt): void { + this.parseAttributes(stmt); + if (this.name !== COMPONENT_FOR_EACH && this.name !== COMPONENT_LAZY_FOR_EACH) { + this.parseStateValues(tree, stmt); + } + } + + private parseAttributes(stmt: Stmt): void { + let expr: AbstractInvokeExpr | undefined; + if (stmt instanceof ArkAssignStmt) { + let op = stmt.getRightOp(); + if (op instanceof ArkInstanceInvokeExpr) { + expr = op; + } else if (op instanceof ArkStaticInvokeExpr) { + expr = op; + } + } else if (stmt instanceof ArkInvokeStmt) { + let invoke = stmt.getInvokeExpr(); + if (invoke instanceof ArkInstanceInvokeExpr) { + expr = invoke; + } else if (invoke instanceof ArkStaticInvokeExpr) { + expr = invoke; + } + } + if (expr) { + let key = expr.getMethodSignature().getMethodSubSignature().getMethodName(); + let relationValues: (Constant | ArkInstanceFieldRef | MethodSignature)[] = []; + for (const arg of expr.getArgs()) { + if (arg instanceof Local) { + this.getBindValues(arg, relationValues); + } else if (arg instanceof Constant) { + relationValues.push(arg); + } + } + this.attributes.set(key, [stmt, relationValues]); + } + } + + private getBindValues( + local: Local, + relationValues: (Constant | ArkInstanceFieldRef | MethodSignature)[], + visitor: Set = new Set() + ): void { + if (visitor.has(local)) { + return; + } + visitor.add(local); + const stmt = local.getDeclaringStmt(); + if (!stmt) { + let type = local.getType(); + if (type instanceof FunctionType) { + relationValues.push(type.getMethodSignature()); + } + return; + } + for (const v of stmt.getUses()) { + if (v instanceof Constant) { + relationValues.push(v); + } else if (v instanceof ArkInstanceFieldRef) { + relationValues.push(v); + } else if (v instanceof Local) { + this.getBindValues(v, relationValues, visitor); + } + } + } + + public parseStateValues(tree: ViewTreeImpl, stmt: Stmt): void { + let stateValues: Set = StateValuesUtils.getInstance( + tree.getDeclaringArkClass() + ).parseStmtUsesStateValues(stmt); + stateValues.forEach((field) => { + this.stateValues.add(field); + tree.addStateValue(field, this); + }, this); + } +} + +class TreeNodeStack { + protected root: ViewTreeNodeImpl | null = null; + protected stack: ViewTreeNodeImpl[]; + + constructor() { + this.stack = []; + } + + /** + * @internal + */ + public push(node: ViewTreeNodeImpl) { + let parent = this.getParent(); + node.parent = parent; + this.stack.push(node); + if (parent === null || parent === undefined) { + this.root = node; + } else { + parent.children.push(node); + } + } + + /** + * @internal + */ + public pop() { + this.stack.pop(); + } + + /** + * @internal + */ + public top(): ViewTreeNodeImpl | null { + return this.isEmpty() ? null : this.stack[this.stack.length - 1]; + } + + /** + * @internal + */ + public isEmpty(): boolean { + return this.stack.length === 0; + } + + /** + * @internal + */ + public popAutomicComponent(name: string): void { + if (this.isEmpty()) { + return; + } + + let node = this.stack[this.stack.length - 1]; + if (name !== node.name && !this.isContainer(node.name)) { + this.stack.pop(); + } + } + + /** + * @internal + */ + public popComponentExpect(name: string): TreeNodeStack { + for (let i = this.stack.length - 1; i >= 0; i--) { + if (this.stack[i].name !== name) { + this.stack.pop(); + } else { + break; + } + } + return this; + } + + private getParent(): ViewTreeNodeImpl | null { + if (this.stack.length === 0) { + return null; + } + + let node = this.stack[this.stack.length - 1]; + if (!this.isContainer(node.name)) { + this.stack.pop(); + } + return this.stack[this.stack.length - 1]; + } + + protected isContainer(name: string): boolean { + return isEtsContainerComponent(name) || SPECIAL_CONTAINER_COMPONENT.has(name) || name === BUILDER_DECORATOR; + } +} + +export class ViewTreeImpl extends TreeNodeStack implements ViewTree { + private render: ArkMethod; + private buildViewStatus: boolean; + private stateValues: Map>; + private fieldTypes: Map; + + /** + * @internal + */ + constructor(render: ArkMethod) { + super(); + this.render = render; + this.stateValues = new Map(); + this.fieldTypes = new Map(); + this.buildViewStatus = false; + } + + /** + * ViewTree root node. + * @returns root node + */ + public getRoot(): ViewTreeNode | null { + this.buildViewTree(); + return this.root; + } + + /** + * Map of the component controlled by the state variable + * @returns + */ + public getStateValues(): Map> { + this.buildViewTree(); + return this.stateValues; + } + + /** + * @deprecated Use {@link getStateValues} instead. + */ + public isClassField(name: string): boolean { + return this.fieldTypes.has(name); + } + + /** + * @deprecated Use {@link getStateValues} instead. + */ + public getClassFieldType(name: string): Decorator | Type | undefined { + return this.fieldTypes.get(name); + } + + /** + * @internal + */ + private buildViewTree(): void { + if (!this.render || this.isInitialized()) { + return; + } + this.buildViewStatus = true; + this.loadClasssFieldTypes(); + + if (this.render.hasBuilderDecorator()) { + let node = ViewTreeNodeImpl.createBuilderNode(); + node.signature = this.render.getSignature(); + node.classSignature = node.signature; + this.push(node); + } + + if (this.render.getCfg()) { + this.buildViewTreeFromCfg(this.render.getCfg() as Cfg); + } + } + + /** + * @internal + */ + private isInitialized(): boolean { + return this.root != null || this.buildViewStatus; + } + + /** + * @internal + */ + public addStateValue(field: ArkField, node: ViewTreeNode) { + if (!this.stateValues.has(field)) { + this.stateValues.set(field, new Set()); + } + let sets = this.stateValues.get(field); + sets?.add(node); + } + + /** + * @internal + */ + private isCreateFunc(name: string): boolean { + return COMPONENT_CREATE_FUNCTIONS.has(name); + } + + private loadClasssFieldTypes(): void { + for (const field of this.render.getDeclaringArkClass().getFields()) { + let decorators = field.getStateDecorators(); + if (decorators.length > 0) { + if (decorators.length === 1) { + this.fieldTypes.set(field.getName(), decorators[0]); + } else { + this.fieldTypes.set(field.getName(), decorators[0]); + } + } else { + this.fieldTypes.set(field.getName(), field.getSignature().getType()); + } + } + } + + /** + * @internal + */ + public getDeclaringArkClass(): ArkClass { + return this.render.getDeclaringArkClass(); + } + + /** + * @internal + */ + private findMethod(methodSignature: MethodSignature): ArkMethod | null { + let method = this.render.getDeclaringArkFile().getScene().getMethod(methodSignature); + if (method) { + return method; + } + + // class + method = this.getDeclaringArkClass().getMethod(methodSignature); + if (method) { + return method; + } + + return this.findMethodWithName(methodSignature.getMethodSubSignature().getMethodName()); + } + + /** + * @internal + */ + private findMethodWithName(name: string): ArkMethod | null { + let method = this.getDeclaringArkClass().getMethodWithName(name); + if (method) { + return method; + } + + // namespace + this.getDeclaringArkClass() + .getDeclaringArkNamespace() + ?.getAllMethodsUnderThisNamespace() + .forEach((value) => { + if (value.getName() === name) { + method = value; + } + }); + if (method) { + return method; + } + + this.getDeclaringArkClass() + .getDeclaringArkFile() + .getAllNamespacesUnderThisFile() + .forEach((namespace) => { + namespace.getAllMethodsUnderThisNamespace().forEach((value) => { + if (value.getName() === name) { + method = value; + } + }); + }); + return method; + } + + /** + * @internal + */ + private findClass(classSignature: ClassSignature): ArkClass | null { + return ModelUtils.getClass(this.render, classSignature); + } + + private findBuilderMethod(value: Value): ArkMethod | undefined | null { + let method: ArkMethod | undefined | null; + if (value instanceof ArkInstanceFieldRef) { + method = this.findMethodWithName(value.getFieldName()); + } else if (value instanceof ArkStaticInvokeExpr) { + method = this.findMethod(value.getMethodSignature()); + } else if (value instanceof Local && value.getType() instanceof FunctionType) { + method = this.findMethod((value.getType() as FunctionType).getMethodSignature()); + } else if (value instanceof Local) { + method = this.findMethodWithName(value.getName()); + } + if (method && !method.hasBuilderDecorator()) { + method = this.findMethodInvokeBuilderMethod(method); + } + + return method; + } + + /** + * @internal + */ + private addBuilderNode(method: ArkMethod): ViewTreeNodeImpl { + let builderViewTree = method.getViewTree(); + if (!builderViewTree || !builderViewTree.getRoot()) { + logger.error(`ViewTree->addBuilderNode ${method.getSignature().toString()} build viewtree fail.`); + // add empty node + let node = ViewTreeNodeImpl.createBuilderNode(); + node.signature = method.getSignature(); + node.classSignature = node.signature; + this.push(node); + this.pop(); + return node; + } + + let root = builderViewTree.getRoot() as ViewTreeNodeImpl; + this.push(root); + if (method.getDeclaringArkClass() === this.render.getDeclaringArkClass()) { + for (const [field, nodes] of builderViewTree.getStateValues()) { + for (const node of nodes) { + this.addStateValue(field, node); + } + } + } + this.pop(); + return root; + } + + /** + * @internal + */ + private addCustomComponentNode( + cls: ArkClass, + arg: Value | undefined, + builder: ArkMethod | undefined + ): ViewTreeNodeImpl { + let node = ViewTreeNodeImpl.createCustomComponent(); + node.signature = cls.getSignature(); + node.classSignature = node.signature; + node.stateValuesTransfer = this.parseObjectLiteralExpr(cls, arg, builder); + if (arg instanceof Local && arg.getType()) { + let stateValues = StateValuesUtils.getInstance(this.getDeclaringArkClass()).parseObjectUsedStateValues( + arg.getType() + ); + stateValues.forEach((field) => { + node.stateValues.add(field); + this.addStateValue(field, node); + }); + } + this.push(node); + let componentViewTree = cls.getViewTree(); + if (!componentViewTree || !componentViewTree.getRoot()) { + logger.error(`ViewTree->addCustomComponentNode ${cls.getSignature().toString()} build viewtree fail.`); + return node; + } + let root = componentViewTree.getRoot() as ViewTreeNodeImpl; + if (root.hasBuilderParam()) { + root = this.cloneBuilderParamNode(node, root); + } + node.children.push(root); + + return node; + } + + private cloneBuilderParamNode(node: ViewTreeNodeImpl, root: ViewTreeNodeImpl): ViewTreeNodeImpl { + root = root.clone(node); + if (node.stateValuesTransfer) { + root.walk((item) => { + let child = item as ViewTreeNodeImpl; + if (!child.isBuilderParam() || !child.builderParam) { + return false; + } + let method = node.stateValuesTransfer?.get(child.builderParam) as ArkMethod; + if (method) { + child.changeBuilderParam2BuilderNode(method); + } + + return false; + }); + } + return root; + } + + /** + * @internal + */ + private addBuilderParamNode(field: ArkField): ViewTreeNodeImpl { + let node = ViewTreeNodeImpl.createBuilderParamNode(); + node.builderParam = field; + this.push(node); + this.pop(); + + return node; + } + + /** + * @internal + */ + private addSystemComponentNode(name: string): ViewTreeNodeImpl { + let node = new ViewTreeNodeImpl(name); + this.push(node); + + return node; + } + + private findMethodInvokeBuilderMethod(method: ArkMethod): ArkMethod | undefined { + let stmts = method.getCfg()?.getStmts(); + if (!stmts) { + return; + } + for (const stmt of stmts) { + let expr: AbstractInvokeExpr | undefined; + + if (stmt instanceof ArkInvokeStmt) { + expr = stmt.getInvokeExpr(); + } else if (stmt instanceof ArkAssignStmt) { + let rightOp = stmt.getRightOp(); + if (rightOp instanceof ArkInstanceInvokeExpr || rightOp instanceof ArkStaticInvokeExpr) { + expr = rightOp; + } + } + + if (expr === undefined) { + continue; + } + + let method = this.findMethod(expr.getMethodSignature()); + if (method?.hasBuilderDecorator()) { + return method; + } + } + } + + private parseFieldInObjectLiteral(field: ArkField, cls: ArkClass, transferMap: Map): void { + let dstField = cls.getFieldWithName(field.getName()); + if (dstField?.getStateDecorators().length === 0 && !dstField?.hasBuilderParamDecorator()) { + return; + } + + let stmts = field.getInitializer(); + if (stmts.length === 0) { + return; + } + + let assignStmt = stmts[stmts.length - 1]; + if (!(assignStmt instanceof ArkAssignStmt)) { + return; + } + + let value = assignStmt.getRightOp(); + if (value instanceof Local) { + value = backtraceLocalInitValue(value); + } + if (dstField?.hasBuilderParamDecorator()) { + let method = this.findBuilderMethod(value); + if (method) { + transferMap.set(dstField, method); + } + } else { + let srcField: ArkField | undefined | null; + if (value instanceof ArkInstanceFieldRef) { + srcField = this.getDeclaringArkClass().getFieldWithName(value.getFieldName()); + } + if (srcField && dstField) { + transferMap.set(dstField, srcField); + } + } + } + + private parseObjectLiteralExpr( + cls: ArkClass, + object: Value | undefined, + builder: ArkMethod | undefined + ): Map | undefined { + let transferMap: Map = new Map(); + if (object instanceof Local && object.getType() instanceof ClassType) { + let anonymousSig = (object.getType() as ClassType).getClassSignature(); + let anonymous = this.findClass(anonymousSig); + anonymous?.getFields().forEach((field) => { + this.parseFieldInObjectLiteral(field, cls, transferMap); + }); + } + // If the builder exists, there will be a unique BuilderParam + if (builder) { + cls.getFields().forEach((value) => { + if (value.hasBuilderParamDecorator()) { + transferMap.set(value, builder); + } + }); + } + + if (transferMap.size === 0) { + return; + } + return transferMap; + } + + private viewComponentCreationParser( + name: string, + stmt: Stmt, + expr: AbstractInvokeExpr + ): ViewTreeNodeImpl | undefined { + let temp = expr.getArg(0) as Local; + let arg: Value | undefined; + temp.getUsedStmts().forEach((value) => { + if (value instanceof ArkInvokeStmt) { + let invokerExpr = value.getInvokeExpr(); + let methodName = invokerExpr.getMethodSignature().getMethodSubSignature().getMethodName(); + if (methodName === 'constructor') { + arg = invokerExpr.getArg(0); + } + } + }); + + let builderMethod: ArkMethod | undefined; + let builder = expr.getArg(1) as Local; + if (builder) { + let method = this.findMethod((builder.getType() as FunctionType).getMethodSignature()); + if (!method?.hasBuilderDecorator()) { + method?.addDecorator(new Decorator(BUILDER_DECORATOR)); + } + if (!method?.hasViewTree()) { + method?.setViewTree(new ViewTreeImpl(method)); + } + if (method) { + builderMethod = method; + } + } + + let initValue = backtraceLocalInitValue(temp); + if (!(initValue instanceof ArkNewExpr)) { + return undefined; + } + + let clsSignature = (initValue.getType() as ClassType).getClassSignature(); + if (clsSignature) { + let cls = this.findClass(clsSignature); + if (cls && cls.hasComponentDecorator()) { + return this.addCustomComponentNode(cls, arg, builderMethod); + } else { + logger.error( + `ViewTree->viewComponentCreationParser not found class ${clsSignature.toString()}. ${stmt.toString()}` + ); + } + } + return undefined; + } + + private waterFlowCreationParser(name: string, stmt: Stmt, expr: AbstractInvokeExpr): ViewTreeNodeImpl { + let node = this.addSystemComponentNode(name); + let object = expr.getArg(0); + if (object instanceof Local && object.getType() instanceof ClassType) { + let anonymousSig = (object.getType() as ClassType).getClassSignature(); + let anonymous = this.findClass(anonymousSig); + let footer = anonymous?.getFieldWithName('footer'); + if (!footer) { + return node; + } + let stmts = footer.getInitializer(); + let assignStmt = stmts[stmts.length - 1]; + if (!(assignStmt instanceof ArkAssignStmt)) { + return node; + } + + let value = assignStmt.getRightOp(); + let method = this.findBuilderMethod(value); + if (method?.hasBuilderDecorator()) { + return this.addBuilderNode(method); + } + } + + return node; + } + + private forEachCreationParser(name: string, stmt: Stmt, expr: AbstractInvokeExpr): ViewTreeNodeImpl { + let node = this.addSystemComponentNode(name); + let values = expr.getArg(0) as Local; + let declaringStmt = values?.getDeclaringStmt(); + if (declaringStmt) { + let stateValues = StateValuesUtils.getInstance(this.getDeclaringArkClass()).parseStmtUsesStateValues( + declaringStmt + ); + stateValues.forEach((field) => { + node.stateValues.add(field); + this.addStateValue(field, node); + }); + } + + let type = (expr.getArg(1) as Local).getType() as FunctionType; + let method = this.findMethod(type.getMethodSignature()); + if (method && method.getCfg()) { + this.buildViewTreeFromCfg(method.getCfg() as Cfg); + } + return node; + } + + private repeatCreationParser(name: string, stmt: Stmt, expr: AbstractInvokeExpr): ViewTreeNodeImpl { + let node = this.addSystemComponentNode(name); + let arg = expr.getArg(0) as Local; + let declaringStmt = arg?.getDeclaringStmt(); + if (declaringStmt) { + let stateValues = StateValuesUtils.getInstance(this.getDeclaringArkClass()).parseStmtUsesStateValues( + declaringStmt + ); + stateValues.forEach((field) => { + node.stateValues.add(field); + this.addStateValue(field, node); + }); + } + + return node; + } + + private ifBranchCreationParser(name: string, stmt: Stmt, expr: AbstractInvokeExpr): ViewTreeNodeImpl { + this.popComponentExpect(COMPONENT_IF); + return this.addSystemComponentNode(COMPONENT_IF_BRANCH); + } + + private COMPONENT_CREATE_PARSERS: Map< + string, + (name: string, stmt: Stmt, expr: AbstractInvokeExpr) => ViewTreeNodeImpl | undefined + > = new Map([ + ['ForEach.create', this.forEachCreationParser.bind(this)], + ['LazyForEach.create', this.forEachCreationParser.bind(this)], + ['Repeat.create', this.repeatCreationParser.bind(this)], + ['View.create', this.viewComponentCreationParser.bind(this)], + ['If.branch', this.ifBranchCreationParser.bind(this)], + ['WaterFlow.create', this.waterFlowCreationParser.bind(this)], + ]); + + private componentCreateParse( + componentName: string, + methodName: string, + stmt: Stmt, + expr: ArkStaticInvokeExpr + ): ViewTreeNodeImpl | undefined { + let parserFn = this.COMPONENT_CREATE_PARSERS.get(`${componentName}.${methodName}`); + if (parserFn) { + let node = parserFn(componentName, stmt, expr); + node?.addStmt(this, stmt); + return node; + } + this.popAutomicComponent(componentName); + let node = this.addSystemComponentNode(componentName); + node.addStmt(this, stmt); + return node; + } + + private parseStaticInvokeExpr( + local2Node: Map, + stmt: Stmt, + expr: ArkStaticInvokeExpr + ): ViewTreeNodeImpl | undefined { + let methodSignature = expr.getMethodSignature(); + let method = this.findMethod(methodSignature); + if (method?.hasBuilderDecorator()) { + let node = this.addBuilderNode(method); + node.parseStateValues(this, stmt); + return node; + } + + let name = methodSignature.getDeclaringClassSignature().getClassName(); + let methodName = methodSignature.getMethodSubSignature().getMethodName(); + + if (this.isCreateFunc(methodName)) { + return this.componentCreateParse(name, methodName, stmt, expr); + } + + let currentNode = this.top(); + if (name === currentNode?.name) { + currentNode.addStmt(this, stmt); + if (methodName === COMPONENT_POP_FUNCTION) { + this.pop(); + } + return currentNode; + } else if (name === COMPONENT_IF && methodName === COMPONENT_POP_FUNCTION) { + this.popComponentExpect(COMPONENT_IF); + this.pop(); + } + return undefined; + } + + /** + * $temp4.margin({ top: 20 }); + * @param viewTree + * @param local2Node + * @param expr + */ + private parseInstanceInvokeExpr( + local2Node: Map, + stmt: Stmt, + expr: ArkInstanceInvokeExpr + ): ViewTreeNodeImpl | undefined { + let temp = expr.getBase(); + if (local2Node.has(temp)) { + let component = local2Node.get(temp); + if ( + component?.name === COMPONENT_REPEAT && + expr.getMethodSignature().getMethodSubSignature().getMethodName() === 'each' + ) { + let arg = expr.getArg(0); + let type = arg.getType(); + if (type instanceof FunctionType) { + let method = this.findMethod(type.getMethodSignature()); + this.buildViewTreeFromCfg(method?.getCfg() as Cfg); + } + this.pop(); + } else { + component?.addStmt(this, stmt); + } + + return component; + } + + let name = expr.getBase().getName(); + if (name.startsWith(TEMP_LOCAL_PREFIX)) { + let initValue = backtraceLocalInitValue(expr.getBase()); + if (initValue instanceof ArkThisRef) { + name = 'this'; + } + } + + let methodName = expr.getMethodSignature().getMethodSubSignature().getMethodName(); + let field = this.getDeclaringArkClass().getFieldWithName(methodName); + if (name === 'this' && field?.hasBuilderParamDecorator()) { + return this.addBuilderParamNode(field); + } + + let method = this.findMethod(expr.getMethodSignature()); + if (name === 'this' && method?.hasBuilderDecorator()) { + return this.addBuilderNode(method); + } + + return undefined; + } + + private parsePtrInvokeExpr( + local2Node: Map, + stmt: Stmt, + expr: ArkPtrInvokeExpr + ): ViewTreeNodeImpl | undefined { + let temp = expr.getFuncPtrLocal(); + if (temp instanceof Local && local2Node.has(temp)) { + let component = local2Node.get(temp); + if ( + component?.name === COMPONENT_REPEAT && + expr.getMethodSignature().getMethodSubSignature().getMethodName() === 'each' + ) { + let arg = expr.getArg(0); + let type = arg.getType(); + if (type instanceof FunctionType) { + let method = this.findMethod(type.getMethodSignature()); + this.buildViewTreeFromCfg(method?.getCfg() as Cfg); + } + this.pop(); + } else { + component?.addStmt(this, stmt); + } + + return component; + } else if (temp instanceof ArkInstanceFieldRef) { + let name = temp.getBase().getName(); + if (name.startsWith(TEMP_LOCAL_PREFIX)) { + let initValue = backtraceLocalInitValue(temp.getBase()); + if (initValue instanceof ArkThisRef) { + name = 'this'; + } + } + + let methodName = temp.getFieldName(); + let field = this.getDeclaringArkClass().getFieldWithName(methodName); + if (name === 'this' && field?.hasBuilderParamDecorator()) { + return this.addBuilderParamNode(field); + } + + let method = this.findMethod(expr.getMethodSignature()); + if (name === 'this' && method?.hasBuilderDecorator()) { + return this.addBuilderNode(method); + } + } + return undefined; + } + + /** + * $temp3 = View.create($temp2); + * $temp4 = View.pop(); + * $temp4.margin({ top: 20 }); + * + * $temp2 = List.create(); + * $temp5 = $temp2.width('100%'); + * $temp6 = $temp5.height('100%'); + * $temp6.backgroundColor('#FFDCDCDC'); + * @param viewTree + * @param local2Node + * @param stmt + * @returns + */ + private parseAssignStmt(local2Node: Map, stmt: ArkAssignStmt): void { + let left = stmt.getLeftOp(); + let right = stmt.getRightOp(); + + if (!(left instanceof Local)) { + return; + } + + let component: ViewTreeNodeImpl | undefined; + if (right instanceof ArkStaticInvokeExpr) { + component = this.parseStaticInvokeExpr(local2Node, stmt, right); + } else if (right instanceof ArkInstanceInvokeExpr) { + component = this.parseInstanceInvokeExpr(local2Node, stmt, right); + } else if (right instanceof ArkPtrInvokeExpr) { + component = this.parsePtrInvokeExpr(local2Node, stmt, right); + } + if (component) { + local2Node.set(left, component); + } + } + + private parseInvokeStmt(local2Node: Map, stmt: ArkInvokeStmt): void { + let expr = stmt.getInvokeExpr(); + if (expr instanceof ArkStaticInvokeExpr) { + this.parseStaticInvokeExpr(local2Node, stmt, expr); + } else if (expr instanceof ArkInstanceInvokeExpr) { + this.parseInstanceInvokeExpr(local2Node, stmt, expr); + } else if (expr instanceof ArkPtrInvokeExpr) { + this.parsePtrInvokeExpr(local2Node, stmt, expr); + } + } + + private buildViewTreeFromCfg(cfg: Cfg, local2Node: Map = new Map()): void { + if (!cfg) { + return; + } + let blocks = cfg.getBlocks(); + for (const block of blocks) { + for (const stmt of block.getStmts()) { + if (!(stmt instanceof ArkInvokeStmt || stmt instanceof ArkAssignStmt)) { + continue; + } + + if (stmt instanceof ArkAssignStmt) { + this.parseAssignStmt(local2Node, stmt); + } else if (stmt instanceof ArkInvokeStmt) { + this.parseInvokeStmt(local2Node, stmt); + } + } + } + } +} + +export function buildViewTree(render: ArkMethod): ViewTree { + return new ViewTreeImpl(render); +} diff --git a/ets2panda/linter/arkanalyzer/src/core/model/ArkBaseModel.ts b/ets2panda/linter/arkanalyzer/src/core/model/ArkBaseModel.ts new file mode 100644 index 0000000000..9d363cdcb4 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/model/ArkBaseModel.ts @@ -0,0 +1,283 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import ts from 'ohos-typescript'; +import { Decorator } from '../base/Decorator'; +import { COMPONENT_DECORATOR, ENTRY_DECORATOR, BUILDER_PARAM_DECORATOR, BUILDER_DECORATOR } from '../common/EtsConst'; +import { ArkError, ArkErrorCode } from '../common/ArkError'; +import Logger, { LOG_MODULE_TYPE } from '../../utils/logger'; +import { ArkMetadata, ArkMetadataKind, ArkMetadataType } from './ArkMetadata'; +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'ArkBaseModel'); + +const COMPONENT_MEMBER_DECORATORS: Set = new Set([ + 'State', + 'Prop', + 'Link', + 'StorageProp', + 'StorageLink', + 'Provide', + 'Consume', + 'ObjectLink', + 'LocalStorageLink', + 'LocalStorageProp', + 'Local', + 'Param', + 'Event', + 'Provider', + 'Consumer', +]); + +export enum ModifierType { + PRIVATE = 1, + PROTECTED = 1 << 1, + PUBLIC = 1 << 2, + EXPORT = 1 << 3, + STATIC = 1 << 4, + ABSTRACT = 1 << 5, + ASYNC = 1 << 6, + CONST = 1 << 7, + ACCESSOR = 1 << 8, + DEFAULT = 1 << 9, + IN = 1 << 10, + READONLY = 1 << 11, + OUT = 1 << 12, + OVERRIDE = 1 << 13, + DECLARE = 1 << 14, +} + +export const MODIFIER_TYPE_MASK = 0xffff; + +const MODIFIER_TYPE_STRINGS = [ + 'private', + 'protected', + 'public', + 'export', + 'static', + 'abstract', + 'async', + 'const', + 'accessor', + 'default', + 'in', + 'readonly', + 'out', + 'override', + 'declare', +]; + +const MODIFIER_KIND_2_ENUM = new Map([ + [ts.SyntaxKind.AbstractKeyword, ModifierType.ABSTRACT], + [ts.SyntaxKind.AccessorKeyword, ModifierType.ACCESSOR], + [ts.SyntaxKind.AsyncKeyword, ModifierType.ASYNC], + [ts.SyntaxKind.ConstKeyword, ModifierType.CONST], + [ts.SyntaxKind.DeclareKeyword, ModifierType.DECLARE], + [ts.SyntaxKind.DefaultKeyword, ModifierType.DEFAULT], + [ts.SyntaxKind.ExportKeyword, ModifierType.EXPORT], + [ts.SyntaxKind.InKeyword, ModifierType.IN], + [ts.SyntaxKind.PrivateKeyword, ModifierType.PRIVATE], + [ts.SyntaxKind.ProtectedKeyword, ModifierType.PROTECTED], + [ts.SyntaxKind.PublicKeyword, ModifierType.PUBLIC], + [ts.SyntaxKind.ReadonlyKeyword, ModifierType.READONLY], + [ts.SyntaxKind.OutKeyword, ModifierType.OUT], + [ts.SyntaxKind.OverrideKeyword, ModifierType.OVERRIDE], + [ts.SyntaxKind.StaticKeyword, ModifierType.STATIC], +]); + +export function modifierKind2Enum(kind: ts.SyntaxKind): ModifierType { + return MODIFIER_KIND_2_ENUM.get(kind)!; +} + +export function modifiers2stringArray(modifiers: number): string[] { + let strs: string[] = []; + for (let idx = 0; idx < MODIFIER_TYPE_STRINGS.length; idx++) { + if (modifiers & 0x01) { + strs.push(MODIFIER_TYPE_STRINGS[idx]); + } + modifiers = modifiers >>> 1; + } + return strs; +} + +export abstract class ArkBaseModel { + protected modifiers?: number; + protected decorators?: Set; + protected metadata?: ArkMetadata; + + public getMetadata(kind: ArkMetadataKind): ArkMetadataType | undefined { + return this.metadata?.getMetadata(kind); + } + + public setMetadata(kind: ArkMetadataKind, value: ArkMetadataType): void { + if (!this.metadata) { + this.metadata = new ArkMetadata(); + } + return this.metadata?.setMetadata(kind, value); + } + + public getModifiers(): number { + if (!this.modifiers) { + return 0; + } + return this.modifiers; + } + + public setModifiers(modifiers: number): void { + if (modifiers !== 0) { + this.modifiers = modifiers; + } + } + + public addModifier(modifier: ModifierType | number): void { + this.modifiers = this.getModifiers() | modifier; + } + + public removeModifier(modifier: ModifierType): void { + if (!this.modifiers) { + return; + } + this.modifiers &= MODIFIER_TYPE_MASK ^ modifier; + } + + public isStatic(): boolean { + return this.containsModifier(ModifierType.STATIC); + } + + public isProtected(): boolean { + return this.containsModifier(ModifierType.PROTECTED); + } + + public isPrivate(): boolean { + return this.containsModifier(ModifierType.PRIVATE); + } + + public isPublic(): boolean { + return this.containsModifier(ModifierType.PUBLIC); + } + + public isReadonly(): boolean { + return this.containsModifier(ModifierType.READONLY); + } + + public isAbstract(): boolean { + return this.containsModifier(ModifierType.ABSTRACT); + } + + public isExport(): boolean { + return this.containsModifier(ModifierType.EXPORT); + } + + public isDefault(): boolean { + return this.containsModifier(ModifierType.DEFAULT); + } + + /** @deprecated Use {@link isExport} instead. */ + public isExported(): boolean { + return this.isExport(); + } + + public isDeclare(): boolean { + return this.containsModifier(ModifierType.DECLARE); + } + + public containsModifier(modifierType: ModifierType): boolean { + if (!this.modifiers) { + return false; + } + + return (this.modifiers & modifierType) === modifierType; + } + + public getDecorators(): Decorator[] { + if (this.decorators) { + return Array.from(this.decorators); + } + return []; + } + + public setDecorators(decorators: Set): void { + if (decorators.size > 0) { + this.decorators = decorators; + } + } + + public addDecorator(decorator: Decorator): void { + if (!this.decorators) { + this.decorators = new Set(); + } + this.decorators.add(decorator); + } + + public removeDecorator(kind: string): void { + this.decorators?.forEach((value) => { + if (value.getKind() === kind) { + this.decorators?.delete(value); + } + }); + } + + public hasBuilderDecorator(): boolean { + return this.hasDecorator(BUILDER_DECORATOR); + } + + public getStateDecorators(): Decorator[] { + if (!this.decorators) { + return []; + } + return Array.from(this.decorators).filter((item) => { + return COMPONENT_MEMBER_DECORATORS.has(item.getKind()); + }) as Decorator[]; + } + + public hasBuilderParamDecorator(): boolean { + return this.hasDecorator(BUILDER_PARAM_DECORATOR); + } + + public hasEntryDecorator(): boolean { + return this.hasDecorator(ENTRY_DECORATOR); + } + + public hasComponentDecorator(): boolean { + return this.hasDecorator(COMPONENT_DECORATOR); + } + + public hasDecorator(kind: string | Set): boolean { + let decorators = this.getDecorators(); + return ( + decorators.filter((value) => { + if (kind instanceof Set) { + return kind.has(value.getKind()); + } + return value.getKind() === kind; + }).length !== 0 + ); + } + + protected validateFields(fields: string[]): ArkError { + let errs: string[] = []; + for (const field of fields) { + let value = Reflect.get(this, field); + if (!value) { + errs.push(field); + } + } + if (errs.length === 0) { + return { errCode: ArkErrorCode.OK }; + } + logger.error(`class fields: ${errs.join(',')} is undefined.`); + return { errCode: ArkErrorCode.CLASS_INSTANCE_FIELD_UNDEFINDED, errMsg: `${errs.join(',')} is undefined.` }; + } + + public abstract validate(): ArkError; +} diff --git a/ets2panda/linter/arkanalyzer/src/core/model/ArkBody.ts b/ets2panda/linter/arkanalyzer/src/core/model/ArkBody.ts new file mode 100644 index 0000000000..100e84ff01 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/model/ArkBody.ts @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Local } from '../base/Local'; +import { Cfg } from '../graph/Cfg'; +import { AliasType } from '../base/Type'; +import { Trap } from '../base/Trap'; +import { Value } from '../base/Value'; +import { ArkAliasTypeDefineStmt } from '../base/Stmt'; + +export class ArkBody { + private locals: Map; + private usedGlobals?: Map; + private cfg: Cfg; + private aliasTypeMap?: Map; + private traps?: Trap[]; + + constructor(locals: Set, cfg: Cfg, aliasTypeMap?: Map, + traps?: Trap[]) { + this.cfg = cfg; + this.aliasTypeMap = aliasTypeMap; + this.locals = new Map(); + locals.forEach(local => this.locals.set(local.getName(), local)); + this.traps = traps; + } + + public getLocals(): Map { + return this.locals; + } + + public setLocals(locals: Set): void { + if (!this.locals) { + this.locals = new Map(); + } + locals.forEach(local => this.locals.set(local.getName(), local)); + } + + public addLocal(name: string, local: Local): void { + this.locals.set(name, local); + } + + public getUsedGlobals(): Map | undefined { + return this.usedGlobals; + } + + public setUsedGlobals(globals: Map): void { + this.usedGlobals = globals; + } + + public getCfg(): Cfg { + return this.cfg; + } + + public setCfg(cfg: Cfg): void { + this.cfg = cfg; + } + + public getAliasTypeMap(): Map | undefined { + return this.aliasTypeMap; + } + + public getAliasTypeByName(name: string): AliasType | null { + const aliasTypeInfo: [AliasType, ArkAliasTypeDefineStmt] | undefined = this.aliasTypeMap?.get(name); + if (aliasTypeInfo) { + return aliasTypeInfo[0]; + } + return null; + } + + public getTraps(): Trap[] | undefined { + return this.traps; + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/model/ArkClass.ts b/ets2panda/linter/arkanalyzer/src/core/model/ArkClass.ts new file mode 100644 index 0000000000..71584a6492 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/model/ArkClass.ts @@ -0,0 +1,535 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ClassType, GenericType, Type } from '../base/Type'; +import { ViewTree } from '../graph/ViewTree'; +import { ArkField } from './ArkField'; +import { ArkFile, Language } from './ArkFile'; +import { ArkMethod } from './ArkMethod'; +import { ArkNamespace } from './ArkNamespace'; +import { ClassSignature, FieldSignature, FileSignature, MethodSignature, NamespaceSignature } from './ArkSignature'; +import { Local } from '../base/Local'; +import { ArkExport, ExportType } from './ArkExport'; +import { TypeInference } from '../common/TypeInference'; +import { ANONYMOUS_CLASS_PREFIX, DEFAULT_ARK_CLASS_NAME, NAME_DELIMITER, NAME_PREFIX } from '../common/Const'; +import { getColNo, getLineNo, LineCol, setCol, setLine } from '../base/Position'; +import { ArkBaseModel } from './ArkBaseModel'; +import { ArkError } from '../common/ArkError'; + +export enum ClassCategory { + CLASS = 0, + STRUCT = 1, + INTERFACE = 2, + ENUM = 3, + TYPE_LITERAL = 4, + OBJECT = 5, +} + +/** + * @category core/model + */ +export class ArkClass extends ArkBaseModel implements ArkExport { + private category!: ClassCategory; + private code?: string; + private lineCol: LineCol = 0; + + private declaringArkFile!: ArkFile; + private declaringArkNamespace: ArkNamespace | undefined; + private classSignature!: ClassSignature; + /** + * The keys of the `heritageClasses` map represent the names of superclass and interfaces. + * The superclass name is placed first; if it does not exist, an empty string `''` will occupy this position. + * The values of the `heritageClasses` map will be replaced with `ArkClass` or `null` during type inference. + */ + private heritageClasses: Map = new Map(); + + private genericsTypes?: GenericType[]; + private realTypes?: Type[]; + private defaultMethod: ArkMethod | null = null; + + // name to model + private methods: Map = new Map(); + private fields: Map = new Map(); + private extendedClasses: Map = new Map(); + private staticMethods: Map = new Map(); + private staticFields: Map = new Map(); + + private instanceInitMethod: ArkMethod = new ArkMethod(); + private staticInitMethod: ArkMethod = new ArkMethod(); + + private anonymousMethodNumber: number = 0; + private indexSignatureNumber: number = 0; + + private viewTree?: ViewTree; + + constructor() { + super(); + } + + /** + * Returns the program language of the file where this class defined. + */ + public getLanguage(): Language { + return this.getDeclaringArkFile().getLanguage(); + } + + /** + * Returns the **string**name of this class. + * @returns The name of this class. + */ + public getName() { + return this.classSignature.getClassName(); + } + + /** + * Returns the codes of class as a **string.** + * @returns the codes of class. + */ + public getCode() { + return this.code; + } + + public setCode(code: string) { + this.code = code; + } + + /** + * Returns the line position of this class. + * @returns The line position of this class. + */ + public getLine() { + return getLineNo(this.lineCol); + } + + public setLine(line: number) { + this.lineCol = setLine(this.lineCol, line); + } + + /** + * Returns the column position of this class. + * @returns The column position of this class. + */ + public getColumn() { + return getColNo(this.lineCol); + } + + public setColumn(column: number) { + this.lineCol = setCol(this.lineCol, column); + } + + public getCategory(): ClassCategory { + return this.category; + } + + public setCategory(category: ClassCategory): void { + this.category = category; + } + + /** + * Returns the declaring file. + * @returns A file defined by ArkAnalyzer. + * @example + * 1. Get the {@link ArkFile} which the ArkClass is in. + + ```typescript + const arkFile = arkClass.getDeclaringArkFile(); + ``` + */ + public getDeclaringArkFile() { + return this.declaringArkFile; + } + + public setDeclaringArkFile(declaringArkFile: ArkFile) { + this.declaringArkFile = declaringArkFile; + } + + /** + * Returns the declaring namespace of this class, which may also be an **undefined**. + * @returns The declaring namespace (may be **undefined**) of this class. + */ + public getDeclaringArkNamespace(): ArkNamespace | undefined { + return this.declaringArkNamespace; + } + + public setDeclaringArkNamespace(declaringArkNamespace: ArkNamespace | undefined) { + this.declaringArkNamespace = declaringArkNamespace; + } + + public isDefaultArkClass(): boolean { + return this.getName() === DEFAULT_ARK_CLASS_NAME; + } + + public isAnonymousClass(): boolean { + return this.getName().startsWith(ANONYMOUS_CLASS_PREFIX); + } + + /** + * Returns the signature of current class (i.e., {@link ClassSignature}). + * The {@link ClassSignature} can uniquely identify a class, according to which we can find the class from the scene. + * @returns The class signature. + */ + public getSignature() { + return this.classSignature; + } + + public setSignature(classSig: ClassSignature) { + this.classSignature = classSig; + } + + public getSuperClassName(): string { + return this.heritageClasses.keys().next().value || ''; + } + + public addHeritageClassName(className: string): void { + this.heritageClasses.set(className, undefined); + } + + /** + * Returns the superclass of this class. + * @returns The superclass of this class. + */ + public getSuperClass(): ArkClass | null { + const heritageClass = this.getHeritageClass(this.getSuperClassName()); + if (heritageClass && heritageClass.getCategory() !== ClassCategory.INTERFACE) { + return heritageClass; + } + return null; + } + + private getHeritageClass(heritageClassName: string): ArkClass | null { + if (!heritageClassName) { + return null; + } + let superClass = this.heritageClasses.get(heritageClassName); + if (superClass === undefined) { + let type = TypeInference.inferUnclearRefName(heritageClassName, this); + if (type) { + type = TypeInference.replaceAliasType(type); + } + if (type instanceof ClassType && + (superClass = this.declaringArkFile.getScene().getClass(type.getClassSignature()))) { + superClass.addExtendedClass(this); + const realGenericTypes = type.getRealGenericTypes(); + if (realGenericTypes) { + this.realTypes = realGenericTypes; + } + } + this.heritageClasses.set(heritageClassName, superClass || null); + } + return superClass || null; + } + + public getAllHeritageClasses(): ArkClass[] { + const result: ArkClass[] = []; + this.heritageClasses.forEach((v, k) => { + const heritage = v ?? this.getHeritageClass(k); + if (heritage) { + result.push(heritage); + } + }); + return result; + } + + public getExtendedClasses(): Map { + return this.extendedClasses; + } + + public addExtendedClass(extendedClass: ArkClass) { + this.extendedClasses.set(extendedClass.getName(), extendedClass); + } + + public getImplementedInterfaceNames(): string[] { + if (this.category === ClassCategory.INTERFACE) { + return []; + } + return Array.from(this.heritageClasses.keys()).slice(1); + } + + public hasImplementedInterface(interfaceName: string) { + return this.heritageClasses.has(interfaceName) && this.getSuperClassName() !== interfaceName; + } + + public getImplementedInterface(interfaceName: string): ArkClass | null { + const heritageClass = this.getHeritageClass(interfaceName); + if (heritageClass && heritageClass.getCategory() === ClassCategory.INTERFACE) { + return heritageClass; + } + return null; + } + + /** + * Get the field according to its field signature. + * If no field cound be found, **null**will be returned. + * @param fieldSignature - the field's signature. + * @returns A field. If there is no field in this class, the return will be a **null**. + */ + public getField(fieldSignature: FieldSignature): ArkField | null { + const fieldName = fieldSignature.getFieldName(); + let fieldSearched: ArkField | null = this.getFieldWithName(fieldName); + if (!fieldSearched) { + fieldSearched = this.getStaticFieldWithName(fieldName); + } + return fieldSearched; + } + + public getFieldWithName(fieldName: string): ArkField | null { + return this.fields.get(fieldName) || null; + } + + public getStaticFieldWithName(fieldName: string): ArkField | null { + return this.staticFields.get(fieldName) || null; + } + + /** + * Returns an **array** of fields in the class. + * @returns an **array** of fields in the class. + */ + public getFields(): ArkField[] { + const allFields: ArkField[] = Array.from(this.fields.values()); + allFields.push(...this.staticFields.values()); + return allFields; + } + + public addField(field: ArkField) { + if (field.isStatic()) { + this.staticFields.set(field.getName(), field); + } else { + this.fields.set(field.getName(), field); + } + } + + public addFields(fields: ArkField[]) { + fields.forEach((field) => { + this.addField(field); + }); + } + + public getRealTypes(): Type[] | undefined { + return this.realTypes ? Array.from(this.realTypes) : undefined; + } + + public getGenericsTypes(): GenericType[] | undefined { + return this.genericsTypes ? Array.from(this.genericsTypes) : undefined; + } + + public addGenericType(gType: GenericType) { + if (!this.genericsTypes) { + this.genericsTypes = []; + } + this.genericsTypes.push(gType); + } + + /** + * Returns all methods defined in the specific class in the form of an array. + * @param generated - indicating whether this API returns the methods that are dynamically + * generated at runtime. If it is not specified as true or false, the return will not include the generated method. + * @returns An array of all methods in this class. + * @example + * 1. Get methods defined in class `BookService`. + + ```typescript + let classes: ArkClass[] = scene.getClasses(); + let serviceClass : ArkClass = classes[1]; + let methods: ArkMethod[] = serviceClass.getMethods(); + let methodNames: string[] = methods.map(mthd => mthd.name); + console.log(methodNames); + ``` + */ + public getMethods(generated?: boolean): ArkMethod[] { + const allMethods = Array.from(this.methods.values()) + .filter(f => !generated && !f.isGenerated() || generated); + allMethods.push(...this.staticMethods.values()); + return [...new Set(allMethods)]; + } + + public getMethod(methodSignature: MethodSignature): ArkMethod | null { + const methodName = methodSignature.getMethodSubSignature().getMethodName(); + const methodSearched = this.getMethodWithName(methodName) ?? this.getStaticMethodWithName(methodName); + if (methodSearched === null) { + return null; + } + const implSignature = methodSearched.getImplementationSignature(); + if (implSignature !== null && implSignature.isMatch(methodSignature)) { + return methodSearched; + } + const declareSignatures = methodSearched.getDeclareSignatures(); + if (declareSignatures !== null) { + for (let i = 0; i < declareSignatures.length; i++) { + if (declareSignatures[i].isMatch(methodSignature)) { + return methodSearched; + } + } + } + return null; + } + + public getMethodWithName(methodName: string): ArkMethod | null { + return this.methods.get(methodName) || null; + } + + public getStaticMethodWithName(methodName: string): ArkMethod | null { + return this.staticMethods.get(methodName) || null; + } + + /** + * add a method in class. + * when a nested method with declare name, add both the declare origin name and signature name + * %${declare name}$${outer method name} in class. + */ + public addMethod(method: ArkMethod, originName?: string): void { + const name = originName ?? method.getName(); + if (method.isStatic()) { + this.staticMethods.set(name, method); + } else { + this.methods.set(name, method); + } + if (!originName && !method.isAnonymousMethod() && name.startsWith(NAME_PREFIX)) { + const index = name.indexOf(NAME_DELIMITER); + if (index > 1) { + const originName = name.substring(1, index); + this.addMethod(method, originName); + } + } + } + + public setDefaultArkMethod(defaultMethod: ArkMethod) { + this.defaultMethod = defaultMethod; + this.addMethod(defaultMethod); + } + + public getDefaultArkMethod(): ArkMethod | null { + return this.defaultMethod; + } + + public setViewTree(viewTree: ViewTree) { + this.viewTree = viewTree; + } + + /** + * Returns the view tree of the ArkClass. + * @returns The view tree of the ArkClass. + * @example + * 1. get viewTree of ArkClass. + + ```typescript + for (let arkFiles of scene.getFiles()) { + for (let arkClasss of arkFiles.getClasses()) { + if (arkClasss.hasViewTree()) { + arkClasss.getViewTree(); + } + } + } + ``` + */ + public getViewTree(): ViewTree | undefined { + return this.viewTree; + } + + /** + * Check whether the view tree is defined. + * If it is defined, the return value is true, otherwise it is false. + * @returns True if the view tree is defined; false otherwise. + * @example + * 1. Judge viewTree of ArkClass. + + ```typescript + for (let arkFiles of scene.getFiles()) { + for (let arkClasss of arkFiles.getClasses()) { + if (arkClasss.hasViewTree()) { + arkClasss.getViewTree(); + } + } + } + ``` + */ + public hasViewTree(): boolean { + return this.viewTree !== undefined; + } + + public getStaticFields(classMap: Map): ArkField[] { + const fields: ArkField[] = []; + let classes: ArkClass[] = []; + if (this.declaringArkNamespace) { + classes = classMap.get(this.declaringArkNamespace.getNamespaceSignature())!; + } else { + classes = classMap.get(this.declaringArkFile.getFileSignature())!; + } + for (const arkClass of classes) { + for (const field of arkClass.getFields()) { + if (field.isStatic()) { + fields.push(field); + } + } + } + return fields; + } + + public getGlobalVariable(globalMap: Map): Local[] { + if (this.declaringArkNamespace) { + return globalMap.get(this.declaringArkNamespace.getNamespaceSignature())!; + } + return globalMap.get(this.declaringArkFile.getFileSignature())!; + } + + public getAnonymousMethodNumber() { + return this.anonymousMethodNumber++; + } + + public getIndexSignatureNumber() { + return this.indexSignatureNumber++; + } + + getExportType(): ExportType { + return ExportType.CLASS; + } + + public getInstanceInitMethod(): ArkMethod { + return this.instanceInitMethod; + } + + public getStaticInitMethod(): ArkMethod { + return this.staticInitMethod; + } + + public setInstanceInitMethod(arkMethod: ArkMethod): void { + this.instanceInitMethod = arkMethod; + } + + public setStaticInitMethod(arkMethod: ArkMethod): void { + this.staticInitMethod = arkMethod; + } + + public removeField(field: ArkField): boolean { + if (field.isStatic()) { + return this.staticFields.delete(field.getName()); + } + return this.fields.delete(field.getName()); + } + + public removeMethod(method: ArkMethod): boolean { + let rtn: boolean = false; + if (method.isStatic()) { + rtn = this.staticMethods.delete(method.getName()); + } else { + rtn = this.methods.delete(method.getName()); + } + rtn &&= this.getDeclaringArkFile().getScene().removeMethod(method); + return rtn; + } + + public validate(): ArkError { + return this.validateFields(['declaringArkFile', 'category', 'classSignature']); + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/model/ArkExport.ts b/ets2panda/linter/arkanalyzer/src/core/model/ArkExport.ts new file mode 100644 index 0000000000..3830d69936 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/model/ArkExport.ts @@ -0,0 +1,208 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { LineColPosition } from '../base/Position'; +import { ArkFile, Language } from './ArkFile'; +import { ArkSignature, ClassSignature, LocalSignature, MethodSignature, NamespaceSignature } from './ArkSignature'; +import { DEFAULT } from '../common/TSConst'; +import { ArkBaseModel, ModifierType } from './ArkBaseModel'; +import { ArkError } from '../common/ArkError'; +import { ArkMetadataKind, CommentsMetadata } from './ArkMetadata'; + +export type ExportSignature = NamespaceSignature | ClassSignature | MethodSignature | LocalSignature; + +export enum ExportType { + NAME_SPACE = 0, + CLASS = 1, + METHOD = 2, + LOCAL = 3, + TYPE = 4, + UNKNOWN = 9 +} + +export interface ArkExport extends ArkSignature { + getModifiers(): number; + containsModifier(modifierType: ModifierType): boolean; + + getName(): string; + + getExportType(): ExportType; + +} + +export interface FromInfo { + isDefault(): boolean; + + getOriginName(): string; + + getFrom(): string | undefined; + + getDeclaringArkFile(): ArkFile; +} + +/** + * @category core/model + */ +export class ExportInfo extends ArkBaseModel implements FromInfo { + private _default?: boolean; + private nameBeforeAs?: string; + private exportClauseName: string = ''; + + private exportClauseType: ExportType = ExportType.UNKNOWN; + private arkExport?: ArkExport | null; + private exportFrom?: string; + + private originTsPosition?: LineColPosition; + private tsSourceCode?: string; + private declaringArkFile!: ArkFile; + + private constructor() { + super(); + } + + /** + * Returns the program language of the file where this export info defined. + */ + public getLanguage(): Language { + return this.getDeclaringArkFile().getLanguage(); + } + + public getFrom(): string | undefined { + return this.exportFrom; + } + + public getOriginName(): string { + return this.nameBeforeAs ?? this.exportClauseName; + } + + public getExportClauseName(): string { + return this.exportClauseName; + } + + public setExportClauseType(exportClauseType: ExportType): void { + this.exportClauseType = exportClauseType; + } + + public getExportClauseType(): ExportType { + return this.exportClauseType; + } + + public getNameBeforeAs(): string | undefined { + return this.nameBeforeAs; + } + + public setArkExport(value: ArkExport | null) { + this.arkExport = value; + } + + public getArkExport(): ArkExport | undefined | null { + return this.arkExport; + } + + public isDefault(): boolean { + if (this.exportFrom) { + return this.nameBeforeAs === DEFAULT; + } + if (this._default === undefined) { + this._default = this.containsModifier(ModifierType.DEFAULT); + } + return this._default; + } + + public getOriginTsPosition(): LineColPosition { + return this.originTsPosition ?? LineColPosition.DEFAULT; + } + + public getTsSourceCode(): string { + return this.tsSourceCode ?? ''; + } + + public getDeclaringArkFile(): ArkFile { + return this.declaringArkFile; + } + + public static Builder = class ArkExportBuilder { + exportInfo: ExportInfo = new ExportInfo(); + + public exportClauseName(exportClauseName: string): ArkExportBuilder { + this.exportInfo.exportClauseName = exportClauseName; + return this; + } + + public exportClauseType(exportClauseType: ExportType): ArkExportBuilder { + this.exportInfo.setExportClauseType(exportClauseType); + return this; + } + + public nameBeforeAs(nameBeforeAs: string): ArkExportBuilder { + this.exportInfo.nameBeforeAs = nameBeforeAs; + return this; + } + + public modifiers(modifiers: number): ArkExportBuilder { + this.exportInfo.modifiers = modifiers; + return this; + } + + public originTsPosition(originTsPosition: LineColPosition): ArkExportBuilder { + this.exportInfo.originTsPosition = originTsPosition; + return this; + } + + public tsSourceCode(tsSourceCode: string): ArkExportBuilder { + this.exportInfo.tsSourceCode = tsSourceCode; + return this; + } + + public declaringArkFile(value: ArkFile): ArkExportBuilder { + this.exportInfo.declaringArkFile = value; + return this; + } + + public arkExport(value: ArkExport): ArkExportBuilder { + this.exportInfo.arkExport = value; + return this; + } + + public exportFrom(exportFrom: string): ArkExportBuilder { + if (exportFrom !== '') { + this.exportInfo.exportFrom = exportFrom; + } + return this; + } + + public setLeadingComments(commentsMetadata: CommentsMetadata): ArkExportBuilder { + if (commentsMetadata.getComments().length > 0) { + this.exportInfo.setMetadata(ArkMetadataKind.LEADING_COMMENTS, commentsMetadata); + } + return this; + } + + public setTrailingComments(commentsMetadata: CommentsMetadata): ArkExportBuilder { + if (commentsMetadata.getComments().length > 0) { + this.exportInfo.setMetadata(ArkMetadataKind.TRAILING_COMMENTS, commentsMetadata); + } + return this; + } + + public build(): ExportInfo { + return this.exportInfo; + } + }; + + public validate(): ArkError { + return this.validateFields(['declaringArkFile']); + } +} diff --git a/ets2panda/linter/arkanalyzer/src/core/model/ArkField.ts b/ets2panda/linter/arkanalyzer/src/core/model/ArkField.ts new file mode 100644 index 0000000000..e85ce04d1a --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/model/ArkField.ts @@ -0,0 +1,163 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { LineColPosition } from '../base/Position'; +import { Stmt } from '../base/Stmt'; +import { ArkClass, ClassCategory } from './ArkClass'; +import { FieldSignature } from './ArkSignature'; +import { Type } from '../base/Type'; +import { ArkBaseModel, ModifierType } from './ArkBaseModel'; +import { ArkError } from '../common/ArkError'; +import { Language } from './ArkFile'; + + +export enum FieldCategory { + PROPERTY_DECLARATION = 0, + PROPERTY_ASSIGNMENT = 1, + SHORT_HAND_PROPERTY_ASSIGNMENT = 2, + SPREAD_ASSIGNMENT = 3, + PROPERTY_SIGNATURE = 4, + ENUM_MEMBER = 5, + INDEX_SIGNATURE = 6, + GET_ACCESSOR = 7, + PARAMETER_PROPERTY = 8, +} + +/** + * @category core/model + */ +export class ArkField extends ArkBaseModel { + private code: string = ""; + private category!: FieldCategory; + + private declaringClass!: ArkClass; + private questionToken: boolean = false; + private exclamationToken: boolean = false; + + private fieldSignature!: FieldSignature; + private originPosition?: LineColPosition; + + private initializer: Stmt[] = []; + + constructor() { + super(); + } + + /** + * Returns the program language of the file where this field's class defined. + */ + public getLanguage(): Language { + return this.getDeclaringArkClass().getLanguage(); + } + + public getDeclaringArkClass() { + return this.declaringClass; + } + + public setDeclaringArkClass(declaringClass: ArkClass) { + this.declaringClass = declaringClass; + } + + /** + * Returns the codes of field as a **string.** + * @returns the codes of field. + */ + public getCode() { + return this.code; + } + + public setCode(code: string) { + this.code = code; + } + + public getCategory(): FieldCategory { + return this.category; + } + + public setCategory(category: FieldCategory): void { + this.category = category; + } + + public getName() { + return this.fieldSignature.getFieldName(); + } + + public getType():Type { + return this.fieldSignature.getType(); + } + + public getSignature(): FieldSignature { + return this.fieldSignature; + } + + public setSignature(fieldSig: FieldSignature) { + this.fieldSignature = fieldSig; + } + + /** + * Returns an array of statements used for initialization. + * @returns An array of statements used for initialization. + */ + public getInitializer(): Stmt[] { + return this.initializer; + } + + public setInitializer(initializer: Stmt[]) { + this.initializer = initializer; + } + + public setQuestionToken(questionToken: boolean) { + this.questionToken = questionToken; + } + + public setExclamationToken(exclamationToken: boolean) { + this.exclamationToken = exclamationToken; + } + + public getQuestionToken() { + return this.questionToken; + } + + public getExclamationToken() { + return this.exclamationToken; + } + + public setOriginPosition(position: LineColPosition) { + this.originPosition = position; + } + + /** + * Returns the original position of the field at source code. + * @returns The original position of the field at source code. + */ + public getOriginPosition(): LineColPosition { + return this.originPosition ?? LineColPosition.DEFAULT; + } + + public validate(): ArkError { + return this.validateFields(['category', 'declaringClass', 'fieldSignature']); + } + + // For class field, it is default public if there is not any access modify + public isPublic(): boolean { + if (!this.containsModifier(ModifierType.PUBLIC) && + !this.containsModifier(ModifierType.PRIVATE) && + !this.containsModifier(ModifierType.PROTECTED) && + this.getDeclaringArkClass().getCategory() === ClassCategory.CLASS) { + return true; + } + return this.containsModifier(ModifierType.PUBLIC); + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/model/ArkFile.ts b/ets2panda/linter/arkanalyzer/src/core/model/ArkFile.ts new file mode 100644 index 0000000000..897af2e03f --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/model/ArkFile.ts @@ -0,0 +1,341 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ModuleScene, Scene } from '../../Scene'; +import { ArkExport, ExportInfo } from './ArkExport'; +import { ImportInfo } from './ArkImport'; +import { ArkClass } from './ArkClass'; +import { ArkNamespace } from './ArkNamespace'; +import { AliasClassSignature, ClassSignature, FileSignature, NamespaceSignature } from './ArkSignature'; +import { ALL } from "../common/TSConst"; + +export const notStmtOrExprKind = ['ModuleDeclaration', 'ClassDeclaration', 'InterfaceDeclaration', 'EnumDeclaration', 'ExportDeclaration', + 'ExportAssignment', 'MethodDeclaration', 'Constructor', 'FunctionDeclaration', 'GetAccessor', 'SetAccessor', 'ArrowFunction', + 'FunctionExpression', 'MethodSignature', 'ConstructSignature', 'CallSignature']; + +export enum Language { + TYPESCRIPT = 0, + ARKTS1_1 = 1, + ARKTS1_2 = 2, + UNKNOWN = -1, +} + +/** + * @category core/model + */ +export class ArkFile { + private language: Language; + private absoluteFilePath: string = ''; + private projectDir: string = ''; + private code: string = ''; + + private defaultClass!: ArkClass; + + // name to model + private namespaces: Map = new Map(); // don't contain nested namespaces + private classes: Map = new Map(); // don't contain class in namespace + + private importInfoMap: Map = new Map(); + private exportInfoMap: Map = new Map(); + + private scene!: Scene; + private moduleScene?: ModuleScene; + + private fileSignature: FileSignature = FileSignature.DEFAULT; + + private ohPackageJson5Path: string[] = []; + + private anonymousClassNumber: number = 0; + + constructor(language: Language) { + this.language = language; + } + + /** + * Returns the program language of the file. + */ + public getLanguage(): Language { + return this.language; + } + + public setLanguage(language: Language): void { + this.language = language; + } + + /** + * Returns the **string** name of the file, which also acts as the file's relative path. + * @returns The file's name (also means its relative path). + */ + public getName() { + return this.fileSignature.getFileName(); + } + + public setScene(scene: Scene) { + this.scene = scene; + } + + /** + * Returns the scene (i.e., {@link Scene}) built for the project. The {@link Scene} is the core class of ArkAnalyzer, + * through which users can access all the information of the analyzed code (project), + * including file list, class list, method list, property list, etc. + * @returns The scene of the file. + */ + public getScene() { + return this.scene; + } + + public getModuleScene() { + return this.moduleScene; + } + + public setModuleScene(moduleScene: ModuleScene) { + this.moduleScene = moduleScene; + } + + public setProjectDir(projectDir: string) { + this.projectDir = projectDir; + } + + public getProjectDir(): string { + return this.projectDir; + } + + /** + * Get a file path. + * @returns The absolute file path. + * @example + * 1. Read source code based on file path. + + ```typescript + let str = fs.readFileSync(arkFile.getFilePath(), 'utf8'); + ``` + */ + public getFilePath(): string { + return this.absoluteFilePath; + } + + public setFilePath(absoluteFilePath: string) { + this.absoluteFilePath = absoluteFilePath; + } + + public setCode(code: string) { + this.code = code; + } + + /** + * Returns the codes of file as a **string.** + * @returns the codes of file. + */ + public getCode() { + return this.code; + } + + public addArkClass(arkClass: ArkClass) { + this.classes.set(arkClass.getName(), arkClass); + } + + public getDefaultClass() { + return this.defaultClass; + } + + public setDefaultClass(defaultClass: ArkClass) { + this.defaultClass = defaultClass; + } + + public getNamespace(namespaceSignature: NamespaceSignature): ArkNamespace | null { + const namespaceName = namespaceSignature.getNamespaceName(); + return this.getNamespaceWithName(namespaceName); + } + + public getNamespaceWithName(namespaceName: string): ArkNamespace | null { + return this.namespaces.get(namespaceName) || null; + } + + public getNamespaces(): ArkNamespace[] { + return Array.from(this.namespaces.values()); + } + + /** + * Returns the class based on its class signature. If the class could not be found, **null** will be returned. + * @param classSignature - the class signature. + * @returns A class. If there is no class, the return will be a **null**. + */ + public getClass(classSignature: ClassSignature): ArkClass | null { + const className = classSignature instanceof AliasClassSignature ? classSignature.getOriginName() + : classSignature.getClassName(); + return this.getClassWithName(className); + } + + public getClassWithName(Class: string): ArkClass | null { + return this.classes.get(Class) || null; + } + + public getClasses(): ArkClass[] { + return Array.from(this.classes.values()); + } + + public addNamespace(namespace: ArkNamespace) { + this.namespaces.set(namespace.getName(), namespace); + } + + /** + * Returns an **array** of import information. + * The import information includes: clause's name, type, modifiers, location where it is imported from, etc. + * @returns An **array** of import information. + */ + public getImportInfos(): ImportInfo[] { + return Array.from(this.importInfoMap.values()); + } + + public getImportInfoBy(name: string): ImportInfo | undefined { + return this.importInfoMap.get(name); + } + + public addImportInfo(importInfo: ImportInfo) { + this.importInfoMap.set(importInfo.getImportClauseName(), importInfo); + } + + public removeImportInfo(importInfo: ImportInfo): boolean { + return this.importInfoMap.delete(importInfo.getImportClauseName()); + } + + public removeNamespace(namespace: ArkNamespace): boolean { + let rtn = this.namespaces.delete(namespace.getName()); + rtn &&= this.getScene().removeNamespace(namespace); + return rtn; + } + + public removeArkClass(arkClass: ArkClass): boolean { + let rtn = this.classes.delete(arkClass.getName()); + rtn &&= this.getScene().removeClass(arkClass); + return rtn; + } + + public getExportInfos(): ExportInfo[] { + const exportInfos: ExportInfo[] = []; + this.exportInfoMap.forEach((value, key) => { + if (key !== ALL || value.getFrom()) { + exportInfos.push(value); + } + }) + return exportInfos; + } + + /** + * Find out the {@link ExportInfo} of this {@link ArkFile} by the given export name. + * It returns an {@link ExportInfo} or 'undefined' if it failed to find. + * @param name + * @returns + * @example + ```typescript + // abc.ts ArkFile + export class A { + ... + } + + export namespace B { + export namespace C { + export class D {} + } + } + + // xyz.ts call getExportInfoBy + let arkFile = scene.getFile(fileSignature); + + // a is the export class A defined in abc.ts + let a = arkFile.getExportInfoBy('A'); + + // b is the export class D within namespace C defined in abc.ts + let b = arkFile.getExportInfoBy('B.C.D'); + ``` + */ + public getExportInfoBy(name: string): ExportInfo | undefined { + const separator = '.'; + const names = name.split(separator); + if (names.length === 1) { + return this.exportInfoMap.get(names[0]); + } + + let index = 0; + let currExportInfo = this.exportInfoMap.get(names[index]); + if (currExportInfo === undefined) { + return undefined; + } + + for (let i = 1; i < names.length; i++) { + const arkExport: ArkExport | null | undefined = currExportInfo.getArkExport(); + if (arkExport && arkExport instanceof ArkNamespace) { + currExportInfo = arkExport.getExportInfoBy(names[i]); + if (currExportInfo === undefined) { + return undefined; + } + } + } + return currExportInfo; + } + + public addExportInfo(exportInfo: ExportInfo, key?: string) { + this.exportInfoMap.set(key ?? exportInfo.getExportClauseName(), exportInfo); + } + + public removeExportInfo(exportInfo: ExportInfo, key?: string): void { + if (key) { + this.exportInfoMap.delete(key); + return; + } + this.exportInfoMap.delete(exportInfo.getExportClauseName()); + } + + public getProjectName() { + return this.fileSignature.getProjectName(); + } + + public getModuleName() { + return this.moduleScene?.getModuleName(); + } + + public setOhPackageJson5Path(ohPackageJson5Path: string[]) { + this.ohPackageJson5Path = ohPackageJson5Path; + } + + public getOhPackageJson5Path() { + return this.ohPackageJson5Path; + } + + /** + * Returns the file signature of this file. A file signature consists of project's name and file's name. + * @returns The file signature of this file. + */ + public getFileSignature() { + return this.fileSignature; + } + + public setFileSignature(fileSignature: FileSignature): void { + this.fileSignature = fileSignature; + } + + public getAllNamespacesUnderThisFile(): ArkNamespace[] { + let namespaces: ArkNamespace[] = []; + namespaces.push(...this.namespaces.values()); + this.namespaces.forEach((ns) => { + namespaces.push(...ns.getAllNamespacesUnderThisNamespace()); + }); + return namespaces; + } + + public getAnonymousClassNumber() { + return this.anonymousClassNumber++; + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/model/ArkImport.ts b/ets2panda/linter/arkanalyzer/src/core/model/ArkImport.ts new file mode 100644 index 0000000000..80c95ddff1 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/model/ArkImport.ts @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkFile, Language } from './ArkFile'; +import { LineColPosition } from '../base/Position'; +import { ExportInfo, FromInfo } from './ArkExport'; +import { findExportInfo } from "../common/ModelUtils"; +import { ArkBaseModel } from './ArkBaseModel'; +import { ArkError } from '../common/ArkError'; + +/** + * @category core/model + */ +export class ImportInfo extends ArkBaseModel implements FromInfo { + private importClauseName: string = ''; + private importType: string = ''; + private importFrom?: string; + private nameBeforeAs?: string; + private declaringArkFile!: ArkFile; + + private originTsPosition?: LineColPosition; + private tsSourceCode?: string; + private lazyExportInfo?: ExportInfo | null; + + constructor() { + super(); + } + + /** + * Returns the program language of the file where this import info defined. + */ + public getLanguage(): Language { + return this.getDeclaringArkFile().getLanguage(); + } + + public build(importClauseName: string, importType: string, importFrom: string, originTsPosition: LineColPosition, + modifiers: number, nameBeforeAs?: string) { + this.setImportClauseName(importClauseName); + this.setImportType(importType); + this.setImportFrom(importFrom); + this.setOriginTsPosition(originTsPosition); + this.addModifier(modifiers); + this.setNameBeforeAs(nameBeforeAs); + } + + public getOriginName(): string { + return this.nameBeforeAs ?? this.importClauseName; + } + + /** + * Returns the export information, i.e., the actual reference generated at the time of call. + * The export information includes: clause's name, clause's type, modifiers, location + * where it is exported from, etc. If the export information could not be found, **null** will be returned. + * @returns The export information. If there is no export information, the return will be a **null**. + */ + public getLazyExportInfo(): ExportInfo | null { + if (this.lazyExportInfo === undefined) { + this.lazyExportInfo = findExportInfo(this); + } + return this.lazyExportInfo || null; + } + + public setDeclaringArkFile(declaringArkFile: ArkFile): void { + this.declaringArkFile = declaringArkFile; + } + + public getDeclaringArkFile(): ArkFile { + return this.declaringArkFile; + } + + public getImportClauseName(): string { + return this.importClauseName; + } + + public setImportClauseName(importClauseName: string): void { + this.importClauseName = importClauseName; + } + + public getImportType(): string { + return this.importType; + } + + public setImportType(importType: string): void { + this.importType = importType; + } + + public setImportFrom(importFrom: string): void { + this.importFrom = importFrom; + } + + public getNameBeforeAs(): string | undefined { + return this.nameBeforeAs; + } + + public setNameBeforeAs(nameBeforeAs: string | undefined) { + this.nameBeforeAs = nameBeforeAs; + } + + public setOriginTsPosition(originTsPosition: LineColPosition): void { + this.originTsPosition = originTsPosition; + } + + public getOriginTsPosition(): LineColPosition { + return this.originTsPosition ?? LineColPosition.DEFAULT; + } + + public setTsSourceCode(tsSourceCode: string): void { + this.tsSourceCode = tsSourceCode; + } + + public getTsSourceCode(): string { + return this.tsSourceCode ?? ''; + } + + public getFrom(): string | undefined { + return this.importFrom; + } + + public isDefault(): boolean { + if (this.nameBeforeAs === 'default') { + return true; + } + return this.importType === 'Identifier'; + } + + public validate(): ArkError { + return this.validateFields(['declaringArkFile']); + } +} diff --git a/ets2panda/linter/arkanalyzer/src/core/model/ArkMetadata.ts b/ets2panda/linter/arkanalyzer/src/core/model/ArkMetadata.ts new file mode 100644 index 0000000000..76e7cd36e6 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/model/ArkMetadata.ts @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { FullPosition } from '../base/Position'; + +export enum ArkMetadataKind { + LEADING_COMMENTS, + TRAILING_COMMENTS, +} + +export interface ArkMetadataType { +} + +/** + * ArkMetadata + * @example + * // get leading comments + * let stmt: Stmt = xxx; + * let comments = stmt.getMetadata(ArkMetadataKind.LEADING_COMMENTS) || []; + * comments.forEach((comment) => { + * logger.info(comment); + * }); + */ +export class ArkMetadata { + protected metadata?: Map; + + public getMetadata(kind: ArkMetadataKind): ArkMetadataType | undefined { + return this.metadata?.get(kind); + } + + public setMetadata(kind: ArkMetadataKind, value: ArkMetadataType): void { + if (!this.metadata) { + this.metadata = new Map(); + } + this.metadata.set(kind, value); + } +} + +export type CommentItem = { + content: string, + position: FullPosition +}; + +export class CommentsMetadata implements ArkMetadataType { + private comments: CommentItem[] = []; + + constructor(comments: CommentItem[]) { + this.comments = comments; + } + + public getComments(): CommentItem[] { + return this.comments; + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/model/ArkMethod.ts b/ets2panda/linter/arkanalyzer/src/core/model/ArkMethod.ts new file mode 100644 index 0000000000..0f3f704fc8 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/model/ArkMethod.ts @@ -0,0 +1,694 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkParameterRef, ArkThisRef } from '../base/Ref'; +import { ArkAssignStmt, ArkReturnStmt, Stmt } from '../base/Stmt'; +import { ClassType, FunctionType, GenericType, LiteralType, NumberType, Type, UnionType } from '../base/Type'; +import { Value } from '../base/Value'; +import { Cfg } from '../graph/Cfg'; +import { ViewTree } from '../graph/ViewTree'; +import { ArkBody } from './ArkBody'; +import { ArkClass, ClassCategory } from './ArkClass'; +import { MethodSignature } from './ArkSignature'; +import { BodyBuilder } from './builder/BodyBuilder'; +import { ArkExport, ExportType } from './ArkExport'; +import { ANONYMOUS_METHOD_PREFIX, DEFAULT_ARK_METHOD_NAME } from '../common/Const'; +import { getColNo, getLineNo, LineCol, setCol, setLine } from '../base/Position'; +import { ArkBaseModel, ModifierType } from './ArkBaseModel'; +import { ArkError, ArkErrorCode } from '../common/ArkError'; +import { CALL_BACK } from '../common/EtsConst'; +import { Scene } from '../../Scene'; +import { Constant } from '../base/Constant'; +import { Local } from '../base/Local'; +import { Language } from './ArkFile'; +import { CONSTRUCTOR_NAME } from '../common/TSConst'; + +export const arkMethodNodeKind = ['MethodDeclaration', 'Constructor', 'FunctionDeclaration', 'GetAccessor', + 'SetAccessor', 'ArrowFunction', 'FunctionExpression', 'MethodSignature', 'ConstructSignature', 'CallSignature']; + +/** + * @category core/model + */ +export class ArkMethod extends ArkBaseModel implements ArkExport { + private code?: string; + private declaringArkClass!: ArkClass; + // used for the nested function to locate its outer function + private outerMethod?: ArkMethod; + + private genericTypes?: GenericType[]; + + private methodDeclareSignatures?: MethodSignature[]; + private methodDeclareLineCols?: LineCol[]; + + private methodSignature?: MethodSignature; + private lineCol?: LineCol; + + private body?: ArkBody; + private viewTree?: ViewTree; + + private bodyBuilder?: BodyBuilder; + + private isGeneratedFlag: boolean = false; + private asteriskToken: boolean = false; + private questionToken: boolean = false; + + constructor() { + super(); + } + + /** + * Returns the program language of the file where this method defined. + */ + public getLanguage(): Language { + return this.getDeclaringArkClass().getLanguage(); + } + + public getExportType(): ExportType { + return ExportType.METHOD; + } + + public getName() { + return this.getSignature().getMethodSubSignature().getMethodName(); + } + + /** + * Returns the codes of method as a **string.** + * @returns the codes of method. + */ + public getCode() { + return this.code; + } + + public setCode(code: string) { + this.code = code; + } + + /** + * Get all lines of the method's declarations or null if the method has no seperated declaration. + * @returns null or the lines of the method's declarations with number type. + */ + public getDeclareLines(): number[] | null { + if (this.methodDeclareLineCols === undefined) { + return null; + } + let lines: number[] = []; + this.methodDeclareLineCols.forEach(lineCol => { + lines.push(getLineNo(lineCol)); + }); + return lines; + } + + /** + * Get all columns of the method's declarations or null if the method has no seperated declaration. + * @returns null or the columns of the method's declarations with number type. + */ + public getDeclareColumns(): number[] | null { + if (this.methodDeclareLineCols === undefined) { + return null; + } + let columns: number[] = []; + this.methodDeclareLineCols.forEach(lineCol => { + columns.push(getColNo(lineCol)); + }); + return columns; + } + + /** + * Set lines and columns of the declarations with number type inputs and then encoded them to LineCol type. + * The length of lines and columns should be the same otherwise they cannot be encoded together. + * @param lines - the number of lines. + * @param columns - the number of columns. + * @returns + */ + public setDeclareLinesAndCols(lines: number[], columns: number[]): void { + if (lines?.length !== columns?.length) { + return; + } + this.methodDeclareLineCols = []; + lines.forEach((line, index) => { + let lineCol: LineCol = 0; + lineCol = setLine(lineCol, line); + lineCol = setCol(lineCol, columns[index]); + (this.methodDeclareLineCols as LineCol[]).push(lineCol); + }); + } + + /** + * Set lineCols of the declarations directly with LineCol type input. + * @param lineCols - the encoded lines and columns with LineCol type. + * @returns + */ + public setDeclareLineCols(lineCols: LineCol[]): void { + this.methodDeclareLineCols = lineCols; + } + + /** + * Get encoded lines and columns of the method's declarations or null if the method has no seperated declaration. + * @returns null or the encoded lines and columns of the method's declarations with LineCol type. + */ + public getDeclareLineCols(): LineCol[] | null { + return this.methodDeclareLineCols ?? null; + } + + /** + * Get line of the method's implementation or null if the method has no implementation. + * @returns null or the number of the line. + */ + public getLine(): number | null { + if (this.lineCol === undefined) { + return null; + } + return getLineNo(this.lineCol); + } + + /** + * Set line of the implementation with line number input. + * The line number will be encoded together with the original column number. + * @param line - the line number of the method implementation. + * @returns + */ + public setLine(line: number): void { + if (this.lineCol === undefined) { + this.lineCol = 0; + } + this.lineCol = setLine(this.lineCol, line); + } + + /** + * Get column of the method's implementation or null if the method has no implementation. + * @returns null or the number of the column. + */ + public getColumn(): number | null { + if (this.lineCol === undefined) { + return null; + } + return getColNo(this.lineCol); + } + + /** + * Set column of the implementation with column number input. + * The column number will be encoded together with the original line number. + * @param column - the column number of the method implementation. + * @returns + */ + public setColumn(column: number): void { + if (this.lineCol === undefined) { + this.lineCol = 0; + } + this.lineCol = setCol(this.lineCol, column); + } + + /** + * Get encoded line and column of the method's implementation or null if the method has no implementation. + * @returns null or the encoded line and column of the method's implementation with LineCol type. + */ + public getLineCol(): LineCol | null { + return this.lineCol ?? null; + } + + /** + * Set lineCol of the implementation directly with LineCol type input. + * @param lineCol - the encoded line and column with LineCol type. + * @returns + */ + public setLineCol(lineCol: LineCol): void { + this.lineCol = lineCol; + } + + /** + * Returns the declaring class of the method. + * @returns The declaring class of the method. + */ + public getDeclaringArkClass() { + return this.declaringArkClass; + } + + public setDeclaringArkClass(declaringArkClass: ArkClass) { + this.declaringArkClass = declaringArkClass; + } + + public getDeclaringArkFile() { + return this.declaringArkClass.getDeclaringArkFile(); + } + + public isDefaultArkMethod(): boolean { + return this.getName() === DEFAULT_ARK_METHOD_NAME; + } + + public isAnonymousMethod(): boolean { + return this.getName().startsWith(ANONYMOUS_METHOD_PREFIX); + } + + public getParameters() { + return this.getSignature().getMethodSubSignature().getParameters(); + } + + public getReturnType() { + return this.getSignature().getType(); + } + + /** + * Get all declare signatures. + * The results could be null if there is no seperated declaration of the method. + * @returns null or the method declare signatures. + */ + public getDeclareSignatures(): MethodSignature[] | null { + return this.methodDeclareSignatures ?? null; + } + + /** + * Get the index of the matched method declare signature among all declare signatures. + * The index will be -1 if there is no matched signature found. + * @param targetSignature - the target declare signature want to search. + * @returns -1 or the index of the matched signature. + */ + public getDeclareSignatureIndex(targetSignature: MethodSignature): number { + let declareSignatures = this.methodDeclareSignatures; + if (declareSignatures === undefined) { + return -1; + } + for (let i = 0; i < declareSignatures.length; i++) { + if (declareSignatures[i].isMatch(targetSignature)) { + return i; + } + } + return -1; + } + + /** + * Get the method signature of the implementation. + * The signature could be null if the method is only a declaration which body is undefined. + * @returns null or the method implementation signature. + */ + public getImplementationSignature(): MethodSignature | null { + return this.methodSignature ?? null; + } + + /** + * Get the method signature of the implementation or the first declaration if there is no implementation. + * For a method, the implementation and declaration signatures must not be undefined at the same time. + * A {@link MethodSignature} includes: + * - Class Signature: indicates which class this method belong to. + * - Method SubSignature: indicates the detail info of this method such as method name, parameters, returnType, etc. + * @returns The method signature. + * @example + * 1. Get the signature of method mtd. + + ```typescript + let signature = mtd.getSignature(); + // ... ... + ``` + */ + public getSignature(): MethodSignature { + return this.methodSignature ?? (this.methodDeclareSignatures as MethodSignature[])[0]; + } + + /** + * Set signatures of all declarations. + * It will reset the declaration signatures if they are already defined before. + * @param signatures - one signature or a list of signatures. + * @returns + */ + public setDeclareSignatures(signatures: MethodSignature | MethodSignature[]): void { + if (Array.isArray(signatures)) { + this.methodDeclareSignatures = signatures; + } else { + this.methodDeclareSignatures = [signatures]; + } + } + + /** + * Reset signature of one declaration with the specified index. + * Will do nothing if the index doesn't exist. + * @param signature - new signature want to set. + * @param index - index of signature want to set. + * @returns + */ + public setDeclareSignatureWithIndex(signature: MethodSignature, index: number): void { + if (this.methodDeclareSignatures === undefined || this.methodDeclareSignatures.length <= index) { + return; + } + this.methodDeclareSignatures[index] = signature; + } + + /** + * Set signature of implementation. + * It will reset the implementation signature if it is already defined before. + * @param signature - signature of implementation. + * @returns + */ + public setImplementationSignature(signature: MethodSignature): void { + this.methodSignature = signature; + } + + public getSubSignature() { + return this.getSignature().getMethodSubSignature(); + } + + public getGenericTypes(): GenericType[] | undefined { + return this.genericTypes; + } + + public isGenericsMethod(): boolean { + return this.genericTypes !== undefined; + } + + public setGenericTypes(genericTypes: GenericType[]): void { + this.genericTypes = genericTypes; + } + + public getBodyBuilder(): BodyBuilder | undefined { + return this.bodyBuilder; + } + + /** + * Get {@link ArkBody} of a Method. + * A {@link ArkBody} contains the CFG and actual instructions or operations to be executed for a method. + * It is analogous to the body of a function or method in high-level programming languages, + * which contains the statements and expressions that define what the function does. + * @returns The {@link ArkBody} of a method. + * @example + * 1. Get cfg or stmt through ArkBody. + + ```typescript + let cfg = this.scene.getMethod()?.getBody().getCfg(); + const body = arkMethod.getBody() + ``` + + 2. Get local variable through ArkBody. + + ```typescript + arkClass.getDefaultArkMethod()?.getBody().getLocals.forEach(local=>{...}) + let locals = arkFile().getDefaultClass().getDefaultArkMethod()?.getBody()?.getLocals(); + ``` + */ + public getBody(): ArkBody | undefined { + return this.body; + } + + public setBody(body: ArkBody) { + this.body = body; + } + + /** + * Get the CFG (i.e., control flow graph) of a method. + * The CFG is a graphical representation of all possible control flow paths within a method's body. + * A CFG consists of blocks, statements and goto control jumps. + * @returns The CFG (i.e., control flow graph) of a method. + * @example + * 1. get stmt through ArkBody cfg. + + ```typescript + body = arkMethod.getBody(); + const cfg = body.getCfg(); + for (const threeAddressStmt of cfg.getStmts()) { + ... ... + } + ``` + + 2. get blocks through ArkBody cfg. + + ```typescript + const body = arkMethod.getBody(); + const blocks = [...body.getCfg().getBlocks()]; + for (let i=0; i stmts.push(stmt)); + } + let results: Value[] = []; + for (let stmt of stmts) { + if (stmt instanceof ArkAssignStmt) { + if (stmt.getRightOp() instanceof ArkParameterRef) { + results.push((stmt as ArkAssignStmt).getLeftOp()); + } + } + if (results.length === this.getParameters().length) { + return results; + } + } + return results; + } + + public getThisInstance(): Value | null { + // 获取方法体中This实例 + let stmts: Stmt[] = []; + if (this.getCfg()) { + const cfg = this.getCfg() as Cfg; + cfg.getStmts().forEach(stmt => stmts.push(stmt)); + } + for (let stmt of stmts) { + if (stmt instanceof ArkAssignStmt) { + if (stmt.getRightOp() instanceof ArkThisRef) { + return stmt.getLeftOp(); + } + } + } + return null; + } + + public getReturnValues(): Value[] { + // 获取方法体中return值实例 + let resultValues: Value[] = []; + this.getCfg()?.getStmts().forEach(stmt => { + if (stmt instanceof ArkReturnStmt) { + resultValues.push(stmt.getOp()); + } + }); + return resultValues; + } + + public getReturnStmt(): Stmt[] { + return this.getCfg()!.getStmts().filter(stmt => stmt instanceof ArkReturnStmt); + } + + public setViewTree(viewTree: ViewTree) { + this.viewTree = viewTree; + } + + public getViewTree(): ViewTree | undefined { + return this.viewTree; + } + + public hasViewTree(): boolean { + return this.viewTree !== undefined; + } + + public setBodyBuilder(bodyBuilder: BodyBuilder) { + this.bodyBuilder = bodyBuilder; + if (this.getDeclaringArkFile().getScene().buildClassDone()) { + this.buildBody(); + } + } + + public freeBodyBuilder(): void { + this.bodyBuilder = undefined; + } + + public buildBody() { + if (this.bodyBuilder) { + const arkBody: ArkBody | null = this.bodyBuilder.build(); + if (arkBody) { + this.setBody(arkBody); + arkBody.getCfg().setDeclaringMethod(this); + if (this.getOuterMethod() === undefined) { + this.bodyBuilder.handleGlobalAndClosure(); + } + } + } + } + + public isGenerated(): boolean { + return this.isGeneratedFlag; + } + + public setIsGeneratedFlag(isGeneratedFlag: boolean) { + this.isGeneratedFlag = isGeneratedFlag; + } + + public getAsteriskToken(): boolean { + return this.asteriskToken; + } + + public setAsteriskToken(asteriskToken: boolean) { + this.asteriskToken = asteriskToken; + } + + public validate(): ArkError { + const declareSignatures = this.getDeclareSignatures(); + const declareLineCols = this.getDeclareLineCols(); + const signature = this.getImplementationSignature(); + const lineCol = this.getLineCol(); + + if (declareSignatures === null && signature === null) { + return { + errCode: ArkErrorCode.METHOD_SIGNATURE_UNDEFINED, + errMsg: 'methodDeclareSignatures and methodSignature are both undefined.' + }; + } + if ((declareSignatures === null) !== (declareLineCols === null)) { + return { + errCode: ArkErrorCode.METHOD_SIGNATURE_LINE_UNMATCHED, + errMsg: 'methodDeclareSignatures and methodDeclareLineCols are not matched.' + }; + } + if (declareSignatures !== null && declareLineCols !== null && declareSignatures.length !== declareLineCols.length) { + return { + errCode: ArkErrorCode.METHOD_SIGNATURE_LINE_UNMATCHED, + errMsg: 'methodDeclareSignatures and methodDeclareLineCols are not matched.' + }; + } + if ((signature === null) !== (lineCol === null)) { + return { + errCode: ArkErrorCode.METHOD_SIGNATURE_LINE_UNMATCHED, + errMsg: 'methodSignature and lineCol are not matched.' + }; + } + return this.validateFields(['declaringArkClass']); + } + + public matchMethodSignature(args: Value[]): MethodSignature { + const signatures = this.methodDeclareSignatures?.filter(f => { + const parameters = f.getMethodSubSignature().getParameters(); + const max = parameters.length; + let min = 0; + while (min < max && !parameters[min].isOptional()) { + min++; + } + return args.length >= min && args.length <= max; + }); + const scene = this.getDeclaringArkFile().getScene(); + return signatures?.find(p => { + const parameters = p.getMethodSubSignature().getParameters(); + for (let i = 0; i < parameters.length; i++) { + if (!args[i]) { + return parameters[i].isOptional(); + } + const isMatched = this.matchParam(parameters[i].getType(), args[i], scene); + if (!isMatched) { + return false; + } + } + return true; + }) ?? signatures?.[0] ?? this.getSignature(); + } + + private matchParam(paramType: Type, arg: Value, scene: Scene): boolean { + const argType = arg.getType(); + if (arg instanceof Local) { + const stmt = arg.getDeclaringStmt(); + if (stmt instanceof ArkAssignStmt && stmt.getRightOp() instanceof Constant) { + arg = stmt.getRightOp(); + } + } + if (paramType instanceof UnionType) { + let matched = false; + for (const e of paramType.getTypes()) { + if (argType.constructor === e.constructor) { + matched = true; + break; + } + } + return matched; + } else if (argType instanceof FunctionType && paramType instanceof FunctionType) { + return argType.getMethodSignature().getParamLength() === paramType.getMethodSignature().getParamLength(); + } else if (argType instanceof FunctionType && paramType instanceof ClassType && + paramType.getClassSignature().getClassName().includes(CALL_BACK)) { + return true; + } else if (paramType instanceof LiteralType && arg instanceof Constant) { + return arg.getValue().replace(/[\"|\']/g, '') === paramType.getLiteralName() + .toString().replace(/[\"|\']/g, ''); + } else if (paramType instanceof NumberType && argType instanceof ClassType && ClassCategory.ENUM === + scene.getClass(argType.getClassSignature())?.getCategory()) { + return true; + } + return argType.constructor === paramType.constructor; + } + + public getOuterMethod(): ArkMethod | undefined { + return this.outerMethod; + } + + public setOuterMethod(method: ArkMethod): void { + this.outerMethod = method; + } + + public getFunctionLocal(name: string): Local | null { + const local = this.getBody()?.getLocals().get(name); + return local?.getType() instanceof FunctionType ? local : null; + } + + public setQuestionToken(questionToken: boolean): void { + this.questionToken = questionToken; + } + + public getQuestionToken(): boolean { + return this.questionToken; + } + + // For class method, if there is no public/private/protected access modifier, it is actually public + public isPublic(): boolean { + if (!this.containsModifier(ModifierType.PUBLIC) && + !this.containsModifier(ModifierType.PRIVATE) && + !this.containsModifier(ModifierType.PROTECTED) && + !this.getDeclaringArkClass().isDefaultArkClass() && + !this.isGenerated() && + !this.isAnonymousMethod() && + this.getName() !== CONSTRUCTOR_NAME && + this.getDeclaringArkClass().getCategory() === ClassCategory.CLASS) { + return true; + } + return this.containsModifier(ModifierType.PUBLIC); + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/model/ArkNamespace.ts b/ets2panda/linter/arkanalyzer/src/core/model/ArkNamespace.ts new file mode 100644 index 0000000000..b6fb1659c6 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/model/ArkNamespace.ts @@ -0,0 +1,273 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkExport, ExportInfo, ExportType } from './ArkExport'; +import { ArkClass } from './ArkClass'; +import { ArkFile, Language } from './ArkFile'; +import { ArkMethod } from './ArkMethod'; +import { AliasClassSignature, ClassSignature, NamespaceSignature } from './ArkSignature'; +import { ALL } from '../common/TSConst'; +import { getColNo, getLineNo, LineCol, setCol, setLine, setLineCol } from '../base/Position'; +import { ArkBaseModel } from './ArkBaseModel'; +import { ArkError } from '../common/ArkError'; + +/** + * @category core/model + */ +export class ArkNamespace extends ArkBaseModel implements ArkExport { + private sourceCodes: string[] = ['']; + private lineCols: LineCol[] = []; + + private declaringArkFile!: ArkFile; + private declaringArkNamespace: ArkNamespace | null = null; + + private declaringInstance!: ArkFile | ArkNamespace; + + private exportInfos: Map = new Map(); + + private defaultClass!: ArkClass; + + // name to model + private namespaces: Map = new Map(); // don't contain nested namespace + private classes: Map = new Map(); + + private namespaceSignature!: NamespaceSignature; + + private anonymousClassNumber: number = 0; + + constructor() { + super(); + } + + /** + * Returns the program language of the file where this namespace defined. + */ + public getLanguage(): Language { + return this.getDeclaringArkFile().getLanguage(); + } + + public addNamespace(namespace: ArkNamespace) { + this.namespaces.set(namespace.getName(), namespace); + } + + public getNamespace(namespaceSignature: NamespaceSignature): ArkNamespace | null { + const namespaceName = namespaceSignature.getNamespaceName(); + return this.getNamespaceWithName(namespaceName); + } + + public getNamespaceWithName(namespaceName: string): ArkNamespace | null { + return this.namespaces.get(namespaceName) || null; + } + + public getNamespaces(): ArkNamespace[] { + return Array.from(this.namespaces.values()); + } + + public setSignature(namespaceSignature: NamespaceSignature): void { + this.namespaceSignature = namespaceSignature; + } + + public getSignature() { + return this.namespaceSignature; + } + + public getNamespaceSignature() { + return this.namespaceSignature; + } + + public getName() { + return this.namespaceSignature.getNamespaceName(); + } + + public getCode() { + return this.sourceCodes[0]; + } + + public setCode(sourceCode: string) { + this.sourceCodes[0] = sourceCode; + } + + /* + * Get multiple sourceCodes when the arkNamespace is merged from multiple namespace with the same name + */ + public getCodes(): string[] { + return this.sourceCodes; + } + + /* + * Set multiple sourceCodes when the arkNamespace is merged from multiple namespace with the same name + */ + public setCodes(sourceCodes: string[]): void { + this.sourceCodes = []; + this.sourceCodes.push(...sourceCodes); + } + + public addCode(sourceCode: string): void { + this.sourceCodes.push(sourceCode); + } + + public getLine() { + return getLineNo(this.lineCols[0]); + } + + public setLine(line: number) { + this.lineCols[0] = setLine(this.lineCols[0], line); + } + + public getColumn() { + return getColNo(this.lineCols[0]); + } + + public setColumn(column: number) { + this.lineCols[0] = setCol(this.lineCols[0], column); + } + + public getLineColPairs(): [number, number][] { + const lineColPairs: [number, number][] = []; + this.lineCols.forEach(lineCol => { + lineColPairs.push([getLineNo(lineCol), getColNo(lineCol)]); + }); + return lineColPairs; + } + + public setLineCols(lineColPairs: [number, number][]): void { + this.lineCols = []; + lineColPairs.forEach(lineColPair => { + this.lineCols.push(setLineCol(lineColPair[0], lineColPair[1])); + }); + } + + public getDeclaringInstance() { + return this.declaringInstance; + } + + public setDeclaringInstance(declaringInstance: ArkFile | ArkNamespace) { + this.declaringInstance = declaringInstance; + } + + public getDeclaringArkFile() { + return this.declaringArkFile; + } + + public setDeclaringArkFile(declaringArkFile: ArkFile) { + this.declaringArkFile = declaringArkFile; + } + + public getDeclaringArkNamespace() { + return this.declaringArkNamespace; + } + + public setDeclaringArkNamespace(declaringArkNamespace: ArkNamespace) { + this.declaringArkNamespace = declaringArkNamespace; + } + + public getClass(classSignature: ClassSignature): ArkClass | null { + const className = classSignature instanceof AliasClassSignature ? classSignature.getOriginName() + : classSignature.getClassName(); + return this.getClassWithName(className); + } + + public getClassWithName(Class: string): ArkClass | null { + return this.classes.get(Class) || null; + } + + public getClasses(): ArkClass[] { + return Array.from(this.classes.values()); + } + + public addArkClass(arkClass: ArkClass) { + this.classes.set(arkClass.getName(), arkClass); + } + + public getExportInfos(): ExportInfo[] { + const exportInfos: ExportInfo[] = []; + this.exportInfos.forEach((value, key) => { + if (key !== ALL || value.getFrom()) { + exportInfos.push(value); + } + }); + return exportInfos; + } + + public getExportInfoBy(name: string): ExportInfo | undefined { + return this.exportInfos.get(name); + } + + public addExportInfo(exportInfo: ExportInfo) { + this.exportInfos.set(exportInfo.getExportClauseName(), exportInfo); + } + + public getDefaultClass() { + return this.defaultClass; + } + + public setDefaultClass(defaultClass: ArkClass) { + this.defaultClass = defaultClass; + } + + public getAllMethodsUnderThisNamespace(): ArkMethod[] { + let methods: ArkMethod[] = []; + this.classes.forEach((cls) => { + methods.push(...cls.getMethods()); + }); + this.namespaces.forEach((ns) => { + methods.push(...ns.getAllMethodsUnderThisNamespace()); + }); + return methods; + } + + public getAllClassesUnderThisNamespace(): ArkClass[] { + let classes: ArkClass[] = []; + classes.push(...this.classes.values()); + this.namespaces.forEach((ns) => { + classes.push(...ns.getAllClassesUnderThisNamespace()); + }); + return classes; + } + + public getAllNamespacesUnderThisNamespace(): ArkNamespace[] { + let namespaces: ArkNamespace[] = []; + namespaces.push(...this.namespaces.values()); + this.namespaces.forEach((ns) => { + namespaces.push(...ns.getAllNamespacesUnderThisNamespace()); + }); + return namespaces; + } + + public getAnonymousClassNumber() { + return this.anonymousClassNumber++; + } + + getExportType(): ExportType { + return ExportType.NAME_SPACE; + } + + public removeArkClass(arkClass: ArkClass): boolean { + let rtn = this.classes.delete(arkClass.getName()); + rtn &&= this.getDeclaringArkFile().getScene().removeClass(arkClass); + return rtn; + } + + public removeNamespace(namespace: ArkNamespace): boolean { + let rtn = this.namespaces.delete(namespace.getName()); + rtn &&= this.getDeclaringArkFile().getScene().removeNamespace(namespace); + return rtn; + } + + public validate(): ArkError { + return this.validateFields(['declaringArkFile', 'declaringInstance', 'namespaceSignature', 'defaultClass']); + } +} + diff --git a/ets2panda/linter/arkanalyzer/src/core/model/ArkSignature.ts b/ets2panda/linter/arkanalyzer/src/core/model/ArkSignature.ts new file mode 100644 index 0000000000..a7d875221a --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/model/ArkSignature.ts @@ -0,0 +1,498 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import path from 'path'; +import { transfer2UnixPath } from '../../utils/pathTransfer'; +import { ClassType, Type } from '../base/Type'; +import { MethodParameter } from './builder/ArkMethodBuilder'; +import { + ANONYMOUS_CLASS_PREFIX, + LEXICAL_ENV_NAME_PREFIX, + NAME_DELIMITER, + UNKNOWN_CLASS_NAME, + UNKNOWN_FILE_NAME, + UNKNOWN_NAMESPACE_NAME, + UNKNOWN_PROJECT_NAME +} from '../common/Const'; +import { CryptoUtils } from '../../utils/crypto_utils'; + +export type Signature = + FileSignature + | NamespaceSignature + | ClassSignature + | MethodSignature + | FieldSignature + | LocalSignature + | AliasTypeSignature; + +export interface ArkSignature { + getSignature(): Signature; +} + +/** + * @category core/model + */ +export class FileSignature { + private projectName: string; + private fileName: string; + private hashcode: number; + + public static readonly DEFAULT: FileSignature = new FileSignature(UNKNOWN_PROJECT_NAME, UNKNOWN_FILE_NAME); + + constructor(projectName: string, fileName: string) { + this.projectName = projectName; + this.fileName = transfer2UnixPath(fileName); + this.hashcode = CryptoUtils.hashcode(this.toString()); + } + + public getProjectName() { + return this.projectName; + } + + public getFileName() { + return this.fileName; + } + + public toString(): string { + return `@${this.projectName}/${this.fileName}: `; + } + + public toMapKey(): string { + return `${this.hashcode}${path.basename(this.fileName)}`; + } +} + +export class NamespaceSignature { + private namespaceName: string; + private declaringFileSignature: FileSignature; + private declaringNamespaceSignature: NamespaceSignature | null; + + public static readonly DEFAULT: NamespaceSignature = new NamespaceSignature(UNKNOWN_NAMESPACE_NAME, + FileSignature.DEFAULT, null); + + constructor(namespaceName: string, declaringFileSignature: FileSignature, + declaringNamespaceSignature: NamespaceSignature | null = null) { + this.namespaceName = namespaceName; + this.declaringFileSignature = declaringFileSignature; + this.declaringNamespaceSignature = declaringNamespaceSignature; + } + + public getNamespaceName() { + return this.namespaceName; + } + + public getDeclaringFileSignature() { + return this.declaringFileSignature; + } + + public getDeclaringNamespaceSignature() { + return this.declaringNamespaceSignature; + } + + public toString(): string { + if (this.declaringNamespaceSignature) { + return this.declaringNamespaceSignature.toString() + '.' + this.namespaceName; + } else { + return this.declaringFileSignature.toString() + this.namespaceName; + } + } + + public toMapKey(): string { + if (this.declaringNamespaceSignature) { + return this.declaringNamespaceSignature.toMapKey() + '.' + this.namespaceName; + } else { + return this.declaringFileSignature.toMapKey() + this.namespaceName; + } + } +} + +export class ClassSignature { + private declaringFileSignature: FileSignature; + private declaringNamespaceSignature: NamespaceSignature | null; + private className: string; + + public static readonly DEFAULT: ClassSignature = new ClassSignature(UNKNOWN_CLASS_NAME, FileSignature.DEFAULT, + null); + + constructor(className: string, declaringFileSignature: FileSignature, + declaringNamespaceSignature: NamespaceSignature | null = null) { + this.className = className; + this.declaringFileSignature = declaringFileSignature; + this.declaringNamespaceSignature = declaringNamespaceSignature; + } + + /** + * Returns the declaring file signature. + * @returns The declaring file signature. + */ + public getDeclaringFileSignature() { + return this.declaringFileSignature; + } + + /** + * Get the declaring namespace's signature. + * @returns the declaring namespace's signature. + */ + public getDeclaringNamespaceSignature() { + return this.declaringNamespaceSignature; + } + + /** + * Get the **string** name of class from the the class signature. The default value is `""`. + * @returns The name of this class. + */ + public getClassName() { + return this.className; + } + + /** + * + * @returns The name of the declare class. + */ + public getDeclaringClassName(): string { + if (this.className.startsWith(ANONYMOUS_CLASS_PREFIX)) { + let temp = this.className; + do { + temp = temp.substring(temp.indexOf(NAME_DELIMITER) + 1, temp.lastIndexOf('.')); + } while (temp.startsWith(ANONYMOUS_CLASS_PREFIX)); + return temp; + } + return this.className; + } + + public setClassName(className: string) { + this.className = className; + } + + public getType(): ClassType { + return new ClassType(this); + } + + public toString(): string { + if (this.declaringNamespaceSignature) { + return this.declaringNamespaceSignature.toString() + '.' + this.className; + } else { + return this.declaringFileSignature.toString() + this.className; + } + } + + public toMapKey(): string { + if (this.declaringNamespaceSignature) { + return this.declaringNamespaceSignature.toMapKey() + '.' + this.className; + } else { + return this.declaringFileSignature.toMapKey() + this.className; + } + } +} + +/** + * `AliasClassSignature` is used to extend `ClassSignature`, preserving the actual name used during invocation. + */ +export class AliasClassSignature extends ClassSignature { + private readonly aliasName: string; + + constructor(aliasName: string, signature: ClassSignature) { + super(signature.getClassName(), signature.getDeclaringFileSignature(), signature.getDeclaringNamespaceSignature()); + this.aliasName = aliasName; + } + + /** + * Returns the name used in the code. + */ + public getClassName(): string { + return this.aliasName; + } + + /** + * Return the original name of declared class + */ + public getOriginName(): string { + return super.getClassName(); + } +} + +export type BaseSignature = ClassSignature | NamespaceSignature; + +export class FieldSignature { + private declaringSignature: BaseSignature; + private fieldName: string; + private type: Type; + private staticFlag: boolean; + + constructor(fieldName: string, declaringSignature: BaseSignature, type: Type, staticFlag: boolean = false) { + this.fieldName = fieldName; + this.declaringSignature = declaringSignature; + this.type = type; + this.staticFlag = staticFlag; + } + + public getDeclaringSignature() { + return this.declaringSignature; + } + + public getBaseName() { + return this.declaringSignature instanceof ClassSignature ? this.declaringSignature.getClassName() + : this.declaringSignature.getNamespaceName(); + } + + public getFieldName() { + return this.fieldName; + } + + public getType(): Type { + return this.type; + } + + public isStatic(): boolean { + return this.staticFlag; + } + + // temp for being compatible with existing type inference + public setType(type: Type): void { + this.type = type; + } + + // temp for being compatible with existing type inference + public setStaticFlag(flag: boolean): void { + this.staticFlag = flag; + } + + public toString(): string { + let tmpSig = this.fieldName; + if (this.isStatic()) { + tmpSig = '[static]' + tmpSig; + } + return this.getDeclaringSignature().toString() + '.' + tmpSig; + } +} + +export class MethodSubSignature { + private methodName: string; + private parameters: MethodParameter[]; + private returnType: Type; + private staticFlag: boolean; + + constructor(methodName: string, parameters: MethodParameter[], returnType: Type, staticFlag: boolean = false) { + this.methodName = methodName; + this.parameters = parameters; + this.returnType = returnType; + this.staticFlag = staticFlag; + } + + public getMethodName() { + return this.methodName; + } + + public getParameters() { + return this.parameters; + } + + public getParameterTypes(): Type[] { + const parameterTypes: Type[] = []; + this.parameters.forEach((parameter) => { + parameterTypes.push(parameter.getType()); + }); + return parameterTypes; + } + + public getReturnType(): Type { + return this.returnType; + } + + public setReturnType(returnType: Type): void { + this.returnType = returnType; + } + + public isStatic(): boolean { + return this.staticFlag; + } + + public toString(ptrName?: string): string { + let paraStr = ""; + this.getParameterTypes().forEach((parameterType) => { + paraStr += parameterType.toString() + ", "; + }); + paraStr = paraStr.replace(/, $/, ''); + let tmpSig = `${ptrName ?? this.getMethodName()}(${paraStr})`; + if (this.isStatic()) { + tmpSig = '[static]' + tmpSig; + } + return tmpSig; + } +} + +/** + * @category core/model + */ +export class MethodSignature { + private declaringClassSignature: ClassSignature; + private methodSubSignature: MethodSubSignature; + + constructor(declaringClassSignature: ClassSignature, methodSubSignature: MethodSubSignature) { + this.declaringClassSignature = declaringClassSignature; + this.methodSubSignature = methodSubSignature; + } + + /** + * Return the declaring class signature. + * A {@link ClassSignature} includes: + * - File Signature: including the **string** names of the project and file, respectively. The default value of project's name is "%unk" and the default value of file's name is "%unk". + * - Namespace Signature | **null**: it may be a namespace signature or **null**. A namespace signature can indicate its **string** name of namespace and its file signature. + * - Class Name: the **string** name of this class. + * @returns The declaring class signature. + * @example + * 1. get class signature from ArkMethod. + + ```typescript + let methodSignature = expr.getMethodSignature(); + let name = methodSignature.getDeclaringClassSignature().getClassName(); + ``` + * + */ + public getDeclaringClassSignature() { + return this.declaringClassSignature; + } + + /** + * Returns the sub-signature of this method signature. + * The sub-signature is part of the method signature, which is used to + * identify the name of the method, its parameters and the return value type. + * @returns The sub-signature of this method signature. + */ + public getMethodSubSignature() { + return this.methodSubSignature; + } + + public getType(): Type { + return this.methodSubSignature.getReturnType(); + } + + public toString(ptrName?: string): string { + return this.declaringClassSignature.toString() + '.' + this.methodSubSignature.toString(ptrName); + } + + public toMapKey(): string { + return this.declaringClassSignature.toMapKey() + '.' + this.methodSubSignature.toString(); + } + + public isMatch(signature: MethodSignature): boolean { + return ((this.toString() === signature.toString()) && (this.getType().toString() === signature.getType().toString())); + } + + public getParamLength(): number { + return this.methodSubSignature.getParameters() + .filter(p => !p.getName().startsWith(LEXICAL_ENV_NAME_PREFIX)).length; + } +} + +export class LocalSignature { + private name: string; + private declaringMethodSignature: MethodSignature; + + constructor(name: string, declaringMethodSignature: MethodSignature) { + this.name = name; + this.declaringMethodSignature = declaringMethodSignature; + } + + public getName(): string { + return this.name; + } + + public getDeclaringMethodSignature(): MethodSignature { + return this.declaringMethodSignature; + } + + public toString(): string { + return this.declaringMethodSignature.toString() + '#' + this.name; + } +} + +export class AliasTypeSignature { + private name: string; + private declaringMethodSignature: MethodSignature; + + constructor(name: string, declaringMethodSignature: MethodSignature) { + this.name = name; + this.declaringMethodSignature = declaringMethodSignature; + } + + public getName(): string { + return this.name; + } + + public getDeclaringMethodSignature(): MethodSignature { + return this.declaringMethodSignature; + } + + public toString(): string { + return this.declaringMethodSignature.toString() + '#' + this.name; + } +} + +//TODO, reconstruct +export function fieldSignatureCompare(leftSig: FieldSignature, rightSig: FieldSignature): boolean { + if (leftSig.getDeclaringSignature().toString() === rightSig.getDeclaringSignature().toString() && + (leftSig.getFieldName() === rightSig.getFieldName())) { + return true; + } + return false; +} + +export function methodSignatureCompare(leftSig: MethodSignature, rightSig: MethodSignature): boolean { + if (classSignatureCompare(leftSig.getDeclaringClassSignature(), rightSig.getDeclaringClassSignature()) && + methodSubSignatureCompare(leftSig.getMethodSubSignature(), rightSig.getMethodSubSignature())) { + return true; + } + return false; +} + +export function methodSubSignatureCompare(leftSig: MethodSubSignature, rightSig: MethodSubSignature): boolean { + if ((leftSig.getMethodName() === rightSig.getMethodName()) && arrayCompare(leftSig.getParameterTypes(), + rightSig.getParameterTypes()) && leftSig.getReturnType() === rightSig.getReturnType()) { + return true; + } + return false; +} + +export function classSignatureCompare(leftSig: ClassSignature, rightSig: ClassSignature): boolean { + if ((fileSignatureCompare(leftSig.getDeclaringFileSignature(), rightSig.getDeclaringFileSignature())) && + (leftSig.getClassName() === rightSig.getClassName())) { + return true; + } + return false; +} + +export function fileSignatureCompare(leftSig: FileSignature, rightSig: FileSignature): boolean { + if ((leftSig.getFileName() === rightSig.getFileName()) && (leftSig.getProjectName() === rightSig.getProjectName())) { + return true; + } + return false; +} + +function arrayCompare(leftArray: any[], rightArray: any[]) { + if (leftArray.length !== rightArray.length) { + return false; + } + for (let i = 0; i < leftArray.length; i++) { + if (leftArray[i] !== rightArray[i]) { + return false; + } + } + return true; +} + +export function genSignature4ImportClause(arkFileName: string, importClauseName: string): string { + return `<${arkFileName}>.<${importClauseName}>`; +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkClassBuilder.ts b/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkClassBuilder.ts new file mode 100644 index 0000000000..62b1f124c0 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkClassBuilder.ts @@ -0,0 +1,522 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkField, FieldCategory } from '../ArkField'; +import { ArkFile } from '../ArkFile'; +import { ArkMethod } from '../ArkMethod'; +import { ArkNamespace } from '../ArkNamespace'; +import Logger, { LOG_MODULE_TYPE } from '../../../utils/logger'; +import ts, { ParameterDeclaration } from 'ohos-typescript'; +import { ArkClass, ClassCategory } from '../ArkClass'; +import { buildArkMethodFromArkClass, buildDefaultArkMethodFromArkClass, buildInitMethod, checkAndUpdateMethod } from './ArkMethodBuilder'; +import { buildDecorators, buildGenericType, buildHeritageClauses, buildModifiers, buildTypeParameters, tsNode2Type } from './builderUtils'; +import { buildGetAccessor2ArkField, buildIndexSignature2ArkField, buildProperty2ArkField } from './ArkFieldBuilder'; +import { ArkIRTransformer } from '../../common/ArkIRTransformer'; +import { ArkAssignStmt, ArkInvokeStmt, Stmt } from '../../base/Stmt'; +import { ArkInstanceFieldRef } from '../../base/Ref'; +import { + ANONYMOUS_CLASS_DELIMITER, + ANONYMOUS_CLASS_PREFIX, + DEFAULT_ARK_CLASS_NAME, + INSTANCE_INIT_METHOD_NAME, + STATIC_BLOCK_METHOD_NAME_PREFIX, + STATIC_INIT_METHOD_NAME, +} from '../../common/Const'; +import { IRUtils } from '../../common/IRUtils'; +import { ClassSignature, FieldSignature, MethodSignature, MethodSubSignature } from '../ArkSignature'; +import { ArkSignatureBuilder } from './ArkSignatureBuilder'; +import { FullPosition, LineColPosition } from '../../base/Position'; +import { Type, UnknownType, VoidType } from '../../base/Type'; +import { BodyBuilder } from './BodyBuilder'; +import { ArkStaticInvokeExpr } from '../../base/Expr'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'ArkClassBuilder'); + +export type ClassLikeNode = + ts.ClassDeclaration | + ts.InterfaceDeclaration | + ts.EnumDeclaration | + ts.ClassExpression | + ts.TypeLiteralNode | + ts.StructDeclaration | + ts.ObjectLiteralExpression; + +type ClassLikeNodeWithMethod = + ts.ClassDeclaration | + ts.InterfaceDeclaration | + ts.EnumDeclaration | + ts.ClassExpression | + ts.TypeLiteralNode | + ts.StructDeclaration; + +export function buildDefaultArkClassFromArkFile(arkFile: ArkFile, defaultClass: ArkClass, astRoot: ts.SourceFile) { + defaultClass.setDeclaringArkFile(arkFile); + defaultClass.setCategory(ClassCategory.CLASS); + buildDefaultArkClass(defaultClass, astRoot); +} + +export function buildDefaultArkClassFromArkNamespace(arkNamespace: ArkNamespace, defaultClass: ArkClass, + nsNode: ts.ModuleDeclaration, sourceFile: ts.SourceFile) { + defaultClass.setDeclaringArkNamespace(arkNamespace); + defaultClass.setDeclaringArkFile(arkNamespace.getDeclaringArkFile()); + buildDefaultArkClass(defaultClass, sourceFile, nsNode); +} + +export function buildNormalArkClassFromArkMethod(clsNode: ClassLikeNode, cls: ArkClass, sourceFile: ts.SourceFile, + declaringMethod?: ArkMethod) { + const namespace = cls.getDeclaringArkNamespace(); + if (namespace) { + buildNormalArkClassFromArkNamespace(clsNode, namespace, cls, sourceFile, declaringMethod); + } else { + buildNormalArkClassFromArkFile(clsNode, cls.getDeclaringArkFile(), cls, sourceFile, declaringMethod); + } +} + +export function buildNormalArkClassFromArkFile(clsNode: ClassLikeNode, arkFile: ArkFile, cls: ArkClass, + sourceFile: ts.SourceFile, declaringMethod?: ArkMethod) { + cls.setDeclaringArkFile(arkFile); + cls.setCode(clsNode.getText(sourceFile)); + const { line, character } = ts.getLineAndCharacterOfPosition( + sourceFile, + clsNode.getStart(sourceFile), + ); + cls.setLine(line + 1); + cls.setColumn(character + 1); + + buildNormalArkClass(clsNode, cls, sourceFile, declaringMethod); + arkFile.addArkClass(cls); +} + +export function buildNormalArkClassFromArkNamespace(clsNode: ClassLikeNode, arkNamespace: ArkNamespace, cls: ArkClass, + sourceFile: ts.SourceFile, declaringMethod?: ArkMethod) { + cls.setDeclaringArkNamespace(arkNamespace); + cls.setDeclaringArkFile(arkNamespace.getDeclaringArkFile()); + cls.setCode(clsNode.getText(sourceFile)); + const { line, character } = ts.getLineAndCharacterOfPosition( + sourceFile, + clsNode.getStart(sourceFile), + ); + cls.setLine(line + 1); + cls.setColumn(character + 1); + + buildNormalArkClass(clsNode, cls, sourceFile, declaringMethod); + arkNamespace.addArkClass(cls); +} + +function buildDefaultArkClass(cls: ArkClass, sourceFile: ts.SourceFile, node?: ts.ModuleDeclaration) { + const defaultArkClassSignature = new ClassSignature(DEFAULT_ARK_CLASS_NAME, + cls.getDeclaringArkFile().getFileSignature(), cls.getDeclaringArkNamespace()?.getSignature() || null); + cls.setSignature(defaultArkClassSignature); + + genDefaultArkMethod(cls, sourceFile, node); +} + +function genDefaultArkMethod(cls: ArkClass, sourceFile: ts.SourceFile, node?: ts.ModuleDeclaration) { + let defaultMethod = new ArkMethod(); + buildDefaultArkMethodFromArkClass(cls, defaultMethod, sourceFile, node); + cls.setDefaultArkMethod(defaultMethod); +} + +export function buildNormalArkClass(clsNode: ClassLikeNode, cls: ArkClass, sourceFile: ts.SourceFile, declaringMethod?: ArkMethod) { + switch (clsNode.kind) { + case ts.SyntaxKind.StructDeclaration: + buildStruct2ArkClass(clsNode, cls, sourceFile, declaringMethod); + break; + case ts.SyntaxKind.ClassDeclaration: + buildClass2ArkClass(clsNode, cls, sourceFile, declaringMethod); + break; + case ts.SyntaxKind.ClassExpression: + buildClass2ArkClass(clsNode, cls, sourceFile, declaringMethod); + break; + case ts.SyntaxKind.InterfaceDeclaration: + buildInterface2ArkClass(clsNode, cls, sourceFile, declaringMethod); + break; + case ts.SyntaxKind.EnumDeclaration: + buildEnum2ArkClass(clsNode, cls, sourceFile, declaringMethod); + break; + case ts.SyntaxKind.TypeLiteral: + buildTypeLiteralNode2ArkClass(clsNode, cls, sourceFile, declaringMethod); + break; + case ts.SyntaxKind.ObjectLiteralExpression: + buildObjectLiteralExpression2ArkClass(clsNode, cls, sourceFile, declaringMethod); + break; + default: + ; + } + IRUtils.setComments(cls, clsNode, sourceFile, cls.getDeclaringArkFile().getScene().getOptions()); +} + +function init4InstanceInitMethod(cls: ArkClass) { + const instanceInit = new ArkMethod(); + instanceInit.setDeclaringArkClass(cls); + instanceInit.setIsGeneratedFlag(true); + const methodSubSignature = ArkSignatureBuilder.buildMethodSubSignatureFromMethodName(INSTANCE_INIT_METHOD_NAME); + methodSubSignature.setReturnType(VoidType.getInstance()); + const methodSignature = new MethodSignature(instanceInit.getDeclaringArkClass().getSignature(), + methodSubSignature); + instanceInit.setImplementationSignature(methodSignature); + instanceInit.setLineCol(0); + + checkAndUpdateMethod(instanceInit, cls); + cls.addMethod(instanceInit); + cls.setInstanceInitMethod(instanceInit); +} + +function init4StaticInitMethod(cls: ArkClass) { + const staticInit = new ArkMethod(); + staticInit.setDeclaringArkClass(cls); + staticInit.setIsGeneratedFlag(true); + const methodSubSignature = ArkSignatureBuilder.buildMethodSubSignatureFromMethodName(STATIC_INIT_METHOD_NAME); + methodSubSignature.setReturnType(VoidType.getInstance()); + const methodSignature = new MethodSignature(staticInit.getDeclaringArkClass().getSignature(), + methodSubSignature); + staticInit.setImplementationSignature(methodSignature); + staticInit.setLineCol(0); + + checkAndUpdateMethod(staticInit, cls); + cls.addMethod(staticInit); + cls.setStaticInitMethod(staticInit); +} + +function buildStruct2ArkClass(clsNode: ts.StructDeclaration, cls: ArkClass, sourceFile: ts.SourceFile, declaringMethod?: ArkMethod) { + const className = genClassName(clsNode.name ? clsNode.name.text : '', cls, declaringMethod); + const classSignature = new ClassSignature(className, + cls.getDeclaringArkFile().getFileSignature(), cls.getDeclaringArkNamespace()?.getSignature() || null); + cls.setSignature(classSignature); + + if (clsNode.typeParameters) { + buildTypeParameters(clsNode.typeParameters, sourceFile, cls).forEach((typeParameter) => { + cls.addGenericType(typeParameter); + }); + } + + initHeritage(buildHeritageClauses(clsNode.heritageClauses), cls); + + cls.setModifiers(buildModifiers(clsNode)); + cls.setDecorators(buildDecorators(clsNode, sourceFile)); + + cls.setCategory(ClassCategory.STRUCT); + init4InstanceInitMethod(cls); + init4StaticInitMethod(cls); + buildArkClassMembers(clsNode, cls, sourceFile); +} + +function buildClass2ArkClass(clsNode: ts.ClassDeclaration | ts.ClassExpression, cls: ArkClass, sourceFile: ts.SourceFile, declaringMethod?: ArkMethod) { + const className = genClassName(clsNode.name ? clsNode.name.text : '', cls, declaringMethod); + const classSignature = new ClassSignature(className, + cls.getDeclaringArkFile().getFileSignature(), cls.getDeclaringArkNamespace()?.getSignature() || null); + cls.setSignature(classSignature); + + if (clsNode.typeParameters) { + buildTypeParameters(clsNode.typeParameters, sourceFile, cls).forEach((typeParameter) => { + cls.addGenericType(typeParameter); + }); + } + + initHeritage(buildHeritageClauses(clsNode.heritageClauses), cls); + + cls.setModifiers(buildModifiers(clsNode)); + cls.setDecorators(buildDecorators(clsNode, sourceFile)); + + cls.setCategory(ClassCategory.CLASS); + init4InstanceInitMethod(cls); + init4StaticInitMethod(cls); + buildArkClassMembers(clsNode, cls, sourceFile); +} + +function initHeritage(heritageClauses: Map, cls: ArkClass): void { + let superName = ''; + for (let [key, value] of heritageClauses) { + if (value === ts.SyntaxKind[ts.SyntaxKind.ExtendsKeyword]) { + superName = key; + break; + } + } + cls.addHeritageClassName(superName); + for (let key of heritageClauses.keys()) { + cls.addHeritageClassName(key); + } +} + +function buildInterface2ArkClass(clsNode: ts.InterfaceDeclaration, cls: ArkClass, sourceFile: ts.SourceFile, declaringMethod?: ArkMethod) { + const className = genClassName(clsNode.name ? clsNode.name.text : '', cls, declaringMethod); + const classSignature = new ClassSignature(className, + cls.getDeclaringArkFile().getFileSignature(), cls.getDeclaringArkNamespace()?.getSignature() || null); + cls.setSignature(classSignature); + + if (clsNode.typeParameters) { + buildTypeParameters(clsNode.typeParameters, sourceFile, cls).forEach((typeParameter) => { + cls.addGenericType(typeParameter); + }); + } + + initHeritage(buildHeritageClauses(clsNode.heritageClauses), cls); + + cls.setModifiers(buildModifiers(clsNode)); + cls.setDecorators(buildDecorators(clsNode, sourceFile)); + + cls.setCategory(ClassCategory.INTERFACE); + + buildArkClassMembers(clsNode, cls, sourceFile); +} + +function buildEnum2ArkClass(clsNode: ts.EnumDeclaration, cls: ArkClass, sourceFile: ts.SourceFile, declaringMethod?: ArkMethod) { + const className = genClassName(clsNode.name ? clsNode.name.text : '', cls, declaringMethod); + const classSignature = new ClassSignature(className, + cls.getDeclaringArkFile().getFileSignature(), cls.getDeclaringArkNamespace()?.getSignature() || null); + cls.setSignature(classSignature); + + cls.setModifiers(buildModifiers(clsNode)); + cls.setDecorators(buildDecorators(clsNode, sourceFile)); + + cls.setCategory(ClassCategory.ENUM); + + init4StaticInitMethod(cls); + buildArkClassMembers(clsNode, cls, sourceFile); +} + +function buildTypeLiteralNode2ArkClass(clsNode: ts.TypeLiteralNode, cls: ArkClass, + sourceFile: ts.SourceFile, declaringMethod?: ArkMethod) { + const className = genClassName('', cls, declaringMethod); + const classSignature = new ClassSignature(className, + cls.getDeclaringArkFile().getFileSignature(), cls.getDeclaringArkNamespace()?.getSignature() || null); + cls.setSignature(classSignature); + + + cls.setCategory(ClassCategory.TYPE_LITERAL); + if (ts.isTypeAliasDeclaration(clsNode.parent) && clsNode.parent.typeParameters) { + buildTypeParameters(clsNode.parent.typeParameters, sourceFile, cls).forEach((typeParameter) => { + cls.addGenericType(typeParameter); + }); + } + buildArkClassMembers(clsNode, cls, sourceFile); +} + +function buildObjectLiteralExpression2ArkClass(clsNode: ts.ObjectLiteralExpression, cls: ArkClass, + sourceFile: ts.SourceFile, declaringMethod?: ArkMethod) { + const className = genClassName('', cls, declaringMethod); + const classSignature = new ClassSignature(className, + cls.getDeclaringArkFile().getFileSignature(), cls.getDeclaringArkNamespace()?.getSignature() || null); + cls.setSignature(classSignature); + + cls.setCategory(ClassCategory.OBJECT); + + let arkMethods: ArkMethod[] = []; + + init4InstanceInitMethod(cls); + const instanceIRTransformer = new ArkIRTransformer(sourceFile, cls.getInstanceInitMethod()); + const instanceFieldInitializerStmts: Stmt[] = []; + clsNode.properties.forEach((property) => { + if (ts.isPropertyAssignment(property) || ts.isShorthandPropertyAssignment(property) || ts.isSpreadAssignment(property)) { + const arkField = buildProperty2ArkField(property, sourceFile, cls); + if (ts.isPropertyAssignment(property)) { + getInitStmts(instanceIRTransformer, arkField, property.initializer); + arkField.getInitializer().forEach(stmt => instanceFieldInitializerStmts.push(stmt)); + } + } else { + let arkMethod = new ArkMethod(); + arkMethod.setDeclaringArkClass(cls); + buildArkMethodFromArkClass(property, cls, arkMethod, sourceFile); + } + }); + buildInitMethod(cls.getInstanceInitMethod(), instanceFieldInitializerStmts, instanceIRTransformer.getThisLocal()); + arkMethods.forEach((mtd) => { + checkAndUpdateMethod(mtd, cls); + cls.addMethod(mtd); + }); +} + +function genClassName(declaringName: string, cls: ArkClass, declaringMethod?: ArkMethod): string { + if (!declaringName) { + const declaringArkNamespace = cls.getDeclaringArkNamespace(); + const num = declaringArkNamespace ? declaringArkNamespace.getAnonymousClassNumber() : cls.getDeclaringArkFile().getAnonymousClassNumber(); + declaringName = ANONYMOUS_CLASS_PREFIX + num; + } + const suffix = declaringMethod ? ANONYMOUS_CLASS_DELIMITER + declaringMethod.getDeclaringArkClass().getName() + '.' + declaringMethod.getName() : ''; + return declaringName + suffix; +} + +function buildArkClassMembers(clsNode: ClassLikeNode, cls: ArkClass, sourceFile: ts.SourceFile) { + if (ts.isObjectLiteralExpression(clsNode)) { + return; + } + buildMethodsForClass(clsNode, cls, sourceFile); + const staticBlockMethodSignatures = buildStaticBlocksForClass(clsNode, cls, sourceFile); + let instanceIRTransformer: ArkIRTransformer; + let staticIRTransformer: ArkIRTransformer; + if (ts.isClassDeclaration(clsNode) || ts.isClassExpression(clsNode) || ts.isStructDeclaration(clsNode)) { + instanceIRTransformer = new ArkIRTransformer(sourceFile, cls.getInstanceInitMethod()); + staticIRTransformer = new ArkIRTransformer(sourceFile, cls.getStaticInitMethod()); + } + if (ts.isEnumDeclaration(clsNode)) { + staticIRTransformer = new ArkIRTransformer(sourceFile, cls.getStaticInitMethod()); + } + const staticInitStmts: Stmt[] = []; + const instanceInitStmts: Stmt[] = []; + let staticBlockId = 0; + clsNode.members.forEach((member) => { + if (ts.isPropertyDeclaration(member) || ts.isPropertySignature(member)) { + const arkField = buildProperty2ArkField(member, sourceFile, cls); + if (ts.isClassDeclaration(clsNode) || ts.isClassExpression(clsNode) || ts.isStructDeclaration(clsNode)) { + if (arkField.isStatic()) { + getInitStmts(staticIRTransformer, arkField, member.initializer); + arkField.getInitializer().forEach(stmt => staticInitStmts.push(stmt)); + } else { + if (!instanceIRTransformer) + console.log(clsNode.getText(sourceFile)); + getInitStmts(instanceIRTransformer, arkField, member.initializer); + arkField.getInitializer().forEach(stmt => instanceInitStmts.push(stmt)); + } + } + } else if (ts.isEnumMember(member)) { + const arkField = buildProperty2ArkField(member, sourceFile, cls); + getInitStmts(staticIRTransformer, arkField, member.initializer); + arkField.getInitializer().forEach(stmt => staticInitStmts.push(stmt)); + } else if (ts.isIndexSignatureDeclaration(member)) { + buildIndexSignature2ArkField(member, sourceFile, cls); + } else if (ts.isClassStaticBlockDeclaration(member)) { + const currStaticBlockMethodSig = staticBlockMethodSignatures[staticBlockId++]; + const staticBlockInvokeExpr = new ArkStaticInvokeExpr(currStaticBlockMethodSig, []); + staticInitStmts.push(new ArkInvokeStmt(staticBlockInvokeExpr)); + } else if (ts.isSemicolonClassElement(member)) { + logger.debug('Skip these members.'); + } else { + logger.warn('Please contact developers to support new member type!'); + } + }); + if (ts.isClassDeclaration(clsNode) || ts.isClassExpression(clsNode) || ts.isStructDeclaration(clsNode)) { + buildInitMethod(cls.getInstanceInitMethod(), instanceInitStmts, instanceIRTransformer!.getThisLocal()); + buildInitMethod(cls.getStaticInitMethod(), staticInitStmts, staticIRTransformer!.getThisLocal()); + } + if (ts.isEnumDeclaration(clsNode)) { + buildInitMethod(cls.getStaticInitMethod(), staticInitStmts, staticIRTransformer!.getThisLocal()); + } +} + +function buildMethodsForClass(clsNode: ClassLikeNodeWithMethod, cls: ArkClass, sourceFile: ts.SourceFile): void { + clsNode.members.forEach((member) => { + if ( + ts.isMethodDeclaration(member) || + ts.isConstructorDeclaration(member) || + ts.isMethodSignature(member) || + ts.isConstructSignatureDeclaration(member) || + ts.isAccessor(member) || + ts.isCallSignatureDeclaration(member) + ) { + let mthd: ArkMethod = new ArkMethod(); + buildArkMethodFromArkClass(member, cls, mthd, sourceFile); + if (ts.isGetAccessor(member)) { + buildGetAccessor2ArkField(member, mthd, sourceFile); + } else if (ts.isConstructorDeclaration(member)) { + buildParameterProperty2ArkField(member.parameters, cls, sourceFile); + } + } + }); +} + +// params of constructor method may have modifiers such as public or private to directly define class properties with constructor +function buildParameterProperty2ArkField(params: ts.NodeArray, cls: ArkClass, sourceFile: ts.SourceFile): void { + if (params.length === 0) { + return; + } + params.forEach((parameter) => { + if (parameter.modifiers === undefined || !ts.isIdentifier(parameter.name)) { + return; + } + let field = new ArkField(); + field.setDeclaringArkClass(cls); + + field.setCode(parameter.getText(sourceFile)); + field.setCategory(FieldCategory.PARAMETER_PROPERTY); + field.setOriginPosition(LineColPosition.buildFromNode(parameter, sourceFile)); + + let fieldName = parameter.name.text; + let fieldType: Type; + if (parameter.type) { + fieldType = (buildGenericType(tsNode2Type(parameter.type, sourceFile, field), field)); + } else { + fieldType = UnknownType.getInstance(); + } + const fieldSignature = new FieldSignature(fieldName, cls.getSignature(), fieldType, false); + field.setSignature(fieldSignature); + field.setModifiers(buildModifiers(parameter)); + cls.addField(field); + }); +} + +function buildStaticBlocksForClass(clsNode: ClassLikeNodeWithMethod, cls: ArkClass, + sourceFile: ts.SourceFile): MethodSignature[] { + let staticInitBlockId = 0; + const staticBlockMethodSignatures: MethodSignature[] = []; + clsNode.members.forEach((member) => { + if (ts.isClassStaticBlockDeclaration(member)) { + const staticBlockMethod = new ArkMethod(); + staticBlockMethod.setDeclaringArkClass(cls); + staticBlockMethod.setIsGeneratedFlag(true); + staticBlockMethod.setCode(member.getText(sourceFile)); + const methodName = STATIC_BLOCK_METHOD_NAME_PREFIX + staticInitBlockId++; + const methodSubSignature = new MethodSubSignature(methodName, [], VoidType.getInstance(), true); + const methodSignature = new MethodSignature(cls.getSignature(), methodSubSignature); + staticBlockMethodSignatures.push(methodSignature); + staticBlockMethod.setImplementationSignature(methodSignature); + const { line, character } = ts.getLineAndCharacterOfPosition( + sourceFile, + member.getStart(sourceFile), + ); + staticBlockMethod.setLine(line + 1); + staticBlockMethod.setColumn(character + 1); + + let bodyBuilder = new BodyBuilder(staticBlockMethod.getSignature(), member, staticBlockMethod, sourceFile); + staticBlockMethod.setBodyBuilder(bodyBuilder); + + cls.addMethod(staticBlockMethod); + } + }); + return staticBlockMethodSignatures; +} + +function getInitStmts(transformer: ArkIRTransformer, field: ArkField, initNode?: ts.Node) { + if (initNode) { + const stmts: Stmt[] = []; + let { + value: initValue, + valueOriginalPositions: initPositions, + stmts: initStmts, + } = transformer.tsNodeToValueAndStmts(initNode); + initStmts.forEach(stmt => stmts.push(stmt)); + if (IRUtils.moreThanOneAddress(initValue)) { + ({ value: initValue, valueOriginalPositions: initPositions, stmts: initStmts } = + transformer.generateAssignStmtForValue(initValue, initPositions)); + initStmts.forEach(stmt => stmts.push(stmt)); + } + + const fieldRef = new ArkInstanceFieldRef(transformer.getThisLocal(), field.getSignature()); + const fieldRefPositions = [FullPosition.DEFAULT, FullPosition.DEFAULT]; + const assignStmt = new ArkAssignStmt(fieldRef, initValue); + assignStmt.setOperandOriginalPositions([...fieldRefPositions, ...initPositions]); + stmts.push(assignStmt); + + const fieldSourceCode = field.getCode(); + const fieldOriginPosition = field.getOriginPosition(); + for (const stmt of stmts) { + stmt.setOriginPositionInfo(fieldOriginPosition); + stmt.setOriginalText(fieldSourceCode); + } + field.setInitializer(stmts); + if (field.getType() instanceof UnknownType) { + field.getSignature().setType(initValue.getType()); + } + } +} diff --git a/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkExportBuilder.ts b/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkExportBuilder.ts new file mode 100644 index 0000000000..9bfee8c4c8 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkExportBuilder.ts @@ -0,0 +1,212 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import ts from 'ohos-typescript'; +import { LineColPosition } from '../../base/Position'; +import { ArkExport, ExportInfo, ExportType, FromInfo } from '../ArkExport'; +import { buildModifiers } from './builderUtils'; +import { ArkFile } from '../ArkFile'; +import { ALL, DEFAULT } from '../../common/TSConst'; +import { ArkBaseModel, ModifierType } from '../ArkBaseModel'; +import { IRUtils } from '../../common/IRUtils'; +import { ArkClass } from '../ArkClass'; +import { buildNormalArkClassFromArkFile } from './ArkClassBuilder'; + +export { buildExportInfo, buildExportAssignment, buildExportDeclaration }; + +function buildExportInfo(arkInstance: ArkExport, arkFile: ArkFile, line: LineColPosition): ExportInfo { + let exportClauseName: string; + if (arkInstance instanceof ArkBaseModel && arkInstance.isDefault()) { + exportClauseName = DEFAULT; + } else { + exportClauseName = arkInstance.getName(); + } + return new ExportInfo.Builder() + .exportClauseName(exportClauseName) + .exportClauseType(arkInstance.getExportType()) + .modifiers(arkInstance.getModifiers()) + .arkExport(arkInstance) + .originTsPosition(line) + .declaringArkFile(arkFile) + .build(); +} + + +export function buildDefaultExportInfo(im: FromInfo, file: ArkFile, arkExport?: ArkExport) { + return new ExportInfo.Builder() + .exportClauseType(arkExport?.getExportType() ?? ExportType.CLASS) + .exportClauseName(im.getOriginName()) + .declaringArkFile(file) + .arkExport(arkExport ?? file.getDefaultClass()) + .build(); +} + +function buildExportDeclaration(node: ts.ExportDeclaration, sourceFile: ts.SourceFile, arkFile: ArkFile): ExportInfo[] { + const originTsPosition = LineColPosition.buildFromNode(node, sourceFile); + const tsSourceCode = node.getText(sourceFile); + const modifiers = node.modifiers ? buildModifiers(node) : 0; + let exportFrom = ''; + if (node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) { + exportFrom = node.moduleSpecifier.text; + } + let exportInfos: ExportInfo[] = []; + // just like: export {xxx as x} from './yy' + if (node.exportClause && ts.isNamedExports(node.exportClause) && node.exportClause.elements) { + node.exportClause.elements.forEach((element) => { + let builder = new ExportInfo.Builder() + .exportClauseType(ExportType.UNKNOWN) + .exportClauseName(element.name.text) + .tsSourceCode(tsSourceCode) + .exportFrom(exportFrom) + .originTsPosition(originTsPosition) + .declaringArkFile(arkFile) + .setLeadingComments(IRUtils.getCommentsMetadata(node, sourceFile, arkFile.getScene().getOptions(), true)) + .setTrailingComments(IRUtils.getCommentsMetadata(node, sourceFile, arkFile.getScene().getOptions(), false)) + .modifiers(modifiers); + if (element.propertyName && ts.isIdentifier(element.propertyName)) { + builder.nameBeforeAs(element.propertyName.text); + } + exportInfos.push(builder.build()); + }); + return exportInfos; + } + + let builder1 = new ExportInfo.Builder() + .exportClauseType(ExportType.UNKNOWN) + .nameBeforeAs(ALL) + .modifiers(modifiers) + .tsSourceCode(tsSourceCode) + .exportFrom(exportFrom) + .declaringArkFile(arkFile) + .setLeadingComments(IRUtils.getCommentsMetadata(node, sourceFile, arkFile.getScene().getOptions(), true)) + .setTrailingComments(IRUtils.getCommentsMetadata(node, sourceFile, arkFile.getScene().getOptions(), false)) + .originTsPosition(originTsPosition); + if (node.exportClause && ts.isNamespaceExport(node.exportClause) && ts.isIdentifier(node.exportClause.name)) { // just like: export * as xx from './yy' + exportInfos.push(builder1.exportClauseName(node.exportClause.name.text).build()); + } else if (!node.exportClause && node.moduleSpecifier) { // just like: export * from './yy' + exportInfos.push(builder1.exportClauseName(ALL).build()); + } + return exportInfos; +} + +function buildExportAssignment(node: ts.ExportAssignment, sourceFile: ts.SourceFile, arkFile: ArkFile): ExportInfo[] { + let exportInfos: ExportInfo[] = []; + if (!node.expression) { + return exportInfos; + } + const originTsPosition = LineColPosition.buildFromNode(node, sourceFile); + const tsSourceCode = node.getText(sourceFile); + let modifiers = buildModifiers(node); + + if (isKeyword(node.getChildren(sourceFile), ts.SyntaxKind.DefaultKeyword) || node.isExportEquals) { + modifiers |= ModifierType.DEFAULT; + } + + let exportInfo = new ExportInfo.Builder() + .exportClauseType(ExportType.UNKNOWN) + .modifiers(modifiers) + .tsSourceCode(tsSourceCode) + .originTsPosition(originTsPosition) + .declaringArkFile(arkFile) + .exportClauseName(DEFAULT) + .setLeadingComments(IRUtils.getCommentsMetadata(node, sourceFile, arkFile.getScene().getOptions(), true)) + .setTrailingComments(IRUtils.getCommentsMetadata(node, sourceFile, arkFile.getScene().getOptions(), false)) + + if (ts.isNewExpression(node.expression) && ts.isClassExpression(node.expression.expression)) { + let cls: ArkClass = new ArkClass(); + buildNormalArkClassFromArkFile(node.expression.expression, arkFile, cls, sourceFile); + } + + if (ts.isIdentifier(node.expression)) { // just like: export default xx + exportInfo.nameBeforeAs(node.expression.text); + } else if (ts.isAsExpression(node.expression)) { // just like: export default xx as YY + exportInfo.nameBeforeAs(node.expression.expression.getText(sourceFile)) + } + exportInfos.push(exportInfo.build()); + + return exportInfos; +} + +/** + * export const c = '', b = 1; + * @param node + * @param sourceFile + * @param arkFile + */ +export function buildExportVariableStatement(node: ts.VariableStatement, sourceFile: ts.SourceFile, arkFile: ArkFile): ExportInfo[] { + let exportInfos: ExportInfo[] = []; + const originTsPosition = LineColPosition.buildFromNode(node, sourceFile); + const modifiers = node.modifiers ? buildModifiers(node) : 0; + const tsSourceCode = node.getText(sourceFile); + node.declarationList.declarations.forEach(dec => { + const exportInfo = new ExportInfo.Builder() + .exportClauseName(dec.name.getText(sourceFile)) + .exportClauseType(ExportType.LOCAL) + .modifiers(modifiers) + .tsSourceCode(tsSourceCode) + .originTsPosition(originTsPosition) + .declaringArkFile(arkFile) + .build(); + exportInfos.push(exportInfo); + }) + return exportInfos; +} + +/** + * export type MyType = string; + * @param node + * @param sourceFile + * @param arkFile + */ +export function buildExportTypeAliasDeclaration(node: ts.TypeAliasDeclaration, sourceFile: ts.SourceFile, arkFile: ArkFile): ExportInfo[] { + let exportInfos: ExportInfo[] = []; + const originTsPosition = LineColPosition.buildFromNode(node, sourceFile); + const modifiers = node.modifiers ? buildModifiers(node) : 0; + const tsSourceCode = node.getText(sourceFile); + const exportInfo = new ExportInfo.Builder() + .exportClauseName(node.name.text) + .exportClauseType(ExportType.TYPE) + .tsSourceCode(tsSourceCode) + .modifiers(modifiers) + .originTsPosition(originTsPosition) + .declaringArkFile(arkFile) + .build(); + exportInfos.push(exportInfo); + return exportInfos; +} + +export function isExported(modifierArray: ts.NodeArray | undefined): boolean { + if (!modifierArray) { + return false; + } + for (let child of modifierArray) { + if (child.kind === ts.SyntaxKind.ExportKeyword) { + return true; + } + } + return false; +} + +function isKeyword(modifierArray: ts.Node[] | undefined, keyword: ts.SyntaxKind): boolean { + if (!modifierArray) { + return false; + } + for (let child of modifierArray) { + if (child.kind === keyword) { + return true; + } + } + return false; +} diff --git a/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkFieldBuilder.ts b/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkFieldBuilder.ts new file mode 100644 index 0000000000..f6db292b17 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkFieldBuilder.ts @@ -0,0 +1,175 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import ts from 'ohos-typescript'; +import { ArkField, FieldCategory } from '../ArkField'; +import Logger, { LOG_MODULE_TYPE } from '../../../utils/logger'; +import { ArkClass } from '../ArkClass'; +import { ArkMethod } from '../ArkMethod'; +import { buildDecorators, buildGenericType, buildModifiers, handlePropertyAccessExpression, tsNode2Type } from './builderUtils'; +import { FieldSignature } from '../ArkSignature'; +import { ClassType, Type, UnknownType } from '../../base/Type'; +import { LineColPosition } from '../../base/Position'; +import { ModifierType } from '../ArkBaseModel'; +import { IRUtils } from '../../common/IRUtils'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'ArkFieldBuilder'); + +export type PropertyLike = ts.PropertyDeclaration | ts.PropertyAssignment; + +export function buildProperty2ArkField(member: ts.PropertyDeclaration | ts.PropertyAssignment | ts.ShorthandPropertyAssignment + | ts.SpreadAssignment | ts.PropertySignature | ts.EnumMember, sourceFile: ts.SourceFile, cls: ArkClass): ArkField { + + let field = new ArkField(); + field.setCategory(mapSyntaxKindToFieldOriginType(member.kind) as FieldCategory); + field.setCode(member.getText(sourceFile)); + field.setDeclaringArkClass(cls); + field.setOriginPosition(LineColPosition.buildFromNode(member, sourceFile)); + + let fieldName = member.getText(sourceFile); + if (member.name && ts.isComputedPropertyName(member.name)) { + if (ts.isIdentifier(member.name.expression)) { + fieldName = member.name.expression.text; + } else if (ts.isPropertyAccessExpression(member.name.expression)) { + fieldName = handlePropertyAccessExpression(member.name.expression); + } else { + logger.warn("Other property expression type found!"); + } + } else if (member.name && (ts.isIdentifier(member.name) || ts.isLiteralExpression(member.name))) { + fieldName = member.name.text; + } else if (member.name && ts.isPrivateIdentifier(member.name)) { + let propertyName = member.name.text; + fieldName = propertyName.substring(1); + field.addModifier(ModifierType.PRIVATE); + } else { + logger.warn("Other type of property name found!"); + } + + let fieldType: Type = UnknownType.getInstance(); + if ((ts.isPropertyDeclaration(member) || ts.isPropertySignature(member))) { + if (member.modifiers) { + field.addModifier(buildModifiers(member)); + } + field.addModifier(0); + field.setDecorators(buildDecorators(member, sourceFile)); + field.setQuestionToken(member.questionToken !== undefined); + + if (member.type) { + fieldType = buildGenericType(tsNode2Type(member.type, sourceFile, cls), field); + } + } + + if (ts.isEnumMember(member)) { + field.addModifier(ModifierType.STATIC); + fieldType = new ClassType(cls.getSignature()); + } + field.setSignature(new FieldSignature(fieldName, cls.getSignature(), fieldType, field.isStatic())); + + if (ts.isPropertyDeclaration(member) && member.exclamationToken) { + field.setExclamationToken(true); + } + IRUtils.setComments(field, member, sourceFile, cls.getDeclaringArkFile().getScene().getOptions()); + cls.addField(field); + return field; +} + +export function buildIndexSignature2ArkField(member: ts.IndexSignatureDeclaration, sourceFile: ts.SourceFile, cls: ArkClass) { + const field = new ArkField(); + field.setCode(member.getText(sourceFile)); + field.setCategory(mapSyntaxKindToFieldOriginType(member.kind) as FieldCategory); + field.setDeclaringArkClass(cls); + + field.setOriginPosition(LineColPosition.buildFromNode(member, sourceFile)); + + if (member.modifiers) { + let modifier = buildModifiers(member); + field.addModifier(modifier); + } + + const fieldName = '[' + member.parameters[0].getText(sourceFile) + ']'; + const fieldType = buildGenericType(tsNode2Type(member.type, sourceFile, field), field); + const fieldSignature = new FieldSignature(fieldName, cls.getSignature(), fieldType, true); + field.setSignature(fieldSignature); + IRUtils.setComments(field, member, sourceFile, cls.getDeclaringArkFile().getScene().getOptions()); + cls.addField(field); +} + +export function buildGetAccessor2ArkField(member: ts.GetAccessorDeclaration, mthd: ArkMethod, sourceFile: ts.SourceFile) { + let cls = mthd.getDeclaringArkClass(); + let field = new ArkField(); + field.setDeclaringArkClass(cls); + + field.setCode(member.getText(sourceFile)); + field.setCategory(mapSyntaxKindToFieldOriginType(member.kind) as FieldCategory); + field.setOriginPosition(LineColPosition.buildFromNode(member, sourceFile)); + + let fieldName = member.getText(sourceFile); + if (ts.isIdentifier(member.name) || ts.isLiteralExpression(member.name)) { + fieldName = member.name.text; + } + else if (ts.isComputedPropertyName(member.name)) { + if (ts.isIdentifier(member.name.expression)) { + let propertyName = member.name.expression.text; + fieldName = propertyName; + } else if (ts.isPropertyAccessExpression(member.name.expression)) { + fieldName = handlePropertyAccessExpression(member.name.expression); + } else if (ts.isLiteralExpression(member.name.expression)) { + fieldName = member.name.expression.text; + } else { + logger.warn("Other type of computed property name found!"); + } + } + else { + logger.warn("Please contact developers to support new type of GetAccessor name!"); + } + + const fieldType = mthd.getReturnType(); + const fieldSignature = new FieldSignature(fieldName, cls.getSignature(), fieldType, false); + field.setSignature(fieldSignature); + cls.addField(field); +} + +function mapSyntaxKindToFieldOriginType(syntaxKind: ts.SyntaxKind): FieldCategory | null { + let fieldOriginType: FieldCategory | null = null; + switch (syntaxKind) { + case ts.SyntaxKind.PropertyDeclaration: + fieldOriginType = FieldCategory.PROPERTY_DECLARATION; + break; + case ts.SyntaxKind.PropertyAssignment: + fieldOriginType = FieldCategory.PROPERTY_ASSIGNMENT; + break; + case ts.SyntaxKind.ShorthandPropertyAssignment: + fieldOriginType = FieldCategory.SHORT_HAND_PROPERTY_ASSIGNMENT; + break; + case ts.SyntaxKind.SpreadAssignment: + fieldOriginType = FieldCategory.SPREAD_ASSIGNMENT; + break; + case ts.SyntaxKind.PropertySignature: + fieldOriginType = FieldCategory.PROPERTY_SIGNATURE; + break; + case ts.SyntaxKind.EnumMember: + fieldOriginType = FieldCategory.ENUM_MEMBER; + break; + case ts.SyntaxKind.IndexSignature: + fieldOriginType = FieldCategory.INDEX_SIGNATURE; + break; + case ts.SyntaxKind.GetAccessor: + fieldOriginType = FieldCategory.GET_ACCESSOR; + break; + default: + ; + } + return fieldOriginType; +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkFileBuilder.ts b/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkFileBuilder.ts new file mode 100644 index 0000000000..52935cbb5b --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkFileBuilder.ts @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import fs from 'fs'; +import path from 'path'; +import ts from 'ohos-typescript'; +import { ArkFile, Language } from '../ArkFile'; +import { ArkNamespace } from '../ArkNamespace'; +import Logger, { LOG_MODULE_TYPE } from '../../../utils/logger'; +import { buildDefaultArkClassFromArkFile, buildNormalArkClassFromArkFile } from './ArkClassBuilder'; +import { buildArkMethodFromArkClass } from './ArkMethodBuilder'; +import { buildImportInfo } from './ArkImportBuilder'; +import { + buildExportAssignment, + buildExportDeclaration, + buildExportInfo, + buildExportTypeAliasDeclaration, + buildExportVariableStatement, + isExported, +} from './ArkExportBuilder'; +import { buildArkNamespace, mergeNameSpaces } from './ArkNamespaceBuilder'; +import { ArkClass } from '../ArkClass'; +import { ArkMethod } from '../ArkMethod'; +import { LineColPosition } from '../../base/Position'; +import { ETS_COMPILER_OPTIONS } from '../../common/EtsConst'; +import { FileSignature } from '../ArkSignature'; +import { ARKTS_STATIC_MARK } from '../../common/Const'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'ArkFileBuilder'); + +export const notStmtOrExprKind = ['ModuleDeclaration', 'ClassDeclaration', 'InterfaceDeclaration', 'EnumDeclaration', 'ExportDeclaration', + 'ExportAssignment', 'MethodDeclaration', 'Constructor', 'FunctionDeclaration', 'GetAccessor', 'SetAccessor', 'ArrowFunction', + 'FunctionExpression', 'MethodSignature', 'ConstructSignature', 'CallSignature']; + +/** + * Entry of building ArkFile instance + * + * @param arkFile + * @returns + */ +export function buildArkFileFromFile(absoluteFilePath: string, projectDir: string, arkFile: ArkFile, + projectName: string) { + arkFile.setFilePath(absoluteFilePath); + arkFile.setProjectDir(projectDir); + + const fileSignature = new FileSignature(projectName, path.relative(projectDir, absoluteFilePath)); + arkFile.setFileSignature(fileSignature); + + arkFile.setCode(fs.readFileSync(arkFile.getFilePath(), 'utf8')); + const sourceFile = ts.createSourceFile( + arkFile.getName(), + arkFile.getCode(), + ts.ScriptTarget.Latest, + true, + undefined, + ETS_COMPILER_OPTIONS, + ); + genDefaultArkClass(arkFile, sourceFile); + buildArkFile(arkFile, sourceFile); +} + +/** + * Building ArkFile instance + * + * @param arkFile + * @param astRoot + * @returns + */ +function buildArkFile(arkFile: ArkFile, astRoot: ts.SourceFile) { + const statements = astRoot.statements; + const namespaces: ArkNamespace[] = []; + statements.forEach((child) => { + if ( + ts.isModuleDeclaration(child) + ) { + let ns: ArkNamespace = new ArkNamespace(); + ns.setDeclaringArkFile(arkFile); + + buildArkNamespace(child, arkFile, ns, astRoot); + namespaces.push(ns); + if (ns.isExported()) { + arkFile.addExportInfo(buildExportInfo(ns, arkFile, LineColPosition.buildFromNode(child, astRoot))); + } + } else if ( + ts.isClassDeclaration(child) || + ts.isInterfaceDeclaration(child) || + ts.isEnumDeclaration(child) || + ts.isStructDeclaration(child) + ) { + let cls: ArkClass = new ArkClass(); + + buildNormalArkClassFromArkFile(child, arkFile, cls, astRoot); + arkFile.addArkClass(cls); + + if (cls.isExported()) { + arkFile.addExportInfo(buildExportInfo(cls, arkFile, LineColPosition.buildFromNode(child, astRoot))); + } + } + // TODO: Check + else if (ts.isMethodDeclaration(child)) { + logger.warn('This is a MethodDeclaration in ArkFile.'); + let mthd: ArkMethod = new ArkMethod(); + + buildArkMethodFromArkClass(child, arkFile.getDefaultClass(), mthd, astRoot); + + if (mthd.isExported()) { + arkFile.addExportInfo(buildExportInfo(mthd, arkFile, LineColPosition.buildFromNode(child, astRoot))); + } + } else if (ts.isFunctionDeclaration(child)) { + let mthd: ArkMethod = new ArkMethod(); + + buildArkMethodFromArkClass(child, arkFile.getDefaultClass(), mthd, astRoot); + + if (mthd.isExported()) { + arkFile.addExportInfo(buildExportInfo(mthd, arkFile, LineColPosition.buildFromNode(child, astRoot))); + } + } else if ( + ts.isImportEqualsDeclaration(child) || + ts.isImportDeclaration(child) + ) { + let importInfos = buildImportInfo(child, astRoot, arkFile); + importInfos?.forEach((element) => { + element.setDeclaringArkFile(arkFile); + arkFile.addImportInfo(element); + + }); + } else if (ts.isExportDeclaration(child)) { + buildExportDeclaration(child, astRoot, arkFile).forEach(item => arkFile.addExportInfo(item)); + } else if (ts.isExportAssignment(child)) { + buildExportAssignment(child, astRoot, arkFile).forEach(item => arkFile.addExportInfo(item)); + } else if (ts.isVariableStatement(child) && isExported(child.modifiers)) { + buildExportVariableStatement(child, astRoot, arkFile).forEach(item => arkFile.addExportInfo(item)); + } else if (ts.isTypeAliasDeclaration(child) && isExported(child.modifiers)) { + buildExportTypeAliasDeclaration(child, astRoot, arkFile).forEach(item => arkFile.addExportInfo(item)); + } else if (ts.isExpressionStatement(child) && ts.isStringLiteral(child.expression)) { + child.expression.text.trim() === ARKTS_STATIC_MARK && arkFile.setLanguage(Language.ARKTS1_2); + } else { + logger.info('Child joined default method of arkFile: ', ts.SyntaxKind[child.kind]); + } + }); + + const mergedNameSpaces = mergeNameSpaces(namespaces); + mergedNameSpaces.forEach(mergedNameSpace => { + arkFile.addNamespace(mergedNameSpace); + if (mergedNameSpace.isExport()) { + const linCol = new LineColPosition(mergedNameSpace.getLine(), mergedNameSpace.getColumn()); + arkFile.addExportInfo(buildExportInfo(mergedNameSpace, arkFile, linCol)); + } + }); +} + +function genDefaultArkClass(arkFile: ArkFile, astRoot: ts.SourceFile) { + let defaultClass = new ArkClass(); + + buildDefaultArkClassFromArkFile(arkFile, defaultClass, astRoot); + arkFile.setDefaultClass(defaultClass); + arkFile.addArkClass(defaultClass); +} + + + diff --git a/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkImportBuilder.ts b/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkImportBuilder.ts new file mode 100644 index 0000000000..e73d267268 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkImportBuilder.ts @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import ts from 'ohos-typescript'; +import { LineColPosition } from '../../base/Position'; +import { ImportInfo } from '../ArkImport'; +import { buildModifiers } from './builderUtils'; +import { IRUtils } from '../../common/IRUtils'; +import { ArkFile } from '../ArkFile'; + + +export function buildImportInfo(node: ts.ImportEqualsDeclaration | ts.ImportDeclaration, sourceFile: ts.SourceFile, arkFile: ArkFile): ImportInfo[] { + if (ts.isImportDeclaration(node)) { + return buildImportDeclarationNode(node, sourceFile, arkFile); + } else if (ts.isImportEqualsDeclaration(node)) { + return buildImportEqualsDeclarationNode(node, sourceFile, arkFile); + } + return []; +} + +function buildImportDeclarationNode(node: ts.ImportDeclaration, sourceFile: ts.SourceFile, arkFile: ArkFile): ImportInfo[] { + const originTsPosition = LineColPosition.buildFromNode(node, sourceFile); + const tsSourceCode = node.getText(sourceFile); + + let importInfos: ImportInfo[] = []; + let importFrom: string = ''; + if (ts.isStringLiteral(node.moduleSpecifier)) { + importFrom = node.moduleSpecifier.text; + } + + let modifiers = 0; + if (node.modifiers) { + modifiers = buildModifiers(node); + } + + // just like: import '../xxx' + if (!node.importClause) { + let importClauseName = ''; + let importType = ''; + let importInfo = new ImportInfo(); + importInfo.build(importClauseName, importType, importFrom, originTsPosition, modifiers); + importInfo.setTsSourceCode(tsSourceCode); + IRUtils.setComments(importInfo, node, sourceFile, arkFile.getScene().getOptions()); + importInfos.push(importInfo); + } + + //just like: import fs from 'fs' + if (node.importClause && node.importClause.name && ts.isIdentifier(node.importClause.name)) { + let importClauseName = node.importClause.name.text; + let importType = 'Identifier'; + let importInfo = new ImportInfo(); + importInfo.build(importClauseName, importType, importFrom, originTsPosition, modifiers); + importInfo.setTsSourceCode(tsSourceCode); + IRUtils.setComments(importInfo, node, sourceFile, arkFile.getScene().getOptions()); + importInfos.push(importInfo); + } + + // just like: import {xxx} from './yyy' + if (node.importClause && node.importClause.namedBindings && ts.isNamedImports(node.importClause.namedBindings)) { + let importType = 'NamedImports'; + if (node.importClause.namedBindings.elements) { + node.importClause.namedBindings.elements.forEach((element) => { + if (element.name && ts.isIdentifier(element.name)) { + let importClauseName = element.name.text; + if (element.propertyName && ts.isIdentifier(element.propertyName)) { + let importInfo = new ImportInfo(); + importInfo.build(importClauseName, importType, importFrom, originTsPosition, modifiers, element.propertyName.text); + importInfo.setTsSourceCode(tsSourceCode); + IRUtils.setComments(importInfo, node, sourceFile, arkFile.getScene().getOptions()); + importInfos.push(importInfo); + } else { + let importInfo = new ImportInfo(); + importInfo.build(importClauseName, importType, importFrom, originTsPosition, modifiers); + importInfo.setTsSourceCode(tsSourceCode); + IRUtils.setComments(importInfo, node, sourceFile, arkFile.getScene().getOptions()); + importInfos.push(importInfo); + } + } + }); + } + } + + // just like: import * as ts from 'ohos-typescript' + if (node.importClause && node.importClause.namedBindings && ts.isNamespaceImport(node.importClause.namedBindings)) { + let importType = 'NamespaceImport'; + if (node.importClause.namedBindings.name && ts.isIdentifier(node.importClause.namedBindings.name)) { + let importClauseName = node.importClause.namedBindings.name.text; + let importInfo = new ImportInfo(); + let nameBeforeAs = '*'; + importInfo.build(importClauseName, importType, importFrom, originTsPosition, modifiers, nameBeforeAs); + importInfo.setTsSourceCode(tsSourceCode); + IRUtils.setComments(importInfo, node, sourceFile, arkFile.getScene().getOptions()); + importInfos.push(importInfo); + } + } + + return importInfos; +} + +function buildImportEqualsDeclarationNode(node: ts.ImportEqualsDeclaration, sourceFile: ts.SourceFile, arkFile: ArkFile): ImportInfo[] { + const originTsPosition = LineColPosition.buildFromNode(node, sourceFile); + const tsSourceCode = node.getText(sourceFile); + + let importInfos: ImportInfo[] = []; + let importType = 'EqualsImport'; + let modifiers = 0; + if (node.modifiers) { + modifiers = buildModifiers(node); + } + if (node.moduleReference && ts.isExternalModuleReference(node.moduleReference) && + node.moduleReference.expression && ts.isStringLiteral(node.moduleReference.expression)) { + let importFrom = node.moduleReference.expression.text; + let importClauseName = node.name.text; + let importInfo = new ImportInfo(); + importInfo.build(importClauseName, importType, importFrom, originTsPosition, modifiers); + importInfo.setTsSourceCode(tsSourceCode); + IRUtils.setComments(importInfo, node, sourceFile, arkFile.getScene().getOptions()); + importInfos.push(importInfo); + } + return importInfos; +} diff --git a/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkMethodBuilder.ts b/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkMethodBuilder.ts new file mode 100644 index 0000000000..d124679e6b --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkMethodBuilder.ts @@ -0,0 +1,516 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ClassType, Type, UnknownType } from '../../base/Type'; +import { BodyBuilder } from './BodyBuilder'; +import { buildViewTree } from '../../graph/builder/ViewTreeBuilder'; +import { ArkClass, ClassCategory } from '../ArkClass'; +import { ArkMethod } from '../ArkMethod'; +import ts from 'ohos-typescript'; +import { + buildDecorators, + buildGenericType, + buildModifiers, + buildParameters, + buildReturnType, + buildTypeParameters, + handlePropertyAccessExpression, +} from './builderUtils'; +import Logger, { LOG_MODULE_TYPE } from '../../../utils/logger'; +import { ArkParameterRef, ArkThisRef, ClosureFieldRef } from '../../base/Ref'; +import { ArkBody } from '../ArkBody'; +import { Cfg } from '../../graph/Cfg'; +import { ArkInstanceInvokeExpr, ArkStaticInvokeExpr } from '../../base/Expr'; +import { MethodSignature, MethodSubSignature } from '../ArkSignature'; +import { ArkAssignStmt, ArkInvokeStmt, ArkReturnStmt, ArkReturnVoidStmt, Stmt } from '../../base/Stmt'; +import { BasicBlock } from '../../graph/BasicBlock'; +import { Local } from '../../base/Local'; +import { Value } from '../../base/Value'; +import { CONSTRUCTOR_NAME, SUPER_NAME, THIS_NAME } from '../../common/TSConst'; +import { + ANONYMOUS_METHOD_PREFIX, + CALL_SIGNATURE_NAME, + DEFAULT_ARK_CLASS_NAME, + DEFAULT_ARK_METHOD_NAME, + NAME_DELIMITER, + NAME_PREFIX, +} from '../../common/Const'; +import { ArkSignatureBuilder } from './ArkSignatureBuilder'; +import { IRUtils } from '../../common/IRUtils'; +import { ArkErrorCode } from '../../common/ArkError'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'ArkMethodBuilder'); + +export type MethodLikeNode = + ts.FunctionDeclaration | + ts.MethodDeclaration | + ts.ConstructorDeclaration | + ts.ArrowFunction | + ts.AccessorDeclaration | + ts.FunctionExpression | + ts.MethodSignature | + ts.ConstructSignatureDeclaration | + ts.CallSignatureDeclaration | + ts.FunctionTypeNode; + +export function buildDefaultArkMethodFromArkClass(declaringClass: ArkClass, mtd: ArkMethod, + sourceFile: ts.SourceFile, node?: ts.ModuleDeclaration) { + mtd.setDeclaringArkClass(declaringClass); + + const methodSubSignature = ArkSignatureBuilder.buildMethodSubSignatureFromMethodName(DEFAULT_ARK_METHOD_NAME, true); + const methodSignature = new MethodSignature(mtd.getDeclaringArkClass().getSignature(), methodSubSignature); + mtd.setImplementationSignature(methodSignature); + mtd.setLineCol(0); + + const defaultMethodNode = node ? node : sourceFile; + + let bodyBuilder = new BodyBuilder(mtd.getSignature(), defaultMethodNode, mtd, sourceFile); + mtd.setBodyBuilder(bodyBuilder); +} + +export function buildArkMethodFromArkClass(methodNode: MethodLikeNode, declaringClass: ArkClass, mtd: ArkMethod, sourceFile: ts.SourceFile, declaringMethod?: ArkMethod) { + mtd.setDeclaringArkClass(declaringClass); + declaringMethod !== undefined && mtd.setOuterMethod(declaringMethod); + + ts.isFunctionDeclaration(methodNode) && mtd.setAsteriskToken(methodNode.asteriskToken !== undefined); + + // All MethodLikeNode except FunctionTypeNode have questionToken. + !ts.isFunctionTypeNode(methodNode) && mtd.setQuestionToken(methodNode.questionToken !== undefined); + + mtd.setCode(methodNode.getText(sourceFile)); + mtd.setModifiers(buildModifiers(methodNode)); + mtd.setDecorators(buildDecorators(methodNode, sourceFile)); + + if (methodNode.typeParameters) { + mtd.setGenericTypes(buildTypeParameters(methodNode.typeParameters, sourceFile, mtd)); + } + + // build methodDeclareSignatures and methodSignature as well as corresponding positions + const methodName = buildMethodName(methodNode, declaringClass, sourceFile, declaringMethod); + const methodParameters: MethodParameter[] = []; + buildParameters(methodNode.parameters, mtd, sourceFile).forEach((parameter) => { + buildGenericType(parameter.getType(), mtd); + methodParameters.push(parameter); + }); + let returnType = UnknownType.getInstance(); + if (methodNode.type) { + returnType = buildGenericType(buildReturnType(methodNode.type, sourceFile, mtd), mtd); + } + const methodSubSignature = new MethodSubSignature(methodName, methodParameters, returnType, mtd.isStatic()); + const methodSignature = new MethodSignature(mtd.getDeclaringArkClass().getSignature(), methodSubSignature); + const { line, character } = ts.getLineAndCharacterOfPosition(sourceFile, methodNode.getStart(sourceFile)); + if (isMethodImplementation(methodNode)) { + mtd.setImplementationSignature(methodSignature); + mtd.setLine(line + 1); + mtd.setColumn(character + 1); + } else { + mtd.setDeclareSignatures(methodSignature); + mtd.setDeclareLinesAndCols([line + 1], [character + 1]); + } + + let bodyBuilder = new BodyBuilder(mtd.getSignature(), methodNode, mtd, sourceFile); + mtd.setBodyBuilder(bodyBuilder); + + if (mtd.hasBuilderDecorator()) { + mtd.setViewTree(buildViewTree(mtd)); + } else if (declaringClass.hasComponentDecorator() && mtd.getSubSignature().toString() === 'build()' && !mtd.isStatic()) { + declaringClass.setViewTree(buildViewTree(mtd)); + } + checkAndUpdateMethod(mtd, declaringClass); + declaringClass.addMethod(mtd); + IRUtils.setComments(mtd, methodNode, sourceFile, mtd.getDeclaringArkFile().getScene().getOptions()); +} + +function buildMethodName(node: MethodLikeNode, declaringClass: ArkClass, sourceFile: ts.SourceFile, declaringMethod?: ArkMethod): string { + let name: string = ''; + if (ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node)) { + name = node.name ? node.name.text : buildAnonymousMethodName(node, declaringClass); + } else if (ts.isFunctionTypeNode(node)) { + //TODO: check name type + name = node.name ? node.name.getText(sourceFile) : buildAnonymousMethodName(node, declaringClass); + } else if (ts.isMethodDeclaration(node) || ts.isMethodSignature(node)) { + if (ts.isIdentifier(node.name)) { + name = (node.name as ts.Identifier).text; + } else if (ts.isComputedPropertyName(node.name)) { + if (ts.isIdentifier(node.name.expression)) { + name = node.name.expression.text; + } else if (ts.isPropertyAccessExpression(node.name.expression)) { + name = handlePropertyAccessExpression(node.name.expression); + } else { + logger.warn('Other method ComputedPropertyName found!'); + } + } else { + logger.warn('Other method declaration type found!'); + } + } + //TODO, hard code + else if (ts.isConstructorDeclaration(node)) { + name = CONSTRUCTOR_NAME; + } else if (ts.isConstructSignatureDeclaration(node)) { + name = 'construct-signature'; + } else if (ts.isCallSignatureDeclaration(node)) { + name = CALL_SIGNATURE_NAME; + } else if (ts.isGetAccessor(node) && ts.isIdentifier(node.name)) { + name = 'Get-' + node.name.text; + } else if (ts.isSetAccessor(node) && ts.isIdentifier(node.name)) { + name = 'Set-' + node.name.text; + } else if (ts.isArrowFunction(node)) { + name = buildAnonymousMethodName(node, declaringClass); + } + + if (declaringMethod !== undefined && !declaringMethod.isDefaultArkMethod()) { + name = buildNestedMethodName(name, declaringMethod.getName()); + } + return name; +} + +function buildAnonymousMethodName(node: MethodLikeNode, declaringClass: ArkClass) { + return `${ANONYMOUS_METHOD_PREFIX}${declaringClass.getAnonymousMethodNumber()}`; +} + +function buildNestedMethodName(originName: string, declaringMethodName: string): string { + if (originName.startsWith(NAME_PREFIX)) { + return `${originName}${NAME_DELIMITER}${declaringMethodName}`; + } + return `${NAME_PREFIX}${originName}${NAME_DELIMITER}${declaringMethodName}`; +} + +export class ObjectBindingPatternParameter { + private propertyName: string = ''; + private name: string = ''; + private optional: boolean = false; + + constructor() { + } + + public getName() { + return this.name; + } + + public setName(name: string) { + this.name = name; + } + + public getPropertyName() { + return this.propertyName; + } + + public setPropertyName(propertyName: string) { + this.propertyName = propertyName; + } + + public isOptional() { + return this.optional; + } + + public setOptional(optional: boolean) { + this.optional = optional; + } +} + +export class ArrayBindingPatternParameter { + private propertyName: string = ''; + private name: string = ''; + private optional: boolean = false; + + constructor() { + } + + public getName() { + return this.name; + } + + public setName(name: string) { + this.name = name; + } + + public getPropertyName() { + return this.propertyName; + } + + public setPropertyName(propertyName: string) { + this.propertyName = propertyName; + } + + public isOptional() { + return this.optional; + } + + public setOptional(optional: boolean) { + this.optional = optional; + } +} + +export class MethodParameter implements Value { + private name: string = ''; + private type!: Type; + private optional: boolean = false; + private dotDotDotToken: boolean = false; + private objElements: ObjectBindingPatternParameter[] = []; + private arrayElements: ArrayBindingPatternParameter[] = []; + + constructor() { + } + + public getName() { + return this.name; + } + + public setName(name: string) { + this.name = name; + } + + public getType() { + return this.type; + } + + public setType(type: Type) { + this.type = type; + } + + public isOptional() { + return this.optional; + } + + public setOptional(optional: boolean) { + this.optional = optional; + } + + public hasDotDotDotToken() { + return this.dotDotDotToken; + } + + public setDotDotDotToken(dotDotDotToken: boolean) { + this.dotDotDotToken = dotDotDotToken; + } + + public addObjElement(element: ObjectBindingPatternParameter) { + this.objElements.push(element); + } + + public getObjElements() { + return this.objElements; + } + + public setObjElements(objElements: ObjectBindingPatternParameter[]) { + this.objElements = objElements; + } + + public addArrayElement(element: ArrayBindingPatternParameter) { + this.arrayElements.push(element); + } + + public getArrayElements() { + return this.arrayElements; + } + + public setArrayElements(arrayElements: ArrayBindingPatternParameter[]) { + this.arrayElements = arrayElements; + } + + public getUses(): Value[] { + return []; + } +} + +function needDefaultConstructorInClass(arkClass: ArkClass): boolean { + const originClassType = arkClass.getCategory(); + return arkClass.getMethodWithName(CONSTRUCTOR_NAME) === null && + (originClassType === ClassCategory.CLASS || originClassType === ClassCategory.OBJECT) && + arkClass.getName() !== DEFAULT_ARK_CLASS_NAME && + !arkClass.isDeclare(); +} + +function recursivelyCheckAndBuildSuperConstructor(arkClass: ArkClass): void { + let superClass: ArkClass | null = arkClass.getSuperClass(); + while (superClass !== null) { + if (superClass.getMethodWithName(CONSTRUCTOR_NAME) === null) { + buildDefaultConstructor(superClass); + } + superClass = superClass.getSuperClass(); + } +} + +export function buildDefaultConstructor(arkClass: ArkClass): boolean { + if (!needDefaultConstructorInClass(arkClass)) { + return false; + } + + recursivelyCheckAndBuildSuperConstructor(arkClass); + + const defaultConstructor: ArkMethod = new ArkMethod(); + defaultConstructor.setDeclaringArkClass(arkClass); + defaultConstructor.setCode(''); + defaultConstructor.setIsGeneratedFlag(true); + defaultConstructor.setLineCol(0); + + const thisLocal = new Local(THIS_NAME, new ClassType(arkClass.getSignature())); + const locals: Set = new Set([thisLocal]); + const basicBlock = new BasicBlock(); + basicBlock.setId(0); + + let parameters: MethodParameter[] = []; + let parameterArgs: Value[] = []; + const superConstructor = arkClass.getSuperClass()?.getMethodWithName(CONSTRUCTOR_NAME); + if (superConstructor) { + parameters = superConstructor.getParameters(); + + for (let index = 0; index < parameters.length; index++) { + const parameterRef = new ArkParameterRef(index, parameters[index].getType()); + const parameterLocal = new Local(parameters[index].getName(), parameterRef.getType()); + locals.add(parameterLocal); + parameterArgs.push(parameterLocal); + basicBlock.addStmt(new ArkAssignStmt(parameterLocal, parameterRef)); + index++; + } + } + + basicBlock.addStmt(new ArkAssignStmt(thisLocal, new ArkThisRef(new ClassType(arkClass.getSignature())))); + + if (superConstructor) { + const superMethodSubSignature = new MethodSubSignature(SUPER_NAME, parameters, superConstructor.getReturnType()); + const superMethodSignature = new MethodSignature(arkClass.getSignature(), superMethodSubSignature); + const superInvokeExpr = new ArkStaticInvokeExpr(superMethodSignature, parameterArgs); + basicBlock.addStmt(new ArkInvokeStmt(superInvokeExpr)); + } + + const methodSubSignature = new MethodSubSignature(CONSTRUCTOR_NAME, parameters, thisLocal.getType(), defaultConstructor.isStatic()); + defaultConstructor.setImplementationSignature(new MethodSignature(arkClass.getSignature(), methodSubSignature)); + basicBlock.addStmt(new ArkReturnStmt(thisLocal)); + + const cfg = new Cfg(); + cfg.addBlock(basicBlock); + cfg.setStartingStmt(basicBlock.getHead()!); + cfg.setDeclaringMethod(defaultConstructor); + cfg.getStmts().forEach(s => s.setCfg(cfg)); + + defaultConstructor.setBody(new ArkBody(locals, cfg)); + checkAndUpdateMethod(defaultConstructor, arkClass); + arkClass.addMethod(defaultConstructor); + + return true; +} + +export function buildInitMethod(initMethod: ArkMethod, fieldInitializerStmts: Stmt[], thisLocal: Local): void { + const classType = new ClassType(initMethod.getDeclaringArkClass().getSignature()); + const assignStmt = new ArkAssignStmt(thisLocal, new ArkThisRef(classType)); + const block = new BasicBlock(); + block.setId(0); + block.addStmt(assignStmt); + const locals: Set = new Set([thisLocal]); + for (const stmt of fieldInitializerStmts) { + block.addStmt(stmt); + if (stmt.getDef() && stmt.getDef() instanceof Local) { + locals.add(stmt.getDef() as Local); + } + } + block.addStmt(new ArkReturnVoidStmt()); + const cfg = new Cfg(); + cfg.addBlock(block); + for (const stmt of block.getStmts()) { + stmt.setCfg(cfg); + } + cfg.setStartingStmt(assignStmt); + cfg.buildDefUseStmt(locals); + cfg.setDeclaringMethod(initMethod); + initMethod.setBody(new ArkBody(locals, cfg)); +} + +export function addInitInConstructor(constructor: ArkMethod): void { + const thisLocal = constructor.getBody()?.getLocals().get(THIS_NAME); + if (!thisLocal) { + return; + } + const blocks = constructor.getCfg()?.getBlocks(); + if (!blocks) { + return; + } + const firstBlockStmts = [...blocks][0].getStmts(); + let index = 0; + for (let i = 0; i < firstBlockStmts.length; i++) { + const stmt = firstBlockStmts[i]; + if (stmt instanceof ArkInvokeStmt && stmt.getInvokeExpr().getMethodSignature().getMethodSubSignature().getMethodName() === SUPER_NAME) { + index++; + continue; + } + if (stmt instanceof ArkAssignStmt) { + const rightOp = stmt.getRightOp(); + if (rightOp instanceof ArkParameterRef || rightOp instanceof ArkThisRef || rightOp instanceof ClosureFieldRef) { + index++; + continue; + } + } + break; + } + const initInvokeStmt = new ArkInvokeStmt( + new ArkInstanceInvokeExpr(thisLocal, constructor.getDeclaringArkClass().getInstanceInitMethod().getSignature(), [])); + firstBlockStmts.splice(index, 0, initInvokeStmt); +} + +export function isMethodImplementation(node: MethodLikeNode): boolean { + if (ts.isFunctionDeclaration(node) || + ts.isMethodDeclaration(node) || + ts.isConstructorDeclaration(node) || + ts.isGetAccessorDeclaration(node) || + ts.isSetAccessorDeclaration(node) || + ts.isFunctionExpression(node) || + ts.isArrowFunction(node)) { + if (node.body !== undefined) { + return true; + } + } + return false; +} + +export function checkAndUpdateMethod(method: ArkMethod, cls: ArkClass): void { + let presentMethod: ArkMethod | null; + if (method.isStatic()) { + presentMethod = cls.getStaticMethodWithName(method.getName()); + } else { + presentMethod = cls.getMethodWithName(method.getName()); + } + if (presentMethod === null) { + return; + } + + if (method.validate().errCode !== ArkErrorCode.OK || presentMethod.validate().errCode !== ArkErrorCode.OK) { + return; + } + const presentDeclareSignatures = presentMethod.getDeclareSignatures(); + const presentDeclareLineCols = presentMethod.getDeclareLineCols(); + const presentImplSignature = presentMethod.getImplementationSignature(); + const newDeclareSignature = method.getDeclareSignatures(); + const newDeclareLineCols = method.getDeclareLineCols(); + const newImplSignature = method.getImplementationSignature(); + + if (presentDeclareSignatures !== null && presentImplSignature === null) { + if (newDeclareSignature === null || presentMethod.getDeclareSignatureIndex(newDeclareSignature[0]) >= 0) { + method.setDeclareSignatures(presentDeclareSignatures); + method.setDeclareLineCols((presentDeclareLineCols as number[])); + } else { + method.setDeclareSignatures(presentDeclareSignatures.concat(newDeclareSignature)); + method.setDeclareLineCols((presentDeclareLineCols as number[]).concat(newDeclareLineCols as number[])); + } + return; + } + if (presentDeclareSignatures === null && presentImplSignature !== null) { + if (newImplSignature === null) { + method.setImplementationSignature(presentImplSignature); + method.setLineCol(presentMethod.getLineCol() as number); + } + return; + } +} + diff --git a/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkNamespaceBuilder.ts b/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkNamespaceBuilder.ts new file mode 100644 index 0000000000..a4d4b6428d --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkNamespaceBuilder.ts @@ -0,0 +1,196 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { LineColPosition } from '../../base/Position'; +import { buildDefaultArkClassFromArkNamespace, buildNormalArkClassFromArkNamespace } from './ArkClassBuilder'; +import { ArkFile } from '../ArkFile'; +import { buildArkMethodFromArkClass } from './ArkMethodBuilder'; +import ts from 'ohos-typescript'; +import { ArkNamespace } from '../ArkNamespace'; +import { buildDecorators, buildModifiers } from './builderUtils'; +import Logger, { LOG_MODULE_TYPE } from '../../../utils/logger'; +import { buildExportAssignment, buildExportDeclaration, buildExportInfo } from './ArkExportBuilder'; +import { ArkClass } from '../ArkClass'; +import { ArkMethod } from '../ArkMethod'; +import { NamespaceSignature } from '../ArkSignature'; +import { IRUtils } from '../../common/IRUtils'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'ArkNamespaceBuilder'); + +export function buildArkNamespace(node: ts.ModuleDeclaration, declaringInstance: ArkFile | ArkNamespace, ns: ArkNamespace, sourceFile: ts.SourceFile) { + // modifiers + if (node.modifiers) { + ns.setModifiers(buildModifiers(node)); + ns.setDecorators(buildDecorators(node, sourceFile)); + } + + if (declaringInstance instanceof ArkFile) { + ns.setDeclaringArkFile(declaringInstance); + } else { + ns.setDeclaringArkNamespace(declaringInstance); + ns.setDeclaringArkFile(declaringInstance.getDeclaringArkFile()); + } + ns.setDeclaringInstance(declaringInstance); + const namespaceName = node.name.text; + const namespaceSignature = new NamespaceSignature(namespaceName, ns.getDeclaringArkFile().getFileSignature(), + ns.getDeclaringArkNamespace()?.getSignature() || null); + ns.setSignature(namespaceSignature); + + // TODO: whether needed? + ns.setCode(node.getText(sourceFile)); + + // set line and column + const { line, character } = ts.getLineAndCharacterOfPosition( + sourceFile, + node.getStart(sourceFile), + ); + ns.setLine(line + 1); + ns.setColumn(character + 1); + + genDefaultArkClass(ns, node, sourceFile); + + // build ns member + if (node.body) { + if (ts.isModuleBlock(node.body)) { + buildNamespaceMembers(node.body, ns, sourceFile); + } + // NamespaceDeclaration extends ModuleDeclaration + //TODO: Check + else if (ts.isModuleDeclaration(node.body)) { + logger.warn('This ModuleBody is an NamespaceDeclaration.'); + let childNs: ArkNamespace = new ArkNamespace(); + buildArkNamespace(node.body, ns, childNs, sourceFile); + ns.addNamespace(childNs); + } else if (ts.isIdentifier(node.body)) { + logger.warn('ModuleBody is Identifier.'); + } else { + logger.warn('JSDocNamespaceDeclaration found.'); + } + } else { + logger.warn('JSDocNamespaceDeclaration found.'); + } + IRUtils.setComments(ns, node, sourceFile, ns.getDeclaringArkFile().getScene().getOptions()); +} + +// TODO: check and update +function buildNamespaceMembers(node: ts.ModuleBlock, namespace: ArkNamespace, sourceFile: ts.SourceFile) { + const statements = node.statements; + const nestedNamespaces: ArkNamespace[] = []; + statements.forEach((child) => { + if ( + ts.isModuleDeclaration(child) + ) { + let childNs: ArkNamespace = new ArkNamespace(); + childNs.setDeclaringArkNamespace(namespace); + childNs.setDeclaringArkFile(namespace.getDeclaringArkFile()); + + buildArkNamespace(child, namespace, childNs, sourceFile); + nestedNamespaces.push(childNs); + } else if ( + ts.isClassDeclaration(child) || + ts.isInterfaceDeclaration(child) || + ts.isEnumDeclaration(child) || + ts.isStructDeclaration(child) + ) { + let cls: ArkClass = new ArkClass(); + + buildNormalArkClassFromArkNamespace(child, namespace, cls, sourceFile); + namespace.addArkClass(cls); + + if (cls.isExported()) { + namespace.addExportInfo(buildExportInfo(cls, namespace.getDeclaringArkFile(), + LineColPosition.buildFromNode(child, sourceFile))); + } + } + // TODO: Check + else if (ts.isMethodDeclaration(child)) { + logger.warn('This is a MethodDeclaration in ArkNamespace.'); + let mthd: ArkMethod = new ArkMethod(); + + buildArkMethodFromArkClass(child, namespace.getDefaultClass(), mthd, sourceFile); + + if (mthd.isExported()) { + namespace.addExportInfo(buildExportInfo(mthd, namespace.getDeclaringArkFile(), + LineColPosition.buildFromNode(child, sourceFile))); + } + } else if (ts.isFunctionDeclaration(child)) { + let mthd: ArkMethod = new ArkMethod(); + + buildArkMethodFromArkClass(child, namespace.getDefaultClass(), mthd, sourceFile); + + if (mthd.isExported()) { + namespace.addExportInfo(buildExportInfo(mthd, namespace.getDeclaringArkFile(), + LineColPosition.buildFromNode(child, sourceFile))); + } + } else if (ts.isExportDeclaration(child)) { + buildExportDeclaration(child, sourceFile, namespace.getDeclaringArkFile()) + .forEach(item => namespace.addExportInfo(item)); + } else if (ts.isExportAssignment(child)) { + buildExportAssignment(child, sourceFile, namespace.getDeclaringArkFile()) + .forEach(item => namespace.addExportInfo(item)); + } else { + logger.info('Child joined default method of arkFile: ', ts.SyntaxKind[child.kind]); + // join default method + } + }); + + const nestedMergedNameSpaces = mergeNameSpaces(nestedNamespaces); + nestedMergedNameSpaces.forEach(nestedNameSpace => { + namespace.addNamespace(nestedNameSpace); + if (nestedNameSpace.isExport()) { + const linCol = new LineColPosition(nestedNameSpace.getLine(), nestedNameSpace.getColumn()); + namespace.addExportInfo(buildExportInfo(nestedNameSpace, namespace.getDeclaringArkFile(), linCol)); + } + }); +} + +function genDefaultArkClass(ns: ArkNamespace, node: ts.ModuleDeclaration, sourceFile: ts.SourceFile) { + let defaultClass = new ArkClass(); + + buildDefaultArkClassFromArkNamespace(ns, defaultClass, node, sourceFile); + ns.setDefaultClass(defaultClass); + ns.addArkClass(defaultClass); +} + + +export function mergeNameSpaces(arkNamespaces: ArkNamespace[]): ArkNamespace[] { + const namespaceMap = new Map(); + for (let i = 0; i < arkNamespaces.length; i++) { + const currNamespace = arkNamespaces[i]; + const currName = currNamespace.getName(); + if (namespaceMap.has(currName)) { + const prevNamespace = namespaceMap.get(currName)!; + const nestedPrevNamespaces = prevNamespace.getNamespaces(); + const nestedCurrNamespaces = currNamespace.getNamespaces(); + const nestedMergedNameSpaces = mergeNameSpaces([...nestedPrevNamespaces, ...nestedCurrNamespaces]); + nestedMergedNameSpaces.forEach(nestedNameSpace => { + prevNamespace.addNamespace(nestedNameSpace); + }); + const classes = currNamespace.getClasses(); + classes.forEach(cls => { + prevNamespace.addArkClass(cls); + }); + const preSourceCodes = prevNamespace.getCodes(); + const currSourceCodes = currNamespace.getCodes(); + prevNamespace.setCodes([...preSourceCodes, ...currSourceCodes]); + const prevLineColPairs = prevNamespace.getLineColPairs(); + const currLineColPairs = currNamespace.getLineColPairs(); + prevNamespace.setLineCols([...prevLineColPairs, ...currLineColPairs]); + } else { + namespaceMap.set(currName, currNamespace); + } + } + return [...namespaceMap.values()]; +} diff --git a/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkSignatureBuilder.ts b/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkSignatureBuilder.ts new file mode 100644 index 0000000000..1c0ecdaefd --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkSignatureBuilder.ts @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ClassSignature, FieldSignature, FileSignature, MethodSignature, MethodSubSignature } from '../ArkSignature'; +import { UnknownType } from '../../base/Type'; + +export class ArkSignatureBuilder { + public static buildMethodSignatureFromClassNameAndMethodName(className: string, methodName: string, + staticFlag: boolean = false): MethodSignature { + const classSignature = this.buildClassSignatureFromClassName(className); + const methodSubSignature = this.buildMethodSubSignatureFromMethodName(methodName, staticFlag); + return new MethodSignature(classSignature, methodSubSignature); + } + + public static buildMethodSignatureFromMethodName(methodName: string, staticFlag: boolean = false): MethodSignature { + const methodSubSignature = this.buildMethodSubSignatureFromMethodName(methodName, staticFlag); + return new MethodSignature(ClassSignature.DEFAULT, methodSubSignature); + } + + public static buildMethodSubSignatureFromMethodName(methodName: string, + staticFlag: boolean = false): MethodSubSignature { + return new MethodSubSignature(methodName, [], UnknownType.getInstance(), staticFlag); + } + + public static buildClassSignatureFromClassName(className: string): ClassSignature { + return new ClassSignature(className, FileSignature.DEFAULT); + } + + public static buildFieldSignatureFromFieldName(fieldName: string, staticFlag: boolean = false): FieldSignature { + return new FieldSignature(fieldName, ClassSignature.DEFAULT, UnknownType.getInstance(), staticFlag); + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/model/builder/BodyBuilder.ts b/ets2panda/linter/arkanalyzer/src/core/model/builder/BodyBuilder.ts new file mode 100644 index 0000000000..67f2d15b4a --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/model/builder/BodyBuilder.ts @@ -0,0 +1,601 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkBody } from '../ArkBody'; +import { ArkMethod } from '../ArkMethod'; +import { FieldSignature, MethodSignature, methodSignatureCompare, MethodSubSignature } from '../ArkSignature'; +import { CfgBuilder } from '../../graph/builder/CfgBuilder'; +import * as ts from 'ohos-typescript'; +import { Local } from '../../base/Local'; +import { MethodParameter } from './ArkMethodBuilder'; +import { LEXICAL_ENV_NAME_PREFIX, NAME_DELIMITER, NAME_PREFIX } from '../../common/Const'; +import { ArkParameterRef, ArkStaticFieldRef, ClosureFieldRef, GlobalRef } from '../../base/Ref'; +import { ArkAliasTypeDefineStmt, ArkAssignStmt, ArkInvokeStmt, ArkReturnStmt } from '../../base/Stmt'; +import { + AliasType, + ArrayType, + ClosureType, + FunctionType, + LexicalEnvType, + Type, + UnclearReferenceType, + UnionType, +} from '../../base/Type'; +import { AbstractInvokeExpr, ArkPtrInvokeExpr } from '../../base/Expr'; + +type NestedMethodChain = { + parent: ArkMethod; + children: NestedMethodChain[] | null; +}; + +export class BodyBuilder { + private cfgBuilder: CfgBuilder; + private globals?: Map; + + constructor(methodSignature: MethodSignature, sourceAstNode: ts.Node, declaringMethod: ArkMethod, sourceFile: ts.SourceFile) { + this.cfgBuilder = new CfgBuilder(sourceAstNode, methodSignature.getMethodSubSignature().getMethodName(), declaringMethod, sourceFile); + } + + public build(): ArkBody | null { + this.cfgBuilder.buildCfgBuilder(); + if (!this.cfgBuilder.isBodyEmpty()) { + const { cfg, locals, globals, aliasTypeMap, traps } = this.cfgBuilder.buildCfg(); + if (globals !== null) { + this.setGlobals(globals); + } + cfg.buildDefUseStmt(locals); + + return new ArkBody(locals, cfg, aliasTypeMap, traps.length ? traps : undefined); + } + return null; + } + + public getCfgBuilder(): CfgBuilder { + return this.cfgBuilder; + } + + public getGlobals(): Map | undefined { + return this.globals; + } + + public setGlobals(globals: Map): void { + this.globals = globals; + } + + /** + * Find out all locals in the parent method which are used by the childrenChain, these locals are the closures of the root node of the childrenChain. + * childrenChain contains all nested method from the root node of the childrenChain. + * baseLocals are all locals defined in the outer function. + * allNestedLocals are collect all locals defined in all outer functions of this childrenChain. + * Only the globals of the root of the childrenChain, which are in the baseLocals but not in the allNestedLocals are the actual closures that in baseLocals. + */ + private findClosuresUsedInNested(childrenChain: NestedMethodChain, baseLocals: Map, allNestedLocals: Map): Local[] | null { + let closuresRes: Local[] = []; + + const nestedMethod = childrenChain.parent; + let nestedGlobals = nestedMethod.getBodyBuilder()?.getGlobals(); + if (nestedGlobals !== undefined) { + for (let global of nestedGlobals.values()) { + const nestedLocal = allNestedLocals.get(global.getName()); + const closure = baseLocals.get(global.getName()); + if (nestedLocal === undefined && closure !== undefined) { + closuresRes.push(closure); + } + } + } + const children = childrenChain.children; + if (children === null) { + return closuresRes; + } + for (let chain of children) { + const nestedLocals = nestedMethod.getBody()?.getLocals(); + if (nestedLocals !== undefined) { + nestedLocals.forEach((value, key) => { + allNestedLocals.set(key, value); + }); + } + const closures = this.findClosuresUsedInNested(chain, baseLocals, allNestedLocals); + if (closures) { + closuresRes.push(...closures); + } + } + return closuresRes; + } + + /** + * 1. Find out all locals in the parent method which are used by the childrenChain, these locals are the closures of the root node of the childrenChain. + * 2. Create a lexical env local in the parent method, and pass it to root node of the childrenChain through the method signature. + * 3. Update the root node of the childrenChain to add parameterRef assign stmt and closureRef assign stmt. + * 4. Recursively do this for all nested method level by level. + */ + private buildLexicalEnv(childrenChain: NestedMethodChain, baseLocals: Map, index: number): number { + let usedClosures = this.findClosuresUsedInNested(childrenChain, baseLocals, new Map); + const nestedMethod = childrenChain.parent; + const nestedSignature = nestedMethod.getImplementationSignature(); + if (nestedSignature !== null && usedClosures !== null && usedClosures.length > 0) { + let lexicalEnv = new LexicalEnvType(nestedSignature, usedClosures); + const closuresLocal = new Local(`${LEXICAL_ENV_NAME_PREFIX}${index++}`, lexicalEnv); + baseLocals.set(closuresLocal.getName(), closuresLocal); + this.updateNestedMethodWithClosures(nestedMethod, closuresLocal); + } else if (usedClosures === null || usedClosures.length === 0) { + this.moveCurrentMethodLocalToGlobal(nestedMethod); + } + + const nextNestedChains = childrenChain.children; + if (nextNestedChains === null) { + return index; + } + for (let nextChain of nextNestedChains) { + const newBaseLocals = nestedMethod.getBody()?.getLocals(); + if (newBaseLocals === undefined) { + return index; + } + index = this.buildLexicalEnv(nextChain, newBaseLocals, index); + } + return index; + } + + /** + * Find out and tag all closures from globals, and remove closures from both globals and locals. + * Precondition: body build has been done. All locals, globals and closures are both set as Local in body, + * while potential globals and closures are also recorded in bodybuilder. + * Constraint: only the outermost function can call this method to recursively handle closures of itself as well as all nested methods. + */ + public handleGlobalAndClosure(): void { + /** + * Step1: Handle the outermost function, take it as Level 0. + * There must be no closures in Level 0. So only need to remove the locals which with the same name as the ones in globals. + */ + let outerMethod = this.getCfgBuilder().getDeclaringMethod(); + let outerGlobals = outerMethod.getBodyBuilder()?.getGlobals(); + outerMethod.freeBodyBuilder(); + let outerLocals = outerMethod.getBody()?.getLocals(); + if (outerGlobals !== undefined && outerLocals !== undefined) { + outerGlobals.forEach((value, key) => { + const local = outerLocals!.get(key); + if (local !== undefined) { + value.addUsedStmts(local.getUsedStmts()); + outerLocals!.delete(key); + } + }); + if (outerGlobals.size > 0) { + outerMethod.getBody()?.setUsedGlobals(outerGlobals); + } + } + + let nestedMethodChains = this.generateNestedMethodChains(outerMethod).children; + if (nestedMethodChains === null || outerLocals === undefined) { + return; + } + let closuresIndex = 0; + for (let nestedChain of nestedMethodChains) { + /** + * Step2: Handle each nested function in Level 1 one by one. + * Find out all closures from Level 0 used by these Level 1 functions as well as all their children nested functions. + * This will be done level by level recursively. + */ + closuresIndex = this.buildLexicalEnv(nestedChain, outerLocals, closuresIndex); + + /** + * Step3: Delete old globals which are recognized as closures, then the rest globals are the true globals. + * The redundancy locals should be deleted but the used stmts of them should be restored to globals. + * This will be done level by level recursively. + */ + this.reorganizeGlobalAndLocal(nestedChain); + + /** + * Step4: Infer UnclearReferenceType to check whether it is the type alias define in its parent function.. + */ + this.inferTypesDefineInOuter(outerMethod, nestedChain); + + /** + * Step5: For each nested function, find out whether it is called by its parent function and update the related locals, globals and stmts. + */ + this.updateNestedMethodUsedInOuter(nestedChain); + + this.freeBodyBuilder(nestedChain); + } + } + + private freeBodyBuilder(nestedChain: NestedMethodChain): void { + nestedChain.parent.freeBodyBuilder(); + const childrenChains = nestedChain.children; + if (childrenChains === null) { + return; + } + for (const chain of childrenChains) { + this.freeBodyBuilder(chain); + } + } + + private updateLocalTypesWithTypeAlias(locals: Map, typeAliases: Map): void { + for (let local of locals.values()) { + const newType = this.inferUnclearReferenceTypeWithTypeAlias(local.getType(), typeAliases); + if (newType !== null) { + local.setType(newType); + } + } + } + + private inferUnclearReferenceTypeWithTypeAlias(localType: Type, typeAliases: Map): Type | null { + if (localType instanceof ArrayType && localType.getBaseType() instanceof UnclearReferenceType) { + const typeAlias = typeAliases.get((localType.getBaseType() as UnclearReferenceType).getName()); + if (typeAlias !== undefined) { + localType.setBaseType(typeAlias[0]); + return localType; + } + return null; + } + if (localType instanceof UnionType) { + const optionTypes = localType.getTypes(); + for (let i = 0; i < optionTypes.length; i++) { + const newType = this.inferUnclearReferenceTypeWithTypeAlias(optionTypes[i], typeAliases); + if (newType !== null) { + optionTypes[i] = newType; + } + } + return localType; + } + if (localType instanceof UnclearReferenceType) { + const typeAlias = typeAliases.get(localType.getName()); + if (typeAlias !== undefined) { + return typeAlias[0]; + } + } + return null; + } + + private generateNestedMethodChains(outerMethod: ArkMethod): NestedMethodChain { + let candidateMethods: ArkMethod[] = []; + outerMethod.getDeclaringArkClass().getMethods().forEach(method => { + if (method.getName().startsWith(NAME_PREFIX) && method.getName().endsWith(`${NAME_DELIMITER}${outerMethod.getName()}`)) { + candidateMethods.push(method); + } + }); + const childrenChains = this.getNestedChildrenChains(outerMethod, candidateMethods); + if (childrenChains.length > 0) { + return { parent: outerMethod, children: childrenChains }; + } + return { parent: outerMethod, children: null }; + } + + private getNestedChildrenChains(parentMethod: ArkMethod, candidateMethods: ArkMethod[]): NestedMethodChain[] { + let nestedMethodChain: NestedMethodChain[] = []; + for (let method of candidateMethods) { + const outerMethodSignature = method.getOuterMethod()?.getSignature(); + if (outerMethodSignature !== undefined && methodSignatureCompare(parentMethod.getSignature(), outerMethodSignature)) { + const childrenChains = this.getNestedChildrenChains(method, candidateMethods); + if (childrenChains.length > 0) { + nestedMethodChain.push({parent: method, children: childrenChains}); + } else { + nestedMethodChain.push({parent: method, children: null}); + } + } + } + return nestedMethodChain; + } + + private moveCurrentMethodLocalToGlobal(method: ArkMethod): void { + const globals = method.getBodyBuilder()?.getGlobals(); + const locals = method.getBody()?.getLocals(); + if (locals === undefined || globals === undefined) { + return; + } + globals.forEach((value, key) => { + const local = locals.get(key); + if (local !== undefined) { + value.addUsedStmts(local.getUsedStmts()); + locals.delete(key); + } + }); + + if (globals.size > 0) { + method.getBody()?.setUsedGlobals(globals); + } + } + + private reorganizeGlobalAndLocal(nestedChain: NestedMethodChain): void { + const nestedMethod = nestedChain.parent; + const params = nestedMethod.getSubSignature().getParameters(); + const globals = nestedMethod.getBodyBuilder()?.getGlobals(); + if (params.length > 0 && params[0].getType() instanceof LexicalEnvType && globals !== undefined) { + const closures = (params[0].getType() as LexicalEnvType).getClosures(); + for (let closure of closures) { + globals.delete(closure.getName()); + } + } + + this.moveCurrentMethodLocalToGlobal(nestedMethod); + + const childrenChains = nestedChain.children; + if (childrenChains === null) { + return; + } + for (const chain of childrenChains) { + this.reorganizeGlobalAndLocal(chain); + } + } + + // 对嵌套函数中的UnclearReferenceType类型的变量进行类型推导,类型是否为外层函数中定义的类型别名 + private inferTypesDefineInOuter(outerMethod: ArkMethod, childrenChain: NestedMethodChain): void { + const typeAliases = outerMethod.getBody()?.getAliasTypeMap(); + const nestedLocals = childrenChain.parent.getBody()?.getLocals(); + if (typeAliases !== undefined && nestedLocals !== undefined) { + this.updateLocalTypesWithTypeAlias(nestedLocals, typeAliases); + } + const childrenChains = childrenChain.children; + if (childrenChains === null) { + return; + } + for (const chain of childrenChains) { + this.inferTypesDefineInOuter(childrenChain.parent, chain); + } + } + + private updateNestedMethodUsedInOuter(nestedChain: NestedMethodChain) : void { + const nestedMethod = nestedChain.parent; + const outerMethod = nestedMethod.getOuterMethod(); + if (outerMethod === undefined) { + return; + } + const outerLocals = outerMethod.getBody()?.getLocals(); + if (outerLocals !== undefined) { + for (let local of outerLocals.values()) { + if (local.getType() instanceof LexicalEnvType && + methodSignatureCompare((local.getType() as LexicalEnvType).getNestedMethod(), nestedMethod.getSignature())) { + this.updateOuterMethodWithClosures(outerMethod, nestedMethod, local); + break; + } + } + } + + const nestedMethodName = nestedMethod.getName(); + const originalMethodName = this.getOriginalNestedMethodName(nestedMethodName) ?? ''; + const outerGlobals = outerMethod.getBody()?.getUsedGlobals(); + const callGlobal = outerGlobals?.get(nestedMethodName) ?? outerGlobals?.get(originalMethodName); + if (callGlobal !== undefined && callGlobal instanceof GlobalRef && callGlobal.getRef() === null) { + const fieldSignature = new FieldSignature( + nestedMethodName, + nestedMethod.getDeclaringArkClass().getSignature(), + new FunctionType(nestedMethod.getSignature())); + callGlobal.setRef(new ArkStaticFieldRef((fieldSignature))); + } + + const childrenChains = nestedChain.children; + if (childrenChains === null) { + return; + } + for (const chain of childrenChains) { + this.updateNestedMethodUsedInOuter(chain); + } + } + + private updateNestedMethodWithClosures(nestedMethod: ArkMethod, closuresLocal: Local): void { + if (!(closuresLocal.getType() instanceof LexicalEnvType)) { + return; + } + + const declareSignatures = nestedMethod.getDeclareSignatures(); + declareSignatures?.forEach((signature, index) => { + nestedMethod.setDeclareSignatureWithIndex(this.createNewSignatureWithClosures(closuresLocal, signature), index); + }); + + const implementSignature = nestedMethod.getImplementationSignature(); + if (implementSignature !== null) { + nestedMethod.setImplementationSignature(this.createNewSignatureWithClosures(closuresLocal, implementSignature)); + } + + this.addClosureParamsAssignStmts(closuresLocal, nestedMethod); + } + + private updateOuterMethodWithClosures(outerMethod: ArkMethod, nestedMethod: ArkMethod, closuresLocal: Local): void { + const nestedMethodName = nestedMethod.getName(); + const nestedMethodLocal = outerMethod.getBody()?.getLocals().get(nestedMethodName); + if (nestedMethodLocal !== undefined) { + this.updateLocalInfoWithClosures(nestedMethodLocal, outerMethod, nestedMethod, closuresLocal); + } else { + const nestedMethodGlobal = outerMethod.getBody()?.getUsedGlobals()?.get(nestedMethodName); + if (nestedMethodGlobal !== undefined && nestedMethodGlobal instanceof GlobalRef) { + this.updateGlobalInfoWithClosures(nestedMethodGlobal, outerMethod, nestedMethod, closuresLocal); + } + } + + const originalMethodName = this.getOriginalNestedMethodName(nestedMethodName); + if (originalMethodName === null) { + return; + } + const originalMethodLocal = outerMethod.getBody()?.getLocals().get(originalMethodName); + if (originalMethodLocal !== undefined) { + this.updateLocalInfoWithClosures(originalMethodLocal, outerMethod, nestedMethod, closuresLocal); + } else { + const originalMethodGlobal = outerMethod.getBody()?.getUsedGlobals()?.get(originalMethodName); + if (originalMethodGlobal !== undefined && originalMethodGlobal instanceof GlobalRef) { + this.updateGlobalInfoWithClosures(originalMethodGlobal, outerMethod, nestedMethod, closuresLocal); + } + } + } + + private getOriginalNestedMethodName(nestedMethodName: string): string | null { + if (nestedMethodName.startsWith(NAME_PREFIX) && nestedMethodName.includes(NAME_DELIMITER)) { + const nameComponents = nestedMethodName.slice(1).split(NAME_DELIMITER); + if (nameComponents.length > 1) { + return nameComponents[0]; + } + } + return null; + } + + private updateGlobalInfoWithClosures(globalRef: GlobalRef, outerMethod: ArkMethod, nestedMethod: ArkMethod, closuresLocal: Local): void { + if (globalRef.getRef() !== null) { + return; + } + const methodSignature = nestedMethod.getImplementationSignature(); + if (methodSignature === null) { + return; + } + const lexicalEnv = closuresLocal.getType(); + if (!(lexicalEnv instanceof LexicalEnvType)) { + return; + } + const fieldSignature = new FieldSignature( + methodSignature.getMethodSubSignature().getMethodName(), + methodSignature.getDeclaringClassSignature(), + new ClosureType(lexicalEnv, methodSignature)); + globalRef.setRef(new ArkStaticFieldRef((fieldSignature))); + this.updateAbstractInvokeExprWithClosures(globalRef, outerMethod.getSignature(), nestedMethod.getSignature(), closuresLocal); + } + + private updateLocalInfoWithClosures(local: Local, outerMethod: ArkMethod, nestedMethod: ArkMethod, closuresLocal: Local): void { + const localType = local.getType(); + if (!(localType instanceof FunctionType)) { + return; + } + + const lexicalEnv = closuresLocal.getType(); + if (!(lexicalEnv instanceof LexicalEnvType)) { + return; + } + + // 更新local的类型为ClosureType,methodSignature为内层嵌套函数 + const nestedMethodSignature = nestedMethod.getImplementationSignature(); + if (nestedMethodSignature !== null) { + local.setType(new ClosureType(lexicalEnv, nestedMethodSignature, localType.getRealGenericTypes())); + } else { + local.setType(new ClosureType(lexicalEnv, localType.getMethodSignature(), localType.getRealGenericTypes())); + } + + this.updateAbstractInvokeExprWithClosures(local, outerMethod.getSignature(), nestedMethod.getSignature(), closuresLocal); + } + + // 更新所有stmt中调用内层函数处的AbstractInvokeExpr中的函数签名和实参args,加入闭包参数 + // 更新所有stmt中定义的函数指针的usedStmt中的函数签名和实参args,加入闭包参数 + private updateAbstractInvokeExprWithClosures(value: Local | GlobalRef, outerMethodSignature: MethodSignature, + nestedMethodSignature: MethodSignature, closuresLocal: Local): void { + for (const usedStmt of value.getUsedStmts()) { + if (usedStmt instanceof ArkInvokeStmt) { + this.updateSignatureAndArgsInArkInvokeExpr(usedStmt, nestedMethodSignature, closuresLocal); + } else if (usedStmt instanceof ArkAssignStmt) { + const rightOp = usedStmt.getRightOp(); + if (rightOp instanceof AbstractInvokeExpr) { + this.updateSignatureAndArgsInArkInvokeExpr(usedStmt, nestedMethodSignature, closuresLocal); + } + const leftOp = usedStmt.getLeftOp(); + if (leftOp instanceof Local) { + leftOp.setType(rightOp.getType()); + } + } else if (usedStmt instanceof ArkReturnStmt) { + outerMethodSignature.getMethodSubSignature().setReturnType(value.getType()); + } + const defValue = usedStmt.getDef(); + if (defValue === null) { + continue; + } + if ((defValue instanceof Local || defValue instanceof GlobalRef) && defValue.getType() instanceof FunctionType) { + this.updateAbstractInvokeExprWithClosures(defValue, outerMethodSignature, nestedMethodSignature, closuresLocal); + } + } + } + + private createNewSignatureWithClosures(closuresLocal: Local, oldSignature: MethodSignature): MethodSignature { + let oldSubSignature = oldSignature.getMethodSubSignature(); + const params = oldSubSignature.getParameters(); + const closuresParam = new MethodParameter(); + closuresParam.setName(closuresLocal.getName()); + closuresParam.setType(closuresLocal.getType()); + params.unshift(closuresParam); + let newSubSignature = new MethodSubSignature( + oldSubSignature.getMethodName(), + params, + oldSubSignature.getReturnType(), + oldSubSignature.isStatic() + ); + return new MethodSignature(oldSignature.getDeclaringClassSignature(), newSubSignature); + } + + private updateSignatureAndArgsInArkInvokeExpr(stmt: ArkInvokeStmt | ArkAssignStmt, methodSignature: MethodSignature, closuresLocal: Local): void { + let expr: AbstractInvokeExpr; + if (stmt instanceof ArkInvokeStmt) { + expr = stmt.getInvokeExpr(); + } else { + const rightOp = stmt.getRightOp(); + if (!(rightOp instanceof AbstractInvokeExpr)) { + return; + } + expr = rightOp; + } + const exprMethodName = expr.getMethodSignature().getMethodSubSignature().getMethodName(); + const nestedMethodName = methodSignature.getMethodSubSignature().getMethodName(); + if (exprMethodName === nestedMethodName) { + expr.setMethodSignature(this.createNewSignatureWithClosures(closuresLocal, methodSignature)); + expr.getArgs().unshift(closuresLocal); + closuresLocal.addUsedStmt(stmt); + return; + } + + const originalMethodName = this.getOriginalNestedMethodName(nestedMethodName); + if (originalMethodName !== null) { + if (exprMethodName === originalMethodName || expr instanceof ArkPtrInvokeExpr) { + expr.setMethodSignature(methodSignature); + expr.getArgs().unshift(closuresLocal); + closuresLocal.addUsedStmt(stmt); + } + } + } + + private addClosureParamsAssignStmts(closuresParam: Local, method: ArkMethod): void { + const lexicalEnv = closuresParam.getType(); + if (!(lexicalEnv instanceof LexicalEnvType)) { + return; + } + const closures = lexicalEnv.getClosures(); + if (closures.length === 0) { + return; + } + const oldParamRefs = method.getParameterRefs(); + let body = method.getBody(); + if (body === undefined) { + return; + } + let stmts = Array.from(body.getCfg().getBlocks())[0].getStmts(); + let index = 0; + const parameterRef = new ArkParameterRef(index, lexicalEnv); + const closuresLocal = new Local(closuresParam.getName(), lexicalEnv); + body.addLocal(closuresLocal.getName(), closuresLocal); + let assignStmt = new ArkAssignStmt(closuresLocal, parameterRef); + stmts.splice(index, 0, assignStmt); + closuresLocal.setDeclaringStmt(assignStmt); + + oldParamRefs?.forEach((paramRef) => { + index++; + paramRef.setIndex(index); + }); + + for (let closure of closures) { + let local = body.getLocals().get(closure.getName()); + if (local === undefined) { + local = new Local(closure.getName(), closure.getType()); + body.addLocal(local.getName(), local); + } else { + local.setType(closure.getType()); + } + index++; + const closureFieldRef = new ClosureFieldRef(closuresParam, closure.getName(), closure.getType()); + let assignStmt = new ArkAssignStmt(local, closureFieldRef); + stmts.splice(index, 0, assignStmt); + local.setDeclaringStmt(assignStmt); + closuresLocal.addUsedStmt(assignStmt); + } + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/core/model/builder/builderUtils.ts b/ets2panda/linter/arkanalyzer/src/core/model/builder/builderUtils.ts new file mode 100644 index 0000000000..73c93776b2 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/core/model/builder/builderUtils.ts @@ -0,0 +1,579 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import ts, { HeritageClause, ParameterDeclaration, TypeNode, TypeParameterDeclaration } from 'ohos-typescript'; +import { + AliasType, + ArrayType, + ClassType, + FunctionType, + GenericType, + IntersectionType, + TupleType, + Type, + UnclearReferenceType, + UnionType, + UnknownType, +} from '../../base/Type'; +import { TypeInference } from '../../common/TypeInference'; +import { ArkField } from '../ArkField'; +import Logger, { LOG_MODULE_TYPE } from '../../../utils/logger'; +import { ArkClass } from '../ArkClass'; +import { ArkMethod } from '../ArkMethod'; +import { Decorator } from '../../base/Decorator'; +import { + ArrayBindingPatternParameter, + buildArkMethodFromArkClass, + MethodParameter, + ObjectBindingPatternParameter, +} from './ArkMethodBuilder'; +import { buildNormalArkClassFromArkMethod } from './ArkClassBuilder'; +import { Builtin } from '../../common/Builtin'; +import { modifierKind2Enum } from '../ArkBaseModel'; +import { ArkValueTransformer } from '../../common/ArkValueTransformer'; +import { KeyofTypeExpr, TypeQueryExpr } from '../../base/TypeExpr'; +import { + ANY_KEYWORD, + BIGINT_KEYWORD, + BOOLEAN_KEYWORD, NEVER_KEYWORD, + NULL_KEYWORD, + NUMBER_KEYWORD, + STRING_KEYWORD, + THIS_NAME, + UNDEFINED_KEYWORD, VOID_KEYWORD, +} from '../../common/TSConst'; +import { ArkSignatureBuilder } from './ArkSignatureBuilder'; +import { ArkInstanceFieldRef } from '../../base/Ref'; +import { Local } from '../../base/Local'; +import { Value } from '../../base/Value'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'builderUtils'); + +export function handleQualifiedName(node: ts.QualifiedName): string { + let right = (node.right as ts.Identifier).text; + let left: string = ''; + if (node.left.kind === ts.SyntaxKind.Identifier) { + left = (node.left as ts.Identifier).text; + } else if (node.left.kind === ts.SyntaxKind.QualifiedName) { + left = handleQualifiedName(node.left as ts.QualifiedName); + } + let qualifiedName = left + '.' + right; + return qualifiedName; +} + +export function handlePropertyAccessExpression(node: ts.PropertyAccessExpression): string { + let right = (node.name as ts.Identifier).text; + let left: string = ''; + if (ts.SyntaxKind[node.expression.kind] === 'Identifier') { + left = (node.expression as ts.Identifier).text; + } else if (ts.isStringLiteral(node.expression)) { + left = node.expression.text; + } else if (ts.isPropertyAccessExpression(node.expression)) { + left = handlePropertyAccessExpression(node.expression as ts.PropertyAccessExpression); + } + let propertyAccessExpressionName = left + '.' + right; + return propertyAccessExpressionName; +} + +export function buildDecorators(node: ts.Node, sourceFile: ts.SourceFile): Set { + let decorators: Set = new Set(); + ts.getAllDecorators(node).forEach((decoratorNode) => { + let decorator = parseDecorator(decoratorNode); + if (decorator) { + decorator.setContent(decoratorNode.expression.getText(sourceFile)); + decorators.add(decorator); + } + }); + return decorators; +} + +function parseDecorator(node: ts.Decorator): Decorator | undefined { + if (!node.expression) { + return undefined; + } + + let expression = node.expression; + if (ts.isIdentifier(expression)) { + return new Decorator(expression.text); + } + if (!ts.isCallExpression(expression) || !ts.isIdentifier(expression.expression)) { + return undefined; + } + + let decorator = new Decorator(expression.expression.text); + + if (expression.arguments.length > 0) { + const arg = expression.arguments[0]; + if (ts.isArrowFunction(arg) && ts.isIdentifier(arg.body)) { + decorator.setParam(arg.body.text); + } + } + + return decorator; +} + +export function buildModifiers(node: ts.Node): number { + let modifiers: number = 0; + + if (ts.canHaveModifiers(node)) { + ts.getModifiers(node)?.forEach((modifier) => { + modifiers |= modifierKind2Enum(modifier.kind); + }); + } + + return modifiers; +} + +export function buildHeritageClauses(heritageClauses?: ts.NodeArray): Map { + let heritageClausesMap: Map = new Map(); + heritageClauses?.forEach((heritageClause) => { + heritageClause.types.forEach((type) => { + let heritageClauseName: string = ''; + if (type.typeArguments) { + heritageClauseName = type.getText(); + } else if (ts.isIdentifier(type.expression)) { + heritageClauseName = (type.expression as ts.Identifier).text; + } else if (ts.isPropertyAccessExpression(type.expression)) { + heritageClauseName = handlePropertyAccessExpression(type.expression); + } else { + heritageClauseName = type.getText(); + } + heritageClausesMap.set(heritageClauseName, ts.SyntaxKind[heritageClause.token]); + }); + }); + return heritageClausesMap; +} + +export function buildTypeParameters(typeParameters: ts.NodeArray, + sourceFile: ts.SourceFile, arkInstance: ArkMethod | ArkClass): GenericType[] { + const genericTypes: GenericType[] = []; + let index = 0; + if (arkInstance instanceof ArkMethod) { + const len = arkInstance.getDeclaringArkClass().getGenericsTypes()?.length; + if (len) { + index = len; + } + } + typeParameters.forEach((typeParameter) => { + const genericType = tsNode2Type(typeParameter, sourceFile, arkInstance); + if (genericType instanceof GenericType) { + genericType.setIndex(index++); + genericTypes.push(genericType); + } + + if (typeParameter.modifiers) { + logger.warn('This typeparameter has modifiers.'); + } + + if (typeParameter.expression) { + logger.warn('This typeparameter has expression.'); + } + }); + return genericTypes; +} + +function buildObjectBindingPatternParam(methodParameter: MethodParameter, paramNameNode: ts.ObjectBindingPattern): void { + methodParameter.setName('ObjectBindingPattern'); + let elements: ObjectBindingPatternParameter[] = []; + paramNameNode.elements.forEach((element) => { + let paraElement = new ObjectBindingPatternParameter(); + if (element.propertyName) { + if (ts.isIdentifier(element.propertyName)) { + paraElement.setPropertyName(element.propertyName.text); + } else { + logger.warn('New propertyName of ObjectBindingPattern found, please contact developers to support this!'); + } + } + + if (element.name) { + if (ts.isIdentifier(element.name)) { + paraElement.setName(element.name.text); + } else { + logger.warn('New name of ObjectBindingPattern found, please contact developers to support this!'); + } + } + + if (element.initializer) { + logger.warn('TODO: support ObjectBindingPattern initializer.'); + } + + if (element.dotDotDotToken) { + paraElement.setOptional(true); + } + elements.push(paraElement); + }); + methodParameter.setObjElements(elements); +} + +function buildBindingElementOfBindingPatternParam(element: ts.BindingElement, paraElement: ArrayBindingPatternParameter): void { + if (element.propertyName) { + if (ts.isIdentifier(element.propertyName)) { + paraElement.setPropertyName(element.propertyName.text); + } else { + logger.warn('New propertyName of ArrayBindingPattern found, please contact developers to support this!'); + } + } + + if (element.name) { + if (ts.isIdentifier(element.name)) { + paraElement.setName(element.name.text); + } else { + logger.warn('New name of ArrayBindingPattern found, please contact developers to support this!'); + } + } + + if (element.initializer) { + logger.warn('TODO: support ArrayBindingPattern initializer.'); + } + + if (element.dotDotDotToken) { + paraElement.setOptional(true); + } +} + +function buildArrayBindingPatternParam(methodParameter: MethodParameter, paramNameNode: ts.ArrayBindingPattern): void { + methodParameter.setName('ArrayBindingPattern'); + let elements: ArrayBindingPatternParameter[] = []; + paramNameNode.elements.forEach((element) => { + let paraElement = new ArrayBindingPatternParameter(); + if (ts.isBindingElement(element)) { + buildBindingElementOfBindingPatternParam(element, paraElement); + } else if (ts.isOmittedExpression(element)) { + logger.warn('TODO: support OmittedExpression for ArrayBindingPattern parameter name.'); + } + elements.push(paraElement); + }); + methodParameter.setArrayElements(elements); +} + +export function buildParameters(params: ts.NodeArray, arkInstance: ArkMethod | ArkField, sourceFile: ts.SourceFile): MethodParameter[] { + let parameters: MethodParameter[] = []; + params.forEach((parameter) => { + let methodParameter = new MethodParameter(); + + // name + if (ts.isIdentifier(parameter.name)) { + methodParameter.setName(parameter.name.text); + } else if (ts.isObjectBindingPattern(parameter.name)) { + buildObjectBindingPatternParam(methodParameter, parameter.name); + } else if (ts.isArrayBindingPattern(parameter.name)) { + buildArrayBindingPatternParam(methodParameter, parameter.name); + } else { + logger.warn('Parameter name is not identifier, ObjectBindingPattern nor ArrayBindingPattern, please contact developers to support this!'); + } + + // questionToken + if (parameter.questionToken) { + methodParameter.setOptional(true); + } + + // type + if (parameter.type) { + methodParameter.setType(buildGenericType(tsNode2Type(parameter.type, sourceFile, arkInstance), arkInstance)); + } else { + methodParameter.setType(UnknownType.getInstance()); + } + + // initializer + if (parameter.initializer) { + //TODO? + } + + // dotDotDotToken + if (parameter.dotDotDotToken) { + methodParameter.setDotDotDotToken(true); + } + + // modifiers + if (parameter.modifiers) { + // + } + + parameters.push(methodParameter); + }); + return parameters; +} + +export function buildGenericType(type: Type, arkInstance: ArkMethod | ArkField | AliasType): Type { + function replace(urType: UnclearReferenceType): Type { + const typeName = urType.getName(); + let gType; + if (arkInstance instanceof AliasType) { + gType = arkInstance.getGenericTypes()?.find(f => f.getName() === typeName); + } else { + if (arkInstance instanceof ArkMethod) { + gType = arkInstance.getGenericTypes()?.find(f => f.getName() === typeName); + } + if (!gType) { + gType = arkInstance.getDeclaringArkClass().getGenericsTypes()?.find(f => f.getName() === typeName); + } + } + if (gType) { + return gType; + } + const types = urType.getGenericTypes(); + for (let i = 0; i < types.length; i++) { + const mayType = types[i]; + if (mayType instanceof UnclearReferenceType) { + types[i] = replace(mayType); + } + } + return urType; + } + + if (type instanceof UnclearReferenceType) { + return replace(type); + } else if (type instanceof ClassType && arkInstance instanceof AliasType) { + type.setRealGenericTypes(arkInstance.getGenericTypes()); + } else if (type instanceof UnionType || type instanceof TupleType) { + const types = type.getTypes(); + for (let i = 0; i < types.length; i++) { + const mayType = types[i]; + if (mayType instanceof UnclearReferenceType) { + types[i] = replace(mayType); + } + } + } else if (type instanceof ArrayType) { + const baseType = type.getBaseType(); + if (baseType instanceof UnclearReferenceType) { + type.setBaseType(replace(baseType)); + } + } else if (type instanceof FunctionType) { + const returnType = type.getMethodSignature().getType(); + if (returnType instanceof UnclearReferenceType) { + type.getMethodSignature().getMethodSubSignature().setReturnType(replace(returnType)); + } + } + return type; +} + +export function buildReturnType(node: TypeNode, sourceFile: ts.SourceFile, method: ArkMethod) { + if (node) { + return tsNode2Type(node, sourceFile, method); + } else { + return UnknownType.getInstance(); + } +} + +export function tsNode2Type(typeNode: ts.TypeNode | ts.TypeParameterDeclaration, sourceFile: ts.SourceFile, + arkInstance: ArkMethod | ArkClass | ArkField): Type { + if (ts.isTypeReferenceNode(typeNode)) { + const genericTypes: Type[] = []; + if (typeNode.typeArguments) { + for (const typeArgument of typeNode.typeArguments) { + genericTypes.push(tsNode2Type(typeArgument, sourceFile, arkInstance)); + } + } + let referenceNodeName = typeNode.typeName; + if (ts.isQualifiedName(referenceNodeName)) { + let parameterTypeStr = handleQualifiedName(referenceNodeName as ts.QualifiedName); + return new UnclearReferenceType(parameterTypeStr, genericTypes); + } else { + let parameterTypeStr = referenceNodeName.text; + if (parameterTypeStr === Builtin.OBJECT) { + return Builtin.OBJECT_CLASS_TYPE; + } + return new UnclearReferenceType(parameterTypeStr, genericTypes); + } + } else if (ts.isUnionTypeNode(typeNode) || ts.isIntersectionTypeNode(typeNode)) { + let multipleTypePara: Type[] = []; + typeNode.types.forEach((tmpType) => { + multipleTypePara.push(tsNode2Type(tmpType, sourceFile, arkInstance)); + }); + if (ts.isUnionTypeNode(typeNode)) { + return new UnionType(multipleTypePara); + } else { + return new IntersectionType(multipleTypePara); + } + } else if (ts.isLiteralTypeNode(typeNode)) { + return ArkValueTransformer.resolveLiteralTypeNode(typeNode, sourceFile); + } else if (ts.isTypeLiteralNode(typeNode)) { + let cls: ArkClass = new ArkClass(); + let declaringClass: ArkClass; + + if (arkInstance instanceof ArkMethod) { + declaringClass = arkInstance.getDeclaringArkClass(); + } else if (arkInstance instanceof ArkField) { + declaringClass = arkInstance.getDeclaringArkClass(); + } else { + declaringClass = arkInstance; + } + if (declaringClass.getDeclaringArkNamespace()) { + cls.setDeclaringArkNamespace(declaringClass.getDeclaringArkNamespace()); + cls.setDeclaringArkFile(declaringClass.getDeclaringArkFile()); + } else { + cls.setDeclaringArkFile(declaringClass.getDeclaringArkFile()); + } + buildNormalArkClassFromArkMethod(typeNode, cls, sourceFile); + + return new ClassType(cls.getSignature()); + } else if (ts.isFunctionTypeNode(typeNode)) { + let mtd: ArkMethod = new ArkMethod(); + let cls: ArkClass; + if (arkInstance instanceof ArkMethod) { + cls = arkInstance.getDeclaringArkClass(); + } else if (arkInstance instanceof ArkClass) { + cls = arkInstance; + } else { + cls = arkInstance.getDeclaringArkClass(); + } + buildArkMethodFromArkClass(typeNode, cls, mtd, sourceFile); + return new FunctionType(mtd.getSignature()); + } else if (ts.isTypeParameterDeclaration(typeNode)) { + const name = typeNode.name.text; + let defaultType; + if (typeNode.default) { + defaultType = tsNode2Type(typeNode.default, sourceFile, arkInstance); + } + let constraint; + if (typeNode.constraint) { + constraint = tsNode2Type(typeNode.constraint, sourceFile, arkInstance); + } + return new GenericType(name, defaultType, constraint); + } else if (ts.isTupleTypeNode(typeNode)) { + const types: Type[] = []; + typeNode.elements.forEach(element => { + types.push(tsNode2Type(element, sourceFile, arkInstance)); + }); + return new TupleType(types); + } else if (ts.isArrayTypeNode(typeNode)) { + return new ArrayType(tsNode2Type((typeNode as ts.ArrayTypeNode).elementType, sourceFile, arkInstance), 1); + } else if (ts.isParenthesizedTypeNode(typeNode)) { + return tsNode2Type(typeNode.type, sourceFile, arkInstance); + } else if (ts.isTypeOperatorNode(typeNode)) { + return buildTypeFromTypeOperator(typeNode as ts.TypeOperatorNode, sourceFile, arkInstance); + } else if (ts.isTypeQueryNode(typeNode)) { + return buildTypeFromTypeQuery(typeNode as ts.TypeQueryNode, sourceFile, arkInstance); + } else if (typeNode.kind === ts.SyntaxKind.ObjectKeyword) { + // TODO: type object which is different from Object is needed to support, such as let a: object = {} + return new UnclearReferenceType('object'); + } else { + return buildTypeFromPreStr(ts.SyntaxKind[typeNode.kind]); + } +} + +export function buildTypeFromPreStr(preStr: string) { + let postStr = ''; + switch (preStr) { + case 'BooleanKeyword': + postStr = BOOLEAN_KEYWORD; + break; + case 'FalseKeyword': + postStr = BOOLEAN_KEYWORD; + break; + case 'TrueKeyword': + postStr = BOOLEAN_KEYWORD; + break; + case 'NumberKeyword': + postStr = NUMBER_KEYWORD; + break; + case 'NumericLiteral': + postStr = NUMBER_KEYWORD; + break; + case 'FirstLiteralToken': + postStr = NUMBER_KEYWORD; + break; + case 'StringKeyword': + postStr = STRING_KEYWORD; + break; + case 'StringLiteral': + postStr = STRING_KEYWORD; + break; + case 'UndefinedKeyword': + postStr = UNDEFINED_KEYWORD; + break; + case 'NullKeyword': + postStr = NULL_KEYWORD; + break; + case 'AnyKeyword': + postStr = ANY_KEYWORD; + break; + case 'VoidKeyword': + postStr = VOID_KEYWORD; + break; + case 'NeverKeyword': + postStr = NEVER_KEYWORD; + break; + case 'BigIntKeyword': + postStr = BIGINT_KEYWORD; + break; + default: + postStr = preStr; + } + return TypeInference.buildTypeFromStr(postStr); +} + +function buildTypeFromTypeOperator(typeOperatorNode: ts.TypeOperatorNode, sourceFile: ts.SourceFile, + arkInstance: ArkMethod | ArkClass | ArkField): Type { + const typeNode = typeOperatorNode.type; + let type = tsNode2Type(typeNode, sourceFile, arkInstance); + + switch (typeOperatorNode.operator) { + case (ts.SyntaxKind.ReadonlyKeyword): { + if (type instanceof ArrayType || type instanceof TupleType) { + type.setReadonlyFlag(true); + } + return type; + } + case (ts.SyntaxKind.KeyOfKeyword): + return new KeyofTypeExpr(type); + case (ts.SyntaxKind.UniqueKeyword): + return UnknownType.getInstance(); + default: + return UnknownType.getInstance(); + } +} + +function buildTypeFromTypeQuery(typeQueryNode: ts.TypeQueryNode, sourceFile: ts.SourceFile, arkInstance: ArkMethod | ArkClass | ArkField): Type { + const exprNameNode = typeQueryNode.exprName; + let opValue: Value; + if (ts.isQualifiedName(exprNameNode)) { + if (exprNameNode.left.getText(sourceFile) === THIS_NAME) { + const fieldName = exprNameNode.right.getText(sourceFile); + if (arkInstance instanceof ArkMethod) { + const fieldSignature = arkInstance.getDeclaringArkClass().getFieldWithName(fieldName)?.getSignature() ?? + ArkSignatureBuilder.buildFieldSignatureFromFieldName(fieldName); + const baseLocal = arkInstance.getBody()?.getLocals().get(THIS_NAME) ?? + new Local(THIS_NAME, new ClassType(arkInstance.getDeclaringArkClass().getSignature(), + arkInstance.getDeclaringArkClass().getGenericsTypes())); + opValue = new ArkInstanceFieldRef(baseLocal, fieldSignature); + } else if (arkInstance instanceof ArkClass) { + const fieldSignature = arkInstance.getFieldWithName(fieldName)?.getSignature() ?? + ArkSignatureBuilder.buildFieldSignatureFromFieldName(fieldName); + const baseLocal = new Local(THIS_NAME, new ClassType(arkInstance.getSignature(), arkInstance.getGenericsTypes())); + opValue = new ArkInstanceFieldRef(baseLocal, fieldSignature); + } else { + const fieldSignature = arkInstance.getSignature(); + const baseLocal = new Local(THIS_NAME, new ClassType(arkInstance.getDeclaringArkClass().getSignature(), + arkInstance.getDeclaringArkClass().getGenericsTypes())); + opValue = new ArkInstanceFieldRef(baseLocal, fieldSignature); + } + } else { + const exprName = exprNameNode.getText(sourceFile); + opValue = new Local(exprName, UnknownType.getInstance()); + } + } else { + const exprName = exprNameNode.escapedText.toString(); + opValue = new Local(exprName, UnknownType.getInstance()); + } + + let expr = new TypeQueryExpr(opValue); + if (typeQueryNode.typeArguments) { + for (const typeArgument of typeQueryNode.typeArguments) { + expr.addGenericType(tsNode2Type(typeArgument, sourceFile, arkInstance)); + } + } + return expr; +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/index.ts b/ets2panda/linter/arkanalyzer/src/index.ts new file mode 100644 index 0000000000..174ea7c493 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/index.ts @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// callgraph/algorithm +export { AbstractAnalysis } from './callgraph/algorithm/AbstractAnalysis'; +export { ClassHierarchyAnalysis } from './callgraph/algorithm/ClassHierarchyAnalysis'; +export { RapidTypeAnalysis } from './callgraph/algorithm/RapidTypeAnalysis'; + +// callgraph/common +export { PTAStat, PAGStat, CGStat } from './callgraph/common/Statistics'; + +// callgraph/model +export * from './callgraph/model/CallGraph'; +export { CallGraphBuilder } from './callgraph/model/builder/CallGraphBuilder'; + +// callgraph/pointerAnalysis +export { KLimitedContextSensitive } from './callgraph/pointerAnalysis/Context'; +export { DummyCallCreator } from './callgraph/pointerAnalysis/DummyCallCreator'; +export * from './callgraph/pointerAnalysis/Pag'; +export { CSFuncID, PagBuilder } from './callgraph/pointerAnalysis/PagBuilder'; +export { PointerAnalysis } from './callgraph/pointerAnalysis/PointerAnalysis'; +export { PointerAnalysisConfig } from './callgraph/pointerAnalysis/PointerAnalysisConfig'; +export { PtsSet, DiffPTData } from './callgraph/pointerAnalysis/PtsDS'; + +export { DVFG } from './VFG/DVFG'; +export { DVFGBuilder } from './VFG/builder/DVFGBuilder'; + +// core/base +export { Constant } from './core/base/Constant'; +export { Decorator } from './core/base/Decorator'; +export { DefUseChain } from './core/base/DefUseChain'; +export * from './core/base/Expr'; +export { Local } from './core/base/Local'; +export { LineColPosition, FullPosition } from './core/base/Position'; +export * from './core/base/Ref'; +export * from './core/base/Stmt'; +export * from './core/base/Type'; +export { Value } from './core/base/Value'; + +// core/common +export { ModelUtils } from './core/common/ModelUtils'; +export * from './core/common/Const'; +export { DummyMainCreater } from './core/common/DummyMainCreater'; +export * from './core/common/EtsConst'; +export { ExprUseReplacer } from './core/common/ExprUseReplacer'; +export { IRUtils } from './core/common/IRUtils'; +export { RefUseReplacer } from './core/common/RefUseReplacer'; +export { StmtUseReplacer } from './core/common/StmtUseReplacer'; +export * from './core/common/TSConst'; +export { TypeInference } from './core/common/TypeInference'; +export { ValueUtil } from './core/common/ValueUtil'; +export { VisibleValue, Scope } from './core/common/VisibleValue'; + +// core/dataflow +export { DataflowProblem, FlowFunction } from './core/dataflow/DataflowProblem'; +export { DataflowResult } from './core/dataflow/DataflowResult'; +export { DataflowSolver } from './core/dataflow/DataflowSolver'; +export { PathEdgePoint, PathEdge } from './core/dataflow/Edge'; +export { Fact } from './core/dataflow/Fact'; +export { UndefinedVariableChecker, UndefinedVariableSolver } from './core/dataflow/UndefinedVariable'; + +// core/graph +export { BasicBlock } from './core/graph/BasicBlock'; +export { Cfg } from './core/graph/Cfg'; +export { ViewTree, ViewTreeNode } from './core/graph/ViewTree'; +export { DominanceFinder } from './core/graph/DominanceFinder'; +export { DominanceTree } from './core/graph/DominanceTree'; +export { NodeID, Kind, BaseEdge, BaseNode, BaseExplicitGraph } from './core/graph/BaseExplicitGraph'; +export { SCCDetection } from './core/graph/Scc'; + +// core/model +export { ArkFile } from './core/model/ArkFile'; +export { ArkNamespace } from './core/model/ArkNamespace'; +export { ArkClass } from './core/model/ArkClass'; +export { ArkMethod } from './core/model/ArkMethod'; +export { ArkField } from './core/model/ArkField'; +export { ExportInfo } from './core/model/ArkExport'; +export { ImportInfo } from './core/model/ArkImport'; +export { ArkBody } from './core/model/ArkBody'; +export * from './core/model/ArkSignature'; +export * from './core/model/builder/ArkSignatureBuilder'; + +export { SceneConfig } from './Config'; +export { Scene } from './Scene'; + +// save +export { Printer } from './save/Printer'; +export { PrinterBuilder } from './save/PrinterBuilder'; +export { DotMethodPrinter, DotClassPrinter, DotNamespacePrinter, DotFilePrinter } from './save/DotPrinter'; +export { SourceMethod as SourceMethodPrinter } from './save/source/SourceMethod'; +export { SourceClass as SourceClassPrinter } from './save/source/SourceClass'; +export { SourceNamespace as SourceNamespacePrinter } from './save/source/SourceNamespace'; +export { SourceFilePrinter } from './save/source/SourceFilePrinter'; +export { JsonPrinter } from './save/JsonPrinter'; +export { GraphPrinter } from './save/GraphPrinter'; +export { ViewTreePrinter } from './save/ViewTreePrinter'; + +// transformer +export * from './transformer/StaticSingleAssignmentFormer'; + +// utils +export * from './utils/callGraphUtils'; +export * from './utils/entryMethodUtils'; +export * from './utils/FileUtils'; +export * from './utils/getAllFiles'; +export * from './utils/json5parser'; +export * from './utils/pathTransfer'; +export * from './utils/AstTreeUtils'; +export { LOG_LEVEL, LOG_MODULE_TYPE } from './utils/logger'; +export { default as Logger } from './utils/logger'; + + +//ohos-typescript +import ts from 'ohos-typescript'; +export { ts }; \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/save/ArkStream.ts b/ets2panda/linter/arkanalyzer/src/save/ArkStream.ts new file mode 100644 index 0000000000..51929115b4 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/save/ArkStream.ts @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import fs from 'fs'; + +export class ArkCodeBuffer { + output: string[] = []; + indent: string = ''; + + constructor(indent: string = '') { + this.indent = indent; + } + + public write(s: string): this { + this.output.push(s); + return this; + } + + public writeLine(s: string): this { + this.write(s); + this.write('\n'); + return this; + } + + public writeSpace(s: string): this { + if (s.length === 0) { + return this; + } + this.write(s); + this.write(' '); + return this; + } + + public writeStringLiteral(s: string): this { + this.write(`'${s}'`); + return this; + } + + public writeIndent(): this { + this.write(this.indent); + return this; + } + + public incIndent(): this { + this.indent += ' '; + return this; + } + + public decIndent(): this { + if (this.indent.length >= 2) { + this.indent = this.indent.substring(0, this.indent.length - 2); + } + return this; + } + + public getIndent(): string { + return this.indent; + } + + public toString(): string { + return this.output.join(''); + } + + public clear() { + this.output = []; + } +} + +export class ArkStream extends ArkCodeBuffer { + streamOut: fs.WriteStream; + + constructor(streamOut: fs.WriteStream) { + super(''); + this.streamOut = streamOut; + } + + public write(s: string): this { + this.streamOut.write(s); + return this; + } + + public close(): void { + this.streamOut.close(); + } +} diff --git a/ets2panda/linter/arkanalyzer/src/save/DotPrinter.ts b/ets2panda/linter/arkanalyzer/src/save/DotPrinter.ts new file mode 100644 index 0000000000..2992ff6653 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/save/DotPrinter.ts @@ -0,0 +1,205 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { BasicBlock } from '../core/graph/BasicBlock'; +import { ArkClass } from '../core/model/ArkClass'; +import { ArkFile } from '../core/model/ArkFile'; +import { ArkMethod } from '../core/model/ArkMethod'; +import { ArkNamespace } from '../core/model/ArkNamespace'; +import { Printer } from './Printer'; +import { Cfg } from '../core/graph/Cfg'; + +/** + * @category save + */ +export class DotMethodPrinter extends Printer { + method: ArkMethod; + nesting: boolean; + + constructor(method: ArkMethod, nesting: boolean = false) { + super(); + this.method = method; + this.nesting = nesting; + } + + public dump(): string { + this.printer.clear(); + if (this.nesting) { + this.printer.writeIndent().writeLine(`subgraph "cluster_${this.method.getSignature()}" {`); + } else { + this.printer.writeIndent().writeLine(`digraph "${this.method.getSignature()}" {`); + } + this.printer.incIndent(); + this.printer.writeIndent().writeLine(`label="${this.method.getSignature()}";`); + + let blocks = (this.method.getCfg() as Cfg)?.getBlocks(); + let prefix = `Node${this.stringHashCode(this.method.getSignature().toString())}`; + this.printBlocks(blocks, prefix); + + this.printer.decIndent(); + this.printer.writeIndent().writeLine('}'); + + return this.printer.toString(); + } + + protected stringHashCode(name: string): number { + let hashCode = 0; + for (let i = 0; i < name.length; i++) { + hashCode += name.charCodeAt(i); + } + return Math.abs(hashCode); + } + + private printBlocks(blocks: Set, prefix: string): void { + if (!blocks) { + return; + } + let blockToNode: Map = new Map(); + let index = 0; + for (let block of blocks) { + let name = prefix + index++; + blockToNode.set(block, name); + /** Node0 [label="entry"]; */ + this.printer + .writeIndent() + .writeLine(`${name} [label="${this.getBlockContent(block, this.printer.getIndent())}"];`); + } + + for (let block of blocks) { + for (let nextBlock of block.getSuccessors()) { + // Node0 -> Node1; + this.printer.writeIndent().writeLine(`${blockToNode.get(block)} -> ${blockToNode.get(nextBlock)};`); + } + + let exceptionalNextBlock = block.getExceptionalSuccessorBlocks(); + if (!exceptionalNextBlock) { + continue; + } + for (const nextBlock of exceptionalNextBlock) { + this.printer.writeIndent().writeLine(`${blockToNode.get(block)} -> ${blockToNode.get(nextBlock)}[style="dotted"];`); + } + } + } + + private getBlockContent(block: BasicBlock, indent: string): string { + let content: string[] = [`id:${block.getId()}`]; + for (let stmt of block.getStmts()) { + content.push(stmt.toString().replace(/"/g, '\\"')); + } + return content.join('\n ' + indent); + } +} + +/** + * @category save + */ +export class DotClassPrinter extends Printer { + cls: ArkClass; + nesting: boolean; + + constructor(cls: ArkClass, nesting: boolean = false) { + super(); + this.cls = cls; + this.nesting = nesting; + } + + public dump(): string { + this.printer.clear(); + if (!this.nesting) { + this.printer.writeLine(`digraph "${this.cls.getName()}" {`); + this.printer.incIndent(); + } + + for (let method of this.cls.getMethods()) { + let mtd = new DotMethodPrinter(method, true); + this.printer.write(mtd.dump()); + } + + if (!this.nesting) { + this.printer.decIndent(); + this.printer.writeLine(`}`); + } + + return this.printer.toString(); + } +} + +/** + * @category save + */ +export class DotNamespacePrinter extends Printer { + ns: ArkNamespace; + nesting: boolean; + + constructor(ns: ArkNamespace, nesting: boolean = false) { + super(); + this.ns = ns; + this.nesting = nesting; + } + + public dump(): string { + this.printer.clear(); + if (!this.nesting) { + this.printer.writeLine(`digraph "${this.ns.getName()}" {`); + this.printer.incIndent(); + } + + for (let method of this.ns.getAllMethodsUnderThisNamespace()) { + let mtd = new DotMethodPrinter(method, true); + this.printer.write(mtd.dump()); + } + + if (!this.nesting) { + this.printer.decIndent(); + this.printer.writeLine(`}`); + } + + return this.printer.toString(); + } +} + +/** + * @category save + */ +export class DotFilePrinter extends Printer { + arkFile: ArkFile; + + constructor(arkFile: ArkFile) { + super(); + this.arkFile = arkFile; + } + + public dump(): string { + this.printer.clear(); + this.printer.writeLine(`digraph "${this.arkFile.getName()}" {`); + this.printer.incIndent(); + + for (let ns of this.arkFile.getNamespaces()) { + let nsPrinter = new DotNamespacePrinter(ns, true); + this.printer.write(nsPrinter.dump()); + } + + // print class + for (let cls of this.arkFile.getClasses()) { + let clsPrinter = new DotClassPrinter(cls, true); + this.printer.write(clsPrinter.dump()); + } + + this.printer.decIndent(); + this.printer.writeLine('}'); + + return this.printer.toString(); + } +} diff --git a/ets2panda/linter/arkanalyzer/src/save/GraphPrinter.ts b/ets2panda/linter/arkanalyzer/src/save/GraphPrinter.ts new file mode 100644 index 0000000000..20f5938165 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/save/GraphPrinter.ts @@ -0,0 +1,153 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { BaseEdge, BaseNode, NodeID } from '../core/graph/BaseExplicitGraph'; +import { GraphTraits } from '../core/graph/GraphTraits'; +import { Printer } from './Printer'; + +function escapeStr(input: string): string { + let str = input; + for (let i = 0; i < str.length; ++i) { + switch (str[i]) { + case '\n': + str = str.substring(0, i) + '\\n' + str.substring(i + 1); + ++i; + break; + case '\t': + str = str.substring(0, i) + ' ' + str.substring(i + 1); + ++i; + break; + case '\\': + if (i + 1 < str.length) { + switch (str[i + 1]) { + case 'l': + continue; // don't disturb \l + case '|': + case '{': + case '}': + str = str.substring(0, i) + str.substring(i + 1); + continue; + default: + break; + } + } + str = str.substring(0, i) + '\\\\' + str.substring(i + 1); + ++i; + break; + case '{': + case '}': + case '<': + case '>': + case '|': + case '"': + str = str.substring(0, i) + '\\' + str[i] + str.substring(i + 1); + ++i; + break; + default: + ; + } + } + return str; +} + +export class GraphPrinter> extends Printer { + graph: GraphType; + title!: string; + startID: NodeID | undefined = undefined; + + constructor(g: GraphType, t?: string) { + super(); + this.graph = g; + if (t) { + this.title = t; + } + } + + public setStartID(n: NodeID) { + this.startID = n; + } + + public dump(): string { + this.printer.clear(); + this.writeGraph(); + return this.printer.toString(); + } + + public writeGraph(): void { + this.writeHeader(); + this.writeNodes(); + this.writeFooter(); + } + + public writeNodes(): void { + let itor: IterableIterator = this.graph.nodesItor(); + if (this.startID) { + // from start id + let nodes = new Set(); + let startNode = this.graph.getNode(this.startID)!; + let worklist = [startNode]; + while (worklist.length > 0) { + let n = worklist.shift()!; + if (nodes.has(n)) { + continue; + } + nodes.add(n); + n.getOutgoingEdges()?.forEach(e => worklist.push(e.getDstNode())); + } + itor = nodes.values(); + } + + for(let node of itor) { + let nodeAttr = node.getDotAttr(); + if (nodeAttr === '') { + continue; + } + let nodeLabel = escapeStr(node.getDotLabel()); + + this.printer.writeLine(`\tNode${node.getID()} [shape=recode,${nodeAttr},label="${nodeLabel}"];`) + + for (let edge of node.getOutgoingEdges()) { + this.writeEdge(edge); + } + } + + + } + + public writeEdge(edge: BaseEdge): void { + let edgeAttr = edge.getDotAttr(); + if (edgeAttr === '') { + return + } + this.printer.writeLine(`\tNode${edge.getSrcID()} -> Node${edge.getDstID()}[${edgeAttr}]`); + } + + public writeHeader(): void { + const GraphName = this.graph.getGraphName(); + + let graphNameStr = `digraph "${escapeStr(this.title || GraphName || 'unnamed')}" {\n`; + this.printer.writeLine(graphNameStr); + + + let labelStr = `\tlabel="${escapeStr(this.title || GraphName)}";\n`; + this.printer.writeLine(labelStr); + + // TODO: need graph attr? + } + + public writeFooter(): void { + this.printer.writeLine("}\n"); + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/save/JsonPrinter.ts b/ets2panda/linter/arkanalyzer/src/save/JsonPrinter.ts new file mode 100644 index 0000000000..3f533f2244 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/save/JsonPrinter.ts @@ -0,0 +1,620 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Printer } from './Printer'; +import { ArkFile } from '../core/model/ArkFile'; +import { ArkMethod } from '../core/model/ArkMethod'; +import { ArkNamespace } from '../core/model/ArkNamespace'; +import { ArkClass } from '../core/model/ArkClass'; +import { ArkField } from '../core/model/ArkField'; +import { + AliasType, + AnnotationNamespaceType, + AnnotationType, + AnnotationTypeQueryType, + AnyType, + ArrayType, BigIntType, + BooleanType, + ClassType, + FunctionType, + GenericType, + LiteralType, + NeverType, + NullType, + NumberType, + PrimitiveType, + StringType, + TupleType, + Type, + UnclearReferenceType, + UndefinedType, + UnionType, + UnknownType, + VoidType, +} from '../core/base/Type'; +import { Value } from '../core/base/Value'; +import { + ArkAssignStmt, + ArkIfStmt, + ArkInvokeStmt, + ArkReturnStmt, + ArkReturnVoidStmt, + ArkThrowStmt, + Stmt, +} from '../core/base/Stmt'; +import { + AbstractBinopExpr, + AbstractExpr, + AbstractInvokeExpr, + ArkAwaitExpr, + ArkCastExpr, + ArkConditionExpr, + ArkDeleteExpr, + ArkInstanceInvokeExpr, + ArkInstanceOfExpr, + ArkNewArrayExpr, + ArkNewExpr, + ArkNormalBinopExpr, + ArkPhiExpr, + ArkPtrInvokeExpr, + ArkStaticInvokeExpr, + ArkTypeOfExpr, + ArkUnopExpr, + ArkYieldExpr, +} from '../core/base/Expr'; +import { Constant } from '../core/base/Constant'; +import { MethodParameter } from '../core/model/builder/ArkMethodBuilder'; +import { ImportInfo } from '../core/model/ArkImport'; +import { ExportInfo } from '../core/model/ArkExport'; +import { + AliasTypeSignature, + ClassSignature, + FieldSignature, + FileSignature, + MethodSignature, + NamespaceSignature, +} from '../core/model/ArkSignature'; +import { LineColPosition } from '../core/base/Position'; +import { AbstractFieldRef, AbstractRef, ArkArrayRef, ArkInstanceFieldRef, ArkParameterRef, ArkStaticFieldRef, ArkThisRef } from '../core/base/Ref'; +import { Local } from '../core/base/Local'; +import { Cfg } from '../core/graph/Cfg'; +import { BasicBlock } from '../core/graph/BasicBlock'; +import { ArkBody } from '../core/model/ArkBody'; +import { Decorator } from '../core/base/Decorator'; +import util from 'util'; + +export class JsonPrinter extends Printer { + constructor(private arkFile: ArkFile) { + super(); + } + + public dump(): string { + const jsonObject = this.serializeArkFile(this.arkFile); + return JSON.stringify(jsonObject, null, 2); + } + + private serializeArkFile(file: ArkFile): object { + return { + signature: this.serializeFileSignature(file.getFileSignature()), + namespaces: file.getNamespaces().map((ns) => this.serializeNamespace(ns)), + classes: file.getClasses().map((cls) => this.serializeClass(cls)), + importInfos: file.getImportInfos().map((info) => this.serializeImportInfo(info)), + exportInfos: file.getExportInfos().map((info) => this.serializeExportInfo(info)), + }; + } + + private serializeNamespace(namespace: ArkNamespace): object { + return { + signature: this.serializeNamespaceSignature(namespace.getSignature()), + classes: namespace.getClasses().map((cls) => this.serializeClass(cls)), + namespaces: namespace.getNamespaces().map((ns) => this.serializeNamespace(ns)), + }; + } + + private serializeClass(clazz: ArkClass): object { + return { + signature: this.serializeClassSignature(clazz.getSignature()), + modifiers: clazz.getModifiers(), + decorators: clazz.getDecorators().map((decorator) => this.serializeDecorator(decorator)), + typeParameters: clazz.getGenericsTypes()?.map((type) => this.serializeType(type)), + superClassName: clazz.getSuperClassName(), + implementedInterfaceNames: clazz.getImplementedInterfaceNames(), + fields: clazz.getFields().map((field) => this.serializeField(field)), + methods: clazz.getMethods(true).map((method) => this.serializeMethod(method)), + }; + } + + private serializeField(field: ArkField): object { + return { + signature: this.serializeFieldSignature(field.getSignature()), + modifiers: field.getModifiers(), + decorators: field.getDecorators().map((decorator) => this.serializeDecorator(decorator)), + questionToken: field.getQuestionToken(), + exclamationToken: field.getExclamationToken(), + }; + } + + private serializeMethod(method: ArkMethod): object { + let body = method.getBody(); + return { + signature: this.serializeMethodSignature(method.getSignature()), + modifiers: method.getModifiers(), + decorators: method.getDecorators().map((decorator) => this.serializeDecorator(decorator)), + typeParameters: method.getGenericTypes()?.map(type => this.serializeType(type)), + body: body && this.serializeMethodBody(body), + }; + } + + private serializeMethodBody(body: ArkBody): object { + return { + locals: Array.from(body.getLocals().values()).map((local) => this.serializeLocal(local)), + cfg: this.serializeCfg(body.getCfg()), + }; + } + + private serializeMethodParameter(parameter: MethodParameter): object { + return { + name: parameter.getName(), + type: this.serializeType(parameter.getType()), + isOptional: parameter.isOptional(), + }; + } + + private serializeImportInfo(importInfo: ImportInfo): object { + return { + importClauseName: importInfo.getImportClauseName(), + importType: importInfo.getImportType(), + importFrom: importInfo.getFrom(), + nameBeforeAs: importInfo.getNameBeforeAs(), + modifiers: importInfo.getModifiers(), + originTsPosition: this.serializeLineColPosition(importInfo.getOriginTsPosition()), + }; + } + + private serializeExportInfo(exportInfo: ExportInfo): object { + return { + exportClauseName: exportInfo.getExportClauseName(), + exportClauseType: exportInfo.getExportClauseType(), + exportFrom: exportInfo.getFrom(), + nameBeforeAs: exportInfo.getNameBeforeAs(), + isDefault: exportInfo.isDefault(), + modifiers: exportInfo.getModifiers(), + originTsPosition: this.serializeLineColPosition(exportInfo.getOriginTsPosition()), + }; + } + + private serializeDecorator(decorator: Decorator): object { + return { + kind: decorator.getKind(), + }; + } + + private serializeLineColPosition(position: LineColPosition): object { + return { + line: position.getLineNo(), + col: position.getColNo(), + }; + } + + private serializeType(type: Type): object { + if (type === undefined) { + throw new Error('Type is undefined'); + } + + if (type instanceof AnyType) { + return { + _: 'AnyType', + }; + } else if (type instanceof UnknownType) { + return { + _: 'UnknownType', + }; + } else if (type instanceof VoidType) { + return { + _: 'VoidType', + }; + } else if (type instanceof NeverType) { + return { + _: 'NeverType', + }; + } else if (type instanceof UnionType) { + return { + _: 'UnionType', + types: type.getTypes().map((type) => this.serializeType(type)), + }; + } else if (type instanceof TupleType) { + return { + _: 'TupleType', + types: type.getTypes().map((type) => this.serializeType(type)), + }; + } else if (type instanceof BooleanType) { + return { + _: 'BooleanType', + }; + } else if (type instanceof NumberType) { + return { + _: 'NumberType', + }; + } else if (type instanceof BigIntType) { + return { + _: 'BigIntType', + }; + } else if (type instanceof StringType) { + return { + _: 'StringType', + }; + } else if (type instanceof NullType) { + return { + _: 'NullType', + }; + } else if (type instanceof UndefinedType) { + return { + _: 'UndefinedType', + }; + } else if (type instanceof LiteralType) { + return { + _: 'LiteralType', + literal: type.getLiteralName(), + }; + } else if (type instanceof PrimitiveType) { + throw new Error('Unhandled PrimitiveType: ' + util.inspect(type, { showHidden: true, depth: null })); + } else if (type instanceof ClassType) { + return { + _: 'ClassType', + signature: this.serializeClassSignature(type.getClassSignature()), + typeParameters: type.getRealGenericTypes()?.map((type) => this.serializeType(type)), + }; + } else if (type instanceof FunctionType) { + return { + _: 'FunctionType', + signature: this.serializeMethodSignature(type.getMethodSignature()), + typeParameters: type.getRealGenericTypes()?.map((type) => this.serializeType(type)), + }; + } else if (type instanceof ArrayType) { + return { + _: 'ArrayType', + elementType: this.serializeType(type.getBaseType()), + dimensions: type.getDimension(), + }; + } else if (type instanceof UnclearReferenceType) { + return { + _: 'UnclearReferenceType', + name: type.getName(), + typeParameters: type.getGenericTypes().map((type) => this.serializeType(type)), + }; + } else if (type instanceof GenericType) { + let defaultType = type.getDefaultType(); + let constraint = type.getConstraint(); + return { + _: 'GenericType', + name: type.getName(), + defaultType: defaultType && this.serializeType(defaultType), + constraint: constraint && this.serializeType(constraint), + }; + } else if (type instanceof AliasType) { + return { + _: 'AliasType', + name: type.getName(), + originalType: this.serializeType(type.getOriginalType()), + signature: this.serializeAliasTypeSignature(type.getSignature()), + }; + } else if (type instanceof AnnotationNamespaceType) { + return { + _: 'AnnotationNamespaceType', + originType: type.getOriginType(), + namespaceSignature: this.serializeNamespaceSignature(type.getNamespaceSignature()), + }; + } else if (type instanceof AnnotationTypeQueryType) { + return { + _: 'AnnotationTypeQueryType', + originType: type.getOriginType(), + }; + } else if (type instanceof AnnotationType) { + throw new Error('Unhandled AnnotationType: ' + util.inspect(type, { showHidden: true, depth: null })); + } else { + throw new Error('Unhandled Type: ' + util.inspect(type, { showHidden: true, depth: null })); + } + } + + private serializeFileSignature(file: FileSignature): object { + return { + projectName: file.getProjectName(), + fileName: file.getFileName(), + }; + } + + private serializeNamespaceSignature(namespace: NamespaceSignature): object { + let dns = namespace.getDeclaringNamespaceSignature(); + return { + name: namespace.getNamespaceName(), + declaringFile: this.serializeFileSignature(namespace.getDeclaringFileSignature()), + declaringNamespace: dns && this.serializeNamespaceSignature(dns), + }; + } + + private serializeClassSignature(clazz: ClassSignature): object { + let dns = clazz.getDeclaringNamespaceSignature(); + return { + name: clazz.getClassName(), + declaringFile: this.serializeFileSignature(clazz.getDeclaringFileSignature()), + declaringNamespace: dns && this.serializeNamespaceSignature(dns), + }; + } + + private serializeFieldSignature(field: FieldSignature): object { + let declaringSignature: ClassSignature | NamespaceSignature = field.getDeclaringSignature(); + let declaringClass; + if (declaringSignature instanceof ClassSignature) { + declaringClass = this.serializeClassSignature(declaringSignature); + } else { + declaringClass = this.serializeNamespaceSignature(declaringSignature); + } + return { + declaringClass, + name: field.getFieldName(), + type: this.serializeType(field.getType()), + }; + } + + private serializeMethodSignature(method: MethodSignature): object { + return { + declaringClass: this.serializeClassSignature(method.getDeclaringClassSignature()), + name: method.getMethodSubSignature().getMethodName(), + parameters: method + .getMethodSubSignature() + .getParameters() + .map((param) => this.serializeMethodParameter(param)), + returnType: this.serializeType(method.getType()), + }; + } + + private serializeAliasTypeSignature(signature: AliasTypeSignature): object { + return { + name: signature.getName(), + method: this.serializeMethodSignature(signature.getDeclaringMethodSignature()), + }; + } + + private serializeCfg(cfg: Cfg): object { + const visited = new Set(); + const stack: BasicBlock[] = []; + const startingBlock = cfg.getStartingBlock(); + if (startingBlock) { + stack.push(startingBlock); + } + let id = 0; + while (stack.length > 0) { + const block = stack.pop()!; + if (visited.has(block)) { + continue; + } + visited.add(block); + block.setId(id++); + stack.push(...block.getSuccessors()); + } + return { + blocks: Array.from(visited).map((block) => this.serializeBasicBlock(block)), + }; + } + + private serializeBasicBlock(block: BasicBlock): object { + const successors = block.getSuccessors().map((succ) => succ.getId()); + successors.sort((a, b) => a - b); + const predecessors = block.getPredecessors().map((pred) => pred.getId()); + predecessors.sort((a, b) => a - b); + return { + id: block.getId(), + successors, + predecessors, + stmts: block.getStmts().map((stmt) => this.serializeStmt(stmt)), + }; + } + + private serializeLocal(local: Local): object { + return { + name: local.getName(), + type: this.serializeType(local.getType()), + }; + } + + private serializeValue(value: Value): object { + if (value === undefined) { + throw new Error('Value is undefined'); + } + + if (value instanceof Local) { + return { + _: 'Local', + ...this.serializeLocal(value), + }; + } else if (value instanceof Constant) { + return { + _: 'Constant', + value: value.getValue(), + type: this.serializeType(value.getType()), + }; + } else if (value instanceof ArkNewExpr) { + return { + _: 'NewExpr', + classType: this.serializeType(value.getClassType()), + }; + } else if (value instanceof ArkNewArrayExpr) { + return { + _: 'NewArrayExpr', + elementType: this.serializeType(value.getBaseType()), + size: this.serializeValue(value.getSize()), + }; + } else if (value instanceof ArkDeleteExpr) { + return { + _: 'DeleteExpr', + arg: this.serializeValue(value.getField()), + }; + } else if (value instanceof ArkAwaitExpr) { + return { + _: 'AwaitExpr', + arg: this.serializeValue(value.getPromise()), + }; + } else if (value instanceof ArkYieldExpr) { + return { + _: 'YieldExpr', + arg: this.serializeValue(value.getYieldValue()), + }; + } else if (value instanceof ArkTypeOfExpr) { + return { + _: 'TypeOfExpr', + arg: this.serializeValue(value.getOp()), + }; + } else if (value instanceof ArkInstanceOfExpr) { + return { + _: 'InstanceOfExpr', + arg: this.serializeValue(value.getOp()), + checkType: this.serializeType(value.getCheckType()), + }; + } else if (value instanceof ArkCastExpr) { + return { + _: 'CastExpr', + arg: this.serializeValue(value.getOp()), + type: this.serializeType(value.getType()), + }; + } else if (value instanceof ArkPhiExpr) { + const args = value.getArgs(); + const argToBlock = value.getArgToBlock(); + return { + _: 'PhiExpr', + args: args.map((arg) => this.serializeValue(arg)), + blocks: args.map((arg) => argToBlock.get(arg)!.getId()), + type: this.serializeType(value.getType()), + }; + } else if (value instanceof ArkConditionExpr) { + return { + _: 'ConditionExpr', + op: value.getOperator(), + left: this.serializeValue(value.getOp1()), + right: this.serializeValue(value.getOp2()), + type: this.serializeType(value.getType()), + }; + } else if (value instanceof ArkNormalBinopExpr) { + return { + _: 'BinopExpr', + op: value.getOperator(), + left: this.serializeValue(value.getOp1()), + right: this.serializeValue(value.getOp2()), + }; + } else if (value instanceof AbstractBinopExpr) { + return new Error('Unhandled BinopExpr: ' + util.inspect(value, { showHidden: true, depth: null })); + } else if (value instanceof ArkUnopExpr) { + return { + _: 'UnopExpr', + op: value.getOperator(), + arg: this.serializeValue(value.getOp()), + }; + } else if (value instanceof ArkInstanceInvokeExpr) { + return { + _: 'InstanceCallExpr', + instance: this.serializeValue(value.getBase()), + method: this.serializeMethodSignature(value.getMethodSignature()), + args: value.getArgs().map((arg) => this.serializeValue(arg)), + }; + } else if (value instanceof ArkStaticInvokeExpr) { + return { + _: 'StaticCallExpr', + method: this.serializeMethodSignature(value.getMethodSignature()), + args: value.getArgs().map((arg) => this.serializeValue(arg)), + }; + } else if (value instanceof ArkPtrInvokeExpr) { + return { + _: 'PtrCallExpr', + ptr: this.serializeValue(value.getFuncPtrLocal()), + method: this.serializeMethodSignature(value.getMethodSignature()), + args: value.getArgs().map((arg) => this.serializeValue(arg)), + }; + } else if (value instanceof AbstractInvokeExpr) { + throw new Error('Unhandled CallExpr: ' + util.inspect(value, { showHidden: true, depth: null })); + } else if (value instanceof ArkThisRef) { + return { + _: 'ThisRef', + type: this.serializeType(value.getType()), + }; + } else if (value instanceof ArkParameterRef) { + return { + _: 'ParameterRef', + index: value.getIndex(), + type: this.serializeType(value.getType()), + }; + } else if (value instanceof ArkArrayRef) { + return { + _: 'ArrayRef', + array: this.serializeValue(value.getBase()), + index: this.serializeValue(value.getIndex()), + type: this.serializeType(value.getType()), + }; + } else if (value instanceof ArkInstanceFieldRef) { + return { + _: 'InstanceFieldRef', + instance: this.serializeValue(value.getBase()), + field: this.serializeFieldSignature(value.getFieldSignature()), + }; + } else if (value instanceof ArkStaticFieldRef) { + return { + _: 'StaticFieldRef', + field: this.serializeFieldSignature(value.getFieldSignature()), + }; + } else if (value instanceof AbstractFieldRef) { + throw new Error('Unhandled FieldRef: ' + util.inspect(value, { showHidden: true, depth: null })); + } else if (value instanceof AbstractRef) { + throw new Error('Unhandled Ref: ' + util.inspect(value, { showHidden: true, depth: null })); + } else if (value instanceof AbstractExpr) { + throw new Error('Unhandled Expr: ' + util.inspect(value, { showHidden: true, depth: null })); + } else { + throw new Error('Unhandled Value: ' + util.inspect(value, { showHidden: true, depth: null })); + } + } + + private serializeStmt(stmt: Stmt): object { + if (stmt instanceof ArkAssignStmt) { + return { + _: 'AssignStmt', + left: this.serializeValue(stmt.getLeftOp()), + right: this.serializeValue(stmt.getRightOp()), + }; + } else if (stmt instanceof ArkInvokeStmt) { + return { + _: 'CallStmt', + expr: this.serializeValue(stmt.getInvokeExpr()), + }; + } else if (stmt instanceof ArkIfStmt) { + return { + _: 'IfStmt', + condition: this.serializeValue(stmt.getConditionExpr()), + }; + } else if (stmt instanceof ArkReturnVoidStmt) { + return { + _: 'ReturnVoidStmt', + }; + } else if (stmt instanceof ArkReturnStmt) { + return { + _: 'ReturnStmt', + arg: this.serializeValue(stmt.getOp()), + }; + } else if (stmt instanceof ArkThrowStmt) { + return { + _: 'ThrowStmt', + arg: this.serializeValue(stmt.getOp()), + }; + } else { + throw new Error('Unhandled Stmt: ' + util.inspect(stmt, { showHidden: true, depth: null })); + } + } +} diff --git a/ets2panda/linter/arkanalyzer/src/save/Printer.ts b/ets2panda/linter/arkanalyzer/src/save/Printer.ts new file mode 100644 index 0000000000..a01b50d55c --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/save/Printer.ts @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkCodeBuffer } from './ArkStream'; + +/** + * @category save + */ +export abstract class Printer { + protected printer: ArkCodeBuffer; + + public constructor(indent: string = '') { + this.printer = new ArkCodeBuffer(indent); + } + + /** + * ArkIR dump + */ + public abstract dump(): string; +} diff --git a/ets2panda/linter/arkanalyzer/src/save/PrinterBuilder.ts b/ets2panda/linter/arkanalyzer/src/save/PrinterBuilder.ts new file mode 100644 index 0000000000..96420e0501 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/save/PrinterBuilder.ts @@ -0,0 +1,172 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import fs from 'fs'; +import path from 'path'; +import { ArkFile } from '../core/model/ArkFile'; +import { DotFilePrinter } from './DotPrinter'; +import { SourceFilePrinter } from './source/SourceFilePrinter'; +import { Printer } from './Printer'; +import { JsonPrinter } from './JsonPrinter'; +import { ArkIRFilePrinter } from './arkir/ArkIRFilePrinter'; +import { Scene } from '../Scene'; +import { PrinterOptions, setPrinterOptions } from './base/BasePrinter'; + +/** + * @example + * // dump method IR to ts source + * let method: Method = xx; + * let srcPrinter = new SourceMethodPrinter(method); + * PrinterBuilder.dump(srcPrinter, 'output.ts'); + * + * + * // dump method cfg to dot + * let dotPrinter = new DotMethodPrinter(method); + * PrinterBuilder.dump(dotPrinter, 'output.dot'); + * + * // dump project + * let printer = new PrinterBuilder('output'); + * for (let f of scene.getFiles()) { + * printer.dumpToTs(f); + * } + * + * @category save + */ +export class PrinterBuilder { + outputDir: string; + constructor(outputDir: string = '') { + this.outputDir = outputDir; + } + + public static dump(source: Printer, output: string) { + fs.writeFileSync(output, source.dump()); + } + + protected getOutputDir(arkFile: ArkFile): string { + if (this.outputDir === '') { + return path.join(arkFile.getProjectDir(), '..', 'output'); + } else { + return path.join(this.outputDir); + } + } + + public dumpToDot( + arkFile: ArkFile, + output: string | undefined = undefined + ): void { + let filename = output; + if (filename === undefined) { + filename = path.join(this.getOutputDir(arkFile), arkFile.getName() + '.dot'); + } + fs.mkdirSync(path.dirname(filename), { recursive: true }); + + let printer: Printer = new DotFilePrinter(arkFile); + PrinterBuilder.dump(printer, filename as string); + } + + public dumpToTs( + arkFile: ArkFile, + output: string | undefined = undefined + ): void { + let filename = output; + if (filename === undefined) { + filename = path.join(this.getOutputDir(arkFile), arkFile.getName()); + } + if (path.extname(filename) === '') { + filename += '.ts'; + } + fs.mkdirSync(path.dirname(filename), { recursive: true }); + + let printer: Printer = new SourceFilePrinter(arkFile); + PrinterBuilder.dump(printer, filename); + } + + public dumpToJson(arkFile: ArkFile, output: string | undefined = undefined): void { + let filename = output; + if (filename === undefined) { + filename = path.join(this.getOutputDir(arkFile), arkFile.getName() + '.json'); + } + fs.mkdirSync(path.dirname(filename), { recursive: true }); + + let printer: Printer = new JsonPrinter(arkFile); + PrinterBuilder.dump(printer, filename); + } + + public dumpToIR( + arkFile: ArkFile, + output: string | undefined = undefined + ): void { + let filename = output; + if (filename === undefined) { + filename = path.join(this.getOutputDir(arkFile), arkFile.getName()); + } + + filename += '.ir'; + + fs.mkdirSync(path.dirname(filename), { recursive: true }); + + let printer: Printer = new ArkIRFilePrinter(arkFile); + PrinterBuilder.dump(printer, filename); + } +} + +/** + * @example + * // dump scene + * let scenePrinter = new ScenePrinter(scene, 'output'); + * scenePrinter.dumpToTs(); + * scenePrinter.dumpToIR(); + * + * @category save + */ +export class ScenePrinter { + scene: Scene; + outputDir: string; + printer: PrinterBuilder; + + constructor(scene: Scene, outputDir: string, option?: PrinterOptions) { + this.scene = scene; + this.outputDir = outputDir; + this.printer = new PrinterBuilder(outputDir); + if (option) { + setPrinterOptions(option); + } + } + + public dumpToDot() { + for (let f of this.scene.getFiles()) { + this.printer.dumpToDot(f); + } + } + + public dumpToTs() { + for (let f of this.scene.getFiles()) { + let relativePath = path.relative(f.getProjectDir(), f.getFilePath()); + this.printer.dumpToTs(f, path.join(this.outputDir, relativePath)); + } + } + + public dumpToJson() { + for (let f of this.scene.getFiles()) { + this.printer.dumpToJson(f); + } + } + + public dumpToIR() { + for (let f of this.scene.getFiles()) { + this.printer.dumpToIR(f); + } + } +} diff --git a/ets2panda/linter/arkanalyzer/src/save/ViewTreePrinter.ts b/ets2panda/linter/arkanalyzer/src/save/ViewTreePrinter.ts new file mode 100644 index 0000000000..58066a98df --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/save/ViewTreePrinter.ts @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { COMPONENT_POP_FUNCTION } from '../core/common/EtsConst'; +import { ViewTree, ViewTreeNode } from '../core/graph/ViewTree'; +import { ClassSignature, MethodSignature } from '../core/model/ArkSignature'; +import { Printer } from './Printer'; + +const DOT_FILE_HEADER = `digraph G { + graph [nodesep=0.1] + node [shape=box] + edge [arrowhead=vee] +`; + +export class ViewTreePrinter extends Printer { + private viewTree: ViewTree; + private dupCnt: number; + + constructor(viewTree: ViewTree) { + super(); + this.viewTree = viewTree; + this.dupCnt = 0; + } + + public dump(): string { + this.printer.clear(); + + let root = this.viewTree.getRoot(); + if (!root) { + return this.printer.toString(); + } + + this.printer.write(DOT_FILE_HEADER); + this.walk(root, root.parent); + this.printer.write('}'); + + return this.printer.toString(); + } + + private walk( + item: ViewTreeNode, + parent: ViewTreeNode | null, + map: Map = new Map() + ): void { + let skipChildren = this.writeNode(item, parent, map); + if (skipChildren) { + return; + } + for (const child of item.children) { + this.walk(child, item, map); + } + } + + private escapeDotLabel(content: string[]): string { + const MAX_LABEL_LEN = 64; + const PRE_FIX_LEN = 5; + let label = content.join('|'); + if (label.length > MAX_LABEL_LEN) { + return ( + label.substring(0, PRE_FIX_LEN) + '...' + label.substring(label.length - MAX_LABEL_LEN + PRE_FIX_LEN) + ); + } + return label; + } + + private writeNode( + item: ViewTreeNode, + parent: ViewTreeNode | null, + map: Map + ): boolean { + let id = `Node${map.size}`; + let hasSameNode = map.has(item) || map.has(item.signature!); + + if (hasSameNode) { + id = `${id}_${this.dupCnt++}`; + this.printer.write(` ${id} [label="${item.name}" style=filled color="green"]\n`); + } else { + this.printer.write(` ${id} [label="${item.name}"]\n`); + } + + if (parent) { + this.printer.write(` ${map.get(parent)!} -> ${id}\n`); + } + + this.writeNodeStateValues(item, id); + this.writeNodeAttributes(item, id); + this.writeNodeSignature(item, id); + + if (map.get(item)) { + this.printer.write(` {rank="same"; ${id};${map.get(item)};}\n`); + this.printer.write(` ${id} -> ${map.get(item)}[style=dotted]\n`); + return true; + } else if (map.get(item.signature!)) { + this.printer.write(` {rank="same"; ${id};${map.get(item.signature!)};}\n`); + this.printer.write(` ${id} -> ${map.get(item.signature!)}[style=dotted]\n`); + return true; + } + + map.set(item, id); + if (item.signature && !map.has(item.signature)) { + map.set(item.signature, id); + } + return false; + } + + private writeNodeStateValues(item: ViewTreeNode, id: string): void { + if (item.stateValues.size > 0) { + let stateValuesId = `${id}val`; + let content: string[] = []; + item.stateValues.forEach((value) => { + content.push(value.getName()); + }); + + this.printer.write( + ` ${stateValuesId} [shape=ellipse label="StateValues\n ${this.escapeDotLabel( + content + )}" fontsize=10 height=.1 style=filled color=".7 .3 1.0" ]\n` + ); + this.printer.write(` ${id} -> ${stateValuesId}\n`); + } + } + + private writeNodeAttributes(item: ViewTreeNode, id: string): void { + if (item.attributes.size > 0) { + let attributesId = `${id}attributes`; + let content: string[] = []; + for (const [key, _] of item.attributes) { + if (key !== COMPONENT_POP_FUNCTION) { + content.push(key); + } + } + if (content.length > 0) { + this.printer.write( + ` ${attributesId} [shape=ellipse label="property|Event\n${this.escapeDotLabel( + content + )}" fontsize=10 height=.1 style=filled color=".7 .3 1.0" ]\n` + ); + this.printer.write(` ${id} -> ${attributesId}\n`); + } + } + } + private writeNodeSignature(item: ViewTreeNode, id: string): void { + if (item.signature) { + let signatureId = `${id}signature`; + let content = [item.signature.toString()]; + this.printer.write( + ` ${signatureId} [shape=ellipse label="signature\n${this.escapeDotLabel( + content + )}" fontsize=10 height=.1 style=filled color=".7 .3 1.0" ]\n` + ); + this.printer.write(` ${id} -> ${signatureId}\n`); + } + } +} diff --git a/ets2panda/linter/arkanalyzer/src/save/arkir/ArkIRClassPrinter.ts b/ets2panda/linter/arkanalyzer/src/save/arkir/ArkIRClassPrinter.ts new file mode 100644 index 0000000000..d8b49f9f27 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/save/arkir/ArkIRClassPrinter.ts @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkClass } from '../../core/model/ArkClass'; +import { ArkMetadataKind, CommentsMetadata } from '../../core/model/ArkMetadata'; +import { BasePrinter, Dump } from '../base/BasePrinter'; +import { ArkIRFieldPrinter } from './ArkIRFieldPrinter'; +import { ArkIRMethodPrinter } from './ArkIRMethodPrinter'; + +/** + * @category save + */ +export class ArkIRClassPrinter extends BasePrinter { + protected cls: ArkClass; + + public constructor(cls: ArkClass, indent: string = '') { + super(indent); + this.cls = cls; + } + + public getLine(): number { + return this.cls.getLine(); + } + + public dump(): string { + this.printer.clear(); + + const commentsMetadata = this.cls.getMetadata(ArkMetadataKind.LEADING_COMMENTS); + if (commentsMetadata instanceof CommentsMetadata) { + this.printComments(commentsMetadata); + } + + this.printDecorator(this.cls.getDecorators()); + // print export class name<> + extends c0 implements x1, x2 { + this.printer + .writeIndent() + .writeSpace(this.modifiersToString(this.cls.getModifiers())) + .write(`${this.classOriginTypeToString(this.cls.getCategory())} `); + + this.printer.write(this.cls.getName()); + + const genericsTypes = this.cls.getGenericsTypes(); + if (genericsTypes) { + this.printer.write(`<${genericsTypes.map((v) => v.toString()).join(', ')}>`); + } + if (this.cls.getSuperClassName() && !this.cls.hasComponentDecorator()) { + this.printer.write(` extends ${this.cls.getSuperClassName()}`); + } + if (this.cls.getImplementedInterfaceNames().length > 0) { + this.printer.write(` implements ${this.cls.getImplementedInterfaceNames().join(', ')}`); + } + + this.printer.writeLine(' {'); + this.printer.incIndent(); + let items: Dump[] = []; + + let fieldItems = this.printFields(); + fieldItems.sort((a, b) => a.getLine() - b.getLine()); + items.push(...fieldItems); + + let methodItems = this.printMethods(); + methodItems.sort((a, b) => a.getLine() - b.getLine()); + items.push(...methodItems); + let isFirstMethod = true; + let hasField = false; + items.forEach((v): void => { + if (v instanceof ArkIRMethodPrinter) { + if (!isFirstMethod || hasField) { + this.printer.writeLine(''); + } else { + isFirstMethod = false; + } + } else if (v instanceof ArkIRFieldPrinter) { + hasField = true; + } + this.printer.write(v.dump()); + }); + + this.printer.decIndent(); + this.printer.writeIndent().writeLine('}'); + + return this.printer.toString(); + } + + protected printMethods(): Dump[] { + let items: Dump[] = []; + for (let method of this.cls.getMethods(true)) { + items.push(new ArkIRMethodPrinter(method, this.printer.getIndent())); + } + return items; + } + + private printFields(): Dump[] { + let items: Dump[] = []; + for (let field of this.cls.getFields()) { + items.push(new ArkIRFieldPrinter(field, this.printer.getIndent())); + } + return items; + } +} diff --git a/ets2panda/linter/arkanalyzer/src/save/arkir/ArkIRFieldPrinter.ts b/ets2panda/linter/arkanalyzer/src/save/arkir/ArkIRFieldPrinter.ts new file mode 100644 index 0000000000..61bbecfb38 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/save/arkir/ArkIRFieldPrinter.ts @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkField, FieldCategory } from '../../core/model/ArkField'; +import { UnknownType } from '../../core/base/Type'; +import { ArkMetadataKind, CommentsMetadata } from '../../core/model/ArkMetadata'; +import { BasePrinter } from '../base/BasePrinter'; + +/** + * @category save + */ +export class ArkIRFieldPrinter extends BasePrinter { + private field: ArkField; + + public constructor(field: ArkField, indent: string = '') { + super(indent); + this.field = field; + } + + public getLine(): number { + return this.field.getOriginPosition().getLineNo(); + } + public dump(): string { + this.printer.clear(); + const commentsMetadata = this.field.getMetadata(ArkMetadataKind.LEADING_COMMENTS); + if (commentsMetadata instanceof CommentsMetadata) { + this.printComments(commentsMetadata); + } + this.printDecorator(this.field.getDecorators()); + this.printer.writeIndent(); + if (this.field.getCategory() !== FieldCategory.ENUM_MEMBER) { + this.printer.writeSpace(this.modifiersToString(this.field.getModifiers())); + } + + this.printer.write(this.field.getName()); + + if (this.field.getQuestionToken()) { + this.printer.write('?'); + } + if (this.field.getExclamationToken()) { + this.printer.write('!'); + } + + // property.getInitializer() PropertyAccessExpression ArrowFunction ClassExpression FirstLiteralToken StringLiteral + if (!(this.field.getType() instanceof UnknownType) && this.field.getCategory() !== FieldCategory.ENUM_MEMBER) { + this.printer.write(`: ${this.field.getType().toString()}`); + } + + if (this.field.getCategory() === FieldCategory.ENUM_MEMBER) { + this.printer.writeLine(','); + } else { + this.printer.writeLine(''); + } + return this.printer.toString(); + } +} diff --git a/ets2panda/linter/arkanalyzer/src/save/arkir/ArkIRFilePrinter.ts b/ets2panda/linter/arkanalyzer/src/save/arkir/ArkIRFilePrinter.ts new file mode 100644 index 0000000000..990dc467f2 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/save/arkir/ArkIRFilePrinter.ts @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkFile } from '../../core/model/ArkFile'; +import { Dump } from '../base/BasePrinter'; +import { Printer } from '../Printer'; +import { ArkIRClassPrinter } from './ArkIRClassPrinter'; +import { ExportPrinter } from '../base/ExportPrinter'; +import { printImports } from '../base/ImportPrinter'; +import { ArkIRNamespacePrinter } from './ArkIRNamespacePrinter'; + +/** + * @category save + */ +export class ArkIRFilePrinter extends Printer { + arkFile: ArkFile; + items: Dump[] = []; + + constructor(arkFile: ArkFile) { + super(); + this.arkFile = arkFile; + } + + public dump(): string { + // print imports + this.items.push(...printImports(this.arkFile.getImportInfos(), this.printer.getIndent())); + + // print namespace + for (let ns of this.arkFile.getNamespaces()) { + this.items.push(new ArkIRNamespacePrinter(ns)); + } + // print class + for (let cls of this.arkFile.getClasses()) { + this.items.push(new ArkIRClassPrinter(cls)); + } + + // print export + for (let info of this.arkFile.getExportInfos()) { + this.items.push(new ExportPrinter(info)); + } + + this.items.sort((a, b) => a.getLine() - b.getLine()); + this.items.forEach((v): void => { + this.printer.write(v.dump()); + }); + + return this.printer.toString(); + } +} diff --git a/ets2panda/linter/arkanalyzer/src/save/arkir/ArkIRMethodPrinter.ts b/ets2panda/linter/arkanalyzer/src/save/arkir/ArkIRMethodPrinter.ts new file mode 100644 index 0000000000..9097552396 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/save/arkir/ArkIRMethodPrinter.ts @@ -0,0 +1,175 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkMethod } from '../../core/model/ArkMethod'; +import { ArkCodeBuffer } from '../ArkStream'; + +import { ArkIfStmt, Stmt } from '../../core/base/Stmt'; +import { ArkMetadataKind, CommentsMetadata } from '../../core/model/ArkMetadata'; +import { BasePrinter } from '../base/BasePrinter'; +import { Cfg } from '../../core/graph/Cfg'; +import { BasicBlock } from '../../core/graph/BasicBlock'; + +/** + * @category save + */ +export class ArkIRMethodPrinter extends BasePrinter { + private method: ArkMethod; + + public constructor(method: ArkMethod, indent: string = '') { + super(indent); + this.method = method; + } + + public dump(): string { + this.printer.clear(); + const commentsMetadata = this.method.getMetadata(ArkMetadataKind.LEADING_COMMENTS); + if (commentsMetadata instanceof CommentsMetadata) { + this.printComments(commentsMetadata); + } + + this.printMethod(this.method); + + return this.printer.toString(); + } + + public getLine(): number { + let line = this.method.getLine(); + if (line === null) { + line = 0; + } + if (line > 0) { + return line; + } + + const stmts: Stmt[] = []; + const cfg = this.method.getCfg(); + if (cfg) { + cfg.getStmts() + .reverse() + .forEach((stmt) => stmts.push(stmt)); + } + for (const stmt of stmts) { + if (stmt.getOriginPositionInfo().getLineNo() > 0) { + return stmt.getOriginPositionInfo().getLineNo(); + } + } + + return line; + } + + private printMethod(method: ArkMethod): void { + this.printDecorator(method.getDecorators()); + this.printer.writeIndent().write(this.methodProtoToString(method)); + // abstract function no body + if (!method.getBody()) { + this.printer.writeLine(''); + return; + } + + this.printer.writeLine(' {'); + this.printer.incIndent(); + this.printBody(method); + this.printer.decIndent(); + this.printer.writeIndent().writeLine('}'); + } + + private printBody(method: ArkMethod): void { + if (method.getCfg()) { + this.printCfg(method.getCfg()!); + } + } + + protected methodProtoToString(method: ArkMethod): string { + let code = new ArkCodeBuffer(); + code.writeSpace(this.modifiersToString(method.getModifiers())); + + if (method.getAsteriskToken()) { + code.writeSpace('*'); + } + code.write(this.resolveMethodName(method.getName())); + + const genericTypes = method.getGenericTypes(); + if (genericTypes && genericTypes.length > 0) { + let typeParameters: string[] = []; + genericTypes.forEach((genericType) => { + typeParameters.push(genericType.toString()); + }); + code.write(`<${genericTypes.join(', ')}>`); + } + + let parameters: string[] = []; + method.getParameters().forEach((parameter) => { + let str: string = parameter.getName(); + if (parameter.hasDotDotDotToken()) { + str = `...${parameter.getName()}`; + } + if (parameter.isOptional()) { + str += '?'; + } + if (parameter.getType()) { + str += ': ' + parameter.getType().toString(); + } + parameters.push(str); + }); + code.write(`(${parameters.join(', ')})`); + const returnType = method.getReturnType(); + code.write(`: ${returnType.toString()}`); + return code.toString(); + } + + private printCfg(cfg: Cfg): void { + let blocks = cfg.getBlocks(); + + let firstBB = true; + for (const block of blocks) { + if (!firstBB) { + this.printer.writeLine(''); + } + this.printBasicBlock(block); + if (firstBB) { + firstBB = false; + } + } + } + + private printBasicBlock(block: BasicBlock): void { + let successors = block.getSuccessors(); + + this.printer.writeIndent().writeLine(`label${block.getId()}:`); + this.printer.incIndent(); + + if (successors.length === 1) { + block.getStmts().map((stmt) => { + this.printer.writeIndent().writeLine(stmt.toString()); + }); + this.printer.writeIndent().writeLine(`goto label${successors[0].getId()}`); + } else if (successors.length === 2) { + for (const stmt of block.getStmts()) { + if (stmt instanceof ArkIfStmt) { + this.printer.writeIndent().writeLine(`${stmt.toString()} goto label${successors[0].getId()} label${successors[1].getId()}`); + } else { + this.printer.writeIndent().writeLine(stmt.toString()); + } + } + } else { + block.getStmts().map((stmt) => { + this.printer.writeIndent().writeLine(stmt.toString()); + }); + } + + this.printer.decIndent(); + } +} diff --git a/ets2panda/linter/arkanalyzer/src/save/arkir/ArkIRNamespacePrinter.ts b/ets2panda/linter/arkanalyzer/src/save/arkir/ArkIRNamespacePrinter.ts new file mode 100644 index 0000000000..3e2fc8d57f --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/save/arkir/ArkIRNamespacePrinter.ts @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkMetadataKind, CommentsMetadata } from '../../core/model/ArkMetadata'; +import { ArkNamespace } from '../../core/model/ArkNamespace'; + +import { BasePrinter, Dump } from '../base/BasePrinter'; +import { ArkIRClassPrinter } from './ArkIRClassPrinter'; +import { ExportPrinter } from '../base/ExportPrinter'; + +/** + * @category save + */ +export class ArkIRNamespacePrinter extends BasePrinter { + ns: ArkNamespace; + + public constructor(ns: ArkNamespace, indent: string = '') { + super(indent); + this.ns = ns; + } + + public getLine(): number { + return this.ns.getLine(); + } + + public dump(): string { + const commentsMetadata = this.ns.getMetadata(ArkMetadataKind.LEADING_COMMENTS); + if (commentsMetadata instanceof CommentsMetadata) { + const comments = commentsMetadata.getComments(); + comments.forEach((comment) => { + this.printer.writeIndent().writeLine(comment.content); + }); + } + this.printer.writeIndent().writeSpace(this.modifiersToString(this.ns.getModifiers())) + .writeLine(`namespace ${this.ns.getName()} {`); + this.printer.incIndent(); + + let items: Dump[] = []; + // print class + for (let cls of this.ns.getClasses()) { + + items.push(new ArkIRClassPrinter(cls, this.printer.getIndent())); + + } + // print namespace + for (let childNs of this.ns.getNamespaces()) { + items.push(new ArkIRNamespacePrinter(childNs, this.printer.getIndent())); + } + // print exportInfos + for (let exportInfo of this.ns.getExportInfos()) { + items.push( + new ExportPrinter(exportInfo, this.printer.getIndent()) + ); + } + + items.sort((a, b) => a.getLine() - b.getLine()); + items.forEach((v): void => { + this.printer.write(v.dump()); + }); + this.printer.decIndent(); + this.printer.writeIndent().writeLine('}'); + return this.printer.toString(); + } +} diff --git a/ets2panda/linter/arkanalyzer/src/save/base/BasePrinter.ts b/ets2panda/linter/arkanalyzer/src/save/base/BasePrinter.ts new file mode 100644 index 0000000000..551c2f37f2 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/save/base/BasePrinter.ts @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Decorator } from '../../core/base/Decorator'; +import { modifiers2stringArray } from '../../core/model/ArkBaseModel'; +import { ClassCategory } from '../../core/model/ArkClass'; +import { CommentsMetadata } from '../../core/model/ArkMetadata'; +import { Printer } from '../Printer'; +import { PrinterUtils } from './PrinterUtils'; + +export interface Dump { + getLine(): number; + dump(): string; +} + +export interface PrinterOptions { + pureTs: boolean; // struct 转成class + noMethodBody: boolean; // 仅输出函数原型,不输出函数体 +} + +let printerOptions: PrinterOptions = { pureTs: false, noMethodBody: false }; +export function setPrinterOptions(options: PrinterOptions): void { + printerOptions = { ...printerOptions, ...options }; +} + +export abstract class BasePrinter extends Printer implements Dump { + public constructor(indent: string) { + super(indent); + } + abstract getLine(): number; + + protected printDecorator(docorator: Decorator[]): void { + docorator.forEach((value) => { + this.printer.writeIndent().writeLine(value.toString()); + }); + } + + protected printComments(commentsMetadata: CommentsMetadata): void { + const comments = commentsMetadata.getComments(); + comments.forEach((comment) => { + this.printer.writeIndent().writeLine(comment.content); + }); + } + + protected modifiersToString(modifiers: number): string { + let modifiersStr: string[] = modifiers2stringArray(modifiers); + return modifiersStr.join(' '); + } + + protected resolveMethodName(name: string): string { + if (name === '_Constructor') { + return 'constructor'; + } + if (name.startsWith('Get-')) { + return name.replace('Get-', 'get '); + } + if (name.startsWith('Set-')) { + return name.replace('Set-', 'set '); + } + return name; + } + + protected classOriginTypeToString(clsCategory: ClassCategory): string { + if (printerOptions.pureTs) { + if (clsCategory === ClassCategory.STRUCT) { + clsCategory = ClassCategory.CLASS; + } + } + + return PrinterUtils.classOriginTypeToString.get(clsCategory)!; + } + + public static getPrinterOptions(): PrinterOptions { + return printerOptions; + } +} diff --git a/ets2panda/linter/arkanalyzer/src/save/base/ExportPrinter.ts b/ets2panda/linter/arkanalyzer/src/save/base/ExportPrinter.ts new file mode 100644 index 0000000000..d76e919e82 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/save/base/ExportPrinter.ts @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ExportInfo, ExportType } from '../../core/model/ArkExport'; +import { ArkMetadataKind, CommentsMetadata } from '../../core/model/ArkMetadata'; +import { BasePrinter } from './BasePrinter'; + +export class ExportPrinter extends BasePrinter { + info: ExportInfo; + + public constructor(info: ExportInfo, indent: string = '') { + super(indent); + this.info = info; + } + + public getLine(): number { + return this.info.getOriginTsPosition().getLineNo(); + } + + public dump(): string { + this.printer.clear(); + const commentsMetadata = this.info.getMetadata(ArkMetadataKind.LEADING_COMMENTS); + if (commentsMetadata instanceof CommentsMetadata) { + this.printComments(commentsMetadata); + } + + if ( + !this.info.getFrom() && (this.info.isExport() || + this.info.getExportClauseType() === ExportType.LOCAL || + this.info.getExportClauseType() === ExportType.TYPE) + ) { + return this.printer.toString(); + } + + if (this.info.getExportClauseName() === '*') { + // just like: export * as xx from './yy' + if (this.info.getNameBeforeAs() && this.info.getNameBeforeAs() !== '*') { + this.printer + .writeIndent() + .write(`export ${this.info.getNameBeforeAs()} as ${this.info.getExportClauseName()}`); + } else { + this.printer.writeIndent().write(`export ${this.info.getExportClauseName()}`); + } + } else { + // just like: export {xxx as x} from './yy' + if (this.info.getNameBeforeAs()) { + this.printer.write(`export {${this.info.getNameBeforeAs()} as ${this.info.getExportClauseName()}}`); + } else { + this.printer.write(`export {${this.info.getExportClauseName()}}`); + } + } + if (this.info.getFrom()) { + this.printer.write(` from '${this.info.getFrom() as string}'`); + } + this.printer.writeLine(';'); + + return this.printer.toString(); + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/save/base/ImportPrinter.ts b/ets2panda/linter/arkanalyzer/src/save/base/ImportPrinter.ts new file mode 100644 index 0000000000..14d08b429b --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/save/base/ImportPrinter.ts @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ImportInfo } from '../../core/model/ArkImport'; +import { ArkMetadataKind, CommentsMetadata } from '../../core/model/ArkMetadata'; +import { BasePrinter, Dump } from './BasePrinter'; + +export class ImportPrinter extends BasePrinter { + infos: ImportInfo[]; + + public constructor(infos: ImportInfo[], indent: string = '') { + super(indent); + this.infos = infos; + } + + public getLine(): number { + return this.infos[0].getOriginTsPosition().getLineNo(); + } + + public dump(): string { + const commentsMetadata = this.infos[0].getMetadata(ArkMetadataKind.LEADING_COMMENTS); + if (commentsMetadata instanceof CommentsMetadata) { + this.printComments(commentsMetadata); + } + let clauseNames: string[] = []; + let namedImports: string[] = []; + + for (const info of this.infos) { + if (info.getImportType() === 'Identifier') { + // sample: import fs from 'fs' + clauseNames.push(info.getImportClauseName()); + } else if (info.getImportType() === 'NamedImports') { + // sample: import {xxx} from './yyy' + if (info.getNameBeforeAs()) { + namedImports.push(`${info.getNameBeforeAs()} as ${info.getImportClauseName()}`); + } else { + namedImports.push(info.getImportClauseName()); + } + } else if (info.getImportType() === 'NamespaceImport') { + // sample: import * as ts from 'ohos-typescript' + clauseNames.push(`* as ${info.getImportClauseName()}`); + } else if (info.getImportType() === 'EqualsImport') { + // sample: import mmmm = require('./xxx') + this.printer + .writeIndent() + .writeLine(`import ${info.getImportClauseName()} = require('${info.getFrom() as string}');`); + } else { + // sample: import '../xxx' + this.printer.writeIndent().writeLine(`import '${info.getFrom() as string}';`); + } + } + + if (namedImports.length > 0) { + clauseNames.push(`{${namedImports.join(', ')}}`); + } + + this.printer + .writeIndent() + .writeLine(`import ${clauseNames.join(', ')} from '${this.infos[0].getFrom() as string}';`); + + return this.printer.toString(); + } +} + +function mergeImportInfos(infos: ImportInfo[]): Map { + let map = new Map(); + + for (let info of infos) { + let key = `${info.getOriginTsPosition().getLineNo()}-${info.getFrom()}` + let merge = map.get(key) || []; + merge.push(info); + map.set(key, merge); + } + + return map; +} + +export function printImports(imports: ImportInfo[], indent: string): Dump[] { + let mergeImports = mergeImportInfos(imports); + let items: Dump[] = []; + + for (const [_, importInfos] of mergeImports) { + items.push(new ImportPrinter(importInfos, indent)); + } + return items; +} diff --git a/ets2panda/linter/arkanalyzer/src/save/base/PrinterUtils.ts b/ets2panda/linter/arkanalyzer/src/save/base/PrinterUtils.ts new file mode 100644 index 0000000000..ee019a536e --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/save/base/PrinterUtils.ts @@ -0,0 +1,232 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Constant } from '../../core/base/Constant'; +import { + ArkInstanceInvokeExpr, + ArkNormalBinopExpr, + ArkStaticInvokeExpr, + NormalBinaryOperator, +} from '../../core/base/Expr'; +import { Local } from '../../core/base/Local'; +import { ArkAssignStmt, Stmt } from '../../core/base/Stmt'; +import { + COMPONENT_BRANCH_FUNCTION, + COMPONENT_CREATE_FUNCTION, + COMPONENT_IF, + COMPONENT_POP_FUNCTION, + isEtsSystemComponent, + SPECIAL_CONTAINER_COMPONENT, +} from '../../core/common/EtsConst'; +import { ArkClass, ClassCategory } from '../../core/model/ArkClass'; +import Logger, { LOG_MODULE_TYPE } from '../../utils/logger'; +import { ANONYMOUS_CLASS_PREFIX, ANONYMOUS_METHOD_PREFIX, DEFAULT_ARK_CLASS_NAME } from '../../core/common/Const'; +import { ClassSignature } from '../../core/model/ArkSignature'; +import { ArkNamespace } from '../../core/model/ArkNamespace'; +import ts from 'ohos-typescript'; +import { TEMP_LOCAL_PREFIX } from '../../core/common/Const'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'PrinterUtils'); + +export const CLASS_CATEGORY_COMPONENT = 100; + +export class PrinterUtils { + public static classOriginTypeToString = new Map([ + [ClassCategory.CLASS, 'class'], + [ClassCategory.STRUCT, 'struct'], + [ClassCategory.INTERFACE, 'interface'], + [ClassCategory.ENUM, 'enum'], + [ClassCategory.TYPE_LITERAL, 'typeliteral'], + [ClassCategory.OBJECT, 'object'], + [CLASS_CATEGORY_COMPONENT, 'component'], + ]); + + public static isAnonymousClass(name: string): boolean { + return name.startsWith(ANONYMOUS_CLASS_PREFIX); + } + + public static isDefaultClass(name: string): boolean { + return name === DEFAULT_ARK_CLASS_NAME; + } + + public static isAnonymousMethod(name: string): boolean { + return name.startsWith(ANONYMOUS_METHOD_PREFIX); + } + + public static isConstructorMethod(name: string): boolean { + return name === 'constructor'; + } + + public static isDeIncrementStmt(stmt: Stmt | null, op: NormalBinaryOperator): boolean { + if (!(stmt instanceof ArkAssignStmt)) { + return false; + } + + let leftOp = stmt.getLeftOp(); + let rightOp = stmt.getRightOp(); + if (!(leftOp instanceof Local) || !(rightOp instanceof ArkNormalBinopExpr)) { + return false; + } + + let op1 = rightOp.getOp1(); + let op2 = rightOp.getOp2(); + let operator = rightOp.getOperator(); + if (!(op1 instanceof Local) || !(op2 instanceof Constant)) { + return false; + } + + return leftOp.getName() === op1.getName() && operator === op && op2.getValue() === '1'; + } + + public static isTemp(name: string): boolean { + return name.startsWith(TEMP_LOCAL_PREFIX); + } + + public static getOriginType(cls: ArkClass): number { + if (cls.hasComponentDecorator()) { + return CLASS_CATEGORY_COMPONENT; + } + return cls.getCategory(); + } + + public static isComponentPop(invokeExpr: ArkStaticInvokeExpr): boolean { + let className = invokeExpr.getMethodSignature().getDeclaringClassSignature().getClassName(); + let methodName = invokeExpr.getMethodSignature().getMethodSubSignature().getMethodName(); + + if ( + methodName === COMPONENT_POP_FUNCTION && + (isEtsSystemComponent(className) || SPECIAL_CONTAINER_COMPONENT.has(className)) + ) { + return true; + } + + return false; + } + + public static isComponentCreate(invokeExpr: ArkStaticInvokeExpr): boolean { + let className = invokeExpr.getMethodSignature().getDeclaringClassSignature().getClassName(); + let methodName = invokeExpr.getMethodSignature().getMethodSubSignature().getMethodName(); + + if ( + methodName === COMPONENT_CREATE_FUNCTION && + (isEtsSystemComponent(className) || SPECIAL_CONTAINER_COMPONENT.has(className)) + ) { + return true; + } + + return false; + } + + public static isComponentAttributeInvoke( + invokeExpr: ArkInstanceInvokeExpr, + visitor: Set = new Set() + ): boolean { + if (visitor.has(invokeExpr)) { + return false; + } + visitor.add(invokeExpr); + let base = invokeExpr.getBase(); + if (!(base instanceof Local)) { + logger.error(`PrinterUtils->isComponentAttributeInvoke illegal invoke expr ${invokeExpr}`); + return false; + } + let stmt = base.getDeclaringStmt(); + if (!stmt || !(stmt instanceof ArkAssignStmt)) { + return false; + } + + let rightOp = stmt.getRightOp(); + if (rightOp instanceof ArkInstanceInvokeExpr) { + return PrinterUtils.isComponentAttributeInvoke(rightOp, visitor); + } + + if (rightOp instanceof ArkStaticInvokeExpr) { + return PrinterUtils.isComponentCreate(rightOp); + } + + return false; + } + + public static isComponentIfBranchInvoke(invokeExpr: ArkStaticInvokeExpr): boolean { + let className = invokeExpr.getMethodSignature().getDeclaringClassSignature().getClassName(); + let methodName = invokeExpr.getMethodSignature().getMethodSubSignature().getMethodName(); + + if (className === COMPONENT_IF && methodName === COMPONENT_BRANCH_FUNCTION) { + return true; + } + return false; + } + + public static isComponentIfElseInvoke(invokeExpr: ArkStaticInvokeExpr): boolean { + let className = invokeExpr.getMethodSignature().getDeclaringClassSignature().getClassName(); + let methodName = invokeExpr.getMethodSignature().getMethodSubSignature().getMethodName(); + + if (className === COMPONENT_IF && methodName === COMPONENT_BRANCH_FUNCTION) { + let arg0 = invokeExpr.getArg(0) as Constant; + if (arg0.getValue() === '1') { + return true; + } + } + return false; + } + + public static getStaticInvokeClassFullName(classSignature: ClassSignature, namespace?: ArkNamespace): string { + let code: string[] = []; + let declareNamespace = classSignature.getDeclaringNamespaceSignature(); + while (declareNamespace !== null) { + let namespaceName = declareNamespace.getNamespaceName(); + if (namespaceName.length > 0 && namespaceName !== namespace?.getName()) { + code.unshift(namespaceName); + declareNamespace = declareNamespace.getDeclaringNamespaceSignature(); + } else { + break; + } + } + + let className = classSignature.getClassName(); + if (className && className.length > 0 && !PrinterUtils.isDefaultClass(className)) { + code.push(className); + } + return code.join('.'); + } + + public static isIdentifierText(text: string): boolean { + let ch = text.charCodeAt(0); + if (!ts.isIdentifierStart(ch, ts.ScriptTarget.Latest)) { + return false; + } + + for (let i = 1; i < text.length; i++) { + if (!ts.isIdentifierPart(text.charCodeAt(i), ts.ScriptTarget.Latest)) { + return false; + } + } + + return true; + } + + public static escape(text: string): string { + return text + .replace(/\\/g, '\\\\') + .replace(/\f/g, `\\f`) + .replace(/\n/g, `\\n`) + .replace(/\r/g, '\\r') + .replace(/\t/g, '\\t') + .replace(/\v/g, '\\v') + .replace(/\?/g, '\\?') + .replace(/\'/g, "\\'") + .replace(/\"/g, '\\"'); + } +} diff --git a/ets2panda/linter/arkanalyzer/src/save/serializeArkIR.ts b/ets2panda/linter/arkanalyzer/src/save/serializeArkIR.ts new file mode 100644 index 0000000000..1793f879f0 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/save/serializeArkIR.ts @@ -0,0 +1,316 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import path from 'path'; +import fs from 'fs'; +import { Command, InvalidArgumentError } from 'commander'; +import { PrinterBuilder } from './PrinterBuilder'; +import { SceneConfig } from '../Config'; +import { Scene } from '../Scene'; +import { ArkFile } from '../core/model/ArkFile'; +import { JsonPrinter } from './JsonPrinter'; +import { Printer } from './Printer'; +import { PointerAnalysis } from '../callgraph/pointerAnalysis/PointerAnalysis'; + +export function buildSceneFromSingleFile(filename: string, verbose: boolean = false): Scene { + if (verbose) { + console.log('Building scene...'); + } + const filepath = path.resolve(filename); + const projectDir = path.dirname(filepath); + const config = new SceneConfig(); + config.buildConfig('single-file', projectDir, []); + config.getProjectFiles().push(filepath); + const scene = new Scene(); + scene.buildSceneFromProjectDir(config); + return scene; +} + +export function buildSceneFromProjectDir(inputDir: string, verbose: boolean = false): Scene { + if (verbose) { + console.log('Building scene...'); + } + const config = new SceneConfig(); + config.buildFromProjectDir(inputDir); + const scene = new Scene(); + scene.buildSceneFromProjectDir(config); + return scene; +} + +export function serializeArkFile(arkFile: ArkFile, output?: string): void { + let filename = output; + if (filename === undefined) { + const outputDir = path.join(arkFile.getProjectDir(), '..', 'output'); + filename = path.join(outputDir, arkFile.getName() + '.json'); + } + fs.mkdirSync(path.dirname(filename), { recursive: true }); + let printer: Printer = new JsonPrinter(arkFile); + const fd = fs.openSync(filename, 'w'); + fs.writeFileSync(fd, printer.dump()); + fs.closeSync(fd); +} + +export function serializeScene( + scene: Scene, + outDir: string, + verbose: boolean = false, +): void { + let files = scene.getFiles(); + console.log(`Serializing Scene with ${files.length} files to '${outDir}'...`); + for (let f of files) { + let filepath = f.getName(); + let outPath = path.join(outDir, filepath + '.json'); + if (verbose) { + console.log(`Serializing ArkIR for '${filepath}' to '${outPath}'...`); + } + serializeArkFile(f, outPath); + } + if (verbose) { + console.log(`All ${files.length} files in scene are serialized`); + } +} + +function serializeSingleTsFile(input: string, output: string, options: any): void { + options.verbose && console.log(`Serializing TS file to JSON: '${input}' -> '${output}'`); + + let filepath = path.resolve(input); + let projectDir = path.dirname(filepath); + + const scene = buildSceneFromSingleFile(filepath, options.verbose); + + let files = scene.getFiles(); + if (options.verbose) { + console.log(`Scene contains ${files.length} files`); + for (let f of files) { + console.log(`- '${f.getName()}'`); + } + } + + if (options.inferTypes) { + options.verbose && console.log('Inferring types...'); + scene.inferTypes(); + if (options.inferTypes > 1) { + for (let i = 1; i < options.inferTypes; i++) { + options.verbose && console.log(`Inferring types one more time (${i + 1} / ${options.inferTypes})...`); + scene.inferTypes(); + } + } + } + + if (options.entrypoint) { + options.verbose && console.log('Generating entrypoint...'); + PointerAnalysis.pointerAnalysisForWholeProject(scene); + } + + options.verbose && console.log('Extracting single ArkFile...'); + + if (files.length === 0) { + console.error(`ERROR: No files found in the project directory '${projectDir}'.`); + process.exit(1); + } + if (files.length > 1) { + console.error(`ERROR: More than one file found in the project directory '${projectDir}'.`); + process.exit(1); + } + // Note: we explicitly push a single path to the project files (in config), + // so we expect there is only *one* ArkFile in the scene. + let arkFile = scene.getFiles()[0]; + serializeFile(arkFile, output, options, scene); + + options.verbose && console.log('All done!'); +} + +function serializeFile(arkFile: ArkFile, output: string, options: any, scene: Scene): void { + let outPath: string; + if (fs.existsSync(output) && fs.statSync(output).isDirectory()) { + outPath = path.join(output, arkFile.getName() + '.json'); + } else if (!fs.existsSync(output) && output.endsWith('/')) { + outPath = path.join(output, arkFile.getName() + '.json'); + } else { + outPath = output; + } + + console.log(`Serializing ArkIR for '${arkFile.getName()}' to '${outPath}'...`); + let printer = new PrinterBuilder(); + printer.dumpToJson(arkFile, outPath); + + if (options.entrypoint) { + let arkFile = scene.getFiles()[1]; + let outPath: string; + if (fs.existsSync(output) && fs.statSync(output).isDirectory()) { + outPath = path.join(output, arkFile.getName() + '.json'); + } else if (!fs.existsSync(output) && output.endsWith('/')) { + outPath = path.join(output, arkFile.getName() + '.json'); + } else { + outPath = path.join(path.dirname(output), arkFile.getName() + '.json'); + } + console.log(`Serializing entrypoint to '${outPath}'...`); + printer.dumpToJson(arkFile, outPath); + } +} + +function serializeMultipleTsFiles( + inputDir: string, + outDir: string, + options: any, +): void { + console.log(`Serializing multiple TS files to JSON: '${inputDir}' -> '${outDir}'`); + if (fs.existsSync(outDir) && !fs.statSync(outDir).isDirectory()) { + console.error(`ERROR: Output path must be a directory.`); + process.exit(1); + } + + if (options.verbose) { + console.log('Building scene...'); + } + let config = new SceneConfig(); + config.buildFromProjectDir(inputDir); + let scene = new Scene(); + scene.buildSceneFromProjectDir(config); + + let files = scene.getFiles(); + if (options.verbose) { + console.log(`Scene contains ${files.length} files`); + files.forEach((f) => console.log(`- '${f.getName()}'`)); + } + + if (options.inferTypes) { + if (options.verbose) { + console.log('Inferring types...'); + } + scene.inferTypes(); + if (options.inferTypes > 1) { + for (let i = 1; i < options.inferTypes; i++) { + options.verbose && console.log(`Inferring types one more time (${i + 1} / ${options.inferTypes})...`); + scene.inferTypes(); + } + } + } + + if (options.entrypoint) { + if (options.verbose) { + console.log('Generating entrypoint...'); + } + PointerAnalysis.pointerAnalysisForWholeProject(scene); + files = scene.getFiles(); + } + + if (options.verbose) { + console.log('Serializing...'); + } + let printer = new PrinterBuilder(); + for (let f of files) { + let filepath = f.getName(); + let outPath = path.join(outDir, filepath + '.json'); + console.log(`Serializing ArkIR for '${filepath}' to '${outPath}'...`); + printer.dumpToJson(f, outPath); + } + console.log('All done!'); +} + +function serializeTsProject( + inputDir: string, + outDir: string, + options: any, +): void { + console.log(`Serializing TS project to JSON: '${inputDir}' -> '${outDir}'`); + + if (fs.existsSync(outDir) && !fs.statSync(outDir).isDirectory()) { + console.error(`ERROR: Output path must be a directory.`); + process.exit(1); + } + + const scene = buildSceneFromProjectDir(inputDir, options.verbose); + + if (options.inferTypes) { + if (options.verbose) { + console.log('Inferring types...'); + } + scene.inferTypes(); + if (options.inferTypes > 1) { + for (let i = 1; i < options.inferTypes; i++) { + options.verbose && console.log(`Inferring types one more time (${i + 1} / ${options.inferTypes})...`); + scene.inferTypes(); + } + } + } + + if (options.entrypoint) { + if (options.verbose) { + console.log('Generating entrypoint...'); + } + PointerAnalysis.pointerAnalysisForWholeProject(scene); + } + + serializeScene(scene, outDir, options.verbose); + + if (options.verbose) { + console.log('All done!'); + } +} + +function myParseInt(value: string, _previous: number): number { + const parsedValue = parseInt(value, 10); + if (isNaN(parsedValue)) { + throw new InvalidArgumentError('Must be a number.'); + } + if (parsedValue < 1) { + throw new InvalidArgumentError('Must be greater than 0.'); + } + return parsedValue; +} + +export const program = new Command() + .name('serializeArkIR') + .description('Serialize ArkIR for TypeScript files or projects to JSON') + .argument('', 'Input file or directory') + .argument('', 'Output file or directory') + .option('-m, --multi', 'Flag to indicate the input is a directory', false) + .option('-p, --project', 'Flag to indicate the input is a project directory', false) + .option('-t, --infer-types [times]', 'Infer types in the ArkIR', myParseInt) + .option('-e, --entrypoint', 'Generate entrypoint for the files', false) + .option('-v, --verbose', 'Verbose output', false) + .action((input: any, output: any, options: any) => { + + // Check for invalid combinations of flags + if (options.multi && options.project) { + console.error(`ERROR: You cannot provide both the '-m' and '-p' flags.`); + process.exit(1); + } + + // Ensure the input path exists + if (!fs.existsSync(input)) { + console.error(`ERROR: The input path '${input}' does not exist.`); + process.exit(1); + } + + // Handle the case where the input is a directory + if (fs.statSync(input).isDirectory() && !(options.multi || options.project)) { + console.error(`ERROR: If the input is a directory, you must provide the '-p' or '-m' flag.`); + process.exit(1); + } + + if (options.project) { + serializeTsProject(input, output, options); + } else if (options.multi) { + serializeMultipleTsFiles(input, output, options); + } else { + serializeSingleTsFile(input, output, options); + } + }); + +if (require.main === module) { + program.parse(process.argv); +} diff --git a/ets2panda/linter/arkanalyzer/src/save/source/SourceBase.ts b/ets2panda/linter/arkanalyzer/src/save/source/SourceBase.ts new file mode 100644 index 0000000000..c2d917f9c7 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/save/source/SourceBase.ts @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkFile } from '../../core/model/ArkFile'; +import { ArkMethod } from '../../core/model/ArkMethod'; +import { ClassSignature, MethodSignature } from '../../core/model/ArkSignature'; +import { ArkClass } from '../../core/model/ArkClass'; +import { ArkCodeBuffer } from '../ArkStream'; +import { Local } from '../../core/base/Local'; +import { TransformerContext } from './SourceTransformer'; +import { ArkNamespace } from '../../core/model/ArkNamespace'; +import { BasePrinter } from '../base/BasePrinter'; + +export abstract class SourceBase + extends BasePrinter + implements TransformerContext +{ + protected arkFile: ArkFile; + protected inBuilder: boolean = false; + + public constructor(arkFile: ArkFile, indent: string = '') { + super(indent); + this.arkFile = arkFile; + } + + public getDeclaringArkNamespace(): ArkNamespace | undefined { + return undefined + } + + public getArkFile(): ArkFile { + return this.arkFile; + } + + public getMethod(signature: MethodSignature): ArkMethod | null { + return this.getArkFile().getScene().getMethod(signature); + } + + public getClass(signature: ClassSignature): ArkClass | null { + return this.getArkFile().getScene().getClass(signature); + } + + public getPrinter(): ArkCodeBuffer { + return this.printer; + } + + public transTemp2Code(temp: Local): string { + return temp.getName(); + } + + public isInBuilderMethod(): boolean { + return this.inBuilder; + } + + protected resolveKeywordType(keywordStr: string): string { + // 'NumberKeyword | NullKeyword | + let types: string[] = []; + for (let keyword of keywordStr.split('|')) { + keyword = keyword.trim(); + if (keyword.length === 0) { + continue; + } + if (keyword.endsWith('Keyword')) { + keyword = keyword + .substring(0, keyword.length - 'Keyword'.length) + .toLowerCase(); + } + types.push(keyword); + } + + return types.join(' | '); + } + +} diff --git a/ets2panda/linter/arkanalyzer/src/save/source/SourceBody.ts b/ets2panda/linter/arkanalyzer/src/save/source/SourceBody.ts new file mode 100644 index 0000000000..9d048c158e --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/save/source/SourceBody.ts @@ -0,0 +1,331 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkInstanceInvokeExpr } from '../../core/base/Expr'; +import { Local } from '../../core/base/Local'; +import { ArkAssignStmt, ArkIfStmt, ArkInvokeStmt, Stmt } from '../../core/base/Stmt'; +import { BasicBlock } from '../../core/graph/BasicBlock'; +import { ArkBody } from '../../core/model/ArkBody'; +import { ArkMethod } from '../../core/model/ArkMethod'; +import Logger, { LOG_MODULE_TYPE } from '../../utils/logger'; +import { ArkCodeBuffer } from '../ArkStream'; +import { + SourceBreakStmt, + SourceCatchStmt, + SourceCompoundEndStmt, + SourceContinueStmt, + SourceDoStmt, + SourceDoWhileStmt, + SourceElseStmt, + SourceFinallyStmt, + SourceForStmt, + SourceIfStmt, + SourceStmt, + SourceTryStmt, + SourceWhileStmt, + stmt2SourceStmt, + StmtPrinterContext, +} from './SourceStmt'; +import { AbstractFlowGraph, CodeBlockType } from '../../utils/CfgStructualAnalysis'; +import { ArkClass } from '../../core/model/ArkClass'; +import { ArkFile } from '../../core/model/ArkFile'; +import { ClassSignature, MethodSignature } from '../../core/model/ArkSignature'; +import { ModelUtils } from '../../core/common/ModelUtils'; +import { PrinterUtils } from '../base/PrinterUtils'; +import { ArkNamespace } from '../../core/model/ArkNamespace'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'SourceBody'); + +export class SourceBody implements StmtPrinterContext { + protected printer: ArkCodeBuffer; + private arkBody: ArkBody; + private stmts: SourceStmt[] = []; + private method: ArkMethod; + private cfgUtils: AbstractFlowGraph; + private tempCodeMap: Map; + private tempVisitor: Set; + private skipStmts: Set; + private stmtReader: StmtReader; + private definedLocals: Set; + private inBuilder: boolean; + private lastStmt: Stmt; + + public constructor(indent: string, method: ArkMethod, inBuilder: boolean) { + this.printer = new ArkCodeBuffer(indent); + this.method = method; + this.arkBody = method.getBody()!; + this.cfgUtils = new AbstractFlowGraph(method.getCfg()!, this.arkBody.getTraps()); + this.tempCodeMap = new Map(); + this.tempVisitor = new Set(); + this.definedLocals = new Set(); + this.inBuilder = inBuilder; + this.skipStmts = new Set(); + this.stmtReader = new StmtReader([]); + this.lastStmt = this.arkBody.getCfg().getStartingStmt(); + this.buildSourceStmt(); + } + setSkipStmt(stmt: Stmt): void { + this.skipStmts.add(stmt); + } + + isInBuilderMethod(): boolean { + return this.inBuilder; + } + isInDefaultMethod(): boolean { + return this.method.isDefaultArkMethod(); + } + public getArkFile(): ArkFile { + return this.method.getDeclaringArkFile(); + } + + public getDeclaringArkNamespace(): ArkNamespace | undefined { + return this.method.getDeclaringArkClass().getDeclaringArkNamespace(); + } + + public getMethod(signature: MethodSignature): ArkMethod | null { + let method = this.method.getDeclaringArkFile().getScene().getMethod(signature); + if (method) { + return method; + } + return this.method.getDeclaringArkClass().getMethodWithName(signature.getMethodSubSignature().getMethodName()); + } + + public getClass(signature: ClassSignature): ArkClass | null { + return ModelUtils.getClass(this.method, signature); + } + + public getLocals(): Map { + return this.arkBody.getLocals(); + } + + public defineLocal(local: Local): void { + this.definedLocals.add(local); + } + + public isLocalDefined(local: Local): boolean { + return this.definedLocals.has(local); + } + + public getStmtReader(): StmtReader { + return this.stmtReader; + } + + public setTempCode(temp: string, code: string): void { + this.tempCodeMap.set(temp, code); + } + + public transTemp2Code(temp: Local): string { + if (this.tempCodeMap.has(temp.getName()) && PrinterUtils.isTemp(temp.getName())) { + this.tempVisitor.add(temp.getName()); + return this.tempCodeMap.get(temp.getName())!; + } + + return temp.getName(); + } + + public getTempCodeMap(): Map { + return this.tempCodeMap; + } + + public hasTempVisit(temp: string): boolean { + return this.tempVisitor.has(temp); + } + + public setTempVisit(temp: string): void { + this.tempVisitor.add(temp); + } + + public getPrinter(): ArkCodeBuffer { + return this.printer; + } + + public dump(): string { + this.printStmts(); + return this.printer.toString(); + } + + private buildSourceStmt(): void { + this.cfgUtils.preOrder(this.cfgUtils.getEntry(), (block, type) => { + this.buildBasicBlock(block, type); + }); + } + + private buildBasicBlock(block: BasicBlock | undefined, type: CodeBlockType): void { + if (type === CodeBlockType.BREAK) { + this.pushStmt(new SourceBreakStmt(this, this.lastStmt)); + return; + } else if (type === CodeBlockType.CONTINUE) { + this.pushStmt(new SourceContinueStmt(this, this.lastStmt)); + } else if (type === CodeBlockType.COMPOUND_END) { + this.pushStmt(new SourceCompoundEndStmt(this, this.lastStmt, '}')); + } else if (type === CodeBlockType.ELSE) { + this.pushStmt(new SourceElseStmt(this, this.lastStmt)); + } else if (type === CodeBlockType.DO) { + this.pushStmt(new SourceDoStmt(this, this.lastStmt)); + } else if (type === CodeBlockType.TRY) { + this.pushStmt(new SourceTryStmt(this, this.lastStmt)); + } else if (type === CodeBlockType.CATCH) { + this.pushStmt(new SourceCatchStmt(this, this.lastStmt, block)); + // catch need read block first stmt, using return to void walk block twice. + return; + } else if (type === CodeBlockType.FINALLY) { + this.pushStmt(new SourceFinallyStmt(this, this.lastStmt)); + } + + if (!block) { + return; + } + + let originalStmts: Stmt[] = this.sortStmt(block.getStmts()); + this.stmtReader = new StmtReader(originalStmts); + while (this.stmtReader.hasNext()) { + let stmt = this.stmtReader.next(); + if (this.skipStmts.has(stmt)) { + continue; + } + if (stmt instanceof ArkIfStmt) { + if (type === CodeBlockType.IF) { + this.pushStmt(new SourceIfStmt(this, stmt)); + } else if (type === CodeBlockType.WHILE) { + this.pushStmt(new SourceWhileStmt(this, stmt, block)); + } else if (type === CodeBlockType.FOR) { + let inc = this.cfgUtils.getForIncBlock(block)!; + this.pushStmt(new SourceForStmt(this, stmt, block, inc)); + } else if (type === CodeBlockType.DO_WHILE) { + this.pushStmt(new SourceDoWhileStmt(this, stmt, block)); + } + } else { + this.pushStmt(stmt2SourceStmt(this, stmt)); + } + this.lastStmt = stmt; + } + } + + private printStmts(): void { + for (let stmt of this.stmts) { + if (this.skipStmts.has(stmt.original)) { + continue; + } + this.printer.write(stmt.dump()); + } + } + + public getStmts(): SourceStmt[] { + return this.stmts.filter((value) => { + if (!this.skipStmts.has(value.original)) { + return value; + } + }); + } + + public pushStmt(stmt: SourceStmt): void { + let lastLine = this.getLastLine(); + if (stmt.getLine() < lastLine) { + stmt.setLine(lastLine + 0.1); + } + stmt.transfer2ts(); + this.stmts.push(stmt); + } + + private getLastLine(): number { + if (this.stmts.length > 0) { + return this.stmts[this.stmts.length - 1].getLine(); + } + + return 0; + } + + /* + * temp9 = new <>.<>(); temp10 = new Array(3); + * temp10 = new Array(3); temp10[0] = 'Cat'; + * temp10[0] = 'Cat'; ==> temp10[1] = 'Dog'; + * temp10[1] = 'Dog'; temp10[2] = 'Hamster'; + * temp10[2] = 'Hamster'; temp9 = new <>.<>(); + * temp9.constructor(temp10); temp9.constructor(temp10); + */ + private sortStmt(stmts: Stmt[]): Stmt[] { + for (let i = stmts.length - 1; i > 0; i--) { + if (stmts[i] instanceof ArkInvokeStmt && (stmts[i].getInvokeExpr() as ArkInstanceInvokeExpr)) { + let instanceInvokeExpr = stmts[i].getInvokeExpr() as ArkInstanceInvokeExpr; + if ('constructor' !== instanceInvokeExpr.getMethodSignature().getMethodSubSignature().getMethodName()) { + continue; + } + let localName = instanceInvokeExpr.getBase().getName(); + let newExprIdx = findNewExpr(i, localName); + if (newExprIdx >= 0 && newExprIdx < i - 1) { + moveStmt(i, newExprIdx); + } + } + } + return stmts; + + function findNewExpr(constructorIdx: number, name: string): number { + for (let j = constructorIdx - 1; j >= 0; j--) { + if (!(stmts[j] instanceof ArkAssignStmt)) { + continue; + } + const leftOp = (stmts[j] as ArkAssignStmt).getLeftOp(); + if (leftOp instanceof Local && leftOp.getName() === name) { + return j; + } + } + return -1; + } + + function moveStmt(constructorIdx: number, newExprIdx: number): void { + let back = stmts[newExprIdx]; + for (let i = newExprIdx; i < constructorIdx - 1; i++) { + stmts[i] = stmts[i + 1]; + } + stmts[constructorIdx - 1] = back; + } + } +} + +export class StmtReader { + private stmts: Stmt[] = []; + private pos: number; + + constructor(stmts: Stmt[]) { + this.stmts = stmts; + this.pos = 0; + } + + first(): Stmt { + return this.stmts[0]; + } + + hasNext(): boolean { + return this.pos < this.stmts.length; + } + + next(): Stmt { + if (!this.hasNext()) { + logger.error('SourceBody: StmtReader->next No more stmt.'); + throw new Error('No more stmt.'); + } + let stmt = this.stmts[this.pos]; + this.pos++; + return stmt; + } + + rollback(): void { + if (this.pos === 0) { + logger.error('SourceBody: StmtReader->rollback No more stmt to rollback.'); + throw new Error('No more stmt to rollback.'); + } + this.pos--; + } +} diff --git a/ets2panda/linter/arkanalyzer/src/save/source/SourceClass.ts b/ets2panda/linter/arkanalyzer/src/save/source/SourceClass.ts new file mode 100644 index 0000000000..26de605704 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/save/source/SourceClass.ts @@ -0,0 +1,214 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkClass, ClassCategory } from '../../core/model/ArkClass'; +import { SourceBase } from './SourceBase'; +import { SourceBody } from './SourceBody'; +import { SourceField } from './SourceField'; +import { SourceMethod } from './SourceMethod'; +import { SourceTransformer } from './SourceTransformer'; +import { PrinterUtils } from '../base/PrinterUtils'; +import { INSTANCE_INIT_METHOD_NAME, STATIC_INIT_METHOD_NAME } from '../../core/common/Const'; +import { ArkNamespace } from '../../core/model/ArkNamespace'; +import { FieldCategory } from '../../core/model/ArkField'; +import { ArkMetadataKind, CommentsMetadata } from '../../core/model/ArkMetadata'; +import { Dump } from '../base/BasePrinter'; + +/** + * @category save + */ +export class SourceClass extends SourceBase { + protected cls: ArkClass; + private transformer: SourceTransformer; + + public constructor(cls: ArkClass, indent: string = '') { + super(cls.getDeclaringArkFile(), indent); + this.cls = cls; + this.transformer = new SourceTransformer(this); + } + + public getDeclaringArkNamespace(): ArkNamespace | undefined { + return this.cls.getDeclaringArkNamespace(); + } + + public getLine(): number { + return this.cls.getLine(); + } + + public dump(): string { + this.printer.clear(); + + if (this.cls.getCategory() === ClassCategory.OBJECT) { + return this.dumpObject(); + } + + if (this.cls.getCategory() === ClassCategory.TYPE_LITERAL) { + return this.dumpTypeLiteral(); + } + + const commentsMetadata = this.cls.getMetadata(ArkMetadataKind.LEADING_COMMENTS); + if (commentsMetadata instanceof CommentsMetadata) { + const comments = commentsMetadata.getComments(); + comments.forEach((comment) => { + this.printer.writeIndent().writeLine(comment.content); + }); + } + + this.printDecorator(this.cls.getDecorators()); + // print export class name<> + extends c0 implements x1, x2 { + this.printer + .writeIndent() + .writeSpace(this.modifiersToString(this.cls.getModifiers())) + .write(`${this.classOriginTypeToString(this.cls.getCategory())} `); + + if (!PrinterUtils.isAnonymousClass(this.cls.getName())) { + this.printer.write(this.cls.getName()); + } + const genericsTypes = this.cls.getGenericsTypes(); + if (genericsTypes) { + this.printer.write(`<${this.transformer.typeArrayToString(genericsTypes)}>`); + } + if (this.cls.getSuperClassName() && !this.cls.hasComponentDecorator()) { + this.printer.write(` extends ${this.cls.getSuperClassName()}`); + } + if (this.cls.getImplementedInterfaceNames().length > 0) { + this.printer.write(` implements ${this.cls.getImplementedInterfaceNames().join(', ')}`); + } + + this.printer.writeLine(' {'); + this.printer.incIndent(); + let items: Dump[] = []; + + items.push(...this.printFields()); + items.push(...this.printMethods()); + + items.sort((a, b) => a.getLine() - b.getLine()); + items.forEach((v): void => { + this.printer.write(v.dump()); + }); + + this.printer.decIndent(); + this.printer.writeIndent().write('}'); + if (!PrinterUtils.isAnonymousClass(this.cls.getName())) { + this.printer.writeLine(''); + } + return this.printer.toString(); + } + + private dumpObject(): string { + this.printer.write('{'); + + this.cls.getFields().forEach((field, index, array) => { + let name = PrinterUtils.escape(field.getName()); + if (PrinterUtils.isIdentifierText(field.getName())) { + this.printer.write(name); + } else { + this.printer.write(`'${name}'`); + } + + let instanceInitializer = this.parseFieldInitMethod(INSTANCE_INIT_METHOD_NAME); + if (instanceInitializer.has(field.getName())) { + this.printer.write(`: ${instanceInitializer.get(field.getName())}`); + } + + if (index !== array.length - 1) { + this.printer.write(`, `); + } + }); + this.printer.write('}'); + return this.printer.toString(); + } + + private dumpTypeLiteral(): string { + this.printer.write('{'); + + this.cls.getFields().forEach((field, index, array) => { + let name = PrinterUtils.escape(field.getName()); + if (PrinterUtils.isIdentifierText(field.getName())) { + this.printer.write(`${name}: ${this.transformer.typeToString(field.getType())}`); + } else { + this.printer.write(`'${name}': ${this.transformer.typeToString(field.getType())}`); + } + + if (index !== array.length - 1) { + this.printer.write(`, `); + } + }); + this.printer.write('}'); + return this.printer.toString(); + } + + protected printMethods(): Dump[] { + let items: Dump[] = []; + for (let method of this.cls.getMethods()) { + if ( + method.isGenerated() || + (PrinterUtils.isConstructorMethod(method.getName()) && this.cls.hasViewTree()) + ) { + continue; + } + + if (method.isDefaultArkMethod()) { + items.push(...new SourceMethod(method, this.printer.getIndent()).dumpDefaultMethod()); + } else if (!PrinterUtils.isAnonymousMethod(method.getName())) { + items.push(new SourceMethod(method, this.printer.getIndent())); + } + } + return items; + } + + private printFields(): Dump[] { + let instanceInitializer = this.parseFieldInitMethod(INSTANCE_INIT_METHOD_NAME); + let staticInitializer = this.parseFieldInitMethod(STATIC_INIT_METHOD_NAME); + let items: Dump[] = []; + for (let field of this.cls.getFields()) { + if (field.getCategory() === FieldCategory.GET_ACCESSOR) { + continue; + } + if (field.isStatic()) { + items.push(new SourceField(field, this.printer.getIndent(), staticInitializer)); + } else { + items.push(new SourceField(field, this.printer.getIndent(), instanceInitializer)); + } + } + return items; + } + + private parseFieldInitMethod(name: string): Map { + let method = this.cls.getMethodWithName(name); + if (!method || method?.getBody() === undefined) { + return new Map(); + } + + let srcBody = new SourceBody(this.printer.getIndent(), method, false); + srcBody.dump(); + return srcBody.getTempCodeMap(); + } +} + +export class SourceDefaultClass extends SourceClass { + public constructor(cls: ArkClass, indent: string = '') { + super(cls, indent); + } + + public getLine(): number { + return this.cls.getLine(); + } + + public dump(): string { + this.printMethods(); + return this.printer.toString(); + } +} diff --git a/ets2panda/linter/arkanalyzer/src/save/source/SourceField.ts b/ets2panda/linter/arkanalyzer/src/save/source/SourceField.ts new file mode 100644 index 0000000000..50fb363319 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/save/source/SourceField.ts @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkField, FieldCategory } from '../../core/model/ArkField'; +import { SourceBase } from './SourceBase'; +import { SourceTransformer } from './SourceTransformer'; +import { UnknownType } from '../../core/base/Type'; +import { ArkMetadataKind, CommentsMetadata } from '../../core/model/ArkMetadata'; + +/** + * @category save + */ +export class SourceField extends SourceBase { + private field: ArkField; + private transformer: SourceTransformer; + private initializer: Map; + + public constructor(field: ArkField, indent: string = '', initializer: Map) { + super(field.getDeclaringArkClass().getDeclaringArkFile(), indent); + this.field = field; + this.transformer = new SourceTransformer(this); + this.initializer = initializer; + } + + public getLine(): number { + return this.field.getOriginPosition().getLineNo(); + } + public dump(): string { + this.printer.clear(); + const commentsMetadata = this.field.getMetadata(ArkMetadataKind.LEADING_COMMENTS); + if (commentsMetadata instanceof CommentsMetadata) { + const comments = commentsMetadata.getComments(); + comments.forEach((comment) => { + this.printer.writeIndent().writeLine(comment.content); + }); + } + this.printDecorator(this.field.getDecorators()); + this.printer.writeIndent(); + if (this.field.getCategory() !== FieldCategory.ENUM_MEMBER) { + this.printer.writeSpace(this.modifiersToString(this.field.getModifiers())); + } + + this.printer.write(this.field.getName()); + + if (this.field.getQuestionToken()) { + this.printer.write('?'); + } + if (this.field.getExclamationToken()) { + this.printer.write('!'); + } + + // property.getInitializer() PropertyAccessExpression ArrowFunction ClassExpression FirstLiteralToken StringLiteral + if (!(this.field.getType() instanceof UnknownType) && this.field.getCategory() !== FieldCategory.ENUM_MEMBER) { + this.printer.write(`: ${this.transformer.typeToString(this.field.getType())}`); + } + + if (this.initializer.has(this.field.getName())) { + this.printer.write(` = ${this.initializer.get(this.field.getName())}`); + } + + if (this.field.getCategory() === FieldCategory.ENUM_MEMBER) { + this.printer.writeLine(','); + } else { + this.printer.writeLine(';'); + } + return this.printer.toString(); + } +} diff --git a/ets2panda/linter/arkanalyzer/src/save/source/SourceFilePrinter.ts b/ets2panda/linter/arkanalyzer/src/save/source/SourceFilePrinter.ts new file mode 100644 index 0000000000..9e7b9c467f --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/save/source/SourceFilePrinter.ts @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * TODO: + * + * 1. Method parameter: + * a) default value 不支持 + * source: move(distanceInMeters = 5) + * parsed: move(distanceInMeters) + * c) string[] 类型解析为 ArrayType,无法还原 + * d) 构造函数Access Modifiers 不支持 + * constructor(public make: string, public model: string) { + * } + * + * 2. 泛型 + * a) field泛型<>类型丢失 + * class GenericNumber { + * private methods: Set; + * private calls: Map; + * } + */ +import { ArkFile } from '../../core/model/ArkFile'; +import { Dump } from '../base/BasePrinter'; +import { SourceClass } from './SourceClass'; +import { SourceMethod } from './SourceMethod'; +import { SourceNamespace } from './SourceNamespace'; +import { PrinterUtils } from '../base/PrinterUtils'; +import { printImports } from '../base/ImportPrinter'; +import { ExportPrinter } from '../base/ExportPrinter'; +import { Printer } from '../Printer'; +import { ArkClass } from '../../core/model/ArkClass'; + +/** + * @category save + */ +export class SourceFilePrinter extends Printer { + arkFile: ArkFile; + items: Dump[] = []; + + constructor(arkFile: ArkFile) { + super(); + this.arkFile = arkFile; + } + + private printDefaultClassInFile(cls: ArkClass): void { + for (let method of cls.getMethods()) { + if (method.isDefaultArkMethod()) { + this.items.push(...new SourceMethod(method, this.printer.getIndent()).dumpDefaultMethod()); + } else if ( + !PrinterUtils.isAnonymousMethod(method.getName()) + ) { + this.items.push(new SourceMethod(method)); + } + } + } + + public dump(): string { + this.printer.clear(); + // print imports + this.items.push(...printImports(this.arkFile.getImportInfos(), this.printer.getIndent())); + + // print namespace + for (let ns of this.arkFile.getNamespaces()) { + this.items.push(new SourceNamespace(ns)); + } + + // print class + for (let cls of this.arkFile.getClasses()) { + if (cls.isDefaultArkClass()) { + this.printDefaultClassInFile(cls); + } else if (!PrinterUtils.isAnonymousClass(cls.getName())) { + this.items.push(new SourceClass(cls)); + } + } + // print export + for (let info of this.arkFile.getExportInfos()) { + this.items.push(new ExportPrinter(info)); + } + + this.items.sort((a, b) => a.getLine() - b.getLine()); + this.items.forEach((v): void => { + this.printer.write(v.dump()); + }); + + return this.printer.toString(); + } +} diff --git a/ets2panda/linter/arkanalyzer/src/save/source/SourceMethod.ts b/ets2panda/linter/arkanalyzer/src/save/source/SourceMethod.ts new file mode 100644 index 0000000000..2d0d70abd0 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/save/source/SourceMethod.ts @@ -0,0 +1,227 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { UnknownType } from '../../core/base/Type'; +import { ArkMethod } from '../../core/model/ArkMethod'; +import { ArkCodeBuffer } from '../ArkStream'; +import { SourceBase } from './SourceBase'; +import { SourceBody } from './SourceBody'; +import { SourceStmt } from './SourceStmt'; +import { SourceTransformer } from './SourceTransformer'; +import { PrinterUtils } from '../base/PrinterUtils'; +import { Stmt } from '../../core/base/Stmt'; +import { ArkNamespace } from '../../core/model/ArkNamespace'; +import { ArkMetadataKind, CommentsMetadata } from '../../core/model/ArkMetadata'; +import { getLineNo } from '../../core/base/Position'; +import { MethodSignature } from '../../core/model/ArkSignature'; +import { LEXICAL_ENV_NAME_PREFIX } from '../../core/common/Const'; + +/** + * @category save + */ +export class SourceMethod extends SourceBase { + private method: ArkMethod; + private transformer: SourceTransformer; + + public constructor(method: ArkMethod, indent: string = '') { + super(method.getDeclaringArkFile(), indent); + this.method = method; + this.transformer = new SourceTransformer(this); + this.inBuilder = this.initInBuilder(); + } + + public getDeclaringArkNamespace(): ArkNamespace | undefined { + return this.method.getDeclaringArkClass().getDeclaringArkNamespace(); + } + + public setInBuilder(inBuilder: boolean): void { + this.inBuilder = inBuilder; + } + + public dump(): string { + this.printer.clear(); + const commentsMetadata = this.method.getMetadata(ArkMetadataKind.LEADING_COMMENTS); + if (commentsMetadata instanceof CommentsMetadata) { + const comments = commentsMetadata.getComments(); + comments.forEach((comment) => { + this.printer.writeIndent().writeLine(comment.content); + }); + } + if (!this.method.isDefaultArkMethod()) { + this.printMethod(this.method); + } else { + this.printBody(this.method); + } + return this.printer.toString(); + } + + public getLine(): number { + let line = this.method.getLine(); + if (line === null && this.method.getDeclareLineCols()) { + line = getLineNo(this.method.getDeclareLineCols()![0]); + } + if (line === null) { + line = 0; + } + if (line > 0) { + return line; + } + + const stmts: Stmt[] = []; + const cfg = this.method.getCfg(); + if (cfg) { + cfg.getStmts() + .reverse() + .forEach((stmt) => stmts.push(stmt)); + } + for (const stmt of stmts) { + if (stmt.getOriginPositionInfo().getLineNo() > 0) { + return stmt.getOriginPositionInfo().getLineNo(); + } + } + + return line; + } + + public dumpDefaultMethod(): SourceStmt[] { + let srcBody = new SourceBody(this.printer.getIndent(), this.method, false); + return srcBody.getStmts(); + } + + private printMethod(method: ArkMethod): void { + this.printDecorator(method.getDecorators()); + + let implementationSig = method.getImplementationSignature(); + + if (this.method.getDeclareSignatures()) { + for (const methodSig of this.method.getDeclareSignatures()!) { + this.printer.writeIndent().writeLine(`${this.methodProtoToString(methodSig)};`); + } + } + + if (!implementationSig) { + return; + } + + this.printer.writeIndent().write(this.methodProtoToString(implementationSig!)); + + // abstract function no body + if (SourceMethod.getPrinterOptions().noMethodBody) { + this.printer.writeIndent().writeLine(`;`); + return; + } + + this.printer.writeLine(' {'); + this.printer.incIndent(); + this.printBody(method); + this.printer.decIndent(); + + this.printer.writeIndent(); + if (PrinterUtils.isAnonymousMethod(method.getName())) { + this.printer.write('}'); + } else { + this.printer.writeLine('}'); + } + } + + private printBody(method: ArkMethod): void { + let srcBody = new SourceBody(this.printer.getIndent(), method, this.inBuilder); + this.printer.write(srcBody.dump()); + } + + private methodProtoToString(methodSig: MethodSignature): string { + let code = new ArkCodeBuffer(); + code.writeSpace(this.modifiersToString(this.method.getModifiers())); + if (!PrinterUtils.isAnonymousMethod(methodSig.getMethodSubSignature().getMethodName())) { + if (this.method.getDeclaringArkClass()?.isDefaultArkClass()) { + code.writeSpace('function'); + } + if (this.method.getAsteriskToken()) { + code.writeSpace('*'); + } + code.write(this.resolveMethodName(methodSig.getMethodSubSignature().getMethodName())); + } + + const genericTypes = this.method.getGenericTypes(); + if (genericTypes && genericTypes.length > 0) { + code.write(`<${this.transformer.typeArrayToString(genericTypes)}>`); + } + + let parameters: string[] = []; + methodSig + .getMethodSubSignature() + .getParameters() + .forEach((parameter) => { + let str: string = parameter.getName(); + if (parameter.hasDotDotDotToken()) { + str = `...${parameter.getName()}`; + } + if (parameter.isOptional()) { + str += '?'; + } + if (parameter.getType()) { + str += ': ' + this.transformer.typeToString(parameter.getType()); + } + if (!str.startsWith(LEXICAL_ENV_NAME_PREFIX)) + { + parameters.push(str); + } + }); + code.write(`(${parameters.join(', ')})`); + const returnType = methodSig.getMethodSubSignature().getReturnType(); + if ( + methodSig.getMethodSubSignature().getMethodName() !== 'constructor' && + !(returnType instanceof UnknownType) + ) { + code.write(`: ${this.transformer.typeToString(returnType)}`); + } + if (PrinterUtils.isAnonymousMethod(methodSig.getMethodSubSignature().getMethodName())) { + code.write(' =>'); + } + return code.toString(); + } + + public toArrowFunctionTypeString(): string { + let code = new ArkCodeBuffer(); + + let parameters: string[] = []; + this.method.getParameters().forEach((parameter) => { + let str: string = parameter.getName(); + if (parameter.isOptional()) { + str += '?'; + } + if (parameter.getType()) { + str += ': ' + this.transformer.typeToString(parameter.getType()); + } + parameters.push(str); + }); + code.write(`(${parameters.join(', ')}) => `); + const returnType = this.method.getReturnType(); + if (!(returnType instanceof UnknownType)) { + code.writeSpace(`${this.transformer.typeToString(returnType)}`); + } + + return code.toString(); + } + + private initInBuilder(): boolean { + return ( + this.method.hasBuilderDecorator() || + ((this.method.getName() === 'build' || this.method.getName() === 'pageTransition') && + !this.method.isStatic() && + this.method.getDeclaringArkClass().hasViewTree()) + ); + } +} diff --git a/ets2panda/linter/arkanalyzer/src/save/source/SourceNamespace.ts b/ets2panda/linter/arkanalyzer/src/save/source/SourceNamespace.ts new file mode 100644 index 0000000000..d1e608120a --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/save/source/SourceNamespace.ts @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkMetadataKind, CommentsMetadata } from '../../core/model/ArkMetadata'; +import { ArkNamespace } from '../../core/model/ArkNamespace'; +import { SourceBase } from './SourceBase'; +import { SourceClass } from './SourceClass'; +import { SourceMethod } from './SourceMethod'; +import { PrinterUtils } from '../base/PrinterUtils'; +import { Dump } from '../base/BasePrinter'; +import { ExportPrinter } from '../base/ExportPrinter'; +import { ArkClass } from '../../core/model/ArkClass'; + +/** + * @category save + */ +export class SourceNamespace extends SourceBase { + ns: ArkNamespace; + + public constructor(ns: ArkNamespace, indent: string = '') { + super(ns.getDeclaringArkFile(), indent); + this.ns = ns; + } + + public getLine(): number { + return this.ns.getLine(); + } + + private printDefaultClassInNamespace(items: Dump[], cls: ArkClass): void { + for (let method of cls.getMethods()) { + if (method.isDefaultArkMethod()) { + items.push(...new SourceMethod(method, this.printer.getIndent()).dumpDefaultMethod()); + } else if (!PrinterUtils.isAnonymousMethod(method.getName())) { + items.push(new SourceMethod(method, this.printer.getIndent())); + } + } + } + + public dump(): string { + const commentsMetadata = this.ns.getMetadata(ArkMetadataKind.LEADING_COMMENTS); + if (commentsMetadata instanceof CommentsMetadata) { + const comments = commentsMetadata.getComments(); + comments.forEach((comment) => { + this.printer.writeIndent().writeLine(comment.content); + }); + } + this.printer.writeIndent().writeSpace(this.modifiersToString(this.ns.getModifiers())) + .writeLine(`namespace ${this.ns.getName()} {`); + this.printer.incIndent(); + + let items: Dump[] = []; + // print class + for (let cls of this.ns.getClasses()) { + if (PrinterUtils.isAnonymousClass(cls.getName())) { + continue; + } + if (cls.isDefaultArkClass()) { + this.printDefaultClassInNamespace(items, cls); + } else { + items.push(new SourceClass(cls, this.printer.getIndent())); + } + } + // print namespace + for (let childNs of this.ns.getNamespaces()) { + items.push(new SourceNamespace(childNs, this.printer.getIndent())); + } + // print exportInfos + for (let exportInfo of this.ns.getExportInfos()) { + items.push( + new ExportPrinter(exportInfo, this.printer.getIndent()) + ); + } + + items.sort((a, b) => a.getLine() - b.getLine()); + items.forEach((v): void => { + this.printer.write(v.dump()); + }); + this.printer.decIndent(); + this.printer.writeIndent().writeLine('}'); + return this.printer.toString(); + } +} diff --git a/ets2panda/linter/arkanalyzer/src/save/source/SourceStmt.ts b/ets2panda/linter/arkanalyzer/src/save/source/SourceStmt.ts new file mode 100644 index 0000000000..3007cd765e --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/save/source/SourceStmt.ts @@ -0,0 +1,974 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Constant } from '../../core/base/Constant'; +import { + ArkInstanceInvokeExpr, + ArkNewArrayExpr, + ArkNewExpr, + ArkStaticInvokeExpr, + NormalBinaryOperator, +} from '../../core/base/Expr'; +import { Local } from '../../core/base/Local'; +import { ArkArrayRef, ArkInstanceFieldRef, ArkParameterRef, ArkStaticFieldRef, ClosureFieldRef } from '../../core/base/Ref'; +import { + ArkAliasTypeDefineStmt, + ArkAssignStmt, + ArkIfStmt, + ArkInvokeStmt, + ArkReturnStmt, + ArkReturnVoidStmt, + ArkThrowStmt, + Stmt, +} from '../../core/base/Stmt'; +import { AliasType, ClassType, Type } from '../../core/base/Type'; +import { Value } from '../../core/base/Value'; +import { BasicBlock } from '../../core/graph/BasicBlock'; +import Logger, { LOG_MODULE_TYPE } from '../../utils/logger'; +import { ArkCodeBuffer } from '../ArkStream'; +import { StmtReader } from './SourceBody'; +import { SourceTransformer, TransformerContext } from './SourceTransformer'; +import { CLASS_CATEGORY_COMPONENT, PrinterUtils } from '../base/PrinterUtils'; +import { ValueUtil } from '../../core/common/ValueUtil'; +import { ArkClass, ClassCategory } from '../../core/model/ArkClass'; +import { modifiers2stringArray } from '../../core/model/ArkBaseModel'; +import { ArkMetadataKind, CommentsMetadata } from '../../core/model/ArkMetadata'; +import { ImportInfo } from '../../core/model/ArkImport'; +import { ArkMethod } from '../../core/model/ArkMethod'; +import { Dump } from '../base/BasePrinter'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'SourceStmt'); +const IGNOR_TYPES = new Set(['any', 'Map', 'Set']); + +export interface StmtPrinterContext extends TransformerContext { + getStmtReader(): StmtReader; + + setTempCode(temp: string, code: string): void; + + hasTempVisit(temp: string): boolean; + + setTempVisit(temp: string): void; + + setSkipStmt(stmt: Stmt): void; + + getLocals(): Map; + + defineLocal(local: Local): void; + + isLocalDefined(local: Local): boolean; + + isInDefaultMethod(): boolean; +} + +export abstract class SourceStmt implements Dump { + original: Stmt; + context: StmtPrinterContext; + line: number; + text: string = ''; + transformer: SourceTransformer; + + constructor(context: StmtPrinterContext, original: Stmt) { + this.original = original; + this.context = context; + this.line = original.getOriginPositionInfo().getLineNo(); + this.transformer = new SourceTransformer(context); + } + + public getLine(): number { + return this.line; + } + + public setLine(line: number) { + this.line = line; + } + + public dump(): string { + this.beforeDump(); + let code = this.dumpTs(); + this.afterDump(); + return code; + } + + protected beforeDump(): void {} + + protected afterDump(): void {} + + protected dumpTs(): string { + let content: string[] = []; + const commentsMetadata = this.original.getMetadata(ArkMetadataKind.LEADING_COMMENTS); + if (commentsMetadata instanceof CommentsMetadata) { + const comments = commentsMetadata.getComments(); + comments.forEach((comment) => { + content.push(`${this.printer.getIndent()}${comment.content}\n`); + }); + } + if (this.text.length > 0) { + content.push(`${this.printer.getIndent()}${this.text}\n`); + } + return content.join(''); + } + + protected get printer(): ArkCodeBuffer { + return this.context.getPrinter(); + } + + public toString(): string { + return this.text; + } + + protected setText(text: string): void { + this.text = text; + } + + protected getIntent(): string { + return this.context.getPrinter().getIndent(); + } + + public abstract transfer2ts(): void; + + protected isLocalTempValue(value: Value): boolean { + if (!(value instanceof Local)) { + return false; + } + + return PrinterUtils.isTemp(value.getName()); + } +} + +enum AssignStmtDumpType { + NORMAL, + TEMP_REPLACE, + COMPONENT_CREATE, +} + +export class SourceAssignStmt extends SourceStmt { + private leftOp: Value = ValueUtil.getUndefinedConst(); + private rightOp: Value = ValueUtil.getUndefinedConst(); + private leftCode: string = ''; + private rightCode: string = ''; + private dumpType?: AssignStmtDumpType; + private leftTypeCode: string; + + constructor(context: StmtPrinterContext, original: ArkAssignStmt) { + super(context, original); + this.leftTypeCode = ''; + } + + public transfer2ts(): void { + this.leftOp = (this.original as ArkAssignStmt).getLeftOp(); + this.rightOp = (this.original as ArkAssignStmt).getRightOp(); + + if ( + (this.leftOp instanceof Local && this.leftOp.getName() === 'this') || + (this.rightOp instanceof Constant && this.rightOp.getValue() === 'undefined') || + this.rightOp instanceof ArkParameterRef || this.rightOp instanceof ClosureFieldRef + ) { + this.setText(''); + this.dumpType = AssignStmtDumpType.NORMAL; + return; + } + + this.leftCode = this.transformer.valueToString(this.leftOp); + + if (this.leftOp instanceof Local && this.rightOp instanceof ArkNewExpr) { + this.transferRightNewExpr(); + } else if (this.leftOp instanceof Local && this.rightOp instanceof ArkNewArrayExpr) { + this.transferRightNewArrayExpr(); + } else if (this.rightOp instanceof ArkStaticInvokeExpr && PrinterUtils.isComponentCreate(this.rightOp)) { + this.transferRightComponentCreate(); + } else if ( + this.rightOp instanceof ArkInstanceInvokeExpr && + PrinterUtils.isComponentAttributeInvoke(this.rightOp) + ) { + this.transferRightComponentAttribute(); + } else { + this.rightCode = this.transformer.valueToString(this.rightOp); + } + + if (this.isLocalTempValue(this.leftOp)) { + this.context.setTempCode((this.leftOp as Local).getName(), this.rightCode); + } + + if ( + (this.leftOp instanceof ArkInstanceFieldRef && this.leftOp.getBase().getName() === 'this') || + this.leftOp instanceof ArkStaticFieldRef + ) { + this.context.setTempCode(this.leftOp.getFieldName(), this.rightCode); + } + + if (this.dumpType === undefined) { + this.setText(`${this.leftCode} = ${this.rightCode}`); + this.dumpType = AssignStmtDumpType.TEMP_REPLACE; + } + + let leftOpType = this.leftOp.getType(); + if (leftOpType instanceof ClassType) { + let name = leftOpType.getClassSignature().getClassName(); + if (PrinterUtils.isAnonymousClass(name)) { + this.leftTypeCode = 'any'; + } else { + this.leftTypeCode = name; + } + } else { + this.leftTypeCode = this.transformer.typeToString(leftOpType); + } + if (IGNOR_TYPES.has(this.leftTypeCode)) { + this.leftTypeCode = ''; + } + } + + protected beforeDump(): void { + if (this.dumpType !== AssignStmtDumpType.TEMP_REPLACE) { + return; + } + + if (this.context.hasTempVisit(this.leftCode)) { + this.setText(''); + return; + } else if (PrinterUtils.isTemp(this.leftCode)) { + this.setText(`${this.rightCode};`); + return; + } + if ( + this.leftOp instanceof Local && + this.context.getLocals().has(this.leftOp.getName()) && + !this.isLocalTempValue(this.leftOp) + ) { + if (this.context.isLocalDefined(this.leftOp)) { + this.setText(`${this.leftCode} = ${this.rightCode};`); + return; + } + let flag = this.leftOp.getConstFlag() ? 'const' : 'let'; + if (this.context.getArkFile().getExportInfoBy(this.leftCode) && this.context.isInDefaultMethod()) { + this.setText(`export ${flag} ${this.leftCode} = ${this.rightCode};`); + } else { + if (this.leftTypeCode.length > 0) { + this.setText(`${flag} ${this.leftCode}: ${this.leftTypeCode} = ${this.rightCode};`); + } else { + this.setText(`${flag} ${this.leftCode} = ${this.rightCode};`); + } + } + this.context.defineLocal(this.leftOp); + } else { + this.setText(`${this.leftCode} = ${this.rightCode};`); + } + } + + protected afterDump(): void { + if (this.dumpType === AssignStmtDumpType.COMPONENT_CREATE) { + this.printer.incIndent(); + } + } + + private getClassOriginType(type: Type): number | undefined { + if (!(type instanceof ClassType)) { + return undefined; + } + + let signature = type.getClassSignature(); + let cls = this.context.getClass(signature); + if (!cls) { + return undefined; + } + return PrinterUtils.getOriginType(cls); + } + + /** + * temp1 = new Person + * temp1.constructor(10) + */ + private transferRightNewExpr(): void { + let originType = this.getClassOriginType(this.rightOp.getType()); + if (this.context.getStmtReader().hasNext()) { + let stmt = this.context.getStmtReader().next(); + let rollback = true; + if (stmt instanceof ArkInvokeStmt && (stmt.getInvokeExpr() as ArkInstanceInvokeExpr)) { + let instanceInvokeExpr = stmt.getInvokeExpr() as ArkInstanceInvokeExpr; + if ( + 'constructor' === instanceInvokeExpr.getMethodSignature().getMethodSubSignature().getMethodName() && + instanceInvokeExpr.getBase().getName() === (this.leftOp as Local).getName() + ) { + this.handleConstructorInvoke(instanceInvokeExpr, originType); + return; + } + } + if (rollback) { + this.context.getStmtReader().rollback(); + } + } + + if (originType === CLASS_CATEGORY_COMPONENT) { + this.rightCode = `${this.transformer.typeToString(this.rightOp.getType())}()`; + } else if (originType === ClassCategory.TYPE_LITERAL || originType === ClassCategory.OBJECT) { + this.rightCode = `${this.transformer.typeToString(this.rightOp.getType())}`; + } else { + this.rightCode = `new ${this.transformer.typeToString(this.rightOp.getType())}()`; + } + } + + private handleConstructorInvoke(instanceInvokeExpr: ArkInstanceInvokeExpr, originType?: number): void { + let args: string[] = []; + instanceInvokeExpr.getArgs().forEach((v) => { + args.push(this.transformer.valueToString(v)); + }); + + if (originType === CLASS_CATEGORY_COMPONENT) { + this.rightCode = `${this.transformer.typeToString(this.rightOp.getType())}(${args.join(', ')})`; + } else if (originType === ClassCategory.TYPE_LITERAL || originType === ClassCategory.OBJECT) { + this.rightCode = `${this.transformer.literalObjectToString( + this.rightOp.getType() as ClassType + )}`; + } else { + this.rightCode = `new ${this.transformer.typeToString(this.rightOp.getType())}(${args.join( + ', ' + )})`; + } + } + + /** + * $temp0 = newarray[4] + * $temp0[0] = 1 + * $temp0[1] = 2 + * $temp0[2] = 3 + */ + private transferRightNewArrayExpr(): void { + let arrayExpr = new SourceNewArrayExpr(this.rightOp as ArkNewArrayExpr); + let localName = (this.leftOp as Local).getName(); + while (this.context.getStmtReader().hasNext()) { + let stmt = this.context.getStmtReader().next(); + if (stmt instanceof ArkAssignStmt) { + let left = stmt.getLeftOp(); + if (left instanceof ArkArrayRef && left.getBase().getName() === localName) { + arrayExpr.addInitValue(this.transformer.valueToString(stmt.getRightOp())); + } else { + this.context.getStmtReader().rollback(); + break; + } + } else { + this.context.getStmtReader().rollback(); + break; + } + } + this.rightCode = arrayExpr.toString(); + } + + private transferRightComponentCreate(): void { + this.rightCode = this.transformer.valueToString(this.rightOp); + if (this.context.getStmtReader().hasNext()) { + let stmt = this.context.getStmtReader().next(); + if (stmt instanceof ArkInvokeStmt) { + let expr = stmt.getInvokeExpr(); + if (expr instanceof ArkStaticInvokeExpr && PrinterUtils.isComponentPop(expr)) { + this.setText(`${this.rightCode}`); + this.dumpType = AssignStmtDumpType.NORMAL; + return; + } + } + + this.context.getStmtReader().rollback(); + } + this.setText(`${this.rightCode} {`); + this.dumpType = AssignStmtDumpType.COMPONENT_CREATE; + } + + private transferRightComponentAttribute(): void { + this.rightCode = this.transformer.valueToString(this.rightOp); + this.setText(`${this.rightCode}`); + this.dumpType = AssignStmtDumpType.NORMAL; + } +} + +export class SourceInvokeStmt extends SourceStmt { + constructor(context: StmtPrinterContext, original: ArkInvokeStmt) { + super(context, original); + } + + public transfer2ts(): void { + let invokeExpr = this.original.getInvokeExpr(); + let code = ''; + let isAttr = false; + if (invokeExpr instanceof ArkStaticInvokeExpr) { + if (PrinterUtils.isComponentPop(invokeExpr)) { + code = '}'; + isAttr = true; + } else { + code = this.transformer.staticInvokeExprToString(invokeExpr); + isAttr = PrinterUtils.isComponentIfElseInvoke(invokeExpr); + } + } else if (invokeExpr instanceof ArkInstanceInvokeExpr) { + code = this.transformer.instanceInvokeExprToString(invokeExpr); + isAttr = PrinterUtils.isComponentAttributeInvoke(invokeExpr); + } + + if (code.length > 0 && !isAttr) { + this.setText(`${code};`); + } else { + this.setText(`${code}`); + } + } + + protected beforeDump(): void { + let invokeExpr = this.original.getInvokeExpr(); + if ( + (invokeExpr instanceof ArkStaticInvokeExpr && PrinterUtils.isComponentPop(invokeExpr)) || + (invokeExpr instanceof ArkStaticInvokeExpr && PrinterUtils.isComponentIfElseInvoke(invokeExpr)) + ) { + this.printer.decIndent(); + return; + } + } + + protected afterDump(): void { + let invokeExpr = this.original.getInvokeExpr(); + if (invokeExpr instanceof ArkStaticInvokeExpr && PrinterUtils.isComponentIfElseInvoke(invokeExpr)) { + this.printer.incIndent(); + return; + } + } +} + +export class SourceIfStmt extends SourceStmt { + constructor(context: StmtPrinterContext, original: ArkIfStmt) { + super(context, original); + } + + public transfer2ts(): void { + let code: string; + let expr = (this.original as ArkIfStmt).getConditionExpr(); + code = `if (${this.transformer.valueToString(expr.getOp1())}`; + code += ` ${expr.getOperator()} `; + code += `${this.transformer.valueToString(expr.getOp2())}) {`; + this.setText(code); + } + + protected afterDump(): void { + this.printer.incIndent(); + } +} + +export class SourceWhileStmt extends SourceStmt { + block: BasicBlock; + + constructor(context: StmtPrinterContext, original: ArkIfStmt, block: BasicBlock) { + super(context, original); + this.block = block; + } + + protected afterDump(): void { + this.printer.incIndent(); + } + + /** + * $temp2 = $temp1.next() + * $temp3 = $temp2.done() + * if $temp3 === true + * $temp4 = $temp2.value + * $temp5 = <> cast + * @returns + */ + private forOf2ts(): boolean { + let expr = (this.original as ArkIfStmt).getConditionExpr(); + let temp3 = expr.getOp1(); + let op2 = expr.getOp2(); + let firstStmt = this.context.getStmtReader().first(); + if (!(firstStmt instanceof ArkAssignStmt)) { + return false; + } + + if (!(this.isLocalTempValue(temp3) && op2 instanceof Constant && (op2 as Constant).getValue() === 'true')) { + return false; + } + + let stmt = (temp3 as Local).getDeclaringStmt(); + if (!(stmt instanceof ArkAssignStmt)) { + return false; + } + + let done = stmt.getRightOp(); + if (!(done instanceof ArkInstanceFieldRef)) { + return false; + } + + if (done.getFieldSignature().toString() !== '@ES2015/BuiltinClass: IteratorResult.done') { + return false; + } + + let temp2 = done.getBase(); + if (!(temp2 instanceof Local)) { + return false; + } + + stmt = temp2.getDeclaringStmt(); + if (!(stmt instanceof ArkAssignStmt)) { + return false; + } + + let next = stmt.getRightOp(); + if (!(next instanceof ArkInstanceInvokeExpr)) { + return false; + } + + if (next.getMethodSignature().getMethodSubSignature().getMethodName() !== 'next') { + return false; + } + + let temp1 = next.getBase(); + if (!(temp1 instanceof Local)) { + return false; + } + + stmt = temp1.getDeclaringStmt(); + if (!(stmt instanceof ArkAssignStmt)) { + return false; + } + + let iterator = stmt.getRightOp(); + if (!(iterator instanceof ArkInstanceInvokeExpr)) { + return false; + } + + if (iterator.getMethodSignature().getMethodSubSignature().getMethodName() !== 'iterator') { + return false; + } + + let successors = this.block.getSuccessors(); + if (successors.length !== 2) { + return false; + } + + let stmts = successors[0].getStmts(); + if (stmts.length < 2) { + return false; + } + + stmt = stmts[1]; + if (!(stmt instanceof ArkAssignStmt)) { + return false; + } + + this.context.setSkipStmt(stmts[0]); + this.context.setSkipStmt(stmts[1]); + + while (this.context.getStmtReader().hasNext()) { + this.context.getStmtReader().next(); + } + + let v = stmt.getLeftOp() as Local; + let valueName = v.getName(); + if (!this.isLocalTempValue(v)) { + this.setText(`for (let ${valueName} of ${this.transformer.valueToString(iterator.getBase())}) {`); + this.context.setTempVisit((temp1 as Local).getName()); + this.context.setTempVisit((temp3 as Local).getName()); + return true; + } + + // iterate map 'for (let [key, value] of map)' + let stmtReader = new StmtReader(stmts); + stmtReader.next(); + stmtReader.next(); + + let arrayValueNames = []; + while (stmtReader.hasNext()) { + stmt = stmtReader.next(); + if (!(stmt instanceof ArkAssignStmt)) { + break; + } + let ref = stmt.getRightOp(); + if (!(ref instanceof ArkArrayRef)) { + break; + } + if (ref.getBase().getName() !== valueName) { + break; + } + let name = (stmt.getLeftOp() as Local).getName(); + arrayValueNames.push(name); + this.context.setTempVisit(name); + } + + this.setText( + `for (let [${arrayValueNames.join(', ')}] of ${this.transformer.valueToString(iterator.getBase())}) {` + ); + this.context.setTempVisit((temp3 as Local).getName()); + + return true; + } + + public transfer2ts(): void { + if (this.forOf2ts()) { + return; + } + let code: string; + let expr = (this.original as ArkIfStmt).getConditionExpr(); + code = `while (${this.valueToString(expr.getOp1())}`; + code += ` ${expr.getOperator().trim()} `; + code += `${this.valueToString(expr.getOp2())}) {`; + this.setText(code); + } + + protected valueToString(value: Value): string { + if (!(value instanceof Local)) { + return this.transformer.valueToString(value); + } + + for (const stmt of this.block.getStmts()) { + if (!(stmt instanceof ArkAssignStmt)) { + continue; + } + if ( + PrinterUtils.isDeIncrementStmt(stmt, NormalBinaryOperator.Addition) && + (stmt.getLeftOp() as Local).getName() === value.getName() + ) { + this.context.setSkipStmt(stmt); + return `${value.getName()}++`; + } + + if ( + PrinterUtils.isDeIncrementStmt(stmt, NormalBinaryOperator.Subtraction) && + (stmt.getLeftOp() as Local).getName() === value.getName() + ) { + this.context.setSkipStmt(stmt); + return `${value.getName()}--`; + } + } + + return this.transformer.valueToString(value); + } +} + +export class SourceForStmt extends SourceWhileStmt { + incBlock: BasicBlock; + + constructor(context: StmtPrinterContext, original: ArkIfStmt, block: BasicBlock, incBlock: BasicBlock) { + super(context, original, block); + this.incBlock = incBlock; + } + + public transfer2ts(): void { + let code: string; + let expr = (this.original as ArkIfStmt).getConditionExpr(); + code = `for (; ${this.transformer.valueToString(expr.getOp1())}`; + code += ` ${expr.getOperator().trim()} `; + code += `${this.transformer.valueToString(expr.getOp2())}; `; + + let stmtReader = new StmtReader(this.incBlock.getStmts()); + while (stmtReader.hasNext()) { + let sourceStmt = stmt2SourceStmt(this.context, stmtReader.next()); + sourceStmt.transfer2ts(); + code += sourceStmt.toString(); + if (stmtReader.hasNext()) { + code += ', '; + } + } + code += `) {`; + this.setText(code); + } +} + +export class SourceDoStmt extends SourceStmt { + constructor(context: StmtPrinterContext, stmt: Stmt) { + super(context, stmt); + } + + public transfer2ts(): void { + this.setText('do {'); + } + + protected afterDump(): void { + this.printer.incIndent(); + } +} + +export class SourceDoWhileStmt extends SourceWhileStmt { + constructor(context: StmtPrinterContext, stmt: ArkIfStmt, block: BasicBlock) { + super(context, stmt, block); + } + + public transfer2ts(): void { + let code: string; + let expr = (this.original as ArkIfStmt).getConditionExpr(); + code = `} while (${this.valueToString(expr.getOp1())}`; + code += ` ${expr.getOperator().trim()} `; + code += `${this.valueToString(expr.getOp2())})`; + this.setText(code); + } + + protected beforeDump(): void { + this.printer.decIndent(); + } + + protected afterDump(): void {} +} + +export class SourceElseStmt extends SourceStmt { + constructor(context: StmtPrinterContext, original: Stmt) { + super(context, original); + } + + public transfer2ts(): void { + this.setText('} else {'); + } + + protected beforeDump(): void { + this.printer.decIndent(); + } + + protected afterDump(): void { + this.printer.incIndent(); + } +} + +export class SourceContinueStmt extends SourceStmt { + constructor(context: StmtPrinterContext, original: Stmt) { + super(context, original); + } + + // trans 2 break or continue + public transfer2ts(): void { + this.setText('continue;'); + } +} + +export class SourceBreakStmt extends SourceStmt { + constructor(context: StmtPrinterContext, original: Stmt) { + super(context, original); + } + + // trans 2 break or continue + public transfer2ts(): void { + this.setText('break;'); + } +} + +export class SourceReturnStmt extends SourceStmt { + constructor(context: StmtPrinterContext, original: ArkReturnStmt) { + super(context, original); + } + + public transfer2ts(): void { + this.setText(`return ${this.transformer.valueToString((this.original as ArkReturnStmt).getOp())};`); + } +} + +export class SourceReturnVoidStmt extends SourceStmt { + constructor(context: StmtPrinterContext, original: ArkReturnVoidStmt) { + super(context, original); + } + + public transfer2ts(): void { + if (this.original.getOriginPositionInfo().getLineNo() <= 0) { + this.setText(''); + } else { + this.setText('return;'); + } + } +} + +export class SourceCompoundEndStmt extends SourceStmt { + constructor(context: StmtPrinterContext, stmt: Stmt, text: string) { + super(context, stmt); + this.setText(text); + } + + public transfer2ts(): void {} + + protected beforeDump(): void { + this.printer.decIndent(); + } +} + +export class SourceCommonStmt extends SourceStmt { + constructor(context: StmtPrinterContext, stmt: Stmt) { + super(context, stmt); + } + + public transfer2ts(): void { + this.setText(this.original.toString()); + } +} + +export class SourceThrowStmt extends SourceStmt { + constructor(context: StmtPrinterContext, original: ArkThrowStmt) { + super(context, original); + } + + public transfer2ts(): void { + this.setText(`throw ${this.transformer.valueToString((this.original as ArkThrowStmt).getOp())};`); + } +} + +export class SourceTypeAliasStmt extends SourceStmt { + aliasType: AliasType; + constructor(context: StmtPrinterContext, original: Stmt, aliasType: AliasType) { + super(context, original); + this.aliasType = aliasType; + } + + public transfer2ts(): void { + let modifiersArray: string[] = modifiers2stringArray(this.aliasType.getModifiers()); + let modifier = modifiersArray.length > 0 ? `${modifiersArray.join(' ')} ` : ''; + + const expr = (this.original as ArkAliasTypeDefineStmt).getAliasTypeExpr(); + let typeOf = expr.getTransferWithTypeOf() ? 'typeof ' : ''; + let realGenericTypes = expr.getRealGenericTypes() ? `<${expr.getRealGenericTypes()!.join(', ')}>` : ''; + let genericTypes = this.aliasType.getGenericTypes() ? `<${this.transformer.typeArrayToString(this.aliasType.getGenericTypes()!)}>` : ''; + + let typeObject = expr.getOriginalObject(); + if (typeObject instanceof Type) { + if (typeObject instanceof AliasType) { + this.setText(`${modifier}type ${this.aliasType.getName()}${genericTypes} = ${typeOf}${typeObject.getName()}${realGenericTypes};`); + } else { + this.setText(`${modifier}type ${this.aliasType.getName()}${genericTypes} = ${typeOf}${this.transformer.typeToString(typeObject)}${realGenericTypes};`); + } + return; + } + if (typeObject instanceof ImportInfo) { + let exprStr = `import('${typeObject.getFrom()}')`; + if (typeObject.getImportClauseName() !== '') { + exprStr = `${exprStr}.${typeObject.getImportClauseName()}`; + } + this.setText(`${modifier}type ${this.aliasType.getName()}${genericTypes} = ${typeOf}${exprStr}${realGenericTypes};`); + return; + } + if (typeObject instanceof Local) { + this.setText(`${modifier}type ${this.aliasType.getName()}${genericTypes} = ${typeOf}${this.transformer.valueToString(typeObject)}${realGenericTypes};`); + return; + } + if (typeObject instanceof ArkClass) { + let classTS = this.generateClassTS(typeObject); + this.setText(`${modifier}type ${this.aliasType.getName()}${genericTypes} = ${typeOf}${classTS}${realGenericTypes};`); + return; + } + if (typeObject instanceof ArkMethod) { + this.setText(`${modifier}type ${this.aliasType.getName()}${genericTypes} = ${typeOf}${typeObject.getName()}${realGenericTypes};`); + return; + } + this.setText(`${modifier}type ${this.aliasType.getName()}${genericTypes} = ${typeOf}${typeObject.getName()}${realGenericTypes};`); + } + + private generateClassTS(arkClass: ArkClass): string { + let res = ''; + let classType = new ClassType(arkClass.getSignature()); + if (arkClass.getCategory() === ClassCategory.TYPE_LITERAL || arkClass.getCategory() === ClassCategory.OBJECT) { + res = this.transformer.literalObjectToString(classType); + } else { + res = this.transformer.typeToString(classType); + } + return res; + } +} + +export class SourceTryStmt extends SourceStmt { + constructor(context: StmtPrinterContext, stmt: Stmt) { + super(context, stmt); + } + + public transfer2ts(): void { + this.setText('try {'); + } + + protected afterDump(): void { + this.printer.incIndent(); + } +} + +export class SourceCatchStmt extends SourceStmt { + block: BasicBlock | undefined; + constructor(context: StmtPrinterContext, stmt: Stmt, block?: BasicBlock) { + super(context, stmt); + this.block = block; + } + + public transfer2ts(): void { + if (this.block) { + let stmt = this.block!.getStmts()[0]; + if (stmt instanceof ArkAssignStmt) { + if (stmt.getLeftOp() instanceof Local) { + let name = (stmt.getLeftOp() as Local).getName(); + this.setText(`} catch (${name}) {`); + this.context.setSkipStmt(stmt); + return; + } + } + } + this.setText('} catch (e) {'); + } + + protected beforeDump(): void { + this.printer.decIndent(); + } + + protected afterDump(): void { + this.printer.incIndent(); + } +} + +export class SourceFinallyStmt extends SourceStmt { + constructor(context: StmtPrinterContext, stmt: Stmt) { + super(context, stmt); + } + + public transfer2ts(): void { + this.setText('} finally {'); + } + + protected beforeDump(): void { + this.printer.decIndent(); + } + + protected afterDump(): void { + this.printer.incIndent(); + } +} + +export class SourceNewArrayExpr { + expr: ArkNewArrayExpr; + values: string[]; + + constructor(expr: ArkNewArrayExpr) { + this.expr = expr; + this.values = []; + } + + public addInitValue(value: string) { + this.values.push(value); + } + + public toString(): string { + return `[${this.values.join(', ')}]`; + } +} + +export function stmt2SourceStmt(context: StmtPrinterContext, stmt: Stmt): SourceStmt { + if (stmt instanceof ArkAssignStmt) { + return new SourceAssignStmt(context, stmt); + } + if (stmt instanceof ArkInvokeStmt) { + return new SourceInvokeStmt(context, stmt); + } + if (stmt instanceof ArkReturnVoidStmt) { + return new SourceReturnVoidStmt(context, stmt); + } + if (stmt instanceof ArkReturnStmt) { + return new SourceReturnStmt(context, stmt); + } + if (stmt instanceof ArkThrowStmt) { + return new SourceThrowStmt(context, stmt); + } + if (stmt instanceof ArkAliasTypeDefineStmt) { + return new SourceTypeAliasStmt(context, stmt, stmt.getAliasType()); + } + logger.info(`stmt2SourceStmt ${stmt.constructor} not support.`); + return new SourceCommonStmt(context, stmt); +} diff --git a/ets2panda/linter/arkanalyzer/src/save/source/SourceTransformer.ts b/ets2panda/linter/arkanalyzer/src/save/source/SourceTransformer.ts new file mode 100644 index 0000000000..51b9736218 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/save/source/SourceTransformer.ts @@ -0,0 +1,563 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Constant } from '../../core/base/Constant'; +import { + AbstractBinopExpr, + AbstractExpr, + ArkAwaitExpr, + ArkCastExpr, + ArkDeleteExpr, + ArkInstanceInvokeExpr, + ArkInstanceOfExpr, + ArkNewArrayExpr, + ArkNewExpr, + ArkNormalBinopExpr, + ArkStaticInvokeExpr, + ArkTypeOfExpr, + ArkUnopExpr, + ArkYieldExpr, + NormalBinaryOperator, +} from '../../core/base/Expr'; +import { Local } from '../../core/base/Local'; +import { ArkClass, ClassCategory } from '../../core/model/ArkClass'; +import { ArkMethod } from '../../core/model/ArkMethod'; +import { ClassSignature, MethodSignature } from '../../core/model/ArkSignature'; +import { ArkCodeBuffer } from '../ArkStream'; +import Logger, { LOG_MODULE_TYPE } from '../../utils/logger'; +import { PrinterUtils } from '../base/PrinterUtils'; +import { SourceMethod } from './SourceMethod'; +import { + AliasType, + ArrayType, + ClassType, + FunctionType, + GenericType, + IntersectionType, + LiteralType, + PrimitiveType, + StringType, + TupleType, + Type, + UnclearReferenceType, + UnionType, + UnknownType, + VoidType, +} from '../../core/base/Type'; +import { SourceClass } from './SourceClass'; +import { Value } from '../../core/base/Value'; +import { AbstractRef, ArkArrayRef, ArkInstanceFieldRef, ArkStaticFieldRef, ArkThisRef } from '../../core/base/Ref'; +import { ArkFile } from '../../core/model/ArkFile'; +import { + COMPONENT_CREATE_FUNCTION, + COMPONENT_CUSTOMVIEW, + COMPONENT_IF, + COMPONENT_POP_FUNCTION, +} from '../../core/common/EtsConst'; +import { INSTANCE_INIT_METHOD_NAME } from '../../core/common/Const'; +import { ArkAssignStmt } from '../../core/base/Stmt'; +import { ArkNamespace } from '../../core/model/ArkNamespace'; +import { AbstractTypeExpr, KeyofTypeExpr, TypeQueryExpr } from '../../core/base/TypeExpr'; +import { ArkBaseModel } from '../../core/model/ArkBaseModel'; +import { ArkField } from '../../core/model/ArkField'; +import { ExportInfo } from '../../core/model/ArkExport'; +import { ImportInfo } from '../../core/model/ArkImport'; +import { BIGINT_KEYWORD, SUPER_NAME } from '../../core/common/TSConst'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'SourceTransformer'); + +export interface TransformerContext { + getArkFile(): ArkFile; + + getDeclaringArkNamespace(): ArkNamespace | undefined; + + getMethod(signature: MethodSignature): ArkMethod | null; + + getClass(signature: ClassSignature): ArkClass | null; + + getPrinter(): ArkCodeBuffer; + + transTemp2Code(temp: Local): string; + + isInBuilderMethod(): boolean; +} + +export class SourceTransformer { + protected context: TransformerContext; + + constructor(context: TransformerContext) { + this.context = context; + } + + private anonymousMethodToString(method: ArkMethod, indent: string): string { + let mtdPrinter = new SourceMethod(method, indent); + mtdPrinter.setInBuilder(this.context.isInBuilderMethod()); + return mtdPrinter.dump().trimStart(); + } + + private anonymousClassToString(cls: ArkClass, indent: string): string { + let clsPrinter = new SourceClass(cls, indent); + return clsPrinter.dump().trimStart(); + } + + public instanceInvokeExprToString(invokeExpr: ArkInstanceInvokeExpr): string { + let methodName = invokeExpr.getMethodSignature().getMethodSubSignature().getMethodName(); + if (methodName === INSTANCE_INIT_METHOD_NAME) { + return ''; + } + let args: string[] = []; + invokeExpr.getArgs().forEach((v) => { + args.push(this.valueToString(v)); + }); + let genericCode = this.genericTypesToString(invokeExpr.getRealGenericTypes()); + + if (PrinterUtils.isComponentAttributeInvoke(invokeExpr) && this.context.isInBuilderMethod()) { + return `.${methodName}${genericCode}(${args.join(', ')})`; + } + + return `${this.valueToString(invokeExpr.getBase())}.${methodName}${genericCode}(${args.join(', ')})`; + } + + private transBuilderMethod(className: string, methodName: string, args: string[], + invokeExpr: ArkStaticInvokeExpr, genericCode: string): string | null { + if (className === COMPONENT_CUSTOMVIEW) { + if (methodName === COMPONENT_CREATE_FUNCTION) { + // Anonymous @Builder method + if (args.length > 1) { + // remove the substring '() =>' or '(x, y): type =>' at the beginning of args[1] + const pattern = /^\([^)]*\)\s*:\s*\w*\s*=>\s*/; + args[1] = args[1].replace(pattern, ''); + } + return `${args.join(' ')}`; + } + if (methodName === COMPONENT_POP_FUNCTION) { + return ''; + } + } + + if (PrinterUtils.isComponentCreate(invokeExpr)) { + if (className === COMPONENT_IF) { + return `if (${args.join(', ')})`; + } + return `${className}${genericCode}(${args.join(', ')})`; + } + + if (PrinterUtils.isComponentIfBranchInvoke(invokeExpr)) { + let arg0 = invokeExpr.getArg(0) as Constant; + if (arg0.getValue() === '0') { + return ``; + } else { + return '} else {'; + } + } + + if (PrinterUtils.isComponentPop(invokeExpr)) { + return '}'; + } + + return null; + } + + public staticInvokeExprToString(invokeExpr: ArkStaticInvokeExpr): string { + let methodSignature = invokeExpr.getMethodSignature(); + let method = this.context.getMethod(methodSignature); + if (method && PrinterUtils.isAnonymousMethod(method.getName())) { + return this.anonymousMethodToString(method, this.context.getPrinter().getIndent()); + } + + let classSignature = methodSignature.getDeclaringClassSignature(); + let className = PrinterUtils.getStaticInvokeClassFullName(classSignature, this.context.getDeclaringArkNamespace()); + let methodName = methodSignature.getMethodSubSignature().getMethodName(); + let args: string[] = []; + invokeExpr.getArgs().forEach((v) => { + args.push(this.valueToString(v)); + }); + + let genericCode = this.genericTypesToString(invokeExpr.getRealGenericTypes()); + + if (this.context.isInBuilderMethod()) { + const res = this.transBuilderMethod(className, methodName, args, invokeExpr, genericCode); + if (res !== null) { + return res; + } + } + + if (className && className.length > 0 && methodName !== SUPER_NAME) { + return `${className}.${methodName}${genericCode}(${args.join(', ')})`; + } + return `${methodName}${genericCode}(${args.join(', ')})`; + } + + private genericTypesToString(types: Type[] | undefined): string { + if (!types) { + return ''; + } + + let code = this.typeArrayToString(types); + if (code.length > 0) { + return `<${code}>`; + } + return ''; + } + + public typeArrayToString(types: Type[], split: string = ', '): string { + let typesStr: string[] = []; + types.forEach((t) => { + typesStr.push(this.typeToString(t)); + }); + + return typesStr.join(split); + } + + public static constToString(value: Constant): string { + if (value.getType().toString() === 'string') { + return `'${PrinterUtils.escape(value.getValue())}'`; + } else if (value.getType().toString() === BIGINT_KEYWORD) { + return `${value.getValue()}n`; + } else { + return value.getValue(); + } + } + + private exprToString(expr: AbstractExpr): string { + if (expr instanceof ArkInstanceInvokeExpr) { + return `${this.instanceInvokeExprToString(expr)}`; + } + + if (expr instanceof ArkStaticInvokeExpr) { + return `${this.staticInvokeExprToString(expr)}`; + } + + if (expr instanceof ArkNewArrayExpr) { + return `new Array<${this.typeToString(expr.getBaseType())}>(${expr.getSize()})`; + } + + if (expr instanceof ArkNewExpr) { + return `new ${this.typeToString(expr.getType())}()`; + } + + if (expr instanceof ArkDeleteExpr) { + return `delete ${this.valueToString(expr.getField())}`; + } + + if (expr instanceof AbstractBinopExpr) { + let op1: Value = expr.getOp1(); + let op2: Value = expr.getOp2(); + let operator: string = expr.getOperator(); + + return `${this.valueToString(op1, operator)} ${operator} ${this.valueToString(op2, operator)}`; + } + + if (expr instanceof ArkTypeOfExpr) { + return `typeof(${this.valueToString(expr.getOp())})`; + } + + if (expr instanceof ArkInstanceOfExpr) { + return `${this.valueToString(expr.getOp())} instanceof ${this.typeToString(expr.getType())}`; + } + + if (expr instanceof ArkCastExpr) { + let baseOp = expr.getOp(); + return `${this.valueToString(baseOp)} as ${this.typeToString(expr.getType())}`; + } + + if (expr instanceof ArkUnopExpr) { + return `${expr.getOperator()}${this.valueToString(expr.getOp())}`; + } + + if (expr instanceof ArkAwaitExpr) { + return `await ${this.valueToString(expr.getPromise())}`; + } + + if (expr instanceof ArkYieldExpr) { + return `yield ${this.valueToString(expr.getYieldValue())}`; + } + + logger.info(`exprToString ${expr.constructor} not support.`); + // ArkPhiExpr + return `${expr}`; + } + + public refToString(value: AbstractRef): string { + if (value instanceof ArkInstanceFieldRef) { + return `${this.valueToString(value.getBase())}.${value.getFieldName()}`; + } + + if (value instanceof ArkStaticFieldRef) { + return `${value.getFieldSignature().getBaseName()}.${value.getFieldName()}`; + } + + if (value instanceof ArkArrayRef) { + let index = value.getIndex(); + if ( + index instanceof Constant && + index.getType() instanceof StringType && + PrinterUtils.isTemp(index.getValue()) + ) { + return `${this.valueToString(value.getBase())}[${this.valueToString(new Local(index.getValue()))}]`; + } + return `${this.valueToString(value.getBase())}[${this.valueToString(value.getIndex())}]`; + } + + if (value instanceof ArkThisRef) { + return 'this'; + } + + // ArkCaughtExceptionRef + logger.info(`refToString ${value.constructor} not support.`); + return `${value}`; + } + + public valueToString(value: Value, operator?: string): string { + if (value instanceof AbstractExpr) { + return this.exprToString(value); + } + + if (value instanceof AbstractRef) { + return this.refToString(value); + } + + if (value instanceof Constant) { + return SourceTransformer.constToString(value); + } + + if (value instanceof Local) { + return this.localToString(value, operator); + } + + logger.info(`valueToString ${value.constructor} not support.`); + return `${value}`; + } + + private localToString(value: Local, operator?: string): string { + if (PrinterUtils.isAnonymousMethod(value.getName())) { + let methodSignature = (value.getType() as FunctionType).getMethodSignature(); + let anonymousMethod = this.context.getMethod(methodSignature); + if (anonymousMethod) { + return this.anonymousMethodToString(anonymousMethod, this.context.getPrinter().getIndent()); + } + } + if (PrinterUtils.isAnonymousClass(value.getName())) { + let clsSignature = (value.getType() as ClassType).getClassSignature(); + let cls = this.context.getClass(clsSignature); + if (cls) { + return this.anonymousClassToString(cls, this.context.getPrinter().getIndent()); + } + } + + if ( + operator === NormalBinaryOperator.Division || + operator === NormalBinaryOperator.Multiplication || + operator === NormalBinaryOperator.Remainder + ) { + if (PrinterUtils.isTemp(value.getName())) { + let stmt = value.getDeclaringStmt(); + if (stmt instanceof ArkAssignStmt && stmt.getRightOp() instanceof ArkNormalBinopExpr) { + return `(${this.context.transTemp2Code(value)})`; + } + } + } + + return this.context.transTemp2Code(value); + } + + public literalObjectToString(type: ClassType): string { + let name = type.getClassSignature().getClassName(); + if (PrinterUtils.isAnonymousClass(name)) { + let cls = this.context.getClass(type.getClassSignature()); + if (cls) { + return this.anonymousClassToString(cls, this.context.getPrinter().getIndent()); + } + } + return name; + } + + public typeToString(type: Type): string { + if (type instanceof LiteralType) { + return this.literalType2string(type); + } + + if (type instanceof PrimitiveType || type instanceof GenericType) { + return type.getName(); + } + + if (type instanceof UnionType || type instanceof IntersectionType) { + return this.multipleType2string(type); + } + + if (type instanceof UnknownType) { + return 'any'; + } + + if (type instanceof VoidType) { + return 'void'; + } + + if (type instanceof ClassType) { + return this.classType2string(type); + } + if (type instanceof ArrayType) { + return this.arrayType2string(type); + } + if (type instanceof TupleType) { + return this.tupleType2string(type); + } + + if (type instanceof FunctionType) { + let methodSignature = type.getMethodSignature(); + let method = this.context.getMethod(methodSignature); + if (method && PrinterUtils.isAnonymousMethod(method.getName())) { + return new SourceMethod(method).toArrowFunctionTypeString(); + } + } + + if (type instanceof UnclearReferenceType) { + return this.unclearReferenceType2string(type); + } + + if (type instanceof AliasType) { + return this.aliasType2string(type); + } + + if (type instanceof KeyofTypeExpr) { + return this.keyofTypeExpr2string(type); + } + + if (type instanceof TypeQueryExpr) { + return this.typeQueryExpr2string(type); + } + + if (!type) { + return 'any'; + } + + logger.info(`valueToString ${type.constructor} not support.`); + return type.toString(); + } + + private literalType2string(type: LiteralType): string { + let literalName = type.getLiteralName(); + if (typeof literalName === 'string' && literalName.endsWith('Keyword')) { + return literalName.substring(0, literalName.length - 'Keyword'.length).toLowerCase(); + } + return `${literalName}`; + } + + private multipleType2string(type: UnionType | IntersectionType): string { + let typesStr: string[] = []; + for (const member of type.getTypes()) { + if (member instanceof UnionType || member instanceof IntersectionType) { + typesStr.push(`(${this.typeToString(member)})`); + } else { + typesStr.push(this.typeToString(member)); + } + } + if (type instanceof UnionType) { + return typesStr.join(' | '); + } else { + return typesStr.join(' & '); + } + } + + private arrayType2string(type: ArrayType): string { + const readonly = type.getReadonlyFlag() ? 'readonly ' : ''; + const dimensions: string[] = []; + for (let i = 0; i < type.getDimension(); i++) { + dimensions.push('[]'); + } + + let baseType = type.getBaseType(); + if (baseType instanceof UnionType || baseType instanceof IntersectionType || baseType instanceof AbstractTypeExpr) { + return `${readonly}(${this.typeToString(baseType)})${dimensions.join('')}`; + } + return `${readonly}${this.typeToString(baseType)}${dimensions.join('')}`; + } + + private tupleType2string(type: TupleType): string { + const readonly = type.getReadonlyFlag() ? 'readonly ' : ''; + let typesStr: string[] = []; + for (const member of type.getTypes()) { + typesStr.push(this.typeToString(member)); + } + return `${readonly}[${typesStr.join(', ')}]`; + } + + private aliasType2string(type: AliasType): string { + let typesStr: string[] = []; + let genericTypes = type.getRealGenericTypes() ?? type.getGenericTypes(); + if (genericTypes) { + for (const gType of genericTypes) { + typesStr.push(this.typeToString(gType)); + } + } + if (typesStr.length > 0) { + return `${type.getName()}<${typesStr.join(', ')}>`; + } + return type.getName(); + } + + private keyofTypeExpr2string(type: KeyofTypeExpr): string { + if (type.getOpType() instanceof UnionType || type.getOpType() instanceof IntersectionType) { + return `keyof (${this.typeToString(type.getOpType())})`; + } + return `keyof ${this.typeToString(type.getOpType())}`; + } + + private typeQueryExpr2string(type: TypeQueryExpr): string { + const gTypes = type.getGenerateTypes(); + const genericStr = this.genericTypesToString(gTypes); + const opValue = type.getOpValue(); + if (opValue instanceof ArkBaseModel) { + if (opValue instanceof ArkClass || opValue instanceof ArkMethod || opValue instanceof ArkNamespace || opValue instanceof ArkField) { + return `typeof ${opValue.getName()}${genericStr}`; + } else if (opValue instanceof ExportInfo) { + return `typeof ${opValue.getExportClauseName()}${genericStr}`; + } else if (opValue instanceof ImportInfo) { + return `typeof ${opValue.getImportClauseName()}${genericStr}`; + } else { + return `typeof *invalid*`; + } + } else { + return `typeof ${this.valueToString(opValue)}${genericStr}`; + } + } + + private unclearReferenceType2string(type: UnclearReferenceType): string { + let genericTypes = type.getGenericTypes(); + if (genericTypes.length > 0) { + return `${type.getName()}<${genericTypes.map((value)=>this.typeToString(value)).join(', ')}>`; + } + return type.getName(); + } + + private classType2string(type: ClassType): string { + const name = PrinterUtils.getStaticInvokeClassFullName(type.getClassSignature()); + if (PrinterUtils.isDefaultClass(name)) { + return 'any'; + } + if (PrinterUtils.isAnonymousClass(name)) { + let cls = this.context.getClass(type.getClassSignature()); + if (cls && cls.getCategory() === ClassCategory.TYPE_LITERAL) { + return this.anonymousClassToString(cls, this.context.getPrinter().getIndent()); + } + return 'Object'; + } + let genericTypes = type.getRealGenericTypes(); + if (genericTypes && genericTypes.length > 0) { + return `${name}${this.genericTypesToString(genericTypes)}`; + } + return name; + } +} diff --git a/ets2panda/linter/arkanalyzer/src/transformer/FunctionTransformer.ts b/ets2panda/linter/arkanalyzer/src/transformer/FunctionTransformer.ts new file mode 100644 index 0000000000..24dbe1869e --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/transformer/FunctionTransformer.ts @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +class FunctionTransformer extends Transformer{ + +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/transformer/SceneTransformer.ts b/ets2panda/linter/arkanalyzer/src/transformer/SceneTransformer.ts new file mode 100644 index 0000000000..7d29148dd4 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/transformer/SceneTransformer.ts @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +class SceneTransformer extends Transformer{ + +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/transformer/StaticSingleAssignmentFormer.ts b/ets2panda/linter/arkanalyzer/src/transformer/StaticSingleAssignmentFormer.ts new file mode 100644 index 0000000000..0f930f64ea --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/transformer/StaticSingleAssignmentFormer.ts @@ -0,0 +1,311 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkPhiExpr } from '../core/base/Expr'; +import { Local } from '../core/base/Local'; +import { ArkAssignStmt, Stmt } from '../core/base/Stmt'; +import { BasicBlock } from '../core/graph/BasicBlock'; +import { Cfg } from '../core/graph/Cfg'; +import { DominanceFinder } from '../core/graph/DominanceFinder'; +import { DominanceTree } from '../core/graph/DominanceTree'; +import { ArkBody } from '../core/model/ArkBody'; + +export class StaticSingleAssignmentFormer { + public transformBody(body: ArkBody): void { + let cfg = body.getCfg(); + + let blockToDefs = new Map>(); + let localToBlocks = new Map>(); + for (const block of cfg.getBlocks()) { + let defs = new Set(); + for (const stmt of block.getStmts()) { + this.transformStmt(stmt, defs, localToBlocks, block); + } + blockToDefs.set(block, defs); + } + + let dominanceFinder = new DominanceFinder(cfg); + let blockToPhiStmts = this.decideBlockToPhiStmts(body, dominanceFinder, blockToDefs, localToBlocks); + this.addPhiStmts(blockToPhiStmts, cfg, blockToDefs); + let dominanceTree = new DominanceTree(dominanceFinder); + + this.renameLocals(body, dominanceTree, blockToPhiStmts); + } + + private transformStmt(stmt: Stmt, defs: Set, localToBlocks: Map>, block: BasicBlock): void { + if (stmt.getDef() != null && stmt.getDef() instanceof Local) { + let local = stmt.getDef() as Local; + defs.add(local); + if (localToBlocks.has(local)) { + localToBlocks.get(local)?.add(block); + } else { + let blcoks = new Set(); + blcoks.add(block); + localToBlocks.set(local, blcoks); + } + } + } + + private decideBlockToPhiStmts(body: ArkBody, dominanceFinder: DominanceFinder, + blockToDefs: Map>, localToBlocks: Map>): + Map> { + let blockToPhiStmts = new Map>(); + let blockToPhiLocals = new Map>(); + let localToPhiBlock = new Map>(); + + for (const [_, local] of body.getLocals()) { + localToPhiBlock.set(local, new Set()); + let phiBlocks = localToPhiBlock.get(local) as Set; + let blocks = Array.from(localToBlocks.get(local) as Set); + while (blocks.length !== 0) { + let block = blocks.splice(0, 1).at(0) as BasicBlock; + let dfs = dominanceFinder.getDominanceFrontiers(block); + for (const df of dfs) { + this.handleDf(blockToPhiStmts, blockToPhiLocals, phiBlocks, df, local, blockToDefs, blocks); + } + } + } + + return blockToPhiStmts; + } + + private handleDf(blockToPhiStmts: Map>, + blockToPhiLocals: Map>, + phiBlocks: Set, df: BasicBlock, local: Local, + blockToDefs: Map>, + blocks: BasicBlock[]): void { + if (!phiBlocks.has(df)) { + phiBlocks.add(df); + + let phiStmt = this.createEmptyPhiStmt(local); + if (blockToPhiStmts.has(df)) { + blockToPhiStmts.get(df)?.add(phiStmt); + blockToPhiLocals.get(df)?.add(local); + } else { + let phiStmts = new Set(); + phiStmts.add(phiStmt); + blockToPhiStmts.set(df, phiStmts); + let phiLocals = new Set(); + phiLocals.add(local); + blockToPhiLocals.set(df, phiLocals); + } + blockToDefs.get(df)?.add(local); + + if (!blockToDefs.get(df)?.has(local)) { + blocks.push(df); + } + } + } + + private handleBlockWithSucc(blockToPhiStmts: Map>, + succ: BasicBlock, + blockToDefs: Map>, + block: BasicBlock, + phiArgsNum: Map): void { + for (const phi of (blockToPhiStmts.get(succ) as Set)) { + let local = phi.getDef() as Local; + if (blockToDefs.get(block)?.has(local)) { + if (phiArgsNum.has(phi)) { + let num = phiArgsNum.get(phi) as number; + phiArgsNum.set(phi, num + 1); + } else { + phiArgsNum.set(phi, 1); + } + } + } + } + + private addPhiStmts(blockToPhiStmts: Map>, cfg: Cfg, + blockToDefs: Map>): void { + + let phiArgsNum = new Map(); + for (const block of cfg.getBlocks()) { + let succs = Array.from(block.getSuccessors()); + for (const succ of succs) { + if (blockToPhiStmts.has(succ)) { + this.handleBlockWithSucc(blockToPhiStmts, succ, blockToDefs, block, phiArgsNum); + } + } + } + + for (const block of blockToPhiStmts.keys()) { + let phis = blockToPhiStmts.get(block) as Set; + let phisTocheck = new Set(phis); + for (const phi of phisTocheck) { + if ((phiArgsNum.get(phi) as number) < 2) { + phis.delete(phi); + } + } + + for (const phi of phis) { + cfg.insertBefore(phi, block.getHead() as Stmt); + } + } + } + + private renameUseAndDef(stmt: Stmt, localToNameStack: Map, nextFreeIdx: number, + newLocals: Set, newPhiStmts: Set): number { + let uses = stmt.getUses(); + if (uses.length > 0 && !this.constainsPhiExpr(stmt)) { + for (const use of uses) { + if (use instanceof Local) { + let nameStack = localToNameStack.get(use) as Local[]; + let newUse = nameStack[nameStack.length - 1]; + stmt.replaceUse(use, newUse); + } + } + } + + // rename def + let def = stmt.getDef(); + if (def != null && def instanceof Local) { + let newName = def.getName() + '#' + nextFreeIdx; + nextFreeIdx++; + let newDef = new Local(newName); + newDef.setOriginalValue(def); + newLocals.add(newDef); + localToNameStack.get(def)?.push(newDef); + (stmt).setLeftOp(newDef); + if (this.constainsPhiExpr(stmt)) { + newPhiStmts.add(stmt); + } + } + return nextFreeIdx; + } + + private renameLocals(body: ArkBody, dominanceTree: DominanceTree, + blockToPhiStmts: Map>): void { + let newLocals = new Set(body.getLocals().values()); + let localToNameStack = new Map(); + for (const local of newLocals) { + localToNameStack.set(local, new Array()) + } + + let blockStack = new Array(); + let visited = new Set(); + let dfsBlocks = dominanceTree.getAllNodesDFS(); + let nextFreeIdx = 0; + for (const block of dfsBlocks) { + let newPhiStmts = new Set(); + for (const stmt of block.getStmts()) { + // rename uses and def + nextFreeIdx = this.renameUseAndDef(stmt, localToNameStack, nextFreeIdx, newLocals, newPhiStmts); + } + visited.add(block); + blockStack.push(block); + if (blockToPhiStmts.has(block)) { + blockToPhiStmts.set(block, newPhiStmts); + } + + // rename phiStmts' args + let succs = Array.from(block.getSuccessors()); + for (const succ of succs) { + if (!blockToPhiStmts.has(succ)) { + continue; + } + let phiStmts = blockToPhiStmts.get(succ) as Set; + for (const phiStmt of phiStmts) { + let def = phiStmt.getDef() as Local; + let oriDef = this.getOriginalLocal(def, new Set(localToNameStack.keys())) as Local; + let nameStack = localToNameStack.get(oriDef) as Local[]; + let arg = nameStack[nameStack.length - 1]; + this.addNewArgToPhi(phiStmt, arg, block); + } + } + + // if a block's children in dominance tree are visited, remove it + this.removeVisitedTree(blockStack, dominanceTree, visited, localToNameStack); + } + body.setLocals(newLocals); + } + + private removeVisitedTree(blockStack: BasicBlock[], dominanceTree: DominanceTree, + visited: Set, localToNameStack: Map): void { + let top = blockStack[blockStack.length - 1]; + let children = dominanceTree.getChildren(top); + while (this.containsAllChildren(visited, children)) { + blockStack.pop(); + for (const stmt of top.getStmts()) { + let def = stmt.getDef(); + if (def != null && def instanceof Local) { + let oriDef = this.getOriginalLocal(def, new Set(localToNameStack.keys())) as Local; + localToNameStack.get(oriDef)?.pop(); + } + } + + // next block to check + if (blockStack.length > 0) { + top = blockStack[blockStack.length - 1]; + children = dominanceTree.getChildren(top); + } else { + break; + } + } + } + + private constainsPhiExpr(stmt: Stmt): boolean { + if (stmt instanceof ArkAssignStmt && stmt.getUses().length > 0) { + for (const use of stmt.getUses()) { + if (use instanceof ArkPhiExpr) { + return true; + } + } + } + return false; + } + + private getOriginalLocal(local: Local, locals: Set): Local | null { + if (locals.has(local)) { + return local; + } + let hashPos = local.getName().indexOf('#'); + let oriName = local.getName().substring(0, hashPos); + for (const oriLocal of locals) { + if (oriLocal.getName() === oriName) { + return oriLocal; + } + } + return null; + } + + private addNewArgToPhi(phiStmt: Stmt, arg: Local, block: BasicBlock): void { + for (let use of phiStmt.getUses()) { + if (use instanceof ArkPhiExpr) { + let phiExpr = use as ArkPhiExpr; + let args = phiExpr.getArgs(); + let argToBlock = phiExpr.getArgToBlock(); + args.push(arg); + argToBlock.set(arg, block); + phiExpr.setArgs(args); + phiExpr.setArgToBlock(argToBlock); + break; + } + } + } + + private containsAllChildren(blockSet: Set, children: BasicBlock[]): boolean { + for (const child of children) { + if (!blockSet.has(child)) { + return false; + } + } + return true; + } + + private createEmptyPhiStmt(local: Local): ArkAssignStmt { + let phiExpr = new ArkPhiExpr(); + return new ArkAssignStmt(local, phiExpr); + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/transformer/Transformer.ts b/ets2panda/linter/arkanalyzer/src/transformer/Transformer.ts new file mode 100644 index 0000000000..5b4d7f30bb --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/transformer/Transformer.ts @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/** + * + */ +class Transformer { + internalTransform() { + + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/utils/AstTreeUtils.ts b/ets2panda/linter/arkanalyzer/src/utils/AstTreeUtils.ts new file mode 100644 index 0000000000..8a86f8d57a --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/utils/AstTreeUtils.ts @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ts } from '..'; +import { ETS_COMPILER_OPTIONS } from '../core/common/EtsConst'; + +export class AstTreeUtils { + public static getASTNode(fileName: string, code: string): ts.SourceFile { + const sourceFile = ts.createSourceFile( + fileName, + code, + ts.ScriptTarget.Latest, + true, + undefined, + ETS_COMPILER_OPTIONS + ); + return sourceFile; + } +} diff --git a/ets2panda/linter/arkanalyzer/src/utils/CfgStructualAnalysis.ts b/ets2panda/linter/arkanalyzer/src/utils/CfgStructualAnalysis.ts new file mode 100644 index 0000000000..886b47ad45 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/utils/CfgStructualAnalysis.ts @@ -0,0 +1,1497 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkIfStmt, ArkReturnStmt, ArkThrowStmt } from '../core/base/Stmt'; +import { Trap } from '../core/base/Trap'; +import { BasicBlock } from '../core/graph/BasicBlock'; +import { Cfg } from '../core/graph/Cfg'; + +export enum CodeBlockType { + NORMAL, + IF, + ELSE, + BREAK, + CONTINUE, + DO, + DO_WHILE, + WHILE, + FOR, + COMPOUND_END, + TRY, + CATCH, + FINALLY, +} + +export type TraversalCallback = (block: BasicBlock | undefined, type: CodeBlockType) => void; + +export class AbstractFlowGraph { + private nodes: AbstractNode[] = []; + private entry: AbstractNode; + private block2NodeMap: Map; + private structOf: Map = new Map(); + private structTypes: Map = new Map(); + private structBlocks: Map> = new Map(); + private loopMap: Map = new Map(); + + constructor(cfg: Cfg, traps?: Trap[]) { + this.block2NodeMap = new Map(); + for (const bb of cfg.getBlocks()) { + let an = new AbstractNode(); + an.setBlock(bb); + this.block2NodeMap.set(bb, an); + } + + for (const bb of cfg.getBlocks()) { + let an = this.block2NodeMap.get(bb)!; + for (const succ of bb.getSuccessors()) { + an.addSucc(this.block2NodeMap.get(succ)!); + } + for (const pred of bb.getPredecessors()) { + an.addPred(this.block2NodeMap.get(pred)!); + } + } + + let trapRegions = this.buildTrap(traps); + this.searchTrapFinallyNodes(trapRegions); + this.trapsStructuralAnalysis(trapRegions); + + this.entry = this.block2NodeMap.get(cfg.getStartingBlock()!)!; + this.entry = this.structuralAnalysis(this.entry); + } + + public getEntry(): AbstractNode { + return this.entry; + } + + public getForIncBlock(block: BasicBlock): BasicBlock { + let node = this.block2NodeMap.get(block)!; + let loop = this.loopMap.get(node)! as ForLoopRegion; + return loop.inc.getBlock()!; + } + + public preOrder(node: AbstractNode, callback: TraversalCallback, visitor: Set = new Set()) { + visitor.add(node); + node.traversal(callback, CodeBlockType.NORMAL); + for (const succ of node.getSucc()) { + if (!visitor.has(succ)) { + this.preOrder(succ, callback, visitor); + } + } + } + + private structuralAnalysis(entry: AbstractNode, scope?: Set): AbstractNode { + let preds = entry.getPred(); + let entryBak = entry; + this.nodes = this.dfsPostOrder(entry, scope); + this.entry = entry; + this.buildCyclicStructural(); + + // acyclic structural + let postMax = this.nodes.length; + let change = true; + while (postMax > 1 && change) { + change = false; + for (let i = 0; i < postMax; i++) { + let node = this.nodes[i]; + let nset = new Set(); + let rtype = this.identifyRegionType(node, nset, scope); + if (!rtype) { + continue; + } + + let p = this.reduce(rtype, nset); + if (!p) { + continue; + } + + scope?.add(p); + if (nset.has(entry)) { + entry = p; + } + this.nodes = this.dfsPostOrder(entry, scope); + change = postMax !== this.nodes.length; + postMax = this.nodes.length; + } + } + + for (const pred of preds) { + pred.replaceSucc(entryBak, entry); + entry.addPred(pred); + } + + return entry; + } + + private dfsPostOrder( + node: AbstractNode, + scope?: Set, + visitor: Set = new Set(), + postOrder: AbstractNode[] = [] + ): AbstractNode[] { + visitor.add(node); + for (const succ of node.getSucc()) { + if (visitor.has(succ)) { + continue; + } + + if (scope && !scope.has(succ)) { + continue; + } + + this.dfsPostOrder(succ, scope, visitor, postOrder); + } + postOrder.push(node); + return postOrder; + } + + private buildCyclicStructural(): void { + for (const loop of this.prepareBuildLoops()) { + let nset = new Set(); + for (const n of loop) { + if (this.structOf.has(n)) { + nset.add(this.structOf.get(n)!); + } else { + nset.add(n); + } + } + let rtype = this.cyclicRegionType(nset); + let region = this.createRegion(rtype, nset)! as NaturalLoopRegion; + region.revise(); + this.structTypes.set(region, rtype); + let blocks = new Set(); + for (const s of nset) { + this.handleRegion(s, region, blocks); + } + this.structBlocks.set(region, blocks); + this.loopMap.set(region.header, region); + } + } + + private handleRegion(s: AbstractNode | Region, region: NaturalLoopRegion, blocks: Set): void { + if (!this.structOf.has(s)) { + this.structOf.set(s, region); + } + if (this.structBlocks.has(s as Region)) { + for (const b of this.structBlocks.get(s as Region)!) { + blocks.add(b); + } + } else { + blocks.add(s); + } + } + + private prepareBuildLoops(): Set[] { + let dom = this.buildDominator(); + let loops: Set[] = []; + for (const header of this.nodes) { + let innermost: Set | undefined; + let longest: number = 0; + + let backEdges = this.getBackEdges(dom, header); + if (backEdges.size === 0) { + continue; + } + + if (this.isSelfLoopNode(header)) { + loops.push(new Set([header])); + } + + for (const start of backEdges) { + let loop = this.naturalLoop(start, header); + if (!innermost || loop.size > longest) { + innermost = loop; + longest = loop.size; + } + } + loops.push(innermost!); + } + loops.sort((a, b) => a.size - b.size); + return loops; + } + + private buildDominator(): Map> { + let domin = new Map>(); + domin.set(this.entry, new Set([this.entry])); + for (const node of this.nodes) { + if (node !== this.entry) { + domin.set(node, new Set(this.nodes)); + } + } + + let change = true; + while (change) { + change = false; + for (const node of this.nodes) { + if (node === this.entry) { + continue; + } + let t = new Set(domin.get(node)!); + for (const p of node.getPred()) { + t = this.setIntersect(t, domin.get(p)!); + } + t.add(node); + if (!this.isSetEqual(t, domin.get(node)!)) { + change = true; + domin.set(node, t); + } + } + } + + return domin; + } + + private getBackEdges(dom: Map>, header: AbstractNode): Set { + let backEdges = new Set(); + for (const n of header.getPred()) { + // h dom n && n -> h + if (dom.get(n)?.has(header)) { + backEdges.add(n); + } + } + return backEdges; + } + + private naturalLoop(backEdgeStart: AbstractNode, backEdgeEnd: AbstractNode): Set { + let stack: AbstractNode[] = []; + let loop = new Set([backEdgeEnd, backEdgeStart]); + + stack.push(backEdgeStart); + + while (stack.length > 0) { + let m = stack.shift()!; + for (const pred of m.getPred()) { + if (loop.has(pred)) { + continue; + } + loop.add(pred); + stack.push(pred); + } + } + + return loop; + } + + private isSelfLoopNode(node: AbstractNode): boolean { + let inSucc = false; + let inPred = false; + + for (const pred of node.getPred()) { + if (pred === node) { + inPred = true; + } + } + + for (const succ of node.getSucc()) { + if (succ === node) { + inSucc = true; + } + } + + return inSucc && inPred; + } + + private isForLoopIncNode(node: AbstractNode): boolean { + for (const loop of this.loopMap.values()) { + if (loop.getType() === RegionType.FOR_LOOP_REGION) { + if (node === (loop as ForLoopRegion).inc) { + return true; + } + } + } + return false; + } + + private isValidInBlocks(node: AbstractNode, scope?: Set): boolean { + if (this.isForLoopIncNode(node) || node.hasIfStmt()) { + return false; + } + if (scope && !scope.has(node)) { + return false; + } + + return true; + } + + private isIfRegion(node: AbstractNode, nodeSet: Set): boolean { + nodeSet.clear(); + if (node.getSucc().length !== 2) { + return false; + } + let m = node.getSucc()[0]; + let n = node.getSucc()[1]; + if (m.getSucc().length === 1 && m.getSucc()[0] === n) { + nodeSet.add(node).add(m); + return true; + } + + return false; + } + + private isIfExitRegion(node: AbstractNode, nodeSet: Set): boolean { + nodeSet.clear(); + if (node.getSucc().length !== 2) { + return false; + } + let m = node.getSucc()[0]; + if (m.hasReturnStmt()) { + nodeSet.add(node).add(m); + return true; + } + + return false; + } + + private isIfElseRegion(node: AbstractNode, nodeSet: Set): boolean { + nodeSet.clear(); + if (node.getSucc().length !== 2) { + return false; + } + let m = node.getSucc()[0]; + let n = node.getSucc()[1]; + if ( + (m.getSucc().length === 1 && + n.getSucc().length === 1 && + m.getPred().length === 1 && + n.getPred().length === 1 && + m.getSucc()[0] === n.getSucc()[0]) || + (m.getSucc().length === 0 && n.getSucc().length === 0) + ) { + nodeSet.add(node).add(m).add(n); + return true; + } + + return false; + } + + private isBlockRegion(node: AbstractNode, nodeSet: Set, scope?: Set): boolean { + let n = node; + let p = true; + let s = n.getSucc().length === 1; + nodeSet.clear(); + + let blocks = []; + while (p && s && !nodeSet.has(n) && this.isValidInBlocks(n, scope)) { + nodeSet.add(n); + blocks.push(n); + n = n.getSucc()[0]; + p = n.getPred().length === 1; + s = n.getSucc().length === 1; + } + + if (p && this.isValidInBlocks(n, scope)) { + if (!nodeSet.has(n)) { + blocks.push(n); + } + nodeSet.add(n); + } + + n = node; + p = n.getPred().length === 1; + s = true; + while (p && s && this.isValidInBlocks(n, scope)) { + if (!nodeSet.has(n)) { + blocks.unshift(n); + } + nodeSet.add(n); + n = n.getPred()[0]; + if (nodeSet.has(n)) { + break; + } + p = n.getPred().length === 1; + s = n.getSucc().length === 1; + } + + if (s && this.isValidInBlocks(n, scope)) { + if (!nodeSet.has(n)) { + blocks.unshift(n); + } + nodeSet.add(n); + } + + nodeSet.clear(); + for (const n of blocks) { + nodeSet.add(n); + } + + if (nodeSet.size >= 2) { + return true; + } + return false; + } + + private isIfBreakRegion(node: AbstractNode, nodeSet: Set, loop: NaturalLoopRegion): boolean { + let m = node.getSucc()[0]; + nodeSet.clear(); + if (this.isExitLoop(m, this.structBlocks.get(loop)!)) { + nodeSet.add(node); + return true; + } + + if (m.getSucc().length === 1 && this.isExitLoop(m.getSucc()[0], this.structBlocks.get(loop)!)) { + nodeSet.add(node).add(m); + return true; + } + + return false; + } + + private isIfContinueRegion(node: AbstractNode, nodeSet: Set, loop: NaturalLoopRegion): boolean { + nodeSet.clear(); + let m = node.getSucc()[0]; + let n = node.getSucc()[1]; + if (loop.control.has(m)) { + nodeSet.add(node); + return true; + } + + if ( + m.getSucc().length === 1 && + loop.control.has(m.getSucc()[0]) && + !loop.control.has(n) && + !this.isIfElseRegion(node, nodeSet) + ) { + nodeSet.add(node).add(m); + return true; + } + return false; + } + + private isWhileRegion(node: AbstractNode, nodeSet: Set, loop: NaturalLoopRegion): boolean { + nodeSet.clear(); + let m = node.getSucc()[0]; + if (loop.header === node && m.getSucc().length === 1 && m.getPred().length === 1 && m.getSucc()[0] === node) { + nodeSet.add(node).add(m); + return true; + } + return false; + } + + private isForRegion(node: AbstractNode, nodeSet: Set, loop: NaturalLoopRegion): boolean { + nodeSet.clear(); + if (loop.header === node && loop.getType() === RegionType.FOR_LOOP_REGION) { + let forLoop = loop as ForLoopRegion; + let blocks = node.getSucc()[0]; + if ( + forLoop.inc.getPred().length === 1 && + forLoop.inc.getPred()[0] === blocks && + blocks.getSucc().length === 1 + ) { + nodeSet.add(node).add(forLoop.inc).add(blocks); + return true; + } + } + return false; + } + + private isDoWhileRegion(node: AbstractNode, nodeSet: Set, loop: NaturalLoopRegion): boolean { + nodeSet.clear(); + if (loop.back === node && loop.getType() === RegionType.DO_WHILE_LOOP_REGION) { + let blocks = node.getPred()[0]; + if (blocks.getSucc().length === 1 && blocks.getSucc()[0] === node && node.getSucc()[0] === blocks) { + nodeSet.add(blocks).add(node); + return true; + } + } + return false; + } + + private identifyRegionType( + node: AbstractNode, + nodeSet: Set, + scope?: Set + ): RegionType | undefined { + if (this.isBlockRegion(node, nodeSet, scope)) { + return RegionType.BLOCK_REGION; + } + + let inLoop = false; + let region = this.structOf.get(node); + if (region && LOOP_TYPES.has(region?.getType())) { + inLoop = true; + } + + if (new Set(node.getPred()).has(node) && new Set(node.getSucc()).has(node)) { + nodeSet.add(node); + if (inLoop) { + return region?.getType(); + } + return RegionType.SELF_LOOP_REGION; + } + + if (node.getSucc().length !== 2) { + return undefined; + } + + if (inLoop) { + let loop = region as NaturalLoopRegion; + if (!loop.control.has(node)) { + if (this.isIfBreakRegion(node, nodeSet, loop)) { + return RegionType.IF_THEN_BREAK_REGION; + } + + if (this.isIfContinueRegion(node, nodeSet, loop)) { + return RegionType.IF_THEN_CONTINUE_REGION; + } + } + if (this.isWhileRegion(node, nodeSet, loop)) { + return RegionType.WHILE_LOOP_REGION; + } + + if (this.isForRegion(node, nodeSet, loop)) { + return RegionType.FOR_LOOP_REGION; + } + + if (this.isDoWhileRegion(node, nodeSet, loop)) { + return RegionType.DO_WHILE_LOOP_REGION; + } + } + + // check for if + if (this.isIfExitRegion(node, nodeSet)) { + return RegionType.IF_THEN_EXIT_REGION; + } + if (this.isIfRegion(node, nodeSet)) { + return RegionType.IF_REGION; + } + + // check for an if else + if (this.isIfElseRegion(node, nodeSet)) { + return RegionType.IF_ELSE_REGION; + } + + return undefined; + } + + private cyclicRegionType(nodeSet: Set): RegionType { + let nodes = Array.from(nodeSet); + let header = nodes[0]; + if (nodeSet.size === 1) { + let tail = nodes[0].getBlock()?.getTail(); + if (tail instanceof ArkIfStmt) { + return RegionType.DO_WHILE_LOOP_REGION; + } + return RegionType.WHILE_LOOP_REGION; + } + + let back = nodes[1]; + // exit loop from back + if (!this.hasExitLoopSucc(header, nodeSet) && this.hasExitLoopSucc(back, nodeSet)) { + return RegionType.DO_WHILE_LOOP_REGION; + } + + if (this.hasExitLoopSucc(header, nodeSet) && this.hasExitLoopSucc(back, nodeSet)) { + // header true exit loop --> exit is break + if (!nodeSet.has(header.getSucc()[0])) { + return RegionType.DO_WHILE_LOOP_REGION; + } + } + + // for + if (back.getSucc().length === 1 && back.getBlock()?.getStmts()?.length === 1) { + let isForLoop = true; + for (const pred of header.getPred()) { + if (nodeSet.has(pred) && pred !== back) { + isForLoop = false; + } + } + if (isForLoop) { + return RegionType.FOR_LOOP_REGION; + } + } + + return RegionType.WHILE_LOOP_REGION; + } + + private hasExitLoopSucc(node: AbstractNode, nodeSet: Set): boolean { + for (const succ of node.getSucc()) { + if (!nodeSet.has(succ)) { + return true; + } + } + + return false; + } + + private isExitLoop(node: AbstractNode | Region, nodeSet: Set): boolean { + if (this.structBlocks.has(node)) { + for (const n of this.structBlocks.get(node)!) { + if (!nodeSet.has(n)) { + return true; + } + } + } else { + if (!nodeSet.has(node)) { + return true; + } + } + + return false; + } + + private createRegion(rtype: RegionType, nodeSet: Set): Region | undefined { + let node: Region | undefined; + if (rtype === RegionType.BLOCK_REGION) { + node = new BlockRegion(nodeSet); + } else if (rtype === RegionType.IF_ELSE_REGION) { + node = new IfElseRegion(nodeSet); + } else if (rtype === RegionType.IF_REGION) { + node = new IfRegion(nodeSet); + } else if (rtype === RegionType.IF_THEN_EXIT_REGION) { + node = new IfExitRegion(nodeSet); + } else if (rtype === RegionType.IF_THEN_BREAK_REGION) { + node = new IfBreakRegion(nodeSet); + } else if (rtype === RegionType.IF_THEN_CONTINUE_REGION) { + node = new IfContinueRegion(nodeSet); + } else if (rtype === RegionType.SELF_LOOP_REGION) { + node = new SelfLoopRegion(nodeSet); + } else if (rtype === RegionType.WHILE_LOOP_REGION) { + let whileLoop = new WhileLoopRegion(nodeSet); + this.loopMap.set(whileLoop.header, whileLoop); + node = whileLoop; + } else if (rtype === RegionType.FOR_LOOP_REGION) { + let forLoop = new ForLoopRegion(nodeSet); + this.loopMap.set(forLoop.header, forLoop); + node = forLoop; + } else if (rtype === RegionType.DO_WHILE_LOOP_REGION) { + let doWhileLoop = new DoWhileLoopRegion(nodeSet); + this.loopMap.set(doWhileLoop.header, doWhileLoop); + node = doWhileLoop; + } else if ( + rtype === RegionType.TRY_CATCH_REGION || + rtype === RegionType.TRY_FINALLY_REGION || + rtype === RegionType.TRY_CATCH_FINALLY_REGION + ) { + node = new TrapRegion(nodeSet, rtype); + } + + return node; + } + + private reduce(rtype: RegionType, nodeSet: Set): Region | undefined { + let region = this.createRegion(rtype, nodeSet); + region?.replace(); + if (region === undefined) { + return undefined; + } + this.structTypes.set(region, rtype); + let blocks = new Set(); + for (const s of nodeSet) { + this.structOf.set(s, region); + if (this.structBlocks.has(s as Region)) { + for (const b of this.structBlocks.get(s as Region)!) { + blocks.add(b); + } + } else { + blocks.add(s); + } + } + this.structBlocks.set(region, blocks); + return region; + } + + private setIntersect(a: Set, b: Set): Set { + let r = new Set(); + if (!b) { + return r; + } + for (const n of b) { + if (a.has(n)) { + r.add(n); + } + } + + return r; + } + + private isSetEqual(a: Set, b: Set): boolean { + if (a.size !== b.size) { + return false; + } + + return this.setIntersect(a, b).size === a.size; + } + + private buildTrap(traps?: Trap[]): NaturalTrapRegion[] { + if (!traps) { + return []; + } + traps.sort( + (a, b) => + a.getTryBlocks().length + + a.getCatchBlocks().length - + (b.getTryBlocks().length + b.getCatchBlocks().length) + ); + + let trapRegions: NaturalTrapRegion[] = []; + + for (const trap of traps) { + let region = new NaturalTrapRegion(trap, this.block2NodeMap); + let findTrapRegion = this.getNaturalTrapRegion(region); + + if (!findTrapRegion) { + for (const n of region.getNodes()) { + this.structOf.set(n, region); + } + trapRegions.push(region); + continue; + } + if (findTrapRegion.type === RegionType.TRY_FINALLY_REGION) { + findTrapRegion.trySet = region.trySet; + findTrapRegion.catchSet = region.catchSet; + region = findTrapRegion; + } else { + findTrapRegion.finallySet = region.finallySet; + region = findTrapRegion; + } + + for (const n of region.getNodes()) { + this.structOf.set(n, region); + } + region.type = RegionType.TRY_CATCH_FINALLY_REGION; + } + + this.structOf.clear(); + + return trapRegions; + } + + private searchTrapFinallyNodes(trapRegions: NaturalTrapRegion[]): void { + // search finally + for (const region of trapRegions) { + if (region.type === RegionType.TRY_CATCH_REGION) { + continue; + } + + this.bfs(region); + } + } + + private bfs(region: NaturalTrapRegion): void { + let finallyNodes = new Set(); + let count = (region as NaturalTrapRegion).finallySet!.size; + let queue = [region.getSucc()[0]]; + while (queue.length > 0 && finallyNodes.size < count) { + let node = queue[0]; + queue.splice(0, 1); + finallyNodes.add(node); + (region as NaturalTrapRegion).identifyFinallySet.add(node); + for (const succ of node.getSucc()) { + if (!finallyNodes.has(succ)) { + queue.push(succ); + } + } + } + } + + private getNaturalTrapRegion(trap: NaturalTrapRegion): NaturalTrapRegion | undefined { + let findTrap = this.findNaturalTrapRegion(trap.trySet); + if (findTrap) { + return findTrap; + } + if (trap.catchSet) { + findTrap = this.findNaturalTrapRegion(trap.catchSet); + } + + if (findTrap) { + return findTrap; + } + + if (trap.finallySet) { + findTrap = this.findNaturalTrapRegion(trap.finallySet); + } + + return findTrap; + } + + private findNaturalTrapRegion(nodes: Set): NaturalTrapRegion | undefined { + let findTrap: NaturalTrapRegion | undefined; + for (const node of nodes) { + if (!this.structOf.has(node)) { + return undefined; + } + if (!findTrap) { + findTrap = this.structOf.get(node)! as NaturalTrapRegion; + continue; + } + if (findTrap !== this.structOf.get(node)) { + return undefined; + } + } + return findTrap; + } + + private trapsStructuralAnalysis(trapRegions: NaturalTrapRegion[]): void { + trapRegions.sort((a, b) => a.size() - b.size()); + + for (const trap of trapRegions) { + let tryNode = this.trapsSubStructuralAnalysis(trap.trySet)!; + let catchNode: AbstractNode | undefined = this.trapsSubStructuralAnalysis(trap.catchSet); + let finnallyNode: AbstractNode | undefined = this.trapsSubStructuralAnalysis(trap.identifyFinallySet); + + if (catchNode === undefined) { + this.reduce(RegionType.TRY_FINALLY_REGION, new Set([tryNode, finnallyNode!])); + } else if (finnallyNode === undefined) { + this.reduce(RegionType.TRY_CATCH_REGION, new Set([tryNode, catchNode!])); + } else { + this.reduce(RegionType.TRY_CATCH_FINALLY_REGION, new Set([tryNode, catchNode!, finnallyNode!])); + } + } + } + + private trapsSubStructuralAnalysis(nodes?: Set): AbstractNode | undefined { + if (!nodes) { + return undefined; + } + let entry = Array.from(nodes)[0]; + if (nodes.size <= 1) { + return entry; + } + + for (const node of nodes) { + if (this.structOf.has(node)) { + nodes.add(this.structOf.get(node)!); + } + } + + return this.structuralAnalysis(entry, nodes); + } +} + +enum RegionType { + ABSTRACT_NODE, + TRY_NODE, + CATCH_NODE, + FINALLY_NODE, + /* Sequence of blocks. */ + BLOCK_REGION, + IF_REGION, + IF_ELSE_REGION, + IF_THEN_EXIT_REGION, + IF_THEN_BREAK_REGION, + IF_THEN_CONTINUE_REGION, + SELF_LOOP_REGION, + NATURAL_LOOP_REGION, + WHILE_LOOP_REGION, + DO_WHILE_LOOP_REGION, + FOR_LOOP_REGION, + CASE_REGION, + SWITCH_REGION, + TRY_CATCH_REGION, + TRY_FINALLY_REGION, + TRY_CATCH_FINALLY_REGION, +} + +const LOOP_TYPES = new Set([ + RegionType.SELF_LOOP_REGION, + RegionType.NATURAL_LOOP_REGION, + RegionType.WHILE_LOOP_REGION, + RegionType.FOR_LOOP_REGION, + RegionType.DO_WHILE_LOOP_REGION, +]); + +class AbstractNode { + type: RegionType; + private predNodes: AbstractNode[] = []; + private succNodes: AbstractNode[] = []; + private bb: BasicBlock | undefined; + + constructor() { + this.type = RegionType.ABSTRACT_NODE; + } + + public traversal(callback: TraversalCallback, type: CodeBlockType) { + callback(this.bb, type); + } + + public getType(): RegionType { + return this.type; + } + + public getSucc(): AbstractNode[] { + return this.succNodes; + } + + public addSucc(node: AbstractNode) { + this.succNodes.push(node); + } + + public replaceSucc(src: AbstractNode, dst: AbstractNode) { + for (let i = 0; i < this.succNodes.length; i++) { + if (this.succNodes[i] === src) { + this.succNodes[i] = dst; + break; + } + } + } + + public removeSucc(src: AbstractNode) { + for (let i = 0; i < this.predNodes.length; i++) { + if (this.succNodes[i] === src) { + this.succNodes.splice(i, 1); + break; + } + } + } + + public getPred(): AbstractNode[] { + return this.predNodes; + } + + public addPred(block: AbstractNode): void { + let set = new Set(this.predNodes); + if (set.has(block)) { + return; + } + this.predNodes.push(block); + } + + public replacePred(src: AbstractNode, dst: AbstractNode) { + for (let i = 0; i < this.predNodes.length; i++) { + if (this.predNodes[i] === src) { + this.predNodes[i] = dst; + break; + } + } + } + + public removePred(src: AbstractNode) { + for (let i = 0; i < this.predNodes.length; i++) { + if (this.predNodes[i] === src) { + this.predNodes.splice(i, 1); + break; + } + } + } + + public setBlock(bb: BasicBlock) { + this.bb = bb; + } + + public getBlock(): BasicBlock | undefined { + return this.bb; + } + + public hasIfStmt(): boolean { + if (!this.bb) { + return false; + } + + for (let stmt of this.bb.getStmts()) { + if (stmt instanceof ArkIfStmt) { + return true; + } + } + return false; + } + + public hasReturnStmt(): boolean { + if (!this.bb) { + return false; + } + for (let stmt of this.bb.getStmts()) { + if (stmt instanceof ArkReturnStmt) { + return true; + } + } + return false; + } +} + +abstract class Region extends AbstractNode { + nset: Set; + constructor(nset: Set, type: RegionType) { + super(); + this.nset = nset; + this.type = type; + } + + public getBlock(): BasicBlock | undefined { + if (this.nset.size === 0) { + return undefined; + } + + return Array.from(this.nset)[0].getBlock(); + } + + public abstract replace(): void; +} + +class BlockRegion extends Region { + blocks: AbstractNode[]; + constructor(nset: Set) { + super(nset, RegionType.BLOCK_REGION); + this.blocks = Array.from(nset); + } + + public replace() { + for (let pred of this.blocks[0].getPred()) { + pred.replaceSucc(this.blocks[0], this); + this.addPred(pred); + } + + for (let succ of this.blocks[this.blocks.length - 1].getSucc()) { + succ.replacePred(this.blocks[this.blocks.length - 1], this); + this.addSucc(succ); + } + } + + public traversal(callback: TraversalCallback) { + for (const node of this.blocks) { + node.traversal(callback, CodeBlockType.NORMAL); + } + } +} + +abstract class NaturalLoopRegion extends Region { + header: AbstractNode; + back: AbstractNode; + control: Set; + + constructor(nset: Set, type: RegionType = RegionType.NATURAL_LOOP_REGION) { + super(nset, type); + let nodes = Array.from(nset); + this.header = nodes[0]; + if (nset.size > 1) { + this.back = nodes[1]; + } else { + this.back = nodes[0]; + } + this.control = new Set([this.header]); + } + + public replace(): void { + for (let pred of this.header.getPred()) { + if (!this.nset.has(pred)) { + pred.replaceSucc(this.header, this); + this.addPred(pred); + } + } + + let succNodes = new Set(); + for (let node of this.nset) { + for (let succ of node.getSucc()) { + if (!this.nset.has(succ)) { + succNodes.add(succ); + } + } + } + + if (succNodes.size === 0) { + return; + } + + let pred = Array.from(succNodes)[0]; + let replaced = false; + for (let succ of pred.getPred()) { + if (this.nset.has(succ)) { + if (!replaced) { + pred.replacePred(succ, this); + this.addSucc(pred); + replaced = true; + } else { + pred.removePred(succ); + } + } + } + } + + public revise(): void { + // add node to loop sets + for (const node of this.nset) { + for (const succ of node.getSucc()) { + if ( + !this.nset.has(succ) && + succ !== this.getExitNode() && + succ.getSucc().length === 1 && + succ.getSucc()[0] === this.getExitNode() + ) { + this.nset.add(succ); + } + } + } + } + + abstract getExitNode(): AbstractNode; +} + +class SelfLoopRegion extends NaturalLoopRegion { + constructor(nset: Set) { + super(nset, RegionType.SELF_LOOP_REGION); + this.back = this.header; + } + + public replace() { + for (let pred of this.header.getPred()) { + if (pred !== this.header) { + pred.replaceSucc(this.header, this); + this.addPred(pred); + } + } + + for (let succ of this.header.getSucc()) { + if (succ !== this.header) { + succ.replacePred(this.header, this); + this.addSucc(succ); + } + } + } + + getExitNode(): AbstractNode { + return this.header.getSucc()[1]; + } +} + +class WhileLoopRegion extends NaturalLoopRegion { + constructor(nset: Set) { + super(nset, RegionType.WHILE_LOOP_REGION); + } + + public traversal(callback: TraversalCallback) { + this.header.traversal(callback, CodeBlockType.WHILE); + if (this.header !== this.back) { + this.back.traversal(callback, CodeBlockType.NORMAL); + } + callback(undefined, CodeBlockType.COMPOUND_END); + } + + getExitNode(): AbstractNode { + return this.header.getSucc()[1]; + } +} + +class DoWhileLoopRegion extends NaturalLoopRegion { + constructor(nset: Set) { + super(nset, RegionType.DO_WHILE_LOOP_REGION); + this.control.clear(); + this.control.add(this.back); + } + + public traversal(callback: TraversalCallback) { + callback(undefined, CodeBlockType.DO); + if (this.header !== this.back) { + this.header.traversal(callback, CodeBlockType.NORMAL); + } + this.back.traversal(callback, CodeBlockType.DO_WHILE); + } + + getExitNode(): AbstractNode { + return this.back.getSucc()[1]; + } +} + +class ForLoopRegion extends NaturalLoopRegion { + inc: AbstractNode; + + constructor(nset: Set) { + super(nset, RegionType.FOR_LOOP_REGION); + this.inc = this.back; + this.control.add(this.inc); + } + + public traversal(callback: TraversalCallback) { + this.header.traversal(callback, CodeBlockType.FOR); + for (const node of this.nset) { + if (node !== this.header && node !== this.inc) { + node.traversal(callback, CodeBlockType.NORMAL); + } + } + callback(undefined, CodeBlockType.COMPOUND_END); + } + + getExitNode(): AbstractNode { + return this.header.getSucc()[1]; + } +} + +class IfRegion extends Region { + contition: AbstractNode; + then: AbstractNode; + + constructor(nset: Set) { + super(nset, RegionType.IF_REGION); + let nodes = Array.from(nset); + this.contition = nodes[0]; + this.then = nodes[1]; + } + + public replace(): void { + this.replaceContitionPred(); + + for (let succ of this.then.getSucc()) { + if (succ !== this.then) { + succ.replacePred(this.then, this); + succ.removePred(this.contition); + this.addSucc(succ); + } + } + } + + public traversal(callback: TraversalCallback) { + this.contition.traversal(callback, CodeBlockType.IF); + this.then.traversal(callback, CodeBlockType.NORMAL); + callback(undefined, CodeBlockType.COMPOUND_END); + } + + protected replaceContitionPred(): void { + for (let pred of this.contition.getPred()) { + if (pred !== this.contition) { + pred.replaceSucc(this.contition, this); + this.addPred(pred); + } + } + } +} + +class IfExitRegion extends IfRegion { + constructor(nset: Set) { + super(nset); + this.type = RegionType.IF_THEN_EXIT_REGION; + } + + public replace() { + this.replaceContitionPred(); + + let succ = this.contition.getSucc()[1]; + succ.replacePred(this.contition, this); + this.addSucc(succ); + } +} + +class IfBreakRegion extends IfRegion { + constructor(nset: Set) { + super(nset); + this.type = RegionType.IF_THEN_BREAK_REGION; + } + + public replace() { + this.replaceContitionPred(); + + let succ = this.contition.getSucc()[1]; + succ.replacePred(this.contition, this); + this.addSucc(succ); + + if (this.then) { + succ = this.then.getSucc()[0]; + succ.removePred(this.then); + } else { + succ = this.contition.getSucc()[0]; + succ.removePred(this.contition); + } + } + + public traversal(callback: TraversalCallback) { + this.contition.traversal(callback, CodeBlockType.IF); + this.then?.traversal(callback, CodeBlockType.NORMAL); + callback(undefined, CodeBlockType.BREAK); + callback(undefined, CodeBlockType.COMPOUND_END); + } +} + +class IfContinueRegion extends IfBreakRegion { + constructor(nset: Set) { + super(nset); + this.type = RegionType.IF_THEN_CONTINUE_REGION; + } + + public traversal(callback: TraversalCallback) { + this.contition.traversal(callback, CodeBlockType.IF); + this.then?.traversal(callback, CodeBlockType.NORMAL); + callback(undefined, CodeBlockType.CONTINUE); + callback(undefined, CodeBlockType.COMPOUND_END); + } +} + +class IfElseRegion extends Region { + contition: AbstractNode; + then: AbstractNode; + else: AbstractNode; + + constructor(nset: Set) { + super(nset, RegionType.IF_ELSE_REGION); + let nodes = Array.from(nset); + this.contition = nodes[0]; + this.then = nodes[1]; + this.else = nodes[2]; + } + + public replace() { + for (let pred of this.contition.getPred()) { + if (pred !== this.contition) { + pred.replaceSucc(this.contition, this); + this.addPred(pred); + } + } + + for (let succ of this.then.getSucc()) { + if (succ !== this.then) { + succ.replacePred(this.then, this); + succ.removePred(this.else); + this.addSucc(succ); + } + } + } + + public traversal(callback: TraversalCallback) { + this.contition.traversal(callback, CodeBlockType.IF); + this.then.traversal(callback, CodeBlockType.NORMAL); + callback(undefined, CodeBlockType.ELSE); + this.else.traversal(callback, CodeBlockType.NORMAL); + callback(undefined, CodeBlockType.COMPOUND_END); + } +} + +class TrapRegion extends Region { + tryNode: AbstractNode; + catchNode?: AbstractNode; + finallyNode?: AbstractNode; + + constructor(nset: Set, type: RegionType) { + super(nset, type); + let nodes = Array.from(nset); + + this.tryNode = nodes[0]; + if (type === RegionType.TRY_CATCH_REGION) { + this.catchNode = nodes[1]; + } else if (type === RegionType.TRY_FINALLY_REGION) { + this.finallyNode = nodes[1]; + } else { + this.catchNode = nodes[1]; + this.finallyNode = nodes[2]; + } + } + + public replace(): void { + for (let pred of this.tryNode.getPred()) { + if (pred !== this.tryNode) { + pred.replaceSucc(this.tryNode, this); + this.addPred(pred); + } + } + + if (this.finallyNode) { + for (let succ of this.finallyNode.getSucc()) { + if (succ !== this.finallyNode) { + succ.replacePred(this.finallyNode, this); + this.addSucc(succ); + } + } + } else { + for (let succ of this.tryNode.getSucc()) { + if (succ !== this.tryNode) { + succ.replacePred(this.tryNode, this); + this.addSucc(succ); + } + } + } + } + + public traversal(callback: TraversalCallback) { + callback(undefined, CodeBlockType.TRY); + this.tryNode.traversal(callback, CodeBlockType.NORMAL); + if (this.catchNode) { + callback(this.catchNode.getBlock(), CodeBlockType.CATCH); + this.catchNode?.traversal(callback, CodeBlockType.NORMAL); + } + if (this.finallyNode) { + callback(undefined, CodeBlockType.FINALLY); + this.finallyNode?.traversal(callback, CodeBlockType.NORMAL); + } + callback(undefined, CodeBlockType.COMPOUND_END); + } +} + +class NaturalTrapRegion extends Region { + trySet: Set; + catchSet?: Set; + finallySet?: Set; + identifyFinallySet: Set; + + constructor(trap: Trap, block2NodeMap: Map) { + super(new Set(), RegionType.TRY_CATCH_FINALLY_REGION); + this.trySet = new Set(); + this.catchSet = new Set(); + this.identifyFinallySet = new Set(); + + for (const block of trap.getTryBlocks()) { + this.trySet.add(block2NodeMap.get(block)!); + } + + for (const block of trap.getCatchBlocks()) { + this.catchSet.add(block2NodeMap.get(block)!); + } + + if (this.isFinallyNode(Array.from(this.catchSet!)[this.catchSet.size - 1])!) { + this.type = RegionType.TRY_FINALLY_REGION; + this.finallySet = this.catchSet; + this.catchSet = undefined; + } else { + this.type = RegionType.TRY_CATCH_REGION; + } + } + + private isFinallyNode(node: AbstractNode): boolean { + let block = node.getBlock(); + if (!block) { + return false; + } + + let stmtLen = block.getStmts().length; + if (stmtLen < 1) { + return false; + } + + let stmtLast = block.getStmts()[stmtLen - 1]; + return stmtLast instanceof ArkThrowStmt; + } + + public size(): number { + let size = this.trySet.size; + if (this.catchSet) { + size += this.catchSet.size; + } + if (this.finallySet) { + size += this.finallySet.size; + } + return size; + } + + public replace(): void {} + + public getNodes(): AbstractNode[] { + let nodes = Array.from(this.trySet); + + if (this.catchSet) { + nodes.push(...this.catchSet); + } + + if (this.finallySet) { + nodes.push(...this.finallySet); + } + return nodes; + } + + public getSucc(): AbstractNode[] { + let succ = new Set(); + + for (const node of this.trySet) { + for (const s of node.getSucc()) { + if (!this.trySet.has(s)) { + succ.add(s); + } + } + } + return Array.from(succ); + } +} diff --git a/ets2panda/linter/arkanalyzer/src/utils/FileUtils.ts b/ets2panda/linter/arkanalyzer/src/utils/FileUtils.ts new file mode 100644 index 0000000000..4cf756fc0b --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/utils/FileUtils.ts @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import fs from 'fs'; +import path from 'path'; +import Logger, { LOG_MODULE_TYPE } from './logger'; +import { transfer2UnixPath } from './pathTransfer'; +import { OH_PACKAGE_JSON5 } from '../core/common/EtsConst'; +import { Language } from '../core/model/ArkFile'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'FileUtils'); + +export class FileUtils { + public static readonly FILE_FILTER = { + ignores: ['.git', '.preview', '.hvigor', '.idea', 'test', 'ohosTest'], + include: /(?): Map { + const moduleMap: Map = new Map(); + ohPkgContentMap.forEach((content, filePath) => { + const moduleName = content.name as string; + if (moduleName && moduleName.startsWith('@')) { + const modulePath = path.dirname(filePath); + moduleMap.set(moduleName, new ModulePath(modulePath, content.main ? + path.resolve(modulePath, content.main as string) : '')); + } + }) + ohPkgContentMap.forEach((content, filePath) => { + if (!content.dependencies) { + return; + } + Object.entries(content.dependencies).forEach(([name, value]) => { + if (moduleMap.get(name)) { + return; + } + const modulePath = path.resolve(path.dirname(filePath), value.replace('file:', '')); + const key = path.resolve(modulePath, OH_PACKAGE_JSON5); + const target = ohPkgContentMap.get(key); + if (target) { + moduleMap.set(name, new ModulePath(modulePath, target.main ? + path.resolve(modulePath, target.main as string) : '')); + } + }); + }) + return moduleMap; + } + + public static getFileLanguage(file: string, fileTags?: Map): Language { + if (fileTags && fileTags.has(file)) { + return fileTags.get(file) as Language; + } + const extension = path.extname(file).toLowerCase(); + switch (extension) { + case '.ts': + return Language.TYPESCRIPT; + case '.ets': + return Language.ARKTS1_1; + default: + return Language.UNKNOWN; + } + } +} + +export class ModulePath { + path: string; + main: string; + + constructor(path: string, main: string) { + this.path = transfer2UnixPath(path); + this.main = transfer2UnixPath(main); + } +} + +export function getFileRecursively(srcDir: string, fileName: string, visited: Set = new Set()): string { + let res = ''; + if (!fs.existsSync(srcDir) || !fs.statSync(srcDir).isDirectory()) { + logger.warn(`Input directory ${srcDir} is not exist`); + return res; + } + + const filesUnderThisDir = fs.readdirSync(srcDir, { withFileTypes: true }); + const realSrc = fs.realpathSync(srcDir) + if (visited.has(realSrc)) { + return res; + } + visited.add(realSrc); + + filesUnderThisDir.forEach(file => { + if (res !== '') { + return res; + } + if (file.name === fileName) { + res = path.resolve(srcDir, file.name); + return res; + } + const tmpDir = path.resolve(srcDir, '../'); + res = getFileRecursively(tmpDir, fileName, visited); + }); + return res; +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/utils/SparseBitVector.ts b/ets2panda/linter/arkanalyzer/src/utils/SparseBitVector.ts new file mode 100644 index 0000000000..ec36ed6ee8 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/utils/SparseBitVector.ts @@ -0,0 +1,544 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * SparseBitVector is a LLVM-interfaces-like data structure designed to efficiently + * represent and manipulate large sets of integers where the majority of the elements + * are unset (i.e., sparse). It is particularly useful in scenarios where memory efficiency + * is critical, and the set of integers contains large gaps between set bits. + * + * The SparseBitVector is implemented as a collection of SparseBitVectorElement objects, + * where each element represents a fixed-size chunk of the bit vector. This allows the + * structure to only allocate memory for the portions of the bit vector that contain + * set bits, significantly reducing memory usage for sparse data. + * + * Key Features: + * - **Unordered**: We implement it as unordered rather than LLVM's for performance reason. + * - **Sparse Storage**: Only stores the indices of set bits, making it memory-efficient + * for sparse datasets. + * - **Efficient Operations**: Supports fast bitwise operations such as union and intersection + * - **Iterable**: Provides an iterator to traverse all set bits in stored order. + * - **Dynamic Resizing**: Automatically adjusts its internal structure as bits are set + * or reset. + * + * Perforceman VS Array + * - **Random Store** 2.5:1 + * - **Continuous Store** 1:1 + * - **Random Test** 1:6 + * - **Continuous Test** 1:1 + * - **Random Iterator** 4:1 + * - **Continuous Iterator** 2:1 + * + * The SparseBitVector is parameterized by `ElementSize`, which defines the size of each + * chunk (element) in the bit vector and MUST be times of 32. This allows for customization + * based on the expected sparsity and performance requirements. + * + */ + +export type Word = Uint16Array; +const BITWORD_SIZE = 16; // bits of a Word +const DEFAULT_SIZE = 64; +class SparseBitVectorElement { + private ELEMENT_SIZE; // bits of element. Default as 128 + private BITWORDS_NUM; // number of words + private bits: Word; + + constructor(elementSize: number = DEFAULT_SIZE) { + this.ELEMENT_SIZE = elementSize; + this.BITWORDS_NUM = Math.ceil(this.ELEMENT_SIZE / BITWORD_SIZE); + this.bits = new Uint16Array(this.BITWORDS_NUM); + } + + word(idx: number): number { + return this.bits[idx]; + } + + clone(): Word { + return new Uint16Array(this.bits); + } + + get elementSize(): number { + return this.ELEMENT_SIZE; + } + + get bitWordNum(): number { + return this.BITWORDS_NUM; + } + + // Check if the element is empty (all bits are zero) + isEmpty(): boolean { + return this.isZero(); + } + + // Set a bit at the given index + set(bitIdx: number): void { + const wordIndex = Math.floor(bitIdx / BITWORD_SIZE); + const bitOffset = bitIdx % BITWORD_SIZE; + this.bits[wordIndex] |= 1 << bitOffset; + } + + setWord(word: Word): void { + this.bits = word; + } + + // Reset a bit at the given index + reset(bitIdx: number): void { + const wordIndex = Math.floor(bitIdx / BITWORD_SIZE); + const bitOffset = bitIdx % BITWORD_SIZE; + this.bits[wordIndex] &= ~(1 << bitOffset); + } + + // Test if a bit is set + test(bitIdx: number): boolean { + const wordIndex = Math.floor(bitIdx / BITWORD_SIZE); + const bitOffset = bitIdx % BITWORD_SIZE; + return (this.bits[wordIndex] & (1 << bitOffset)) !== 0; + } + + // Set if not existing, else return + test_and_set(bitIdx: number): boolean { + let old = this.test(bitIdx); + if (!old) { + this.set(bitIdx); + return true; + } + return false; + } + + // Count the number of set bits in this element + count(): number { + let numBits = 0; + this.bits.forEach((word) => { + numBits += this.countBits(word); + }); + return numBits; + } + + // Find the index of the first set bit in this element + findFirst(): number { + for (let i = 0; i < this.bits.length; i++) { + if (this.bits[i] !== 0) { + return i * BITWORD_SIZE + this.countTrailingZeros(this.bits[i]); + } + } + return -1; // No bits are set + } + + // Find the next set bit after the given index + findNext(bitIdx: number): number { + bitIdx++; + let wordIndex = Math.floor(bitIdx / BITWORD_SIZE); + let bitOffset = bitIdx % BITWORD_SIZE; + + // Check the current word + // Mask off previous bits + let word = this.bits[wordIndex] & (~0 << bitOffset); + if (word !== 0) { + return wordIndex * BITWORD_SIZE + this.countTrailingZeros(word); + } + + // Check subsequent words + for (let i = wordIndex + 1; i < this.bits.length; i++) { + if (this.bits[i] !== 0) { + return i * BITWORD_SIZE + this.countTrailingZeros(this.bits[i]); + } + } + + return -1; // No more bits are set + } + + // Comparison + equals(rhs: SparseBitVectorElement): boolean { + for (let i = 0; i < this.BITWORDS_NUM; i++) { + if (this.bits[i] !== rhs.word(i)) { + return false; + } + } + + return true; + } + + // Union this element with another element and return true if this one changed + unionWith(other: SparseBitVectorElement): boolean { + let changed = false; + for (let i = 0; i < this.bits.length; i++) { + const oldWord = changed ? 0 : this.bits[i]; + this.bits[i] |= other.bits[i]; + if (!changed && oldWord !== this.bits[i]) { + changed = true; + } + } + return changed; + } + + // Intersect this element with another element and return true if this one changed. + intersectWith(other: SparseBitVectorElement): boolean { + let changed = false; + for (let i = 0; i < this.bits.length; i++) { + const oldWord = changed ? 0 : this.bits[i]; + this.bits[i] &= other.bits[i]; + if (!changed && oldWord !== this.bits[i]) { + changed = true; + } + } + return changed; + } + + // Subtract another SparseBitVectorElement from this one. + subtractWith(rhs: SparseBitVectorElement): boolean { + let changed = false; + // Perform subtraction: this = this & ~rhs + for (let i = 0; i < this.bits.length; i++) { + const oldWord = this.bits[i]; + this.bits[i] &= ~rhs.bits[i]; + + // If any bit was changed, mark as changed + if (this.bits[i] !== oldWord) { + changed = true; + } + } + + return changed; + } + + // Count the number of set bits in a word + countBitsV2(word: number): number { + let count = 0; + while (word !== 0) { + word &= word - 1; + count++; + } + return count; + } + + // Count the number of set bits in a word + countBits(word: number): number { + // assume the value is treated as a unsigned integer + let v = word; + + // Step 1: Pairwise addition of bits + v = v - ((v >> 1) & 0x55555555); + // Step 2: Group bits into 4-bit chunks and add + v = (v & 0x33333333) + ((v >> 2) & 0x33333333); + // Step 3: Group bits into 8-bit chunks and add + v = (v + (v >> 4)) & 0xf0f0f0f; + // Step 4: Multiply by a magic number to sum all 8-bit chunks into the highest byte + v = (v * 0x1010101) >> 24; + + return v; + } + + isZero(): boolean { + for (let i = 0; i < this.BITWORDS_NUM; i++) { + if (this.bits[i] !== 0) { + return false; + } + } + return true; + } + + // Count trailing zeros in a word + private countTrailingZeros(word: number): number { + if (word === 0) { + return BITWORD_SIZE; + } + + if ((word & 1) !== 0) { + return 0; + } + + let zeroBits = 0; + let shift = BITWORD_SIZE / 2; // Start with half the bit width + let mask = (1 << shift) - 1; // Mask for the lower half + + while (shift > 0) { + if ((word & mask) === 0) { + word >>= shift; + zeroBits |= Number(shift); + } + shift >>= 1; + mask >>= shift; + } + + return zeroBits; + } +} + +export class SparseBitVector { + private ELEMENT_SIZE: number; + // Unordered storage of elements. + // key is actually the element index (normally it is in element) + private elements: Map = new Map(); + + constructor(elementsSize: number = DEFAULT_SIZE) { + this.ELEMENT_SIZE = elementsSize; + } + + get elementSize(): number { + return this.ELEMENT_SIZE; + } + + get elems(): Map { + return this.elements; + } + + // Set a bit at the given index + set(bitIdx: number): void { + const elementIndex = Math.floor(bitIdx / this.ELEMENT_SIZE); + let element = this.elements.get(elementIndex); + if (!element) { + element = new SparseBitVectorElement(this.ELEMENT_SIZE); + this.elements.set(elementIndex, element); + } + element.set(bitIdx % this.ELEMENT_SIZE); + } + + // Test if a bit is set + test(bitIdx: number): boolean { + const elementIndex = Math.floor(bitIdx / this.ELEMENT_SIZE); + const element = this.elements.get(elementIndex); + return element ? element.test(bitIdx % this.ELEMENT_SIZE) : false; + } + + // Set a bit if not existing. Else return + testAndSet(bitIdx: number): boolean { + let old = this.test(bitIdx); + if (!old) { + this.set(bitIdx); + return true; + } + return false; + } + + // Reset a bit at the given index + reset(bitIdx: number): void { + const elementIndex = Math.floor(bitIdx / this.ELEMENT_SIZE); + let element = this.elements.get(elementIndex); + if (element) { + element.reset(bitIdx % this.ELEMENT_SIZE); + if (element.isEmpty()) { + this.elements.delete(elementIndex); + } + } + } + + // Clear all elements + clear(): void { + this.elements.clear(); + } + + // Clone, return a deep copied object + clone(): SparseBitVector { + const newVector = new SparseBitVector(this.elementSize); + for (const [idx, element] of this.elements) { + const newElement = new SparseBitVectorElement(this.elementSize); + newElement.setWord(element.clone()); + + newVector.elems.set(idx, newElement); + } + + return newVector; + } + + // Find the first set bit in the vector + findFirst(): number { + if (this.elements.size === 0) return -1; + const firstElement = this.elements.entries().next().value; + if (firstElement) { + const firstBit = firstElement[1].findFirst(); + return firstElement[0] * this.ELEMENT_SIZE + firstBit; + } else { + return -1; + } + } + + // Count the number of set bits in the vector + count(): number { + let count = 0; + this.elements.forEach((elem, _) => { + count += elem.count(); + }); + return count; + } + + // Check if the vector is empty + isEmpty(): boolean { + return this.elements.size === 0; + } + + [Symbol.iterator](): IterableIterator { + let iter = this.elements.entries(); + let next = iter.next(); + const elementSize = this.ELEMENT_SIZE; + let element = next.value; + if (!element) { + return { + next() { + return { value: undefined, done: true }; + }, + [Symbol.iterator]() { + return this; // Make the iterator itself iterable + }, + }; + } + let bitIndex = element[1].findFirst(); + return { + next(): IteratorResult { + if (element) { + let v = element[0] * elementSize + bitIndex; + bitIndex = element[1].findNext(bitIndex); + if (bitIndex === -1) { + next = iter.next(); + element = next.value; + if (element) { + bitIndex = element[1].findFirst(); + } + } + return { value: v, done: false }; + } + return { value: undefined, done: true }; + }, + [Symbol.iterator]() { + return this; // Make the iterator itself iterable + }, + }; + } + + /** + * Check if this SparseBitVector is equal to another SparseBitVector. + */ + equals(rhs: SparseBitVector): boolean { + if (this.ELEMENT_SIZE !== rhs.ELEMENT_SIZE || this.elems.size !== rhs.elems.size) { + return false; + } + + let rhsElems = rhs.elems; + for (let p of this.elements) { + let rhsElem = rhsElems.get(p[0]); + if (!rhsElem) { + return false; + } + if (!rhsElem.equals(p[1])) { + return false; + } + } + return true; + } + + /** + * Perform a union operation with another SparseBitVector. + * Returns True if this vector was changed, false otherwise. + */ + unionWith(rhs: SparseBitVector): boolean { + if (this.equals(rhs) || rhs.elems.size === 0) { + return false; + } + + let changed = false; + let newElems = new Map(); + for (let p of rhs.elems) { + let elem = this.elements.get(p[0]); + if (elem) { + changed = elem!.unionWith(p[1]) || changed; + } else { + newElems.set(p[0], p[1]); + } + } + + if (newElems.size > 0) { + newElems.forEach((v, k) => this.elements.set(k, v)); + changed = true; + } + + return changed; + } + + /** + * Perform an intersection operation with another SparseBitVector. + * Returns True if this vector was changed, false otherwise. + */ + intersectWith(rhs: SparseBitVector): boolean { + if (this.equals(rhs) || rhs.elems.size === 0) { + return false; + } + + let changed = false; + // If either vector is empty, the result is empty + if (this.elements.size === 0 || rhs.elems.size === 0) { + if (this.elements.size > 0) { + this.elements = new Map(); + changed = true; + } + return changed; + } + + let needDeleteIdx: Set = new Set(); + for (let p of this.elems) { + let elem = rhs.elems.get(p[0]); + if (elem) { + changed = p[1].intersectWith(elem) || changed; + if (changed && p[1].isZero()) { + needDeleteIdx.add(p[0]); + } + } else { + needDeleteIdx.add(p[0]); + } + } + + if (needDeleteIdx.size > 0) { + needDeleteIdx.forEach((idx) => this.elements.delete(idx)); + changed = true; + } + + return changed; + } + + /** + * Subtract another SparseBitVector from this one. + * This operation modifies the current SparseBitVector in place. + * Return True if the current SparseBitVector was modified, false otherwise. + */ + subtractWith(rhs: SparseBitVector): boolean { + if (this.elementSize !== rhs.elementSize || this.isEmpty() || rhs.isEmpty()) { + return false; + } + + let needDeleteIdx: Set = new Set(); + let changed = false; + for (const [elementIndex, element] of this.elements) { + const rhsElement = rhs.elements.get(elementIndex); + + if (rhsElement) { + changed = element.subtractWith(rhsElement) || changed; + if (element.isEmpty()) { + needDeleteIdx.add(elementIndex); + } + } + } + + if (needDeleteIdx.size > 0) { + needDeleteIdx.forEach((idx) => this.elements.delete(idx)); + changed = true; + } + + return changed; + } + + // Dump as string + toString(): string { + let ar = [...this]; + return ar.toString(); + } +} diff --git a/ets2panda/linter/arkanalyzer/src/utils/callGraphUtils.ts b/ets2panda/linter/arkanalyzer/src/utils/callGraphUtils.ts new file mode 100644 index 0000000000..d37b14203c --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/utils/callGraphUtils.ts @@ -0,0 +1,224 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Scene } from '../Scene'; +import { ArkClass } from '../core/model/ArkClass'; +import { ArkMethod } from '../core/model/ArkMethod'; +import { ClassSignature, MethodSignature } from '../core/model/ArkSignature'; +import Logger, { LOG_MODULE_TYPE } from './logger'; +import { ModelUtils } from '../core/common/ModelUtils'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'callGraphUtils'); + +export class MethodSignatureManager { + private _workList: MethodSignature[] = []; + private _processedList: MethodSignature[] = []; + + get workList(): MethodSignature[] { + return this._workList; + } + + set workList(list: MethodSignature[]) { + this._workList = list; + } + + get processedList(): MethodSignature[] { + return this._processedList; + } + + set processedList(list: MethodSignature[]) { + this._processedList = list; + } + + public findInWorkList(signature: MethodSignature): MethodSignature | undefined { + return this.workList.find(item => item === signature); + } + + public findInProcessedList(signature: MethodSignature): boolean { + let result = this.processedList.find(item => item.toString() === signature.toString()); + return typeof result !== "undefined"; + } + + public addToWorkList(signature: MethodSignature): void { + if (!isItemRegistered( + signature, this.workList, + (a, b) => + a.toString() === b.toString() + )) { + this.workList.push(signature); + } + } + + public addToProcessedList(signature: MethodSignature): void { + if (!isItemRegistered( + signature, this.processedList, + (a, b) => + a === b + )) { + this.processedList.push(signature); + } + } + + public removeFromWorkList(signature: MethodSignature): void { + this.workList = this.workList.filter(item => item !== signature); + } + + public removeFromProcessedList(signature: MethodSignature): void { + this.processedList = this.processedList.filter(item => item.toString() !== signature.toString()); + } +} + +export class SceneManager { + private _scene!: Scene; + + get scene(): Scene { + return this._scene; + } + + set scene(value: Scene) { + this._scene = value; + } + + public getMethod(method: MethodSignature): ArkMethod | null { + let targetMethod = this._scene.getMethod(method); + if (targetMethod != null) { + return targetMethod; + } + // 支持SDK调用解析 + let file = this._scene.getFile(method.getDeclaringClassSignature().getDeclaringFileSignature()); + if (file) { + const methods = ModelUtils.getAllMethodsInFile(file); + for (let methodUnderFile of methods) { + if (method.toString() === methodUnderFile.getSignature().toString()) { + return methodUnderFile; + } + } + } + return targetMethod; + } + + public getClass(arkClass: ClassSignature): ArkClass | null { + if (typeof arkClass.getClassName() === "undefined") + return null + let classInstance = this._scene.getClass(arkClass) + if (classInstance != null) { + return classInstance; + } + let sdkOrTargetProjectFile = this._scene.getFile(arkClass.getDeclaringFileSignature()); + // TODO: support get sdk class, targetProject class waiting to be supported + if (sdkOrTargetProjectFile != null) { + for (let classUnderFile of ModelUtils.getAllClassesInFile(sdkOrTargetProjectFile)) { + if (classUnderFile.getSignature().toString() === arkClass.toString()) { + return classUnderFile + } + } + } + return classInstance + } + + public getExtendedClasses(arkClass: ClassSignature): ArkClass[] { + let sourceClass = this.getClass(arkClass) + let classList = [sourceClass] // 待处理类 + let extendedClasses: ArkClass[] = [] // 已经处理的类 + + while (classList.length > 0) { + let tempClass = classList.shift() + if (tempClass == null) + continue + let firstLevelSubclasses: ArkClass[] = Array.from(tempClass.getExtendedClasses().values()); + + if (!firstLevelSubclasses) { + continue; + } + + for (let subclass of firstLevelSubclasses) { + if (!isItemRegistered( + subclass, extendedClasses, + (a, b) => + a.getSignature().toString() === b.getSignature().toString() + )) { + // 子类未处理,加入到classList + classList.push(subclass) + } + } + + // 当前类处理完毕,标记为已处理 + if (!isItemRegistered( + tempClass, extendedClasses, + (a, b) => + a.getSignature().toString() === b.getSignature().toString() + )) { + extendedClasses.push(tempClass) + } + } + return extendedClasses + } +} + +export function isItemRegistered(item: T, array: T[], compareFunc: (a: T, b: T) => boolean): boolean { + for (let tempItem of array) { + if (compareFunc(tempItem, item)) { + return true; + } + } + return false; +} + +export function splitStringWithRegex(input: string): string[] { + // 正则表达式匹配 "a.b.c()" 并捕获 "a" "b" "c" + const regex = /^(\w+)\.(\w+)\.(\w+)\(\)$/; + const match = input.match(regex); + + if (match) { + // 返回捕获的部分,忽略整个匹配结果 + return match.slice(1); + } else { + // 如果输入不匹配,返回空数组 + return []; + } +} + +export function printCallGraphDetails(methods: Set, calls: Map, rootDir: string): void { + // 打印 Methods + logger.info("Call Graph:\n") + logger.info('\tMethods:'); + methods.forEach(method => { + logger.info(`\t\t${method}`); + }); + + // 打印 Calls + logger.info('\tCalls:'); + const arrow = '->'; + calls.forEach((calledMethods, method) => { + // 对于每个调用源,只打印一次调用源和第一个目标方法 + const modifiedMethodName = `<${method}`; + logger.info(`\t\t${modifiedMethodName.padEnd(4)} ${arrow}`); + + for (let i = 0; i < calledMethods.length; i++) { + const modifiedCalledMethod = `\t\t<${calledMethods[i]}`; + logger.info(`\t\t${modifiedCalledMethod}`); + } + logger.info("\n") + }); +} + +export function extractLastBracketContent(input: string): string { + // 正则表达式匹配最后一个尖括号内的内容,直到遇到左圆括号 + const match = input.match(/<([^<>]*)\(\)>$/); + if (match && match[1]) { + return match[1].trim(); + } + return ""; +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/utils/crypto_utils.ts b/ets2panda/linter/arkanalyzer/src/utils/crypto_utils.ts new file mode 100644 index 0000000000..39a64826f0 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/utils/crypto_utils.ts @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as crypto from 'crypto'; + +export class CryptoUtils { + + public static sha256(content: string): string { + return this.hash(content, 'sha256'); + } + + public static hash(content: string, algorithm: string): string { + return crypto.createHash(algorithm).update(content).digest('base64url'); + } + + public static hashcode(content: string): number { + let h = 0; + for (let i = 0; i < content.length; i++) { + h = Math.imul(31, h) + content.charCodeAt(i) | 0; + } + return h; + } +} diff --git a/ets2panda/linter/arkanalyzer/src/utils/entryMethodUtils.ts b/ets2panda/linter/arkanalyzer/src/utils/entryMethodUtils.ts new file mode 100644 index 0000000000..c9bfa8e0d6 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/utils/entryMethodUtils.ts @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Scene } from '../Scene'; +import { ArkMethod } from '../core/model/ArkMethod'; +import { Stmt } from '../core/base/Stmt'; +import { FunctionType } from '../core/base/Type'; + +export const LIFECYCLE_METHOD_NAME: string[] = [ + 'onCreate', // 组件实例创建 + 'onDestroy', // 组件实例销毁 + 'onWindowStageCreate', // 窗口创建 + 'onWindowStageDestroy', // 窗口销毁 + 'onForeground', // 应用进入前台 + 'onBackground', // 应用进入后台 + 'onBackup', // 应用数据备份 + 'onRestore', // 应用数据恢复 + 'onContinue', + 'onNewWant', + 'onDump', + 'onSaveState', + 'onShare', + 'onPrepareToTerminate', + 'onBackPressed', + 'onSessionCreate', + 'onSessionDestory', + 'onAddForm', + 'onCastToNormalForm', + 'onUpdateForm', + 'onChangeFormVisibility', + 'onFormEvent', + 'onRemoveForm', + 'onConfigurationUpdate', + 'onAcquireFormState', + 'onWindowStageWillDestroy', + ]; +export const CALLBACK_METHOD_NAME: string[] = [ + "onClick", // 点击事件,当用户点击组件时触发 + "onTouch", // 触摸事件,当手指在组件上按下、滑动、抬起时触发 + "onAppear", // 组件挂载显示时触发 + "onDisAppear", // 组件卸载消失时触发 + "onDragStart", // 拖拽开始事件,当组件被长按后开始拖拽时触发 + "onDragEnter", // 拖拽进入组件范围时触发 + "onDragMove", // 拖拽在组件范围内移动时触发 + "onDragLeave", // 拖拽离开组件范围内时触发 + "onDrop", // 拖拽释放目标,当在本组件范围内停止拖拽行为时触发 + "onKeyEvent", // 按键事件,当组件获焦后,按键动作触发 + "onFocus", // 焦点事件,当组件获取焦点时触发 + "onBlur", // 当组件失去焦点时触发的回调 + "onHover", // 鼠标悬浮事件,鼠标进入或退出组件时触发 + "onMouse", // 鼠标事件,当鼠标按键点击或在组件上移动时触发 + "onAreaChange", // 组件区域变化事件,组件尺寸、位置变化时触发 + "onVisibleAreaChange", // 组件可见区域变化事件,组件在屏幕中的显示区域面积变化时触发 + ]; + +export const COMPONENT_LIFECYCLE_METHOD_NAME: string[] = [ + 'build', + 'aboutToAppear', + 'aboutToDisappear', + 'aboutToReuse', + 'aboutToRecycle', + 'onWillApplyTheme', + 'onLayout', + 'onPlaceChildren', + 'onMeasure', + 'onMeasureSize', + 'onPageShow', + 'onPageHide', + 'onFormRecycle', + 'onFormRecover', + 'onBackPress', + 'pageTransition', + 'onDidBuild' +]; + +export interface AbilityMessage { + srcEntry: string; + name: string; + srcEntrance: string; +} + +export function getCallbackMethodFromStmt(stmt: Stmt, scene: Scene): ArkMethod | null { + const invokeExpr = stmt.getInvokeExpr(); + if (invokeExpr === undefined || + invokeExpr.getMethodSignature().getDeclaringClassSignature().getClassName() !== '' || + !CALLBACK_METHOD_NAME.includes(invokeExpr.getMethodSignature().getMethodSubSignature().getMethodName())) { + return null; + } + + for (const arg of invokeExpr.getArgs()) { + const argType = arg.getType(); + if (argType instanceof FunctionType) { + const cbMethod = scene.getMethod(argType.getMethodSignature()); + if (cbMethod) { + return cbMethod; + } + } + } + return null; +} + +export function addCfg2Stmt(method: ArkMethod) { + const cfg = method.getCfg(); + if (cfg) { + for (const block of cfg.getBlocks()) { + for (const stmt of block.getStmts()) { + stmt.setCfg(cfg); + } + } + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/utils/getAllFiles.ts b/ets2panda/linter/arkanalyzer/src/utils/getAllFiles.ts new file mode 100644 index 0000000000..17823aea70 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/utils/getAllFiles.ts @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import fs from 'fs'; +import path from 'path'; +import Logger, { LOG_MODULE_TYPE } from './logger'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'getAllFiles'); +/** + * 从指定目录中提取指定后缀名的所有文件 + * @param srcPath string 要提取文件的项目入口,相对或绝对路径都可 + * @param exts string[] 要提取的文件扩展名数组,每个扩展名需以点开头 + * @param filenameArr string[] 用来存放提取出的文件的原始路径的数组,可不传,默认为空数组 + * @param visited: Set 用来存放已经访问过的路径,避免递归栈溢出,可不传,默认为空数组 + * @return string[] 提取出的文件的原始路径数组 + */ +export function getAllFiles( + srcPath: string, + exts: string[], + ignore: string[] = [], + filenameArr: string[] = [], + visited: Set = new Set() +): string[] { + let ignoreFiles: Set = new Set(ignore); + // 如果源目录不存在,直接结束程序 + if (!fs.existsSync(srcPath)) { + logger.error(`Input directory ${srcPath} is not exist, please check!`); + return filenameArr; + } + + // 获取src的绝对路径 + const realSrc = fs.realpathSync(srcPath); + if (visited.has(realSrc)) { + return filenameArr; + } + visited.add(realSrc); + + // 遍历src,判断文件类型 + fs.readdirSync(realSrc).forEach(filename => { + if (ignoreFiles.has(filename)) { + return; + } + // 拼接文件的绝对路径 + const realFile = path.resolve(realSrc, filename); + + //TODO: 增加排除文件后缀和目录 + + // 如果是目录,递归提取 + if (fs.statSync(realFile).isDirectory()) { + getAllFiles(realFile, exts, ignore, filenameArr, visited); + } else { + // 如果是文件,则判断其扩展名是否在给定的扩展名数组中 + if (exts.includes(path.extname(filename))) { + filenameArr.push(realFile); + } + } + }) + return filenameArr; +} diff --git a/ets2panda/linter/arkanalyzer/src/utils/json5parser.ts b/ets2panda/linter/arkanalyzer/src/utils/json5parser.ts new file mode 100644 index 0000000000..7ca3f86354 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/utils/json5parser.ts @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as ts from 'ohos-typescript'; +import * as fs from 'fs'; +import Logger, { LOG_MODULE_TYPE } from './logger'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'json5parser'); + +export function fetchDependenciesFromFile(filePath: string): { [k: string]: unknown } { + if (!fs.existsSync(filePath)) { + return {}; + } + let configurationsText: string; + try { + configurationsText = fs.readFileSync(filePath, 'utf-8'); + } catch (error) { + logger.error(`Error reading file: ${error}`); + return {}; + } + const file = parseJsonText(configurationsText); + return file; +} + +export function parseJsonText(text: string): { [k: string]: unknown } { + let file; + try { + file = ts.parseJsonText('', text); + } catch (error) { + logger.error(`Error parsing file: ${error}`); + return {}; + } + const rootObjectLiteralExpression = getRootObjectLiteral(file); + if (!rootObjectLiteralExpression) { + logger.error('The JSON5 file format is incorrect, rootObjectLiteralExpression is null.'); + return {}; + } + return parseObjectLiteralExpression(rootObjectLiteralExpression, file); +} + +function getRootObjectLiteral(file: ts.JsonSourceFile): ts.ObjectLiteralExpression | undefined { + if (!file || !file.statements || !file.statements.length) { + logger.error('The JSON5 file format is incorrect, the root node statements is empty.'); + return undefined; + } + const expressionStatement = file.statements[0]; + if (expressionStatement.kind !== ts.SyntaxKind.ExpressionStatement) { + logger.error(`The JSON5 file format is incorrect, the first child node is not ExpressionStatement. kind: ${expressionStatement.kind}`); + return undefined; + } + const rootObjectLiteralExpression = (expressionStatement as ts.ExpressionStatement).expression; + if (!rootObjectLiteralExpression) { + logger.error('The JSON5 file format is incorrect, the first child node is empty.') + return undefined; + } + + if (rootObjectLiteralExpression.kind === ts.SyntaxKind.ObjectLiteralExpression) { + return rootObjectLiteralExpression as ts.ObjectLiteralExpression; + } + + if (rootObjectLiteralExpression.kind === ts.SyntaxKind.ArrayLiteralExpression) { + const elements = (rootObjectLiteralExpression as ts.ArrayLiteralExpression).elements; + if (elements && elements.length && elements[0].kind === ts.SyntaxKind.ObjectLiteralExpression) { + return elements[0] as ts.ObjectLiteralExpression; + } + logger.error('The JSON5 file format is incorrect, the node ArrayLiteralExpression first element is not ObjectLiteralExpression.'); + } + logger.error('The JSON5 file format is incorrect.'); + return undefined; +} + +function parsePropertyInitializer(node: ts.Expression, file: ts.JsonSourceFile): unknown { + if (node.kind === ts.SyntaxKind.StringLiteral) { + return (node as ts.StringLiteral).text; + } else if (node.kind === ts.SyntaxKind.NumericLiteral) { + return (node as ts.NumericLiteral).text; + } else if (node.kind === ts.SyntaxKind.PrefixUnaryExpression) { + return (node as ts.PrefixUnaryExpression).getText(file); + } else if (node.kind === ts.SyntaxKind.ArrayLiteralExpression) { + return parseArrayLiteral(node, file); + } else if (node.kind === ts.SyntaxKind.ObjectLiteralExpression) { + return parseObjectLiteralExpression(node as ts.ObjectLiteralExpression, file); + } else if (node.kind === ts.SyntaxKind.TrueKeyword) { + return true; + } else if (node.kind === ts.SyntaxKind.FalseKeyword) { + return false; + } + return undefined; +} + +function parseArrayLiteral(node: ts.Expression, file: ts.JsonSourceFile) { + const res: unknown[] = []; + (node as ts.ArrayLiteralExpression).elements.forEach(n => { + res.push(parsePropertyInitializer(n, file)); + }) + return res; +} + +function parseObjectLiteralExpression(ObjectLiteralExpression: ts.ObjectLiteralExpression, file: ts.JsonSourceFile): { [k: string]: unknown } { + const res: { [k: string]: unknown } = {}; + ObjectLiteralExpression.properties.forEach(node => { + const propNode = node as ts.PropertyAssignment; + const key = (propNode.name as ts.Identifier).text; + const value = parsePropertyInitializer(propNode.initializer, file); + res[key] = value; + }) + return res; +} + diff --git a/ets2panda/linter/arkanalyzer/src/utils/logger.ts b/ets2panda/linter/arkanalyzer/src/utils/logger.ts new file mode 100644 index 0000000000..904ffc8a55 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/utils/logger.ts @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { Logger } from 'log4js'; +import { configure, getLogger } from 'log4js'; + +export enum LOG_LEVEL { + ERROR = 'ERROR', + WARN = 'WARN', + INFO = 'INFO', + DEBUG = 'DEBUG', + TRACE = 'TRACE', +} + +export enum LOG_MODULE_TYPE { + DEFAULT = 'default', + ARKANALYZER = 'ArkAnalyzer', + HOMECHECK = 'HomeCheck', + TOOL = 'Tool', +} + +export default class ConsoleLogger { + public static configure(logFilePath: string, + arkanalyzer_level: LOG_LEVEL = LOG_LEVEL.ERROR, + tool_level: LOG_LEVEL = LOG_LEVEL.INFO, + use_console: boolean = false): void { + let appendersTypes: string[] = []; + if (logFilePath) { + appendersTypes.push('file'); + } + if (!appendersTypes.length || use_console) { + appendersTypes.push('console'); + } + configure({ + appenders: { + file: { + type: 'fileSync', + filename: `${logFilePath}`, + maxLogSize: 5 * 1024 * 1024, + backups: 5, + compress: true, + encoding: 'utf-8', + layout: { + type: 'pattern', + pattern: '[%d] [%p] [%z] [%X{module}] - [%X{tag}] %m', + }, + }, + console: { + type: 'console', + layout: { + type: 'pattern', + pattern: '[%d] [%p] [%z] [%X{module}] - [%X{tag}] %m', + }, + }, + }, + categories: { + default: { + appenders: ['console'], + level: 'info', + enableCallStack: false, + }, + ArkAnalyzer: { + appenders: appendersTypes, + level: arkanalyzer_level, + enableCallStack: true, + }, + Tool: { + appenders: appendersTypes, + level: tool_level, + enableCallStack: true, + }, + }, + }); + } + + public static getLogger(log_type: LOG_MODULE_TYPE, tag: string = '-'): Logger { + let logger; + if (log_type === LOG_MODULE_TYPE.DEFAULT || log_type === LOG_MODULE_TYPE.ARKANALYZER) { + logger = getLogger(log_type); + } else { + logger = getLogger(LOG_MODULE_TYPE.TOOL); + } + logger.addContext('module', log_type); + logger.addContext('tag', tag); + return logger; + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/utils/pathTransfer.ts b/ets2panda/linter/arkanalyzer/src/utils/pathTransfer.ts new file mode 100644 index 0000000000..7a491cabb0 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/utils/pathTransfer.ts @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import path from 'path'; + +export function transfer2UnixPath(path2Do: string) { + return path.posix.join(...path2Do.split(/\\/)); +} + +export function getArkAnalyzerModulePath(moduleName: string): string | null { + try { + return path.dirname(path.dirname(require.resolve(moduleName))); + } catch (e) { + return null; + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/tsconfig.json b/ets2panda/linter/arkanalyzer/tsconfig.json new file mode 100644 index 0000000000..4f03c1a567 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/tsconfig.json @@ -0,0 +1,12 @@ +{ + "extends": "./tsconfig.main.json", + "include": [ + "index.ts", + "src/**/*", + "tests/unit/**/*", + "tests/HeapDumpTest.ts" + ], + "compilerOptions": { + "outDir": "./out" + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/tsconfig.main.json b/ets2panda/linter/arkanalyzer/tsconfig.main.json new file mode 100644 index 0000000000..c96613a134 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/tsconfig.main.json @@ -0,0 +1,101 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig to read more about this file */ + /* Projects */ + // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ + //"composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ + // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ + // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ + // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ + /* Language and Environment */ + "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "jsx": "preserve", /* Specify what JSX code is generated. */ + // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ + // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ + // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ + // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ + // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ + // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + /* Modules */ + "module": "commonjs", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ + // "types": [], /* Specify type package names to be included without being referenced in a source file. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ + // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ + // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ + // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ + // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ + // "resolveJsonModule": true, /* Enable importing .json files. */ + // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ + // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ + /* JavaScript Support */ + // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ + // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ + /* Emit */ + "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + "declarationMap": true, /* Create sourcemaps for d.ts files. */ + // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ + // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ + // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ + //"outFile": "lib", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ + // "removeComments": true, /* Disable emitting comments. */ + // "noEmit": true, /* Disable emitting files from a compilation. */ + // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ + // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ + // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ + // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ + // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ + // "newLine": "crlf", /* Set the newline character for emitting files. */ + // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ + // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ + // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ + // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ + // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ + // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ + /* Interop Constraints */ + // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ + // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ + // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ + // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + "strictPropertyInitialization": true, + // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ + // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ + // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ + // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ + // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ + // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ + // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ + "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ + // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ + // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ + // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ + // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ + // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ + // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ + // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ + // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ + // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ + /* Completeness */ + // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ + "skipLibCheck": true /* Skip type checking all .d.ts files. */ + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/tsconfig.prod.json b/ets2panda/linter/arkanalyzer/tsconfig.prod.json new file mode 100644 index 0000000000..2be4cb427c --- /dev/null +++ b/ets2panda/linter/arkanalyzer/tsconfig.prod.json @@ -0,0 +1,9 @@ +{ + "extends": "./tsconfig.main.json", + "include": [ + "src/**/*" + ], + "compilerOptions": { + "outDir": "./lib" + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/typedoc.json b/ets2panda/linter/arkanalyzer/typedoc.json new file mode 100644 index 0000000000..1b08d68d69 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/typedoc.json @@ -0,0 +1,21 @@ +{ + "$schema": "https://typedoc.org/schema.json", + "name": "ArkAnalyzer", + "categoryOrder": [ + "core/base", + "core/base/expr", + "core/base/stmt", + "core/base/type", + "core/base/ref", + "core/model", + "core/graph", + "*" + ], + "entryPoints": [ + "./src/index.ts" + ], + "excludeInternal": true, + "useTsLinkResolution": true, + "out": "docs/api_docs", + "readme": "./README.en.md" +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/vitest.config.ts b/ets2panda/linter/arkanalyzer/vitest.config.ts new file mode 100644 index 0000000000..2ba68acd21 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/vitest.config.ts @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + include: ["tests/unit/**/*.test.ts"], + coverage: { + include: ["src/**"] + } + } +}) \ No newline at end of file diff --git a/ets2panda/linter/build_linter.py b/ets2panda/linter/build_linter.py index 24cf53c3f6..17b58ba3ba 100755 --- a/ets2panda/linter/build_linter.py +++ b/ets2panda/linter/build_linter.py @@ -39,7 +39,7 @@ def run_cmd(cmd, execution_path=None): stdin=subprocess.PIPE, stderr=subprocess.PIPE, cwd=execution_path) - stdout, stderr = proc.communicate(timeout=300) + stdout, stderr = proc.communicate(timeout=600) if proc.returncode != 0: raise Exception(stderr.decode()) @@ -74,6 +74,69 @@ def install_typescript(options): run_cmd(cmd, options.source_path) +def find_files_by_prefix_suffix(directory, prefix, suffix): + matched_files = [] + for filename in os.listdir(directory): + if filename.startswith(prefix) and filename.endswith(suffix): + matched_files.append(os.path.join(directory, filename)) + return sorted(matched_files, key=os.path.getctime, reverse=True) + + +def clean_old_packages(directory, prefix, suffix): + res = True + matched_files = find_files_by_prefix_suffix(directory, prefix, suffix) + if (matched_files): + for file in matched_files: + try: + os.remove(file) + except Exception: + res = False + return res + + +def pack_arkanalyzer(options): + aa_path = os.path.join(options.source_path, 'arkanalyzer') + pack_prefix = 'arkanalyzer-' + pack_suffix = '.tgz' + clean_old_packages(aa_path, pack_prefix, pack_suffix) + + ts_install_cmd = [options.npm, 'install', options.typescript] + compile_cmd = [options.npm, 'run', 'compile'] + pack_cmd = [options.npm, 'pack'] + run_cmd(ts_install_cmd, aa_path) + run_cmd(compile_cmd, aa_path) + run_cmd(pack_cmd, aa_path) + + +def install_homecheck(options): + pack_arkanalyzer(options) + aa_path = os.path.join(options.source_path, 'arkanalyzer') + hc_path = os.path.join(options.source_path, 'homecheck') + aa_pack_prefix = 'arkanalyzer-' + hc_pack_prefix = 'homecheck-' + pack_suffix = '.tgz' + exist_aa_packs = find_files_by_prefix_suffix(aa_path, aa_pack_prefix, pack_suffix) + if (exist_aa_packs): + aa_install_cmd = [options.npm, 'install', exist_aa_packs[0]] + run_cmd(aa_install_cmd, hc_path) + else: + raise Exception('Failed to find arkanalyzer npm package') + + clean_old_packages(hc_path, hc_pack_prefix, pack_suffix) + ts_install_cmd = [options.npm, 'install', '--no-save', options.typescript] + pack_cmd = [options.npm, 'pack'] + compile_cmd = [options.npm, 'run', 'compile'] + run_cmd(ts_install_cmd, hc_path) + run_cmd(compile_cmd, hc_path) + run_cmd(pack_cmd, hc_path) + exist_hc_packs = find_files_by_prefix_suffix(hc_path, hc_pack_prefix, pack_suffix) + if (exist_hc_packs): + hc_install_cmd = [options.npm, 'install', exist_hc_packs[0]] + run_cmd(hc_install_cmd, options.source_path) + else: + raise Exception('Failed to find homecheck npm package') + + def extract(package_path, dest_path, package_name): try: with tarfile.open(package_path, 'r:gz') as tar: @@ -100,6 +163,7 @@ def parse_args(): def main(): options = parse_args() + install_homecheck(options) install_typescript(options) node_modules_path = os.path.join(options.source_path, "node_modules") extract(options.typescript, node_modules_path, "typescript") diff --git a/ets2panda/linter/eslint.config.mjs b/ets2panda/linter/eslint.config.mjs index ab024a62fd..d39b40f91a 100644 --- a/ets2panda/linter/eslint.config.mjs +++ b/ets2panda/linter/eslint.config.mjs @@ -34,7 +34,9 @@ export default tseslint.config( 'third_party/**/*', 'test/**/*', '**/**.json', - '**/**.js' + '**/**.js', + 'arkanalyzer/*', + 'homecheck/*' ] }, { diff --git a/ets2panda/linter/homecheck/LICENSE b/ets2panda/linter/homecheck/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/ets2panda/linter/homecheck/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/ets2panda/linter/homecheck/OAT.xml b/ets2panda/linter/homecheck/OAT.xml new file mode 100644 index 0000000000..e377d607f4 --- /dev/null +++ b/ets2panda/linter/homecheck/OAT.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/ets2panda/linter/homecheck/config/projectConfig.json b/ets2panda/linter/homecheck/config/projectConfig.json new file mode 100644 index 0000000000..55aac136da --- /dev/null +++ b/ets2panda/linter/homecheck/config/projectConfig.json @@ -0,0 +1,23 @@ +{ + "projectName": "TestProject", + "projectPath": "D:\\arkProject", + "logPath": "./HomeCheck.log", + "ohosSdkPath": "D:\\DevEco Studio\\sdk\\default\\openharmony\\ets", + "hmsSdkPath": "D:\\DevEco Studio\\sdk\\default\\hms\\ets", + "checkPath": "", + "sdkVersion": 14, + "fix": "false", + "npmPath": "", + "npmInstallDir": "./", + "reportDir": "./report", + "arkCheckPath": "./", + "product": "default", + "sdksThirdParty": [ + { + "name": "thirdParty", + "path": "./resources/thirdPartyModules", + "moduleName": "" + } + ], + "fileOrFolderToCheck": [ "D:\\arkProject" ] +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/config/ruleConfig.json b/ets2panda/linter/homecheck/config/ruleConfig.json new file mode 100644 index 0000000000..141445e713 --- /dev/null +++ b/ets2panda/linter/homecheck/config/ruleConfig.json @@ -0,0 +1,21 @@ +{ + "files": [ + "**/*.ets", + "**/*.ts" + ], + "ignore": [ + "**/ohosTest/**/*", + "**/node_modules/**/*", + "**/build/**/*", + "**/hvigorfile/**/*", + "**/oh_modules/**/*", + "**/.preview/**/*" + ], + "rules": { + }, + "ruleSet": [ + "plugin:@migration/all" + ], + "overrides": [], + "extRuleSet": [] +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/package.json b/ets2panda/linter/homecheck/package.json new file mode 100644 index 0000000000..0a5b274695 --- /dev/null +++ b/ets2panda/linter/homecheck/package.json @@ -0,0 +1,32 @@ +{ + "scripts": { + "installArkAnalyzer": "bash ./scripts/install_arkanalyzer.sh", + "compile": "tsc -p ./tsconfig.prod.json", + "test": "vitest --no-color run", + "coverage": "vitest run --coverage", + "pack": "npm pack" + }, + "dependencies": { + "commander": "11.0.0", + "fs-extra": "11.2.0" + }, + "devDependencies": { + "@types/fs-extra": "9.0.13", + "ts-node": "10.9.1", + "typedoc": "^0.25.13", + "vite-tsconfig-paths": "4.3.1", + "vitest": "1.5.1" + }, + "name": "homecheck", + "version": "0.9.11-arkts1.2", + "description": "该项目(homecheck)专为提升代码质量而设计,能高效识别代码缺陷并提出方案;其核心功能是对应用工程项目执行静态代码分析,评估代码在安全性、性能等方面上的表现,精准定位问题及其在代码中的位置。", + "main": "lib/Index.js", + "files": [ + "docs", + "lib", + "resources", + "ruleSet.json" + ], + "author": "", + "license": "ISC" +} diff --git a/ets2panda/linter/homecheck/resources/internalSdk/@internal/es5.d.ts b/ets2panda/linter/homecheck/resources/internalSdk/@internal/es5.d.ts new file mode 100644 index 0000000000..5972cfdced --- /dev/null +++ b/ets2panda/linter/homecheck/resources/internalSdk/@internal/es5.d.ts @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the 'License'); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an 'AS IS' BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +interface ObjectConstructor { + new (value?: any): Object; + (): any; + (value: any): any; + + readonly prototype: Object; + + getPrototypeOf(o: any): any; + + getOwnPropertyDescriptor(o: any, p: PropertyKey): PropertyDescriptor | undefined; + + getOwnPropertyNames(o: any): string[]; + + create(o: object | null): any; + + create(o: object | null, properties: PropertyDescriptorMap & ThisType): any; + + defineProperty(o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType): T; + + defineProperties(o: T, properties: PropertyDescriptorMap & ThisType): T; + + seal(o: T): T; + + freeze(f: T): T; + + freeze(o: T): Readonly; + + freeze(o: T): Readonly; + + preventExtensions(o: T): T; + + isSealed(o: any): boolean; + + isFrozen(o: any): boolean; + + isExtensible(o: any): boolean; + + keys(o: object): string[]; +} + +declare var Object: ObjectConstructor; \ No newline at end of file diff --git a/ets2panda/linter/homecheck/resources/sdkConfig.json b/ets2panda/linter/homecheck/resources/sdkConfig.json new file mode 100644 index 0000000000..51715b0b78 --- /dev/null +++ b/ets2panda/linter/homecheck/resources/sdkConfig.json @@ -0,0 +1,24 @@ +{ + "sdks": [ + { + "name": "internalSdk", + "path": "./resources/internalSdk", + "moduleName": "" + }, + { + "name": "ohosSdk", + "path": "", + "moduleName": "" + }, + { + "name": "hmsSdk", + "path": "", + "moduleName": "" + }, + { + "name": "thirdParty", + "path": "./resources/thirdPartyModules", + "moduleName": "" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/resources/thirdPartyModules/@hview/moment/index.d.ts b/ets2panda/linter/homecheck/resources/thirdPartyModules/@hview/moment/index.d.ts new file mode 100644 index 0000000000..8e41abd4a3 --- /dev/null +++ b/ets2panda/linter/homecheck/resources/thirdPartyModules/@hview/moment/index.d.ts @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @param strict Strict parsing disables the deprecated fallback to the native Date constructor when + * parsing a string. + */ +export default function moment(): moment.Moment; +declare namespace moment { + interface Moment extends Object { + utcOffset(): number; + utcOffset(b: number|string, keepLocalTime?: boolean): Moment; + } +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/resources/thirdPartyModules/@ohos/gif-drawable/index.ets b/ets2panda/linter/homecheck/resources/thirdPartyModules/@ohos/gif-drawable/index.ets new file mode 100644 index 0000000000..f8d5dcb73d --- /dev/null +++ b/ets2panda/linter/homecheck/resources/thirdPartyModules/@ohos/gif-drawable/index.ets @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { default as GIFComponentV2 } from './src/main/ets/components/gif/display/GIFComponentV2'; +export { default as GIFComponent } from './src/main/ets/components/gif/display/GIFComponent'; \ No newline at end of file diff --git a/ets2panda/linter/homecheck/resources/thirdPartyModules/@ohos/gif-drawable/src/main/ets/components/gif/display/GIFComponent.ets b/ets2panda/linter/homecheck/resources/thirdPartyModules/@ohos/gif-drawable/src/main/ets/components/gif/display/GIFComponent.ets new file mode 100644 index 0000000000..4cb318ca64 --- /dev/null +++ b/ets2panda/linter/homecheck/resources/thirdPartyModules/@ohos/gif-drawable/src/main/ets/components/gif/display/GIFComponent.ets @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +namespace GIFComponent { + export class ControllerOptions { + private openHardware: boolean = false; + setOpenHardware(open: boolean) { + this.openHardware = open; + return this; + } + } +} + +export default GIFComponent; diff --git a/ets2panda/linter/homecheck/resources/thirdPartyModules/@ohos/gif-drawable/src/main/ets/components/gif/display/GIFComponentV2.ets b/ets2panda/linter/homecheck/resources/thirdPartyModules/@ohos/gif-drawable/src/main/ets/components/gif/display/GIFComponentV2.ets new file mode 100644 index 0000000000..49f39c777a --- /dev/null +++ b/ets2panda/linter/homecheck/resources/thirdPartyModules/@ohos/gif-drawable/src/main/ets/components/gif/display/GIFComponentV2.ets @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +namespace GIFComponentV2 { + export class ControllerOptions { + private openHardware: boolean = false; + setOpenHardware(open: boolean) { + this.openHardware = open; + return this; + } + } +} + +export default GIFComponentV2; diff --git a/ets2panda/linter/homecheck/resources/thirdPartyModules/@ohos/lottie/index.d.ts b/ets2panda/linter/homecheck/resources/thirdPartyModules/@ohos/lottie/index.d.ts new file mode 100644 index 0000000000..41e2169ce8 --- /dev/null +++ b/ets2panda/linter/homecheck/resources/thirdPartyModules/@ohos/lottie/index.d.ts @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export class AnimationItem {destroy(name?: string): void;addEventListener(name: string, callback: LoadCallback): () => void; }; +export default class LottiePlayer {loadAnimation(params: Object): AnimationItem; destroy(name?: string): void;}; \ No newline at end of file diff --git a/ets2panda/linter/homecheck/ruleSet.json b/ets2panda/linter/homecheck/ruleSet.json new file mode 100644 index 0000000000..197cfacae1 --- /dev/null +++ b/ets2panda/linter/homecheck/ruleSet.json @@ -0,0 +1,207 @@ +{ + "plugin:@ArkTS-eslint/all": { + "@ArkTS-eslint/require-await-check": 2, + "@ArkTS-eslint/triple-slash-reference-check": 2, + "@ArkTS-eslint/restrict-template-expressions-check": 2, + "@ArkTS-eslint/restrict-plus-operands-check": 2, + "@ArkTS-eslint/switch-exhaustiveness-check": 2, + "@ArkTS-eslint/unified-signatures-check": 2, + "@ArkTS-eslint/no-regex-spaces-check": 2, + "@ArkTS-eslint/valid-typeof-check": 2, + "@ArkTS-eslint/array-type-check": 2, + "@ArkTS-eslint/no-useless-backreference-check": 2, + "@ArkTS-eslint/ban-tslint-comment-check": 2, + "@ArkTS-eslint/prefer-arrow-callback-check":2, + "@ArkTS-eslint/no-unnecessary-boolean-literal-compare-check":2, + "@ArkTS-eslint/ban-types-check": 2, + "@ArkTS-eslint/brace-style-check": 2, + "@ArkTS-eslint/no-unsafe-optional-chaining-check": 2, + "@ArkTS-eslint/no-useless-escape-check": 2, + "@ArkTS-eslint/no-useless-catch-check": 2, + "@ArkTS-eslint/no-this-alias-check": 2, + "@ArkTS-eslint/no-non-null-assertion-check": 2, + "@ArkTS-eslint/no-misused-new-check": 2, + "@ArkTS-eslint/no-require-imports-check": 2, + "@ArkTS-eslint/no-parameter-properties-check": 2, + "@ArkTS-eslint/no-redeclare-check": 2, + "@ArkTS-eslint/no-shadow-check": 2, + "@ArkTS-eslint/no-non-null-asserted-optional-chain-check": 2, + "@ArkTS-eslint/consistent-type-assertions-check": 2, + "@ArkTS-eslint/consistent-type-definitions-check": 2, + "@ArkTS-eslint/consistent-type-imports-check": 2, + "@ArkTS-eslint/consistent-indexed-object-style-check": 2, + "@ArkTS-eslint/no-new-wrappers-check": 2, + "@ArkTS-eslint/max-classes-per-file-check": 2, + "@ArkTS-eslint/max-nested-callbacks-check": 2, + "@ArkTS-eslint/no-async-promise-executor-check": 2, + "@ArkTS-eslint/no-array-constructor-check": 2, + "@ArkTS-eslint/max-depth-check": 2, + "@ArkTS-eslint/eqeqeq-check": 2, + "@ArkTS-eslint/no-array-constructor-ts-check": 2, + "@ArkTS-eslint/no-extra-semi-check": 2, + "@ArkTS-eslint/no-extra-boolean-cast-check":2, + "@ArkTS-eslint/no-confusing-void-expression-check":2, + "@ArkTS-eslint/prefer-const-check": 2, + "@ArkTS-eslint/await-thenable-check": 2, + "@ArkTS-eslint/init-declarations-check": 2, + "@ArkTS-eslint/default-param-last-check": 2, + "@ArkTS-eslint/explicit-function-return-type-check": 2, + "@ArkTS-eslint/explicit-module-boundary-types-check": 2, + "@ArkTS-eslint/no-dupe-class-members-check": 2, + "@ArkTS-eslint/ban-ts-comment-check": 2, + "@ArkTS-eslint/member-ordering-check": 2, + "@ArkTS-eslint/no-unnecessary-condition-check": 2, + "@ArkTS-eslint/no-unnecessary-qualifier-check": 2, + "@ArkTS-eslint/no-unnecessary-type-arguments-check": 2, + "@ArkTS-eslint/no-unnecessary-type-assertion-check": 2, + "@ArkTS-eslint/prefer-string-starts-ends-with-check": 2, + "@ArkTS-eslint/prefer-regexp-exec-check": 2, + "@ArkTS-eslint/max-lines-per-function-check": 2, + "@ArkTS-eslint/no-cond-assign-check": 2, + "@ArkTS-eslint/no-for-in-array-check": 2, + "@ArkTS-eslint/no-loss-of-precision-check": 2, + "@ArkTS-eslint/no-loop-func-check": 2, + "@ArkTS-eslint/no-extraneous-class-check": 2, + "@ArkTS-eslint/no-duplicate-imports-check": 2, + "@ArkTS-eslint/no-case-declarations-check": 2, + "@ArkTS-eslint/default-case-check": 2, + "@ArkTS-eslint/default-case-last-check": 2, + "@ArkTS-eslint/use-isnan-check": 2, + "@ArkTS-eslint/no-invalid-void-type-check": 2, + "@ArkTS-eslint/no-namespace-check": 2, + "@ArkTS-eslint/typedef-check": 2, + "@ArkTS-eslint/return-await-check":2, + "@ArkTS-eslint/prefer-reduce-type-parameter-check":2, + "@ArkTS-eslint/prefer-nullish-coalescing-check": 2, + "@ArkTS-eslint/max-lines-check": 2, + "@ArkTS-eslint/no-unnecessary-type-constraint-check": 2, + "@ArkTS-eslint/no-unsafe-argument-check": 2, + "@ArkTS-eslint/no-unsafe-call-check": 2, + "@ArkTS-eslint/no-control-regex-check": 2, + "@ArkTS-eslint/no-empty-character-class-check": 2, + "@ArkTS-eslint/no-ex-assign-check": 2, + "@ArkTS-eslint/no-invalid-regexp-check": 2, + "@ArkTS-eslint/no-octal-check": 2, + "@ArkTS-eslint/no-unexpected-multiline-check": 2, + "@ArkTS-eslint/no-unreachable-check": 2, + "@ArkTS-eslint/no-inferrable-types-check": 2, + "@ArkTS-eslint/space-before-function-paren-check": 2, + "@ArkTS-eslint/space-infix-ops-check": 2, + "@ArkTS-eslint/no-restricted-syntax-check": 2, + "@ArkTS-eslint/adjacent-overload-signatures-check": 2, + "@ArkTS-eslint/class-literal-property-style-check": 2, + "@ArkTS-eslint/no-confusing-non-null-assertion-check": 2, + "@ArkTS-eslint/no-empty-function-check": 2, + "@ArkTS-eslint/no-magic-numbers-check": 2, + "@ArkTS-eslint/prefer-enum-initializers-check": 2, + "@ArkTS-eslint/prefer-literal-enum-member-check": 2, + "@ArkTS-eslint/prefer-readonly-parameter-types-check": 2, + "@ArkTS-eslint/require-array-sort-compare-check": 2, + "@ArkTS-eslint/no-invalid-this-check": 2, + "@ArkTS-eslint/no-fallthrough-check": 2, + "@ArkTS-eslint/no-explicit-any-check": 2, + "@ArkTS-eslint/no-unused-expressions-check": 2, + "@ArkTS-eslint/no-throw-literal-check": 2, + "@ArkTS-eslint/comma-dangle-check": 2, + "@ArkTS-eslint/prefer-ts-expect-error-check": 2, + "@ArkTS-eslint/no-extra-parens-check": 2, + "@ArkTS-eslint/no-dynamic-delete-check": 2, + "@ArkTS-eslint/no-implicit-any-catch-check": 2, + "@ArkTS-eslint/no-empty-interface-check": 2, + "@ArkTS-eslint/no-unsafe-finally-check": 3, + "@ArkTS-eslint/prefer-function-type-check":3, + "@ArkTS-eslint/prefer-namespace-keyword-check": 3, + "@ArkTS-eslint/prefer-readonly-check": 2, + "@ArkTS-eslint/comma-spacing-check": 2, + "@ArkTS-eslint/naming-convention-check": 2, + "@ArkTS-eslint/no-extra-non-null-assertion-check": 2, + "@ArkTS-eslint/no-type-alias-check": 2, + "@ArkTS-eslint/type-annotation-spacing-check": 2, + "@ArkTS-eslint/func-call-spacing-check": 1, + "@ArkTS-eslint/unbound-method-check": 2, + "@ArkTS-eslint/method-signature-style-check": 2, + "@ArkTS-eslint/lines-between-class-members-check": 2, + "@ArkTS-eslint/member-delimiter-style-check": 2, + "@ArkTS-eslint/no-unsafe-return-check": 2, + "@ArkTS-eslint/no-use-before-define-check": 1, + "@ArkTS-eslint/quotes-check": 2, + "@ArkTS-eslint/prefer-as-const-check": 2, + "@ArkTS-eslint/prefer-optional-chain-check": 2, + "@ArkTS-eslint/no-trailing-spaces-check": 2, + "@ArkTS-eslint/no-unsafe-assignment-check": 2, + "@ArkTS-eslint/prefer-for-of-check": 2, + "@ArkTS-eslint/strict-boolean-expressions-check": 2, + "@ArkTS-eslint/no-implied-eval-check": 2, + "@ArkTS-eslint/semi-check": 2, + "@ArkTS-eslint/no-base-to-string-check": 2, + "@ArkTS-eslint/promise-function-async-check": 2, + "@ArkTS-eslint/prefer-includes-check": 2, + "@ArkTS-eslint/no-unsafe-member-access-check": 2, + "@ArkTS-eslint/no-unused-vars-check": 2, + "@ArkTS-eslint/no-useless-constructor-check": 2, + "@ArkTS-eslint/dot-notation-check": 2, + "@ArkTS-eslint/explicit-member-accessibility-check": 2, + "@ArkTS-eslint/keyword-spacing-check": 2, + "@ArkTS-eslint/no-floating-promises-check": 2, + "@ArkTS-eslint/no-misused-promises-check": 2 + }, + "plugin:@performance/all": { + "@performance/array-definition-check": 3, + "@performance/avoid-empty-callback-check": 3, + "@performance/avoid-update-auto-state-var-in-aboutToReuse-check": 3, + "@performance/constant-property-referencing-check-in-loops": 3, + "@performance/effectkit-blur-check": 3, + "@performance/foreach-args-check": 3, + "@performance/foreach-index-check": 1, + "@performance/image-sync-load-check": 3, + "@performance/list-in-scroll-check": 3, + "@performance/lottie-animation-destroy-check": 3, + "@performance/multiple-associations-state-var-check": 3, + "@performance/remove-redundant-state-var-check": 3, + "@performance/set-cached-count-for-lazyforeach-check": 3, + "@performance/start-window-icon-check": 3, + "@performance/timezone-interface-check": 3, + "@performance/typed-array-check": 3, + "@performance/use-object-link-to-replace-prop-check": 3, + "@performance/web-cache-mode-check": 3, + "@performance/number-init-check": 3, + "@performance/sparse-array-check": 3, + "@performance/high-frequency-log-check": 1, + "@performance/waterflow-data-preload-check": 3, + "@performance/union-type-array-check": 3, + "@performance/layout-properties-scale-check": 3, + "@performance/optional-parameters-check": 3, + "@performance/use-grid-layout-options-check": 3, + "@performance/remove-unchanged-state-var-check": 3, + "@performance/js-code-cache-by-precompile-check": 3, + "@performance/js-code-cache-by-interception-check": 3, + "@performance/web-on-active-check": 3, + "@performance/gif-hardware-decoding-check": 1 + }, + "plugin:@performance/recommended": { + "@performance/foreach-args-check": 1, + "@performance/start-window-icon-check": 3, + "@performance/waterflow-data-preload-check": 3, + "@performance/high-frequency-log-check": 1 + }, + "plugin:@security/all": { + "@security/specified-interface-call-chain-check": 3 + }, + "plugin:@correctness/all": { + "@correctness/audio-interrupt-check": 2, + "@correctness/audio-pause-or-mute-check": 1, + "@correctness/avsession-buttons-check": 1, + "@correctness/avsession-metadata-check": 1, + "@correctness/image-interpolation-check": 1, + "@correctness/image-pixel-format-check": 1 + }, + "plugin:@migration/all": { + "@migration/arkts-obj-literal-generate-class-instance": 1, + "@migration/arkts-instance-method-bind-this": 1, + "@migration/arkui-data-observation-2": 1, + "@migration/arkui-stateful-appstorage": 1, + "@migration/arkui-no-update-in-rending": 1, + "@migration/arkui-custombuiler": 1, + "@migration/no-method-overriding-field-check": 1 + } +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/scripts/install_arkanalyzer.sh b/ets2panda/linter/homecheck/scripts/install_arkanalyzer.sh new file mode 100644 index 0000000000..282d190c67 --- /dev/null +++ b/ets2panda/linter/homecheck/scripts/install_arkanalyzer.sh @@ -0,0 +1,33 @@ +#!/bin/bash +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +set -x + +# install and pack dependency arkanalyzer +cd ../arkanalyzer +npm install + +cp package.json package.json.bak + +sed -i '/postinstall/d' package.json +npm pack + +TAR_FILE=$(find . -maxdepth 1 -name "arkanalyzer-*.tgz" -print0) +cd ../homecheck +npm install ../arkanalyzer/$TAR_FILE + +# revert the project files +mv ../arkanalyzer/package.json.bak ../arkanalyzer/package.json +rm ../arkanalyzer/$TAR_FILE diff --git a/ets2panda/linter/homecheck/scripts/run_ci_ut.sh b/ets2panda/linter/homecheck/scripts/run_ci_ut.sh new file mode 100644 index 0000000000..56f455f87b --- /dev/null +++ b/ets2panda/linter/homecheck/scripts/run_ci_ut.sh @@ -0,0 +1,71 @@ +#!/bin/bash +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +set -x + +if [ -z "${ROOT_DIR+x}" ]; then + export ROOT_DIR=$(pwd) + echo "ROOT_DIR was not set. Initialized to $ROOT_DIR" +else + echo "ROOT_DIR is already set to $ROOT_DIR" +fi + +NODE_VERSION=v22.3.0 +NODE_HOME=$ROOT_DIR/pre_scripts/node-$NODE_VERSION-linux-x64 +NODE_URL=https://gitee.com/muya318/pre_scripts/raw/master/node-v22.3.0-linux-x64.tar.gz +NODE_BIN=node-v22.3.0-linux-x64.tar.gz + +prepare_nodejs() { + echo "### preparing nodejs" + if [ ! -d "$NODE_HOME" ]; then + cd $ROOT_DIR/pre_scripts + tar -xf $NODE_BIN + chmod 777 $NODE_HOME/bin/* + cd - + export PATH=$NODE_HOME/bin:$PATH + fi + npm config set registry=https://repo.huaweicloud.com/repository/npm/ + npm config set strict-ssl false + echo "###nodejs env ready" +} + +git clone https://gitee.com/muya318/pre_scripts.git + +prepare_nodejs + +pwd +cd $ROOT_DIR + +node -v +npm -v + +npm install +npm run test + +if [ $? -ne 0 ]; then + echo "************* Unit test failed *************" + exit 1 +fi + +echo "************* Unit test success *************" + +npm pack +if [ $? -ne 0 ]; then + echo "************* Npm pack failed *************" + exit 1 +fi +echo "************* Npm pack success *************" + +exit 0 \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/Index.ts b/ets2panda/linter/homecheck/src/Index.ts new file mode 100644 index 0000000000..f2ca91bcba --- /dev/null +++ b/ets2panda/linter/homecheck/src/Index.ts @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// main +export { start, run } from './Main'; + +// checkers +export { BaseMetaData, BaseChecker } from './checker/BaseChecker'; + +// matchers +export * from './matcher/Matchers'; + +// models +export { CheckerStorage } from './utils/common/CheckerStorage'; +export { Rule } from './model/Rule'; +export { Defects, IssueReport, FileReports } from './model/Defects'; +export { Message, MessageType } from './model/Message'; +export { ProjectConfig } from './model/ProjectConfig'; +export { RuleConfig } from './model/RuleConfig'; +export * from './model/Scope'; + +// utils +export { CheckEntry } from './utils/common/CheckEntry'; +export { CheckerUtils } from './utils/checker/CheckerUtils'; +export { ConfigUtils } from './utils/common/ConfigUtils'; +export { FileUtils, WriteFileMode } from './utils/common/FileUtils'; +export { Json5parser } from './utils/common/Json5parser'; +export { Utils } from './utils/common/Utils'; + +// tools +export { runTool, Tools } from './tools/toolEntry'; +export { MigrationTool } from './tools/migrationTool/MigrationTool'; +export { ProblemInfo, AutoFix } from './tools/migrationTool/ExportIssue'; \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/Main.ts b/ets2panda/linter/homecheck/src/Main.ts new file mode 100644 index 0000000000..b706c8e150 --- /dev/null +++ b/ets2panda/linter/homecheck/src/Main.ts @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import Logger, { LOG_MODULE_TYPE } from "arkanalyzer/lib/utils/logger"; +import { processAfterCheck } from "./utils/common/AfterCheck"; +import { CheckEntry, checkEntryBuilder, getSelectFileList } from "./utils/common/CheckEntry"; +import { ConfigUtils } from "./utils/common/ConfigUtils"; +import { defaultMessage } from "./model/Message"; +import { Utils } from "./utils/common/Utils"; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'Main'); + +export async function start(checkEntry: CheckEntry): Promise { + // 外部没有建立消息通道,使用默认通道 + if (!checkEntry.message) { + checkEntry.message = new defaultMessage(); + } + + // 前处理 + if (!await checkEntryBuilder(checkEntry)) { + return false; + } + + // 开始检查 + await checkEntry.runAll(); + + // 后处理 + await processAfterCheck(checkEntry); + logger.info('Checking completed.'); + return true; +} + +export async function run(): Promise { + const startTime = new Date().getTime(); + const checkEntry = new CheckEntry(); + // 构建ruleConfig和projectConfig,保存至checkEntry中 + if (!ConfigUtils.parseConfig(Utils.parseCliOptions(process.argv), checkEntry)) { + return false; + } + + // 设置指定文件检查,不设置默认检查所有文件 + checkEntry.setCheckFileList(getSelectFileList(checkEntry.projectConfig.checkPath)); + + // 启动homecheck检查 + await start(checkEntry); + + const endTime = new Date().getTime(); + logger.info(`HomeCheck took: ${(endTime - startTime) / 1000} s.`); + return true; +}; \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/checker/BaseChecker.ts b/ets2panda/linter/homecheck/src/checker/BaseChecker.ts new file mode 100644 index 0000000000..930c88f5c7 --- /dev/null +++ b/ets2panda/linter/homecheck/src/checker/BaseChecker.ts @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkFile } from "arkanalyzer"; +import { Rule } from "../model/Rule"; +import { MatcherCallback } from "../matcher/Matchers"; +import { IssueReport } from "../model/Defects"; + +export interface BaseMetaData { + severity: number, + ruleDocPath: string, + description: string, + [extendField: string]: any +} + +export interface BaseChecker { + metaData: object; + // 在CheckerFactory构建checker实例时,已对rule进行赋值 + rule: Rule; + registerMatchers(): MatcherCallback[]; + check(target: any): void; + codeFix?(arkFile: ArkFile, fixKey: string): boolean; + // 用于保存当前checker发现的告警信息与fix相关信息 + issues: IssueReport[]; +} diff --git a/ets2panda/linter/homecheck/src/checker/migration/AppStorageGetCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/AppStorageGetCheck.ts new file mode 100644 index 0000000000..91186ddc1a --- /dev/null +++ b/ets2panda/linter/homecheck/src/checker/migration/AppStorageGetCheck.ts @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkInstanceInvokeExpr, ArkMethod, ArkStaticInvokeExpr, CallGraph, CallGraphBuilder, Stmt, Value } from 'arkanalyzer/lib'; +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; +import { BaseChecker, BaseMetaData } from '../BaseChecker'; +import { Rule, Defects, ClassMatcher, MethodMatcher, MatcherTypes, MatcherCallback } from '../../Index'; +import { IssueReport } from '../../model/Defects'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'AppStorageGetCheck'); +const gMetaData: BaseMetaData = { + severity: 1, + ruleDocPath: '', + description: 'Get State of AppStorage in component build function, it will update UI interface when the state of AppStorage is changed.' +}; + +const APP_STORAGE_STR = "AppStorage"; +const API_SET: Set = new Set(['Has', 'has', 'Get', 'get', + 'Keys', 'keys', 'IsMutable', 'Size', 'size']); + +const CALLBACK_METHOD_NAME: string[] = [ + "onClick", // 点击事件,当用户点击组件时触发 + "onTouch", // 触摸事件,当手指在组件上按下、滑动、抬起时触发 + "onAppear", // 组件挂载显示时触发 + "onDisAppear", // 组件卸载消失时触发 + "onDragStart", // 拖拽开始事件,当组件被长按后开始拖拽时触发 + "onDragEnter", // 拖拽进入组件范围时触发 + "onDragMove", // 拖拽在组件范围内移动时触发 + "onDragLeave", // 拖拽离开组件范围内时触发 + "onDrop", // 拖拽释放目标,当在本组件范围内停止拖拽行为时触发 + "onKeyEvent", // 按键事件,当组件获焦后,按键动作触发 + "onFocus", // 焦点事件,当组件获取焦点时触发 + "onBlur", // 当组件失去焦点时触发的回调 + "onHover", // 鼠标悬浮事件,鼠标进入或退出组件时触发 + "onMouse", // 鼠标事件,当鼠标按键点击或在组件上移动时触发 + "onAreaChange", // 组件区域变化事件,组件尺寸、位置变化时触发 + "onVisibleAreaChange", // 组件可见区域变化事件,组件在屏幕中的显示区域面积变化时触发 +]; + +export class AppStorageGetCheck implements BaseChecker { + readonly metaData: BaseMetaData = gMetaData; + public rule: Rule; + public defects: Defects[] = []; + public issues: IssueReport[] = []; + + private classMatcher: ClassMatcher = { + matcherType: MatcherTypes.CLASS, + hasViewTree: true, + }; + + private buildMatcher: MethodMatcher = { + matcherType: MatcherTypes.METHOD, + class: [this.classMatcher], + name: ["build"] + }; + + public registerMatchers(): MatcherCallback[] { + const matchBuildCb: MatcherCallback = { + matcher: this.buildMatcher, + callback: this.check + }; + return [matchBuildCb]; + } + + public check = (targetMtd: ArkMethod) => { + const scene = targetMtd.getDeclaringArkFile().getScene(); + let callGraph = new CallGraph(scene); + let callGraphBuilder = new CallGraphBuilder(callGraph, scene); + callGraphBuilder.buildClassHierarchyCallGraph([targetMtd.getSignature()], true); + + this.checkMethod(targetMtd, callGraph); + } + + private checkMethod(targetMtd: ArkMethod, cg: CallGraph, depth: number = 0) { + if (depth > 2) { + return; + } + const stmts = targetMtd.getBody()?.getCfg().getStmts() ?? []; + for (const stmt of stmts) { + this.checkAppStorageGet(stmt) + const invokeExpr = stmt.getInvokeExpr(); + if (invokeExpr && invokeExpr instanceof ArkInstanceInvokeExpr) { + if (CALLBACK_METHOD_NAME.includes(invokeExpr.getMethodSignature().getMethodSubSignature().getMethodName())) { + continue; + } + } + let callsite = cg.getCallSiteByStmt(stmt); + callsite.forEach(cs => { + let callee = cg.getArkMethodByFuncID(cs.calleeFuncID); + if (callee) { + this.checkMethod(callee, cg, depth + 1); + } + }) + } + } + + private checkAppStorageGet(stmt: Stmt) { + let invokeExpr = stmt.getInvokeExpr(); + if (!(invokeExpr instanceof ArkStaticInvokeExpr)) { + return; + } + const methodSig = invokeExpr.getMethodSignature(); + if (methodSig.getDeclaringClassSignature().getClassName() !== APP_STORAGE_STR) { + return; + } + if (!API_SET.has(methodSig.getMethodSubSignature().getMethodName())) { + return; + } + this.addIssueReport(stmt, invokeExpr); + } + + private addIssueReport(stmt: Stmt, operand: Value) { + const severity = this.rule.alert ?? this.metaData.severity; + const warnInfo = this.getLineAndColumn(stmt, operand); + let defects = new Defects(warnInfo.line, warnInfo.startCol, warnInfo.endCol, this.metaData.description, severity, this.rule.ruleId, + warnInfo.filePath, this.metaData.ruleDocPath, true, false, false); + this.issues.push(new IssueReport(defects, undefined)); + } + + private getLineAndColumn(stmt: Stmt, operand: Value) { + const arkFile = stmt.getCfg()?.getDeclaringMethod().getDeclaringArkFile(); + const originPosition = stmt.getOperandOriginalPosition(operand); + if (arkFile && originPosition) { + const originPath = arkFile.getFilePath(); + const line = originPosition.getFirstLine(); + const startCol = originPosition.getFirstCol(); + const endCol = startCol; + return { line, startCol, endCol, filePath: originPath }; + } else { + logger.debug('ArkFile is null.'); + } + return { line: -1, startCol: -1, endCol: -1, filePath: '' }; + } +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/checker/migration/CustomBuilderCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/CustomBuilderCheck.ts new file mode 100644 index 0000000000..f022bc63c8 --- /dev/null +++ b/ets2panda/linter/homecheck/src/checker/migration/CustomBuilderCheck.ts @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkAssignStmt, Scene, Local, Stmt, Type, ArkMethod, AliasType, AbstractInvokeExpr, Value } from "arkanalyzer"; +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; +import { BaseChecker, BaseMetaData } from "../BaseChecker"; +import { Rule, Defects, MatcherTypes, MatcherCallback, MethodMatcher } from "../../Index"; +import { IssueReport } from "../../model/Defects"; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'CustomBuilderCheck'); +const gMetaData: BaseMetaData = { + severity: 1, + ruleDocPath: "", + description: 'The CustomBuilder type parameter only accepts functions annotated with @Builder.' +}; + +export class CustomBuilderCheck implements BaseChecker { + readonly metaData: BaseMetaData = gMetaData; + public rule: Rule; + public defects: Defects[] = []; + public issues: IssueReport[] = []; + + private buildMatcher: MethodMatcher = { + matcherType: MatcherTypes.METHOD + }; + + public registerMatchers(): MatcherCallback[] { + const matchBuildCb: MatcherCallback = { + matcher: this.buildMatcher, + callback: this.check + }; + return [matchBuildCb]; + } + + public check = (target: ArkMethod): void => { + const scene = target.getDeclaringArkFile().getScene(); + const stmts = target.getBody()?.getCfg().getStmts() ?? []; + let locals = new Set(); + for (const stmt of stmts) { + const local = this.isCallToBuilder(stmt, scene); + if (local) { + locals.add(local); + continue; + } + const usage = this.isPassToCustomBuilder(stmt, locals); + if (usage) { + this.addIssueReport(usage.getDeclaringStmt()!, usage); + } + } + }; + + private isCallToBuilder(stmt: Stmt, scene: Scene): Local | undefined { + if (!(stmt instanceof ArkAssignStmt)) { + return undefined; + } + const leftOp = stmt.getLeftOp(); + if (!(leftOp instanceof Local)) { + return undefined; + } + const rightOp = stmt.getRightOp(); + if (!(rightOp instanceof AbstractInvokeExpr)) { + return undefined; + } + const method = scene.getMethod(rightOp.getMethodSignature()); + if (method && method.hasBuilderDecorator()) { + return leftOp; + } + return undefined; + } + + private isCumtomBuilderTy(ty: Type) { + return ty instanceof AliasType && ty.getName() === 'CustomBuilder'; + } + + private isPassToCustomBuilder(stmt: Stmt, locals: Set): Local | undefined { + if (stmt instanceof ArkAssignStmt) { + if (!this.isCumtomBuilderTy(stmt.getLeftOp().getType())) { + return undefined; + } + const rightOp = stmt.getRightOp(); + if (rightOp instanceof Local && locals.has(rightOp)) { + return rightOp; + } + } + const invokeExpr = stmt.getInvokeExpr(); + if (invokeExpr) { + const paramTys = invokeExpr.getMethodSignature().getMethodSubSignature().getParameterTypes(); + const args = invokeExpr.getArgs(); + for (let i = 0; i < paramTys.length && i < args.length; ++i) { + if (!this.isCumtomBuilderTy(paramTys[i])) { + continue; + } + const arg = args[i]; + if (arg instanceof Local && locals.has(arg)) { + return arg; + } + } + } + return undefined; + } + + private addIssueReport(stmt: Stmt, operand: Value) { + const severity = this.rule.alert ?? this.metaData.severity; + const warnInfo = this.getLineAndColumn(stmt, operand); + let defects = new Defects(warnInfo.line, warnInfo.startCol, warnInfo.endCol, this.metaData.description, severity, this.rule.ruleId, + warnInfo.filePath, this.metaData.ruleDocPath, true, false, false); + this.issues.push(new IssueReport(defects, undefined)); + } + + private getLineAndColumn(stmt: Stmt, operand: Value) { + const arkFile = stmt.getCfg()?.getDeclaringMethod().getDeclaringArkFile(); + const originPosition = stmt.getOperandOriginalPosition(operand); + if (arkFile && originPosition) { + const originPath = arkFile.getFilePath(); + const line = originPosition.getFirstLine(); + const startCol = originPosition.getFirstCol(); + const endCol = startCol; + return { line, startCol, endCol, filePath: originPath }; + } else { + logger.debug('ArkFile is null.'); + } + return { line: -1, startCol: -1, endCol: -1, filePath: '' }; + } +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/checker/migration/ModifyStateVarCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/ModifyStateVarCheck.ts new file mode 100644 index 0000000000..09e8f03c75 --- /dev/null +++ b/ets2panda/linter/homecheck/src/checker/migration/ModifyStateVarCheck.ts @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkAssignStmt, ArkInstanceFieldRef, Local, Stmt, Value, FieldSignature, ArkMethod } from "arkanalyzer"; +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; +import { BaseChecker, BaseMetaData } from "../BaseChecker"; +import { Rule, Defects, MatcherTypes, MatcherCallback, ClassMatcher, MethodMatcher } from "../../Index"; +import { IssueReport } from "../../model/Defects"; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'ModifyStateVarCheck'); +const gMetaData: BaseMetaData = { + severity: 1, + ruleDocPath: "", + description: 'It is not allowed to update state when the view is changing.' +}; + +export class ModifyStateVarCheck implements BaseChecker { + readonly metaData: BaseMetaData = gMetaData; + public rule: Rule; + public defects: Defects[] = []; + public issues: IssueReport[] = []; + + private classMatcher: ClassMatcher = { + matcherType: MatcherTypes.CLASS, + hasViewTree: true, + }; + + private buildMatcher: MethodMatcher = { + matcherType: MatcherTypes.METHOD, + class: [this.classMatcher], + name: ["build"] + }; + + public registerMatchers(): MatcherCallback[] { + const matchBuildCb: MatcherCallback = { + matcher: this.buildMatcher, + callback: this.check + }; + return [matchBuildCb]; + } + + public check = (target: ArkMethod): void => { + const arkClass = target.getDeclaringArkClass(); + const stateVars = new Set(arkClass.getFields().filter(f => f.hasDecorator('State')).map(f => f.getSignature())); + let aliases = new Set(); + const stmts = target.getBody()?.getCfg().getStmts() ?? []; + for (const stmt of stmts) { + if (!(stmt instanceof ArkAssignStmt)) { + continue; + } + if (this.isAssignToStateVar(stmt, stateVars, aliases)) { + this.addIssueReport(stmt, stmt.getLeftOp()); + } else { + const alias = this.isAliasOfStateVar(stmt, stateVars, aliases); + if (alias) { + aliases.add(alias); + } + } + } + }; + + private isAssignToStateVar(stmt: ArkAssignStmt, stateVars: Set, aliases: Set): boolean { + const leftOp = stmt.getLeftOp(); + if (leftOp instanceof ArkInstanceFieldRef) { + // this.n = 1 or this.obj.n = 1 + return stateVars.has(leftOp.getFieldSignature()) || aliases.has(leftOp.getBase()); + } else if (leftOp instanceof Local) { + return aliases.has(leftOp); + } + return false; + } + + private isAliasOfStateVar(stmt: ArkAssignStmt, stateVars: Set, aliases: Set): Local | undefined { + const leftOp = stmt.getLeftOp(); + const rightOp = stmt.getRightOp(); + if (leftOp instanceof Local && rightOp instanceof ArkInstanceFieldRef) { + // %1 = this.n + // or + // %1 = this.obj; %2 = %1.n + if (stateVars.has(rightOp.getFieldSignature()) || aliases.has(rightOp.getBase())) { + return leftOp; + } + } + return undefined; + } + + private addIssueReport(stmt: Stmt, operand: Value) { + const severity = this.rule.alert ?? this.metaData.severity; + const warnInfo = this.getLineAndColumn(stmt, operand); + let defects = new Defects(warnInfo.line, warnInfo.startCol, warnInfo.endCol, this.metaData.description, severity, this.rule.ruleId, + warnInfo.filePath, this.metaData.ruleDocPath, true, false, false); + this.issues.push(new IssueReport(defects, undefined)); + } + + private getLineAndColumn(stmt: Stmt, operand: Value) { + const arkFile = stmt.getCfg()?.getDeclaringMethod().getDeclaringArkFile(); + const originPosition = stmt.getOperandOriginalPosition(operand); + if (arkFile && originPosition) { + const originPath = arkFile.getFilePath(); + const line = originPosition.getFirstLine(); + const startCol = originPosition.getFirstCol(); + const endCol = startCol; + return { line, startCol, endCol, filePath: originPath }; + } else { + logger.debug('ArkFile is null.'); + } + return { line: -1, startCol: -1, endCol: -1, filePath: '' }; + } +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/checker/migration/NoMethodOverridingFieldCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/NoMethodOverridingFieldCheck.ts new file mode 100644 index 0000000000..aeb6ae0a5a --- /dev/null +++ b/ets2panda/linter/homecheck/src/checker/migration/NoMethodOverridingFieldCheck.ts @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkAssignStmt, ArkClass, ArkFile, ArkIfStmt, ArkInstanceFieldRef, ArkInstanceInvokeExpr, ArkMethod, ClassType, FunctionType, Local, Stmt, Value } from "arkanalyzer"; +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; +import { BaseChecker, BaseMetaData } from "../BaseChecker"; +import { Rule, Defects, MatcherTypes, MethodMatcher, MatcherCallback, ClassMatcher } from "../../Index"; +import { IssueReport } from "../../model/Defects"; +import { ClassCategory } from "arkanalyzer/lib/core/model/ArkClass"; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'NoMethodOverridingFieldCheck'); +const gMetaData: BaseMetaData = { + severity: 1, + ruleDocPath: "", + description: '' +}; + +export class NoMethodOverridingFieldCheck implements BaseChecker { + readonly metaData: BaseMetaData = gMetaData; + public rule: Rule; + public defects: Defects[] = []; + public issues: IssueReport[] = []; + + private classMetcher: ClassMatcher = { + matcherType: MatcherTypes.CLASS, + ClassCategory: [ClassCategory.CLASS] + }; + + public registerMatchers(): MatcherCallback[] { + const methodCb: MatcherCallback = { + matcher: this.classMetcher, + callback: this.check + } + return [methodCb]; + } + + public check = (target: ArkClass) => { + const interfaces = target.getAllHeritageClasses().filter(c => c.getCategory() === ClassCategory.INTERFACE); + for (const i of interfaces) { + const fields = i.getFields().filter(f => f.getType() instanceof FunctionType).map(f => f.getName()); + fields.forEach(f => { + const method = target.getMethodWithName(f); + if (method) { + // record class + // console.log(`111`) + } + }) + } + } +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/checker/migration/NoOptionalMethodCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/NoOptionalMethodCheck.ts new file mode 100644 index 0000000000..252c001dfd --- /dev/null +++ b/ets2panda/linter/homecheck/src/checker/migration/NoOptionalMethodCheck.ts @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkClass, ArkMethod} from "arkanalyzer"; +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; +import { BaseChecker, BaseMetaData } from "../BaseChecker"; +import { Rule, Defects, MatcherTypes, MatcherCallback, ClassMatcher } from "../../Index"; +import { IssueReport } from "../../model/Defects"; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'NoOptionalMethodCheck'); +const gMetaData: BaseMetaData = { + severity: 1, + ruleDocPath: "", + description: '' +}; + +export class NoOptionalMethodCheck implements BaseChecker { + readonly metaData: BaseMetaData = gMetaData; + public rule: Rule; + public defects: Defects[] = []; + public issues: IssueReport[] = []; + + private classMetcher: ClassMatcher = { + matcherType: MatcherTypes.CLASS + }; + + public registerMatchers(): MatcherCallback[] { + const classCb: MatcherCallback = { + matcher: this.classMetcher, + callback: this.check + } + return [classCb]; + } + + public check = (target: ArkClass) => { + target.getMethods().filter(m => m.getQuestionToken()).forEach(m => { + const posInfo = this.getMethodPos(m); + this.addIssueReport(posInfo); + }); + } + + private addIssueReport(warnInfo: { line: number; startCol: number; endCol: number; filePath: string; }) { + const severity = this.rule.alert ?? this.metaData.severity; + let defects = new Defects(warnInfo.line, warnInfo.startCol, warnInfo.endCol, this.metaData.description, severity, this.rule.ruleId, + warnInfo.filePath, this.metaData.ruleDocPath, true, false, false); + this.issues.push(new IssueReport(defects, undefined)); + } + + private getMethodPos(cls: ArkMethod): { line: number; startCol: number; endCol: number; filePath: string; } { + const line = cls.getLineCol() ?? -1; + const startCol = cls.getColumn() ?? -1; + const endCol = startCol; + const arkFile = cls.getDeclaringArkFile(); + if (arkFile) { + return { line, startCol, endCol, filePath: arkFile.getFilePath() }; + } else { + logger.debug('ArkFile is null.'); + return { line, startCol, endCol, filePath: '' }; + } + } +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/checker/migration/ObjectLiteralCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/ObjectLiteralCheck.ts new file mode 100644 index 0000000000..f1cb46c499 --- /dev/null +++ b/ets2panda/linter/homecheck/src/checker/migration/ObjectLiteralCheck.ts @@ -0,0 +1,185 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkMethod, ArkAssignStmt, FieldSignature, Stmt, Scene, Value, DVFGBuilder, ArkInstanceOfExpr, ArkNewExpr, CallGraph, CallGraphBuilder, ArkParameterRef, ArkInstanceFieldRef } from "arkanalyzer/lib"; +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; +import { BaseChecker, BaseMetaData } from "../BaseChecker"; +import { Rule, Defects, MatcherCallback } from "../../Index"; +import { IssueReport } from "../../model/Defects"; +import { DVFG, DVFGNode } from "arkanalyzer/lib/VFG/DVFG"; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'ObjectLiteralCheck'); +const gMetaData: BaseMetaData = { + severity: 1, + ruleDocPath: "", + description: 'Object literal shall generate instance of a specific class.' +}; + +export class ObjectLiteralCheck implements BaseChecker { + readonly metaData: BaseMetaData = gMetaData; + public rule: Rule; + public defects: Defects[] = []; + public issues: IssueReport[] = []; + private cg: CallGraph; + private dvfg: DVFG; + + public registerMatchers(): MatcherCallback[] { + const matchBuildCb: MatcherCallback = { + matcher: undefined, + callback: this.check + } + return [matchBuildCb]; + } + + public check = (scene: Scene) => { + this.cg = new CallGraph(scene); + let cgBuilder = new CallGraphBuilder(this.cg, scene); + cgBuilder.buildDirectCallGraphForScene(); + let entries = this.cg.getEntries().map(funcId => this.cg.getArkMethodByFuncID(funcId)!.getSignature()); + cgBuilder.buildClassHierarchyCallGraph(entries, true); + + this.dvfg = new DVFG(this.cg); + const dvfgBuilder = new DVFGBuilder(this.dvfg, scene); + dvfgBuilder.build(); + + for (let arkFile of scene.getFiles()) { + for (let clazz of arkFile.getClasses()) { + for (let mtd of clazz.getMethods()) { + this.processArkMethod(mtd, scene); + } + } + for (let namespace of arkFile.getAllNamespacesUnderThisFile()) { + for (let clazz of namespace.getClasses()) { + for (let mtd of clazz.getMethods()) { + this.processArkMethod(mtd, scene); + } + } + } + } + } + + public processArkMethod(target: ArkMethod, scene: Scene) { + const stmts = target.getBody()?.getCfg().getStmts() ?? []; + for (const stmt of stmts) { + if (!(stmt instanceof ArkAssignStmt)) { + continue; + } + const rightOp = stmt.getRightOp(); + if (!(rightOp instanceof ArkInstanceOfExpr)) { + continue; + } + let result: Stmt[] = []; + let checkAll = { value: true }; + this.checkFromStmt(stmt, scene, result, checkAll); + result.forEach(s => this.addIssueReport(s, (s as ArkAssignStmt).getRightOp())); + if (!checkAll.value) { + this.addIssueReport(stmt, rightOp); + } + } + + } + + private checkFromStmt(stmt: Stmt, scene: Scene, res: Stmt[], checkAll: { value: boolean }, depth: number = 0) { + if (depth > 2) { + checkAll.value = false; + return; + } + const node = this.dvfg.getOrNewDVFGNode(stmt); + let worklist: DVFGNode[] = [node]; + while (worklist.length > 0) { + const current = worklist.shift()!; + const currentStmt = current.getStmt(); + if (this.isObjectLiteral(currentStmt, scene)) { + res.push(currentStmt); + continue; + } + const callsite = this.cg.getCallSiteByStmt(currentStmt); + callsite.forEach(cs => { + let returnStmts = this.cg.getArkMethodByFuncID(cs.calleeFuncID)?.getReturnStmt(); + returnStmts?.forEach(r => this.checkFromStmt(r, scene, res, checkAll, depth + 1)); + }) + const paramRef = this.isFromParameter(currentStmt); + if (paramRef) { + const paramIdx = paramRef.getIndex(); + const callsites = this.cg.getInvokeStmtByMethod(currentStmt.getCfg().getDeclaringMethod().getSignature()); + this.collectArgDefs(paramIdx, callsites).forEach(d => this.checkFromStmt(d, scene, res, checkAll, depth + 1)); + } + current.getIncomingEdge().forEach(e => worklist.push(e.getSrcNode() as DVFGNode)); + } + } + + private isObjectLiteral(stmt: Stmt, scene: Scene): boolean { + if (!(stmt instanceof ArkAssignStmt)) { + return false; + } + const rightOp = stmt.getRightOp(); + if (!(rightOp instanceof ArkNewExpr)) { + return false; + } + const classSig = rightOp.getClassType().getClassSignature(); + if (scene.getClass(classSig)?.isAnonymousClass()) { + return true; + } + return false; + } + + private isFromParameter(stmt: Stmt): ArkParameterRef | undefined { + if (!(stmt instanceof ArkAssignStmt)) { + return undefined; + } + const rightOp = stmt.getRightOp(); + if (rightOp instanceof ArkParameterRef) { + return rightOp; + } + return undefined; + } + + private collectArgDefs(argIdx: number, callsites: Stmt[]): Stmt[] { + const getKey = (v: Value) => { + return v instanceof ArkInstanceFieldRef ? v.getFieldSignature() : v + }; + return callsites.flatMap(callsite => { + const target: Value | FieldSignature = getKey(callsite.getInvokeExpr()!.getArg(argIdx)); + return Array.from(this.dvfg.getOrNewDVFGNode(callsite).getIncomingEdge()) + .map(e => (e.getSrcNode() as DVFGNode).getStmt()) + .filter(s => { + return s instanceof ArkAssignStmt && target === getKey(s.getLeftOp()); + }); + }); + } + + private addIssueReport(stmt: Stmt, operand: Value) { + const severity = this.rule.alert ?? this.metaData.severity; + const warnInfo = this.getLineAndColumn(stmt, operand); + let defects = new Defects(warnInfo.line, warnInfo.startCol, warnInfo.endCol, this.metaData.description, severity, this.rule.ruleId, + warnInfo.filePath, this.metaData.ruleDocPath, true, false, false); + this.issues.push(new IssueReport(defects, undefined)); + } + + private getLineAndColumn(stmt: Stmt, operand: Value) { + const arkFile = stmt.getCfg()?.getDeclaringMethod().getDeclaringArkFile(); + const originPosition = stmt.getOperandOriginalPosition(operand); + if (arkFile && originPosition) { + const originPath = arkFile.getFilePath(); + const line = originPosition.getFirstLine(); + const startCol = originPosition.getFirstCol(); + const endCol = startCol; + return { line, startCol, endCol, filePath: originPath }; + } else { + logger.debug('ArkFile is null.'); + } + return { line: -1, startCol: -1, endCol: -1, filePath: '' }; + } +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/checker/migration/ObservedDecoratorCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/ObservedDecoratorCheck.ts new file mode 100644 index 0000000000..9b4ed0092e --- /dev/null +++ b/ets2panda/linter/homecheck/src/checker/migration/ObservedDecoratorCheck.ts @@ -0,0 +1,155 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkAssignStmt, ArkClass, ArkField, ArkNewExpr, ClassType, Local, Scene } from "arkanalyzer"; +import { ClassCategory } from 'arkanalyzer/lib/core/model/ArkClass'; +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; +import { BaseChecker, BaseMetaData } from "../BaseChecker"; +import { Rule, Defects, ClassMatcher, MatcherTypes, MatcherCallback } from "../../Index"; +import { IssueReport } from "../../model/Defects"; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'ObservedDecoratorCheck'); +const gMetaData: BaseMetaData = { + severity: 1, + ruleDocPath: "", + description: '' +}; + +export class ObservedDecoratorCheck implements BaseChecker { + readonly metaData: BaseMetaData = gMetaData; + public rule: Rule; + public defects: Defects[] = []; + public issues: IssueReport[] = []; + + private clsMatcher: ClassMatcher = { + matcherType: MatcherTypes.CLASS, + }; + + public registerMatchers(): MatcherCallback[] { + const matchClsCb: MatcherCallback = { + matcher: this.clsMatcher, + callback: this.check + }; + return [matchClsCb]; + } + + public check = (arkClass: ArkClass): void => { + const scene = arkClass.getDeclaringArkFile().getScene(); + for (const field of arkClass.getFields()) { + if (!field.getDecorators().some(d => d.getKind() === 'State')) { + continue; + } + const fieldType = field.getType(); + if (!(fieldType instanceof ClassType)) { + continue; + } + const fieldClass = scene.getClass(fieldType.getClassSignature()); + const initializers = field.getInitializer(); + let canfindAllTargets = true; + let targets: Set = new Set(); + if (fieldClass?.getCategory() === ClassCategory.CLASS) { + targets.add(fieldClass); + } + let locals: Set = new Set(); + let start = (initializers[initializers.length - 1] as ArkAssignStmt).getRightOp() as Local; + locals.add(start); + for (const stmt of initializers.slice(0, -1).reverse()) { + if (!(stmt instanceof ArkAssignStmt)) { + continue; + } + + const leftOp = stmt.getLeftOp(); + const rightOp = stmt.getRightOp(); + if (!(leftOp instanceof Local)) { + continue; + } + if (!locals.has(leftOp)) { + continue; + } + if (rightOp instanceof Local) { + locals.add(rightOp); + } else if (rightOp instanceof ArkNewExpr) { + canfindAllTargets = this.handleNewExpr(scene, rightOp, targets); + } else { + canfindAllTargets = false; + } + } + + for (const target of targets) { + const pos = this.getClassPos(target); + this.addIssueReport(pos); + } + + if (!canfindAllTargets) { + const pos = this.getFieldPos(field); + this.addIssueReport(pos); + } + } + }; + + private handleNewExpr(scene: Scene, rightOp: ArkNewExpr, targets: Set): boolean { + let canfindAllTargets = true; + + const target = scene.getClass(rightOp.getClassType().getClassSignature()); + if (target && !target.isAnonymousClass()) { + targets.add(target); + const superClasses = target.getAllHeritageClasses(); + for (const superCls of superClasses) { + if (superCls.getCategory() === ClassCategory.CLASS) { + targets.add(superCls); + } + } + } else { + canfindAllTargets = false; + } + return canfindAllTargets; + } + + private getClassPos(cls: ArkClass): { line: number; startCol: number; endCol: number; filePath: string; } { + const arkFile = cls.getDeclaringArkFile(); + if (arkFile) { + const originPath = arkFile.getFilePath(); + const line = cls.getLine(); + const startCol = cls.getColumn(); + const endCol = startCol; + return { line, startCol, endCol, filePath: originPath }; + } else { + logger.debug('ArkFile is null.'); + return { line: -1, startCol: -1, endCol: -1, filePath: '' }; + } + } + + private getFieldPos(field: ArkField): { line: number; startCol: number; endCol: number; filePath: string; } { + const arkFile = field.getDeclaringArkClass().getDeclaringArkFile(); + const pos = field.getOriginPosition(); + if (arkFile && pos) { + const originPath = arkFile.getFilePath(); + const line = pos.getLineNo(); + const startCol = pos.getColNo(); + const endCol = startCol; + return { line, startCol, endCol, filePath: originPath }; + } else { + logger.debug('ArkFile is null.'); + return { line: -1, startCol: -1, endCol: -1, filePath: '' }; + } + } + + private addIssueReport(warnInfo: { line: number; startCol: number; endCol: number; filePath: string; }) { + const severity = this.rule.alert ?? this.metaData.severity; + let defects = new Defects(warnInfo.line, warnInfo.startCol, warnInfo.endCol, this.metaData.description, severity, this.rule.ruleId, + warnInfo.filePath, this.metaData.ruleDocPath, true, false, false); + this.issues.push(new IssueReport(defects, undefined)); + } +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/checker/migration/ThisBindCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/ThisBindCheck.ts new file mode 100644 index 0000000000..65bb480443 --- /dev/null +++ b/ets2panda/linter/homecheck/src/checker/migration/ThisBindCheck.ts @@ -0,0 +1,159 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkAssignStmt, ArkIfStmt, ArkInstanceFieldRef, ArkInstanceInvokeExpr, ArkMethod, ClassType, FunctionType, Local, Stmt, Value } from "arkanalyzer"; +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; +import { BaseChecker, BaseMetaData } from "../BaseChecker"; +import { Rule, Defects, MatcherTypes, MethodMatcher, MatcherCallback } from "../../Index"; +import { IssueReport } from "../../model/Defects"; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'ThisBindCheck'); +const gMetaData: BaseMetaData = { + severity: 1, + ruleDocPath: "", + description: 'Instance method shall bind the \'this\' by dafault.' +}; + +export class ThisBindCheck implements BaseChecker { + readonly metaData: BaseMetaData = gMetaData; + public rule: Rule; + public defects: Defects[] = []; + public issues: IssueReport[] = []; + + private methodMatcher: MethodMatcher = { + matcherType: MatcherTypes.METHOD + }; + + public registerMatchers(): MatcherCallback[] { + const methodCb: MatcherCallback = { + matcher: this.methodMatcher, + callback: this.check + } + return [methodCb]; + } + + public check = (targetMtd: ArkMethod) => { + const file = targetMtd.getDeclaringArkFile(); + if (file.getName().includes("test.ets")) { + return; + } + const scene = file.getScene(); + const stmts = targetMtd.getBody()?.getCfg().getStmts() ?? []; + for (let i = 0; i < stmts.length; ++i) { + const stmt = stmts[i]; + // const method = a.foo + if (!(stmt instanceof ArkAssignStmt)) { + continue; + } + const rightOp = stmt.getRightOp(); + if (!(rightOp instanceof ArkInstanceFieldRef)) { + continue; + } + const base = rightOp.getBase(); + const classTy = base.getType(); + if (!(classTy instanceof ClassType)) { + continue; + } + if (!(rightOp.getFieldSignature().getType() instanceof FunctionType)) { + continue; + } + const klass = scene.getClass(classTy.getClassSignature()); + const method = klass?.getMethodWithName(rightOp.getFieldName()); + if (!method || !method.getCfg() || !this.useThisInBody(method)) { + continue; + } + if (base.getName() === "this" && targetMtd.isAnonymousMethod()) { + continue; + } + const leftOp = stmt.getLeftOp(); + if (i + 1 >= stmts.length || !this.hasBindThis(leftOp, stmts[i + 1])) { + if (!this.isSafeUse(leftOp)) { + this.addIssueReport(stmt, base); + } + } + } + } + + private useThisInBody(method: ArkMethod): boolean { + const thisInstance = (method.getThisInstance() as Local)!; + return thisInstance.getUsedStmts().length > 0; + } + + private isSafeUse(v: Value): boolean { + if (!(v instanceof Local)) { + return false; + } + + const users = v.getUsedStmts(); + if (users.length === 0) { + return false; + } + for (const user of users) { + if (user instanceof ArkIfStmt) { + const cond = user.getConditionExpr(); + if (v !== cond.getOp1() && v !== cond.getOp2()) { + return false; + } + } else { + return false; + } + } + return true; + } + + private hasBindThis(base: Value, next: Stmt): boolean { + if (!(next instanceof ArkAssignStmt)) { + return false; + } + const rightOp = next.getRightOp(); + if (rightOp instanceof ArkInstanceFieldRef && rightOp.getBase() === base) { + // const method = a.foo.name + return true; + } + if (!(rightOp instanceof ArkInstanceInvokeExpr)) { + return false; + } + if (rightOp.getBase() !== base) { + return false; + } + if (rightOp.getMethodSignature().getMethodSubSignature().getMethodName() !== "bind") { + return false; + } + return true; + } + + private addIssueReport(stmt: Stmt, operand: Value) { + const severity = this.rule.alert ?? this.metaData.severity; + const warnInfo = this.getLineAndColumn(stmt, operand); + let defects = new Defects(warnInfo.line, warnInfo.startCol, warnInfo.endCol, this.metaData.description, severity, this.rule.ruleId, + warnInfo.filePath, this.metaData.ruleDocPath, true, false, false); + this.issues.push(new IssueReport(defects, undefined)); + } + + private getLineAndColumn(stmt: Stmt, operand: Value) { + const arkFile = stmt.getCfg()?.getDeclaringMethod().getDeclaringArkFile(); + const originPosition = stmt.getOperandOriginalPosition(operand); + if (arkFile && originPosition) { + const originPath = arkFile.getFilePath(); + const line = originPosition.getFirstLine(); + const startCol = originPosition.getFirstCol(); + const endCol = startCol; + return { line, startCol, endCol, filePath: originPath }; + } else { + logger.debug('ArkFile is null.'); + } + return { line: -1, startCol: -1, endCol: -1, filePath: '' }; + } +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/codeFix/FixEngine.ts b/ets2panda/linter/homecheck/src/codeFix/FixEngine.ts new file mode 100644 index 0000000000..6b312508d7 --- /dev/null +++ b/ets2panda/linter/homecheck/src/codeFix/FixEngine.ts @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Engine } from "../model/Engine"; +import { FixMode } from "../model/Fix"; +import { AIFixEngine } from "./engines/AIFixEngine"; +import { EsLintFixEngine } from "./engines/EsLintFixEngine"; +import { HomeCheckFixEngine } from "./engines/HomeCheckFixEngine"; + +export class FixEngine { + public getEngine(mode: FixMode): Engine { + if (mode === FixMode.AST) { + return new EsLintFixEngine(); + } else if (mode === FixMode.ARKFILE) { + return new HomeCheckFixEngine(); + } else if (mode === FixMode.AI) { + return new AIFixEngine(); + } + throw TypeError(`${mode} does not support!`); + } +} diff --git a/ets2panda/linter/homecheck/src/codeFix/engines/AIFixEngine.ts b/ets2panda/linter/homecheck/src/codeFix/engines/AIFixEngine.ts new file mode 100644 index 0000000000..bcfd58c7a5 --- /dev/null +++ b/ets2panda/linter/homecheck/src/codeFix/engines/AIFixEngine.ts @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkFile } from "arkanalyzer"; +import { FileReports, IssueReport } from "../../model/Defects"; +import { Engine } from "../../model/Engine"; +import Logger, { LOG_MODULE_TYPE } from "arkanalyzer/lib/utils/logger"; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'EsLintFixEngine'); + +export class AIFixEngine implements Engine { + applyFix(arkFile: ArkFile, isses: IssueReport[]): FileReports { + logger.info('Todo implement.'); + throw TypeError('todo implement'); + } +} diff --git a/ets2panda/linter/homecheck/src/codeFix/engines/EsLintFixEngine.ts b/ets2panda/linter/homecheck/src/codeFix/engines/EsLintFixEngine.ts new file mode 100644 index 0000000000..0c1583ed96 --- /dev/null +++ b/ets2panda/linter/homecheck/src/codeFix/engines/EsLintFixEngine.ts @@ -0,0 +1,145 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkFile } from "arkanalyzer"; +import { FileReports, IssueReport } from "../../model/Defects"; +import { Engine } from "../../model/Engine"; +import { RuleFix } from "../../model/Fix"; +import Logger, { LOG_MODULE_TYPE } from "arkanalyzer/lib/utils/logger"; +import { FixUtils } from "../../utils/common/FixUtils"; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'EsLintFixEngine'); +const BOM = '\uFEFF'; +let eof = '\r\n'; + + +export class EsLintFixEngine implements Engine { + applyFix(arkFile: ArkFile, fixIssues: IssueReport[], remainIssues: IssueReport[]): FileReports { + let sourceText = arkFile.getCode(); + const bom = sourceText.startsWith(BOM) ? BOM : "", + text = bom ? sourceText.slice(1) : sourceText; + let lastPos = Number.NEGATIVE_INFINITY, output = bom; + eof = FixUtils.getTextEof(text) || eof; + // issue非法数据检查及排序 + const ret = this.checkAndSortIssues(fixIssues, remainIssues); + fixIssues = ret.fixIssues, remainIssues = ret.remainIssues; + + if (fixIssues.length === 0) { + return { defects: remainIssues.map((issue => issue.defect)), output: '', filePath: arkFile.getFilePath() }; + } + // 深拷贝remainIssues,防止在遍历过程中修改remainIssues导致后续迭代出错 + const remainIssuesCopy = JSON.parse(JSON.stringify(remainIssues)); + for (const issue of fixIssues) { + let fix = issue.fix as RuleFix; + const start = fix.range[0]; + const end = fix.range[1]; + + output += text.slice(Math.max(0, lastPos), Math.max(0, start)); + output += fix.text; + lastPos = end; + fix.fixed = true; + this.updateRemainIssues(text, issue, remainIssues, remainIssuesCopy); + } + output += text.slice(Math.max(0, lastPos)); + return { defects: remainIssues.map((issue => issue.defect)), output: bom + output, filePath: arkFile.getFilePath() } + } + + private checkAndSortIssues(fixIssues: IssueReport[], remainIssues: IssueReport[]): { + fixIssues: IssueReport[], remainIssues: IssueReport[] } { + const fixIssuesValid: IssueReport[] = []; + fixIssues.forEach((issue) => { + const fix = issue.fix as RuleFix; + if (fix.range[0] <= fix.range[1] && fix.range[1] !== 0 && fix.range[0] >= 0) { + fixIssuesValid.push(issue); + } else { + remainIssues.push(issue); + } + }); + return { fixIssues: fixIssuesValid.sort(this.compareIssueByRange), remainIssues: remainIssues.sort(this.compareIssueByLocation) }; + } + + private compareIssueByRange(issue1: IssueReport, issue2: IssueReport) { + let fix1 = issue1.fix; + let fix2 = issue2.fix; + if (FixUtils.isRuleFix(fix1) && FixUtils.isRuleFix(fix2)) { + return fix1.range[0] - fix2.range[0] || fix1.range[1] - fix2.range[1]; + } else { + return 0; + } + } + + private compareIssueByLocation(a: IssueReport, b: IssueReport) { + return a.defect.reportLine - b.defect.reportLine || a.defect.reportColumn - b.defect.reportColumn; + } + + private updateRemainIssues(sourceText: string, issue: IssueReport, remainIssues: IssueReport[], remainIssuesOld: IssueReport[]): void { + if (remainIssues.length === 0) { + return; + } + let fix = issue.fix as RuleFix; + const start = fix.range[0]; + const end = fix.range[1]; + const fixEndCol = Number.parseInt(issue.defect.fixKey.split('%')[2]); + + const originLineNum = sourceText.slice(start, end).split(eof).length; + const fixTextLineNUM = fix.text.split(eof).length; + const subLine = fixTextLineNUM - originLineNum; + for (let i = 0; i < remainIssuesOld.length; i++) { + const defectOld = remainIssuesOld[i].defect; + const defectOldEndCol = Number.parseInt(defectOld.fixKey.split('%')[2]); + + // 1、当前告警区域完全在修复区域之前,不做处理。注意判断需使用旧的defect信息 + if (defectOld.reportLine < issue.defect.reportLine || + (defectOld.reportLine === issue.defect.reportLine && defectOldEndCol < issue.defect.reportColumn)) { + continue; + } + // 2、当前告警区域跟修复区域有重叠,不进行修复,直接删除该issue。TODO:该操作会导致重叠告警漏报,后续优化 + if (defectOld.reportLine === issue.defect.reportLine && + ((issue.defect.reportColumn < defectOld.reportColumn && defectOld.reportColumn < fixEndCol) || + (issue.defect.reportColumn < defectOldEndCol && defectOldEndCol < fixEndCol))) { + logger.warn(`The current defect area overlaps with the repair area, delete the defect, fixKey = ${defectOld.fixKey}`); + remainIssues.splice(i, 1); + remainIssuesOld.splice(i, 1); + i--; + continue; + } + // 注意行列号的累加需使用新的defect信息进行叠加 + const defectNew = remainIssues[i].defect; + // 更新行号 + defectNew.reportLine += subLine; + defectNew.fixKey = defectNew.fixKey.replace(/^[^%]*/, `${defectNew.reportLine}`); + defectNew.mergeKey = defectNew.mergeKey.replace(/%(.*?)%/, `%${defectNew.fixKey}%`); + // 更新列号, 当前告警跟修复issue在同一行,且在修复issue之后,需要进行列偏移 + if (defectOld.reportLine === issue.defect.reportLine) { + const splitText = fix.text.split(eof); + let endCol = 0; + if (splitText.length > 1) { + // 单行改多行,则偏移后的列号 = fixCode最后一行的长度 + 修复之前两个告警的间隔差值subCol + const subCol = defectNew.reportColumn - fixEndCol; + const colLen = Number.parseInt(defectNew.fixKey.split('%')[2]) - defectNew.reportColumn; + defectNew.reportColumn = splitText[splitText.length - 1].length + subCol; + endCol = defectNew.reportColumn + colLen; + } else { + // 单行改单行,则偏移后的列号 = 当前列号 + 修复后的列差(fixCode的长度 - 被替换的文本长度) + const subCol = fix.text.length - (end - start); + defectNew.reportColumn += subCol; + endCol = Number.parseInt(defectNew.fixKey.split('%')[2]) + subCol; + } + defectNew.fixKey = `${defectNew.reportLine}%${defectNew.reportColumn}%${endCol}%${defectNew.ruleId}`; + defectNew.mergeKey = defectNew.mergeKey.replace(/%(.*?)%/, `%${defectNew.fixKey}%`); + } + } + } +} diff --git a/ets2panda/linter/homecheck/src/codeFix/engines/HomeCheckFixEngine.ts b/ets2panda/linter/homecheck/src/codeFix/engines/HomeCheckFixEngine.ts new file mode 100644 index 0000000000..bb634e8eb6 --- /dev/null +++ b/ets2panda/linter/homecheck/src/codeFix/engines/HomeCheckFixEngine.ts @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkFile, SourceFilePrinter } from "arkanalyzer"; +import { FileReports, IssueReport } from "../../model/Defects"; +import { Engine } from "../../model/Engine"; +import { FunctionFix } from "../../model/Fix"; +import path from "path"; +import { removeSync } from "fs-extra"; +import { FileUtils, WriteFileMode } from "../../utils/common/FileUtils"; +import Logger, { LOG_MODULE_TYPE } from "arkanalyzer/lib/utils/logger"; +import { FixUtils } from "../../utils/common/FixUtils"; + +const FIX_OUTPUT_DIR = './fixedCode'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'HomeCheckFixEngine'); + +export class HomeCheckFixEngine implements Engine { + + constructor() { + removeSync(FIX_OUTPUT_DIR); + } + + applyFix(arkFile: ArkFile, issues: IssueReport[]): FileReports { + let fixPath = ''; + const remainIssues: IssueReport[] = []; + for (let issue of issues) { + let fix = issue.fix; + if (fix === undefined) { + remainIssues.push(issue); + continue; + } + if (!FixUtils.isFunctionFix(fix)) { + remainIssues.push(issue); + continue; + } + let functionFix = fix as FunctionFix; + if (!issue.defect.fixable) { + remainIssues.push(issue); + continue; + } + if (!functionFix.fix(arkFile, issue.defect.fixKey)) { + remainIssues.push(issue); + continue; + } + fixPath = path.join(FIX_OUTPUT_DIR, arkFile.getName() + '.fix'); + if (this.arkFileToFile(arkFile, fixPath)) { + functionFix.fixed = true; + break; + } + } + return {defects: remainIssues.map((issue => issue.defect)), output: '', filePath: fixPath}; + } + + private arkFileToFile(arkFile: ArkFile, outputPath: string): boolean { + if (!arkFile) { + return false; + } + const printer = new SourceFilePrinter(arkFile); + try { + FileUtils.writeToFile(outputPath, printer.dump(), WriteFileMode.OVERWRITE); + return true; + } catch (e) { + logger.error(e); + return false; + } + } +} diff --git a/ets2panda/linter/homecheck/src/matcher/Matchers.ts b/ets2panda/linter/homecheck/src/matcher/Matchers.ts new file mode 100644 index 0000000000..c817e6c135 --- /dev/null +++ b/ets2panda/linter/homecheck/src/matcher/Matchers.ts @@ -0,0 +1,227 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkField, ArkFile, ArkMethod, ArkNamespace, Scene } from "arkanalyzer"; +import { ArkClass, ClassCategory } from "arkanalyzer/lib/core/model/ArkClass"; + +export enum MethodCategory { + Accessor = 0, + ArrowFunction = 1, + FunctionExpression = 2, + Constructor = 3 +} + +export enum MatcherTypes { + FILE = 0, + NAMESPACE = 1, + CLASS = 2, + METHOD = 3, + FIELD = 4, + EXPR = 5 +} + +export interface BaseMatcher { + [matchFieldName: string]: any; +} + +//TODO: move to FileMatcher.ts +export interface FileMatcher extends BaseMatcher { + readonly matcherType: MatcherTypes.FILE; + name?: string; +} + +export interface NamespaceMatcher extends BaseMatcher { + readonly matcherType: MatcherTypes.NAMESPACE; + name?: string[]; + file?: (FileMatcher | ArkFile)[]; + namespace?: (NamespaceMatcher | ArkNamespace)[]; + isExport?: boolean; +} + +export interface ClassMatcher extends BaseMatcher { + readonly matcherType: MatcherTypes.CLASS; + name?: string[]; + file?: (FileMatcher | ArkFile)[]; + namespace?: (NamespaceMatcher | ArkNamespace)[]; + category?: ClassCategory[]; + isAbstract?: boolean; + isExport?: boolean; + extends?: (ClassMatcher | ArkClass)[]; + implements?: (ClassMatcher | ArkClass)[]; + hasViewTree?: boolean; +} + +export interface MethodMatcher extends BaseMatcher { + readonly matcherType: MatcherTypes.METHOD; + name?: string[]; + file?: (FileMatcher | ArkFile)[]; + namespace?: (NamespaceMatcher | ArkNamespace)[]; + class?: (ClassMatcher | ArkClass)[]; + category?: MethodCategory[]; + decorators?: string[]; + isStatic?: boolean; + isExport?: boolean; + isPublic?: boolean; + isPrivate?: boolean; + isProtected?: boolean; + isAbstract?: boolean; + hasViewTree?: boolean; + isAnonymous?: boolean; +} + +export interface FieldMatcher extends BaseMatcher { + readonly matcherType: MatcherTypes.FIELD; + name?: string[]; + file?: (FileMatcher | ArkFile)[]; + namespace?: (NamespaceMatcher | ArkNamespace)[]; + class?: (ClassMatcher | ArkClass)[]; + decorators?: string[]; + isStatic?: boolean; + isPublic?: boolean; + isPrivate?: boolean; + isProtected?: boolean; + isReadonly?: boolean; +} + +export interface MatcherCallback { + matcher: BaseMatcher | undefined, + callback: Function +} + +export function isMatchedFile(arkFile: ArkFile, matchers: (FileMatcher | ArkFile)[]): boolean { + for (const fileMatcher of matchers) { + if (fileMatcher instanceof ArkFile) { + if (arkFile === fileMatcher) { + return true; + } + } else { + if (fileMatcher.name && arkFile.getName() !== fileMatcher.name) { + continue; + } + return true; + } + } + return false; +} + +export function isMatchedNamespace(arkNs: ArkNamespace | null | undefined, matchers: (NamespaceMatcher | ArkNamespace)[]): boolean { + if (!arkNs) { + return false; + } + + for (const nsMatcher of matchers) { + if (nsMatcher instanceof ArkNamespace) { + if (arkNs === nsMatcher) { + return true; + } + } else { + if (nsMatcher.file && !isMatchedFile(arkNs.getDeclaringArkFile(), nsMatcher.file) || + nsMatcher.namespace && !isMatchedNamespace(arkNs.getDeclaringArkNamespace(), nsMatcher.namespace) || + nsMatcher.name && !nsMatcher.name.includes(arkNs.getName()) || + nsMatcher.isExported !== undefined && nsMatcher.isExported !== arkNs.isExport()) { + continue; + } + // todo: 未考虑嵌套ns场景 + return true; + } + } + return false; +} + +export function isMatchedClass(arkClass: ArkClass | null | undefined, matchers: (ClassMatcher | ArkClass)[]): boolean { + if (!arkClass) { + return false; + } + for (const classMatcher of matchers) { + if (classMatcher instanceof ArkClass) { + if (arkClass === classMatcher) { + return true; + } + } else { + if (classMatcher.file && !isMatchedFile(arkClass.getDeclaringArkFile(), classMatcher.file) || + classMatcher.namespace && !isMatchedNamespace(arkClass.getDeclaringArkNamespace(), classMatcher.namespace) || + classMatcher.name && !classMatcher.name.includes(arkClass.getName()) || + classMatcher.category && !classMatcher.category.includes(arkClass.getCategory()) || + classMatcher.isAbstract !== undefined && classMatcher.isAbstract !== arkClass.isAbstract() || + classMatcher.isExport !== undefined && classMatcher.isExport !== arkClass.isExport() || + classMatcher.hasViewTree !== undefined && classMatcher.hasViewTree !== arkClass.hasViewTree() || + // classMatcher.implements && !isMatchedClass(arkClass.getImplementedInterfaces(), classMatcher.implements) || + classMatcher.extends && !isMatchedClass(arkClass.getSuperClass(), classMatcher.extends)) { + continue; + } + return true; + } + } + return false; +} + +export function isMatchedMethod(arkMethod: ArkMethod | null | undefined, matchers: (MethodMatcher | ArkMethod)[]): boolean { + if (!arkMethod) { + return false; + } + for (const mtdMatcher of matchers) { + if (mtdMatcher instanceof ArkMethod) { + if (mtdMatcher === arkMethod) { + return true; + } + } else { + if (mtdMatcher.file && !isMatchedFile(arkMethod.getDeclaringArkFile(), mtdMatcher.file) || + mtdMatcher.namespace && !isMatchedNamespace(arkMethod.getDeclaringArkClass().getDeclaringArkNamespace(), mtdMatcher.namespace) || + mtdMatcher.class && !isMatchedClass(arkMethod.getDeclaringArkClass(), mtdMatcher.class) || + // mtdMatcher.category && !mtdMatcher.category.includes(arkMethod.getCategory()) || + mtdMatcher.isAnonymous && !arkMethod.isAnonymousMethod() || + mtdMatcher.name && !mtdMatcher.name.includes(arkMethod.getName()) || + mtdMatcher.decorators && !arkMethod.getDecorators().some(d => mtdMatcher.decorators!.includes(d.getKind())) || + mtdMatcher.isStatic !== undefined && mtdMatcher.isStatic !== arkMethod.isStatic() || + mtdMatcher.isExport !== undefined && mtdMatcher.isExport !== arkMethod.isExport() || + mtdMatcher.isPublic !== undefined && mtdMatcher.isPublic !== arkMethod.isPublic() || + mtdMatcher.isPrivate !== undefined && mtdMatcher.isPrivate !== arkMethod.isPrivate() || + mtdMatcher.isProtected !== undefined && mtdMatcher.isProtected !== arkMethod.isProtected() || + mtdMatcher.hasViewTree !== undefined && mtdMatcher.hasViewTree !== arkMethod.hasViewTree() || + mtdMatcher.isAbstract !== undefined && mtdMatcher.isAbstract !== arkMethod.isAbstract()) { + continue; + } + return true; + } + } + return false; +} + +export function isMatchedField(arkField: ArkField | null | undefined, matchers: (FieldMatcher | ArkField)[]): boolean { + if (!arkField) { + return false; + } + for (const fieldMatcher of matchers) { + if (fieldMatcher instanceof ArkField) { + if (fieldMatcher === arkField) { + return true; + } + } else { + if (fieldMatcher.file && !isMatchedFile(arkField.getDeclaringArkClass().getDeclaringArkFile(), fieldMatcher.file) || + fieldMatcher.namespace && !isMatchedNamespace(arkField.getDeclaringArkClass().getDeclaringArkNamespace(), fieldMatcher.namespace) || + fieldMatcher.class && !isMatchedClass(arkField.getDeclaringArkClass(), fieldMatcher.class) || + fieldMatcher.name && !fieldMatcher.name.includes(arkField.getName()) || + fieldMatcher.decorators && !arkField.getDecorators().some(d => fieldMatcher.decorators!.includes(d.getKind())) || + fieldMatcher.isStatic !== undefined && fieldMatcher.isStatic !== arkField.isStatic() || + fieldMatcher.isPublic !== undefined && fieldMatcher.isPublic !== arkField.isPublic() || + fieldMatcher.isPrivate !== undefined && fieldMatcher.isPrivate !== arkField.isPrivate() || + fieldMatcher.isProtected !== undefined && fieldMatcher.isProtected !== arkField.isProtected()) { + continue; + } + return true; + } + } + return false; +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchClass.ts b/ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchClass.ts new file mode 100644 index 0000000000..e9bb0cf523 --- /dev/null +++ b/ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchClass.ts @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkClass, ArkFile } from 'arkanalyzer'; +import { ClassMatcher, isMatchedFile, isMatchedNamespace, isMatchedClass } from '../Matchers'; + +export function matchClass(arkFiles: ArkFile[], matcher: ClassMatcher, callback: Function) { + for (let arkFile of arkFiles) { + if (matcher.file && !isMatchedFile(arkFile, matcher.file)) { + continue; + } + for (const ns of arkFile.getAllNamespacesUnderThisFile()) { + if (matcher.namespace && !isMatchedNamespace(ns, matcher.namespace)) { + continue; + } + matchClassProcess(matcher, ns.getClasses(), callback); + } + matchClassProcess(matcher, arkFile.getClasses(), callback); + } +} + +function matchClassProcess(matcher: ClassMatcher, classes: ArkClass[], callback: Function) { + for (const arkClass of classes) { + if (isMatchedClass(arkClass, [matcher])) { + callback(arkClass); + } + } +} diff --git a/ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchFields.ts b/ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchFields.ts new file mode 100644 index 0000000000..5e4d3496ab --- /dev/null +++ b/ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchFields.ts @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkClass, ArkFile } from 'arkanalyzer'; +import { isMatchedFile, isMatchedNamespace, isMatchedClass, FieldMatcher, isMatchedField } from '../Matchers'; + + +export function matchFields(arkFiles: ArkFile[], matcher: FieldMatcher, callback: Function) { + for (let arkFile of arkFiles) { + if (matcher.file && !isMatchedFile(arkFile, matcher.file)) { + continue; + } + for (const ns of arkFile.getAllNamespacesUnderThisFile()) { + if (matcher.namespace && !isMatchedNamespace(ns, matcher.namespace)) { + continue; + } + matchFieldsInClasses(matcher, ns.getClasses(), callback); + } + matchFieldsInClasses(matcher, arkFile.getClasses(), callback); + } +} + +function matchFieldsInClasses(matcher: FieldMatcher, classes: ArkClass[], callback: Function) { + for (const arkClass of classes) { + if (matcher.class && !isMatchedClass(arkClass, matcher.class)) { + continue; + } + for (const arkField of arkClass.getFields()) { + if (isMatchedField(arkField, [matcher])) { + callback(arkField); + } + } + } +} diff --git a/ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchFiles.ts b/ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchFiles.ts new file mode 100644 index 0000000000..cd56ad20d0 --- /dev/null +++ b/ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchFiles.ts @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkFile } from 'arkanalyzer'; +import { FileMatcher, isMatchedFile } from '../Matchers'; + +export function matchFiles(arkFiles: ArkFile[], matcher: FileMatcher, callback: Function) { + for (let arkFile of arkFiles) { + if (isMatchedFile(arkFile, [matcher])) { + callback(arkFile); + } + } +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchMethods.ts b/ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchMethods.ts new file mode 100644 index 0000000000..881cab942f --- /dev/null +++ b/ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchMethods.ts @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkClass, ArkFile } from 'arkanalyzer'; +import { MethodMatcher, isMatchedFile, isMatchedNamespace, isMatchedClass, isMatchedMethod } from '../Matchers'; + + +export function matchMethods(arkFiles: ArkFile[], matcher: MethodMatcher, callback: Function) { + for (let arkFile of arkFiles) { + if (matcher.file && !isMatchedFile(arkFile, matcher.file)) { + continue; + } + for (const ns of arkFile.getAllNamespacesUnderThisFile()) { + if (matcher.namespace && !isMatchedNamespace(ns, matcher.namespace)) { + continue; + } + matchMethodsInClasses(matcher, ns.getClasses(), callback); + } + matchMethodsInClasses(matcher, arkFile.getClasses(), callback); + } +} + +function matchMethodsInClasses(matcher: MethodMatcher, classes: ArkClass[], callback: Function) { + for (const arkClass of classes) { + if (matcher.class && !isMatchedClass(arkClass, matcher.class)) { + continue; + } + for (const arkMethod of arkClass.getMethods(true)) { + if (isMatchedMethod(arkMethod, [matcher])) { + callback(arkMethod); + } + } + } +} diff --git a/ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchNameSpaces.ts b/ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchNameSpaces.ts new file mode 100644 index 0000000000..4b628c28ba --- /dev/null +++ b/ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchNameSpaces.ts @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkFile } from 'arkanalyzer'; +import { NamespaceMatcher, isMatchedFile, isMatchedNamespace } from '../Matchers'; + +export function matchNameSpaces(arkFiles: ArkFile[], matcher: NamespaceMatcher, callback: Function) { + for (let arkFile of arkFiles) { + if (matcher.file && !isMatchedFile(arkFile, matcher.file)) { + continue; + } + for (const ns of arkFile.getAllNamespacesUnderThisFile()) { + if (isMatchedNamespace(ns, [matcher])) { + callback(ns); + } + } + } +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/model/Defects.ts b/ets2panda/linter/homecheck/src/model/Defects.ts new file mode 100644 index 0000000000..0338b8ae30 --- /dev/null +++ b/ets2panda/linter/homecheck/src/model/Defects.ts @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AIFix, FunctionFix, RuleFix } from "./Fix"; + +export const engine = { + engineName: '' +} + +export class Defects { + reportLine: number; + reportColumn: number; + description: string = ''; + severity: number = -1; // 0:info, 1:warning, 2:error + ruleId: string = '@perforce/'; + mergeKey: string = ''; // 文件路径%行号%开始列号%结束列号%规则%规则描述 + ruleDocPath: string = 'doc/.md'; + disabled: boolean = true; + checked: boolean = false; + fixable: boolean = false; // 是否可以修复 + fixKey: string = ''; // 行号%开始列号%结束列号%规则id + showIgnoreIcon: boolean = true; + engineName: string = engine.engineName; + + constructor(reportLine: number, reportColumn: number, endColumn: number, description: string, severity: number, ruleId: string, + filePath: string, ruleDocPath: string, disabled: boolean, checked: boolean, fixable: boolean, showIgnoreIcon: boolean = true) { + this.reportLine = reportLine; + this.reportColumn = reportColumn; + this.description = description; + this.severity = severity; + this.ruleId = ruleId; + this.fixKey = this.reportLine + '%' + this.reportColumn + '%' + endColumn + '%' + this.ruleId; + this.mergeKey = filePath + '%' + this.fixKey + '%' + this.description; + this.ruleDocPath = ruleDocPath; + this.disabled = disabled; + this.checked = checked; + this.fixable = fixable; + this.showIgnoreIcon = showIgnoreIcon; + } +} + +export class IssueReport { + defect: Defects; + fix: RuleFix | FunctionFix | AIFix | undefined; + + constructor(defect: Defects, fix: RuleFix | FunctionFix | AIFix | undefined) { + this.defect = defect; + this.fix = fix; + } +} + +export interface FileIssues { + filePath: string; + issues: IssueReport[]; +} + +export interface FileReports { + filePath: string; + defects: Defects[]; + output?: string; +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/model/Engine.ts b/ets2panda/linter/homecheck/src/model/Engine.ts new file mode 100644 index 0000000000..64c09751f9 --- /dev/null +++ b/ets2panda/linter/homecheck/src/model/Engine.ts @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkFile } from "arkanalyzer"; +import { FileReports, IssueReport } from "./Defects"; + +export interface Engine { + /** + * 首次调用修复引擎时会调用,不同引擎的后续修复,可以内部单独实现 + * @param arkFile + * @param fixIssues 需要修复的issues列表 + * @param remainIssues 剩余issues列表 + * @returns FileReports + */ + applyFix(arkFile: ArkFile, fixIssues: IssueReport[], remainIssues: IssueReport[]): FileReports +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/model/File2Check.ts b/ets2panda/linter/homecheck/src/model/File2Check.ts new file mode 100644 index 0000000000..87465db69c --- /dev/null +++ b/ets2panda/linter/homecheck/src/model/File2Check.ts @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ArkFile } from "arkanalyzer"; +import { BaseChecker } from "../checker/BaseChecker"; +import { MatcherTypes } from "../matcher/Matchers"; +import { matchFiles } from "../matcher/matcherAdapter/matchFiles"; +import { matchNameSpaces } from "../matcher/matcherAdapter/matchNameSpaces"; +import { matchClass } from "../matcher/matcherAdapter/matchClass"; +import { matchMethods } from "../matcher/matcherAdapter/matchMethods"; +import { matchFields } from "../matcher/matcherAdapter/matchFields"; +import { FileUtils } from "../utils/common/FileUtils"; +import { filterDisableIssue } from "../utils/common/Disable"; +import Logger, { LOG_MODULE_TYPE } from "arkanalyzer/lib/utils/logger"; +import { IssueReport } from "./Defects"; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'File2Check'); + +export class File2Check { + public arkFile: ArkFile; + public enabledRuleCheckerMap: Map = new Map(); // TODO: key改为枚举 + public issues: IssueReport[] = []; + + private flMatcherMap = new Map(); + private nsMatcherMap = new Map(); + private clsMatcherMap = new Map(); + private mtdMatcherMap = new Map(); + private fieldMatcherMap = new Map(); + + constructor() { + } + + public addChecker(ruleId: string, checker: BaseChecker) { + this.enabledRuleCheckerMap.set(ruleId, checker); + } + + public collectMatcherCallbacks() { + this.enabledRuleCheckerMap.forEach(checker => { + const matcherCallbacks = checker.registerMatchers(); + matcherCallbacks.forEach(obj => { + const matcher = obj.matcher; + const callback = obj.callback; + switch (matcher?.matcherType) { + case MatcherTypes.FILE: + this.flMatcherMap.set(matcher, callback); + break; + case MatcherTypes.NAMESPACE: + this.nsMatcherMap.set(matcher, callback); + break; + case MatcherTypes.CLASS: + this.clsMatcherMap.set(matcher, callback); + break; + case MatcherTypes.METHOD: + this.mtdMatcherMap.set(matcher, callback); + break; + case MatcherTypes.FIELD: + this.fieldMatcherMap.set(matcher, callback); + break; + } + }) + }); + } + + public async emitCheck() { + this.flMatcherMap.forEach((callback, matcher) => { + matchFiles([this.arkFile], matcher, callback) + }); + this.nsMatcherMap.forEach((callback, matcher) => { + matchNameSpaces([this.arkFile], matcher, callback) + }); + this.clsMatcherMap.forEach((callback, matcher) => { + matchClass([this.arkFile], matcher, callback) + }); + this.mtdMatcherMap.forEach((callback, matcher) => { + matchMethods([this.arkFile], matcher, callback) + }); + this.fieldMatcherMap.forEach((callback, matcher) => { + matchFields([this.arkFile], matcher, callback) + }); + } + + public collectIssues() { + this.enabledRuleCheckerMap.forEach((v, k) => { + this.issues.push(...(v.issues?.reduce((acc, cur) => { + if (acc.some((item) => item.defect.mergeKey === cur.defect.mergeKey)) { + logger.debug('Skip the repeated issue, please check. issue.mergeKey = ' + cur.defect.mergeKey); + } else { + acc.push(cur); + } + return acc; + }, [] as IssueReport[]))); + }); + } + + public async checkDisable() { + const fileLineList = await FileUtils.readLinesFromFile(this.arkFile.getFilePath()); + this.issues = filterDisableIssue(fileLineList, this.issues); + } + + public async run() { + this.collectMatcherCallbacks(); + await this.emitCheck(); + this.collectIssues(); + await this.checkDisable(); + } +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/model/Fix.ts b/ets2panda/linter/homecheck/src/model/Fix.ts new file mode 100644 index 0000000000..12dcdc4152 --- /dev/null +++ b/ets2panda/linter/homecheck/src/model/Fix.ts @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export type Range = [number, number]; + +export class FixInfo { + fixed?: boolean = false; +} + +// eslint修复信息 +export class RuleFix extends FixInfo { + /** + * 被修复字符串的起始位置 + */ + range: Range; + /** + * 要替换的文本 + */ + text: string; +} + +// homecheck的修复信息 +export class FunctionFix extends FixInfo { + /** + * 修复方法,入参为ArkFile和fixkey + */ + fix: Function; +} + +// AI修复的信息 +export class AIFix extends FixInfo { + /** + * 提供给大模型的修复语义 + */ + text: string[]; +} + +export enum FixMode { + AST, + ARKFILE, + AI, + UNKNOWN +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/model/Interfaces.ts b/ets2panda/linter/homecheck/src/model/Interfaces.ts new file mode 100644 index 0000000000..f0da83d853 --- /dev/null +++ b/ets2panda/linter/homecheck/src/model/Interfaces.ts @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export interface ImageInfo { + width: number; + height: number; + type?: string; +} + +export type ImagesInfo = { + images?: ImageInfo[] +} & ImageInfo + +export interface ImageData { + validate: (intput: Uint8Array) => boolean; + calculate: (input: Uint8Array, filepath?: string) => ImagesInfo +} + +export interface IAttributes { + width: number | null; + height: number | null; + viewbox?: IAttributes | null; +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/model/Message.ts b/ets2panda/linter/homecheck/src/model/Message.ts new file mode 100644 index 0000000000..a0a3a4d16d --- /dev/null +++ b/ets2panda/linter/homecheck/src/model/Message.ts @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; +import { FileReports } from './Defects'; +import { GeneratingJsonFile } from '../utils/common/GeneratingJsonFile'; +import path from 'path'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'Message'); + +export interface Message { + sendResult(fileReports: FileReports[], reportDir?: string): void; + messageNotify(messageLevel: MessageType, msg: string): void; + progressNotify(progress: number, msg: string): void; +} + +export class defaultMessage implements Message { + /** + * 发送消息 + * + * @param msg 要发送的消息内容 + */ + async sendResult(fileReports: FileReports[], reportDir?: string | undefined): Promise { + if (reportDir && reportDir.length !== 0) { + GeneratingJsonFile.generatingJsonFile(path.resolve(reportDir, 'issuesReport.json'), fileReports); + } else { + process.stdout.write(JSON.stringify(fileReports)); + } + } + + + /** + * 消息通知函数 + * + * @param messageLevel 消息类型,类型为MessageType枚举 + * @param msg 消息内容,类型为字符串 + */ + messageNotify(messageLevel: MessageType, msg: string): void { + logger.error(JSON.stringify(msg)); + return; + } + + + /** + * 通知进度更新 + * + * @param progress 进度值,取值范围为 0 到 1 之间 + * @param msg 与进度相关的消息 + */ + progressNotify(progress: number, msg: string): void { + const checkPercent = Math.floor(progress * 100); + if (checkPercent % 20 === 0) { + logger.info(`===== progress: ${checkPercent}% ======`); + } + } +} + +/** + * 告警消息类型 + */ +export enum MessageType { + BASE_ERROR = 0, + CHECK_ERROR = -1, + CHECK_WARN = -2, + CHECK_INFO = -3 +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/model/NumberValue.ts b/ets2panda/linter/homecheck/src/model/NumberValue.ts new file mode 100644 index 0000000000..67d6cf4995 --- /dev/null +++ b/ets2panda/linter/homecheck/src/model/NumberValue.ts @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export class NumberValue { + value: number; + type: ValueType; + + constructor(value: number, type: ValueType) { + this.value = value; + this.type = type; + } +} + +export enum ValueType { + INT, + DOUBLE, + UNKNOWN +} diff --git a/ets2panda/linter/homecheck/src/model/Project2Check.ts b/ets2panda/linter/homecheck/src/model/Project2Check.ts new file mode 100644 index 0000000000..6aad5f1aae --- /dev/null +++ b/ets2panda/linter/homecheck/src/model/Project2Check.ts @@ -0,0 +1,179 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ArkFile } from "arkanalyzer"; +import { BaseChecker } from "../checker/BaseChecker"; +import Logger, { LOG_MODULE_TYPE } from "arkanalyzer/lib/utils/logger"; +import { MatcherTypes } from "../matcher/Matchers"; +import { matchFiles } from "../matcher/matcherAdapter/matchFiles"; +import { matchNameSpaces } from "../matcher/matcherAdapter/matchNameSpaces"; +import { matchClass } from "../matcher/matcherAdapter/matchClass"; +import { matchMethods } from "../matcher/matcherAdapter/matchMethods"; +import { matchFields } from "../matcher/matcherAdapter/matchFields"; +import { FileUtils } from "../utils/common/FileUtils"; +import { filterDisableIssue } from "../utils/common/Disable"; +import { IssueReport } from "./Defects"; +import { Rule } from "./Rule"; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'Project2Check'); + +export class Project2Check { + public arkFiles: ArkFile[]; + public enabledRuleCheckerMap: Map = new Map(); // TODO: key改为枚举 + public issues: IssueReport[] = []; + public ruleMap: Map = new Map(); + + private sceneCallBacks: Function[] = []; + private flMatcherMap = new Map(); + private nsMatcherMap = new Map(); + private clsMatcherMap = new Map(); + private mtdMatcherMap = new Map(); + private fieldMatcherMap = new Map(); + + constructor() { + } + + public addChecker(ruleId: string, checker: BaseChecker) { + this.enabledRuleCheckerMap.set(ruleId, checker); + } + + public collectMatcherCallbacks() { + this.enabledRuleCheckerMap.forEach(checker => { + const matcherCallbacks = checker.registerMatchers(); + matcherCallbacks.forEach(obj => { + const matcher = obj.matcher; + const callback = obj.callback; + if (!matcher) { + this.sceneCallBacks.push(callback); + return; + } + switch (matcher.matcherType) { + case MatcherTypes.FILE: + this.flMatcherMap.set(matcher, callback); + break; + case MatcherTypes.NAMESPACE: + this.nsMatcherMap.set(matcher, callback); + break; + case MatcherTypes.CLASS: + this.clsMatcherMap.set(matcher, callback); + break; + case MatcherTypes.METHOD: + this.mtdMatcherMap.set(matcher, callback); + break; + case MatcherTypes.FIELD: + this.fieldMatcherMap.set(matcher, callback); + break; + default: + break; + } + }) + }); + } + + public async emitCheck() { + await Promise.all(Array.from(this.enabledRuleCheckerMap.values()).map(checker => { + try { + this.processSceneCallbacks(); + this.flMatcherMap.forEach((callback, matcher) => { + matchFiles(this.arkFiles, matcher, callback) + }); + this.nsMatcherMap.forEach((callback, matcher) => { + matchNameSpaces(this.arkFiles, matcher, callback) + }); + this.clsMatcherMap.forEach((callback, matcher) => { + matchClass(this.arkFiles, matcher, callback) + }); + this.mtdMatcherMap.forEach((callback, matcher) => { + matchMethods(this.arkFiles, matcher, callback) + }); + this.fieldMatcherMap.forEach((callback, matcher) => { + matchFields(this.arkFiles, matcher, callback) + }); + } catch (error) { + logger.error(`Checker ${checker.rule.ruleId} error: `, error); + } + })); + } + + private processSceneCallbacks(): void { + try { + this.sceneCallBacks.forEach((callback) => { + if (this.arkFiles.length !== 0) { + callback(this.arkFiles[0].getScene()); + } + }); + } catch (error) { + logger.error(`Error in scene callbacks: `, error); + } + } + + public collectIssues() { + this.enabledRuleCheckerMap.forEach((v, k) => { + this.issues.push(...(v.issues?.reduce((acc, cur) => { + if (acc.some((item) => item.defect.mergeKey === cur.defect.mergeKey)) { + logger.debug('Skip the repeated issue, please check. issue.mergeKey = ' + cur.defect.mergeKey); + } else { + acc.push(cur); + } + return acc; + }, [] as IssueReport[]))); + }); + const issueMap: Map = new Map(); + this.issues.forEach(issue => { + issueMap.set(issue.defect.mergeKey, issue); + }); + const issueCopyMap = new Map(issueMap); + for (const [key, value] of issueCopyMap.entries()) { + const index = value.defect.mergeKey.indexOf('%' + value.defect.fixKey); + let filePath = ''; + if (index !== -1) { + filePath = value.defect.mergeKey.slice(0, index); + } + if (!this.ruleMap.has(filePath)) { + continue; + } + let rules = this.ruleMap.get(filePath); + if (!rules) { + continue; + } + let result = rules.find(rule => rule.ruleId === value.defect.ruleId); + if (!result) { + issueMap.delete(value.defect.mergeKey); + } else { + value.defect.severity = result.alert; + } + } + this.issues = Array.from(issueMap.values()); + } + + public async checkDisable() { + let filtedIssues: IssueReport[] = []; + for (const issue of this.issues) { + const filePath = issue.defect.mergeKey.split('%')[0]; + const fileLineList = await FileUtils.readLinesFromFile(filePath); + const filtedResult = filterDisableIssue(fileLineList, [issue]); + if (filtedResult.length > 0) { + filtedIssues = filtedIssues.concat(filtedResult[0]); + } + } + this.issues = filtedIssues; + } + + public async run() { + this.collectMatcherCallbacks(); + await this.emitCheck(); + this.collectIssues(); + await this.checkDisable(); + } +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/model/ProjectConfig.ts b/ets2panda/linter/homecheck/src/model/ProjectConfig.ts new file mode 100644 index 0000000000..5d17f94620 --- /dev/null +++ b/ets2panda/linter/homecheck/src/model/ProjectConfig.ts @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Language } from 'arkanalyzer/lib/core/model/ArkFile'; + +export class ProjectConfig { + projectName: string; + projectPath: string; + logPath: string; + ohosSdkPath: string; + hmsSdkPath: string; + checkPath: string; + apiVersion: number; + fix: string; + fixSelected: boolean; + npmPath: string; + npmInstallDir: string; + reportDir: string; + sdksThirdParty: string[]; + arkCheckPath: string; + product: string; + + // [filePath, languageTag] or [folderPath, languageTag] + languageTags: Map; + // [...filePaths, ...folderPaths] + fileOrFolderToCheck: string[]; + + constructor(config: any) { + this.projectName = config.projectName ?? ''; + this.projectPath = config.projectPath ?? ''; + this.logPath = config.logPath ?? ''; + this.ohosSdkPath = config.ohosSdkPath ?? ''; + this.hmsSdkPath = config.hmsSdkPath ?? ''; + this.checkPath = config.checkPath ?? ''; + this.apiVersion = config.sdkVersion ?? 14; + this.fix = config.fix ?? 'false'; + this.fixSelected = config.fixSelected ?? false; + this.npmPath = config.npmPath ? config.npmPath : 'npm'; + this.npmInstallDir = config.npmInstallDir ? config.npmInstallDir : './'; + this.reportDir = config.reportDir ? config.reportDir : './'; + this.sdksThirdParty = config.sdksThirdParty ?? []; + this.arkCheckPath = config.arkCheckPath ?? ''; + this.product = config.product ?? ''; + this.languageTags = config.languageTags ?? new Map(); + this.fileOrFolderToCheck = config.fileOrFolderToCheck ?? []; + } +} + +export interface SelectedFileInfo { + filePath: string; + fixKey?: string[]; +} + +export class FileToCheck implements SelectedFileInfo { + public filePath: string; + + constructor(filePath: string) { + this.filePath = filePath; + } +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/model/Rule.ts b/ets2panda/linter/homecheck/src/model/Rule.ts new file mode 100644 index 0000000000..71a912835f --- /dev/null +++ b/ets2panda/linter/homecheck/src/model/Rule.ts @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export class Rule { + ruleId: string; + alert: ALERT_LEVEL; + allowExpressions: boolean + ignoreRestArgs: boolean + option: Object[] = [] + + constructor(ruleId: string, alert: ALERT_LEVEL = ALERT_LEVEL.SUGGESTION) { + this.ruleId = ruleId; + this.alert = alert; + this.allowExpressions = false; + this.ignoreRestArgs = false; + } +} + +export enum ALERT_LEVEL { + OFF = 0, + WARN = 1, + ERROR = 2, + SUGGESTION = 3, +} + +export interface ExtRuleSet { + ruleSetName: string; + packagePath: string; + extRules: object; +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/model/RuleConfig.ts b/ets2panda/linter/homecheck/src/model/RuleConfig.ts new file mode 100644 index 0000000000..281f4bc08a --- /dev/null +++ b/ets2panda/linter/homecheck/src/model/RuleConfig.ts @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { GlobMatch } from "../utils/common/GlobMatch"; + +export class RuleConfig { + public files: GlobMatch; + public ignore: GlobMatch; + public rules: object; + public extRules: object; + public extRuleSet: object[]; + public ruleSet: string[]; + public overrides: RuleConfig[]; + + constructor(config: any) { + if (config.files && config.files.length > 0) { + this.files = new GlobMatch(config.files); + } else { + this.files = new GlobMatch(['**/*.ets']); + } + if (config.ignore) { + if (config.ignore.length > 0) { + this.ignore = new GlobMatch(config.ignore); + } + } else if (config.excluded && config.excluded.length > 0) { + this.ignore = new GlobMatch(config.excluded); + } + this.rules = config.rules ?? {}; + this.extRules = config.extRules ?? {}; + this.extRuleSet = config.extRuleSet ?? []; + this.ruleSet = config.ruleSet ?? []; + + if (config.overrides) { + let overrides: RuleConfig[] = []; + let overRuleConfigs = config.overrides; + overRuleConfigs.forEach((overRuleConfig: any) => { + overrides.push(new RuleConfig(overRuleConfig)); + }); + this.overrides = overrides; + } else { + this.overrides = []; + } + } +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/model/Scope.ts b/ets2panda/linter/homecheck/src/model/Scope.ts new file mode 100644 index 0000000000..0710a9a41f --- /dev/null +++ b/ets2panda/linter/homecheck/src/model/Scope.ts @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BasicBlock } from "arkanalyzer"; +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; +import { Variable } from "./Variable"; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'Scope'); + +export enum TempLocation { + NOFOUND = 0, + LEFT, + RIGHT +} + +export enum ScopeType { + IF_TYPE = 0, + ELSE_TYPE, + FOR_CONDITION_TYPE, + FOR_IN_TYPE, + WHILE_TYPE, + CASE_TYPE, + UNKNOWN_TYPE = 10 +} + +export class Scope { + parentScope: Scope | null; + childScopeList: Array; + defList: Array; + blocks: Set; + scopeLevel: number; + scopeType: ScopeType; + + constructor(parent: Scope | null, defList: Array, level: number, type: ScopeType = ScopeType.UNKNOWN_TYPE) { + this.parentScope = parent; + this.childScopeList = new Array(); + this.defList = defList; + this.blocks = new Set(); + this.scopeLevel = level; + this.scopeType = type; + } + + public setChildScope(child: Scope): void { + this.childScopeList.push(child); + } + + public addVariable(variable: Variable): void { + this.defList.push(variable); + } +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/model/SparseArrayValue.ts b/ets2panda/linter/homecheck/src/model/SparseArrayValue.ts new file mode 100644 index 0000000000..59f6931abd --- /dev/null +++ b/ets2panda/linter/homecheck/src/model/SparseArrayValue.ts @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export class SparseArrayValue { + + sparseArrayType: SparseArrayType; + baseStr: string; + valStr: string; + fulBaseStr: string; + fulStmtStr: string; + constructor(StmtType: SparseArrayType, baseStr: string, valStr: string) { + this.sparseArrayType = StmtType; + this.baseStr = baseStr; + this.valStr = valStr; + this.fulBaseStr = this.baseStr + this.valStr; + if (this.sparseArrayType == SparseArrayType.NEW_ARRAY) { + this.fulStmtStr = this.fulBaseStr + ')'; + } else if (this.sparseArrayType == SparseArrayType.ARRAY_RIGHT) { + this.fulStmtStr = this.fulBaseStr + ']'; + } else if (this.sparseArrayType == SparseArrayType.ARRAY_LEFT) { + this.fulStmtStr = this.fulBaseStr + ']'; + } else { + this.fulStmtStr = this.fulBaseStr; + } + } +} + +export enum SparseArrayType { + NEW_ARRAY, + ARRAY_RIGHT, + ARRAY_LEFT, + UNKNOWN +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/model/StmtExt.ts b/ets2panda/linter/homecheck/src/model/StmtExt.ts new file mode 100644 index 0000000000..2d87c87ae4 --- /dev/null +++ b/ets2panda/linter/homecheck/src/model/StmtExt.ts @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Stmt } from "arkanalyzer"; +import { Scope } from "./Scope"; + +export class StmtExt extends Stmt { + scope: Scope; + toString(): string { + return ''; + } +} diff --git a/ets2panda/linter/homecheck/src/model/VarInfo.ts b/ets2panda/linter/homecheck/src/model/VarInfo.ts new file mode 100644 index 0000000000..33534649b2 --- /dev/null +++ b/ets2panda/linter/homecheck/src/model/VarInfo.ts @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Stmt } from "arkanalyzer"; +import { Scope } from "./Scope"; + +export class VarInfo { + stmt: Stmt; + scope: Scope; + + constructor(stmt: Stmt, scope: Scope) { + this.stmt = stmt; + this.scope = scope; + } +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/model/Variable.ts b/ets2panda/linter/homecheck/src/model/Variable.ts new file mode 100644 index 0000000000..2066a30d58 --- /dev/null +++ b/ets2panda/linter/homecheck/src/model/Variable.ts @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Local, Stmt } from "arkanalyzer"; +import { VarInfo } from "./VarInfo"; + +export class Variable { + defStmt: Stmt; + redefInfo: Set; + leftUsedInfo: Set; + + constructor(defStmt: Stmt) { + this.defStmt = defStmt; + this.redefInfo = new Set(); + this.leftUsedInfo = new Set(); + } + + public getName(): string { + return (this.defStmt.getDef() as Local).getName(); + } +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/run.ts b/ets2panda/linter/homecheck/src/run.ts new file mode 100644 index 0000000000..5196e1de7d --- /dev/null +++ b/ets2panda/linter/homecheck/src/run.ts @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { run } from "./Main"; + +run(); \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/runTool.ts b/ets2panda/linter/homecheck/src/runTool.ts new file mode 100644 index 0000000000..530d825115 --- /dev/null +++ b/ets2panda/linter/homecheck/src/runTool.ts @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ConfigUtils } from "./utils/common/ConfigUtils"; +import { Utils } from "./utils/common/Utils"; +import { MigrationTool } from "./tools/migrationTool/MigrationTool"; + +async function run(): Promise { + const argvObj = Utils.parseCliOptions(process.argv); + const ruleConfig = ConfigUtils.getConfig(argvObj.configPath, argvObj.arkCheckPath); + const projectConfig = ConfigUtils.getConfig(argvObj.projectConfigPath); + if (!ruleConfig || !projectConfig) { + return false; + } + + const migrationTool = new MigrationTool(ruleConfig, projectConfig); + await migrationTool.buildCheckEntry(); + const result = await migrationTool.start(); + + return true; +}; + +run(); \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/tools/BuildModuleChains.ts b/ets2panda/linter/homecheck/src/tools/BuildModuleChains.ts new file mode 100644 index 0000000000..1bb83d4672 --- /dev/null +++ b/ets2panda/linter/homecheck/src/tools/BuildModuleChains.ts @@ -0,0 +1,585 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { AbstractFieldRef, ArkAssignStmt, ArkFile, ArkIfStmt, ArkInvokeStmt, ArkMethod, ArkNamespace, ArkNewExpr, + ArkNormalBinopExpr, ArkStaticInvokeExpr, ArkUnopExpr, ClassSignature, ClassType, DEFAULT_ARK_CLASS_NAME, + FunctionType, LocalSignature, MethodSignature, NamespaceSignature, Scene, Signature, TEMP_LOCAL_PREFIX, Value, + transfer2UnixPath } from 'arkanalyzer'; +import { ArkClass, ClassCategory } from 'arkanalyzer/lib/core/model/ArkClass'; +import { ExportSignature } from 'arkanalyzer/lib/core/model/ArkExport'; +import { Local } from 'arkanalyzer/lib/core/base/Local'; +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; +import path from 'path'; +import { FileUtils, WriteFileMode } from '../utils/common/FileUtils'; + +const OUTPUT_DIR_PATH = './ModuleChains'; +const FILE_NAME_CHAINS_JSON = 'ModuleChains.json'; +const FILE_NAME_FILE_ID_MAP = 'FileIdMap.json'; +const FILE_NAME_CHAINS_TXT = 'ModuleChains.txt'; +const logger = Logger.getLogger(LOG_MODULE_TYPE.TOOL, 'BuildModuleChains'); + +type ModuleSignature = ExportSignature | string; +const gFinishScanMap = new Map(); +const gNodeMap: Map = new Map(); +const gModuleIdMap: Map = new Map(); +const repeatFilePath: string[] = []; +let gOutPutDirPath: string = OUTPUT_DIR_PATH; +let gIsSkipSdk = true; + +let gOutStorage = ''; +let gOutNum = 0; + +interface NodeInfo { + filePath: string; + name: string; + type: number; + line: number; +} + +export function buildModuleChains(scene: Scene, arkFiles: ArkFile[], outputDirPath: string): boolean { + let fileNameFlag = ''; + if (outputDirPath.length !== 0) { + gOutPutDirPath = outputDirPath; + } + if (arkFiles.length === 0) { + fileNameFlag = 'allFiles'; + arkFiles = scene.getFiles(); + } else { + fileNameFlag = arkFiles[0].getName(); + } + let isOutput = false; + for (const arkFile of arkFiles) { + const busyArray = new Array(); + fileProcess(arkFile, busyArray); + } + logger.debug('Scan completed, start to write file...'); + isOutput = genResultForJson(scene, fileNameFlag); + clearGlobalMem(); + return isOutput; +} + +function clearGlobalMem() { + gFinishScanMap.clear(); + gNodeMap.clear(); + gModuleIdMap.clear(); + repeatFilePath.length = 0; + gOutStorage = ''; + gOutNum = 0; +} + +function genResultForJson(scene: Scene, fileName: string): boolean { + for (const [module] of gFinishScanMap) { + if (typeof module === 'string') { + const uniqueId = genUniqueId(); + genJsonNode(scene, module, uniqueId); + } + } + return outputNodeList(fileName.replace(/[\\/]/g, '_')); +} + +function genUniqueId(): string { + return Math.random().toString(36).substring(2); +} + +function genJsonNode(scene: Scene, module: ModuleSignature, uniqueId: string) { + const nodeInfo = genNodeInfo(scene, module); + if (nodeInfo) { + gNodeMap.set(uniqueId, { nodeInfo: nodeInfo, nextNodes: [] }); + gModuleIdMap.set(module, uniqueId); + } else { + logger.warn(`create nodeInfo failed!`); + } + + let nextNodeList = gFinishScanMap.get(module); + if (!nextNodeList) { + return; + } + + for (const nextNode of nextNodeList) { + let nextUniqueId = gModuleIdMap.get(nextNode); + if (nextUniqueId) { + gNodeMap.get(uniqueId)?.nextNodes.push(nextUniqueId); + } else { + nextUniqueId = genUniqueId(); + gNodeMap.get(uniqueId)?.nextNodes.push(nextUniqueId); + genJsonNode(scene, nextNode, nextUniqueId); + } + } +} + +function classTypeToString(scene: Scene, classSign: ClassSignature): string { + const type = scene.getClass(classSign)?.getCategory(); + switch (type) { + case ClassCategory.CLASS: + return 'class'; + case ClassCategory.STRUCT: + return 'struct'; + case ClassCategory.INTERFACE: + return 'interface'; + case ClassCategory.ENUM: + return 'enum'; + case ClassCategory.TYPE_LITERAL: + return 'literal'; + case ClassCategory.OBJECT: + return 'object'; + default: + return ''; + } +} + +enum NodeType { + FILE = 0, + NAMESPACE, + CLASS, + STRUCT, + INTERFACE, + ENUM, + TYPE_LITERAL, + OBJECT, + FUNCTION, + VARIABLE +} + +function genNodeInfo(scene: Scene, module: ModuleSignature): NodeInfo | null { + let nodeInfo: NodeInfo | null = null; + if (module instanceof ClassSignature) { + const type = scene.getClass(module)?.getCategory(); + nodeInfo = { + filePath: module.getDeclaringFileSignature().getFileName(), + name: module.getClassName(), + // 底座ArkClass的枚举值差2 + type: (type !== undefined) ? type + 2 : -1, + line: -1 + }; + } else if (module instanceof MethodSignature) { + let className = module.getDeclaringClassSignature()?.getClassName(); + if (className === DEFAULT_ARK_CLASS_NAME) { + className = module.getDeclaringClassSignature().getDeclaringNamespaceSignature()?.getNamespaceName() ?? '' + } + let methodName = module.getMethodSubSignature().getMethodName(); + const methodLine = scene.getMethod(module)?.getLine(); + let curLine: number = -1; + if (methodLine) { + curLine = methodLine; + } + methodName = className.length > 0 ? `${className}.${methodName}` : methodName; + nodeInfo = { + filePath: module.getDeclaringClassSignature()?.getDeclaringFileSignature().getFileName(), + name: methodName, + type: NodeType.FUNCTION, + line: curLine + }; + } else if (module instanceof NamespaceSignature) { + nodeInfo = { + filePath: module.getDeclaringFileSignature().getFileName(), + name: module.getNamespaceName(), + type: NodeType.NAMESPACE, + line: -1 + }; + } else if (module instanceof LocalSignature) { + const fileSign = module.getDeclaringMethodSignature().getDeclaringClassSignature().getDeclaringFileSignature(); + const methodLine = scene.getMethod(module.getDeclaringMethodSignature())?.getLine(); + let curLine: number = -1; + if (methodLine) { + curLine = methodLine; + } + nodeInfo = { + filePath: fileSign.getFileName() ?? '', + name: module.getName(), + type: NodeType.VARIABLE, + line: curLine + }; + } else if (typeof module === 'string') { + nodeInfo = { + filePath: module, + name: path.basename(module), + type: NodeType.FILE, + line: -1 + }; + } + return nodeInfo; +} + +function genResultForChains(arkFile: ArkFile): boolean { + for (const [module] of gFinishScanMap) { + if (typeof (module) === 'string' && module.includes(arkFile.getFileSignature().getFileName().replace(/\//g, '\\'))) { + genChain(module); + } + } + if (gOutStorage.length > 0 && outputStorage()) { + logger.info(gOutStorage.length + ' chains have been written to the file.'); + return true; + } + return false; +} + +function genChain(module: ModuleSignature, headChain: string = '') { + const nextNodes = gFinishScanMap.get(module); + if (nextNodes) { + for (const nextNode of nextNodes) { + genChain(nextNode, headChain + module.toString().replace(`/${DEFAULT_ARK_CLASS_NAME}./g`, '') + '\n>>'); + } + } else { + gOutStorage += headChain + module.toString().replace(`/${DEFAULT_ARK_CLASS_NAME}./g`, '') + '\n'; + gOutNum++; + if (gOutNum >= 1000 && outputStorage()) { + gOutStorage = ''; + gOutNum = 0; + } + } +} + +function fileProcess(arkFile: ArkFile, busyArray: Array) { + const filePath = path.join('@' + arkFile.getProjectName(), transfer2UnixPath(arkFile.getName())); + if (!busyArray.includes(filePath) && !repeatFilePath.includes(filePath)) { + repeatFilePath.push(filePath); + busyArray.push(filePath); + const importList = arkFile.getImportInfos(); + for (const importModule of importList) { + const moduleSign = importModule.getLazyExportInfo()?.getArkExport()?.getSignature(); + if (!moduleSign) { + continue; + } + // 添加文件间依赖 + const importFile = importModule.getLazyExportInfo()?.getDeclaringArkFile(); + if (importFile) { + fileProcess(importFile, busyArray); + } + moduleDeeplyProcess(moduleSign, busyArray, arkFile.getScene()); + } + if (busyArray.length > 1 && typeof (busyArray[busyArray.length - 1]) === 'string') { + addLastNodeToMap(busyArray); + } + // 查找全局调用 + findGlobalDef(arkFile.getDefaultClass().getDefaultArkMethod(), busyArray); + busyArray.pop(); + } +} + +function findGlobalDef(dfltMethod: ArkMethod | null, busyArray: Array) { + const stmts = dfltMethod?.getBody()?.getCfg().getStmts(); + for (const stmt of stmts ?? []) { + if (stmt instanceof ArkInvokeStmt) { + busyArray.push(stmt.getInvokeExpr().getMethodSignature()); + addLastNodeToMap(busyArray); + busyArray.pop(); + } + } +} + +function moduleDeeplyProcess(moduleSign: Signature, busyArray: Array, scene: Scene ) { + if (moduleSign instanceof ClassSignature) { + classProcess(scene.getClass(moduleSign), busyArray); + } else if (moduleSign instanceof MethodSignature) { + methodProcess(scene.getMethod(moduleSign), busyArray); + } else if (moduleSign instanceof NamespaceSignature) { + namespaceProcess(scene.getNamespace(moduleSign), busyArray); + } else if (moduleSign instanceof LocalSignature) { + busyArray.push(moduleSign); + addLastNodeToMap(busyArray); + busyArray.pop(); + } +} + +function namespaceProcess(ns: ArkNamespace | null, busyArray: Array) { + if (!ns || busyArray.includes(ns.getSignature())) { + return; + } + const nsSign = ns.getSignature(); + busyArray.push(nsSign); + addLastNodeToMap(busyArray); + // 遍历过的节点不再遍历 + if (gFinishScanMap.has(nsSign)) { + busyArray.pop(); + return; + } + // 处理sdk跳过逻辑 + if (gIsSkipSdk && nsSign.getDeclaringFileSignature().getProjectName() !== ns.getDeclaringArkFile().getScene().getProjectName()) { + busyArray.pop(); + return; + } + // 处理当前层ns的类 + for (const arkClass of ns.getClasses()) { + classProcess(arkClass, busyArray); + } + // 递归处理嵌套ns的类 + for (const innerNs of ns.getNamespaces()) { + namespaceProcess(innerNs, busyArray); + } + busyArray.pop(); +} + +function classProcess(arkClass: ArkClass | null, busyArray: Array) { + if (!arkClass || busyArray.includes(arkClass.getSignature())) { + return; + } + const arkClassSign = arkClass.getSignature(); + busyArray.push(arkClassSign); + if (!arkClass.isAnonymousClass()) { + addLastNodeToMap(busyArray); + } + + // 遍历过的节点不再遍历 + if (gFinishScanMap.has(arkClassSign)) { + busyArray.pop(); + return; + } + // 处理sdk跳过逻辑 + if (gIsSkipSdk && arkClassSign.getDeclaringFileSignature().getProjectName() !== arkClass.getDeclaringArkFile().getScene().getProjectName()) { + busyArray.pop(); + return; + } + // 1、继承类处理 + superClassProcess(arkClass, busyArray); + // 2、成员变量处理 + arkFieldProcess(arkClass, busyArray); + // 3、方法内处理 + for (const arkMethod of arkClass.getMethods()) { + methodProcess(arkMethod, busyArray); + } + busyArray.pop(); +} + +function methodProcess(arkMethod: ArkMethod | null | undefined, busyArray: Array) { + if (!arkMethod || busyArray.includes(arkMethod.getSignature())) { + return; + } + const arkMethodSign = arkMethod.getSignature(); + busyArray.push(arkMethodSign); + if (!arkMethod.isAnonymousMethod()) { + addLastNodeToMap(busyArray); + } + // 遍历过的节点不再遍历 + if (gFinishScanMap.has(arkMethodSign)) { + busyArray.pop(); + return; + } + // 处理sdk跳过逻辑 + if (gIsSkipSdk && arkMethod.getDeclaringArkFile().getProjectName() !== arkMethod.getDeclaringArkFile().getScene().getProjectName()) { + busyArray.pop(); + return; + } + const stmts = arkMethod.getBody()?.getCfg()?.getStmts() ?? []; + const arkFile = arkMethod.getDeclaringArkFile(); + for (const stmt of stmts) { + if (stmt instanceof ArkInvokeStmt && stmt.getInvokeExpr() instanceof ArkStaticInvokeExpr) { + // 判断static调用是否为import, 仅考虑静态调用,示例调用场景在new stmt中处理 + staticExprProcess(stmt.getInvokeExpr() as ArkStaticInvokeExpr, arkFile, busyArray); + } else if (stmt instanceof ArkAssignStmt) { + // 判断右值中1、new class; 2、Local; 3、一元运算;4、二元运算;5、实例调用/实例字段 是否为import导入的模块 + rightOpProcess(stmt.getRightOp(), arkFile, busyArray); + } else if (stmt instanceof ArkIfStmt) { + // 判断ifStmt中变量或常量是否为import导入的模块 + ifStmtProcess(stmt, arkFile, busyArray); + } + } + busyArray.pop(); +} + +function staticExprProcess(invokeExpr: ArkStaticInvokeExpr, arkFile: ArkFile, busyArray: Array) { + const methodSignature = invokeExpr.getMethodSignature(); + const classSignature = methodSignature.getDeclaringClassSignature(); + const methodName = methodSignature.getMethodSubSignature().getMethodName(); + let className = classSignature.getClassName(); + if (className === DEFAULT_ARK_CLASS_NAME) { + className = classSignature.getDeclaringNamespaceSignature()?.getNamespaceName() ?? ''; + } + const fileSign = classSignature.getDeclaringFileSignature(); + let invokeFilePath = arkFile.getScene().getFile(fileSign)?.getFilePath(); + if (invokeFilePath && invokeFilePath === arkFile.getFilePath()) { + // 本文件的模块,深搜 + methodProcess(arkFile.getScene().getMethod(methodSignature), busyArray); + return; + } + // 导入的模块 + for (const importInfo of arkFile.getImportInfos()) { + const importName = importInfo.getImportClauseName(); + const typeSign = importInfo.getLazyExportInfo()?.getArkExport()?.getSignature(); + if (typeSign && (methodName === importName || className === importName)) { + moduleDeeplyProcess(typeSign, busyArray, arkFile.getScene()); + } + } +} + +function ifStmtProcess(stmt: ArkIfStmt, curFile: ArkFile, busyArray: Array) { + const op1 = stmt.getConditionExpr().getOp1(); + const op2 = stmt.getConditionExpr().getOp2(); + if (op1 instanceof Local) { + localProcess(op1, curFile, busyArray); + } + if (op2 instanceof Local) { + localProcess(op2, curFile, busyArray); + } +} + +function superClassProcess(arkClass: ArkClass, busyArray: Array) { + const superName = arkClass.getSuperClass()?.getName(); + if (!superName || busyArray.includes(arkClass.getSuperClass()?.getSignature()!)) { + return; + } + for (const importInfo of arkClass.getDeclaringArkFile().getImportInfos()) { + const typeSign = importInfo.getLazyExportInfo()?.getArkExport()?.getSignature(); + if (importInfo.getImportClauseName() === superName && typeSign) { + moduleDeeplyProcess(typeSign, busyArray, arkClass.getDeclaringArkFile().getScene()); + } + } +} + +function arkFieldProcess(arkClass: ArkClass, busyArray: Array) { + const arkFields = arkClass.getFields(); + for ( const arkField of arkFields) { + const fieldStmts = arkField.getInitializer(); + for (const stmt of fieldStmts) { + if (stmt instanceof ArkAssignStmt) { + rightOpProcess(stmt.getRightOp(), arkClass.getDeclaringArkFile(), busyArray); + } + } + } +} + +function rightOpProcess(rightOp: Value, curFile: ArkFile, busyArray: Array) { + if (rightOp instanceof ArkNewExpr) { + // 右值为new class场景 + const type = rightOp.getType(); + if (type instanceof ClassType) { + newExprProcess(type, curFile, busyArray); + } + } else if (rightOp instanceof Local) { + // 右值为Local场景 + localProcess(rightOp, curFile, busyArray); + } else if (rightOp instanceof ArkUnopExpr) { + // 右值为一元运算场景 + const ops = rightOp.getUses(); + for (const op of ops) { + if (op instanceof Local) { + localProcess(op, curFile, busyArray); + } + } + } else if (rightOp instanceof ArkNormalBinopExpr) { + // 右值为二元运算场景 + const op1 = rightOp.getOp1(); + const op2 = rightOp.getOp2(); + if (op1 instanceof Local) { + localProcess(op1, curFile, busyArray); + } + if (op2 instanceof Local) { + localProcess(op2, curFile, busyArray); + } + } else if (rightOp instanceof AbstractFieldRef) { + moduleDeeplyProcess(rightOp.getFieldSignature().getDeclaringSignature(), busyArray, curFile.getScene()); + } else if (rightOp instanceof ArkStaticInvokeExpr) { + staticExprProcess(rightOp, curFile, busyArray); + } +} + +function newExprProcess(type: ClassType, arkFile: ArkFile, busyArray: Array) { + const classSign = type.getClassSignature(); + const className = classSign.getClassName(); + const curFilePath = arkFile.getFilePath(); + const classFilePath = arkFile.getScene().getFile(classSign.getDeclaringFileSignature())?.getFilePath(); + if (!curFilePath || !classFilePath) { + logger.debug('Get curFilePath or classFilePath failed.'); + return; + } + if (curFilePath === classFilePath) { + // 本文件类 + classProcess(arkFile.getClass(classSign), busyArray); + } else { + // 非本文件类 + for (const importInfo of arkFile.getImportInfos()) { + const typeSign = importInfo.getLazyExportInfo()?.getArkExport()?.getSignature(); + if (className === importInfo.getImportClauseName() && typeSign) { + moduleDeeplyProcess(typeSign, busyArray, arkFile.getScene()); + } + } + } +} + +function localProcess(rightOp: Local, curFile: ArkFile, busyArray: Array) { + const type = rightOp.getType(); + // todo: Local变量为方法或者类地址,let a = class1,目前右值type为unknown,走else分支 + if (type instanceof ClassType) { + if (rightOp.getName().includes(TEMP_LOCAL_PREFIX)) { + return; + } + moduleDeeplyProcess(type.getClassSignature(), busyArray, curFile.getScene()); + } else if (type instanceof FunctionType) { + moduleDeeplyProcess(type.getMethodSignature(), busyArray, curFile.getScene()); + } else { + for (const importInfo of curFile.getImportInfos()) { + const typeSign = importInfo.getLazyExportInfo()?.getArkExport()?.getSignature(); + if (importInfo.getImportClauseName() === rightOp.getName() && typeSign) { + moduleDeeplyProcess(typeSign, busyArray, curFile.getScene()); + break; + } + } + } +} + +function isAnonymous(module: ModuleSignature): boolean { + return module.toString().includes('%A'); +} + +function addLastNodeToMap(busyArray: Array) { + let index = busyArray.length - 2; + let lastModule = busyArray[index]; + while (isAnonymous(lastModule) && index > 0) { + index--; + lastModule = busyArray[index]; + } + let curModule = busyArray[busyArray.length - 1]; + const storage = gFinishScanMap.get(lastModule); + if (!storage) { + gFinishScanMap.set(lastModule, [curModule]); + } else if (!storage.includes(curModule)) { + storage.push(curModule); + } +} + +function outputNodeList(fileName: string): boolean { + // 文件和节点编号映射落盘 + + // import链落盘 + try { + FileUtils.writeToFile(path.join(gOutPutDirPath, fileName + '_' + FILE_NAME_CHAINS_JSON), JSON.stringify(mapToJson(gNodeMap)), WriteFileMode.OVERWRITE); + return true; + } catch (error) { + logger.error((error as Error).message); + return false; + } +} + +function outputStorage() { + try { + FileUtils.writeToFile(path.join(gOutPutDirPath, FILE_NAME_CHAINS_TXT), gOutStorage); + return true; + } catch (error) { + logger.error((error as Error).message); + return false; + } +} + +function mapToJson(map: Map): any { + const obj: { [key: string]: any } = Object.create(null); + for (const [key, value] of map) { + if (value instanceof Map) { + // 递归转换嵌套的Map + obj[key] = mapToJson(value); + } else { + obj[key] = value; + } + } + return obj; +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/tools/depGraph/builder.ts b/ets2panda/linter/homecheck/src/tools/depGraph/builder.ts new file mode 100644 index 0000000000..720b240465 --- /dev/null +++ b/ets2panda/linter/homecheck/src/tools/depGraph/builder.ts @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {ArkFile, BUILD_PROFILE_JSON5, parseJsonText, Scene} from 'arkanalyzer'; +import {File, FileDepsGraph} from './fileComponent'; +import {ArkFileDeps} from './fileDeps'; +import Logger, {LOG_MODULE_TYPE} from 'arkanalyzer/lib/utils/logger'; +import {Module, ModuleDepsGraph} from './moduleComponent'; +import {ModuleDeps} from './moduleDeps'; +import {getModuleKind} from './utils'; +import path from 'path'; +import fs from 'fs'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.TOOL, 'DepGraph'); + +export function buildFileDepGraph(arkFiles: ArkFile[]): FileDepsGraph { + let depGraph: FileDepsGraph = new FileDepsGraph(); + let arkFileDeps = ArkFileDeps.getInstance(); + arkFiles.forEach(arkFile => { + const nodeAttr: File = { + name: arkFile.getFilePath(), + kind: 0, + }; + let srcNode = depGraph.addDepsNode(arkFile.getFilePath(), nodeAttr); + arkFileDeps.addDeps(depGraph, srcNode, arkFile); + }); + return depGraph; +} + +export function buildModuleDepGraph(scene: Scene): ModuleDepsGraph { + let moduleGraph: ModuleDepsGraph = new ModuleDepsGraph(); + let moduleDeps: ModuleDeps = ModuleDeps.getInstance(); + const modules = getModules(scene.getRealProjectDir()); + modules.forEach((modulePath) => { + logger.info(`Project module: ${modulePath} found.`); + const nodeAttr: Module = { + name: modulePath, + kind: getModuleKind(modulePath), + }; + if (!moduleGraph.hasDepsNode(modulePath)) { + let srcNode = moduleGraph.addDepsNode(modulePath, nodeAttr); + moduleDeps.addDeps(moduleGraph, srcNode); + } + }); + return moduleGraph; +} + +function getModules(projectPath: string): string[] { + const buildProfile = path.join(projectPath, BUILD_PROFILE_JSON5); + let modulePaths: string[] = []; + if (fs.existsSync(buildProfile)) { + let configurationsText: string; + try { + configurationsText = fs.readFileSync(buildProfile, 'utf-8'); + } catch (error) { + logger.error(`Error reading file: ${error}`); + return modulePaths; + } + const buildProfileJson = parseJsonText(configurationsText); + const modules = buildProfileJson.modules; + if (modules instanceof Array) { + modules.forEach((module) => { + modulePaths.push(path.resolve(projectPath, module.srcPath as string)); + }); + } + } else { + logger.warn('There is no build-profile.json5 for this project.'); + } + return modulePaths; +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/tools/depGraph/fileComponent.ts b/ets2panda/linter/homecheck/src/tools/depGraph/fileComponent.ts new file mode 100644 index 0000000000..04e8ad97ac --- /dev/null +++ b/ets2panda/linter/homecheck/src/tools/depGraph/fileComponent.ts @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {DependsGraph, DependsNode} from 'arkanalyzer/lib/core/graph/DependsGraph'; +import {GraphPrinter} from 'arkanalyzer'; + +export enum FileCategory { + FILE = 0, + PKG = 1, + SO = 2, + UNKNOWN = -1, +} + +export interface FileCategoryType { + name: string; + id: number; +} + +export function getComponentCategories(): FileCategoryType[] { + return Object.entries(FileCategory) + .filter((e) => !isNaN(e[0] as any)) + .map((e) => ({name: e[1] as string, id: parseInt(e[0])})); +} + +export interface File { + id?: number; + name: string; + version?: number; + files?: Set; + kind: FileCategory; + tag?: string; +} + +export interface ImportInfo4Dep { + importClauseName: string; + importType: string; + importFrom?: string; + nameBeforeAs?: string; + isDefault?: boolean; +} + +export interface FileEdgeAttr { + kind: 0; + // import clause name + import type, import info + attr: Map; +} + +export class FileDepsGraph extends DependsGraph { + public constructor() { + super(); + } + + addImportInfo2Edge(edge: FileEdgeAttr, importInfo: ImportInfo4Dep): void { + const attrKey = `${importInfo.importClauseName} + ${importInfo.importType}`; + edge.attr.set(attrKey, importInfo); + } + + public toJson(): { nodes: File[]; edges: any[]; categories: {} } { + return { + categories: getComponentCategories(), + nodes: Array.from(this.getNodesIter()).map((value) => { + let pkg = (value as DependsNode).getNodeAttr() as File; + pkg.id = (value as DependsNode).getID(); + return pkg; + }), + edges: Array.from(this.edgesMap.values()).map((value) => { + return { + source: value.getSrcID(), + target: value.getDstID(), + attr: Array.from(value.getEdgeAttr().attr.values()) + }; + }), + }; + } + + public dump(): string { + return new GraphPrinter(this).dump(); + } + + getGraphName(): string { + return 'File Dependency Graph'; + } +} diff --git a/ets2panda/linter/homecheck/src/tools/depGraph/fileDeps.ts b/ets2panda/linter/homecheck/src/tools/depGraph/fileDeps.ts new file mode 100644 index 0000000000..2e3f9a5304 --- /dev/null +++ b/ets2panda/linter/homecheck/src/tools/depGraph/fileDeps.ts @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type {ArkFile, ImportInfo} from 'arkanalyzer'; +import type {DependsNode} from 'arkanalyzer/lib/core/graph/DependsGraph'; +import type {File, FileDepsGraph, ImportInfo4Dep} from './fileComponent'; + +export class ArkFileDeps { + private static instance: ArkFileDeps; + + private constructor() { + } + + public static getInstance(): ArkFileDeps { + if (!this.instance) { + this.instance = new ArkFileDeps(); + } + return this.instance; + } + + public addDeps(depsGraph: FileDepsGraph, node: DependsNode, arkFile: ArkFile): void { + let importInfos = arkFile.getImportInfos(); + if (importInfos && importInfos.length > 0) { + for (let importInfo of importInfos) { + this.processImportInfo(depsGraph, node, importInfo); + } + } + } + + private processImportInfo(depsGraph: FileDepsGraph, src: DependsNode, importInfo: ImportInfo): void { + const nodeAttr = this.genNodeByImportInfo(importInfo); + if (nodeAttr) { + const dst = depsGraph.addDepsNode(nodeAttr.name, nodeAttr); + const edge = depsGraph.addEdge(src, dst, {kind: 0, attr: new Map()}); + depsGraph.addImportInfo2Edge(edge.getEdgeAttr(), this.simplifyImportInfo(importInfo)); + } + } + + private genNodeByImportInfo(importInfo: ImportInfo): File | undefined { + const lazyExport = importInfo.getLazyExportInfo(); + if (lazyExport) { + const exportArkFile = lazyExport.getDeclaringArkFile(); + if (exportArkFile) { + return { + name: exportArkFile.getFilePath(), + kind: 0, + }; + } + } + const from = importInfo.getFrom(); + if (from?.endsWith('.so')) { + return { + name: importInfo.getFrom()!, + kind: 0, + }; + } + if (from) { + return { + name: importInfo.getFrom()!, + kind: 1, + }; + } + return undefined; + } + + private simplifyImportInfo(importInfo: ImportInfo): ImportInfo4Dep { + return { + importClauseName: importInfo.getImportClauseName(), + importType: importInfo.getImportType(), + importFrom: importInfo.getFrom(), + nameBeforeAs: importInfo.getNameBeforeAs(), + isDefault: importInfo.isDefault(), + }; + } +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/tools/depGraph/moduleComponent.ts b/ets2panda/linter/homecheck/src/tools/depGraph/moduleComponent.ts new file mode 100644 index 0000000000..61e8f671a1 --- /dev/null +++ b/ets2panda/linter/homecheck/src/tools/depGraph/moduleComponent.ts @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {DependsGraph, DependsNode} from 'arkanalyzer/lib/core/graph/DependsGraph'; +import {GraphPrinter} from 'arkanalyzer'; + +export enum ModuleCategory { + ENTRY = 0, + FEATURE = 1, + HAR = 2, + HSP = 3, + THIRD_PARTY_PACKAGE = 4, + TAGGED_PACKAGE = 5, + UNKNOWN = -1, +} + +export interface ModuleCategoryType { + name: string; + id: number; +} + +export function getComponentCategories(): ModuleCategoryType[] { + return Object.entries(ModuleCategory) + .filter((e) => !isNaN(e[0] as any)) + .map((e) => ({name: e[1] as string, id: parseInt(e[0])})); +} + +export interface Module { + id?: number; + name: string; + version?: number; + files?: Set; + kind: ModuleCategory; + tag?: string; + originPath?: string;//for .har, .tgz, .hsp +} + +export interface ModuleEdgeAttr { + kind: 0; +} + +export class ModuleDepsGraph extends DependsGraph { + public constructor() { + super(); + } + + public toJson(): { nodes: Module[]; edges: any[]; categories: {} } { + return { + categories: getComponentCategories(), + nodes: Array.from(this.getNodesIter()).map((value) => { + let module = (value as DependsNode).getNodeAttr() as Module; + module.id = (value as DependsNode).getID(); + return module; + }), + edges: Array.from(this.edgesMap.values()).map((value) => { + return { + source: value.getSrcID(), + target: value.getDstID() + }; + }), + }; + } + + public dump(): string { + return new GraphPrinter(this).dump(); + } + + getGraphName(): string { + return 'Module Dependency Graph'; + } +} diff --git a/ets2panda/linter/homecheck/src/tools/depGraph/moduleDeps.ts b/ets2panda/linter/homecheck/src/tools/depGraph/moduleDeps.ts new file mode 100644 index 0000000000..1a84a2c289 --- /dev/null +++ b/ets2panda/linter/homecheck/src/tools/depGraph/moduleDeps.ts @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { fetchDependenciesFromFile, OH_PACKAGE_JSON5 } from 'arkanalyzer'; +import type { DependsNode } from 'arkanalyzer/lib/core/graph/DependsGraph'; +import { Module, ModuleCategory, ModuleDepsGraph } from './moduleComponent'; +import path from 'path'; +import fs from 'fs'; +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; +import { getModuleKind, OH_MODULES_DIR } from './utils'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.TOOL, 'moduleDeps'); + +export class ModuleDeps { + private static instance: ModuleDeps; + + private constructor() { + } + + public static getInstance(): ModuleDeps { + if (!this.instance) { + this.instance = new ModuleDeps(); + } + return this.instance; + } + + public addDeps(depsGraph: ModuleDepsGraph, src: DependsNode): void { + const moduleOhPkgPath = path.join(src.getNodeAttr().name, OH_PACKAGE_JSON5); + if (moduleOhPkgPath) { + const dstNodes: Module[] = this.getDstDeps(moduleOhPkgPath); + dstNodes.forEach((dstNode) => { + if (!depsGraph.hasDepsNode(dstNode.name)) { + const dst = depsGraph.addDepsNode(dstNode.name, dstNode); + const edge = depsGraph.addEdge(src, dst, { kind: 0 }); + this.addDeps(depsGraph, dst); + } + }); + } + } + + private getDstDeps(ohPkgPath: string): Module[] { + let dstDeps: Module[] = []; + const ohContent = fetchDependenciesFromFile(ohPkgPath); + let depMaps: Map = new Map(); + + if (ohContent && ohContent.dependencies) { + Object.entries(ohContent.dependencies).forEach(([name, value]) => { + dstDeps.push(this.genDstNode(name, value as string, ohPkgPath)); + }); + } + + return dstDeps; + } + + private genDstNode(key: string, value: string, ohPkgPath: string): Module { + if (value.startsWith('tag:')) { + return { + name: path.join(path.dirname(ohPkgPath), OH_MODULES_DIR, key), + kind: ModuleCategory.TAGGED_PACKAGE, + tag: value.replace(/^tag:/, ''), + }; + } else if (/^(file:|\.\/|\.\.\/)/.test(value)) { + return this.handleLocal(key, value.replace(/^file:/, ''), ohPkgPath); + } else if (/^[~^0-9]/.test(value)) { + return { + name: path.join(path.dirname(ohPkgPath), OH_MODULES_DIR, key), + kind: ModuleCategory.THIRD_PARTY_PACKAGE, + tag: value, + }; + } else { + return { + name: `Unknown: key is ${key}, value is ${value}, module path is ${path.dirname(ohPkgPath)}.`, + kind: ModuleCategory.UNKNOWN, + }; + } + } + + private handleLocal(moduleName: string, modulePath: string, ohPkgPath: string): Module { + const moduleInstalledPath = path.join(path.dirname(ohPkgPath), OH_MODULES_DIR, moduleName); + const originPkgPath = path.join(path.dirname(ohPkgPath), modulePath); + const isDir = fs.statSync(originPkgPath).isDirectory(); + let moduleKind = getModuleKind(moduleInstalledPath); + if (moduleKind === ModuleCategory.UNKNOWN && (modulePath.endsWith('.hsp') || modulePath.endsWith('.tgz'))) { + moduleKind = ModuleCategory.HSP; + } else if (moduleKind === ModuleCategory.UNKNOWN && (modulePath.endsWith('.har'))) { + moduleKind = ModuleCategory.HAR; + } + return { + name: isDir ? originPkgPath : moduleInstalledPath, + kind: moduleKind, + originPath: isDir ? undefined : originPkgPath, + }; + } +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/tools/depGraph/utils.ts b/ets2panda/linter/homecheck/src/tools/depGraph/utils.ts new file mode 100644 index 0000000000..0fbd2ae0af --- /dev/null +++ b/ets2panda/linter/homecheck/src/tools/depGraph/utils.ts @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import fs from 'fs'; +import {fetchDependenciesFromFile, OH_PACKAGE_JSON5} from 'arkanalyzer'; +import Logger, {LOG_MODULE_TYPE} from 'arkanalyzer/lib/utils/logger'; +import path from 'path'; +import {ModuleCategory} from './moduleComponent'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.TOOL, 'depGraphUtils'); + +export const OH_MODULES_DIR = './oh_modules/'; + +export function getModuleKind(modulePath: string): ModuleCategory { + const moduleJson5Path = path.join(modulePath, './src/main/module.json5'); + const content = fetchDependenciesFromFile(moduleJson5Path); + if (!content.type) { + switch (content.type as string) { + case 'entry': + return ModuleCategory.ENTRY; + case 'feature': + return ModuleCategory.FEATURE; + case 'har': + return ModuleCategory.HAR; + case 'shared': + return ModuleCategory.HSP; + default: + break; + } + } + + const ohPkgPath = path.join(modulePath, OH_PACKAGE_JSON5); + if (!fs.existsSync(ohPkgPath)) { + return ModuleCategory.UNKNOWN; + } + const ohPkgContent = fetchDependenciesFromFile(ohPkgPath); + if (ohPkgContent.packageType) { + return ModuleCategory.HSP; + } else { + return ModuleCategory.HAR; + } +} diff --git a/ets2panda/linter/homecheck/src/tools/migrationTool/ExportIssue.ts b/ets2panda/linter/homecheck/src/tools/migrationTool/ExportIssue.ts new file mode 100644 index 0000000000..7d3b3bb62f --- /dev/null +++ b/ets2panda/linter/homecheck/src/tools/migrationTool/ExportIssue.ts @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { CheckEntry } from '../../utils/common/CheckEntry'; + +export interface ProblemInfo { + line: number; + column: number, + endLine: number; + endColumn: number; + start?: number; + end?: number; + type?: string; + severity: number; + problem: string; + suggest: string; + rule: string; + ruleTag: number; + autofixable?: boolean; + aotufix?: AutoFix[]; + autofixTitle?: string; +} + +export interface AutoFix { + replacementText: string; + start: number; + end: number; +} + +export async function exportIssues(checkEntry: CheckEntry): Promise> { + let result = new Map(); + checkEntry.sortIssues().forEach(fileIssue => { + const problemInfos: ProblemInfo[] = fileIssue.issues.map(issueReport => { + const defect = issueReport.defect; + const line = defect.reportLine; + const column = defect.reportColumn; + const endLine = line; + const endColumn = column; + const severity = defect.severity; + const problem = defect.description; + const suggest = ''; + const rule = defect.ruleId; + const ruleTag = -1; + const autofixable = false; + return { line, column, endLine, endColumn, severity, problem, suggest, rule, ruleTag, autofixable }; + }); + result.set(fileIssue.filePath, problemInfos); + }); + return result; +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/tools/migrationTool/MigrationTool.ts b/ets2panda/linter/homecheck/src/tools/migrationTool/MigrationTool.ts new file mode 100644 index 0000000000..6c5ab6f581 --- /dev/null +++ b/ets2panda/linter/homecheck/src/tools/migrationTool/MigrationTool.ts @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { CheckEntry, checkEntryBuilder } from '../../utils/common/CheckEntry'; +import { RuleConfig } from '../../model/RuleConfig'; +import { ProjectConfig } from '../../model/ProjectConfig'; +import { Utils } from '../../utils/common/Utils'; +import { CheckerStorage } from '../../utils/common/CheckerStorage'; +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; +import { FileUtils } from '../../utils/common/FileUtils'; +import { defaultMessage } from '../../model/Message'; +import { exportIssues, ProblemInfo } from './ExportIssue'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'MigrationTool'); + +export class MigrationTool { + private checkEntry: CheckEntry; + + constructor(ruleConfig: any, projectConfig: any) { + this.checkEntry = new CheckEntry(); + // 解析规则配置文件 + this.checkEntry.ruleConfig = new RuleConfig(ruleConfig); + // 解析项目配置文件 + this.checkEntry.projectConfig = new ProjectConfig(projectConfig); + } + + public async buildCheckEntry(): Promise { + logger.info(`buildCheckEntry start`); + // 日志配置 + const logPath = this.checkEntry.projectConfig.logPath; + Utils.setLogPath(logPath.length === 0 ? './HomeCheck.log' : logPath); + // api版本配置 + CheckerStorage.getInstance().setApiVersion(this.checkEntry.projectConfig.apiVersion); + // product配置 + CheckerStorage.getInstance().setProduct(this.checkEntry.projectConfig.product); + // 设置指定文件检查,不设置默认检查所有文件 + this.checkEntry.setCheckFileList(FileUtils.getFileInfoFromFileList(this.checkEntry.projectConfig.fileOrFolderToCheck)); + + // 外部没有建立消息通道,使用默认通道 + if (!this.checkEntry.message) { + this.checkEntry.message = new defaultMessage(); + } + + // 前处理 + if (!await checkEntryBuilder(this.checkEntry)) { + return false; + } + logger.info(`buildCheckEntry end`); + return true; + } + + public async start(): Promise> { + logger.info(`MigrationTool run start`); + await this.checkEntry.runAll(); + + let result = await exportIssues(this.checkEntry); + logger.info(`MigrationTool run end`); + return result; + } +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/tools/toolEntry.ts b/ets2panda/linter/homecheck/src/tools/toolEntry.ts new file mode 100644 index 0000000000..1fc8811c89 --- /dev/null +++ b/ets2panda/linter/homecheck/src/tools/toolEntry.ts @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {ArkFile, Scene, SceneConfig} from 'arkanalyzer'; +import Logger, {LOG_MODULE_TYPE} from 'arkanalyzer/lib/utils/logger'; +import {buildModuleChains} from './BuildModuleChains'; +import {ProjectConfig} from '../model/ProjectConfig'; +import {FileUtils, WriteFileMode} from '../utils/common/FileUtils'; +import {Utils} from '../utils/common/Utils'; +import {buildFileDepGraph, buildModuleDepGraph} from './depGraph/builder'; +import {OptionValues} from 'commander'; +import {ConfigUtils} from '../Index'; +import path from 'path'; +import fs from 'fs'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.TOOL, 'runTool'); + +export function runTool(tool: Tools, argvObj: OptionValues): void { + const startTime = new Date().getTime(); + const projectConfig = new ProjectConfig(ConfigUtils.getConfig(argvObj.projectConfigPath)); + let depGraphOutputDir = argvObj.depGraphOutputDir; + + try { + // 配置日志文件路径 + const logPath = projectConfig.logPath; + Utils.setLogPath(logPath.length ? logPath : './HomeCheckTools.log'); + logger.info('start to run tool...'); + const scene = buildScene(projectConfig); + if (!scene) { + return; + } + // 运行对应工具模块 + switch (tool) { + case Tools.ImportChains: + logger.info('start to buildModuleChains...'); + buildModuleChains(scene, [], projectConfig.reportDir); + logger.info('buildModuleChains completed.'); + break; + case Tools.DepGraph: + if (!depGraphOutputDir) { + logger.warn('The output directory of dependency graph is not set, by default it will be set to current directory.'); + depGraphOutputDir = './'; + } + if (!fs.existsSync(depGraphOutputDir)) { + logger.error(`The given depGraphOutputDir: ${depGraphOutputDir} is not exist.`); + process.exit(-1); + } + genFileDepGraph(depGraphOutputDir, scene.getFiles()); + genModuleDepGraph(depGraphOutputDir, scene); + break; + default: + logger.error(`Unknown tool: ${tool}`); + break; + } + } catch (error) { + logger.error(`Error occurred: ${(error as Error).message}`); + return; + } + const endTime = new Date().getTime(); + logger.info(`HomeCheck tools took: ${(endTime - startTime) / 1000}s`); +} + +function buildScene(projectConfig: ProjectConfig): Scene | null { + try { + // 构建SceneConfig + const config: SceneConfig = new SceneConfig(); + const fileList = FileUtils.getAllFiles(projectConfig.projectPath, ['.ts', '.ets']); + config.buildFromProjectFiles(projectConfig.projectName, projectConfig.projectPath, fileList, FileUtils.genSdks(projectConfig)); + logger.info('Build sceneConfig completed.'); + // 构建Scene + const scene = new Scene(); + scene.buildSceneFromFiles(config); + logger.info('Build scene completed.'); + scene.inferTypes(); + logger.info('Infer types completed.'); + return scene; + } catch (error) { + logger.error(`Build scene or infer types error: ${(error as Error).message}`); + return null; + } +} + +function genFileDepGraph(outputPath: string, arkFiles: ArkFile[]): void { + const fileDepGraphJson = path.join(outputPath, './fileDepGraph.json'); + const fileDepGraphDot = path.join(outputPath, './fileDepGraph.dot'); + + logger.info('Started to build file dependency graph...'); + + const depGraph = buildFileDepGraph(arkFiles); + + const jsonRes = JSON.stringify(depGraph.toJson()); + FileUtils.writeToFile(fileDepGraphJson, jsonRes, WriteFileMode.OVERWRITE); + logger.info('Building dependency graph in json format has completed.'); + + const dotRes = depGraph.dump(); + FileUtils.writeToFile(fileDepGraphDot, dotRes, WriteFileMode.OVERWRITE); + logger.info('Building dependency graph in dot format has completed.'); + + logger.info('Building file dependency graph completed.'); +} + +function genModuleDepGraph(outputPath: string, scene: Scene): void { + const moduleDepGraphJson = path.join(outputPath, './moduleDepGraph.json'); + const moduleDepGraphDot = path.join(outputPath, './moduleDepGraph.dot'); + + logger.info('Started to build module dependency graph...'); + + const depGraph = buildModuleDepGraph(scene); + + const jsonRes = JSON.stringify(depGraph.toJson()); + FileUtils.writeToFile(moduleDepGraphJson, jsonRes, WriteFileMode.OVERWRITE); + logger.info('Building module graph in json format has completed.'); + + const dotRes = depGraph.dump(); + FileUtils.writeToFile(moduleDepGraphDot, dotRes, WriteFileMode.OVERWRITE); + logger.info('Building module graph in dot format has completed.'); + + logger.info('Building file module graph completed.'); +} + +export enum Tools { + ImportChains = 0, + DepGraph = 1, +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/tools/toolRun.ts b/ets2panda/linter/homecheck/src/tools/toolRun.ts new file mode 100644 index 0000000000..c896db61da --- /dev/null +++ b/ets2panda/linter/homecheck/src/tools/toolRun.ts @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {Utils} from '../utils/common/Utils'; +import {runTool, Tools} from './toolEntry'; + +(function run() { + const argvObj = Utils.parseCliOptions(process.argv); + runTool(Tools.DepGraph, argvObj); +})(); \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/utils/checker/AbilityInterface.ts b/ets2panda/linter/homecheck/src/utils/checker/AbilityInterface.ts new file mode 100644 index 0000000000..0055d844d5 --- /dev/null +++ b/ets2panda/linter/homecheck/src/utils/checker/AbilityInterface.ts @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Record the module in the module.json5. + */ +export interface moduleJson5Module { + name: string; + type: string; + description: string; + mainElement: string; + deviceTypes: string[]; + deliveryWithInstall: boolean; + installationFree: boolean; + abilities: moduleAbility[]; + extensionAbilities: extensionAbility[]; +} + +/** + * Record the ability in the module. + */ +export interface moduleAbility { + name: string; + srcEntry: string; + description: string; + icon: string; + label: string; + startWindowIcon: string; + startWindowBackground: string; + exported: boolean; + skills: abilitySkill[]; +} + +/** + * Record the skill in the ability. + */ +interface abilitySkill { + entities: string[]; + actions: string[]; +} + +/** + * Record the extensionAbility in the module. + */ +export interface extensionAbility { + name: string; + srcEntry: string; + description: string; + icon: string; + label: string; + type: string; + metadata: extensionAbilityMetadata[]; +} + +/** + * Record the metadata in the extensionAbility. + */ +interface extensionAbilityMetadata { + name: string; + resource: string; +} + +/** + * Record the app in the app.json5. + */ +export interface appJson5App { + bundleName: string; + vendor: string; + versionCode: number; + versionName: string; + devicetypes: string[]; + icon: string; + label: string; +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/utils/checker/BytesUtils.ts b/ets2panda/linter/homecheck/src/utils/checker/BytesUtils.ts new file mode 100644 index 0000000000..4be9d506a1 --- /dev/null +++ b/ets2panda/linter/homecheck/src/utils/checker/BytesUtils.ts @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +const decoder = new TextDecoder(); +export const toUTF8String = ( + input: Uint8Array, + start = 0, + end = input.length +) => decoder.decode(input.slice(start, end)); + +export const toHexString = ( + input: Uint8Array, + start = 0, + end = input.length +) => input.slice(start, end).reduce((memo, i) => memo + `0${i.toString(16)}`.slice(-2), ''); + +const getView = ( + input: Uint8Array, + offset: number +) => new DataView(input.buffer, input.byteOffset + offset); + +export const readInt16LE = (input: Uint8Array, offset = 0) => + getView(input, offset).getInt16(0, true); + +export const readUInt16BE = (input: Uint8Array, offset = 0) => + getView(input, offset).getUint16(0, false); + +export const readUInt16LE = (input: Uint8Array, offset = 0) => + getView(input, offset).getUint16(0, true); + +export const readUInt24LE = (input: Uint8Array, offset = 0) => { + const view = getView(input, offset); + return view.getUint16(0, true) + (view.getUint8(2) << 16); +}; + +export const readInt32LE = (input: Uint8Array, offset = 0) => + getView(input, offset).getInt32(0, true); + +export const readUInt32BE = (input: Uint8Array, offset = 0) => + getView(input, offset).getUint32(0, false); + +export const readUInt32LE = (input: Uint8Array, offset = 0) => + getView(input, offset).getUint32(0, true); + +export const readUInt64 = ( + input: Uint8Array, + offset: number, + isBigEndian: boolean +): bigint => getView(input, offset).getBigUint64(0, !isBigEndian); + +const methods = { + readUInt16BE, + readUInt16LE, + readUInt32BE, + readUInt32LE +} as const + +type MethodName = keyof typeof methods; + +export function readUInt( + input: Uint8Array, + bits: 16 | 32, + offset = 0, + isBigEndian = false +): number { + const endian = isBigEndian ? 'BE' : 'LE'; + const methodName = `readUInt${bits}${endian}` as MethodName; + return methods[methodName](input, offset); +} + +const INCH_CM = 2.54; + +const units: Record = { + in: 96, + cm: 96 / INCH_CM, + em: 16, + ex: 8, + m: (96 / INCH_CM) * 100, + mm: 96 / INCH_CM / 10, + pc: 96 / 72 / 12, + pt: 96 / 72, + px: 1, +} +const unitsReg = new RegExp(`^([0-9.]+(?:e\\d+)?)(${Object.keys(units).join('|')})?$`,); + +export function getLength(len: string): number | undefined { + const m = unitsReg.exec(len); + if (!m) { + return undefined; + } + return Math.round(Number(m[1]) * (units[m[2]] || 1)); +} diff --git a/ets2panda/linter/homecheck/src/utils/checker/CheckerUtils.ts b/ets2panda/linter/homecheck/src/utils/checker/CheckerUtils.ts new file mode 100644 index 0000000000..97e7ff487a --- /dev/null +++ b/ets2panda/linter/homecheck/src/utils/checker/CheckerUtils.ts @@ -0,0 +1,178 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ArkAssignStmt, ArkInvokeStmt, Stmt } from 'arkanalyzer/lib/core/base/Stmt'; +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; +import { AbstractInvokeExpr, ArkAwaitExpr } from 'arkanalyzer/lib/core/base/Expr'; +import { Local } from 'arkanalyzer/lib/core/base/Local'; +import path from 'path'; +import { ArkClass, ArkFile, ArkInstanceFieldRef, FileSignature, Scene, Value } from 'arkanalyzer'; +import { ScopeType, TempLocation } from '../../model/Scope'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'CheckUtils'); + +export class CheckerUtils { + /** + * 从给定的语句中获取调用表达式 + * @param stmt - 要处理的语句 + * @returns 如果找到调用表达式,则返回 AbstractInvokeExpr,否则返回 null + */ + public static getInvokeExprFromStmt(stmt: Stmt): AbstractInvokeExpr | null { + if (stmt instanceof ArkInvokeStmt) { + return stmt.getInvokeExpr(); + } else if (stmt instanceof ArkAssignStmt) { + const rightOp = stmt.getRightOp(); + if (rightOp instanceof AbstractInvokeExpr) { + return rightOp; + } + } + return null; + } + + /** + * 从给定的语句中获取调用表达式(Await) + * @param stmt - 要处理的语句 + * @returns 如果找到调用表达式,则返回 AbstractInvokeExpr,否则返回 null + */ + public static getInvokeExprFromAwaitStmt(stmt: Stmt): AbstractInvokeExpr | null { + if (stmt instanceof ArkInvokeStmt) { + return stmt.getInvokeExpr(); + } else if (stmt instanceof ArkAssignStmt) { + let rightOp = stmt.getRightOp(); + if (rightOp instanceof AbstractInvokeExpr) { + return rightOp; + } else if (rightOp instanceof ArkAwaitExpr) { + let promise = rightOp.getPromise(); + if (!(promise instanceof Local)) { + return null; + } + let declaringStmt = promise.getDeclaringStmt(); + if (!(declaringStmt instanceof ArkAssignStmt)) { + return null; + } + rightOp = declaringStmt.getRightOp(); + if (rightOp instanceof AbstractInvokeExpr) { + return rightOp; + } + } + } + return null; + } + + /** + * 获取语句的Scope类型 + * @param stmt 语句对象 + * @returns Scope类型 + */ + public static getScopeType(stmt: Stmt): ScopeType { + const text = stmt.getOriginalText() ?? ''; + if (!text) { + return ScopeType.UNKNOWN_TYPE; + } + if (text.startsWith('for (') || text.startsWith('for(')) { + return ScopeType.FOR_CONDITION_TYPE; + } else if (text.startsWith('while (') || text.startsWith('while(')) { + return ScopeType.WHILE_TYPE; + } else if (text.startsWith('if (') || text.startsWith('if(')) { + return ScopeType.IF_TYPE; + } + return ScopeType.UNKNOWN_TYPE; + } + + /** + * 判断给定的语句是否是声明语句 + * @param defName - 要检查的变量名 + * @param stmt - 要检查的语句 + * @returns 如果语句是声明语句,则返回true,否则返回false + */ + public static isDeclaringStmt(defName: string, stmt: Stmt): boolean { + const text = stmt.getOriginalText() ?? ''; + if (text) { + if (text.includes('let ' + defName) || text.includes('const ' + defName) || + text.includes('var ' + defName)) { + const c = text[text.indexOf(' ' + defName) + defName.length + 1]; + if (c === ' ' || c === ':' || c === '=') { + return true; + } + } + } + return false; + } + + /** + * 获取语句中临时变量的位置 + * @param stmt 语句 + * @returns 临时变量的位置 + */ + public static wherIsTemp(stmt: Stmt): TempLocation { + let def = stmt.getDef(); + if (def instanceof Local) { + if (def.getName().includes('%')) { + return TempLocation.LEFT; + } + } + if (stmt instanceof ArkAssignStmt) { + let right = stmt.getRightOp(); + if (right instanceof Local) { + if (right.getName().includes('%')) { + return TempLocation.RIGHT; + } + } + } + return TempLocation.NOFOUND; + } + + /** + * 根据文件路径获取ArkFile对象 + * @param scene Scene + * @param absolutePath 文件的绝对路径 + * @returns 返回对应的ArkFile对象,如果未找到则返回null + */ + public static getArkFileByFilePath(scene: Scene, absolutePath: string): ArkFile | null { + const relativePath = path.relative(scene.getRealProjectDir(), absolutePath); + const fileSign = new FileSignature(scene.getProjectName(), relativePath); + return scene.getFile(fileSign); + } + + /** + * 获取参数的右值 + * @param arg - 参数 + * @param arkClass - ArkClass对象 + * @returns Value | null - 返回参数的右值,如果不存在则返回null + */ + public static getArgRight(arg: Value, arkClass: ArkClass): Value | null { + if (!(arg instanceof Local)) { + return arg; + } + let decStmt = arg.getDeclaringStmt(); + if (!(decStmt instanceof ArkAssignStmt)) { + return null; + } + let rightOp = decStmt.getRightOp(); + if (!(rightOp instanceof ArkInstanceFieldRef)) { + return rightOp; + } + let field = arkClass.getField(rightOp.getFieldSignature()); + if (!field) { + return null; + } + for (let initializer of field.getInitializer()) { + if (!(initializer instanceof ArkAssignStmt)) { + continue; + } + return initializer.getRightOp(); + } + return null; + } +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/utils/checker/ImageUtils.ts b/ets2panda/linter/homecheck/src/utils/checker/ImageUtils.ts new file mode 100644 index 0000000000..bd90155706 --- /dev/null +++ b/ets2panda/linter/homecheck/src/utils/checker/ImageUtils.ts @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import fs from 'fs'; +import { BMP } from './imageFormat/bmp'; +import { JPG } from './imageFormat/jpg'; +import { PNG } from './imageFormat/png'; +import { SVG } from './imageFormat/svg'; +import { WEBP } from './imageFormat/webp'; +import { ImageInfo } from '../../model/Interfaces'; + +const MaxInputSize = 512 * 1024; +const typeHandlers = { + bmp: BMP, + jpg: JPG, + png: PNG, + svg: SVG, + webp: WEBP, +}; + +export type imageType = keyof typeof typeHandlers; + +const firstBytes: Record = { + 0x42: 'bmp', + 0x52: 'webp', + 0x89: 'png', + 0xff: 'jpg', +}; +const keys = Object.keys(typeHandlers) as imageType[]; + +export function readImageInfo(filePath: string): ImageInfo | undefined { + const input = readFileSync(filePath); + if (!input) return undefined; + const type = detector(input); + if (typeof type === 'undefined') { + return undefined; + } + if (type in typeHandlers) { + const size = typeHandlers[type].calculate(input, filePath); + if (!size) { + return undefined; + } + let imageInfo = { width: size.width, height: size.height, type: '' }; + imageInfo.type = size.type ?? type; + if (size.images && size.images.length > 1) { + const largestImage = size.images.reduce((largest, current) => { + return current.width * current.height > largest.width * largest.height ? current : largest; + }, size.images[0]); + imageInfo.width = largestImage.width; + imageInfo.height = largestImage.height; + } + return imageInfo; + } + return undefined; +} + +function readFileSync(filepath: string): Uint8Array | undefined { + const descriptor = fs.openSync(filepath, 'r'); + try { + const { size } = fs.fstatSync(descriptor); + if (size <= 0) { + return undefined; + } + const inputSize = Math.min(size, MaxInputSize); + const input = new Uint8Array(inputSize); + fs.readSync(descriptor, input, 0, inputSize, 0); + return input; + } finally { + fs.closeSync(descriptor); + } +} + +function detector(input: Uint8Array): imageType | undefined { + try { + const byte = input[0]; + if (byte in firstBytes) { + const type = firstBytes[byte]; + if (type && typeHandlers[type].validate(input)) { + return type; + } + } + const finder = (key: imageType) => typeHandlers[key].validate(input); + return keys.find(finder); + } catch (error) { + return undefined; + } +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/utils/checker/NumberUtils.ts b/ets2panda/linter/homecheck/src/utils/checker/NumberUtils.ts new file mode 100644 index 0000000000..c8cc62f88e --- /dev/null +++ b/ets2panda/linter/homecheck/src/utils/checker/NumberUtils.ts @@ -0,0 +1,343 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { AbstractExpr, ArkAssignStmt, ArkFile, ArkNormalBinopExpr, ArkStaticFieldRef, ArkUnopExpr, ClassSignature, Constant, ImportInfo, Local, NumberType, Stmt, Value } from "arkanalyzer"; +import { VarInfo } from "../../model/VarInfo"; +import { CheckerStorage } from "../common/CheckerStorage"; +import { NumberValue, ValueType } from "../../model/NumberValue"; +import { StmtExt } from "../../model/StmtExt"; + +export class NumberUtils { + public static readonly mBinopList: string[] = ["+", "-", "*", "/", "%", "<<", ">>", "&", "|", "^", ">>>"]; + + private static isSupportOperator(operator: string) { + return this.mBinopList.includes(operator); + } + + public static isValueSupportCalculation(arkFile: ArkFile, valueStmtInfo: VarInfo, value: Value): boolean { + if (value instanceof Constant && value.getType() instanceof NumberType) { + return true; + } else if (value instanceof Local) { + let importInfo = NumberUtils.getValueImportInfo(arkFile, value); + if (importInfo) { + return NumberUtils.isImportValueSupportCalculate(arkFile, importInfo, value); + } else { + return NumberUtils.isMethodValueSupportCalculate(arkFile, valueStmtInfo, value); + } + } else if (value instanceof AbstractExpr && value.getType() instanceof NumberType) { + return NumberUtils.isExprSupportCalculate(arkFile, valueStmtInfo, value); + } else if (value instanceof ArkStaticFieldRef && value.getType() instanceof NumberType) { + return true + } + return false; + } + + private static isExprSupportCalculate(arkFile: ArkFile, valueStmtInfo: VarInfo, value: AbstractExpr) { + if (value instanceof ArkNormalBinopExpr && this.isSupportOperator(value.getOperator())) { + return NumberUtils.isValueSupportCalculation(arkFile, valueStmtInfo, value.getOp1()) && + NumberUtils.isValueSupportCalculation(arkFile, valueStmtInfo, value.getOp2()); + } else if (value instanceof ArkUnopExpr) { + let op = value.getUses()[0]; + return NumberUtils.isValueSupportCalculation(arkFile, valueStmtInfo, op); + } + return false; + } + + private static isMethodValueSupportCalculate(arkFile: ArkFile, valueStmtInfo: VarInfo, value: Local): boolean { + let scope = valueStmtInfo.scope; + let valueStmt: Stmt = valueStmtInfo.stmt; + if (!scope || !scope.defList) { + return false; + } + let hasFind = false; + let defList = scope.defList; + for (let defVar of defList) { + if (defVar.getName() !== value.getName()) { + continue; + } + hasFind = true; + let nearReDefStmtInfo = new VarInfo(defVar.defStmt, scope); + let reDefStmtInfos = defVar.redefInfo; + for (let reDefStmtInfo of reDefStmtInfos) { + let originalLine = valueStmt.getOriginPositionInfo().getLineNo(); + if (reDefStmtInfo.stmt.getOriginPositionInfo().getLineNo() >= originalLine) { + break; + } + nearReDefStmtInfo = reDefStmtInfo; + } + if (!nearReDefStmtInfo || !(nearReDefStmtInfo instanceof VarInfo)) { + continue; + } + let stmt = nearReDefStmtInfo.stmt; + if (stmt instanceof ArkAssignStmt) { + let rightOp = stmt.getRightOp(); + return NumberUtils.isValueSupportCalculation(arkFile, nearReDefStmtInfo, rightOp); + } + } + + if (!hasFind && scope.parentScope != null) { + let defStmtInfo = new VarInfo(valueStmt, scope.parentScope); + return NumberUtils.isValueSupportCalculation(arkFile, defStmtInfo, value); + } + return false; + } + + private static isImportValueSupportCalculate(arkFile: ArkFile, importInfo: ImportInfo, value: Local) { + let exportInfo = importInfo.getLazyExportInfo(); + let importArkFile = exportInfo?.getDeclaringArkFile(); + if (!importArkFile) { + return false; + } + let scope = CheckerStorage.getInstance().getScope(importArkFile.getFilePath()); + if (!scope) { + return false; + } + for (let varDef of scope.defList) { + if (varDef.getName() !== value.getName()) { + continue + } + let stmt = varDef.defStmt; + if (stmt instanceof ArkAssignStmt) { + let defStmtInfo = new VarInfo(stmt, scope); + let rightOp = stmt.getRightOp(); + return NumberUtils.isValueSupportCalculation(importArkFile, defStmtInfo, rightOp); + } + } + return false; + } + + private static getValueImportInfo(arkFile: ArkFile, value: Local) { + let importInfos = arkFile.getImportInfos(); + for (let importInfo of importInfos) { + if (importInfo.getImportClauseName() == value.getName()) { + return importInfo; + } + } + return undefined; + } + + public static getNumberByScope(arkFile: ArkFile, valueStmtInfo: VarInfo, value: Value): NumberValue { + if (value instanceof Constant && value.getType() instanceof NumberType) { + let valueStr = value.getValue(); + let numberValue = Number(valueStr); + if (valueStr.includes('.')) { + return new NumberValue(numberValue, ValueType.DOUBLE) + } else { + return new NumberValue(numberValue, ValueType.INT) + } + } else if (value instanceof Local) { + let importInfo = this.getValueImportInfo(arkFile, value); + if (importInfo) { + return this.getImportNumberValue(arkFile, importInfo, value) + } else { + return this.getMethodNumberValue(arkFile, valueStmtInfo, value) + } + } else if (value instanceof AbstractExpr && value.getType() instanceof NumberType) { + return this.getExprNumberValue(arkFile, valueStmtInfo, value) + } else if (value instanceof ArkStaticFieldRef && value.getType() instanceof NumberType) { + return this.getStaticNumberValue(arkFile, valueStmtInfo, value) + } + return new NumberValue(0, ValueType.UNKNOWN); + } + + private static getImportNumberValue(arkFile: ArkFile, importInfo: ImportInfo, value: Local): NumberValue { + let exportInfo = importInfo.getLazyExportInfo(); + let importArkFile = exportInfo?.getDeclaringArkFile(); + if (!importArkFile) { + return new NumberValue(0, ValueType.UNKNOWN); + } + let scope = CheckerStorage.getInstance().getScope(importArkFile.getFilePath()); + if (!scope) { + return new NumberValue(0, ValueType.UNKNOWN); + } + for (let varDef of scope.defList) { + if (varDef.getName() !== value.getName()) { + continue; + } + let stmt = varDef.defStmt; + if (stmt instanceof ArkAssignStmt) { + let defStmtInfo = new VarInfo(stmt, scope); + let rightOp = stmt.getRightOp(); + return this.getNumberByScope(importArkFile, defStmtInfo, rightOp) + } + } + return new NumberValue(0, ValueType.UNKNOWN); + } + + private static getMethodNumberValue(arkFile: ArkFile, valueStmtInfo: VarInfo, value: Local): NumberValue { + let scope = valueStmtInfo.scope; + let valueStmt = valueStmtInfo.stmt; + if (!scope || !scope.defList) { + return new NumberValue(0, ValueType.UNKNOWN); + } + let hasFind = false; + let defList = scope.defList; + for (let defVar of defList) { + if (defVar.getName() !== value.getName()) { + continue; + } + hasFind = true; + + let nearReDefStmtInfo = new VarInfo(defVar.defStmt, scope); + let reDefStmtInfos = defVar.redefInfo; + + for (let reDefStmtInfo of reDefStmtInfos) { + let originalLine = valueStmt.getOriginPositionInfo().getLineNo(); + let redefLine = reDefStmtInfo.stmt.getOriginPositionInfo().getLineNo(); + if (redefLine >= originalLine) { + break; + } + nearReDefStmtInfo = reDefStmtInfo; + } + let stmt = nearReDefStmtInfo.stmt; + if (stmt instanceof ArkAssignStmt) { + let rightOp = stmt.getRightOp(); + return this.getNumberByScope(arkFile, nearReDefStmtInfo, rightOp) + } + } + + if (!hasFind && scope.parentScope != null) { + let defStmtInfo = new VarInfo(valueStmt, scope.parentScope); + return this.getNumberByScope(arkFile, defStmtInfo, value) + } + return new NumberValue(0, ValueType.UNKNOWN); + } + + private static getExprNumberValue(arkFile: ArkFile, stmeInfo: VarInfo, value: AbstractExpr) { + if (value instanceof ArkNormalBinopExpr) { + if (this.isSupportOperator(value.getOperator())) { + let valueOfOp1 = this.getNumberByScope(arkFile, stmeInfo, value.getOp1()); + let valueOfOp2 = this.getNumberByScope(arkFile, stmeInfo, value.getOp2()); + switch (value.getOperator()) { + case '+': + return new NumberValue(valueOfOp1.value + valueOfOp2.value, valueOfOp1.type | valueOfOp2.type); + case '-': + return new NumberValue(valueOfOp1.value - valueOfOp2.value, valueOfOp1.type | valueOfOp2.type); + case '*': + return new NumberValue(valueOfOp1.value * valueOfOp2.value, valueOfOp1.type | valueOfOp2.type); + case '/': + return new NumberValue(valueOfOp1.value / valueOfOp2.value, valueOfOp1.type | valueOfOp2.type); + case '%': + return new NumberValue(valueOfOp1.value % valueOfOp2.value, valueOfOp1.type | valueOfOp2.type); + case '&': + return new NumberValue(valueOfOp1.value & valueOfOp2.value, valueOfOp1.type | valueOfOp2.type); + case '|': + return new NumberValue(valueOfOp1.value | valueOfOp2.value, valueOfOp1.type | valueOfOp2.type); + case '^': + return new NumberValue(valueOfOp1.value ^ valueOfOp2.value, valueOfOp1.type | valueOfOp2.type); + case '>>': + return new NumberValue(valueOfOp1.value >> valueOfOp2.value, valueOfOp1.type | valueOfOp2.type); + case '<<': + return new NumberValue(valueOfOp1.value << valueOfOp2.value, valueOfOp1.type | valueOfOp2.type); + case '>>>': + return new NumberValue(valueOfOp1.value >>> valueOfOp2.value, valueOfOp1.type | valueOfOp2.type); + } + } + } else if (value instanceof ArkUnopExpr) { + let op = value.getUses()[0]; + let valueOfOp = this.getNumberByScope(arkFile, stmeInfo, op); + switch (value.getOperator()) { + case '-': + return new NumberValue(-valueOfOp.value, valueOfOp.type); + case '~': + return new NumberValue(~valueOfOp.value, valueOfOp.type); + } + } + return new NumberValue(0, ValueType.UNKNOWN); + } + + private static getStaticNumberValue(arkFile: ArkFile, valueStmtInfo: VarInfo, value: ArkStaticFieldRef) { + let classSignature = value.getFieldSignature().getDeclaringSignature(); + if (!(classSignature instanceof ClassSignature)) { + return new NumberValue(0, ValueType.UNKNOWN); + } + + let fileSignature = classSignature.getDeclaringFileSignature(); + let staticClassArkFile = arkFile.getScene().getFile(fileSignature); + + if (staticClassArkFile) { + let staticClass = staticClassArkFile.getClass(classSignature); + if (!staticClass) { + return new NumberValue(0, ValueType.UNKNOWN); + } + + let staticField = staticClass.getStaticFieldWithName(value.getFieldName()); + if (!staticField) { + return new NumberValue(0, ValueType.UNKNOWN); + } + + let stmts = staticField.getInitializer(); + if (stmts.length === 0) { + return new NumberValue(0, ValueType.UNKNOWN); + } + + let stmt = stmts[0]; + new VarInfo(stmt, (stmt as StmtExt).scope) + if (!(stmt instanceof ArkAssignStmt)) { + return new NumberValue(0, ValueType.UNKNOWN); + } + + let initValue = stmt.getRightOp(); + return this.getNumberByScope(arkFile, valueStmtInfo, initValue); + } + return new NumberValue(0, ValueType.UNKNOWN); + } + + public static getOriginalValueText(stmt: Stmt, value: Value): string { + let valStr = ''; + if (value instanceof Constant) { + valStr = value.toString() + } else if (value instanceof Local) { + if (!value.toString().includes('%')) { + valStr = value.toString(); + } else { + let declaringStmt = value.getDeclaringStmt(); + if (declaringStmt instanceof ArkAssignStmt) { + return this.getOriginalValueText(stmt, declaringStmt.getRightOp()); + } + } + } else if (value instanceof ArkNormalBinopExpr) { + if (!value.toString().includes('%')) { + valStr = value.toString(); + } else { + let originalPosition = stmt.getOperandOriginalPosition(value); + if (!originalPosition) { + return this.getOriginalValueText(stmt, value.getOp1()) + ' ' + value.getOperator() + ' ' + + this.getOriginalValueText(stmt, value.getOp2()); + } + const text = stmt.getOriginalText(); + if (!text || text.length === 0) { + return this.getOriginalValueText(stmt, value.getOp1()) + ' ' + value.getOperator() + ' ' + + this.getOriginalValueText(stmt, value.getOp2()); + } + let startColum = stmt.getOriginPositionInfo().getColNo(); + return text.substring(originalPosition.getFirstCol() - startColum, originalPosition.getLastCol() - startColum); + } + } else if (value instanceof ArkUnopExpr) { + if (!value.toString().includes('%')) { + valStr = value.toString(); + } else { + valStr = value.getOperator() + this.getOriginalValueText(stmt, value.getUses()[0]); + } + } else if (value instanceof ArkStaticFieldRef) { + let fieldSignature = value.getFieldSignature(); + let declaringSignature = fieldSignature.getDeclaringSignature(); + if (declaringSignature instanceof ClassSignature) { + valStr = declaringSignature.getClassName() + '.' + fieldSignature.getFieldName(); + } + } + return valStr; + } +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/utils/checker/StringUtils.ts b/ets2panda/linter/homecheck/src/utils/checker/StringUtils.ts new file mode 100644 index 0000000000..9d20691027 --- /dev/null +++ b/ets2panda/linter/homecheck/src/utils/checker/StringUtils.ts @@ -0,0 +1,178 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { AbstractExpr, ArkAssignStmt, ArkFile, ArkNormalBinopExpr, ArkStaticFieldRef, ClassSignature, ClassType, Constant, ImportInfo, Local, Stmt, StringType, Value } from "arkanalyzer"; +import { ClassCategory } from "arkanalyzer/lib/core/model/ArkClass"; +import { VarInfo } from "../../model/VarInfo"; +import { StmtExt } from "../../model/StmtExt"; +import { CheckerStorage } from "../common/CheckerStorage"; +import { Scope } from "../../model/Scope"; + +export class StringUtils { + public static getStringByScope(arkFile: ArkFile, valueStmtInfo: VarInfo, value: Value): string { + if (value instanceof Constant) { + return value.getValue(); + } else if (value instanceof Local) { + if (!value.toString().includes('%')) { + let importInfo = this.getValueImportInfo(arkFile, value); + if (importInfo) { + return this.getImportStringValue(importInfo, value); + } else { + return this.getMethodStringValue(arkFile, valueStmtInfo, value); + } + } else { + let declaringStmt = value.getDeclaringStmt(); + if (!declaringStmt) { + return ''; + } + let tmpStmt = declaringStmt; + if (!(declaringStmt instanceof ArkAssignStmt)) { + return ''; + } + let rightOp = declaringStmt.getRightOp(); + valueStmtInfo.stmt = declaringStmt; + valueStmtInfo.scope = (tmpStmt as StmtExt).scope; + return this.getStringByScope(arkFile, valueStmtInfo, rightOp); + } + } else if (value instanceof AbstractExpr && value.getType() instanceof StringType) { + return this.getExprStringValue(arkFile, valueStmtInfo, value); + } else if (value instanceof ArkStaticFieldRef && value.getType() instanceof StringType) { + return this.getStaticStringValue(arkFile, value); + } else if (value instanceof ArkStaticFieldRef && value.getType() instanceof ClassType) { + return this.getStaticStringValue(arkFile, value); + } + return ''; + } + + private static getValueImportInfo(arkFile: ArkFile, value: Local): ImportInfo | undefined { + let importInfos = arkFile.getImportInfos(); + for (let importInfo of importInfos) { + if (importInfo.getImportClauseName() === value.getName()) { + return importInfo; + } + } + return undefined; + } + + private static getImportStringValue(importInfo: ImportInfo, value: Local): string { + let exportInfo = importInfo.getLazyExportInfo(); + let importArkFile = exportInfo?.getDeclaringArkFile(); + if (!importArkFile) { + return ''; + } + let scope = CheckerStorage.getInstance().getScope(importArkFile.getFilePath()); + if (!scope) { + return ''; + } + for (let varDef of scope.defList) { + if (varDef.getName() === value.getName()) { + continue; + } + let stmt = varDef.defStmt; + const text = stmt.getOriginalText(); + if (!text || text.length === 0 || !text.includes('const')) { + continue; + } + if (stmt instanceof ArkAssignStmt) { + let defStmtInfo = new VarInfo(stmt, scope); + let rightOp = stmt.getRightOp(); + return this.getStringByScope(importArkFile, defStmtInfo, rightOp); + } + } + return ''; + } + + private static getMethodStringValue(arkFile: ArkFile, valueStmtInfo: VarInfo, value: Local): string { + let scope: Scope = valueStmtInfo.scope; + let valueStmt: Stmt = valueStmtInfo.stmt; + let hasFind = false; + if (!scope || !scope.defList) { + return ''; + } + let defLists = scope.defList; + for (let defVar of defLists) { + if (defVar.getName() !== value.getName()) { + continue; + } + hasFind = true; + let nearReDefStmtInfo = new VarInfo(defVar.defStmt, scope); + let reDefStmtInfos = defVar.redefInfo; + for (let reDefStmtInfo of reDefStmtInfos) { + let originalLine = valueStmt.getOriginPositionInfo().getLineNo(); + let redefLine = reDefStmtInfo.stmt.getOriginPositionInfo().getLineNo(); + if (redefLine >= originalLine) { + break; + } + nearReDefStmtInfo = reDefStmtInfo; + } + let stmt = nearReDefStmtInfo.stmt; + if (stmt instanceof ArkAssignStmt) { + let rightOp = stmt.getRightOp(); + return this.getStringByScope(arkFile, nearReDefStmtInfo, rightOp); + } + } + if (!hasFind && scope.parentScope !== null) { + let defStmtInfo = new VarInfo(valueStmt, scope.parentScope); + return this.getStringByScope(arkFile, defStmtInfo, value); + } + return ''; + } + + private static getExprStringValue(arkFile: ArkFile, stmtInfo: VarInfo, value: AbstractExpr): string { + if (value instanceof ArkNormalBinopExpr) { + let stringOfOp1 = this.getStringByScope(arkFile, stmtInfo, value.getOp1()); + let stringOfOp2 = this.getStringByScope(arkFile, stmtInfo, value.getOp2()); + switch (value.getOperator()) { + case '+': + return stringOfOp1 + stringOfOp2; + } + } + return ''; + } + + private static getStaticStringValue(arkFile: ArkFile, value: ArkStaticFieldRef): string { + let classSignature = value.getFieldSignature().getDeclaringSignature(); + if (!(classSignature instanceof ClassSignature)) { + return ''; + } + let fieldSignature = classSignature.getDeclaringFileSignature(); + let staticClassArkFile = arkFile.getScene().getFile(fieldSignature); + if (!staticClassArkFile) { + return ''; + } + let staticClass = staticClassArkFile.getClass(classSignature); + if (!staticClass) { + return ''; + } + let staticField = staticClass.getStaticFieldWithName(value.getFieldName()); + if (!staticField) { + return ''; + } + if (staticClass.getCategory() === ClassCategory.CLASS && !staticField.isReadonly()) { + return ''; + } + let stmts = staticField.getInitializer(); + if (stmts.length === 0) { + return ''; + } + let stmt = stmts[0]; + let varInfo = new VarInfo(stmt, (stmt as StmtExt).scope); + if (!(stmt instanceof ArkAssignStmt)) { + return ''; + } + let initValue = stmt.getRightOp(); + return this.getStringByScope(staticClassArkFile, varInfo, initValue); + } +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/utils/checker/TypeUtils.ts b/ets2panda/linter/homecheck/src/utils/checker/TypeUtils.ts new file mode 100644 index 0000000000..f535e04f48 --- /dev/null +++ b/ets2panda/linter/homecheck/src/utils/checker/TypeUtils.ts @@ -0,0 +1,193 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { AliasType, ArrayType, ClassType, FunctionType, GenericType, TupleType, Type, UnclearReferenceType, UnionType } from "arkanalyzer"; + +/** + * 检查类型是否为指定类型 + * + * @param appointType 指定类型 + * @param type 被检查类型 + * @returns + */ +export function isAppointType(appointType: Type, type: Type): boolean { + + if (appointType.getTypeString() === type.getTypeString()) { + return true; + } + + if (type instanceof ArrayType) { + return isAppointType(appointType, type.getBaseType()); + } + + if (type instanceof UnclearReferenceType) { + return generic(appointType, type.getGenericTypes()); + } + + if (type instanceof UnionType) { + return generic(appointType, type.getTypes()); + } + + if (type instanceof FunctionType) { + return generic(appointType, type.getRealGenericTypes()); + } + + if (type instanceof ClassType) { + return generic(appointType, type.getRealGenericTypes()); + } + + if (type instanceof TupleType) { + return generic(appointType, type.getTypes()); + } + + if (type instanceof AliasType) { + return isAppointType(appointType, type.getOriginalType()); + } + + if (type instanceof GenericType) { + let defType = type.getDefaultType(); + let constraintType = type.getConstraint(); + return (defType ? isAppointType(appointType, defType) : false) || + (constraintType ? isAppointType(appointType, constraintType) : false); + } + return false; +} + +function generic(appointType: Type, type: Type[] | undefined): boolean { + if (!type) { + return false; + } + for (const t of type) { + if (isAppointType(appointType, t)) { + return true; + } + } + return false; +} + +/** + * 递归替换类型中的指定类型 + * + * @param appointType 指定类型 + * @param type 需要被替换的类型 + * @param newType 新的类型 + * @returns + */ +export function fixAppointType(appointType: Type, type: Type, newType: Type): Type { + if (appointType.getTypeString() === type.getTypeString()) { + return newType; + } + + if (type instanceof ArrayType) { + type.setBaseType(fixAppointType(appointType, type.getBaseType(), newType)); + return type; + } + + if (type instanceof UnclearReferenceType) { + return handleUnclearReferenceType(appointType, type, newType); + } + + if (type instanceof UnionType) { + return handleUnionType(appointType, type, newType); + } + + if (type instanceof FunctionType) { + return handleFunctionType(appointType, type, newType); + } + + if (type instanceof ClassType) { + return handleClassType(appointType, type, newType); + } + + if (type instanceof TupleType) { + return handleTupleType(appointType, type, newType); + } + + if (type instanceof AliasType) { + type.setOriginalType(fixAppointType(appointType, type.getOriginalType(), newType)); + return type; + } + + if (type instanceof GenericType) { + return handleGenericType(appointType, type, newType); + } + return type; +} + +// 处理 UnclearReferenceType 的逻辑 +function handleUnclearReferenceType(appointType: Type, type: UnclearReferenceType, newType: Type): Type { + const genericTypes = type.getGenericTypes() || []; + for (let i = 0; i < genericTypes.length; i++) { + genericTypes[i] = fixAppointType(appointType, genericTypes[i], newType); + } + return new UnclearReferenceType(type.getName(), genericTypes); +} + +// 处理 UnionType 的逻辑 +function handleUnionType(appointType: Type, type: UnionType, newType: Type): Type { + const unionTypes = type.getTypes() || []; + for (let i = 0; i < unionTypes.length; i++) { + unionTypes[i] = fixAppointType(appointType, unionTypes[i], newType); + } + return new UnionType(unionTypes); +} + +// 处理 FunctionType 的逻辑 +function handleFunctionType(appointType: Type, type: FunctionType, newType: Type): Type { + const realGenericTypes = type.getRealGenericTypes() || []; + for (let i = 0; i < realGenericTypes.length; i++) { + realGenericTypes[i] = fixAppointType(appointType, realGenericTypes[i], newType); + } + return new FunctionType(type.getMethodSignature(), realGenericTypes); +} + +// 处理 ClassType 的逻辑 +function handleClassType(appointType: Type, type: ClassType, newType: Type): Type { + const realGenericTypes = type.getRealGenericTypes() || []; + for (let i = 0; i < realGenericTypes.length; i++) { + realGenericTypes[i] = fixAppointType(appointType, realGenericTypes[i], newType); + } + type.setRealGenericTypes(realGenericTypes); + return type; +} + +// 处理 TupleType 的逻辑 +function handleTupleType(appointType: Type, type: TupleType, newType: Type): Type { + const tupleTypes = type.getTypes() || []; + for (let i = 0; i < tupleTypes.length; i++) { + tupleTypes[i] = fixAppointType(appointType, tupleTypes[i], newType); + } + return new TupleType(tupleTypes); +} + +// 处理 GenericType 的逻辑 +function handleGenericType(appointType: Type, type: GenericType, newType: Type): Type { + let defType = type.getDefaultType(); + let constraintType = type.getConstraint(); + if (defType) { + defType = fixAppointType(appointType, defType, newType); + } + if (constraintType) { + constraintType = fixAppointType(appointType, constraintType, newType); + } + if (defType) { + type.setDefaultType(defType); + } + + if (constraintType) { + type.setConstraint(constraintType); + } + return type; +} diff --git a/ets2panda/linter/homecheck/src/utils/checker/ViewTreeTool.ts b/ets2panda/linter/homecheck/src/utils/checker/ViewTreeTool.ts new file mode 100644 index 0000000000..b69f6e7b0e --- /dev/null +++ b/ets2panda/linter/homecheck/src/utils/checker/ViewTreeTool.ts @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ViewTreeNode } from "arkanalyzer" +import { ArkClass } from "arkanalyzer" + +export class ViewTreeTool { + private recordMap: Map + + constructor() { + this.recordMap = new Map(); + } + + hasTraverse(item: ArkClass | ViewTreeNode): boolean { + let classSig = ''; + if (item instanceof ArkClass) { + classSig = item.getSignature().toString(); + } else { + if (item.signature) { + classSig = item.signature.toString(); + } else { + return false; + } + } + let result = this.recordMap.get(classSig); + this.recordMap.set(classSig, true); + return result === true; + } +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/utils/checker/imageFormat/bmp.ts b/ets2panda/linter/homecheck/src/utils/checker/imageFormat/bmp.ts new file mode 100644 index 0000000000..6a3d40e359 --- /dev/null +++ b/ets2panda/linter/homecheck/src/utils/checker/imageFormat/bmp.ts @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { ImageData } from '../../../model/Interfaces'; +import { readInt32LE, readUInt32LE, toUTF8String } from '../BytesUtils'; + +export const BMP: ImageData = { + validate: (input) => toUTF8String(input, 0, 2) === 'BM', + calculate: (input) => ({ + height: Math.abs(readInt32LE(input, 22)), + width: readUInt32LE(input, 18), + }), +}; \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/utils/checker/imageFormat/jpg.ts b/ets2panda/linter/homecheck/src/utils/checker/imageFormat/jpg.ts new file mode 100644 index 0000000000..aaa92f977a --- /dev/null +++ b/ets2panda/linter/homecheck/src/utils/checker/imageFormat/jpg.ts @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { ImageInfo, ImageData } from '../../../model/Interfaces'; +import { readUInt, readUInt16BE, toHexString } from '../BytesUtils'; + +const EXIF_MARKER = '45786966'; +const APP1_DATA_SIZE_BYTES = 2; +const EXIF_HEADER_BYTES = 6; +const TIFF_BYTE_ALIGN_BYTES = 2; +const BIG_ENDIAN_BYTE_ALIGN = '4d4d'; +const LITTLE_ENDIAN_BYTE_ALIGN = '4949'; +const IDF_ENTRY_BYTES = 12; +const NUM_DIRECTORY_ENTRIES_BYTES = 2; + +function isEXIF(input: Uint8Array): boolean { + return toHexString(input, 2, 6) === EXIF_MARKER; +} + +function extractSize(input: Uint8Array, index: number): ImageInfo { + return { + height: readUInt16BE(input, index), + width: readUInt16BE(input, index + 2), + } +} + + +function extractOrientation(exifBlock: Uint8Array, isBigEndian: boolean) { + const idfOffset = 8; + const offset = EXIF_HEADER_BYTES + idfOffset; + const idfDirectoryEntries = readUInt(exifBlock, 16, offset, isBigEndian); + for(let directoryEntryNumber = 0; directoryEntryNumber < idfDirectoryEntries; directoryEntryNumber++) { + const start = offset + NUM_DIRECTORY_ENTRIES_BYTES + directoryEntryNumber * IDF_ENTRY_BYTES; + const end = start + IDF_ENTRY_BYTES; + if (start > exifBlock.length) { + return; + } + const block = exifBlock.slice(start, end); + const tagNumber = readUInt(block, 16, 0, isBigEndian); + if (tagNumber === 274) { + const dataFormat = readUInt(block, 16, 2, isBigEndian); + if (dataFormat !== 3) { + return; + } + const numberOfComponents = readUInt(block, 32, 4, isBigEndian); + if (numberOfComponents !== 1) { + return; + } + return readUInt(block, 16, 8, isBigEndian); + } + } +} + +function validateExifBlock(input: Uint8Array, index: number) { + const exifBlock = input.slice(APP1_DATA_SIZE_BYTES, index); + const byteAlign = toHexString(exifBlock, EXIF_HEADER_BYTES, EXIF_HEADER_BYTES + TIFF_BYTE_ALIGN_BYTES); + const isBigEndian = byteAlign === BIG_ENDIAN_BYTE_ALIGN; + const isLittleEndian = byteAlign === LITTLE_ENDIAN_BYTE_ALIGN; + if (isBigEndian || isLittleEndian) { + return extractOrientation(exifBlock, isBigEndian); + } +} + +function validateInput(input: Uint8Array, index: number): void { + if (index > input.length) { + throw new TypeError('Corrupt JPG, exceeded buffer limits'); + } +} + +export const JPG: ImageData = { + validate: (input) => toHexString(input, 0, 2) === 'ffd8', + + calculate(_input) { + let input = _input.slice(4); + let orientation: number | undefined; + let next: number; + while(input.length) { + const i = readUInt16BE(input, 0); + if (input[i] !== 0xff) { + input = input.slice(1); + continue; + } + if(isEXIF(input)) { + orientation = validateExifBlock(input, i); + } + validateInput(input, i); + next = input[i + 1]; + if (next === 0xc0 || next === 0xc1 || next === 0xc2) { + const size = extractSize(input, i + 5); + if (!orientation) { + return size; + } + return { + height: size.height, + orientation, + width: size.width, + } + } + input = input.slice(i + 2); + } + throw new TypeError('Invalid JPG, no size found'); + }, +}; \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/utils/checker/imageFormat/png.ts b/ets2panda/linter/homecheck/src/utils/checker/imageFormat/png.ts new file mode 100644 index 0000000000..3da4803055 --- /dev/null +++ b/ets2panda/linter/homecheck/src/utils/checker/imageFormat/png.ts @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { ImageData } from '../../../model/Interfaces'; +import { readUInt32BE, toUTF8String } from '../BytesUtils'; + +const pngSignature = 'PNG\r\n\x1a\n'; +const pngImageHeaderChunkName = 'IHDR'; +const pngFriedChunkName = 'CgBI'; + +export const PNG: ImageData = { + validate(input) { + if (pngSignature === toUTF8String(input, 1, 8)) { + let chunkName = toUTF8String(input, 12, 16); + if (chunkName === pngFriedChunkName) { + chunkName = toUTF8String(input, 28, 32); + } + if (chunkName !== pngImageHeaderChunkName) { + throw new TypeError('Invalid PNG'); + } + return true; + } + return false; + }, + + calculate(input) { + if (toUTF8String(input, 12, 16) === pngFriedChunkName) { + return { + height: readUInt32BE(input, 36), + width: readUInt32BE(input, 32), + } + } + return { + height: readUInt32BE(input, 20), + width: readUInt32BE(input, 16), + } + }, +}; \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/utils/checker/imageFormat/svg.ts b/ets2panda/linter/homecheck/src/utils/checker/imageFormat/svg.ts new file mode 100644 index 0000000000..ea97b3179e --- /dev/null +++ b/ets2panda/linter/homecheck/src/utils/checker/imageFormat/svg.ts @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { ImageInfo, ImageData, IAttributes } from '../../../model/Interfaces'; +import { toUTF8String, getLength } from '../BytesUtils'; + +const svgReg = /"']|"[^"]*"|'[^']*')*>/; +const extractorRegExps = { + root: svgReg, + height: /\sheight=(['"])([^%]+?)\1/, + width: /\swidth=(['"])([^%]+?)\1/, + viewbox: /\sviewbox=(['"])(.+?)\1/i, +}; + +function parseViewbox(viewbox: string): IAttributes | undefined { + const bounds = viewbox.split(' '); + let tmpWeight = getLength(bounds[3]); + let tmpWidth = getLength(bounds[2]); + if(tmpWidth && tmpWeight) { + return {height: tmpWeight, width: tmpWidth}; + } + return undefined; +} + +function getAttirbutes(root: string): IAttributes | undefined { + const widths = root.match(extractorRegExps.width); + const heights = root.match(extractorRegExps.height); + const viewbox = root.match(extractorRegExps.viewbox); + if (widths && heights && viewbox) { + let tempHeight = getLength(heights[2]); + let tmpWidth = getLength(widths[2]); + if (tmpWidth && tempHeight) { + return { + height: heights && tempHeight, + viewbox: viewbox && parseViewbox(viewbox[2]), + width: widths && tmpWidth, + } + } + } + return undefined; +} + +function calculateByDimensions(attrs: IAttributes): ImageInfo { + return { + height: attrs.height as number, + width: attrs.width as number, + } +} + +function calculateByViewbox(attrs: IAttributes, viewbox: IAttributes): ImageInfo { + const ratio = (viewbox.width as number) / (viewbox.height as number); + if (attrs.height) { + return { + height: attrs.height, + width: Math.floor(attrs.height * ratio) + } + } else if (attrs.width) { + return { + height: Math.floor(attrs.width * ratio), + width: attrs.width, + } + } else { + return { + height: viewbox.height as number, + width: viewbox.width as number, + } + } +} + +export const SVG: ImageData = { + validate: (input) => svgReg.test(toUTF8String(input, 0, 1000)), + + calculate(input) { + const root = toUTF8String(input).match(extractorRegExps.root); + if (root) { + const attrs = getAttirbutes(root[0]); + if (attrs) { + if (attrs.width && attrs.height) { + return calculateByDimensions(attrs); + } + if (attrs.viewbox) { + return calculateByViewbox(attrs, attrs.viewbox); + } + } + } + throw new TypeError('Invalid SVG'); + }, +}; \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/utils/checker/imageFormat/webp.ts b/ets2panda/linter/homecheck/src/utils/checker/imageFormat/webp.ts new file mode 100644 index 0000000000..2c575cc595 --- /dev/null +++ b/ets2panda/linter/homecheck/src/utils/checker/imageFormat/webp.ts @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { ImageInfo, ImageData } from '../../../model/Interfaces'; +import { readInt16LE, readUInt24LE, toHexString, toUTF8String } from '../BytesUtils'; + +function calculateExtended(input: Uint8Array) : ImageInfo { + return { + height: 1 + readUInt24LE(input, 7), + width: 1 + readUInt24LE(input, 4), + } +} + +function calculateLossLess(input: Uint8Array): ImageInfo { + return { + height: 1 + (((input[4] & 0xf) << 10) | (input[3] << 2) | ((input[2] & 0xc0) >> 6)), + width: 1 + (((input[2] & 0x3f) << 8) | input[1]), + } +} + +function calculateLossy(input: Uint8Array): ImageInfo { + return { + height: readInt16LE(input, 8) & 0x3fff, + width: readInt16LE(input, 6) & 0x3fff, + } +} + +export const WEBP: ImageData = { + validate(input) { + const riffHeader = 'RIFF' === toUTF8String(input, 0, 4); + const webpHeader = 'WEBP' === toUTF8String(input, 8, 12); + const vp8Header = 'VP8' === toUTF8String(input, 12, 15); + return riffHeader && webpHeader && vp8Header; + }, + calculate(_input) { + const chunkHeader = toUTF8String(_input, 12, 16); + const input = _input.slice(20, 30); + if (chunkHeader === 'VP8X') { + const extendedHeader = input[0]; + const validStart = (extendedHeader & 0xc0) === 0; + const validEnd = (extendedHeader & 0x01) === 0; + if (validStart && validEnd) { + return calculateExtended(input); + } + throw new TypeError('Invalid WebP'); + } + if (chunkHeader === 'VP8' && input[0] !== 0x2f) { + return calculateLossy(input); + } + const signature = toHexString(input, 3, 6); + if (chunkHeader === 'VP8L' && signature !== '9d012a') { + return calculateLossLess(input); + } + throw new TypeError('Invalid WebP'); + }, +}; \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/utils/common/AfterCheck.ts b/ets2panda/linter/homecheck/src/utils/common/AfterCheck.ts new file mode 100644 index 0000000000..72257923bc --- /dev/null +++ b/ets2panda/linter/homecheck/src/utils/common/AfterCheck.ts @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { FileReports } from "../../Index"; +import { CheckEntry } from "./CheckEntry"; + +export async function processAfterCheck(checkEntry: CheckEntry) { + // 按规则维度统计告警信息,按文件维度汇总告警信息 + const fileIssues = checkEntry.sortIssues(); + let fileReports: FileReports[] = []; + if (checkEntry.projectConfig.fix === 'true') { + // 代码修复 + fileReports = checkEntry.codeFix(fileIssues); + } else { + // 转换输出格式,去掉fix相关信息 + fileIssues.forEach((fileIssue) => { + fileReports.push({ filePath: fileIssue.filePath, defects: fileIssue.issues.map(issue => issue.defect) }); + }); + } + // 发送消息 + await checkEntry.message?.sendResult(fileReports, checkEntry.projectConfig.reportDir); +} diff --git a/ets2panda/linter/homecheck/src/utils/common/CheckBuilder.ts b/ets2panda/linter/homecheck/src/utils/common/CheckBuilder.ts new file mode 100644 index 0000000000..cbc34a3e42 --- /dev/null +++ b/ets2panda/linter/homecheck/src/utils/common/CheckBuilder.ts @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import Logger, { LOG_MODULE_TYPE } from "arkanalyzer/lib/utils/logger"; +import { ArkFile } from "arkanalyzer"; +import { Rule, BaseChecker } from "../../Index"; +import { File2Check } from "../../model/File2Check"; +import { Project2Check } from "../../model/Project2Check"; +import { CheckerFactory } from "./CheckerFactory"; + + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'CheckBuilder'); + +export function fileCheckBuilder(arkFile: ArkFile, enabledRules: Rule[]) { + let checkIns = new File2Check(); + checkIns.arkFile = arkFile; + enabledRules.forEach(rule => { + const checkerInstance = CheckerFactory.getChecker(rule); + if (checkerInstance) { + checkIns.addChecker(rule.ruleId, checkerInstance as BaseChecker); + } else { + logger.error(`Cannot find checker according rule id: ${rule.ruleId}`); + } + }); + return checkIns; +} + +export function projectCheckBuilder(arkFiles: ArkFile[], enabledRules: Rule[]) { + let checkIns = new Project2Check(); + checkIns.arkFiles = arkFiles; + enabledRules.forEach(rule => { + const checkerInstance = CheckerFactory.getChecker(rule); + if (checkerInstance) { + checkIns.addChecker(rule.ruleId, checkerInstance as BaseChecker); + } else { + logger.log(`Cannot find checker according rule id: ${rule.ruleId}`); + } + }); + return checkIns; +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/utils/common/CheckEntry.ts b/ets2panda/linter/homecheck/src/utils/common/CheckEntry.ts new file mode 100644 index 0000000000..6b3fa93aa3 --- /dev/null +++ b/ets2panda/linter/homecheck/src/utils/common/CheckEntry.ts @@ -0,0 +1,281 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Scene } from "arkanalyzer"; +import Logger, { LOG_MODULE_TYPE } from "arkanalyzer/lib/utils/logger"; +import { SceneConfig } from "arkanalyzer"; +import { fileRuleMapping } from "./FileRuleMapping"; +import { RuleConfig } from "../../model/RuleConfig"; +import { ProjectConfig, SelectedFileInfo } from "../../model/ProjectConfig"; +import { Project2Check } from "../../model/Project2Check"; +import { File2Check } from "../../model/File2Check"; +import { DisableText } from "./Disable"; +import { Message } from "../../model/Message"; +import { FileUtils } from "./FileUtils"; +import { ScopeHelper } from "./ScopeHelper"; +import { RuleListUtil } from "./DefectsList"; +import { FixMode } from "../../model/Fix"; +import { FileIssues, FileReports, IssueReport, engine } from "../../model/Defects"; +import { FixUtils } from "./FixUtils"; +import { FixEngine } from "../../codeFix/FixEngine"; +import { CheckerUtils } from "../checker/CheckerUtils"; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'CheckEntry'); + +export class CheckEntry { + public ruleConfig: RuleConfig; + public projectConfig: ProjectConfig; + public projectCheck: Project2Check; + public fileChecks: File2Check[] = []; + public scene: Scene; + public message: Message; + public selectFileList: SelectedFileInfo[] = []; + + constructor() { + } + + public addFileCheck(fileCheck: File2Check): void { + this.fileChecks.push(fileCheck); + } + + public addProjectCheck(projectCheck: Project2Check): void { + this.projectCheck = projectCheck; + } + + public setDisableText(fileDisableText: string, nextLineDisableText: string): void { + DisableText.FILE_DISABLE_TEXT = fileDisableText; + DisableText.NEXT_LINE_DISABLE_TEXT = nextLineDisableText; + } + + public setEngineName(engineName: string): void { + engine.engineName = engineName; + } + + public setCheckFileList(selectFileList: SelectedFileInfo[]): void { + this.selectFileList = selectFileList; + } + + public setMessage(message: Message): void { + this.message = message; + } + + public async runAll(): Promise { + // TODO: worker_threads改造 + let checkedIndex = 1; + for (const fileCheck of this.fileChecks) { + try { + await fileCheck.run(); + // 进度条通知 + this.message?.progressNotify(checkedIndex / (this.fileChecks.length + 1), fileCheck.arkFile.getFilePath()); + checkedIndex++; + } catch (error) { + logger.error(`Error running file check for ${fileCheck.arkFile.getFilePath()}: ${(error as Error).message}`); + continue; + } + } + + if (this.projectCheck) { + try { + await this.projectCheck.run(); + this.message?.progressNotify(checkedIndex / (this.fileChecks.length + 1), 'Project Check'); + } catch (error) { + logger.error(`Error running project check: ${(error as Error).message}`); + } + } + } + + /** + * 按规则维度统计并输出告警信息,按文件维度汇总并返回告警信息。 + * + * @returns FileReport[] 文件报告数组,每个元素包含文件名、缺陷列表和输出信息 + */ + public sortIssues(): FileIssues[] { + const issuesMapByChecker: Map = new Map(); + const issuesMapByFile: Map = new Map(); + RuleListUtil.printDefects(); + for (const fileCheck of this.fileChecks) { + if (!fileCheck.issues || fileCheck.issues.length === 0) { + continue; + } + issuesMapByFile.set(fileCheck.arkFile.getFilePath(), fileCheck.issues); + for (const issue of fileCheck.issues) { + logger.debug(issue.defect.mergeKey); + const checkerStorage = issuesMapByChecker.get(issue.defect.ruleId); + if (checkerStorage) { + checkerStorage.push(issue); + } else { + issuesMapByChecker.set(issue.defect.ruleId, [issue]); + } + } + } + + for (const issue of this.projectCheck?.issues ?? []) { + logger.debug(issue.defect.mergeKey); + const checkerStorage = issuesMapByChecker.get(issue.defect.ruleId); + if (checkerStorage) { + checkerStorage.push(issue); + } else { + issuesMapByChecker.set(issue.defect.ruleId, [issue]); + } + + const filePath = issue.defect.mergeKey.split('%')[0]; + const fileStorage = issuesMapByFile.get(filePath); + if (fileStorage) { + fileStorage.push(issue); + } else { + issuesMapByFile.set(filePath, [issue]); + } + } + issuesMapByChecker.forEach((issues, checker) => { + logger.info(issues.length + ' issues from checker - ' + checker); + }); + const fileReports: FileIssues[] = []; + issuesMapByFile.forEach((issues, filePath) => { + fileReports.push({ filePath, issues }); + }); + return fileReports; + } + + public buildScope(): void { + new ScopeHelper().buildScope(this.scene); + } + + /** + * 修复代码问题 + * + * @param fileIssues 以文件为维度的issues信息 + * @returns 修复后的文件报告数组,去掉已修复issues,且需更新未修复issues行列号等信息 + */ + public codeFix(fileIssues: FileIssues[]): FileReports[] { + const fileReports: FileReports[] = []; + for (const fileIssue of fileIssues) { + const arkFile = CheckerUtils.getArkFileByFilePath(this.scene, fileIssue.filePath); + if (!arkFile) { + fileReports.push({ filePath: fileIssue.filePath, defects: fileIssue.issues.map(issue => issue.defect) }); + continue; + } + let keys: string[] = []; + let isFixAll = false; + // 寻找该文件的fixKey,即需要修复的issue + for (const fileInfo of this.selectFileList) { + if (fileInfo.fixKey && fileInfo.filePath === fileIssue.filePath) { + keys = fileInfo.fixKey; + break; + } + } + // 没有指定key,则修复所有issue + if (keys.length === 0) { + isFixAll = true; + } + + const remainIssues: IssueReport[] = []; + const astFixIssues: IssueReport[] = []; + this.classifyIssues(fileIssue.issues, isFixAll, keys, astFixIssues, remainIssues); + const astFixReport = new FixEngine().getEngine(FixMode.AST).applyFix(arkFile, astFixIssues, remainIssues); + fileReports.push(astFixReport); + } + return fileReports; + } + + private classifyIssues(allIssues: IssueReport[], fixAll: boolean, keys: string[], astFixIssues: IssueReport[], + remainIssues: IssueReport[]): void { + for (const issue of allIssues) { + if (fixAll || keys.includes(issue.defect.fixKey)) { + if (issue.fix && issue.defect.fixable && FixUtils.isRuleFix(issue.fix)) { + astFixIssues.push(issue); + } else { + remainIssues.push(issue); + logger.debug('Fix type is unsupported.'); + } + } else { + remainIssues.push(issue); + } + } + } +} + +export async function checkEntryBuilder(checkEntry: CheckEntry): Promise { + // 1、 无指定文件则检查项目下所有文件 + let checkFileList = checkEntry.selectFileList.map(file => file.filePath); + if (checkFileList.length === 0) { + checkFileList = FileUtils.getAllFiles(checkEntry.projectConfig.projectPath, ['.ts', '.ets', '.json5']); + } + + // 2、文件过滤和文件级屏蔽处理 + checkFileList = await FileUtils.getFiltedFiles(checkFileList, checkEntry.ruleConfig); + logger.info("File count: " + checkFileList.length); + if (checkFileList.length === 0) { + checkEntry.message?.progressNotify(1, 'No file to check.'); + return false; + } + + // 3、scene按需构建、scope构建 + if (!buildScene(checkFileList, checkEntry)) { + return false; + } + + // 4、规则和文件映射构建 + if (!(await fileRuleMapping(checkFileList, checkEntry))) { + return false; + } + return true; +} + +/** + * 获取指定检查的文件列表 + * + * @param checkFilePath - 指定的检查文件路径的配置文件路径,该文件内容示例{"checkPath": [{"filePath": "xxx", "fixKey": ["%line%sCol%eCol%ruleId"]}]} + * filePath为需要检查的文件路径,fixKey为需要修复的缺陷key,空数组则不修复。 + * @returns SelectFileInfo[] - 需要检查的文件列表 + */ +export function getSelectFileList(checkFilePath: string): SelectedFileInfo[] { + if (checkFilePath.length > 0) { + // 解析指定的文件 + return FileUtils.getSeletctedFileInfos(checkFilePath, ['.ts', '.ets', '.json5']); + } + return []; +} + +/** + * 构建Scene + * @param fileList - 文件列表 + * @param checkEntry - 检查条目 + * @returns {boolean} - 构建是否成功 + */ +function buildScene(fileList: string[], checkEntry: CheckEntry): boolean { + try { + // 构建SceneConfig信息 + const sceneConfig = new SceneConfig(); + const projectName = checkEntry.projectConfig.projectName; + const projectPath = checkEntry.projectConfig.projectPath; + const languageTags = checkEntry.projectConfig.languageTags; + const sdkList = FileUtils.genSdks(checkEntry.projectConfig); + sceneConfig.buildFromProjectFiles(projectName, projectPath, fileList, sdkList, languageTags); + logger.info("Build sceneConfig completed."); + // 构建Scene信息 + checkEntry.scene = new Scene(); + checkEntry.scene.buildSceneFromFiles(sceneConfig); + logger.info("Build scene completed."); + checkEntry.scene.inferTypes(); + logger.info("Infer types completed."); + } catch (error) { + logger.error("Build scene or infer types error: ", error); + return false; + } + // 构建Scope信息 + checkEntry.buildScope(); + logger.info("Build scope completed."); + return true; +} diff --git a/ets2panda/linter/homecheck/src/utils/common/CheckerFactory.ts b/ets2panda/linter/homecheck/src/utils/common/CheckerFactory.ts new file mode 100644 index 0000000000..83c369ada5 --- /dev/null +++ b/ets2panda/linter/homecheck/src/utils/common/CheckerFactory.ts @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BaseChecker } from "../../checker/BaseChecker"; +import { Rule } from "../../model/Rule"; +import { ProxyChecker } from "./CheckerIndex"; + +export class CheckerFactory { + static getChecker(rule: Rule): BaseChecker | null { + const checkerInstance = ProxyChecker.getClass(rule.ruleId); + if (!checkerInstance) { + return null; + } + checkerInstance.rule = rule; + return checkerInstance; + } +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/utils/common/CheckerIndex.ts b/ets2panda/linter/homecheck/src/utils/common/CheckerIndex.ts new file mode 100644 index 0000000000..0e238c87d7 --- /dev/null +++ b/ets2panda/linter/homecheck/src/utils/common/CheckerIndex.ts @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; +import { ObservedDecoratorCheck } from '../../checker/migration/ObservedDecoratorCheck'; +import { ThisBindCheck } from '../../checker/migration/ThisBindCheck'; +import { ObjectLiteralCheck } from '../../checker/migration/ObjectLiteralCheck'; +import { AppStorageGetCheck } from '../../checker/migration/AppStorageGetCheck'; +import { ModifyStateVarCheck } from '../../checker/migration/ModifyStateVarCheck'; +import { NoMethodOverridingFieldCheck } from '../../checker/migration/NoMethodOverridingFieldCheck'; +import { CustomBuilderCheck } from '../../checker/migration/CustomBuilderCheck'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'CheckerIndex'); + +export const fileRules = { + "@migration/arkts-instance-method-bind-this": ThisBindCheck, + "@migration/arkui-data-observation-2": ObservedDecoratorCheck, + "@migration/arkui-stateful-appstorage": AppStorageGetCheck, + "@migration/arkui-no-update-in-rending": ModifyStateVarCheck, + "@migration/arkui-custombuiler": CustomBuilderCheck, + "@migration/no-method-overriding-field-check": NoMethodOverridingFieldCheck, +}; + +export const projectRules = { + "@migration/arkts-obj-literal-generate-class-instance": ObjectLiteralCheck, +}; + +// 新增文件级的checker,需要在此处注册 +export const file2CheckRuleMap: Map = new Map(Object.entries(fileRules)); +// 新增项目级checker,需要在此处注册 +export const project2CheckRuleMap: Map = new Map(Object.entries(projectRules)); + +export class ProxyChecker { + static getClass(ruleId: string) { + const checker = file2CheckRuleMap.get(ruleId) ?? project2CheckRuleMap.get(ruleId); + if (!checker) { + logger.error(`${ruleId} is not matched to any checker`); + return null; + } + return new checker(); + } +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/utils/common/CheckerStorage.ts b/ets2panda/linter/homecheck/src/utils/common/CheckerStorage.ts new file mode 100644 index 0000000000..e21b994bbb --- /dev/null +++ b/ets2panda/linter/homecheck/src/utils/common/CheckerStorage.ts @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Scope } from "../../model/Scope"; + +export class CheckerStorage { + private static instance: CheckerStorage; + private scopeMap: Map = new Map(); + private apiVersion: number = 16; + private product: string = ''; + + /** + * 获取 CheckerStorage 的单例实例 + * @returns {CheckerStorage} CheckerStorage 的单例实例 + */ + public static getInstance(): CheckerStorage { + if (!CheckerStorage.instance) { + CheckerStorage.instance = new CheckerStorage(); + } + return CheckerStorage.instance; + } + + /** + * 根据文件路径获取Scope + * @param filePath - 文件路径 + * @returns Scope | undefined - 返回Scope对象或undefined + */ + public getScope(filePath: string): Scope | undefined { + return this.scopeMap.get(filePath); + } + + /** + * 设置Scope映射 + * @param scopeMap - Scope映射,类型为 Map + */ + public setScopeMap(scopeMap: Map) { + this.scopeMap = scopeMap; + } + + /** + * 设置API版本 + * @param api API版本号 + */ + public setApiVersion(api: number): void { + this.apiVersion = api; + } + + /** + * 获取API版本号 + * @returns {number} 返回API版本号 + */ + public getApiVersion(): number { + return this.apiVersion; + } + + /** + * 设置product + * @param product + */ + public setProduct(pro: string): void { + this.product = pro; + } + + /** + * 获取product + * @returns {string} 返回product + */ + public getProduct(): string { + return this.product; + } +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/utils/common/ConfigUtils.ts b/ets2panda/linter/homecheck/src/utils/common/ConfigUtils.ts new file mode 100644 index 0000000000..f79ac650d1 --- /dev/null +++ b/ets2panda/linter/homecheck/src/utils/common/ConfigUtils.ts @@ -0,0 +1,275 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ALERT_LEVEL, ExtRuleSet, Rule } from "../../model/Rule"; +import { FileUtils } from "./FileUtils"; +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; +import { Utils } from "./Utils"; +import { execSync } from "child_process"; +import { Json5parser } from "./Json5parser"; +import { OptionValues } from "commander"; +import { CheckerStorage } from "./CheckerStorage"; +import path from "path"; +import { CheckEntry } from "./CheckEntry"; +import { RuleConfig } from "../../model/RuleConfig"; +import { ProjectConfig } from "../../model/ProjectConfig"; +import { file2CheckRuleMap, project2CheckRuleMap } from "./CheckerIndex"; +import fs from "fs"; +import { Message, MessageType } from "../../model/Message"; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'ConfigUtils'); + +export class ConfigUtils { + /** + * 获取配置文件 + * @param configPath 配置文件路径 + * @param rootDir 根目录,可选参数 + * @returns 返回解析后的配置对象,如果解析失败则返回null + */ + public static getConfig(configPath: string, rootDir?: string): any | null { + if (!fs.existsSync(configPath) && rootDir) { + // 规则配置文件不存在,使用默认配置文件 + configPath = path.join(rootDir, 'config', 'ruleConfg.json'); + } + + try { + return Json5parser.parseJsonText(FileUtils.readFile(configPath)); + } catch (e) { + logger.error(e); + return null; + } + } + + /** + * 解析配置文件并设置检查入口 + * @param argvObj 命令行参数对象 + * @param checkEntry 检查入口对象 + * @returns 是否成功解析配置文件 + */ + public static parseConfig(argvObj: OptionValues, checkEntry: CheckEntry): boolean { + const ruleConfig = ConfigUtils.getConfig(argvObj.configPath, argvObj.arkCheckPath); + const projectConfig = ConfigUtils.getConfig(argvObj.projectConfigPath); + if (!ruleConfig || !projectConfig) { + return false; + } + + // 解析规则配置文件 + checkEntry.ruleConfig = new RuleConfig(ruleConfig); + // 解析项目配置文件 + checkEntry.projectConfig = new ProjectConfig(projectConfig); + // 日志配置 + const logPath = checkEntry.projectConfig.logPath; + Utils.setLogPath(logPath.length === 0 ? './HomeCheck.log' : logPath); + logger.info('Checking started.'); + // api版本配置 + CheckerStorage.getInstance().setApiVersion(checkEntry.projectConfig.apiVersion); + // product配置 + CheckerStorage.getInstance().setProduct(checkEntry.projectConfig.product); + return true; + } + + /** + * 从配置文件中获取规则 + * @param ruleConfig 规则配置 + * @param projectConfig 项目配置 + * @param message 消息通知实例 + * @returns Map, ruleId -- Rule + */ + public static getRuleMap(ruleConfig: RuleConfig, projectConfig: ProjectConfig, message: Message): Map { + let ruleMap: Map = new Map(); + const allRules = ConfigUtils.getRuleSetMap(projectConfig.arkCheckPath); + for (const ruleSetStr of ruleConfig.ruleSet ?? []) { + const ruleSet = allRules.get(ruleSetStr); + if (!ruleSet) { + logger.error('Invalid ruleSet name: ' + ruleSetStr); + continue; + } + for (const [ruleId, level] of Object.entries(ruleSet)) { + const alert = Utils.getEnumValues(level, ALERT_LEVEL); + const rule = new Rule(ruleId, alert); + ruleMap.set(rule.ruleId, rule); + } + } + + for (const ruleInfo of Object.entries(ruleConfig.rules ?? {})) { + if (!this.isOnlineRule(ruleInfo[0], allRules)) { + logger.error('Invalid rule name: ' + ruleInfo[0]); + continue; + } + const rule = this.genRuleByOneRuleCfg(ruleInfo); + if (!rule) { + continue; + } + ruleMap.set(rule.ruleId, rule); + } + + // override 独有配置 + Object.entries(ruleConfig.extRules ?? {}).forEach(ruleInfo => { + const rule = this.genRuleByOneRuleCfg(ruleInfo); + if (!rule) { + return; + } + ruleMap.set(rule.ruleId, rule); + }); + + // 解析自定义规则集配置 + this.parseExtRuleConfig(ruleConfig, projectConfig, message, allRules, ruleMap); + return ruleMap;; + } + + /** + * 解析自定义规则配置 + * @param ruleConfig 规则配置 + * @param projectConfig 项目配置 + * @param message 消息对象 + * @param allRules 所有规则集合 + * @param ruleMap 规则映射 + */ + private static parseExtRuleConfig(ruleConfig: RuleConfig, projectConfig: ProjectConfig, message: Message, + allRules: Map, ruleMap: Map): void { + logger.info('The npmPath:' + projectConfig.npmPath); + logger.info('The npmInstallDir:' + projectConfig.npmInstallDir); + const extRuleSetSet = new Set(); + (ruleConfig.extRuleSet as ExtRuleSet[]).forEach((ruleSet) => { + if (!this.checkExtRuleSetConfig(ruleSet, allRules, extRuleSetSet, message)) { + return; + } + try { + const cmd = `${projectConfig.npmPath} install --no-save --prefix "${projectConfig.npmInstallDir}" "${ruleSet.packagePath}"`; + logger.info('Start to execute cmd: ' + cmd); + const execLog = execSync(cmd); + logger.info('Exec log: ' + execLog.toString()); + } catch (e) { + logger.error((e as Error).message); + return; + } + logger.info('npm install completed.'); + + let extPkg: any = null; + try { + extPkg = require(path.resolve(projectConfig.npmInstallDir, 'node_modules', ruleSet.ruleSetName)); + } catch (e) { + logger.error((e as Error).message); + message?.messageNotify(MessageType.CHECK_WARN, `Failed to get ${ruleSet.ruleSetName}, please check the ruleSetName.`); + return; + } + extRuleSetSet.add(ruleSet.ruleSetName); + + this.processExternalRules(ruleSet, allRules, extPkg, message, ruleMap); + }); + } + + private static processExternalRules(ruleSet: ExtRuleSet, allRules: Map, extPkg: any, message: Message, ruleMap: Map): void { + Object.entries(ruleSet.extRules ?? {}).forEach(ruleInfo => { + if (this.isOnlineRule(ruleInfo[0], allRules)) { + message?.messageNotify(MessageType.CHECK_WARN, `The extRuleName can't be the same as the internal rules name, name = ${ruleInfo[0]}.`); + return; + } + const rule = this.genRuleByOneRuleCfg(ruleInfo); + if (!rule) { + return; + } + let module = extPkg?.file2CheckRuleMap?.get(rule.ruleId); + if (module) { + file2CheckRuleMap.set(rule.ruleId, module); + } else { + module = extPkg?.project2CheckRuleMap?.get(rule.ruleId); + if (module) { + project2CheckRuleMap.set(rule.ruleId, module); + } else { + message?.messageNotify(MessageType.CHECK_WARN, `Failed to get '${rule.ruleId}' in '${ruleSet.ruleSetName}', please check the extRules.`); + return; + } + } + ruleMap.set(rule.ruleId, rule); + }); + } + + /** + * 通过单个规则配置生成Rule对象,eg: "@ruleSet/ruleName": "error" | ["error", []...] + * @param ruleCfg - 规则配置,格式为 [string, any] + * @returns Rule | null - 生成的规则对象或 null + */ + private static genRuleByOneRuleCfg(ruleCfg: [string, any]): Rule | null { + let alert = ALERT_LEVEL.SUGGESTION; + let option: any[] = []; + if (ruleCfg[1] instanceof Array) { + alert = Utils.getEnumValues(ruleCfg[1][0], ALERT_LEVEL); + for (let i = 1; i < ruleCfg[1].length; i++) { + option.push(ruleCfg[1][i]); + } + } else { + alert = Utils.getEnumValues(ruleCfg[1], ALERT_LEVEL); + } + const rule = new Rule(ruleCfg[0], alert); + rule.option = option; + return rule; + } + + /** + * 读取RuleSet.json中配置的规则集 + */ + static getRuleSetMap(rootDir: string): Map { + const ruleSetMap: Map = new Map(); + try { + const fileStr = FileUtils.readFile(path.join(rootDir, 'ruleSet.json')); + const config: Record = JSON.parse(fileStr); + for (const [key, value] of Object.entries(config)) { + ruleSetMap.set(key, value); + } + } catch (error) { + logger.error((error as Error).message); + } + return ruleSetMap; + } + + /** + * 检查指定的规则是否存在 + * @param ruleId - 要检查的规则ID + * @param allRules - 包含所有规则的Map对象 + * @returns 如果规则存在则返回true,否则返回false + */ + static isOnlineRule(ruleId: string, allRules: Map): boolean { + for (const [ruleSet, rules] of allRules) { + if (rules.hasOwnProperty(ruleId)) { + return true; + } + } + return false; + } + + /** + * 检查自定义规则集配置的有效性 + * @param ruleSet - 自定义规则集 + * @param allRules - 所有规则集合 + * @param extRuleSetSet - 自定义规则集集合 + * @param message - 消息对象 + * @returns {boolean} - 是否通过检查 + */ + static checkExtRuleSetConfig(ruleSet: ExtRuleSet, allRules: Map, extRuleSetSet: Set, message: Message): boolean { + if (allRules.get(`${ruleSet.ruleSetName}`)) { + message?.messageNotify(MessageType.CHECK_WARN, `The extRuleSetName can't be the same as the name of internal rule set name, name = ${ruleSet.ruleSetName}.`); + return false; + } + if (!ruleSet.packagePath || ruleSet.packagePath.length === 0 || FileUtils.isExistsSync(ruleSet.packagePath) === false) { + message?.messageNotify(MessageType.CHECK_WARN, `'${ruleSet.packagePath}' is invalid or not exist, please check the packagePath.`); + return false; + } + if (extRuleSetSet.has(ruleSet.ruleSetName)) { + message?.messageNotify(MessageType.CHECK_WARN, `'${ruleSet.ruleSetName}' is conflict, please check the ruleSetName.`); + return false; + } + return true; + } +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/utils/common/DefectsList.ts b/ets2panda/linter/homecheck/src/utils/common/DefectsList.ts new file mode 100644 index 0000000000..4d798e5ddc --- /dev/null +++ b/ets2panda/linter/homecheck/src/utils/common/DefectsList.ts @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an 'AS IS' BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Defects } from '../../model/Defects'; +import Logger, { LOG_MODULE_TYPE } from "arkanalyzer/lib/utils/logger"; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'CheckEntry'); + +namespace DefectsList { + let defects: Defects[] = []; + + export function add(defect: Defects) { + defects.push(defect); + } + + export function updateDefectByIndex(index: number, defect: Defects) { + defects[index] = defect; + } + + export function getDefects(): Defects[] { + return defects; + } + + export function clear() { + defects = []; + } +} + + +export class RuleListUtil { + static push(defect: Defects) { + } + + static updateDefect(defect: Defects) { + } + + static printDefects() { + } + + static isFilter(ruleId: string): boolean { + return ruleId.startsWith('@ArkTS-eslint'); + } +} diff --git a/ets2panda/linter/homecheck/src/utils/common/Disable.ts b/ets2panda/linter/homecheck/src/utils/common/Disable.ts new file mode 100644 index 0000000000..9ed537c699 --- /dev/null +++ b/ets2panda/linter/homecheck/src/utils/common/Disable.ts @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { IssueReport } from "../../model/Defects"; + +export const DisableText = { + FILE_DISABLE_TEXT: "\/* homecheck-disable *\/", + NEXT_LINE_DISABLE_TEXT: "\/\/ homecheck-disable-next-line ", +}; + +export function filterDisableIssue(lineList: string[], issues: IssueReport[]): IssueReport[] { + let filtedIssues: IssueReport[] = []; + issues.forEach(issue => { + // 有些特殊规则允许返回行列号为0 + if (issue.defect.reportLine < 0 || issue.defect.reportLine - 1 > lineList.length) { + return; + } + const text = lineList[issue.defect.reportLine - 2]; + if (!isDisableIssue(text, issue.defect.ruleId)) { + filtedIssues.push(issue); + } + }); + return filtedIssues; +} + +function isDisableIssue(lineText: string, ruleId: string): boolean { + if (!lineText || lineText.length === 0) { + return false; + } + + if (lineText.includes(DisableText.NEXT_LINE_DISABLE_TEXT) && lineText.includes(ruleId)) { + return true; + } + return false; +} diff --git a/ets2panda/linter/homecheck/src/utils/common/FileRuleMapping.ts b/ets2panda/linter/homecheck/src/utils/common/FileRuleMapping.ts new file mode 100644 index 0000000000..548a248142 --- /dev/null +++ b/ets2panda/linter/homecheck/src/utils/common/FileRuleMapping.ts @@ -0,0 +1,153 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkFile } from "arkanalyzer"; +import { CheckEntry } from "./CheckEntry"; +import { ConfigUtils } from "./ConfigUtils"; +import { CheckerUtils } from "../checker/CheckerUtils"; +import { file2CheckRuleMap, project2CheckRuleMap } from "./CheckerIndex"; +import { Rule } from "../../model/Rule"; +import { RuleConfig } from "../../model/RuleConfig"; +import { fileCheckBuilder, projectCheckBuilder } from "./CheckBuilder"; +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; +import { FileUtils } from "./FileUtils"; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'fileRuleMapping'); + +export async function fileRuleMapping(checkFileList: string[], checkEntry: CheckEntry): Promise { + // 获取规则配置文件的规则,除了override + const allRulesMap = ConfigUtils.getRuleMap(checkEntry.ruleConfig, checkEntry.projectConfig, checkEntry.message); + if (allRulesMap.size === 0) { + checkEntry.message?.progressNotify(1, "No rule to check"); + return false; + } + + let arkFiles: ArkFile[] = []; + const fiRulesMap: Map = new Map(); + const fileRulesMap = await createFileRulesMap(checkFileList, allRulesMap, checkEntry, file2CheckRuleMap, fiRulesMap); + for (const filePath of checkFileList) { + try { + const arkFile = CheckerUtils.getArkFileByFilePath(checkEntry.scene, filePath); + if (!arkFile) { + continue; + } + + arkFiles.push(arkFile); + const enabledRules = fileRulesMap.get(filePath); + if (enabledRules) { + checkEntry.addFileCheck(fileCheckBuilder(arkFile, enabledRules)); + } + } catch (error) { + logger.error(`Error processing file ${filePath}: ${(error as Error).message}`); + } + } + + const proRulesMap: Map = new Map(); + const projectRulesMap = await createFileRulesMap(checkFileList, allRulesMap, checkEntry, project2CheckRuleMap, proRulesMap); + const projectRules = Array.from(proRulesMap.values()); + try { + checkEntry.addProjectCheck(projectCheckBuilder(arkFiles, projectRules)); + checkEntry.projectCheck.ruleMap = projectRulesMap; + } catch (error) { + logger.error(`Error adding project check: ${(error as Error).message}`); + } + return true; +} + +function filterRule(allRulesMap: Map, filterMap?: Map): Rule[] { + const rules: Rule[] = []; + for (const [key, value] of allRulesMap) { + if (filterMap && !filterMap.has(key)) { + continue; + } + rules.push(value); + } + return rules; +} + +async function createFileRulesMap(allFiles: string[], allRulesMap: Map, checkEntry: CheckEntry, + checksRuleMap: Map, proRulesMap: Map): Promise> { + // 获取配置的规则列表 + let fileRulesMap: Map = new Map(); + const ruleMap = filterRule(allRulesMap, checksRuleMap); + + const defaultRules = Array.from(ruleMap.values()); + allFiles.forEach(filePath => fileRulesMap.set(filePath, defaultRules)); + ruleMap.forEach(rule => { + proRulesMap.set(rule.ruleId, rule); + }); + // 检查额外规则覆盖 + for (const override of checkEntry.ruleConfig.overrides ?? []) { + try { + const overrideFileRulesMap = await createFileRulesMapWithOverride(checkEntry, override, checksRuleMap, proRulesMap); + fileRulesMap = mergeFileRulesMap(fileRulesMap, overrideFileRulesMap); + } catch (error) { + logger.error(`Error check extra rule overrides: ${(error as Error).message}`); + } + } + return fileRulesMap; +} + +async function createFileRulesMapWithOverride(checkEntry: CheckEntry, override: RuleConfig, + checksRuleMap: Map, proRulesMap: Map): Promise> { + let checkFileList = checkEntry.selectFileList.map(file => file.filePath); + if (checkFileList.length === 0) { + checkFileList = FileUtils.getAllFiles(checkEntry.projectConfig.projectPath, ['.ts', '.ets', '.json5']); + } + checkFileList = await FileUtils.getFiltedFiles(checkFileList, override); + const allRuleMap = ConfigUtils.getRuleMap(override, checkEntry.projectConfig, checkEntry.message); + const ruleMap = filterRule(allRuleMap, checksRuleMap); + ruleMap.forEach(rule => { + if (!proRulesMap.has(rule.ruleId)) { + proRulesMap.set(rule.ruleId, rule); + } + }); + const fileRulesMap: Map = new Map(); + const defaultRules = Array.from(ruleMap.values()); + checkFileList.forEach(filePath => fileRulesMap.set(filePath, defaultRules)); + return fileRulesMap; +} + +function mergeFileRulesMap(fileRulesMap: Map, + overrideFileRulesMap: Map): Map { + // 取fileRule和overrideRule交集 + for (const [key, vals] of overrideFileRulesMap) { + if (!fileRulesMap.has(key) || vals.length === 0) { + continue; + } + let fileRules = fileRulesMap.get(key); + if (!fileRules || fileRules.length === 0) { + fileRulesMap.set(key, vals); + continue; + } + let newRules = [...fileRules]; + vals.forEach(val => { + let existIndex = fileRules?.findIndex(fileRule => fileRule.ruleId === val.ruleId); + if (existIndex === undefined || existIndex === -1) { + newRules.push(val); + } else { + newRules[existIndex] = val; + } + }); + fileRulesMap.set(key, newRules); + } + // 筛除关闭的rule + const filteredRulesMap = new Map(); + for (const [key, rules] of fileRulesMap) { + const filteredRules = rules.filter(rule => rule.alert !== 0); + filteredRulesMap.set(key, filteredRules); + } + return filteredRulesMap; +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/utils/common/FileUtils.ts b/ets2panda/linter/homecheck/src/utils/common/FileUtils.ts new file mode 100644 index 0000000000..5b32b9f048 --- /dev/null +++ b/ets2panda/linter/homecheck/src/utils/common/FileUtils.ts @@ -0,0 +1,289 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import * as fs from "fs"; +import * as path from "path"; +import { createInterface } from "readline"; +import { DisableText } from "./Disable"; +import { Sdk } from "arkanalyzer/lib/Config"; +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; +import { FileToCheck, ProjectConfig, SelectedFileInfo } from '../../model/ProjectConfig'; +import { RuleConfig } from "../../model/RuleConfig"; +import { GlobMatch } from "./GlobMatch"; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'FileUtils'); +export class FileUtils { + /** + * 读取指定文件并返回其内容 + * @param {string} fileName - 要读取的文件名 + * @returns {string} - 文件内容 + */ + public static readFile(fileName: string): string { + return fs.readFileSync(fileName, 'utf8').replace(/^\ufeff/u, ''); + } + + /** + * 根据给定的文件列表和规则配置,过滤出符合规则的文件列表。 + * @param fileList 文件列表。 + * @param ruleConfig 规则配置,包含匹配和忽略文件的规则,以及可能的重写规则。 + * @returns 返回符合规则的文件列表,异常情况下返回空数组。 + */ + public static async getFiltedFiles(fileList: string[], ruleConfig: RuleConfig): Promise { + try { + let result = await this.matchFiles(fileList, ruleConfig.files, ruleConfig.ignore); + const overrides = ruleConfig.overrides; + if (overrides.length > 0) { + for (const override of overrides) { + result = result.concat(await this.getFiltedFiles(fileList, override)); + result = [...new Set(result)]; + } + } + return result; + } catch (error) { + logger.error(`Error occurred while reading files: ${error}`); + return []; + } + } + + /** + * 匹配文件列表中的文件,返回符合条件的文件路径列表 + * @param fileList 文件路径列表 + * @param fileTypes 文件类型列表,使用glob模式匹配 + * @param ignoreDirs 要忽略的目录列表,使用glob模式匹配,默认为空数组 + * @returns 符合条件的文件路径列表 + */ + public static async matchFiles(fileList: string[], fileGlob: GlobMatch, ignoreGlob: GlobMatch): Promise { + let result: string[] = []; + for (const filePath of fileList) { + if (!ignoreGlob?.matchGlob(filePath) && fileGlob.matchGlob(filePath)) { + // 读取file文件内容首行,若为屏蔽行则跳过 + const firstLineText = await this.readLinesFromFile(filePath, 1); + if (firstLineText.includes(DisableText.FILE_DISABLE_TEXT)) { + continue; + } + result.push(filePath); + } + } + return result; + } + + + /** + * 从文件中读取指定行或全部行 + * @param filePath 文件路径 + * @param lineNo 要读取的行号,不传或者0值则读取全部行 + * @returns 读取到的行组成的字符串数组 + * @throws 如果读取文件时发生错误,将抛出异常 + */ + public static async readLinesFromFile(filePath: string, lineNo?: number): Promise { + return new Promise((resolve, reject) => { + let lines: string[] = []; + let readLineNo = 1; + + let rl = createInterface({ + input: fs.createReadStream(filePath), + crlfDelay: Infinity + }); + + const handleLine = (line: string): void => { + if (lineNo) { + if (readLineNo === lineNo) { + lines.push(line); + rl.close(); + } + } else { + lines.push(line); + } + readLineNo++; + }; + + rl.on('line', handleLine); + + rl.on('close', () => { + resolve(lines); + }); + + rl.on('error', (err) => { + reject(err); + }); + }) + } + + /** + * 检查文件是否存在 + * @param filePath 文件路径 + * @returns 如果文件存在则返回true,否则返回false + */ + public static isExistsSync(filePath: string): boolean { + return fs.existsSync(filePath); + } + + /** + * 从指定路径的JSON文件中获取符合条件的文件信息列表 + * @param jsonPath JSON文件路径 + * @param exts 文件扩展名数组 + * @returns 符合条件的文件信息数组 + */ + public static getSeletctedFileInfos(jsonPath: string, exts: string[]): SelectedFileInfo[] { + const fileInfoList: SelectedFileInfo[] = []; + try { + const jsonData = JSON.parse(fs.readFileSync(jsonPath, 'utf8')); + jsonData.checkPath?.forEach((fileInfo: SelectedFileInfo) => { + if (exts.includes(path.extname(fileInfo.filePath))) { + fileInfoList.push(fileInfo); + } + }); + } catch (error) { + logger.error(`Error occurred while reading file list from ${jsonPath}: ${error}`); + } + return fileInfoList; + } + + public static getFileInfoFromFileList(fileOrFolderList: string[]): SelectedFileInfo[] { + const fileInfoList: SelectedFileInfo[] = []; + fileOrFolderList.forEach((fileOrFolderPath) => { + if (fs.statSync(fileOrFolderPath).isFile()){ + fileInfoList.push(new FileToCheck(fileOrFolderPath)) + }else { + const filesInFolder = FileUtils.getAllFiles(fileOrFolderPath, []); + filesInFolder.forEach((filePath) => { + fileInfoList.push(new FileToCheck(filePath)) + }) + } + }) + return fileInfoList; + } + + /** + * 获取指定目录下所有符合条件的文件 + * @param dirPath - 目录路径 + * @param exts - 文件扩展名数组,如果为空则获取所有文件,['.ts', '.ets', '.json5'] + * @param filenameArr - 存储符合条件的文件路径的数组,默认为空数组 + * @param visited - 已访问的目录集合,默认为空集合 + * @returns 符合条件的文件路径数组 + */ + public static getAllFiles(dirPath: string, exts: string[], filenameArr: string[] = [], visited: Set = new Set()): string[] { + // 检查目录是否存在 + if (!fs.existsSync(dirPath)) { + logger.error(`'${dirPath}' is not exist, please check!`); + return filenameArr; + } + // 获取目录的绝对路径 + const realSrc = fs.realpathSync(dirPath); + // 避免重复访问 + if (visited.has(realSrc)) { + return filenameArr; + } + visited.add(realSrc); + // 读取目录下的文件和文件夹 + fs.readdirSync(realSrc).forEach(fileName => { + if (this.shouldSkipFile(fileName)) { + return; + } + const realFile = path.resolve(realSrc, fileName); + // 如果是文件夹,则递归调用 + if (fs.statSync(realFile).isDirectory()) { + this.getAllFiles(realFile, exts, filenameArr, visited); + } else { + // 如果扩展名为空,则添加所有文件 + if (exts.length === 0) { + filenameArr.push(realFile); + } else if (this.shouldAddFile(realFile, exts)) { + filenameArr.push(realFile); + } + } + }) + return filenameArr; + } + + private static shouldSkipFile(fileName: string): boolean { + return ['oh_modules', 'node_modules', 'hvigorfile.ts', 'ohosTest'].includes(fileName); + } + + private static shouldAddFile(filePath: string, exts: string[]): boolean { + if (exts.length === 0) { + return true; + } + const ext = path.extname(filePath).toLowerCase(); + return exts.includes(ext); + } + + /** + * 生成SDK数组 + * @param projectConfig - 项目配置 + * @returns Sdk[] - SDK数组 + */ + public static genSdks(projectConfig: ProjectConfig): Sdk[] { + let sdks: Sdk[] = []; + const sdkConfigPath = path.join(projectConfig.arkCheckPath, 'resources', 'sdkConfig.json'); + if (fs.existsSync(sdkConfigPath)) { + const configurations = JSON.parse(fs.readFileSync(sdkConfigPath, 'utf-8')); + sdks = configurations.sdks ?? []; + } + if (!projectConfig.ohosSdkPath && !projectConfig.hmsSdkPath) { + return sdks; + } + sdks.forEach(sdk => { + if (sdk.name === 'ohosSdk') { + sdk.path = projectConfig.ohosSdkPath; + } else if (sdk.name === 'hmsSdk') { + sdk.path = projectConfig.hmsSdkPath; + } else { + sdk.path = path.join(projectConfig.arkCheckPath, sdk.path); + } + }); + projectConfig.sdksThirdParty?.forEach(sdkThirdParty => { + let sdkJson = JSON.parse(JSON.stringify(sdkThirdParty)); + let sdkFd = sdks.find(sdk => sdk.name === sdkJson.name); + if (!sdkFd) { + let sdk3rd: Sdk = { + name: sdkJson.name, + path: path.resolve(sdkJson.path), + moduleName: sdkJson.moduleName, + }; + sdks.push(sdk3rd); + } else { + sdkFd.path = path.resolve(sdkJson.path); + sdkFd.moduleName = sdkJson.moduleName; + } + }); + return sdks; + } + + + /** + * 写入文件,同步接口 + * @param filePath 文件路径 + * @param content 写入的内容 + * @param mode 写入模式,不传默认为追加模式 + **/ + public static writeToFile(filePath: string, content: string, mode: WriteFileMode = WriteFileMode.APPEND) { + const dirName = path.dirname(filePath); + if (!fs.existsSync(dirName)) { + fs.mkdirSync(dirName, { recursive: true }); + } + if (mode === WriteFileMode.OVERWRITE) { + fs.writeFileSync(filePath, content, { encoding: 'utf8' }); + } else if (mode === WriteFileMode.APPEND) { + fs.appendFileSync(filePath, content, { encoding: 'utf8' }); + } else { + logger.error(`Invalid write mode: ${mode}`); + } + } +} + +export enum WriteFileMode { + OVERWRITE, + APPEND +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/utils/common/FixUtils.ts b/ets2panda/linter/homecheck/src/utils/common/FixUtils.ts new file mode 100644 index 0000000000..234825a056 --- /dev/null +++ b/ets2panda/linter/homecheck/src/utils/common/FixUtils.ts @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkClass, ArkFile, ArkMethod, ExportInfo, ImportInfo, Stmt } from "arkanalyzer"; +import { AIFix, FunctionFix, RuleFix } from "../../model/Fix"; + +export class FixUtils { + + public static getRangeStart(arkFile: ArkFile, codeNode: Stmt | ArkMethod | ArkClass | ExportInfo | ImportInfo): number { + let lineNum = 0; + let startColumn = 0; + if (codeNode instanceof Stmt) { + let originalPosition = codeNode.getOriginPositionInfo(); + lineNum = originalPosition.getLineNo(); + startColumn = originalPosition.getColNo(); + } else if (codeNode instanceof ArkMethod) { + lineNum = codeNode.getLine()?? 0; + startColumn = codeNode.getColumn()?? 0; + } else if (codeNode instanceof ArkClass) { + lineNum = codeNode.getLine()?? 0; + startColumn = codeNode.getColumn()?? 0; + } else if (codeNode instanceof ExportInfo) { + let originalPosition = codeNode.getOriginTsPosition(); + lineNum = originalPosition.getLineNo(); + startColumn = originalPosition.getColNo(); + } else if (codeNode instanceof ImportInfo) { + let originalPosition = codeNode.getOriginTsPosition(); + lineNum = originalPosition.getLineNo(); + startColumn = originalPosition.getColNo(); + } + // 原文代码 + let code = arkFile.getCode(); + // 找到当前分割符所在行 + let lineBreak = this.getTextEof(code); + let cnt = 0; + if (lineBreak.length > 0) { + for(let index = 1; index !== lineNum; index++) { + cnt = code.indexOf(lineBreak, cnt + 1); + } + } + let start = (cnt === 0 && startColumn === 1) ? 0 : (cnt + startColumn + 1);//对第一行第一列特殊处理,后续代码都是以0,所以需要+1 + return start; + } + + public static getTextEof(text: string): string { + if (text.includes('\r\n')) { + return '\r\n'; + } else if (text.includes('\n')) { + return '\n'; + } else if (text.includes('\r')) { + return '\r'; + } else { + return ''; + } + } + + public static isRuleFix(object: any): object is RuleFix { + return typeof object === "object" && 'range' in object && 'text' in object; + } + + public static isFunctionFix(object: any): object is FunctionFix { + return typeof object === "object" && 'fix' in object; + } + + public static isAIFix(object: any): object is AIFix { + return typeof object === "object" && 'text' in object; + } + + public static hasOwnProperty(object: any, key: string): boolean { + return typeof object === "object" && key in object; + } +} diff --git a/ets2panda/linter/homecheck/src/utils/common/GeneratingJsonFile.ts b/ets2panda/linter/homecheck/src/utils/common/GeneratingJsonFile.ts new file mode 100644 index 0000000000..33c2b38193 --- /dev/null +++ b/ets2panda/linter/homecheck/src/utils/common/GeneratingJsonFile.ts @@ -0,0 +1,151 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; +import { FileReports } from '../../model/Defects'; +import { FileUtils, WriteFileMode } from './FileUtils'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'GeneratingJsonFile'); +const severitys: string[] = ['OFF', 'WARN', 'ERROR', 'SUGGESTION']; +const FILE_NAMING_RULE = '@hw-stylistic/file-naming-convention'; + +export class GeneratingJsonFile { + public static generatingJsonFile(filePath: string, fileReports: FileReports[]) { + const fileDefectInfos = this.format(fileReports); + let results: Map = new Map(); + for (let fileDefectInfo of fileDefectInfos) { + this.addResult(fileDefectInfo, results); + } + const jsonString = this.format2(results); + try { + FileUtils.writeToFile(filePath, jsonString, WriteFileMode.OVERWRITE); + } catch (error) { + logger.error(`write file ${filePath} failed, error: ${error}`); + } + } + + /** + * 过滤掉部分不需要的defect属性 + * + * @param fileReports 原始文件缺陷信息数组 + * @returns 过滤后的文件缺陷信息数组 + */ + private static format(fileReports: FileReports[]): FileDefectInfo[] { + const fileDefectInfos: FileDefectInfo[] = []; + for (const fileReport of fileReports) { + const fileDefectInfo: FileDefectInfo = { + filePath: fileReport.filePath, + defects: [] + } + for (const defect of fileReport.defects) { + const defectInfo: DefectInfo = { + reportLine: defect.reportLine, + reportColumn: defect.reportColumn, + ruleId: defect.ruleId, + severity: severitys[defect.severity], + mergeKey: defect.mergeKey, + description: defect.description, + ruleDocPath: defect.ruleDocPath + } + fileDefectInfo.defects.push(defectInfo); + } + fileDefectInfos.push(fileDefectInfo); + } + return fileDefectInfos; + } + + private static addResult(defect: FileDefectInfo, results: Map) { + const normalizedPath = path.normalize(defect.filePath).toLocaleLowerCase(); + if (!results.has(normalizedPath)) { + results.set(normalizedPath, defect); + } else { + results.get(normalizedPath)?.defects.push(...defect.defects); + } + const defectInfo = results.get(normalizedPath); + defectInfo?.defects.sort((defectA, defectB) => { + if (defectA.ruleId === FILE_NAMING_RULE) { + return -1; + } + if (defectB.ruleId === FILE_NAMING_RULE) { + return 1; + } + if (defectA.reportLine === defectB.reportLine) { + if (defectA.reportColumn === defectB.reportColumn) { + return defectA.mergeKey.localeCompare(defectB.mergeKey); + } + return defectA.reportColumn - defectB.reportColumn; + } + return defectA.reportLine - defectB.reportLine; + }); + } + + private static format2(results: Map) { + const jsonResults: JsonResult[] = []; + for (let result of results) { + const oneResult: JsonResult = { + filePath: '', + messages: [] + } + oneResult.filePath = result[1].filePath; + let defects = result[1].defects; + for (let defect of defects) { + const oneDefect: SimpleDefect = { + line: 0, + column: 0, + severity: '', + message: '', + rule: '', + } + oneDefect.line = defect.reportLine; + oneDefect.column = defect.reportColumn; + oneDefect.severity = defect.severity; + oneDefect.message = defect.description; + oneDefect.rule = defect.ruleId; + oneResult.messages.push(oneDefect); + } + jsonResults.push(oneResult); + } + return JSON.stringify(jsonResults, null, 2); + } +} + +interface JsonResult { + filePath: string; + messages: SimpleDefect[]; +} + +interface SimpleDefect { + line: number; + column: number; + severity: string; + message: string; + rule: string | null; +} + +interface FileDefectInfo { + filePath: string; + defects: DefectInfo[]; +} + +interface DefectInfo { + severity: string; + description: string; + mergeKey: string; + reportLine: number; + reportColumn: number; + ruleId: string | null; + ruleDocPath: string | null; +} diff --git a/ets2panda/linter/homecheck/src/utils/common/GlobMatch.ts b/ets2panda/linter/homecheck/src/utils/common/GlobMatch.ts new file mode 100644 index 0000000000..c1f25cdc7c --- /dev/null +++ b/ets2panda/linter/homecheck/src/utils/common/GlobMatch.ts @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export class GlobMatch { + private regexps: string[] = []; + + constructor(globPattern: string[]) { + this.regexps = globPattern.map(pattern => this.globToRegexp(pattern)); + } + + matchGlob(path: string): boolean { + path = path.replace(/\\/g, '/'); + return this.regexps.some(regexp => new RegExp(regexp).test(path)); + } + + private globToRegexp(glob: string): string { + glob = glob.replace(/\\/g, '/').replace(/\/+/g, '/'); + const specialChars = new Set(['.', '+', '*', '?', '[', '^', ']', '(', ')', '{', '}', '|']); + let regexp = ''; + let isStar = false; + for (let i = 0; i < glob.length; i++) { + const char = glob[i]; + if (char === '*') { + if (!isStar) { + regexp += '.*'; // 匹配任意字符序列,包括空字符串。 + } + isStar = true; + continue; + } else if (char === '?') { + regexp += '.'; // 匹配任意单个字符。 + } else if (specialChars.has(char)) { + regexp += `\\${char}`; // 转义特殊字符。 + } else { + regexp += char; + } + isStar = false; + } + // 防止配置的是'.c', 匹配到了'.cpp' + if (regexp.match('.*\\.[a-zA-Z]+$')) { + regexp = `${regexp}$`; + } + return regexp; + } +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/utils/common/Json5parser.ts b/ets2panda/linter/homecheck/src/utils/common/Json5parser.ts new file mode 100644 index 0000000000..78d4ef7bdf --- /dev/null +++ b/ets2panda/linter/homecheck/src/utils/common/Json5parser.ts @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ts } from "arkanalyzer"; +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'Json5parser'); + +export class Json5parser { + /** + * 获取JSON5文件的根对象字面量表达式 + * @param file - JSON5文件的源文件对象 + * @returns 如果找到根对象字面量表达式,则返回该表达式;否则返回undefined + */ + public static getRootObjectLiteral(file: ts.JsonSourceFile): ts.ObjectLiteralExpression | undefined { + // 检查文件语句是否为空 + if (!file.statements || !file.statements.length) { + logger.error('The JSON5 file format is incorrect, the root node statements is empty.'); + return undefined; + } + const expressionStatement = file.statements[0]; + if (expressionStatement.kind !== ts.SyntaxKind.ExpressionStatement) { + logger.error(`The JSON5 file format is incorrect, the first child node is not ExpressionStatement. kind: ${expressionStatement.kind}`); + return undefined; + } + // JSON5顶层对象仅识别一个 + const rootObjectLiteralExpression = (expressionStatement as ts.ExpressionStatement).expression; + if (!rootObjectLiteralExpression) { + logger.error('The JSON5 file format is incorrect, the first child node expression is empty.'); + return undefined; + } + // 检查表达式是否为对象字面量表达式 + if (rootObjectLiteralExpression.kind === ts.SyntaxKind.ObjectLiteralExpression) { + return rootObjectLiteralExpression as ts.ObjectLiteralExpression; + } + // 检查表达式是否为数组字面量表达式 + if (rootObjectLiteralExpression.kind === ts.SyntaxKind.ArrayLiteralExpression) { + const elements = (rootObjectLiteralExpression as ts.ArrayLiteralExpression).elements; + // 检查数组是否为空或第一个元素是否为对象字面量表达式 + if (elements && elements.length && elements[0].kind === ts.SyntaxKind.ObjectLiteralExpression) { + return elements[0] as ts.ObjectLiteralExpression; + } + logger.error('The JSON5 file format is incorrect, the node ArrayLiteralExpression first element is not ObjectLiteralExpression.'); + } + logger.error('The JSON5 file format is incorrect.'); + return undefined; + } + + /** + * 解析对象字面量表达式 + * @param objectLiteralExpression - 对象字面量表达式 + * @param file - JSON源文件 + * @returns 解析后的对象字面量表达式 + */ + private static parseObjectLiteralExpression(objectLiteralExpression: ts.ObjectLiteralExpression, file: ts.JsonSourceFile): { [k: string]: unknown } { + const res: { [k: string]: unknown } = {}; + objectLiteralExpression.properties.forEach(node => { + const propNode = node as ts.PropertyAssignment; + const key = (propNode.name as ts.Identifier).text; + const value = this.parsePropertyInitializer(propNode.initializer, file); + res[key] = value; + }); + return res; + } + + /** + * 解析语法树中的表达式节点 + * @param node - 表达式节点 + * @param file - JSON源文件 + * @returns 解析后的值 + */ + private static parsePropertyInitializer(node: ts.Expression, file: ts.JsonSourceFile): unknown { + if (node.kind === ts.SyntaxKind.StringLiteral) { + return (node as ts.StringLiteral).text; + } else if (node.kind === ts.SyntaxKind.NumericLiteral) { + return parseInt((node as ts.NumericLiteral).text); + } else if (node.kind === ts.SyntaxKind.PrefixUnaryExpression) { + return Number((node as ts.PrefixUnaryExpression).getText(file)); + } else if (node.kind === ts.SyntaxKind.ArrayLiteralExpression) { + return this.parseArrayLiteral(node, file); + } else if (node.kind === ts.SyntaxKind.ObjectLiteralExpression) { + return this.parseObjectLiteralExpression(node as ts.ObjectLiteralExpression, file); + } else if (node.kind === ts.SyntaxKind.TrueKeyword) { + return true; + } else if (node.kind === ts.SyntaxKind.FalseKeyword) { + return false; + } + return undefined; + } + + /** + * 解析数组字面量表达式 + * @param node - 要解析的表达式节点 + * @param file - 所属的 JSON 源文件 + * @returns 解析后的数组 + */ + private static parseArrayLiteral(node: ts.Expression, file: ts.JsonSourceFile) { + const res: unknown[] = []; + (node as ts.ArrayLiteralExpression).elements.forEach(n => { + res.push(this.parsePropertyInitializer(n, file)); + }); + return res; + } + + /** + * 解析JSON文本 + * @param text - 要解析的JSON文本 + * @returns 解析后的对象 + */ + public static parseJsonText(text: string): { [k: string]: unknown } { + const file = ts.parseJsonText('', text); + const rootObjectLiteralExpression = this.getRootObjectLiteral(file); + if (!rootObjectLiteralExpression) { + return {}; + } + return this.parseObjectLiteralExpression(rootObjectLiteralExpression, file); + } +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/utils/common/ScopeHelper.ts b/ets2panda/linter/homecheck/src/utils/common/ScopeHelper.ts new file mode 100644 index 0000000000..9bf9c65260 --- /dev/null +++ b/ets2panda/linter/homecheck/src/utils/common/ScopeHelper.ts @@ -0,0 +1,273 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ArkArrayRef, ArkAssignStmt, ArkClass, ArkIfStmt, ArkThisRef, BasicBlock, DEFAULT_ARK_METHOD_NAME, Local, Scene, Stmt } from "arkanalyzer"; +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; +import { CheckerStorage, CheckerUtils, Scope, ScopeType, TempLocation } from "../../Index"; +import { Variable } from "../../model/Variable"; +import { VarInfo } from "../../model/VarInfo"; +import { FixUtils } from "./FixUtils"; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'ScopeHelper'); + +export class ScopeHelper { + private gFilePath: string = ''; + private firstBlock: BasicBlock | undefined; + private finishBlockSet: Set; + private isSwitchLastCase = false; + private gFinishIfStmtLines: number[] = []; + private gTernaryConditionLines: Set = new Set(); + + public buildScope(scene: Scene): void { + let scopeMap = new Map(); + for (const file of scene.getFiles()) { + this.gFilePath = file.getFilePath(); + const firstScope = new Scope(null, new Array(), 0); + scopeMap.set(this.gFilePath, firstScope); + for (const clazz of file.getClasses()) { + this.createScopeInClass(clazz, firstScope); + } + } + CheckerStorage.getInstance().setScopeMap(scopeMap); + } + + private createScopeInClass(clazz: ArkClass, firstScope: Scope): void { + for (let method of clazz.getMethods()) { + this.gFinishIfStmtLines = []; + this.gTernaryConditionLines.clear(); + this.finishBlockSet = new Set(); + this.firstBlock = method.getBody()?.getCfg()?.getStartingBlock(); + if (!this.firstBlock) { + logger.debug(`${clazz.getName()}::${method.getName()} has no body.`); + continue; + } + let curScope = firstScope; + if (method.getName() !== DEFAULT_ARK_METHOD_NAME) { + curScope = new Scope(firstScope, new Array(), 1); + firstScope.setChildScope(curScope); + } + this.blockProcess(this.firstBlock, curScope); + } + } + + private blockProcess(block: BasicBlock, parentScope: Scope): void { + let curScope = parentScope; + let stmts = block.getStmts(); + if (stmts.length === 0) { + return; + } + if (this.isFirstThisBlock(block)) { + const succBlocks = block.getSuccessors(); + if (succBlocks.length > 0) { + this.blockProcess(block.getSuccessors()[0], curScope); + return; + } + } + let isSwitchBlock = false; + let nextScopeType = CheckerUtils.getScopeType(stmts[stmts.length - 1]); + curScope.blocks.add(block); + this.finishBlockSet.add(block); + for (let i = 0; i < stmts.length; i++) { + const stmt = stmts[i]; + if ((i === stmts.length - 1) && (this.isForStmtDefinedPart(stmts[stmts.length - 1], nextScopeType))) { + curScope = this.genChildScope(curScope, ScopeType.FOR_CONDITION_TYPE); + nextScopeType = ScopeType.UNKNOWN_TYPE; + } + if (!FixUtils.hasOwnProperty(stmt, 'scope')) { + Object.defineProperty(stmt, 'scope', { value: curScope }); + } + if (stmt instanceof ArkAssignStmt && !this.assignStmtProcess(stmt, curScope)) { + continue; + } else if (stmt instanceof ArkIfStmt) { + this.gFinishIfStmtLines.push(stmt.getOriginPositionInfo().getLineNo()); + if (/^.*\?.*:.*$/.test(stmt.getOriginalText() ?? '')) { + this.gTernaryConditionLines.add(stmt.getOriginPositionInfo().getLineNo()); + } + } + } + if (isSwitchBlock) { + this.switchBlockPreProcess(block, curScope); + } else { + this.nextBlockPreProcess(block, curScope, nextScopeType); + } + } + + private isFirstThisBlock(block: BasicBlock): boolean { + if (block.getPredecessors().length === 0) { + const stmts = block.getStmts(); + if (stmts.length === 1) { + if (stmts[0] instanceof ArkAssignStmt && + stmts[0].getRightOp() instanceof ArkThisRef) { + return true; + } + } + } + return false; + } + + private isForStmtDefinedPart(stmt: Stmt, nextScopeType: ScopeType): boolean { + if (stmt instanceof ArkAssignStmt && nextScopeType === ScopeType.FOR_CONDITION_TYPE && + !this.gFinishIfStmtLines.includes(stmt.getOriginPositionInfo().getLineNo())) { + return true; + } + return false; + } + + private genChildScope(curScope: Scope, scopeType: ScopeType): Scope { + let newScope = new Scope(curScope, new Array(), curScope.scopeLevel + 1, scopeType); + curScope.setChildScope(newScope); + return newScope; + } + + private assignStmtProcess(stmt: Stmt, curScope: Scope): boolean { + let def = stmt.getDef(); + if (def instanceof Local) { + if (def.getName() === 'this') { + return false; + } + const isForStmtThirdPart = (CheckerUtils.getScopeType(stmt) === ScopeType.FOR_CONDITION_TYPE && + this.gFinishIfStmtLines.includes(stmt.getOriginPositionInfo().getLineNo())); + if (CheckerUtils.wherIsTemp(stmt) === TempLocation.LEFT || + (!isForStmtThirdPart && CheckerUtils.isDeclaringStmt(def.getName(), stmt))) { + curScope.addVariable(new Variable(stmt)); + } else { + this.getDefAndSetRedef(def.getName(), curScope, curScope, stmt, SetDefMode.REDEF); + } + } else if (def instanceof ArkArrayRef) { + let base = def.getBase(); + if (base instanceof Local && !base.getName().includes('%')) { + this.getDefAndSetRedef(base.getName(), curScope, curScope, stmt, SetDefMode.LEFTUSED); + } + } + return true; + } + + private getDefAndSetRedef(name: string, searchScope: Scope, varScope: Scope, stmt: Stmt, mode: SetDefMode): boolean { + let defList = searchScope.defList; + for (let variable of defList) { + if (variable.getName() === name) { + if (mode === SetDefMode.REDEF) { + variable.redefInfo.add(new VarInfo(stmt, varScope)); + } else if (mode === SetDefMode.LEFTUSED) { + variable.leftUsedInfo.add(new VarInfo(stmt, varScope)); + } + } + } + if (searchScope.parentScope !== null) { + return this.getDefAndSetRedef(name, searchScope.parentScope, varScope, stmt, mode); + } + return false; + } + + private switchBlockPreProcess(block: BasicBlock, curScope: Scope): void { + const caseBlocks = block.getSuccessors(); + for (let caseBlock of caseBlocks) { + this.finishBlockSet.add(caseBlock); + } + for (let i = 0; i < caseBlocks.length; i++) { + if (i === caseBlocks.length - 1) { + this.isSwitchLastCase = true; + } + this.blockProcess(caseBlocks[i], this.genChildScope(curScope, ScopeType.CASE_TYPE)); + } + this.isSwitchLastCase = false; + } + + private nextBlockPreProcess(block: BasicBlock, curScope: Scope, nextScopeType: ScopeType): void { + const succBlocks = block.getSuccessors(); + const proedBlocks = block.getPredecessors(); + for (let i = 0; i < succBlocks.length; i++) { + if (this.finishBlockSet.has(succBlocks[i])) { + continue; + } + if (this.isTernaryCondition(succBlocks[i], proedBlocks)) { + this.blockProcess(succBlocks[i], curScope); + continue; + } + this.handleSuccessorBlock(succBlocks[i], curScope, nextScopeType, i); + } + } + + private handleSuccessorBlock(succBlock: BasicBlock, curScope: Scope, nextScopeType: ScopeType, index: number): void { + if (index === 0) { + if (this.isNeedCreateScope(nextScopeType)) { + const type = (nextScopeType === ScopeType.FOR_CONDITION_TYPE) ? ScopeType.FOR_IN_TYPE : nextScopeType; + this.blockProcess(succBlock, this.genChildScope(curScope, type)); + } else { + if (this.isSwitchLastCase) { + this.isSwitchLastCase = false; + curScope = curScope.parentScope ?? curScope; + } + this.blockProcess(succBlock, this.getReturnScope(succBlock, curScope)); + } + } else { + if (nextScopeType === ScopeType.FOR_CONDITION_TYPE) { + this.blockProcess(succBlock, this.getReturnScope(succBlock, curScope.parentScope ?? curScope)); + } else if (nextScopeType === ScopeType.WHILE_TYPE) { + this.blockProcess(succBlock, this.getReturnScope(succBlock, curScope)); + } else { + this.blockProcess(succBlock, this.genChildScope(curScope, ScopeType.ELSE_TYPE)); + } + } + } + + private isTernaryCondition(succBlock: BasicBlock, predBlocks: BasicBlock[]): boolean { + const succStmts = succBlock.getStmts(); + if (succStmts.length > 0 && this.gTernaryConditionLines.has(succStmts[0].getOriginPositionInfo().getLineNo())) { + return true; + } else if (predBlocks.length === 1 && this.gTernaryConditionLines.has(predBlocks?.[0].getStmts()?.at(-1)?.getOriginPositionInfo().getLineNo() ?? 0)) { + return true; + } else { + return false; + } + } + + private isNeedCreateScope(nextScopeType: ScopeType): boolean { + if (nextScopeType === ScopeType.IF_TYPE || + nextScopeType === ScopeType.FOR_CONDITION_TYPE || + nextScopeType === ScopeType.WHILE_TYPE) { + return true; + } + return false; + } + + private getReturnScope(succBlock: BasicBlock, curScope: Scope): Scope { + const stmts = succBlock.getStmts(); + if (stmts.length !== 0) { + const type = CheckerUtils.getScopeType(stmts[0]); + if ([ScopeType.WHILE_TYPE, ScopeType.FOR_CONDITION_TYPE].includes(type)) { + return curScope; + } + } else { + return curScope; + } + let returnScopeLevel = curScope.scopeLevel - (succBlock.getPredecessors().length - 1); + let exitNum = curScope.scopeLevel - returnScopeLevel; + while (exitNum) { + if (curScope.parentScope !== null) { + curScope = curScope.parentScope; + exitNum--; + } else { + logger.debug('CountExitScopeNum error!'); + break; + } + } + return curScope; + } +} + +enum SetDefMode { + REDEF = 0, + LEFTUSED +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/utils/common/Utils.ts b/ets2panda/linter/homecheck/src/utils/common/Utils.ts new file mode 100644 index 0000000000..555f05ec86 --- /dev/null +++ b/ets2panda/linter/homecheck/src/utils/common/Utils.ts @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import Logger, {LOG_LEVEL, LOG_MODULE_TYPE} from 'arkanalyzer/lib/utils/logger'; +import {Command, OptionValues} from 'commander'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'Utils'); + +export class Utils { + /** + * 解析命令行选项 + * @param args 命令行参数数组 + * @returns 解析后的选项值 + */ + static parseCliOptions(args: string[]): OptionValues { + logger.info('Parse cli options.'); + const program = new Command(); + return this.getCliOptions(program, args); + } + + /** + * 获取命令行选项 + * @param program Command 对象 + * @param args 命令行参数数组 + * @returns 选项值对象 + */ + static getCliOptions(program: Command, args: string[]): OptionValues { + program + .option('--configPath ', 'rule config path') + .option('--projectConfigPath ', 'project config path') + .option('--depGraphOutputDir ', 'output directory of dependency graph') + .parse(args); + return program.opts(); + } + + /** + * 设置日志路径 + * @param logPath 日志路径 + */ + static setLogPath(logPath: string) { + Logger.configure(logPath, LOG_LEVEL.INFO, LOG_LEVEL.INFO); + } + + /** + * 获取枚举类型的值 + * @param value - 枚举值,可以是字符串或数字 + * @param enumType - 枚举类型 + * @returns 枚举值对应的枚举类型值 + */ + static getEnumValues(value: string | number, enumType: any): any { + const key = Object.keys(enumType).find(k => k.toLowerCase() === value || enumType[k as string] === value); + return enumType[key as string] + } + + /** + * 按行号和列号对键值对进行排序 + * @param keyA 格式为 "行号%列号%规则ID" 的字符串 + * @param keyB 格式为 "行号%列号%规则ID" 的字符串 + * @returns 排序比较结果 + */ + public static sortByLineAndColumn(keyA: string, keyB: string): number { + const [lineA, colA] = keyA.split('%', 2).map(Number); + const [lineB, colB] = keyB.split('%', 2).map(Number); + if (lineA !== lineB) { + return lineA - lineB; + } + return colA - colB; + } +} diff --git a/ets2panda/linter/homecheck/tsconfig.json b/ets2panda/linter/homecheck/tsconfig.json new file mode 100644 index 0000000000..29c940a875 --- /dev/null +++ b/ets2panda/linter/homecheck/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.main.json", + "include": [ + "Index.ts", + "src/**/*" + ], + "compilerOptions": { + "outDir": "./out" + } +} diff --git a/ets2panda/linter/homecheck/tsconfig.main.json b/ets2panda/linter/homecheck/tsconfig.main.json new file mode 100644 index 0000000000..8aa61bd2c1 --- /dev/null +++ b/ets2panda/linter/homecheck/tsconfig.main.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig to read more about this file */ + + /* Language and Environment */ + "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + /* Modules */ + "module": "commonjs", /* Specify what module code is generated. */ + "declaration": true, + "declarationMap": false, + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + "strictPropertyInitialization": false, + "outDir": "dist", + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + "skipLibCheck": true, /* Skip type checking all .d.ts files. */ + } +} diff --git a/ets2panda/linter/homecheck/tsconfig.prod.json b/ets2panda/linter/homecheck/tsconfig.prod.json new file mode 100644 index 0000000000..4aa413773d --- /dev/null +++ b/ets2panda/linter/homecheck/tsconfig.prod.json @@ -0,0 +1,9 @@ +{ + "extends": "./tsconfig.main.json", + "include": [ + "src/**/*", + ], + "compilerOptions": { + "outDir": "./lib" + } +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/typedoc.json b/ets2panda/linter/homecheck/typedoc.json new file mode 100644 index 0000000000..23abcc61a9 --- /dev/null +++ b/ets2panda/linter/homecheck/typedoc.json @@ -0,0 +1,9 @@ +{ + "$schema": "https://typedoc.org/schema.json", + "name": "homecheck", + "entryPoints": [ + "./src/Index.ts" + ], + "out": "doc", + "readme": "./README.md" +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/vitest.config.ts b/ets2panda/linter/homecheck/vitest.config.ts new file mode 100644 index 0000000000..fe1725a625 --- /dev/null +++ b/ets2panda/linter/homecheck/vitest.config.ts @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import tsconfigPaths from 'vite-tsconfig-paths' +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + include: ['test/**/**.test.ts'], + }, + plugins: [ + tsconfigPaths() + ] +}) \ No newline at end of file diff --git a/ets2panda/linter/package.json b/ets2panda/linter/package.json index e93784e047..e56918d6e1 100644 --- a/ets2panda/linter/package.json +++ b/ets2panda/linter/package.json @@ -16,7 +16,8 @@ "compile": "npm run tsc", "postcompile": "node scripts/testRunner/post-compile.mjs", "build": "npm run clean && npm run compile && npm run webpack && npm run pack:linter", - "install-ohos-typescript": "node scripts/install-ohos-typescript.mjs", + "preinstall": "npm install --prefix arkanalyzer && npm install --prefix homecheck", + "install-ohos-typescript": "node scripts/install-ohos-typescript-and-homecheck.mjs", "pack:linter": "rimraf bundle && mkdir bundle && npm pack --pack-destination bundle", "pretest": " npm run fix", "test": "npm run test_all && npm run test_ts_import_ets", @@ -66,6 +67,7 @@ }, "bundleDependencies": [ "log4js", - "commander" + "commander", + "homecheck" ] } diff --git a/ets2panda/linter/scripts/install-ohos-typescript.mjs b/ets2panda/linter/scripts/install-ohos-typescript-and-homecheck.mjs similarity index 63% rename from ets2panda/linter/scripts/install-ohos-typescript.mjs rename to ets2panda/linter/scripts/install-ohos-typescript-and-homecheck.mjs index 74b60af557..0852d74006 100644 --- a/ets2panda/linter/scripts/install-ohos-typescript.mjs +++ b/ets2panda/linter/scripts/install-ohos-typescript-and-homecheck.mjs @@ -19,6 +19,7 @@ import { exit } from 'node:process' import { dirname } from 'path' import shell from 'shelljs' import { fileURLToPath } from 'url' +import path from 'node:path' // waitTime in ms function sleep(waitTime) { @@ -45,6 +46,32 @@ function detectOS() { return detectedOS } +function backupPackageJson(dirPath) { + const pkgPath = path.join(dirPath, 'package.json') + const backupName = `package.json.bak-${Date.now()}` + + if (!fs.existsSync(pkgPath)) { + console.error(`[ERROR] package.json not found in ${dirPath}`) + process.exit(1) + } + + fs.copyFileSync(pkgPath, path.join(dirPath, backupName)) + return backupName +} + +function restorePackageJson(dirPath, backupFile) { + const currentPkg = path.join(dirPath, 'package.json') + const backupPath = path.join(dirPath, backupFile) + + if (!fs.existsSync(backupPath)) { + console.error(`[ERROR] Backup file not found: ${backupPath}`) + process.exit(1) + } + + fs.rmSync(currentPkg, { force: true }) + fs.renameSync(backupPath, currentPkg) +} + function getTypescript(detectedOS) { const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); @@ -52,6 +79,8 @@ function getTypescript(detectedOS) { const linter = __dirname + '/..' const third_party = __dirname + '/../third_party' const typescript_dir = third_party + '/third_party_typescript' + const arkanalyzer = __dirname + '/../arkanalyzer' + const homecheck = __dirname + '/../homecheck' if (!fs.existsSync(third_party)) { fs.mkdirSync(third_party); @@ -103,15 +132,36 @@ function getTypescript(detectedOS) { exit(1) } - const npm_package = shell.exec('npm pack').stdout.trim() + const npm_typescript_package = shell.exec('npm pack').stdout.trim() + + shell.cd(arkanalyzer) + const arkanalyzerBackFile = backupPackageJson(arkanalyzer) + shell.exec(`npm install ${typescript_dir}/${npm_typescript_package}`) + shell.exec('npm run compile') + const npm_arkanalyzer_package = shell.exec('npm pack').stdout.trim() + restorePackageJson(arkanalyzer, arkanalyzerBackFile) + shell.rm('-rf', 'lib') + + shell.cd(homecheck) + const homecheckBackFile = backupPackageJson(homecheck) + + shell.exec(`npm install ${arkanalyzer}/${npm_arkanalyzer_package}`) + shell.exec(`npm install --no-save ${typescript_dir}/${npm_typescript_package}`) + shell.exec('npm run compile') + const npm_homecheck_package = shell.exec('npm pack').stdout.trim() + restorePackageJson(homecheck, homecheckBackFile) + shell.rm('-rf', 'lib') + shell.cd(linter) - shell.exec(`npm install --no-save ${typescript_dir}/${npm_package}`) + shell.exec(`npm install --no-save ${typescript_dir}/${npm_typescript_package} ${homecheck}/${npm_homecheck_package}`) const node_modules = linter + '/node_modules' fs.rmSync(node_modules + '/typescript', {recursive: true, force: true}) - shell.exec(`tar -xzf "${typescript_dir}/${npm_package}" -C node_modules --strip-components 1 --one-top-level=typescript`); - shell.rm(`${typescript_dir}/${npm_package}`) + shell.exec(`tar -xzf "${typescript_dir}/${npm_typescript_package}" -C node_modules --strip-components 1 --one-top-level=typescript`) + shell.rm(`${typescript_dir}/${npm_typescript_package}`) + shell.rm(`${arkanalyzer}/${npm_arkanalyzer_package}`) + shell.rm(`${homecheck}/${npm_homecheck_package}`) } const detectedOS = detectOS() diff --git a/ets2panda/linter/src/cli/CommandLineParser.ts b/ets2panda/linter/src/cli/CommandLineParser.ts index ae1471a6be..1c82cf92eb 100644 --- a/ets2panda/linter/src/cli/CommandLineParser.ts +++ b/ets2panda/linter/src/cli/CommandLineParser.ts @@ -144,6 +144,9 @@ function formCommandLineOptions(parsedCmd: ParsedCommand): CommandLineOptions { opts.linterOptions.migratorMode = options.migrate; opts.linterOptions.enableAutofix = true; } + if (options.homecheck) { + opts.homecheck = true; + } return formOptionPaths(opts, options); } @@ -174,6 +177,7 @@ function createCommand(): Command { option('--ide-interactive', 'Migration Helper IDE interactive mode'). option('-w, --arkts-whole-project-path ', 'path to whole project'). option('--migrate', 'run as ArkTS migrator'). + option('--homecheck', 'added homecheck rule validation'). addOption(new Option('--warnings-as-errors', 'treat warnings as errors').hideHelp(true)). addOption(new Option('--no-check-ts-as-source', 'check TS files as third-party libary').hideHelp(true)). addOption(new Option('--no-use-rt-logic', 'run linter with SDK logic').hideHelp(true)). diff --git a/ets2panda/linter/src/cli/LinterCLI.ts b/ets2panda/linter/src/cli/LinterCLI.ts index 8c5b72e75e..5738d48662 100644 --- a/ets2panda/linter/src/cli/LinterCLI.ts +++ b/ets2panda/linter/src/cli/LinterCLI.ts @@ -26,6 +26,9 @@ import { parseCommandLine } from './CommandLineParser'; import { compileLintOptions } from './Compiler'; import type { LinterConfig } from '../lib/LinterConfig'; import { arkts2Rules } from '../lib/utils/consts/ArkTS2Rules'; +import type { ProblemInfo as HomeCheckProblemInfo } from 'homecheck'; +import { MigrationTool } from 'homecheck'; +import { getHomeCheckConfigInfo } from '../lib/HomeCheck'; export function run(): void { const commandLineArgs = process.argv.slice(2); @@ -52,14 +55,38 @@ export function run(): void { async function runMigrationCliMode(cmdOptions: CommandLineOptions): Promise { const compileOptions = compileLintOptions(cmdOptions); const result = lint(compileOptions, getEtsLoaderPath(compileOptions)); + const mergedProblems = new Map(); + + if (cmdOptions.homecheck === true) { + const { ruleConfigInfo, projectConfigInfo } = getHomeCheckConfigInfo(cmdOptions); + const migrationTool = new MigrationTool(ruleConfigInfo, projectConfigInfo); + await migrationTool.buildCheckEntry(); + const homeCheckResult = await migrationTool.start(); + + for (const [filePath, problems] of homeCheckResult) { + if (!mergedProblems.has(filePath)) { + mergedProblems.set(filePath, []); + } + mergedProblems.get(filePath)!.push(...problems); + } + } + for (const [filePath, problems] of result.problemsInfos) { + if (!mergedProblems.has(filePath)) { + mergedProblems.set(filePath, []); + } + const filteredProblems = problems.filter((problem) => { return arkts2Rules.includes(problem.ruleTag); }); + mergedProblems.get(filePath)!.push(...filteredProblems); + } + + for (const [filePath, problems] of mergedProblems) { await processSyncOut( JSON.stringify({ filePath, - problems: filteredProblems + problems }) + '\n' ); } diff --git a/ets2panda/linter/src/lib/CommandLineOptions.ts b/ets2panda/linter/src/lib/CommandLineOptions.ts index 2cf9dd3baa..6468a28327 100644 --- a/ets2panda/linter/src/lib/CommandLineOptions.ts +++ b/ets2panda/linter/src/lib/CommandLineOptions.ts @@ -25,4 +25,5 @@ export interface CommandLineOptions { sdkDefaultApiPath?: string; sdkExternalApiPath?: string[]; arktsWholeProjectPath?: string; + homecheck?: boolean; } diff --git a/ets2panda/linter/src/lib/HomeCheck.ts b/ets2panda/linter/src/lib/HomeCheck.ts new file mode 100644 index 0000000000..1ebb9fbd7c --- /dev/null +++ b/ets2panda/linter/src/lib/HomeCheck.ts @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import type { CommandLineOptions } from './CommandLineOptions'; + +interface RuleConfigInfo { + ruleSet: string[]; +} + +interface ProjectConfigInfo { + projectName: string | undefined; + projectPath: string | undefined; + logPath: string; + arkCheckPath: string; + ohosSdkPath: string; + hmsSdkPath: string; + reportDir: string; + languageTags: Map; + fileOrFolderToCheck: string[]; +} + +export function getHomeCheckConfigInfo(cmdOptions: CommandLineOptions): { + ruleConfigInfo: RuleConfigInfo; + projectConfigInfo: ProjectConfigInfo; +} { + const languageTags = new Map(); + const inputFiles = cmdOptions.inputFiles; + inputFiles.forEach((file) => { + languageTags.set(file, 2); + }); + const ruleConfigInfo = { + ruleSet: ['plugin:@migration/all'] + }; + const projectConfigInfo = { + projectName: cmdOptions.arktsWholeProjectPath, + projectPath: cmdOptions.arktsWholeProjectPath, + logPath: './HomeCheck.log', + arkCheckPath: './node_modules/homecheck', + ohosSdkPath: cmdOptions.sdkDefaultApiPath ? cmdOptions.sdkDefaultApiPath : '', + hmsSdkPath: cmdOptions.sdkExternalApiPath ? cmdOptions.sdkExternalApiPath[0] : '', + reportDir: './', + languageTags: languageTags, + fileOrFolderToCheck: inputFiles + }; + return { ruleConfigInfo, projectConfigInfo }; +} diff --git a/ets2panda/linter/tsconfig.json b/ets2panda/linter/tsconfig.json index 2dece78605..8f1b726704 100644 --- a/ets2panda/linter/tsconfig.json +++ b/ets2panda/linter/tsconfig.json @@ -10,7 +10,9 @@ "sourceMap": true, "outDir": "build", "strict": true, - "resolveJsonModule": true + "resolveJsonModule": true, + "esModuleInterop": true, + "allowSyntheticDefaultImports": true }, "include": ["src/**/*"] -- Gitee From 818d59888f62fc82ed619e3dfa68c77e8b8384a5 Mon Sep 17 00:00:00 2001 From: c30058867 Date: Wed, 9 Apr 2025 01:10:08 +0800 Subject: [PATCH 057/268] arkts-sdk-optional-methods Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC0L18 Signed-off-by: caiy Change-Id: I695637b5431ff176d131dc1a8903eb793a9af22c --- ets2panda/linter/src/lib/CookBookMsg.ts | 3 +- ets2panda/linter/src/lib/FaultAttrs.ts | 1 + ets2panda/linter/src/lib/FaultDesc.ts | 2 +- ets2panda/linter/src/lib/Problems.ts | 1 + ets2panda/linter/src/lib/TypeScriptLinter.ts | 40 +++++++++- .../linter/src/lib/data/SdkWhitelist.json | 79 +++++++++++++++++++ .../src/lib/utils/consts/ArkTS2Rules.ts | 3 +- .../sdkwhite/OptionalMethod1.ets.args.json | 19 +++++ .../sdkwhite/OptionalMethod1.ets.arkts2.json | 41 +++++++++- .../limit_void_type_sdk2.ets.arkts2.json | 10 +++ 10 files changed, 191 insertions(+), 8 deletions(-) create mode 100644 ets2panda/linter/test/sdkwhite/OptionalMethod1.ets.args.json diff --git a/ets2panda/linter/src/lib/CookBookMsg.ts b/ets2panda/linter/src/lib/CookBookMsg.ts index 33dff6b05c..85fa589a04 100644 --- a/ets2panda/linter/src/lib/CookBookMsg.ts +++ b/ets2panda/linter/src/lib/CookBookMsg.ts @@ -16,7 +16,7 @@ export const cookBookMsg: string[] = []; export const cookBookTag: string[] = []; -for (let i = 0; i <= 308; i++) { +for (let i = 0; i <= 309; i++) { cookBookMsg[i] = ''; } @@ -277,3 +277,4 @@ cookBookTag[305] = 'Typescript class decorators are not allowed (arkts-interop-n cookBookTag[306] = 'Cannot access typescript types directly (arkts-interop-access-ts-types)'; cookBookTag[307] = 'Cannot invoke functions implemented in TypeScript (arkts-interop-ts-function)'; cookBookTag[308] = 'Type "void" has no instances.(arkts-sdk-limited-void-type)'; +cookBookTag[309] = 'API no longer supports optional methods (sdk-optional-methods)'; diff --git a/ets2panda/linter/src/lib/FaultAttrs.ts b/ets2panda/linter/src/lib/FaultAttrs.ts index e9d415f6b9..1fb1e8336b 100644 --- a/ets2panda/linter/src/lib/FaultAttrs.ts +++ b/ets2panda/linter/src/lib/FaultAttrs.ts @@ -189,3 +189,4 @@ faultsAttrs[FaultID.InteropNoDecorators] = new FaultAttributes(305); faultsAttrs[FaultID.InteropDirectAccessToTSTypes] = new FaultAttributes(306); faultsAttrs[FaultID.InteropTSFunctionInvoke] = new FaultAttributes(307); faultsAttrs[FaultID.LimitedVoidTypeFromSdk] = new FaultAttributes(308); +faultsAttrs[FaultID.OptionalMethodFromSdk] = new FaultAttributes(309); diff --git a/ets2panda/linter/src/lib/FaultDesc.ts b/ets2panda/linter/src/lib/FaultDesc.ts index 8c92fa9689..66c543f407 100644 --- a/ets2panda/linter/src/lib/FaultDesc.ts +++ b/ets2panda/linter/src/lib/FaultDesc.ts @@ -177,4 +177,4 @@ faultDesc[FaultID.InteropTSFunctionInvoke] = 'TS Function Invoke'; faultDesc[FaultID.LimitedVoidTypeFromSdk] = 'Limited void type from sdk'; faultDesc[FaultID.EntryAnnotation] = '"@Entry" decorator parameter'; faultDesc[FaultID.ProvideAnnotation] = '"@Provide" decorator parameter'; - +faultDesc[FaultID.OptionalMethodFromSdk] = 'Optional method from sdk'; diff --git a/ets2panda/linter/src/lib/Problems.ts b/ets2panda/linter/src/lib/Problems.ts index 459e9d2a6c..d859be0203 100644 --- a/ets2panda/linter/src/lib/Problems.ts +++ b/ets2panda/linter/src/lib/Problems.ts @@ -178,6 +178,7 @@ export enum FaultID { LimitedVoidTypeFromSdk, EntryAnnotation, ProvideAnnotation, + OptionalMethodFromSdk, // this should always be last enum LAST_ID } diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index 233a77b40d..c1cdd9f87a 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -1864,6 +1864,27 @@ export class TypeScriptLinter { this.handleLimitedVoidType(tsVarDecl); this.handleInvalidIdentifier(tsVarDecl); this.checkAssignmentNumericSemanticsly(tsVarDecl); + this.checkTypeFromSdk(tsVarDecl.type); + } + + private checkTypeFromSdk(type: ts.TypeNode | undefined): void { + if (!this.options.arkts2 || !type) { + return; + } + + const fullTypeName = type.getText(); + const nameArr = fullTypeName.split('.'); + const sdkInfos = this.interfaceMap.get(nameArr[0]); + if (!sdkInfos || sdkInfos.size === 0) { + return; + } + + for (const sdkInfo of sdkInfos) { + if (nameArr.includes(sdkInfo.api_name)) { + this.incrementCounters(type, FaultID.LimitedVoidTypeFromSdk); + return; + } + } } private handleDeclarationDestructuring(decl: ts.VariableDeclaration | ts.ParameterDeclaration): void { @@ -2094,9 +2115,13 @@ export class TypeScriptLinter { } const memberName = member.name?.getText(); - if (sdkInfo.api_name === memberName && sdkInfo.api_func_args.length === member.parameters.length) { + + if (sdkInfo.api_name === memberName) { if (TypeScriptLinter.areParametersEqual(sdkInfo.api_func_args, member.parameters)) { - this.incrementCounters(member, FaultID.LimitedVoidTypeFromSdk); + this.incrementCounters( + member, + sdkInfo.problem === 'OptionalMethod' ? FaultID.OptionalMethodFromSdk : FaultID.LimitedVoidTypeFromSdk + ); } } } @@ -2106,8 +2131,15 @@ export class TypeScriptLinter { sdkFuncArgs: { name: string; type: string }[], memberParams: ts.NodeArray ): boolean { - for (let i = 0; i < sdkFuncArgs.length; i++) { - if (sdkFuncArgs[i].type !== memberParams[i].type?.getText()) { + const apiParamCout = sdkFuncArgs.length; + const memberParamCout = memberParams.length; + if (apiParamCout > memberParamCout && sdkFuncArgs[memberParamCout + 1]) { + return false; + } + + for (let i = 0; i < apiParamCout; i++) { + const typeName = memberParams[i].type?.getText(); + if (!typeName?.match(sdkFuncArgs[i].type)) { return false; } } diff --git a/ets2panda/linter/src/lib/data/SdkWhitelist.json b/ets2panda/linter/src/lib/data/SdkWhitelist.json index 6ad29180ae..83d9fd552e 100644 --- a/ets2panda/linter/src/lib/data/SdkWhitelist.json +++ b/ets2panda/linter/src/lib/data/SdkWhitelist.json @@ -49,6 +49,85 @@ "methd_return_type": "void | Promise", "codeKind": 115 } + }, + { + "import_path": ["@hms.collaboration.rcp", "@kit.RemoteCommunicationKit"], + "file_path": ["api/@hms.collaboration.rcp.d.ts"], + "is_global": false, + "api_info": { + "problem": "LimitiedVoidType", + "api_name": "IncomingDataCallback", + "api_type": "TypeAliasDeclaration", + "api_optional": false, + "api_auto_fix": false, + "api_auto_fix_context": "", + "target_type": "", + "api_func_args": [{ "name": "incomingData", "type": "ArrayBuffer", "is_optional": false, "hasDefault": false }], + "parent_api": [ + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "methd_return_type": "void | Promise", + "codeKind": 115 + } + }, + { + "import_path": ["@ohos.web.webview", "@kit.ArkWeb"], + "file_path": ["api/@ohos.web.webview.d.ts"], + "is_global": false, + "api_info": { + "problem": "OptionalMethod", + "api_name": "resumePlayer", + "api_type": "MethodSignature", + "api_optional": true, + "api_auto_fix": false, + "api_auto_fix_context": "", + "target_type": "", + "api_func_args": [], + "parent_api": [ + { + "api_name": "NativeMediaPlayerBridge", + "api_type": "InterfaceDeclaration" + }, + { + "api_name": "webview", + "api_type": "ModuleDeclaration" + } + ], + "methd_return_type": "void", + "codeKind": 173 + } + }, + { + "import_path": ["@ohos.web.webview", "@kit.ArkWeb"], + "file_path": ["api/@ohos.web.webview.d.ts"], + "is_global": false, + "api_info": { + "problem": "OptionalMethod", + "api_name": "suspendPlayer", + "api_type": "MethodSignature", + "api_optional": true, + "api_auto_fix": false, + "api_auto_fix_context": "", + "target_type": "", + "api_func_args": [ + { "name": "type", "type": "SuspendType", "is_optional": false, "hasDefault": false } + ], + "parent_api": [ + { + "api_name": "NativeMediaPlayerBridge", + "api_type": "InterfaceDeclaration" + }, + { + "api_name": "webview", + "api_type": "ModuleDeclaration" + } + ], + "methd_return_type": "void", + "codeKind": 173 + } } ] } diff --git a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts index 7d2be8a961..faa4bf2919 100644 --- a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts +++ b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts @@ -69,5 +69,6 @@ export const arkts2Rules: number[] = [ 305, 306, 307, - 308 + 308, + 309 ]; diff --git a/ets2panda/linter/test/sdkwhite/OptionalMethod1.ets.args.json b/ets2panda/linter/test/sdkwhite/OptionalMethod1.ets.args.json new file mode 100644 index 0000000000..948b846fe0 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/OptionalMethod1.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} diff --git a/ets2panda/linter/test/sdkwhite/OptionalMethod1.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/OptionalMethod1.ets.arkts2.json index 5e75d5b3e7..d7b0f6777b 100644 --- a/ets2panda/linter/test/sdkwhite/OptionalMethod1.ets.arkts2.json +++ b/ets2panda/linter/test/sdkwhite/OptionalMethod1.ets.arkts2.json @@ -14,6 +14,45 @@ "limitations under the License." ], "result": [ - + { + "line": 59, + "column": 3, + "endLine": 61, + "endColumn": 4, + "problem": "OptionalMethodFromSdk", + "suggest": "", + "rule": "API no longer supports optional methods (sdk-optional-methods)", + "severity": "ERROR" + }, + { + "line": 63, + "column": 3, + "endLine": 65, + "endColumn": 4, + "problem": "OptionalMethodFromSdk", + "suggest": "", + "rule": "API no longer supports optional methods (sdk-optional-methods)", + "severity": "ERROR" + }, + { + "line": 59, + "column": 15, + "endLine": 59, + "endColumn": 16, + "problem": "OptionalMethod", + "suggest": "", + "rule": "Optional methods are not supported (arkts-optional-methods)", + "severity": "ERROR" + }, + { + "line": 63, + "column": 16, + "endLine": 63, + "endColumn": 17, + "problem": "OptionalMethod", + "suggest": "", + "rule": "Optional methods are not supported (arkts-optional-methods)", + "severity": "ERROR" + } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/limit_void_type_sdk2.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk2.ets.arkts2.json index 07e4765956..bd91b2508b 100644 --- a/ets2panda/linter/test/sdkwhite/limit_void_type_sdk2.ets.arkts2.json +++ b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk2.ets.arkts2.json @@ -34,6 +34,16 @@ "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", "severity": "ERROR" }, + { + "line": 23, + "column": 10, + "endLine": 23, + "endColumn": 34, + "problem": "LimitedVoidTypeFromSdk", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-sdk-limited-void-type)", + "severity": "ERROR" + }, { "line": 23, "column": 38, -- Gitee From b109a7940e0f9457e1577e157808e949767ab1e5 Mon Sep 17 00:00:00 2001 From: chenhantao Date: Fri, 11 Apr 2025 20:06:10 +0800 Subject: [PATCH 058/268] Add sendable sdk Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC0L18 Signed-off-by: chenhantao Change-Id: I9b8280c5f37d383315a3b6d913fd1103cae0e255 --- ets2panda/linter/src/lib/CookBookMsg.ts | 4 +- ets2panda/linter/src/lib/FaultAttrs.ts | 1 + ets2panda/linter/src/lib/FaultDesc.ts | 2 + ets2panda/linter/src/lib/Problems.ts | 1 + ets2panda/linter/src/lib/TypeScriptLinter.ts | 18 +++ .../linter/src/lib/data/SdkWhitelist.json | 142 ++++++++++++++++++ .../sendable_class_interface_property_sdk.ets | 17 +++ ...class_interface_property_sdk.ets.args.json | 19 +++ ...ass_interface_property_sdk.ets.arkts2.json | 28 ++++ ...able_class_interface_property_sdk.ets.json | 17 +++ 10 files changed, 248 insertions(+), 1 deletion(-) create mode 100644 ets2panda/linter/test/main/sendable_class_interface_property_sdk.ets create mode 100644 ets2panda/linter/test/main/sendable_class_interface_property_sdk.ets.args.json create mode 100644 ets2panda/linter/test/main/sendable_class_interface_property_sdk.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/sendable_class_interface_property_sdk.ets.json diff --git a/ets2panda/linter/src/lib/CookBookMsg.ts b/ets2panda/linter/src/lib/CookBookMsg.ts index 85fa589a04..d45569f6fb 100644 --- a/ets2panda/linter/src/lib/CookBookMsg.ts +++ b/ets2panda/linter/src/lib/CookBookMsg.ts @@ -16,7 +16,7 @@ export const cookBookMsg: string[] = []; export const cookBookTag: string[] = []; -for (let i = 0; i <= 309; i++) { +for (let i = 0; i <= 312; i++) { cookBookMsg[i] = ''; } @@ -278,3 +278,5 @@ cookBookTag[306] = 'Cannot access typescript types directly (arkts-interop-acces cookBookTag[307] = 'Cannot invoke functions implemented in TypeScript (arkts-interop-ts-function)'; cookBookTag[308] = 'Type "void" has no instances.(arkts-sdk-limited-void-type)'; cookBookTag[309] = 'API no longer supports optional methods (sdk-optional-methods)'; +cookBookTag[312] = + 'Properties in "Sendable" classes and interfaces must have a Sendable data type (sdk-no-sendable-prop-types)'; diff --git a/ets2panda/linter/src/lib/FaultAttrs.ts b/ets2panda/linter/src/lib/FaultAttrs.ts index 1fb1e8336b..5c93836565 100644 --- a/ets2panda/linter/src/lib/FaultAttrs.ts +++ b/ets2panda/linter/src/lib/FaultAttrs.ts @@ -190,3 +190,4 @@ faultsAttrs[FaultID.InteropDirectAccessToTSTypes] = new FaultAttributes(306); faultsAttrs[FaultID.InteropTSFunctionInvoke] = new FaultAttributes(307); faultsAttrs[FaultID.LimitedVoidTypeFromSdk] = new FaultAttributes(308); faultsAttrs[FaultID.OptionalMethodFromSdk] = new FaultAttributes(309); +faultsAttrs[FaultID.SendablePropTypeFromSdk] = new FaultAttributes(312); diff --git a/ets2panda/linter/src/lib/FaultDesc.ts b/ets2panda/linter/src/lib/FaultDesc.ts index 66c543f407..dfcb9a498b 100644 --- a/ets2panda/linter/src/lib/FaultDesc.ts +++ b/ets2panda/linter/src/lib/FaultDesc.ts @@ -178,3 +178,5 @@ faultDesc[FaultID.LimitedVoidTypeFromSdk] = 'Limited void type from sdk'; faultDesc[FaultID.EntryAnnotation] = '"@Entry" decorator parameter'; faultDesc[FaultID.ProvideAnnotation] = '"@Provide" decorator parameter'; faultDesc[FaultID.OptionalMethodFromSdk] = 'Optional method from sdk'; +faultDesc[FaultID.SendablePropTypeFromSdk] = 'ISendable is no longer supported'; + diff --git a/ets2panda/linter/src/lib/Problems.ts b/ets2panda/linter/src/lib/Problems.ts index d859be0203..3f75ecf0e7 100644 --- a/ets2panda/linter/src/lib/Problems.ts +++ b/ets2panda/linter/src/lib/Problems.ts @@ -179,6 +179,7 @@ export enum FaultID { EntryAnnotation, ProvideAnnotation, OptionalMethodFromSdk, + SendablePropTypeFromSdk, // this should always be last enum LAST_ID } diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index c1cdd9f87a..95846e684f 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -823,6 +823,8 @@ export class TypeScriptLinter { if (importDeclNode.assertClause) { this.incrementCounters(importDeclNode.assertClause, FaultID.ImportAssertion); } + const stringLiteral = expr as ts.StringLiteral; + this.handleSdkSendable(stringLiteral); } // handle no side effect import in sendable module @@ -831,6 +833,22 @@ export class TypeScriptLinter { this.checkWorkerImport(importDeclNode); } + private handleSdkSendable(tsStringLiteral: ts.StringLiteral): void { + if (!this.options.arkts2) { + return; + } + + const moduleSpecifierValue = tsStringLiteral.getText(); + const sdkInfos = TypeScriptLinter.pathMap.get(moduleSpecifierValue); + + if (!sdkInfos || sdkInfos.size === 0) { + return; + } + if (moduleSpecifierValue.includes('sendable')) { + this.incrementCounters(tsStringLiteral, FaultID.SendablePropTypeFromSdk); + } + } + private handleImportModule(importDeclNode: ts.ImportDeclaration): void { if (!this.options.arkts2) { return; diff --git a/ets2panda/linter/src/lib/data/SdkWhitelist.json b/ets2panda/linter/src/lib/data/SdkWhitelist.json index 83d9fd552e..be5b45ef24 100644 --- a/ets2panda/linter/src/lib/data/SdkWhitelist.json +++ b/ets2panda/linter/src/lib/data/SdkWhitelist.json @@ -128,6 +128,148 @@ "methd_return_type": "void", "codeKind": 173 } + }, + { + "import_path": ["@ohos.file.sendablePhotoAccessHelper", "@kit.MediaLibraryKit"], + "file_path": ["api/@ohos.file.sendablePhotoAccessHelper.d.ets"], + "is_global": false, + "api_info": { + "problem": "SendablePropType", + "api_name": "position", + "api_type": "PropertySignatrue", + "api_optional": false, + "api_auto_fix": false, + "api_auto_fix_context": "", + "target_type": "", + "api_func_args": [], + "parent_api": [ + { + "api_name": "SharedPhotoAsset", + "api_type": "InterfaceDeclaration" + }, + { + "api_name": "sendablePhotoAccessHelper", + "api_type": "ModuleDeclaration" + } + ], + "methd_return_type": "", + "codeKind": 170 + } + }, + { + "import_path": [], + "file_path": ["component/progress.d.ts"], + "is_global": true, + "api_info": { + "problem": "ComputedPropertyName", + "api_name": "[ProgressType.Linear]", + "api_type": "PropertySignatrue", + "api_optional": false, + "api_auto_fix": false, + "api_auto_fix_context": "", + "target_type": "", + "api_func_args": [], + "parent_api": [ + { + "api_name": "ProgressStyleMap", + "api_type": "InterfaceDeclaration" + } + ], + "methd_return_type": "", + "codeKind": 170 + } + }, + { + "import_path": [], + "file_path": ["component/progress.d.ts"], + "is_global": true, + "api_info": { + "problem": "ComputedPropertyName", + "api_name": "[ProgressType.Ring]", + "api_type": "PropertySignatrue", + "api_optional": false, + "api_auto_fix": false, + "api_auto_fix_context": "", + "target_type": "", + "api_func_args": [], + "parent_api": [ + { + "api_name": "ProgressStyleMap", + "api_type": "InterfaceDeclaration" + } + ], + "methd_return_type": "", + "codeKind": 170 + } + }, + { + "import_path": [], + "file_path": ["component/progress.d.ts"], + "is_global": true, + "api_info": { + "problem": "ComputedPropertyName", + "api_name": "[ProgressType.Eclipse]", + "api_type": "PropertySignatrue", + "api_optional": false, + "api_auto_fix": false, + "api_auto_fix_context": "", + "target_type": "", + "api_func_args": [], + "parent_api": [ + { + "api_name": "ProgressStyleMap", + "api_type": "InterfaceDeclaration" + } + ], + "methd_return_type": "", + "codeKind": 170 + } + }, + { + "import_path": [], + "file_path": ["component/progress.d.ts"], + "is_global": true, + "api_info": { + "problem": "ComputedPropertyName", + "api_name": "[ProgressType.ScaleRing]", + "api_type": "PropertySignatrue", + "api_optional": false, + "api_auto_fix": false, + "api_auto_fix_context": "", + "target_type": "", + "api_func_args": [], + "parent_api": [ + { + "api_name": "ProgressStyleMap", + "api_type": "InterfaceDeclaration" + } + ], + "methd_return_type": "", + "codeKind": 170 + } + }, + { + "import_path": [], + "file_path": ["component/progress.d.ts"], + "is_global": true, + "api_info": { + "problem": "ComputedPropertyName", + "api_name": "[ProgressType.Capsule]", + "api_type": "PropertySignatrue", + "api_optional": false, + "api_auto_fix": false, + "api_auto_fix_context": "", + "target_type": "", + "api_func_args": [], + "parent_api": [ + { + "api_name": "ProgressStyleMap", + "api_type": "InterfaceDeclaration" + } + ], + "methd_return_type": "", + "codeKind": 170 + } } ] } diff --git a/ets2panda/linter/test/main/sendable_class_interface_property_sdk.ets b/ets2panda/linter/test/main/sendable_class_interface_property_sdk.ets new file mode 100644 index 0000000000..3b39666b33 --- /dev/null +++ b/ets2panda/linter/test/main/sendable_class_interface_property_sdk.ets @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { SharedPhotoAsset } from '@ohos.file.sendablePhotoAccessHelper'; +import { SharedPhotoAsset } from '@ohos.file.photoAccessHelper'; diff --git a/ets2panda/linter/test/main/sendable_class_interface_property_sdk.ets.args.json b/ets2panda/linter/test/main/sendable_class_interface_property_sdk.ets.args.json new file mode 100644 index 0000000000..d8d3390ad9 --- /dev/null +++ b/ets2panda/linter/test/main/sendable_class_interface_property_sdk.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/sendable_class_interface_property_sdk.ets.arkts2.json b/ets2panda/linter/test/main/sendable_class_interface_property_sdk.ets.arkts2.json new file mode 100644 index 0000000000..824e83e4a1 --- /dev/null +++ b/ets2panda/linter/test/main/sendable_class_interface_property_sdk.ets.arkts2.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 34, + "endLine": 16, + "endColumn": 72, + "problem": "SendablePropTypeFromSdk", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (sdk-no-sendable-prop-types)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/sendable_class_interface_property_sdk.ets.json b/ets2panda/linter/test/main/sendable_class_interface_property_sdk.ets.json new file mode 100644 index 0000000000..9f305c86d7 --- /dev/null +++ b/ets2panda/linter/test/main/sendable_class_interface_property_sdk.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} -- Gitee From 44ed9250c65eea53150b2b529a039f1acf8f8275 Mon Sep 17 00:00:00 2001 From: lizhonghan Date: Wed, 9 Apr 2025 10:55:23 +0800 Subject: [PATCH 059/268] Add sdk-no-ctor-signatures-iface Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC0L18 Change-Id: Ibd1ea56ee759fee88323105220d18ccc67c3659b Signed-off-by: lizhonghan --- ets2panda/linter/src/lib/CookBookMsg.ts | 1 + ets2panda/linter/src/lib/FaultAttrs.ts | 1 + ets2panda/linter/src/lib/FaultDesc.ts | 2 +- ets2panda/linter/src/lib/Problems.ts | 1 + ets2panda/linter/src/lib/TypeScriptLinter.ts | 25 ++++++++++++++++ .../linter/src/lib/data/SdkWhitelist.json | 30 +++++++++++++++++++ .../sdkwhite/ConstructorIface4.ets.args.json | 19 ++++++++++++ .../ConstructorIface4.ets.arkts2.json | 11 ++++++- 8 files changed, 88 insertions(+), 2 deletions(-) create mode 100644 ets2panda/linter/test/sdkwhite/ConstructorIface4.ets.args.json diff --git a/ets2panda/linter/src/lib/CookBookMsg.ts b/ets2panda/linter/src/lib/CookBookMsg.ts index d45569f6fb..35fe90e311 100644 --- a/ets2panda/linter/src/lib/CookBookMsg.ts +++ b/ets2panda/linter/src/lib/CookBookMsg.ts @@ -280,3 +280,4 @@ cookBookTag[308] = 'Type "void" has no instances.(arkts-sdk-limited-void-type)'; cookBookTag[309] = 'API no longer supports optional methods (sdk-optional-methods)'; cookBookTag[312] = 'Properties in "Sendable" classes and interfaces must have a Sendable data type (sdk-no-sendable-prop-types)'; +cookBookTag[313] = 'Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)'; diff --git a/ets2panda/linter/src/lib/FaultAttrs.ts b/ets2panda/linter/src/lib/FaultAttrs.ts index 5c93836565..b111b1be7a 100644 --- a/ets2panda/linter/src/lib/FaultAttrs.ts +++ b/ets2panda/linter/src/lib/FaultAttrs.ts @@ -191,3 +191,4 @@ faultsAttrs[FaultID.InteropTSFunctionInvoke] = new FaultAttributes(307); faultsAttrs[FaultID.LimitedVoidTypeFromSdk] = new FaultAttributes(308); faultsAttrs[FaultID.OptionalMethodFromSdk] = new FaultAttributes(309); faultsAttrs[FaultID.SendablePropTypeFromSdk] = new FaultAttributes(312); +faultsAttrs[FaultID.ConstructorIfaceFromSdk] = new FaultAttributes(313); diff --git a/ets2panda/linter/src/lib/FaultDesc.ts b/ets2panda/linter/src/lib/FaultDesc.ts index dfcb9a498b..17425377ac 100644 --- a/ets2panda/linter/src/lib/FaultDesc.ts +++ b/ets2panda/linter/src/lib/FaultDesc.ts @@ -179,4 +179,4 @@ faultDesc[FaultID.EntryAnnotation] = '"@Entry" decorator parameter'; faultDesc[FaultID.ProvideAnnotation] = '"@Provide" decorator parameter'; faultDesc[FaultID.OptionalMethodFromSdk] = 'Optional method from sdk'; faultDesc[FaultID.SendablePropTypeFromSdk] = 'ISendable is no longer supported'; - +faultDesc[FaultID.ConstructorIfaceFromSdk] = 'Construct signatures are not supported in interfaces from sdk'; diff --git a/ets2panda/linter/src/lib/Problems.ts b/ets2panda/linter/src/lib/Problems.ts index 3f75ecf0e7..60958041b2 100644 --- a/ets2panda/linter/src/lib/Problems.ts +++ b/ets2panda/linter/src/lib/Problems.ts @@ -180,6 +180,7 @@ export enum FaultID { ProvideAnnotation, OptionalMethodFromSdk, SendablePropTypeFromSdk, + ConstructorIfaceFromSdk, // this should always be last enum LAST_ID } diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index 95846e684f..7e9fd45a72 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -3493,9 +3493,34 @@ export class TypeScriptLinter { } } + private handleSdkConstructorIface(typeRef: ts.TypeReferenceNode): void { + if (!this.options.arkts2 && typeRef?.typeName === undefined && !ts.isQualifiedName(typeRef.typeName)) { + return; + } + const qualifiedName = typeRef.typeName as ts.QualifiedName; + // tsc version diff + const topName = qualifiedName.left?.getText(); + const sdkInfos = this.interfaceMap.get(topName); + if (!sdkInfos) { + return; + } + for (const sdkInfo of sdkInfos) { + if (sdkInfo.api_type !== 'ConstructSignature') { + continue; + } + // sdk api from json has 3 overload. need consider these case. + if (sdkInfo.parent_api[0].api_name === qualifiedName.right.getText()) { + this.incrementCounters(typeRef, FaultID.ConstructorIfaceFromSdk); + break; + } + } + } + private handleTypeReference(node: ts.Node): void { const typeRef = node as ts.TypeReferenceNode; + this.handleSdkConstructorIface(typeRef); + const isESObject = TsUtils.isEsObjectType(typeRef); const isPossiblyValidContext = TsUtils.isEsObjectPossiblyAllowed(typeRef); if (isESObject && !isPossiblyValidContext) { diff --git a/ets2panda/linter/src/lib/data/SdkWhitelist.json b/ets2panda/linter/src/lib/data/SdkWhitelist.json index be5b45ef24..70ca1b4308 100644 --- a/ets2panda/linter/src/lib/data/SdkWhitelist.json +++ b/ets2panda/linter/src/lib/data/SdkWhitelist.json @@ -270,6 +270,36 @@ "methd_return_type": "", "codeKind": 170 } + }, + { + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "file_path": ["api/@hms.collaboration.rcp.d.ts"], + "is_global": false, + "api_info": { + "problem": "ConstructorIface", + "api_name": "", + "api_type": "ConstructSignature", + "api_optional": false, + "api_auto_fix": false, + "api_auto_fix_context": "", + "target_type": "", + "api_func_args": [], + "parent_api": [ + { + "api_name": "NetworkOutputQueueConstructor", + "api_type": "InterfaceDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "methd_return_type": "INetworkOutputQueue", + "codeKind": 180 + } } ] } diff --git a/ets2panda/linter/test/sdkwhite/ConstructorIface4.ets.args.json b/ets2panda/linter/test/sdkwhite/ConstructorIface4.ets.args.json new file mode 100644 index 0000000000..3ef4496a81 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/ConstructorIface4.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} diff --git a/ets2panda/linter/test/sdkwhite/ConstructorIface4.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/ConstructorIface4.ets.arkts2.json index 5e75d5b3e7..aef924b6e9 100644 --- a/ets2panda/linter/test/sdkwhite/ConstructorIface4.ets.arkts2.json +++ b/ets2panda/linter/test/sdkwhite/ConstructorIface4.ets.arkts2.json @@ -14,6 +14,15 @@ "limitations under the License." ], "result": [ - + { + "line": 19, + "column": 40, + "endLine": 19, + "endColumn": 73, + "problem": "ConstructorIfaceFromSdk", + "suggest": "", + "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", + "severity": "ERROR" + } ] } \ No newline at end of file -- Gitee From eeb551abd35458e9e6b24ff00145c36c36364fe6 Mon Sep 17 00:00:00 2001 From: lizhonghan Date: Wed, 9 Apr 2025 17:02:30 +0800 Subject: [PATCH 060/268] Add sdk-no-props-by-index Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC0L18 Change-Id: I8c7723b64446ed8ab8236d14d99d5814f8db2572 Signed-off-by: lizhonghan --- ets2panda/linter/src/lib/CookBookMsg.ts | 3 +- ets2panda/linter/src/lib/FaultAttrs.ts | 1 + ets2panda/linter/src/lib/FaultDesc.ts | 1 + ets2panda/linter/src/lib/Problems.ts | 1 + ets2panda/linter/src/lib/TypeScriptLinter.ts | 49 +++++++++++++- .../linter/src/lib/data/SdkWhitelist.json | 66 +++++++++++++++++++ .../lib/utils/consts/WhiteListProblemType.ts | 29 ++++++++ .../test/sdkwhite/IndexedAccessType.ets | 38 +++++++++-- .../sdkwhite/IndexedAccessType.ets.args.json | 19 ++++++ .../IndexedAccessType.ets.arkts2.json | 41 +++++++++++- .../test/sdkwhite/IndexedAccessType.ets.json | 33 +++++++++- .../sdkwhite/sdk/@kit.AccessibilityKit.d.ts | 25 +++++++ .../AccessibilityExtensionContext.d.ts | 30 +++++++++ 13 files changed, 326 insertions(+), 10 deletions(-) create mode 100644 ets2panda/linter/src/lib/utils/consts/WhiteListProblemType.ts create mode 100644 ets2panda/linter/test/sdkwhite/IndexedAccessType.ets.args.json create mode 100644 ets2panda/linter/test/sdkwhite/sdk/@kit.AccessibilityKit.d.ts create mode 100644 ets2panda/linter/test/sdkwhite/sdk/api/application/AccessibilityExtensionContext.d.ts diff --git a/ets2panda/linter/src/lib/CookBookMsg.ts b/ets2panda/linter/src/lib/CookBookMsg.ts index 35fe90e311..5eedac09cc 100644 --- a/ets2panda/linter/src/lib/CookBookMsg.ts +++ b/ets2panda/linter/src/lib/CookBookMsg.ts @@ -16,7 +16,7 @@ export const cookBookMsg: string[] = []; export const cookBookTag: string[] = []; -for (let i = 0; i <= 312; i++) { +for (let i = 0; i <= 314; i++) { cookBookMsg[i] = ''; } @@ -281,3 +281,4 @@ cookBookTag[309] = 'API no longer supports optional methods (sdk-optional-method cookBookTag[312] = 'Properties in "Sendable" classes and interfaces must have a Sendable data type (sdk-no-sendable-prop-types)'; cookBookTag[313] = 'Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)'; +cookBookTag[314] = 'Indexed access is not supported for fields (sdk-no-props-by-index)'; diff --git a/ets2panda/linter/src/lib/FaultAttrs.ts b/ets2panda/linter/src/lib/FaultAttrs.ts index b111b1be7a..e1f163bca8 100644 --- a/ets2panda/linter/src/lib/FaultAttrs.ts +++ b/ets2panda/linter/src/lib/FaultAttrs.ts @@ -192,3 +192,4 @@ faultsAttrs[FaultID.LimitedVoidTypeFromSdk] = new FaultAttributes(308); faultsAttrs[FaultID.OptionalMethodFromSdk] = new FaultAttributes(309); faultsAttrs[FaultID.SendablePropTypeFromSdk] = new FaultAttributes(312); faultsAttrs[FaultID.ConstructorIfaceFromSdk] = new FaultAttributes(313); +faultsAttrs[FaultID.PropertyAccessByIndexFromSdk] = new FaultAttributes(314); diff --git a/ets2panda/linter/src/lib/FaultDesc.ts b/ets2panda/linter/src/lib/FaultDesc.ts index 17425377ac..16b0823294 100644 --- a/ets2panda/linter/src/lib/FaultDesc.ts +++ b/ets2panda/linter/src/lib/FaultDesc.ts @@ -180,3 +180,4 @@ faultDesc[FaultID.ProvideAnnotation] = '"@Provide" decorator parameter'; faultDesc[FaultID.OptionalMethodFromSdk] = 'Optional method from sdk'; faultDesc[FaultID.SendablePropTypeFromSdk] = 'ISendable is no longer supported'; faultDesc[FaultID.ConstructorIfaceFromSdk] = 'Construct signatures are not supported in interfaces from sdk'; +faultDesc[FaultID.PropertyAccessByIndexFromSdk] = 'property access by index from sdk'; diff --git a/ets2panda/linter/src/lib/Problems.ts b/ets2panda/linter/src/lib/Problems.ts index 60958041b2..903e4e6a41 100644 --- a/ets2panda/linter/src/lib/Problems.ts +++ b/ets2panda/linter/src/lib/Problems.ts @@ -181,6 +181,7 @@ export enum FaultID { OptionalMethodFromSdk, SendablePropTypeFromSdk, ConstructorIfaceFromSdk, + PropertyAccessByIndexFromSdk, // this should always be last enum LAST_ID } diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index 7e9fd45a72..f00a45d730 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -92,9 +92,10 @@ import { arkuiImportList } from './utils/consts/ArkuiImportList'; import { REFLECT_PROPERTIES, USE_STATIC } from './utils/consts/InteropAPI'; import { EXTNAME_TS, EXTNAME_D_TS } from './utils/consts/ExtensionName'; import { ARKTS_IGNORE_DIRS_OH_MODULES } from './utils/consts/ArktsIgnorePaths'; -import type { ApiInfo } from './utils/consts/SdkWhitelist'; +import type { ApiInfo, ApiListItem } from './utils/consts/SdkWhitelist'; import { ApiList } from './utils/consts/SdkWhitelist'; import * as apiWhiteList from './data/SdkWhitelist.json'; +import { SdkProblem } from './utils/consts/WhiteListProblemType'; export class TypeScriptLinter { totalVisitedNodes: number = 0; @@ -126,6 +127,7 @@ export class TypeScriptLinter { private funcMap: Map> = new Map>(); private interfaceMap: Map> = new Map>(); static pathMap: Map>; + static indexedTypeSet: Set; static initGlobals(): void { TypeScriptLinter.sharedModulesCache = new Map(); @@ -157,7 +159,14 @@ export class TypeScriptLinter { } } + private static addSdkIndexedTypeSetData(item: ApiListItem): void { + if (item.api_info.problem === SdkProblem.IndexedAccessType) { + TypeScriptLinter.indexedTypeSet.add(item); + } + } + private static initSdkWhitelist(): void { + TypeScriptLinter.indexedTypeSet = new Set(); const list: ApiList = new ApiList(apiWhiteList); if (list?.api_list?.length > 0) { for (const item of list.api_list) { @@ -167,6 +176,7 @@ export class TypeScriptLinter { item.import_path.forEach((path) => { TypeScriptLinter.addOrUpdateData(TypeScriptLinter.pathMap, `'${path}'`, item.api_info); }); + TypeScriptLinter.addSdkIndexedTypeSetData(item); } } } @@ -2957,10 +2967,47 @@ export class TypeScriptLinter { } } + private handleSdkPropertyAccessByIndex(tsCallExpr: ts.CallExpression): void { + const propertyAccessNode = tsCallExpr.expression as ts.PropertyAccessExpression; + if (!ts.isPropertyAccessExpression(propertyAccessNode)) { + return; + } + + const funcName = propertyAccessNode.name; + const indexedTypeSdkInfos = Array.from(TypeScriptLinter.indexedTypeSet); + const isCallInDeprecatedApi = indexedTypeSdkInfos.some((indexedTypeSdkInfo) => { + const isApiNameMismatch = funcName?.getText() !== indexedTypeSdkInfo.api_info.api_name; + if (isApiNameMismatch) { + return false; + } + + const funcDecls = this.tsTypeChecker.getTypeAtLocation(funcName).symbol?.declarations; + return funcDecls?.some((declaration) => { + const interfaceDecl = declaration.parent as ts.InterfaceDeclaration; + if (!(ts.isMethodSignature(declaration) && ts.isInterfaceDeclaration(interfaceDecl))) { + return false; + } + const isSameSdkFilePath = path. + normalize(interfaceDecl.getSourceFile().fileName). + endsWith(indexedTypeSdkInfo.file_path[0]); + const interfaceNameData = indexedTypeSdkInfo.api_info.parent_api[0].api_name; + const isSameInterfaceName = interfaceDecl.name.getText() === interfaceNameData; + return isSameSdkFilePath && isSameInterfaceName; + }); + }); + if (isCallInDeprecatedApi) { + this.incrementCounters(tsCallExpr.expression, FaultID.PropertyAccessByIndexFromSdk); + } + } + private handleCallExpression(node: ts.Node): void { const tsCallExpr = node as ts.CallExpression; this.handleStateStyles(tsCallExpr); + if (this.options.arkts2 && tsCallExpr.typeArguments !== undefined) { + this.handleSdkPropertyAccessByIndex(tsCallExpr); + } + this.handleTsInterop(tsCallExpr.expression, () => { this.checkInteropFunctionCall(tsCallExpr); }); diff --git a/ets2panda/linter/src/lib/data/SdkWhitelist.json b/ets2panda/linter/src/lib/data/SdkWhitelist.json index 70ca1b4308..cf2b5fdccc 100644 --- a/ets2panda/linter/src/lib/data/SdkWhitelist.json +++ b/ets2panda/linter/src/lib/data/SdkWhitelist.json @@ -300,6 +300,72 @@ "methd_return_type": "INetworkOutputQueue", "codeKind": 180 } + }, + { + "import_path": [ + "@ohos.application.AccessibilityExtensionAbility", + "@kit.AccessibilityKit" + ], + "file_path": ["api/application/AccessibilityExtensionContext.d.ts"], + "is_global": false, + "api_info": { + "problem": "IndexedAccessType", + "api_name": "attributeValue", + "api_type": "MethodSignature", + "api_optional": false, + "api_auto_fix": false, + "api_auto_fix_context": "", + "target_type": "", + "api_func_args": [ + { + "name": "attributeName", + "type": "T", + "is_optional": false, + "hasDefault": false + } + ], + "parent_api": [ + { + "api_name": "AccessibilityElement", + "api_type": "InterfaceDeclaration" + } + ], + "methd_return_type": "Promise", + "codeKind": 173 + } + }, + { + "import_path": [ + "@ohos.application.AccessibilityExtensionAbility", + "@kit.AccessibilityKit" + ], + "file_path": ["api/application/AccessibilityExtensionContext.d.ts"], + "is_global": false, + "api_info": { + "problem": "IndexedAccessType", + "api_name": "attributeValue", + "api_type": "MethodSignature", + "api_optional": false, + "api_auto_fix": false, + "api_auto_fix_context": "", + "target_type": "", + "api_func_args": [ + { + "name": "attributeName", + "type": "T", + "is_optional": false, + "hasDefault": false + } + ], + "parent_api": [ + { + "api_name": "AccessibilityElement", + "api_type": "InterfaceDeclaration" + } + ], + "methd_return_type": "Promise", + "codeKind": 173 + } } ] } diff --git a/ets2panda/linter/src/lib/utils/consts/WhiteListProblemType.ts b/ets2panda/linter/src/lib/utils/consts/WhiteListProblemType.ts new file mode 100644 index 0000000000..7a3ba9733a --- /dev/null +++ b/ets2panda/linter/src/lib/utils/consts/WhiteListProblemType.ts @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export enum SdkProblem { + LimitedVoidType = 'LimitedVoidType', + ConstructorIface = 'ConstructorIface', + LiteralAsPropertyName = 'LiteralAsPropertyName', + OptionalMethod = 'OptionalMethod', + ConstructorFuncs = 'ConstructorFuncs', + IndexedAccessType = 'IndexedAccessType', + SendablePropType = 'SendablePropType', + TypeQuery = 'TypeQuery', + GlobalThisError = 'GlobalThisError', + InterfaceExtendsClass = 'InterfaceExtendsClass', + DeclWithDuplicateName = 'DeclWithDuplicateName', + ComputedPropertyName = 'ComputedPropertyName' +} diff --git a/ets2panda/linter/test/sdkwhite/IndexedAccessType.ets b/ets2panda/linter/test/sdkwhite/IndexedAccessType.ets index ab5be3eefd..04afb6c7b8 100644 --- a/ets2panda/linter/test/sdkwhite/IndexedAccessType.ets +++ b/ets2panda/linter/test/sdkwhite/IndexedAccessType.ets @@ -13,13 +13,39 @@ * limitations under the License. */ -// Does not support index access -// todo Unsupported syntax: Can developers use this API? -import { AccessibilityElement, - AccessibilityExtensionAbility, ElementAttributeKeys } from '@kit.AccessibilityKit'; -import { BusinessError } from '@kit.BasicServicesKit'; - +// if in real env, remvoe './sdk/' +import { AccessibilityExtensionAbility } from './sdk/@kit.AccessibilityKit'; +class EntryAbility extends AccessibilityExtensionAbility { + onConnect(): void { + let axContext = this.context; + let accessibilityElement = axContext.getFocusElement(); + accessibilityElement.then((data) => { + data.attributeValue<'accessibilityFocused'>('accessibilityFocused'); // error + }); + } + noErrorCase(): void { + let localAccessibilityElement = customFoo(); + localAccessibilityElement.then((data) => { + data.attributeValue<'accessibilityFocused'>('accessibilityFocused'); // ok + }); + let axContext = this.context; + let notAccessibilityElement = axContext.getFocusElementNotAccessibilityElement(); + notAccessibilityElement.then((data) => { + data.attributeValue<'accessibilityFocused'>('accessibilityFocused'); // ok + }); + } +} +interface AccessibilityElement { + attributeValue( + attributeName: T, + callback: AsyncCallback + ): void; + attributeValue(attributeName: T): Promise; +} +async function customFoo(): Promise { + return (await {}) as AccessibilityElement; +} diff --git a/ets2panda/linter/test/sdkwhite/IndexedAccessType.ets.args.json b/ets2panda/linter/test/sdkwhite/IndexedAccessType.ets.args.json new file mode 100644 index 0000000000..948b846fe0 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/IndexedAccessType.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} diff --git a/ets2panda/linter/test/sdkwhite/IndexedAccessType.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/IndexedAccessType.ets.arkts2.json index 5e75d5b3e7..2e3d6073f6 100644 --- a/ets2panda/linter/test/sdkwhite/IndexedAccessType.ets.arkts2.json +++ b/ets2panda/linter/test/sdkwhite/IndexedAccessType.ets.arkts2.json @@ -14,6 +14,45 @@ "limitations under the License." ], "result": [ - + { + "line": 24, + "column": 7, + "endLine": 24, + "endColumn": 26, + "problem": "PropertyAccessByIndexFromSdk", + "suggest": "", + "rule": "Indexed access is not supported for fields (sdk-no-props-by-index)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 29, + "endLine": 44, + "endColumn": 54, + "problem": "IndexedAccessType", + "suggest": "", + "rule": "Indexed access types are not supported (arkts-no-aliases-by-index)", + "severity": "ERROR" + }, + { + "line": 46, + "column": 85, + "endLine": 46, + "endColumn": 110, + "problem": "IndexedAccessType", + "suggest": "", + "rule": "Indexed access types are not supported (arkts-no-aliases-by-index)", + "severity": "ERROR" + }, + { + "line": 50, + "column": 17, + "endLine": 50, + "endColumn": 18, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/IndexedAccessType.ets.json b/ets2panda/linter/test/sdkwhite/IndexedAccessType.ets.json index ca88f857e9..0ffe95853a 100644 --- a/ets2panda/linter/test/sdkwhite/IndexedAccessType.ets.json +++ b/ets2panda/linter/test/sdkwhite/IndexedAccessType.ets.json @@ -13,5 +13,36 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "result": [] + "result": [ + { + "line": 44, + "column": 29, + "endLine": 44, + "endColumn": 54, + "problem": "IndexedAccessType", + "suggest": "", + "rule": "Indexed access types are not supported (arkts-no-aliases-by-index)", + "severity": "ERROR" + }, + { + "line": 46, + "column": 85, + "endLine": 46, + "endColumn": 110, + "problem": "IndexedAccessType", + "suggest": "", + "rule": "Indexed access types are not supported (arkts-no-aliases-by-index)", + "severity": "ERROR" + }, + { + "line": 50, + "column": 17, + "endLine": 50, + "endColumn": 18, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + } + ] } \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/sdk/@kit.AccessibilityKit.d.ts b/ets2panda/linter/test/sdkwhite/sdk/@kit.AccessibilityKit.d.ts new file mode 100644 index 0000000000..d4147faf05 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/sdk/@kit.AccessibilityKit.d.ts @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { AccessibilityElement, NotAccessibilityElement } from './api/application/AccessibilityExtensionContext'; + +interface Simulate { + getFocusElement(): Promise; + getFocusElementNotAccessibilityElement(): Promise; +} + +export class AccessibilityExtensionAbility { + context: Simulate; +} diff --git a/ets2panda/linter/test/sdkwhite/sdk/api/application/AccessibilityExtensionContext.d.ts b/ets2panda/linter/test/sdkwhite/sdk/api/application/AccessibilityExtensionContext.d.ts new file mode 100644 index 0000000000..4b217c9535 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/sdk/api/application/AccessibilityExtensionContext.d.ts @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// save it in api/application/AccessibilityExtensionContext.d.ts +export interface AccessibilityElement { + attributeValue( + attributeName: T, + callback: AsyncCallback + ): void; + attributeValue(attributeName: T): Promise; +} +export interface NotAccessibilityElement { + attributeValue( + attributeName: T, + callback: AsyncCallback + ): void; + attributeValue(attributeName: T): Promise; +} -- Gitee From 59636a0d12f7d20e1c4d10b17aa7bd0e300eb34f Mon Sep 17 00:00:00 2001 From: ZhongNing Date: Tue, 8 Apr 2025 15:57:41 +0800 Subject: [PATCH 061/268] add sdk whitelist for arkts-constructor-funcs Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC0L18 Test scenarios:new tests add to the linter Signed-off-by: ZhongNing Change-Id: I0f9e36eb19d800df63cd9fc04317291b9f664e73 --- ets2panda/linter/src/lib/CookBookMsg.ts | 3 +- ets2panda/linter/src/lib/FaultAttrs.ts | 1 + ets2panda/linter/src/lib/FaultDesc.ts | 1 + ets2panda/linter/src/lib/Problems.ts | 1 + ets2panda/linter/src/lib/TypeScriptLinter.ts | 19 +++++++++- .../linter/src/lib/data/SdkWhitelist.json | 35 +++++++++++++++++ .../src/lib/utils/consts/ArkTS2Rules.ts | 3 +- .../src/lib/utils/consts/SdkWhitelist.ts | 2 + .../constructor_types_deprecated_sdk.ets | 20 ++++++++++ ...tructor_types_deprecated_sdk.ets.args.json | 19 ++++++++++ ...uctor_types_deprecated_sdk.ets.arkts2.json | 38 +++++++++++++++++++ .../constructor_types_deprecated_sdk.ets.json | 17 +++++++++ 12 files changed, 156 insertions(+), 3 deletions(-) create mode 100755 ets2panda/linter/test/sdkwhite/constructor_types_deprecated_sdk.ets create mode 100755 ets2panda/linter/test/sdkwhite/constructor_types_deprecated_sdk.ets.args.json create mode 100755 ets2panda/linter/test/sdkwhite/constructor_types_deprecated_sdk.ets.arkts2.json create mode 100755 ets2panda/linter/test/sdkwhite/constructor_types_deprecated_sdk.ets.json diff --git a/ets2panda/linter/src/lib/CookBookMsg.ts b/ets2panda/linter/src/lib/CookBookMsg.ts index 5eedac09cc..09766ea918 100644 --- a/ets2panda/linter/src/lib/CookBookMsg.ts +++ b/ets2panda/linter/src/lib/CookBookMsg.ts @@ -16,7 +16,7 @@ export const cookBookMsg: string[] = []; export const cookBookTag: string[] = []; -for (let i = 0; i <= 314; i++) { +for (let i = 0; i <= 325; i++) { cookBookMsg[i] = ''; } @@ -282,3 +282,4 @@ cookBookTag[312] = 'Properties in "Sendable" classes and interfaces must have a Sendable data type (sdk-no-sendable-prop-types)'; cookBookTag[313] = 'Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)'; cookBookTag[314] = 'Indexed access is not supported for fields (sdk-no-props-by-index)'; +cookBookTag[325] = 'Constructor types are not supported - use lambda functions instead. (sdk-constructor-funcs)'; diff --git a/ets2panda/linter/src/lib/FaultAttrs.ts b/ets2panda/linter/src/lib/FaultAttrs.ts index e1f163bca8..f723d51d57 100644 --- a/ets2panda/linter/src/lib/FaultAttrs.ts +++ b/ets2panda/linter/src/lib/FaultAttrs.ts @@ -193,3 +193,4 @@ faultsAttrs[FaultID.OptionalMethodFromSdk] = new FaultAttributes(309); faultsAttrs[FaultID.SendablePropTypeFromSdk] = new FaultAttributes(312); faultsAttrs[FaultID.ConstructorIfaceFromSdk] = new FaultAttributes(313); faultsAttrs[FaultID.PropertyAccessByIndexFromSdk] = new FaultAttributes(314); +faultsAttrs[FaultID.ConstructorTypesDeprecated] = new FaultAttributes(325); diff --git a/ets2panda/linter/src/lib/FaultDesc.ts b/ets2panda/linter/src/lib/FaultDesc.ts index 16b0823294..7a21f540a3 100644 --- a/ets2panda/linter/src/lib/FaultDesc.ts +++ b/ets2panda/linter/src/lib/FaultDesc.ts @@ -181,3 +181,4 @@ faultDesc[FaultID.OptionalMethodFromSdk] = 'Optional method from sdk'; faultDesc[FaultID.SendablePropTypeFromSdk] = 'ISendable is no longer supported'; faultDesc[FaultID.ConstructorIfaceFromSdk] = 'Construct signatures are not supported in interfaces from sdk'; faultDesc[FaultID.PropertyAccessByIndexFromSdk] = 'property access by index from sdk'; +faultDesc[FaultID.ConstructorTypesDeprecated] = 'Constructor funcs'; diff --git a/ets2panda/linter/src/lib/Problems.ts b/ets2panda/linter/src/lib/Problems.ts index 903e4e6a41..31d0e9ff6e 100644 --- a/ets2panda/linter/src/lib/Problems.ts +++ b/ets2panda/linter/src/lib/Problems.ts @@ -182,6 +182,7 @@ export enum FaultID { SendablePropTypeFromSdk, ConstructorIfaceFromSdk, PropertyAccessByIndexFromSdk, + ConstructorTypesDeprecated, // this should always be last enum LAST_ID } diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index f00a45d730..962e98d020 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -952,6 +952,7 @@ export class TypeScriptLinter { this.incrementCounters(propertyAccessNode, FaultID.SendableFunctionProperty); } this.checkFunctionProperty(propertyAccessNode, baseExprSym, baseExprType); + this.handleSdkForConstructorFuncs(propertyAccessNode); } checkFunctionProperty( @@ -2143,7 +2144,6 @@ export class TypeScriptLinter { } const memberName = member.name?.getText(); - if (sdkInfo.api_name === memberName) { if (TypeScriptLinter.areParametersEqual(sdkInfo.api_func_args, member.parameters)) { this.incrementCounters( @@ -5389,4 +5389,21 @@ export class TypeScriptLinter { ): node is ts.FunctionDeclaration | ts.MethodDeclaration | ts.FunctionExpression { return ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node) || ts.isFunctionExpression(node); } + + private handleSdkForConstructorFuncs(node: ts.PropertyAccessExpression): void { + if (!this.options.arkts2 || !node) { + return; + } + const sdkInfos = this.interfaceMap.get(node.expression.getText()); + if (!sdkInfos || sdkInfos.size === 0) { + return; + } + + for (const sdkInfo of sdkInfos) { + const propertyName = node.name.getText(); + if (propertyName === sdkInfo.api_name) { + this.incrementCounters(node.name, FaultID.ConstructorTypesDeprecated); + } + } + } } diff --git a/ets2panda/linter/src/lib/data/SdkWhitelist.json b/ets2panda/linter/src/lib/data/SdkWhitelist.json index cf2b5fdccc..0e844ac388 100644 --- a/ets2panda/linter/src/lib/data/SdkWhitelist.json +++ b/ets2panda/linter/src/lib/data/SdkWhitelist.json @@ -366,6 +366,41 @@ "methd_return_type": "Promise", "codeKind": 173 } + }, + { + "import_path": [ + "@hms.core.deviceCloudGateway.cloudDatabase", + "@kit.CloudFoundationKit" + ], + "file_path": [ + "api/@hms.core.deviceCloudGateway.cloudDatabase.d.ts" + ], + "is_global": false, + "api_info": { + "problem": "ConstructorFuncs", + "api_name": "DatabaseQuery", + "api_type": "ClassDeclaration", + "api_optional": false, + "api_auto_fix": false, + "api_auto_fix_context": "", + "target_type": "", + "api_func_args": [ + { + "name": "entityClass", + "type": "new () => T", + "is_optional": false, + "hasDefault": false + } + ], + "parent_api": [ + { + "api_name": "cloudDatabase", + "api_type": "ModuleDeclaration" + } + ], + "methd_return_type": "DatabaseQuery", + "codeKind": 264 + } } ] } diff --git a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts index faa4bf2919..ad02221bff 100644 --- a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts +++ b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts @@ -70,5 +70,6 @@ export const arkts2Rules: number[] = [ 306, 307, 308, - 309 + 309, + 325 ]; diff --git a/ets2panda/linter/src/lib/utils/consts/SdkWhitelist.ts b/ets2panda/linter/src/lib/utils/consts/SdkWhitelist.ts index cddc6d0964..948bc61769 100644 --- a/ets2panda/linter/src/lib/utils/consts/SdkWhitelist.ts +++ b/ets2panda/linter/src/lib/utils/consts/SdkWhitelist.ts @@ -18,11 +18,13 @@ export class ApiFuncArg { name: string; type: string; is_optional: boolean; + hasDefault: boolean; constructor(data: Partial) { this.name = data.name || ''; this.type = data.type || ''; this.is_optional = data.is_optional || false; + this.hasDefault = data.hasDefault || false; } } diff --git a/ets2panda/linter/test/sdkwhite/constructor_types_deprecated_sdk.ets b/ets2panda/linter/test/sdkwhite/constructor_types_deprecated_sdk.ets new file mode 100755 index 0000000000..c50d5885da --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/constructor_types_deprecated_sdk.ets @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {cloudDatabase} from '@hms.core.deviceCloudGateway.cloudDatabase'; +class Test extends cloudDatabase.DatabaseObject{ + +} +new cloudDatabase.DatabaseQuery(Test); // NOT OK \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/constructor_types_deprecated_sdk.ets.args.json b/ets2panda/linter/test/sdkwhite/constructor_types_deprecated_sdk.ets.args.json new file mode 100755 index 0000000000..9c3d973432 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/constructor_types_deprecated_sdk.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/constructor_types_deprecated_sdk.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/constructor_types_deprecated_sdk.ets.arkts2.json new file mode 100755 index 0000000000..745ab994b2 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/constructor_types_deprecated_sdk.ets.arkts2.json @@ -0,0 +1,38 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 20, + "column": 5, + "endLine": 20, + "endColumn": 32, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 19, + "endLine": 20, + "endColumn": 32, + "problem": "ConstructorTypesDeprecated", + "suggest": "", + "rule": "Constructor types are not supported - use lambda functions instead. (sdk-constructor-funcs)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/sdkwhite/constructor_types_deprecated_sdk.ets.json b/ets2panda/linter/test/sdkwhite/constructor_types_deprecated_sdk.ets.json new file mode 100755 index 0000000000..9f305c86d7 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/constructor_types_deprecated_sdk.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} -- Gitee From 6f1f874e768144fb29970bee0f8f0933bf727d80 Mon Sep 17 00:00:00 2001 From: ZhongNing Date: Tue, 8 Apr 2025 15:20:57 +0800 Subject: [PATCH 062/268] add SdkRule sdk-no-literal-as-property-name Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC0L18 Test scenarios:new tests add to the linter Signed-off-by: ZhongNing Change-Id: I0c681a7809a507c06ad4f0b2587204c157706c92 --- ets2panda/linter/src/lib/CookBookMsg.ts | 2 + ets2panda/linter/src/lib/FaultAttrs.ts | 1 + ets2panda/linter/src/lib/FaultDesc.ts | 1 + ets2panda/linter/src/lib/Problems.ts | 1 + ets2panda/linter/src/lib/TypeScriptLinter.ts | 72 +++++++++ .../linter/src/lib/data/SdkWhitelist.json | 150 ++++++++++++++++++ .../src/lib/utils/consts/ArkTS2Rules.ts | 3 +- .../src/lib/utils/consts/SdkWhitelist.ts | 2 - .../quoted_hyphen_props_deprecated_sdk.ets | 31 ++++ ..._hyphen_props_deprecated_sdk.ets.args.json | 19 +++ ...yphen_props_deprecated_sdk.ets.arkts2.json | 138 ++++++++++++++++ ...uoted_hyphen_props_deprecated_sdk.ets.json | 17 ++ 12 files changed, 434 insertions(+), 3 deletions(-) create mode 100755 ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk.ets create mode 100755 ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk.ets.args.json create mode 100755 ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk.ets.arkts2.json create mode 100755 ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk.ets.json diff --git a/ets2panda/linter/src/lib/CookBookMsg.ts b/ets2panda/linter/src/lib/CookBookMsg.ts index 09766ea918..17e15de6ed 100644 --- a/ets2panda/linter/src/lib/CookBookMsg.ts +++ b/ets2panda/linter/src/lib/CookBookMsg.ts @@ -283,3 +283,5 @@ cookBookTag[312] = cookBookTag[313] = 'Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)'; cookBookTag[314] = 'Indexed access is not supported for fields (sdk-no-props-by-index)'; cookBookTag[325] = 'Constructor types are not supported - use lambda functions instead. (sdk-constructor-funcs)'; +cookBookTag[324] = + 'Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)'; diff --git a/ets2panda/linter/src/lib/FaultAttrs.ts b/ets2panda/linter/src/lib/FaultAttrs.ts index f723d51d57..dc3d55e2f6 100644 --- a/ets2panda/linter/src/lib/FaultAttrs.ts +++ b/ets2panda/linter/src/lib/FaultAttrs.ts @@ -194,3 +194,4 @@ faultsAttrs[FaultID.SendablePropTypeFromSdk] = new FaultAttributes(312); faultsAttrs[FaultID.ConstructorIfaceFromSdk] = new FaultAttributes(313); faultsAttrs[FaultID.PropertyAccessByIndexFromSdk] = new FaultAttributes(314); faultsAttrs[FaultID.ConstructorTypesDeprecated] = new FaultAttributes(325); +faultsAttrs[FaultID.QuotedHyphenPropsDeprecated] = new FaultAttributes(324); diff --git a/ets2panda/linter/src/lib/FaultDesc.ts b/ets2panda/linter/src/lib/FaultDesc.ts index 7a21f540a3..789903f7a9 100644 --- a/ets2panda/linter/src/lib/FaultDesc.ts +++ b/ets2panda/linter/src/lib/FaultDesc.ts @@ -182,3 +182,4 @@ faultDesc[FaultID.SendablePropTypeFromSdk] = 'ISendable is no longer supported'; faultDesc[FaultID.ConstructorIfaceFromSdk] = 'Construct signatures are not supported in interfaces from sdk'; faultDesc[FaultID.PropertyAccessByIndexFromSdk] = 'property access by index from sdk'; faultDesc[FaultID.ConstructorTypesDeprecated] = 'Constructor funcs'; +faultDesc[FaultID.QuotedHyphenPropsDeprecated] = 'Quoted hyphen props deprecated'; diff --git a/ets2panda/linter/src/lib/Problems.ts b/ets2panda/linter/src/lib/Problems.ts index 31d0e9ff6e..caff426e5a 100644 --- a/ets2panda/linter/src/lib/Problems.ts +++ b/ets2panda/linter/src/lib/Problems.ts @@ -183,6 +183,7 @@ export enum FaultID { ConstructorIfaceFromSdk, PropertyAccessByIndexFromSdk, ConstructorTypesDeprecated, + QuotedHyphenPropsDeprecated, // this should always be last enum LAST_ID } diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index 962e98d020..ad1d236ecd 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -3592,6 +3592,7 @@ export class TypeScriptLinter { if (this.tsUtils.isSendableClassOrInterface(typeNameType)) { this.checkSendableTypeArguments(typeRef); } + this.handleQuotedHyphenPropsDeprecated(typeRef); } private checkPartialType(node: ts.Node): void { @@ -5406,4 +5407,75 @@ export class TypeScriptLinter { } } } + + private handleQuotedHyphenPropsDeprecated(typeRef: ts.TypeReferenceNode): void { + if (!this.options.arkts2 || !ts.isQualifiedName(typeRef.typeName)) { + return; + } + const qualNode = typeRef.typeName; + const parent = typeRef.parent; + const sdkInfos = this.interfaceMap.get(qualNode.left.getText()); + if (!sdkInfos || sdkInfos.size === 0) { + return; + } + + for (const sdkInfo of sdkInfos) { + this.processQuotedHyphenPropsDeprecated(parent, sdkInfo.api_name); + } + } + + private processQuotedHyphenPropsDeprecated(node: ts.Node, apiName: string): void { + if (ts.isVariableDeclaration(node)) { + this.handleQuotedHyphenPropsDeprecatedOnVarDecl(node, apiName); + } else if (ts.isFunctionDeclaration(node)) { + this.handleQuotedHyphenPropsDeprecatedOnFunDecl(node, apiName); + } + } + + private handleQuotedHyphenPropsDeprecatedOnVarDecl(node: ts.VariableDeclaration, apiName: string): void { + const initializer = node.initializer; + if (initializer && ts.isObjectLiteralExpression(initializer)) { + initializer.properties.forEach((property) => { + if (ts.isPropertyAssignment(property)) { + const propertyName = property.name.getText(); + if (propertyName === apiName) { + this.incrementCounters(property.name, FaultID.QuotedHyphenPropsDeprecated); + } + } + }); + } + } + + private handleQuotedHyphenPropsDeprecatedOnFunDecl(node: ts.FunctionDeclaration, apiName: string): void { + const body = node.body; + if (!body || !ts.isBlock(body)) { + return; + } + + body.statements.forEach(this.processStatement.bind(this, apiName)); + } + + private processStatement(apiName: string, statement: ts.Statement): void { + if (!ts.isReturnStatement(statement)) { + return; + } + + const returnValue = statement.expression; + if (!returnValue || !ts.isObjectLiteralExpression(returnValue)) { + return; + } + + returnValue.properties.forEach(this.processProperty.bind(this, apiName)); + } + + private processProperty(apiName: string, property: ts.ObjectLiteralElementLike): void { + if (!ts.isPropertyAssignment(property)) { + return; + } + + const isMatch = property.name.getText() === apiName; + if (isMatch) { + this.incrementCounters(property.name, FaultID.QuotedHyphenPropsDeprecated); + } + } } diff --git a/ets2panda/linter/src/lib/data/SdkWhitelist.json b/ets2panda/linter/src/lib/data/SdkWhitelist.json index 0e844ac388..b73d0d16cb 100644 --- a/ets2panda/linter/src/lib/data/SdkWhitelist.json +++ b/ets2panda/linter/src/lib/data/SdkWhitelist.json @@ -401,6 +401,156 @@ "methd_return_type": "DatabaseQuery", "codeKind": 264 } + }, + { + "import_path": [ + "@hms.collaboration.rcp.d.ts", + "@kit.RemoteCommunicationKit" + ], + "file_path": ["api/@hms.collaboration.rcp.d.ts"], + "is_global": false, + "api_info": { + "problem": "LiteralAsPropertyName", + "api_name": "'authorization'", + "api_type": "PropertySignature", + "api_optional": true, + "api_auto_fix": false, + "api_auto_fix_context": "", + "target_type": "", + "api_func_args": [], + "parent_api": [ + { + "api_name": "RequestHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "methd_return_type": "string", + "codeKind": 170 + } + }, + { + "import_path": [ + "@hms.collaboration.rcp.d.ts", + "@kit.RemoteCommunicationKit" + ], + "file_path": ["api/@hms.collaboration.rcp.d.ts"], + "is_global": false, + "api_info": { + "problem": "LiteralAsPropertyName", + "api_name": "'content-type'", + "api_type": "PropertySignature", + "api_optional": true, + "api_auto_fix": false, + "api_auto_fix_context": "", + "target_type": "", + "api_func_args": [], + "parent_api": [ + { + "api_name": "RequestHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "methd_return_type": "string", + "codeKind": 170 + } + }, + { + "import_path": [ + "@hms.collaboration.rcp.d.ts", + "@kit.RemoteCommunicationKit" + ], + "file_path": ["api/@hms.collaboration.rcp.d.ts"], + "is_global": false, + "api_info": { + "problem": "LiteralAsPropertyName", + "api_name": "'accept'", + "api_type": "PropertySignature", + "api_optional": true, + "api_auto_fix": false, + "api_auto_fix_context": "", + "target_type": "", + "api_func_args": [], + "parent_api": [ + { + "api_name": "RequestHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "methd_return_type": "ContentType | ContentType[]", + "codeKind": 170 + } + }, + { + "import_path": [ + "@hms.collaboration.rcp.d.ts", + "@kit.RemoteCommunicationKit" + ], + "file_path": ["api/@hms.collaboration.rcp.d.ts"], + "is_global": false, + "api_info": { + "problem": "LiteralAsPropertyName", + "api_name": "'cache-control'", + "api_type": "PropertySignature", + "api_optional": true, + "api_auto_fix": false, + "api_auto_fix_context": "", + "target_type": "", + "api_func_args": [], + "parent_api": [ + { + "api_name": "RequestHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "methd_return_type": "string | string[]", + "codeKind": 170 + } + }, + { + "import_path": [ + "@hms.collaboration.rcp.d.ts", + "@kit.RemoteCommunicationKit" + ], + "file_path": ["api/@hms.collaboration.rcp.d.ts"], + "is_global": false, + "api_info": { + "problem": "LiteralAsPropertyName", + "api_name": "'user-agent'", + "api_type": "PropertySignature", + "api_optional": true, + "api_auto_fix": false, + "api_auto_fix_context": "", + "target_type": "", + "api_func_args": [], + "parent_api": [ + { + "api_name": "RequestHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "methd_return_type": "string", + "codeKind": 170 + } } ] } diff --git a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts index ad02221bff..ee0103d4e5 100644 --- a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts +++ b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts @@ -71,5 +71,6 @@ export const arkts2Rules: number[] = [ 307, 308, 309, - 325 + 325, + 324 ]; diff --git a/ets2panda/linter/src/lib/utils/consts/SdkWhitelist.ts b/ets2panda/linter/src/lib/utils/consts/SdkWhitelist.ts index 948bc61769..3c8dd7b5cf 100644 --- a/ets2panda/linter/src/lib/utils/consts/SdkWhitelist.ts +++ b/ets2panda/linter/src/lib/utils/consts/SdkWhitelist.ts @@ -77,13 +77,11 @@ export class ApiListItem { import_path: string[]; file_path: string[]; api_info: ApiInfo; - is_global: boolean; constructor(data: Partial) { this.import_path = data.import_path || []; this.file_path = data.file_path || []; this.api_info = new ApiInfo(data.api_info || {}); - this.is_global = data.is_global || false; } } diff --git a/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk.ets b/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk.ets new file mode 100755 index 0000000000..10ed3b18e1 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk.ets @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {rcp} from '@kit.RemoteCommunicationKit'; +// case1 +const basicHeaders: rcp.RequestHeaders = { + 'authorization': 'Bearer abc123', // error + 'content-type': 'application/json' // error +} + +// case2 +function createHeaders(): rcp.RequestHeaders { + return { + 'authorization': '', // error + 'accept': 'application/json', // error + 'cache-control': 'no-cache', // error + 'user-agent': 'MyApp/2.0' // error + }; +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk.ets.args.json b/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk.ets.args.json new file mode 100755 index 0000000000..3ef4496a81 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} diff --git a/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk.ets.arkts2.json new file mode 100755 index 0000000000..381a73c1da --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk.ets.arkts2.json @@ -0,0 +1,138 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 19, + "column": 3, + "endLine": 19, + "endColumn": 18, + "problem": "QuotedHyphenPropsDeprecated", + "suggest": "", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 3, + "endLine": 20, + "endColumn": 17, + "problem": "QuotedHyphenPropsDeprecated", + "suggest": "", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 3, + "endLine": 19, + "endColumn": 18, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 3, + "endLine": 20, + "endColumn": 17, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 5, + "endLine": 26, + "endColumn": 20, + "problem": "QuotedHyphenPropsDeprecated", + "suggest": "", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 5, + "endLine": 27, + "endColumn": 13, + "problem": "QuotedHyphenPropsDeprecated", + "suggest": "", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 5, + "endLine": 28, + "endColumn": 20, + "problem": "QuotedHyphenPropsDeprecated", + "suggest": "", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 5, + "endLine": 29, + "endColumn": 17, + "problem": "QuotedHyphenPropsDeprecated", + "suggest": "", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 5, + "endLine": 26, + "endColumn": 20, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 5, + "endLine": 27, + "endColumn": 13, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 5, + "endLine": 28, + "endColumn": 20, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 5, + "endLine": 29, + "endColumn": 17, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk.ets.json b/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk.ets.json new file mode 100755 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file -- Gitee From 34efbcd0e96df57a8ccee348ff651117f1b0b4b8 Mon Sep 17 00:00:00 2001 From: ZhongNing Date: Tue, 8 Apr 2025 20:40:09 +0800 Subject: [PATCH 063/268] Add checks for arkts-sdk-apipath-changed Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC0L18 Test scenarios: new tests added to the linter Signed-off-by: ZhongNing Change-Id: Ib94c202c7f7bc3f16a8e14235168f31295ef2c0f --- ets2panda/linter/src/lib/CookBookMsg.ts | 1 + ets2panda/linter/src/lib/FaultAttrs.ts | 1 + ets2panda/linter/src/lib/FaultDesc.ts | 1 + ets2panda/linter/src/lib/Problems.ts | 1 + ets2panda/linter/src/lib/TypeScriptLinter.ts | 33 +++++- .../linter/src/lib/data/SdkWhitelist.json | 27 ++++- .../src/lib/utils/consts/ArkTS2Rules.ts | 3 +- .../lib/utils/consts/ArktsWhiteApiPaths.ts | 16 +++ .../lib/utils/consts/WhiteListProblemType.ts | 3 + .../linter/test/sdkwhite/api_path_changed.ets | 24 ++++ .../sdkwhite/api_path_changed.ets.args.json | 19 +++ .../sdkwhite/api_path_changed.ets.arkts2.json | 108 ++++++++++++++++++ .../test/sdkwhite/api_path_changed.ets.json | 17 +++ 13 files changed, 251 insertions(+), 3 deletions(-) create mode 100755 ets2panda/linter/src/lib/utils/consts/ArktsWhiteApiPaths.ts create mode 100755 ets2panda/linter/test/sdkwhite/api_path_changed.ets create mode 100755 ets2panda/linter/test/sdkwhite/api_path_changed.ets.args.json create mode 100755 ets2panda/linter/test/sdkwhite/api_path_changed.ets.arkts2.json create mode 100755 ets2panda/linter/test/sdkwhite/api_path_changed.ets.json diff --git a/ets2panda/linter/src/lib/CookBookMsg.ts b/ets2panda/linter/src/lib/CookBookMsg.ts index 17e15de6ed..bb2f2d3c6d 100644 --- a/ets2panda/linter/src/lib/CookBookMsg.ts +++ b/ets2panda/linter/src/lib/CookBookMsg.ts @@ -285,3 +285,4 @@ cookBookTag[314] = 'Indexed access is not supported for fields (sdk-no-props-by- cookBookTag[325] = 'Constructor types are not supported - use lambda functions instead. (sdk-constructor-funcs)'; cookBookTag[324] = 'Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)'; +cookBookTag[320] = 'API path have changed - please update your imports accordingly (arkts-sdk-no-decl-with-duplicate-name)'; diff --git a/ets2panda/linter/src/lib/FaultAttrs.ts b/ets2panda/linter/src/lib/FaultAttrs.ts index dc3d55e2f6..442afd9752 100644 --- a/ets2panda/linter/src/lib/FaultAttrs.ts +++ b/ets2panda/linter/src/lib/FaultAttrs.ts @@ -195,3 +195,4 @@ faultsAttrs[FaultID.ConstructorIfaceFromSdk] = new FaultAttributes(313); faultsAttrs[FaultID.PropertyAccessByIndexFromSdk] = new FaultAttributes(314); faultsAttrs[FaultID.ConstructorTypesDeprecated] = new FaultAttributes(325); faultsAttrs[FaultID.QuotedHyphenPropsDeprecated] = new FaultAttributes(324); +faultsAttrs[FaultID.ApiPathChanged] = new FaultAttributes(320); diff --git a/ets2panda/linter/src/lib/FaultDesc.ts b/ets2panda/linter/src/lib/FaultDesc.ts index 789903f7a9..3055e38edd 100644 --- a/ets2panda/linter/src/lib/FaultDesc.ts +++ b/ets2panda/linter/src/lib/FaultDesc.ts @@ -183,3 +183,4 @@ faultDesc[FaultID.ConstructorIfaceFromSdk] = 'Construct signatures are not suppo faultDesc[FaultID.PropertyAccessByIndexFromSdk] = 'property access by index from sdk'; faultDesc[FaultID.ConstructorTypesDeprecated] = 'Constructor funcs'; faultDesc[FaultID.QuotedHyphenPropsDeprecated] = 'Quoted hyphen props deprecated'; +faultDesc[FaultID.ApiPathChanged] = 'API path have changed'; diff --git a/ets2panda/linter/src/lib/Problems.ts b/ets2panda/linter/src/lib/Problems.ts index caff426e5a..3050536dd7 100644 --- a/ets2panda/linter/src/lib/Problems.ts +++ b/ets2panda/linter/src/lib/Problems.ts @@ -184,6 +184,7 @@ export enum FaultID { PropertyAccessByIndexFromSdk, ConstructorTypesDeprecated, QuotedHyphenPropsDeprecated, + ApiPathChanged, // this should always be last enum LAST_ID } diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index ad1d236ecd..9f2298f019 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -95,7 +95,7 @@ import { ARKTS_IGNORE_DIRS_OH_MODULES } from './utils/consts/ArktsIgnorePaths'; import type { ApiInfo, ApiListItem } from './utils/consts/SdkWhitelist'; import { ApiList } from './utils/consts/SdkWhitelist'; import * as apiWhiteList from './data/SdkWhitelist.json'; -import { SdkProblem } from './utils/consts/WhiteListProblemType'; +import { SdkProblem, ARKTS_WHITE_API_PATH_TEXTSTYLE } from './utils/consts/WhiteListProblemType'; export class TypeScriptLinter { totalVisitedNodes: number = 0; @@ -1086,6 +1086,7 @@ export class TypeScriptLinter { this.checkAssignmentNumericSemanticslyPro(node); this.handleInvalidIdentifier(node); this.handleStructPropertyDecl(node); + this.handleApipathChanged(node); } private handleSendableClassProperty(node: ts.PropertyDeclaration): void { @@ -5478,4 +5479,34 @@ export class TypeScriptLinter { this.incrementCounters(property.name, FaultID.QuotedHyphenPropsDeprecated); } } + + private handleApipathChanged(node: ts.PropertyDeclaration): void { + if (!this.options.arkts2 || !ts.isPropertyDeclaration(node)) { + return; + } + const processApiNode = (apiName: string, errorNode: ts.Node): void => { + const sdkInfos = TypeScriptLinter.pathMap.get(`'${ARKTS_WHITE_API_PATH_TEXTSTYLE}'`); + if (!sdkInfos) { + return; + } + const matchedApi = [...sdkInfos].find((sdkInfo) => { + return sdkInfo.api_name === apiName; + }); + if (matchedApi) { + this.incrementCounters(errorNode, FaultID.ApiPathChanged); + } + }; + if (node.type && ts.isTypeReferenceNode(node.type)) { + const typeName = node.type.typeName; + if (ts.isIdentifier(typeName)) { + processApiNode(typeName.text, node.type); + } + } + if (node.initializer && ts.isNewExpression(node.initializer)) { + const expression = node.initializer.expression; + if (ts.isIdentifier(expression)) { + processApiNode(expression.text, expression); + } + } + } } diff --git a/ets2panda/linter/src/lib/data/SdkWhitelist.json b/ets2panda/linter/src/lib/data/SdkWhitelist.json index b73d0d16cb..9479aeb666 100644 --- a/ets2panda/linter/src/lib/data/SdkWhitelist.json +++ b/ets2panda/linter/src/lib/data/SdkWhitelist.json @@ -551,6 +551,31 @@ "methd_return_type": "string", "codeKind": 170 } + }, + { + "import_path": [], + "file_path": ["component/styled_string.d.ts"], + "is_global": true, + "api_info": { + "problem": "DeclWithDuplicateName", + "api_name": "TextStyle", + "api_type": "ClassDeclaration", + "api_optional": false, + "api_auto_fix": false, + "api_auto_fix_context": "", + "target_type": "", + "api_func_args": [ + { + "name": "value", + "type": "TextStyleInterface", + "is_optional": true, + "hasDefault": false + } + ], + "parent_api": [], + "methd_return_type": "TextStyle", + "codeKind": 264 + } } ] -} +} \ No newline at end of file diff --git a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts index ee0103d4e5..41b8552faf 100644 --- a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts +++ b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts @@ -72,5 +72,6 @@ export const arkts2Rules: number[] = [ 308, 309, 325, - 324 + 324, + 320 ]; diff --git a/ets2panda/linter/src/lib/utils/consts/ArktsWhiteApiPaths.ts b/ets2panda/linter/src/lib/utils/consts/ArktsWhiteApiPaths.ts new file mode 100755 index 0000000000..bd6d904c93 --- /dev/null +++ b/ets2panda/linter/src/lib/utils/consts/ArktsWhiteApiPaths.ts @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const ARKTS_WHITE_API_PATH_TEXTSTYLE = 'component/styled_string.d.ts'; diff --git a/ets2panda/linter/src/lib/utils/consts/WhiteListProblemType.ts b/ets2panda/linter/src/lib/utils/consts/WhiteListProblemType.ts index 7a3ba9733a..c99ec1a02b 100644 --- a/ets2panda/linter/src/lib/utils/consts/WhiteListProblemType.ts +++ b/ets2panda/linter/src/lib/utils/consts/WhiteListProblemType.ts @@ -27,3 +27,6 @@ export enum SdkProblem { DeclWithDuplicateName = 'DeclWithDuplicateName', ComputedPropertyName = 'ComputedPropertyName' } + + +export const ARKTS_WHITE_API_PATH_TEXTSTYLE = 'component/styled_string.d.ts'; \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/api_path_changed.ets b/ets2panda/linter/test/sdkwhite/api_path_changed.ets new file mode 100755 index 0000000000..5f3d51d879 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/api_path_changed.ets @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@Entry +@Component +struct Index { + fontStyleAttr1: TextStyle = new TextStyle({fontColor: Color.Blue}); + fontStyleAttr2: TextStyle; + build() { + Text(); + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/api_path_changed.ets.args.json b/ets2panda/linter/test/sdkwhite/api_path_changed.ets.args.json new file mode 100755 index 0000000000..66fb88f859 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/api_path_changed.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} diff --git a/ets2panda/linter/test/sdkwhite/api_path_changed.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/api_path_changed.ets.arkts2.json new file mode 100755 index 0000000000..5360a1f441 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/api_path_changed.ets.arkts2.json @@ -0,0 +1,108 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 19, + "column": 19, + "endLine": 19, + "endColumn": 28, + "problem": "ApiPathChanged", + "suggest": "", + "rule": "API path have changed - please update your imports accordingly (arkts-sdk-no-decl-with-duplicate-name)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 35, + "endLine": 19, + "endColumn": 44, + "problem": "ApiPathChanged", + "suggest": "", + "rule": "API path have changed - please update your imports accordingly (arkts-sdk-no-decl-with-duplicate-name)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 35, + "endLine": 19, + "endColumn": 44, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 19, + "endLine": 20, + "endColumn": 28, + "problem": "ApiPathChanged", + "suggest": "", + "rule": "API path have changed - please update your imports accordingly (arkts-sdk-no-decl-with-duplicate-name)", + "severity": "ERROR" + }, + { + "line": 16, + "column": 2, + "endLine": 16, + "endColumn": 7, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 2, + "endLine": 17, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 19, + "endLine": 19, + "endColumn": 28, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 57, + "endLine": 19, + "endColumn": 62, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 5, + "endLine": 22, + "endColumn": 9, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/api_path_changed.ets.json b/ets2panda/linter/test/sdkwhite/api_path_changed.ets.json new file mode 100755 index 0000000000..8af4f78669 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/api_path_changed.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file -- Gitee From 113e2c1ae0b53657022a304feb7a82dec12038cc Mon Sep 17 00:00:00 2001 From: ZhongNing Date: Wed, 9 Apr 2025 15:23:13 +0800 Subject: [PATCH 064/268] Add checks for arkts-sdk-Type-Query Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC0L18 Test scenarios: new tests added to the linter Signed-off-by: ZhongNing Change-Id: I3a5e29cd376167fff6344c3af7d83176d8d8d52c --- ets2panda/linter/src/lib/CookBookMsg.ts | 16 +++-- ets2panda/linter/src/lib/FaultAttrs.ts | 13 ++-- ets2panda/linter/src/lib/FaultDesc.ts | 1 + ets2panda/linter/src/lib/Problems.ts | 1 + ets2panda/linter/src/lib/TypeScriptLinter.ts | 49 +++++++++---- .../linter/src/lib/data/SdkWhitelist.json | 26 +++++++ .../src/lib/utils/consts/ArkTS2Rules.ts | 10 ++- .../lib/utils/consts/WhiteListProblemType.ts | 3 +- .../linter/test/sdkwhite/sdk_type_query.ets | 22 ++++++ .../sdkwhite/sdk_type_query.ets.args.json | 19 ++++++ .../sdkwhite/sdk_type_query.ets.arkts2.json | 68 +++++++++++++++++++ .../test/sdkwhite/sdk_type_query.ets.json | 28 ++++++++ 12 files changed, 225 insertions(+), 31 deletions(-) create mode 100755 ets2panda/linter/test/sdkwhite/sdk_type_query.ets create mode 100755 ets2panda/linter/test/sdkwhite/sdk_type_query.ets.args.json create mode 100755 ets2panda/linter/test/sdkwhite/sdk_type_query.ets.arkts2.json create mode 100755 ets2panda/linter/test/sdkwhite/sdk_type_query.ets.json diff --git a/ets2panda/linter/src/lib/CookBookMsg.ts b/ets2panda/linter/src/lib/CookBookMsg.ts index bb2f2d3c6d..177c831f8d 100644 --- a/ets2panda/linter/src/lib/CookBookMsg.ts +++ b/ets2panda/linter/src/lib/CookBookMsg.ts @@ -16,7 +16,7 @@ export const cookBookMsg: string[] = []; export const cookBookTag: string[] = []; -for (let i = 0; i <= 325; i++) { +for (let i = 0; i <= 316; i++) { cookBookMsg[i] = ''; } @@ -278,11 +278,13 @@ cookBookTag[306] = 'Cannot access typescript types directly (arkts-interop-acces cookBookTag[307] = 'Cannot invoke functions implemented in TypeScript (arkts-interop-ts-function)'; cookBookTag[308] = 'Type "void" has no instances.(arkts-sdk-limited-void-type)'; cookBookTag[309] = 'API no longer supports optional methods (sdk-optional-methods)'; -cookBookTag[312] = +cookBookTag[310] = 'Properties in "Sendable" classes and interfaces must have a Sendable data type (sdk-no-sendable-prop-types)'; -cookBookTag[313] = 'Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)'; -cookBookTag[314] = 'Indexed access is not supported for fields (sdk-no-props-by-index)'; -cookBookTag[325] = 'Constructor types are not supported - use lambda functions instead. (sdk-constructor-funcs)'; -cookBookTag[324] = +cookBookTag[311] = 'Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)'; +cookBookTag[312] = 'Indexed access is not supported for fields (sdk-no-props-by-index)'; +cookBookTag[313] = 'Constructor types are not supported - use lambda functions instead. (sdk-constructor-funcs)'; +cookBookTag[314] = 'Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)'; -cookBookTag[320] = 'API path have changed - please update your imports accordingly (arkts-sdk-no-decl-with-duplicate-name)'; +cookBookTag[315] = + 'API path have changed - please update your imports accordingly (arkts-sdk-no-decl-with-duplicate-name)'; +cookBookTag[316] = 'Using typeof as a type is not allowed in this API (arkts-sdk-Type-Query)'; diff --git a/ets2panda/linter/src/lib/FaultAttrs.ts b/ets2panda/linter/src/lib/FaultAttrs.ts index 442afd9752..7517fc2d3b 100644 --- a/ets2panda/linter/src/lib/FaultAttrs.ts +++ b/ets2panda/linter/src/lib/FaultAttrs.ts @@ -190,9 +190,10 @@ faultsAttrs[FaultID.InteropDirectAccessToTSTypes] = new FaultAttributes(306); faultsAttrs[FaultID.InteropTSFunctionInvoke] = new FaultAttributes(307); faultsAttrs[FaultID.LimitedVoidTypeFromSdk] = new FaultAttributes(308); faultsAttrs[FaultID.OptionalMethodFromSdk] = new FaultAttributes(309); -faultsAttrs[FaultID.SendablePropTypeFromSdk] = new FaultAttributes(312); -faultsAttrs[FaultID.ConstructorIfaceFromSdk] = new FaultAttributes(313); -faultsAttrs[FaultID.PropertyAccessByIndexFromSdk] = new FaultAttributes(314); -faultsAttrs[FaultID.ConstructorTypesDeprecated] = new FaultAttributes(325); -faultsAttrs[FaultID.QuotedHyphenPropsDeprecated] = new FaultAttributes(324); -faultsAttrs[FaultID.ApiPathChanged] = new FaultAttributes(320); +faultsAttrs[FaultID.SendablePropTypeFromSdk] = new FaultAttributes(310); +faultsAttrs[FaultID.ConstructorIfaceFromSdk] = new FaultAttributes(311); +faultsAttrs[FaultID.PropertyAccessByIndexFromSdk] = new FaultAttributes(312); +faultsAttrs[FaultID.ConstructorTypesDeprecated] = new FaultAttributes(313); +faultsAttrs[FaultID.QuotedHyphenPropsDeprecated] = new FaultAttributes(314); +faultsAttrs[FaultID.ApiPathChanged] = new FaultAttributes(315); +faultsAttrs[FaultID.SdkTypeQuery] = new FaultAttributes(316); diff --git a/ets2panda/linter/src/lib/FaultDesc.ts b/ets2panda/linter/src/lib/FaultDesc.ts index 3055e38edd..105baabb94 100644 --- a/ets2panda/linter/src/lib/FaultDesc.ts +++ b/ets2panda/linter/src/lib/FaultDesc.ts @@ -184,3 +184,4 @@ faultDesc[FaultID.PropertyAccessByIndexFromSdk] = 'property access by index from faultDesc[FaultID.ConstructorTypesDeprecated] = 'Constructor funcs'; faultDesc[FaultID.QuotedHyphenPropsDeprecated] = 'Quoted hyphen props deprecated'; faultDesc[FaultID.ApiPathChanged] = 'API path have changed'; +faultDesc[FaultID.SdkTypeQuery] = 'NO typeof as a type in API'; diff --git a/ets2panda/linter/src/lib/Problems.ts b/ets2panda/linter/src/lib/Problems.ts index 3050536dd7..3084036b12 100644 --- a/ets2panda/linter/src/lib/Problems.ts +++ b/ets2panda/linter/src/lib/Problems.ts @@ -185,6 +185,7 @@ export enum FaultID { ConstructorTypesDeprecated, QuotedHyphenPropsDeprecated, ApiPathChanged, + SdkTypeQuery, // this should always be last enum LAST_ID } diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index 9f2298f019..699fc53304 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -913,7 +913,7 @@ export class TypeScriptLinter { private handlePropertyAccessExpression(node: ts.Node): void { this.handleDoubleDollar(node); - + this.handleSdkTypeQuery(node as ts.PropertyAccessExpression); this.checkUnionTypes(node as ts.PropertyAccessExpression); if (ts.isCallExpression(node.parent) && node === node.parent.expression) { return; @@ -2988,9 +2988,10 @@ export class TypeScriptLinter { if (!(ts.isMethodSignature(declaration) && ts.isInterfaceDeclaration(interfaceDecl))) { return false; } - const isSameSdkFilePath = path. - normalize(interfaceDecl.getSourceFile().fileName). - endsWith(indexedTypeSdkInfo.file_path[0]); + const declFileFromJson = path.normalize(interfaceDecl.getSourceFile().fileName); + const declFileFromSdk = + indexedTypeSdkInfo.file_path.length > 0 ? path.normalize(indexedTypeSdkInfo.file_path[0]) : ''; + const isSameSdkFilePath = declFileFromJson.endsWith(declFileFromSdk); const interfaceNameData = indexedTypeSdkInfo.api_info.parent_api[0].api_name; const isSameInterfaceName = interfaceDecl.name.getText() === interfaceNameData; return isSameSdkFilePath && isSameInterfaceName; @@ -5435,16 +5436,18 @@ export class TypeScriptLinter { private handleQuotedHyphenPropsDeprecatedOnVarDecl(node: ts.VariableDeclaration, apiName: string): void { const initializer = node.initializer; - if (initializer && ts.isObjectLiteralExpression(initializer)) { - initializer.properties.forEach((property) => { - if (ts.isPropertyAssignment(property)) { - const propertyName = property.name.getText(); - if (propertyName === apiName) { - this.incrementCounters(property.name, FaultID.QuotedHyphenPropsDeprecated); - } - } - }); + if (!(initializer && ts.isObjectLiteralExpression(initializer))) { + return; } + initializer.properties.forEach((property) => { + if (!ts.isPropertyAssignment(property)) { + return; + } + const propertyName = property.name.getText(); + if (propertyName === apiName) { + this.incrementCounters(property.name, FaultID.QuotedHyphenPropsDeprecated); + } + }); } private handleQuotedHyphenPropsDeprecatedOnFunDecl(node: ts.FunctionDeclaration, apiName: string): void { @@ -5509,4 +5512,24 @@ export class TypeScriptLinter { } } } + + private handleSdkTypeQuery(decl: ts.PropertyAccessExpression): void { + if (!this.options.arkts2 || !ts.isPropertyAccessExpression(decl)) { + return; + } + if (ts.isPropertyAccessExpression(decl.expression)) { + const importApiName = ts.isIdentifier(decl.expression.expression) && decl.expression.expression.text || ''; + const sdkInfos = importApiName && this.interfaceMap.get(importApiName); + if (!sdkInfos) { + return; + } + const apiName = ts.isIdentifier(decl.name) && decl.name.text || ''; + const matchedApi = [...sdkInfos].find((sdkInfo) => { + return sdkInfo.api_name === apiName; + }); + if (matchedApi) { + this.incrementCounters(decl.name, FaultID.SdkTypeQuery); + } + } + } } diff --git a/ets2panda/linter/src/lib/data/SdkWhitelist.json b/ets2panda/linter/src/lib/data/SdkWhitelist.json index 9479aeb666..8aee8281b8 100644 --- a/ets2panda/linter/src/lib/data/SdkWhitelist.json +++ b/ets2panda/linter/src/lib/data/SdkWhitelist.json @@ -576,6 +576,32 @@ "methd_return_type": "TextStyle", "codeKind": 264 } + }, + { + "import_path": [ + "@ohos.worker.d.ts", + "@kit.ArkTS" + ], + "file_path": ["api/@ohos.worker.d.ts"], + "is_global": false, + "api_info": { + "problem": "TypeQuery", + "api_name": "self", + "api_type": "PropertySignature", + "api_optional": false, + "api_auto_fix": false, + "api_auto_fix_context": "", + "target_type": "", + "api_func_args": [], + "parent_api": [ + { + "api_name": "DedicatedWorkerGlobalScope", + "api_type": "InterfaceDeclaration" + } + ], + "methd_return_type": "WorkerGlobalScope & typeof globalThis", + "codeKind": 170 + } } ] } \ No newline at end of file diff --git a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts index 41b8552faf..c2827aa4db 100644 --- a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts +++ b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts @@ -71,7 +71,11 @@ export const arkts2Rules: number[] = [ 307, 308, 309, - 325, - 324, - 320 + 310, + 311, + 312, + 313, + 314, + 315, + 316 ]; diff --git a/ets2panda/linter/src/lib/utils/consts/WhiteListProblemType.ts b/ets2panda/linter/src/lib/utils/consts/WhiteListProblemType.ts index c99ec1a02b..084fa5f156 100644 --- a/ets2panda/linter/src/lib/utils/consts/WhiteListProblemType.ts +++ b/ets2panda/linter/src/lib/utils/consts/WhiteListProblemType.ts @@ -28,5 +28,4 @@ export enum SdkProblem { ComputedPropertyName = 'ComputedPropertyName' } - -export const ARKTS_WHITE_API_PATH_TEXTSTYLE = 'component/styled_string.d.ts'; \ No newline at end of file +export const ARKTS_WHITE_API_PATH_TEXTSTYLE = 'component/styled_string.d.ts'; diff --git a/ets2panda/linter/test/sdkwhite/sdk_type_query.ets b/ets2panda/linter/test/sdkwhite/sdk_type_query.ets new file mode 100755 index 0000000000..e975f42d4d --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/sdk_type_query.ets @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2023-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {worker} from '@kit.ArkTS'; + +worker.parentPort.self; + +const self = worker.parentPort.self; + +console.log(worker.parentPort.self) \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/sdk_type_query.ets.args.json b/ets2panda/linter/test/sdkwhite/sdk_type_query.ets.args.json new file mode 100755 index 0000000000..3ef4496a81 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/sdk_type_query.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} diff --git a/ets2panda/linter/test/sdkwhite/sdk_type_query.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/sdk_type_query.ets.arkts2.json new file mode 100755 index 0000000000..d13b1aa522 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/sdk_type_query.ets.arkts2.json @@ -0,0 +1,68 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 35, + "problem": "LimitedStdLibApi", + "suggest": "", + "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 19, + "endLine": 18, + "endColumn": 23, + "problem": "SdkTypeQuery", + "suggest": "", + "rule": "Using typeof as a type is not allowed in this API (arkts-sdk-Type-Query)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 7, + "endLine": 20, + "endColumn": 36, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 32, + "endLine": 20, + "endColumn": 36, + "problem": "SdkTypeQuery", + "suggest": "", + "rule": "Using typeof as a type is not allowed in this API (arkts-sdk-Type-Query)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 31, + "endLine": 22, + "endColumn": 35, + "problem": "SdkTypeQuery", + "suggest": "", + "rule": "Using typeof as a type is not allowed in this API (arkts-sdk-Type-Query)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/sdk_type_query.ets.json b/ets2panda/linter/test/sdkwhite/sdk_type_query.ets.json new file mode 100755 index 0000000000..41b84cda9d --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/sdk_type_query.ets.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 20, + "column": 7, + "endLine": 20, + "endColumn": 36, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + } + ] +} \ No newline at end of file -- Gitee From 98eb34185afd98a26e00ffb5916dffb31a588aba Mon Sep 17 00:00:00 2001 From: ZhongNing Date: Tue, 8 Apr 2025 19:32:23 +0800 Subject: [PATCH 065/268] fix issue for arkts-no-structural-typing Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBSOHR Test scenarios: new tests added to the linter Signed-off-by: ZhongNing --- ets2panda/linter/src/lib/TypeScriptLinter.ts | 198 ++++++++++++++++++ .../linter/test/main/structural_identity.ets | 35 ++-- .../main/structural_identity.ets.arkts2.json | 24 +-- .../test/main/structural_identity.ets.json | 10 + 4 files changed, 242 insertions(+), 25 deletions(-) diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index 699fc53304..add11d0205 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -97,6 +97,15 @@ import { ApiList } from './utils/consts/SdkWhitelist'; import * as apiWhiteList from './data/SdkWhitelist.json'; import { SdkProblem, ARKTS_WHITE_API_PATH_TEXTSTYLE } from './utils/consts/WhiteListProblemType'; +interface InterfaceSymbolTypeResult { + propNames: string[]; + typeNames: string[]; + allProps: Map; +} +interface InterfaceSymbolTypePropertyNames { + propertyNames: string[]; + typeNames: string[]; +} export class TypeScriptLinter { totalVisitedNodes: number = 0; nodeCounters: number[] = []; @@ -1895,6 +1904,7 @@ export class TypeScriptLinter { this.handleInvalidIdentifier(tsVarDecl); this.checkAssignmentNumericSemanticsly(tsVarDecl); this.checkTypeFromSdk(tsVarDecl.type); + this.handleNoStructuralTyping(tsVarDecl); } private checkTypeFromSdk(type: ts.TypeNode | undefined): void { @@ -1917,6 +1927,194 @@ export class TypeScriptLinter { } } + private static extractUsedObjectType(tsVarDecl: ts.VariableDeclaration): InterfaceSymbolTypePropertyNames | null { + const result = { + propertyNames: [] as string[], + typeNames: [] as string[] + }; + + if (!this.isObjectLiteralWithProperties(tsVarDecl)) { + return null; + } + + this.processObjectLiteralProperties(tsVarDecl.initializer as ts.ObjectLiteralExpression, result); + return result.propertyNames.length > 0 ? result : null; + } + + private static isObjectLiteralWithProperties(tsVarDecl: ts.VariableDeclaration): boolean { + return ( + tsVarDecl.initializer !== undefined && + ts.isObjectLiteralExpression(tsVarDecl.initializer) && + tsVarDecl.initializer.properties.length > 0 + ); + } + + private static processObjectLiteralProperties( + objectLiteral: ts.ObjectLiteralExpression, + result: { propertyNames: string[]; typeNames: string[] } + ): void { + objectLiteral.properties.forEach((property) => { + if (!ts.isPropertyAssignment(property)) { + return; + } + + const propertyName = property.name.getText(); + result.propertyNames.push(propertyName); + + if (ts.isNewExpression(property.initializer)) { + const typeName = property.initializer.expression.getText(); + result.typeNames.push(typeName); + } + }); + } + + private interfaceSymbolType(tsVarDecl: ts.VariableDeclaration): InterfaceSymbolTypeResult | null { + if (!tsVarDecl.type) { + return null; + } + + const typeSymbol = this.getTypeSymbol(tsVarDecl); + if (!typeSymbol) { + return null; + } + + const interfaceType = this.getInterfaceType(tsVarDecl); + if (!interfaceType) { + return null; + } + + return this.collectInterfaceProperties(interfaceType, tsVarDecl); + } + + private getTypeSymbol(tsVarDecl: ts.VariableDeclaration): ts.Symbol | null { + const typeNode = ts.isTypeReferenceNode(tsVarDecl.type!) ? tsVarDecl.type.typeName : tsVarDecl.type; + return this.tsTypeChecker.getSymbolAtLocation(typeNode!) ?? null; + } + + private getInterfaceType(tsVarDecl: ts.VariableDeclaration): ts.InterfaceType | null { + const type = this.tsTypeChecker.getTypeAtLocation(tsVarDecl.type!); + return type && (type as ts.ObjectType).objectFlags & ts.ObjectFlags.Interface ? (type as ts.InterfaceType) : null; + } + + private collectInterfaceProperties( + interfaceType: ts.InterfaceType, + tsVarDecl: ts.VariableDeclaration + ): InterfaceSymbolTypeResult { + const result = { + propNames: [] as string[], + typeNames: [] as string[], + allProps: new Map() + }; + + this.collectPropertiesRecursive(interfaceType, result, tsVarDecl); + return result; + } + + private collectPropertiesRecursive( + type: ts.Type, + result: { + propNames: string[]; + typeNames: string[]; + allProps: Map; + }, + tsVarDecl: ts.VariableDeclaration + ): void { + type.getProperties().forEach((property) => { + this.collectProperty(property, result, tsVarDecl); + }); + + if ('getBaseTypes' in type) { + type.getBaseTypes()?.forEach((baseType) => { + this.collectPropertiesRecursive(baseType, result, tsVarDecl); + }); + } + } + + private collectProperty( + property: ts.Symbol, + result: { + propNames: string[]; + typeNames: string[]; + allProps: Map; + }, + tsVarDecl: ts.VariableDeclaration + ): void { + const propName = property.getName(); + const propType = this.tsTypeChecker.getTypeOfSymbolAtLocation( + property, + property.valueDeclaration || tsVarDecl.type! + ); + const typeString = this.tsTypeChecker.typeToString(propType); + + if (!result.allProps.has(propName)) { + result.propNames.push(propName); + result.typeNames.push(typeString); + result.allProps.set(propName, typeString); + } + } + + handleNoStructuralTyping(tsVarDecl: ts.VariableDeclaration): void { + const { interfaceInfo, actualUsage } = this.getTypeComparisonData(tsVarDecl); + if (!interfaceInfo || !actualUsage) { + return; + } + if (!this.options.arkts2) { + return; + } + const actualMap = TypeScriptLinter.createActualTypeMap(actualUsage); + const hasMismatch = TypeScriptLinter.checkTypeMismatches(interfaceInfo, actualMap); + + if (hasMismatch) { + this.incrementCounters(tsVarDecl, FaultID.StructuralIdentity); + } + } + + private getTypeComparisonData(tsVarDecl: ts.VariableDeclaration): { + interfaceInfo: { propNames: string[]; typeNames: string[]; allProps: Map } | null; + actualUsage: { + propertyNames: string[]; + typeNames: string[]; + } | null; + } { + return { + interfaceInfo: this.interfaceSymbolType(tsVarDecl), + actualUsage: TypeScriptLinter.extractUsedObjectType(tsVarDecl) + }; + } + + private static createActualTypeMap(actualUsage: { + propertyNames: string[]; + typeNames: string[]; + }): Map { + const actualMap = new Map(); + actualUsage.propertyNames.forEach((prop, index) => { + if (actualUsage.typeNames[index]) { + actualMap.set(prop, actualUsage.typeNames[index]); + } + }); + return actualMap; + } + + private static checkTypeMismatches( + interfaceInfo: { allProps: Map }, + actualMap: Map + ): boolean { + let hasMismatch = false; + + interfaceInfo.allProps.forEach((expectedType, prop) => { + if (!actualMap.has(prop)) { + return; + } + + const actualType = actualMap.get(prop)!; + if (expectedType !== actualType) { + hasMismatch = true; + } + }); + + return hasMismatch; + } + private handleDeclarationDestructuring(decl: ts.VariableDeclaration | ts.ParameterDeclaration): void { const faultId = ts.isVariableDeclaration(decl) ? FaultID.DestructuringDeclaration : FaultID.DestructuringParameter; if (ts.isObjectBindingPattern(decl.name)) { diff --git a/ets2panda/linter/test/main/structural_identity.ets b/ets2panda/linter/test/main/structural_identity.ets index 8ecde15cd2..eae4133097 100644 --- a/ets2panda/linter/test/main/structural_identity.ets +++ b/ets2panda/linter/test/main/structural_identity.ets @@ -671,16 +671,25 @@ function test_10(): B_10 { return obj1; // NOT OK } -let task1: taskpool.Task = new taskpool.Task(funObject1); - taskpool.execute(task1).then((value:Object) => { - console.info("result test taskpool: " + JSON.stringify(value)); - let aa = value as Array; - expect(aa[0]).assertEqual('toString result: bb : cc') - expect(aa[1]).assertEqual(200) - expect(aa[2]).assertEqual('testtoString') - }) -function funObject1():Array{ - let aa:ObjectInfo1=new ObjectInfo1('bb','cc') - let ee:Array=[aa.toString(),aa.toString(2),aa.toString('test')] - return ee; -} \ No newline at end of file +class MyObj2 { + +} +class MyObj1 { + +} +class MyObj3 { + +} +interface goodPerson extends IPerson { + like: MyObj2, + like1: MyObj3 + } + + let lily:goodPerson = { + like: new MyObj1(), + name: 'Alice', + age: 30, + sayHello:()=> { + return new MyObj2() + } + } \ No newline at end of file diff --git a/ets2panda/linter/test/main/structural_identity.ets.arkts2.json b/ets2panda/linter/test/main/structural_identity.ets.arkts2.json index 7ddd4b230e..2546e534df 100644 --- a/ets2panda/linter/test/main/structural_identity.ets.arkts2.json +++ b/ets2panda/linter/test/main/structural_identity.ets.arkts2.json @@ -1555,23 +1555,23 @@ "severity": "ERROR" }, { - "line": 674, - "column": 32, - "endLine": 674, - "endColumn": 45, - "problem": "DynamicCtorCall", + "line": 688, + "column": 6, + "endLine": 695, + "endColumn": 3, + "problem": "StructuralIdentity", "suggest": "", - "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "rule": "Structural typing is not supported (arkts-no-structural-typing)", "severity": "ERROR" }, { - "line": 683, - "column": 26, - "endLine": 683, - "endColumn": 37, - "problem": "DynamicCtorCall", + "line": 688, + "column": 24, + "endLine": 688, + "endColumn": 25, + "problem": "ObjectLiteralNoContextType", "suggest": "", - "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/main/structural_identity.ets.json b/ets2panda/linter/test/main/structural_identity.ets.json index e2e91f0c1d..ba557cfd43 100644 --- a/ets2panda/linter/test/main/structural_identity.ets.json +++ b/ets2panda/linter/test/main/structural_identity.ets.json @@ -643,6 +643,16 @@ "suggest": "", "rule": "Structural typing is not supported (arkts-no-structural-typing)", "severity": "ERROR" + }, + { + "line": 688, + "column": 24, + "endLine": 688, + "endColumn": 25, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" } ] } \ No newline at end of file -- Gitee From facd65aaca94998ae018cf118406900f86b987c0 Mon Sep 17 00:00:00 2001 From: cihatfurkaneken Date: Mon, 14 Apr 2025 12:06:09 +0300 Subject: [PATCH 066/268] add limited-stdlib-no-import-concurrency rule Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBZK0H Signed-off-by: cihatfurkaneken --- ets2panda/linter/src/lib/CookBookMsg.ts | 1 + ets2panda/linter/src/lib/FaultAttrs.ts | 1 + ets2panda/linter/src/lib/FaultDesc.ts | 1 + ets2panda/linter/src/lib/Problems.ts | 1 + ets2panda/linter/src/lib/TypeScriptLinter.ts | 37 +++++++++++++- .../src/lib/utils/consts/ArkTS2Rules.ts | 3 +- .../src/lib/utils/consts/LimitedStdAPI.ts | 5 ++ .../test/main/no_import_concurrency.ets | 22 +++++++++ .../main/no_import_concurrency.ets.args.json | 19 ++++++++ .../no_import_concurrency.ets.arkts2.json | 48 +++++++++++++++++++ .../test/main/no_import_concurrency.ets.json | 17 +++++++ 11 files changed, 153 insertions(+), 2 deletions(-) create mode 100644 ets2panda/linter/test/main/no_import_concurrency.ets create mode 100644 ets2panda/linter/test/main/no_import_concurrency.ets.args.json create mode 100644 ets2panda/linter/test/main/no_import_concurrency.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/no_import_concurrency.ets.json diff --git a/ets2panda/linter/src/lib/CookBookMsg.ts b/ets2panda/linter/src/lib/CookBookMsg.ts index 177c831f8d..4a5677c9d8 100644 --- a/ets2panda/linter/src/lib/CookBookMsg.ts +++ b/ets2panda/linter/src/lib/CookBookMsg.ts @@ -288,3 +288,4 @@ cookBookTag[314] = cookBookTag[315] = 'API path have changed - please update your imports accordingly (arkts-sdk-no-decl-with-duplicate-name)'; cookBookTag[316] = 'Using typeof as a type is not allowed in this API (arkts-sdk-Type-Query)'; +cookBookTag[321] = 'Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)'; diff --git a/ets2panda/linter/src/lib/FaultAttrs.ts b/ets2panda/linter/src/lib/FaultAttrs.ts index 7517fc2d3b..091ca6410f 100644 --- a/ets2panda/linter/src/lib/FaultAttrs.ts +++ b/ets2panda/linter/src/lib/FaultAttrs.ts @@ -197,3 +197,4 @@ faultsAttrs[FaultID.ConstructorTypesDeprecated] = new FaultAttributes(313); faultsAttrs[FaultID.QuotedHyphenPropsDeprecated] = new FaultAttributes(314); faultsAttrs[FaultID.ApiPathChanged] = new FaultAttributes(315); faultsAttrs[FaultID.SdkTypeQuery] = new FaultAttributes(316); +faultsAttrs[FaultID.LimitedStdLibNoImportConcurrency] = new FaultAttributes(321); diff --git a/ets2panda/linter/src/lib/FaultDesc.ts b/ets2panda/linter/src/lib/FaultDesc.ts index 105baabb94..09e2232d83 100644 --- a/ets2panda/linter/src/lib/FaultDesc.ts +++ b/ets2panda/linter/src/lib/FaultDesc.ts @@ -185,3 +185,4 @@ faultDesc[FaultID.ConstructorTypesDeprecated] = 'Constructor funcs'; faultDesc[FaultID.QuotedHyphenPropsDeprecated] = 'Quoted hyphen props deprecated'; faultDesc[FaultID.ApiPathChanged] = 'API path have changed'; faultDesc[FaultID.SdkTypeQuery] = 'NO typeof as a type in API'; +faultDesc[FaultID.LimitedStdLibNoImportConcurrency] = 'Import Concurrency Deprecated'; diff --git a/ets2panda/linter/src/lib/Problems.ts b/ets2panda/linter/src/lib/Problems.ts index 3084036b12..88e8e4d311 100644 --- a/ets2panda/linter/src/lib/Problems.ts +++ b/ets2panda/linter/src/lib/Problems.ts @@ -186,6 +186,7 @@ export enum FaultID { QuotedHyphenPropsDeprecated, ApiPathChanged, SdkTypeQuery, + LimitedStdLibNoImportConcurrency, // this should always be last enum LAST_ID } diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index add11d0205..fd590c19af 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -65,7 +65,8 @@ import { LIMITED_STD_GLOBAL_API, LIMITED_STD_OBJECT_API, LIMITED_STD_PROXYHANDLER_API, - LIMITED_STD_REFLECT_API + LIMITED_STD_REFLECT_API, + MODULE_IMPORTS } from './utils/consts/LimitedStdAPI'; import { SupportedStdCallApiChecker } from './utils/functions/SupportedStdCallAPI'; import { identiferUseInValueContext } from './utils/functions/identiferUseInValueContext'; @@ -850,6 +851,7 @@ export class TypeScriptLinter { this.handleSharedModuleNoSideEffectImport(importDeclNode); this.handleInvalidIdentifier(importDeclNode); this.checkWorkerImport(importDeclNode); + this.checkStdLibConcurrencyImport(importDeclNode); } private handleSdkSendable(tsStringLiteral: ts.StringLiteral): void { @@ -5730,4 +5732,37 @@ export class TypeScriptLinter { } } } + + private checkStdLibConcurrencyImport(importDeclaration: ts.ImportDeclaration): void { + if (!this.options.arkts2) { + return; + } + + const importClause = importDeclaration.importClause; + if (!importClause) { + return; + } + + const moduleName = (importDeclaration.moduleSpecifier as ts.StringLiteral).text; + const expectedImports = MODULE_IMPORTS[moduleName]; + if (!expectedImports) { + return; + } + + const namedBindings = importClause.namedBindings; + const defaultImportName = importClause.name?.getText(); + + if (defaultImportName && expectedImports.includes(defaultImportName)) { + this.incrementCounters(importDeclaration, FaultID.LimitedStdLibNoImportConcurrency); + } + + if (namedBindings && ts.isNamedImports(namedBindings)) { + for (const element of namedBindings.elements) { + const name = element.name.getText(); + if (expectedImports.includes(name)) { + this.incrementCounters(importDeclaration, FaultID.LimitedStdLibNoImportConcurrency); + } + } + } + } } diff --git a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts index c2827aa4db..a59849d2aa 100644 --- a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts +++ b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts @@ -77,5 +77,6 @@ export const arkts2Rules: number[] = [ 313, 314, 315, - 316 + 316, + 321 ]; diff --git a/ets2panda/linter/src/lib/utils/consts/LimitedStdAPI.ts b/ets2panda/linter/src/lib/utils/consts/LimitedStdAPI.ts index 6853676eee..fb9fcb6e2c 100644 --- a/ets2panda/linter/src/lib/utils/consts/LimitedStdAPI.ts +++ b/ets2panda/linter/src/lib/utils/consts/LimitedStdAPI.ts @@ -151,3 +151,8 @@ export const LIMITED_STD_API = new Map = { + '@kit.ArkTS': ['taskpool', 'ArkTSUtils'], + '@ohos.process': ['process'] +}; diff --git a/ets2panda/linter/test/main/no_import_concurrency.ets b/ets2panda/linter/test/main/no_import_concurrency.ets new file mode 100644 index 0000000000..3414485f76 --- /dev/null +++ b/ets2panda/linter/test/main/no_import_concurrency.ets @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +import { taskpool }from '@kit.ArkTS'; +import { anyClass } from '@kit.ArkTS'; //legal +import process from '@ohos.process'; +import fooke from '@ohos.process'; //legal +import { fooClass } from '@ohos.process'; //legal +import { ArkTSUtils } from '@kit.ArkTS' \ No newline at end of file diff --git a/ets2panda/linter/test/main/no_import_concurrency.ets.args.json b/ets2panda/linter/test/main/no_import_concurrency.ets.args.json new file mode 100644 index 0000000000..d8d3390ad9 --- /dev/null +++ b/ets2panda/linter/test/main/no_import_concurrency.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/no_import_concurrency.ets.arkts2.json b/ets2panda/linter/test/main/no_import_concurrency.ets.arkts2.json new file mode 100644 index 0000000000..66ab81cc70 --- /dev/null +++ b/ets2panda/linter/test/main/no_import_concurrency.ets.arkts2.json @@ -0,0 +1,48 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 38, + "problem": "LimitedStdLibNoImportConcurrency", + "suggest": "", + "rule": "Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 37, + "problem": "LimitedStdLibNoImportConcurrency", + "suggest": "", + "rule": "Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 1, + "endLine": 22, + "endColumn": 40, + "problem": "LimitedStdLibNoImportConcurrency", + "suggest": "", + "rule": "Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/no_import_concurrency.ets.json b/ets2panda/linter/test/main/no_import_concurrency.ets.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/no_import_concurrency.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file -- Gitee From 68874345b26fab3495adc2182d3f69aad80e1e23 Mon Sep 17 00:00:00 2001 From: zhongning Date: Mon, 14 Apr 2025 17:58:32 +0800 Subject: [PATCH 067/268] Fix issue for arkts-array-index-expr-type Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC0ZRP Test scenarios: new tests added to the linter Signed-off-by: zhongning --- ets2panda/linter/src/lib/TypeScriptLinter.ts | 14 +++++++++----- .../linter/src/lib/utils/consts/StringLiteral.ts | 5 ++++- .../linter/test/main/array_index_expr_type.ets | 14 +++++++++++++- .../main/array_index_expr_type.ets.arkts2.json | 10 ++++++++++ 4 files changed, 36 insertions(+), 7 deletions(-) diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index fd590c19af..b621a657d7 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -34,8 +34,10 @@ import { STRINGLITERAL_NUMBER, STRINGLITERAL_STRING, STRINGLITERAL_INT, - STRINGLITERAL_ANY -} from './utils/consts/StringLiteral'; + STRINGLITERAL_ANY, + STRINGLITERAL_BYTE, + STRINGLITERAL_SHORT, + STRINGLITERAL_LONG } from './utils/consts/StringLiteral'; import { NON_INITIALIZABLE_PROPERTY_CLASS_DECORATORS, NON_INITIALIZABLE_PROPERTY_DECORATORS, @@ -2996,9 +2998,12 @@ export class TypeScriptLinter { const argExpr = TypeScriptLinter.getUnwrappedArgumentExpression(expr.argumentExpression); + const validStringLiteralTypes = [STRINGLITERAL_INT, STRINGLITERAL_BYTE, STRINGLITERAL_SHORT, STRINGLITERAL_LONG]; + const argTypeString = this.tsTypeChecker.typeToString(argType); + if (this.tsUtils.isNumberLikeType(argType)) { this.handleNumericArgument(argExpr); - } else if (this.tsTypeChecker.typeToString(argType) !== STRINGLITERAL_INT) { + } else if (!validStringLiteralTypes.includes(argTypeString)) { this.incrementCounters(argExpr, FaultID.ArrayIndexExprType); } } @@ -3037,8 +3042,7 @@ export class TypeScriptLinter { const initializerNumber = isNumericInitializer ? Number(initializerText) : NaN; const isUnsafeNumber = isNumericInitializer && !Number.isInteger(initializerNumber); const isConstDeclaration = firstDeclaration.parent.flags === ts.NodeFlags.Let; - const isUndefinedButNotMaxSafeInteger = - initializerText === 'undefined' && argExpr.getText() !== 'Number.MAX_SAFE_INTEGER'; + const isUndefinedButNotMaxSafeInteger = initializerText === 'undefined'; if ( isUnsafeNumber || diff --git a/ets2panda/linter/src/lib/utils/consts/StringLiteral.ts b/ets2panda/linter/src/lib/utils/consts/StringLiteral.ts index 27a4b2412d..323023487f 100644 --- a/ets2panda/linter/src/lib/utils/consts/StringLiteral.ts +++ b/ets2panda/linter/src/lib/utils/consts/StringLiteral.ts @@ -17,4 +17,7 @@ export const STRINGLITERAL_NUMBER = 'number'; export const STRINGLITERAL_NUMBER_ARRAY = 'number[]'; export const STRINGLITERAL_STRING = 'string'; export const STRINGLITERAL_INT = 'int'; -export const STRINGLITERAL_ANY = 'ANY'; +export const STRINGLITERAL_BYTE = 'byte'; +export const STRINGLITERAL_SHORT = 'short'; +export const STRINGLITERAL_LONG = 'long'; +export const STRINGLITERAL_ANY = 'ANY'; \ No newline at end of file diff --git a/ets2panda/linter/test/main/array_index_expr_type.ets b/ets2panda/linter/test/main/array_index_expr_type.ets index 5c8d438eaf..c8eed0c0d8 100644 --- a/ets2panda/linter/test/main/array_index_expr_type.ets +++ b/ets2panda/linter/test/main/array_index_expr_type.ets @@ -70,4 +70,16 @@ arr1[+0]; arr1[-0]; arr1[+1]; arr1[-1]; -arr1[1.1 as number]; \ No newline at end of file +arr1[1.1 as number]; + +let a:short = 1; +let b:byte = 1; +let c:int = 1; +let d:long = 1; + +let arr:number[] = [1,2,3] + +arr[a] = 1; +arr[b] = 1; +arr[c] = 1; +arr[d] = 1; \ No newline at end of file diff --git a/ets2panda/linter/test/main/array_index_expr_type.ets.arkts2.json b/ets2panda/linter/test/main/array_index_expr_type.ets.arkts2.json index 5e19a4451b..16b8d6a258 100644 --- a/ets2panda/linter/test/main/array_index_expr_type.ets.arkts2.json +++ b/ets2panda/linter/test/main/array_index_expr_type.ets.arkts2.json @@ -264,6 +264,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 32, + "column": 20, + "endLine": 32, + "endColumn": 43, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, { "line": 35, "column": 5, -- Gitee From 34fad64269375999c9777179424154df4518176e Mon Sep 17 00:00:00 2001 From: sniperc96 Date: Fri, 11 Apr 2025 19:24:17 +0800 Subject: [PATCH 068/268] [ArkUI] fix bug Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC0EGK Signed-off-by: sniperc96 --- ets2panda/linter/src/lib/TypeScriptLinter.ts | 166 +- .../linter/src/lib/autofixes/Autofixer.ts | 82 +- .../src/lib/utils/consts/ArkuiConstants.ts | 2 +- ...atable_extend_decorator_1.ets.autofix.json | 9 +- .../main/animatable_extend_decorator_2.ets | 2 +- .../linter/test/main/data_observation_1.ets | 62 +- .../main/data_observation_1.ets.arkts2.json | 258 ++- .../main/data_observation_1.ets.autofix.json | 337 +++- .../test/main/data_observation_1.ets.json | 13 +- .../linter/test/main/data_observation_2.ets | 81 +- .../main/data_observation_2.ets.arkts2.json | 63 +- .../main/data_observation_2.ets.autofix.json | 70 +- .../linter/test/main/dollar_binding_1.ets | 4 +- .../main/dollar_binding_1.ets.arkts2.json | 30 +- .../main/dollar_binding_1.ets.autofix.json | 66 +- .../linter/test/main/dollar_binding_2.ets | 6 +- .../test/main/double_dollar_binding_1.ets | 6 +- .../double_dollar_binding_1.ets.arkts2.json | 58 +- .../double_dollar_binding_1.ets.autofix.json | 77 +- .../test/main/double_dollar_binding_2.ets | 8 +- .../test/main/double_excla_binding_1.ets | 12 +- .../double_excla_binding_1.ets.arkts2.json | 272 ++- .../double_excla_binding_1.ets.autofix.json | 324 +++- .../test/main/double_excla_binding_2.ets | 44 +- .../double_excla_binding_2.ets.arkts2.json | 4 +- .../double_excla_binding_2.ets.autofix.json | 4 +- .../test/main/double_excla_binding_2.ets.json | 4 +- .../main/extend_decorator_1.ets.autofix.json | 7 +- .../linter/test/main/extend_decorator_2.ets | 2 +- .../linter/test/main/interface_import_1.ets | 22 +- .../main/interface_import_1.ets.arkts2.json | 106 +- .../main/interface_import_1.ets.autofix.json | 138 +- .../linter/test/main/interface_import_2.ets | 39 +- .../main/interface_import_2.ets.arkts2.json | 60 +- .../main/interface_import_2.ets.autofix.json | 60 +- .../test/main/interface_import_2.ets.json | 54 +- .../main/invalid_identifier.ets.arkts2.json | 30 + .../literals_as_prop_names.ets.autofix.json | 3 +- .../main/numeric_semantics.ets.autofix.json | 1603 +++++++++-------- .../main/provide_annotation_1.ets.arkts2.json | 254 ++- .../provide_annotation_1.ets.autofix.json | 304 ++-- .../main/provide_annotation_2.ets.arkts2.json | 214 ++- .../provide_annotation_2.ets.autofix.json | 236 ++- .../styles_decorator_anon_1.ets.autofix.json | 7 +- .../test/main/styles_decorator_anon_2.ets | 2 + .../styles_decorator_anon_2.ets.arkts2.json | 73 +- .../styles_decorator_anon_2.ets.autofix.json | 80 +- .../styles_decorator_global_1.ets.arkts2.json | 10 + ...styles_decorator_global_1.ets.autofix.json | 18 +- .../test/main/styles_decorator_global_2.ets | 2 + .../styles_decorator_global_2.ets.arkts2.json | 73 +- ...styles_decorator_global_2.ets.autofix.json | 80 +- .../test/main/styles_decorator_struct_1.ets | 11 + .../styles_decorator_struct_1.ets.arkts2.json | 92 +- ...styles_decorator_struct_1.ets.autofix.json | 113 +- .../main/styles_decorator_struct_1.ets.json | 4 +- .../test/main/styles_decorator_struct_2.ets | 13 + .../styles_decorator_struct_2.ets.arkts2.json | 102 +- ...styles_decorator_struct_2.ets.autofix.json | 109 +- .../main/styles_decorator_struct_2.ets.json | 4 +- .../sdkwhite/api_path_changed.ets.arkts2.json | 20 + 61 files changed, 3639 insertions(+), 2370 deletions(-) mode change 100755 => 100644 ets2panda/linter/test/main/invalid_identifier.ets.arkts2.json mode change 100755 => 100644 ets2panda/linter/test/main/numeric_semantics.ets.autofix.json mode change 100755 => 100644 ets2panda/linter/test/sdkwhite/api_path_changed.ets.arkts2.json diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index b621a657d7..69145df2b4 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -4997,7 +4997,7 @@ export class TypeScriptLinter { } } - return this.importedInterfaces.has(callExpr.expression.getText()); + return this.interfacesAlreadyImported.has(callExpr.expression.getText()); } private handleDoubleDollar(node: ts.Node): void { @@ -5236,22 +5236,25 @@ export class TypeScriptLinter { } } - interfaceIdentifiers: ts.Identifier[] = []; + interfacesNeedToAlarm: ts.Identifier[] = []; interfacesNeedToImport: Set = new Set(); - importedInterfaces: Set = new Set(); + interfacesAlreadyImported: Set = new Set(); private handleInterfaceImport(identifier: ts.Identifier): void { if (!this.options.arkts2) { return; } - const name = identifier.getText(); if (this.shouldSkipIdentifier(identifier)) { return; } - this.interfaceIdentifiers.push(identifier); - this.interfacesNeedToImport.add(name); + const name = identifier.getText(); + if (!this.interfacesNeedToImport.has(name)) { + this.interfacesNeedToImport.add(name); + } + + this.interfacesNeedToAlarm.push(identifier); } private shouldSkipIdentifier(identifier: ts.Identifier): boolean { @@ -5281,7 +5284,7 @@ export class TypeScriptLinter { } } - return this.interfacesNeedToImport.has(name) || this.importedInterfaces.has(name); + return this.interfacesAlreadyImported.has(name); } private processInterfacesToImport(): void { @@ -5289,22 +5292,22 @@ export class TypeScriptLinter { return; } - this.interfaceIdentifiers.forEach((identifier, index) => { - if (index === this.interfaceIdentifiers.length - 1) { - const autofix = this.autofixer?.fixSingleImport( + this.interfacesNeedToAlarm.forEach((identifier, index) => { + if (index === this.interfacesNeedToAlarm.length - 1) { + const autofix = this.autofixer?.fixInterfaceImport( this.interfacesNeedToImport, - this.importedInterfaces, + this.interfacesAlreadyImported, identifier.getSourceFile() ); this.incrementCounters(identifier, FaultID.UIInterfaceImport, autofix); } else { - this.incrementCounters(identifier, FaultID.UIInterfaceImport); + this.incrementCounters(identifier, FaultID.UIInterfaceImport, []); } }); - this.interfaceIdentifiers = []; + this.interfacesNeedToAlarm = []; this.interfacesNeedToImport.clear(); - this.importedInterfaces.clear(); + this.interfacesAlreadyImported.clear(); } private extractImportedNames(sourceFile: ts.SourceFile): void { @@ -5328,7 +5331,7 @@ export class TypeScriptLinter { for (const specifier of namedBindings.elements) { const importedName = specifier.name.getText(sourceFile); - this.importedInterfaces.add(importedName); + this.interfacesAlreadyImported.add(importedName); } } } @@ -5410,7 +5413,7 @@ export class TypeScriptLinter { return functionCalls; } - needObservation: Set = new Set(); + addObservedDecorator: Set = new Set(); private handleDataObservation(node: ts.PropertyDeclaration): void { if (!this.options.arkts2) { @@ -5421,7 +5424,6 @@ export class TypeScriptLinter { if (!decorators || decorators.length === 0) { return; } - const decorator = decorators[0]; let decoratorName = ''; if (ts.isIdentifier(decorator.expression)) { @@ -5429,53 +5431,95 @@ export class TypeScriptLinter { } else if (ts.isCallExpression(decorator.expression)) { decoratorName = decorator.expression.expression.getText(); } - if (!observedDecoratorName.has(decoratorName)) { return; } + let firstClassDecls: ts.ClassDeclaration[] | undefined; + const expr = node.initializer; + if (expr && ts.isNewExpression(expr)) { + firstClassDecls = this.addFromNewExpression(expr); + } + + let secondClassDecls: ts.ClassDeclaration[] | undefined; const type = node.type; - if (!type) { + if (type) { + secondClassDecls = this.addFromTypeNode(type); + } + + const classDecls = (firstClassDecls || []).concat(secondClassDecls || []); + if (classDecls.length === 0) { return; } + const filteredClassDecls = classDecls.filter((classDecl) => { + if (this.addObservedDecorator.has(classDecl)) { + return false; + } + this.addObservedDecorator.add(classDecl); + return true; + }); + if (filteredClassDecls.length !== 0) { + this.interfacesNeedToImport.add(CustomDecoratorName.Observed); + } + const autofix = this.autofixer?.fixDataObservation(filteredClassDecls); + this.incrementCounters(node, FaultID.DataObservation, autofix); + } + + private addFromNewExpression(expr: ts.NewExpression): ts.ClassDeclaration[] | undefined { + const identifier = expr.expression; + if (!ts.isIdentifier(identifier)) { + return undefined; + } + + const decl: ts.ClassDeclaration | undefined = this.getClassDeclaration(identifier); + if (!decl) { + return undefined; + } + + const classDecls: ts.ClassDeclaration[] = this.getClassHierarchy(decl); + const filteredClassDecls = classDecls.filter((classDecl) => { + if (TypeScriptLinter.hasObservedDecorator(classDecl)) { + return false; + } + return true; + }); + return filteredClassDecls; + } + + private addFromTypeNode(type: ts.TypeNode): ts.ClassDeclaration[] | undefined { const targets: ts.Node[] = []; if (ts.isUnionTypeNode(type)) { const types = type.types; types.forEach((typeNode) => { - this.processTypeNode(typeNode, targets); + if (ts.isTypeReferenceNode(typeNode)) { + targets.push(typeNode.typeName); + } }); - } else { - this.processTypeNode(type, targets); + } else if (ts.isTypeReferenceNode(type)) { + targets.push(type.typeName); } + const classDecls: ts.ClassDeclaration[] = []; targets.forEach((target) => { - const targetName = target.getText(); - const classDecl = this.findClassDeclaration(targetName); - if (TypeScriptLinter.hasObservedDecorator(classDecl)) { + const decl: ts.ClassDeclaration | undefined = this.getClassDeclaration(target); + if (!decl) { return; } - const autofix = this.autofixer?.fixDataObservation(classDecl); - this.incrementCounters(target, FaultID.DataObservation, autofix); - }); - } - private processTypeNode(typeNode: ts.TypeNode, targets: ts.Node[]): void { - if (ts.isTypeReferenceNode(typeNode)) { - const target = typeNode.typeName; - const targetName = target.getText(); - if (!this.needObservation.has(targetName)) { - targets.push(target); - this.needObservation.add(targetName); + const decls: ts.ClassDeclaration[] = this.getClassHierarchy(decl); + classDecls.push(...decls); + }); + const filteredClassDecls = classDecls.filter((classDecl) => { + if (TypeScriptLinter.hasObservedDecorator(classDecl)) { + return false; } - } + return true; + }); + return filteredClassDecls; } - private static hasObservedDecorator(classDecl: ts.ClassDeclaration | undefined): boolean { - if (!classDecl || !ts.isClassDeclaration(classDecl)) { - return false; - } - + private static hasObservedDecorator(classDecl: ts.ClassDeclaration): boolean { return ( ts.getDecorators(classDecl)?.some((decorator) => { return decorator.getText() === '@' + CustomDecoratorName.Observed; @@ -5483,22 +5527,40 @@ export class TypeScriptLinter { ); } - private findClassDeclaration(targetName: string): ts.ClassDeclaration | undefined { - const sourceFile = this.sourceFile as ts.SourceFile; - const statements = sourceFile.statements; - if (!statements) { + private getClassDeclaration(node: ts.Node): ts.ClassDeclaration | undefined { + const symbol = this.tsTypeChecker.getSymbolAtLocation(node); + let decl: ts.Declaration | undefined; + if (symbol) { + decl = this.tsUtils.getDeclarationNode(node); + if (decl?.getSourceFile() !== node.getSourceFile()) { + return undefined; + } + } + + if (!decl || !ts.isClassDeclaration(decl)) { return undefined; } - const classDecl = statements.find((statement) => { - return ts.isClassDeclaration(statement) && statement.name?.getText() === targetName; - }); + return decl; + } - if (!classDecl || !ts.isClassDeclaration(classDecl)) { - return undefined; + private getClassHierarchy(classDecl: ts.ClassDeclaration): ts.ClassDeclaration[] { + const hierarchy: ts.ClassDeclaration[] = []; + let currentClass: ts.ClassDeclaration | undefined = classDecl; + + while (currentClass) { + hierarchy.push(currentClass); + const heritageClause = currentClass.heritageClauses?.find((clause) => { + return clause.token === ts.SyntaxKind.ExtendsKeyword; + }); + const identifier = heritageClause?.types[0]?.expression as ts.Identifier | undefined; + if (!identifier) { + break; + } + currentClass = this.getClassDeclaration(identifier); } - return classDecl; + return hierarchy; } private checkArkTSObjectInterop(tsCallExpr: ts.CallExpression): void { diff --git a/ets2panda/linter/src/lib/autofixes/Autofixer.ts b/ets2panda/linter/src/lib/autofixes/Autofixer.ts index 60bed5f883..5e842eecb2 100644 --- a/ets2panda/linter/src/lib/autofixes/Autofixer.ts +++ b/ets2panda/linter/src/lib/autofixes/Autofixer.ts @@ -2742,14 +2742,71 @@ export class Autofixer { ]; } - fixSingleImport( + checkEnumMemberNameConflict(tsEnumMember: ts.EnumMember, autofix: Autofix[] | undefined): void { + if (!autofix?.length) { + return; + } + + const parentEnum = tsEnumMember.parent; + if (!this.hasNameConflict(parentEnum, tsEnumMember, autofix)) { + return; + } + + const existingNames = this.collectExistingNames(parentEnum, tsEnumMember); + this.adjustAutofixNames(autofix, existingNames); + } + + hasNameConflict(parentEnum: ts.EnumDeclaration, tsEnumMember: ts.EnumMember, autofix: Autofix[]): boolean { + void this; + return parentEnum.members.some((member) => { + return ( + member !== tsEnumMember && + (ts.isStringLiteral(member.name) || member.name.getText() === autofix[0].replacementText) + ); + }); + } + + collectExistingNames(parentEnum: ts.EnumDeclaration, tsEnumMember: ts.EnumMember): Set { + void this; + return new Set( + parentEnum.members. + filter((m) => { + return m !== tsEnumMember; + }). + map((m) => { + const nameNode = m.name; + if (ts.isStringLiteral(nameNode)) { + const fix = this.fixLiteralAsPropertyNamePropertyName(nameNode); + return fix?.[0]?.replacementText || nameNode.text; + } + return nameNode.getText(); + }) + ); + } + + adjustAutofixNames(autofix: Autofix[], existingNames: Set): void { + void this; + const baseName = autofix[0].replacementText; + let newName = baseName; + let counter = 1; + + while (existingNames.has(newName)) { + newName = `${baseName}_${counter++}`; + } + + autofix.forEach((fix) => { + fix.replacementText = newName; + }); + } + + fixInterfaceImport( interfacesNeedToImport: Set, - importedInterfaces: Set, + interfacesAlreadyImported: Set, sourceFile: ts.SourceFile ): Autofix[] { const importSpecifiers: ts.ImportSpecifier[] = []; interfacesNeedToImport.forEach((interfaceName) => { - if (importedInterfaces.has(interfaceName)) { + if (interfacesAlreadyImported.has(interfaceName)) { return; } const identifier = ts.factory.createIdentifier(interfaceName); @@ -2969,15 +3026,16 @@ export class Autofixer { return newProperties; } - fixDataObservation(classDecl: ts.ClassDeclaration | undefined): Autofix[] | undefined { - if (!classDecl) { - return undefined; - } - - const observedDecorator = ts.factory.createDecorator(ts.factory.createIdentifier(CustomDecoratorName.Observed)); - const sourceFile = classDecl.getSourceFile(); - const text = this.printer.printNode(ts.EmitHint.Unspecified, observedDecorator, sourceFile) + '\n'; - return [{ start: classDecl.getStart(), end: classDecl.getStart(), replacementText: text }]; + fixDataObservation(classDecls: ts.ClassDeclaration[]): Autofix[] | undefined { + const autofixes: Autofix[] = []; + classDecls.forEach((classDecl) => { + const observedDecorator = ts.factory.createDecorator(ts.factory.createIdentifier(CustomDecoratorName.Observed)); + const sourceFile = classDecl.getSourceFile(); + const text = this.printer.printNode(ts.EmitHint.Unspecified, observedDecorator, sourceFile) + '\n'; + const autofix = { start: classDecl.getStart(), end: classDecl.getStart(), replacementText: text }; + autofixes.push(autofix); + }); + return autofixes.length !== 0 ? autofixes : undefined; } static fixInteropTsType( diff --git a/ets2panda/linter/src/lib/utils/consts/ArkuiConstants.ts b/ets2panda/linter/src/lib/utils/consts/ArkuiConstants.ts index 633b4e5ef1..4764c82dfd 100644 --- a/ets2panda/linter/src/lib/utils/consts/ArkuiConstants.ts +++ b/ets2panda/linter/src/lib/utils/consts/ArkuiConstants.ts @@ -20,7 +20,7 @@ export const INSTANCE_IDENTIFIER = 'instance'; export const COMMON_METHOD_IDENTIFIER = 'CommonMethod'; export const APPLY_STYLES_IDENTIFIER = 'applyStyles'; export const STATE_STYLES = 'stateStyles'; -export const ARKUI_PACKAGE_NAME = '@kits.ArkUI'; +export const ARKUI_PACKAGE_NAME = '@kit.ArkUI'; export const VALUE_IDENTIFIER = 'value'; export const INDENT_STEP = 2; diff --git a/ets2panda/linter/test/main/animatable_extend_decorator_1.ets.autofix.json b/ets2panda/linter/test/main/animatable_extend_decorator_1.ets.autofix.json index 8d0d9a6ac8..5136b5c4cb 100644 --- a/ets2panda/linter/test/main/animatable_extend_decorator_1.ets.autofix.json +++ b/ets2panda/linter/test/main/animatable_extend_decorator_1.ets.autofix.json @@ -37,6 +37,7 @@ "endLine": 16, "endColumn": 18, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -47,6 +48,7 @@ "endLine": 21, "endColumn": 7, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -57,6 +59,7 @@ "endLine": 22, "endColumn": 11, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -67,6 +70,7 @@ "endLine": 24, "endColumn": 9, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -77,6 +81,7 @@ "endLine": 27, "endColumn": 11, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -87,6 +92,7 @@ "endLine": 28, "endColumn": 11, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -97,6 +103,7 @@ "endLine": 30, "endColumn": 50, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -111,7 +118,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { TextAttribute, AnimatableExtend, Entry, Component, State, Column, Text, Curve, Button } from '@kits.ArkUI';" + "replacementText": "\n\nimport { TextAttribute, AnimatableExtend, Entry, Component, State, Column, Text, Curve, Button } from '@kit.ArkUI';" } ], "suggest": "", diff --git a/ets2panda/linter/test/main/animatable_extend_decorator_2.ets b/ets2panda/linter/test/main/animatable_extend_decorator_2.ets index 06a71f16a1..eebe111df2 100644 --- a/ets2panda/linter/test/main/animatable_extend_decorator_2.ets +++ b/ets2panda/linter/test/main/animatable_extend_decorator_2.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import { AnimatableExtend, TextAttribute, Entry, Component, State, Column, Text, Curve, Button } from '@kits.ArkUI'; +import { AnimatableExtend, TextAttribute, Entry, Component, State, Column, Text, Curve, Button } from '@kit.ArkUI'; @AnimatableExtend function animatableWidth(this: TextAttribute, width: number): this { diff --git a/ets2panda/linter/test/main/data_observation_1.ets b/ets2panda/linter/test/main/data_observation_1.ets index 855d8cb121..3ccdd38f94 100644 --- a/ets2panda/linter/test/main/data_observation_1.ets +++ b/ets2panda/linter/test/main/data_observation_1.ets @@ -13,40 +13,58 @@ * limitations under the License. */ -import { MyClassB, MyClassD } from './' +class MyClassA {} -class MyClassA { +class MyClassB { + name: string = '' } -class MyClassC { -} +class MyClassC1 {} + +class MyClassC2 extends MyClassC1 {} + +class MyClassC3 extends MyClassC2 {} + +class MyClassD extends MyClassC3 {} + +class MyClassC4 extends MyClassD {} + +interface IntfA {} + +class MyClassE implements IntfA {} @Observed -class MyClassE { -} +class MyClassF {} + +class MyClassG {} + +class MyClassH {} + +class MyClassI {} -AppStorage.setOrCreate('PropA', 47); -AppStorage.setOrCreate('PropB', new MyClassC()); -let storage = new LocalStorage(); -storage.setOrCreate('LinkA', 48); -storage.setOrCreate('LinkB', new MyClassA()); +@Observed +class MyClassJ extends MyClassI {} + +@Observed +class MyClassK extends MyClassJ {} @Entry @Component struct Test { @State data1: number = 0 - @State data2: MyClassA = 0 - @State data3: MyClassB | string = 0 - @State data4: undefined | string | MyClassC | MyClassD = 0 - @State data5: MyClassE = 0 - @Prop data6: MyClassA = 0 + @State data2: MyClassA = new MyClassA() + @State data3: MyClassB = { name: "jack" } + @State data4: MyClassC2 = new MyClassD() + @State data5: IntfA = new MyClassE() + @Prop data6: MyClassE = new MyClassE() + @Prop data7: MyClassF = new MyClassF() + @Prop data8: MyClassG | MyClassH | number = 0 + @Prop data9: MyClassJ = new MyClassK() @Provide selectedDate: Date = new Date('2021-08-08') - @StorageLink('PropA') storageLink1: number = 1 - @StorageLink('PropB') storageLink2: MyClassC = new MyClassC() - @LocalStorageLink('LinkA') localStorageLink1: number = 1 - @LocalStorageLink('LinkB') localStorageLink2: MyClassA = new MyClassA() - @StorageProp('test') test1: MyClassB = 0; - @LocalStorageProp('test') test2: MyClassB = 0; + @StorageLink('PropB') storageLink: MyClassA = new MyClassA() + @LocalStorageLink('LinkB') localStorageLink: MyClassB = new MyClassB() + @StorageProp('test') test1: MyClassC2 = new MyClassC3() + @LocalStorageProp('test') test2: MyClassD = new MyClassD() build() { diff --git a/ets2panda/linter/test/main/data_observation_1.ets.arkts2.json b/ets2panda/linter/test/main/data_observation_1.ets.arkts2.json index fc333a843f..da9c036907 100644 --- a/ets2panda/linter/test/main/data_observation_1.ets.arkts2.json +++ b/ets2panda/linter/test/main/data_observation_1.ets.arkts2.json @@ -15,79 +15,129 @@ ], "result": [ { - "line": 30, - "column": 5, - "endLine": 30, - "endColumn": 33, - "problem": "AnyType", + "line": 55, + "column": 3, + "endLine": 55, + "endColumn": 42, + "problem": "DataObservation", + "suggest": "", + "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", + "severity": "ERROR" + }, + { + "line": 56, + "column": 3, + "endLine": 56, + "endColumn": 44, + "problem": "DataObservation", + "suggest": "", + "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", + "severity": "ERROR" + }, + { + "line": 57, + "column": 3, + "endLine": 57, + "endColumn": 43, + "problem": "DataObservation", + "suggest": "", + "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", + "severity": "ERROR" + }, + { + "line": 58, + "column": 3, + "endLine": 58, + "endColumn": 39, + "problem": "DataObservation", + "suggest": "", + "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", + "severity": "ERROR" + }, + { + "line": 59, + "column": 3, + "endLine": 59, + "endColumn": 41, + "problem": "DataObservation", + "suggest": "", + "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 3, + "endLine": 61, + "endColumn": 48, + "problem": "DataObservation", "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", "severity": "ERROR" }, { - "line": 30, - "column": 19, - "endLine": 30, - "endColumn": 31, - "problem": "DynamicCtorCall", + "line": 62, + "column": 3, + "endLine": 62, + "endColumn": 41, + "problem": "DataObservation", "suggest": "", - "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", "severity": "ERROR" }, { - "line": 38, - "column": 17, - "endLine": 38, - "endColumn": 25, + "line": 64, + "column": 3, + "endLine": 64, + "endColumn": 63, "problem": "DataObservation", "suggest": "", "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", "severity": "ERROR" }, { - "line": 39, - "column": 17, - "endLine": 39, - "endColumn": 25, + "line": 65, + "column": 3, + "endLine": 65, + "endColumn": 73, "problem": "DataObservation", "suggest": "", "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", "severity": "ERROR" }, { - "line": 40, - "column": 38, - "endLine": 40, - "endColumn": 46, + "line": 66, + "column": 3, + "endLine": 66, + "endColumn": 58, "problem": "DataObservation", "suggest": "", "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", "severity": "ERROR" }, { - "line": 40, - "column": 49, - "endLine": 40, - "endColumn": 57, + "line": 67, + "column": 3, + "endLine": 67, + "endColumn": 61, "problem": "DataObservation", "suggest": "", "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", "severity": "ERROR" }, { - "line": 43, - "column": 26, - "endLine": 43, - "endColumn": 30, + "line": 76, + "column": 3, + "endLine": 76, + "endColumn": 24, "problem": "DataObservation", "suggest": "", "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", "severity": "ERROR" }, { - "line": 24, + "line": 36, "column": 2, - "endLine": 24, + "endLine": 36, "endColumn": 10, "problem": "UIInterfaceImport", "suggest": "", @@ -95,29 +145,29 @@ "severity": "ERROR" }, { - "line": 28, - "column": 1, - "endLine": 28, - "endColumn": 11, + "line": 45, + "column": 2, + "endLine": 45, + "endColumn": 10, "problem": "UIInterfaceImport", "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 30, - "column": 19, - "endLine": 30, - "endColumn": 31, + "line": 48, + "column": 2, + "endLine": 48, + "endColumn": 10, "problem": "UIInterfaceImport", "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 34, + "line": 51, "column": 2, - "endLine": 34, + "endLine": 51, "endColumn": 7, "problem": "UIInterfaceImport", "suggest": "", @@ -125,9 +175,9 @@ "severity": "ERROR" }, { - "line": 35, + "line": 52, "column": 2, - "endLine": 35, + "endLine": 52, "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", @@ -135,9 +185,9 @@ "severity": "ERROR" }, { - "line": 37, + "line": 54, "column": 4, - "endLine": 37, + "endLine": 54, "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", @@ -145,9 +195,49 @@ "severity": "ERROR" }, { - "line": 42, + "line": 55, "column": 4, - "endLine": 42, + "endLine": 55, + "endColumn": 9, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 56, + "column": 4, + "endLine": 56, + "endColumn": 9, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 57, + "column": 4, + "endLine": 57, + "endColumn": 9, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 58, + "column": 4, + "endLine": 58, + "endColumn": 9, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 59, + "column": 4, + "endLine": 59, "endColumn": 8, "problem": "UIInterfaceImport", "suggest": "", @@ -155,9 +245,39 @@ "severity": "ERROR" }, { - "line": 43, + "line": 60, "column": 4, - "endLine": 43, + "endLine": 60, + "endColumn": 8, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 4, + "endLine": 61, + "endColumn": 8, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 62, + "column": 4, + "endLine": 62, + "endColumn": 8, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 63, + "column": 4, + "endLine": 63, "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", @@ -165,9 +285,9 @@ "severity": "ERROR" }, { - "line": 44, + "line": 64, "column": 4, - "endLine": 44, + "endLine": 64, "endColumn": 15, "problem": "UIInterfaceImport", "suggest": "", @@ -175,9 +295,9 @@ "severity": "ERROR" }, { - "line": 46, + "line": 65, "column": 4, - "endLine": 46, + "endLine": 65, "endColumn": 20, "problem": "UIInterfaceImport", "suggest": "", @@ -185,9 +305,9 @@ "severity": "ERROR" }, { - "line": 48, + "line": 66, "column": 4, - "endLine": 48, + "endLine": 66, "endColumn": 15, "problem": "UIInterfaceImport", "suggest": "", @@ -195,9 +315,9 @@ "severity": "ERROR" }, { - "line": 49, + "line": 67, "column": 4, - "endLine": 49, + "endLine": 67, "endColumn": 20, "problem": "UIInterfaceImport", "suggest": "", @@ -205,9 +325,19 @@ "severity": "ERROR" }, { - "line": 58, + "line": 74, + "column": 2, + "endLine": 74, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 76, "column": 4, - "endLine": 58, + "endLine": 76, "endColumn": 8, "problem": "UIInterfaceImport", "suggest": "", @@ -215,9 +345,9 @@ "severity": "ERROR" }, { - "line": 59, + "line": 77, "column": 4, - "endLine": 59, + "endLine": 77, "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", diff --git a/ets2panda/linter/test/main/data_observation_1.ets.autofix.json b/ets2panda/linter/test/main/data_observation_1.ets.autofix.json index 04f4870665..e5da4631b9 100644 --- a/ets2panda/linter/test/main/data_observation_1.ets.autofix.json +++ b/ets2panda/linter/test/main/data_observation_1.ets.autofix.json @@ -15,35 +15,81 @@ ], "result": [ { - "line": 30, - "column": 5, - "endLine": 30, - "endColumn": 33, - "problem": "AnyType", + "line": 55, + "column": 3, + "endLine": 55, + "endColumn": 42, + "problem": "DataObservation", + "autofix": [ + { + "start": 605, + "end": 605, + "replacementText": "@Observed\n" + } + ], "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", "severity": "ERROR" }, { - "line": 30, - "column": 19, - "endLine": 30, - "endColumn": 31, - "problem": "DynamicCtorCall", + "line": 56, + "column": 3, + "endLine": 56, + "endColumn": 44, + "problem": "DataObservation", + "autofix": [ + { + "start": 624, + "end": 624, + "replacementText": "@Observed\n" + } + ], "suggest": "", - "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", "severity": "ERROR" }, { - "line": 38, - "column": 17, - "endLine": 38, - "endColumn": 25, + "line": 57, + "column": 3, + "endLine": 57, + "endColumn": 43, "problem": "DataObservation", "autofix": [ { - "start": 646, - "end": 646, + "start": 760, + "end": 760, + "replacementText": "@Observed\n" + }, + { + "start": 722, + "end": 722, + "replacementText": "@Observed\n" + }, + { + "start": 684, + "end": 684, + "replacementText": "@Observed\n" + }, + { + "start": 664, + "end": 664, + "replacementText": "@Observed\n" + } + ], + "suggest": "", + "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", + "severity": "ERROR" + }, + { + "line": 58, + "column": 3, + "endLine": 58, + "endColumn": 39, + "problem": "DataObservation", + "autofix": [ + { + "start": 854, + "end": 854, "replacementText": "@Observed\n" } ], @@ -52,25 +98,47 @@ "severity": "ERROR" }, { - "line": 39, - "column": 17, - "endLine": 39, - "endColumn": 25, + "line": 59, + "column": 3, + "endLine": 59, + "endColumn": 41, + "problem": "DataObservation", + "suggest": "", + "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 3, + "endLine": 61, + "endColumn": 48, "problem": "DataObservation", + "autofix": [ + { + "start": 919, + "end": 919, + "replacementText": "@Observed\n" + }, + { + "start": 938, + "end": 938, + "replacementText": "@Observed\n" + } + ], "suggest": "", "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", "severity": "ERROR" }, { - "line": 40, - "column": 38, - "endLine": 40, - "endColumn": 46, + "line": 62, + "column": 3, + "endLine": 62, + "endColumn": 41, "problem": "DataObservation", "autofix": [ { - "start": 666, - "end": 666, + "start": 957, + "end": 957, "replacementText": "@Observed\n" } ], @@ -79,166 +147,297 @@ "severity": "ERROR" }, { - "line": 40, - "column": 49, - "endLine": 40, - "endColumn": 57, + "line": 64, + "column": 3, + "endLine": 64, + "endColumn": 63, "problem": "DataObservation", "suggest": "", "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", "severity": "ERROR" }, { - "line": 43, - "column": 26, - "endLine": 43, - "endColumn": 30, + "line": 65, + "column": 3, + "endLine": 65, + "endColumn": 73, "problem": "DataObservation", "suggest": "", "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", "severity": "ERROR" }, { - "line": 24, + "line": 66, + "column": 3, + "endLine": 66, + "endColumn": 58, + "problem": "DataObservation", + "suggest": "", + "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", + "severity": "ERROR" + }, + { + "line": 67, + "column": 3, + "endLine": 67, + "endColumn": 61, + "problem": "DataObservation", + "suggest": "", + "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", + "severity": "ERROR" + }, + { + "line": 76, + "column": 3, + "endLine": 76, + "endColumn": 24, + "problem": "DataObservation", + "suggest": "", + "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", + "severity": "ERROR" + }, + { + "line": 36, "column": 2, - "endLine": 24, + "endLine": 36, "endColumn": 10, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 28, - "column": 1, - "endLine": 28, - "endColumn": 11, + "line": 45, + "column": 2, + "endLine": 45, + "endColumn": 10, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 30, - "column": 19, - "endLine": 30, - "endColumn": 31, + "line": 48, + "column": 2, + "endLine": 48, + "endColumn": 10, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 34, + "line": 51, "column": 2, - "endLine": 34, + "endLine": 51, "endColumn": 7, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 35, + "line": 52, "column": 2, - "endLine": 35, + "endLine": 52, "endColumn": 11, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 37, + "line": 54, "column": 4, - "endLine": 37, + "endLine": 54, "endColumn": 9, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 42, + "line": 55, "column": 4, - "endLine": 42, + "endLine": 55, + "endColumn": 9, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 56, + "column": 4, + "endLine": 56, + "endColumn": 9, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 57, + "column": 4, + "endLine": 57, + "endColumn": 9, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 58, + "column": 4, + "endLine": 58, + "endColumn": 9, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 59, + "column": 4, + "endLine": 59, "endColumn": 8, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 43, + "line": 60, "column": 4, - "endLine": 43, + "endLine": 60, + "endColumn": 8, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 4, + "endLine": 61, + "endColumn": 8, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 62, + "column": 4, + "endLine": 62, + "endColumn": 8, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 63, + "column": 4, + "endLine": 63, "endColumn": 11, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 44, + "line": 64, "column": 4, - "endLine": 44, + "endLine": 64, "endColumn": 15, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 46, + "line": 65, "column": 4, - "endLine": 46, + "endLine": 65, "endColumn": 20, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 48, + "line": 66, "column": 4, - "endLine": 48, + "endLine": 66, "endColumn": 15, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 49, + "line": 67, "column": 4, - "endLine": 49, + "endLine": 67, "endColumn": 20, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 58, + "line": 74, + "column": 2, + "endLine": 74, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 76, "column": 4, - "endLine": 58, + "endLine": 76, "endColumn": 8, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 59, + "line": 77, "column": 4, - "endLine": 59, + "endLine": 77, "endColumn": 11, "problem": "UIInterfaceImport", "autofix": [ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Observed, AppStorage, LocalStorage, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kits.ArkUI';" + "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" } ], "suggest": "", diff --git a/ets2panda/linter/test/main/data_observation_1.ets.json b/ets2panda/linter/test/main/data_observation_1.ets.json index c6dcaec09e..ca88f857e9 100644 --- a/ets2panda/linter/test/main/data_observation_1.ets.json +++ b/ets2panda/linter/test/main/data_observation_1.ets.json @@ -13,16 +13,5 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "result": [ - { - "line": 30, - "column": 5, - "endLine": 30, - "endColumn": 33, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - } - ] + "result": [] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/data_observation_2.ets b/ets2panda/linter/test/main/data_observation_2.ets index 7ce00c004c..7a91607067 100644 --- a/ets2panda/linter/test/main/data_observation_2.ets +++ b/ets2panda/linter/test/main/data_observation_2.ets @@ -13,23 +13,82 @@ * limitations under the License. */ -import { MyClassB, MyClassD } from './' +import { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI'; + +@Observed +class MyClassA {} + +@Observed +class MyClassB { + name: string = '' +} + +@Observed +class MyClassC1 {} + +@Observed +class MyClassC2 extends MyClassC1 {} + +@Observed +class MyClassC3 extends MyClassC2 {} + +@Observed +class MyClassD extends MyClassC3 {} + +class MyClassC4 extends MyClassD {} + +interface IntfA {} + +@Observed +class MyClassE implements IntfA {} + +@Observed +class MyClassF {} + +@Observed +class MyClassG {} + +@Observed +class MyClassH {} + +@Observed +class MyClassI {} + +@Observed +class MyClassJ extends MyClassI {} + +@Observed +class MyClassK extends MyClassJ {} @Entry @Component struct Test { - @State data1: number = 0 - @State data2: MyClassA = 0 - @State data3: MyClassB | string = 0 - @State data3: undefined | string | MyClassC | MyClassD = 0 -} + @State data1: number = 0 + @State data2: MyClassA = new MyClassA() + @State data3: MyClassB = { name: "jack" } + @State data4: MyClassC2 = new MyClassD() + @State data5: IntfA = new MyClassE() + @Prop data6: MyClassE = new MyClassE() + @Prop data7: MyClassF = new MyClassF() + @Prop data8: MyClassG | MyClassH | number = 0 + @Prop data9: MyClassJ = new MyClassK() + @Provide selectedDate: Date = new Date('2021-08-08') + @StorageLink('PropB') storageLink: MyClassA = new MyClassA() + @LocalStorageLink('LinkB') localStorageLink: MyClassB = new MyClassB() + @StorageProp('test') test1: MyClassC2 = new MyClassC3() + @LocalStorageProp('test') test2: MyClassD = new MyClassD() -@Observed -class MyClassA { + build() { + } } -@Observed -class MyClassC { - +@Component +struct MyComponent { + @Link data2: MyClassA + @Consume selectedDate: Date + + build() { + + } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/data_observation_2.ets.arkts2.json b/ets2panda/linter/test/main/data_observation_2.ets.arkts2.json index e1facf8812..ca88f857e9 100644 --- a/ets2panda/linter/test/main/data_observation_2.ets.arkts2.json +++ b/ets2panda/linter/test/main/data_observation_2.ets.arkts2.json @@ -13,66 +13,5 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "result": [ - { - "line": 23, - "column": 19, - "endLine": 23, - "endColumn": 27, - "problem": "DataObservation", - "suggest": "", - "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", - "severity": "ERROR" - }, - { - "line": 24, - "column": 51, - "endLine": 24, - "endColumn": 59, - "problem": "DataObservation", - "suggest": "", - "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", - "severity": "ERROR" - }, - { - "line": 18, - "column": 2, - "endLine": 18, - "endColumn": 7, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 19, - "column": 2, - "endLine": 19, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 21, - "column": 6, - "endLine": 21, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 27, - "column": 2, - "endLine": 27, - "endColumn": 10, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - } - ] + "result": [] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/data_observation_2.ets.autofix.json b/ets2panda/linter/test/main/data_observation_2.ets.autofix.json index 9779e28293..ca88f857e9 100644 --- a/ets2panda/linter/test/main/data_observation_2.ets.autofix.json +++ b/ets2panda/linter/test/main/data_observation_2.ets.autofix.json @@ -13,73 +13,5 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "result": [ - { - "line": 23, - "column": 19, - "endLine": 23, - "endColumn": 27, - "problem": "DataObservation", - "suggest": "", - "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", - "severity": "ERROR" - }, - { - "line": 24, - "column": 51, - "endLine": 24, - "endColumn": 59, - "problem": "DataObservation", - "suggest": "", - "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", - "severity": "ERROR" - }, - { - "line": 18, - "column": 2, - "endLine": 18, - "endColumn": 7, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 19, - "column": 2, - "endLine": 19, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 21, - "column": 6, - "endLine": 21, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 27, - "column": 2, - "endLine": 27, - "endColumn": 10, - "problem": "UIInterfaceImport", - "autofix": [ - { - "start": 603, - "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Observed } from '@kits.ArkUI';" - } - ], - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - } - ] + "result": [] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/dollar_binding_1.ets b/ets2panda/linter/test/main/dollar_binding_1.ets index dc21222d0f..6ba7a322f1 100644 --- a/ets2panda/linter/test/main/dollar_binding_1.ets +++ b/ets2panda/linter/test/main/dollar_binding_1.ets @@ -16,6 +16,7 @@ @Component struct MyComponent { @State count: number = 0 + build() { Column() { MyCounter({ @@ -27,7 +28,8 @@ struct MyComponent { @Component struct MyCounter { - @Link count: number; + @Link count: number + build() { Row() { Text(`${this.count}`) diff --git a/ets2panda/linter/test/main/dollar_binding_1.ets.arkts2.json b/ets2panda/linter/test/main/dollar_binding_1.ets.arkts2.json index a182150903..2d1bdf9c5a 100644 --- a/ets2panda/linter/test/main/dollar_binding_1.ets.arkts2.json +++ b/ets2panda/linter/test/main/dollar_binding_1.ets.arkts2.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 22, + "line": 23, "column": 9, - "endLine": 22, + "endLine": 23, "endColumn": 22, "problem": "DollarBindingNotSupported", "suggest": "", @@ -45,9 +45,9 @@ "severity": "ERROR" }, { - "line": 20, + "line": 21, "column": 5, - "endLine": 20, + "endLine": 21, "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", @@ -55,9 +55,19 @@ "severity": "ERROR" }, { - "line": 30, + "line": 29, + "column": 2, + "endLine": 29, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 31, "column": 4, - "endLine": 30, + "endLine": 31, "endColumn": 8, "problem": "UIInterfaceImport", "suggest": "", @@ -65,9 +75,9 @@ "severity": "ERROR" }, { - "line": 32, + "line": 34, "column": 5, - "endLine": 32, + "endLine": 34, "endColumn": 8, "problem": "UIInterfaceImport", "suggest": "", @@ -75,9 +85,9 @@ "severity": "ERROR" }, { - "line": 33, + "line": 35, "column": 7, - "endLine": 33, + "endLine": 35, "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", diff --git a/ets2panda/linter/test/main/dollar_binding_1.ets.autofix.json b/ets2panda/linter/test/main/dollar_binding_1.ets.autofix.json index 3f59e43157..a9310c105e 100644 --- a/ets2panda/linter/test/main/dollar_binding_1.ets.autofix.json +++ b/ets2panda/linter/test/main/dollar_binding_1.ets.autofix.json @@ -1,29 +1,29 @@ { "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." ], "result": [ { - "line": 22, + "line": 23, "column": 9, - "endLine": 22, + "endLine": 23, "endColumn": 22, "problem": "DollarBindingNotSupported", "autofix": [ { - "start": 724, - "end": 730, + "start": 725, + "end": 731, "replacementText": "this.count" } ], @@ -37,6 +37,7 @@ "endLine": 16, "endColumn": 11, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -47,51 +48,66 @@ "endLine": 18, "endColumn": 9, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 20, + "line": 21, "column": 5, - "endLine": 20, + "endLine": 21, "endColumn": 11, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 30, + "line": 29, + "column": 2, + "endLine": 29, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 31, "column": 4, - "endLine": 30, + "endLine": 31, "endColumn": 8, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 32, + "line": 34, "column": 5, - "endLine": 32, + "endLine": 34, "endColumn": 8, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 33, + "line": 35, "column": 7, - "endLine": 33, + "endLine": 35, "endColumn": 11, "problem": "UIInterfaceImport", "autofix": [ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Link, Row, Text } from '@kits.ArkUI';" + "replacementText": "\n\nimport { Component, State, Column, Link, Row, Text } from '@kit.ArkUI';" } ], "suggest": "", diff --git a/ets2panda/linter/test/main/dollar_binding_2.ets b/ets2panda/linter/test/main/dollar_binding_2.ets index 022416bfb9..f776eb8d17 100644 --- a/ets2panda/linter/test/main/dollar_binding_2.ets +++ b/ets2panda/linter/test/main/dollar_binding_2.ets @@ -13,11 +13,12 @@ * limitations under the License. */ -import { Component, State, Column, Link, Row, Text } from '@kits.ArkUI'; +import { Component, State, Column, Link, Row, Text } from '@kit.ArkUI'; @Component struct MyComponent { @State count: number = 0 + build() { Column() { MyCounter({ @@ -29,7 +30,8 @@ struct MyComponent { @Component struct MyCounter { - @Link count: number; + @Link count: number + build() { Row() { Text(`${this.count}`) diff --git a/ets2panda/linter/test/main/double_dollar_binding_1.ets b/ets2panda/linter/test/main/double_dollar_binding_1.ets index 53dce1a70c..37be34c3bf 100644 --- a/ets2panda/linter/test/main/double_dollar_binding_1.ets +++ b/ets2panda/linter/test/main/double_dollar_binding_1.ets @@ -14,8 +14,9 @@ */ @Component -struct Myomponent { - @State value: number = 0; +struct MyComponent { + @State value: number = 0 + build() { Row() { Slider({ @@ -28,6 +29,7 @@ struct Myomponent { @Component struct Test { @State checked: boolean = false + build() { Row() { Checkbox().select($$this.checked) diff --git a/ets2panda/linter/test/main/double_dollar_binding_1.ets.arkts2.json b/ets2panda/linter/test/main/double_dollar_binding_1.ets.arkts2.json index 280b7fd22f..0a8b4da88d 100644 --- a/ets2panda/linter/test/main/double_dollar_binding_1.ets.arkts2.json +++ b/ets2panda/linter/test/main/double_dollar_binding_1.ets.arkts2.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 22, + "line": 23, "column": 16, - "endLine": 22, + "endLine": 23, "endColumn": 28, "problem": "DoubleDollarBindingNotSupported", "suggest": "", @@ -25,9 +25,9 @@ "severity": "ERROR" }, { - "line": 33, + "line": 35, "column": 25, - "endLine": 33, + "endLine": 35, "endColumn": 39, "problem": "DoubleDollarBindingNotSupported", "suggest": "", @@ -55,9 +55,9 @@ "severity": "ERROR" }, { - "line": 20, + "line": 21, "column": 5, - "endLine": 20, + "endLine": 21, "endColumn": 8, "problem": "UIInterfaceImport", "suggest": "", @@ -65,9 +65,9 @@ "severity": "ERROR" }, { - "line": 21, + "line": 22, "column": 7, - "endLine": 21, + "endLine": 22, "endColumn": 13, "problem": "UIInterfaceImport", "suggest": "", @@ -75,10 +75,20 @@ "severity": "ERROR" }, { - "line": 33, - "column": 7, - "endLine": 33, - "endColumn": 15, + "line": 29, + "column": 2, + "endLine": 29, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 4, + "endLine": 31, + "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", @@ -86,9 +96,9 @@ }, { "line": 34, - "column": 7, + "column": 5, "endLine": 34, - "endColumn": 12, + "endColumn": 8, "problem": "UIInterfaceImport", "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", @@ -98,6 +108,26 @@ "line": 35, "column": 7, "endLine": 35, + "endColumn": 15, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 36, + "column": 7, + "endLine": 36, + "endColumn": 12, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 7, + "endLine": 37, "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", diff --git a/ets2panda/linter/test/main/double_dollar_binding_1.ets.autofix.json b/ets2panda/linter/test/main/double_dollar_binding_1.ets.autofix.json index 9dee2674f0..932235e593 100644 --- a/ets2panda/linter/test/main/double_dollar_binding_1.ets.autofix.json +++ b/ets2panda/linter/test/main/double_dollar_binding_1.ets.autofix.json @@ -15,15 +15,15 @@ ], "result": [ { - "line": 22, + "line": 23, "column": 16, - "endLine": 22, + "endLine": 23, "endColumn": 28, "problem": "DoubleDollarBindingNotSupported", "autofix": [ { - "start": 718, - "end": 730, + "start": 719, + "end": 731, "replacementText": "$$(this.value)" } ], @@ -32,15 +32,15 @@ "severity": "ERROR" }, { - "line": 33, + "line": 35, "column": 25, - "endLine": 33, + "endLine": 35, "endColumn": 39, "problem": "DoubleDollarBindingNotSupported", "autofix": [ { - "start": 860, - "end": 874, + "start": 862, + "end": 876, "replacementText": "$$(this.checked)" } ], @@ -54,6 +54,7 @@ "endLine": 16, "endColumn": 11, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -64,46 +65,62 @@ "endLine": 18, "endColumn": 9, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 20, + "line": 21, "column": 5, - "endLine": 20, + "endLine": 21, "endColumn": 8, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 21, + "line": 22, "column": 7, - "endLine": 21, + "endLine": 22, "endColumn": 13, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 33, - "column": 7, - "endLine": 33, - "endColumn": 15, + "line": 29, + "column": 2, + "endLine": 29, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 4, + "endLine": 31, + "endColumn": 9, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { "line": 34, - "column": 7, + "column": 5, "endLine": 34, - "endColumn": 12, + "endColumn": 8, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -112,13 +129,35 @@ "line": 35, "column": 7, "endLine": 35, + "endColumn": 15, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 36, + "column": 7, + "endLine": 36, + "endColumn": 12, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 7, + "endLine": 37, "endColumn": 11, "problem": "UIInterfaceImport", "autofix": [ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text } from '@kits.ArkUI';" + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text } from '@kit.ArkUI';" } ], "suggest": "", diff --git a/ets2panda/linter/test/main/double_dollar_binding_2.ets b/ets2panda/linter/test/main/double_dollar_binding_2.ets index 84b8d5448e..e598afe1a5 100644 --- a/ets2panda/linter/test/main/double_dollar_binding_2.ets +++ b/ets2panda/linter/test/main/double_dollar_binding_2.ets @@ -13,11 +13,12 @@ * limitations under the License. */ -import { Component, State, Row, Slider, Checkbox, Blank, Text } from '@kits.ArkUI'; +import { Component, State, Row, Slider, $$, Checkbox, Blank, Text } from '@kit.ArkUI'; @Component -struct Myomponent { - @State value: number = 0; +struct MyComponent { + @State value: number = 0 + build() { Row() { Slider({ @@ -30,6 +31,7 @@ struct Myomponent { @Component struct Test { @State checked: boolean = false + build() { Row() { Checkbox().select($$(this.checked)) diff --git a/ets2panda/linter/test/main/double_excla_binding_1.ets b/ets2panda/linter/test/main/double_excla_binding_1.ets index 91a26fca7c..2026351a80 100644 --- a/ets2panda/linter/test/main/double_excla_binding_1.ets +++ b/ets2panda/linter/test/main/double_excla_binding_1.ets @@ -16,8 +16,9 @@ import { MyCard } from './' @Component -struct Myomponent { - @State value: number = 0; +struct MyComponent1 { + @State value: number = 0 + build() { Row() { Slider({ @@ -30,6 +31,7 @@ struct Myomponent { @Component struct Test { @State checked: boolean = false + build() { Row() { Checkbox().select(this.checked!!) @@ -40,7 +42,7 @@ struct Test { } @Component -struct Myomponent { +struct MyComponent2 { @State value: number = 0; build() { Row() { @@ -52,7 +54,7 @@ struct Myomponent { } @Component -struct Myomponent { +struct MyComponent3 { @State value: number = 0; build() { Row() { @@ -64,7 +66,7 @@ struct Myomponent { } @Component -struct Myomponent { +struct MyComponent4 { @State value: number = 0; build() { Row() { diff --git a/ets2panda/linter/test/main/double_excla_binding_1.ets.arkts2.json b/ets2panda/linter/test/main/double_excla_binding_1.ets.arkts2.json index ba41761671..3211c8ca2f 100644 --- a/ets2panda/linter/test/main/double_excla_binding_1.ets.arkts2.json +++ b/ets2panda/linter/test/main/double_excla_binding_1.ets.arkts2.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 24, + "line": 25, "column": 16, - "endLine": 24, + "endLine": 25, "endColumn": 28, "problem": "DoubleExclaBindingNotSupported", "suggest": "", @@ -25,9 +25,9 @@ "severity": "ERROR" }, { - "line": 35, + "line": 37, "column": 25, - "endLine": 35, + "endLine": 37, "endColumn": 39, "problem": "DoubleExclaBindingNotSupported", "suggest": "", @@ -35,9 +35,9 @@ "severity": "ERROR" }, { - "line": 90, + "line": 92, "column": 21, - "endLine": 90, + "endLine": 92, "endColumn": 33, "problem": "DoubleExclaBindingNotSupported", "suggest": "", @@ -45,9 +45,9 @@ "severity": "ERROR" }, { - "line": 91, + "line": 93, "column": 21, - "endLine": 91, + "endLine": 93, "endColumn": 31, "problem": "DoubleExclaBindingNotSupported", "suggest": "", @@ -75,9 +75,9 @@ "severity": "ERROR" }, { - "line": 22, + "line": 23, "column": 5, - "endLine": 22, + "endLine": 23, "endColumn": 8, "problem": "UIInterfaceImport", "suggest": "", @@ -85,9 +85,9 @@ "severity": "ERROR" }, { - "line": 23, + "line": 24, "column": 7, - "endLine": 23, + "endLine": 24, "endColumn": 13, "problem": "UIInterfaceImport", "suggest": "", @@ -95,10 +95,20 @@ "severity": "ERROR" }, { - "line": 35, - "column": 7, - "endLine": 35, - "endColumn": 15, + "line": 31, + "column": 2, + "endLine": 31, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 4, + "endLine": 33, + "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", @@ -106,9 +116,9 @@ }, { "line": 36, - "column": 7, + "column": 5, "endLine": 36, - "endColumn": 12, + "endColumn": 8, "problem": "UIInterfaceImport", "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", @@ -118,6 +128,26 @@ "line": 37, "column": 7, "endLine": 37, + "endColumn": 15, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 7, + "endLine": 38, + "endColumn": 12, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 7, + "endLine": 39, "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", @@ -125,19 +155,79 @@ "severity": "ERROR" }, { - "line": 78, + "line": 44, "column": 2, - "endLine": 78, - "endColumn": 7, + "endLine": 44, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 46, + "column": 4, + "endLine": 46, + "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 79, + "line": 48, + "column": 5, + "endLine": 48, + "endColumn": 8, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 7, + "endLine": 49, + "endColumn": 13, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 56, "column": 2, - "endLine": 79, + "endLine": 56, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 58, + "column": 4, + "endLine": 58, + "endColumn": 9, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 60, + "column": 5, + "endLine": 60, + "endColumn": 8, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 7, + "endLine": 61, "endColumn": 13, "problem": "UIInterfaceImport", "suggest": "", @@ -145,9 +235,79 @@ "severity": "ERROR" }, { - "line": 81, + "line": 68, + "column": 2, + "endLine": 68, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 70, "column": 4, + "endLine": 70, + "endColumn": 9, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 5, + "endLine": 72, + "endColumn": 8, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 7, + "endLine": 73, + "endColumn": 13, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 80, + "column": 2, + "endLine": 80, + "endColumn": 7, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 81, + "column": 2, "endLine": 81, + "endColumn": 13, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 83, + "column": 4, + "endLine": 83, + "endColumn": 9, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 84, + "column": 4, + "endLine": 84, "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", @@ -155,9 +315,9 @@ "severity": "ERROR" }, { - "line": 85, + "line": 87, "column": 5, - "endLine": 85, + "endLine": 87, "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", @@ -165,9 +325,19 @@ "severity": "ERROR" }, { - "line": 87, + "line": 88, "column": 7, - "endLine": 87, + "endLine": 88, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 89, + "column": 7, + "endLine": 89, "endColumn": 13, "problem": "UIInterfaceImport", "suggest": "", @@ -176,8 +346,18 @@ }, { "line": 99, - "column": 4, + "column": 2, "endLine": 99, + "endColumn": 13, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 101, + "column": 4, + "endLine": 101, "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", @@ -185,14 +365,44 @@ "severity": "ERROR" }, { - "line": 100, + "line": 102, "column": 4, - "endLine": 100, + "endLine": 102, "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" + }, + { + "line": 105, + "column": 5, + "endLine": 105, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 106, + "column": 7, + "endLine": 106, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 107, + "column": 7, + "endLine": 107, + "endColumn": 13, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/double_excla_binding_1.ets.autofix.json b/ets2panda/linter/test/main/double_excla_binding_1.ets.autofix.json index a7a253ec1f..5e7a183c39 100644 --- a/ets2panda/linter/test/main/double_excla_binding_1.ets.autofix.json +++ b/ets2panda/linter/test/main/double_excla_binding_1.ets.autofix.json @@ -15,15 +15,15 @@ ], "result": [ { - "line": 24, + "line": 25, "column": 16, - "endLine": 24, + "endLine": 25, "endColumn": 28, "problem": "DoubleExclaBindingNotSupported", "autofix": [ { - "start": 747, - "end": 759, + "start": 749, + "end": 761, "replacementText": "$$(this.value)" } ], @@ -32,15 +32,15 @@ "severity": "ERROR" }, { - "line": 35, + "line": 37, "column": 25, - "endLine": 35, + "endLine": 37, "endColumn": 39, "problem": "DoubleExclaBindingNotSupported", "autofix": [ { - "start": 889, - "end": 903, + "start": 892, + "end": 906, "replacementText": "$$(this.checked)" } ], @@ -49,15 +49,15 @@ "severity": "ERROR" }, { - "line": 90, + "line": 92, "column": 21, - "endLine": 90, + "endLine": 92, "endColumn": 33, "problem": "DoubleExclaBindingNotSupported", "autofix": [ { - "start": 1653, - "end": 1676, + "start": 1662, + "end": 1685, "replacementText": "{\n value: this.value,\n $value: value => {\n this.value = value;\n }\n }" } ], @@ -66,15 +66,15 @@ "severity": "ERROR" }, { - "line": 91, + "line": 93, "column": 21, - "endLine": 91, + "endLine": 93, "endColumn": 31, "problem": "DoubleExclaBindingNotSupported", "autofix": [ { - "start": 1691, - "end": 1710, + "start": 1700, + "end": 1719, "replacementText": "{\n str: this.str,\n $str: value => {\n this.str = value;\n }\n }" } ], @@ -88,6 +88,7 @@ "endLine": 18, "endColumn": 11, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -98,46 +99,62 @@ "endLine": 20, "endColumn": 9, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 22, + "line": 23, "column": 5, - "endLine": 22, + "endLine": 23, "endColumn": 8, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 23, + "line": 24, "column": 7, - "endLine": 23, + "endLine": 24, "endColumn": 13, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 35, - "column": 7, - "endLine": 35, - "endColumn": 15, + "line": 31, + "column": 2, + "endLine": 31, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 4, + "endLine": 33, + "endColumn": 9, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { "line": 36, - "column": 7, + "column": 5, "endLine": 36, - "endColumn": 12, + "endColumn": 8, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -146,83 +163,310 @@ "line": 37, "column": 7, "endLine": 37, + "endColumn": 15, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 7, + "endLine": 38, + "endColumn": 12, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 7, + "endLine": 39, "endColumn": 11, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 78, + "line": 44, "column": 2, - "endLine": 78, - "endColumn": 7, + "endLine": 44, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 46, + "column": 4, + "endLine": 46, + "endColumn": 9, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 79, + "line": 48, + "column": 5, + "endLine": 48, + "endColumn": 8, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 7, + "endLine": 49, + "endColumn": 13, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 56, "column": 2, - "endLine": 79, + "endLine": 56, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 58, + "column": 4, + "endLine": 58, + "endColumn": 9, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 60, + "column": 5, + "endLine": 60, + "endColumn": 8, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 7, + "endLine": 61, "endColumn": 13, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 81, + "line": 68, + "column": 2, + "endLine": 68, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 70, "column": 4, + "endLine": 70, + "endColumn": 9, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 5, + "endLine": 72, + "endColumn": 8, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 7, + "endLine": 73, + "endColumn": 13, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 80, + "column": 2, + "endLine": 80, + "endColumn": 7, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 81, + "column": 2, "endLine": 81, + "endColumn": 13, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 83, + "column": 4, + "endLine": 83, + "endColumn": 9, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 84, + "column": 4, + "endLine": 84, "endColumn": 9, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 85, + "line": 87, "column": 5, - "endLine": 85, + "endLine": 87, "endColumn": 11, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 87, + "line": 88, "column": 7, - "endLine": 87, + "endLine": 88, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 89, + "column": 7, + "endLine": 89, "endColumn": 13, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { "line": 99, - "column": 4, + "column": 2, "endLine": 99, + "endColumn": 13, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 101, + "column": 4, + "endLine": 101, "endColumn": 9, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 100, + "line": 102, "column": 4, - "endLine": 100, + "endLine": 102, "endColumn": 9, "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 105, + "column": 5, + "endLine": 105, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 106, + "column": 7, + "endLine": 106, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 107, + "column": 7, + "endLine": 107, + "endColumn": 13, + "problem": "UIInterfaceImport", "autofix": [ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kits.ArkUI';" + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';" } ], "suggest": "", diff --git a/ets2panda/linter/test/main/double_excla_binding_2.ets b/ets2panda/linter/test/main/double_excla_binding_2.ets index c8526bdd61..3f5d8563a9 100644 --- a/ets2panda/linter/test/main/double_excla_binding_2.ets +++ b/ets2panda/linter/test/main/double_excla_binding_2.ets @@ -13,13 +13,14 @@ * limitations under the License. */ -import { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kits.ArkUI'; +import { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI'; import { MyCard } from './' @Component -struct Myomponent { - @State value: number = 0; +struct MyComponent { + @State value: number = 0 + build() { Row() { Slider({ @@ -32,6 +33,7 @@ struct Myomponent { @Component struct Test { @State checked: boolean = false + build() { Row() { Checkbox().select($$(this.checked)) @@ -41,6 +43,42 @@ struct Test { } } +@Component +struct MyComponent2 { + @State value: number = 0; + build() { + Row() { + Slider({ + value: this.value!!! + }) + } + } +} + +@Component +struct MyComponent3 { + @State value: number = 0; + build() { + Row() { + Slider({ + value: this.value!!!! + }) + } + } +} + +@Component +struct MyComponent4 { + @State value: number = 0; + build() { + Row() { + Slider({ + value: this.value!!!!! + }) + } + } +} + @Entry @ComponentV2 struct Index { diff --git a/ets2panda/linter/test/main/double_excla_binding_2.ets.arkts2.json b/ets2panda/linter/test/main/double_excla_binding_2.ets.arkts2.json index 9077c4db99..56397bece3 100644 --- a/ets2panda/linter/test/main/double_excla_binding_2.ets.arkts2.json +++ b/ets2panda/linter/test/main/double_excla_binding_2.ets.arkts2.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 63, + "line": 101, "column": 15, - "endLine": 63, + "endLine": 101, "endColumn": 20, "problem": "AnyType", "suggest": "", diff --git a/ets2panda/linter/test/main/double_excla_binding_2.ets.autofix.json b/ets2panda/linter/test/main/double_excla_binding_2.ets.autofix.json index 9077c4db99..56397bece3 100644 --- a/ets2panda/linter/test/main/double_excla_binding_2.ets.autofix.json +++ b/ets2panda/linter/test/main/double_excla_binding_2.ets.autofix.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 63, + "line": 101, "column": 15, - "endLine": 63, + "endLine": 101, "endColumn": 20, "problem": "AnyType", "suggest": "", diff --git a/ets2panda/linter/test/main/double_excla_binding_2.ets.json b/ets2panda/linter/test/main/double_excla_binding_2.ets.json index 9077c4db99..56397bece3 100644 --- a/ets2panda/linter/test/main/double_excla_binding_2.ets.json +++ b/ets2panda/linter/test/main/double_excla_binding_2.ets.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 63, + "line": 101, "column": 15, - "endLine": 63, + "endLine": 101, "endColumn": 20, "problem": "AnyType", "suggest": "", diff --git a/ets2panda/linter/test/main/extend_decorator_1.ets.autofix.json b/ets2panda/linter/test/main/extend_decorator_1.ets.autofix.json index a9ac719f4c..a89e2a668d 100644 --- a/ets2panda/linter/test/main/extend_decorator_1.ets.autofix.json +++ b/ets2panda/linter/test/main/extend_decorator_1.ets.autofix.json @@ -11,7 +11,7 @@ "distributed under the License is distributed on an 'AS IS' BASIS,", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "See the License for the specific language governing permissions and", - "limitations under the License." + "limitations under the License." ], "result": [ { @@ -54,6 +54,7 @@ "endLine": 16, "endColumn": 11, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -64,6 +65,7 @@ "endLine": 19, "endColumn": 11, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -74,6 +76,7 @@ "endLine": 20, "endColumn": 11, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -88,7 +91,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Column, Text, ColumnAttribute, Color } from '@kits.ArkUI';" + "replacementText": "\n\nimport { Component, Column, Text, ColumnAttribute, Color } from '@kit.ArkUI';" } ], "suggest": "", diff --git a/ets2panda/linter/test/main/extend_decorator_2.ets b/ets2panda/linter/test/main/extend_decorator_2.ets index 4826808ccc..c53497da05 100644 --- a/ets2panda/linter/test/main/extend_decorator_2.ets +++ b/ets2panda/linter/test/main/extend_decorator_2.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import { Component, Column, Text, ColumnAttribute, Color } from '@kits.ArkUI'; +import { Component, Column, Text, ColumnAttribute, Color } from '@kit.ArkUI'; @Component struct MyCard { diff --git a/ets2panda/linter/test/main/interface_import_1.ets b/ets2panda/linter/test/main/interface_import_1.ets index b9eb1edf2d..a6cf768c0b 100644 --- a/ets2panda/linter/test/main/interface_import_1.ets +++ b/ets2panda/linter/test/main/interface_import_1.ets @@ -13,15 +13,13 @@ * limitations under the License. */ -import { Row, Slider } from '@kits.ArkUI'; +import { Slider } from '@kit.ArkUI'; @Entry @Component struct Test { - - @State num: number = 0; - - @State a: MyClassA = new MyClassA(); + @State num: number = 0 + @State a: MyClassA = new MyClassA() build() { Column() { @@ -31,7 +29,7 @@ struct Test { } - MyComponent() { + MyComponent1() { } @@ -49,8 +47,9 @@ function Circle() { } @Component -struct MyComponent { +struct MyComponent1 { @State count: number = 0; + build() { Row() { Slider(){} @@ -70,8 +69,9 @@ function animatableWidth(width: number) { } @Component -struct Myomponent { +struct MyComponent2 { @State value: number = 0; + build() { Row() { Slider({ @@ -81,11 +81,9 @@ struct Myomponent { } } -function processImageFit(imageFit: ImageFit): void { -} - -class MyClassA { +class MyClassA {} +function processImageFit(imageFit: ImageFit): void { } function Calendar() { diff --git a/ets2panda/linter/test/main/interface_import_1.ets.arkts2.json b/ets2panda/linter/test/main/interface_import_1.ets.arkts2.json index f86a07369e..745ac0fec0 100644 --- a/ets2panda/linter/test/main/interface_import_1.ets.arkts2.json +++ b/ets2panda/linter/test/main/interface_import_1.ets.arkts2.json @@ -15,19 +15,19 @@ ], "result": [ { - "line": 24, - "column": 13, - "endLine": 24, - "endColumn": 21, + "line": 22, + "column": 3, + "endLine": 22, + "endColumn": 38, "problem": "DataObservation", "suggest": "", "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", "severity": "ERROR" }, { - "line": 61, + "line": 60, "column": 1, - "endLine": 65, + "endLine": 64, "endColumn": 2, "problem": "ExtendDecoratorNotSupported", "suggest": "", @@ -35,9 +35,9 @@ "severity": "ERROR" }, { - "line": 67, + "line": 66, "column": 1, - "endLine": 70, + "endLine": 69, "endColumn": 2, "problem": "AnimatableExtendDecoratorTransform", "suggest": "", @@ -74,6 +74,16 @@ "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, + { + "line": 21, + "column": 4, + "endLine": 21, + "endColumn": 9, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, { "line": 22, "column": 4, @@ -85,9 +95,9 @@ "severity": "ERROR" }, { - "line": 27, + "line": 25, "column": 5, - "endLine": 27, + "endLine": 25, "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", @@ -95,9 +105,9 @@ "severity": "ERROR" }, { - "line": 28, + "line": 26, "column": 7, - "endLine": 28, + "endLine": 26, "endColumn": 13, "problem": "UIInterfaceImport", "suggest": "", @@ -105,9 +115,19 @@ "severity": "ERROR" }, { - "line": 38, + "line": 36, "column": 7, - "endLine": 38, + "endLine": 36, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 2, + "endLine": 49, "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", @@ -115,9 +135,29 @@ "severity": "ERROR" }, { - "line": 67, + "line": 51, + "column": 4, + "endLine": 51, + "endColumn": 9, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 54, + "column": 5, + "endLine": 54, + "endColumn": 8, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 66, "column": 2, - "endLine": 67, + "endLine": 66, "endColumn": 18, "problem": "UIInterfaceImport", "suggest": "", @@ -125,9 +165,39 @@ "severity": "ERROR" }, { - "line": 84, + "line": 71, + "column": 2, + "endLine": 71, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 4, + "endLine": 73, + "endColumn": 9, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 76, + "column": 5, + "endLine": 76, + "endColumn": 8, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 86, "column": 36, - "endLine": 84, + "endLine": 86, "endColumn": 44, "problem": "UIInterfaceImport", "suggest": "", diff --git a/ets2panda/linter/test/main/interface_import_1.ets.autofix.json b/ets2panda/linter/test/main/interface_import_1.ets.autofix.json index fe19afdb79..5873970379 100644 --- a/ets2panda/linter/test/main/interface_import_1.ets.autofix.json +++ b/ets2panda/linter/test/main/interface_import_1.ets.autofix.json @@ -15,15 +15,15 @@ ], "result": [ { - "line": 24, - "column": 13, - "endLine": 24, - "endColumn": 21, + "line": 22, + "column": 3, + "endLine": 22, + "endColumn": 38, "problem": "DataObservation", "autofix": [ { - "start": 1469, - "end": 1469, + "start": 1409, + "end": 1409, "replacementText": "@Observed\n" } ], @@ -32,15 +32,15 @@ "severity": "ERROR" }, { - "line": 61, + "line": 60, "column": 1, - "endLine": 65, + "endLine": 64, "endColumn": 2, "problem": "ExtendDecoratorNotSupported", "autofix": [ { - "start": 1106, - "end": 1176, + "start": 1099, + "end": 1169, "replacementText": "function cardStyle(this: TextAttribute): this {\n this.backgroundColor(Color.Green);\n return this;\n}" } ], @@ -49,15 +49,15 @@ "severity": "ERROR" }, { - "line": 67, + "line": 66, "column": 1, - "endLine": 70, + "endLine": 69, "endColumn": 2, "problem": "AnimatableExtendDecoratorTransform", "autofix": [ { - "start": 1178, - "end": 1263, + "start": 1171, + "end": 1256, "replacementText": "@AnimatableExtend\nfunction animatableWidth(this: ColumnAttribute, width: number): this {\n this.width(width);\n return this;\n}" } ], @@ -73,8 +73,8 @@ "problem": "DoubleDollarBindingNotSupported", "autofix": [ { - "start": 1378, - "end": 1390, + "start": 1374, + "end": 1386, "replacementText": "$$(this.value)" } ], @@ -88,6 +88,7 @@ "endLine": 18, "endColumn": 7, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -98,6 +99,18 @@ "endLine": 19, "endColumn": 11, "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 4, + "endLine": 21, + "endColumn": 9, + "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -108,61 +121,132 @@ "endLine": 22, "endColumn": 9, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 27, + "line": 25, "column": 5, - "endLine": 27, + "endLine": 25, "endColumn": 11, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 28, + "line": 26, "column": 7, - "endLine": 28, + "endLine": 26, "endColumn": 13, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 38, + "line": 36, "column": 7, - "endLine": 38, + "endLine": 36, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 2, + "endLine": 49, "endColumn": 11, "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 51, + "column": 4, + "endLine": 51, + "endColumn": 9, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 54, + "column": 5, + "endLine": 54, + "endColumn": 8, + "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 67, + "line": 66, "column": 2, - "endLine": 67, + "endLine": 66, "endColumn": 18, "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 2, + "endLine": 71, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 4, + "endLine": 73, + "endColumn": 9, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 76, + "column": 5, + "endLine": 76, + "endColumn": 8, + "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 84, + "line": 86, "column": 36, - "endLine": 84, + "endLine": 86, "endColumn": 44, "problem": "UIInterfaceImport", "autofix": [ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Column, Button, Text, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kits.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, State, Observed, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" } ], "suggest": "", diff --git a/ets2panda/linter/test/main/interface_import_2.ets b/ets2panda/linter/test/main/interface_import_2.ets index d34ed23f61..49eea0d570 100644 --- a/ets2panda/linter/test/main/interface_import_2.ets +++ b/ets2panda/linter/test/main/interface_import_2.ets @@ -13,13 +13,15 @@ * limitations under the License. */ -import { Row, Slider, Entry, Component, State, Column, Button, Text, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kits.ArkUI'; +import { Entry, Component, State, Observed, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI'; + +import { Slider } from '@kit.ArkUI'; @Entry @Component struct Test { - - @State col: number = 0; + @State num: number = 0 + @State a: MyClassA = new MyClassA() build() { Column() { @@ -29,7 +31,7 @@ struct Test { } - MyComponent() { + MyComponent1() { } @@ -47,8 +49,9 @@ function Circle() { } @Component -struct MyComponent { +struct MyComponent1 { @State count: number = 0; + build() { Row() { Slider(){} @@ -56,21 +59,21 @@ struct MyComponent { } } -function cardStyle(this: TextAttribute): TextAttribute -{ - this.backgroundColor('#ffffff'); - return this; +function cardStyle(this: TextAttribute): this { + this.backgroundColor(Color.Green); + return this; } @AnimatableExtend -function animatableWidth(this: ColumnAttribute, width: number) { - this.width(width) - return this; +function animatableWidth(this: ColumnAttribute, width: number): this { + this.width(width); + return this; } @Component -struct Myomponent { +struct MyComponent2 { @State value: number = 0; + build() { Row() { Slider({ @@ -78,4 +81,14 @@ struct Myomponent { }) } } +} + +@Observed +class MyClassA {} + +function processImageFit(imageFit: ImageFit): void { +} + +function Calendar() { + } \ No newline at end of file diff --git a/ets2panda/linter/test/main/interface_import_2.ets.arkts2.json b/ets2panda/linter/test/main/interface_import_2.ets.arkts2.json index fd007c9b76..0d99665991 100644 --- a/ets2panda/linter/test/main/interface_import_2.ets.arkts2.json +++ b/ets2panda/linter/test/main/interface_import_2.ets.arkts2.json @@ -15,29 +15,29 @@ ], "result": [ { - "line": 61, - "column": 3, - "endLine": 61, - "endColumn": 7, + "line": 63, + "column": 5, + "endLine": 63, + "endColumn": 9, "problem": "FunctionContainsThis", "suggest": "", "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", "severity": "ERROR" }, { - "line": 62, - "column": 10, - "endLine": 62, - "endColumn": 14, + "line": 64, + "column": 12, + "endLine": 64, + "endColumn": 16, "problem": "FunctionContainsThis", "suggest": "", "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", "severity": "ERROR" }, { - "line": 59, + "line": 62, "column": 20, - "endLine": 59, + "endLine": 62, "endColumn": 24, "problem": "InvalidIdentifier", "suggest": "", @@ -45,34 +45,54 @@ "severity": "ERROR" }, { - "line": 67, - "column": 3, - "endLine": 67, - "endColumn": 7, + "line": 62, + "column": 42, + "endLine": 62, + "endColumn": 46, + "problem": "ThisType", + "suggest": "", + "rule": "Type notation using \"this\" is not supported (arkts-no-typing-with-this)", + "severity": "ERROR" + }, + { + "line": 69, + "column": 5, + "endLine": 69, + "endColumn": 9, "problem": "FunctionContainsThis", "suggest": "", "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", "severity": "ERROR" }, { - "line": 68, - "column": 10, - "endLine": 68, - "endColumn": 14, + "line": 70, + "column": 12, + "endLine": 70, + "endColumn": 16, "problem": "FunctionContainsThis", "suggest": "", "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", "severity": "ERROR" }, { - "line": 66, + "line": 68, "column": 26, - "endLine": 66, + "endLine": 68, "endColumn": 30, "problem": "InvalidIdentifier", "suggest": "", "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", "severity": "ERROR" + }, + { + "line": 68, + "column": 65, + "endLine": 68, + "endColumn": 69, + "problem": "ThisType", + "suggest": "", + "rule": "Type notation using \"this\" is not supported (arkts-no-typing-with-this)", + "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/interface_import_2.ets.autofix.json b/ets2panda/linter/test/main/interface_import_2.ets.autofix.json index fd007c9b76..0d99665991 100644 --- a/ets2panda/linter/test/main/interface_import_2.ets.autofix.json +++ b/ets2panda/linter/test/main/interface_import_2.ets.autofix.json @@ -15,29 +15,29 @@ ], "result": [ { - "line": 61, - "column": 3, - "endLine": 61, - "endColumn": 7, + "line": 63, + "column": 5, + "endLine": 63, + "endColumn": 9, "problem": "FunctionContainsThis", "suggest": "", "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", "severity": "ERROR" }, { - "line": 62, - "column": 10, - "endLine": 62, - "endColumn": 14, + "line": 64, + "column": 12, + "endLine": 64, + "endColumn": 16, "problem": "FunctionContainsThis", "suggest": "", "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", "severity": "ERROR" }, { - "line": 59, + "line": 62, "column": 20, - "endLine": 59, + "endLine": 62, "endColumn": 24, "problem": "InvalidIdentifier", "suggest": "", @@ -45,34 +45,54 @@ "severity": "ERROR" }, { - "line": 67, - "column": 3, - "endLine": 67, - "endColumn": 7, + "line": 62, + "column": 42, + "endLine": 62, + "endColumn": 46, + "problem": "ThisType", + "suggest": "", + "rule": "Type notation using \"this\" is not supported (arkts-no-typing-with-this)", + "severity": "ERROR" + }, + { + "line": 69, + "column": 5, + "endLine": 69, + "endColumn": 9, "problem": "FunctionContainsThis", "suggest": "", "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", "severity": "ERROR" }, { - "line": 68, - "column": 10, - "endLine": 68, - "endColumn": 14, + "line": 70, + "column": 12, + "endLine": 70, + "endColumn": 16, "problem": "FunctionContainsThis", "suggest": "", "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", "severity": "ERROR" }, { - "line": 66, + "line": 68, "column": 26, - "endLine": 66, + "endLine": 68, "endColumn": 30, "problem": "InvalidIdentifier", "suggest": "", "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", "severity": "ERROR" + }, + { + "line": 68, + "column": 65, + "endLine": 68, + "endColumn": 69, + "problem": "ThisType", + "suggest": "", + "rule": "Type notation using \"this\" is not supported (arkts-no-typing-with-this)", + "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/interface_import_2.ets.json b/ets2panda/linter/test/main/interface_import_2.ets.json index 97ab47201a..161c753493 100644 --- a/ets2panda/linter/test/main/interface_import_2.ets.json +++ b/ets2panda/linter/test/main/interface_import_2.ets.json @@ -15,54 +15,64 @@ ], "result": [ { - "line": 61, - "column": 3, - "endLine": 61, - "endColumn": 7, + "line": 63, + "column": 5, + "endLine": 63, + "endColumn": 9, "problem": "FunctionContainsThis", "suggest": "", "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", "severity": "ERROR" }, { - "line": 62, - "column": 10, - "endLine": 62, - "endColumn": 14, + "line": 64, + "column": 12, + "endLine": 64, + "endColumn": 16, "problem": "FunctionContainsThis", "suggest": "", "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", "severity": "ERROR" }, { - "line": 66, - "column": 10, - "endLine": 66, - "endColumn": 25, - "problem": "LimitedReturnTypeInference", + "line": 62, + "column": 42, + "endLine": 62, + "endColumn": 46, + "problem": "ThisType", "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "Type notation using \"this\" is not supported (arkts-no-typing-with-this)", "severity": "ERROR" }, { - "line": 67, - "column": 3, - "endLine": 67, - "endColumn": 7, + "line": 69, + "column": 5, + "endLine": 69, + "endColumn": 9, "problem": "FunctionContainsThis", "suggest": "", "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", "severity": "ERROR" }, { - "line": 68, - "column": 10, - "endLine": 68, - "endColumn": 14, + "line": 70, + "column": 12, + "endLine": 70, + "endColumn": 16, "problem": "FunctionContainsThis", "suggest": "", "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", "severity": "ERROR" + }, + { + "line": 68, + "column": 65, + "endLine": 68, + "endColumn": 69, + "problem": "ThisType", + "suggest": "", + "rule": "Type notation using \"this\" is not supported (arkts-no-typing-with-this)", + "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/invalid_identifier.ets.arkts2.json b/ets2panda/linter/test/main/invalid_identifier.ets.arkts2.json old mode 100755 new mode 100644 index f25f62f469..9704178b5e --- a/ets2panda/linter/test/main/invalid_identifier.ets.arkts2.json +++ b/ets2panda/linter/test/main/invalid_identifier.ets.arkts2.json @@ -783,6 +783,36 @@ "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" + }, + { + "line": 194, + "column": 4, + "endLine": 194, + "endColumn": 9, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 197, + "column": 5, + "endLine": 197, + "endColumn": 22, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 198, + "column": 7, + "endLine": 198, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/literals_as_prop_names.ets.autofix.json b/ets2panda/linter/test/main/literals_as_prop_names.ets.autofix.json index 3706ab2eee..7fb93cd36b 100644 --- a/ets2panda/linter/test/main/literals_as_prop_names.ets.autofix.json +++ b/ets2panda/linter/test/main/literals_as_prop_names.ets.autofix.json @@ -592,6 +592,7 @@ "endLine": 115, "endColumn": 11, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -606,7 +607,7 @@ { "start": 608, "end": 608, - "replacementText": "\n\nimport { Component, State } from '@kits.ArkUI';" + "replacementText": "\n\nimport { Component, State } from '@kit.ArkUI';" } ], "suggest": "", diff --git a/ets2panda/linter/test/main/numeric_semantics.ets.autofix.json b/ets2panda/linter/test/main/numeric_semantics.ets.autofix.json old mode 100755 new mode 100644 index 9593057bff..cf6e169c5d --- a/ets2panda/linter/test/main/numeric_semantics.ets.autofix.json +++ b/ets2panda/linter/test/main/numeric_semantics.ets.autofix.json @@ -1,800 +1,805 @@ -{ - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "result": [ - { - "line": 18, - "column": 5, - "endLine": 18, - "endColumn": 10, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 744, - "end": 749, - "replacementText": "a: number = 1" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 21, - "column": 1, - "endLine": 21, - "endColumn": 8, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 24, - "column": 1, - "endLine": 24, - "endColumn": 9, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 28, - "column": 13, - "endLine": 28, - "endColumn": 18, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 30, - "column": 13, - "endLine": 30, - "endColumn": 18, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 34, - "column": 1, - "endLine": 34, - "endColumn": 6, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 35, - "column": 1, - "endLine": 35, - "endColumn": 7, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 39, - "column": 5, - "endLine": 39, - "endColumn": 12, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 1377, - "end": 1384, - "replacementText": "c: number = 1.5" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 40, - "column": 1, - "endLine": 40, - "endColumn": 6, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 41, - "column": 1, - "endLine": 41, - "endColumn": 7, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 45, - "column": 5, - "endLine": 45, - "endColumn": 10, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 1561, - "end": 1566, - "replacementText": "d: number = 2" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 49, - "column": 13, - "endLine": 49, - "endColumn": 18, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 51, - "column": 5, - "endLine": 51, - "endColumn": 10, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 1712, - "end": 1717, - "replacementText": "n: number = 2" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 55, - "column": 5, - "endLine": 55, - "endColumn": 18, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 1747, - "end": 1760, - "replacementText": "g: number[] = [1, 2, 3]" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 57, - "column": 5, - "endLine": 57, - "endColumn": 15, - "problem": "DefiniteAssignmentError", - "suggest": "", - "rule": "Definite assignment assertions are not supported (arkts-no-definite-assignment)", - "severity": "ERROR" - }, - { - "line": 59, - "column": 5, - "endLine": 59, - "endColumn": 18, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 1786, - "end": 1799, - "replacementText": "t8: number = Infinity" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 61, - "column": 5, - "endLine": 61, - "endColumn": 19, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 1807, - "end": 1821, - "replacementText": "t9: number = -Infinity" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 63, - "column": 5, - "endLine": 63, - "endColumn": 14, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 1830, - "end": 1839, - "replacementText": "t10: number = NaN" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 65, - "column": 5, - "endLine": 65, - "endColumn": 27, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 1848, - "end": 1870, - "replacementText": "t11: number = Number.MAX_VALUE" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 67, - "column": 5, - "endLine": 67, - "endColumn": 27, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 1879, - "end": 1901, - "replacementText": "t12: number = Number.MIN_VALUE" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 73, - "column": 5, - "endLine": 73, - "endColumn": 11, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 1959, - "end": 1965, - "replacementText": "o2: number = o" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 75, - "column": 5, - "endLine": 75, - "endColumn": 12, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 1975, - "end": 1982, - "replacementText": "o3: number = oo" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 78, - "column": 4, - "endLine": 78, - "endColumn": 10, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 2001, - "end": 2007, - "replacementText": "a: number = 1;" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 83, - "column": 5, - "endLine": 83, - "endColumn": 14, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 2043, - "end": 2052, - "replacementText": "t2: number = +123" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 85, - "column": 5, - "endLine": 85, - "endColumn": 14, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 2061, - "end": 2070, - "replacementText": "t3: number = -234" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 87, - "column": 5, - "endLine": 87, - "endColumn": 26, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 2079, - "end": 2100, - "replacementText": "num: number = Math.floor(4.8)" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 89, - "column": 5, - "endLine": 89, - "endColumn": 27, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 2124, - "end": 2146, - "replacementText": "value: number = parseInt(\"42\")" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 92, - "column": 1, - "endLine": 94, - "endColumn": 2, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 2188, - "end": 2193, - "replacementText": "x: number = 2" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 92, - "column": 1, - "endLine": 94, - "endColumn": 2, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 2195, - "end": 2200, - "replacementText": "y: number = 3" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 92, - "column": 1, - "endLine": 94, - "endColumn": 2, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 2201, - "end": 2201, - "replacementText": ": number" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 96, - "column": 1, - "endLine": 98, - "endColumn": 2, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 2264, - "end": 2264, - "replacementText": ": number" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 103, - "column": 1, - "endLine": 103, - "endColumn": 13, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 2347, - "end": 2359, - "replacementText": "identity(42)" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 105, - "column": 5, - "endLine": 105, - "endColumn": 23, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 2368, - "end": 2386, - "replacementText": "an_array: number[] = [1, 2, 3]" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 107, - "column": 5, - "endLine": 107, - "endColumn": 19, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 2394, - "end": 2408, - "replacementText": "g: number = an_array[]" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 107, - "column": 18, - "endLine": 107, - "endColumn": 18, - "problem": "ArrayIndexExprType", - "suggest": "", - "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", - "severity": "ERROR" - }, - { - "line": 109, - "column": 7, - "endLine": 109, - "endColumn": 12, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 2418, - "end": 2423, - "replacementText": "a: number = 1" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 115, - "column": 7, - "endLine": 115, - "endColumn": 20, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 2493, - "end": 2506, - "replacementText": "test: number = Test.A" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 121, - "column": 3, - "endLine": 121, - "endColumn": 19, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 2593, - "end": 2609, - "replacementText": "readonly c1: number = 1;" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 122, - "column": 3, - "endLine": 122, - "endColumn": 21, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 2620, - "end": 2638, - "replacementText": "readonly c4: number = 1.7;" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 123, - "column": 3, - "endLine": 123, - "endColumn": 23, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 2651, - "end": 2671, - "replacementText": "readonly c5: number = 0x123;" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 124, - "column": 3, - "endLine": 124, - "endColumn": 23, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 2683, - "end": 2703, - "replacementText": "readonly c6: number = 0o123;" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 125, - "column": 3, - "endLine": 125, - "endColumn": 23, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 2713, - "end": 2733, - "replacementText": "readonly c7: number = 0b101;" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 126, - "column": 3, - "endLine": 126, - "endColumn": 24, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 2743, - "end": 2764, - "replacementText": "readonly c8: number[] = [1, 2, 3];" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 137, - "column": 7, - "endLine": 137, - "endColumn": 13, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 2893, - "end": 2899, - "replacementText": "c1: number = 1" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 140, - "column": 3, - "endLine": 140, - "endColumn": 19, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 2923, - "end": 2939, - "replacementText": "readonly a5: number = 4;" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 143, - "column": 7, - "endLine": 143, - "endColumn": 123, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 143, - "column": 30, - "endLine": 143, - "endColumn": 118, - "problem": "NumericSemantics", - "autofix": [ - { - "replacementText": "fingerprintPositionY: number = AppStorage.get(FingerprintConstants.COORDINATE_Y_OF_FINGERPRINT_UD_SCREEN_IN_PX) ?? 0", - "start": 2952, - "end": 3068 - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 117, - "column": 2, - "endLine": 117, - "endColumn": 7, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 118, - "column": 2, - "endLine": 118, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 120, - "column": 4, - "endLine": 120, - "endColumn": 9, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 129, - "column": 5, - "endLine": 129, - "endColumn": 22, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 130, - "column": 7, - "endLine": 130, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 143, - "column": 30, - "endLine": 143, - "endColumn": 40, - "problem": "UIInterfaceImport", - "autofix": [ - { - "start": 738, - "end": 738, - "replacementText": "\n\nimport { Entry, Component, State, RelativeContainer, Text, AppStorage } from '@kits.ArkUI';\n" - } - ], - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - } - ] +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 5, + "endLine": 18, + "endColumn": 10, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 744, + "end": 749, + "replacementText": "a: number = 1" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 8, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 1, + "endLine": 24, + "endColumn": 9, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 13, + "endLine": 28, + "endColumn": 18, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 13, + "endLine": 30, + "endColumn": 18, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 1, + "endLine": 34, + "endColumn": 6, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 1, + "endLine": 35, + "endColumn": 7, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 5, + "endLine": 39, + "endColumn": 12, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1377, + "end": 1384, + "replacementText": "c: number = 1.5" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 40, + "column": 1, + "endLine": 40, + "endColumn": 6, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 1, + "endLine": 41, + "endColumn": 7, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 5, + "endLine": 45, + "endColumn": 10, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1561, + "end": 1566, + "replacementText": "d: number = 2" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 13, + "endLine": 49, + "endColumn": 18, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 51, + "column": 5, + "endLine": 51, + "endColumn": 10, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1712, + "end": 1717, + "replacementText": "n: number = 2" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 55, + "column": 5, + "endLine": 55, + "endColumn": 18, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1747, + "end": 1760, + "replacementText": "g: number[] = [1, 2, 3]" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 57, + "column": 5, + "endLine": 57, + "endColumn": 15, + "problem": "DefiniteAssignmentError", + "suggest": "", + "rule": "Definite assignment assertions are not supported (arkts-no-definite-assignment)", + "severity": "ERROR" + }, + { + "line": 59, + "column": 5, + "endLine": 59, + "endColumn": 18, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1786, + "end": 1799, + "replacementText": "t8: number = Infinity" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 5, + "endLine": 61, + "endColumn": 19, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1807, + "end": 1821, + "replacementText": "t9: number = -Infinity" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 63, + "column": 5, + "endLine": 63, + "endColumn": 14, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1830, + "end": 1839, + "replacementText": "t10: number = NaN" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 65, + "column": 5, + "endLine": 65, + "endColumn": 27, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1848, + "end": 1870, + "replacementText": "t11: number = Number.MAX_VALUE" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 67, + "column": 5, + "endLine": 67, + "endColumn": 27, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1879, + "end": 1901, + "replacementText": "t12: number = Number.MIN_VALUE" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 5, + "endLine": 73, + "endColumn": 11, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1959, + "end": 1965, + "replacementText": "o2: number = o" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 75, + "column": 5, + "endLine": 75, + "endColumn": 12, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1975, + "end": 1982, + "replacementText": "o3: number = oo" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 78, + "column": 4, + "endLine": 78, + "endColumn": 10, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2001, + "end": 2007, + "replacementText": "a: number = 1;" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 83, + "column": 5, + "endLine": 83, + "endColumn": 14, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2043, + "end": 2052, + "replacementText": "t2: number = +123" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 85, + "column": 5, + "endLine": 85, + "endColumn": 14, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2061, + "end": 2070, + "replacementText": "t3: number = -234" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 87, + "column": 5, + "endLine": 87, + "endColumn": 26, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2079, + "end": 2100, + "replacementText": "num: number = Math.floor(4.8)" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 89, + "column": 5, + "endLine": 89, + "endColumn": 27, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2124, + "end": 2146, + "replacementText": "value: number = parseInt(\"42\")" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 92, + "column": 1, + "endLine": 94, + "endColumn": 2, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2188, + "end": 2193, + "replacementText": "x: number = 2" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 92, + "column": 1, + "endLine": 94, + "endColumn": 2, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2195, + "end": 2200, + "replacementText": "y: number = 3" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 92, + "column": 1, + "endLine": 94, + "endColumn": 2, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2201, + "end": 2201, + "replacementText": ": number" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 96, + "column": 1, + "endLine": 98, + "endColumn": 2, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2264, + "end": 2264, + "replacementText": ": number" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 103, + "column": 1, + "endLine": 103, + "endColumn": 13, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2347, + "end": 2359, + "replacementText": "identity(42)" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 105, + "column": 5, + "endLine": 105, + "endColumn": 23, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2368, + "end": 2386, + "replacementText": "an_array: number[] = [1, 2, 3]" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 107, + "column": 5, + "endLine": 107, + "endColumn": 19, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2394, + "end": 2408, + "replacementText": "g: number = an_array[]" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 107, + "column": 18, + "endLine": 107, + "endColumn": 18, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 109, + "column": 7, + "endLine": 109, + "endColumn": 12, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2418, + "end": 2423, + "replacementText": "a: number = 1" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 115, + "column": 7, + "endLine": 115, + "endColumn": 20, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2493, + "end": 2506, + "replacementText": "test: number = Test.A" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 121, + "column": 3, + "endLine": 121, + "endColumn": 19, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2593, + "end": 2609, + "replacementText": "readonly c1: number = 1;" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 122, + "column": 3, + "endLine": 122, + "endColumn": 21, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2620, + "end": 2638, + "replacementText": "readonly c4: number = 1.7;" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 123, + "column": 3, + "endLine": 123, + "endColumn": 23, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2651, + "end": 2671, + "replacementText": "readonly c5: number = 0x123;" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 124, + "column": 3, + "endLine": 124, + "endColumn": 23, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2683, + "end": 2703, + "replacementText": "readonly c6: number = 0o123;" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 125, + "column": 3, + "endLine": 125, + "endColumn": 23, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2713, + "end": 2733, + "replacementText": "readonly c7: number = 0b101;" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 126, + "column": 3, + "endLine": 126, + "endColumn": 24, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2743, + "end": 2764, + "replacementText": "readonly c8: number[] = [1, 2, 3];" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 137, + "column": 7, + "endLine": 137, + "endColumn": 13, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2893, + "end": 2899, + "replacementText": "c1: number = 1" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 140, + "column": 3, + "endLine": 140, + "endColumn": 19, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2923, + "end": 2939, + "replacementText": "readonly a5: number = 4;" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 143, + "column": 7, + "endLine": 143, + "endColumn": 123, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 143, + "column": 30, + "endLine": 143, + "endColumn": 118, + "problem": "NumericSemantics", + "autofix": [ + { + "replacementText": "fingerprintPositionY: number = AppStorage.get(FingerprintConstants.COORDINATE_Y_OF_FINGERPRINT_UD_SCREEN_IN_PX) ?? 0", + "start": 2952, + "end": 3068 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 117, + "column": 2, + "endLine": 117, + "endColumn": 7, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 118, + "column": 2, + "endLine": 118, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 120, + "column": 4, + "endLine": 120, + "endColumn": 9, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 129, + "column": 5, + "endLine": 129, + "endColumn": 22, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 130, + "column": 7, + "endLine": 130, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 143, + "column": 30, + "endLine": 143, + "endColumn": 40, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 738, + "end": 738, + "replacementText": "\n\nimport { Entry, Component, State, RelativeContainer, Text, AppStorage } from '@kit.ArkUI';\n" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + } + ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/provide_annotation_1.ets.arkts2.json b/ets2panda/linter/test/main/provide_annotation_1.ets.arkts2.json index 1111f1a6e8..a11e915085 100644 --- a/ets2panda/linter/test/main/provide_annotation_1.ets.arkts2.json +++ b/ets2panda/linter/test/main/provide_annotation_1.ets.arkts2.json @@ -1,98 +1,158 @@ -{ - "copyright": [ - "Copyright (c) 2023-2024 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "result": [ - { - "line": 28, - "column": 3, - "endLine": 29, - "endColumn": 17, - "problem": "ProvideAnnotation", - "suggest": "", - "rule": "The \"@Provide\" annotation does not support dynamic parameters (arkui-provide-annotation-parameters)", - "severity": "ERROR" - }, - { - "line": 38, - "column": 3, - "endLine": 39, - "endColumn": 17, - "problem": "ProvideAnnotation", - "suggest": "", - "rule": "The \"@Provide\" annotation does not support dynamic parameters (arkui-provide-annotation-parameters)", - "severity": "ERROR" - }, - { - "line": 16, - "column": 2, - "endLine": 16, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 18, - "column": 4, - "endLine": 18, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 21, - "column": 5, - "endLine": 21, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 19, - "column": 3, - "endLine": 19, - "endColumn": 8, - "problem": "StrictDiagnostic", - "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", - "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", - "severity": "ERROR" - }, - { - "line": 29, - "column": 3, - "endLine": 29, - "endColumn": 8, - "problem": "StrictDiagnostic", - "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", - "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", - "severity": "ERROR" - }, - { - "line": 39, - "column": 3, - "endLine": 39, - "endColumn": 8, - "problem": "StrictDiagnostic", - "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", - "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", - "severity": "ERROR" - } - ] +{ + "copyright": [ + "Copyright (c) 2023-2024 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 28, + "column": 3, + "endLine": 29, + "endColumn": 17, + "problem": "ProvideAnnotation", + "suggest": "", + "rule": "The \"@Provide\" annotation does not support dynamic parameters (arkui-provide-annotation-parameters)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 3, + "endLine": 39, + "endColumn": 17, + "problem": "ProvideAnnotation", + "suggest": "", + "rule": "The \"@Provide\" annotation does not support dynamic parameters (arkui-provide-annotation-parameters)", + "severity": "ERROR" + }, + { + "line": 16, + "column": 2, + "endLine": 16, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 4, + "endLine": 18, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 5, + "endLine": 21, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 2, + "endLine": 26, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 4, + "endLine": 28, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 5, + "endLine": 31, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 36, + "column": 2, + "endLine": 36, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 4, + "endLine": 38, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 5, + "endLine": 41, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 3, + "endLine": 19, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 29, + "column": 3, + "endLine": 29, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 39, + "column": 3, + "endLine": 39, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + } + ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/provide_annotation_1.ets.autofix.json b/ets2panda/linter/test/main/provide_annotation_1.ets.autofix.json index 0aa483a8a8..48f1ccb311 100644 --- a/ets2panda/linter/test/main/provide_annotation_1.ets.autofix.json +++ b/ets2panda/linter/test/main/provide_annotation_1.ets.autofix.json @@ -1,119 +1,187 @@ -{ - "copyright": [ - "Copyright (c) 2023-2024 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "result": [ - { - "line": 28, - "column": 3, - "endLine": 29, - "endColumn": 17, - "problem": "ProvideAnnotation", - "autofix": [ - { - "start": 754, - "end": 771, - "replacementText": "@Provide({ alias: \"value\" })" - } - ], - "suggest": "", - "rule": "The \"@Provide\" annotation does not support dynamic parameters (arkui-provide-annotation-parameters)", - "severity": "ERROR" - }, - { - "line": 38, - "column": 3, - "endLine": 39, - "endColumn": 17, - "problem": "ProvideAnnotation", - "autofix": [ - { - "start": 867, - "end": 901, - "replacementText": "@Provide({ alias: \"value\", allowOverride: true })" - } - ], - "suggest": "", - "rule": "The \"@Provide\" annotation does not support dynamic parameters (arkui-provide-annotation-parameters)", - "severity": "ERROR" - }, - { - "line": 16, - "column": 2, - "endLine": 16, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 18, - "column": 4, - "endLine": 18, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 21, - "column": 5, - "endLine": 21, - "endColumn": 11, - "problem": "UIInterfaceImport", - "autofix": [ - { - "start": 616, - "end": 616, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kits.ArkUI';" - } - ], - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 19, - "column": 3, - "endLine": 19, - "endColumn": 8, - "problem": "StrictDiagnostic", - "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", - "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", - "severity": "ERROR" - }, - { - "line": 29, - "column": 3, - "endLine": 29, - "endColumn": 8, - "problem": "StrictDiagnostic", - "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", - "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", - "severity": "ERROR" - }, - { - "line": 39, - "column": 3, - "endLine": 39, - "endColumn": 8, - "problem": "StrictDiagnostic", - "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", - "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", - "severity": "ERROR" - } - ] +{ + "copyright": [ + "Copyright (c) 2023-2024 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 28, + "column": 3, + "endLine": 29, + "endColumn": 17, + "problem": "ProvideAnnotation", + "autofix": [ + { + "start": 754, + "end": 771, + "replacementText": "@Provide({ alias: \"value\" })" + } + ], + "suggest": "", + "rule": "The \"@Provide\" annotation does not support dynamic parameters (arkui-provide-annotation-parameters)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 3, + "endLine": 39, + "endColumn": 17, + "problem": "ProvideAnnotation", + "autofix": [ + { + "start": 867, + "end": 901, + "replacementText": "@Provide({ alias: \"value\", allowOverride: true })" + } + ], + "suggest": "", + "rule": "The \"@Provide\" annotation does not support dynamic parameters (arkui-provide-annotation-parameters)", + "severity": "ERROR" + }, + { + "line": 16, + "column": 2, + "endLine": 16, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 4, + "endLine": 18, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 5, + "endLine": 21, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 2, + "endLine": 26, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 4, + "endLine": 28, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 5, + "endLine": 31, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 36, + "column": 2, + "endLine": 36, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 4, + "endLine": 38, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 5, + "endLine": 41, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 616, + "end": 616, + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 3, + "endLine": 19, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 29, + "column": 3, + "endLine": 29, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 39, + "column": 3, + "endLine": 39, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + } + ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/provide_annotation_2.ets.arkts2.json b/ets2panda/linter/test/main/provide_annotation_2.ets.arkts2.json index d5f43e0789..5683673096 100644 --- a/ets2panda/linter/test/main/provide_annotation_2.ets.arkts2.json +++ b/ets2panda/linter/test/main/provide_annotation_2.ets.arkts2.json @@ -1,78 +1,138 @@ -{ - "copyright": [ - "Copyright (c) 2023-2024 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "result": [ - { - "line": 16, - "column": 2, - "endLine": 16, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 18, - "column": 4, - "endLine": 18, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 21, - "column": 5, - "endLine": 21, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 19, - "column": 3, - "endLine": 19, - "endColumn": 8, - "problem": "StrictDiagnostic", - "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", - "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", - "severity": "ERROR" - }, - { - "line": 29, - "column": 3, - "endLine": 29, - "endColumn": 8, - "problem": "StrictDiagnostic", - "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", - "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", - "severity": "ERROR" - }, - { - "line": 39, - "column": 3, - "endLine": 39, - "endColumn": 8, - "problem": "StrictDiagnostic", - "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", - "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", - "severity": "ERROR" - } - ] +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 2, + "endLine": 16, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 4, + "endLine": 18, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 5, + "endLine": 21, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 2, + "endLine": 26, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 4, + "endLine": 28, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 5, + "endLine": 31, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 36, + "column": 2, + "endLine": 36, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 4, + "endLine": 38, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 5, + "endLine": 41, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 3, + "endLine": 19, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 29, + "column": 3, + "endLine": 29, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 39, + "column": 3, + "endLine": 39, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + } + ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/provide_annotation_2.ets.autofix.json b/ets2panda/linter/test/main/provide_annotation_2.ets.autofix.json index 7f9665e664..24c62f190c 100644 --- a/ets2panda/linter/test/main/provide_annotation_2.ets.autofix.json +++ b/ets2panda/linter/test/main/provide_annotation_2.ets.autofix.json @@ -1,85 +1,153 @@ -{ - "copyright": [ - "Copyright (c) 2023-2024 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "result": [ - { - "line": 16, - "column": 2, - "endLine": 16, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 18, - "column": 4, - "endLine": 18, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 21, - "column": 5, - "endLine": 21, - "endColumn": 11, - "problem": "UIInterfaceImport", - "autofix": [ - { - "start": 616, - "end": 616, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kits.ArkUI';" - } - ], - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 19, - "column": 3, - "endLine": 19, - "endColumn": 8, - "problem": "StrictDiagnostic", - "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", - "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", - "severity": "ERROR" - }, - { - "line": 29, - "column": 3, - "endLine": 29, - "endColumn": 8, - "problem": "StrictDiagnostic", - "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", - "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", - "severity": "ERROR" - }, - { - "line": 39, - "column": 3, - "endLine": 39, - "endColumn": 8, - "problem": "StrictDiagnostic", - "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", - "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", - "severity": "ERROR" - } - ] +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 2, + "endLine": 16, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 4, + "endLine": 18, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 5, + "endLine": 21, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 2, + "endLine": 26, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 4, + "endLine": 28, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 5, + "endLine": 31, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 36, + "column": 2, + "endLine": 36, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 4, + "endLine": 38, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 5, + "endLine": 41, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 616, + "end": 616, + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 3, + "endLine": 19, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 29, + "column": 3, + "endLine": 29, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 39, + "column": 3, + "endLine": 39, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + } + ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_anon_1.ets.autofix.json b/ets2panda/linter/test/main/styles_decorator_anon_1.ets.autofix.json index 0256a3c35f..e3b6e42cd4 100644 --- a/ets2panda/linter/test/main/styles_decorator_anon_1.ets.autofix.json +++ b/ets2panda/linter/test/main/styles_decorator_anon_1.ets.autofix.json @@ -37,6 +37,7 @@ "endLine": 16, "endColumn": 7, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -47,6 +48,7 @@ "endLine": 17, "endColumn": 11, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -57,6 +59,7 @@ "endLine": 19, "endColumn": 16, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -67,6 +70,7 @@ "endLine": 20, "endColumn": 11, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -77,6 +81,7 @@ "endLine": 24, "endColumn": 11, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -91,7 +96,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, BuilderParam, Require, Button, CommonMethod, Color } from '@kits.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, BuilderParam, Require, Button, CommonMethod, Color } from '@kit.ArkUI';" } ], "suggest": "", diff --git a/ets2panda/linter/test/main/styles_decorator_anon_2.ets b/ets2panda/linter/test/main/styles_decorator_anon_2.ets index 3128e8490c..a0888e5b74 100644 --- a/ets2panda/linter/test/main/styles_decorator_anon_2.ets +++ b/ets2panda/linter/test/main/styles_decorator_anon_2.ets @@ -13,6 +13,8 @@ * limitations under the License. */ +import { Entry, Component, BuilderParam, Require, Button, CommonMethod, Color } from '@kit.ArkUI'; + @Entry @Component struct TestStateStyle { diff --git a/ets2panda/linter/test/main/styles_decorator_anon_2.ets.arkts2.json b/ets2panda/linter/test/main/styles_decorator_anon_2.ets.arkts2.json index 20326902e8..ca88f857e9 100644 --- a/ets2panda/linter/test/main/styles_decorator_anon_2.ets.arkts2.json +++ b/ets2panda/linter/test/main/styles_decorator_anon_2.ets.arkts2.json @@ -13,76 +13,5 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "result": [ - { - "line": 16, - "column": 2, - "endLine": 16, - "endColumn": 7, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 17, - "column": 2, - "endLine": 17, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 19, - "column": 4, - "endLine": 19, - "endColumn": 16, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 20, - "column": 4, - "endLine": 20, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 24, - "column": 5, - "endLine": 24, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 28, - "column": 26, - "endLine": 28, - "endColumn": 38, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 33, - "column": 34, - "endLine": 33, - "endColumn": 39, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - } - ] + "result": [] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_anon_2.ets.autofix.json b/ets2panda/linter/test/main/styles_decorator_anon_2.ets.autofix.json index 813c6ee518..ca88f857e9 100644 --- a/ets2panda/linter/test/main/styles_decorator_anon_2.ets.autofix.json +++ b/ets2panda/linter/test/main/styles_decorator_anon_2.ets.autofix.json @@ -13,83 +13,5 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "result": [ - { - "line": 16, - "column": 2, - "endLine": 16, - "endColumn": 7, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 17, - "column": 2, - "endLine": 17, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 19, - "column": 4, - "endLine": 19, - "endColumn": 16, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 20, - "column": 4, - "endLine": 20, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 24, - "column": 5, - "endLine": 24, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 28, - "column": 26, - "endLine": 28, - "endColumn": 38, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 33, - "column": 34, - "endLine": 33, - "endColumn": 39, - "problem": "UIInterfaceImport", - "autofix": [ - { - "start": 603, - "end": 603, - "replacementText": "\n\nimport { Entry, Component, BuilderParam, Require, Button, CommonMethod, Color } from '@kits.ArkUI';" - } - ], - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - } - ] + "result": [] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_global_1.ets.arkts2.json b/ets2panda/linter/test/main/styles_decorator_global_1.ets.arkts2.json index e0c5852c04..58303d7e15 100644 --- a/ets2panda/linter/test/main/styles_decorator_global_1.ets.arkts2.json +++ b/ets2panda/linter/test/main/styles_decorator_global_1.ets.arkts2.json @@ -74,6 +74,16 @@ "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, + { + "line": 51, + "column": 2, + "endLine": 51, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, { "line": 53, "column": 6, diff --git a/ets2panda/linter/test/main/styles_decorator_global_1.ets.autofix.json b/ets2panda/linter/test/main/styles_decorator_global_1.ets.autofix.json index 44d0256c44..5226a810e9 100644 --- a/ets2panda/linter/test/main/styles_decorator_global_1.ets.autofix.json +++ b/ets2panda/linter/test/main/styles_decorator_global_1.ets.autofix.json @@ -76,6 +76,7 @@ "endLine": 22, "endColumn": 23, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -86,6 +87,7 @@ "endLine": 31, "endColumn": 11, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -96,6 +98,18 @@ "endLine": 34, "endColumn": 15, "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 51, + "column": 2, + "endLine": 51, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -106,6 +120,7 @@ "endLine": 53, "endColumn": 18, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -116,6 +131,7 @@ "endLine": 54, "endColumn": 13, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -130,7 +146,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Component, Column, BuilderParam, Require, Button } from '@kits.ArkUI';" + "replacementText": "\n\nimport { CommonMethod, Color, Component, Column, BuilderParam, Require, Button } from '@kit.ArkUI';" } ], "suggest": "", diff --git a/ets2panda/linter/test/main/styles_decorator_global_2.ets b/ets2panda/linter/test/main/styles_decorator_global_2.ets index 2084a55a1f..a3f4363eb4 100644 --- a/ets2panda/linter/test/main/styles_decorator_global_2.ets +++ b/ets2panda/linter/test/main/styles_decorator_global_2.ets @@ -13,6 +13,8 @@ * limitations under the License. */ +import { CommonMethod, Color, Component, Column, BuilderParam, Require, Button } from '@kit.ArkUI'; + const mycolor: string = "#ffff00" function cardStyle1(instance: CommonMethod): void { diff --git a/ets2panda/linter/test/main/styles_decorator_global_2.ets.arkts2.json b/ets2panda/linter/test/main/styles_decorator_global_2.ets.arkts2.json index e6ae793311..ca88f857e9 100644 --- a/ets2panda/linter/test/main/styles_decorator_global_2.ets.arkts2.json +++ b/ets2panda/linter/test/main/styles_decorator_global_2.ets.arkts2.json @@ -13,76 +13,5 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "result": [ - { - "line": 18, - "column": 31, - "endLine": 18, - "endColumn": 43, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 20, - "column": 26, - "endLine": 20, - "endColumn": 31, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 29, - "column": 2, - "endLine": 29, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 32, - "column": 9, - "endLine": 32, - "endColumn": 15, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 49, - "column": 6, - "endLine": 49, - "endColumn": 18, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 50, - "column": 6, - "endLine": 50, - "endColumn": 13, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 54, - "column": 9, - "endLine": 54, - "endColumn": 15, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - } - ] + "result": [] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_global_2.ets.autofix.json b/ets2panda/linter/test/main/styles_decorator_global_2.ets.autofix.json index 2fb5c0d920..ca88f857e9 100644 --- a/ets2panda/linter/test/main/styles_decorator_global_2.ets.autofix.json +++ b/ets2panda/linter/test/main/styles_decorator_global_2.ets.autofix.json @@ -13,83 +13,5 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "result": [ - { - "line": 18, - "column": 31, - "endLine": 18, - "endColumn": 43, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 20, - "column": 26, - "endLine": 20, - "endColumn": 31, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 29, - "column": 2, - "endLine": 29, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 32, - "column": 9, - "endLine": 32, - "endColumn": 15, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 49, - "column": 6, - "endLine": 49, - "endColumn": 18, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 50, - "column": 6, - "endLine": 50, - "endColumn": 13, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 54, - "column": 9, - "endLine": 54, - "endColumn": 15, - "problem": "UIInterfaceImport", - "autofix": [ - { - "start": 603, - "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Component, Column, BuilderParam, Require, Button } from '@kits.ArkUI';" - } - ], - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - } - ] + "result": [] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_struct_1.ets b/ets2panda/linter/test/main/styles_decorator_struct_1.ets index de87528cfb..f757e64088 100644 --- a/ets2panda/linter/test/main/styles_decorator_struct_1.ets +++ b/ets2panda/linter/test/main/styles_decorator_struct_1.ets @@ -83,6 +83,17 @@ struct MyButton { } } +const TAG: string = 'common_ImageTest'; + +class MediaItem { + public path: string = ''; + public uri: string = ''; + + public getDateModified(): string { + return '' + } +} + @Component struct imageTest { private mediaItem: MediaItem | undefined; diff --git a/ets2panda/linter/test/main/styles_decorator_struct_1.ets.arkts2.json b/ets2panda/linter/test/main/styles_decorator_struct_1.ets.arkts2.json index b0c0508af5..a134245793 100644 --- a/ets2panda/linter/test/main/styles_decorator_struct_1.ets.arkts2.json +++ b/ets2panda/linter/test/main/styles_decorator_struct_1.ets.arkts2.json @@ -75,9 +75,9 @@ "severity": "ERROR" }, { - "line": 92, + "line": 103, "column": 3, - "endLine": 105, + "endLine": 116, "endColumn": 4, "problem": "StylesDecoratorNotSupported", "suggest": "", @@ -85,9 +85,9 @@ "severity": "ERROR" }, { - "line": 95, + "line": 106, "column": 18, - "endLine": 103, + "endLine": 114, "endColumn": 6, "problem": "LimitedReturnTypeInference", "suggest": "", @@ -124,6 +124,16 @@ "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, + { + "line": 32, + "column": 2, + "endLine": 32, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, { "line": 43, "column": 23, @@ -134,6 +144,46 @@ "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, + { + "line": 44, + "column": 12, + "endLine": 44, + "endColumn": 17, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 52, + "column": 5, + "endLine": 52, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 53, + "column": 7, + "endLine": 53, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 59, + "column": 2, + "endLine": 59, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, { "line": 61, "column": 4, @@ -154,6 +204,26 @@ "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, + { + "line": 67, + "column": 22, + "endLine": 67, + "endColumn": 27, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 22, + "endLine": 72, + "endColumn": 27, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, { "line": 76, "column": 5, @@ -165,9 +235,19 @@ "severity": "ERROR" }, { - "line": 90, + "line": 97, + "column": 2, + "endLine": 97, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 101, "column": 24, - "endLine": 90, + "endLine": 101, "endColumn": 37, "problem": "UIInterfaceImport", "suggest": "", diff --git a/ets2panda/linter/test/main/styles_decorator_struct_1.ets.autofix.json b/ets2panda/linter/test/main/styles_decorator_struct_1.ets.autofix.json index 3ccac695e3..0268206013 100644 --- a/ets2panda/linter/test/main/styles_decorator_struct_1.ets.autofix.json +++ b/ets2panda/linter/test/main/styles_decorator_struct_1.ets.autofix.json @@ -113,15 +113,15 @@ "severity": "ERROR" }, { - "line": 92, + "line": 103, "column": 3, - "endLine": 105, + "endLine": 116, "endColumn": 4, "problem": "StylesDecoratorNotSupported", "autofix": [ { - "start": 1694, - "end": 2190, + "start": 1867, + "end": 2363, "replacementText": "imageStyle = (instance: CommonMethod): void => {\n instance.draggable(this.isShowLongPressMenu() && this.isPC());\n instance.onDragStart(() => {\n console.info(TAG, 'onDragStart');\n this.touchVibrate(VibrateType.DRAG);\n if (this.mediaItem?.path) {\n this.previewUri =\n this.getPreviewUri(this.mediaItem?.path, this.mediaItem?.getDateModified?.(), false, true);\n }\n return this.DragBuilder;\n });\n instance.accessibilityText(this.isOpenTouchGuide ? this.getImageItemGridAccessibilityText() : '');\n };" } ], @@ -130,9 +130,9 @@ "severity": "ERROR" }, { - "line": 95, + "line": 106, "column": 18, - "endLine": 103, + "endLine": 114, "endColumn": 6, "problem": "LimitedReturnTypeInference", "suggest": "", @@ -145,6 +145,7 @@ "endLine": 16, "endColumn": 11, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -155,6 +156,7 @@ "endLine": 25, "endColumn": 11, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -165,6 +167,18 @@ "endLine": 26, "endColumn": 11, "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 2, + "endLine": 32, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -175,6 +189,51 @@ "endLine": 43, "endColumn": 28, "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 12, + "endLine": 44, + "endColumn": 17, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 52, + "column": 5, + "endLine": 52, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 53, + "column": 7, + "endLine": 53, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 59, + "column": 2, + "endLine": 59, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -185,6 +244,7 @@ "endLine": 61, "endColumn": 16, "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -195,6 +255,29 @@ "endLine": 62, "endColumn": 11, "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 67, + "column": 22, + "endLine": 67, + "endColumn": 27, + "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 22, + "endLine": 72, + "endColumn": 27, + "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -205,21 +288,33 @@ "endLine": 76, "endColumn": 11, "problem": "UIInterfaceImport", + "autofix": [], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 97, + "column": 2, + "endLine": 97, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 90, + "line": 101, "column": 24, - "endLine": 90, + "endLine": 101, "endColumn": 37, "problem": "UIInterfaceImport", "autofix": [ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kits.ArkUI';" + "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';" } ], "suggest": "", diff --git a/ets2panda/linter/test/main/styles_decorator_struct_1.ets.json b/ets2panda/linter/test/main/styles_decorator_struct_1.ets.json index d77952feeb..3b43bc06e5 100644 --- a/ets2panda/linter/test/main/styles_decorator_struct_1.ets.json +++ b/ets2panda/linter/test/main/styles_decorator_struct_1.ets.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 95, + "line": 106, "column": 18, - "endLine": 103, + "endLine": 114, "endColumn": 6, "problem": "LimitedReturnTypeInference", "suggest": "", diff --git a/ets2panda/linter/test/main/styles_decorator_struct_2.ets b/ets2panda/linter/test/main/styles_decorator_struct_2.ets index aa902ed6fe..82fe4ba1fe 100644 --- a/ets2panda/linter/test/main/styles_decorator_struct_2.ets +++ b/ets2panda/linter/test/main/styles_decorator_struct_2.ets @@ -13,6 +13,8 @@ * limitations under the License. */ +import { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI'; + @Component struct MyCard1 { cardStyle1 = (instance: CommonMethod): void => { @@ -78,6 +80,17 @@ struct MyButton { } } +const TAG: string = 'common_ImageTest'; + +class MediaItem { + public path: string = ''; + public uri: string = ''; + + public getDateModified(): string { + return '' + } +} + @Component struct imageTest { private mediaItem: MediaItem | undefined; diff --git a/ets2panda/linter/test/main/styles_decorator_struct_2.ets.arkts2.json b/ets2panda/linter/test/main/styles_decorator_struct_2.ets.arkts2.json index 7a64351059..13eb52986b 100644 --- a/ets2panda/linter/test/main/styles_decorator_struct_2.ets.arkts2.json +++ b/ets2panda/linter/test/main/styles_decorator_struct_2.ets.arkts2.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 75, + "line": 77, "column": 15, - "endLine": 75, + "endLine": 77, "endColumn": 34, "problem": "LimitedVoidType", "suggest": "", @@ -25,9 +25,9 @@ "severity": "ERROR" }, { - "line": 76, + "line": 78, "column": 16, - "endLine": 76, + "endLine": 78, "endColumn": 36, "problem": "LimitedVoidType", "suggest": "", @@ -35,104 +35,14 @@ "severity": "ERROR" }, { - "line": 89, + "line": 102, "column": 26, - "endLine": 97, + "endLine": 110, "endColumn": 6, "problem": "LimitedReturnTypeInference", "suggest": "", "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", "severity": "ERROR" - }, - { - "line": 16, - "column": 2, - "endLine": 16, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 18, - "column": 27, - "endLine": 18, - "endColumn": 39, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 24, - "column": 5, - "endLine": 24, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 25, - "column": 7, - "endLine": 25, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 40, - "column": 23, - "endLine": 40, - "endColumn": 28, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 58, - "column": 4, - "endLine": 58, - "endColumn": 16, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 59, - "column": 4, - "endLine": 59, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 71, - "column": 5, - "endLine": 71, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 85, - "column": 24, - "endLine": 85, - "endColumn": 37, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_struct_2.ets.autofix.json b/ets2panda/linter/test/main/styles_decorator_struct_2.ets.autofix.json index 3e83e8d210..13eb52986b 100644 --- a/ets2panda/linter/test/main/styles_decorator_struct_2.ets.autofix.json +++ b/ets2panda/linter/test/main/styles_decorator_struct_2.ets.autofix.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 75, + "line": 77, "column": 15, - "endLine": 75, + "endLine": 77, "endColumn": 34, "problem": "LimitedVoidType", "suggest": "", @@ -25,9 +25,9 @@ "severity": "ERROR" }, { - "line": 76, + "line": 78, "column": 16, - "endLine": 76, + "endLine": 78, "endColumn": 36, "problem": "LimitedVoidType", "suggest": "", @@ -35,111 +35,14 @@ "severity": "ERROR" }, { - "line": 89, + "line": 102, "column": 26, - "endLine": 97, + "endLine": 110, "endColumn": 6, "problem": "LimitedReturnTypeInference", "suggest": "", "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", "severity": "ERROR" - }, - { - "line": 16, - "column": 2, - "endLine": 16, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 18, - "column": 27, - "endLine": 18, - "endColumn": 39, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 24, - "column": 5, - "endLine": 24, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 25, - "column": 7, - "endLine": 25, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 40, - "column": 23, - "endLine": 40, - "endColumn": 28, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 58, - "column": 4, - "endLine": 58, - "endColumn": 16, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 59, - "column": 4, - "endLine": 59, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 71, - "column": 5, - "endLine": 71, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 85, - "column": 24, - "endLine": 85, - "endColumn": 37, - "problem": "UIInterfaceImport", - "autofix": [ - { - "start": 603, - "end": 603, - "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kits.ArkUI';" - } - ], - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_struct_2.ets.json b/ets2panda/linter/test/main/styles_decorator_struct_2.ets.json index 46020fc92a..ce898503c6 100644 --- a/ets2panda/linter/test/main/styles_decorator_struct_2.ets.json +++ b/ets2panda/linter/test/main/styles_decorator_struct_2.ets.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 89, + "line": 102, "column": 26, - "endLine": 97, + "endLine": 110, "endColumn": 6, "problem": "LimitedReturnTypeInference", "suggest": "", diff --git a/ets2panda/linter/test/sdkwhite/api_path_changed.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/api_path_changed.ets.arkts2.json old mode 100755 new mode 100644 index 5360a1f441..cec30e7f8b --- a/ets2panda/linter/test/sdkwhite/api_path_changed.ets.arkts2.json +++ b/ets2panda/linter/test/sdkwhite/api_path_changed.ets.arkts2.json @@ -84,6 +84,16 @@ "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, + { + "line": 19, + "column": 35, + "endLine": 19, + "endColumn": 44, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, { "line": 19, "column": 57, @@ -94,6 +104,16 @@ "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, + { + "line": 20, + "column": 19, + "endLine": 20, + "endColumn": 28, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, { "line": 22, "column": 5, -- Gitee From 7c550a27287818e022afead4ea213fbff2ed78dc Mon Sep 17 00:00:00 2001 From: sefayilmazunal Date: Wed, 16 Apr 2025 08:11:37 +0300 Subject: [PATCH 069/268] Restricted direct JS imports Description: - Restricted direct imports of JavaScript objects and properties, suggesting getPropertyByName() for property access. - Improved handling of JavaScript interop, including class inheritance, iteration, and function calls with ArkTS parameters. Issue: #IBW5ZK Signed-off-by: sefayilmazunal --- ets2panda/linter/src/lib/CookBookMsg.ts | 3 +- ets2panda/linter/src/lib/FaultAttrs.ts | 1 + ets2panda/linter/src/lib/FaultDesc.ts | 1 + ets2panda/linter/src/lib/Problems.ts | 1 + ets2panda/linter/src/lib/TypeScriptLinter.ts | 111 ++++++++++- .../linter/src/lib/autofixes/Autofixer.ts | 51 +++++ ets2panda/linter/src/lib/utils/TsUtils.ts | 121 +++++++++--- .../src/lib/utils/consts/ArkuiConstants.ts | 2 +- .../test/interop/interop_import_js_rules.ets | 61 ++++++ .../interop_import_js_rules.ets.args.json | 20 ++ .../interop_import_js_rules.ets.arkts2.json | 138 +++++++++++++ .../interop_import_js_rules.ets.autofix.json | 187 ++++++++++++++++++ .../interop/interop_import_js_rules.ets.json | 17 ++ .../oh_modules/interop_import_js_rules.js | 32 +++ .../main/extends_expression.ets.arkts2.json | 8 +- 15 files changed, 714 insertions(+), 40 deletions(-) create mode 100644 ets2panda/linter/test/interop/interop_import_js_rules.ets create mode 100644 ets2panda/linter/test/interop/interop_import_js_rules.ets.args.json create mode 100644 ets2panda/linter/test/interop/interop_import_js_rules.ets.arkts2.json create mode 100644 ets2panda/linter/test/interop/interop_import_js_rules.ets.autofix.json create mode 100644 ets2panda/linter/test/interop/interop_import_js_rules.ets.json create mode 100644 ets2panda/linter/test/interop/oh_modules/interop_import_js_rules.js diff --git a/ets2panda/linter/src/lib/CookBookMsg.ts b/ets2panda/linter/src/lib/CookBookMsg.ts index 4a5677c9d8..b41449034a 100644 --- a/ets2panda/linter/src/lib/CookBookMsg.ts +++ b/ets2panda/linter/src/lib/CookBookMsg.ts @@ -258,7 +258,7 @@ cookBookTag[251] = '"!!" for bidirectional data binding is not supported (arkui- cookBookTag[252] = '"$$" for bidirectional data binding is not supported (arkui-no-$$-bidirectional-data-binding)'; cookBookTag[253] = '"${variable}" for decorator binding is not supported (arkui-link-decorator-passing)'; cookBookTag[254] = '"@Extend" decorator is not supported (arkui-no-extend-decorator)'; -cookBookTag[255] = 'Extends or implemetns expression are not supported(arkts-no-extends-expression)'; +cookBookTag[255] = 'Extends or implements expression are not supported(arkts-no-extends-expression)'; cookBookTag[256] = '"@Styles" decorator is not supported (arkui-no-styles-decorator)'; cookBookTag[257] = '"@AnimatableExtend" decorator should be transformed to use receiver (arkui-animatableextend-use-receiver)'; @@ -288,4 +288,5 @@ cookBookTag[314] = cookBookTag[315] = 'API path have changed - please update your imports accordingly (arkts-sdk-no-decl-with-duplicate-name)'; cookBookTag[316] = 'Using typeof as a type is not allowed in this API (arkts-sdk-Type-Query)'; +cookBookTag[319] = 'Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)'; cookBookTag[321] = 'Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)'; diff --git a/ets2panda/linter/src/lib/FaultAttrs.ts b/ets2panda/linter/src/lib/FaultAttrs.ts index 091ca6410f..d1a86bff39 100644 --- a/ets2panda/linter/src/lib/FaultAttrs.ts +++ b/ets2panda/linter/src/lib/FaultAttrs.ts @@ -197,4 +197,5 @@ faultsAttrs[FaultID.ConstructorTypesDeprecated] = new FaultAttributes(313); faultsAttrs[FaultID.QuotedHyphenPropsDeprecated] = new FaultAttributes(314); faultsAttrs[FaultID.ApiPathChanged] = new FaultAttributes(315); faultsAttrs[FaultID.SdkTypeQuery] = new FaultAttributes(316); +faultsAttrs[FaultID.InteropJsObjectUsage] = new FaultAttributes(319); faultsAttrs[FaultID.LimitedStdLibNoImportConcurrency] = new FaultAttributes(321); diff --git a/ets2panda/linter/src/lib/FaultDesc.ts b/ets2panda/linter/src/lib/FaultDesc.ts index 09e2232d83..5e2d3fce06 100644 --- a/ets2panda/linter/src/lib/FaultDesc.ts +++ b/ets2panda/linter/src/lib/FaultDesc.ts @@ -164,6 +164,7 @@ faultDesc[FaultID.InvalidIdentifier] = 'Invalid identifiers'; faultDesc[FaultID.ExtendsExpression] = 'Extends Expression'; faultDesc[FaultID.NumericSemantics] = 'Numeric semantics'; faultDesc[FaultID.AnimatableExtendDecoratorTransform] = '"@AnimatableExtend" decorator'; +faultDesc[FaultID.InteropJsObjectUsage] = 'Interop JS object usage'; faultDesc[FaultID.NoDuplicateFunctionName] = 'No duplicate function name'; faultDesc[FaultID.OhmUrlFullPath] = 'Require full path file name'; faultDesc[FaultID.UIInterfaceImport] = 'UI interface'; diff --git a/ets2panda/linter/src/lib/Problems.ts b/ets2panda/linter/src/lib/Problems.ts index 88e8e4d311..d4fc37a9ab 100644 --- a/ets2panda/linter/src/lib/Problems.ts +++ b/ets2panda/linter/src/lib/Problems.ts @@ -186,6 +186,7 @@ export enum FaultID { QuotedHyphenPropsDeprecated, ApiPathChanged, SdkTypeQuery, + InteropJsObjectUsage, LimitedStdLibNoImportConcurrency, // this should always be last enum LAST_ID diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index 69145df2b4..078918d4ea 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -287,7 +287,7 @@ export class TypeScriptLinter { [ts.SyntaxKind.ArrayType, this.handleArrayType], [ts.SyntaxKind.LiteralType, this.handleLimitedLiteralType], [ts.SyntaxKind.NonNullExpression, this.handleNonNullExpression], - [ts.SyntaxKind.HeritageClause, this.checkExtendsExpression], + [ts.SyntaxKind.HeritageClause, this.handleHeritageClause], [ts.SyntaxKind.TaggedTemplateExpression, this.handleTaggedTemplatesExpression], [ts.SyntaxKind.StructDeclaration, this.handleStructDeclaration] ]); @@ -966,6 +966,7 @@ export class TypeScriptLinter { } this.checkFunctionProperty(propertyAccessNode, baseExprSym, baseExprType); this.handleSdkForConstructorFuncs(propertyAccessNode); + this.fixJsImportPropertyAccessExpression(node); } checkFunctionProperty( @@ -1649,6 +1650,11 @@ export class TypeScriptLinter { return; } + // Early return if the variable is imported from JS + if (this.tsUtils.isPossiblyImportedFromJS(name) || this.tsUtils.isPossiblyImportedFromJS(initializer)) { + return; + } + const sym = this.tsTypeChecker.getSymbolAtLocation(name); if (!sym) { return; @@ -2989,6 +2995,8 @@ export class TypeScriptLinter { this.handleIndexNegative(node); } this.checkArrayIndexType(tsElemAccessBaseExprType, tsElemAccessArgType, tsElementAccessExpr); + + this.fixJsImportElementAccessExpression(tsElementAccessExpr); } private checkArrayIndexType(exprType: ts.Type, argType: ts.Type, expr: ts.ElementAccessExpression): void { @@ -3249,6 +3257,7 @@ export class TypeScriptLinter { this.checkArkTSObjectInterop(tsCallExpr); this.handleAppStorageCallExpression(tsCallExpr); + this.fixJsImportCallExpression(tsCallExpr); } private handleAppStorageCallExpression(tsCallExpr: ts.CallExpression): void { @@ -5150,7 +5159,7 @@ export class TypeScriptLinter { } } - private checkExtendsExpression(node: ts.HeritageClause): void { + private handleHeritageClause(node: ts.HeritageClause): void { if (!this.options.arkts2) { return; } @@ -5167,6 +5176,8 @@ export class TypeScriptLinter { this.tsUtils.isBuiltinClassHeritageClause(node) ) { this.incrementCounters(expr, FaultID.ExtendsExpression); + } else if (ts.isIdentifier(expr)) { + this.fixJsImportExtendsClass(node.parent, expr); } }); } @@ -5799,6 +5810,102 @@ export class TypeScriptLinter { } } + private fixJsImportCallExpression(callExpr: ts.CallExpression): void { + if (!this.options.arkts2) { + return; + } + + const identifier = this.tsUtils.findIdentifierInExpression(callExpr); + if (!identifier) { + return; + } + + if (!this.tsUtils.isImportedFromJS(identifier)) { + return; + } + + this.incrementCounters(callExpr, FaultID.InteropJsObjectUsage); + } + + private fixJsImportExtendsClass( + node: ts.ClassLikeDeclaration | ts.InterfaceDeclaration, + identifier: ts.Identifier + ): void { + if (!this.options.arkts2) { + return; + } + + if (!this.tsUtils.isImportedFromJS(identifier)) { + return; + } + + const className = node.name?.text; + if (!className) { + return; + } + this.incrementCounters(node, FaultID.InteropJsObjectUsage); + } + + private fixJsImportPropertyAccessExpression(node: ts.Node): void { + if (!this.options.arkts2) { + return; + } + + const identifier = this.tsUtils.findIdentifierInExpression(node); + if (!identifier) { + return; + } + + // Try direct check first + if (this.tsUtils.isImportedFromJS(identifier)) { + const autofix = + this.autofixer?.createReplacementForJsImportPropertyAccessExpression(node as ts.PropertyAccessExpression); + this.incrementCounters(node, FaultID.InteropJsObjectUsage, autofix); + return; + } + + // Try indirect reference (e.g., const foo = importedObj;) + const originalIdentifier = this.tsUtils.findOriginalIdentifier(identifier); + if (originalIdentifier && this.tsUtils.isImportedFromJS(originalIdentifier)) { + const autofix = + this.autofixer?.createReplacementForJsIndirectImportPropertyAccessExpression( + node as ts.PropertyAccessExpression + ); + this.incrementCounters(node, FaultID.InteropJsObjectUsage, autofix); + } + } + + private fixJsImportElementAccessExpression(elementAccessExpr: ts.ElementAccessExpression): void { + if (!this.options.arkts2) { + return; + } + + const variableDeclaration = ts.isIdentifier(elementAccessExpr.expression) ? + this.tsUtils.findVariableDeclaration(elementAccessExpr.expression) : + undefined; + if (!variableDeclaration?.initializer) { + return; + } + + const identifier = ts.isPropertyAccessExpression(variableDeclaration.initializer) ? + variableDeclaration.initializer.expression as ts.Identifier : + undefined; + if (!identifier) { + return; + } + + if (!this.tsUtils.isImportedFromJS(identifier)) { + return; + } + + const autofix = this.autofixer?.createReplacementJsImportElementAccessExpression( + elementAccessExpr, + elementAccessExpr.expression as ts.Identifier + ); + + this.incrementCounters(elementAccessExpr, FaultID.InteropJsObjectUsage, autofix); + } + private checkStdLibConcurrencyImport(importDeclaration: ts.ImportDeclaration): void { if (!this.options.arkts2) { return; diff --git a/ets2panda/linter/src/lib/autofixes/Autofixer.ts b/ets2panda/linter/src/lib/autofixes/Autofixer.ts index 5e842eecb2..80a19e3cc4 100644 --- a/ets2panda/linter/src/lib/autofixes/Autofixer.ts +++ b/ets2panda/linter/src/lib/autofixes/Autofixer.ts @@ -3050,6 +3050,57 @@ export class Autofixer { return [{ start: binaryExpr.getStart(), end: binaryExpr.getEnd(), replacementText }]; } + createReplacementForJsIndirectImportPropertyAccessExpression(node: ts.PropertyAccessExpression): Autofix[] { + // Bypass eslint-check + void this; + + const objName = node.expression.getText(); + const propName = node.name.getText(); + + let start = node.getStart(); + let end = node.getEnd(); + let replacementText = `${objName}.getPropertyByName('${propName}')`; + + // Check if there is an "as number" type assertion in the statement + if (ts.isAsExpression(node.parent) && node.parent.type.kind === ts.SyntaxKind.NumberKeyword) { + replacementText += '.toNumber()'; + start = node.parent.getStart(); + end = node.parent.getEnd(); + } + + return [{ replacementText, start, end }]; + } + + createReplacementForJsImportPropertyAccessExpression(node: ts.PropertyAccessExpression): Autofix[] { + const objName = node.expression.getText(); + const propName = node.name.getText(); + + const start = node.getStart(); + const end = node.getEnd(); + + const replacement = `${objName}.getPropertyByName('${propName}')${this.utils.findTypeOfNodeForConversion(node)}`; + + return [{ replacementText: replacement, start, end }]; + } + + createReplacementJsImportElementAccessExpression( + elementAccessExpr: ts.ElementAccessExpression, + identifier: ts.Identifier + ): Autofix[] { + const isParentBinaryExp = ts.isBinaryExpression(elementAccessExpr.parent); + const exprText = elementAccessExpr.argumentExpression.getText(); + const start = isParentBinaryExp ? elementAccessExpr.parent.getStart() : elementAccessExpr.getStart(); + const end = isParentBinaryExp ? elementAccessExpr.parent.getEnd() : elementAccessExpr.getEnd(); + + const replacementText = + isParentBinaryExp && elementAccessExpr.parent.operatorToken.kind === ts.SyntaxKind.EqualsToken ? + `${identifier.text}.setPropertyByIndex(${exprText},` + + ` ESObject.wrap(${elementAccessExpr.parent.right.getText()}))` : + `${identifier.text}.getPropertyByIndex(${exprText})` + + this.utils.findTypeOfNodeForConversion(elementAccessExpr); + return [{ replacementText, start, end }]; + } + fixAppStorageCallExpression(callExpr: ts.CallExpression): Autofix[] | undefined { const varDecl = Autofixer.findParentVariableDeclaration(callExpr); if (!varDecl || varDecl.type) { diff --git a/ets2panda/linter/src/lib/utils/TsUtils.ts b/ets2panda/linter/src/lib/utils/TsUtils.ts index 2dce4b6fec..8334bbac03 100644 --- a/ets2panda/linter/src/lib/utils/TsUtils.ts +++ b/ets2panda/linter/src/lib/utils/TsUtils.ts @@ -44,6 +44,7 @@ import type { LinterOptions } from '../LinterOptions'; import { ETS } from './consts/TsSuffix'; import { STRINGLITERAL_NUMBER, STRINGLITERAL_NUMBER_ARRAY } from './consts/StringLiteral'; import { ETS_MODULE, VALID_OHM_COMPONENTS_MODULE_PATH } from './consts/OhmUrl'; +import { EXTNAME_JS } from './consts/ExtensionName'; export const SYMBOL = 'Symbol'; export const SYMBOL_CONSTRUCTOR = 'SymbolConstructor'; @@ -3364,52 +3365,108 @@ export class TsUtils { return isNumberLike; } - static isOhModule(path: string): boolean { - if (path.includes(ETS_MODULE)) { + isImportedFromJS(identifier: ts.Identifier): boolean { + const sym = this.trueSymbolAtLocation(identifier); + const declaration = sym?.declarations?.[0]; + return !!declaration?.getSourceFile().fileName.endsWith(EXTNAME_JS); + } + + isPossiblyImportedFromJS(node: ts.Node): boolean { + const identifier = this.findIdentifierInExpression(node); + if (!identifier) { + return false; + } + + // Direct import check + if (this.isImportedFromJS(identifier)) { return true; } - return false; + // Indirect import check + const originalIdentifier = this.findOriginalIdentifier(identifier); + return !!originalIdentifier && this.isImportedFromJS(originalIdentifier); + } + + /** + * Extracts the Identifier from the given node. returns undefined if no Identifier is found. + * + * Direct Identifier (foo) → Returns it. + * Binary Expressions (foo + bar) → Recursively checks left and right. + * Property Access (obj.foo) → Extracts obj. + * Function Calls (foo()) → Extracts foo. + * Array Access (arr[foo]) → Extracts foo. + * Variable Declaration (let foo = ...) → Extracts foo. + * Assignments (foo = ...) → Extracts foo. + */ + findIdentifierInExpression(node: ts.Node): ts.Identifier | undefined { + if (ts.isIdentifier(node)) { + return node; + } else if (ts.isBinaryExpression(node)) { + return this.findIdentifierInExpression(node.left) || this.findIdentifierInExpression(node.right); + } else if (ts.isPropertyAccessExpression(node)) { + return this.findIdentifierInExpression(node.expression); + } else if (ts.isCallExpression(node) || ts.isNewExpression(node)) { + return this.findIdentifierInExpression(node.expression); + } else if (ts.isElementAccessExpression(node)) { + return this.findIdentifierInExpression(node.expression); + } else if (ts.isAsExpression(node)) { + return this.findIdentifierInExpression(node.expression); + } else if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name)) { + return node.name; + } + return undefined; } - static isValidOhModulePath(path: string): boolean { - if (path.includes(VALID_OHM_COMPONENTS_MODULE_PATH)) { - return true; + // Helper function: Find the variable declaration of an identifier -> let arr = foo.arr -> returns foo + findVariableDeclaration(identifier: ts.Identifier): ts.VariableDeclaration | undefined { + const sym = this.tsTypeChecker.getSymbolAtLocation(identifier); + const decl = TsUtils.getDeclaration(sym); + if (decl && ts.isVariableDeclaration(decl)) { + return decl; } - - return false; + return undefined; } - isMixedEnumType(enumType: ts.EnumType): boolean { - let hasNumber = false; - let hasString = false; - for (const member of enumType.getProperties()) { - if (!member.valueDeclaration) { - continue; - } - const memberType = this.tsTypeChecker.getTypeOfSymbolAtLocation(member, member.valueDeclaration); + findOriginalIdentifier(identifier: ts.Identifier): ts.Identifier | undefined { + const variableDeclaration = this.findVariableDeclaration(identifier); + if (!variableDeclaration?.initializer) { + return undefined; + } - // Check the type of the enum value (number or string) - if (memberType.flags & ts.TypeFlags.Number) { - hasNumber = true; - } else if (memberType.flags & ts.TypeFlags.String) { - hasString = true; - } + const originalIdentifier = ts.isPropertyAccessExpression(variableDeclaration.initializer) ? + (variableDeclaration.initializer.expression as ts.Identifier) : + undefined; + + if (!originalIdentifier) { + return undefined; } - return hasString && hasNumber; + return originalIdentifier; } - static isStringLiteralUnionType(baseType: ts.Type): boolean { - if (baseType.isUnion()) { - const unionType = baseType; - for (const type of unionType.types) { - if (type.isStringLiteral()) { - return true; - } - } + findTypeOfNodeForConversion(node: ts.Node): string { + // Get type of the property + const type = this.tsTypeChecker.getTypeAtLocation(node); + // Default + let conversionMethod = ''; + + if (this.tsTypeChecker.typeToString(type) === 'boolean') { + conversionMethod = '.toBoolean()'; + } else if (this.tsTypeChecker.typeToString(type) === 'number') { + conversionMethod = '.toNumber()'; + } else if (this.tsTypeChecker.typeToString(type) === 'string') { + conversionMethod = '.toString()'; } - return false; + + return conversionMethod; + } + + static isOhModule(path: string): boolean { + return path.includes(ETS_MODULE); + } + + static isValidOhModulePath(path: string): boolean { + return path.includes(VALID_OHM_COMPONENTS_MODULE_PATH); } findEnumMember(enumDecl: ts.EnumDeclaration | undefined, name: string): ts.Symbol | undefined { diff --git a/ets2panda/linter/src/lib/utils/consts/ArkuiConstants.ts b/ets2panda/linter/src/lib/utils/consts/ArkuiConstants.ts index 4764c82dfd..aab38266ad 100644 --- a/ets2panda/linter/src/lib/utils/consts/ArkuiConstants.ts +++ b/ets2panda/linter/src/lib/utils/consts/ArkuiConstants.ts @@ -54,4 +54,4 @@ export const GET_LOCAL_STORAGE_FUNC_NAME = '__get_local_storage__'; export const PROVIDE_DECORATOR_NAME = 'Provide'; export const PROVIDE_ALIAS_PROPERTY_NAME = 'alias'; -export const PROVIDE_ALLOW_OVERRIDE_PROPERTY_NAME = 'allowOverride'; \ No newline at end of file +export const PROVIDE_ALLOW_OVERRIDE_PROPERTY_NAME = 'allowOverride'; diff --git a/ets2panda/linter/test/interop/interop_import_js_rules.ets b/ets2panda/linter/test/interop/interop_import_js_rules.ets new file mode 100644 index 0000000000..9962b58ee5 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_js_rules.ets @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { foo } from "./oh_modules/interop_import_js_rules" +import { ff1, ff2 } from "./oh_modules/interop_import_js_rules" + +import { A } from "./oh_modules/interop_import_js_rules" +import { C } from "./oh_modules/interop_import_js_rules" + +import { ff3 } from "./oh_modules/interop_import_js_rules" + +import { ff4 } from "./oh_modules/interop_import_js_rules" + +import { handle } from "./oh_modules/interop_import_js_rules" + +if (foo.isGood) {} + +if (ff1.f1 > 18) { + console.log("adult"); +} + +class B extends A {} +let b = new B() +let c = new B() + +class E extends C {} // no autofix+error, handled in different pr + +try { + ff4() +} catch (e) { + e as number // 123 +} + +let arr = ff3.arr +let len = arr.length as number +for (let i = 0; i < len; ++i) { + let x = arr[i] + arr[i] = 0 +} + +interface Person { + name: string +} + +function foo2(p: Person) {} +let lambda = (p: Person) => {} + +handle(foo2) +handle(lambda) diff --git a/ets2panda/linter/test/interop/interop_import_js_rules.ets.args.json b/ets2panda/linter/test/interop/interop_import_js_rules.ets.args.json new file mode 100644 index 0000000000..ff420e5839 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_js_rules.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2" + } +} diff --git a/ets2panda/linter/test/interop/interop_import_js_rules.ets.arkts2.json b/ets2panda/linter/test/interop/interop_import_js_rules.ets.arkts2.json new file mode 100644 index 0000000000..3ce37c6742 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_js_rules.ets.arkts2.json @@ -0,0 +1,138 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 28, + "column": 5, + "endLine": 28, + "endColumn": 15, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 5, + "endLine": 30, + "endColumn": 11, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 1, + "endLine": 34, + "endColumn": 21, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 1, + "endLine": 38, + "endColumn": 21, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 3, + "endLine": 41, + "endColumn": 8, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 46, + "column": 11, + "endLine": 46, + "endColumn": 18, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 47, + "column": 11, + "endLine": 47, + "endColumn": 21, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 48, + "column": 10, + "endLine": 48, + "endColumn": 15, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 11, + "endLine": 49, + "endColumn": 17, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 50, + "column": 3, + "endLine": 50, + "endColumn": 9, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 60, + "column": 1, + "endLine": 60, + "endColumn": 13, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 1, + "endLine": 61, + "endColumn": 15, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/interop/interop_import_js_rules.ets.autofix.json b/ets2panda/linter/test/interop/interop_import_js_rules.ets.autofix.json new file mode 100644 index 0000000000..f386321dc2 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_js_rules.ets.autofix.json @@ -0,0 +1,187 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 28, + "column": 5, + "endLine": 28, + "endColumn": 15, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "foo.getPropertyByName('isGood').toBoolean()", + "start": 1031, + "end": 1041 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 5, + "endLine": 30, + "endColumn": 11, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "ff1.getPropertyByName('f1').toNumber()", + "start": 1051, + "end": 1057 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 1, + "endLine": 34, + "endColumn": 21, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 1, + "endLine": 38, + "endColumn": 21, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 3, + "endLine": 41, + "endColumn": 8, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 46, + "column": 11, + "endLine": 46, + "endColumn": 18, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "ff3.getPropertyByName('arr')", + "start": 1277, + "end": 1284 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 47, + "column": 11, + "endLine": 47, + "endColumn": 21, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "arr.getPropertyByName('length').toNumber()", + "start": 1295, + "end": 1315 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 48, + "column": 10, + "endLine": 48, + "endColumn": 15, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1325, + "end": 1330, + "replacementText": "i: number = 0" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 11, + "endLine": 49, + "endColumn": 17, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "arr.getPropertyByIndex(i).toNumber()", + "start": 1358, + "end": 1364 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 50, + "column": 3, + "endLine": 50, + "endColumn": 9, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "arr.setPropertyByIndex(i, ESObject.wrap(0))", + "start": 1367, + "end": 1377 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 60, + "column": 1, + "endLine": 60, + "endColumn": 13, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 1, + "endLine": 61, + "endColumn": 15, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/interop/interop_import_js_rules.ets.json b/ets2panda/linter/test/interop/interop_import_js_rules.ets.json new file mode 100644 index 0000000000..dd03fcf544 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_js_rules.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} diff --git a/ets2panda/linter/test/interop/oh_modules/interop_import_js_rules.js b/ets2panda/linter/test/interop/oh_modules/interop_import_js_rules.js new file mode 100644 index 0000000000..13f6e3cd58 --- /dev/null +++ b/ets2panda/linter/test/interop/oh_modules/interop_import_js_rules.js @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export let foo = {isGood: true} +export let ff1 = {f1: 10} +export let ff2 = {f2: 15} + +export class A {} +export class C {} + +export let ff3 = {arr: [1, 2, 3, 4, 5, 6, 7, 8, 9]} + +export function ff4() { + throw 123 +} + +export function handle(cb) { + let p = {name: 'hello'} + cb(p) +} diff --git a/ets2panda/linter/test/main/extends_expression.ets.arkts2.json b/ets2panda/linter/test/main/extends_expression.ets.arkts2.json index b347754475..1c73b16814 100755 --- a/ets2panda/linter/test/main/extends_expression.ets.arkts2.json +++ b/ets2panda/linter/test/main/extends_expression.ets.arkts2.json @@ -31,7 +31,7 @@ "endColumn": 18, "problem": "ExtendsExpression", "suggest": "", - "rule": "Extends or implemetns expression are not supported(arkts-no-extends-expression)", + "rule": "Extends or implements expression are not supported(arkts-no-extends-expression)", "severity": "ERROR" }, { @@ -111,7 +111,7 @@ "endColumn": 39, "problem": "ExtendsExpression", "suggest": "", - "rule": "Extends or implemetns expression are not supported(arkts-no-extends-expression)", + "rule": "Extends or implements expression are not supported(arkts-no-extends-expression)", "severity": "ERROR" }, { @@ -121,8 +121,8 @@ "endColumn": 39, "problem": "ExtendsExpression", "suggest": "", - "rule": "Extends or implemetns expression are not supported(arkts-no-extends-expression)", + "rule": "Extends or implements expression are not supported(arkts-no-extends-expression)", "severity": "ERROR" } ] -} \ No newline at end of file +} -- Gitee From 8a6efaf75c78907a0649f4f5b0e815047c29a02e Mon Sep 17 00:00:00 2001 From: zhongning Date: Tue, 8 Apr 2025 11:39:02 +0800 Subject: [PATCH 070/268] fix issue for arkts-no-classes-as-obj Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBUOMS Test scenarios:optional parameters Signed-off-by: zhongning --- .../linter/test/main/class_as_object.ets | 20 +- .../test/main/class_as_object.ets.arkts2.json | 82 +++- .../linter/test/main/class_as_object.ets.json | 460 ++++++++++++++++++ .../test/main/explicit_function_type.ets.json | 94 ++-- ets2panda/linter/test/main/modules.ets.json | 10 + ...t_literals_prop_func_type.ets.autofix.json | 10 + .../object_literals_prop_func_type.ets.json | 10 + ets2panda/linter/test/rules/rule84.ets.json | 10 + 8 files changed, 647 insertions(+), 49 deletions(-) diff --git a/ets2panda/linter/test/main/class_as_object.ets b/ets2panda/linter/test/main/class_as_object.ets index b1e3cf1f68..fcc5a36250 100644 --- a/ets2panda/linter/test/main/class_as_object.ets +++ b/ets2panda/linter/test/main/class_as_object.ets @@ -185,4 +185,22 @@ const str = String('value'); const sym = Symbol('symbol1'); const syntaxErr = SyntaxError('message'); const typeErr = TypeError('message'); -const uriErr = URIError('message'); \ No newline at end of file +const uriErr = URIError('message'); + +let aaa4 = typeof DataView; + +let obj = new Object(); +switch (obj) { + case Object: + console.log('A'); + break; + default: + console.log('F'); +} + +function parse(type: "number" | "boolean", value: string): number | boolean { + return type === "number" ? Number(value) : value === "true"; +} +function format(input: string | number): string[] | number[] { + return typeof input === "string" ? input.split("") : input.toString().split("").map(Number); +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/class_as_object.ets.arkts2.json b/ets2panda/linter/test/main/class_as_object.ets.arkts2.json index 3d497ea7a8..743b046cc0 100644 --- a/ets2panda/linter/test/main/class_as_object.ets.arkts2.json +++ b/ets2panda/linter/test/main/class_as_object.ets.arkts2.json @@ -345,14 +345,14 @@ "severity": "ERROR" }, { - "line": 128, - "column": 15, - "endLine": 128, - "endColumn": 23, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" + "line": 128, + "column": 15, + "endLine": 128, + "endColumn": 23, + "problem": "ExplicitFunctionType", + "suggest": "", + "rule": "The function type should be explicit (arkts-no-ts-like-function)", + "severity": "ERROR" }, { "line": 129, @@ -775,14 +775,14 @@ "severity": "ERROR" }, { - "line": 178, - "column": 14, - "endLine": 178, - "endColumn": 22, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" + "line": 178, + "column": 14, + "endLine": 178, + "endColumn": 22, + "problem": "ExplicitFunctionType", + "suggest": "", + "rule": "The function type should be explicit (arkts-no-ts-like-function)", + "severity": "ERROR" }, { "line": 179, @@ -823,6 +823,56 @@ "suggest": "", "rule": "\"Symbol()\" API is not supported (arkts-no-symbol)", "severity": "ERROR" + }, + { + "line": 190, + "column": 19, + "endLine": 190, + "endColumn": 27, + "problem": "ClassAsObjectError", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "ERROR" + }, + { + "line": 193, + "column": 9, + "endLine": 193, + "endColumn": 12, + "problem": "SwitchExpression", + "suggest": "", + "rule": "The switch expression type must be of type number,string or enum (arkts-switch-expr)", + "severity": "ERROR" + }, + { + "line": 194, + "column": 8, + "endLine": 194, + "endColumn": 14, + "problem": "ClassAsObjectError", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "ERROR" + }, + { + "line": 205, + "column": 56, + "endLine": 205, + "endColumn": 94, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 205, + "column": 87, + "endLine": 205, + "endColumn": 93, + "problem": "ClassAsObjectError", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/class_as_object.ets.json b/ets2panda/linter/test/main/class_as_object.ets.json index 9a3588b472..cb35d61776 100644 --- a/ets2panda/linter/test/main/class_as_object.ets.json +++ b/ets2panda/linter/test/main/class_as_object.ets.json @@ -192,6 +192,436 @@ "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, + { + "line": 127, + "column": 15, + "endLine": 127, + "endColumn": 21, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 128, + "column": 15, + "endLine": 128, + "endColumn": 23, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 129, + "column": 15, + "endLine": 129, + "endColumn": 21, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 130, + "column": 15, + "endLine": 130, + "endColumn": 22, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 131, + "column": 15, + "endLine": 131, + "endColumn": 21, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 132, + "column": 15, + "endLine": 132, + "endColumn": 19, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 133, + "column": 15, + "endLine": 133, + "endColumn": 19, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 134, + "column": 15, + "endLine": 134, + "endColumn": 21, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 135, + "column": 15, + "endLine": 135, + "endColumn": 20, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 136, + "column": 15, + "endLine": 136, + "endColumn": 24, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 137, + "column": 15, + "endLine": 137, + "endColumn": 25, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 138, + "column": 15, + "endLine": 138, + "endColumn": 29, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 139, + "column": 15, + "endLine": 139, + "endColumn": 26, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 140, + "column": 15, + "endLine": 140, + "endColumn": 24, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 141, + "column": 15, + "endLine": 141, + "endColumn": 23, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 142, + "column": 15, + "endLine": 142, + "endColumn": 29, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 143, + "column": 15, + "endLine": 143, + "endColumn": 19, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 144, + "column": 15, + "endLine": 144, + "endColumn": 20, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 145, + "column": 15, + "endLine": 145, + "endColumn": 26, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 146, + "column": 15, + "endLine": 146, + "endColumn": 23, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 147, + "column": 15, + "endLine": 147, + "endColumn": 24, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 148, + "column": 15, + "endLine": 148, + "endColumn": 25, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 149, + "column": 15, + "endLine": 149, + "endColumn": 32, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 150, + "column": 15, + "endLine": 150, + "endColumn": 25, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 151, + "column": 15, + "endLine": 151, + "endColumn": 26, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 152, + "column": 15, + "endLine": 152, + "endColumn": 25, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 153, + "column": 15, + "endLine": 153, + "endColumn": 26, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 154, + "column": 15, + "endLine": 154, + "endColumn": 27, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 155, + "column": 15, + "endLine": 155, + "endColumn": 27, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 156, + "column": 15, + "endLine": 156, + "endColumn": 18, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 157, + "column": 15, + "endLine": 157, + "endColumn": 22, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 158, + "column": 15, + "endLine": 158, + "endColumn": 18, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 159, + "column": 15, + "endLine": 159, + "endColumn": 22, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 160, + "column": 15, + "endLine": 160, + "endColumn": 22, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 161, + "column": 15, + "endLine": 161, + "endColumn": 20, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 162, + "column": 15, + "endLine": 162, + "endColumn": 21, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 163, + "column": 15, + "endLine": 163, + "endColumn": 32, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 164, + "column": 15, + "endLine": 164, + "endColumn": 22, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 165, + "column": 15, + "endLine": 165, + "endColumn": 21, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 166, + "column": 15, + "endLine": 166, + "endColumn": 28, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 167, + "column": 15, + "endLine": 167, + "endColumn": 29, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 168, + "column": 15, + "endLine": 168, + "endColumn": 22, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 169, + "column": 15, + "endLine": 169, + "endColumn": 35, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, { "line": 180, "column": 7, @@ -211,6 +641,36 @@ "suggest": "", "rule": "\"Symbol()\" API is not supported (arkts-no-symbol)", "severity": "ERROR" + }, + { + "line": 190, + "column": 19, + "endLine": 190, + "endColumn": 27, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 194, + "column": 8, + "endLine": 194, + "endColumn": 14, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 205, + "column": 87, + "endLine": 205, + "endColumn": 93, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/explicit_function_type.ets.json b/ets2panda/linter/test/main/explicit_function_type.ets.json index 8620bd2581..d138186989 100755 --- a/ets2panda/linter/test/main/explicit_function_type.ets.json +++ b/ets2panda/linter/test/main/explicit_function_type.ets.json @@ -14,35 +14,65 @@ "limitations under the License." ], "result": [ - { - "line": 16, - "column": 20, - "endLine": 16, - "endColumn": 33, - "problem": "FunctionExpression", - "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", - "severity": "ERROR" - }, - { - "line": 18, - "column": 10, - "endLine": 18, - "endColumn": 23, - "problem": "FunctionExpression", - "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", - "severity": "ERROR" - }, - { - "line": 154, - "column": 9, - "endLine": 154, - "endColumn": 31, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - } - ] -} + { + "line": 16, + "column": 20, + "endLine": 16, + "endColumn": 33, + "problem": "FunctionExpression", + "suggest": "", + "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 10, + "endLine": 18, + "endColumn": 23, + "problem": "FunctionExpression", + "suggest": "", + "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "severity": "ERROR" + }, + { + "line": 70, + "column": 12, + "endLine": 70, + "endColumn": 20, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 79, + "column": 11, + "endLine": 79, + "endColumn": 19, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 118, + "column": 16, + "endLine": 118, + "endColumn": 24, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 154, + "column": 9, + "endLine": 154, + "endColumn": 31, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/modules.ets.json b/ets2panda/linter/test/main/modules.ets.json index 108257f764..d952c6ff27 100644 --- a/ets2panda/linter/test/main/modules.ets.json +++ b/ets2panda/linter/test/main/modules.ets.json @@ -24,6 +24,16 @@ "rule": "\"with\" statement is not supported (arkts-no-with)", "severity": "ERROR" }, + { + "line": 22, + "column": 9, + "endLine": 22, + "endColumn": 13, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, { "line": 23, "column": 11, diff --git a/ets2panda/linter/test/main/object_literals_prop_func_type.ets.autofix.json b/ets2panda/linter/test/main/object_literals_prop_func_type.ets.autofix.json index ed06927858..6d432798b1 100644 --- a/ets2panda/linter/test/main/object_literals_prop_func_type.ets.autofix.json +++ b/ets2panda/linter/test/main/object_literals_prop_func_type.ets.autofix.json @@ -24,6 +24,16 @@ "rule": "Use \"class\" instead of a type with call signature (arkts-no-call-signatures)", "severity": "ERROR" }, + { + "line": 53, + "column": 6, + "endLine": 53, + "endColumn": 14, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, { "line": 23, "column": 3, diff --git a/ets2panda/linter/test/main/object_literals_prop_func_type.ets.json b/ets2panda/linter/test/main/object_literals_prop_func_type.ets.json index a5443694a5..04c9b8ff99 100644 --- a/ets2panda/linter/test/main/object_literals_prop_func_type.ets.json +++ b/ets2panda/linter/test/main/object_literals_prop_func_type.ets.json @@ -24,6 +24,16 @@ "rule": "Use \"class\" instead of a type with call signature (arkts-no-call-signatures)", "severity": "ERROR" }, + { + "line": 53, + "column": 6, + "endLine": 53, + "endColumn": 14, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, { "line": 23, "column": 3, diff --git a/ets2panda/linter/test/rules/rule84.ets.json b/ets2panda/linter/test/rules/rule84.ets.json index b5974d6293..55a787dc30 100644 --- a/ets2panda/linter/test/rules/rule84.ets.json +++ b/ets2panda/linter/test/rules/rule84.ets.json @@ -23,6 +23,16 @@ "suggest": "", "rule": "\"with\" statement is not supported (arkts-no-with)", "severity": "ERROR" + }, + { + "line": 16, + "column": 7, + "endLine": 16, + "endColumn": 11, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" } ] } \ No newline at end of file -- Gitee From c5a97fc0893fd5e3423e0cd2a6f1e9f1351b726b Mon Sep 17 00:00:00 2001 From: zhongning Date: Tue, 8 Apr 2025 18:51:48 +0800 Subject: [PATCH 071/268] Fix issue for arkts-limited-stdlib Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBWQMX Test scenarios: new tests added to the linter Signed-off-by: zhongning --- .../test/main/concurrent_decorator_arkts2.ets | 10 +++ ...oncurrent_decorator_arkts2.ets.arkts2.json | 42 ++++++++++++- ...ncurrent_decorator_arkts2.ets.autofix.json | 63 ++++++++++++++++++- 3 files changed, 113 insertions(+), 2 deletions(-) diff --git a/ets2panda/linter/test/main/concurrent_decorator_arkts2.ets b/ets2panda/linter/test/main/concurrent_decorator_arkts2.ets index 6dcc364512..a51746c471 100644 --- a/ets2panda/linter/test/main/concurrent_decorator_arkts2.ets +++ b/ets2panda/linter/test/main/concurrent_decorator_arkts2.ets @@ -15,3 +15,13 @@ @Concurrent // ERROR function func() {} + +@Concurrent +type a2 = number +let n18: a2 = 10; + +@Concurrent +type funtType1 = () => void + +@Concurrent +type funtType2 = () => void | number \ No newline at end of file diff --git a/ets2panda/linter/test/main/concurrent_decorator_arkts2.ets.arkts2.json b/ets2panda/linter/test/main/concurrent_decorator_arkts2.ets.arkts2.json index b74e38da0e..7989c221a5 100644 --- a/ets2panda/linter/test/main/concurrent_decorator_arkts2.ets.arkts2.json +++ b/ets2panda/linter/test/main/concurrent_decorator_arkts2.ets.arkts2.json @@ -23,6 +23,46 @@ "suggest": "", "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 12, + "problem": "LimitedStdLibApi", + "suggest": "", + "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 1, + "endLine": 23, + "endColumn": 12, + "problem": "LimitedStdLibApi", + "suggest": "", + "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 1, + "endLine": 26, + "endColumn": 12, + "problem": "LimitedStdLibApi", + "suggest": "", + "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 24, + "endLine": 27, + "endColumn": 28, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" } ] -} +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/concurrent_decorator_arkts2.ets.autofix.json b/ets2panda/linter/test/main/concurrent_decorator_arkts2.ets.autofix.json index ba5d03fc2c..586af08091 100644 --- a/ets2panda/linter/test/main/concurrent_decorator_arkts2.ets.autofix.json +++ b/ets2panda/linter/test/main/concurrent_decorator_arkts2.ets.autofix.json @@ -30,6 +30,67 @@ "suggest": "", "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 12, + "problem": "LimitedStdLibApi", + "autofix": [ + { + "start": 651, + "end": 662, + "replacementText": "" + } + ], + "suggest": "", + "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 1, + "endLine": 23, + "endColumn": 12, + "problem": "LimitedStdLibApi", + "autofix": [ + { + "start": 699, + "end": 710, + "replacementText": "" + } + ], + "suggest": "", + "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 1, + "endLine": 26, + "endColumn": 12, + "problem": "LimitedStdLibApi", + "autofix": [ + { + "start": 740, + "end": 751, + "replacementText": "" + } + ], + "suggest": "", + "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 24, + "endLine": 27, + "endColumn": 28, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" } ] -} +} \ No newline at end of file -- Gitee From 4523294019836607b8e9105b608289f78375ec96 Mon Sep 17 00:00:00 2001 From: Mikhail Ivanov Date: Thu, 3 Apr 2025 16:21:58 +0300 Subject: [PATCH 072/268] Node history Description: Implement node history functionality and unit-tests Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBZIWP Signed-off-by: Mikhail Ivanov --- ets2panda/BUILD.gn | 1 + ets2panda/CMakeLists.txt | 1 + ets2panda/compiler/lowering/phase.cpp | 7 +- ets2panda/compiler/lowering/phase.h | 2 +- ets2panda/ir/astNodeHistory.cpp | 143 +++++++ ets2panda/ir/astNodeHistory.h | 48 +++ ets2panda/test/unit/lowerings/CMakeLists.txt | 3 + .../test/unit/lowerings/node_history.cpp | 370 ++++++++++++++++++ ets2panda/util/doubleLinkedList.h | 168 ++++++++ 9 files changed, 741 insertions(+), 2 deletions(-) create mode 100644 ets2panda/ir/astNodeHistory.cpp create mode 100644 ets2panda/ir/astNodeHistory.h create mode 100644 ets2panda/test/unit/lowerings/node_history.cpp create mode 100644 ets2panda/util/doubleLinkedList.h diff --git a/ets2panda/BUILD.gn b/ets2panda/BUILD.gn index 8636a69d2a..58c631bc59 100644 --- a/ets2panda/BUILD.gn +++ b/ets2panda/BUILD.gn @@ -266,6 +266,7 @@ libes2panda_sources = [ "ir/as/prefixAssertionExpression.cpp", "ir/astDump.cpp", "ir/astNode.cpp", + "ir/astNodeHistory.cpp", "ir/base/catchClause.cpp", "ir/base/classDefinition.cpp", "ir/base/classElement.cpp", diff --git a/ets2panda/CMakeLists.txt b/ets2panda/CMakeLists.txt index 7931019cfc..79faeba0b6 100644 --- a/ets2panda/CMakeLists.txt +++ b/ets2panda/CMakeLists.txt @@ -292,6 +292,7 @@ set(ES2PANDA_LIB_SRC ir/astDump.cpp ir/srcDump.cpp ir/astNode.cpp + ir/astNodeHistory.cpp ir/irnode.cpp ir/typeNode.cpp ir/opaqueTypeNode.cpp diff --git a/ets2panda/compiler/lowering/phase.cpp b/ets2panda/compiler/lowering/phase.cpp index ba1d8f78d9..6d153cc3e6 100644 --- a/ets2panda/compiler/lowering/phase.cpp +++ b/ets2panda/compiler/lowering/phase.cpp @@ -208,9 +208,14 @@ PhaseManager *GetPhaseManager() return g_phaseManager; } +void SetPhaseManager(PhaseManager *phaseManager) +{ + g_phaseManager = phaseManager; +} + bool Phase::Apply(public_lib::Context *ctx, parser::Program *program) { - g_phaseManager = ctx->phaseManager; + SetPhaseManager(ctx->phaseManager); GetPhaseManager()->SetCurrentPhaseId(id_); #ifndef NDEBUG diff --git a/ets2panda/compiler/lowering/phase.h b/ets2panda/compiler/lowering/phase.h index 2c0b2a5747..e1ff9c3885 100644 --- a/ets2panda/compiler/lowering/phase.h +++ b/ets2panda/compiler/lowering/phase.h @@ -100,7 +100,6 @@ public: int32_t PreviousPhaseId() const { - ES2PANDA_ASSERT(prev_ != INVALID_PHASE_ID); return prev_; } @@ -157,6 +156,7 @@ private: }; PhaseManager *GetPhaseManager(); +void SetPhaseManager(PhaseManager *phaseManager); } // namespace ark::es2panda::compiler diff --git a/ets2panda/ir/astNodeHistory.cpp b/ets2panda/ir/astNodeHistory.cpp new file mode 100644 index 0000000000..c27d68e8d2 --- /dev/null +++ b/ets2panda/ir/astNodeHistory.cpp @@ -0,0 +1,143 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "astNodeHistory.h" +#include "compiler/lowering/phase.h" + +namespace ark::es2panda::ir { + +AstNodeHistory::AstNodeHistory(AstNode *node, int32_t phaseId, ArenaAllocator *allocator) : list_ {allocator} +{ + Set(node, phaseId); +} + +AstNode *AstNodeHistory::FindBackwardEquals(int32_t phaseId) +{ + auto item = item_; + + while ((item = item->prev) != nullptr) { + if (LIKELY(item->data.phaseId == phaseId)) { + item_ = item; + return item->data.node; + } + } + + return nullptr; +} + +AstNode *AstNodeHistory::FindForwardEquals(int32_t phaseId) +{ + auto item = item_; + + do { + if (LIKELY(item->data.phaseId == phaseId)) { + item_ = item; + return item->data.node; + } + } while ((item = item->next) != nullptr); + + return nullptr; +} + +// Find node state precisely at phase with a given ID +// (e.g. find the node history record with `phaseId` equal to a given value) +AstNode *AstNodeHistory::At(int32_t phaseId) +{ + if (LIKELY(item_->data.phaseId == phaseId)) { + // Start searching with last accessed item + // In most cases last accessed item is the one we are looking for + return item_->data.node; + } + if (LIKELY(item_->data.phaseId > phaseId)) { + // Search backwards starting at last accessed node for the node at previous phase + return FindBackwardEquals(phaseId); + } + // Search forward starting at last accessed node for the node at next phase + return FindForwardEquals(phaseId); +} + +// Find node state at phase with a given ID +// (e.g. find last node history record with `phaseId` less or equal to a given value) +AstNode *AstNodeHistory::Get(int32_t phaseId) +{ + auto found = FindLessOrEquals(phaseId); + if (LIKELY(found != nullptr)) { + item_ = found; + return item_->data.node; + } + + return nullptr; +} + +// Find node state at phase with a given ID and set its new value, insert new history record if not found +void AstNodeHistory::Set(AstNode *node, int32_t phaseId) +{ + HistoryRecord record {node, phaseId}; + if (LIKELY(list_.Empty() || list_.Tail()->data.phaseId < phaseId)) { + item_ = list_.Append(record); + } else if (list_.Head()->data.phaseId > phaseId) { + item_ = list_.Prepend(record); + } else if (auto found = FindLessOrEquals(phaseId); found != nullptr) { + if (found->data.phaseId == phaseId) { + item_ = found; + item_->data.node = node; + } else { + item_ = list_.Insert(found, record); + ES2PANDA_ASSERT(item_->prev->data.phaseId < item_->data.phaseId && + item_->data.phaseId < item_->next->data.phaseId); + } + } else { + ES2PANDA_UNREACHABLE(); + } +} + +// Find node state at phase with a given ID +// (e.g. find last node history record with `phaseId` less or equal to a given value) +AstNodeHistory::HistoryList::Item *AstNodeHistory::FindLessOrEquals(int32_t phaseId) +{ + // Start searching with last accessed item + auto item = item_; + + if (LIKELY(item->data.phaseId == phaseId)) { + // In most cases last accessed item is the one we are looking for + return item; + } + if (LIKELY(item->data.phaseId > phaseId)) { + // Search backwards starting at last accessed node for the node at previous phase + while ((item = item->prev) != nullptr) { + if (item->data.phaseId <= phaseId) { + return item; + } + } + } else { + // Search forward starting at last accessed node for the node at next phase + while (item->next != nullptr) { + if (item->data.phaseId == phaseId) { + return item; + } + if (item->data.phaseId > phaseId && item->prev != nullptr) { + item = item->prev; + return item; + } + item = item->next; + } + if (item->data.phaseId <= phaseId) { + return item; + } + } + + return nullptr; +} +} // namespace ark::es2panda::ir diff --git a/ets2panda/ir/astNodeHistory.h b/ets2panda/ir/astNodeHistory.h new file mode 100644 index 0000000000..8aebde4a7a --- /dev/null +++ b/ets2panda/ir/astNodeHistory.h @@ -0,0 +1,48 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ES2PANDA_IR_AST_NODE_HISTORY_H +#define ES2PANDA_IR_AST_NODE_HISTORY_H + +#include "ir/astNode.h" +#include "util/doubleLinkedList.h" + +namespace ark::es2panda::ir { + +class AstNodeHistory { +public: + AstNodeHistory(AstNode *node, int32_t phaseId, ArenaAllocator *allocator); + + AstNode *At(int32_t phaseId); + AstNode *Get(int32_t phaseId); + void Set(AstNode *node, int32_t phaseId); + +private: + struct HistoryRecord { + AstNode *node; + int32_t phaseId; + }; + + using HistoryList = util::ArenaDoubleLinkedList; + + AstNode *FindBackwardEquals(int32_t phaseId); + AstNode *FindForwardEquals(int32_t phaseId); + HistoryList::Item *FindLessOrEquals(int32_t phaseId); + + HistoryList list_; // Node history list + HistoryList::Item *item_ {nullptr}; // Last accessed history record +}; +} // namespace ark::es2panda::ir +#endif diff --git a/ets2panda/test/unit/lowerings/CMakeLists.txt b/ets2panda/test/unit/lowerings/CMakeLists.txt index fdcf9b2fe8..4fcbd1a701 100644 --- a/ets2panda/test/unit/lowerings/CMakeLists.txt +++ b/ets2panda/test/unit/lowerings/CMakeLists.txt @@ -27,3 +27,6 @@ ets2panda_add_gtest(const_expression_test ets2panda_add_gtest(top_level_statements_test CPP_SOURCES top_level_statements.cpp ) +ets2panda_add_gtest(node_history_test + CPP_SOURCES node_history.cpp +) diff --git a/ets2panda/test/unit/lowerings/node_history.cpp b/ets2panda/test/unit/lowerings/node_history.cpp new file mode 100644 index 0000000000..c3b982aa63 --- /dev/null +++ b/ets2panda/test/unit/lowerings/node_history.cpp @@ -0,0 +1,370 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include "compiler/lowering/phase.h" +#include "ir/astNodeHistory.h" + +namespace ark::es2panda { + +class NodeHistoryTest : public testing::Test { +public: + ~NodeHistoryTest() override = default; + + static void SetUpTestCase() + { + ark::mem::MemConfig::Initialize(0, 0, ark::es2panda::COMPILER_SIZE, 0, 0, 0); + ark::PoolManager::Initialize(); + } + + NodeHistoryTest() + { + allocator_ = std::make_unique(SpaceType::SPACE_TYPE_COMPILER); + phaseManager_ = std::make_unique(ScriptExtension::ETS, Allocator()); + compiler::SetPhaseManager(phaseManager_.get()); + } + + NO_COPY_SEMANTIC(NodeHistoryTest); + NO_MOVE_SEMANTIC(NodeHistoryTest); + + ArenaAllocator *Allocator() const + { + return allocator_.get(); + } + + compiler::PhaseManager *PhaseManager() const + { + return phaseManager_.get(); + } + +private: + std::unique_ptr allocator_; + std::unique_ptr phaseManager_; +}; + +constexpr int32_t PHASE_ID_0 = 0; +constexpr int32_t PHASE_ID_1 = 1; +constexpr int32_t PHASE_ID_2 = 2; +constexpr int32_t PHASE_ID_3 = 3; +constexpr int32_t PHASE_ID_4 = 4; +constexpr int32_t PHASE_ID_5 = 5; + +constexpr int32_t INDEX_0 = 0; +constexpr int32_t INDEX_1 = 1; +constexpr int32_t INDEX_2 = 2; +constexpr int32_t INDEX_3 = 3; +constexpr int32_t INDEX_4 = 4; + +constexpr int32_t VALUE_0 = 0; +constexpr int32_t VALUE_1 = 1; +constexpr int32_t VALUE_2 = 2; +constexpr int32_t VALUE_3 = 3; +constexpr int32_t VALUE_4 = 4; + +constexpr int32_t SIZE_5 = 5; + +// CC-OFFNXT(huge_method, G.FUN.01-CPP, G.FUD.05) solid logic +TEST_F(NodeHistoryTest, DoubleLinkedList) +{ + util::ArenaDoubleLinkedList list {Allocator()}; + + ASSERT_EQ(list.Head(), nullptr); + ASSERT_EQ(list.Tail(), nullptr); + ASSERT_TRUE(list.Empty()); + + // Make list: (1,2,4,0,3) + std::array data = {VALUE_0, VALUE_1, VALUE_2, VALUE_3, VALUE_4}; + + auto item4 = list.Append(data[INDEX_4]); + auto item0 = list.Append(data[INDEX_0]); + auto item3 = list.Insert(item0, data[INDEX_3]); + auto item1 = list.Prepend(data[INDEX_1]); + auto item2 = list.Insert(item1, data[INDEX_2]); + + ASSERT_FALSE(list.Empty()); + + ASSERT_EQ(item0->data, data[INDEX_0]); + ASSERT_EQ(item1->data, data[INDEX_1]); + ASSERT_EQ(item2->data, data[INDEX_2]); + ASSERT_EQ(item3->data, data[INDEX_3]); + ASSERT_EQ(item4->data, data[INDEX_4]); + + ASSERT_EQ(list.Head(), item1); + ASSERT_EQ(item1->next, item2); + ASSERT_EQ(item2->next, item4); + ASSERT_EQ(item4->next, item0); + ASSERT_EQ(item0->next, item3); + ASSERT_EQ(item3, list.Tail()); + ASSERT_EQ(list.Tail()->next, nullptr); + + ASSERT_EQ(item3->prev, item0); + ASSERT_EQ(item0->prev, item4); + ASSERT_EQ(item4->prev, item2); + ASSERT_EQ(item2->prev, item1); + ASSERT_EQ(item1->prev, nullptr); + + ASSERT_EQ(item2->prev->next, item2); + ASSERT_EQ(item4->prev->next, item4); + ASSERT_EQ(item0->prev->next, item0); + + ASSERT_EQ(item2->next->prev, item2); + ASSERT_EQ(item4->next->prev, item4); + ASSERT_EQ(item0->next->prev, item0); + + list.Erase(item4); + ASSERT_EQ(item2->next, item0); + ASSERT_EQ(item0->prev, item2); + + list.Erase(item0); + ASSERT_EQ(item2->next, item3); + ASSERT_EQ(item3->prev, item2); + + list.Erase(list.Tail()); + ASSERT_EQ(list.Tail(), item2); + ASSERT_EQ(item2->next, nullptr); + ASSERT_EQ(item2->prev, item1); + + list.Erase(list.Head()); + ASSERT_EQ(list.Head(), item2); + ASSERT_EQ(item2->next, nullptr); + ASSERT_EQ(item2->prev, nullptr); + + list.Erase(item2); + ASSERT_EQ(list.Head(), nullptr); + ASSERT_EQ(list.Tail(), nullptr); + ASSERT_TRUE(list.Empty()); +} + +TEST_F(NodeHistoryTest, HistoryAt) +{ + ASSERT_EQ(PhaseManager()->CurrentPhaseId(), compiler::PARSER_PHASE_ID); + + PhaseManager()->SetCurrentPhaseId(PHASE_ID_0); + auto identifier = Allocator()->New(Allocator())->AsIdentifier(); + auto history = Allocator()->New(identifier, PhaseManager()->CurrentPhaseId(), Allocator()); + + ASSERT_EQ(history->At(compiler::PARSER_PHASE_ID), nullptr); + ASSERT_EQ(history->At(PHASE_ID_0), identifier); + ASSERT_EQ(history->At(PHASE_ID_1), nullptr); +} + +TEST_F(NodeHistoryTest, HistoryGet) +{ + ASSERT_EQ(PhaseManager()->CurrentPhaseId(), compiler::PARSER_PHASE_ID); + + PhaseManager()->SetCurrentPhaseId(PHASE_ID_0); + auto identifier = Allocator()->New(Allocator())->AsIdentifier(); + auto history = Allocator()->New(identifier, PhaseManager()->CurrentPhaseId(), Allocator()); + + ASSERT_EQ(history->Get(compiler::PARSER_PHASE_ID), nullptr); + ASSERT_EQ(history->Get(PHASE_ID_0), identifier); + ASSERT_EQ(history->Get(PHASE_ID_1), identifier); + ASSERT_EQ(history->Get(PHASE_ID_2), identifier); + ASSERT_EQ(history->Get(PHASE_ID_3), identifier); +} + +// CC-OFFNXT(huge_method, G.FUN.01-CPP, G.FUD.05) solid logic +TEST_F(NodeHistoryTest, HistorySet) +{ + ASSERT_EQ(PhaseManager()->CurrentPhaseId(), compiler::PARSER_PHASE_ID); + + PhaseManager()->SetCurrentPhaseId(PHASE_ID_0); + auto identifier0 = Allocator()->New(Allocator())->AsIdentifier(); + auto history = Allocator()->New(identifier0, PhaseManager()->CurrentPhaseId(), Allocator()); + + PhaseManager()->SetCurrentPhaseId(PHASE_ID_1); + auto identifier1 = Allocator()->New(Allocator())->AsIdentifier(); + history->Set(identifier1, PhaseManager()->CurrentPhaseId()); + + PhaseManager()->SetCurrentPhaseId(PHASE_ID_2); + auto identifier2 = Allocator()->New(Allocator())->AsIdentifier(); + history->Set(identifier2, PhaseManager()->CurrentPhaseId()); + + PhaseManager()->SetCurrentPhaseId(PHASE_ID_3); + history->Set(nullptr, PhaseManager()->CurrentPhaseId()); + + // Search forward + ASSERT_EQ(history->Get(compiler::PARSER_PHASE_ID), nullptr); + ASSERT_EQ(history->Get(PHASE_ID_0), identifier0); + ASSERT_EQ(history->Get(PHASE_ID_1), identifier1); + ASSERT_EQ(history->Get(PHASE_ID_2), identifier2); + ASSERT_EQ(history->Get(PHASE_ID_3), nullptr); + ASSERT_EQ(history->Get(PHASE_ID_4), nullptr); + ASSERT_EQ(history->Get(PHASE_ID_5), nullptr); + + // Search backward + ASSERT_EQ(history->Get(PHASE_ID_5), nullptr); + ASSERT_EQ(history->Get(PHASE_ID_4), nullptr); + ASSERT_EQ(history->Get(PHASE_ID_3), nullptr); + ASSERT_EQ(history->Get(PHASE_ID_2), identifier2); + ASSERT_EQ(history->Get(PHASE_ID_1), identifier1); + ASSERT_EQ(history->Get(PHASE_ID_0), identifier0); + ASSERT_EQ(history->Get(compiler::PARSER_PHASE_ID), nullptr); + + // Search random + ASSERT_EQ(history->Get(PHASE_ID_1), identifier1); + ASSERT_EQ(history->Get(PHASE_ID_5), nullptr); + ASSERT_EQ(history->Get(PHASE_ID_2), identifier2); + ASSERT_EQ(history->Get(PHASE_ID_4), nullptr); + ASSERT_EQ(history->Get(PHASE_ID_0), identifier0); + ASSERT_EQ(history->Get(compiler::PARSER_PHASE_ID), nullptr); + ASSERT_EQ(history->Get(PHASE_ID_3), nullptr); + + // Search precise + ASSERT_EQ(history->At(compiler::PARSER_PHASE_ID), nullptr); + ASSERT_EQ(history->At(PHASE_ID_0), identifier0); + ASSERT_EQ(history->At(PHASE_ID_1), identifier1); + ASSERT_EQ(history->At(PHASE_ID_2), identifier2); + ASSERT_EQ(history->At(PHASE_ID_3), nullptr); + ASSERT_EQ(history->At(PHASE_ID_4), nullptr); + ASSERT_EQ(history->At(PHASE_ID_5), nullptr); +} + +TEST_F(NodeHistoryTest, HistoryReplace) +{ + ASSERT_EQ(PhaseManager()->CurrentPhaseId(), compiler::PARSER_PHASE_ID); + + PhaseManager()->SetCurrentPhaseId(PHASE_ID_0); + auto identifier0Orig = Allocator()->New(Allocator())->AsIdentifier(); + auto history = Allocator()->New(identifier0Orig, PhaseManager()->CurrentPhaseId(), Allocator()); + + PhaseManager()->SetCurrentPhaseId(PHASE_ID_1); + auto identifier1Orig = Allocator()->New(Allocator())->AsIdentifier(); + history->Set(identifier1Orig, PhaseManager()->CurrentPhaseId()); + + ASSERT_EQ(history->Get(compiler::PARSER_PHASE_ID), nullptr); + ASSERT_EQ(history->Get(PHASE_ID_0), identifier0Orig); + ASSERT_EQ(history->Get(PHASE_ID_1), identifier1Orig); + ASSERT_EQ(history->Get(PHASE_ID_2), identifier1Orig); + ASSERT_EQ(history->Get(PHASE_ID_3), identifier1Orig); + + ASSERT_EQ(history->At(compiler::PARSER_PHASE_ID), nullptr); + ASSERT_EQ(history->At(PHASE_ID_0), identifier0Orig); + ASSERT_EQ(history->At(PHASE_ID_1), identifier1Orig); + ASSERT_EQ(history->At(PHASE_ID_2), nullptr); + + PhaseManager()->SetCurrentPhaseId(PHASE_ID_0); + auto identifier0New = Allocator()->New(Allocator())->AsIdentifier(); + history->Set(identifier0New, PhaseManager()->CurrentPhaseId()); + + PhaseManager()->SetCurrentPhaseId(PHASE_ID_1); + auto identifier1New = Allocator()->New(Allocator())->AsIdentifier(); + history->Set(identifier1New, PhaseManager()->CurrentPhaseId()); + + PhaseManager()->SetCurrentPhaseId(PHASE_ID_2); + history->Set(nullptr, PhaseManager()->CurrentPhaseId()); + + ASSERT_EQ(history->Get(compiler::PARSER_PHASE_ID), nullptr); + ASSERT_EQ(history->Get(PHASE_ID_0), identifier0New); + ASSERT_EQ(history->Get(PHASE_ID_1), identifier1New); + ASSERT_EQ(history->Get(PHASE_ID_2), nullptr); + ASSERT_EQ(history->Get(PHASE_ID_3), nullptr); + + ASSERT_EQ(history->At(compiler::PARSER_PHASE_ID), nullptr); + ASSERT_EQ(history->At(PHASE_ID_0), identifier0New); + ASSERT_EQ(history->At(PHASE_ID_1), identifier1New); + ASSERT_EQ(history->At(PHASE_ID_2), nullptr); +} + +ir::ClassDefinition *NewClassDefinition(ArenaAllocator *allocator) +{ + ArenaVector body {allocator->Adapter()}; + return allocator + ->New(allocator, nullptr, std::move(body), ir::ClassDefinitionModifiers::NONE, + ir::ModifierFlags::NONE, Language::Id::ETS) + ->AsClassDefinition(); +} + +/// NOTE(mivanov): To be enabled after #24153/#24424 implemented +TEST_F(NodeHistoryTest, DISABLED_UpdateField) +{ + ASSERT_EQ(PhaseManager()->CurrentPhaseId(), compiler::PARSER_PHASE_ID); + + auto definition = NewClassDefinition(Allocator()); + ASSERT_FALSE(definition->IsAbstract()); + definition->ClearModifier(ir::ModifierFlags::ABSTRACT); + ASSERT_FALSE(definition->IsAbstract()); + definition->AddModifier(ir::ModifierFlags::FINAL); + ASSERT_TRUE(definition->IsFinal()); + + PhaseManager()->SetCurrentPhaseId(PHASE_ID_0); + definition->AddModifier(ir::ModifierFlags::ABSTRACT); + ASSERT_TRUE(definition->IsAbstract()); + definition->ClearModifier(ir::ModifierFlags::FINAL); + ASSERT_FALSE(definition->IsFinal()); + + PhaseManager()->SetCurrentPhaseId(PHASE_ID_1); + definition->ClearModifier(ir::ModifierFlags::ABSTRACT); + ASSERT_FALSE(definition->IsAbstract()); + definition->AddModifier(ir::ModifierFlags::FINAL); + ASSERT_TRUE(definition->IsFinal()); + + PhaseManager()->SetCurrentPhaseId(PHASE_ID_2); + definition->ClearModifier(ir::ModifierFlags::FINAL); + ASSERT_FALSE(definition->IsFinal()); + + PhaseManager()->Restart(); + ASSERT_FALSE(definition->IsAbstract()); + ASSERT_TRUE(definition->IsFinal()); + + PhaseManager()->SetCurrentPhaseId(PHASE_ID_0); + ASSERT_TRUE(definition->IsAbstract()); + ASSERT_FALSE(definition->IsFinal()); + + PhaseManager()->SetCurrentPhaseId(PHASE_ID_1); + ASSERT_FALSE(definition->IsAbstract()); + ASSERT_TRUE(definition->IsFinal()); + + PhaseManager()->SetCurrentPhaseId(PHASE_ID_2); + ASSERT_FALSE(definition->IsAbstract()); + ASSERT_FALSE(definition->IsFinal()); +} + +/// NOTE(mivanov): To be enabled after #24153/#24424 implemented +TEST_F(NodeHistoryTest, DISABLED_UpdateChild) +{ + ASSERT_EQ(PhaseManager()->CurrentPhaseId(), compiler::PARSER_PHASE_ID); + + auto declaration = + Allocator()->New(NewClassDefinition(Allocator()), Allocator())->AsClassDeclaration(); + ASSERT_EQ(declaration->Definition()->Ident(), nullptr); + + PhaseManager()->SetCurrentPhaseId(PHASE_ID_0); + auto identifier0 = Allocator()->New(Allocator())->AsIdentifier(); + declaration->Definition()->SetIdent(identifier0); + ASSERT_EQ(declaration->Definition()->Ident(), identifier0); + + PhaseManager()->SetCurrentPhaseId(PHASE_ID_1); + auto identifier1 = Allocator()->New(Allocator())->AsIdentifier(); + declaration->Definition()->SetIdent(identifier1); + ASSERT_EQ(declaration->Definition()->Ident(), identifier1); + + PhaseManager()->SetCurrentPhaseId(PHASE_ID_2); + declaration->Definition()->SetIdent(nullptr); + ASSERT_EQ(declaration->Definition()->Ident(), nullptr); + + PhaseManager()->Restart(); + ASSERT_EQ(declaration->Definition()->Ident(), nullptr); + + PhaseManager()->SetCurrentPhaseId(PHASE_ID_0); + ASSERT_EQ(declaration->Definition()->Ident(), identifier0); + + PhaseManager()->SetCurrentPhaseId(PHASE_ID_1); + ASSERT_EQ(declaration->Definition()->Ident(), identifier1); + + PhaseManager()->SetCurrentPhaseId(PHASE_ID_2); + ASSERT_EQ(declaration->Definition()->Ident(), nullptr); +} +} // namespace ark::es2panda diff --git a/ets2panda/util/doubleLinkedList.h b/ets2panda/util/doubleLinkedList.h new file mode 100644 index 0000000000..a4d5a5a919 --- /dev/null +++ b/ets2panda/util/doubleLinkedList.h @@ -0,0 +1,168 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ES2PANDA_UTIL_DOUBLE_LINKED_LIST_H +#define ES2PANDA_UTIL_DOUBLE_LINKED_LIST_H + +#include "mem/arena_allocator.h" + +namespace ark::es2panda::util { + +template +class ArenaDoubleLinkedList { +public: + explicit ArenaDoubleLinkedList(ArenaAllocator *allocator) : allocator_ {allocator} {} + + struct Item { + T data {}; + Item *next {nullptr}; + Item *prev {nullptr}; + }; + + Item *Head() + { + return head_; + } + + Item *Tail() + { + return tail_; + } + + bool Empty() + { + return head_ == nullptr; + }; + + ArenaAllocator *Allocator() + { + return allocator_; + } + + Item *Append(const T &data) + { + auto item = allocator_->New(); + item->data = data; + Append(item); + return item; + } + + void Append(Item *item) + { + item->next = nullptr; + item->prev = nullptr; + + if (Empty()) { + head_ = item; + tail_ = item; + } else { + tail_->next = item; + item->prev = tail_; + tail_ = item; + } + } + + Item *Prepend(const T &data) + { + auto item = allocator_->New(); + item->data = data; + Prepend(item); + return item; + } + + void Prepend(Item *item) + { + item->next = nullptr; + item->prev = nullptr; + + if (Empty()) { + head_ = item; + tail_ = item; + } else { + head_->prev = item; + item->next = head_; + head_ = item; + } + } + + Item *Insert(Item *after, const T &data) + { + auto item = allocator_->New(); + item->data = data; + Insert(after, item); + return item; + } + + void Insert(Item *after, Item *item) + { + ES2PANDA_ASSERT(!Empty()); + ES2PANDA_ASSERT(after != nullptr); + ES2PANDA_ASSERT(item != nullptr); + + auto afterNext = after->next; + + after->next = item; + item->prev = after; + + item->next = afterNext; + if (afterNext != nullptr) { + afterNext->prev = item; + } + + if (after == tail_) { + tail_ = item; + } + } + + void Erase(Item *item) + { + ES2PANDA_ASSERT(!Empty()); + ES2PANDA_ASSERT(item != nullptr); + + if (item == head_ && item == tail_) { + // Item is the only element in list + head_ = nullptr; + tail_ = nullptr; + } else if (item == head_) { + head_ = head_->next; + if (head_ != nullptr) { + head_->prev = nullptr; + } + } else if (item == tail_) { + tail_ = tail_->prev; + if (tail_ != nullptr) { + tail_->next = nullptr; + } + } else { + // Item is not a head or tail element of list + auto prev = item->prev; + auto next = item->next; + + ES2PANDA_ASSERT(prev != nullptr && next != nullptr); + prev->next = next; + next->prev = prev; + } + + item->next = nullptr; + item->prev = nullptr; + } + +private: + Item *head_ {nullptr}; + Item *tail_ {nullptr}; + ArenaAllocator *allocator_; +}; +} // namespace ark::es2panda::util +#endif -- Gitee From d6773fe8d31ad4a0afc31a445d1cf1e1031efb40 Mon Sep 17 00:00:00 2001 From: Kaskov Mikhail Date: Sat, 5 Apr 2025 19:17:09 +0800 Subject: [PATCH 073/268] Fixed conflicts of imported functions Fixed conflict of imported functions during overloading. Changes by actual SPEC 17.17.3 and 17.8.3 If a declaration scope declares and/or imports two or more function with the same name but different signatures that are not overload-equivalent, then such functions are overloaded. Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBYRXJ Signed-off-by: Kaskov Mikhail --- .../ets/import_tests/import_name_conflicts/main_1.ets | 5 +++-- ets2panda/varbinder/ETSBinder.cpp | 8 ++++---- ets2panda/varbinder/ETSBinder.h | 3 +-- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/ets2panda/test/ast/parser/ets/import_tests/import_name_conflicts/main_1.ets b/ets2panda/test/ast/parser/ets/import_tests/import_name_conflicts/main_1.ets index a762c4c108..31857cd3ba 100644 --- a/ets2panda/test/ast/parser/ets/import_tests/import_name_conflicts/main_1.ets +++ b/ets2panda/test/ast/parser/ets/import_tests/import_name_conflicts/main_1.ets @@ -14,9 +14,10 @@ */ import {foo_1 as foo} from "./imported_module_1.ets" -import {foo_2_1param as foo} from /* @@ label */"./imported_module_2.ets" +import {foo_2 as foo} from "./imported_module_2.ets" function main() : void {} -/* @@@ label Error TypeError: Function 'foo' is already defined. */ +// NOTE(kaskov): Add more precise error, when will be suggestions +/* @@? imported_module_2.ets:27:8 Error TypeError: Function foo_1 is already declared. */ diff --git a/ets2panda/varbinder/ETSBinder.cpp b/ets2panda/varbinder/ETSBinder.cpp index 23cd6c7c9f..216018b1b4 100644 --- a/ets2panda/varbinder/ETSBinder.cpp +++ b/ets2panda/varbinder/ETSBinder.cpp @@ -830,13 +830,13 @@ void ETSBinder::ValidateImportVariable(const ir::AstNode *node, const ir::ETSImp } bool ETSBinder::DetectNameConflict(const util::StringView localName, Variable *const var, Variable *const otherVar, - const ir::StringLiteral *const importPath, bool overloadAllowed) + const ir::StringLiteral *const importPath) { if (otherVar == nullptr || var == otherVar) { return false; } - if (overloadAllowed && var->Declaration()->IsFunctionDecl() && otherVar->Declaration()->IsFunctionDecl()) { + if (var->Declaration()->IsFunctionDecl() && otherVar->Declaration()->IsFunctionDecl()) { AddOverloadFlag(Allocator(), util::Helpers::IsStdLib(Program()), var, otherVar); return true; } @@ -898,8 +898,8 @@ bool ETSBinder::AddImportSpecifiersToTopBindings(Span re const auto localName = importSpecifier->Local()->Name(); auto varInGlobalClassScope = Program()->GlobalClassScope()->FindLocal(localName, ResolveBindingOptions::ALL); auto previouslyImportedVariable = TopScope()->FindLocal(localName, ResolveBindingOptions::ALL); - if (DetectNameConflict(localName, var, varInGlobalClassScope, importPath, true) || - DetectNameConflict(localName, var, previouslyImportedVariable, importPath, false)) { + if (DetectNameConflict(localName, var, varInGlobalClassScope, importPath) || + DetectNameConflict(localName, var, previouslyImportedVariable, importPath)) { return true; } diff --git a/ets2panda/varbinder/ETSBinder.h b/ets2panda/varbinder/ETSBinder.h index 81f7705bcb..66b242933f 100644 --- a/ets2panda/varbinder/ETSBinder.h +++ b/ets2panda/varbinder/ETSBinder.h @@ -150,8 +150,7 @@ public: const ir::ETSImportDeclaration *const import); void BuildETSNewClassInstanceExpression(ir::ETSNewClassInstanceExpression *classInstance); [[nodiscard]] bool DetectNameConflict(const util::StringView localName, Variable *const var, - Variable *const otherVar, const ir::StringLiteral *const importPath, - bool overloadAllowed); + Variable *const otherVar, const ir::StringLiteral *const importPath); [[nodiscard]] ArenaVector GetExternalProgram(util::StringView sourceName, const ir::StringLiteral *importPath); -- Gitee From f5a619f258d54f93f9a25730163ee3ca92d58935 Mon Sep 17 00:00:00 2001 From: sniperc96 Date: Thu, 17 Apr 2025 19:21:52 +0800 Subject: [PATCH 074/268] [ArkUI] fix bug Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC20MY Signed-off-by: sniperc96 --- ets2panda/linter/src/lib/TypeScriptLinter.ts | 23 +- ...atable_extend_decorator_1.ets.autofix.json | 56 +++- .../main/data_observation_1.ets.autofix.json | 168 ++++++++-- .../main/dollar_binding_1.ets.autofix.json | 48 ++- .../double_dollar_binding_1.ets.autofix.json | 72 ++++- .../double_excla_binding_1.ets.autofix.json | 296 +++++++++++++++--- .../main/extend_decorator_1.ets.autofix.json | 48 ++- .../main/interface_import_1.ets.autofix.json | 136 ++++++-- .../literals_as_prop_names.ets.autofix.json | 10 +- .../main/numeric_semantics.ets.autofix.json | 40 ++- .../provide_annotation_1.ets.autofix.json | 66 +++- .../provide_annotation_2.ets.autofix.json | 64 +++- .../styles_decorator_anon_1.ets.autofix.json | 40 ++- ...styles_decorator_global_1.ets.autofix.json | 48 ++- ...styles_decorator_struct_1.ets.autofix.json | 120 ++++++- 15 files changed, 1042 insertions(+), 193 deletions(-) diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index 078918d4ea..96a4824645 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -4331,7 +4331,7 @@ export class TypeScriptLinter { this.extractImportedNames(this.sourceFile); this.visitSourceFile(this.sourceFile); this.handleCommentDirectives(this.sourceFile); - this.processInterfacesToImport(); + this.processInterfacesToImport(this.sourceFile); } private handleExportKeyword(node: ts.Node): void { @@ -5298,22 +5298,19 @@ export class TypeScriptLinter { return this.interfacesAlreadyImported.has(name); } - private processInterfacesToImport(): void { + private processInterfacesToImport(sourceFile: ts.SourceFile): void { if (!this.options.arkts2) { return; } - this.interfacesNeedToAlarm.forEach((identifier, index) => { - if (index === this.interfacesNeedToAlarm.length - 1) { - const autofix = this.autofixer?.fixInterfaceImport( - this.interfacesNeedToImport, - this.interfacesAlreadyImported, - identifier.getSourceFile() - ); - this.incrementCounters(identifier, FaultID.UIInterfaceImport, autofix); - } else { - this.incrementCounters(identifier, FaultID.UIInterfaceImport, []); - } + const autofix = this.autofixer?.fixInterfaceImport( + this.interfacesNeedToImport, + this.interfacesAlreadyImported, + sourceFile + ); + + this.interfacesNeedToAlarm.forEach((identifier) => { + this.incrementCounters(identifier, FaultID.UIInterfaceImport, autofix); }); this.interfacesNeedToAlarm = []; diff --git a/ets2panda/linter/test/main/animatable_extend_decorator_1.ets.autofix.json b/ets2panda/linter/test/main/animatable_extend_decorator_1.ets.autofix.json index 5136b5c4cb..c75ea9c0cb 100644 --- a/ets2panda/linter/test/main/animatable_extend_decorator_1.ets.autofix.json +++ b/ets2panda/linter/test/main/animatable_extend_decorator_1.ets.autofix.json @@ -37,7 +37,13 @@ "endLine": 16, "endColumn": 18, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { TextAttribute, AnimatableExtend, Entry, Component, State, Column, Text, Curve, Button } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -48,7 +54,13 @@ "endLine": 21, "endColumn": 7, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { TextAttribute, AnimatableExtend, Entry, Component, State, Column, Text, Curve, Button } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -59,7 +71,13 @@ "endLine": 22, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { TextAttribute, AnimatableExtend, Entry, Component, State, Column, Text, Curve, Button } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -70,7 +88,13 @@ "endLine": 24, "endColumn": 9, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { TextAttribute, AnimatableExtend, Entry, Component, State, Column, Text, Curve, Button } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -81,7 +105,13 @@ "endLine": 27, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { TextAttribute, AnimatableExtend, Entry, Component, State, Column, Text, Curve, Button } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -92,7 +122,13 @@ "endLine": 28, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { TextAttribute, AnimatableExtend, Entry, Component, State, Column, Text, Curve, Button } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -103,7 +139,13 @@ "endLine": 30, "endColumn": 50, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { TextAttribute, AnimatableExtend, Entry, Component, State, Column, Text, Curve, Button } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" diff --git a/ets2panda/linter/test/main/data_observation_1.ets.autofix.json b/ets2panda/linter/test/main/data_observation_1.ets.autofix.json index e5da4631b9..272ff28a6c 100644 --- a/ets2panda/linter/test/main/data_observation_1.ets.autofix.json +++ b/ets2panda/linter/test/main/data_observation_1.ets.autofix.json @@ -202,7 +202,13 @@ "endLine": 36, "endColumn": 10, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -213,7 +219,13 @@ "endLine": 45, "endColumn": 10, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -224,7 +236,13 @@ "endLine": 48, "endColumn": 10, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -235,7 +253,13 @@ "endLine": 51, "endColumn": 7, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -246,7 +270,13 @@ "endLine": 52, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -257,7 +287,13 @@ "endLine": 54, "endColumn": 9, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -268,7 +304,13 @@ "endLine": 55, "endColumn": 9, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -279,7 +321,13 @@ "endLine": 56, "endColumn": 9, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -290,7 +338,13 @@ "endLine": 57, "endColumn": 9, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -301,7 +355,13 @@ "endLine": 58, "endColumn": 9, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -312,7 +372,13 @@ "endLine": 59, "endColumn": 8, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -323,7 +389,13 @@ "endLine": 60, "endColumn": 8, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -334,7 +406,13 @@ "endLine": 61, "endColumn": 8, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -345,7 +423,13 @@ "endLine": 62, "endColumn": 8, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -356,7 +440,13 @@ "endLine": 63, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -367,7 +457,13 @@ "endLine": 64, "endColumn": 15, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -378,7 +474,13 @@ "endLine": 65, "endColumn": 20, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -389,7 +491,13 @@ "endLine": 66, "endColumn": 15, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -400,7 +508,13 @@ "endLine": 67, "endColumn": 20, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -411,7 +525,13 @@ "endLine": 74, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -422,7 +542,13 @@ "endLine": 76, "endColumn": 8, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" diff --git a/ets2panda/linter/test/main/dollar_binding_1.ets.autofix.json b/ets2panda/linter/test/main/dollar_binding_1.ets.autofix.json index a9310c105e..b07e1eb473 100644 --- a/ets2panda/linter/test/main/dollar_binding_1.ets.autofix.json +++ b/ets2panda/linter/test/main/dollar_binding_1.ets.autofix.json @@ -37,7 +37,13 @@ "endLine": 16, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Link, Row, Text } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -48,7 +54,13 @@ "endLine": 18, "endColumn": 9, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Link, Row, Text } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -59,7 +71,13 @@ "endLine": 21, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Link, Row, Text } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -70,7 +88,13 @@ "endLine": 29, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Link, Row, Text } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -81,7 +105,13 @@ "endLine": 31, "endColumn": 8, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Link, Row, Text } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -92,7 +122,13 @@ "endLine": 34, "endColumn": 8, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Link, Row, Text } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" diff --git a/ets2panda/linter/test/main/double_dollar_binding_1.ets.autofix.json b/ets2panda/linter/test/main/double_dollar_binding_1.ets.autofix.json index 932235e593..bc08ccf2ef 100644 --- a/ets2panda/linter/test/main/double_dollar_binding_1.ets.autofix.json +++ b/ets2panda/linter/test/main/double_dollar_binding_1.ets.autofix.json @@ -54,7 +54,13 @@ "endLine": 16, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -65,7 +71,13 @@ "endLine": 18, "endColumn": 9, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -76,7 +88,13 @@ "endLine": 21, "endColumn": 8, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -87,7 +105,13 @@ "endLine": 22, "endColumn": 13, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -98,7 +122,13 @@ "endLine": 29, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -109,7 +139,13 @@ "endLine": 31, "endColumn": 9, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -120,7 +156,13 @@ "endLine": 34, "endColumn": 8, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -131,7 +173,13 @@ "endLine": 35, "endColumn": 15, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -142,7 +190,13 @@ "endLine": 36, "endColumn": 12, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" diff --git a/ets2panda/linter/test/main/double_excla_binding_1.ets.autofix.json b/ets2panda/linter/test/main/double_excla_binding_1.ets.autofix.json index 5e7a183c39..4b94dfd390 100644 --- a/ets2panda/linter/test/main/double_excla_binding_1.ets.autofix.json +++ b/ets2panda/linter/test/main/double_excla_binding_1.ets.autofix.json @@ -1,17 +1,17 @@ { "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." ], "result": [ { @@ -88,7 +88,13 @@ "endLine": 18, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -99,7 +105,13 @@ "endLine": 20, "endColumn": 9, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -110,7 +122,13 @@ "endLine": 23, "endColumn": 8, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -121,7 +139,13 @@ "endLine": 24, "endColumn": 13, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -132,7 +156,13 @@ "endLine": 31, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -143,7 +173,13 @@ "endLine": 33, "endColumn": 9, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -154,7 +190,13 @@ "endLine": 36, "endColumn": 8, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -165,7 +207,13 @@ "endLine": 37, "endColumn": 15, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -176,7 +224,13 @@ "endLine": 38, "endColumn": 12, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -187,7 +241,13 @@ "endLine": 39, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -198,7 +258,13 @@ "endLine": 44, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -209,7 +275,13 @@ "endLine": 46, "endColumn": 9, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -220,7 +292,13 @@ "endLine": 48, "endColumn": 8, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -231,7 +309,13 @@ "endLine": 49, "endColumn": 13, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -242,7 +326,13 @@ "endLine": 56, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -253,7 +343,13 @@ "endLine": 58, "endColumn": 9, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -264,7 +360,13 @@ "endLine": 60, "endColumn": 8, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -275,7 +377,13 @@ "endLine": 61, "endColumn": 13, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -286,7 +394,13 @@ "endLine": 68, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -297,7 +411,13 @@ "endLine": 70, "endColumn": 9, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -308,7 +428,13 @@ "endLine": 72, "endColumn": 8, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -319,7 +445,13 @@ "endLine": 73, "endColumn": 13, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -330,7 +462,13 @@ "endLine": 80, "endColumn": 7, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -341,7 +479,13 @@ "endLine": 81, "endColumn": 13, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -352,7 +496,13 @@ "endLine": 83, "endColumn": 9, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -363,7 +513,13 @@ "endLine": 84, "endColumn": 9, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -374,7 +530,13 @@ "endLine": 87, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -385,7 +547,13 @@ "endLine": 88, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -396,7 +564,13 @@ "endLine": 89, "endColumn": 13, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -407,7 +581,13 @@ "endLine": 99, "endColumn": 13, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -418,7 +598,13 @@ "endLine": 101, "endColumn": 9, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -429,7 +615,13 @@ "endLine": 102, "endColumn": 9, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -440,7 +632,13 @@ "endLine": 105, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -451,7 +649,13 @@ "endLine": 106, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" diff --git a/ets2panda/linter/test/main/extend_decorator_1.ets.autofix.json b/ets2panda/linter/test/main/extend_decorator_1.ets.autofix.json index a89e2a668d..4c4123dea8 100644 --- a/ets2panda/linter/test/main/extend_decorator_1.ets.autofix.json +++ b/ets2panda/linter/test/main/extend_decorator_1.ets.autofix.json @@ -1,17 +1,17 @@ { "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." ], "result": [ { @@ -54,7 +54,13 @@ "endLine": 16, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, Column, Text, ColumnAttribute, Color } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -65,7 +71,13 @@ "endLine": 19, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, Column, Text, ColumnAttribute, Color } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -76,7 +88,13 @@ "endLine": 20, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, Column, Text, ColumnAttribute, Color } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" diff --git a/ets2panda/linter/test/main/interface_import_1.ets.autofix.json b/ets2panda/linter/test/main/interface_import_1.ets.autofix.json index 5873970379..cebc9338ef 100644 --- a/ets2panda/linter/test/main/interface_import_1.ets.autofix.json +++ b/ets2panda/linter/test/main/interface_import_1.ets.autofix.json @@ -1,17 +1,17 @@ { "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." ], "result": [ { @@ -88,7 +88,13 @@ "endLine": 18, "endColumn": 7, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, State, Observed, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -99,7 +105,13 @@ "endLine": 19, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, State, Observed, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -110,7 +122,13 @@ "endLine": 21, "endColumn": 9, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, State, Observed, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -121,7 +139,13 @@ "endLine": 22, "endColumn": 9, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, State, Observed, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -132,7 +156,13 @@ "endLine": 25, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, State, Observed, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -143,7 +173,13 @@ "endLine": 26, "endColumn": 13, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, State, Observed, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -154,7 +190,13 @@ "endLine": 36, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, State, Observed, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -165,7 +207,13 @@ "endLine": 49, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, State, Observed, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -176,7 +224,13 @@ "endLine": 51, "endColumn": 9, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, State, Observed, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -187,7 +241,13 @@ "endLine": 54, "endColumn": 8, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, State, Observed, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -198,7 +258,13 @@ "endLine": 66, "endColumn": 18, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, State, Observed, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -209,7 +275,13 @@ "endLine": 71, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, State, Observed, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -220,7 +292,13 @@ "endLine": 73, "endColumn": 9, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, State, Observed, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -231,7 +309,13 @@ "endLine": 76, "endColumn": 8, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, State, Observed, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" diff --git a/ets2panda/linter/test/main/literals_as_prop_names.ets.autofix.json b/ets2panda/linter/test/main/literals_as_prop_names.ets.autofix.json index 7fb93cd36b..0b1642d1da 100644 --- a/ets2panda/linter/test/main/literals_as_prop_names.ets.autofix.json +++ b/ets2panda/linter/test/main/literals_as_prop_names.ets.autofix.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2023-2025 Huawei Device Co., Ltd.", + "Copyright (c) 2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -592,7 +592,13 @@ "endLine": 115, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 608, + "end": 608, + "replacementText": "\n\nimport { Component, State } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" diff --git a/ets2panda/linter/test/main/numeric_semantics.ets.autofix.json b/ets2panda/linter/test/main/numeric_semantics.ets.autofix.json index cf6e169c5d..8344ba36aa 100644 --- a/ets2panda/linter/test/main/numeric_semantics.ets.autofix.json +++ b/ets2panda/linter/test/main/numeric_semantics.ets.autofix.json @@ -735,7 +735,13 @@ "endLine": 117, "endColumn": 7, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 738, + "end": 738, + "replacementText": "\n\nimport { Entry, Component, State, RelativeContainer, Text, AppStorage } from '@kit.ArkUI';\n" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -746,7 +752,13 @@ "endLine": 118, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 738, + "end": 738, + "replacementText": "\n\nimport { Entry, Component, State, RelativeContainer, Text, AppStorage } from '@kit.ArkUI';\n" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -757,7 +769,13 @@ "endLine": 120, "endColumn": 9, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 738, + "end": 738, + "replacementText": "\n\nimport { Entry, Component, State, RelativeContainer, Text, AppStorage } from '@kit.ArkUI';\n" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -768,7 +786,13 @@ "endLine": 129, "endColumn": 22, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 738, + "end": 738, + "replacementText": "\n\nimport { Entry, Component, State, RelativeContainer, Text, AppStorage } from '@kit.ArkUI';\n" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -779,7 +803,13 @@ "endLine": 130, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 738, + "end": 738, + "replacementText": "\n\nimport { Entry, Component, State, RelativeContainer, Text, AppStorage } from '@kit.ArkUI';\n" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" diff --git a/ets2panda/linter/test/main/provide_annotation_1.ets.autofix.json b/ets2panda/linter/test/main/provide_annotation_1.ets.autofix.json index 48f1ccb311..73e8de4b45 100644 --- a/ets2panda/linter/test/main/provide_annotation_1.ets.autofix.json +++ b/ets2panda/linter/test/main/provide_annotation_1.ets.autofix.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2023-2024 Huawei Device Co., Ltd.", + "Copyright (c) 2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -54,7 +54,13 @@ "endLine": 16, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 616, + "end": 616, + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -65,7 +71,13 @@ "endLine": 18, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 616, + "end": 616, + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -76,7 +88,13 @@ "endLine": 21, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 616, + "end": 616, + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -87,7 +105,13 @@ "endLine": 26, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 616, + "end": 616, + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -98,7 +122,13 @@ "endLine": 28, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 616, + "end": 616, + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -109,7 +139,13 @@ "endLine": 31, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 616, + "end": 616, + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -120,7 +156,13 @@ "endLine": 36, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 616, + "end": 616, + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -131,7 +173,13 @@ "endLine": 38, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 616, + "end": 616, + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" diff --git a/ets2panda/linter/test/main/provide_annotation_2.ets.autofix.json b/ets2panda/linter/test/main/provide_annotation_2.ets.autofix.json index 24c62f190c..4db8f1e8f2 100644 --- a/ets2panda/linter/test/main/provide_annotation_2.ets.autofix.json +++ b/ets2panda/linter/test/main/provide_annotation_2.ets.autofix.json @@ -20,7 +20,13 @@ "endLine": 16, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 616, + "end": 616, + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -31,7 +37,13 @@ "endLine": 18, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 616, + "end": 616, + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -42,7 +54,13 @@ "endLine": 21, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 616, + "end": 616, + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -53,7 +71,13 @@ "endLine": 26, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 616, + "end": 616, + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -64,7 +88,13 @@ "endLine": 28, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 616, + "end": 616, + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -75,7 +105,13 @@ "endLine": 31, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 616, + "end": 616, + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -86,7 +122,13 @@ "endLine": 36, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 616, + "end": 616, + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -97,7 +139,13 @@ "endLine": 38, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 616, + "end": 616, + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" diff --git a/ets2panda/linter/test/main/styles_decorator_anon_1.ets.autofix.json b/ets2panda/linter/test/main/styles_decorator_anon_1.ets.autofix.json index e3b6e42cd4..bbf6e8f769 100644 --- a/ets2panda/linter/test/main/styles_decorator_anon_1.ets.autofix.json +++ b/ets2panda/linter/test/main/styles_decorator_anon_1.ets.autofix.json @@ -37,7 +37,13 @@ "endLine": 16, "endColumn": 7, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, BuilderParam, Require, Button, CommonMethod, Color } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -48,7 +54,13 @@ "endLine": 17, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, BuilderParam, Require, Button, CommonMethod, Color } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -59,7 +71,13 @@ "endLine": 19, "endColumn": 16, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, BuilderParam, Require, Button, CommonMethod, Color } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -70,7 +88,13 @@ "endLine": 20, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, BuilderParam, Require, Button, CommonMethod, Color } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -81,7 +105,13 @@ "endLine": 24, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, BuilderParam, Require, Button, CommonMethod, Color } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" diff --git a/ets2panda/linter/test/main/styles_decorator_global_1.ets.autofix.json b/ets2panda/linter/test/main/styles_decorator_global_1.ets.autofix.json index 5226a810e9..e385b5de17 100644 --- a/ets2panda/linter/test/main/styles_decorator_global_1.ets.autofix.json +++ b/ets2panda/linter/test/main/styles_decorator_global_1.ets.autofix.json @@ -76,7 +76,13 @@ "endLine": 22, "endColumn": 23, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { CommonMethod, Color, Component, Column, BuilderParam, Require, Button } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -87,7 +93,13 @@ "endLine": 31, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { CommonMethod, Color, Component, Column, BuilderParam, Require, Button } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -98,7 +110,13 @@ "endLine": 34, "endColumn": 15, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { CommonMethod, Color, Component, Column, BuilderParam, Require, Button } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -109,7 +127,13 @@ "endLine": 51, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { CommonMethod, Color, Component, Column, BuilderParam, Require, Button } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -120,7 +144,13 @@ "endLine": 53, "endColumn": 18, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { CommonMethod, Color, Component, Column, BuilderParam, Require, Button } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -131,7 +161,13 @@ "endLine": 54, "endColumn": 13, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { CommonMethod, Color, Component, Column, BuilderParam, Require, Button } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" diff --git a/ets2panda/linter/test/main/styles_decorator_struct_1.ets.autofix.json b/ets2panda/linter/test/main/styles_decorator_struct_1.ets.autofix.json index 0268206013..778dc5b85f 100644 --- a/ets2panda/linter/test/main/styles_decorator_struct_1.ets.autofix.json +++ b/ets2panda/linter/test/main/styles_decorator_struct_1.ets.autofix.json @@ -145,7 +145,13 @@ "endLine": 16, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -156,7 +162,13 @@ "endLine": 25, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -167,7 +179,13 @@ "endLine": 26, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -178,7 +196,13 @@ "endLine": 32, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -189,7 +213,13 @@ "endLine": 43, "endColumn": 28, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -200,7 +230,13 @@ "endLine": 44, "endColumn": 17, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -211,7 +247,13 @@ "endLine": 52, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -222,7 +264,13 @@ "endLine": 53, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -233,7 +281,13 @@ "endLine": 59, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -244,7 +298,13 @@ "endLine": 61, "endColumn": 16, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -255,7 +315,13 @@ "endLine": 62, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -266,7 +332,13 @@ "endLine": 67, "endColumn": 27, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -277,7 +349,13 @@ "endLine": 72, "endColumn": 27, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -288,7 +366,13 @@ "endLine": 76, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" @@ -299,7 +383,13 @@ "endLine": 97, "endColumn": 11, "problem": "UIInterfaceImport", - "autofix": [], + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';" + } + ], "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" -- Gitee From 02facd691d38dce9fdc0d2c650f2f4ce757cce81 Mon Sep 17 00:00:00 2001 From: ZhongNing Date: Mon, 7 Apr 2025 15:04:22 +0800 Subject: [PATCH 075/268] [InterOp] ArkTS1.2 import js Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBUOUD Test scenarios:new tests add to the linter Signed-off-by: ZhongNing --- ets2panda/linter/src/lib/CookBookMsg.ts | 3 +- ets2panda/linter/src/lib/FaultAttrs.ts | 1 + ets2panda/linter/src/lib/FaultDesc.ts | 1 + ets2panda/linter/src/lib/Problems.ts | 1 + ets2panda/linter/src/lib/TypeScriptLinter.ts | 53 +++- .../linter/src/lib/autofixes/AutofixTitles.ts | 3 +- .../linter/src/lib/autofixes/Autofixer.ts | 140 ++++++++++ ets2panda/linter/src/lib/utils/TsUtils.ts | 27 ++ .../src/lib/utils/consts/ArkTS2Rules.ts | 3 +- .../linter/src/lib/utils/consts/InteropAPI.ts | 2 + .../linter/test/interop/interop_import_js.ets | 23 ++ .../interop/interop_import_js.ets.args.json | 20 ++ .../interop/interop_import_js.ets.arkts2.json | 158 ++++++++++++ .../interop_import_js.ets.autofix.json | 242 ++++++++++++++++++ .../test/interop/interop_import_js.ets.json | 88 +++++++ .../test/interop/interop_import_js_js.js | 21 ++ .../test/interop/jsfiles/preview_import_js.js | 18 ++ 17 files changed, 800 insertions(+), 4 deletions(-) create mode 100755 ets2panda/linter/test/interop/interop_import_js.ets create mode 100755 ets2panda/linter/test/interop/interop_import_js.ets.args.json create mode 100755 ets2panda/linter/test/interop/interop_import_js.ets.arkts2.json create mode 100755 ets2panda/linter/test/interop/interop_import_js.ets.autofix.json create mode 100755 ets2panda/linter/test/interop/interop_import_js.ets.json create mode 100755 ets2panda/linter/test/interop/interop_import_js_js.js create mode 100755 ets2panda/linter/test/interop/jsfiles/preview_import_js.js diff --git a/ets2panda/linter/src/lib/CookBookMsg.ts b/ets2panda/linter/src/lib/CookBookMsg.ts index b41449034a..3fd4254391 100644 --- a/ets2panda/linter/src/lib/CookBookMsg.ts +++ b/ets2panda/linter/src/lib/CookBookMsg.ts @@ -16,7 +16,7 @@ export const cookBookMsg: string[] = []; export const cookBookTag: string[] = []; -for (let i = 0; i <= 316; i++) { +for (let i = 0; i <= 319; i++) { cookBookMsg[i] = ''; } @@ -290,3 +290,4 @@ cookBookTag[315] = cookBookTag[316] = 'Using typeof as a type is not allowed in this API (arkts-sdk-Type-Query)'; cookBookTag[319] = 'Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)'; cookBookTag[321] = 'Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)'; +cookBookTag[330] = 'Importing directly from "JS" module is not supported (arkts-no-js-import)'; diff --git a/ets2panda/linter/src/lib/FaultAttrs.ts b/ets2panda/linter/src/lib/FaultAttrs.ts index d1a86bff39..76d868a122 100644 --- a/ets2panda/linter/src/lib/FaultAttrs.ts +++ b/ets2panda/linter/src/lib/FaultAttrs.ts @@ -199,3 +199,4 @@ faultsAttrs[FaultID.ApiPathChanged] = new FaultAttributes(315); faultsAttrs[FaultID.SdkTypeQuery] = new FaultAttributes(316); faultsAttrs[FaultID.InteropJsObjectUsage] = new FaultAttributes(319); faultsAttrs[FaultID.LimitedStdLibNoImportConcurrency] = new FaultAttributes(321); +faultsAttrs[FaultID.InterOpImportJs] = new FaultAttributes(330); diff --git a/ets2panda/linter/src/lib/FaultDesc.ts b/ets2panda/linter/src/lib/FaultDesc.ts index 5e2d3fce06..047e32b801 100644 --- a/ets2panda/linter/src/lib/FaultDesc.ts +++ b/ets2panda/linter/src/lib/FaultDesc.ts @@ -187,3 +187,4 @@ faultDesc[FaultID.QuotedHyphenPropsDeprecated] = 'Quoted hyphen props deprecated faultDesc[FaultID.ApiPathChanged] = 'API path have changed'; faultDesc[FaultID.SdkTypeQuery] = 'NO typeof as a type in API'; faultDesc[FaultID.LimitedStdLibNoImportConcurrency] = 'Import Concurrency Deprecated'; +faultDesc[FaultID.InterOpImportJs] = 'No JS import'; diff --git a/ets2panda/linter/src/lib/Problems.ts b/ets2panda/linter/src/lib/Problems.ts index d4fc37a9ab..8e0c70c979 100644 --- a/ets2panda/linter/src/lib/Problems.ts +++ b/ets2panda/linter/src/lib/Problems.ts @@ -188,6 +188,7 @@ export enum FaultID { SdkTypeQuery, InteropJsObjectUsage, LimitedStdLibNoImportConcurrency, + InterOpImportJs, // this should always be last enum LAST_ID } diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index 96a4824645..7ea5ca22e7 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -93,7 +93,7 @@ import { } from './utils/consts/ArkuiConstants'; import { arkuiImportList } from './utils/consts/ArkuiImportList'; import { REFLECT_PROPERTIES, USE_STATIC } from './utils/consts/InteropAPI'; -import { EXTNAME_TS, EXTNAME_D_TS } from './utils/consts/ExtensionName'; +import { EXTNAME_TS, EXTNAME_D_TS, EXTNAME_JS } from './utils/consts/ExtensionName'; import { ARKTS_IGNORE_DIRS_OH_MODULES } from './utils/consts/ArktsIgnorePaths'; import type { ApiInfo, ApiListItem } from './utils/consts/SdkWhitelist'; import { ApiList } from './utils/consts/SdkWhitelist'; @@ -131,6 +131,7 @@ export class TypeScriptLinter { private fileExportDeclCaches: Set | undefined; private sourceFile?: ts.SourceFile; + private useStatic?: boolean; private readonly compatibleSdkVersion: number; private readonly compatibleSdkVersionStage: string; private static sharedModulesCache: Map; @@ -854,6 +855,7 @@ export class TypeScriptLinter { this.handleInvalidIdentifier(importDeclNode); this.checkWorkerImport(importDeclNode); this.checkStdLibConcurrencyImport(importDeclNode); + this.handleInterOpImportJs(importDeclNode); } private handleSdkSendable(tsStringLiteral: ts.StringLiteral): void { @@ -4327,6 +4329,7 @@ export class TypeScriptLinter { } this.sourceFile = sourceFile; + this.useStatic = TsUtils.isArkts12File(sourceFile); this.fileExportDeclCaches = undefined; this.extractImportedNames(this.sourceFile); this.visitSourceFile(this.sourceFile); @@ -5935,4 +5938,52 @@ export class TypeScriptLinter { } } } + + private handleInterOpImportJs(importDecl: ts.ImportDeclaration): void { + if (!this.options.arkts2 || !importDecl || !this.useStatic) { + return; + } + const importClause = importDecl.importClause; + if (!importClause) { + return; + } + const namedBindings = importClause.namedBindings; + let symbol: ts.Symbol | undefined; + let defaultSymbol: ts.Symbol | undefined; + if (importClause.name) { + defaultSymbol = this.tsUtils.trueSymbolAtLocation(importClause.name); + } + if (namedBindings) { + if (ts.isNamedImports(namedBindings)) { + symbol = this.tsUtils.trueSymbolAtLocation(namedBindings.elements[0].name); + } else if (ts.isNamespaceImport(namedBindings)) { + symbol = this.tsUtils.trueSymbolAtLocation(namedBindings.name); + } + } + const symbolToUse = defaultSymbol || symbol; + if (symbolToUse) { + this.tryAutoFixInterOpImportJs(importDecl, importClause, symbolToUse, defaultSymbol); + } + } + + private tryAutoFixInterOpImportJs( + importDecl: ts.ImportDeclaration, + importClause: ts.ImportClause, + symbolToUse: ts.Symbol, + defaultSymbol?: ts.Symbol + ): void { + const declaration = symbolToUse.declarations?.[0]; + if (declaration) { + const sourceFile = declaration.getSourceFile(); + if (sourceFile.fileName.endsWith(EXTNAME_JS)) { + const autofix = this.autofixer?.fixInterOpImportJs( + importDecl, + importClause, + TsUtils.removeOrReplaceQuotes(importDecl.moduleSpecifier.getText(this.sourceFile), false), + defaultSymbol + ); + this.incrementCounters(importDecl, FaultID.InterOpImportJs, autofix); + } + } + } } diff --git a/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts b/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts index f750480c16..d58e12c758 100644 --- a/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts +++ b/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts @@ -48,5 +48,6 @@ export const cookBookRefToFixTitle: Map = new Map([ [258, 'Add "@Observed" decorator'], [259, 'Add UI Interface Import'], [260, '"@Entry" annotaion fixed'], - [263, '"@Provide" annotation fixed'] + [263, '"@Provide" annotation fixed'], + [330, 'Convert import named objects from JS to ESObject'] ]); diff --git a/ets2panda/linter/src/lib/autofixes/Autofixer.ts b/ets2panda/linter/src/lib/autofixes/Autofixer.ts index 80a19e3cc4..01db4d556b 100644 --- a/ets2panda/linter/src/lib/autofixes/Autofixer.ts +++ b/ets2panda/linter/src/lib/autofixes/Autofixer.ts @@ -42,6 +42,8 @@ import { PROVIDE_ALIAS_PROPERTY_NAME, PROVIDE_ALLOW_OVERRIDE_PROPERTY_NAME } from '../utils/consts/ArkuiConstants'; +import { ES_OBJECT } from '../utils/consts/ESObject'; +import { LOAD, GET_PROPERTY_BY_NAME } from '../utils/consts/InteropAPI'; const UNDEFINED_NAME = 'undefined'; @@ -56,6 +58,10 @@ const GENERATED_DESTRUCT_OBJECT_TRESHOLD = 1000; const GENERATED_DESTRUCT_ARRAY_NAME = 'GeneratedDestructArray_'; const GENERATED_DESTRUCT_ARRAY_TRESHOLD = 1000; + +const GENERATED_IMPORT_VARIABLE_NAME = 'GeneratedImportVar_'; +const GENERATED_IMPORT_VARIABLE_TRESHOLD = 1000; + const SPECIAL_LIB_NAME = 'specialAutofixLib'; export interface Autofix { @@ -97,6 +103,14 @@ export class Autofixer { GENERATED_OBJECT_LITERAL_INTERFACE_TRESHOLD ); + private readonly importVarNameGenerator = new NameGenerator( + GENERATED_IMPORT_VARIABLE_NAME, + GENERATED_IMPORT_VARIABLE_TRESHOLD + ); + + private modVarName: string = ''; + private readonly lastImportEndMap = new Map(); + private readonly symbolCache: SymbolCache; private readonly renameSymbolAsIdentifierCache = new Map(); @@ -3135,4 +3149,130 @@ export class Autofixer { } return undefined; } + + private static createVariableForInteropImport( + newVarName: string, + interopObject: string, + interopMethod: string, + interopPropertyOrModule: string + ): ts.VariableStatement { + const newVarDecl = ts.factory.createVariableStatement( + undefined, + ts.factory.createVariableDeclarationList( + [ + ts.factory.createVariableDeclaration( + ts.factory.createIdentifier(newVarName), + undefined, + undefined, + ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression( + ts.factory.createIdentifier(interopObject), + ts.factory.createIdentifier(interopMethod) + ), + undefined, + [ts.factory.createStringLiteral(interopPropertyOrModule)] + ) + ) + ], + ts.NodeFlags.Let + ) + ); + return newVarDecl; + } + + private static getOriginalNameAtSymbol(symbolName: string, symbol?: ts.Symbol): string { + if (symbol) { + const originalDeclaration = symbol.declarations?.[0]; + let originalName = ''; + if (originalDeclaration) { + const isReturnNameOnSomeCase = + ts.isFunctionDeclaration(originalDeclaration) || + ts.isClassDeclaration(originalDeclaration) || + ts.isInterfaceDeclaration(originalDeclaration) || + ts.isEnumDeclaration(originalDeclaration); + if (isReturnNameOnSomeCase) { + originalName = originalDeclaration.name?.text || symbolName; + } else if (ts.isVariableDeclaration(originalDeclaration)) { + originalName = originalDeclaration.name.getText(); + } + } + return originalName; + } + return ''; + } + + fixInterOpImportJs( + importDecl: ts.ImportDeclaration, + importClause: ts.ImportClause, + moduleSpecifier: string, + defaultSymbol?: ts.Symbol + ): Autofix[] | undefined { + let statements: string[] = []; + statements = this.constructAndSaveimportDecl2Arrays(importDecl, moduleSpecifier, undefined, statements, true); + if (importClause.name) { + const symbolName = importClause.name.text; + const originalName = Autofixer.getOriginalNameAtSymbol(symbolName, defaultSymbol); + statements = this.constructAndSaveimportDecl2Arrays(importDecl, symbolName, originalName, statements, false); + } + const namedBindings = importClause.namedBindings; + if (namedBindings && ts.isNamedImports(namedBindings)) { + namedBindings.elements.map((element) => { + const symbolName = element.name.text; + const originalName = element.propertyName ? element.propertyName.text : symbolName; + statements = this.constructAndSaveimportDecl2Arrays(importDecl, symbolName, originalName, statements, false); + return statements; + }); + } + if (statements.length <= 0) { + return undefined; + } + let lastImportEnd = this.lastImportEndMap.get(this.sourceFile.fileName); + if (!lastImportEnd) { + lastImportEnd = this.getLastImportEnd(); + this.lastImportEndMap.set(this.sourceFile.fileName, lastImportEnd); + } + return [ + { start: importDecl.getStart(), end: importDecl.getEnd(), replacementText: '' }, + { start: lastImportEnd, end: lastImportEnd, replacementText: statements.join('\n') } + ]; + } + + private constructAndSaveimportDecl2Arrays( + importDecl: ts.ImportDeclaration, + symbolName: string, + originalName: string | undefined, + statements: string[], + isLoad: boolean + ): string[] { + if (isLoad) { + const newVarName = TsUtils.generateUniqueName(this.importVarNameGenerator, this.sourceFile); + if (!newVarName) { + return []; + } + this.modVarName = newVarName; + } + const propertyName = originalName || symbolName; + const constructDeclInfo: string[] = isLoad ? + [this.modVarName, ES_OBJECT, LOAD] : + [symbolName, this.modVarName, GET_PROPERTY_BY_NAME]; + const newVarDecl = Autofixer.createVariableForInteropImport( + constructDeclInfo[0], + constructDeclInfo[1], + constructDeclInfo[2], + propertyName + ); + const text = this.printer.printNode(ts.EmitHint.Unspecified, newVarDecl, importDecl.getSourceFile()); + statements.push(TsUtils.removeOrReplaceQuotes(text, true)); + return statements; + } + + private getLastImportEnd(): number { + let lastImportEnd = 0; + this.sourceFile.statements.forEach((statement) => { + if (ts.isImportDeclaration(statement)) { + lastImportEnd = statement.getEnd(); + } + }); + return lastImportEnd; + } } diff --git a/ets2panda/linter/src/lib/utils/TsUtils.ts b/ets2panda/linter/src/lib/utils/TsUtils.ts index 8334bbac03..d2a6a7a450 100644 --- a/ets2panda/linter/src/lib/utils/TsUtils.ts +++ b/ets2panda/linter/src/lib/utils/TsUtils.ts @@ -45,6 +45,7 @@ import { ETS } from './consts/TsSuffix'; import { STRINGLITERAL_NUMBER, STRINGLITERAL_NUMBER_ARRAY } from './consts/StringLiteral'; import { ETS_MODULE, VALID_OHM_COMPONENTS_MODULE_PATH } from './consts/OhmUrl'; import { EXTNAME_JS } from './consts/ExtensionName'; +import { USE_STATIC } from './consts/InteropAPI'; export const SYMBOL = 'Symbol'; export const SYMBOL_CONSTRUCTOR = 'SymbolConstructor'; @@ -3490,4 +3491,30 @@ export class TsUtils { return undefined; } + + static isArkts12File(sourceFile: ts.SourceFile): boolean { + if (!sourceFile) { + return false; + } + const statements = sourceFile.statements; + return ( + ts.isExpressionStatement(statements[0]) && + ts.isStringLiteral(statements[0].expression) && + statements[0].expression.getText() === USE_STATIC + ); + } + + static removeOrReplaceQuotes(str: string, isReplace: boolean): string { + if (isReplace) { + const charArray = new Array(str.length); + for (let i = 0; i < str.length; i++) { + charArray[i] = str[i] === '"' ? '\'' : str[i]; + } + return charArray.join(''); + } + if (str.startsWith('\'') && str.endsWith('\'') || str.startsWith('"') && str.endsWith('"')) { + return str.slice(1, -1); + } + return str; + } } diff --git a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts index a59849d2aa..f7598ddc67 100644 --- a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts +++ b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts @@ -78,5 +78,6 @@ export const arkts2Rules: number[] = [ 314, 315, 316, - 321 + 321, + 330 ]; diff --git a/ets2panda/linter/src/lib/utils/consts/InteropAPI.ts b/ets2panda/linter/src/lib/utils/consts/InteropAPI.ts index 8571c768d5..bdc4f457ab 100644 --- a/ets2panda/linter/src/lib/utils/consts/InteropAPI.ts +++ b/ets2panda/linter/src/lib/utils/consts/InteropAPI.ts @@ -30,3 +30,5 @@ export const REFLECT_PROPERTIES = [ 'isExtensible', 'preventExtensions' ]; +export const LOAD = 'load'; +export const GET_PROPERTY_BY_NAME = 'getPropertyByName'; diff --git a/ets2panda/linter/test/interop/interop_import_js.ets b/ets2panda/linter/test/interop/interop_import_js.ets new file mode 100755 index 0000000000..3325f1bdd9 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_js.ets @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use static' +import { Cjs } from '../main/js_lib'; +import { fjs } from '../main/js_lib'; +import { CPreview,bar,foo } from "./jsfiles/preview_import_js"; +import myAaa from "./interop_import_js_js"; +import myAaa,{ClassA,Dog} from "./interop_import_js_js"; +import * as namespace from "./interop_import_js_js"; +import { Wiki, Dog as Doge } from './interop_import_js_js' \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_import_js.ets.args.json b/ets2panda/linter/test/interop/interop_import_js.ets.args.json new file mode 100755 index 0000000000..815373beb6 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_js.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_import_js.ets.arkts2.json b/ets2panda/linter/test/interop/interop_import_js.ets.arkts2.json new file mode 100755 index 0000000000..d8a70abf60 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_js.ets.arkts2.json @@ -0,0 +1,158 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 38, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 38, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 38, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 38, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 64, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 64, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 44, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 44, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 57, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 57, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 1, + "endLine": 22, + "endColumn": 53, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 1, + "endLine": 22, + "endColumn": 53, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 1, + "endLine": 23, + "endColumn": 59, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 1, + "endLine": 23, + "endColumn": 59, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_import_js.ets.autofix.json b/ets2panda/linter/test/interop/interop_import_js.ets.autofix.json new file mode 100755 index 0000000000..f1de093cb7 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_js.ets.autofix.json @@ -0,0 +1,242 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 38, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 38, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 619, + "end": 656, + "replacementText": "" + }, + { + "start": 971, + "end": 971, + "replacementText": "let GeneratedImportVar_1 = ESObject.load('../main/js_lib');\nlet Cjs = GeneratedImportVar_1.getPropertyByName('Cjs');" + } + ], + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 38, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 38, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 657, + "end": 694, + "replacementText": "" + }, + { + "start": 971, + "end": 971, + "replacementText": "let GeneratedImportVar_2 = ESObject.load('../main/js_lib');\nlet fjs = GeneratedImportVar_2.getPropertyByName('fjs');" + } + ], + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 64, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 64, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 695, + "end": 758, + "replacementText": "" + }, + { + "start": 971, + "end": 971, + "replacementText": "let GeneratedImportVar_3 = ESObject.load('./jsfiles/preview_import_js');\nlet CPreview = GeneratedImportVar_3.getPropertyByName('CPreview');\nlet bar = GeneratedImportVar_3.getPropertyByName('bar');\nlet foo = GeneratedImportVar_3.getPropertyByName('foo');" + } + ], + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 44, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 44, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 759, + "end": 802, + "replacementText": "" + }, + { + "start": 971, + "end": 971, + "replacementText": "let GeneratedImportVar_4 = ESObject.load('./interop_import_js_js');\nlet myAaa = GeneratedImportVar_4.getPropertyByName('aaa');" + } + ], + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 57, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 57, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 803, + "end": 859, + "replacementText": "" + }, + { + "start": 971, + "end": 971, + "replacementText": "let GeneratedImportVar_5 = ESObject.load('./interop_import_js_js');\nlet myAaa = GeneratedImportVar_5.getPropertyByName('aaa');\nlet ClassA = GeneratedImportVar_5.getPropertyByName('ClassA');\nlet Dog = GeneratedImportVar_5.getPropertyByName('Dog');" + } + ], + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 1, + "endLine": 22, + "endColumn": 53, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 1, + "endLine": 22, + "endColumn": 53, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 860, + "end": 912, + "replacementText": "" + }, + { + "start": 971, + "end": 971, + "replacementText": "let GeneratedImportVar_6 = ESObject.load('./interop_import_js_js');" + } + ], + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 1, + "endLine": 23, + "endColumn": 59, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 1, + "endLine": 23, + "endColumn": 59, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 913, + "end": 971, + "replacementText": "" + }, + { + "start": 971, + "end": 971, + "replacementText": "let GeneratedImportVar_7 = ESObject.load('./interop_import_js_js');\nlet Wiki = GeneratedImportVar_7.getPropertyByName('Wiki');\nlet Doge = GeneratedImportVar_7.getPropertyByName('Dog');" + } + ], + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_import_js.ets.json b/ets2panda/linter/test/interop/interop_import_js.ets.json new file mode 100755 index 0000000000..c75509e775 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_js.ets.json @@ -0,0 +1,88 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 38, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 38, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 64, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 44, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 57, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 1, + "endLine": 22, + "endColumn": 53, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 1, + "endLine": 23, + "endColumn": 59, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_import_js_js.js b/ets2panda/linter/test/interop/interop_import_js_js.js new file mode 100755 index 0000000000..b0bcaa8cba --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_js_js.js @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export default function aaa() { + return "Hello Default Export"; +} +export class ClassA {} +export function Dog(a){} +export let Wiki = {name: "123"} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/jsfiles/preview_import_js.js b/ets2panda/linter/test/interop/jsfiles/preview_import_js.js new file mode 100755 index 0000000000..f9e84c9a1b --- /dev/null +++ b/ets2panda/linter/test/interop/jsfiles/preview_import_js.js @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2023-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export class CPreview {} +export function bar(a){} +export let foo = {name: "123"} \ No newline at end of file -- Gitee From 7c6ca1c46363d596546e090001f3da4fef23cfb5 Mon Sep 17 00:00:00 2001 From: zhongning Date: Thu, 10 Apr 2025 16:46:22 +0800 Subject: [PATCH 076/268] Check arkTS directly call JS function Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBX12O Test scenarios:ArkTS directly call JS functions or parameters Signed-off-by: zhongning --- ets2panda/linter/src/lib/CookBookMsg.ts | 1 + ets2panda/linter/src/lib/FaultAttrs.ts | 1 + ets2panda/linter/src/lib/FaultDesc.ts | 1 + ets2panda/linter/src/lib/Problems.ts | 1 + ets2panda/linter/src/lib/TypeScriptLinter.ts | 12 ++ .../src/lib/utils/consts/ArkTS2Rules.ts | 3 +- .../linter/test/interop/call_function.ets | 19 +++ .../test/interop/call_function.ets.args.json | 19 +++ .../interop/call_function.ets.arkts2.json | 68 ++++++++ .../test/interop/call_function.ets.json | 28 ++++ .../linter/test/interop/call_function_js.js | 17 ++ .../interop_import_js_rules.ets.arkts2.json | 76 ++++++--- .../interop_import_js_rules.ets.autofix.json | 146 +++++++++++------- 13 files changed, 310 insertions(+), 82 deletions(-) create mode 100644 ets2panda/linter/test/interop/call_function.ets create mode 100644 ets2panda/linter/test/interop/call_function.ets.args.json create mode 100644 ets2panda/linter/test/interop/call_function.ets.arkts2.json create mode 100644 ets2panda/linter/test/interop/call_function.ets.json create mode 100644 ets2panda/linter/test/interop/call_function_js.js diff --git a/ets2panda/linter/src/lib/CookBookMsg.ts b/ets2panda/linter/src/lib/CookBookMsg.ts index 3fd4254391..8c0c2887b2 100644 --- a/ets2panda/linter/src/lib/CookBookMsg.ts +++ b/ets2panda/linter/src/lib/CookBookMsg.ts @@ -291,3 +291,4 @@ cookBookTag[316] = 'Using typeof as a type is not allowed in this API (arkts-sdk cookBookTag[319] = 'Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)'; cookBookTag[321] = 'Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)'; cookBookTag[330] = 'Importing directly from "JS" module is not supported (arkts-no-js-import)'; +cookBookTag[331] = 'ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)'; diff --git a/ets2panda/linter/src/lib/FaultAttrs.ts b/ets2panda/linter/src/lib/FaultAttrs.ts index 76d868a122..8e45c99cd6 100644 --- a/ets2panda/linter/src/lib/FaultAttrs.ts +++ b/ets2panda/linter/src/lib/FaultAttrs.ts @@ -200,3 +200,4 @@ faultsAttrs[FaultID.SdkTypeQuery] = new FaultAttributes(316); faultsAttrs[FaultID.InteropJsObjectUsage] = new FaultAttributes(319); faultsAttrs[FaultID.LimitedStdLibNoImportConcurrency] = new FaultAttributes(321); faultsAttrs[FaultID.InterOpImportJs] = new FaultAttributes(330); +faultsAttrs[FaultID.CallJSFunction] = new FaultAttributes(331); diff --git a/ets2panda/linter/src/lib/FaultDesc.ts b/ets2panda/linter/src/lib/FaultDesc.ts index 047e32b801..33a98de33d 100644 --- a/ets2panda/linter/src/lib/FaultDesc.ts +++ b/ets2panda/linter/src/lib/FaultDesc.ts @@ -188,3 +188,4 @@ faultDesc[FaultID.ApiPathChanged] = 'API path have changed'; faultDesc[FaultID.SdkTypeQuery] = 'NO typeof as a type in API'; faultDesc[FaultID.LimitedStdLibNoImportConcurrency] = 'Import Concurrency Deprecated'; faultDesc[FaultID.InterOpImportJs] = 'No JS import'; +faultDesc[FaultID.CallJSFunction] = 'Call JS Function'; diff --git a/ets2panda/linter/src/lib/Problems.ts b/ets2panda/linter/src/lib/Problems.ts index 8e0c70c979..93d9bd4dc3 100644 --- a/ets2panda/linter/src/lib/Problems.ts +++ b/ets2panda/linter/src/lib/Problems.ts @@ -189,6 +189,7 @@ export enum FaultID { InteropJsObjectUsage, LimitedStdLibNoImportConcurrency, InterOpImportJs, + CallJSFunction, // this should always be last enum LAST_ID } diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index 7ea5ca22e7..3dd1ee219c 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -3260,6 +3260,7 @@ export class TypeScriptLinter { this.checkArkTSObjectInterop(tsCallExpr); this.handleAppStorageCallExpression(tsCallExpr); this.fixJsImportCallExpression(tsCallExpr); + this.handleCallJSFunction(tsCallExpr, calleeSym, callSignature); } private handleAppStorageCallExpression(tsCallExpr: ts.CallExpression): void { @@ -3307,6 +3308,17 @@ export class TypeScriptLinter { } } + handleCallJSFunction(tsCallExpr: ts.CallExpression, sym: ts.Symbol | undefined, callSignature: ts.Signature | undefined): void { + if (!callSignature) { + return; + } + if (TypeScriptLinter.isDeclaredInArkTs2(callSignature) && this.options.arkts2) { + if (sym?.declarations?.[0]?.getSourceFile().fileName.endsWith(EXTNAME_JS)) { + this.incrementCounters(tsCallExpr, FaultID.CallJSFunction); + } + } + } + private handleInteropForCallExpression(tsCallExpr: ts.CallExpression): void { const callSignature = this.tsTypeChecker.getResolvedSignature(tsCallExpr); if (!callSignature) { diff --git a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts index f7598ddc67..2ce82e1a06 100644 --- a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts +++ b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts @@ -79,5 +79,6 @@ export const arkts2Rules: number[] = [ 315, 316, 321, - 330 + 330, + 331 ]; diff --git a/ets2panda/linter/test/interop/call_function.ets b/ets2panda/linter/test/interop/call_function.ets new file mode 100644 index 0000000000..b76d862f4a --- /dev/null +++ b/ets2panda/linter/test/interop/call_function.ets @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +'use static' +import {foo,bar} from "./call_function_js" + +foo() +bar(123) \ No newline at end of file diff --git a/ets2panda/linter/test/interop/call_function.ets.args.json b/ets2panda/linter/test/interop/call_function.ets.args.json new file mode 100644 index 0000000000..9c3d973432 --- /dev/null +++ b/ets2panda/linter/test/interop/call_function.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/call_function.ets.arkts2.json b/ets2panda/linter/test/interop/call_function.ets.arkts2.json new file mode 100644 index 0000000000..fe84731cc8 --- /dev/null +++ b/ets2panda/linter/test/interop/call_function.ets.arkts2.json @@ -0,0 +1,68 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 43, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 6, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 6, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 9, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 9, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/call_function.ets.json b/ets2panda/linter/test/interop/call_function.ets.json new file mode 100644 index 0000000000..08b4bd7b56 --- /dev/null +++ b/ets2panda/linter/test/interop/call_function.ets.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 43, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/call_function_js.js b/ets2panda/linter/test/interop/call_function_js.js new file mode 100644 index 0000000000..1ca0a23aeb --- /dev/null +++ b/ets2panda/linter/test/interop/call_function_js.js @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export function foo(){} +export function bar(a){} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_import_js_rules.ets.arkts2.json b/ets2panda/linter/test/interop/interop_import_js_rules.ets.arkts2.json index 3ce37c6742..06fc63cc77 100644 --- a/ets2panda/linter/test/interop/interop_import_js_rules.ets.arkts2.json +++ b/ets2panda/linter/test/interop/interop_import_js_rules.ets.arkts2.json @@ -23,8 +23,8 @@ "suggest": "", "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", "severity": "ERROR" - }, - { + }, + { "line": 30, "column": 5, "endLine": 30, @@ -33,8 +33,8 @@ "suggest": "", "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", "severity": "ERROR" - }, - { + }, + { "line": 34, "column": 1, "endLine": 34, @@ -43,8 +43,8 @@ "suggest": "", "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", "severity": "ERROR" - }, - { + }, + { "line": 38, "column": 1, "endLine": 38, @@ -53,8 +53,8 @@ "suggest": "", "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", "severity": "ERROR" - }, - { + }, + { "line": 41, "column": 3, "endLine": 41, @@ -63,8 +63,18 @@ "suggest": "", "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", "severity": "ERROR" - }, - { + }, + { + "line": 41, + "column": 3, + "endLine": 41, + "endColumn": 8, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + }, + { "line": 46, "column": 11, "endLine": 46, @@ -73,8 +83,8 @@ "suggest": "", "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", "severity": "ERROR" - }, - { + }, + { "line": 47, "column": 11, "endLine": 47, @@ -83,8 +93,8 @@ "suggest": "", "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", "severity": "ERROR" - }, - { + }, + { "line": 48, "column": 10, "endLine": 48, @@ -93,8 +103,8 @@ "suggest": "", "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" - }, - { + }, + { "line": 49, "column": 11, "endLine": 49, @@ -103,8 +113,8 @@ "suggest": "", "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", "severity": "ERROR" - }, - { + }, + { "line": 50, "column": 3, "endLine": 50, @@ -113,8 +123,8 @@ "suggest": "", "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", "severity": "ERROR" - }, - { + }, + { "line": 60, "column": 1, "endLine": 60, @@ -123,8 +133,18 @@ "suggest": "", "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", "severity": "ERROR" - }, - { + }, + { + "line": 60, + "column": 1, + "endLine": 60, + "endColumn": 13, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + }, + { "line": 61, "column": 1, "endLine": 61, @@ -133,6 +153,16 @@ "suggest": "", "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", "severity": "ERROR" - } + }, + { + "line": 61, + "column": 1, + "endLine": 61, + "endColumn": 15, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + } ] } diff --git a/ets2panda/linter/test/interop/interop_import_js_rules.ets.autofix.json b/ets2panda/linter/test/interop/interop_import_js_rules.ets.autofix.json index f386321dc2..6378a926e0 100644 --- a/ets2panda/linter/test/interop/interop_import_js_rules.ets.autofix.json +++ b/ets2panda/linter/test/interop/interop_import_js_rules.ets.autofix.json @@ -21,34 +21,34 @@ "endColumn": 15, "problem": "InteropJsObjectUsage", "autofix": [ - { - "replacementText": "foo.getPropertyByName('isGood').toBoolean()", - "start": 1031, - "end": 1041 - } + { + "replacementText": "foo.getPropertyByName('isGood').toBoolean()", + "start": 1031, + "end": 1041 + } ], "suggest": "", "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", "severity": "ERROR" - }, - { + }, + { "line": 30, "column": 5, "endLine": 30, "endColumn": 11, "problem": "InteropJsObjectUsage", "autofix": [ - { - "replacementText": "ff1.getPropertyByName('f1').toNumber()", - "start": 1051, - "end": 1057 - } + { + "replacementText": "ff1.getPropertyByName('f1').toNumber()", + "start": 1051, + "end": 1057 + } ], "suggest": "", "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", "severity": "ERROR" - }, - { + }, + { "line": 34, "column": 1, "endLine": 34, @@ -57,8 +57,8 @@ "suggest": "", "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", "severity": "ERROR" - }, - { + }, + { "line": 38, "column": 1, "endLine": 38, @@ -67,8 +67,8 @@ "suggest": "", "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", "severity": "ERROR" - }, - { + }, + { "line": 41, "column": 3, "endLine": 41, @@ -77,93 +77,103 @@ "suggest": "", "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", "severity": "ERROR" - }, - { + }, + { + "line": 41, + "column": 3, + "endLine": 41, + "endColumn": 8, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + }, + { "line": 46, "column": 11, "endLine": 46, "endColumn": 18, "problem": "InteropJsObjectUsage", "autofix": [ - { - "replacementText": "ff3.getPropertyByName('arr')", - "start": 1277, - "end": 1284 - } + { + "replacementText": "ff3.getPropertyByName('arr')", + "start": 1277, + "end": 1284 + } ], "suggest": "", "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", "severity": "ERROR" - }, - { + }, + { "line": 47, "column": 11, "endLine": 47, "endColumn": 21, "problem": "InteropJsObjectUsage", "autofix": [ - { - "replacementText": "arr.getPropertyByName('length').toNumber()", - "start": 1295, - "end": 1315 - } + { + "replacementText": "arr.getPropertyByName('length').toNumber()", + "start": 1295, + "end": 1315 + } ], "suggest": "", "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", "severity": "ERROR" - }, - { + }, + { "line": 48, "column": 10, "endLine": 48, "endColumn": 15, "problem": "NumericSemantics", "autofix": [ - { - "start": 1325, - "end": 1330, - "replacementText": "i: number = 0" - } + { + "start": 1325, + "end": 1330, + "replacementText": "i: number = 0" + } ], "suggest": "", "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" - }, - { + }, + { "line": 49, "column": 11, "endLine": 49, "endColumn": 17, "problem": "InteropJsObjectUsage", "autofix": [ - { - "replacementText": "arr.getPropertyByIndex(i).toNumber()", - "start": 1358, - "end": 1364 - } + { + "replacementText": "arr.getPropertyByIndex(i).toNumber()", + "start": 1358, + "end": 1364 + } ], "suggest": "", "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", "severity": "ERROR" - }, - { + }, + { "line": 50, "column": 3, "endLine": 50, "endColumn": 9, "problem": "InteropJsObjectUsage", "autofix": [ - { - "replacementText": "arr.setPropertyByIndex(i, ESObject.wrap(0))", - "start": 1367, - "end": 1377 - } + { + "replacementText": "arr.setPropertyByIndex(i, ESObject.wrap(0))", + "start": 1367, + "end": 1377 + } ], "suggest": "", "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", "severity": "ERROR" - }, - { + }, + { "line": 60, "column": 1, "endLine": 60, @@ -172,8 +182,18 @@ "suggest": "", "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", "severity": "ERROR" - }, - { + }, + { + "line": 60, + "column": 1, + "endLine": 60, + "endColumn": 13, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + }, + { "line": 61, "column": 1, "endLine": 61, @@ -182,6 +202,16 @@ "suggest": "", "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", "severity": "ERROR" - } + }, + { + "line": 61, + "column": 1, + "endLine": 61, + "endColumn": 15, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + } ] } -- Gitee From 7ce308744a5fcb6c14ea0dac19f24e368e10fa20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=92=9F=E6=9F=A0?= Date: Mon, 7 Apr 2025 16:58:14 +0800 Subject: [PATCH 077/268] [InterOp] arkts-no-js-obj-property MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBUZD4 Test scenarios: new tests added to the linter Signed-off-by: 钟柠 --- ets2panda/linter/src/lib/CookBookMsg.ts | 1 + ets2panda/linter/src/lib/FaultAttrs.ts | 1 + ets2panda/linter/src/lib/FaultDesc.ts | 1 + ets2panda/linter/src/lib/Problems.ts | 1 + ets2panda/linter/src/lib/TypeScriptLinter.ts | 23 ++++- .../linter/src/lib/autofixes/AutofixTitles.ts | 3 +- .../linter/src/lib/autofixes/Autofixer.ts | 44 +++++++++ .../src/lib/utils/consts/ArkTS2Rules.ts | 3 +- .../linter/test/interop/interop_import_js.js | 16 ++++ .../interop_not_have_property_arkts2.ets | 22 +++++ ...rop_not_have_property_arkts2.ets.args.json | 20 ++++ ...p_not_have_property_arkts2.ets.arkts2.json | 68 +++++++++++++ ..._not_have_property_arkts2.ets.autofix.json | 96 +++++++++++++++++++ .../interop_not_have_property_arkts2.ets.json | 28 ++++++ 14 files changed, 324 insertions(+), 3 deletions(-) create mode 100755 ets2panda/linter/test/interop/interop_import_js.js create mode 100755 ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets create mode 100755 ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.args.json create mode 100755 ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.arkts2.json create mode 100755 ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.autofix.json create mode 100755 ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.json diff --git a/ets2panda/linter/src/lib/CookBookMsg.ts b/ets2panda/linter/src/lib/CookBookMsg.ts index 8c0c2887b2..d864f5d0e9 100644 --- a/ets2panda/linter/src/lib/CookBookMsg.ts +++ b/ets2panda/linter/src/lib/CookBookMsg.ts @@ -292,3 +292,4 @@ cookBookTag[319] = 'Direct usage of interop JS objects is not supported (arkts-i cookBookTag[321] = 'Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)'; cookBookTag[330] = 'Importing directly from "JS" module is not supported (arkts-no-js-import)'; cookBookTag[331] = 'ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)'; +cookBookTag[332] = 'Properties of interop objects can\'t be accessed directly (arkts-no-js-obj-property)'; diff --git a/ets2panda/linter/src/lib/FaultAttrs.ts b/ets2panda/linter/src/lib/FaultAttrs.ts index 8e45c99cd6..6031b808fb 100644 --- a/ets2panda/linter/src/lib/FaultAttrs.ts +++ b/ets2panda/linter/src/lib/FaultAttrs.ts @@ -201,3 +201,4 @@ faultsAttrs[FaultID.InteropJsObjectUsage] = new FaultAttributes(319); faultsAttrs[FaultID.LimitedStdLibNoImportConcurrency] = new FaultAttributes(321); faultsAttrs[FaultID.InterOpImportJs] = new FaultAttributes(330); faultsAttrs[FaultID.CallJSFunction] = new FaultAttributes(331); +faultsAttrs[FaultID.InteropObjectProperty] = new FaultAttributes(332); diff --git a/ets2panda/linter/src/lib/FaultDesc.ts b/ets2panda/linter/src/lib/FaultDesc.ts index 33a98de33d..e5cdec5110 100644 --- a/ets2panda/linter/src/lib/FaultDesc.ts +++ b/ets2panda/linter/src/lib/FaultDesc.ts @@ -189,3 +189,4 @@ faultDesc[FaultID.SdkTypeQuery] = 'NO typeof as a type in API'; faultDesc[FaultID.LimitedStdLibNoImportConcurrency] = 'Import Concurrency Deprecated'; faultDesc[FaultID.InterOpImportJs] = 'No JS import'; faultDesc[FaultID.CallJSFunction] = 'Call JS Function'; +faultDesc[FaultID.InteropObjectProperty] = 'Interop property access'; diff --git a/ets2panda/linter/src/lib/Problems.ts b/ets2panda/linter/src/lib/Problems.ts index 93d9bd4dc3..df323bae43 100644 --- a/ets2panda/linter/src/lib/Problems.ts +++ b/ets2panda/linter/src/lib/Problems.ts @@ -190,6 +190,7 @@ export enum FaultID { LimitedStdLibNoImportConcurrency, InterOpImportJs, CallJSFunction, + InteropObjectProperty, // this should always be last enum LAST_ID } diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index 3dd1ee219c..5a98f7aadd 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -941,7 +941,7 @@ export class TypeScriptLinter { this.handleTsInterop(propertyAccessNode, () => { this.checkInteropForPropertyAccess(propertyAccessNode); }); - + this.propertyAccessExpressionForInterop(exprSym, propertyAccessNode); if (this.isPrototypePropertyAccess(propertyAccessNode, exprSym, baseExprSym, baseExprType)) { this.incrementCounters(propertyAccessNode.name, FaultID.Prototype); } @@ -971,6 +971,27 @@ export class TypeScriptLinter { this.fixJsImportPropertyAccessExpression(node); } + propertyAccessExpressionForInterop( + exprSym: ts.Symbol | undefined, + propertyAccessNode: ts.PropertyAccessExpression + ): void { + if (this.useStatic && this.options.arkts2) { + const declaration = exprSym?.declarations?.[0]; + if (declaration?.getSourceFile().fileName.endsWith(EXTNAME_JS)) { + if ( + ts.isBinaryExpression(propertyAccessNode.parent) && + propertyAccessNode.parent.operatorToken.kind === ts.SyntaxKind.EqualsToken + ) { + const autofix = this.autofixer?.fixInteropBinaryExpression(propertyAccessNode.parent); + this.incrementCounters(propertyAccessNode.parent, FaultID.InteropObjectProperty, autofix); + } else { + const autofix = this.autofixer?.fixInteropPropertyAccessExpression(propertyAccessNode); + this.incrementCounters(propertyAccessNode, FaultID.InteropObjectProperty, autofix); + } + } + } + } + checkFunctionProperty( node: ts.PropertyAccessExpression, baseExprSym: ts.Symbol | undefined, diff --git a/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts b/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts index d58e12c758..eb1852e7cb 100644 --- a/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts +++ b/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts @@ -49,5 +49,6 @@ export const cookBookRefToFixTitle: Map = new Map([ [259, 'Add UI Interface Import'], [260, '"@Entry" annotaion fixed'], [263, '"@Provide" annotation fixed'], - [330, 'Convert import named objects from JS to ESObject'] + [330, 'Convert import named objects from JS to ESObject'], + [332, 'Using the ESObject interface to access properties'] ]); diff --git a/ets2panda/linter/src/lib/autofixes/Autofixer.ts b/ets2panda/linter/src/lib/autofixes/Autofixer.ts index 01db4d556b..78d75dcd50 100644 --- a/ets2panda/linter/src/lib/autofixes/Autofixer.ts +++ b/ets2panda/linter/src/lib/autofixes/Autofixer.ts @@ -3275,4 +3275,48 @@ export class Autofixer { }); return lastImportEnd; } + + fixInteropPropertyAccessExpression(express: ts.PropertyAccessExpression): Autofix[] | undefined { + let text: string = ''; + const statements = ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression(express.expression, ts.factory.createIdentifier('getPropertyByName')), + undefined, + [ts.factory.createStringLiteral(express.name.getText())] + ); + text = this.printer.printNode(ts.EmitHint.Unspecified, statements, express.getSourceFile()); + return [{ start: express.getStart(), end: express.getEnd(), replacementText: text }]; + } + + fixInteropBinaryExpression(express: ts.BinaryExpression): Autofix[] | undefined { + const left = express.left; + const right = express.right; + let objectName = ''; + let propertyName = ''; + if (ts.isPropertyAccessExpression(left)) { + objectName = left.expression.getText(); + propertyName = left.name.text; + } else { + return undefined; + } + const statements = ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression( + ts.factory.createIdentifier(objectName), + ts.factory.createIdentifier('setPropertyByName') + ), + undefined, + [ + ts.factory.createStringLiteral(propertyName), + ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression( + ts.factory.createIdentifier(ES_OBJECT), + ts.factory.createIdentifier('wrap') + ), + undefined, + [ts.factory.createIdentifier(right.getText())] + ) + ] + ); + const replacementText = this.printer.printNode(ts.EmitHint.Unspecified, statements, express.getSourceFile()); + return [{ start: express.getStart(), end: express.getEnd(), replacementText: replacementText }]; + } } diff --git a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts index 2ce82e1a06..5040cb692e 100644 --- a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts +++ b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts @@ -80,5 +80,6 @@ export const arkts2Rules: number[] = [ 316, 321, 330, - 331 + 331, + 332 ]; diff --git a/ets2panda/linter/test/interop/interop_import_js.js b/ets2panda/linter/test/interop/interop_import_js.js new file mode 100755 index 0000000000..cd3b2ad79c --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_js.js @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export let foo = {name: "123"} +export let person = {age: 12, male: [1, 2, 3]} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets b/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets new file mode 100755 index 0000000000..072c3453aa --- /dev/null +++ b/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +'use static' + +import {foo, person} from "./interop_import_js" + +foo.name +foo.name = "456" +person.age = 23 +person.male = [2, 3] \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.args.json b/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.args.json new file mode 100755 index 0000000000..a2c0f14eb2 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.arkts2.json b/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.arkts2.json new file mode 100755 index 0000000000..a276adba42 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.arkts2.json @@ -0,0 +1,68 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 48, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 9, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 17, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 16, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 1, + "endLine": 22, + "endColumn": 21, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.autofix.json b/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.autofix.json new file mode 100755 index 0000000000..553491bcdd --- /dev/null +++ b/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.autofix.json @@ -0,0 +1,96 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 48, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 9, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 667, + "end": 675, + "replacementText": "foo.getPropertyByName(\"name\")" + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 17, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 676, + "end": 692, + "replacementText": "foo.setPropertyByName(\"name\", ESObject.wrap(\"456\"))" + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 16, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 693, + "end": 708, + "replacementText": "person.setPropertyByName(\"age\", ESObject.wrap(23))" + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 1, + "endLine": 22, + "endColumn": 21, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 709, + "end": 729, + "replacementText": "person.setPropertyByName(\"male\", ESObject.wrap([2, 3]))" + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.json b/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.json new file mode 100755 index 0000000000..e5a73a02b4 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 48, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + } + ] +} \ No newline at end of file -- Gitee From 5fe1a9cf8aea8a23840a6b5349af82e222237f42 Mon Sep 17 00:00:00 2001 From: ZhongNing Date: Sat, 12 Apr 2025 18:27:51 +0800 Subject: [PATCH 078/268] Add checks for arkts-no-import-number-type Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBWJJS Test scenarios: new tests added to the linter Signed-off-by: ZhongNing --- ets2panda/linter/src/lib/CookBookMsg.ts | 1 + ets2panda/linter/src/lib/FaultAttrs.ts | 1 + ets2panda/linter/src/lib/FaultDesc.ts | 1 + ets2panda/linter/src/lib/Problems.ts | 1 + ets2panda/linter/src/lib/TypeScriptLinter.ts | 24 ++++++++++++ .../src/lib/utils/consts/ArkTS2Rules.ts | 3 +- .../src/lib/utils/consts/SendableAPI.ts | 1 + .../test/interop/interop_convert_import.ets | 19 ++++++++++ .../interop_convert_import.ets.args.json | 19 ++++++++++ .../interop_convert_import.ets.arkts2.json | 38 +++++++++++++++++++ .../interop/interop_convert_import.ets.json | 28 ++++++++++++++ .../test/interop/interop_convert_import_js.js | 16 ++++++++ 12 files changed, 151 insertions(+), 1 deletion(-) create mode 100755 ets2panda/linter/test/interop/interop_convert_import.ets create mode 100755 ets2panda/linter/test/interop/interop_convert_import.ets.args.json create mode 100755 ets2panda/linter/test/interop/interop_convert_import.ets.arkts2.json create mode 100755 ets2panda/linter/test/interop/interop_convert_import.ets.json create mode 100755 ets2panda/linter/test/interop/interop_convert_import_js.js diff --git a/ets2panda/linter/src/lib/CookBookMsg.ts b/ets2panda/linter/src/lib/CookBookMsg.ts index d864f5d0e9..a2de91dd9e 100644 --- a/ets2panda/linter/src/lib/CookBookMsg.ts +++ b/ets2panda/linter/src/lib/CookBookMsg.ts @@ -293,3 +293,4 @@ cookBookTag[321] = 'Import Concurrency is not required (arkts-limited-stdlib-no- cookBookTag[330] = 'Importing directly from "JS" module is not supported (arkts-no-js-import)'; cookBookTag[331] = 'ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)'; cookBookTag[332] = 'Properties of interop objects can\'t be accessed directly (arkts-no-js-obj-property)'; +cookBookTag[333] = 'Casting interop JS objects to "number" type is not allowed (arkts-no-js-number-cast)' diff --git a/ets2panda/linter/src/lib/FaultAttrs.ts b/ets2panda/linter/src/lib/FaultAttrs.ts index 6031b808fb..60806b8674 100644 --- a/ets2panda/linter/src/lib/FaultAttrs.ts +++ b/ets2panda/linter/src/lib/FaultAttrs.ts @@ -202,3 +202,4 @@ faultsAttrs[FaultID.LimitedStdLibNoImportConcurrency] = new FaultAttributes(321) faultsAttrs[FaultID.InterOpImportJs] = new FaultAttributes(330); faultsAttrs[FaultID.CallJSFunction] = new FaultAttributes(331); faultsAttrs[FaultID.InteropObjectProperty] = new FaultAttributes(332); +faultsAttrs[FaultID.InterOpConvertImport] = new FaultAttributes(333); diff --git a/ets2panda/linter/src/lib/FaultDesc.ts b/ets2panda/linter/src/lib/FaultDesc.ts index e5cdec5110..85e7d4841c 100644 --- a/ets2panda/linter/src/lib/FaultDesc.ts +++ b/ets2panda/linter/src/lib/FaultDesc.ts @@ -190,3 +190,4 @@ faultDesc[FaultID.LimitedStdLibNoImportConcurrency] = 'Import Concurrency Deprec faultDesc[FaultID.InterOpImportJs] = 'No JS import'; faultDesc[FaultID.CallJSFunction] = 'Call JS Function'; faultDesc[FaultID.InteropObjectProperty] = 'Interop property access'; +faultDesc[FaultID.InterOpConvertImport] = 'No import number from js file'; diff --git a/ets2panda/linter/src/lib/Problems.ts b/ets2panda/linter/src/lib/Problems.ts index df323bae43..ca654a5646 100644 --- a/ets2panda/linter/src/lib/Problems.ts +++ b/ets2panda/linter/src/lib/Problems.ts @@ -191,6 +191,7 @@ export enum FaultID { InterOpImportJs, CallJSFunction, InteropObjectProperty, + InterOpConvertImport, // this should always be last enum LAST_ID } diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index 5a98f7aadd..73a5041124 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -3788,6 +3788,30 @@ export class TypeScriptLinter { this.incrementCounters(node, FaultID.StructuralIdentity); } } + this.handleAsExpressionNumber(tsAsExpr); + } + + private handleAsExpressionNumber(tsAsExpr): void { + const type = tsAsExpr.type; + + if ( + this.useStatic && + this.options.arkts2 && + ts.isAsExpression(tsAsExpr) && + type.kind === ts.SyntaxKind.NumberKeyword + ) { + const expr = ts.isPropertyAccessExpression(tsAsExpr.expression) + ? tsAsExpr.expression.expression + : tsAsExpr.expression; + + if (ts.isIdentifier(expr)) { + const sym = this.tsUtils.trueSymbolAtLocation(expr); + const decl = TsUtils.getDeclaration(sym); + if (decl?.getSourceFile().fileName.endsWith(EXTNAME_JS)) { + this.incrementCounters(tsAsExpr, FaultID.InterOpConvertImport); + } + } + } } private handleSdkConstructorIface(typeRef: ts.TypeReferenceNode): void { diff --git a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts index 5040cb692e..2518331d58 100644 --- a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts +++ b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts @@ -81,5 +81,6 @@ export const arkts2Rules: number[] = [ 321, 330, 331, - 332 + 332, + 333 ]; diff --git a/ets2panda/linter/src/lib/utils/consts/SendableAPI.ts b/ets2panda/linter/src/lib/utils/consts/SendableAPI.ts index e6a6cdae37..ddeb2975fa 100644 --- a/ets2panda/linter/src/lib/utils/consts/SendableAPI.ts +++ b/ets2panda/linter/src/lib/utils/consts/SendableAPI.ts @@ -28,3 +28,4 @@ export const SENDABLE_CLOSURE_DECLS = [ts.SyntaxKind.ClassDeclaration, ts.Syntax export const SENDBALE_FUNCTION_START_VERSION = 12; export const SENDABLE_FUNCTION_UNSUPPORTED_STAGES_IN_API12 = ['beta1', 'beta2']; +export const ISINSTANCEOF = 'isInstanceOf'; diff --git a/ets2panda/linter/test/interop/interop_convert_import.ets b/ets2panda/linter/test/interop/interop_convert_import.ets new file mode 100755 index 0000000000..15717d92cc --- /dev/null +++ b/ets2panda/linter/test/interop/interop_convert_import.ets @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + 'use static' + + import {foo} from "./interop_convert_import_js.js" + + let a: number = foo.num as number \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_convert_import.ets.args.json b/ets2panda/linter/test/interop/interop_convert_import.ets.args.json new file mode 100755 index 0000000000..88d4f72683 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_convert_import.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_convert_import.ets.arkts2.json b/ets2panda/linter/test/interop/interop_convert_import.ets.arkts2.json new file mode 100755 index 0000000000..97ac686ac5 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_convert_import.ets.arkts2.json @@ -0,0 +1,38 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 2, + "endLine": 17, + "endColumn": 52, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 18, + "endLine": 19, + "endColumn": 35, + "problem": "InterOpConvertImport", + "suggest": "", + "rule": "Casting interop JS objects to \"number\" type is not allowed (arkts-no-js-number-cast)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_convert_import.ets.json b/ets2panda/linter/test/interop/interop_convert_import.ets.json new file mode 100755 index 0000000000..a543d16416 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_convert_import.ets.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 2, + "endLine": 17, + "endColumn": 52, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_convert_import_js.js b/ets2panda/linter/test/interop/interop_convert_import_js.js new file mode 100755 index 0000000000..16cbaf6cf8 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_convert_import_js.js @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export let foo = {name: 123} \ No newline at end of file -- Gitee From 0b9b9b90e576ede8f759f44a768de4ab77c2d6e9 Mon Sep 17 00:00:00 2001 From: ZhongNing Date: Mon, 7 Apr 2025 15:45:37 +0800 Subject: [PATCH 079/268] [InterOp] ArkTS1.2 import js for typeof Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBW6QR Test scenarios:new tests add to the linter Signed-off-by: ZhongNing --- ets2panda/linter/src/lib/CookBookMsg.ts | 3 +- ets2panda/linter/src/lib/FaultAttrs.ts | 1 + ets2panda/linter/src/lib/FaultDesc.ts | 1 + ets2panda/linter/src/lib/Problems.ts | 1 + ets2panda/linter/src/lib/TypeScriptLinter.ts | 85 +++- .../linter/src/lib/autofixes/Autofixer.ts | 35 ++ .../src/lib/utils/consts/ArkTS2Rules.ts | 3 +- .../test/interop/interop_import_js_js.js | 17 +- .../test/interop/interop_import_typeof_js.ets | 73 ++++ .../interop_import_typeof_js.ets.args.json | 20 + .../interop_import_typeof_js.ets.arkts2.json | 258 +++++++++++++ .../interop_import_typeof_js.ets.autofix.json | 363 ++++++++++++++++++ .../interop/interop_import_typeof_js.ets.json | 48 +++ 13 files changed, 903 insertions(+), 5 deletions(-) create mode 100755 ets2panda/linter/test/interop/interop_import_typeof_js.ets create mode 100755 ets2panda/linter/test/interop/interop_import_typeof_js.ets.args.json create mode 100755 ets2panda/linter/test/interop/interop_import_typeof_js.ets.arkts2.json create mode 100755 ets2panda/linter/test/interop/interop_import_typeof_js.ets.autofix.json create mode 100755 ets2panda/linter/test/interop/interop_import_typeof_js.ets.json diff --git a/ets2panda/linter/src/lib/CookBookMsg.ts b/ets2panda/linter/src/lib/CookBookMsg.ts index a2de91dd9e..e35eaa117b 100644 --- a/ets2panda/linter/src/lib/CookBookMsg.ts +++ b/ets2panda/linter/src/lib/CookBookMsg.ts @@ -16,7 +16,7 @@ export const cookBookMsg: string[] = []; export const cookBookTag: string[] = []; -for (let i = 0; i <= 319; i++) { +for (let i = 0; i <= 320; i++) { cookBookMsg[i] = ''; } @@ -294,3 +294,4 @@ cookBookTag[330] = 'Importing directly from "JS" module is not supported (arkts- cookBookTag[331] = 'ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)'; cookBookTag[332] = 'Properties of interop objects can\'t be accessed directly (arkts-no-js-obj-property)'; cookBookTag[333] = 'Casting interop JS objects to "number" type is not allowed (arkts-no-js-number-cast)' +cookBookTag[334] = 'The "typeof" expression can\'t be used with interop JS objects (arkts-interop-js-typeof)'; diff --git a/ets2panda/linter/src/lib/FaultAttrs.ts b/ets2panda/linter/src/lib/FaultAttrs.ts index 60806b8674..3dbfc7f62e 100644 --- a/ets2panda/linter/src/lib/FaultAttrs.ts +++ b/ets2panda/linter/src/lib/FaultAttrs.ts @@ -203,3 +203,4 @@ faultsAttrs[FaultID.InterOpImportJs] = new FaultAttributes(330); faultsAttrs[FaultID.CallJSFunction] = new FaultAttributes(331); faultsAttrs[FaultID.InteropObjectProperty] = new FaultAttributes(332); faultsAttrs[FaultID.InterOpConvertImport] = new FaultAttributes(333); +faultsAttrs[FaultID.InterOpImportJsForTypeOf] = new FaultAttributes(334); diff --git a/ets2panda/linter/src/lib/FaultDesc.ts b/ets2panda/linter/src/lib/FaultDesc.ts index 85e7d4841c..6cc0446939 100644 --- a/ets2panda/linter/src/lib/FaultDesc.ts +++ b/ets2panda/linter/src/lib/FaultDesc.ts @@ -191,3 +191,4 @@ faultDesc[FaultID.InterOpImportJs] = 'No JS import'; faultDesc[FaultID.CallJSFunction] = 'Call JS Function'; faultDesc[FaultID.InteropObjectProperty] = 'Interop property access'; faultDesc[FaultID.InterOpConvertImport] = 'No import number from js file'; +faultDesc[FaultID.InterOpImportJsForTypeOf] = 'TypeOf import from JS'; diff --git a/ets2panda/linter/src/lib/Problems.ts b/ets2panda/linter/src/lib/Problems.ts index ca654a5646..c052cdc0fd 100644 --- a/ets2panda/linter/src/lib/Problems.ts +++ b/ets2panda/linter/src/lib/Problems.ts @@ -192,6 +192,7 @@ export enum FaultID { CallJSFunction, InteropObjectProperty, InterOpConvertImport, + InterOpImportJsForTypeOf, // this should always be last enum LAST_ID } diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index 73a5041124..4a6513a0cc 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -290,7 +290,8 @@ export class TypeScriptLinter { [ts.SyntaxKind.NonNullExpression, this.handleNonNullExpression], [ts.SyntaxKind.HeritageClause, this.handleHeritageClause], [ts.SyntaxKind.TaggedTemplateExpression, this.handleTaggedTemplatesExpression], - [ts.SyntaxKind.StructDeclaration, this.handleStructDeclaration] + [ts.SyntaxKind.StructDeclaration, this.handleStructDeclaration], + [ts.SyntaxKind.TypeOfExpression, this.handleInterOpImportJsOnTypeOfNode] ]); private getLineAndCharacterOfNode(node: ts.Node | ts.CommentRange): ts.LineAndCharacter { @@ -5847,6 +5848,75 @@ export class TypeScriptLinter { } } + private getOriginalSymbol(node: ts.Node): ts.Symbol | undefined { + if (ts.isIdentifier(node)) { + const variableDeclaration = this.findVariableDeclaration(node); + if (variableDeclaration?.initializer) { + return this.getOriginalSymbol(variableDeclaration.initializer); + } + } else if (ts.isNewExpression(node)) { + const constructor = node.expression; + if (ts.isIdentifier(constructor)) { + return this.tsUtils.trueSymbolAtLocation(constructor); + } + } else if (ts.isCallExpression(node)) { + const callee = node.expression; + if (ts.isIdentifier(callee)) { + return this.tsUtils.trueSymbolAtLocation(callee); + } else if (ts.isPropertyAccessExpression(callee)) { + return this.getOriginalSymbol(callee.expression); + } + } else if (ts.isPropertyAccessExpression(node)) { + return this.getOriginalSymbol(node.expression); + } + return this.tsUtils.trueSymbolAtLocation(node); + } + + private static isFromJsImport(symbol: ts.Symbol): boolean { + const declaration = symbol.declarations?.[0]; + if (declaration) { + const sourceFile = declaration.getSourceFile(); + return sourceFile.fileName.endsWith(EXTNAME_JS); + } + return false; + } + + private hasLocalAssignment(node: ts.Node): boolean { + if (ts.isIdentifier(node)) { + const variableDeclaration = this.findVariableDeclaration(node); + return !!variableDeclaration?.initializer; + } + return false; + } + + private isLocalCall(node: ts.Node): boolean { + if (ts.isCallExpression(node)) { + const callee = node.expression; + if (ts.isIdentifier(callee)) { + return this.hasLocalAssignment(callee); + } else if (ts.isPropertyAccessExpression(callee)) { + const objectNode = callee.expression; + return this.hasLocalAssignment(objectNode); + } + } + return false; + } + + private handleInterOpImportJsOnTypeOfNode(typeofExpress: ts.TypeOfExpression): void { + if (!this.options.arkts2 || !typeofExpress || !this.useStatic) { + return; + } + const targetNode = typeofExpress.expression; + if (this.hasLocalAssignment(targetNode) || this.isLocalCall(targetNode)) { + return; + } + const targetSymbol = this.getOriginalSymbol(targetNode); + if (targetSymbol && TypeScriptLinter.isFromJsImport(targetSymbol)) { + const autofix = this.autofixer?.fixInterOpImportJsOnTypeOf(typeofExpress); + this.incrementCounters(typeofExpress, FaultID.InterOpImportJsForTypeOf, autofix); + } + } + private handleSdkTypeQuery(decl: ts.PropertyAccessExpression): void { if (!this.options.arkts2 || !ts.isPropertyAccessExpression(decl)) { return; @@ -6043,4 +6113,17 @@ export class TypeScriptLinter { } } } + + private findVariableDeclaration(identifier: ts.Identifier): ts.VariableDeclaration | undefined { + const sym = this.tsUtils.trueSymbolAtLocation(identifier); + const decl = TsUtils.getDeclaration(sym); + if ( + decl && + ts.isVariableDeclaration(decl) && + decl.getSourceFile().fileName === identifier.getSourceFile().fileName + ) { + return decl; + } + return undefined; + } } diff --git a/ets2panda/linter/src/lib/autofixes/Autofixer.ts b/ets2panda/linter/src/lib/autofixes/Autofixer.ts index 78d75dcd50..884c97e754 100644 --- a/ets2panda/linter/src/lib/autofixes/Autofixer.ts +++ b/ets2panda/linter/src/lib/autofixes/Autofixer.ts @@ -3200,6 +3200,32 @@ export class Autofixer { } return ''; } + + private static fixInterOpImportJsWrapArgs(args: ts.NodeArray): string { + return args. + map((arg) => { + return `ESObject.wrap(${arg.getText()})`; + }). + join(', '); + } + + private fixInterOpImportJsProcessNode(node: ts.Node): string { + if (ts.isIdentifier(node)) { + return node.text; + } else if (ts.isCallExpression(node)) { + const callee = this.fixInterOpImportJsProcessNode(node.expression); + const args = Autofixer.fixInterOpImportJsWrapArgs(node.arguments); + return `${callee}.invoke(${args})`; + } else if (ts.isPropertyAccessExpression(node)) { + const base = this.fixInterOpImportJsProcessNode(node.expression); + const propName = node.name.text; + return `${base}.getPropertyByName('${propName}')`; + } else if (ts.isNewExpression(node)) { + const constructor = this.fixInterOpImportJsProcessNode(node.expression); + return `${constructor}.instantiate()`; + } + return ''; + } fixInterOpImportJs( importDecl: ts.ImportDeclaration, @@ -3319,4 +3345,13 @@ export class Autofixer { const replacementText = this.printer.printNode(ts.EmitHint.Unspecified, statements, express.getSourceFile()); return [{ start: express.getStart(), end: express.getEnd(), replacementText: replacementText }]; } + + fixInterOpImportJsOnTypeOf(typeofExpress: ts.TypeOfExpression): Autofix[] | undefined { + const node = typeofExpress.expression; + const start = typeofExpress.getStart(); + const end = typeofExpress.getEnd(); + const processed = this.fixInterOpImportJsProcessNode(node); + const replacementText = `${processed}.typeOf()`; + return replacementText ? [{ start, end, replacementText }] : undefined; + } } diff --git a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts index 2518331d58..e47c092cb4 100644 --- a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts +++ b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts @@ -82,5 +82,6 @@ export const arkts2Rules: number[] = [ 330, 331, 332, - 333 + 333, + 334 ]; diff --git a/ets2panda/linter/test/interop/interop_import_js_js.js b/ets2panda/linter/test/interop/interop_import_js_js.js index b0bcaa8cba..37abf27ef6 100755 --- a/ets2panda/linter/test/interop/interop_import_js_js.js +++ b/ets2panda/linter/test/interop/interop_import_js_js.js @@ -17,5 +17,18 @@ export default function aaa() { return "Hello Default Export"; } export class ClassA {} -export function Dog(a){} -export let Wiki = {name: "123"} \ No newline at end of file +export function Dog(a) { } +export let Wiki = { name: "123" } +export class Person { + name = "" + age = 0 + location = "" + getName() { + return this.name; + } + setAge(age) { + this.age = age; + } +} + +export let aaa = 1 diff --git a/ets2panda/linter/test/interop/interop_import_typeof_js.ets b/ets2panda/linter/test/interop/interop_import_typeof_js.ets new file mode 100755 index 0000000000..eeb6eba253 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_typeof_js.ets @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use static' +import myAaa,{ClassA,Dog,Person,Wiki} from "./interop_import_js_js"; +import { Dog as Doge } from './interop_import_js_js'; +import { Wiki as wiki } from './interop_import_js_js'; + +typeof myAaa(); //error +let fun = myAaa(); +typeof fun; +typeof Dog; //error +typeof Dog('doge'); //error +typeof Doge('doge'); //error +typeof Wiki //error +typeof Wiki.name //error +typeof wiki //error +let val = wiki.name +typeof val; +const aClass:ClassA = new ClassA() +typeof new ClassA() //error +typeof aClass; +let person:Person = new Person(); +let name =person.name +let name2 =person.getName() +function getPersonInfo(){ + typeof person; + typeof person.getName(); + typeof name2; + typeof name; + typeof person.setAge(111); + typeof person; + typeof new Person(); //error +} + +const age = typeof person.setAge(111); +let person2 = typeof person +class Object { + code: string = "www" + location: string = typeof ('123') + getLocation(){ + console.log(`nameType=${ typeof code} `); + return typeof this.location; + } + setLocation(location: string){ + this.location = location; + typeof location; + } + tips(){ + typeof wiki.name; //error + typeof age; + typeof person2; + typeof fun; + console.log(`ClassA=${ typeof new ClassA()} `); //error + } +} + +typeof myAaa; //error +typeof new Person().name //error +typeof new Person().getName() //error +typeof new Person().setAge(22) //error diff --git a/ets2panda/linter/test/interop/interop_import_typeof_js.ets.args.json b/ets2panda/linter/test/interop/interop_import_typeof_js.ets.args.json new file mode 100755 index 0000000000..815373beb6 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_typeof_js.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_import_typeof_js.ets.arkts2.json b/ets2panda/linter/test/interop/interop_import_typeof_js.ets.arkts2.json new file mode 100755 index 0000000000..549a79b5f4 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_typeof_js.ets.arkts2.json @@ -0,0 +1,258 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 69, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 54, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 55, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 15, + "problem": "InterOpImportJsForTypeOf", + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 1, + "endLine": 24, + "endColumn": 11, + "problem": "InterOpImportJsForTypeOf", + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 1, + "endLine": 25, + "endColumn": 19, + "problem": "InterOpImportJsForTypeOf", + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 8, + "endLine": 25, + "endColumn": 19, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 1, + "endLine": 26, + "endColumn": 20, + "problem": "InterOpImportJsForTypeOf", + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 8, + "endLine": 26, + "endColumn": 20, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 1, + "endLine": 27, + "endColumn": 12, + "problem": "InterOpImportJsForTypeOf", + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 1, + "endLine": 28, + "endColumn": 17, + "problem": "InterOpImportJsForTypeOf", + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 1, + "endLine": 29, + "endColumn": 12, + "problem": "InterOpImportJsForTypeOf", + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 1, + "endLine": 33, + "endColumn": 20, + "problem": "InterOpImportJsForTypeOf", + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "severity": "ERROR" + }, + { + "line": 43, + "column": 12, + "endLine": 43, + "endColumn": 30, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 5, + "endLine": 45, + "endColumn": 24, + "problem": "InterOpImportJsForTypeOf", + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "severity": "ERROR" + }, + { + "line": 48, + "column": 21, + "endLine": 48, + "endColumn": 39, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 50, + "column": 7, + "endLine": 50, + "endColumn": 13, + "problem": "InvalidIdentifier", + "suggest": "", + "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", + "severity": "ERROR" + }, + { + "line": 62, + "column": 5, + "endLine": 62, + "endColumn": 21, + "problem": "InterOpImportJsForTypeOf", + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "severity": "ERROR" + }, + { + "line": 66, + "column": 28, + "endLine": 66, + "endColumn": 47, + "problem": "InterOpImportJsForTypeOf", + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "severity": "ERROR" + }, + { + "line": 70, + "column": 1, + "endLine": 70, + "endColumn": 13, + "problem": "InterOpImportJsForTypeOf", + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 1, + "endLine": 71, + "endColumn": 25, + "problem": "InterOpImportJsForTypeOf", + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 1, + "endLine": 72, + "endColumn": 30, + "problem": "InterOpImportJsForTypeOf", + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 1, + "endLine": 73, + "endColumn": 31, + "problem": "InterOpImportJsForTypeOf", + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 8, + "endLine": 73, + "endColumn": 31, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_import_typeof_js.ets.autofix.json b/ets2panda/linter/test/interop/interop_import_typeof_js.ets.autofix.json new file mode 100755 index 0000000000..c786032f72 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_typeof_js.ets.autofix.json @@ -0,0 +1,363 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 69, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 54, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 55, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 15, + "problem": "InterOpImportJsForTypeOf", + "autofix": [ + { + "start": 798, + "end": 812, + "replacementText": "myAaa.invoke().typeOf()" + } + ], + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 1, + "endLine": 24, + "endColumn": 11, + "problem": "InterOpImportJsForTypeOf", + "autofix": [ + { + "start": 853, + "end": 863, + "replacementText": "Dog.typeOf()" + } + ], + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 1, + "endLine": 25, + "endColumn": 19, + "problem": "InterOpImportJsForTypeOf", + "autofix": [ + { + "start": 873, + "end": 891, + "replacementText": "Dog.invoke(ESObject.wrap('doge')).typeOf()" + } + ], + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 8, + "endLine": 25, + "endColumn": 19, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 1, + "endLine": 26, + "endColumn": 20, + "problem": "InterOpImportJsForTypeOf", + "autofix": [ + { + "start": 901, + "end": 920, + "replacementText": "Doge.invoke(ESObject.wrap('doge')).typeOf()" + } + ], + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 8, + "endLine": 26, + "endColumn": 20, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 1, + "endLine": 27, + "endColumn": 12, + "problem": "InterOpImportJsForTypeOf", + "autofix": [ + { + "start": 930, + "end": 941, + "replacementText": "Wiki.typeOf()" + } + ], + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 1, + "endLine": 28, + "endColumn": 17, + "problem": "InterOpImportJsForTypeOf", + "autofix": [ + { + "start": 950, + "end": 966, + "replacementText": "Wiki.getPropertyByName('name').typeOf()" + } + ], + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 1, + "endLine": 29, + "endColumn": 12, + "problem": "InterOpImportJsForTypeOf", + "autofix": [ + { + "start": 975, + "end": 986, + "replacementText": "wiki.typeOf()" + } + ], + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 1, + "endLine": 33, + "endColumn": 20, + "problem": "InterOpImportJsForTypeOf", + "autofix": [ + { + "start": 1062, + "end": 1081, + "replacementText": "ClassA.instantiate().typeOf()" + } + ], + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "severity": "ERROR" + }, + { + "line": 43, + "column": 12, + "endLine": 43, + "endColumn": 30, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 5, + "endLine": 45, + "endColumn": 24, + "problem": "InterOpImportJsForTypeOf", + "autofix": [ + { + "start": 1352, + "end": 1371, + "replacementText": "Person.instantiate().typeOf()" + } + ], + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "severity": "ERROR" + }, + { + "line": 48, + "column": 21, + "endLine": 48, + "endColumn": 39, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 50, + "column": 7, + "endLine": 50, + "endColumn": 13, + "problem": "InvalidIdentifier", + "suggest": "", + "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", + "severity": "ERROR" + }, + { + "line": 62, + "column": 5, + "endLine": 62, + "endColumn": 21, + "problem": "InterOpImportJsForTypeOf", + "autofix": [ + { + "start": 1729, + "end": 1745, + "replacementText": "wiki.getPropertyByName('name').typeOf()" + } + ], + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "severity": "ERROR" + }, + { + "line": 66, + "column": 28, + "endLine": 66, + "endColumn": 47, + "problem": "InterOpImportJsForTypeOf", + "autofix": [ + { + "start": 1834, + "end": 1853, + "replacementText": "ClassA.instantiate().typeOf()" + } + ], + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "severity": "ERROR" + }, + { + "line": 70, + "column": 1, + "endLine": 70, + "endColumn": 13, + "problem": "InterOpImportJsForTypeOf", + "autofix": [ + { + "start": 1874, + "end": 1886, + "replacementText": "myAaa.typeOf()" + } + ], + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 1, + "endLine": 71, + "endColumn": 25, + "problem": "InterOpImportJsForTypeOf", + "autofix": [ + { + "start": 1896, + "end": 1920, + "replacementText": "Person.instantiate().getPropertyByName('name').typeOf()" + } + ], + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 1, + "endLine": 72, + "endColumn": 30, + "problem": "InterOpImportJsForTypeOf", + "autofix": [ + { + "start": 1930, + "end": 1959, + "replacementText": "Person.instantiate().getPropertyByName('getName').invoke().typeOf()" + } + ], + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 1, + "endLine": 73, + "endColumn": 31, + "problem": "InterOpImportJsForTypeOf", + "autofix": [ + { + "start": 1968, + "end": 1998, + "replacementText": "Person.instantiate().getPropertyByName('setAge').invoke(ESObject.wrap(22)).typeOf()" + } + ], + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 8, + "endLine": 73, + "endColumn": 31, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_import_typeof_js.ets.json b/ets2panda/linter/test/interop/interop_import_typeof_js.ets.json new file mode 100755 index 0000000000..b61974a218 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_typeof_js.ets.json @@ -0,0 +1,48 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 69, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 54, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 55, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + } + ] +} \ No newline at end of file -- Gitee From f0845e40c949ea559693d449188eb9eac76c5ed7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=92=9F=E6=9F=A0?= Date: Mon, 7 Apr 2025 17:26:04 +0800 Subject: [PATCH 080/268] Add arkts-interop-does-not-have-num MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBWGAB Test scenarios: new tests added to the linter Signed-off-by: 钟柠 --- ets2panda/linter/src/lib/CookBookMsg.ts | 1 + ets2panda/linter/src/lib/FaultAttrs.ts | 1 + ets2panda/linter/src/lib/FaultDesc.ts | 1 + ets2panda/linter/src/lib/Problems.ts | 1 + ets2panda/linter/src/lib/TypeScriptLinter.ts | 31 ++++++ .../linter/src/lib/autofixes/Autofixer.ts | 23 +++++ .../src/lib/utils/consts/ArkTS2Rules.ts | 3 +- .../interop_not_have_property_num_arkts2.ets | 22 +++++ ...not_have_property_num_arkts2.ets.args.json | 20 ++++ ...t_have_property_num_arkts2.ets.arkts2.json | 68 +++++++++++++ ..._have_property_num_arkts2.ets.autofix.json | 96 +++++++++++++++++++ ...erop_not_have_property_num_arkts2.ets.json | 28 ++++++ .../test/interop/interop_property_num_js.js | 16 ++++ 13 files changed, 310 insertions(+), 1 deletion(-) create mode 100755 ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets create mode 100755 ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.args.json create mode 100755 ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.arkts2.json create mode 100755 ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.autofix.json create mode 100755 ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.json create mode 100755 ets2panda/linter/test/interop/interop_property_num_js.js diff --git a/ets2panda/linter/src/lib/CookBookMsg.ts b/ets2panda/linter/src/lib/CookBookMsg.ts index e35eaa117b..04dae42bc0 100644 --- a/ets2panda/linter/src/lib/CookBookMsg.ts +++ b/ets2panda/linter/src/lib/CookBookMsg.ts @@ -295,3 +295,4 @@ cookBookTag[331] = 'ArkTS directly call JS functions or parameters is not suppor cookBookTag[332] = 'Properties of interop objects can\'t be accessed directly (arkts-no-js-obj-property)'; cookBookTag[333] = 'Casting interop JS objects to "number" type is not allowed (arkts-no-js-number-cast)' cookBookTag[334] = 'The "typeof" expression can\'t be used with interop JS objects (arkts-interop-js-typeof)'; +cookBookTag[335] = 'Interop object does not have property num (arkts-interop-does-not-have-num)'; diff --git a/ets2panda/linter/src/lib/FaultAttrs.ts b/ets2panda/linter/src/lib/FaultAttrs.ts index 3dbfc7f62e..0b00286554 100644 --- a/ets2panda/linter/src/lib/FaultAttrs.ts +++ b/ets2panda/linter/src/lib/FaultAttrs.ts @@ -204,3 +204,4 @@ faultsAttrs[FaultID.CallJSFunction] = new FaultAttributes(331); faultsAttrs[FaultID.InteropObjectProperty] = new FaultAttributes(332); faultsAttrs[FaultID.InterOpConvertImport] = new FaultAttributes(333); faultsAttrs[FaultID.InterOpImportJsForTypeOf] = new FaultAttributes(334); +faultsAttrs[FaultID.InteropNoHaveNum] = new FaultAttributes(335); diff --git a/ets2panda/linter/src/lib/FaultDesc.ts b/ets2panda/linter/src/lib/FaultDesc.ts index 6cc0446939..b7b72cfb50 100644 --- a/ets2panda/linter/src/lib/FaultDesc.ts +++ b/ets2panda/linter/src/lib/FaultDesc.ts @@ -192,3 +192,4 @@ faultDesc[FaultID.CallJSFunction] = 'Call JS Function'; faultDesc[FaultID.InteropObjectProperty] = 'Interop property access'; faultDesc[FaultID.InterOpConvertImport] = 'No import number from js file'; faultDesc[FaultID.InterOpImportJsForTypeOf] = 'TypeOf import from JS'; +faultDesc[FaultID.InteropNoHaveNum] = 'Interop obj with "num" property'; diff --git a/ets2panda/linter/src/lib/Problems.ts b/ets2panda/linter/src/lib/Problems.ts index c052cdc0fd..fa05e3782f 100644 --- a/ets2panda/linter/src/lib/Problems.ts +++ b/ets2panda/linter/src/lib/Problems.ts @@ -193,6 +193,7 @@ export enum FaultID { InteropObjectProperty, InterOpConvertImport, InterOpImportJsForTypeOf, + InteropNoHaveNum, // this should always be last enum LAST_ID } diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index 4a6513a0cc..77cae06675 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -1539,8 +1539,39 @@ export class TypeScriptLinter { return isNumberLike || isAllowedNumericType; } + private handleInteropOperand(tsUnaryArithm: ts.PrefixUnaryExpression): void { + if (ts.isPropertyAccessExpression(tsUnaryArithm.operand)) { + const exprSym = this.tsUtils.trueSymbolAtLocation(tsUnaryArithm.operand); + const declaration = exprSym?.declarations?.[0]; + this.checkAndProcessDeclaration(declaration, tsUnaryArithm); + } + } + + private checkAndProcessDeclaration( + declaration: ts.Declaration | undefined, + tsUnaryArithm: ts.PrefixUnaryExpression + ): void { + if (declaration?.getSourceFile().fileName.endsWith(EXTNAME_JS)) { + if ( + [ + ts.SyntaxKind.PlusToken, + ts.SyntaxKind.ExclamationToken, + ts.SyntaxKind.TildeToken, + ts.SyntaxKind.MinusToken + ].includes(tsUnaryArithm.operator) + ) { + const autofix = this.autofixer?.fixInteropInterfaceConvertNum(tsUnaryArithm); + this.incrementCounters(tsUnaryArithm, FaultID.InteropNoHaveNum, autofix); + } + } + } + private handlePrefixUnaryExpression(node: ts.Node): void { const tsUnaryArithm = node as ts.PrefixUnaryExpression; + if (this.useStatic && this.options.arkts2) { + const tsUnaryArithm = node as ts.PrefixUnaryExpression; + this.handleInteropOperand(tsUnaryArithm); + } const tsUnaryOp = tsUnaryArithm.operator; const tsUnaryOperand = tsUnaryArithm.operand; if ( diff --git a/ets2panda/linter/src/lib/autofixes/Autofixer.ts b/ets2panda/linter/src/lib/autofixes/Autofixer.ts index 884c97e754..0e0b3ccec2 100644 --- a/ets2panda/linter/src/lib/autofixes/Autofixer.ts +++ b/ets2panda/linter/src/lib/autofixes/Autofixer.ts @@ -3354,4 +3354,27 @@ export class Autofixer { const replacementText = `${processed}.typeOf()`; return replacementText ? [{ start, end, replacementText }] : undefined; } + + fixInteropInterfaceConvertNum(express: ts.PrefixUnaryExpression): Autofix[] | undefined { + let text = ''; + if (ts.isPropertyAccessExpression(express.operand)) { + const states = ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression( + ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression( + ts.factory.createIdentifier(express.operand.expression.getText()), + ts.factory.createIdentifier('getPropertyByName') + ), + undefined, + [ts.factory.createStringLiteral(express.operand.name.getText())] + ), + ts.factory.createIdentifier('toNumber') + ), + undefined, + [] + ); + text = this.printer.printNode(ts.EmitHint.Unspecified, states, express.getSourceFile()); + } + return [{ start: express.operand.getStart(), end: express.operand.getEnd(), replacementText: text }]; + } } diff --git a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts index e47c092cb4..aa7fe485cf 100644 --- a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts +++ b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts @@ -83,5 +83,6 @@ export const arkts2Rules: number[] = [ 331, 332, 333, - 334 + 334, + 335 ]; diff --git a/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets b/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets new file mode 100755 index 0000000000..319ea1ded3 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +'use static' + +import {foo} from "./interop_property_num_js" + ++foo.num; +-foo.num; +!foo.num; +~foo.num; \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.args.json b/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.args.json new file mode 100755 index 0000000000..a2c0f14eb2 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.arkts2.json b/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.arkts2.json new file mode 100755 index 0000000000..3f20f3b88d --- /dev/null +++ b/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.arkts2.json @@ -0,0 +1,68 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 46, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 9, + "problem": "InteropNoHaveNum", + "suggest": "", + "rule": "Interop object does not have property num (arkts-interop-does-not-have-num)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 9, + "problem": "InteropNoHaveNum", + "suggest": "", + "rule": "Interop object does not have property num (arkts-interop-does-not-have-num)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 9, + "problem": "InteropNoHaveNum", + "suggest": "", + "rule": "Interop object does not have property num (arkts-interop-does-not-have-num)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 1, + "endLine": 22, + "endColumn": 9, + "problem": "InteropNoHaveNum", + "suggest": "", + "rule": "Interop object does not have property num (arkts-interop-does-not-have-num)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.autofix.json b/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.autofix.json new file mode 100755 index 0000000000..a01a54b243 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.autofix.json @@ -0,0 +1,96 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 46, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 9, + "problem": "InteropNoHaveNum", + "autofix": [ + { + "start": 666, + "end": 673, + "replacementText": "foo.getPropertyByName(\"num\").toNumber()" + } + ], + "suggest": "", + "rule": "Interop object does not have property num (arkts-interop-does-not-have-num)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 9, + "problem": "InteropNoHaveNum", + "autofix": [ + { + "start": 676, + "end": 683, + "replacementText": "foo.getPropertyByName(\"num\").toNumber()" + } + ], + "suggest": "", + "rule": "Interop object does not have property num (arkts-interop-does-not-have-num)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 9, + "problem": "InteropNoHaveNum", + "autofix": [ + { + "start": 686, + "end": 693, + "replacementText": "foo.getPropertyByName(\"num\").toNumber()" + } + ], + "suggest": "", + "rule": "Interop object does not have property num (arkts-interop-does-not-have-num)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 1, + "endLine": 22, + "endColumn": 9, + "problem": "InteropNoHaveNum", + "autofix": [ + { + "start": 696, + "end": 703, + "replacementText": "foo.getPropertyByName(\"num\").toNumber()" + } + ], + "suggest": "", + "rule": "Interop object does not have property num (arkts-interop-does-not-have-num)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.json b/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.json new file mode 100755 index 0000000000..72da46b9de --- /dev/null +++ b/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 46, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_property_num_js.js b/ets2panda/linter/test/interop/interop_property_num_js.js new file mode 100755 index 0000000000..a248e1f84b --- /dev/null +++ b/ets2panda/linter/test/interop/interop_property_num_js.js @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export let foo = {num: 0} \ No newline at end of file -- Gitee From aff329fb511e62a28b0421dea154e7a1067e43fb Mon Sep 17 00:00:00 2001 From: ZhongNing Date: Wed, 9 Apr 2025 14:25:15 +0800 Subject: [PATCH 081/268] Add ArkTS1.2 Binary operations on js objects Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBZPH1 Test scenarios: new tests added to the linter Signed-off-by: ZhongNing --- ets2panda/linter/src/lib/CookBookMsg.ts | 1 + ets2panda/linter/src/lib/FaultAttrs.ts | 1 + ets2panda/linter/src/lib/FaultDesc.ts | 1 + ets2panda/linter/src/lib/Problems.ts | 1 + ets2panda/linter/src/lib/TypeScriptLinter.ts | 18 +++++ ets2panda/linter/src/lib/utils/TsUtils.ts | 2 +- .../src/lib/utils/consts/ArkTS2Rules.ts | 3 +- .../linter/src/lib/utils/consts/TsSuffix.ts | 2 + .../test/interop/binary_operation_js_obj.ets | 24 ++++++ .../binary_operation_js_obj.ets.args.json | 19 +++++ .../binary_operation_js_obj.ets.arkts2.json | 78 +++++++++++++++++++ .../binary_operation_js_obj.ets.autofix.json | 18 +++++ .../interop/binary_operation_js_obj.ets.json | 28 +++++++ .../interop/binary_operation_js_obj_js.js | 16 ++++ 14 files changed, 210 insertions(+), 2 deletions(-) create mode 100755 ets2panda/linter/test/interop/binary_operation_js_obj.ets create mode 100755 ets2panda/linter/test/interop/binary_operation_js_obj.ets.args.json create mode 100755 ets2panda/linter/test/interop/binary_operation_js_obj.ets.arkts2.json create mode 100755 ets2panda/linter/test/interop/binary_operation_js_obj.ets.autofix.json create mode 100755 ets2panda/linter/test/interop/binary_operation_js_obj.ets.json create mode 100755 ets2panda/linter/test/interop/binary_operation_js_obj_js.js diff --git a/ets2panda/linter/src/lib/CookBookMsg.ts b/ets2panda/linter/src/lib/CookBookMsg.ts index 04dae42bc0..c980a702a7 100644 --- a/ets2panda/linter/src/lib/CookBookMsg.ts +++ b/ets2panda/linter/src/lib/CookBookMsg.ts @@ -296,3 +296,4 @@ cookBookTag[332] = 'Properties of interop objects can\'t be accessed directly (a cookBookTag[333] = 'Casting interop JS objects to "number" type is not allowed (arkts-no-js-number-cast)' cookBookTag[334] = 'The "typeof" expression can\'t be used with interop JS objects (arkts-interop-js-typeof)'; cookBookTag[335] = 'Interop object does not have property num (arkts-interop-does-not-have-num)'; +cookBookTag[336] = 'Binary operations on js objects (arkts-no-js-obj-binary-operation)'; diff --git a/ets2panda/linter/src/lib/FaultAttrs.ts b/ets2panda/linter/src/lib/FaultAttrs.ts index 0b00286554..c4fe5c4269 100644 --- a/ets2panda/linter/src/lib/FaultAttrs.ts +++ b/ets2panda/linter/src/lib/FaultAttrs.ts @@ -205,3 +205,4 @@ faultsAttrs[FaultID.InteropObjectProperty] = new FaultAttributes(332); faultsAttrs[FaultID.InterOpConvertImport] = new FaultAttributes(333); faultsAttrs[FaultID.InterOpImportJsForTypeOf] = new FaultAttributes(334); faultsAttrs[FaultID.InteropNoHaveNum] = new FaultAttributes(335); +faultsAttrs[FaultID.BinaryOperations] = new FaultAttributes(336); diff --git a/ets2panda/linter/src/lib/FaultDesc.ts b/ets2panda/linter/src/lib/FaultDesc.ts index b7b72cfb50..c35facc216 100644 --- a/ets2panda/linter/src/lib/FaultDesc.ts +++ b/ets2panda/linter/src/lib/FaultDesc.ts @@ -193,3 +193,4 @@ faultDesc[FaultID.InteropObjectProperty] = 'Interop property access'; faultDesc[FaultID.InterOpConvertImport] = 'No import number from js file'; faultDesc[FaultID.InterOpImportJsForTypeOf] = 'TypeOf import from JS'; faultDesc[FaultID.InteropNoHaveNum] = 'Interop obj with "num" property'; +faultDesc[FaultID.BinaryOperations] = 'Binary operations on js objects'; diff --git a/ets2panda/linter/src/lib/Problems.ts b/ets2panda/linter/src/lib/Problems.ts index fa05e3782f..1d86277fcd 100644 --- a/ets2panda/linter/src/lib/Problems.ts +++ b/ets2panda/linter/src/lib/Problems.ts @@ -194,6 +194,7 @@ export enum FaultID { InterOpConvertImport, InterOpImportJsForTypeOf, InteropNoHaveNum, + BinaryOperations, // this should always be last enum LAST_ID } diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index 77cae06675..32bd5f1c94 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -132,6 +132,7 @@ export class TypeScriptLinter { private sourceFile?: ts.SourceFile; private useStatic?: boolean; + private readonly compatibleSdkVersion: number; private readonly compatibleSdkVersionStage: string; private static sharedModulesCache: Map; @@ -970,6 +971,7 @@ export class TypeScriptLinter { this.checkFunctionProperty(propertyAccessNode, baseExprSym, baseExprType); this.handleSdkForConstructorFuncs(propertyAccessNode); this.fixJsImportPropertyAccessExpression(node); + this.handleArkTSPropertyAccess(propertyAccessNode); } propertyAccessExpressionForInterop( @@ -5775,6 +5777,13 @@ export class TypeScriptLinter { } } } + private handleArkTSPropertyAccess(node: ts.PropertyAccessExpression): void { + if (this.useStatic && this.options.arkts2) { + if (this.isFromJSModule(node.expression)) { + this.incrementCounters(node, FaultID.BinaryOperations); + } + } + } private handleQuotedHyphenPropsDeprecated(typeRef: ts.TypeReferenceNode): void { if (!this.options.arkts2 || !ts.isQualifiedName(typeRef.typeName)) { @@ -6157,4 +6166,13 @@ export class TypeScriptLinter { } return undefined; } + + private isFromJSModule(node: ts.Node): boolean { + const symbol = this.tsUtils.trueSymbolAtLocation(node); + if (symbol?.declarations?.[0]) { + const sourceFile = symbol.declarations[0].getSourceFile(); + return sourceFile.fileName.endsWith(EXTNAME_JS); + } + return false; + } } diff --git a/ets2panda/linter/src/lib/utils/TsUtils.ts b/ets2panda/linter/src/lib/utils/TsUtils.ts index d2a6a7a450..349d82fc76 100644 --- a/ets2panda/linter/src/lib/utils/TsUtils.ts +++ b/ets2panda/linter/src/lib/utils/TsUtils.ts @@ -3491,7 +3491,7 @@ export class TsUtils { return undefined; } - + static isArkts12File(sourceFile: ts.SourceFile): boolean { if (!sourceFile) { return false; diff --git a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts index aa7fe485cf..9e44118bf4 100644 --- a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts +++ b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts @@ -84,5 +84,6 @@ export const arkts2Rules: number[] = [ 332, 333, 334, - 335 + 335, + 336 ]; diff --git a/ets2panda/linter/src/lib/utils/consts/TsSuffix.ts b/ets2panda/linter/src/lib/utils/consts/TsSuffix.ts index f2eff5a93a..de424368df 100644 --- a/ets2panda/linter/src/lib/utils/consts/TsSuffix.ts +++ b/ets2panda/linter/src/lib/utils/consts/TsSuffix.ts @@ -17,3 +17,5 @@ export const KIT = '@kit'; export const D_ETS = '.d.ets'; export const D_TS = '.d.ts'; export const ETS = '.ets'; +export const JS = '.js'; +export const TS = '.ts'; diff --git a/ets2panda/linter/test/interop/binary_operation_js_obj.ets b/ets2panda/linter/test/interop/binary_operation_js_obj.ets new file mode 100755 index 0000000000..29bfa417e5 --- /dev/null +++ b/ets2panda/linter/test/interop/binary_operation_js_obj.ets @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +'use static' +import {foo} from "./binary_operation_js_obj_js" +let a = foo.a +let b = foo.b +a + b +a - b +a * b +a / b +a % b +a ** b \ No newline at end of file diff --git a/ets2panda/linter/test/interop/binary_operation_js_obj.ets.args.json b/ets2panda/linter/test/interop/binary_operation_js_obj.ets.args.json new file mode 100755 index 0000000000..64b4d19108 --- /dev/null +++ b/ets2panda/linter/test/interop/binary_operation_js_obj.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} diff --git a/ets2panda/linter/test/interop/binary_operation_js_obj.ets.arkts2.json b/ets2panda/linter/test/interop/binary_operation_js_obj.ets.arkts2.json new file mode 100755 index 0000000000..1261b93913 --- /dev/null +++ b/ets2panda/linter/test/interop/binary_operation_js_obj.ets.arkts2.json @@ -0,0 +1,78 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 49, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 5, + "endLine": 17, + "endColumn": 14, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 9, + "endLine": 17, + "endColumn": 14, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 5, + "endLine": 18, + "endColumn": 14, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 9, + "endLine": 18, + "endColumn": 14, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 3, + "endLine": 24, + "endColumn": 5, + "problem": "ExponentOp", + "suggest": "", + "rule": "exponent opartions \"**\" and \"**=\" are disabled (arkts-no-exponent-op)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/binary_operation_js_obj.ets.autofix.json b/ets2panda/linter/test/interop/binary_operation_js_obj.ets.autofix.json new file mode 100755 index 0000000000..895325b061 --- /dev/null +++ b/ets2panda/linter/test/interop/binary_operation_js_obj.ets.autofix.json @@ -0,0 +1,18 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/binary_operation_js_obj.ets.json b/ets2panda/linter/test/interop/binary_operation_js_obj.ets.json new file mode 100755 index 0000000000..24e48e6dcb --- /dev/null +++ b/ets2panda/linter/test/interop/binary_operation_js_obj.ets.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 49, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/binary_operation_js_obj_js.js b/ets2panda/linter/test/interop/binary_operation_js_obj_js.js new file mode 100755 index 0000000000..aaf9c1dd4e --- /dev/null +++ b/ets2panda/linter/test/interop/binary_operation_js_obj_js.js @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export let foo = {a: 1, b: 2} -- Gitee From 526ae24cd9792f1e3d11ea232ce79dc6b3633e64 Mon Sep 17 00:00:00 2001 From: zhongning Date: Tue, 1 Apr 2025 13:55:29 +0800 Subject: [PATCH 082/268] Add check for arkts-js-data-compare Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBXWAQ Test scenarios: new tests added to the linter Signed-off-by: zhongning --- ets2panda/linter/src/lib/CookBookMsg.ts | 2 + ets2panda/linter/src/lib/FaultAttrs.ts | 1 + ets2panda/linter/src/lib/FaultDesc.ts | 1 + ets2panda/linter/src/lib/Problems.ts | 1 + ets2panda/linter/src/lib/TypeScriptLinter.ts | 53 ++++ .../src/lib/utils/consts/ArkTS2Rules.ts | 3 +- .../interop/interop_import_js_compare.ets | 42 ++++ .../interop_import_js_compare.ets.args.json | 19 ++ .../interop_import_js_compare.ets.arkts2.json | 228 ++++++++++++++++++ .../interop_import_js_compare.ets.json | 38 +++ .../interop/interop_import_js_compare_js.js | 18 ++ 11 files changed, 405 insertions(+), 1 deletion(-) create mode 100644 ets2panda/linter/test/interop/interop_import_js_compare.ets create mode 100644 ets2panda/linter/test/interop/interop_import_js_compare.ets.args.json create mode 100644 ets2panda/linter/test/interop/interop_import_js_compare.ets.arkts2.json create mode 100644 ets2panda/linter/test/interop/interop_import_js_compare.ets.json create mode 100644 ets2panda/linter/test/interop/interop_import_js_compare_js.js diff --git a/ets2panda/linter/src/lib/CookBookMsg.ts b/ets2panda/linter/src/lib/CookBookMsg.ts index c980a702a7..8127611fe6 100644 --- a/ets2panda/linter/src/lib/CookBookMsg.ts +++ b/ets2panda/linter/src/lib/CookBookMsg.ts @@ -297,3 +297,5 @@ cookBookTag[333] = 'Casting interop JS objects to "number" type is not allowed ( cookBookTag[334] = 'The "typeof" expression can\'t be used with interop JS objects (arkts-interop-js-typeof)'; cookBookTag[335] = 'Interop object does not have property num (arkts-interop-does-not-have-num)'; cookBookTag[336] = 'Binary operations on js objects (arkts-no-js-obj-binary-operation)'; +cookBookTag[337] = + 'Importing data directly from the "JS" module for comparison is not supported (arkts-js-data-compare)'; diff --git a/ets2panda/linter/src/lib/FaultAttrs.ts b/ets2panda/linter/src/lib/FaultAttrs.ts index c4fe5c4269..2194250453 100644 --- a/ets2panda/linter/src/lib/FaultAttrs.ts +++ b/ets2panda/linter/src/lib/FaultAttrs.ts @@ -206,3 +206,4 @@ faultsAttrs[FaultID.InterOpConvertImport] = new FaultAttributes(333); faultsAttrs[FaultID.InterOpImportJsForTypeOf] = new FaultAttributes(334); faultsAttrs[FaultID.InteropNoHaveNum] = new FaultAttributes(335); faultsAttrs[FaultID.BinaryOperations] = new FaultAttributes(336); +faultsAttrs[FaultID.InterOpImportJsDataCompare] = new FaultAttributes(337); \ No newline at end of file diff --git a/ets2panda/linter/src/lib/FaultDesc.ts b/ets2panda/linter/src/lib/FaultDesc.ts index c35facc216..2b5bc5683c 100644 --- a/ets2panda/linter/src/lib/FaultDesc.ts +++ b/ets2panda/linter/src/lib/FaultDesc.ts @@ -194,3 +194,4 @@ faultDesc[FaultID.InterOpConvertImport] = 'No import number from js file'; faultDesc[FaultID.InterOpImportJsForTypeOf] = 'TypeOf import from JS'; faultDesc[FaultID.InteropNoHaveNum] = 'Interop obj with "num" property'; faultDesc[FaultID.BinaryOperations] = 'Binary operations on js objects'; +faultDesc[FaultID.InterOpImportJsDataCompare] = 'NO js import data compare'; diff --git a/ets2panda/linter/src/lib/Problems.ts b/ets2panda/linter/src/lib/Problems.ts index 1d86277fcd..f6b422fd55 100644 --- a/ets2panda/linter/src/lib/Problems.ts +++ b/ets2panda/linter/src/lib/Problems.ts @@ -195,6 +195,7 @@ export enum FaultID { InterOpImportJsForTypeOf, InteropNoHaveNum, BinaryOperations, + InterOpImportJsDataCompare, // this should always be last enum LAST_ID } diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index 32bd5f1c94..e7609ba189 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -1622,6 +1622,59 @@ export class TypeScriptLinter { default: } this.checkNumericSemantics(tsBinaryExpr); + this.checkInterOpImportJsDataCompare(tsBinaryExpr); + } + + private checkInterOpImportJsDataCompare(expr: ts.BinaryExpression): void { + if (!this.useStatic || !this.options.arkts2 || !TypeScriptLinter.isComparisonOperator(expr.operatorToken.kind)) { + return; + } + + const isJsFileSymbol = (symbol: ts.Symbol | undefined): boolean => { + if (!symbol) { + return false; + } + + const declaration = symbol.declarations?.[0]; + if (!declaration || !ts.isVariableDeclaration(declaration)) { + return false; + } + + const initializer = declaration.initializer; + if (!initializer) { + return false; + } + + return isJsFileExpression(initializer); + }; + + const isJsFileExpression = (expr: ts.Expression): boolean => { + if (ts.isPropertyAccessExpression(expr)) { + const initializerSym = this.tsUtils.trueSymbolAtLocation(expr.expression); + return initializerSym?.declarations?.[0]?.getSourceFile()?.fileName.endsWith(EXTNAME_JS) ?? false; + } + return expr.getSourceFile()?.fileName.endsWith(EXTNAME_JS) ?? false; + }; + + const processExpression = (expr: ts.Expression): void => { + const symbol = this.tsUtils.trueSymbolAtLocation(expr); + if (isJsFileSymbol(symbol)) { + this.incrementCounters(expr, FaultID.InterOpImportJsDataCompare); + } + }; + + processExpression(expr.left); + processExpression(expr.right); + } + + private static isComparisonOperator(kind: ts.SyntaxKind): boolean { + return [ + ts.SyntaxKind.GreaterThanToken, + ts.SyntaxKind.LessThanToken, + ts.SyntaxKind.GreaterThanEqualsToken, + ts.SyntaxKind.LessThanEqualsToken, + ts.SyntaxKind.EqualsToken + ].includes(kind); } private handleTsInterop(nodeToCheck: ts.Node, handler: { (): void }): void { diff --git a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts index 9e44118bf4..acc19c2771 100644 --- a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts +++ b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts @@ -85,5 +85,6 @@ export const arkts2Rules: number[] = [ 333, 334, 335, - 336 + 336, + 337 ]; diff --git a/ets2panda/linter/test/interop/interop_import_js_compare.ets b/ets2panda/linter/test/interop/interop_import_js_compare.ets new file mode 100644 index 0000000000..7b719e70d0 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_js_compare.ets @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use static' + +import {foo, m, n} from "./interop_import_js_compare_js" +let a = foo.a +let b = foo.b +a > b +a < b +a >= b +a <= b +a = 1 + +m > n +m = 1 + +let x = 1, y = 2; +x > y; +x < y; +x >= y; +x <= y; + +let bar = { a: 1, b: 2 }; + +let x2 = bar.a, y2 = bar.b; +x2 > y2; +x2 < y2; +x2 >= y2; +x2 <= y2; \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_import_js_compare.ets.args.json b/ets2panda/linter/test/interop/interop_import_js_compare.ets.args.json new file mode 100644 index 0000000000..e2b903f0aa --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_js_compare.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } + } \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_import_js_compare.ets.arkts2.json b/ets2panda/linter/test/interop/interop_import_js_compare.ets.arkts2.json new file mode 100644 index 0000000000..a263cad034 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_js_compare.ets.arkts2.json @@ -0,0 +1,228 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 57, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 57, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 5, + "endLine": 19, + "endColumn": 14, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 5, + "endLine": 20, + "endColumn": 14, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 2, + "problem": "InterOpImportJsDataCompare", + "suggest": "", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-js-data-compare)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 5, + "endLine": 21, + "endColumn": 6, + "problem": "InterOpImportJsDataCompare", + "suggest": "", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-js-data-compare)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 1, + "endLine": 22, + "endColumn": 2, + "problem": "InterOpImportJsDataCompare", + "suggest": "", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-js-data-compare)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 5, + "endLine": 22, + "endColumn": 6, + "problem": "InterOpImportJsDataCompare", + "suggest": "", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-js-data-compare)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 1, + "endLine": 23, + "endColumn": 2, + "problem": "InterOpImportJsDataCompare", + "suggest": "", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-js-data-compare)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 6, + "endLine": 23, + "endColumn": 7, + "problem": "InterOpImportJsDataCompare", + "suggest": "", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-js-data-compare)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 1, + "endLine": 24, + "endColumn": 2, + "problem": "InterOpImportJsDataCompare", + "suggest": "", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-js-data-compare)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 6, + "endLine": 24, + "endColumn": 7, + "problem": "InterOpImportJsDataCompare", + "suggest": "", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-js-data-compare)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 1, + "endLine": 25, + "endColumn": 2, + "problem": "InterOpImportJsDataCompare", + "suggest": "", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-js-data-compare)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 1, + "endLine": 27, + "endColumn": 2, + "problem": "InterOpImportJsDataCompare", + "suggest": "", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-js-data-compare)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 5, + "endLine": 27, + "endColumn": 6, + "problem": "InterOpImportJsDataCompare", + "suggest": "", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-js-data-compare)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 1, + "endLine": 28, + "endColumn": 2, + "problem": "InterOpImportJsDataCompare", + "suggest": "", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-js-data-compare)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 5, + "endLine": 30, + "endColumn": 10, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 12, + "endLine": 30, + "endColumn": 17, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 36, + "column": 11, + "endLine": 36, + "endColumn": 12, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 5, + "endLine": 38, + "endColumn": 15, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 17, + "endLine": 38, + "endColumn": 27, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_import_js_compare.ets.json b/ets2panda/linter/test/interop/interop_import_js_compare.ets.json new file mode 100644 index 0000000000..25d2c46ecd --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_js_compare.ets.json @@ -0,0 +1,38 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 57, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 36, + "column": 11, + "endLine": 36, + "endColumn": 12, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_import_js_compare_js.js b/ets2panda/linter/test/interop/interop_import_js_compare_js.js new file mode 100644 index 0000000000..8135cf86aa --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_js_compare_js.js @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export let foo = {a: 1, b: 2} +export let m = 1 +export let n = 2 \ No newline at end of file -- Gitee From 218edb97aad5a171ba6b12d2f0d28350b4b8a6ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=92=9F=E6=9F=A0?= Date: Thu, 10 Apr 2025 11:22:02 +0800 Subject: [PATCH 083/268] Add performs equality judgment MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBYGKD Test scenarios:add performs equality judgment to the linter Signed-off-by: 钟柠 --- ets2panda/linter/src/lib/CookBookMsg.ts | 2 + ets2panda/linter/src/lib/FaultAttrs.ts | 3 +- ets2panda/linter/src/lib/FaultDesc.ts | 1 + ets2panda/linter/src/lib/Problems.ts | 1 + ets2panda/linter/src/lib/TypeScriptLinter.ts | 27 +++++- .../linter/src/lib/autofixes/AutofixTitles.ts | 3 +- .../linter/src/lib/autofixes/Autofixer.ts | 58 ++++++++++- ets2panda/linter/src/lib/utils/TsUtils.ts | 2 +- .../src/lib/utils/consts/ArkTS2Rules.ts | 3 +- .../linter/src/lib/utils/consts/InteropAPI.ts | 2 + .../interop/interop_equality_judgment.ets | 21 ++++ .../interop_equality_judgment.ets.args.json | 20 ++++ .../interop_equality_judgment.ets.arkts2.json | 68 +++++++++++++ ...interop_equality_judgment.ets.autofix.json | 96 +++++++++++++++++++ .../interop_equality_judgment.ets.json | 28 ++++++ .../interop/interop_equality_judgment_js.js | 18 ++++ 16 files changed, 347 insertions(+), 6 deletions(-) create mode 100644 ets2panda/linter/test/interop/interop_equality_judgment.ets create mode 100644 ets2panda/linter/test/interop/interop_equality_judgment.ets.args.json create mode 100644 ets2panda/linter/test/interop/interop_equality_judgment.ets.arkts2.json create mode 100644 ets2panda/linter/test/interop/interop_equality_judgment.ets.autofix.json create mode 100644 ets2panda/linter/test/interop/interop_equality_judgment.ets.json create mode 100644 ets2panda/linter/test/interop/interop_equality_judgment_js.js diff --git a/ets2panda/linter/src/lib/CookBookMsg.ts b/ets2panda/linter/src/lib/CookBookMsg.ts index 8127611fe6..1b9ab46396 100644 --- a/ets2panda/linter/src/lib/CookBookMsg.ts +++ b/ets2panda/linter/src/lib/CookBookMsg.ts @@ -299,3 +299,5 @@ cookBookTag[335] = 'Interop object does not have property num (arkts-interop-doe cookBookTag[336] = 'Binary operations on js objects (arkts-no-js-obj-binary-operation)'; cookBookTag[337] = 'Importing data directly from the "JS" module for comparison is not supported (arkts-js-data-compare)'; +cookBookTag[338] = + '"JS" objects can\'t be used directly as operands of the equality operators (arkts-js-equality-judgment)'; diff --git a/ets2panda/linter/src/lib/FaultAttrs.ts b/ets2panda/linter/src/lib/FaultAttrs.ts index 2194250453..dca8cbb251 100644 --- a/ets2panda/linter/src/lib/FaultAttrs.ts +++ b/ets2panda/linter/src/lib/FaultAttrs.ts @@ -206,4 +206,5 @@ faultsAttrs[FaultID.InterOpConvertImport] = new FaultAttributes(333); faultsAttrs[FaultID.InterOpImportJsForTypeOf] = new FaultAttributes(334); faultsAttrs[FaultID.InteropNoHaveNum] = new FaultAttributes(335); faultsAttrs[FaultID.BinaryOperations] = new FaultAttributes(336); -faultsAttrs[FaultID.InterOpImportJsDataCompare] = new FaultAttributes(337); \ No newline at end of file +faultsAttrs[FaultID.InterOpImportJsDataCompare] = new FaultAttributes(337); +faultsAttrs[FaultID.InteropEqualityJudgment] = new FaultAttributes(338); diff --git a/ets2panda/linter/src/lib/FaultDesc.ts b/ets2panda/linter/src/lib/FaultDesc.ts index 2b5bc5683c..64b92551cb 100644 --- a/ets2panda/linter/src/lib/FaultDesc.ts +++ b/ets2panda/linter/src/lib/FaultDesc.ts @@ -195,3 +195,4 @@ faultDesc[FaultID.InterOpImportJsForTypeOf] = 'TypeOf import from JS'; faultDesc[FaultID.InteropNoHaveNum] = 'Interop obj with "num" property'; faultDesc[FaultID.BinaryOperations] = 'Binary operations on js objects'; faultDesc[FaultID.InterOpImportJsDataCompare] = 'NO js import data compare'; +faultDesc[FaultID.InteropEqualityJudgment] = 'Equality operator with JS objects'; diff --git a/ets2panda/linter/src/lib/Problems.ts b/ets2panda/linter/src/lib/Problems.ts index f6b422fd55..886c6b2625 100644 --- a/ets2panda/linter/src/lib/Problems.ts +++ b/ets2panda/linter/src/lib/Problems.ts @@ -196,6 +196,7 @@ export enum FaultID { InteropNoHaveNum, BinaryOperations, InterOpImportJsDataCompare, + InteropEqualityJudgment, // this should always be last enum LAST_ID } diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index e7609ba189..fa25ac90ad 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -1623,6 +1623,7 @@ export class TypeScriptLinter { } this.checkNumericSemantics(tsBinaryExpr); this.checkInterOpImportJsDataCompare(tsBinaryExpr); + this.checkInteropEqualityJudgment(tsBinaryExpr); } private checkInterOpImportJsDataCompare(expr: ts.BinaryExpression): void { @@ -1677,6 +1678,30 @@ export class TypeScriptLinter { ].includes(kind); } + private checkInteropEqualityJudgment(tsBinaryExpr: ts.BinaryExpression): void { + if (this.useStatic && this.options.arkts2) { + const leftSym = this.tsUtils.trueSymbolAtLocation(tsBinaryExpr.left); + const rightSym = this.tsUtils.trueSymbolAtLocation(tsBinaryExpr.right); + switch (tsBinaryExpr.operatorToken.kind) { + case ts.SyntaxKind.EqualsEqualsToken: + case ts.SyntaxKind.ExclamationEqualsToken: + case ts.SyntaxKind.EqualsEqualsEqualsToken: + case ts.SyntaxKind.ExclamationEqualsEqualsToken: + if (this.isJsType(leftSym) || this.isJsType(rightSym)) { + const autofix = this.autofixer?.fixInteropEqualityOperator(tsBinaryExpr, tsBinaryExpr.operatorToken.kind); + this.incrementCounters(tsBinaryExpr, FaultID.InteropEqualityJudgment, autofix); + } + break; + default: + } + } + } + + isJsType(sym: ts.Symbol | undefined): boolean { + void this; + return !!sym && !!sym.declarations && sym.declarations[0].getSourceFile().fileName.endsWith(EXTNAME_JS); + } + private handleTsInterop(nodeToCheck: ts.Node, handler: { (): void }): void { if (!this.options.arkts2) { return; @@ -6219,7 +6244,7 @@ export class TypeScriptLinter { } return undefined; } - + private isFromJSModule(node: ts.Node): boolean { const symbol = this.tsUtils.trueSymbolAtLocation(node); if (symbol?.declarations?.[0]) { diff --git a/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts b/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts index eb1852e7cb..2112f31ee8 100644 --- a/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts +++ b/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts @@ -50,5 +50,6 @@ export const cookBookRefToFixTitle: Map = new Map([ [260, '"@Entry" annotaion fixed'], [263, '"@Provide" annotation fixed'], [330, 'Convert import named objects from JS to ESObject'], - [332, 'Using the ESObject interface to access properties'] + [332, 'Using the ESObject interface to access properties'], + [338, 'Replace with library function call'] ]); diff --git a/ets2panda/linter/src/lib/autofixes/Autofixer.ts b/ets2panda/linter/src/lib/autofixes/Autofixer.ts index 0e0b3ccec2..59b0ddb4e2 100644 --- a/ets2panda/linter/src/lib/autofixes/Autofixer.ts +++ b/ets2panda/linter/src/lib/autofixes/Autofixer.ts @@ -43,7 +43,7 @@ import { PROVIDE_ALLOW_OVERRIDE_PROPERTY_NAME } from '../utils/consts/ArkuiConstants'; import { ES_OBJECT } from '../utils/consts/ESObject'; -import { LOAD, GET_PROPERTY_BY_NAME } from '../utils/consts/InteropAPI'; +import { LOAD, GET_PROPERTY_BY_NAME, ARE_EQUAL, ARE_STRICTLY_EQUAL } from '../utils/consts/InteropAPI'; const UNDEFINED_NAME = 'undefined'; @@ -3377,4 +3377,60 @@ export class Autofixer { } return [{ start: express.operand.getStart(), end: express.operand.getEnd(), replacementText: text }]; } + + fixInteropEqualityOperator( + tsBinaryExpr: ts.BinaryExpression, + binaryOperator: ts.BinaryOperator + ): Autofix[] | undefined { + const text = this.replaceInteropEqualityOperator(tsBinaryExpr, binaryOperator); + if (text) { + return [{ start: tsBinaryExpr.getStart(), end: tsBinaryExpr.getEnd(), replacementText: text }]; + } + return undefined; + } + + replaceInteropEqualityOperator( + tsBinaryExpr: ts.BinaryExpression, + binaryOperator: ts.BinaryOperator + ): string | undefined { + const info = this.getInteropEqualityReplacementInfo(binaryOperator); + if (!info) { + return undefined; + } + + const tsLhsExpr = tsBinaryExpr.left; + const tsRhsExpr = tsBinaryExpr.right; + const callExpression = ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression( + ts.factory.createIdentifier(tsLhsExpr.getText()), + ts.factory.createIdentifier(info.functionName) + ), + undefined, + [ts.factory.createIdentifier(tsRhsExpr.getText())] + ); + + let text = this.printer.printNode(ts.EmitHint.Unspecified, callExpression, tsBinaryExpr.getSourceFile()); + if (info.isNegative) { + text = '!' + text; + } + return text; + } + + getInteropEqualityReplacementInfo( + binaryOperator: ts.BinaryOperator + ): { functionName: string; isNegative: boolean } | undefined { + void this; + switch (binaryOperator) { + case ts.SyntaxKind.EqualsEqualsToken: + return { functionName: ARE_EQUAL, isNegative: false }; + case ts.SyntaxKind.ExclamationEqualsToken: + return { functionName: ARE_EQUAL, isNegative: true }; + case ts.SyntaxKind.EqualsEqualsEqualsToken: + return { functionName: ARE_STRICTLY_EQUAL, isNegative: false }; + case ts.SyntaxKind.ExclamationEqualsEqualsToken: + return { functionName: ARE_STRICTLY_EQUAL, isNegative: true }; + default: + return undefined; + } + } } diff --git a/ets2panda/linter/src/lib/utils/TsUtils.ts b/ets2panda/linter/src/lib/utils/TsUtils.ts index 349d82fc76..d2a6a7a450 100644 --- a/ets2panda/linter/src/lib/utils/TsUtils.ts +++ b/ets2panda/linter/src/lib/utils/TsUtils.ts @@ -3491,7 +3491,7 @@ export class TsUtils { return undefined; } - + static isArkts12File(sourceFile: ts.SourceFile): boolean { if (!sourceFile) { return false; diff --git a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts index acc19c2771..6181006e4a 100644 --- a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts +++ b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts @@ -86,5 +86,6 @@ export const arkts2Rules: number[] = [ 334, 335, 336, - 337 + 337, + 338 ]; diff --git a/ets2panda/linter/src/lib/utils/consts/InteropAPI.ts b/ets2panda/linter/src/lib/utils/consts/InteropAPI.ts index bdc4f457ab..849320a828 100644 --- a/ets2panda/linter/src/lib/utils/consts/InteropAPI.ts +++ b/ets2panda/linter/src/lib/utils/consts/InteropAPI.ts @@ -14,6 +14,8 @@ */ export const USE_STATIC = '\'use static\''; +export const ARE_EQUAL = 'areEqual'; +export const ARE_STRICTLY_EQUAL = 'areStrictlyEqual'; export const REFLECT_PROPERTIES = [ 'get', diff --git a/ets2panda/linter/test/interop/interop_equality_judgment.ets b/ets2panda/linter/test/interop/interop_equality_judgment.ets new file mode 100644 index 0000000000..7fe09978d3 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_equality_judgment.ets @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use static' +import {a, b} from "./interop_equality_judgment_js" +a == b +a != b +a === b +a !== b \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_equality_judgment.ets.args.json b/ets2panda/linter/test/interop/interop_equality_judgment.ets.args.json new file mode 100644 index 0000000000..a2c0f14eb2 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_equality_judgment.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_equality_judgment.ets.arkts2.json b/ets2panda/linter/test/interop/interop_equality_judgment.ets.arkts2.json new file mode 100644 index 0000000000..c8f8b95ca9 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_equality_judgment.ets.arkts2.json @@ -0,0 +1,68 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 52, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 7, + "problem": "InteropEqualityJudgment", + "suggest": "", + "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-js-equality-judgment)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 7, + "problem": "InteropEqualityJudgment", + "suggest": "", + "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-js-equality-judgment)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 8, + "problem": "InteropEqualityJudgment", + "suggest": "", + "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-js-equality-judgment)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 8, + "problem": "InteropEqualityJudgment", + "suggest": "", + "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-js-equality-judgment)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_equality_judgment.ets.autofix.json b/ets2panda/linter/test/interop/interop_equality_judgment.ets.autofix.json new file mode 100644 index 0000000000..8224b628a6 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_equality_judgment.ets.autofix.json @@ -0,0 +1,96 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 52, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 7, + "problem": "InteropEqualityJudgment", + "autofix": [ + { + "start": 670, + "end": 676, + "replacementText": "a.areEqual(b)" + } + ], + "suggest": "", + "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-js-equality-judgment)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 7, + "problem": "InteropEqualityJudgment", + "autofix": [ + { + "start": 677, + "end": 683, + "replacementText": "!a.areEqual(b)" + } + ], + "suggest": "", + "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-js-equality-judgment)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 8, + "problem": "InteropEqualityJudgment", + "autofix": [ + { + "start": 684, + "end": 691, + "replacementText": "a.areStrictlyEqual(b)" + } + ], + "suggest": "", + "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-js-equality-judgment)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 8, + "problem": "InteropEqualityJudgment", + "autofix": [ + { + "start": 692, + "end": 699, + "replacementText": "!a.areStrictlyEqual(b)" + } + ], + "suggest": "", + "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-js-equality-judgment)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_equality_judgment.ets.json b/ets2panda/linter/test/interop/interop_equality_judgment.ets.json new file mode 100644 index 0000000000..e48cf9a99b --- /dev/null +++ b/ets2panda/linter/test/interop/interop_equality_judgment.ets.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 52, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_equality_judgment_js.js b/ets2panda/linter/test/interop/interop_equality_judgment_js.js new file mode 100644 index 0000000000..6461191d68 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_equality_judgment_js.js @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class A {} +export let a = new A() +export let b = new A() \ No newline at end of file -- Gitee From 089f8282f51627159ce8daed7851ca0ebfd40217 Mon Sep 17 00:00:00 2001 From: zhongning Date: Wed, 26 Mar 2025 19:59:14 +0800 Subject: [PATCH 084/268] Add check and fix for arkts-no-js-index Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBWJOK Test scenarios: new tests added to the linter Signed-off-by: zhongning --- ets2panda/linter/src/lib/CookBookMsg.ts | 1 + ets2panda/linter/src/lib/FaultAttrs.ts | 1 + ets2panda/linter/src/lib/FaultDesc.ts | 1 + ets2panda/linter/src/lib/Problems.ts | 1 + ets2panda/linter/src/lib/TypeScriptLinter.ts | 41 ++++++- .../linter/src/lib/autofixes/AutofixTitles.ts | 3 +- .../linter/src/lib/autofixes/Autofixer.ts | 35 ++++++ .../src/lib/utils/consts/ArkTS2Rules.ts | 5 +- .../test/interop/interop_import_js_index.ets | 20 ++++ .../interop_import_js_index.ets.args.json | 20 ++++ .../interop_import_js_index.ets.arkts2.json | 68 ++++++++++++ .../interop_import_js_index.ets.autofix.json | 101 ++++++++++++++++++ .../interop/interop_import_js_index.ets.json | 28 +++++ .../interop/interop_import_js_index_js.js | 16 +++ 14 files changed, 338 insertions(+), 3 deletions(-) create mode 100644 ets2panda/linter/test/interop/interop_import_js_index.ets create mode 100644 ets2panda/linter/test/interop/interop_import_js_index.ets.args.json create mode 100644 ets2panda/linter/test/interop/interop_import_js_index.ets.arkts2.json create mode 100644 ets2panda/linter/test/interop/interop_import_js_index.ets.autofix.json create mode 100644 ets2panda/linter/test/interop/interop_import_js_index.ets.json create mode 100644 ets2panda/linter/test/interop/interop_import_js_index_js.js diff --git a/ets2panda/linter/src/lib/CookBookMsg.ts b/ets2panda/linter/src/lib/CookBookMsg.ts index 1b9ab46396..25e3058fb5 100644 --- a/ets2panda/linter/src/lib/CookBookMsg.ts +++ b/ets2panda/linter/src/lib/CookBookMsg.ts @@ -301,3 +301,4 @@ cookBookTag[337] = 'Importing data directly from the "JS" module for comparison is not supported (arkts-js-data-compare)'; cookBookTag[338] = '"JS" objects can\'t be used directly as operands of the equality operators (arkts-js-equality-judgment)'; +cookBookTag[339] = 'Interop objects can\'t be indexed directly (arkts-no-js-index)'; \ No newline at end of file diff --git a/ets2panda/linter/src/lib/FaultAttrs.ts b/ets2panda/linter/src/lib/FaultAttrs.ts index dca8cbb251..6e4e6bfd09 100644 --- a/ets2panda/linter/src/lib/FaultAttrs.ts +++ b/ets2panda/linter/src/lib/FaultAttrs.ts @@ -208,3 +208,4 @@ faultsAttrs[FaultID.InteropNoHaveNum] = new FaultAttributes(335); faultsAttrs[FaultID.BinaryOperations] = new FaultAttributes(336); faultsAttrs[FaultID.InterOpImportJsDataCompare] = new FaultAttributes(337); faultsAttrs[FaultID.InteropEqualityJudgment] = new FaultAttributes(338); +faultsAttrs[FaultID.InterOpImportJsIndex] = new FaultAttributes(339); diff --git a/ets2panda/linter/src/lib/FaultDesc.ts b/ets2panda/linter/src/lib/FaultDesc.ts index 64b92551cb..51ab0cff9e 100644 --- a/ets2panda/linter/src/lib/FaultDesc.ts +++ b/ets2panda/linter/src/lib/FaultDesc.ts @@ -196,3 +196,4 @@ faultDesc[FaultID.InteropNoHaveNum] = 'Interop obj with "num" property'; faultDesc[FaultID.BinaryOperations] = 'Binary operations on js objects'; faultDesc[FaultID.InterOpImportJsDataCompare] = 'NO js import data compare'; faultDesc[FaultID.InteropEqualityJudgment] = 'Equality operator with JS objects'; +faultDesc[FaultID.InterOpImportJsIndex] = 'No js index import'; diff --git a/ets2panda/linter/src/lib/Problems.ts b/ets2panda/linter/src/lib/Problems.ts index 886c6b2625..b38b216820 100644 --- a/ets2panda/linter/src/lib/Problems.ts +++ b/ets2panda/linter/src/lib/Problems.ts @@ -197,6 +197,7 @@ export enum FaultID { BinaryOperations, InterOpImportJsDataCompare, InteropEqualityJudgment, + InterOpImportJsIndex, // this should always be last enum LAST_ID } diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index fa25ac90ad..7489735989 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -3130,8 +3130,47 @@ export class TypeScriptLinter { this.handleIndexNegative(node); } this.checkArrayIndexType(tsElemAccessBaseExprType, tsElemAccessArgType, tsElementAccessExpr); - this.fixJsImportElementAccessExpression(tsElementAccessExpr); + this.checkInterOpImportJsIndex(tsElementAccessExpr); + } + + private checkInterOpImportJsIndex(expr: ts.ElementAccessExpression): void { + if (!this.useStatic || !this.options.arkts2) { + return; + } + + const exprSym = this.tsUtils.trueSymbolAtLocation(expr.expression); + if (!exprSym) { + return; + } + + const exprDecl = TsUtils.getDeclaration(exprSym); + if (!exprDecl || !ts.isVariableDeclaration(exprDecl)) { + return; + } + + const initializer = exprDecl.initializer; + if (!initializer || !ts.isPropertyAccessExpression(initializer)) { + return; + } + + const initSym = this.tsUtils.trueSymbolAtLocation(initializer.expression); + if (!initSym) { + return; + } + + const initDecl = TsUtils.getDeclaration(initSym); + if (!initDecl || !initDecl.getSourceFile().fileName.endsWith(EXTNAME_JS)) { + return; + } + + if (ts.isBinaryExpression(expr.parent) && expr.parent.operatorToken.kind === ts.SyntaxKind.EqualsToken) { + const autofix = this.autofixer?.fixInteropArrayBinaryExpression(expr.parent); + this.incrementCounters(expr.parent, FaultID.InterOpImportJsIndex, autofix); + } else { + const autofix = this.autofixer?.fixInteropArrayElementAccessExpression(expr); + this.incrementCounters(expr, FaultID.InterOpImportJsIndex, autofix); + } } private checkArrayIndexType(exprType: ts.Type, argType: ts.Type, expr: ts.ElementAccessExpression): void { diff --git a/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts b/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts index 2112f31ee8..dc7bc52710 100644 --- a/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts +++ b/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts @@ -51,5 +51,6 @@ export const cookBookRefToFixTitle: Map = new Map([ [263, '"@Provide" annotation fixed'], [330, 'Convert import named objects from JS to ESObject'], [332, 'Using the ESObject interface to access properties'], - [338, 'Replace with library function call'] + [338, 'Replace with library function call'], + [339, 'Using \'ESObject\' interface call'] ]); diff --git a/ets2panda/linter/src/lib/autofixes/Autofixer.ts b/ets2panda/linter/src/lib/autofixes/Autofixer.ts index 59b0ddb4e2..fcf27ec6bb 100644 --- a/ets2panda/linter/src/lib/autofixes/Autofixer.ts +++ b/ets2panda/linter/src/lib/autofixes/Autofixer.ts @@ -3346,6 +3346,41 @@ export class Autofixer { return [{ start: express.getStart(), end: express.getEnd(), replacementText: replacementText }]; } + fixInteropArrayElementAccessExpression(express: ts.ElementAccessExpression): Autofix[] | undefined { + const statements = ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression(express.expression, ts.factory.createIdentifier('getPropertyByIndex')), + undefined, + [express.argumentExpression] + ); + const text = this.printer.printNode(ts.EmitHint.Unspecified, statements, express.getSourceFile()); + return [{ start: express.getStart(), end: express.getEnd(), replacementText: text }]; + } + + fixInteropArrayBinaryExpression(express: ts.BinaryExpression): Autofix[] | undefined { + const left = express.left as ts.ElementAccessExpression; + const right = express.right; + const statements = ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression( + ts.factory.createIdentifier(left.expression.getText()), + ts.factory.createIdentifier('setPropertyByIndex') + ), + undefined, + [ + left.argumentExpression, + ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression( + ts.factory.createIdentifier(ES_OBJECT), + ts.factory.createIdentifier('wrap') + ), + undefined, + [ts.factory.createIdentifier(right.getText())] + ) + ] + ); + const replacementText = this.printer.printNode(ts.EmitHint.Unspecified, statements, express.getSourceFile()); + return [{ start: express.getStart(), end: express.getEnd(), replacementText: replacementText }]; + } + fixInterOpImportJsOnTypeOf(typeofExpress: ts.TypeOfExpression): Autofix[] | undefined { const node = typeofExpress.expression; const start = typeofExpress.getStart(); diff --git a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts index 6181006e4a..7caae3dc3c 100644 --- a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts +++ b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts @@ -62,6 +62,7 @@ export const arkts2Rules: number[] = [ 259, 260, 263, + 300, 301, 302, 303, @@ -78,6 +79,7 @@ export const arkts2Rules: number[] = [ 314, 315, 316, + 320, 321, 330, 331, @@ -87,5 +89,6 @@ export const arkts2Rules: number[] = [ 335, 336, 337, - 338 + 338, + 339 ]; diff --git a/ets2panda/linter/test/interop/interop_import_js_index.ets b/ets2panda/linter/test/interop/interop_import_js_index.ets new file mode 100644 index 0000000000..daf1403ab2 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_js_index.ets @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use static' +import {foo} from "./interop_import_js_index_js" +let arr = foo.arr +arr[1] +arr[3] = 4 \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_import_js_index.ets.args.json b/ets2panda/linter/test/interop/interop_import_js_index.ets.args.json new file mode 100644 index 0000000000..6bbb5430dd --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_js_index.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2" + } + } \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_import_js_index.ets.arkts2.json b/ets2panda/linter/test/interop/interop_import_js_index.ets.arkts2.json new file mode 100644 index 0000000000..4c39084814 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_js_index.ets.arkts2.json @@ -0,0 +1,68 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 49, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 49, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 5, + "endLine": 18, + "endColumn": 18, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 7, + "problem": "InterOpImportJsIndex", + "suggest": "", + "rule": "Interop objects can't be indexed directly (arkts-no-js-index)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 11, + "problem": "InterOpImportJsIndex", + "suggest": "", + "rule": "Interop objects can't be indexed directly (arkts-no-js-index)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_import_js_index.ets.autofix.json b/ets2panda/linter/test/interop/interop_import_js_index.ets.autofix.json new file mode 100644 index 0000000000..7ab1bffb06 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_js_index.ets.autofix.json @@ -0,0 +1,101 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 49, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 49, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 619, + "end": 667, + "replacementText": "" + }, + { + "start": 667, + "end": 667, + "replacementText": "let GeneratedImportVar_1 = ESObject.load('./interop_import_js_index_js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');" + } + ], + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 5, + "endLine": 18, + "endColumn": 18, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 672, + "end": 685, + "replacementText": "arr: number[] = foo.arr" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 7, + "problem": "InterOpImportJsIndex", + "autofix": [ + { + "start": 686, + "end": 692, + "replacementText": "arr.getPropertyByIndex(1)" + } + ], + "suggest": "", + "rule": "Interop objects can't be indexed directly (arkts-no-js-index)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 11, + "problem": "InterOpImportJsIndex", + "autofix": [ + { + "start": 693, + "end": 703, + "replacementText": "arr.setPropertyByIndex(3, ESObject.wrap(4))" + } + ], + "suggest": "", + "rule": "Interop objects can't be indexed directly (arkts-no-js-index)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_import_js_index.ets.json b/ets2panda/linter/test/interop/interop_import_js_index.ets.json new file mode 100644 index 0000000000..5619e69d78 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_js_index.ets.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 49, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_import_js_index_js.js b/ets2panda/linter/test/interop/interop_import_js_index_js.js new file mode 100644 index 0000000000..168f73cb83 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_js_index_js.js @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export let foo = {arr: [1, 2, 3]} \ No newline at end of file -- Gitee From b15a9b5665cb96911be1f20730fb05980bf93894 Mon Sep 17 00:00:00 2001 From: ZhongNing Date: Wed, 2 Apr 2025 16:54:29 +0800 Subject: [PATCH 085/268] Add checks for arkts-no-import-await Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBYBZH Test scenarios: new tests added to the linter Signed-off-by: ZhongNing --- ets2panda/linter/src/lib/CookBookMsg.ts | 3 +- ets2panda/linter/src/lib/FaultAttrs.ts | 1 + ets2panda/linter/src/lib/FaultDesc.ts | 1 + ets2panda/linter/src/lib/Problems.ts | 1 + ets2panda/linter/src/lib/TypeScriptLinter.ts | 22 ++- ets2panda/linter/src/lib/utils/TsUtils.ts | 13 ++ .../src/lib/utils/consts/ArkTS2Rules.ts | 4 +- ets2panda/linter/test/interop/no_js_awai.js | 22 +++ ets2panda/linter/test/interop/no_js_await.ets | 71 ++++++++ .../test/interop/no_js_await.ets.args.json | 19 ++ .../test/interop/no_js_await.ets.arkts2.json | 168 ++++++++++++++++++ .../linter/test/interop/no_js_await.ets.json | 48 +++++ 12 files changed, 370 insertions(+), 3 deletions(-) create mode 100755 ets2panda/linter/test/interop/no_js_awai.js create mode 100755 ets2panda/linter/test/interop/no_js_await.ets create mode 100755 ets2panda/linter/test/interop/no_js_await.ets.args.json create mode 100755 ets2panda/linter/test/interop/no_js_await.ets.arkts2.json create mode 100755 ets2panda/linter/test/interop/no_js_await.ets.json diff --git a/ets2panda/linter/src/lib/CookBookMsg.ts b/ets2panda/linter/src/lib/CookBookMsg.ts index 25e3058fb5..62c254a60a 100644 --- a/ets2panda/linter/src/lib/CookBookMsg.ts +++ b/ets2panda/linter/src/lib/CookBookMsg.ts @@ -301,4 +301,5 @@ cookBookTag[337] = 'Importing data directly from the "JS" module for comparison is not supported (arkts-js-data-compare)'; cookBookTag[338] = '"JS" objects can\'t be used directly as operands of the equality operators (arkts-js-equality-judgment)'; -cookBookTag[339] = 'Interop objects can\'t be indexed directly (arkts-no-js-index)'; \ No newline at end of file +cookBookTag[339] = 'Interop objects can\'t be indexed directly (arkts-no-js-index)'; +cookBookTag[340] = '"Await" operator can\'t be used with interop objects (arkts-no-js-await)'; diff --git a/ets2panda/linter/src/lib/FaultAttrs.ts b/ets2panda/linter/src/lib/FaultAttrs.ts index 6e4e6bfd09..2ad916b462 100644 --- a/ets2panda/linter/src/lib/FaultAttrs.ts +++ b/ets2panda/linter/src/lib/FaultAttrs.ts @@ -209,3 +209,4 @@ faultsAttrs[FaultID.BinaryOperations] = new FaultAttributes(336); faultsAttrs[FaultID.InterOpImportJsDataCompare] = new FaultAttributes(337); faultsAttrs[FaultID.InteropEqualityJudgment] = new FaultAttributes(338); faultsAttrs[FaultID.InterOpImportJsIndex] = new FaultAttributes(339); +faultsAttrs[FaultID.NoJsImportAwait] = new FaultAttributes(340); diff --git a/ets2panda/linter/src/lib/FaultDesc.ts b/ets2panda/linter/src/lib/FaultDesc.ts index 51ab0cff9e..bfbf6a4336 100644 --- a/ets2panda/linter/src/lib/FaultDesc.ts +++ b/ets2panda/linter/src/lib/FaultDesc.ts @@ -197,3 +197,4 @@ faultDesc[FaultID.BinaryOperations] = 'Binary operations on js objects'; faultDesc[FaultID.InterOpImportJsDataCompare] = 'NO js import data compare'; faultDesc[FaultID.InteropEqualityJudgment] = 'Equality operator with JS objects'; faultDesc[FaultID.InterOpImportJsIndex] = 'No js index import'; +faultDesc[FaultID.NoJsImportAwait] = 'No js import await'; diff --git a/ets2panda/linter/src/lib/Problems.ts b/ets2panda/linter/src/lib/Problems.ts index b38b216820..bfaac2fde1 100644 --- a/ets2panda/linter/src/lib/Problems.ts +++ b/ets2panda/linter/src/lib/Problems.ts @@ -198,6 +198,7 @@ export enum FaultID { InterOpImportJsDataCompare, InteropEqualityJudgment, InterOpImportJsIndex, + NoJsImportAwait, // this should always be last enum LAST_ID } diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index 7489735989..4556812ad1 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -292,7 +292,8 @@ export class TypeScriptLinter { [ts.SyntaxKind.HeritageClause, this.handleHeritageClause], [ts.SyntaxKind.TaggedTemplateExpression, this.handleTaggedTemplatesExpression], [ts.SyntaxKind.StructDeclaration, this.handleStructDeclaration], - [ts.SyntaxKind.TypeOfExpression, this.handleInterOpImportJsOnTypeOfNode] + [ts.SyntaxKind.TypeOfExpression, this.handleInterOpImportJsOnTypeOfNode], + [ts.SyntaxKind.AwaitExpression, this.handleAwaitExpression] ]); private getLineAndCharacterOfNode(node: ts.Node | ts.CommentRange): ts.LineAndCharacter { @@ -6292,4 +6293,23 @@ export class TypeScriptLinter { } return false; } + + private handleAwaitExpression(node: ts.Node): void { + if (!this.options.arkts2 || !this.useStatic) { + return + }; + const awaitExpr = node as ts.AwaitExpression; + const checkAndReportJsImportAwait = (targetNode: ts.Node): boolean => { + if (ts.isIdentifier(targetNode) && this.tsUtils.isJsImport(targetNode)) { + this.incrementCounters(node, FaultID.NoJsImportAwait); + return true; + } + return false; + }; + const expr = awaitExpr.expression; + checkAndReportJsImportAwait(expr); + if (ts.isCallExpression(expr)) { + checkAndReportJsImportAwait(expr.expression); + } + } } diff --git a/ets2panda/linter/src/lib/utils/TsUtils.ts b/ets2panda/linter/src/lib/utils/TsUtils.ts index d2a6a7a450..02ce3f35cf 100644 --- a/ets2panda/linter/src/lib/utils/TsUtils.ts +++ b/ets2panda/linter/src/lib/utils/TsUtils.ts @@ -3517,4 +3517,17 @@ export class TsUtils { } return str; } + + isJsImport(node: ts.Node): boolean { + const symbol = this.trueSymbolAtLocation(node); + if (symbol) { + const declaration = symbol.declarations?.[0]; + if (declaration) { + const sourceFile = declaration.getSourceFile(); + const isFromJs = sourceFile.fileName.endsWith(EXTNAME_JS); + return isFromJs; + } + } + return false; + } } diff --git a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts index 7caae3dc3c..4d6e80c053 100644 --- a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts +++ b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts @@ -79,6 +79,7 @@ export const arkts2Rules: number[] = [ 314, 315, 316, + 319, 320, 321, 330, @@ -90,5 +91,6 @@ export const arkts2Rules: number[] = [ 336, 337, 338, - 339 + 339, + 340 ]; diff --git a/ets2panda/linter/test/interop/no_js_awai.js b/ets2panda/linter/test/interop/no_js_awai.js new file mode 100755 index 0000000000..0707e733bb --- /dev/null +++ b/ets2panda/linter/test/interop/no_js_awai.js @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const p = Promise.resolve("resolved value"); +export async function foo() { + return "foo result"; +} +export const pFuncCall = foo(); +export const arrowFunc = async () => "arrow result"; +export const pArrowCall = arrowFunc(); \ No newline at end of file diff --git a/ets2panda/linter/test/interop/no_js_await.ets b/ets2panda/linter/test/interop/no_js_await.ets new file mode 100755 index 0000000000..1df1f4f9e9 --- /dev/null +++ b/ets2panda/linter/test/interop/no_js_await.ets @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +'use static' + +import { p, foo, pFuncCall, arrowFunc, pArrowCall } from "./no_import_awai.js"; + +// 1. 基础 Promise +async function awaitPromise() { + return await p; +} + +// 2. 异步函数调用 +async function awaitFunctionCall() { + return await foo(); +} + +async function awaitFuncResult() { + return await pFuncCall; +} + +// 3. 箭头函数 +async function awaitArrowCall() { + return await arrowFunc(); +} + +async function awaitArrowResult() { + return await pArrowCall; +} + +// 4. 类中使用 +class ExampleClass { + async classMethod() { + return await p; + } + + handler = async () => { + return await pFuncCall; + }; +} + +// 5. 对象方法 +const exampleObj = { + async objMethod() { + return await pArrowCall; + }, + + arrowHandler: async () => { + return await foo(); + } +}; + +// 6. 立即执行函数 +(async function() { + console.log("IIFE result:", await p); +})(); + +(async () => { + console.log("IIFE Arrow result:", await arrowFunc()); +})(); \ No newline at end of file diff --git a/ets2panda/linter/test/interop/no_js_await.ets.args.json b/ets2panda/linter/test/interop/no_js_await.ets.args.json new file mode 100755 index 0000000000..66fb88f859 --- /dev/null +++ b/ets2panda/linter/test/interop/no_js_await.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} diff --git a/ets2panda/linter/test/interop/no_js_await.ets.arkts2.json b/ets2panda/linter/test/interop/no_js_await.ets.arkts2.json new file mode 100755 index 0000000000..c6be12301f --- /dev/null +++ b/ets2panda/linter/test/interop/no_js_await.ets.arkts2.json @@ -0,0 +1,168 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 80, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 10, + "endLine": 21, + "endColumn": 17, + "problem": "NoJsImportAwait", + "suggest": "", + "rule": "ArkTS1.2 cannot import js files directly object is not Promise (arkts-no-import-await)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 10, + "endLine": 26, + "endColumn": 21, + "problem": "NoJsImportAwait", + "suggest": "", + "rule": "ArkTS1.2 cannot import js files directly object is not Promise (arkts-no-import-await)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 10, + "endLine": 30, + "endColumn": 25, + "problem": "NoJsImportAwait", + "suggest": "", + "rule": "ArkTS1.2 cannot import js files directly object is not Promise (arkts-no-import-await)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 10, + "endLine": 35, + "endColumn": 27, + "problem": "NoJsImportAwait", + "suggest": "", + "rule": "ArkTS1.2 cannot import js files directly object is not Promise (arkts-no-import-await)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 10, + "endLine": 39, + "endColumn": 26, + "problem": "NoJsImportAwait", + "suggest": "", + "rule": "ArkTS1.2 cannot import js files directly object is not Promise (arkts-no-import-await)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 12, + "endLine": 45, + "endColumn": 19, + "problem": "NoJsImportAwait", + "suggest": "", + "rule": "ArkTS1.2 cannot import js files directly object is not Promise (arkts-no-import-await)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 12, + "endLine": 49, + "endColumn": 27, + "problem": "NoJsImportAwait", + "suggest": "", + "rule": "ArkTS1.2 cannot import js files directly object is not Promise (arkts-no-import-await)", + "severity": "ERROR" + }, + { + "line": 54, + "column": 20, + "endLine": 54, + "endColumn": 21, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 55, + "column": 3, + "endLine": 57, + "endColumn": 4, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 56, + "column": 12, + "endLine": 56, + "endColumn": 28, + "problem": "NoJsImportAwait", + "suggest": "", + "rule": "ArkTS1.2 cannot import js files directly object is not Promise (arkts-no-import-await)", + "severity": "ERROR" + }, + { + "line": 60, + "column": 12, + "endLine": 60, + "endColumn": 23, + "problem": "NoJsImportAwait", + "suggest": "", + "rule": "ArkTS1.2 cannot import js files directly object is not Promise (arkts-no-import-await)", + "severity": "ERROR" + }, + { + "line": 65, + "column": 2, + "endLine": 67, + "endColumn": 2, + "problem": "FunctionExpression", + "suggest": "", + "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "severity": "ERROR" + }, + { + "line": 66, + "column": 31, + "endLine": 66, + "endColumn": 38, + "problem": "NoJsImportAwait", + "suggest": "", + "rule": "ArkTS1.2 cannot import js files directly object is not Promise (arkts-no-import-await)", + "severity": "ERROR" + }, + { + "line": 70, + "column": 37, + "endLine": 70, + "endColumn": 54, + "problem": "NoJsImportAwait", + "suggest": "", + "rule": "ArkTS1.2 cannot import js files directly object is not Promise (arkts-no-import-await)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/no_js_await.ets.json b/ets2panda/linter/test/interop/no_js_await.ets.json new file mode 100755 index 0000000000..145ba7afed --- /dev/null +++ b/ets2panda/linter/test/interop/no_js_await.ets.json @@ -0,0 +1,48 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 80, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 54, + "column": 20, + "endLine": 54, + "endColumn": 21, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 65, + "column": 2, + "endLine": 67, + "endColumn": 2, + "problem": "FunctionExpression", + "suggest": "", + "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "severity": "ERROR" + } + ] +} \ No newline at end of file -- Gitee From d8117f97ee089e04de92c927ba03113a1e7cc234 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=92=9F=E6=9F=A0?= Date: Wed, 9 Apr 2025 15:07:56 +0800 Subject: [PATCH 086/268] ArkTS directly instantiated JS objects MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBWPHA Test scenarios:ArkTS directly instantiated JS objects Signed-off-by: 钟柠 --- ets2panda/linter/src/lib/CookBookMsg.ts | 1 + ets2panda/linter/src/lib/FaultAttrs.ts | 1 + ets2panda/linter/src/lib/FaultDesc.ts | 1 + ets2panda/linter/src/lib/Problems.ts | 1 + ets2panda/linter/src/lib/TypeScriptLinter.ts | 11 ++ .../linter/src/lib/autofixes/AutofixTitles.ts | 3 +- .../linter/src/lib/autofixes/Autofixer.ts | 34 ++++ .../src/lib/utils/consts/ArkTS2Rules.ts | 3 +- .../linter/src/lib/utils/consts/InteropAPI.ts | 2 + .../test/interop/instantiated_js_obj.ets | 33 ++++ .../interop/instantiated_js_obj.ets.args.json | 20 +++ .../instantiated_js_obj.ets.arkts2.json | 98 ++++++++++++ .../instantiated_js_obj.ets.autofix.json | 147 ++++++++++++++++++ .../test/interop/instantiated_js_obj.ets.json | 28 ++++ .../test/interop/instantiated_js_obj_js.js | 22 +++ 15 files changed, 403 insertions(+), 2 deletions(-) create mode 100644 ets2panda/linter/test/interop/instantiated_js_obj.ets create mode 100644 ets2panda/linter/test/interop/instantiated_js_obj.ets.args.json create mode 100644 ets2panda/linter/test/interop/instantiated_js_obj.ets.arkts2.json create mode 100644 ets2panda/linter/test/interop/instantiated_js_obj.ets.autofix.json create mode 100644 ets2panda/linter/test/interop/instantiated_js_obj.ets.json create mode 100644 ets2panda/linter/test/interop/instantiated_js_obj_js.js diff --git a/ets2panda/linter/src/lib/CookBookMsg.ts b/ets2panda/linter/src/lib/CookBookMsg.ts index 62c254a60a..da038cda83 100644 --- a/ets2panda/linter/src/lib/CookBookMsg.ts +++ b/ets2panda/linter/src/lib/CookBookMsg.ts @@ -303,3 +303,4 @@ cookBookTag[338] = '"JS" objects can\'t be used directly as operands of the equality operators (arkts-js-equality-judgment)'; cookBookTag[339] = 'Interop objects can\'t be indexed directly (arkts-no-js-index)'; cookBookTag[340] = '"Await" operator can\'t be used with interop objects (arkts-no-js-await)'; +cookBookTag[341] = 'ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)'; diff --git a/ets2panda/linter/src/lib/FaultAttrs.ts b/ets2panda/linter/src/lib/FaultAttrs.ts index 2ad916b462..ffbcb66e00 100644 --- a/ets2panda/linter/src/lib/FaultAttrs.ts +++ b/ets2panda/linter/src/lib/FaultAttrs.ts @@ -210,3 +210,4 @@ faultsAttrs[FaultID.InterOpImportJsDataCompare] = new FaultAttributes(337); faultsAttrs[FaultID.InteropEqualityJudgment] = new FaultAttributes(338); faultsAttrs[FaultID.InterOpImportJsIndex] = new FaultAttributes(339); faultsAttrs[FaultID.NoJsImportAwait] = new FaultAttributes(340); +faultsAttrs[FaultID.InstantiatedJsOjbect] = new FaultAttributes(341); diff --git a/ets2panda/linter/src/lib/FaultDesc.ts b/ets2panda/linter/src/lib/FaultDesc.ts index bfbf6a4336..c85096c03c 100644 --- a/ets2panda/linter/src/lib/FaultDesc.ts +++ b/ets2panda/linter/src/lib/FaultDesc.ts @@ -198,3 +198,4 @@ faultDesc[FaultID.InterOpImportJsDataCompare] = 'NO js import data compare'; faultDesc[FaultID.InteropEqualityJudgment] = 'Equality operator with JS objects'; faultDesc[FaultID.InterOpImportJsIndex] = 'No js index import'; faultDesc[FaultID.NoJsImportAwait] = 'No js import await'; +faultDesc[FaultID.InstantiatedJsOjbect] = 'Instantiated js ojbect'; diff --git a/ets2panda/linter/src/lib/Problems.ts b/ets2panda/linter/src/lib/Problems.ts index bfaac2fde1..5fb0e17785 100644 --- a/ets2panda/linter/src/lib/Problems.ts +++ b/ets2panda/linter/src/lib/Problems.ts @@ -199,6 +199,7 @@ export enum FaultID { InteropEqualityJudgment, InterOpImportJsIndex, NoJsImportAwait, + InstantiatedJsOjbect, // this should always be last enum LAST_ID } diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index 4556812ad1..719c65ea2a 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -3887,6 +3887,17 @@ export class TypeScriptLinter { this.handleGenericCallWithNoTypeArgs(tsNewExpr, callSignature); } this.handleSendableGenericTypes(tsNewExpr); + this.handleInstantiatedJsObject(tsNewExpr, sym); + } + + handleInstantiatedJsObject(tsNewExpr: ts.NewExpression, sym: ts.Symbol | undefined): void { + if (this.useStatic && this.options.arkts2) { + if (sym?.declarations?.[0]?.getSourceFile().fileName.endsWith(EXTNAME_JS)) { + const args = tsNewExpr.arguments; + const autofix = this.autofixer?.fixInteropInstantiateExpression(tsNewExpr, args); + this.incrementCounters(tsNewExpr, FaultID.InstantiatedJsOjbect, autofix); + } + } } private handleSendableGenericTypes(node: ts.NewExpression): void { diff --git a/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts b/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts index dc7bc52710..7c807a1eb1 100644 --- a/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts +++ b/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts @@ -52,5 +52,6 @@ export const cookBookRefToFixTitle: Map = new Map([ [330, 'Convert import named objects from JS to ESObject'], [332, 'Using the ESObject interface to access properties'], [338, 'Replace with library function call'], - [339, 'Using \'ESObject\' interface call'] + [339, 'Using \'ESObject\' interface call'], + [341, 'Create JS objects using instantite'] ]); diff --git a/ets2panda/linter/src/lib/autofixes/Autofixer.ts b/ets2panda/linter/src/lib/autofixes/Autofixer.ts index fcf27ec6bb..bd52afcca0 100644 --- a/ets2panda/linter/src/lib/autofixes/Autofixer.ts +++ b/ets2panda/linter/src/lib/autofixes/Autofixer.ts @@ -44,6 +44,7 @@ import { } from '../utils/consts/ArkuiConstants'; import { ES_OBJECT } from '../utils/consts/ESObject'; import { LOAD, GET_PROPERTY_BY_NAME, ARE_EQUAL, ARE_STRICTLY_EQUAL } from '../utils/consts/InteropAPI'; +import { WRAP, INSTANTIATE } from '../utils/consts/InteropAPI'; const UNDEFINED_NAME = 'undefined'; @@ -2688,6 +2689,39 @@ export class Autofixer { ]; } + fixInteropInstantiateExpression( + express: ts.NewExpression, + args: ts.NodeArray | undefined + ): Autofix[] | undefined { + const statements = ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression( + ts.factory.createIdentifier(express.expression.getText()), + ts.factory.createIdentifier(INSTANTIATE) + ), + undefined, + this.createArgs(args) + ); + const replacementText = this.printer.printNode(ts.EmitHint.Unspecified, statements, express.getSourceFile()); + return [{ start: express.getStart(), end: express.getEnd(), replacementText: replacementText }]; + } + + createArgs(args: ts.NodeArray | undefined): ts.Expression[] | undefined { + void this; + if (args && args.length > 0) { + return args.map((arg) => { + return ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression( + ts.factory.createIdentifier(ES_OBJECT), + ts.factory.createIdentifier(WRAP) + ), + undefined, + [ts.factory.createIdentifier(arg.getText())] + ); + }); + } + return undefined; + } + fixParameter(param: ts.ParameterDeclaration): Autofix[] { const newParam = ts.factory.createParameterDeclaration( param.modifiers, diff --git a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts index 4d6e80c053..1b0cdcc27e 100644 --- a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts +++ b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts @@ -92,5 +92,6 @@ export const arkts2Rules: number[] = [ 337, 338, 339, - 340 + 340, + 341 ]; diff --git a/ets2panda/linter/src/lib/utils/consts/InteropAPI.ts b/ets2panda/linter/src/lib/utils/consts/InteropAPI.ts index 849320a828..678b6aa37c 100644 --- a/ets2panda/linter/src/lib/utils/consts/InteropAPI.ts +++ b/ets2panda/linter/src/lib/utils/consts/InteropAPI.ts @@ -16,6 +16,8 @@ export const USE_STATIC = '\'use static\''; export const ARE_EQUAL = 'areEqual'; export const ARE_STRICTLY_EQUAL = 'areStrictlyEqual'; +export const WRAP = 'wrap'; +export const INSTANTIATE = 'instantiate'; export const REFLECT_PROPERTIES = [ 'get', diff --git a/ets2panda/linter/test/interop/instantiated_js_obj.ets b/ets2panda/linter/test/interop/instantiated_js_obj.ets new file mode 100644 index 0000000000..f24de83f1a --- /dev/null +++ b/ets2panda/linter/test/interop/instantiated_js_obj.ets @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use static' +import {Foo, Foo1} from "./instantiated_js_obj_js" +class A { + num: number = 1; + constructor() { + } +} +new Foo(123) +new Foo('hello') +new Foo(new A()) +let a: A = new A(); +new Foo(a.num) +new Foo(a) +function test(): number { + return 1; +} +new Foo(test()) +new Foo1(123, 'hello') \ No newline at end of file diff --git a/ets2panda/linter/test/interop/instantiated_js_obj.ets.args.json b/ets2panda/linter/test/interop/instantiated_js_obj.ets.args.json new file mode 100644 index 0000000000..e237d4be28 --- /dev/null +++ b/ets2panda/linter/test/interop/instantiated_js_obj.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2" + } + } \ No newline at end of file diff --git a/ets2panda/linter/test/interop/instantiated_js_obj.ets.arkts2.json b/ets2panda/linter/test/interop/instantiated_js_obj.ets.arkts2.json new file mode 100644 index 0000000000..d3dee80079 --- /dev/null +++ b/ets2panda/linter/test/interop/instantiated_js_obj.ets.arkts2.json @@ -0,0 +1,98 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 51, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 1, + "endLine": 23, + "endColumn": 13, + "problem": "InstantiatedJsOjbect", + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 1, + "endLine": 24, + "endColumn": 17, + "problem": "InstantiatedJsOjbect", + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 1, + "endLine": 25, + "endColumn": 17, + "problem": "InstantiatedJsOjbect", + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 1, + "endLine": 27, + "endColumn": 15, + "problem": "InstantiatedJsOjbect", + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 1, + "endLine": 28, + "endColumn": 11, + "problem": "InstantiatedJsOjbect", + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 1, + "endLine": 32, + "endColumn": 16, + "problem": "InstantiatedJsOjbect", + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 1, + "endLine": 33, + "endColumn": 23, + "problem": "InstantiatedJsOjbect", + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/instantiated_js_obj.ets.autofix.json b/ets2panda/linter/test/interop/instantiated_js_obj.ets.autofix.json new file mode 100644 index 0000000000..2e9335492b --- /dev/null +++ b/ets2panda/linter/test/interop/instantiated_js_obj.ets.autofix.json @@ -0,0 +1,147 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 51, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 1, + "endLine": 23, + "endColumn": 13, + "problem": "InstantiatedJsOjbect", + "autofix": [ + { + "start": 728, + "end": 740, + "replacementText": "Foo.instantiate(ESObject.wrap(123))" + } + ], + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 1, + "endLine": 24, + "endColumn": 17, + "problem": "InstantiatedJsOjbect", + "autofix": [ + { + "start": 741, + "end": 757, + "replacementText": "Foo.instantiate(ESObject.wrap('hello'))" + } + ], + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 1, + "endLine": 25, + "endColumn": 17, + "problem": "InstantiatedJsOjbect", + "autofix": [ + { + "start": 758, + "end": 774, + "replacementText": "Foo.instantiate(ESObject.wrap(new A()))" + } + ], + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 1, + "endLine": 27, + "endColumn": 15, + "problem": "InstantiatedJsOjbect", + "autofix": [ + { + "start": 795, + "end": 809, + "replacementText": "Foo.instantiate(ESObject.wrap(a.num))" + } + ], + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 1, + "endLine": 28, + "endColumn": 11, + "problem": "InstantiatedJsOjbect", + "autofix": [ + { + "start": 810, + "end": 820, + "replacementText": "Foo.instantiate(ESObject.wrap(a))" + } + ], + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 1, + "endLine": 32, + "endColumn": 16, + "problem": "InstantiatedJsOjbect", + "autofix": [ + { + "start": 861, + "end": 876, + "replacementText": "Foo.instantiate(ESObject.wrap(test()))" + } + ], + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 1, + "endLine": 33, + "endColumn": 23, + "problem": "InstantiatedJsOjbect", + "autofix": [ + { + "start": 877, + "end": 899, + "replacementText": "Foo1.instantiate(ESObject.wrap(123), ESObject.wrap('hello'))" + } + ], + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/instantiated_js_obj.ets.json b/ets2panda/linter/test/interop/instantiated_js_obj.ets.json new file mode 100644 index 0000000000..ad8f5eb1ae --- /dev/null +++ b/ets2panda/linter/test/interop/instantiated_js_obj.ets.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 51, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/instantiated_js_obj_js.js b/ets2panda/linter/test/interop/instantiated_js_obj_js.js new file mode 100644 index 0000000000..76d9721f90 --- /dev/null +++ b/ets2panda/linter/test/interop/instantiated_js_obj_js.js @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export class Foo { + constructor(a) {} +} + +export class Foo1 { + constructor(a, b) {} +} \ No newline at end of file -- Gitee From 1f296388abbe3008fd92aa6a17cb874d41845846 Mon Sep 17 00:00:00 2001 From: zhongning Date: Thu, 10 Apr 2025 09:46:13 +0800 Subject: [PATCH 087/268] Check arkTS directly call JS methods Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBZWWG Test scenarios:ArkTS directly call JS methods Signed-off-by: zhongning --- ets2panda/linter/src/lib/CookBookMsg.ts | 1 + ets2panda/linter/src/lib/FaultAttrs.ts | 1 + ets2panda/linter/src/lib/FaultDesc.ts | 1 + ets2panda/linter/src/lib/Problems.ts | 1 + ets2panda/linter/src/lib/TypeScriptLinter.ts | 12 +++++ .../src/lib/utils/consts/ArkTS2Rules.ts | 3 +- .../test/interop/call_object_methods.ets | 19 +++++++ .../interop/call_object_methods.ets.args.json | 20 ++++++++ .../call_object_methods.ets.arkts2.json | 48 ++++++++++++++++++ .../call_object_methods.ets.autofix.json | 49 +++++++++++++++++++ .../test/interop/call_object_methods.ets.json | 28 +++++++++++ .../test/interop/call_object_methods_js.js | 20 ++++++++ 12 files changed, 202 insertions(+), 1 deletion(-) create mode 100644 ets2panda/linter/test/interop/call_object_methods.ets create mode 100644 ets2panda/linter/test/interop/call_object_methods.ets.args.json create mode 100644 ets2panda/linter/test/interop/call_object_methods.ets.arkts2.json create mode 100644 ets2panda/linter/test/interop/call_object_methods.ets.autofix.json create mode 100644 ets2panda/linter/test/interop/call_object_methods.ets.json create mode 100644 ets2panda/linter/test/interop/call_object_methods_js.js diff --git a/ets2panda/linter/src/lib/CookBookMsg.ts b/ets2panda/linter/src/lib/CookBookMsg.ts index da038cda83..8115daea27 100644 --- a/ets2panda/linter/src/lib/CookBookMsg.ts +++ b/ets2panda/linter/src/lib/CookBookMsg.ts @@ -304,3 +304,4 @@ cookBookTag[338] = cookBookTag[339] = 'Interop objects can\'t be indexed directly (arkts-no-js-index)'; cookBookTag[340] = '"Await" operator can\'t be used with interop objects (arkts-no-js-await)'; cookBookTag[341] = 'ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)'; +cookBookTag[342] = 'Calling methods of JS Object directly in interop is not allowed (arkts-interop-method-call)'; diff --git a/ets2panda/linter/src/lib/FaultAttrs.ts b/ets2panda/linter/src/lib/FaultAttrs.ts index ffbcb66e00..e9fde0162a 100644 --- a/ets2panda/linter/src/lib/FaultAttrs.ts +++ b/ets2panda/linter/src/lib/FaultAttrs.ts @@ -211,3 +211,4 @@ faultsAttrs[FaultID.InteropEqualityJudgment] = new FaultAttributes(338); faultsAttrs[FaultID.InterOpImportJsIndex] = new FaultAttributes(339); faultsAttrs[FaultID.NoJsImportAwait] = new FaultAttributes(340); faultsAttrs[FaultID.InstantiatedJsOjbect] = new FaultAttributes(341); +faultsAttrs[FaultID.InteropCallObjectMethods] = new FaultAttributes(342); diff --git a/ets2panda/linter/src/lib/FaultDesc.ts b/ets2panda/linter/src/lib/FaultDesc.ts index c85096c03c..470fb0ebe9 100644 --- a/ets2panda/linter/src/lib/FaultDesc.ts +++ b/ets2panda/linter/src/lib/FaultDesc.ts @@ -199,3 +199,4 @@ faultDesc[FaultID.InteropEqualityJudgment] = 'Equality operator with JS objects' faultDesc[FaultID.InterOpImportJsIndex] = 'No js index import'; faultDesc[FaultID.NoJsImportAwait] = 'No js import await'; faultDesc[FaultID.InstantiatedJsOjbect] = 'Instantiated js ojbect'; +faultDesc[FaultID.InteropCallObjectMethods] = 'Interop call methods in object'; diff --git a/ets2panda/linter/src/lib/Problems.ts b/ets2panda/linter/src/lib/Problems.ts index 5fb0e17785..b65f871e81 100644 --- a/ets2panda/linter/src/lib/Problems.ts +++ b/ets2panda/linter/src/lib/Problems.ts @@ -200,6 +200,7 @@ export enum FaultID { InterOpImportJsIndex, NoJsImportAwait, InstantiatedJsOjbect, + InteropCallObjectMethods, // this should always be last enum LAST_ID } diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index 719c65ea2a..1cbe8b7ec0 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -3434,6 +3434,7 @@ export class TypeScriptLinter { this.handleAppStorageCallExpression(tsCallExpr); this.fixJsImportCallExpression(tsCallExpr); this.handleCallJSFunction(tsCallExpr, calleeSym, callSignature); + this.handleInteropForCallObjectMethods(tsCallExpr, calleeSym, callSignature); } private handleAppStorageCallExpression(tsCallExpr: ts.CallExpression): void { @@ -3506,6 +3507,17 @@ export class TypeScriptLinter { this.checkForReflectAPIUse(callSignature, tsCallExpr); } + private handleInteropForCallObjectMethods(tsCallExpr: ts.CallExpression, sym: ts.Symbol | undefined, callSignature: ts.Signature | undefined): void { + if (!callSignature) { + return; + } + if (TypeScriptLinter.isDeclaredInArkTs2(callSignature) && this.options.arkts2) { + if (sym?.declarations?.[0]?.getSourceFile().fileName.endsWith(EXTNAME_JS)) { + this.incrementCounters(tsCallExpr, FaultID.InteropCallObjectMethods); + } + } + } + private static isDeclaredInArkTs2(callSignature: ts.Signature): boolean | undefined { const declarationSourceFile = callSignature?.declaration?.getSourceFile(); if (!declarationSourceFile) { diff --git a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts index 1b0cdcc27e..c9fefdd495 100644 --- a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts +++ b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts @@ -93,5 +93,6 @@ export const arkts2Rules: number[] = [ 338, 339, 340, - 341 + 341, + 342 ]; diff --git a/ets2panda/linter/test/interop/call_object_methods.ets b/ets2panda/linter/test/interop/call_object_methods.ets new file mode 100644 index 0000000000..f1aeeec2f2 --- /dev/null +++ b/ets2panda/linter/test/interop/call_object_methods.ets @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +'use static' +import { foo } from "./call_object_methods_js" + +foo.bar(123) + diff --git a/ets2panda/linter/test/interop/call_object_methods.ets.args.json b/ets2panda/linter/test/interop/call_object_methods.ets.args.json new file mode 100644 index 0000000000..70f3351f7e --- /dev/null +++ b/ets2panda/linter/test/interop/call_object_methods.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix":"--arkts-2" + } + } \ No newline at end of file diff --git a/ets2panda/linter/test/interop/call_object_methods.ets.arkts2.json b/ets2panda/linter/test/interop/call_object_methods.ets.arkts2.json new file mode 100644 index 0000000000..4f7f22e7ce --- /dev/null +++ b/ets2panda/linter/test/interop/call_object_methods.ets.arkts2.json @@ -0,0 +1,48 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 47, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 13, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 13, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-method-call)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/call_object_methods.ets.autofix.json b/ets2panda/linter/test/interop/call_object_methods.ets.autofix.json new file mode 100644 index 0000000000..96af20344f --- /dev/null +++ b/ets2panda/linter/test/interop/call_object_methods.ets.autofix.json @@ -0,0 +1,49 @@ + +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 47, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 13, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 13, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-method-call)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/call_object_methods.ets.json b/ets2panda/linter/test/interop/call_object_methods.ets.json new file mode 100644 index 0000000000..8866623ce5 --- /dev/null +++ b/ets2panda/linter/test/interop/call_object_methods.ets.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 47, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/call_object_methods_js.js b/ets2panda/linter/test/interop/call_object_methods_js.js new file mode 100644 index 0000000000..d1803ae0dd --- /dev/null +++ b/ets2panda/linter/test/interop/call_object_methods_js.js @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class Foo { + bar(a){ + } +} +export let foo = new Foo() \ No newline at end of file -- Gitee From ef32b24f733578632b85cdeb755820b47c0503cd Mon Sep 17 00:00:00 2001 From: ZhongNing Date: Wed, 26 Mar 2025 14:22:59 +0800 Subject: [PATCH 088/268] Add checks for arkts-no-import-obj-type Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBWF0V Test scenarios: new tests added to the linter Signed-off-by: ZhongNing --- ets2panda/linter/src/lib/CookBookMsg.ts | 1 + ets2panda/linter/src/lib/FaultAttrs.ts | 1 + ets2panda/linter/src/lib/FaultDesc.ts | 1 + ets2panda/linter/src/lib/Problems.ts | 1 + ets2panda/linter/src/lib/TypeScriptLinter.ts | 17 +++ ets2panda/linter/src/lib/utils/TsUtils.ts | 2 +- .../src/lib/utils/consts/ArkTS2Rules.ts | 3 +- .../linter/test/interop/no_js_instanceof.ets | 77 ++++++++++ .../interop/no_js_instanceof.ets.args.json | 19 +++ .../interop/no_js_instanceof.ets.arkts2.json | 138 ++++++++++++++++++ .../test/interop/no_js_instanceof.ets.json | 29 ++++ .../test/interop/no_js_instanceof_file.js | 44 ++++++ 12 files changed, 331 insertions(+), 2 deletions(-) create mode 100755 ets2panda/linter/test/interop/no_js_instanceof.ets create mode 100755 ets2panda/linter/test/interop/no_js_instanceof.ets.args.json create mode 100755 ets2panda/linter/test/interop/no_js_instanceof.ets.arkts2.json create mode 100755 ets2panda/linter/test/interop/no_js_instanceof.ets.json create mode 100755 ets2panda/linter/test/interop/no_js_instanceof_file.js diff --git a/ets2panda/linter/src/lib/CookBookMsg.ts b/ets2panda/linter/src/lib/CookBookMsg.ts index 8115daea27..d688ccbcde 100644 --- a/ets2panda/linter/src/lib/CookBookMsg.ts +++ b/ets2panda/linter/src/lib/CookBookMsg.ts @@ -305,3 +305,4 @@ cookBookTag[339] = 'Interop objects can\'t be indexed directly (arkts-no-js-inde cookBookTag[340] = '"Await" operator can\'t be used with interop objects (arkts-no-js-await)'; cookBookTag[341] = 'ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)'; cookBookTag[342] = 'Calling methods of JS Object directly in interop is not allowed (arkts-interop-method-call)'; +cookBookTag[343] = 'Usage of "instanceof" operator is not allowed with interop objects (arkts-no-js-instanceof)'; diff --git a/ets2panda/linter/src/lib/FaultAttrs.ts b/ets2panda/linter/src/lib/FaultAttrs.ts index e9fde0162a..696c2e55e7 100644 --- a/ets2panda/linter/src/lib/FaultAttrs.ts +++ b/ets2panda/linter/src/lib/FaultAttrs.ts @@ -212,3 +212,4 @@ faultsAttrs[FaultID.InterOpImportJsIndex] = new FaultAttributes(339); faultsAttrs[FaultID.NoJsImportAwait] = new FaultAttributes(340); faultsAttrs[FaultID.InstantiatedJsOjbect] = new FaultAttributes(341); faultsAttrs[FaultID.InteropCallObjectMethods] = new FaultAttributes(342); +faultsAttrs[FaultID.InteropJsInstanceof] = new FaultAttributes(343); diff --git a/ets2panda/linter/src/lib/FaultDesc.ts b/ets2panda/linter/src/lib/FaultDesc.ts index 470fb0ebe9..ec26251811 100644 --- a/ets2panda/linter/src/lib/FaultDesc.ts +++ b/ets2panda/linter/src/lib/FaultDesc.ts @@ -200,3 +200,4 @@ faultDesc[FaultID.InterOpImportJsIndex] = 'No js index import'; faultDesc[FaultID.NoJsImportAwait] = 'No js import await'; faultDesc[FaultID.InstantiatedJsOjbect] = 'Instantiated js ojbect'; faultDesc[FaultID.InteropCallObjectMethods] = 'Interop call methods in object'; +faultDesc[FaultID.InteropJsInstanceof] = 'Instanceof operator with interop'; diff --git a/ets2panda/linter/src/lib/Problems.ts b/ets2panda/linter/src/lib/Problems.ts index b65f871e81..9788ae01a1 100644 --- a/ets2panda/linter/src/lib/Problems.ts +++ b/ets2panda/linter/src/lib/Problems.ts @@ -201,6 +201,7 @@ export enum FaultID { NoJsImportAwait, InstantiatedJsOjbect, InteropCallObjectMethods, + InteropJsInstanceof, // this should always be last enum LAST_ID } diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index 1cbe8b7ec0..2183aa957f 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -1608,6 +1608,7 @@ export class TypeScriptLinter { break; case ts.SyntaxKind.InstanceOfKeyword: this.processBinaryInstanceOf(node, tsLhsExpr, leftOperandType); + this.handleInstanceOfExpression(tsBinaryExpr); break; case ts.SyntaxKind.InKeyword: this.incrementCounters(tsBinaryExpr.operatorToken, FaultID.InOperator); @@ -6335,4 +6336,20 @@ export class TypeScriptLinter { checkAndReportJsImportAwait(expr.expression); } } + + handleInstanceOfExpression(node: ts.BinaryExpression): void { + if (!this.options.arkts2 || !this.useStatic) { + return + }; + const left = node.left; + const right = node.right; + const getNode = (expr: ts.Expression): ts.Node => { + return ts.isPropertyAccessExpression(expr) || ts.isCallExpression(expr) ? expr.expression : expr + }; + const leftExpr = getNode(left); + const rightExpr = getNode(right); + if(this.tsUtils.isJsImport(leftExpr) || this.tsUtils.isJsImport(rightExpr)) { + this.incrementCounters(node, FaultID.InteropJsInstanceof); + } + } } diff --git a/ets2panda/linter/src/lib/utils/TsUtils.ts b/ets2panda/linter/src/lib/utils/TsUtils.ts index 02ce3f35cf..5ff5e88c80 100644 --- a/ets2panda/linter/src/lib/utils/TsUtils.ts +++ b/ets2panda/linter/src/lib/utils/TsUtils.ts @@ -3491,7 +3491,7 @@ export class TsUtils { return undefined; } - + static isArkts12File(sourceFile: ts.SourceFile): boolean { if (!sourceFile) { return false; diff --git a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts index c9fefdd495..700dab5972 100644 --- a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts +++ b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts @@ -94,5 +94,6 @@ export const arkts2Rules: number[] = [ 339, 340, 341, - 342 + 342, + 343 ]; diff --git a/ets2panda/linter/test/interop/no_js_instanceof.ets b/ets2panda/linter/test/interop/no_js_instanceof.ets new file mode 100755 index 0000000000..f3e57eeee8 --- /dev/null +++ b/ets2panda/linter/test/interop/no_js_instanceof.ets @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +'use static' + +import { Foo, foo, CreatePerson, a , b, MyNamespace } from "./no_js_instanceof_file.js" + +class Foo1 {} + +let foo1 = new Foo1() + +if(foo1 instanceof Foo1) { + +} + +if(foo instanceof Foo) { + +} + +if(foo1 instanceof Foo) { + +} + +if(foo instanceof Foo1) { + +} + +let person: CreatePerson = CreatePerson('xc', 18) + +if(person instanceof CreatePerson) { + +} + +function test1(): void { + if(person instanceof CreatePerson) { + + } +} + +const test2 = (): void => { + if(person instanceof CreatePerson) { + + } +} + +class Test3 { + init(): void { + if(person instanceof CreatePerson) { + + } + } +} + +if(a instanceof Array) { + +} + +if(b() instanceof Array) { + +} + +const myDog: MyNamespace.Dog = new MyNamespace.Dog('Buddy'); + +if (myDog instanceof MyNamespace.Dog) { + console.log("This is a Dog!"); +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/no_js_instanceof.ets.args.json b/ets2panda/linter/test/interop/no_js_instanceof.ets.args.json new file mode 100755 index 0000000000..3ef4496a81 --- /dev/null +++ b/ets2panda/linter/test/interop/no_js_instanceof.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} diff --git a/ets2panda/linter/test/interop/no_js_instanceof.ets.arkts2.json b/ets2panda/linter/test/interop/no_js_instanceof.ets.arkts2.json new file mode 100755 index 0000000000..e4b8a45960 --- /dev/null +++ b/ets2panda/linter/test/interop/no_js_instanceof.ets.arkts2.json @@ -0,0 +1,138 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 88, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 4, + "endLine": 27, + "endColumn": 22, + "problem": "InteropJsInstanceof", + "suggest": "", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-js-instanceof)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 4, + "endLine": 31, + "endColumn": 23, + "problem": "InteropJsInstanceof", + "suggest": "", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-js-instanceof)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 4, + "endLine": 35, + "endColumn": 23, + "problem": "InteropJsInstanceof", + "suggest": "", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-js-instanceof)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 4, + "endLine": 41, + "endColumn": 34, + "problem": "InteropJsInstanceof", + "suggest": "", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-js-instanceof)", + "severity": "ERROR" + }, + { + "line": 46, + "column": 8, + "endLine": 46, + "endColumn": 38, + "problem": "InteropJsInstanceof", + "suggest": "", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-js-instanceof)", + "severity": "ERROR" + }, + { + "line": 52, + "column": 8, + "endLine": 52, + "endColumn": 38, + "problem": "InteropJsInstanceof", + "suggest": "", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-js-instanceof)", + "severity": "ERROR" + }, + { + "line": 59, + "column": 12, + "endLine": 59, + "endColumn": 42, + "problem": "InteropJsInstanceof", + "suggest": "", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-js-instanceof)", + "severity": "ERROR" + }, + { + "line": 65, + "column": 4, + "endLine": 65, + "endColumn": 22, + "problem": "InteropJsInstanceof", + "suggest": "", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-js-instanceof)", + "severity": "ERROR" + }, + { + "line": 69, + "column": 4, + "endLine": 69, + "endColumn": 24, + "problem": "InteropJsInstanceof", + "suggest": "", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-js-instanceof)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 36, + "endLine": 73, + "endColumn": 51, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 75, + "column": 5, + "endLine": 75, + "endColumn": 37, + "problem": "InteropJsInstanceof", + "suggest": "", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-js-instanceof)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/no_js_instanceof.ets.json b/ets2panda/linter/test/interop/no_js_instanceof.ets.json new file mode 100755 index 0000000000..e6955adae6 --- /dev/null +++ b/ets2panda/linter/test/interop/no_js_instanceof.ets.json @@ -0,0 +1,29 @@ +{ + + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 88, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/no_js_instanceof_file.js b/ets2panda/linter/test/interop/no_js_instanceof_file.js new file mode 100755 index 0000000000..4e16bdf2a5 --- /dev/null +++ b/ets2panda/linter/test/interop/no_js_instanceof_file.js @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export class Foo{} +export let foo = new Foo() +export function CreatePerson(name, age) { + return { + name, + age, + greet() { + return `Hello, I'm ${this.name}`; + } + }; +} +export const a = [1,2,3] +export function b () { + return [1,2,3] +} +export class Animal {} +export class Dog extends Animal {} +export const MyNamespace = { + Animal: class { + constructor(name) { + this.name = name; + } + }, + Dog: class extends MyNamespace.Animal { + bark() { + return 'Woof!'; + } + } +}; \ No newline at end of file -- Gitee From b4c63ff4e71f3471d986bb19a088d8a331ecf955 Mon Sep 17 00:00:00 2001 From: ZhongNing Date: Wed, 16 Apr 2025 15:54:15 +0800 Subject: [PATCH 089/268] Add ArkTS1.2 Increment and decrement Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBWPTB Test scenarios: new tests added to the linter Signed-off-by: ZhongNing --- ets2panda/linter/src/lib/CookBookMsg.ts | 15 +- ets2panda/linter/src/lib/FaultAttrs.ts | 1 + ets2panda/linter/src/lib/FaultDesc.ts | 1 + ets2panda/linter/src/lib/Problems.ts | 1 + ets2panda/linter/src/lib/TypeScriptLinter.ts | 36 +- .../linter/src/lib/autofixes/AutofixTitles.ts | 2 + .../linter/src/lib/autofixes/Autofixer.ts | 30 +- .../src/lib/utils/consts/ArkTS2Rules.ts | 3 +- .../linter/src/lib/utils/consts/InteropAPI.ts | 4 + .../src/lib/utils/consts/SendableAPI.ts | 3 +- .../linter/src/lib/utils/consts/TsSuffix.ts | 2 - .../binary_operation_js_obj.ets.arkts2.json | 42 +- .../interop/call_function.ets.arkts2.json | 30 + .../call_object_methods.ets.arkts2.json | 22 +- .../call_object_methods.ets.autofix.json | 34 +- .../interop/increases_decreases_js_obj.ets | 21 + .../increases_decreases_js_obj.ets.args.json | 19 + ...increases_decreases_js_obj.ets.arkts2.json | 198 +++++ ...ncreases_decreases_js_obj.ets.autofix.json | 18 + .../increases_decreases_js_obj.ets.json | 28 + .../interop/increases_decreases_js_obj_js.js | 16 + .../instantiated_js_obj.ets.arkts2.json | 10 + .../instantiated_js_obj.ets.autofix.json | 22 + .../interop_convert_import.ets.arkts2.json | 32 +- .../interop_equality_judgment.ets.arkts2.json | 10 + ...interop_equality_judgment.ets.autofix.json | 22 + .../interop_import_js_compare.ets.arkts2.json | 52 +- .../interop_import_js_index.ets.arkts2.json | 50 +- .../interop_import_js_index.ets.autofix.json | 75 +- .../interop_import_js_rules.ets.arkts2.json | 334 +++++---- .../interop_import_js_rules.ets.autofix.json | 432 +++++------ .../interop_import_typeof_js.ets.arkts2.json | 520 +++++++++++++- .../interop_import_typeof_js.ets.autofix.json | 675 +++++++++++++++++- .../interop_not_have_property_arkts2.ets | 2 +- ...p_not_have_property_arkts2.ets.arkts2.json | 178 +++-- ..._not_have_property_arkts2.ets.autofix.json | 286 ++++++-- .../interop_not_have_property_arkts2.ets.json | 20 +- ..._js.js => interop_not_have_property_js.js} | 0 ...t_have_property_num_arkts2.ets.arkts2.json | 230 ++++-- ..._have_property_num_arkts2.ets.autofix.json | 354 +++++++-- ...erop_not_have_property_num_arkts2.ets.json | 20 +- .../test/interop/no_js_await.ets.arkts2.json | 128 ++-- .../interop/no_js_instanceof.ets.arkts2.json | 130 +++- 43 files changed, 3312 insertions(+), 796 deletions(-) create mode 100755 ets2panda/linter/test/interop/increases_decreases_js_obj.ets create mode 100755 ets2panda/linter/test/interop/increases_decreases_js_obj.ets.args.json create mode 100755 ets2panda/linter/test/interop/increases_decreases_js_obj.ets.arkts2.json create mode 100755 ets2panda/linter/test/interop/increases_decreases_js_obj.ets.autofix.json create mode 100755 ets2panda/linter/test/interop/increases_decreases_js_obj.ets.json create mode 100755 ets2panda/linter/test/interop/increases_decreases_js_obj_js.js rename ets2panda/linter/test/interop/{interop_import_js.js => interop_not_have_property_js.js} (100%) diff --git a/ets2panda/linter/src/lib/CookBookMsg.ts b/ets2panda/linter/src/lib/CookBookMsg.ts index d688ccbcde..5e1a4eaab7 100644 --- a/ets2panda/linter/src/lib/CookBookMsg.ts +++ b/ets2panda/linter/src/lib/CookBookMsg.ts @@ -16,7 +16,7 @@ export const cookBookMsg: string[] = []; export const cookBookTag: string[] = []; -for (let i = 0; i <= 320; i++) { +for (let i = 0; i <= 344; i++) { cookBookMsg[i] = ''; } @@ -293,16 +293,17 @@ cookBookTag[321] = 'Import Concurrency is not required (arkts-limited-stdlib-no- cookBookTag[330] = 'Importing directly from "JS" module is not supported (arkts-no-js-import)'; cookBookTag[331] = 'ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)'; cookBookTag[332] = 'Properties of interop objects can\'t be accessed directly (arkts-no-js-obj-property)'; -cookBookTag[333] = 'Casting interop JS objects to "number" type is not allowed (arkts-no-js-number-cast)' -cookBookTag[334] = 'The "typeof" expression can\'t be used with interop JS objects (arkts-interop-js-typeof)'; +cookBookTag[333] = 'Casting interop JS objects to "number" type is not allowed (arkts-no-js-number-import)' +cookBookTag[334] = 'The "typeof" expression can\'t be used with interop JS objects (arkts-interop-import-typeof-js)'; cookBookTag[335] = 'Interop object does not have property num (arkts-interop-does-not-have-num)'; cookBookTag[336] = 'Binary operations on js objects (arkts-no-js-obj-binary-operation)'; cookBookTag[337] = 'Importing data directly from the "JS" module for comparison is not supported (arkts-js-data-compare)'; cookBookTag[338] = '"JS" objects can\'t be used directly as operands of the equality operators (arkts-js-equality-judgment)'; -cookBookTag[339] = 'Interop objects can\'t be indexed directly (arkts-no-js-index)'; -cookBookTag[340] = '"Await" operator can\'t be used with interop objects (arkts-no-js-await)'; +cookBookTag[339] = 'Interop objects can\'t be indexed directly (arkts-no-js-index-import)'; +cookBookTag[340] = '"Await" operator can\'t be used with interop objects (arkts-no-import-await)'; cookBookTag[341] = 'ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)'; -cookBookTag[342] = 'Calling methods of JS Object directly in interop is not allowed (arkts-interop-method-call)'; -cookBookTag[343] = 'Usage of "instanceof" operator is not allowed with interop objects (arkts-no-js-instanceof)'; +cookBookTag[342] = 'Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)'; +cookBookTag[343] = 'Usage of "instanceof" operator is not allowed with interop objects (arkts-no-import-obj-type)'; +cookBookTag[344] = 'Interop objects can\'t be incremented or decremented (arkts-no-js-obj-increases-decreases)'; diff --git a/ets2panda/linter/src/lib/FaultAttrs.ts b/ets2panda/linter/src/lib/FaultAttrs.ts index 696c2e55e7..42628f67a1 100644 --- a/ets2panda/linter/src/lib/FaultAttrs.ts +++ b/ets2panda/linter/src/lib/FaultAttrs.ts @@ -213,3 +213,4 @@ faultsAttrs[FaultID.NoJsImportAwait] = new FaultAttributes(340); faultsAttrs[FaultID.InstantiatedJsOjbect] = new FaultAttributes(341); faultsAttrs[FaultID.InteropCallObjectMethods] = new FaultAttributes(342); faultsAttrs[FaultID.InteropJsInstanceof] = new FaultAttributes(343); +faultsAttrs[FaultID.InteropIncrementDecrement] = new FaultAttributes(344); diff --git a/ets2panda/linter/src/lib/FaultDesc.ts b/ets2panda/linter/src/lib/FaultDesc.ts index ec26251811..9257b62772 100644 --- a/ets2panda/linter/src/lib/FaultDesc.ts +++ b/ets2panda/linter/src/lib/FaultDesc.ts @@ -201,3 +201,4 @@ faultDesc[FaultID.NoJsImportAwait] = 'No js import await'; faultDesc[FaultID.InstantiatedJsOjbect] = 'Instantiated js ojbect'; faultDesc[FaultID.InteropCallObjectMethods] = 'Interop call methods in object'; faultDesc[FaultID.InteropJsInstanceof] = 'Instanceof operator with interop'; +faultDesc[FaultID.InteropIncrementDecrement] = 'Interop increment or decrement'; diff --git a/ets2panda/linter/src/lib/Problems.ts b/ets2panda/linter/src/lib/Problems.ts index 9788ae01a1..9b149207d4 100644 --- a/ets2panda/linter/src/lib/Problems.ts +++ b/ets2panda/linter/src/lib/Problems.ts @@ -202,6 +202,7 @@ export enum FaultID { InstantiatedJsOjbect, InteropCallObjectMethods, InteropJsInstanceof, + InteropIncrementDecrement, // this should always be last enum LAST_ID } diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index 2183aa957f..8320b83f34 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -293,7 +293,8 @@ export class TypeScriptLinter { [ts.SyntaxKind.TaggedTemplateExpression, this.handleTaggedTemplatesExpression], [ts.SyntaxKind.StructDeclaration, this.handleStructDeclaration], [ts.SyntaxKind.TypeOfExpression, this.handleInterOpImportJsOnTypeOfNode], - [ts.SyntaxKind.AwaitExpression, this.handleAwaitExpression] + [ts.SyntaxKind.AwaitExpression, this.handleAwaitExpression], + [ts.SyntaxKind.PostfixUnaryExpression, this.handlePostfixUnaryExpression] ]); private getLineAndCharacterOfNode(node: ts.Node | ts.CommentRange): ts.LineAndCharacter { @@ -1568,6 +1569,13 @@ export class TypeScriptLinter { } } } + + private handlePostfixUnaryExpression(node: ts.Node): void { + const unaryExpr = node as ts.PostfixUnaryExpression; + if (unaryExpr.operator === ts.SyntaxKind.PlusPlusToken || unaryExpr.operator === ts.SyntaxKind.MinusMinusToken) { + this.checkAutoIncrementDecrement(unaryExpr); + } + } private handlePrefixUnaryExpression(node: ts.Node): void { const tsUnaryArithm = node as ts.PrefixUnaryExpression; @@ -1590,6 +1598,12 @@ export class TypeScriptLinter { this.incrementCounters(node, FaultID.UnaryArithmNotNumber); } } + if ( + tsUnaryArithm.operator === ts.SyntaxKind.PlusPlusToken || + tsUnaryArithm.operator === ts.SyntaxKind.MinusMinusToken + ) { + this.checkAutoIncrementDecrement(tsUnaryArithm); + } } private handleBinaryExpression(node: ts.Node): void { @@ -1682,14 +1696,12 @@ export class TypeScriptLinter { private checkInteropEqualityJudgment(tsBinaryExpr: ts.BinaryExpression): void { if (this.useStatic && this.options.arkts2) { - const leftSym = this.tsUtils.trueSymbolAtLocation(tsBinaryExpr.left); - const rightSym = this.tsUtils.trueSymbolAtLocation(tsBinaryExpr.right); switch (tsBinaryExpr.operatorToken.kind) { case ts.SyntaxKind.EqualsEqualsToken: case ts.SyntaxKind.ExclamationEqualsToken: case ts.SyntaxKind.EqualsEqualsEqualsToken: case ts.SyntaxKind.ExclamationEqualsEqualsToken: - if (this.isJsType(leftSym) || this.isJsType(rightSym)) { + if (this.tsUtils.isJsImport(tsBinaryExpr.left) || this.tsUtils.isJsImport(tsBinaryExpr.right)) { const autofix = this.autofixer?.fixInteropEqualityOperator(tsBinaryExpr, tsBinaryExpr.operatorToken.kind); this.incrementCounters(tsBinaryExpr, FaultID.InteropEqualityJudgment, autofix); } @@ -1699,11 +1711,6 @@ export class TypeScriptLinter { } } - isJsType(sym: ts.Symbol | undefined): boolean { - void this; - return !!sym && !!sym.declarations && sym.declarations[0].getSourceFile().fileName.endsWith(EXTNAME_JS); - } - private handleTsInterop(nodeToCheck: ts.Node, handler: { (): void }): void { if (!this.options.arkts2) { return; @@ -6352,4 +6359,15 @@ export class TypeScriptLinter { this.incrementCounters(node, FaultID.InteropJsInstanceof); } } + + private checkAutoIncrementDecrement(unaryExpr: ts.PostfixUnaryExpression | ts.PrefixUnaryExpression): void { + if (ts.isPropertyAccessExpression(unaryExpr.operand)) { + const propertyAccess = unaryExpr.operand; + if (this.useStatic && this.options.arkts2) { + if (this.isFromJSModule(propertyAccess.expression)) { + this.incrementCounters(unaryExpr, FaultID.InteropIncrementDecrement); + } + } + } + } } diff --git a/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts b/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts index 7c807a1eb1..8d4c45bfd1 100644 --- a/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts +++ b/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts @@ -51,6 +51,8 @@ export const cookBookRefToFixTitle: Map = new Map([ [263, '"@Provide" annotation fixed'], [330, 'Convert import named objects from JS to ESObject'], [332, 'Using the ESObject interface to access properties'], + [334, 'Call typeOf function'], + [335, 'Call toNumber function to convert'], [338, 'Replace with library function call'], [339, 'Using \'ESObject\' interface call'], [341, 'Create JS objects using instantite'] diff --git a/ets2panda/linter/src/lib/autofixes/Autofixer.ts b/ets2panda/linter/src/lib/autofixes/Autofixer.ts index bd52afcca0..0c3ef9778e 100644 --- a/ets2panda/linter/src/lib/autofixes/Autofixer.ts +++ b/ets2panda/linter/src/lib/autofixes/Autofixer.ts @@ -43,8 +43,18 @@ import { PROVIDE_ALLOW_OVERRIDE_PROPERTY_NAME } from '../utils/consts/ArkuiConstants'; import { ES_OBJECT } from '../utils/consts/ESObject'; -import { LOAD, GET_PROPERTY_BY_NAME, ARE_EQUAL, ARE_STRICTLY_EQUAL } from '../utils/consts/InteropAPI'; -import { WRAP, INSTANTIATE } from '../utils/consts/InteropAPI'; +import { + LOAD, + GET_PROPERTY_BY_NAME, + SET_PROPERTY_BY_NAME, + GET_PROPERTY_BY_INDEX, + SET_PROPERTY_BY_INDEX, + ARE_EQUAL, + ARE_STRICTLY_EQUAL, + WRAP, + INSTANTIATE, + TO_NUMBER +} from '../utils/consts/InteropAPI'; const UNDEFINED_NAME = 'undefined'; @@ -3339,7 +3349,7 @@ export class Autofixer { fixInteropPropertyAccessExpression(express: ts.PropertyAccessExpression): Autofix[] | undefined { let text: string = ''; const statements = ts.factory.createCallExpression( - ts.factory.createPropertyAccessExpression(express.expression, ts.factory.createIdentifier('getPropertyByName')), + ts.factory.createPropertyAccessExpression(express.expression, ts.factory.createIdentifier(GET_PROPERTY_BY_NAME)), undefined, [ts.factory.createStringLiteral(express.name.getText())] ); @@ -3361,7 +3371,7 @@ export class Autofixer { const statements = ts.factory.createCallExpression( ts.factory.createPropertyAccessExpression( ts.factory.createIdentifier(objectName), - ts.factory.createIdentifier('setPropertyByName') + ts.factory.createIdentifier(SET_PROPERTY_BY_NAME) ), undefined, [ @@ -3369,7 +3379,7 @@ export class Autofixer { ts.factory.createCallExpression( ts.factory.createPropertyAccessExpression( ts.factory.createIdentifier(ES_OBJECT), - ts.factory.createIdentifier('wrap') + ts.factory.createIdentifier(WRAP) ), undefined, [ts.factory.createIdentifier(right.getText())] @@ -3382,7 +3392,7 @@ export class Autofixer { fixInteropArrayElementAccessExpression(express: ts.ElementAccessExpression): Autofix[] | undefined { const statements = ts.factory.createCallExpression( - ts.factory.createPropertyAccessExpression(express.expression, ts.factory.createIdentifier('getPropertyByIndex')), + ts.factory.createPropertyAccessExpression(express.expression, ts.factory.createIdentifier(GET_PROPERTY_BY_INDEX)), undefined, [express.argumentExpression] ); @@ -3396,7 +3406,7 @@ export class Autofixer { const statements = ts.factory.createCallExpression( ts.factory.createPropertyAccessExpression( ts.factory.createIdentifier(left.expression.getText()), - ts.factory.createIdentifier('setPropertyByIndex') + ts.factory.createIdentifier(SET_PROPERTY_BY_INDEX) ), undefined, [ @@ -3404,7 +3414,7 @@ export class Autofixer { ts.factory.createCallExpression( ts.factory.createPropertyAccessExpression( ts.factory.createIdentifier(ES_OBJECT), - ts.factory.createIdentifier('wrap') + ts.factory.createIdentifier(WRAP) ), undefined, [ts.factory.createIdentifier(right.getText())] @@ -3432,12 +3442,12 @@ export class Autofixer { ts.factory.createCallExpression( ts.factory.createPropertyAccessExpression( ts.factory.createIdentifier(express.operand.expression.getText()), - ts.factory.createIdentifier('getPropertyByName') + ts.factory.createIdentifier(GET_PROPERTY_BY_NAME) ), undefined, [ts.factory.createStringLiteral(express.operand.name.getText())] ), - ts.factory.createIdentifier('toNumber') + ts.factory.createIdentifier(TO_NUMBER) ), undefined, [] diff --git a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts index 700dab5972..14327f018d 100644 --- a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts +++ b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts @@ -95,5 +95,6 @@ export const arkts2Rules: number[] = [ 340, 341, 342, - 343 + 343, + 344 ]; diff --git a/ets2panda/linter/src/lib/utils/consts/InteropAPI.ts b/ets2panda/linter/src/lib/utils/consts/InteropAPI.ts index 678b6aa37c..8602c17262 100644 --- a/ets2panda/linter/src/lib/utils/consts/InteropAPI.ts +++ b/ets2panda/linter/src/lib/utils/consts/InteropAPI.ts @@ -36,3 +36,7 @@ export const REFLECT_PROPERTIES = [ ]; export const LOAD = 'load'; export const GET_PROPERTY_BY_NAME = 'getPropertyByName'; +export const SET_PROPERTY_BY_NAME = 'setPropertyByName'; +export const GET_PROPERTY_BY_INDEX = 'getPropertyByIndex'; +export const SET_PROPERTY_BY_INDEX = 'setPropertyByIndex'; +export const TO_NUMBER = 'toNumber'; \ No newline at end of file diff --git a/ets2panda/linter/src/lib/utils/consts/SendableAPI.ts b/ets2panda/linter/src/lib/utils/consts/SendableAPI.ts index ddeb2975fa..15a69be6ba 100644 --- a/ets2panda/linter/src/lib/utils/consts/SendableAPI.ts +++ b/ets2panda/linter/src/lib/utils/consts/SendableAPI.ts @@ -27,5 +27,4 @@ export const SENDABLE_DECORATOR_NODES = [ export const SENDABLE_CLOSURE_DECLS = [ts.SyntaxKind.ClassDeclaration, ts.SyntaxKind.FunctionDeclaration]; export const SENDBALE_FUNCTION_START_VERSION = 12; -export const SENDABLE_FUNCTION_UNSUPPORTED_STAGES_IN_API12 = ['beta1', 'beta2']; -export const ISINSTANCEOF = 'isInstanceOf'; +export const SENDABLE_FUNCTION_UNSUPPORTED_STAGES_IN_API12 = ['beta1', 'beta2']; \ No newline at end of file diff --git a/ets2panda/linter/src/lib/utils/consts/TsSuffix.ts b/ets2panda/linter/src/lib/utils/consts/TsSuffix.ts index de424368df..f2eff5a93a 100644 --- a/ets2panda/linter/src/lib/utils/consts/TsSuffix.ts +++ b/ets2panda/linter/src/lib/utils/consts/TsSuffix.ts @@ -17,5 +17,3 @@ export const KIT = '@kit'; export const D_ETS = '.d.ets'; export const D_TS = '.d.ts'; export const ETS = '.ets'; -export const JS = '.js'; -export const TS = '.ts'; diff --git a/ets2panda/linter/test/interop/binary_operation_js_obj.ets.arkts2.json b/ets2panda/linter/test/interop/binary_operation_js_obj.ets.arkts2.json index 1261b93913..b47ee3c9b5 100755 --- a/ets2panda/linter/test/interop/binary_operation_js_obj.ets.arkts2.json +++ b/ets2panda/linter/test/interop/binary_operation_js_obj.ets.arkts2.json @@ -24,14 +24,34 @@ "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", "severity": "ERROR" }, + { + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 49, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 9, + "endLine": 17, + "endColumn": 14, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, { "line": 17, - "column": 5, + "column": 9, "endLine": 17, "endColumn": 14, - "problem": "NumericSemantics", + "problem": "InteropJsObjectUsage", "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", "severity": "ERROR" }, { @@ -46,12 +66,22 @@ }, { "line": 18, - "column": 5, + "column": 9, + "endLine": 18, + "endColumn": 14, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 9, "endLine": 18, "endColumn": 14, - "problem": "NumericSemantics", + "problem": "InteropJsObjectUsage", "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", "severity": "ERROR" }, { diff --git a/ets2panda/linter/test/interop/call_function.ets.arkts2.json b/ets2panda/linter/test/interop/call_function.ets.arkts2.json index fe84731cc8..64199c1b99 100644 --- a/ets2panda/linter/test/interop/call_function.ets.arkts2.json +++ b/ets2panda/linter/test/interop/call_function.ets.arkts2.json @@ -24,6 +24,16 @@ "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", "severity": "ERROR" }, + { + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 43, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, { "line": 18, "column": 1, @@ -44,6 +54,16 @@ "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", "severity": "ERROR" }, + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 6, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "severity": "ERROR" + }, { "line": 19, "column": 1, @@ -63,6 +83,16 @@ "suggest": "", "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 9, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/interop/call_object_methods.ets.arkts2.json b/ets2panda/linter/test/interop/call_object_methods.ets.arkts2.json index 4f7f22e7ce..c80f4a095b 100644 --- a/ets2panda/linter/test/interop/call_object_methods.ets.arkts2.json +++ b/ets2panda/linter/test/interop/call_object_methods.ets.arkts2.json @@ -24,6 +24,16 @@ "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", "severity": "ERROR" }, + { + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 47, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, { "line": 18, "column": 1, @@ -34,6 +44,16 @@ "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", "severity": "ERROR" }, + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 13, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + }, { "line": 18, "column": 1, @@ -41,7 +61,7 @@ "endColumn": 13, "problem": "InteropCallObjectMethods", "suggest": "", - "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-method-call)", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/interop/call_object_methods.ets.autofix.json b/ets2panda/linter/test/interop/call_object_methods.ets.autofix.json index 96af20344f..75701bd0cf 100644 --- a/ets2panda/linter/test/interop/call_object_methods.ets.autofix.json +++ b/ets2panda/linter/test/interop/call_object_methods.ets.autofix.json @@ -25,6 +25,28 @@ "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", "severity": "ERROR" }, + { + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 47, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 632, + "end": 678, + "replacementText": "" + }, + { + "start": 678, + "end": 678, + "replacementText": "let GeneratedImportVar_1 = ESObject.load('./call_object_methods_js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');" + } + ], + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, { "line": 18, "column": 1, @@ -35,6 +57,16 @@ "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", "severity": "ERROR" }, + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 13, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + }, { "line": 18, "column": 1, @@ -42,7 +74,7 @@ "endColumn": 13, "problem": "InteropCallObjectMethods", "suggest": "", - "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-method-call)", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/interop/increases_decreases_js_obj.ets b/ets2panda/linter/test/interop/increases_decreases_js_obj.ets new file mode 100755 index 0000000000..e1d4d726e4 --- /dev/null +++ b/ets2panda/linter/test/interop/increases_decreases_js_obj.ets @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +'use static' +import {foo} from "./increases_decreases_js_obj_js" +let a: number =0 +a = foo.num++ +a = ++foo.num +a = foo.num-- +a = --foo.num diff --git a/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.args.json b/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.args.json new file mode 100755 index 0000000000..64b4d19108 --- /dev/null +++ b/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} diff --git a/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.arkts2.json b/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.arkts2.json new file mode 100755 index 0000000000..7b34fd236b --- /dev/null +++ b/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.arkts2.json @@ -0,0 +1,198 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 52, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 52, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 5, + "endLine": 18, + "endColumn": 14, + "problem": "InteropIncrementDecrement", + "suggest": "", + "rule": "Interop objects can't be incremented or decremented (arkts-no-js-obj-increases-decreases)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 5, + "endLine": 18, + "endColumn": 12, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 5, + "endLine": 18, + "endColumn": 12, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 5, + "endLine": 18, + "endColumn": 12, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 5, + "endLine": 19, + "endColumn": 14, + "problem": "InteropIncrementDecrement", + "suggest": "", + "rule": "Interop objects can't be incremented or decremented (arkts-no-js-obj-increases-decreases)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 7, + "endLine": 19, + "endColumn": 14, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 7, + "endLine": 19, + "endColumn": 14, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 7, + "endLine": 19, + "endColumn": 14, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 5, + "endLine": 20, + "endColumn": 14, + "problem": "InteropIncrementDecrement", + "suggest": "", + "rule": "Interop objects can't be incremented or decremented (arkts-no-js-obj-increases-decreases)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 5, + "endLine": 20, + "endColumn": 12, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 5, + "endLine": 20, + "endColumn": 12, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 5, + "endLine": 20, + "endColumn": 12, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 5, + "endLine": 21, + "endColumn": 14, + "problem": "InteropIncrementDecrement", + "suggest": "", + "rule": "Interop objects can't be incremented or decremented (arkts-no-js-obj-increases-decreases)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 7, + "endLine": 21, + "endColumn": 14, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 7, + "endLine": 21, + "endColumn": 14, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 7, + "endLine": 21, + "endColumn": 14, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.autofix.json b/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.autofix.json new file mode 100755 index 0000000000..895325b061 --- /dev/null +++ b/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.autofix.json @@ -0,0 +1,18 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.json b/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.json new file mode 100755 index 0000000000..cf493da1d6 --- /dev/null +++ b/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 52, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/increases_decreases_js_obj_js.js b/ets2panda/linter/test/interop/increases_decreases_js_obj_js.js new file mode 100755 index 0000000000..88eed7f647 --- /dev/null +++ b/ets2panda/linter/test/interop/increases_decreases_js_obj_js.js @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export let foo = {num: 0} diff --git a/ets2panda/linter/test/interop/instantiated_js_obj.ets.arkts2.json b/ets2panda/linter/test/interop/instantiated_js_obj.ets.arkts2.json index d3dee80079..ed6c8b7f73 100644 --- a/ets2panda/linter/test/interop/instantiated_js_obj.ets.arkts2.json +++ b/ets2panda/linter/test/interop/instantiated_js_obj.ets.arkts2.json @@ -24,6 +24,16 @@ "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", "severity": "ERROR" }, + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 51, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, { "line": 23, "column": 1, diff --git a/ets2panda/linter/test/interop/instantiated_js_obj.ets.autofix.json b/ets2panda/linter/test/interop/instantiated_js_obj.ets.autofix.json index 2e9335492b..d426879406 100644 --- a/ets2panda/linter/test/interop/instantiated_js_obj.ets.autofix.json +++ b/ets2panda/linter/test/interop/instantiated_js_obj.ets.autofix.json @@ -24,6 +24,28 @@ "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", "severity": "ERROR" }, + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 51, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 618, + "end": 668, + "replacementText": "" + }, + { + "start": 668, + "end": 668, + "replacementText": "let GeneratedImportVar_1 = ESObject.load('./instantiated_js_obj_js');\nlet Foo = GeneratedImportVar_1.getPropertyByName('Foo');\nlet Foo1 = GeneratedImportVar_1.getPropertyByName('Foo1');" + } + ], + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, { "line": 23, "column": 1, diff --git a/ets2panda/linter/test/interop/interop_convert_import.ets.arkts2.json b/ets2panda/linter/test/interop/interop_convert_import.ets.arkts2.json index 97ac686ac5..038f42ab25 100755 --- a/ets2panda/linter/test/interop/interop_convert_import.ets.arkts2.json +++ b/ets2panda/linter/test/interop/interop_convert_import.ets.arkts2.json @@ -24,6 +24,16 @@ "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", "severity": "ERROR" }, + { + "line": 17, + "column": 2, + "endLine": 17, + "endColumn": 52, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, { "line": 19, "column": 18, @@ -31,7 +41,27 @@ "endColumn": 35, "problem": "InterOpConvertImport", "suggest": "", - "rule": "Casting interop JS objects to \"number\" type is not allowed (arkts-no-js-number-cast)", + "rule": "Casting interop JS objects to \"number\" type is not allowed (arkts-no-js-number-import)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 18, + "endLine": 19, + "endColumn": 25, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 18, + "endLine": 19, + "endColumn": 25, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/interop/interop_equality_judgment.ets.arkts2.json b/ets2panda/linter/test/interop/interop_equality_judgment.ets.arkts2.json index c8f8b95ca9..5f133df9b9 100644 --- a/ets2panda/linter/test/interop/interop_equality_judgment.ets.arkts2.json +++ b/ets2panda/linter/test/interop/interop_equality_judgment.ets.arkts2.json @@ -24,6 +24,16 @@ "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", "severity": "ERROR" }, + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 52, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, { "line": 18, "column": 1, diff --git a/ets2panda/linter/test/interop/interop_equality_judgment.ets.autofix.json b/ets2panda/linter/test/interop/interop_equality_judgment.ets.autofix.json index 8224b628a6..cbfed6ea9e 100644 --- a/ets2panda/linter/test/interop/interop_equality_judgment.ets.autofix.json +++ b/ets2panda/linter/test/interop/interop_equality_judgment.ets.autofix.json @@ -24,6 +24,28 @@ "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", "severity": "ERROR" }, + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 52, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 618, + "end": 669, + "replacementText": "" + }, + { + "start": 669, + "end": 669, + "replacementText": "let GeneratedImportVar_1 = ESObject.load('./interop_equality_judgment_js');\nlet a = GeneratedImportVar_1.getPropertyByName('a');\nlet b = GeneratedImportVar_1.getPropertyByName('b');" + } + ], + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, { "line": 18, "column": 1, diff --git a/ets2panda/linter/test/interop/interop_import_js_compare.ets.arkts2.json b/ets2panda/linter/test/interop/interop_import_js_compare.ets.arkts2.json index a263cad034..db1438446c 100644 --- a/ets2panda/linter/test/interop/interop_import_js_compare.ets.arkts2.json +++ b/ets2panda/linter/test/interop/interop_import_js_compare.ets.arkts2.json @@ -36,22 +36,62 @@ }, { "line": 19, - "column": 5, + "column": 9, "endLine": 19, "endColumn": 14, - "problem": "NumericSemantics", + "problem": "InteropObjectProperty", "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 9, + "endLine": 19, + "endColumn": 14, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 9, + "endLine": 19, + "endColumn": 14, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", "severity": "ERROR" }, { "line": 20, - "column": 5, + "column": 9, "endLine": 20, "endColumn": 14, - "problem": "NumericSemantics", + "problem": "InteropObjectProperty", "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 9, + "endLine": 20, + "endColumn": 14, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 9, + "endLine": 20, + "endColumn": 14, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", "severity": "ERROR" }, { diff --git a/ets2panda/linter/test/interop/interop_import_js_index.ets.arkts2.json b/ets2panda/linter/test/interop/interop_import_js_index.ets.arkts2.json index 4c39084814..c8e9598d33 100644 --- a/ets2panda/linter/test/interop/interop_import_js_index.ets.arkts2.json +++ b/ets2panda/linter/test/interop/interop_import_js_index.ets.arkts2.json @@ -36,12 +36,42 @@ }, { "line": 18, - "column": 5, + "column": 11, "endLine": 18, "endColumn": 18, - "problem": "NumericSemantics", + "problem": "InteropObjectProperty", "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 11, + "endLine": 18, + "endColumn": 18, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 11, + "endLine": 18, + "endColumn": 18, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 7, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", "severity": "ERROR" }, { @@ -51,7 +81,17 @@ "endColumn": 7, "problem": "InterOpImportJsIndex", "suggest": "", - "rule": "Interop objects can't be indexed directly (arkts-no-js-index)", + "rule": "Interop objects can't be indexed directly (arkts-no-js-index-import)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 7, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", "severity": "ERROR" }, { @@ -61,7 +101,7 @@ "endColumn": 11, "problem": "InterOpImportJsIndex", "suggest": "", - "rule": "Interop objects can't be indexed directly (arkts-no-js-index)", + "rule": "Interop objects can't be indexed directly (arkts-no-js-index-import)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/interop/interop_import_js_index.ets.autofix.json b/ets2panda/linter/test/interop/interop_import_js_index.ets.autofix.json index 7ab1bffb06..9e8c533fc2 100644 --- a/ets2panda/linter/test/interop/interop_import_js_index.ets.autofix.json +++ b/ets2panda/linter/test/interop/interop_import_js_index.ets.autofix.json @@ -48,19 +48,63 @@ }, { "line": 18, - "column": 5, + "column": 11, "endLine": 18, "endColumn": 18, - "problem": "NumericSemantics", + "problem": "InteropObjectProperty", "autofix": [ { - "start": 672, + "start": 678, "end": 685, - "replacementText": "arr: number[] = foo.arr" + "replacementText": "foo.getPropertyByName(\"arr\")" } ], "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 11, + "endLine": 18, + "endColumn": 18, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "foo.getPropertyByName('arr')", + "start": 678, + "end": 685 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 11, + "endLine": 18, + "endColumn": 18, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 7, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "arr.getPropertyByIndex(1).toNumber()", + "start": 686, + "end": 692 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", "severity": "ERROR" }, { @@ -77,7 +121,24 @@ } ], "suggest": "", - "rule": "Interop objects can't be indexed directly (arkts-no-js-index)", + "rule": "Interop objects can't be indexed directly (arkts-no-js-index-import)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 7, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "arr.setPropertyByIndex(3, ESObject.wrap(4))", + "start": 693, + "end": 703 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", "severity": "ERROR" }, { @@ -94,7 +155,7 @@ } ], "suggest": "", - "rule": "Interop objects can't be indexed directly (arkts-no-js-index)", + "rule": "Interop objects can't be indexed directly (arkts-no-js-index-import)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/interop/interop_import_js_rules.ets.arkts2.json b/ets2panda/linter/test/interop/interop_import_js_rules.ets.arkts2.json index 06fc63cc77..aff72256ec 100644 --- a/ets2panda/linter/test/interop/interop_import_js_rules.ets.arkts2.json +++ b/ets2panda/linter/test/interop/interop_import_js_rules.ets.arkts2.json @@ -14,155 +14,185 @@ "limitations under the License." ], "result": [ - { - "line": 28, - "column": 5, - "endLine": 28, - "endColumn": 15, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 30, - "column": 5, - "endLine": 30, - "endColumn": 11, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 34, - "column": 1, - "endLine": 34, - "endColumn": 21, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 38, - "column": 1, - "endLine": 38, - "endColumn": 21, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 41, - "column": 3, - "endLine": 41, - "endColumn": 8, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 41, - "column": 3, - "endLine": 41, - "endColumn": 8, - "problem": "CallJSFunction", - "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", - "severity": "ERROR" - }, - { - "line": 46, - "column": 11, - "endLine": 46, - "endColumn": 18, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 47, - "column": 11, - "endLine": 47, - "endColumn": 21, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 48, - "column": 10, - "endLine": 48, - "endColumn": 15, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 49, - "column": 11, - "endLine": 49, - "endColumn": 17, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 50, - "column": 3, - "endLine": 50, - "endColumn": 9, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 60, - "column": 1, - "endLine": 60, - "endColumn": 13, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 60, - "column": 1, - "endLine": 60, - "endColumn": 13, - "problem": "CallJSFunction", - "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", - "severity": "ERROR" - }, - { - "line": 61, - "column": 1, - "endLine": 61, - "endColumn": 15, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 61, - "column": 1, - "endLine": 61, - "endColumn": 15, - "problem": "CallJSFunction", - "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", - "severity": "ERROR" - } - ] -} + { + "line": 28, + "column": 5, + "endLine": 28, + "endColumn": 15, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 5, + "endLine": 30, + "endColumn": 11, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 1, + "endLine": 34, + "endColumn": 21, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 1, + "endLine": 38, + "endColumn": 21, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 3, + "endLine": 41, + "endColumn": 8, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 3, + "endLine": 41, + "endColumn": 8, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 3, + "endLine": 41, + "endColumn": 8, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "severity": "ERROR" + }, + { + "line": 46, + "column": 11, + "endLine": 46, + "endColumn": 18, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 47, + "column": 11, + "endLine": 47, + "endColumn": 21, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 48, + "column": 10, + "endLine": 48, + "endColumn": 15, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 11, + "endLine": 49, + "endColumn": 17, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 50, + "column": 3, + "endLine": 50, + "endColumn": 9, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 60, + "column": 1, + "endLine": 60, + "endColumn": 13, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 60, + "column": 1, + "endLine": 60, + "endColumn": 13, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + }, + { + "line": 60, + "column": 1, + "endLine": 60, + "endColumn": 13, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 1, + "endLine": 61, + "endColumn": 15, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 1, + "endLine": 61, + "endColumn": 15, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 1, + "endLine": 61, + "endColumn": 15, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_import_js_rules.ets.autofix.json b/ets2panda/linter/test/interop/interop_import_js_rules.ets.autofix.json index 6378a926e0..bd63525409 100644 --- a/ets2panda/linter/test/interop/interop_import_js_rules.ets.autofix.json +++ b/ets2panda/linter/test/interop/interop_import_js_rules.ets.autofix.json @@ -14,204 +14,234 @@ "limitations under the License." ], "result": [ - { - "line": 28, - "column": 5, - "endLine": 28, - "endColumn": 15, - "problem": "InteropJsObjectUsage", - "autofix": [ - { - "replacementText": "foo.getPropertyByName('isGood').toBoolean()", - "start": 1031, - "end": 1041 - } - ], - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 30, - "column": 5, - "endLine": 30, - "endColumn": 11, - "problem": "InteropJsObjectUsage", - "autofix": [ - { - "replacementText": "ff1.getPropertyByName('f1').toNumber()", - "start": 1051, - "end": 1057 - } - ], - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 34, - "column": 1, - "endLine": 34, - "endColumn": 21, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 38, - "column": 1, - "endLine": 38, - "endColumn": 21, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 41, - "column": 3, - "endLine": 41, - "endColumn": 8, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 41, - "column": 3, - "endLine": 41, - "endColumn": 8, - "problem": "CallJSFunction", - "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", - "severity": "ERROR" - }, - { - "line": 46, - "column": 11, - "endLine": 46, - "endColumn": 18, - "problem": "InteropJsObjectUsage", - "autofix": [ - { - "replacementText": "ff3.getPropertyByName('arr')", - "start": 1277, - "end": 1284 - } - ], - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 47, - "column": 11, - "endLine": 47, - "endColumn": 21, - "problem": "InteropJsObjectUsage", - "autofix": [ - { - "replacementText": "arr.getPropertyByName('length').toNumber()", - "start": 1295, - "end": 1315 - } - ], - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 48, - "column": 10, - "endLine": 48, - "endColumn": 15, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 1325, - "end": 1330, - "replacementText": "i: number = 0" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 49, - "column": 11, - "endLine": 49, - "endColumn": 17, - "problem": "InteropJsObjectUsage", - "autofix": [ - { - "replacementText": "arr.getPropertyByIndex(i).toNumber()", - "start": 1358, - "end": 1364 - } - ], - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 50, - "column": 3, - "endLine": 50, - "endColumn": 9, - "problem": "InteropJsObjectUsage", - "autofix": [ - { - "replacementText": "arr.setPropertyByIndex(i, ESObject.wrap(0))", - "start": 1367, - "end": 1377 - } - ], - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 60, - "column": 1, - "endLine": 60, - "endColumn": 13, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 60, - "column": 1, - "endLine": 60, - "endColumn": 13, - "problem": "CallJSFunction", - "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", - "severity": "ERROR" - }, - { - "line": 61, - "column": 1, - "endLine": 61, - "endColumn": 15, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 61, - "column": 1, - "endLine": 61, - "endColumn": 15, - "problem": "CallJSFunction", - "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", - "severity": "ERROR" - } - ] -} + { + "line": 28, + "column": 5, + "endLine": 28, + "endColumn": 15, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "foo.getPropertyByName('isGood').toBoolean()", + "start": 1031, + "end": 1041 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 5, + "endLine": 30, + "endColumn": 11, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "ff1.getPropertyByName('f1').toNumber()", + "start": 1051, + "end": 1057 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 1, + "endLine": 34, + "endColumn": 21, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 1, + "endLine": 38, + "endColumn": 21, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 3, + "endLine": 41, + "endColumn": 8, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 3, + "endLine": 41, + "endColumn": 8, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 3, + "endLine": 41, + "endColumn": 8, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "severity": "ERROR" + }, + { + "line": 46, + "column": 11, + "endLine": 46, + "endColumn": 18, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "ff3.getPropertyByName('arr')", + "start": 1277, + "end": 1284 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 47, + "column": 11, + "endLine": 47, + "endColumn": 21, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "arr.getPropertyByName('length').toNumber()", + "start": 1295, + "end": 1315 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 48, + "column": 10, + "endLine": 48, + "endColumn": 15, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1325, + "end": 1330, + "replacementText": "i: number = 0" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 11, + "endLine": 49, + "endColumn": 17, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "arr.getPropertyByIndex(i).toNumber()", + "start": 1358, + "end": 1364 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 50, + "column": 3, + "endLine": 50, + "endColumn": 9, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "arr.setPropertyByIndex(i, ESObject.wrap(0))", + "start": 1367, + "end": 1377 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 60, + "column": 1, + "endLine": 60, + "endColumn": 13, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 60, + "column": 1, + "endLine": 60, + "endColumn": 13, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + }, + { + "line": 60, + "column": 1, + "endLine": 60, + "endColumn": 13, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 1, + "endLine": 61, + "endColumn": 15, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 1, + "endLine": 61, + "endColumn": 15, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 1, + "endLine": 61, + "endColumn": 15, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_import_typeof_js.ets.arkts2.json b/ets2panda/linter/test/interop/interop_import_typeof_js.ets.arkts2.json index 549a79b5f4..dbe38c107a 100755 --- a/ets2panda/linter/test/interop/interop_import_typeof_js.ets.arkts2.json +++ b/ets2panda/linter/test/interop/interop_import_typeof_js.ets.arkts2.json @@ -24,6 +24,16 @@ "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", "severity": "ERROR" }, + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 69, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, { "line": 18, "column": 1, @@ -34,6 +44,16 @@ "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", "severity": "ERROR" }, + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 54, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, { "line": 19, "column": 1, @@ -44,6 +64,16 @@ "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", "severity": "ERROR" }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 55, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, { "line": 21, "column": 1, @@ -51,7 +81,67 @@ "endColumn": 15, "problem": "InterOpImportJsForTypeOf", "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 8, + "endLine": 21, + "endColumn": 15, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 8, + "endLine": 21, + "endColumn": 15, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 8, + "endLine": 21, + "endColumn": 15, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 11, + "endLine": 22, + "endColumn": 18, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 11, + "endLine": 22, + "endColumn": 18, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 11, + "endLine": 22, + "endColumn": 18, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", "severity": "ERROR" }, { @@ -61,7 +151,7 @@ "endColumn": 11, "problem": "InterOpImportJsForTypeOf", "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", "severity": "ERROR" }, { @@ -71,7 +161,7 @@ "endColumn": 19, "problem": "InterOpImportJsForTypeOf", "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", "severity": "ERROR" }, { @@ -84,6 +174,36 @@ "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", "severity": "ERROR" }, + { + "line": 25, + "column": 8, + "endLine": 25, + "endColumn": 19, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 8, + "endLine": 25, + "endColumn": 19, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 8, + "endLine": 25, + "endColumn": 19, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "severity": "ERROR" + }, { "line": 26, "column": 1, @@ -91,7 +211,7 @@ "endColumn": 20, "problem": "InterOpImportJsForTypeOf", "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", "severity": "ERROR" }, { @@ -104,6 +224,36 @@ "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", "severity": "ERROR" }, + { + "line": 26, + "column": 8, + "endLine": 26, + "endColumn": 20, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 8, + "endLine": 26, + "endColumn": 20, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 8, + "endLine": 26, + "endColumn": 20, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "severity": "ERROR" + }, { "line": 27, "column": 1, @@ -111,7 +261,7 @@ "endColumn": 12, "problem": "InterOpImportJsForTypeOf", "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", "severity": "ERROR" }, { @@ -121,7 +271,37 @@ "endColumn": 17, "problem": "InterOpImportJsForTypeOf", "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 8, + "endLine": 28, + "endColumn": 17, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 8, + "endLine": 28, + "endColumn": 17, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 8, + "endLine": 28, + "endColumn": 17, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", "severity": "ERROR" }, { @@ -131,7 +311,47 @@ "endColumn": 12, "problem": "InterOpImportJsForTypeOf", "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 11, + "endLine": 30, + "endColumn": 20, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 11, + "endLine": 30, + "endColumn": 20, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 11, + "endLine": 30, + "endColumn": 20, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 23, + "endLine": 32, + "endColumn": 35, + "problem": "InstantiatedJsOjbect", + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", "severity": "ERROR" }, { @@ -141,7 +361,77 @@ "endColumn": 20, "problem": "InterOpImportJsForTypeOf", "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 8, + "endLine": 33, + "endColumn": 20, + "problem": "InstantiatedJsOjbect", + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 21, + "endLine": 35, + "endColumn": 33, + "problem": "InstantiatedJsOjbect", + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "severity": "ERROR" + }, + { + "line": 36, + "column": 11, + "endLine": 36, + "endColumn": 22, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 12, + "endLine": 37, + "endColumn": 28, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 12, + "endLine": 37, + "endColumn": 28, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "severity": "ERROR" + }, + { + "line": 40, + "column": 12, + "endLine": 40, + "endColumn": 28, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + }, + { + "line": 40, + "column": 12, + "endLine": 40, + "endColumn": 28, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", "severity": "ERROR" }, { @@ -154,6 +444,26 @@ "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", "severity": "ERROR" }, + { + "line": 43, + "column": 12, + "endLine": 43, + "endColumn": 30, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + }, + { + "line": 43, + "column": 12, + "endLine": 43, + "endColumn": 30, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "severity": "ERROR" + }, { "line": 45, "column": 5, @@ -161,7 +471,17 @@ "endColumn": 24, "problem": "InterOpImportJsForTypeOf", "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 12, + "endLine": 45, + "endColumn": 24, + "problem": "InstantiatedJsOjbect", + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", "severity": "ERROR" }, { @@ -174,6 +494,26 @@ "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", "severity": "ERROR" }, + { + "line": 48, + "column": 21, + "endLine": 48, + "endColumn": 39, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + }, + { + "line": 48, + "column": 21, + "endLine": 48, + "endColumn": 39, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "severity": "ERROR" + }, { "line": 50, "column": 7, @@ -191,7 +531,37 @@ "endColumn": 21, "problem": "InterOpImportJsForTypeOf", "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "severity": "ERROR" + }, + { + "line": 62, + "column": 12, + "endLine": 62, + "endColumn": 21, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 62, + "column": 12, + "endLine": 62, + "endColumn": 21, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 62, + "column": 12, + "endLine": 62, + "endColumn": 21, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", "severity": "ERROR" }, { @@ -201,7 +571,17 @@ "endColumn": 47, "problem": "InterOpImportJsForTypeOf", "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "severity": "ERROR" + }, + { + "line": 66, + "column": 35, + "endLine": 66, + "endColumn": 47, + "problem": "InstantiatedJsOjbect", + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", "severity": "ERROR" }, { @@ -211,7 +591,7 @@ "endColumn": 13, "problem": "InterOpImportJsForTypeOf", "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", "severity": "ERROR" }, { @@ -221,7 +601,37 @@ "endColumn": 25, "problem": "InterOpImportJsForTypeOf", "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 8, + "endLine": 71, + "endColumn": 25, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 8, + "endLine": 71, + "endColumn": 25, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 8, + "endLine": 71, + "endColumn": 20, + "problem": "InstantiatedJsOjbect", + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", "severity": "ERROR" }, { @@ -231,7 +641,47 @@ "endColumn": 30, "problem": "InterOpImportJsForTypeOf", "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 8, + "endLine": 72, + "endColumn": 30, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 8, + "endLine": 72, + "endColumn": 30, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 8, + "endLine": 72, + "endColumn": 30, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 8, + "endLine": 72, + "endColumn": 20, + "problem": "InstantiatedJsOjbect", + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", "severity": "ERROR" }, { @@ -241,7 +691,7 @@ "endColumn": 31, "problem": "InterOpImportJsForTypeOf", "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", "severity": "ERROR" }, { @@ -253,6 +703,46 @@ "suggest": "", "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", "severity": "ERROR" + }, + { + "line": 73, + "column": 8, + "endLine": 73, + "endColumn": 31, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 8, + "endLine": 73, + "endColumn": 31, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 8, + "endLine": 73, + "endColumn": 31, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 8, + "endLine": 73, + "endColumn": 20, + "problem": "InstantiatedJsOjbect", + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_import_typeof_js.ets.autofix.json b/ets2panda/linter/test/interop/interop_import_typeof_js.ets.autofix.json index c786032f72..b362958715 100755 --- a/ets2panda/linter/test/interop/interop_import_typeof_js.ets.autofix.json +++ b/ets2panda/linter/test/interop/interop_import_typeof_js.ets.autofix.json @@ -24,6 +24,28 @@ "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", "severity": "ERROR" }, + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 69, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 619, + "end": 687, + "replacementText": "" + }, + { + "start": 796, + "end": 796, + "replacementText": "let GeneratedImportVar_1 = ESObject.load('./interop_import_js_js');\nlet myAaa = GeneratedImportVar_1.getPropertyByName('aaa');\nlet ClassA = GeneratedImportVar_1.getPropertyByName('ClassA');\nlet Dog = GeneratedImportVar_1.getPropertyByName('Dog');\nlet Person = GeneratedImportVar_1.getPropertyByName('Person');\nlet Wiki = GeneratedImportVar_1.getPropertyByName('Wiki');" + } + ], + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, { "line": 18, "column": 1, @@ -34,6 +56,28 @@ "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", "severity": "ERROR" }, + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 54, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 688, + "end": 741, + "replacementText": "" + }, + { + "start": 796, + "end": 796, + "replacementText": "let GeneratedImportVar_2 = ESObject.load('./interop_import_js_js');\nlet Doge = GeneratedImportVar_2.getPropertyByName('Dog');" + } + ], + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, { "line": 19, "column": 1, @@ -44,6 +88,28 @@ "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", "severity": "ERROR" }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 55, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 742, + "end": 796, + "replacementText": "" + }, + { + "start": 796, + "end": 796, + "replacementText": "let GeneratedImportVar_3 = ESObject.load('./interop_import_js_js');\nlet wiki = GeneratedImportVar_3.getPropertyByName('Wiki');" + } + ], + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, { "line": 21, "column": 1, @@ -58,7 +124,67 @@ } ], "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 8, + "endLine": 21, + "endColumn": 15, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 8, + "endLine": 21, + "endColumn": 15, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 8, + "endLine": 21, + "endColumn": 15, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 11, + "endLine": 22, + "endColumn": 18, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 11, + "endLine": 22, + "endColumn": 18, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 11, + "endLine": 22, + "endColumn": 18, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", "severity": "ERROR" }, { @@ -75,7 +201,7 @@ } ], "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", "severity": "ERROR" }, { @@ -92,7 +218,7 @@ } ], "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", "severity": "ERROR" }, { @@ -105,6 +231,36 @@ "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", "severity": "ERROR" }, + { + "line": 25, + "column": 8, + "endLine": 25, + "endColumn": 19, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 8, + "endLine": 25, + "endColumn": 19, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 8, + "endLine": 25, + "endColumn": 19, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "severity": "ERROR" + }, { "line": 26, "column": 1, @@ -119,7 +275,7 @@ } ], "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", "severity": "ERROR" }, { @@ -132,6 +288,36 @@ "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", "severity": "ERROR" }, + { + "line": 26, + "column": 8, + "endLine": 26, + "endColumn": 20, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 8, + "endLine": 26, + "endColumn": 20, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 8, + "endLine": 26, + "endColumn": 20, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "severity": "ERROR" + }, { "line": 27, "column": 1, @@ -146,7 +332,7 @@ } ], "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", "severity": "ERROR" }, { @@ -163,7 +349,51 @@ } ], "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 8, + "endLine": 28, + "endColumn": 17, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 957, + "end": 966, + "replacementText": "Wiki.getPropertyByName(\"name\")" + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 8, + "endLine": 28, + "endColumn": 17, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "Wiki.getPropertyByName('name').toString()", + "start": 957, + "end": 966 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 8, + "endLine": 28, + "endColumn": 17, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", "severity": "ERROR" }, { @@ -180,7 +410,68 @@ } ], "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 11, + "endLine": 30, + "endColumn": 20, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 1005, + "end": 1014, + "replacementText": "wiki.getPropertyByName(\"name\")" + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 11, + "endLine": 30, + "endColumn": 20, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "wiki.getPropertyByName('name').toString()", + "start": 1005, + "end": 1014 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 11, + "endLine": 30, + "endColumn": 20, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 23, + "endLine": 32, + "endColumn": 35, + "problem": "InstantiatedJsOjbect", + "autofix": [ + { + "start": 1049, + "end": 1061, + "replacementText": "ClassA.instantiate()" + } + ], + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", "severity": "ERROR" }, { @@ -197,7 +488,98 @@ } ], "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 8, + "endLine": 33, + "endColumn": 20, + "problem": "InstantiatedJsOjbect", + "autofix": [ + { + "start": 1069, + "end": 1081, + "replacementText": "ClassA.instantiate()" + } + ], + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 21, + "endLine": 35, + "endColumn": 33, + "problem": "InstantiatedJsOjbect", + "autofix": [ + { + "start": 1125, + "end": 1137, + "replacementText": "Person.instantiate()" + } + ], + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "severity": "ERROR" + }, + { + "line": 36, + "column": 11, + "endLine": 36, + "endColumn": 22, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 1149, + "end": 1160, + "replacementText": "person.getPropertyByName(\"name\")" + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 12, + "endLine": 37, + "endColumn": 28, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 12, + "endLine": 37, + "endColumn": 28, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "severity": "ERROR" + }, + { + "line": 40, + "column": 12, + "endLine": 40, + "endColumn": 28, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + }, + { + "line": 40, + "column": 12, + "endLine": 40, + "endColumn": 28, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", "severity": "ERROR" }, { @@ -210,6 +592,26 @@ "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", "severity": "ERROR" }, + { + "line": 43, + "column": 12, + "endLine": 43, + "endColumn": 30, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + }, + { + "line": 43, + "column": 12, + "endLine": 43, + "endColumn": 30, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "severity": "ERROR" + }, { "line": 45, "column": 5, @@ -224,7 +626,24 @@ } ], "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 12, + "endLine": 45, + "endColumn": 24, + "problem": "InstantiatedJsOjbect", + "autofix": [ + { + "start": 1359, + "end": 1371, + "replacementText": "Person.instantiate()" + } + ], + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", "severity": "ERROR" }, { @@ -237,6 +656,26 @@ "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", "severity": "ERROR" }, + { + "line": 48, + "column": 21, + "endLine": 48, + "endColumn": 39, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + }, + { + "line": 48, + "column": 21, + "endLine": 48, + "endColumn": 39, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "severity": "ERROR" + }, { "line": 50, "column": 7, @@ -261,7 +700,51 @@ } ], "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "severity": "ERROR" + }, + { + "line": 62, + "column": 12, + "endLine": 62, + "endColumn": 21, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 1736, + "end": 1745, + "replacementText": "wiki.getPropertyByName(\"name\")" + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 62, + "column": 12, + "endLine": 62, + "endColumn": 21, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "wiki.getPropertyByName('name').toString()", + "start": 1736, + "end": 1745 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 62, + "column": 12, + "endLine": 62, + "endColumn": 21, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", "severity": "ERROR" }, { @@ -278,7 +761,24 @@ } ], "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "severity": "ERROR" + }, + { + "line": 66, + "column": 35, + "endLine": 66, + "endColumn": 47, + "problem": "InstantiatedJsOjbect", + "autofix": [ + { + "start": 1841, + "end": 1853, + "replacementText": "ClassA.instantiate()" + } + ], + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", "severity": "ERROR" }, { @@ -295,7 +795,7 @@ } ], "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", "severity": "ERROR" }, { @@ -312,7 +812,58 @@ } ], "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 8, + "endLine": 71, + "endColumn": 25, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 1903, + "end": 1920, + "replacementText": "new Person().getPropertyByName(\"name\")" + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 8, + "endLine": 71, + "endColumn": 25, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "new Person().getPropertyByName('name').toString()", + "start": 1903, + "end": 1920 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 8, + "endLine": 71, + "endColumn": 20, + "problem": "InstantiatedJsOjbect", + "autofix": [ + { + "start": 1903, + "end": 1915, + "replacementText": "Person.instantiate()" + } + ], + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", "severity": "ERROR" }, { @@ -329,7 +880,54 @@ } ], "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 8, + "endLine": 72, + "endColumn": 30, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 8, + "endLine": 72, + "endColumn": 30, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 8, + "endLine": 72, + "endColumn": 30, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 8, + "endLine": 72, + "endColumn": 20, + "problem": "InstantiatedJsOjbect", + "autofix": [ + { + "start": 1937, + "end": 1949, + "replacementText": "Person.instantiate()" + } + ], + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", "severity": "ERROR" }, { @@ -346,7 +944,7 @@ } ], "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js-typeof)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", "severity": "ERROR" }, { @@ -358,6 +956,53 @@ "suggest": "", "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", "severity": "ERROR" + }, + { + "line": 73, + "column": 8, + "endLine": 73, + "endColumn": 31, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 8, + "endLine": 73, + "endColumn": 31, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 8, + "endLine": 73, + "endColumn": 31, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 8, + "endLine": 73, + "endColumn": 20, + "problem": "InstantiatedJsOjbect", + "autofix": [ + { + "start": 1975, + "end": 1987, + "replacementText": "Person.instantiate()" + } + ], + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets b/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets index 072c3453aa..70554e5a8f 100755 --- a/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets +++ b/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets @@ -14,7 +14,7 @@ */ 'use static' -import {foo, person} from "./interop_import_js" +import {foo, person} from "./interop_not_have_property_js" foo.name foo.name = "456" diff --git a/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.arkts2.json b/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.arkts2.json index a276adba42..dbcf35243f 100755 --- a/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.arkts2.json +++ b/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.arkts2.json @@ -13,56 +13,146 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "result": [ - { - "line": 17, - "column": 1, - "endLine": 17, - "endColumn": 48, - "problem": "ImportAfterStatement", - "suggest": "", - "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", - "severity": "ERROR" - }, - { - "line": 19, - "column": 1, - "endLine": 19, - "endColumn": 9, - "problem": "InteropObjectProperty", - "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", - "severity": "ERROR" + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 59, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 59, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 9, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 9, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 9, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 17, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 9, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 9, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 16, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 11, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 11, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "severity": "ERROR" }, { - "line": 20, - "column": 1, - "endLine": 20, - "endColumn": 17, - "problem": "InteropObjectProperty", - "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", - "severity": "ERROR" + "line": 22, + "column": 1, + "endLine": 22, + "endColumn": 21, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" }, { - "line": 21, - "column": 1, - "endLine": 21, - "endColumn": 16, - "problem": "InteropObjectProperty", - "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", - "severity": "ERROR" + "line": 22, + "column": 1, + "endLine": 22, + "endColumn": 12, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" }, { - "line": 22, - "column": 1, - "endLine": 22, - "endColumn": 21, - "problem": "InteropObjectProperty", - "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", - "severity": "ERROR" + "line": 22, + "column": 1, + "endLine": 22, + "endColumn": 12, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.autofix.json b/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.autofix.json index 553491bcdd..3b827973a4 100755 --- a/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.autofix.json +++ b/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.autofix.json @@ -14,83 +14,213 @@ "limitations under the License." ], "result": [ - { - "line": 17, - "column": 1, - "endLine": 17, - "endColumn": 48, - "problem": "ImportAfterStatement", - "suggest": "", - "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", - "severity": "ERROR" - }, - { - "line": 19, - "column": 1, - "endLine": 19, - "endColumn": 9, - "problem": "InteropObjectProperty", - "autofix": [ - { - "start": 667, - "end": 675, - "replacementText": "foo.getPropertyByName(\"name\")" - } - ], - "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", - "severity": "ERROR" - }, - { - "line": 20, - "column": 1, - "endLine": 20, - "endColumn": 17, - "problem": "InteropObjectProperty", - "autofix": [ - { - "start": 676, - "end": 692, - "replacementText": "foo.setPropertyByName(\"name\", ESObject.wrap(\"456\"))" - } - ], - "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", - "severity": "ERROR" - }, - { - "line": 21, - "column": 1, - "endLine": 21, - "endColumn": 16, - "problem": "InteropObjectProperty", - "autofix": [ - { - "start": 693, - "end": 708, - "replacementText": "person.setPropertyByName(\"age\", ESObject.wrap(23))" - } - ], - "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", - "severity": "ERROR" - }, - { - "line": 22, - "column": 1, - "endLine": 22, - "endColumn": 21, - "problem": "InteropObjectProperty", - "autofix": [ - { - "start": 709, - "end": 729, - "replacementText": "person.setPropertyByName(\"male\", ESObject.wrap([2, 3]))" - } - ], - "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", - "severity": "ERROR" - } + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 59, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 59, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 618, + "end": 676, + "replacementText": "" + }, + { + "start": 676, + "end": 676, + "replacementText": "let GeneratedImportVar_1 = ESObject.load('./interop_not_have_property_js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');\nlet person = GeneratedImportVar_1.getPropertyByName('person');" + } + ], + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 9, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 678, + "end": 686, + "replacementText": "foo.getPropertyByName(\"name\")" + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 9, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "foo.getPropertyByName('name').toString()", + "start": 678, + "end": 686 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 9, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 17, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 687, + "end": 703, + "replacementText": "foo.setPropertyByName(\"name\", ESObject.wrap(\"456\"))" + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 9, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "foo.getPropertyByName('name').toString()", + "start": 687, + "end": 695 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 9, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 16, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 704, + "end": 719, + "replacementText": "person.setPropertyByName(\"age\", ESObject.wrap(23))" + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 11, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "person.getPropertyByName('age').toNumber()", + "start": 704, + "end": 714 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 11, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 1, + "endLine": 22, + "endColumn": 21, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 720, + "end": 740, + "replacementText": "person.setPropertyByName(\"male\", ESObject.wrap([2, 3]))" + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 1, + "endLine": 22, + "endColumn": 12, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "person.getPropertyByName('male')", + "start": 720, + "end": 731 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 1, + "endLine": 22, + "endColumn": 12, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "severity": "ERROR" + } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.json b/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.json index e5a73a02b4..838a0500a5 100755 --- a/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.json +++ b/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.json @@ -14,15 +14,15 @@ "limitations under the License." ], "result": [ - { - "line": 17, - "column": 1, - "endLine": 17, - "endColumn": 48, - "problem": "ImportAfterStatement", - "suggest": "", - "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", - "severity": "ERROR" - } + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 59, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_import_js.js b/ets2panda/linter/test/interop/interop_not_have_property_js.js similarity index 100% rename from ets2panda/linter/test/interop/interop_import_js.js rename to ets2panda/linter/test/interop/interop_not_have_property_js.js diff --git a/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.arkts2.json b/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.arkts2.json index 3f20f3b88d..91c86ce667 100755 --- a/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.arkts2.json +++ b/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.arkts2.json @@ -14,55 +14,185 @@ "limitations under the License." ], "result": [ - { - "line": 17, - "column": 1, - "endLine": 17, - "endColumn": 46, - "problem": "ImportAfterStatement", - "suggest": "", - "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", - "severity": "ERROR" - }, - { - "line": 19, - "column": 1, - "endLine": 19, - "endColumn": 9, - "problem": "InteropNoHaveNum", - "suggest": "", - "rule": "Interop object does not have property num (arkts-interop-does-not-have-num)", - "severity": "ERROR" - }, - { - "line": 20, - "column": 1, - "endLine": 20, - "endColumn": 9, - "problem": "InteropNoHaveNum", - "suggest": "", - "rule": "Interop object does not have property num (arkts-interop-does-not-have-num)", - "severity": "ERROR" - }, - { - "line": 21, - "column": 1, - "endLine": 21, - "endColumn": 9, - "problem": "InteropNoHaveNum", - "suggest": "", - "rule": "Interop object does not have property num (arkts-interop-does-not-have-num)", - "severity": "ERROR" - }, - { - "line": 22, - "column": 1, - "endLine": 22, - "endColumn": 9, - "problem": "InteropNoHaveNum", - "suggest": "", - "rule": "Interop object does not have property num (arkts-interop-does-not-have-num)", - "severity": "ERROR" - } + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 46, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 46, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 9, + "problem": "InteropNoHaveNum", + "suggest": "", + "rule": "Interop object does not have property num (arkts-interop-does-not-have-num)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 2, + "endLine": 19, + "endColumn": 9, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 2, + "endLine": 19, + "endColumn": 9, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 2, + "endLine": 19, + "endColumn": 9, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 9, + "problem": "InteropNoHaveNum", + "suggest": "", + "rule": "Interop object does not have property num (arkts-interop-does-not-have-num)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 2, + "endLine": 20, + "endColumn": 9, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 2, + "endLine": 20, + "endColumn": 9, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 2, + "endLine": 20, + "endColumn": 9, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 9, + "problem": "InteropNoHaveNum", + "suggest": "", + "rule": "Interop object does not have property num (arkts-interop-does-not-have-num)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 2, + "endLine": 21, + "endColumn": 9, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 2, + "endLine": 21, + "endColumn": 9, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 2, + "endLine": 21, + "endColumn": 9, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 1, + "endLine": 22, + "endColumn": 9, + "problem": "InteropNoHaveNum", + "suggest": "", + "rule": "Interop object does not have property num (arkts-interop-does-not-have-num)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 2, + "endLine": 22, + "endColumn": 9, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 2, + "endLine": 22, + "endColumn": 9, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 2, + "endLine": 22, + "endColumn": 9, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "severity": "ERROR" + } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.autofix.json b/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.autofix.json index a01a54b243..b52102f1f9 100755 --- a/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.autofix.json +++ b/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.autofix.json @@ -14,83 +14,281 @@ "limitations under the License." ], "result": [ - { - "line": 17, - "column": 1, - "endLine": 17, - "endColumn": 46, - "problem": "ImportAfterStatement", - "suggest": "", - "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", - "severity": "ERROR" - }, - { - "line": 19, - "column": 1, - "endLine": 19, - "endColumn": 9, - "problem": "InteropNoHaveNum", - "autofix": [ - { - "start": 666, - "end": 673, - "replacementText": "foo.getPropertyByName(\"num\").toNumber()" - } - ], - "suggest": "", - "rule": "Interop object does not have property num (arkts-interop-does-not-have-num)", - "severity": "ERROR" - }, - { - "line": 20, - "column": 1, - "endLine": 20, - "endColumn": 9, - "problem": "InteropNoHaveNum", - "autofix": [ - { - "start": 676, - "end": 683, - "replacementText": "foo.getPropertyByName(\"num\").toNumber()" - } - ], - "suggest": "", - "rule": "Interop object does not have property num (arkts-interop-does-not-have-num)", - "severity": "ERROR" - }, - { - "line": 21, - "column": 1, - "endLine": 21, - "endColumn": 9, - "problem": "InteropNoHaveNum", - "autofix": [ - { - "start": 686, - "end": 693, - "replacementText": "foo.getPropertyByName(\"num\").toNumber()" - } - ], - "suggest": "", - "rule": "Interop object does not have property num (arkts-interop-does-not-have-num)", - "severity": "ERROR" - }, - { - "line": 22, - "column": 1, - "endLine": 22, - "endColumn": 9, - "problem": "InteropNoHaveNum", - "autofix": [ - { - "start": 696, - "end": 703, - "replacementText": "foo.getPropertyByName(\"num\").toNumber()" - } - ], - "suggest": "", - "rule": "Interop object does not have property num (arkts-interop-does-not-have-num)", - "severity": "ERROR" - } + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 46, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 46, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 618, + "end": 663, + "replacementText": "" + }, + { + "start": 663, + "end": 663, + "replacementText": "let GeneratedImportVar_1 = ESObject.load('./interop_property_num_js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');" + } + ], + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 9, + "problem": "InteropNoHaveNum", + "autofix": [ + { + "start": 666, + "end": 673, + "replacementText": "foo.getPropertyByName(\"num\").toNumber()" + } + ], + "suggest": "", + "rule": "Interop object does not have property num (arkts-interop-does-not-have-num)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 2, + "endLine": 19, + "endColumn": 9, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 666, + "end": 673, + "replacementText": "foo.getPropertyByName(\"num\")" + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 2, + "endLine": 19, + "endColumn": 9, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "foo.getPropertyByName('num').toNumber()", + "start": 666, + "end": 673 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 2, + "endLine": 19, + "endColumn": 9, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 9, + "problem": "InteropNoHaveNum", + "autofix": [ + { + "start": 676, + "end": 683, + "replacementText": "foo.getPropertyByName(\"num\").toNumber()" + } + ], + "suggest": "", + "rule": "Interop object does not have property num (arkts-interop-does-not-have-num)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 2, + "endLine": 20, + "endColumn": 9, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 676, + "end": 683, + "replacementText": "foo.getPropertyByName(\"num\")" + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 2, + "endLine": 20, + "endColumn": 9, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "foo.getPropertyByName('num').toNumber()", + "start": 676, + "end": 683 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 2, + "endLine": 20, + "endColumn": 9, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 9, + "problem": "InteropNoHaveNum", + "autofix": [ + { + "start": 686, + "end": 693, + "replacementText": "foo.getPropertyByName(\"num\").toNumber()" + } + ], + "suggest": "", + "rule": "Interop object does not have property num (arkts-interop-does-not-have-num)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 2, + "endLine": 21, + "endColumn": 9, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 686, + "end": 693, + "replacementText": "foo.getPropertyByName(\"num\")" + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 2, + "endLine": 21, + "endColumn": 9, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "foo.getPropertyByName('num').toNumber()", + "start": 686, + "end": 693 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 2, + "endLine": 21, + "endColumn": 9, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 1, + "endLine": 22, + "endColumn": 9, + "problem": "InteropNoHaveNum", + "autofix": [ + { + "start": 696, + "end": 703, + "replacementText": "foo.getPropertyByName(\"num\").toNumber()" + } + ], + "suggest": "", + "rule": "Interop object does not have property num (arkts-interop-does-not-have-num)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 2, + "endLine": 22, + "endColumn": 9, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 696, + "end": 703, + "replacementText": "foo.getPropertyByName(\"num\")" + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 2, + "endLine": 22, + "endColumn": 9, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "foo.getPropertyByName('num').toNumber()", + "start": 696, + "end": 703 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 2, + "endLine": 22, + "endColumn": 9, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "severity": "ERROR" + } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.json b/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.json index 72da46b9de..456612d680 100755 --- a/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.json +++ b/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.json @@ -14,15 +14,15 @@ "limitations under the License." ], "result": [ - { - "line": 17, - "column": 1, - "endLine": 17, - "endColumn": 46, - "problem": "ImportAfterStatement", - "suggest": "", - "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", - "severity": "ERROR" - } + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 46, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/interop/no_js_await.ets.arkts2.json b/ets2panda/linter/test/interop/no_js_await.ets.arkts2.json index c6be12301f..7b4e605344 100755 --- a/ets2panda/linter/test/interop/no_js_await.ets.arkts2.json +++ b/ets2panda/linter/test/interop/no_js_await.ets.arkts2.json @@ -25,73 +25,73 @@ "severity": "ERROR" }, { - "line": 21, - "column": 10, - "endLine": 21, - "endColumn": 17, - "problem": "NoJsImportAwait", + "line": 20, + "column": 16, + "endLine": 20, + "endColumn": 28, + "problem": "LimitedReturnTypeInference", "suggest": "", - "rule": "ArkTS1.2 cannot import js files directly object is not Promise (arkts-no-import-await)", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", "severity": "ERROR" }, { - "line": 26, - "column": 10, - "endLine": 26, - "endColumn": 21, - "problem": "NoJsImportAwait", + "line": 25, + "column": 16, + "endLine": 25, + "endColumn": 33, + "problem": "LimitedReturnTypeInference", "suggest": "", - "rule": "ArkTS1.2 cannot import js files directly object is not Promise (arkts-no-import-await)", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", "severity": "ERROR" }, { - "line": 30, - "column": 10, - "endLine": 30, - "endColumn": 25, - "problem": "NoJsImportAwait", + "line": 29, + "column": 16, + "endLine": 29, + "endColumn": 31, + "problem": "LimitedReturnTypeInference", "suggest": "", - "rule": "ArkTS1.2 cannot import js files directly object is not Promise (arkts-no-import-await)", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", "severity": "ERROR" }, { - "line": 35, - "column": 10, - "endLine": 35, - "endColumn": 27, - "problem": "NoJsImportAwait", + "line": 34, + "column": 16, + "endLine": 34, + "endColumn": 30, + "problem": "LimitedReturnTypeInference", "suggest": "", - "rule": "ArkTS1.2 cannot import js files directly object is not Promise (arkts-no-import-await)", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", "severity": "ERROR" }, { - "line": 39, - "column": 10, - "endLine": 39, - "endColumn": 26, - "problem": "NoJsImportAwait", + "line": 38, + "column": 16, + "endLine": 38, + "endColumn": 32, + "problem": "LimitedReturnTypeInference", "suggest": "", - "rule": "ArkTS1.2 cannot import js files directly object is not Promise (arkts-no-import-await)", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", "severity": "ERROR" }, { - "line": 45, - "column": 12, - "endLine": 45, - "endColumn": 19, - "problem": "NoJsImportAwait", + "line": 44, + "column": 9, + "endLine": 44, + "endColumn": 20, + "problem": "LimitedReturnTypeInference", "suggest": "", - "rule": "ArkTS1.2 cannot import js files directly object is not Promise (arkts-no-import-await)", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", "severity": "ERROR" }, { - "line": 49, - "column": 12, - "endLine": 49, - "endColumn": 27, - "problem": "NoJsImportAwait", + "line": 48, + "column": 13, + "endLine": 50, + "endColumn": 4, + "problem": "LimitedReturnTypeInference", "suggest": "", - "rule": "ArkTS1.2 cannot import js files directly object is not Promise (arkts-no-import-await)", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", "severity": "ERROR" }, { @@ -115,23 +115,23 @@ "severity": "ERROR" }, { - "line": 56, - "column": 12, - "endLine": 56, - "endColumn": 28, - "problem": "NoJsImportAwait", + "line": 55, + "column": 9, + "endLine": 55, + "endColumn": 18, + "problem": "LimitedReturnTypeInference", "suggest": "", - "rule": "ArkTS1.2 cannot import js files directly object is not Promise (arkts-no-import-await)", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", "severity": "ERROR" }, { - "line": 60, - "column": 12, - "endLine": 60, - "endColumn": 23, - "problem": "NoJsImportAwait", + "line": 59, + "column": 17, + "endLine": 61, + "endColumn": 4, + "problem": "LimitedReturnTypeInference", "suggest": "", - "rule": "ArkTS1.2 cannot import js files directly object is not Promise (arkts-no-import-await)", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", "severity": "ERROR" }, { @@ -143,26 +143,6 @@ "suggest": "", "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", "severity": "ERROR" - }, - { - "line": 66, - "column": 31, - "endLine": 66, - "endColumn": 38, - "problem": "NoJsImportAwait", - "suggest": "", - "rule": "ArkTS1.2 cannot import js files directly object is not Promise (arkts-no-import-await)", - "severity": "ERROR" - }, - { - "line": 70, - "column": 37, - "endLine": 70, - "endColumn": 54, - "problem": "NoJsImportAwait", - "suggest": "", - "rule": "ArkTS1.2 cannot import js files directly object is not Promise (arkts-no-import-await)", - "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/interop/no_js_instanceof.ets.arkts2.json b/ets2panda/linter/test/interop/no_js_instanceof.ets.arkts2.json index e4b8a45960..d50f0569e1 100755 --- a/ets2panda/linter/test/interop/no_js_instanceof.ets.arkts2.json +++ b/ets2panda/linter/test/interop/no_js_instanceof.ets.arkts2.json @@ -24,6 +24,16 @@ "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", "severity": "ERROR" }, + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 88, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "severity": "ERROR" + }, { "line": 27, "column": 4, @@ -31,7 +41,7 @@ "endColumn": 22, "problem": "InteropJsInstanceof", "suggest": "", - "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-js-instanceof)", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-import-obj-type)", "severity": "ERROR" }, { @@ -41,7 +51,7 @@ "endColumn": 23, "problem": "InteropJsInstanceof", "suggest": "", - "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-js-instanceof)", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-import-obj-type)", "severity": "ERROR" }, { @@ -51,7 +61,37 @@ "endColumn": 23, "problem": "InteropJsInstanceof", "suggest": "", - "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-js-instanceof)", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-import-obj-type)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 28, + "endLine": 39, + "endColumn": 50, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 28, + "endLine": 39, + "endColumn": 50, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 28, + "endLine": 39, + "endColumn": 50, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", "severity": "ERROR" }, { @@ -61,7 +101,7 @@ "endColumn": 34, "problem": "InteropJsInstanceof", "suggest": "", - "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-js-instanceof)", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-import-obj-type)", "severity": "ERROR" }, { @@ -71,7 +111,7 @@ "endColumn": 38, "problem": "InteropJsInstanceof", "suggest": "", - "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-js-instanceof)", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-import-obj-type)", "severity": "ERROR" }, { @@ -81,7 +121,7 @@ "endColumn": 38, "problem": "InteropJsInstanceof", "suggest": "", - "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-js-instanceof)", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-import-obj-type)", "severity": "ERROR" }, { @@ -91,7 +131,7 @@ "endColumn": 42, "problem": "InteropJsInstanceof", "suggest": "", - "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-js-instanceof)", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-import-obj-type)", "severity": "ERROR" }, { @@ -101,7 +141,7 @@ "endColumn": 22, "problem": "InteropJsInstanceof", "suggest": "", - "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-js-instanceof)", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-import-obj-type)", "severity": "ERROR" }, { @@ -111,7 +151,37 @@ "endColumn": 24, "problem": "InteropJsInstanceof", "suggest": "", - "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-js-instanceof)", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-import-obj-type)", + "severity": "ERROR" + }, + { + "line": 69, + "column": 4, + "endLine": 69, + "endColumn": 7, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 69, + "column": 4, + "endLine": 69, + "endColumn": 7, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "severity": "ERROR" + }, + { + "line": 69, + "column": 4, + "endLine": 69, + "endColumn": 7, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", "severity": "ERROR" }, { @@ -124,6 +194,26 @@ "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", "severity": "ERROR" }, + { + "line": 73, + "column": 36, + "endLine": 73, + "endColumn": 51, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 36, + "endLine": 73, + "endColumn": 51, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "severity": "ERROR" + }, { "line": 75, "column": 5, @@ -131,7 +221,27 @@ "endColumn": 37, "problem": "InteropJsInstanceof", "suggest": "", - "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-js-instanceof)", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-import-obj-type)", + "severity": "ERROR" + }, + { + "line": 75, + "column": 22, + "endLine": 75, + "endColumn": 37, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 75, + "column": 22, + "endLine": 75, + "endColumn": 37, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", "severity": "ERROR" } ] -- Gitee From 29750b7176c067da7e65c0259708baa94ce82e12 Mon Sep 17 00:00:00 2001 From: xudan16 Date: Fri, 18 Apr 2025 22:57:51 +0800 Subject: [PATCH 090/268] keep linter install local package offline Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC2C95 Signed-off-by: xudan16 --- ets2panda/linter/build_linter.py | 52 +++++++++++++++++++++++++++----- 1 file changed, 45 insertions(+), 7 deletions(-) diff --git a/ets2panda/linter/build_linter.py b/ets2panda/linter/build_linter.py index 17b58ba3ba..943721cf82 100755 --- a/ets2panda/linter/build_linter.py +++ b/ets2panda/linter/build_linter.py @@ -42,6 +42,22 @@ def run_cmd(cmd, execution_path=None): stdout, stderr = proc.communicate(timeout=600) if proc.returncode != 0: raise Exception(stderr.decode()) + return stdout + + +def is_npm_newer_than_6(options): + cmd = [options.npm, '-v'] + stdout = run_cmd(cmd, options.source_path) + version_str = stdout.decode('utf-8').strip() + # get npm major version(i.e. "6.14.15" -> 6) + major_version = int(version_str.split('.')[0]) + if major_version is not None: + if major_version <= 6: + return False + else: + return True + # default set to lower than v7 which can compatible with v7+ + return False def build(options): @@ -70,7 +86,12 @@ def copy_output(options): def install_typescript(options): - cmd = [options.npm, 'install', '--no-save', options.typescript] + new_npm = is_npm_newer_than_6(options) + tsc_file = 'file:' + options.typescript + if new_npm: + cmd = [options.npm, 'install', '--no-save', tsc_file, '--legacy-peer-deps', '--offline'] + else: + cmd = [options.npm, 'install', '--no-save', tsc_file] run_cmd(cmd, options.source_path) @@ -94,13 +115,17 @@ def clean_old_packages(directory, prefix, suffix): return res -def pack_arkanalyzer(options): +def pack_arkanalyzer(options, new_npm): aa_path = os.path.join(options.source_path, 'arkanalyzer') + tsc_file = 'file:' + options.typescript pack_prefix = 'arkanalyzer-' pack_suffix = '.tgz' clean_old_packages(aa_path, pack_prefix, pack_suffix) - ts_install_cmd = [options.npm, 'install', options.typescript] + if new_npm: + ts_install_cmd = [options.npm, 'install', tsc_file, '--legacy-peer-deps', '--offline'] + else: + ts_install_cmd = [options.npm, 'install', tsc_file] compile_cmd = [options.npm, 'run', 'compile'] pack_cmd = [options.npm, 'pack'] run_cmd(ts_install_cmd, aa_path) @@ -109,7 +134,8 @@ def pack_arkanalyzer(options): def install_homecheck(options): - pack_arkanalyzer(options) + new_npm = is_npm_newer_than_6(options) + pack_arkanalyzer(options, new_npm) aa_path = os.path.join(options.source_path, 'arkanalyzer') hc_path = os.path.join(options.source_path, 'homecheck') aa_pack_prefix = 'arkanalyzer-' @@ -117,13 +143,21 @@ def install_homecheck(options): pack_suffix = '.tgz' exist_aa_packs = find_files_by_prefix_suffix(aa_path, aa_pack_prefix, pack_suffix) if (exist_aa_packs): - aa_install_cmd = [options.npm, 'install', exist_aa_packs[0]] + aa_file = 'file:' + exist_aa_packs[0] + if new_npm: + aa_install_cmd = [options.npm, 'install', aa_file, '--legacy-peer-deps', '--offline'] + else: + aa_install_cmd = [options.npm, 'install', aa_file] run_cmd(aa_install_cmd, hc_path) else: raise Exception('Failed to find arkanalyzer npm package') clean_old_packages(hc_path, hc_pack_prefix, pack_suffix) - ts_install_cmd = [options.npm, 'install', '--no-save', options.typescript] + tsc_file = 'file:' + options.typescript + if new_npm: + ts_install_cmd = [options.npm, 'install', '--no-save', tsc_file, '--legacy-peer-deps', '--offline'] + else: + ts_install_cmd = [options.npm, 'install', '--no-save', tsc_file] pack_cmd = [options.npm, 'pack'] compile_cmd = [options.npm, 'run', 'compile'] run_cmd(ts_install_cmd, hc_path) @@ -131,7 +165,11 @@ def install_homecheck(options): run_cmd(pack_cmd, hc_path) exist_hc_packs = find_files_by_prefix_suffix(hc_path, hc_pack_prefix, pack_suffix) if (exist_hc_packs): - hc_install_cmd = [options.npm, 'install', exist_hc_packs[0]] + hc_file = 'file:' + exist_hc_packs[0] + if new_npm: + hc_install_cmd = [options.npm, 'install', hc_file, '--legacy-peer-deps', '--offline'] + else: + hc_install_cmd = [options.npm, 'install', hc_file] run_cmd(hc_install_cmd, options.source_path) else: raise Exception('Failed to find homecheck npm package') -- Gitee From 15435c1c6b326eabe461190f0e360bde14f60a5f Mon Sep 17 00:00:00 2001 From: Utku Enes GURSEL Date: Fri, 18 Apr 2025 15:14:54 +0300 Subject: [PATCH 091/268] add check for same module import Issue: IC0NLC Description: Add checks for getting the module name of the current file if the import starts with "ets/" Signed-off-by: Utku Enes GURSEL --- ets2panda/linter/src/lib/CookBookMsg.ts | 7 +- ets2panda/linter/src/lib/TypeScriptLinter.ts | 96 +++++++++++++------ .../linter/src/lib/autofixes/Autofixer.ts | 26 +++-- ets2panda/linter/src/lib/utils/TsUtils.ts | 28 +++++- .../linter/src/lib/utils/consts/InteropAPI.ts | 2 +- .../src/lib/utils/consts/SendableAPI.ts | 2 +- .../src/lib/utils/consts/StringLiteral.ts | 2 +- 7 files changed, 119 insertions(+), 44 deletions(-) diff --git a/ets2panda/linter/src/lib/CookBookMsg.ts b/ets2panda/linter/src/lib/CookBookMsg.ts index 5e1a4eaab7..2426d7321f 100644 --- a/ets2panda/linter/src/lib/CookBookMsg.ts +++ b/ets2panda/linter/src/lib/CookBookMsg.ts @@ -265,7 +265,8 @@ cookBookTag[257] = cookBookTag[258] = 'Data observation needs to add "@Observed" (arkui-data-observation)'; cookBookTag[259] = 'ArkUI interface should be imported before using (arkui-modular-interface)'; cookBookTag[260] = 'The "@Entry" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)'; -cookBookTag[263] = 'The "@Provide" annotation does not support dynamic parameters (arkui-provide-annotation-parameters)'; +cookBookTag[263] = + 'The "@Provide" annotation does not support dynamic parameters (arkui-provide-annotation-parameters)'; cookBookTag[300] = 'The function type should be explicit (arkts-no-ts-like-function)'; cookBookTag[301] = 'Importing from "oh module" requires specifying full path (arkts-ohmurl-full-path)'; cookBookTag[302] = @@ -293,7 +294,7 @@ cookBookTag[321] = 'Import Concurrency is not required (arkts-limited-stdlib-no- cookBookTag[330] = 'Importing directly from "JS" module is not supported (arkts-no-js-import)'; cookBookTag[331] = 'ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)'; cookBookTag[332] = 'Properties of interop objects can\'t be accessed directly (arkts-no-js-obj-property)'; -cookBookTag[333] = 'Casting interop JS objects to "number" type is not allowed (arkts-no-js-number-import)' +cookBookTag[333] = 'Casting interop JS objects to "number" type is not allowed (arkts-no-js-number-import)'; cookBookTag[334] = 'The "typeof" expression can\'t be used with interop JS objects (arkts-interop-import-typeof-js)'; cookBookTag[335] = 'Interop object does not have property num (arkts-interop-does-not-have-num)'; cookBookTag[336] = 'Binary operations on js objects (arkts-no-js-obj-binary-operation)'; @@ -305,5 +306,5 @@ cookBookTag[339] = 'Interop objects can\'t be indexed directly (arkts-no-js-inde cookBookTag[340] = '"Await" operator can\'t be used with interop objects (arkts-no-import-await)'; cookBookTag[341] = 'ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)'; cookBookTag[342] = 'Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)'; -cookBookTag[343] = 'Usage of "instanceof" operator is not allowed with interop objects (arkts-no-import-obj-type)'; +cookBookTag[343] = 'Usage of "instanceof" operator is not allowed with interop objects (arkts-no-import-obj-type)'; cookBookTag[344] = 'Interop objects can\'t be incremented or decremented (arkts-no-js-obj-increases-decreases)'; diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index 8320b83f34..a95af41659 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -37,7 +37,8 @@ import { STRINGLITERAL_ANY, STRINGLITERAL_BYTE, STRINGLITERAL_SHORT, - STRINGLITERAL_LONG } from './utils/consts/StringLiteral'; + STRINGLITERAL_LONG +} from './utils/consts/StringLiteral'; import { NON_INITIALIZABLE_PROPERTY_CLASS_DECORATORS, NON_INITIALIZABLE_PROPERTY_DECORATORS, @@ -883,6 +884,10 @@ export class TypeScriptLinter { return; } + if (!importDeclNode.importClause) { + return; + } + const modulePath = importDeclNode.moduleSpecifier.getText().slice(1, -1); if (modulePath.startsWith('./') || modulePath.startsWith('../')) { @@ -894,6 +899,10 @@ export class TypeScriptLinter { return; } + if (this.checkFileExists(importDeclNode.importClause)) { + return; + } + if (TsUtils.isValidOhModulePath(modulePath) || !TsUtils.isOhModule(modulePath)) { // Valid or paths that we do not check because they are not ohModules return; @@ -912,6 +921,30 @@ export class TypeScriptLinter { this.incrementCounters(importDeclNode, FaultID.OhmUrlFullPath, autofix); } + private checkFileExists(importClause: ts.ImportClause): boolean { + + /* + * TODO: what would have a symbol on this context + * would the moduleSpecifier? I don't think so + * I think it would be the identifier + * Which would be the expression + * + * We get the symbol from import clause + * get a identifier inside the import clause and check if that file exists or not + */ + for (const child of importClause.getChildren()) { + if (child.kind !== ts.SyntaxKind.Identifier) { + continue; + } + const declNode = this.tsUtils.getDeclarationNode(child); + if (declNode) { + // this is a valid path that and the file should not be checked + return true; + } + } + return false; + } + private handleSharedModuleNoSideEffectImport(node: ts.ImportDeclaration): void { // check 'use shared' if (TypeScriptLinter.inSharedModule(node) && !node.importClause) { @@ -1569,7 +1602,7 @@ export class TypeScriptLinter { } } } - + private handlePostfixUnaryExpression(node: ts.Node): void { const unaryExpr = node as ts.PostfixUnaryExpression; if (unaryExpr.operator === ts.SyntaxKind.PlusPlusToken || unaryExpr.operator === ts.SyntaxKind.MinusMinusToken) { @@ -3169,7 +3202,7 @@ export class TypeScriptLinter { } const initDecl = TsUtils.getDeclaration(initSym); - if (!initDecl || !initDecl.getSourceFile().fileName.endsWith(EXTNAME_JS)) { + if (!initDecl?.getSourceFile().fileName.endsWith(EXTNAME_JS)) { return; } @@ -3490,7 +3523,11 @@ export class TypeScriptLinter { } } - handleCallJSFunction(tsCallExpr: ts.CallExpression, sym: ts.Symbol | undefined, callSignature: ts.Signature | undefined): void { + handleCallJSFunction( + tsCallExpr: ts.CallExpression, + sym: ts.Symbol | undefined, + callSignature: ts.Signature | undefined + ): void { if (!callSignature) { return; } @@ -3515,7 +3552,11 @@ export class TypeScriptLinter { this.checkForReflectAPIUse(callSignature, tsCallExpr); } - private handleInteropForCallObjectMethods(tsCallExpr: ts.CallExpression, sym: ts.Symbol | undefined, callSignature: ts.Signature | undefined): void { + private handleInteropForCallObjectMethods( + tsCallExpr: ts.CallExpression, + sym: ts.Symbol | undefined, + callSignature: ts.Signature | undefined + ): void { if (!callSignature) { return; } @@ -3983,9 +4024,9 @@ export class TypeScriptLinter { ts.isAsExpression(tsAsExpr) && type.kind === ts.SyntaxKind.NumberKeyword ) { - const expr = ts.isPropertyAccessExpression(tsAsExpr.expression) - ? tsAsExpr.expression.expression - : tsAsExpr.expression; + const expr = ts.isPropertyAccessExpression(tsAsExpr.expression) ? + tsAsExpr.expression.expression : + tsAsExpr.expression; if (ts.isIdentifier(expr)) { const sym = this.tsUtils.trueSymbolAtLocation(expr); @@ -5926,6 +5967,7 @@ export class TypeScriptLinter { } } } + private handleArkTSPropertyAccess(node: ts.PropertyAccessExpression): void { if (this.useStatic && this.options.arkts2) { if (this.isFromJSModule(node.expression)) { @@ -6174,8 +6216,9 @@ export class TypeScriptLinter { // Try direct check first if (this.tsUtils.isImportedFromJS(identifier)) { - const autofix = - this.autofixer?.createReplacementForJsImportPropertyAccessExpression(node as ts.PropertyAccessExpression); + const autofix = this.autofixer?.createReplacementForJsImportPropertyAccessExpression( + node as ts.PropertyAccessExpression + ); this.incrementCounters(node, FaultID.InteropJsObjectUsage, autofix); return; } @@ -6183,10 +6226,9 @@ export class TypeScriptLinter { // Try indirect reference (e.g., const foo = importedObj;) const originalIdentifier = this.tsUtils.findOriginalIdentifier(identifier); if (originalIdentifier && this.tsUtils.isImportedFromJS(originalIdentifier)) { - const autofix = - this.autofixer?.createReplacementForJsIndirectImportPropertyAccessExpression( - node as ts.PropertyAccessExpression - ); + const autofix = this.autofixer?.createReplacementForJsIndirectImportPropertyAccessExpression( + node as ts.PropertyAccessExpression + ); this.incrementCounters(node, FaultID.InteropJsObjectUsage, autofix); } } @@ -6204,7 +6246,7 @@ export class TypeScriptLinter { } const identifier = ts.isPropertyAccessExpression(variableDeclaration.initializer) ? - variableDeclaration.initializer.expression as ts.Identifier : + (variableDeclaration.initializer.expression as ts.Identifier) : undefined; if (!identifier) { return; @@ -6302,7 +6344,7 @@ export class TypeScriptLinter { } } } - + private findVariableDeclaration(identifier: ts.Identifier): ts.VariableDeclaration | undefined { const sym = this.tsUtils.trueSymbolAtLocation(identifier); const decl = TsUtils.getDeclaration(sym); @@ -6324,11 +6366,11 @@ export class TypeScriptLinter { } return false; } - + private handleAwaitExpression(node: ts.Node): void { if (!this.options.arkts2 || !this.useStatic) { - return - }; + return; + } const awaitExpr = node as ts.AwaitExpression; const checkAndReportJsImportAwait = (targetNode: ts.Node): boolean => { if (ts.isIdentifier(targetNode) && this.tsUtils.isJsImport(targetNode)) { @@ -6343,22 +6385,22 @@ export class TypeScriptLinter { checkAndReportJsImportAwait(expr.expression); } } - + handleInstanceOfExpression(node: ts.BinaryExpression): void { if (!this.options.arkts2 || !this.useStatic) { - return - }; + return; + } const left = node.left; const right = node.right; const getNode = (expr: ts.Expression): ts.Node => { - return ts.isPropertyAccessExpression(expr) || ts.isCallExpression(expr) ? expr.expression : expr + return ts.isPropertyAccessExpression(expr) || ts.isCallExpression(expr) ? expr.expression : expr; }; const leftExpr = getNode(left); const rightExpr = getNode(right); - if(this.tsUtils.isJsImport(leftExpr) || this.tsUtils.isJsImport(rightExpr)) { - this.incrementCounters(node, FaultID.InteropJsInstanceof); - } - } + if (this.tsUtils.isJsImport(leftExpr) || this.tsUtils.isJsImport(rightExpr)) { + this.incrementCounters(node, FaultID.InteropJsInstanceof); + } + } private checkAutoIncrementDecrement(unaryExpr: ts.PostfixUnaryExpression | ts.PrefixUnaryExpression): void { if (ts.isPropertyAccessExpression(unaryExpr.operand)) { diff --git a/ets2panda/linter/src/lib/autofixes/Autofixer.ts b/ets2panda/linter/src/lib/autofixes/Autofixer.ts index 0c3ef9778e..c67f4ca381 100644 --- a/ets2panda/linter/src/lib/autofixes/Autofixer.ts +++ b/ets2panda/linter/src/lib/autofixes/Autofixer.ts @@ -43,13 +43,13 @@ import { PROVIDE_ALLOW_OVERRIDE_PROPERTY_NAME } from '../utils/consts/ArkuiConstants'; import { ES_OBJECT } from '../utils/consts/ESObject'; -import { - LOAD, +import { + LOAD, GET_PROPERTY_BY_NAME, SET_PROPERTY_BY_NAME, GET_PROPERTY_BY_INDEX, SET_PROPERTY_BY_INDEX, - ARE_EQUAL, + ARE_EQUAL, ARE_STRICTLY_EQUAL, WRAP, INSTANTIATE, @@ -966,7 +966,13 @@ export class Autofixer { static addDefaultModuleToPath(parts: string[], importDeclNode: ts.ImportDeclaration): Autofix[] | undefined { const moduleSpecifier = importDeclNode.moduleSpecifier; - const newPathParts = [DEFAULT_MODULE_NAME, SRC_AND_MAIN, ...parts]; + /* + * check the current file's path + * get the parent directory name of the "src" directory + */ + + const moduleName = TsUtils.getModuleName(importDeclNode); + const newPathParts = [moduleName ?? DEFAULT_MODULE_NAME, SRC_AND_MAIN, ...parts]; const newPath = newPathParts.join(PATH_SEPARATOR); const newPathString = '\'' + newPath + '\''; @@ -3153,9 +3159,9 @@ export class Autofixer { const replacementText = isParentBinaryExp && elementAccessExpr.parent.operatorToken.kind === ts.SyntaxKind.EqualsToken ? `${identifier.text}.setPropertyByIndex(${exprText},` + - ` ESObject.wrap(${elementAccessExpr.parent.right.getText()}))` : + ` ESObject.wrap(${elementAccessExpr.parent.right.getText()}))` : `${identifier.text}.getPropertyByIndex(${exprText})` + - this.utils.findTypeOfNodeForConversion(elementAccessExpr); + this.utils.findTypeOfNodeForConversion(elementAccessExpr); return [{ replacementText, start, end }]; } @@ -3244,7 +3250,7 @@ export class Autofixer { } return ''; } - + private static fixInterOpImportJsWrapArgs(args: ts.NodeArray): string { return args. map((arg) => { @@ -3345,7 +3351,7 @@ export class Autofixer { }); return lastImportEnd; } - + fixInteropPropertyAccessExpression(express: ts.PropertyAccessExpression): Autofix[] | undefined { let text: string = ''; const statements = ts.factory.createCallExpression( @@ -3433,7 +3439,7 @@ export class Autofixer { const replacementText = `${processed}.typeOf()`; return replacementText ? [{ start, end, replacementText }] : undefined; } - + fixInteropInterfaceConvertNum(express: ts.PrefixUnaryExpression): Autofix[] | undefined { let text = ''; if (ts.isPropertyAccessExpression(express.operand)) { @@ -3456,7 +3462,7 @@ export class Autofixer { } return [{ start: express.operand.getStart(), end: express.operand.getEnd(), replacementText: text }]; } - + fixInteropEqualityOperator( tsBinaryExpr: ts.BinaryExpression, binaryOperator: ts.BinaryOperator diff --git a/ets2panda/linter/src/lib/utils/TsUtils.ts b/ets2panda/linter/src/lib/utils/TsUtils.ts index 5ff5e88c80..880d66508e 100644 --- a/ets2panda/linter/src/lib/utils/TsUtils.ts +++ b/ets2panda/linter/src/lib/utils/TsUtils.ts @@ -3366,6 +3366,32 @@ export class TsUtils { return isNumberLike; } + static getModuleName(node: ts.Node): string | undefined { + const currentFilePath = node.getSourceFile().fileName; + if (!currentFilePath.includes('src')) { + return undefined; + } + + /* + * Assuming we are working with a path like "entry/src/main/ets/pages/test1.ets" + * we are splitting at "/src" and get the first item in the list + * in order to capture the "entry" group + * we could have worked with an absolute path like + * "home/user/projects/oh_project/entry/src/main/ets/pages/test1.sts" + * in that case, after the fist split we would have + * "home/user/projects/entry" + * so we split once again with "/" to separate out the directories + * + * and get the last item which is entry or our module + */ + const getPossibleModule = currentFilePath.split('/src')[0]; + if (getPossibleModule.length === 0) { + return undefined; + } + const sanitizedDirectories = getPossibleModule.split('/'); + return sanitizedDirectories[sanitizedDirectories.length - 1]; + } + isImportedFromJS(identifier: ts.Identifier): boolean { const sym = this.trueSymbolAtLocation(identifier); const declaration = sym?.declarations?.[0]; @@ -3491,7 +3517,7 @@ export class TsUtils { return undefined; } - + static isArkts12File(sourceFile: ts.SourceFile): boolean { if (!sourceFile) { return false; diff --git a/ets2panda/linter/src/lib/utils/consts/InteropAPI.ts b/ets2panda/linter/src/lib/utils/consts/InteropAPI.ts index 8602c17262..5aa9c0be54 100644 --- a/ets2panda/linter/src/lib/utils/consts/InteropAPI.ts +++ b/ets2panda/linter/src/lib/utils/consts/InteropAPI.ts @@ -39,4 +39,4 @@ export const GET_PROPERTY_BY_NAME = 'getPropertyByName'; export const SET_PROPERTY_BY_NAME = 'setPropertyByName'; export const GET_PROPERTY_BY_INDEX = 'getPropertyByIndex'; export const SET_PROPERTY_BY_INDEX = 'setPropertyByIndex'; -export const TO_NUMBER = 'toNumber'; \ No newline at end of file +export const TO_NUMBER = 'toNumber'; diff --git a/ets2panda/linter/src/lib/utils/consts/SendableAPI.ts b/ets2panda/linter/src/lib/utils/consts/SendableAPI.ts index 15a69be6ba..e6a6cdae37 100644 --- a/ets2panda/linter/src/lib/utils/consts/SendableAPI.ts +++ b/ets2panda/linter/src/lib/utils/consts/SendableAPI.ts @@ -27,4 +27,4 @@ export const SENDABLE_DECORATOR_NODES = [ export const SENDABLE_CLOSURE_DECLS = [ts.SyntaxKind.ClassDeclaration, ts.SyntaxKind.FunctionDeclaration]; export const SENDBALE_FUNCTION_START_VERSION = 12; -export const SENDABLE_FUNCTION_UNSUPPORTED_STAGES_IN_API12 = ['beta1', 'beta2']; \ No newline at end of file +export const SENDABLE_FUNCTION_UNSUPPORTED_STAGES_IN_API12 = ['beta1', 'beta2']; diff --git a/ets2panda/linter/src/lib/utils/consts/StringLiteral.ts b/ets2panda/linter/src/lib/utils/consts/StringLiteral.ts index 323023487f..4b1653fb1f 100644 --- a/ets2panda/linter/src/lib/utils/consts/StringLiteral.ts +++ b/ets2panda/linter/src/lib/utils/consts/StringLiteral.ts @@ -20,4 +20,4 @@ export const STRINGLITERAL_INT = 'int'; export const STRINGLITERAL_BYTE = 'byte'; export const STRINGLITERAL_SHORT = 'short'; export const STRINGLITERAL_LONG = 'long'; -export const STRINGLITERAL_ANY = 'ANY'; \ No newline at end of file +export const STRINGLITERAL_ANY = 'ANY'; -- Gitee From 9720c65a15d021d53f32c3e6e61835749b043328 Mon Sep 17 00:00:00 2001 From: liwentao_uiw Date: Sun, 20 Apr 2025 16:16:51 +0800 Subject: [PATCH 092/268] Add check for statments length Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC2I28 Test scenarios: linter test, app scan and autofix Signed-off-by: liwentao Change-Id: I9b0b41a7783a1143a0f4512dadd6e9eb12498a4f --- ets2panda/linter/src/lib/utils/TsUtils.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ets2panda/linter/src/lib/utils/TsUtils.ts b/ets2panda/linter/src/lib/utils/TsUtils.ts index 880d66508e..386623e475 100644 --- a/ets2panda/linter/src/lib/utils/TsUtils.ts +++ b/ets2panda/linter/src/lib/utils/TsUtils.ts @@ -3519,7 +3519,7 @@ export class TsUtils { } static isArkts12File(sourceFile: ts.SourceFile): boolean { - if (!sourceFile) { + if (!sourceFile || !sourceFile.statements.length) { return false; } const statements = sourceFile.statements; -- Gitee From 262372155bde3a5cbaae805a445fd6473f4a6046 Mon Sep 17 00:00:00 2001 From: yaohaosen Date: Thu, 17 Apr 2025 16:20:11 +0800 Subject: [PATCH 093/268] [LSP] Fix inconsistent offset of apis Issue: https://gitee.com/openharmony/developtools_ace_ets2bundle/issues/IC1XSX Signed-off-by: yaohaosen --- ets2panda/bindings/src/lsp_helper.ts | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/ets2panda/bindings/src/lsp_helper.ts b/ets2panda/bindings/src/lsp_helper.ts index b9224e4b29..544fbc2a42 100644 --- a/ets2panda/bindings/src/lsp_helper.ts +++ b/ets2panda/bindings/src/lsp_helper.ts @@ -62,7 +62,7 @@ export class Lsp { let arktsconfig = this.fileNameToArktsconfig[filePath]; let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); - const source = fs.readFileSync(filePath, 'utf8').toString().replace(/\r\n/g, '\n'); + const source = this.getFileContent(filePath).replace(/\r\n/g, '\n'); let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); @@ -82,7 +82,7 @@ export class Lsp { let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; let pandaLibPath: string = path.resolve(__dirname, '../../ets2panda/lib'); let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, pandaLibPath); - const source = fs.readFileSync(filePath, 'utf8').toString().replace(/\r\n/g, '\n'); + const source = this.getFileContent(filePath).replace(/\r\n/g, '\n'); let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); @@ -101,7 +101,7 @@ export class Lsp { let arktsconfig = this.fileNameToArktsconfig[filePath]; let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); - const source = fs.readFileSync(filePath, 'utf8').toString().replace(/\r\n/g, '\n'); + const source = this.getFileContent(filePath).replace(/\r\n/g, '\n'); let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); @@ -120,7 +120,7 @@ export class Lsp { let arktsconfig = this.fileNameToArktsconfig[filePath]; let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); - const source = fs.readFileSync(filePath, 'utf8').toString().replace(/\r\n/g, '\n'); + const source = this.getFileContent(filePath).replace(/\r\n/g, '\n'); let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); @@ -139,7 +139,7 @@ export class Lsp { let arktsconfig = this.fileNameToArktsconfig[filePath]; let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); - const source = fs.readFileSync(filePath, 'utf8').toString().replace(/\r\n/g, '\n'); + const source = this.getFileContent(filePath).replace(/\r\n/g, '\n'); let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); @@ -183,7 +183,7 @@ export class Lsp { let arktsconfig = this.fileNameToArktsconfig[filePath]; let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); - const source = fs.readFileSync(filePath, 'utf8').toString().replace(/\r\n/g, '\n'); + const source = this.getFileContent(filePath).replace(/\r\n/g, '\n'); let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); @@ -223,7 +223,7 @@ export class Lsp { let arktsconfig = this.fileNameToArktsconfig[filePath]; let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); - const source = fs.readFileSync(filePath, 'utf8').toString().replace(/\r\n/g, '\n'); + const source = this.getFileContent(filePath).replace(/\r\n/g, '\n'); let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); @@ -242,7 +242,7 @@ export class Lsp { let arktsconfig = this.fileNameToArktsconfig[filePath]; let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); - const source = fs.readFileSync(filePath, 'utf8').toString().replace(/\r\n/g, '\n'); + const source = this.getFileContent(filePath).replace(/\r\n/g, '\n'); let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); @@ -261,7 +261,7 @@ export class Lsp { let arktsconfig = this.fileNameToArktsconfig[filePath]; let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); - const source = fs.readFileSync(filePath, 'utf8').toString().replace(/\r\n/g, '\n'); + const source = this.getFileContent(filePath).replace(/\r\n/g, '\n'); let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); @@ -280,7 +280,7 @@ export class Lsp { let arktsconfig = this.fileNameToArktsconfig[filePath]; let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); - const source = fs.readFileSync(filePath, 'utf8').toString().replace(/\r\n/g, '\n'); + const source = this.getFileContent(filePath).replace(/\r\n/g, '\n'); let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); @@ -328,7 +328,7 @@ export class Lsp { let arktsconfig = this.fileNameToArktsconfig[filePath]; let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); - const source = fs.readFileSync(filePath, 'utf8').toString().replace(/\r\n/g, '\n'); + const source = this.getFileContent(filePath).replace(/\r\n/g, '\n'); let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); -- Gitee From 22aa77657db72efebad266e5756eb4f53bb65e12 Mon Sep 17 00:00:00 2001 From: wangyuxin Date: Wed, 9 Apr 2025 17:50:42 +0800 Subject: [PATCH 094/268] Fix parser bug of <>= Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC2KID Reason: let c: Array= new Array() At ParseTypeParameterInstantiationImpl, the failure to process >= leads to a further syntax error. Description: Cherry pick modification to 0411 Signed-off-by: wangyuxin --- ets2panda/parser/TypedParser.cpp | 6 +++++ .../ast/compiler/ets/greater_than_neg.ets | 24 +++++++++++++++++++ ets2panda/test/runtime/ets/greater_parse.ets | 19 +++++++++++++++ 3 files changed, 49 insertions(+) create mode 100644 ets2panda/test/ast/compiler/ets/greater_than_neg.ets create mode 100644 ets2panda/test/runtime/ets/greater_parse.ets diff --git a/ets2panda/parser/TypedParser.cpp b/ets2panda/parser/TypedParser.cpp index e66067b287..94ba932dc9 100644 --- a/ets2panda/parser/TypedParser.cpp +++ b/ets2panda/parser/TypedParser.cpp @@ -1274,14 +1274,20 @@ ir::AstNode *TypedParser::ParseTypeParameterInstantiationImpl(TypeAnnotationPars Lexer()->NextToken(); continue; } + case lexer::TokenType::PUNCTUATOR_GREATER_THAN_EQUAL: case lexer::TokenType::PUNCTUATOR_RIGHT_SHIFT: { Lexer()->BackwardToken(lexer::TokenType::PUNCTUATOR_GREATER_THAN, 1); break; } + case lexer::TokenType::PUNCTUATOR_RIGHT_SHIFT_EQUAL: case lexer::TokenType::PUNCTUATOR_UNSIGNED_RIGHT_SHIFT: { Lexer()->BackwardToken(lexer::TokenType::PUNCTUATOR_GREATER_THAN, 2U); break; } + case lexer::TokenType::PUNCTUATOR_UNSIGNED_RIGHT_SHIFT_EQUAL: { + Lexer()->BackwardToken(lexer::TokenType::PUNCTUATOR_GREATER_THAN, 3U); + break; + } case lexer::TokenType::PUNCTUATOR_GREATER_THAN: { break; } diff --git a/ets2panda/test/ast/compiler/ets/greater_than_neg.ets b/ets2panda/test/ast/compiler/ets/greater_than_neg.ets new file mode 100644 index 0000000000..172e7b937c --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/greater_than_neg.ets @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +let a: Array>>=2 +let b: Array>=2 + +/* @@? 16:21 Error SyntaxError: Unexpected token '>>='. */ +/* @@? 16:21 Error SyntaxError: Unexpected token '>>='. */ +/* @@? 17:21 Error SyntaxError: Unexpected token '>='. */ +/* @@? 17:21 Error SyntaxError: Unexpected token '>='. */ +/* @@? 17:21 Error TypeError: Bad operand type, the types of the operands must be numeric, same enumeration, or boolean type. */ + diff --git a/ets2panda/test/runtime/ets/greater_parse.ets b/ets2panda/test/runtime/ets/greater_parse.ets new file mode 100644 index 0000000000..d78e2e9b7b --- /dev/null +++ b/ets2panda/test/runtime/ets/greater_parse.ets @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +let a: Array= new Array() +let b: Array>= new Array>() +let c: Array>>= new Array>>() + -- Gitee From ad66ee821cc679dec9388cafe09629376aa80c60 Mon Sep 17 00:00:00 2001 From: zmw Date: Tue, 15 Apr 2025 11:14:25 +0800 Subject: [PATCH 095/268] Fix same name property without CTE Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC15YU Description: Fix same name property without CTE Signed-off-by: zmw --- ets2panda/checker/ETSchecker.cpp | 4 +- .../ets/MultiPropertyWithSameName.ets | 40 +++++++++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) create mode 100644 ets2panda/test/ast/compiler/ets/MultiPropertyWithSameName.ets diff --git a/ets2panda/checker/ETSchecker.cpp b/ets2panda/checker/ETSchecker.cpp index a8d7a1a488..4beac88821 100644 --- a/ets2panda/checker/ETSchecker.cpp +++ b/ets2panda/checker/ETSchecker.cpp @@ -61,12 +61,12 @@ void ETSChecker::CheckObjectLiteralKeys(const ArenaVector &pro } auto propertyDecl = property->AsProperty(); auto propKey = propertyDecl->Key(); - if (!propKey->IsIdentifier()) { + if (!propKey->IsIdentifier() && !propKey->IsStringLiteral()) { continue; } // number kind only used here - auto propName = propKey->AsIdentifier()->Name(); + auto propName = propKey->IsIdentifier() ? propKey->AsIdentifier()->Name() : propKey->AsStringLiteral()->Str(); if (names.find(propName) != names.end()) { LogError(diagnostic::OBJ_LIT_PROPERTY_REDECLARATION, {}, property->Start()); } diff --git a/ets2panda/test/ast/compiler/ets/MultiPropertyWithSameName.ets b/ets2panda/test/ast/compiler/ets/MultiPropertyWithSameName.ets new file mode 100644 index 0000000000..3c7d4737be --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/MultiPropertyWithSameName.ets @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class A { + field = "" +} + +let a: A = { + field: "1", + "field": '2', +} + +let b: A = { + field: "1", + field: "2", + "field": '3', +} + +let c: A = { + "field": '2', + "field": '3', +} + + +/* @@? 22:5 Error TypeError: An object literal cannot have multiple properties with the same name. */ +/* @@? 27:5 Error TypeError: An object literal cannot have multiple properties with the same name. */ +/* @@? 28:5 Error TypeError: An object literal cannot have multiple properties with the same name. */ +/* @@? 33:5 Error TypeError: An object literal cannot have multiple properties with the same name. */ -- Gitee From 25f1178106a1e064c966747b73a9933a4bca6d5d Mon Sep 17 00:00:00 2001 From: openharmony_ci <120357966@qq.com> Date: Sat, 19 Apr 2025 15:24:44 +0000 Subject: [PATCH 096/268] Fix StackOverFlow when calling super accessor Issue : https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC2O7D --- ets2panda/compiler/base/lreference.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ets2panda/compiler/base/lreference.cpp b/ets2panda/compiler/base/lreference.cpp index 48bab0c0d6..e51a2a0b39 100644 --- a/ets2panda/compiler/base/lreference.cpp +++ b/ets2panda/compiler/base/lreference.cpp @@ -303,6 +303,8 @@ void ETSLReference::SetValueGetterSetter(const ir::MemberExpression *memberExpr) if (sig->Function()->IsStatic()) { etsg_->CallExact(Node(), sig->InternalName(), argReg); + } else if (memberExpr->Object()->IsSuperExpression()) { + etsg_->CallExact(Node(), sig->InternalName(), baseReg_, argReg); } else { etsg_->CallVirtual(Node(), sig, baseReg_, argReg); } -- Gitee From d9532fd1a24468f9ea34f10ee94b8d17a3b6cb9e Mon Sep 17 00:00:00 2001 From: Ilya Trubachev Date: Tue, 15 Apr 2025 17:15:58 +0800 Subject: [PATCH 097/268] Support enums in runtime Issue: https://gitee.com/openharmony/arkcompiler_runtime_core/issues/IC2AW0 Change-Id: Ia355cdd25e8319f66896a214dd0456fc574781ab Signed-off-by: Ilya Trubachev --- ets2panda/checker/ETSAnalyzerHelpers.cpp | 3 - ets2panda/checker/ets/arithmetic.cpp | 5 +- ets2panda/checker/ets/typeCheckingHelpers.cpp | 3 +- .../compiler/lowering/ets/enumLowering.cpp | 108 ++- .../compiler/lowering/ets/enumLowering.h | 12 +- ...as_class_member_getValue_call-expected.txt | 594 ++++++++++++- .../ets/import_tests/enum_export-expected.txt | 793 +++++++++++++++--- .../test/parser/ets/declare_enum-expected.txt | 215 +++-- .../ets/switch_enum_string_case-expected.txt | 304 ++++++- ets2panda/test/runtime/ets/enum_reference.ets | 2 +- 10 files changed, 1797 insertions(+), 242 deletions(-) diff --git a/ets2panda/checker/ETSAnalyzerHelpers.cpp b/ets2panda/checker/ETSAnalyzerHelpers.cpp index 5e2d1d5f89..1b2ae1efb1 100644 --- a/ets2panda/checker/ETSAnalyzerHelpers.cpp +++ b/ets2panda/checker/ETSAnalyzerHelpers.cpp @@ -529,9 +529,6 @@ void ProcessExclamationMark(ETSChecker *checker, ir::UnaryExpression *expr, chec expr->SetTsType(tsType); return; } - if (operandType->IsETSEnumType()) { - expr->Argument()->AddAstNodeFlags(ir::AstNodeFlags::GENERATE_VALUE_OF); - } expr->SetTsType(checker->GlobalETSBooleanType()); } diff --git a/ets2panda/checker/ets/arithmetic.cpp b/ets2panda/checker/ets/arithmetic.cpp index 5da89c5a68..f1172e016d 100644 --- a/ets2panda/checker/ets/arithmetic.cpp +++ b/ets2panda/checker/ets/arithmetic.cpp @@ -664,8 +664,11 @@ static Type *HandelReferenceBinaryEquality(ETSChecker *checker, BinaryArithmOper (typeL->IsETSNullType() && typeR->IsETSPrimitiveType())) { return checker->CreateETSUnionType({typeL, typeR}); } - // Do not comparing reference equality for enum. + if (typeL->IsETSEnumType() && typeR->IsETSEnumType()) { + if (checker->Relation()->IsIdenticalTo(typeL, typeR)) { + return typeL; + } return nullptr; } diff --git a/ets2panda/checker/ets/typeCheckingHelpers.cpp b/ets2panda/checker/ets/typeCheckingHelpers.cpp index 3ad56e644b..df6f4d399a 100644 --- a/ets2panda/checker/ets/typeCheckingHelpers.cpp +++ b/ets2panda/checker/ets/typeCheckingHelpers.cpp @@ -291,7 +291,8 @@ bool Type::PossiblyETSString() const static bool IsValueTypedObjectType(ETSObjectType const *t) { - return t->IsGlobalETSObjectType() || t->HasObjectFlag(ETSObjectFlags::VALUE_TYPED); + return t->IsGlobalETSObjectType() || t->HasObjectFlag(ETSObjectFlags::VALUE_TYPED) || + t->HasObjectFlag(ETSObjectFlags::ENUM_OBJECT); } bool Type::PossiblyETSValueTyped() const diff --git a/ets2panda/compiler/lowering/ets/enumLowering.cpp b/ets2panda/compiler/lowering/ets/enumLowering.cpp index bae3d9e960..7a524ec4aa 100644 --- a/ets2panda/compiler/lowering/ets/enumLowering.cpp +++ b/ets2panda/compiler/lowering/ets/enumLowering.cpp @@ -162,10 +162,10 @@ template } void EnumLoweringPhase::CreateEnumItemFields(const ir::TSEnumDeclaration *const enumDecl, - ir::ClassDefinition *const enumClass) + ir::ClassDefinition *const enumClass, EnumType enumType) { int32_t ordinal = 0; - auto createEnumItemField = [this, enumClass, &ordinal](ir::TSEnumMember *const member) { + auto createEnumItemField = [this, enumClass, enumType, &ordinal](ir::TSEnumMember *const member) { auto *const enumMemberIdent = checker_->AllocNode(member->AsTSEnumMember()->Key()->AsIdentifier()->Name(), Allocator()); auto *const enumTypeAnnotation = MakeTypeReference(checker_, enumClass->Ident()->Name()); @@ -174,6 +174,29 @@ void EnumLoweringPhase::CreateEnumItemFields(const ir::TSEnumDeclaration *const ordinal++; ArenaVector newExprArgs(Allocator()->Adapter()); newExprArgs.push_back(ordinalLiteral); + + ir::Expression *valueArgument = nullptr; + switch (enumType) { + case EnumType::INT: { + auto enumFieldValue = + member->AsTSEnumMember()->Init()->AsNumberLiteral()->Number().GetValue(); + valueArgument = checker_->AllocNode(lexer::Number(enumFieldValue)); + break; + } + case EnumType::LONG: { + auto enumFieldValue = + member->AsTSEnumMember()->Init()->AsNumberLiteral()->Number().GetValue(); + valueArgument = checker_->AllocNode(lexer::Number(enumFieldValue)); + break; + } + case EnumType::STRING: { + auto enumFieldValue = member->AsTSEnumMember()->Init()->AsStringLiteral()->Str(); + valueArgument = checker_->AllocNode(enumFieldValue); + break; + } + } + newExprArgs.push_back(valueArgument); + auto enumTypeAnnotation1 = enumTypeAnnotation->Clone(Allocator(), nullptr); auto *const newExpression = checker_->AllocNode(enumTypeAnnotation1, std::move(newExprArgs)); @@ -209,20 +232,52 @@ ir::Identifier *EnumLoweringPhase::CreateEnumNamesArray(const ir::TSEnumDeclarat // clang-format on } +static ir::TypeNode *CreateType(checker::ETSChecker *checker, EnumLoweringPhase::EnumType enumType) +{ + switch (enumType) { + case EnumLoweringPhase::EnumType::INT: { + return checker->AllocNode(ir::PrimitiveType::INT, checker->Allocator()); + } + case EnumLoweringPhase::EnumType::LONG: { + return checker->AllocNode(ir::PrimitiveType::LONG, checker->Allocator()); + } + case EnumLoweringPhase::EnumType::STRING: { + return MakeTypeReference(checker, EnumLoweringPhase::STRING_REFERENCE_TYPE); + } + default: { + ES2PANDA_UNREACHABLE(); + } + } + + return nullptr; +} + ir::ClassDeclaration *EnumLoweringPhase::CreateClass(ir::TSEnumDeclaration *const enumDecl, - const DeclarationFlags flags, bool isIntEnum) + const DeclarationFlags flags, EnumType enumType) { auto *ident = Allocator()->New(enumDecl->Key()->Name(), Allocator()); ident->SetRange(enumDecl->Key()->Range()); - auto enumFlag = isIntEnum ? ir::ClassDefinitionModifiers::INT_ENUM_TRANSFORMED - : ir::ClassDefinitionModifiers::STRING_ENUM_TRANSFORMED; + auto enumFlag = enumType == EnumType::INT || enumType == EnumType::LONG + ? ir::ClassDefinitionModifiers::INT_ENUM_TRANSFORMED + : ir::ClassDefinitionModifiers::STRING_ENUM_TRANSFORMED; auto baseClassDefinitionFlag = ir::ClassDefinitionModifiers::CLASS_DECL | enumFlag; + + auto typeParamsVector = ArenaVector(checker_->Allocator()->Adapter()); + typeParamsVector.push_back(CreateType(checker_, enumType)); + auto *typeParam = checker_->AllocNode(std::move(typeParamsVector)); + + auto *identRef = checker_->AllocNode(util::StringView(BASE_CLASS_NAME), checker_->Allocator()); + auto *typeRefPart = + checker_->AllocNode(identRef, typeParam, nullptr, checker_->Allocator()); + auto *superClass = checker_->AllocNode(typeRefPart, checker_->Allocator()); + auto *classDef = checker_->AllocNode( Allocator(), ident, flags.isLocal ? baseClassDefinitionFlag | ir::ClassDefinitionModifiers::LOCAL : baseClassDefinitionFlag, enumDecl->IsDeclare() ? ir::ModifierFlags::FINAL | ir::ModifierFlags::DECLARE : ir::ModifierFlags::FINAL, Language(Language::Id::ETS)); + classDef->SetSuper(superClass); auto *classDecl = checker_->AllocNode(classDef, Allocator()); if (enumDecl->IsExported()) { @@ -237,7 +292,7 @@ ir::ClassDeclaration *EnumLoweringPhase::CreateClass(ir::TSEnumDeclaration *cons if (!enumDecl->IsDeclare()) { CreateCCtorForEnumClass(classDef); } - CreateCtorForEnumClass(classDef); + CreateCtorForEnumClass(classDef, enumType); return classDecl; } @@ -282,7 +337,8 @@ ir::ClassProperty *EnumLoweringPhase::CreateOrdinalField(ir::ClassDefinition *co return field; } -ir::ScriptFunction *EnumLoweringPhase::CreateFunctionForCtorOfEnumClass(ir::ClassDefinition *const enumClass) +ir::ScriptFunction *EnumLoweringPhase::CreateFunctionForCtorOfEnumClass(ir::ClassDefinition *const enumClass, + EnumType enumType) { ArenaVector params(Allocator()->Adapter()); @@ -290,6 +346,10 @@ ir::ScriptFunction *EnumLoweringPhase::CreateFunctionForCtorOfEnumClass(ir::Clas auto *const inputOrdinalParam = MakeFunctionParam(checker_, PARAM_ORDINAL, intTypeAnnotation); params.push_back(inputOrdinalParam); + ir::TypeNode *typeAnnotation = CreateType(checker_, enumType); + auto *const inputValueParam = MakeFunctionParam(checker_, PARAM_VALUE, typeAnnotation); + params.push_back(inputValueParam); + auto *id = checker_->AllocNode("constructor", Allocator()); ArenaVector statements(Allocator()->Adapter()); @@ -308,6 +368,23 @@ ir::ScriptFunction *EnumLoweringPhase::CreateFunctionForCtorOfEnumClass(ir::Clas func->SetIdent(id); + if (enumClass->IsDeclare()) { + // NOTE: In aliveAnalyzer call to super is processed and leads to error. Need to invetigate it + return func; + } + + auto *valueIdentifier = checker_->AllocNode(PARAM_VALUE, Allocator()); + valueIdentifier->SetVariable(inputValueParam->Ident()->Variable()); + + ArenaVector callArguments(checker_->Allocator()->Adapter()); + auto *callee = checker_->AllocNode(); + callArguments.push_back(valueIdentifier); + auto *superConstructorCall = + checker_->AllocNode(callee, std::move(callArguments), nullptr, false); + auto *superCallStatement = checker_->AllocNode(superConstructorCall); + superCallStatement->SetParent(body); + body->Statements().push_back(superCallStatement); + auto *thisExpr = Allocator()->New(); auto *fieldIdentifier = Allocator()->New(ORDINAL_NAME, Allocator()); auto *leftHandSide = checker_->AllocNode( @@ -323,9 +400,9 @@ ir::ScriptFunction *EnumLoweringPhase::CreateFunctionForCtorOfEnumClass(ir::Clas return func; } -void EnumLoweringPhase::CreateCtorForEnumClass(ir::ClassDefinition *const enumClass) +void EnumLoweringPhase::CreateCtorForEnumClass(ir::ClassDefinition *const enumClass, EnumType enumType) { - auto *func = CreateFunctionForCtorOfEnumClass(enumClass); + auto *func = CreateFunctionForCtorOfEnumClass(enumClass, enumType); auto *funcExpr = checker_->AllocNode(func); auto *const identClone = func->Id()->Clone(Allocator(), nullptr); @@ -375,10 +452,15 @@ template ir::ClassDeclaration *EnumLoweringPhase::CreateEnumIntClassFromEnumDeclaration(ir::TSEnumDeclaration *const enumDecl, const DeclarationFlags flags) { - auto *const enumClassDecl = CreateClass(enumDecl, flags, true); + EnumType enumType = EnumType::INT; + if constexpr (TYPE == ir::PrimitiveType::LONG) { + enumType = EnumType::LONG; + } + + auto *const enumClassDecl = CreateClass(enumDecl, flags, enumType); auto *const enumClass = enumClassDecl->Definition(); - CreateEnumItemFields(enumDecl, enumClass); + CreateEnumItemFields(enumDecl, enumClass, enumType); auto *const namesArrayIdent = CreateEnumNamesArray(enumDecl, enumClass); auto *const valuesArrayIdent = CreateEnumValuesArray(enumDecl, enumClass); auto *const stringValuesArrayIdent = CreateEnumStringValuesArray(enumDecl, enumClass); @@ -411,10 +493,10 @@ ir::ClassDeclaration *EnumLoweringPhase::CreateEnumIntClassFromEnumDeclaration(i ir::ClassDeclaration *EnumLoweringPhase::CreateEnumStringClassFromEnumDeclaration(ir::TSEnumDeclaration *const enumDecl, const DeclarationFlags flags) { - auto *const enumClassDecl = CreateClass(enumDecl, flags, false); + auto *const enumClassDecl = CreateClass(enumDecl, flags, EnumType::STRING); auto *const enumClass = enumClassDecl->Definition(); - CreateEnumItemFields(enumDecl, enumClass); + CreateEnumItemFields(enumDecl, enumClass, EnumType::STRING); auto *const namesArrayIdent = CreateEnumNamesArray(enumDecl, enumClass); auto *const stringValuesArrayIdent = CreateEnumStringValuesArray(enumDecl, enumClass); auto *const itemsArrayIdent = CreateEnumItemsArray(enumDecl, enumClass); diff --git a/ets2panda/compiler/lowering/ets/enumLowering.h b/ets2panda/compiler/lowering/ets/enumLowering.h index 9a4228f574..75a38b23fd 100644 --- a/ets2panda/compiler/lowering/ets/enumLowering.h +++ b/ets2panda/compiler/lowering/ets/enumLowering.h @@ -34,6 +34,9 @@ public: static constexpr std::string_view const NAMES_ARRAY_NAME {"#NamesArray"}; static constexpr std::string_view const VALUES_ARRAY_NAME {"#ValuesArray"}; static constexpr std::string_view const ORDINAL_NAME {"#ordinal"}; + static constexpr std::string_view const BASE_CLASS_NAME {"BaseEnum"}; + + enum EnumType { INT = 0, LONG = 1, STRING = 2 }; struct DeclarationFlags { // NOLINTBEGIN(misc-non-private-member-variables-in-classes) @@ -84,12 +87,12 @@ private: [[nodiscard]] ir::ScriptFunction *MakeFunction(FunctionInfo &&functionInfo); ir::ClassDeclaration *CreateClass(ir::TSEnumDeclaration *const enumDecl, const DeclarationFlags flags, - bool isIntEnum); + EnumType enumType); ir::ClassProperty *CreateOrdinalField(ir::ClassDefinition *const enumClass); ir::MemberExpression *CreateOrdinalAccessExpression(); void CreateCCtorForEnumClass(ir::ClassDefinition *const enumClass); - void CreateCtorForEnumClass(ir::ClassDefinition *const enumClass); - ir::ScriptFunction *CreateFunctionForCtorOfEnumClass(ir::ClassDefinition *const enumClass); + void CreateCtorForEnumClass(ir::ClassDefinition *const enumClass, EnumType enumType); + ir::ScriptFunction *CreateFunctionForCtorOfEnumClass(ir::ClassDefinition *const enumClass, EnumType enumType); void ProcessEnumClassDeclaration(ir::TSEnumDeclaration *const enumDecl, const DeclarationFlags &flags, ir::ClassDeclaration *enumClassDecl); @@ -103,7 +106,8 @@ private: [[nodiscard]] ir::Identifier *MakeArray(const ir::TSEnumDeclaration *const enumDecl, ir::ClassDefinition *enumClass, const util::StringView &name, ir::TypeNode *const typeAnnotation, ElementMaker &&elementMaker); - void CreateEnumItemFields(const ir::TSEnumDeclaration *const enumDecl, ir::ClassDefinition *enumClass); + void CreateEnumItemFields(const ir::TSEnumDeclaration *const enumDecl, ir::ClassDefinition *enumClass, + EnumType enumType); ir::Identifier *CreateEnumNamesArray(const ir::TSEnumDeclaration *const enumDecl, ir::ClassDefinition *enumClass); template ir::Identifier *CreateEnumValuesArray(const ir::TSEnumDeclaration *const enumDecl, ir::ClassDefinition *enumClass); diff --git a/ets2panda/test/compiler/ets/enum_as_class_member_getValue_call-expected.txt b/ets2panda/test/compiler/ets/enum_as_class_member_getValue_call-expected.txt index 27cf62006c..8540bfb296 100644 --- a/ets2panda/test/compiler/ets/enum_as_class_member_getValue_call-expected.txt +++ b/ets2panda/test/compiler/ets/enum_as_class_member_getValue_call-expected.txt @@ -21,7 +21,85 @@ } } }, - "superClass": null, + "superClass": { + "type": "ETSTypeReference", + "part": { + "type": "ETSTypeReferencePart", + "name": { + "type": "Identifier", + "name": "BaseEnum", + "decorators": [], + "loc": { + "start": { + "line": 20, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + }, + "end": { + "line": 20, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + } + } + }, + "typeParams": { + "type": "TSTypeParameterInstantiation", + "params": [ + { + "type": "ETSPrimitiveType", + "loc": { + "start": { + "line": 20, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + }, + "end": { + "line": 20, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + } + } + } + ], + "loc": { + "start": { + "line": 20, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + }, + "end": { + "line": 20, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + } + } + }, + "loc": { + "start": { + "line": 20, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + }, + "end": { + "line": 20, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + } + } + }, + "loc": { + "start": { + "line": 20, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + }, + "end": { + "line": 20, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + } + } + }, "implements": [], "body": [ { @@ -280,11 +358,123 @@ "program": "enum_as_class_member_getValue_call.ets" } } + }, + { + "type": "ETSParameterExpression", + "name": { + "type": "Identifier", + "name": "value", + "typeAnnotation": { + "type": "ETSPrimitiveType", + "loc": { + "start": { + "line": 20, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + }, + "end": { + "line": 20, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + } + } + }, + "decorators": [], + "loc": { + "start": { + "line": 20, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + }, + "end": { + "line": 20, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + } + } + }, + "loc": { + "start": { + "line": 20, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + }, + "end": { + "line": 20, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + } + } } ], "body": { "type": "BlockStatement", "statements": [ + { + "type": "ExpressionStatement", + "expression": { + "type": "CallExpression", + "callee": { + "type": "Super", + "loc": { + "start": { + "line": 20, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + }, + "end": { + "line": 20, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + } + } + }, + "arguments": [ + { + "type": "Identifier", + "name": "value", + "decorators": [], + "loc": { + "start": { + "line": 20, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + }, + "end": { + "line": 20, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + } + } + } + ], + "optional": false, + "loc": { + "start": { + "line": 20, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + }, + "end": { + "line": 20, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + } + } + }, + "loc": { + "start": { + "line": 20, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + }, + "end": { + "line": 20, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + } + } + }, { "type": "ExpressionStatement", "expression": { @@ -506,6 +696,22 @@ } }, "arguments": [ + { + "type": "NumberLiteral", + "value": 0, + "loc": { + "start": { + "line": 20, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + }, + "end": { + "line": 20, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + } + } + }, { "type": "NumberLiteral", "value": 0, @@ -673,6 +879,22 @@ } }, "arguments": [ + { + "type": "NumberLiteral", + "value": 1, + "loc": { + "start": { + "line": 20, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + }, + "end": { + "line": 20, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + } + } + }, { "type": "NumberLiteral", "value": 1, @@ -840,6 +1062,22 @@ } }, "arguments": [ + { + "type": "NumberLiteral", + "value": 2, + "loc": { + "start": { + "line": 20, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + }, + "end": { + "line": 20, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + } + } + }, { "type": "NumberLiteral", "value": 2, @@ -4921,14 +5159,13 @@ } } }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "ClassProperty", - "key": { + "superClass": { + "type": "ETSTypeReference", + "part": { + "type": "ETSTypeReferencePart", + "name": { "type": "Identifier", - "name": "#ordinal", + "name": "BaseEnum", "decorators": [], "loc": { "start": { @@ -4943,25 +5180,136 @@ } } }, - "accessibility": "private", - "static": false, - "readonly": true, - "declare": false, - "optional": false, - "computed": false, - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 26, - "column": 1, - "program": "enum_as_class_member_getValue_call.ets" - }, - "end": { - "line": 26, - "column": 1, - "program": "enum_as_class_member_getValue_call.ets" - } + "typeParams": { + "type": "TSTypeParameterInstantiation", + "params": [ + { + "type": "ETSTypeReference", + "part": { + "type": "ETSTypeReferencePart", + "name": { + "type": "Identifier", + "name": "String", + "decorators": [], + "loc": { + "start": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + }, + "end": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + } + } + }, + "loc": { + "start": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + }, + "end": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + } + } + }, + "loc": { + "start": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + }, + "end": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + } + } + } + ], + "loc": { + "start": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + }, + "end": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + } + } + }, + "loc": { + "start": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + }, + "end": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + } + } + }, + "loc": { + "start": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + }, + "end": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + } + } + }, + "implements": [], + "body": [ + { + "type": "ClassProperty", + "key": { + "type": "Identifier", + "name": "#ordinal", + "decorators": [], + "loc": { + "start": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + }, + "end": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + } + } + }, + "accessibility": "private", + "static": false, + "readonly": true, + "declare": false, + "optional": false, + "computed": false, + "typeAnnotation": { + "type": "ETSPrimitiveType", + "loc": { + "start": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + }, + "end": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + } } }, "definite": false, @@ -5180,11 +5528,155 @@ "program": "enum_as_class_member_getValue_call.ets" } } + }, + { + "type": "ETSParameterExpression", + "name": { + "type": "Identifier", + "name": "value", + "typeAnnotation": { + "type": "ETSTypeReference", + "part": { + "type": "ETSTypeReferencePart", + "name": { + "type": "Identifier", + "name": "String", + "decorators": [], + "loc": { + "start": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + }, + "end": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + } + } + }, + "loc": { + "start": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + }, + "end": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + } + } + }, + "loc": { + "start": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + }, + "end": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + } + } + }, + "decorators": [], + "loc": { + "start": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + }, + "end": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + } + } + }, + "loc": { + "start": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + }, + "end": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + } + } } ], "body": { "type": "BlockStatement", "statements": [ + { + "type": "ExpressionStatement", + "expression": { + "type": "CallExpression", + "callee": { + "type": "Super", + "loc": { + "start": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + }, + "end": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + } + } + }, + "arguments": [ + { + "type": "Identifier", + "name": "value", + "decorators": [], + "loc": { + "start": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + }, + "end": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + } + } + } + ], + "optional": false, + "loc": { + "start": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + }, + "end": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + } + } + }, + "loc": { + "start": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + }, + "end": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + } + } + }, { "type": "ExpressionStatement", "expression": { @@ -5421,6 +5913,22 @@ "program": "enum_as_class_member_getValue_call.ets" } } + }, + { + "type": "StringLiteral", + "value": "CIRCLE", + "loc": { + "start": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + }, + "end": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + } + } } ], "loc": { @@ -5588,6 +6096,22 @@ "program": "enum_as_class_member_getValue_call.ets" } } + }, + { + "type": "StringLiteral", + "value": "SQUARE", + "loc": { + "start": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + }, + "end": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + } + } } ], "loc": { @@ -5755,6 +6279,22 @@ "program": "enum_as_class_member_getValue_call.ets" } } + }, + { + "type": "StringLiteral", + "value": "TRIANGLE", + "loc": { + "start": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + }, + "end": { + "line": 26, + "column": 1, + "program": "enum_as_class_member_getValue_call.ets" + } + } } ], "loc": { diff --git a/ets2panda/test/compiler/ets/import_tests/enum_export-expected.txt b/ets2panda/test/compiler/ets/import_tests/enum_export-expected.txt index 26730a1901..b2189b2a4d 100644 --- a/ets2panda/test/compiler/ets/import_tests/enum_export-expected.txt +++ b/ets2panda/test/compiler/ets/import_tests/enum_export-expected.txt @@ -21,7 +21,85 @@ } } }, - "superClass": null, + "superClass": { + "type": "ETSTypeReference", + "part": { + "type": "ETSTypeReferencePart", + "name": { + "type": "Identifier", + "name": "BaseEnum", + "decorators": [], + "loc": { + "start": { + "line": 20, + "column": 9, + "program": "enum_export.ets" + }, + "end": { + "line": 20, + "column": 9, + "program": "enum_export.ets" + } + } + }, + "typeParams": { + "type": "TSTypeParameterInstantiation", + "params": [ + { + "type": "ETSPrimitiveType", + "loc": { + "start": { + "line": 20, + "column": 9, + "program": "enum_export.ets" + }, + "end": { + "line": 20, + "column": 9, + "program": "enum_export.ets" + } + } + } + ], + "loc": { + "start": { + "line": 20, + "column": 9, + "program": "enum_export.ets" + }, + "end": { + "line": 20, + "column": 9, + "program": "enum_export.ets" + } + } + }, + "loc": { + "start": { + "line": 20, + "column": 9, + "program": "enum_export.ets" + }, + "end": { + "line": 20, + "column": 9, + "program": "enum_export.ets" + } + } + }, + "loc": { + "start": { + "line": 20, + "column": 9, + "program": "enum_export.ets" + }, + "end": { + "line": 20, + "column": 9, + "program": "enum_export.ets" + } + } + }, "implements": [], "body": [ { @@ -174,82 +252,14 @@ "program": "enum_export.ets" } } - } - ], - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "ExpressionStatement", - "expression": { - "type": "AssignmentExpression", - "operator": "=", - "left": { - "type": "MemberExpression", - "object": { - "type": "ThisExpression", - "loc": { - "start": { - "line": 20, - "column": 9, - "program": "enum_export.ets" - }, - "end": { - "line": 20, - "column": 9, - "program": "enum_export.ets" - } - } - }, - "property": { - "type": "Identifier", - "name": "#ordinal", - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 9, - "program": "enum_export.ets" - }, - "end": { - "line": 20, - "column": 9, - "program": "enum_export.ets" - } - } - }, - "computed": false, - "optional": false, - "loc": { - "start": { - "line": 20, - "column": 9, - "program": "enum_export.ets" - }, - "end": { - "line": 20, - "column": 9, - "program": "enum_export.ets" - } - } - }, - "right": { - "type": "Identifier", - "name": "ordinal", - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 9, - "program": "enum_export.ets" - }, - "end": { - "line": 20, - "column": 9, - "program": "enum_export.ets" - } - } - }, + }, + { + "type": "ETSParameterExpression", + "name": { + "type": "Identifier", + "name": "value", + "typeAnnotation": { + "type": "ETSPrimitiveType", "loc": { "start": { "line": 20, @@ -263,6 +273,7 @@ } } }, + "decorators": [], "loc": { "start": { "line": 20, @@ -275,8 +286,24 @@ "program": "enum_export.ets" } } + }, + "loc": { + "start": { + "line": 20, + "column": 9, + "program": "enum_export.ets" + }, + "end": { + "line": 20, + "column": 9, + "program": "enum_export.ets" + } } - ], + } + ], + "body": { + "type": "BlockStatement", + "statements": [], "loc": { "start": { "line": 20, @@ -400,6 +427,22 @@ } }, "arguments": [ + { + "type": "NumberLiteral", + "value": 0, + "loc": { + "start": { + "line": 20, + "column": 9, + "program": "enum_export.ets" + }, + "end": { + "line": 20, + "column": 9, + "program": "enum_export.ets" + } + } + }, { "type": "NumberLiteral", "value": 0, @@ -2356,14 +2399,13 @@ } } }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "ClassProperty", - "key": { + "superClass": { + "type": "ETSTypeReference", + "part": { + "type": "ETSTypeReferencePart", + "name": { "type": "Identifier", - "name": "#ordinal", + "name": "BaseEnum", "decorators": [], "loc": { "start": { @@ -2378,14 +2420,25 @@ } } }, - "accessibility": "private", - "static": false, - "readonly": true, - "declare": false, - "optional": false, - "computed": false, - "typeAnnotation": { - "type": "ETSPrimitiveType", + "typeParams": { + "type": "TSTypeParameterInstantiation", + "params": [ + { + "type": "ETSPrimitiveType", + "loc": { + "start": { + "line": 22, + "column": 8, + "program": "enum_export.ets" + }, + "end": { + "line": 22, + "column": 8, + "program": "enum_export.ets" + } + } + } + ], "loc": { "start": { "line": 22, @@ -2399,8 +2452,6 @@ } } }, - "definite": false, - "decorators": [], "loc": { "start": { "line": 22, @@ -2414,11 +2465,26 @@ } } }, + "loc": { + "start": { + "line": 22, + "column": 8, + "program": "enum_export.ets" + }, + "end": { + "line": 22, + "column": 8, + "program": "enum_export.ets" + } + } + }, + "implements": [], + "body": [ { - "type": "MethodDefinition", + "type": "ClassProperty", "key": { "type": "Identifier", - "name": "", + "name": "#ordinal", "decorators": [], "loc": { "start": { @@ -2433,24 +2499,79 @@ } } }, - "kind": "method", "accessibility": "private", - "static": true, + "static": false, + "readonly": true, + "declare": false, "optional": false, "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "", - "decorators": [], - "loc": { - "start": { - "line": 22, - "column": 8, - "program": "enum_export.ets" + "typeAnnotation": { + "type": "ETSPrimitiveType", + "loc": { + "start": { + "line": 22, + "column": 8, + "program": "enum_export.ets" + }, + "end": { + "line": 22, + "column": 8, + "program": "enum_export.ets" + } + } + }, + "definite": false, + "decorators": [], + "loc": { + "start": { + "line": 22, + "column": 8, + "program": "enum_export.ets" + }, + "end": { + "line": 22, + "column": 8, + "program": "enum_export.ets" + } + } + }, + { + "type": "MethodDefinition", + "key": { + "type": "Identifier", + "name": "", + "decorators": [], + "loc": { + "start": { + "line": 22, + "column": 8, + "program": "enum_export.ets" + }, + "end": { + "line": 22, + "column": 8, + "program": "enum_export.ets" + } + } + }, + "kind": "method", + "accessibility": "private", + "static": true, + "optional": false, + "computed": false, + "value": { + "type": "FunctionExpression", + "function": { + "type": "ScriptFunction", + "id": { + "type": "Identifier", + "name": "", + "decorators": [], + "loc": { + "start": { + "line": 22, + "column": 8, + "program": "enum_export.ets" }, "end": { "line": 22, @@ -2615,11 +2736,123 @@ "program": "enum_export.ets" } } + }, + { + "type": "ETSParameterExpression", + "name": { + "type": "Identifier", + "name": "value", + "typeAnnotation": { + "type": "ETSPrimitiveType", + "loc": { + "start": { + "line": 22, + "column": 8, + "program": "enum_export.ets" + }, + "end": { + "line": 22, + "column": 8, + "program": "enum_export.ets" + } + } + }, + "decorators": [], + "loc": { + "start": { + "line": 22, + "column": 8, + "program": "enum_export.ets" + }, + "end": { + "line": 22, + "column": 8, + "program": "enum_export.ets" + } + } + }, + "loc": { + "start": { + "line": 22, + "column": 8, + "program": "enum_export.ets" + }, + "end": { + "line": 22, + "column": 8, + "program": "enum_export.ets" + } + } } ], "body": { "type": "BlockStatement", "statements": [ + { + "type": "ExpressionStatement", + "expression": { + "type": "CallExpression", + "callee": { + "type": "Super", + "loc": { + "start": { + "line": 22, + "column": 8, + "program": "enum_export.ets" + }, + "end": { + "line": 22, + "column": 8, + "program": "enum_export.ets" + } + } + }, + "arguments": [ + { + "type": "Identifier", + "name": "value", + "decorators": [], + "loc": { + "start": { + "line": 22, + "column": 8, + "program": "enum_export.ets" + }, + "end": { + "line": 22, + "column": 8, + "program": "enum_export.ets" + } + } + } + ], + "optional": false, + "loc": { + "start": { + "line": 22, + "column": 8, + "program": "enum_export.ets" + }, + "end": { + "line": 22, + "column": 8, + "program": "enum_export.ets" + } + } + }, + "loc": { + "start": { + "line": 22, + "column": 8, + "program": "enum_export.ets" + }, + "end": { + "line": 22, + "column": 8, + "program": "enum_export.ets" + } + } + }, { "type": "ExpressionStatement", "expression": { @@ -2841,6 +3074,22 @@ } }, "arguments": [ + { + "type": "NumberLiteral", + "value": 0, + "loc": { + "start": { + "line": 22, + "column": 8, + "program": "enum_export.ets" + }, + "end": { + "line": 22, + "column": 8, + "program": "enum_export.ets" + } + } + }, { "type": "NumberLiteral", "value": 0, @@ -3023,6 +3272,22 @@ "program": "enum_export.ets" } } + }, + { + "type": "NumberLiteral", + "value": 42, + "loc": { + "start": { + "line": 22, + "column": 8, + "program": "enum_export.ets" + }, + "end": { + "line": 22, + "column": 8, + "program": "enum_export.ets" + } + } } ], "loc": { @@ -3190,6 +3455,22 @@ "program": "enum_export.ets" } } + }, + { + "type": "NumberLiteral", + "value": 43, + "loc": { + "start": { + "line": 22, + "column": 8, + "program": "enum_export.ets" + }, + "end": { + "line": 22, + "column": 8, + "program": "enum_export.ets" + } + } } ], "loc": { @@ -7256,7 +7537,117 @@ } } }, - "superClass": null, + "superClass": { + "type": "ETSTypeReference", + "part": { + "type": "ETSTypeReferencePart", + "name": { + "type": "Identifier", + "name": "BaseEnum", + "decorators": [], + "loc": { + "start": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + }, + "end": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + } + } + }, + "typeParams": { + "type": "TSTypeParameterInstantiation", + "params": [ + { + "type": "ETSTypeReference", + "part": { + "type": "ETSTypeReferencePart", + "name": { + "type": "Identifier", + "name": "String", + "decorators": [], + "loc": { + "start": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + }, + "end": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + } + } + }, + "loc": { + "start": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + }, + "end": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + } + } + }, + "loc": { + "start": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + }, + "end": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + } + } + } + ], + "loc": { + "start": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + }, + "end": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + } + } + }, + "loc": { + "start": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + }, + "end": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + } + } + }, + "loc": { + "start": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + }, + "end": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + } + } + }, "implements": [], "body": [ { @@ -7515,11 +7906,155 @@ "program": "enum_export.ets" } } + }, + { + "type": "ETSParameterExpression", + "name": { + "type": "Identifier", + "name": "value", + "typeAnnotation": { + "type": "ETSTypeReference", + "part": { + "type": "ETSTypeReferencePart", + "name": { + "type": "Identifier", + "name": "String", + "decorators": [], + "loc": { + "start": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + }, + "end": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + } + } + }, + "loc": { + "start": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + }, + "end": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + } + } + }, + "loc": { + "start": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + }, + "end": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + } + } + }, + "decorators": [], + "loc": { + "start": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + }, + "end": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + } + } + }, + "loc": { + "start": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + }, + "end": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + } + } } ], "body": { "type": "BlockStatement", "statements": [ + { + "type": "ExpressionStatement", + "expression": { + "type": "CallExpression", + "callee": { + "type": "Super", + "loc": { + "start": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + }, + "end": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + } + } + }, + "arguments": [ + { + "type": "Identifier", + "name": "value", + "decorators": [], + "loc": { + "start": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + }, + "end": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + } + } + } + ], + "optional": false, + "loc": { + "start": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + }, + "end": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + } + } + }, + "loc": { + "start": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + }, + "end": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + } + } + }, { "type": "ExpressionStatement", "expression": { @@ -7756,6 +8291,22 @@ "program": "enum_export.ets" } } + }, + { + "type": "StringLiteral", + "value": "fopen", + "loc": { + "start": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + }, + "end": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + } + } } ], "loc": { @@ -7923,6 +8474,22 @@ "program": "enum_export.ets" } } + }, + { + "type": "StringLiteral", + "value": "fclose", + "loc": { + "start": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + }, + "end": { + "line": 26, + "column": 8, + "program": "enum_export.ets" + } + } } ], "loc": { diff --git a/ets2panda/test/parser/ets/declare_enum-expected.txt b/ets2panda/test/parser/ets/declare_enum-expected.txt index e2aaf71412..cb2de59c3c 100644 --- a/ets2panda/test/parser/ets/declare_enum-expected.txt +++ b/ets2panda/test/parser/ets/declare_enum-expected.txt @@ -21,7 +21,85 @@ } } }, - "superClass": null, + "superClass": { + "type": "ETSTypeReference", + "part": { + "type": "ETSTypeReferencePart", + "name": { + "type": "Identifier", + "name": "BaseEnum", + "decorators": [], + "loc": { + "start": { + "line": 16, + "column": 9, + "program": "declare_enum.ets" + }, + "end": { + "line": 16, + "column": 9, + "program": "declare_enum.ets" + } + } + }, + "typeParams": { + "type": "TSTypeParameterInstantiation", + "params": [ + { + "type": "ETSPrimitiveType", + "loc": { + "start": { + "line": 16, + "column": 9, + "program": "declare_enum.ets" + }, + "end": { + "line": 16, + "column": 9, + "program": "declare_enum.ets" + } + } + } + ], + "loc": { + "start": { + "line": 16, + "column": 9, + "program": "declare_enum.ets" + }, + "end": { + "line": 16, + "column": 9, + "program": "declare_enum.ets" + } + } + }, + "loc": { + "start": { + "line": 16, + "column": 9, + "program": "declare_enum.ets" + }, + "end": { + "line": 16, + "column": 9, + "program": "declare_enum.ets" + } + } + }, + "loc": { + "start": { + "line": 16, + "column": 9, + "program": "declare_enum.ets" + }, + "end": { + "line": 16, + "column": 9, + "program": "declare_enum.ets" + } + } + }, "implements": [], "body": [ { @@ -174,82 +252,14 @@ "program": "declare_enum.ets" } } - } - ], - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "ExpressionStatement", - "expression": { - "type": "AssignmentExpression", - "operator": "=", - "left": { - "type": "MemberExpression", - "object": { - "type": "ThisExpression", - "loc": { - "start": { - "line": 16, - "column": 9, - "program": "declare_enum.ets" - }, - "end": { - "line": 16, - "column": 9, - "program": "declare_enum.ets" - } - } - }, - "property": { - "type": "Identifier", - "name": "#ordinal", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 9, - "program": "declare_enum.ets" - }, - "end": { - "line": 16, - "column": 9, - "program": "declare_enum.ets" - } - } - }, - "computed": false, - "optional": false, - "loc": { - "start": { - "line": 16, - "column": 9, - "program": "declare_enum.ets" - }, - "end": { - "line": 16, - "column": 9, - "program": "declare_enum.ets" - } - } - }, - "right": { - "type": "Identifier", - "name": "ordinal", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 9, - "program": "declare_enum.ets" - }, - "end": { - "line": 16, - "column": 9, - "program": "declare_enum.ets" - } - } - }, + }, + { + "type": "ETSParameterExpression", + "name": { + "type": "Identifier", + "name": "value", + "typeAnnotation": { + "type": "ETSPrimitiveType", "loc": { "start": { "line": 16, @@ -263,6 +273,7 @@ } } }, + "decorators": [], "loc": { "start": { "line": 16, @@ -275,8 +286,24 @@ "program": "declare_enum.ets" } } + }, + "loc": { + "start": { + "line": 16, + "column": 9, + "program": "declare_enum.ets" + }, + "end": { + "line": 16, + "column": 9, + "program": "declare_enum.ets" + } } - ], + } + ], + "body": { + "type": "BlockStatement", + "statements": [], "loc": { "start": { "line": 16, @@ -400,6 +427,22 @@ } }, "arguments": [ + { + "type": "NumberLiteral", + "value": 0, + "loc": { + "start": { + "line": 16, + "column": 9, + "program": "declare_enum.ets" + }, + "end": { + "line": 16, + "column": 9, + "program": "declare_enum.ets" + } + } + }, { "type": "NumberLiteral", "value": 0, @@ -567,6 +610,22 @@ } }, "arguments": [ + { + "type": "NumberLiteral", + "value": 1, + "loc": { + "start": { + "line": 16, + "column": 9, + "program": "declare_enum.ets" + }, + "end": { + "line": 16, + "column": 9, + "program": "declare_enum.ets" + } + } + }, { "type": "NumberLiteral", "value": 1, diff --git a/ets2panda/test/parser/ets/switch_enum_string_case-expected.txt b/ets2panda/test/parser/ets/switch_enum_string_case-expected.txt index 6c09ac3917..7b1934bdf3 100644 --- a/ets2panda/test/parser/ets/switch_enum_string_case-expected.txt +++ b/ets2panda/test/parser/ets/switch_enum_string_case-expected.txt @@ -21,7 +21,117 @@ } } }, - "superClass": null, + "superClass": { + "type": "ETSTypeReference", + "part": { + "type": "ETSTypeReferencePart", + "name": { + "type": "Identifier", + "name": "BaseEnum", + "decorators": [], + "loc": { + "start": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + }, + "end": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + } + } + }, + "typeParams": { + "type": "TSTypeParameterInstantiation", + "params": [ + { + "type": "ETSTypeReference", + "part": { + "type": "ETSTypeReferencePart", + "name": { + "type": "Identifier", + "name": "String", + "decorators": [], + "loc": { + "start": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + }, + "end": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + } + } + }, + "loc": { + "start": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + }, + "end": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + } + } + }, + "loc": { + "start": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + }, + "end": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + } + } + } + ], + "loc": { + "start": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + }, + "end": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + } + } + }, + "loc": { + "start": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + }, + "end": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + } + } + }, + "loc": { + "start": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + }, + "end": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + } + } + }, "implements": [], "body": [ { @@ -280,11 +390,155 @@ "program": "switch_enum_string_case.ets" } } + }, + { + "type": "ETSParameterExpression", + "name": { + "type": "Identifier", + "name": "value", + "typeAnnotation": { + "type": "ETSTypeReference", + "part": { + "type": "ETSTypeReferencePart", + "name": { + "type": "Identifier", + "name": "String", + "decorators": [], + "loc": { + "start": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + }, + "end": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + } + } + }, + "loc": { + "start": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + }, + "end": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + } + } + }, + "loc": { + "start": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + }, + "end": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + } + } + }, + "decorators": [], + "loc": { + "start": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + }, + "end": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + } + } + }, + "loc": { + "start": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + }, + "end": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + } + } } ], "body": { "type": "BlockStatement", "statements": [ + { + "type": "ExpressionStatement", + "expression": { + "type": "CallExpression", + "callee": { + "type": "Super", + "loc": { + "start": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + }, + "end": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + } + } + }, + "arguments": [ + { + "type": "Identifier", + "name": "value", + "decorators": [], + "loc": { + "start": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + }, + "end": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + } + } + } + ], + "optional": false, + "loc": { + "start": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + }, + "end": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + } + } + }, + "loc": { + "start": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + }, + "end": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + } + } + }, { "type": "ExpressionStatement", "expression": { @@ -521,6 +775,22 @@ "program": "switch_enum_string_case.ets" } } + }, + { + "type": "StringLiteral", + "value": "A", + "loc": { + "start": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + }, + "end": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + } + } } ], "loc": { @@ -688,6 +958,22 @@ "program": "switch_enum_string_case.ets" } } + }, + { + "type": "StringLiteral", + "value": "B", + "loc": { + "start": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + }, + "end": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + } + } } ], "loc": { @@ -855,6 +1141,22 @@ "program": "switch_enum_string_case.ets" } } + }, + { + "type": "StringLiteral", + "value": "C", + "loc": { + "start": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + }, + "end": { + "line": 20, + "column": 1, + "program": "switch_enum_string_case.ets" + } + } } ], "loc": { diff --git a/ets2panda/test/runtime/ets/enum_reference.ets b/ets2panda/test/runtime/ets/enum_reference.ets index e7951c5105..ec334ab566 100644 --- a/ets2panda/test/runtime/ets/enum_reference.ets +++ b/ets2panda/test/runtime/ets/enum_reference.ets @@ -17,5 +17,5 @@ enum Color { Red } enum Color2 { Red } function main(): void { - assertNE(Color.Red, Color2.Red) + assertEQ(Color.Red, Color2.Red) } -- Gitee From 67b6f6843aaa6f3180c31d8944344d584b739504 Mon Sep 17 00:00:00 2001 From: mmorozov Date: Fri, 14 Mar 2025 16:13:04 +0300 Subject: [PATCH 098/268] Fix generic union runtime failure Issue: https://gitee.com/openharmony/arkcompiler_runtime_core/issues/IC2TAU Change-Id: I9107b06820bb90fb5ea6a74e57b17061d6f553b0 Signed-off-by: mmorozov --- ets2panda/checker/ETSchecker.h | 3 ++ ets2panda/checker/ets/typeCheckingHelpers.cpp | 38 +++++++++++++++ .../compiler/lowering/ets/unionLowering.cpp | 6 ++- ets2panda/ir/expressions/memberExpression.cpp | 2 + .../compiler/ets/union_generic_class_neg.ets | 48 +++++++++++++++++++ .../test/runtime/ets/union_generic_class.ets | 43 +++++++++++++++++ ets2panda/test/runtime/ets/union_type_RTE.ets | 41 ++++++++++++++++ 7 files changed, 179 insertions(+), 2 deletions(-) create mode 100644 ets2panda/test/ast/compiler/ets/union_generic_class_neg.ets create mode 100644 ets2panda/test/runtime/ets/union_generic_class.ets create mode 100644 ets2panda/test/runtime/ets/union_type_RTE.ets diff --git a/ets2panda/checker/ETSchecker.h b/ets2panda/checker/ETSchecker.h index 44ed5a9c1c..36bae80864 100644 --- a/ets2panda/checker/ETSchecker.h +++ b/ets2panda/checker/ETSchecker.h @@ -169,6 +169,7 @@ public: Type *GuaranteedTypeForUncheckedCast(Type *base, Type *substituted); Type *GuaranteedTypeForUncheckedCallReturn(Signature *sig); Type *GuaranteedTypeForUncheckedPropertyAccess(varbinder::Variable *prop); + Type *GuaranteedTypeForUnionFieldAccess(ir::MemberExpression *memberExpression, ETSUnionType *etsUnionType); [[nodiscard]] bool IsETSChecker() const noexcept override { @@ -945,6 +946,8 @@ private: void CheckProgram(parser::Program *program, bool runAnalysis = false); void CheckWarnings(parser::Program *program, const util::Options &options); + Type *ResolveUnionUncheckedType(ArenaVector &&apparentTypes); + bool ComputeSuperType(ETSObjectType *type); template diff --git a/ets2panda/checker/ets/typeCheckingHelpers.cpp b/ets2panda/checker/ets/typeCheckingHelpers.cpp index 3ad56e644b..8055b97927 100644 --- a/ets2panda/checker/ets/typeCheckingHelpers.cpp +++ b/ets2panda/checker/ets/typeCheckingHelpers.cpp @@ -638,6 +638,44 @@ Type *ETSChecker::GuaranteedTypeForUncheckedCallReturn(Signature *sig) return GuaranteedTypeForUncheckedCast(MaybeBoxType(baseSig->ReturnType()), MaybeBoxType(sig->ReturnType())); } +Type *ETSChecker::ResolveUnionUncheckedType(ArenaVector &&apparentTypes) +{ + if (apparentTypes.empty()) { + return nullptr; + } + auto *unionType = CreateETSUnionType(std::move(apparentTypes)); + if (unionType->IsETSUnionType()) { + checker::Type *typeLUB = unionType->AsETSUnionType()->GetAssemblerLUB(); + return typeLUB; + } + // Is case of single apparent type, just return itself + return unionType; +} + +Type *ETSChecker::GuaranteedTypeForUnionFieldAccess(ir::MemberExpression *memberExpression, ETSUnionType *etsUnionType) +{ + const auto &types = etsUnionType->ConstituentTypes(); + ArenaVector apparentTypes {Allocator()->Adapter()}; + const auto &propertyName = memberExpression->Property()->AsIdentifier()->Name(); + for (auto *type : types) { + auto searchFlags = PropertySearchFlags::SEARCH_FIELD | PropertySearchFlags::SEARCH_METHOD | + PropertySearchFlags::SEARCH_IN_BASE; + if (!type->IsETSObjectType()) { + return nullptr; + } + auto *fieldVar = type->AsETSObjectType()->GetProperty(propertyName, searchFlags); + if (fieldVar == nullptr) { + return nullptr; + } + // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) + auto *fieldType = GuaranteedTypeForUncheckedPropertyAccess(fieldVar); + if (fieldType != nullptr) { + apparentTypes.push_back(fieldType); + } + } + return ResolveUnionUncheckedType(std::move(apparentTypes)); +} + bool ETSChecker::IsAllowedTypeAliasRecursion(const ir::TSTypeAliasDeclaration *typeAliasNode, std::unordered_set &typeAliases) { diff --git a/ets2panda/compiler/lowering/ets/unionLowering.cpp b/ets2panda/compiler/lowering/ets/unionLowering.cpp index 80fe82ec8c..6a961b9c94 100644 --- a/ets2panda/compiler/lowering/ets/unionLowering.cpp +++ b/ets2panda/compiler/lowering/ets/unionLowering.cpp @@ -137,6 +137,8 @@ static varbinder::LocalVariable *CreateNamedAccessProperty(checker::ETSChecker * auto *const accessClass = GetUnionAccessClass(checker, varbinder, GetAccessClassName(unionType)); auto propName = expr->Property()->AsIdentifier()->Name(); auto fieldType = expr->TsType(); + auto uncheckedType = expr->UncheckedType(); + auto *typeToSet = uncheckedType == nullptr ? fieldType : uncheckedType; // Create field name for synthetic class auto *fieldIdent = checker->AllocNode(propName, allocator); @@ -148,9 +150,9 @@ static varbinder::LocalVariable *CreateNamedAccessProperty(checker::ETSChecker * // Add the declaration to the scope auto [decl, var] = varbinder->NewVarDecl(fieldIdent->Start(), fieldIdent->Name()); var->AddFlag(varbinder::VariableFlags::PROPERTY); - var->SetTsType(fieldType); + var->SetTsType(typeToSet); fieldIdent->SetVariable(var); - field->SetTsType(fieldType); + field->SetTsType(typeToSet); decl->BindNode(field); ArenaVector fieldDecl {allocator->Adapter()}; diff --git a/ets2panda/ir/expressions/memberExpression.cpp b/ets2panda/ir/expressions/memberExpression.cpp index f5c1ff44e7..6e89594587 100644 --- a/ets2panda/ir/expressions/memberExpression.cpp +++ b/ets2panda/ir/expressions/memberExpression.cpp @@ -255,6 +255,8 @@ checker::Type *MemberExpression::AdjustType(checker::ETSChecker *checker, checke uncheckedType_ = checker->GuaranteedTypeForUncheckedCast(objType->AsETSArrayType()->ElementType(), type); } else if (IsComputed() && objType->IsETSTupleType()) { uncheckedType_ = checker->GuaranteedTypeForUncheckedCast(objType->AsETSTupleType()->GetLubType(), type); + } else if (objType->IsETSUnionType()) { + uncheckedType_ = checker->GuaranteedTypeForUnionFieldAccess(this, objType->AsETSUnionType()); } else if (checker->IsExtensionAccessorFunctionType(type)) { SetTsType(type); checker::Type *accessorReturnType = checker->GetExtensionAccessorReturnType(this); diff --git a/ets2panda/test/ast/compiler/ets/union_generic_class_neg.ets b/ets2panda/test/ast/compiler/ets/union_generic_class_neg.ets new file mode 100644 index 0000000000..7bfd2cf937 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/union_generic_class_neg.ets @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class A { + fld: T + constructor(p: T) { + this.fld = p + } +} + +class B { + fld: string = 'b' +} + +class C { + fld: Int = 10 +} + +let u1: B|C = new B +let u2: B|C = new C + +let u3: A|A = new A(11) +let u4: A|A = new A('a') + +function main() { + assertEQ(u1.fld, 'b') + assertEQ(u2.fld, 10) + + assertEQ(u3.fld, 11) + assertEQ(u4.fld, 'a') +} + +/* @@? 38:14 Error TypeError: Member type must be the same for all union objects. */ +/* @@? 39:14 Error TypeError: Member type must be the same for all union objects. */ +/* @@? 41:14 Error TypeError: Member type must be the same for all union objects. */ +/* @@? 42:14 Error TypeError: Member type must be the same for all union objects. */ diff --git a/ets2panda/test/runtime/ets/union_generic_class.ets b/ets2panda/test/runtime/ets/union_generic_class.ets new file mode 100644 index 0000000000..969061f19a --- /dev/null +++ b/ets2panda/test/runtime/ets/union_generic_class.ets @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class A { + fld: T + constructor(p: T) { + this.fld = p + } +} + +class B { + fld: string = 'b' +} + +class C { + fld: Int = 11 +} + +let u1: A|B = new A('a') +let u2: A|B = new B + +let u3: A|C = new A(10) +let u4: A|C = new C + +function main() { + assertEQ(u1.fld, 'a') + assertEQ(u2.fld, 'b') + + assertEQ(u3.fld, 10) + assertEQ(u4.fld, 11) +} diff --git a/ets2panda/test/runtime/ets/union_type_RTE.ets b/ets2panda/test/runtime/ets/union_type_RTE.ets new file mode 100644 index 0000000000..18f876f826 --- /dev/null +++ b/ets2panda/test/runtime/ets/union_type_RTE.ets @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class A { + fld: T + constructor(p: T) { + this.fld = p + } +} + +class B { + fld: string = 'b' +} + +function main() { + let caught_counter = 0 + + try { + foo(new A(11) as Object) + } catch (error: ClassCastError) { + caught_counter++ + } + + assertEQ(caught_counter, 1) +} + +function foo(obj: Object) { + return (obj as A|B).fld +} -- Gitee From 04075f1bff2de593361409b4c2967e0ba5c0a8fe Mon Sep 17 00:00:00 2001 From: liyue Date: Tue, 22 Apr 2025 01:12:40 +0800 Subject: [PATCH 099/268] Fix record not found issue between SDK versions Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC2VVC Signed-off-by: liyue Change-Id: I0b75dd84291c18339f624b06fb69842f8e7f9cde --- es2panda/compiler/core/emitter/emitter.cpp | 8 +- es2panda/compiler/core/pandagen.cpp | 3 +- es2panda/parser/parserImpl.cpp | 1 - .../availableTargetApiVersion/10/expected.txt | 2 +- .../availableTargetApiVersion/11/expected.txt | 2 +- .../availableTargetApiVersion/12/expected.txt | 2 +- .../availableTargetApiVersion/9/expected.txt | 2 +- ..._below_API12beta3_asm_version-expected.txt | 1 - ...ual_to_API12beta3_asm_version-expected.txt | 1 - ...supported_compile_asm_version-expected.txt | 1 - ..._below_API12beta3_asm_version-expected.txt | 1 - ...ual_to_API12beta3_asm_version-expected.txt | 1 - ...ual_to_API16beta3_asm_version-expected.txt | 1 - ..._below_API12beta3_asm_version-expected.txt | 1 - ...ual_to_API12beta3_asm_version-expected.txt | 1 - ...supported_compile_asm_version-expected.txt | 1 - ..._below_API12beta3_asm_version-expected.txt | 1 - ...ual_to_API12beta3_asm_version-expected.txt | 1 - ...supported_compile_asm_version-expected.txt | 1 - ..._below_API12beta3_asm_version-expected.txt | 1 - ...ual_to_API12beta3_asm_version-expected.txt | 1 - ...ual_to_API16beta3_asm_version-expected.txt | 1 - ..._below_API12beta3_asm_version-expected.txt | 1 - ...ual_to_API12beta3_asm_version-expected.txt | 1 - ...supported_compile_asm_version-expected.txt | 1 - ..._below_API12beta3_asm_version-expected.txt | 1 - ...ual_to_API12beta3_asm_version-expected.txt | 1 - ...e_for_below_API11_asm_version-expected.txt | 1 - ..._below_API12beta3_asm_version-expected.txt | 1 - ..._below_API12beta3_asm_version-expected.txt | 2 - ...ual_to_API12beta3_asm_version-expected.txt | 2 - ...e_for_below_API11_asm_version-expected.txt | 2 - ..._below_API12beta3_asm_version-expected.txt | 2 - ..._below_API12beta3_asm_version-expected.txt | 256 ------------------ ...ual_to_API12beta3_asm_version-expected.txt | 256 ------------------ ...e_for_below_API11_asm_version-expected.txt | 256 ------------------ ..._below_API12beta3_asm_version-expected.txt | 256 ------------------ ...ual_to_API12beta3_asm_version-expected.txt | 1 - ...ual_to_API16beta3_asm_version-expected.txt | 1 - ...ual_to_API12beta3_asm_version-expected.txt | 1 - ...ual_to_API16beta3_asm_version-expected.txt | 1 - es2panda/util/helpers.cpp | 4 + es2panda/util/helpers.h | 2 + 43 files changed, 18 insertions(+), 1066 deletions(-) diff --git a/es2panda/compiler/core/emitter/emitter.cpp b/es2panda/compiler/core/emitter/emitter.cpp index b1799b3210..5f760e5a3e 100644 --- a/es2panda/compiler/core/emitter/emitter.cpp +++ b/es2panda/compiler/core/emitter/emitter.cpp @@ -75,7 +75,9 @@ void FunctionEmitter::Generate(util::PatchFix *patchFixHelper) if (patchFixHelper != nullptr) { patchFixHelper->ProcessFunction(pg_, func_, literalBuffers_); } - GenExpectedPropertyCountAnnotation(); + if (util::Helpers::IsEnableExpectedPropertyCountApiVersion(pg_->Binder()->Program()->TargetApiVersion())) { + GenExpectedPropertyCountAnnotation(); + } GenSlotNumberAnnotation(); if (pg_->Context()->IsMergeAbc()) { GenConcurrentModuleRequestsAnnotation(); @@ -668,7 +670,9 @@ Emitter::Emitter(CompilerContext *context): source_lang_(context->SourceLang()) } AddSharedModuleRecord(context); AddScopeNamesRecord(context); - AddExpectedPropertyCountRecord(); + if (util::Helpers::IsEnableExpectedPropertyCountApiVersion(context->Binder()->Program()->TargetApiVersion())) { + AddExpectedPropertyCountRecord(); + } AddSlotNumberRecord(); if (context->IsMergeAbc()) { AddConcurrentModuleRequestsRecord(); diff --git a/es2panda/compiler/core/pandagen.cpp b/es2panda/compiler/core/pandagen.cpp index 4806d01e94..72071c9af2 100644 --- a/es2panda/compiler/core/pandagen.cpp +++ b/es2panda/compiler/core/pandagen.cpp @@ -105,7 +105,8 @@ void PandaGen::SetInSendable() size_t PandaGen::GetExpectedPropertyCount() const { - if (rootNode_->IsProgram()) { + if (rootNode_->IsProgram() || + !util::Helpers::IsEnableExpectedPropertyCountApiVersion(context_->Binder()->Program()->TargetApiVersion())) { return 0; } diff --git a/es2panda/parser/parserImpl.cpp b/es2panda/parser/parserImpl.cpp index 2d9643afcc..9b79f9e567 100644 --- a/es2panda/parser/parserImpl.cpp +++ b/es2panda/parser/parserImpl.cpp @@ -4087,7 +4087,6 @@ ir::ScriptFunction *ParserImpl::ParseFunction(ParserStatus newStatus, funcParamScope->BindNode(funcNode); funcNode->SetRange({startLoc, endLoc}); funcNode->CalculateFunctionExpectedPropertyCount(); - return funcNode; } diff --git a/es2panda/test/base64/availableTargetApiVersion/10/expected.txt b/es2panda/test/base64/availableTargetApiVersion/10/expected.txt index 7196886c4e..ea65d584ae 100644 --- a/es2panda/test/base64/availableTargetApiVersion/10/expected.txt +++ b/es2panda/test/base64/availableTargetApiVersion/10/expected.txt @@ -11,4 +11,4 @@ # See the License for the specific language governing permissions and # limitations under the License. -UEFOREEAAAAAAAAACQAAAJwBAAAAAAAAAAAAAAMAAAA8AAAAAQAAAJgBAAAAAAAASAAAAAEAAABIAAAArgAAAN8AAAASAQAAiAAAAJwBAAACAAAAcAAAAAMAAAB4AAAAAAAAAIQAAAABAAAAhAAAAN8AAAASAQAAiAAAAKIAAACpAAAARAEAADFoZWxsbyB3b3JsZCwgdmVyc2lvbiAxMCEAC3ByaW50AAdzdHIASUxfRVNFeHBlY3RlZFByb3BlcnR5Q291bnRBbm5vdGF0aW9uOwAAAAAAgUAAAAIAADNMX0VTU2xvdE51bWJlckFubm90YXRpb247AAAAAACBQAAAAgAAF2Z1bmNfbWFpbl8wABNMX0dMT0JBTDsAAAAAAAEAAQIAAAEAAAAFAQAAiAIBYQEAAAIABYwBAAAGVAEAAAAA7u4AABVTbG90TnVtYmVyAAAAAQBIAQAABQAAADcHAyEARHBEgUSSPgAASAAAAgA/AQEAYQU/AgIAYQZgBSoDBgBlC2uJAQ4A/////w8AAgARAAAAhgEAAA== +UEFOREEAAAAAAAAACQAAAGQBAAAAAAAAAAAAAAIAAAA8AAAAAQAAAGABAAAAAAAARAAAAAEAAABEAAAAqgAAAN0AAACEAAAAZAEAAAIAAABsAAAAAwAAAHQAAAAAAAAAgAAAAAEAAACAAAAAqgAAAN0AAACEAAAAngAAAKUAAAAOAQAAMWhlbGxvIHdvcmxkLCB2ZXJzaW9uIDEwIQALcHJpbnQAB3N0cgAzTF9FU1Nsb3ROdW1iZXJBbm5vdGF0aW9uOwAAAAAAgUAAAAIAABdmdW5jX21haW5fMAATTF9HTE9CQUw7AAAAAAABAAECAAABAAAA0AAAAIgCASsBAAACAAVWAQAABh4BAAAA7u4AABVTbG90TnVtYmVyAAAAAQASAQAABQAAADcHAyEARHBEgUSSPgAASAAAAgA/AQEAYQU/AgIAYQZgBSoDBgBlC2uJAQ4A/////w8AAgARAFABAAA= diff --git a/es2panda/test/base64/availableTargetApiVersion/11/expected.txt b/es2panda/test/base64/availableTargetApiVersion/11/expected.txt index d27a626eee..e4039082c8 100644 --- a/es2panda/test/base64/availableTargetApiVersion/11/expected.txt +++ b/es2panda/test/base64/availableTargetApiVersion/11/expected.txt @@ -11,4 +11,4 @@ # See the License for the specific language governing permissions and # limitations under the License. -UEFOREEAAAAAAAAACwACAJwBAAAAAAAAAAAAAAMAAAA8AAAAAQAAAJgBAAAAAAAASAAAAAEAAABIAAAArgAAAN8AAAASAQAAiAAAAJwBAAACAAAAcAAAAAMAAAB4AAAAAAAAAIQAAAABAAAAhAAAAN8AAAASAQAAiAAAAKIAAACpAAAARAEAADFoZWxsbyB3b3JsZCwgdmVyc2lvbiAxMSEAC3ByaW50AAdzdHIASUxfRVNFeHBlY3RlZFByb3BlcnR5Q291bnRBbm5vdGF0aW9uOwAAAAAAgUAAAAIAADNMX0VTU2xvdE51bWJlckFubm90YXRpb247AAAAAACBQAAAAgAAF2Z1bmNfbWFpbl8wABNMX0dMT0JBTDsAAAAAAAEAAQIAAAEAAAAFAQAAiAIBYQEAAAIABYwBAAAGVAEAAAAA7u4AABVTbG90TnVtYmVyAAAAAQBIAQAABQAAADcHAyEARHBEgUSSPgAASAAAAgA/AQEAYQU/AgIAYQZgBSoDBgBlC2uJAQ4A/////w8AAgARAAAAhgEAAA== +UEFOREEAAAAAAAAACwACAGQBAAAAAAAAAAAAAAIAAAA8AAAAAQAAAGABAAAAAAAARAAAAAEAAABEAAAAqgAAAN0AAACEAAAAZAEAAAIAAABsAAAAAwAAAHQAAAAAAAAAgAAAAAEAAACAAAAAqgAAAN0AAACEAAAAngAAAKUAAAAOAQAAMWhlbGxvIHdvcmxkLCB2ZXJzaW9uIDExIQALcHJpbnQAB3N0cgAzTF9FU1Nsb3ROdW1iZXJBbm5vdGF0aW9uOwAAAAAAgUAAAAIAABdmdW5jX21haW5fMAATTF9HTE9CQUw7AAAAAAABAAECAAABAAAA0AAAAIgCASsBAAACAAVWAQAABh4BAAAA7u4AABVTbG90TnVtYmVyAAAAAQASAQAABQAAADcHAyEARHBEgUSSPgAASAAAAgA/AQEAYQU/AgIAYQZgBSoDBgBlC2uJAQ4A/////w8AAgARAFABAAA= diff --git a/es2panda/test/base64/availableTargetApiVersion/12/expected.txt b/es2panda/test/base64/availableTargetApiVersion/12/expected.txt index 3308f1d348..5851b369e1 100644 --- a/es2panda/test/base64/availableTargetApiVersion/12/expected.txt +++ b/es2panda/test/base64/availableTargetApiVersion/12/expected.txt @@ -11,4 +11,4 @@ # See the License for the specific language governing permissions and # limitations under the License. -UEFOREEAAAAAAAAADAAGANgBAAAAAAAAAAAAAAQAAAA8AAAAAQAAANQBAAABAAAATAAAAAEAAABQAAAAugAAAOsAAAAdAQAAUAEAAIEBAACUAAAA2AEAAAQAAAB4AAAAAwAAAIgAAAD/////////////////////BgAAAOsAAAAdAQAAUAEAAJQAAACuAAAAtQAAADFoZWxsbyB3b3JsZCwgdmVyc2lvbiAxMiEAC3ByaW50AAdzdHIASUxfRVNFeHBlY3RlZFByb3BlcnR5Q291bnRBbm5vdGF0aW9uOwAAAAAAgUAAAAIAACtMX0VTU2NvcGVOYW1lc1JlY29yZDsAAAAAAAEBAAIAAAEAAAAbAQAAAAKBAQAAAAEAM0xfRVNTbG90TnVtYmVyQW5ub3RhdGlvbjsAAAAAAIFAAAACAAAXZnVuY19tYWluXzAAE0xfR0xPQkFMOwAAAAAAAQABAgAAAwD//0MBAACIAgGeAQAAAgAFyQEAAAaRAQAAAAAAAAAVU2xvdE51bWJlcgACAAEAhQEAAAUAAAA3BwMhAERwRIFEkj4AAEgAAAIAPwEBAGEFPwICAGEGYAUqAwYAZQtriQEOAP////8PAAIAEQAAwwEAAA== +UEFOREEAAAAAAAAADAAGAKQBAAAAAAAAAAAAAAMAAAA8AAAAAQAAAKABAAABAAAASAAAAAEAAABMAAAAtgAAAOgAAAAbAQAATAEAAJAAAACkAQAABAAAAHQAAAADAAAAhAAAAP////////////////////8GAAAAtgAAAOgAAAAbAQAAkAAAAKoAAACxAAAAMWhlbGxvIHdvcmxkLCB2ZXJzaW9uIDEyIQALcHJpbnQAB3N0cgArTF9FU1Njb3BlTmFtZXNSZWNvcmQ7AAAAAAABAQACAAABAAAA5gAAAAACTAEAAAABADNMX0VTU2xvdE51bWJlckFubm90YXRpb247AAAAAACBQAAAAgAAF2Z1bmNfbWFpbl8wABNMX0dMT0JBTDsAAAAAAAEAAQIAAAMA//8OAQAAiAIBaQEAAAIABZQBAAAGXAEAAAAAAAAAFVNsb3ROdW1iZXIAAgABAFABAAAFAAAANwcDIQBEcESBRJI+AABIAAACAD8BAQBhBT8CAgBhBmAFKgMGAGULa4kBDgD/////DwACABEAAACOAQAA diff --git a/es2panda/test/base64/availableTargetApiVersion/9/expected.txt b/es2panda/test/base64/availableTargetApiVersion/9/expected.txt index 4493d88c5e..3a5ba6e9a2 100644 --- a/es2panda/test/base64/availableTargetApiVersion/9/expected.txt +++ b/es2panda/test/base64/availableTargetApiVersion/9/expected.txt @@ -11,4 +11,4 @@ # See the License for the specific language governing permissions and # limitations under the License. -UEFOREEAAAAAAAAACQAAAJgBAAAAAAAAAAAAAAMAAAA8AAAAAQAAAJQBAAAAAAAASAAAAAEAAABIAAAArQAAAN4AAAARAQAAiAAAAJgBAAACAAAAcAAAAAMAAAB4AAAAAAAAAIQAAAABAAAAhAAAAN4AAAARAQAAiAAAAKEAAACoAAAAQgEAAC9oZWxsbyB3b3JsZCwgdmVyc2lvbiA5IQALcHJpbnQAB3N0cgBJTF9FU0V4cGVjdGVkUHJvcGVydHlDb3VudEFubm90YXRpb247AAAAAACBQAAAAgAAM0xfRVNTbG90TnVtYmVyQW5ub3RhdGlvbjsAAAAAAIFAAAACAAAXZnVuY19tYWluXzAAE0xfR0xPQkFMOwAAAAAAAQABAgAAAQAAAAQBAACIAgFfAQAAAgAFigEAAAZSAQAAAO7uAAAVU2xvdE51bWJlcgAAAAEARgEAAAUAAAA3BwMhAERwRIFEkj4AAEgAAAIAPwEBAGEFPwICAGEGYAUqAwYAZQtriQEOAP////8PAAIAEQCEAQAA +UEFOREEAAAAAAAAACQAAAGQBAAAAAAAAAAAAAAIAAAA8AAAAAQAAAGABAAAAAAAARAAAAAEAAABEAAAAqQAAANwAAACEAAAAZAEAAAIAAABsAAAAAwAAAHQAAAAAAAAAgAAAAAEAAACAAAAAqQAAANwAAACEAAAAnQAAAKQAAAAOAQAAL2hlbGxvIHdvcmxkLCB2ZXJzaW9uIDkhAAtwcmludAAHc3RyADNMX0VTU2xvdE51bWJlckFubm90YXRpb247AAAAAACBQAAAAgAAF2Z1bmNfbWFpbl8wABNMX0dMT0JBTDsAAAAAAAEAAQIAAAEAAADPAAAAiAIBKwEAAAIABVYBAAAGHgEAAAAA7u4AABVTbG90TnVtYmVyAAAAAQASAQAABQAAADcHAyEARHBEgUSSPgAASAAAAgA/AQEAYQU/AgIAYQZgBSoDBgBlC2uJAQ4A/////w8AAgARAFABAAA= diff --git a/es2panda/test/version_control/API11/bytecode_feature/class_init_callinit_supported_compile_for_below_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API11/bytecode_feature/class_init_callinit_supported_compile_for_below_API12beta3_asm_version-expected.txt index 2657d96753..eae6c92044 100644 --- a/es2panda/test/version_control/API11/bytecode_feature/class_init_callinit_supported_compile_for_below_API12beta3_asm_version-expected.txt +++ b/es2panda/test/version_control/API11/bytecode_feature/class_init_callinit_supported_compile_for_below_API12beta3_asm_version-expected.txt @@ -1,5 +1,4 @@ slotNum = 0x4 -expectedProperty = 0x1 .language ECMAScript .function any .A(any a0, any a1, any a2, any a3) { label_1: diff --git a/es2panda/test/version_control/API11/bytecode_feature/class_init_callinit_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API11/bytecode_feature/class_init_callinit_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt index 13a6183890..918314e6e1 100644 --- a/es2panda/test/version_control/API11/bytecode_feature/class_init_callinit_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt +++ b/es2panda/test/version_control/API11/bytecode_feature/class_init_callinit_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt @@ -1,5 +1,4 @@ slotNum = 0x4 -expectedProperty = 0x1 .language ECMAScript .function any .#~A=#A(any a0, any a1, any a2, any a3) { label_1: diff --git a/es2panda/test/version_control/API11/bytecode_feature/class_init_callinit_unsupported_compile_asm_version-expected.txt b/es2panda/test/version_control/API11/bytecode_feature/class_init_callinit_unsupported_compile_asm_version-expected.txt index 477926b113..f8ea73ca5f 100644 --- a/es2panda/test/version_control/API11/bytecode_feature/class_init_callinit_unsupported_compile_asm_version-expected.txt +++ b/es2panda/test/version_control/API11/bytecode_feature/class_init_callinit_unsupported_compile_asm_version-expected.txt @@ -1,5 +1,4 @@ slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .A(any a0, any a1, any a2, any a3) { label_1: diff --git a/es2panda/test/version_control/API11/bytecode_feature/class_private_property_supported_compile_for_below_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API11/bytecode_feature/class_private_property_supported_compile_for_below_API12beta3_asm_version-expected.txt index d5dbb31f3f..b7e43e9e1f 100644 --- a/es2panda/test/version_control/API11/bytecode_feature/class_private_property_supported_compile_for_below_API12beta3_asm_version-expected.txt +++ b/es2panda/test/version_control/API11/bytecode_feature/class_private_property_supported_compile_for_below_API12beta3_asm_version-expected.txt @@ -1,5 +1,4 @@ slotNum = 0x4 -expectedProperty = 0x1 .language ECMAScript .function any .TestPrivateProperty(any a0, any a1, any a2, any a3) { label_1: diff --git a/es2panda/test/version_control/API11/bytecode_feature/class_private_property_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API11/bytecode_feature/class_private_property_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt index a4e2f5e25d..d568dbc64c 100644 --- a/es2panda/test/version_control/API11/bytecode_feature/class_private_property_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt +++ b/es2panda/test/version_control/API11/bytecode_feature/class_private_property_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt @@ -1,5 +1,4 @@ slotNum = 0x4 -expectedProperty = 0x1 .language ECMAScript .function any .#~@0=#TestPrivateProperty(any a0, any a1, any a2, any a3) { label_1: diff --git a/es2panda/test/version_control/API11/bytecode_feature/class_private_property_supported_compile_for_higher_or_equal_to_API16beta3_asm_version-expected.txt b/es2panda/test/version_control/API11/bytecode_feature/class_private_property_supported_compile_for_higher_or_equal_to_API16beta3_asm_version-expected.txt index 90da189592..2d88735370 100644 --- a/es2panda/test/version_control/API11/bytecode_feature/class_private_property_supported_compile_for_higher_or_equal_to_API16beta3_asm_version-expected.txt +++ b/es2panda/test/version_control/API11/bytecode_feature/class_private_property_supported_compile_for_higher_or_equal_to_API16beta3_asm_version-expected.txt @@ -1,7 +1,6 @@ .language ECMAScript slotNum = 0x4 -expectedProperty = 0x1 .function any .#~@0=#TestPrivateProperty(any a0, any a1, any a2, any a3) { label_1: label_0: diff --git a/es2panda/test/version_control/API11/bytecode_feature/computed_property_name_as_class_key_supported_compile_for_below_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API11/bytecode_feature/computed_property_name_as_class_key_supported_compile_for_below_API12beta3_asm_version-expected.txt index 63208d0f05..0f3aceeaad 100644 --- a/es2panda/test/version_control/API11/bytecode_feature/computed_property_name_as_class_key_supported_compile_for_below_API12beta3_asm_version-expected.txt +++ b/es2panda/test/version_control/API11/bytecode_feature/computed_property_name_as_class_key_supported_compile_for_below_API12beta3_asm_version-expected.txt @@ -1,5 +1,4 @@ slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .A(any a0, any a1, any a2) { label_1: diff --git a/es2panda/test/version_control/API11/bytecode_feature/computed_property_name_as_class_key_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API11/bytecode_feature/computed_property_name_as_class_key_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt index e7087b0c6e..2c0f076a93 100644 --- a/es2panda/test/version_control/API11/bytecode_feature/computed_property_name_as_class_key_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt +++ b/es2panda/test/version_control/API11/bytecode_feature/computed_property_name_as_class_key_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt @@ -1,5 +1,4 @@ slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~A=#A(any a0, any a1, any a2) { label_1: diff --git a/es2panda/test/version_control/API11/bytecode_feature/computed_property_name_as_class_key_unsupported_compile_asm_version-expected.txt b/es2panda/test/version_control/API11/bytecode_feature/computed_property_name_as_class_key_unsupported_compile_asm_version-expected.txt index 71dce89694..2146d96643 100644 --- a/es2panda/test/version_control/API11/bytecode_feature/computed_property_name_as_class_key_unsupported_compile_asm_version-expected.txt +++ b/es2panda/test/version_control/API11/bytecode_feature/computed_property_name_as_class_key_unsupported_compile_asm_version-expected.txt @@ -1,5 +1,4 @@ slotNum = 0x0 -expectedProperty = 0x1 .language ECMAScript .function any .A(any a0, any a1, any a2) { label_1: diff --git a/es2panda/test/version_control/API11/bytecode_feature/define_ld_sendable_class_supported_compile_for_below_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API11/bytecode_feature/define_ld_sendable_class_supported_compile_for_below_API12beta3_asm_version-expected.txt index 69bb8f2086..abb8d603e8 100644 --- a/es2panda/test/version_control/API11/bytecode_feature/define_ld_sendable_class_supported_compile_for_below_API12beta3_asm_version-expected.txt +++ b/es2panda/test/version_control/API11/bytecode_feature/define_ld_sendable_class_supported_compile_for_below_API12beta3_asm_version-expected.txt @@ -13,7 +13,6 @@ label_2: } slotNum = 0x6 -expectedProperty = 0x2 .language ECMAScript .function any .TestTypeA(any a0, any a1, any a2) { label_1: diff --git a/es2panda/test/version_control/API11/bytecode_feature/define_ld_sendable_class_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API11/bytecode_feature/define_ld_sendable_class_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt index 67e2e6c37a..520550704f 100644 --- a/es2panda/test/version_control/API11/bytecode_feature/define_ld_sendable_class_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt +++ b/es2panda/test/version_control/API11/bytecode_feature/define_ld_sendable_class_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt @@ -13,7 +13,6 @@ label_2: } slotNum = 0x6 -expectedProperty = 0x2 .language ECMAScript .function any .#&X~@0=#TestTypeA(any a0, any a1, any a2) { label_1: diff --git a/es2panda/test/version_control/API11/bytecode_feature/define_ld_sendable_class_unsupported_compile_asm_version-expected.txt b/es2panda/test/version_control/API11/bytecode_feature/define_ld_sendable_class_unsupported_compile_asm_version-expected.txt index 6e671f61e2..c24923ed0e 100644 --- a/es2panda/test/version_control/API11/bytecode_feature/define_ld_sendable_class_unsupported_compile_asm_version-expected.txt +++ b/es2panda/test/version_control/API11/bytecode_feature/define_ld_sendable_class_unsupported_compile_asm_version-expected.txt @@ -32,7 +32,6 @@ label_8: .catchall label_2, end_label_3, label_9 slotNum = 0x6 -expectedProperty = 0x2 .language ECMAScript .function any .TestTypeA(any a0, any a1, any a2) { label_1: diff --git a/es2panda/test/version_control/API11/bytecode_feature/in_obj_syntax_supported_compile_for_below_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API11/bytecode_feature/in_obj_syntax_supported_compile_for_below_API12beta3_asm_version-expected.txt index 33c4531ae9..9809190ee5 100644 --- a/es2panda/test/version_control/API11/bytecode_feature/in_obj_syntax_supported_compile_for_below_API12beta3_asm_version-expected.txt +++ b/es2panda/test/version_control/API11/bytecode_feature/in_obj_syntax_supported_compile_for_below_API12beta3_asm_version-expected.txt @@ -1,5 +1,4 @@ slotNum = 0x4 -expectedProperty = 0x1 .language ECMAScript .function any .InObjSyntax(any a0, any a1, any a2, any a3) { label_1: diff --git a/es2panda/test/version_control/API11/bytecode_feature/in_obj_syntax_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API11/bytecode_feature/in_obj_syntax_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt index 4493a6c93d..0674d69a08 100644 --- a/es2panda/test/version_control/API11/bytecode_feature/in_obj_syntax_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt +++ b/es2panda/test/version_control/API11/bytecode_feature/in_obj_syntax_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt @@ -17,7 +17,6 @@ label_4: } slotNum = 0x4 -expectedProperty = 0x1 .language ECMAScript .function any .#~@0=#InObjSyntax(any a0, any a1, any a2, any a3) { label_1: diff --git a/es2panda/test/version_control/API11/bytecode_feature/in_obj_syntax_supported_compile_for_higher_or_equal_to_API16beta3_asm_version-expected.txt b/es2panda/test/version_control/API11/bytecode_feature/in_obj_syntax_supported_compile_for_higher_or_equal_to_API16beta3_asm_version-expected.txt index 46915b5bf7..6d4c25cbee 100644 --- a/es2panda/test/version_control/API11/bytecode_feature/in_obj_syntax_supported_compile_for_higher_or_equal_to_API16beta3_asm_version-expected.txt +++ b/es2panda/test/version_control/API11/bytecode_feature/in_obj_syntax_supported_compile_for_higher_or_equal_to_API16beta3_asm_version-expected.txt @@ -18,7 +18,6 @@ label_4: } slotNum = 0x4 -expectedProperty = 0x1 .function any .#~@0=#InObjSyntax(any a0, any a1, any a2, any a3) { label_1: label_0: diff --git a/es2panda/test/version_control/API11/bytecode_feature/public_field_replace_set_semantics_as_define_supported_compile_for_below_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API11/bytecode_feature/public_field_replace_set_semantics_as_define_supported_compile_for_below_API12beta3_asm_version-expected.txt index 9358f6779e..2417ecc1e7 100644 --- a/es2panda/test/version_control/API11/bytecode_feature/public_field_replace_set_semantics_as_define_supported_compile_for_below_API12beta3_asm_version-expected.txt +++ b/es2panda/test/version_control/API11/bytecode_feature/public_field_replace_set_semantics_as_define_supported_compile_for_below_API12beta3_asm_version-expected.txt @@ -1,5 +1,4 @@ slotNum = 0x2 -expectedProperty = 0x3 .language ECMAScript .function any .A(any a0, any a1, any a2) { label_1: diff --git a/es2panda/test/version_control/API11/bytecode_feature/public_field_replace_set_semantics_as_define_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API11/bytecode_feature/public_field_replace_set_semantics_as_define_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt index aa00c9181c..26d24c71b2 100644 --- a/es2panda/test/version_control/API11/bytecode_feature/public_field_replace_set_semantics_as_define_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt +++ b/es2panda/test/version_control/API11/bytecode_feature/public_field_replace_set_semantics_as_define_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt @@ -1,5 +1,4 @@ slotNum = 0x2 -expectedProperty = 0x3 .language ECMAScript .function any .#~A=#A(any a0, any a1, any a2) { label_1: diff --git a/es2panda/test/version_control/API11/bytecode_feature/public_field_replace_set_semantics_as_define_unsupported_compile_asm_version-expected.txt b/es2panda/test/version_control/API11/bytecode_feature/public_field_replace_set_semantics_as_define_unsupported_compile_asm_version-expected.txt index 302fa2a580..18d32ff7d1 100644 --- a/es2panda/test/version_control/API11/bytecode_feature/public_field_replace_set_semantics_as_define_unsupported_compile_asm_version-expected.txt +++ b/es2panda/test/version_control/API11/bytecode_feature/public_field_replace_set_semantics_as_define_unsupported_compile_asm_version-expected.txt @@ -1,5 +1,4 @@ slotNum = 0x0 -expectedProperty = 0x3 .language ECMAScript .function any .A(any a0, any a1, any a2) { label_1: diff --git a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_supported_compile_for_below_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_supported_compile_for_below_API12beta3_asm_version-expected.txt index 03c820216f..c79b885110 100644 --- a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_supported_compile_for_below_API12beta3_asm_version-expected.txt +++ b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_supported_compile_for_below_API12beta3_asm_version-expected.txt @@ -1,5 +1,4 @@ slotNum = 0x4 -expectedProperty = 0x2 .language ECMAScript .function any .SendableLazyLoading(any a0, any a1, any a2) { label_1: diff --git a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt index 048d8311b3..3709506177 100644 --- a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt +++ b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt @@ -1,5 +1,4 @@ slotNum = 0x4 -expectedProperty = 0x2 .language ECMAScript .function any .#~@0=#SendableLazyLoading(any a0, any a1, any a2) { label_1: diff --git a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_unsupported_compile_for_below_API11_asm_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_unsupported_compile_for_below_API11_asm_version-expected.txt index c856ace10e..dd9c93627b 100644 --- a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_unsupported_compile_for_below_API11_asm_version-expected.txt +++ b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_unsupported_compile_for_below_API11_asm_version-expected.txt @@ -1,5 +1,4 @@ slotNum = 0x4 -expectedProperty = 0x2 .language ECMAScript .function any .SendableLazyLoading(any a0, any a1, any a2) { label_1: diff --git a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_unsupported_compile_for_below_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_unsupported_compile_for_below_API12beta3_asm_version-expected.txt index 0d29c31ce7..6e71af8b31 100644 --- a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_unsupported_compile_for_below_API12beta3_asm_version-expected.txt +++ b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_unsupported_compile_for_below_API12beta3_asm_version-expected.txt @@ -1,5 +1,4 @@ slotNum = 0x4 -expectedProperty = 0x2 .language ECMAScript .function any .SendableLazyLoading(any a0, any a1, any a2) { label_1: diff --git a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_supported_compile_for_below_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_supported_compile_for_below_API12beta3_asm_version-expected.txt index c5f203f625..ab6c662e2d 100644 --- a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_supported_compile_for_below_API12beta3_asm_version-expected.txt +++ b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_supported_compile_for_below_API12beta3_asm_version-expected.txt @@ -1,5 +1,4 @@ slotNum = 0xa -expectedProperty = 0x2 .language ECMAScript .function any .SendableTestClass1(any a0, any a1, any a2) { label_1: @@ -20,7 +19,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass1(any a0, any a1, any a2) { label_1: diff --git a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt index eb03275011..d85ed5764e 100644 --- a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt +++ b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt @@ -1,5 +1,4 @@ slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@0=#TopLevelSendableClass1(any a0, any a1, any a2) { label_1: @@ -12,7 +11,6 @@ label_2: } slotNum = 0xa -expectedProperty = 0x2 .language ECMAScript .function any .#~@1=#SendableTestClass1(any a0, any a1, any a2) { label_1: diff --git a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_unsupported_compile_for_below_API11_asm_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_unsupported_compile_for_below_API11_asm_version-expected.txt index d42096de0c..fdad4e6d3a 100644 --- a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_unsupported_compile_for_below_API11_asm_version-expected.txt +++ b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_unsupported_compile_for_below_API11_asm_version-expected.txt @@ -1,5 +1,4 @@ slotNum = 0xa -expectedProperty = 0x2 .language ECMAScript .function any .SendableTestClass1(any a0, any a1, any a2) { label_1: @@ -20,7 +19,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass1(any a0, any a1, any a2) { label_1: diff --git a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_unsupported_compile_for_below_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_unsupported_compile_for_below_API12beta3_asm_version-expected.txt index 0f14e168d4..9648548b63 100644 --- a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_unsupported_compile_for_below_API12beta3_asm_version-expected.txt +++ b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_unsupported_compile_for_below_API12beta3_asm_version-expected.txt @@ -1,5 +1,4 @@ slotNum = 0xa -expectedProperty = 0x2 .language ECMAScript .function any .SendableTestClass1(any a0, any a1, any a2) { label_1: @@ -20,7 +19,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass1(any a0, any a1, any a2) { label_1: diff --git a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_supported_compile_for_below_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_supported_compile_for_below_API12beta3_asm_version-expected.txt index 6407e1d84b..1517375c8a 100644 --- a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_supported_compile_for_below_API12beta3_asm_version-expected.txt +++ b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_supported_compile_for_below_API12beta3_asm_version-expected.txt @@ -1,5 +1,4 @@ slotNum = 0x406 -expectedProperty = 0x101 .language ECMAScript .function any .SendableTestClass1(any a0, any a1, any a2) { label_1: @@ -1546,7 +1545,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass1(any a0, any a1, any a2) { label_1: @@ -1559,7 +1557,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass10(any a0, any a1, any a2) { label_1: @@ -1572,7 +1569,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass100(any a0, any a1, any a2) { label_1: @@ -1585,7 +1581,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass101(any a0, any a1, any a2) { label_1: @@ -1598,7 +1593,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass102(any a0, any a1, any a2) { label_1: @@ -1611,7 +1605,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass103(any a0, any a1, any a2) { label_1: @@ -1624,7 +1617,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass104(any a0, any a1, any a2) { label_1: @@ -1637,7 +1629,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass105(any a0, any a1, any a2) { label_1: @@ -1650,7 +1641,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass106(any a0, any a1, any a2) { label_1: @@ -1663,7 +1653,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass107(any a0, any a1, any a2) { label_1: @@ -1676,7 +1665,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass108(any a0, any a1, any a2) { label_1: @@ -1689,7 +1677,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass109(any a0, any a1, any a2) { label_1: @@ -1702,7 +1689,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass11(any a0, any a1, any a2) { label_1: @@ -1715,7 +1701,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass110(any a0, any a1, any a2) { label_1: @@ -1728,7 +1713,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass111(any a0, any a1, any a2) { label_1: @@ -1741,7 +1725,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass112(any a0, any a1, any a2) { label_1: @@ -1754,7 +1737,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass113(any a0, any a1, any a2) { label_1: @@ -1767,7 +1749,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass114(any a0, any a1, any a2) { label_1: @@ -1780,7 +1761,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass115(any a0, any a1, any a2) { label_1: @@ -1793,7 +1773,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass116(any a0, any a1, any a2) { label_1: @@ -1806,7 +1785,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass117(any a0, any a1, any a2) { label_1: @@ -1819,7 +1797,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass118(any a0, any a1, any a2) { label_1: @@ -1832,7 +1809,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass119(any a0, any a1, any a2) { label_1: @@ -1845,7 +1821,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass12(any a0, any a1, any a2) { label_1: @@ -1858,7 +1833,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass120(any a0, any a1, any a2) { label_1: @@ -1871,7 +1845,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass121(any a0, any a1, any a2) { label_1: @@ -1884,7 +1857,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass122(any a0, any a1, any a2) { label_1: @@ -1897,7 +1869,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass123(any a0, any a1, any a2) { label_1: @@ -1910,7 +1881,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass124(any a0, any a1, any a2) { label_1: @@ -1923,7 +1893,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass125(any a0, any a1, any a2) { label_1: @@ -1936,7 +1905,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass126(any a0, any a1, any a2) { label_1: @@ -1949,7 +1917,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass127(any a0, any a1, any a2) { label_1: @@ -1962,7 +1929,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass128(any a0, any a1, any a2) { label_1: @@ -1975,7 +1941,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass129(any a0, any a1, any a2) { label_1: @@ -1988,7 +1953,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass13(any a0, any a1, any a2) { label_1: @@ -2001,7 +1965,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass130(any a0, any a1, any a2) { label_1: @@ -2014,7 +1977,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass131(any a0, any a1, any a2) { label_1: @@ -2027,7 +1989,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass132(any a0, any a1, any a2) { label_1: @@ -2040,7 +2001,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass133(any a0, any a1, any a2) { label_1: @@ -2053,7 +2013,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass134(any a0, any a1, any a2) { label_1: @@ -2066,7 +2025,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass135(any a0, any a1, any a2) { label_1: @@ -2079,7 +2037,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass136(any a0, any a1, any a2) { label_1: @@ -2092,7 +2049,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass137(any a0, any a1, any a2) { label_1: @@ -2105,7 +2061,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass138(any a0, any a1, any a2) { label_1: @@ -2118,7 +2073,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass139(any a0, any a1, any a2) { label_1: @@ -2131,7 +2085,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass14(any a0, any a1, any a2) { label_1: @@ -2144,7 +2097,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass140(any a0, any a1, any a2) { label_1: @@ -2157,7 +2109,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass141(any a0, any a1, any a2) { label_1: @@ -2170,7 +2121,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass142(any a0, any a1, any a2) { label_1: @@ -2183,7 +2133,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass143(any a0, any a1, any a2) { label_1: @@ -2196,7 +2145,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass144(any a0, any a1, any a2) { label_1: @@ -2209,7 +2157,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass145(any a0, any a1, any a2) { label_1: @@ -2222,7 +2169,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass146(any a0, any a1, any a2) { label_1: @@ -2235,7 +2181,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass147(any a0, any a1, any a2) { label_1: @@ -2248,7 +2193,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass148(any a0, any a1, any a2) { label_1: @@ -2261,7 +2205,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass149(any a0, any a1, any a2) { label_1: @@ -2274,7 +2217,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass15(any a0, any a1, any a2) { label_1: @@ -2287,7 +2229,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass150(any a0, any a1, any a2) { label_1: @@ -2300,7 +2241,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass151(any a0, any a1, any a2) { label_1: @@ -2313,7 +2253,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass152(any a0, any a1, any a2) { label_1: @@ -2326,7 +2265,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass153(any a0, any a1, any a2) { label_1: @@ -2339,7 +2277,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass154(any a0, any a1, any a2) { label_1: @@ -2352,7 +2289,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass155(any a0, any a1, any a2) { label_1: @@ -2365,7 +2301,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass156(any a0, any a1, any a2) { label_1: @@ -2378,7 +2313,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass157(any a0, any a1, any a2) { label_1: @@ -2391,7 +2325,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass158(any a0, any a1, any a2) { label_1: @@ -2404,7 +2337,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass159(any a0, any a1, any a2) { label_1: @@ -2417,7 +2349,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass16(any a0, any a1, any a2) { label_1: @@ -2430,7 +2361,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass160(any a0, any a1, any a2) { label_1: @@ -2443,7 +2373,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass161(any a0, any a1, any a2) { label_1: @@ -2456,7 +2385,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass162(any a0, any a1, any a2) { label_1: @@ -2469,7 +2397,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass163(any a0, any a1, any a2) { label_1: @@ -2482,7 +2409,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass164(any a0, any a1, any a2) { label_1: @@ -2495,7 +2421,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass165(any a0, any a1, any a2) { label_1: @@ -2508,7 +2433,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass166(any a0, any a1, any a2) { label_1: @@ -2521,7 +2445,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass167(any a0, any a1, any a2) { label_1: @@ -2534,7 +2457,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass168(any a0, any a1, any a2) { label_1: @@ -2547,7 +2469,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass169(any a0, any a1, any a2) { label_1: @@ -2560,7 +2481,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass17(any a0, any a1, any a2) { label_1: @@ -2573,7 +2493,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass170(any a0, any a1, any a2) { label_1: @@ -2586,7 +2505,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass171(any a0, any a1, any a2) { label_1: @@ -2599,7 +2517,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass172(any a0, any a1, any a2) { label_1: @@ -2612,7 +2529,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass173(any a0, any a1, any a2) { label_1: @@ -2625,7 +2541,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass174(any a0, any a1, any a2) { label_1: @@ -2638,7 +2553,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass175(any a0, any a1, any a2) { label_1: @@ -2651,7 +2565,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass176(any a0, any a1, any a2) { label_1: @@ -2664,7 +2577,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass177(any a0, any a1, any a2) { label_1: @@ -2677,7 +2589,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass178(any a0, any a1, any a2) { label_1: @@ -2690,7 +2601,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass179(any a0, any a1, any a2) { label_1: @@ -2703,7 +2613,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass18(any a0, any a1, any a2) { label_1: @@ -2716,7 +2625,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass180(any a0, any a1, any a2) { label_1: @@ -2729,7 +2637,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass181(any a0, any a1, any a2) { label_1: @@ -2742,7 +2649,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass182(any a0, any a1, any a2) { label_1: @@ -2755,7 +2661,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass183(any a0, any a1, any a2) { label_1: @@ -2768,7 +2673,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass184(any a0, any a1, any a2) { label_1: @@ -2781,7 +2685,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass185(any a0, any a1, any a2) { label_1: @@ -2794,7 +2697,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass186(any a0, any a1, any a2) { label_1: @@ -2807,7 +2709,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass187(any a0, any a1, any a2) { label_1: @@ -2820,7 +2721,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass188(any a0, any a1, any a2) { label_1: @@ -2833,7 +2733,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass189(any a0, any a1, any a2) { label_1: @@ -2846,7 +2745,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass19(any a0, any a1, any a2) { label_1: @@ -2859,7 +2757,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass190(any a0, any a1, any a2) { label_1: @@ -2872,7 +2769,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass191(any a0, any a1, any a2) { label_1: @@ -2885,7 +2781,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass192(any a0, any a1, any a2) { label_1: @@ -2898,7 +2793,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass193(any a0, any a1, any a2) { label_1: @@ -2911,7 +2805,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass194(any a0, any a1, any a2) { label_1: @@ -2924,7 +2817,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass195(any a0, any a1, any a2) { label_1: @@ -2937,7 +2829,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass196(any a0, any a1, any a2) { label_1: @@ -2950,7 +2841,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass197(any a0, any a1, any a2) { label_1: @@ -2963,7 +2853,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass198(any a0, any a1, any a2) { label_1: @@ -2976,7 +2865,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass199(any a0, any a1, any a2) { label_1: @@ -2989,7 +2877,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass2(any a0, any a1, any a2) { label_1: @@ -3002,7 +2889,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass20(any a0, any a1, any a2) { label_1: @@ -3015,7 +2901,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass200(any a0, any a1, any a2) { label_1: @@ -3028,7 +2913,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass201(any a0, any a1, any a2) { label_1: @@ -3041,7 +2925,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass202(any a0, any a1, any a2) { label_1: @@ -3054,7 +2937,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass203(any a0, any a1, any a2) { label_1: @@ -3067,7 +2949,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass204(any a0, any a1, any a2) { label_1: @@ -3080,7 +2961,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass205(any a0, any a1, any a2) { label_1: @@ -3093,7 +2973,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass206(any a0, any a1, any a2) { label_1: @@ -3106,7 +2985,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass207(any a0, any a1, any a2) { label_1: @@ -3119,7 +2997,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass208(any a0, any a1, any a2) { label_1: @@ -3132,7 +3009,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass209(any a0, any a1, any a2) { label_1: @@ -3145,7 +3021,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass21(any a0, any a1, any a2) { label_1: @@ -3158,7 +3033,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass210(any a0, any a1, any a2) { label_1: @@ -3171,7 +3045,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass211(any a0, any a1, any a2) { label_1: @@ -3184,7 +3057,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass212(any a0, any a1, any a2) { label_1: @@ -3197,7 +3069,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass213(any a0, any a1, any a2) { label_1: @@ -3210,7 +3081,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass214(any a0, any a1, any a2) { label_1: @@ -3223,7 +3093,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass215(any a0, any a1, any a2) { label_1: @@ -3236,7 +3105,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass216(any a0, any a1, any a2) { label_1: @@ -3249,7 +3117,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass217(any a0, any a1, any a2) { label_1: @@ -3262,7 +3129,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass218(any a0, any a1, any a2) { label_1: @@ -3275,7 +3141,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass219(any a0, any a1, any a2) { label_1: @@ -3288,7 +3153,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass22(any a0, any a1, any a2) { label_1: @@ -3301,7 +3165,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass220(any a0, any a1, any a2) { label_1: @@ -3314,7 +3177,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass221(any a0, any a1, any a2) { label_1: @@ -3327,7 +3189,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass222(any a0, any a1, any a2) { label_1: @@ -3340,7 +3201,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass223(any a0, any a1, any a2) { label_1: @@ -3353,7 +3213,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass224(any a0, any a1, any a2) { label_1: @@ -3366,7 +3225,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass225(any a0, any a1, any a2) { label_1: @@ -3379,7 +3237,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass226(any a0, any a1, any a2) { label_1: @@ -3392,7 +3249,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass227(any a0, any a1, any a2) { label_1: @@ -3405,7 +3261,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass228(any a0, any a1, any a2) { label_1: @@ -3418,7 +3273,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass229(any a0, any a1, any a2) { label_1: @@ -3431,7 +3285,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass23(any a0, any a1, any a2) { label_1: @@ -3444,7 +3297,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass230(any a0, any a1, any a2) { label_1: @@ -3457,7 +3309,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass231(any a0, any a1, any a2) { label_1: @@ -3470,7 +3321,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass232(any a0, any a1, any a2) { label_1: @@ -3483,7 +3333,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass233(any a0, any a1, any a2) { label_1: @@ -3496,7 +3345,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass234(any a0, any a1, any a2) { label_1: @@ -3509,7 +3357,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass235(any a0, any a1, any a2) { label_1: @@ -3522,7 +3369,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass236(any a0, any a1, any a2) { label_1: @@ -3535,7 +3381,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass237(any a0, any a1, any a2) { label_1: @@ -3548,7 +3393,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass238(any a0, any a1, any a2) { label_1: @@ -3561,7 +3405,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass239(any a0, any a1, any a2) { label_1: @@ -3574,7 +3417,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass24(any a0, any a1, any a2) { label_1: @@ -3587,7 +3429,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass240(any a0, any a1, any a2) { label_1: @@ -3600,7 +3441,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass241(any a0, any a1, any a2) { label_1: @@ -3613,7 +3453,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass242(any a0, any a1, any a2) { label_1: @@ -3626,7 +3465,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass243(any a0, any a1, any a2) { label_1: @@ -3639,7 +3477,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass244(any a0, any a1, any a2) { label_1: @@ -3652,7 +3489,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass245(any a0, any a1, any a2) { label_1: @@ -3665,7 +3501,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass246(any a0, any a1, any a2) { label_1: @@ -3678,7 +3513,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass247(any a0, any a1, any a2) { label_1: @@ -3691,7 +3525,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass248(any a0, any a1, any a2) { label_1: @@ -3704,7 +3537,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass249(any a0, any a1, any a2) { label_1: @@ -3717,7 +3549,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass25(any a0, any a1, any a2) { label_1: @@ -3730,7 +3561,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass250(any a0, any a1, any a2) { label_1: @@ -3743,7 +3573,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass251(any a0, any a1, any a2) { label_1: @@ -3756,7 +3585,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass252(any a0, any a1, any a2) { label_1: @@ -3769,7 +3597,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass253(any a0, any a1, any a2) { label_1: @@ -3782,7 +3609,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass254(any a0, any a1, any a2) { label_1: @@ -3795,7 +3621,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass255(any a0, any a1, any a2) { label_1: @@ -3808,7 +3633,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass26(any a0, any a1, any a2) { label_1: @@ -3821,7 +3645,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass27(any a0, any a1, any a2) { label_1: @@ -3834,7 +3657,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass28(any a0, any a1, any a2) { label_1: @@ -3847,7 +3669,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass29(any a0, any a1, any a2) { label_1: @@ -3860,7 +3681,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass3(any a0, any a1, any a2) { label_1: @@ -3873,7 +3693,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass30(any a0, any a1, any a2) { label_1: @@ -3886,7 +3705,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass31(any a0, any a1, any a2) { label_1: @@ -3899,7 +3717,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass32(any a0, any a1, any a2) { label_1: @@ -3912,7 +3729,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass33(any a0, any a1, any a2) { label_1: @@ -3925,7 +3741,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass34(any a0, any a1, any a2) { label_1: @@ -3938,7 +3753,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass35(any a0, any a1, any a2) { label_1: @@ -3951,7 +3765,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass36(any a0, any a1, any a2) { label_1: @@ -3964,7 +3777,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass37(any a0, any a1, any a2) { label_1: @@ -3977,7 +3789,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass38(any a0, any a1, any a2) { label_1: @@ -3990,7 +3801,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass39(any a0, any a1, any a2) { label_1: @@ -4003,7 +3813,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass4(any a0, any a1, any a2) { label_1: @@ -4016,7 +3825,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass40(any a0, any a1, any a2) { label_1: @@ -4029,7 +3837,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass41(any a0, any a1, any a2) { label_1: @@ -4042,7 +3849,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass42(any a0, any a1, any a2) { label_1: @@ -4055,7 +3861,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass43(any a0, any a1, any a2) { label_1: @@ -4068,7 +3873,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass44(any a0, any a1, any a2) { label_1: @@ -4081,7 +3885,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass45(any a0, any a1, any a2) { label_1: @@ -4094,7 +3897,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass46(any a0, any a1, any a2) { label_1: @@ -4107,7 +3909,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass47(any a0, any a1, any a2) { label_1: @@ -4120,7 +3921,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass48(any a0, any a1, any a2) { label_1: @@ -4133,7 +3933,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass49(any a0, any a1, any a2) { label_1: @@ -4146,7 +3945,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass5(any a0, any a1, any a2) { label_1: @@ -4159,7 +3957,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass50(any a0, any a1, any a2) { label_1: @@ -4172,7 +3969,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass51(any a0, any a1, any a2) { label_1: @@ -4185,7 +3981,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass52(any a0, any a1, any a2) { label_1: @@ -4198,7 +3993,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass53(any a0, any a1, any a2) { label_1: @@ -4211,7 +4005,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass54(any a0, any a1, any a2) { label_1: @@ -4224,7 +4017,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass55(any a0, any a1, any a2) { label_1: @@ -4237,7 +4029,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass56(any a0, any a1, any a2) { label_1: @@ -4250,7 +4041,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass57(any a0, any a1, any a2) { label_1: @@ -4263,7 +4053,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass58(any a0, any a1, any a2) { label_1: @@ -4276,7 +4065,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass59(any a0, any a1, any a2) { label_1: @@ -4289,7 +4077,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass6(any a0, any a1, any a2) { label_1: @@ -4302,7 +4089,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass60(any a0, any a1, any a2) { label_1: @@ -4315,7 +4101,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass61(any a0, any a1, any a2) { label_1: @@ -4328,7 +4113,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass62(any a0, any a1, any a2) { label_1: @@ -4341,7 +4125,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass63(any a0, any a1, any a2) { label_1: @@ -4354,7 +4137,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass64(any a0, any a1, any a2) { label_1: @@ -4367,7 +4149,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass65(any a0, any a1, any a2) { label_1: @@ -4380,7 +4161,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass66(any a0, any a1, any a2) { label_1: @@ -4393,7 +4173,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass67(any a0, any a1, any a2) { label_1: @@ -4406,7 +4185,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass68(any a0, any a1, any a2) { label_1: @@ -4419,7 +4197,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass69(any a0, any a1, any a2) { label_1: @@ -4432,7 +4209,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass7(any a0, any a1, any a2) { label_1: @@ -4445,7 +4221,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass70(any a0, any a1, any a2) { label_1: @@ -4458,7 +4233,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass71(any a0, any a1, any a2) { label_1: @@ -4471,7 +4245,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass72(any a0, any a1, any a2) { label_1: @@ -4484,7 +4257,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass73(any a0, any a1, any a2) { label_1: @@ -4497,7 +4269,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass74(any a0, any a1, any a2) { label_1: @@ -4510,7 +4281,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass75(any a0, any a1, any a2) { label_1: @@ -4523,7 +4293,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass76(any a0, any a1, any a2) { label_1: @@ -4536,7 +4305,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass77(any a0, any a1, any a2) { label_1: @@ -4549,7 +4317,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass78(any a0, any a1, any a2) { label_1: @@ -4562,7 +4329,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass79(any a0, any a1, any a2) { label_1: @@ -4575,7 +4341,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass8(any a0, any a1, any a2) { label_1: @@ -4588,7 +4353,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass80(any a0, any a1, any a2) { label_1: @@ -4601,7 +4365,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass81(any a0, any a1, any a2) { label_1: @@ -4614,7 +4377,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass82(any a0, any a1, any a2) { label_1: @@ -4627,7 +4389,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass83(any a0, any a1, any a2) { label_1: @@ -4640,7 +4401,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass84(any a0, any a1, any a2) { label_1: @@ -4653,7 +4413,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass85(any a0, any a1, any a2) { label_1: @@ -4666,7 +4425,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass86(any a0, any a1, any a2) { label_1: @@ -4679,7 +4437,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass87(any a0, any a1, any a2) { label_1: @@ -4692,7 +4449,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass88(any a0, any a1, any a2) { label_1: @@ -4705,7 +4461,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass89(any a0, any a1, any a2) { label_1: @@ -4718,7 +4473,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass9(any a0, any a1, any a2) { label_1: @@ -4731,7 +4485,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass90(any a0, any a1, any a2) { label_1: @@ -4744,7 +4497,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass91(any a0, any a1, any a2) { label_1: @@ -4757,7 +4509,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass92(any a0, any a1, any a2) { label_1: @@ -4770,7 +4521,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass93(any a0, any a1, any a2) { label_1: @@ -4783,7 +4533,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass94(any a0, any a1, any a2) { label_1: @@ -4796,7 +4545,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass95(any a0, any a1, any a2) { label_1: @@ -4809,7 +4557,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass96(any a0, any a1, any a2) { label_1: @@ -4822,7 +4569,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass97(any a0, any a1, any a2) { label_1: @@ -4835,7 +4581,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass98(any a0, any a1, any a2) { label_1: @@ -4848,7 +4593,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass99(any a0, any a1, any a2) { label_1: diff --git a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt index 4eb345368c..a21d8fc543 100644 --- a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt +++ b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt @@ -1,5 +1,4 @@ slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@0=#TopLevelSendableClass1(any a0, any a1, any a2) { label_1: @@ -12,7 +11,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@10=#TopLevelSendableClass17(any a0, any a1, any a2) { label_1: @@ -25,7 +23,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@11=#TopLevelSendableClass18(any a0, any a1, any a2) { label_1: @@ -38,7 +35,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@12=#TopLevelSendableClass19(any a0, any a1, any a2) { label_1: @@ -51,7 +47,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@13=#TopLevelSendableClass20(any a0, any a1, any a2) { label_1: @@ -64,7 +59,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@14=#TopLevelSendableClass21(any a0, any a1, any a2) { label_1: @@ -77,7 +71,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@15=#TopLevelSendableClass22(any a0, any a1, any a2) { label_1: @@ -90,7 +83,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@16=#TopLevelSendableClass23(any a0, any a1, any a2) { label_1: @@ -103,7 +95,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@17=#TopLevelSendableClass24(any a0, any a1, any a2) { label_1: @@ -116,7 +107,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@18=#TopLevelSendableClass25(any a0, any a1, any a2) { label_1: @@ -129,7 +119,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@19=#TopLevelSendableClass26(any a0, any a1, any a2) { label_1: @@ -142,7 +131,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@1=#TopLevelSendableClass2(any a0, any a1, any a2) { label_1: @@ -155,7 +143,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@1a=#TopLevelSendableClass27(any a0, any a1, any a2) { label_1: @@ -168,7 +155,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@1b=#TopLevelSendableClass28(any a0, any a1, any a2) { label_1: @@ -181,7 +167,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@1c=#TopLevelSendableClass29(any a0, any a1, any a2) { label_1: @@ -194,7 +179,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@1d=#TopLevelSendableClass30(any a0, any a1, any a2) { label_1: @@ -207,7 +191,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@1e=#TopLevelSendableClass31(any a0, any a1, any a2) { label_1: @@ -220,7 +203,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@1f=#TopLevelSendableClass32(any a0, any a1, any a2) { label_1: @@ -233,7 +215,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@20=#TopLevelSendableClass33(any a0, any a1, any a2) { label_1: @@ -246,7 +227,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@21=#TopLevelSendableClass34(any a0, any a1, any a2) { label_1: @@ -259,7 +239,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@22=#TopLevelSendableClass35(any a0, any a1, any a2) { label_1: @@ -272,7 +251,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@23=#TopLevelSendableClass36(any a0, any a1, any a2) { label_1: @@ -285,7 +263,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@24=#TopLevelSendableClass37(any a0, any a1, any a2) { label_1: @@ -298,7 +275,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@25=#TopLevelSendableClass38(any a0, any a1, any a2) { label_1: @@ -311,7 +287,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@26=#TopLevelSendableClass39(any a0, any a1, any a2) { label_1: @@ -324,7 +299,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@27=#TopLevelSendableClass40(any a0, any a1, any a2) { label_1: @@ -337,7 +311,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@28=#TopLevelSendableClass41(any a0, any a1, any a2) { label_1: @@ -350,7 +323,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@29=#TopLevelSendableClass42(any a0, any a1, any a2) { label_1: @@ -363,7 +335,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@2=#TopLevelSendableClass3(any a0, any a1, any a2) { label_1: @@ -376,7 +347,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@2a=#TopLevelSendableClass43(any a0, any a1, any a2) { label_1: @@ -389,7 +359,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@2b=#TopLevelSendableClass44(any a0, any a1, any a2) { label_1: @@ -402,7 +371,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@2c=#TopLevelSendableClass45(any a0, any a1, any a2) { label_1: @@ -415,7 +383,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@2d=#TopLevelSendableClass46(any a0, any a1, any a2) { label_1: @@ -428,7 +395,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@2e=#TopLevelSendableClass47(any a0, any a1, any a2) { label_1: @@ -441,7 +407,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@2f=#TopLevelSendableClass48(any a0, any a1, any a2) { label_1: @@ -454,7 +419,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@30=#TopLevelSendableClass49(any a0, any a1, any a2) { label_1: @@ -467,7 +431,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@31=#TopLevelSendableClass50(any a0, any a1, any a2) { label_1: @@ -480,7 +443,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@32=#TopLevelSendableClass51(any a0, any a1, any a2) { label_1: @@ -493,7 +455,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@33=#TopLevelSendableClass52(any a0, any a1, any a2) { label_1: @@ -506,7 +467,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@34=#TopLevelSendableClass53(any a0, any a1, any a2) { label_1: @@ -519,7 +479,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@35=#TopLevelSendableClass54(any a0, any a1, any a2) { label_1: @@ -532,7 +491,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@36=#TopLevelSendableClass55(any a0, any a1, any a2) { label_1: @@ -545,7 +503,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@37=#TopLevelSendableClass56(any a0, any a1, any a2) { label_1: @@ -558,7 +515,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@38=#TopLevelSendableClass57(any a0, any a1, any a2) { label_1: @@ -571,7 +527,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@39=#TopLevelSendableClass58(any a0, any a1, any a2) { label_1: @@ -584,7 +539,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@3=#TopLevelSendableClass4(any a0, any a1, any a2) { label_1: @@ -597,7 +551,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@3a=#TopLevelSendableClass59(any a0, any a1, any a2) { label_1: @@ -610,7 +563,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@3b=#TopLevelSendableClass60(any a0, any a1, any a2) { label_1: @@ -623,7 +575,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@3c=#TopLevelSendableClass61(any a0, any a1, any a2) { label_1: @@ -636,7 +587,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@3d=#TopLevelSendableClass62(any a0, any a1, any a2) { label_1: @@ -649,7 +599,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@3e=#TopLevelSendableClass63(any a0, any a1, any a2) { label_1: @@ -662,7 +611,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@3f=#TopLevelSendableClass64(any a0, any a1, any a2) { label_1: @@ -675,7 +623,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@40=#TopLevelSendableClass65(any a0, any a1, any a2) { label_1: @@ -688,7 +635,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@41=#TopLevelSendableClass66(any a0, any a1, any a2) { label_1: @@ -701,7 +647,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@42=#TopLevelSendableClass67(any a0, any a1, any a2) { label_1: @@ -714,7 +659,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@43=#TopLevelSendableClass68(any a0, any a1, any a2) { label_1: @@ -727,7 +671,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@44=#TopLevelSendableClass69(any a0, any a1, any a2) { label_1: @@ -740,7 +683,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@45=#TopLevelSendableClass70(any a0, any a1, any a2) { label_1: @@ -753,7 +695,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@46=#TopLevelSendableClass71(any a0, any a1, any a2) { label_1: @@ -766,7 +707,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@47=#TopLevelSendableClass72(any a0, any a1, any a2) { label_1: @@ -779,7 +719,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@48=#TopLevelSendableClass73(any a0, any a1, any a2) { label_1: @@ -792,7 +731,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@49=#TopLevelSendableClass74(any a0, any a1, any a2) { label_1: @@ -805,7 +743,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@4=#TopLevelSendableClass5(any a0, any a1, any a2) { label_1: @@ -818,7 +755,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@4a=#TopLevelSendableClass75(any a0, any a1, any a2) { label_1: @@ -831,7 +767,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@4b=#TopLevelSendableClass76(any a0, any a1, any a2) { label_1: @@ -844,7 +779,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@4c=#TopLevelSendableClass77(any a0, any a1, any a2) { label_1: @@ -857,7 +791,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@4d=#TopLevelSendableClass78(any a0, any a1, any a2) { label_1: @@ -870,7 +803,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@4e=#TopLevelSendableClass79(any a0, any a1, any a2) { label_1: @@ -883,7 +815,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@4f=#TopLevelSendableClass80(any a0, any a1, any a2) { label_1: @@ -896,7 +827,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@50=#TopLevelSendableClass81(any a0, any a1, any a2) { label_1: @@ -909,7 +839,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@51=#TopLevelSendableClass82(any a0, any a1, any a2) { label_1: @@ -922,7 +851,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@52=#TopLevelSendableClass83(any a0, any a1, any a2) { label_1: @@ -935,7 +863,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@53=#TopLevelSendableClass84(any a0, any a1, any a2) { label_1: @@ -948,7 +875,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@54=#TopLevelSendableClass85(any a0, any a1, any a2) { label_1: @@ -961,7 +887,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@55=#TopLevelSendableClass86(any a0, any a1, any a2) { label_1: @@ -974,7 +899,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@56=#TopLevelSendableClass87(any a0, any a1, any a2) { label_1: @@ -987,7 +911,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@57=#TopLevelSendableClass88(any a0, any a1, any a2) { label_1: @@ -1000,7 +923,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@58=#TopLevelSendableClass89(any a0, any a1, any a2) { label_1: @@ -1013,7 +935,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@59=#TopLevelSendableClass90(any a0, any a1, any a2) { label_1: @@ -1026,7 +947,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@5=#TopLevelSendableClass6(any a0, any a1, any a2) { label_1: @@ -1039,7 +959,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@5a=#TopLevelSendableClass91(any a0, any a1, any a2) { label_1: @@ -1052,7 +971,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@5b=#TopLevelSendableClass92(any a0, any a1, any a2) { label_1: @@ -1065,7 +983,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@5c=#TopLevelSendableClass93(any a0, any a1, any a2) { label_1: @@ -1078,7 +995,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@5d=#TopLevelSendableClass94(any a0, any a1, any a2) { label_1: @@ -1091,7 +1007,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@5e=#TopLevelSendableClass95(any a0, any a1, any a2) { label_1: @@ -1104,7 +1019,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@5f=#TopLevelSendableClass96(any a0, any a1, any a2) { label_1: @@ -1117,7 +1031,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@60=#TopLevelSendableClass97(any a0, any a1, any a2) { label_1: @@ -1130,7 +1043,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@61=#TopLevelSendableClass98(any a0, any a1, any a2) { label_1: @@ -1143,7 +1055,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@62=#TopLevelSendableClass99(any a0, any a1, any a2) { label_1: @@ -1156,7 +1067,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@63=#TopLevelSendableClass100(any a0, any a1, any a2) { label_1: @@ -1169,7 +1079,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@64=#TopLevelSendableClass101(any a0, any a1, any a2) { label_1: @@ -1182,7 +1091,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@65=#TopLevelSendableClass102(any a0, any a1, any a2) { label_1: @@ -1195,7 +1103,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@66=#TopLevelSendableClass103(any a0, any a1, any a2) { label_1: @@ -1208,7 +1115,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@67=#TopLevelSendableClass104(any a0, any a1, any a2) { label_1: @@ -1221,7 +1127,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@68=#TopLevelSendableClass105(any a0, any a1, any a2) { label_1: @@ -1234,7 +1139,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@69=#TopLevelSendableClass106(any a0, any a1, any a2) { label_1: @@ -1247,7 +1151,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@6=#TopLevelSendableClass7(any a0, any a1, any a2) { label_1: @@ -1260,7 +1163,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@6a=#TopLevelSendableClass107(any a0, any a1, any a2) { label_1: @@ -1273,7 +1175,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@6b=#TopLevelSendableClass108(any a0, any a1, any a2) { label_1: @@ -1286,7 +1187,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@6c=#TopLevelSendableClass109(any a0, any a1, any a2) { label_1: @@ -1299,7 +1199,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@6d=#TopLevelSendableClass110(any a0, any a1, any a2) { label_1: @@ -1312,7 +1211,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@6e=#TopLevelSendableClass111(any a0, any a1, any a2) { label_1: @@ -1325,7 +1223,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@6f=#TopLevelSendableClass112(any a0, any a1, any a2) { label_1: @@ -1338,7 +1235,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@70=#TopLevelSendableClass113(any a0, any a1, any a2) { label_1: @@ -1351,7 +1247,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@71=#TopLevelSendableClass114(any a0, any a1, any a2) { label_1: @@ -1364,7 +1259,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@72=#TopLevelSendableClass115(any a0, any a1, any a2) { label_1: @@ -1377,7 +1271,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@73=#TopLevelSendableClass116(any a0, any a1, any a2) { label_1: @@ -1390,7 +1283,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@74=#TopLevelSendableClass117(any a0, any a1, any a2) { label_1: @@ -1403,7 +1295,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@75=#TopLevelSendableClass118(any a0, any a1, any a2) { label_1: @@ -1416,7 +1307,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@76=#TopLevelSendableClass119(any a0, any a1, any a2) { label_1: @@ -1429,7 +1319,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@77=#TopLevelSendableClass120(any a0, any a1, any a2) { label_1: @@ -1442,7 +1331,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@78=#TopLevelSendableClass121(any a0, any a1, any a2) { label_1: @@ -1455,7 +1343,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@79=#TopLevelSendableClass122(any a0, any a1, any a2) { label_1: @@ -1468,7 +1355,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@7=#TopLevelSendableClass8(any a0, any a1, any a2) { label_1: @@ -1481,7 +1367,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@7a=#TopLevelSendableClass123(any a0, any a1, any a2) { label_1: @@ -1494,7 +1379,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@7b=#TopLevelSendableClass124(any a0, any a1, any a2) { label_1: @@ -1507,7 +1391,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@7c=#TopLevelSendableClass125(any a0, any a1, any a2) { label_1: @@ -1520,7 +1403,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@7d=#TopLevelSendableClass126(any a0, any a1, any a2) { label_1: @@ -1533,7 +1415,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@7e=#TopLevelSendableClass127(any a0, any a1, any a2) { label_1: @@ -1546,7 +1427,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@7f=#TopLevelSendableClass128(any a0, any a1, any a2) { label_1: @@ -1559,7 +1439,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@80=#TopLevelSendableClass129(any a0, any a1, any a2) { label_1: @@ -1572,7 +1451,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@81=#TopLevelSendableClass130(any a0, any a1, any a2) { label_1: @@ -1585,7 +1463,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@82=#TopLevelSendableClass131(any a0, any a1, any a2) { label_1: @@ -1598,7 +1475,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@83=#TopLevelSendableClass132(any a0, any a1, any a2) { label_1: @@ -1611,7 +1487,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@84=#TopLevelSendableClass133(any a0, any a1, any a2) { label_1: @@ -1624,7 +1499,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@85=#TopLevelSendableClass134(any a0, any a1, any a2) { label_1: @@ -1637,7 +1511,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@86=#TopLevelSendableClass135(any a0, any a1, any a2) { label_1: @@ -1650,7 +1523,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@87=#TopLevelSendableClass136(any a0, any a1, any a2) { label_1: @@ -1663,7 +1535,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@88=#TopLevelSendableClass137(any a0, any a1, any a2) { label_1: @@ -1676,7 +1547,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@89=#TopLevelSendableClass138(any a0, any a1, any a2) { label_1: @@ -1689,7 +1559,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@8=#TopLevelSendableClass9(any a0, any a1, any a2) { label_1: @@ -1702,7 +1571,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@8a=#TopLevelSendableClass139(any a0, any a1, any a2) { label_1: @@ -1715,7 +1583,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@8b=#TopLevelSendableClass140(any a0, any a1, any a2) { label_1: @@ -1728,7 +1595,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@8c=#TopLevelSendableClass141(any a0, any a1, any a2) { label_1: @@ -1741,7 +1607,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@8d=#TopLevelSendableClass142(any a0, any a1, any a2) { label_1: @@ -1754,7 +1619,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@8e=#TopLevelSendableClass143(any a0, any a1, any a2) { label_1: @@ -1767,7 +1631,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@8f=#TopLevelSendableClass144(any a0, any a1, any a2) { label_1: @@ -1780,7 +1643,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@90=#TopLevelSendableClass145(any a0, any a1, any a2) { label_1: @@ -1793,7 +1655,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@91=#TopLevelSendableClass146(any a0, any a1, any a2) { label_1: @@ -1806,7 +1667,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@92=#TopLevelSendableClass147(any a0, any a1, any a2) { label_1: @@ -1819,7 +1679,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@93=#TopLevelSendableClass148(any a0, any a1, any a2) { label_1: @@ -1832,7 +1691,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@94=#TopLevelSendableClass149(any a0, any a1, any a2) { label_1: @@ -1845,7 +1703,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@95=#TopLevelSendableClass150(any a0, any a1, any a2) { label_1: @@ -1858,7 +1715,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@96=#TopLevelSendableClass151(any a0, any a1, any a2) { label_1: @@ -1871,7 +1727,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@97=#TopLevelSendableClass152(any a0, any a1, any a2) { label_1: @@ -1884,7 +1739,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@98=#TopLevelSendableClass153(any a0, any a1, any a2) { label_1: @@ -1897,7 +1751,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@99=#TopLevelSendableClass154(any a0, any a1, any a2) { label_1: @@ -1910,7 +1763,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@9=#TopLevelSendableClass10(any a0, any a1, any a2) { label_1: @@ -1923,7 +1775,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@9a=#TopLevelSendableClass155(any a0, any a1, any a2) { label_1: @@ -1936,7 +1787,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@9b=#TopLevelSendableClass156(any a0, any a1, any a2) { label_1: @@ -1949,7 +1799,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@9c=#TopLevelSendableClass157(any a0, any a1, any a2) { label_1: @@ -1962,7 +1811,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@9d=#TopLevelSendableClass158(any a0, any a1, any a2) { label_1: @@ -1975,7 +1823,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@9e=#TopLevelSendableClass159(any a0, any a1, any a2) { label_1: @@ -1988,7 +1835,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@9f=#TopLevelSendableClass160(any a0, any a1, any a2) { label_1: @@ -2001,7 +1847,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@a0=#TopLevelSendableClass161(any a0, any a1, any a2) { label_1: @@ -2014,7 +1859,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@a1=#TopLevelSendableClass162(any a0, any a1, any a2) { label_1: @@ -2027,7 +1871,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@a2=#TopLevelSendableClass163(any a0, any a1, any a2) { label_1: @@ -2040,7 +1883,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@a3=#TopLevelSendableClass164(any a0, any a1, any a2) { label_1: @@ -2053,7 +1895,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@a4=#TopLevelSendableClass165(any a0, any a1, any a2) { label_1: @@ -2066,7 +1907,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@a5=#TopLevelSendableClass166(any a0, any a1, any a2) { label_1: @@ -2079,7 +1919,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@a6=#TopLevelSendableClass167(any a0, any a1, any a2) { label_1: @@ -2092,7 +1931,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@a7=#TopLevelSendableClass168(any a0, any a1, any a2) { label_1: @@ -2105,7 +1943,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@a8=#TopLevelSendableClass169(any a0, any a1, any a2) { label_1: @@ -2118,7 +1955,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@a9=#TopLevelSendableClass170(any a0, any a1, any a2) { label_1: @@ -2131,7 +1967,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@a=#TopLevelSendableClass11(any a0, any a1, any a2) { label_1: @@ -2144,7 +1979,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@aa=#TopLevelSendableClass171(any a0, any a1, any a2) { label_1: @@ -2157,7 +1991,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@ab=#TopLevelSendableClass172(any a0, any a1, any a2) { label_1: @@ -2170,7 +2003,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@ac=#TopLevelSendableClass173(any a0, any a1, any a2) { label_1: @@ -2183,7 +2015,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@ad=#TopLevelSendableClass174(any a0, any a1, any a2) { label_1: @@ -2196,7 +2027,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@ae=#TopLevelSendableClass175(any a0, any a1, any a2) { label_1: @@ -2209,7 +2039,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@af=#TopLevelSendableClass176(any a0, any a1, any a2) { label_1: @@ -2222,7 +2051,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@b0=#TopLevelSendableClass177(any a0, any a1, any a2) { label_1: @@ -2235,7 +2063,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@b1=#TopLevelSendableClass178(any a0, any a1, any a2) { label_1: @@ -2248,7 +2075,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@b2=#TopLevelSendableClass179(any a0, any a1, any a2) { label_1: @@ -2261,7 +2087,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@b3=#TopLevelSendableClass180(any a0, any a1, any a2) { label_1: @@ -2274,7 +2099,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@b4=#TopLevelSendableClass181(any a0, any a1, any a2) { label_1: @@ -2287,7 +2111,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@b5=#TopLevelSendableClass182(any a0, any a1, any a2) { label_1: @@ -2300,7 +2123,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@b6=#TopLevelSendableClass183(any a0, any a1, any a2) { label_1: @@ -2313,7 +2135,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@b7=#TopLevelSendableClass184(any a0, any a1, any a2) { label_1: @@ -2326,7 +2147,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@b8=#TopLevelSendableClass185(any a0, any a1, any a2) { label_1: @@ -2339,7 +2159,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@b9=#TopLevelSendableClass186(any a0, any a1, any a2) { label_1: @@ -2352,7 +2171,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@b=#TopLevelSendableClass12(any a0, any a1, any a2) { label_1: @@ -2365,7 +2183,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@ba=#TopLevelSendableClass187(any a0, any a1, any a2) { label_1: @@ -2378,7 +2195,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@bb=#TopLevelSendableClass188(any a0, any a1, any a2) { label_1: @@ -2391,7 +2207,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@bc=#TopLevelSendableClass189(any a0, any a1, any a2) { label_1: @@ -2404,7 +2219,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@bd=#TopLevelSendableClass190(any a0, any a1, any a2) { label_1: @@ -2417,7 +2231,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@be=#TopLevelSendableClass191(any a0, any a1, any a2) { label_1: @@ -2430,7 +2243,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@bf=#TopLevelSendableClass192(any a0, any a1, any a2) { label_1: @@ -2443,7 +2255,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@c0=#TopLevelSendableClass193(any a0, any a1, any a2) { label_1: @@ -2456,7 +2267,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@c1=#TopLevelSendableClass194(any a0, any a1, any a2) { label_1: @@ -2469,7 +2279,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@c2=#TopLevelSendableClass195(any a0, any a1, any a2) { label_1: @@ -2482,7 +2291,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@c3=#TopLevelSendableClass196(any a0, any a1, any a2) { label_1: @@ -2495,7 +2303,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@c4=#TopLevelSendableClass197(any a0, any a1, any a2) { label_1: @@ -2508,7 +2315,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@c5=#TopLevelSendableClass198(any a0, any a1, any a2) { label_1: @@ -2521,7 +2327,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@c6=#TopLevelSendableClass199(any a0, any a1, any a2) { label_1: @@ -2534,7 +2339,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@c7=#TopLevelSendableClass200(any a0, any a1, any a2) { label_1: @@ -2547,7 +2351,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@c8=#TopLevelSendableClass201(any a0, any a1, any a2) { label_1: @@ -2560,7 +2363,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@c9=#TopLevelSendableClass202(any a0, any a1, any a2) { label_1: @@ -2573,7 +2375,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@c=#TopLevelSendableClass13(any a0, any a1, any a2) { label_1: @@ -2586,7 +2387,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@ca=#TopLevelSendableClass203(any a0, any a1, any a2) { label_1: @@ -2599,7 +2399,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@cb=#TopLevelSendableClass204(any a0, any a1, any a2) { label_1: @@ -2612,7 +2411,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@cc=#TopLevelSendableClass205(any a0, any a1, any a2) { label_1: @@ -2625,7 +2423,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@cd=#TopLevelSendableClass206(any a0, any a1, any a2) { label_1: @@ -2638,7 +2435,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@ce=#TopLevelSendableClass207(any a0, any a1, any a2) { label_1: @@ -2651,7 +2447,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@cf=#TopLevelSendableClass208(any a0, any a1, any a2) { label_1: @@ -2664,7 +2459,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@d0=#TopLevelSendableClass209(any a0, any a1, any a2) { label_1: @@ -2677,7 +2471,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@d1=#TopLevelSendableClass210(any a0, any a1, any a2) { label_1: @@ -2690,7 +2483,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@d2=#TopLevelSendableClass211(any a0, any a1, any a2) { label_1: @@ -2703,7 +2495,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@d3=#TopLevelSendableClass212(any a0, any a1, any a2) { label_1: @@ -2716,7 +2507,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@d4=#TopLevelSendableClass213(any a0, any a1, any a2) { label_1: @@ -2729,7 +2519,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@d5=#TopLevelSendableClass214(any a0, any a1, any a2) { label_1: @@ -2742,7 +2531,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@d6=#TopLevelSendableClass215(any a0, any a1, any a2) { label_1: @@ -2755,7 +2543,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@d7=#TopLevelSendableClass216(any a0, any a1, any a2) { label_1: @@ -2768,7 +2555,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@d8=#TopLevelSendableClass217(any a0, any a1, any a2) { label_1: @@ -2781,7 +2567,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@d9=#TopLevelSendableClass218(any a0, any a1, any a2) { label_1: @@ -2794,7 +2579,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@d=#TopLevelSendableClass14(any a0, any a1, any a2) { label_1: @@ -2807,7 +2591,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@da=#TopLevelSendableClass219(any a0, any a1, any a2) { label_1: @@ -2820,7 +2603,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@db=#TopLevelSendableClass220(any a0, any a1, any a2) { label_1: @@ -2833,7 +2615,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@dc=#TopLevelSendableClass221(any a0, any a1, any a2) { label_1: @@ -2846,7 +2627,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@dd=#TopLevelSendableClass222(any a0, any a1, any a2) { label_1: @@ -2859,7 +2639,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@de=#TopLevelSendableClass223(any a0, any a1, any a2) { label_1: @@ -2872,7 +2651,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@df=#TopLevelSendableClass224(any a0, any a1, any a2) { label_1: @@ -2885,7 +2663,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@e0=#TopLevelSendableClass225(any a0, any a1, any a2) { label_1: @@ -2898,7 +2675,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@e1=#TopLevelSendableClass226(any a0, any a1, any a2) { label_1: @@ -2911,7 +2687,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@e2=#TopLevelSendableClass227(any a0, any a1, any a2) { label_1: @@ -2924,7 +2699,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@e3=#TopLevelSendableClass228(any a0, any a1, any a2) { label_1: @@ -2937,7 +2711,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@e4=#TopLevelSendableClass229(any a0, any a1, any a2) { label_1: @@ -2950,7 +2723,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@e5=#TopLevelSendableClass230(any a0, any a1, any a2) { label_1: @@ -2963,7 +2735,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@e6=#TopLevelSendableClass231(any a0, any a1, any a2) { label_1: @@ -2976,7 +2747,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@e7=#TopLevelSendableClass232(any a0, any a1, any a2) { label_1: @@ -2989,7 +2759,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@e8=#TopLevelSendableClass233(any a0, any a1, any a2) { label_1: @@ -3002,7 +2771,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@e9=#TopLevelSendableClass234(any a0, any a1, any a2) { label_1: @@ -3015,7 +2783,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@e=#TopLevelSendableClass15(any a0, any a1, any a2) { label_1: @@ -3028,7 +2795,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@ea=#TopLevelSendableClass235(any a0, any a1, any a2) { label_1: @@ -3041,7 +2807,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@eb=#TopLevelSendableClass236(any a0, any a1, any a2) { label_1: @@ -3054,7 +2819,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@ec=#TopLevelSendableClass237(any a0, any a1, any a2) { label_1: @@ -3067,7 +2831,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@ed=#TopLevelSendableClass238(any a0, any a1, any a2) { label_1: @@ -3080,7 +2843,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@ee=#TopLevelSendableClass239(any a0, any a1, any a2) { label_1: @@ -3093,7 +2855,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@ef=#TopLevelSendableClass240(any a0, any a1, any a2) { label_1: @@ -3106,7 +2867,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@f0=#TopLevelSendableClass241(any a0, any a1, any a2) { label_1: @@ -3119,7 +2879,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@f1=#TopLevelSendableClass242(any a0, any a1, any a2) { label_1: @@ -3132,7 +2891,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@f2=#TopLevelSendableClass243(any a0, any a1, any a2) { label_1: @@ -3145,7 +2903,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@f3=#TopLevelSendableClass244(any a0, any a1, any a2) { label_1: @@ -3158,7 +2915,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@f4=#TopLevelSendableClass245(any a0, any a1, any a2) { label_1: @@ -3171,7 +2927,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@f5=#TopLevelSendableClass246(any a0, any a1, any a2) { label_1: @@ -3184,7 +2939,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@f6=#TopLevelSendableClass247(any a0, any a1, any a2) { label_1: @@ -3197,7 +2951,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@f7=#TopLevelSendableClass248(any a0, any a1, any a2) { label_1: @@ -3210,7 +2963,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@f8=#TopLevelSendableClass249(any a0, any a1, any a2) { label_1: @@ -3223,7 +2975,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@f9=#TopLevelSendableClass250(any a0, any a1, any a2) { label_1: @@ -3236,7 +2987,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@f=#TopLevelSendableClass16(any a0, any a1, any a2) { label_1: @@ -3249,7 +2999,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@fa=#TopLevelSendableClass251(any a0, any a1, any a2) { label_1: @@ -3262,7 +3011,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@fb=#TopLevelSendableClass252(any a0, any a1, any a2) { label_1: @@ -3275,7 +3023,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@fc=#TopLevelSendableClass253(any a0, any a1, any a2) { label_1: @@ -3288,7 +3035,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@fd=#TopLevelSendableClass254(any a0, any a1, any a2) { label_1: @@ -3301,7 +3047,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@fe=#TopLevelSendableClass255(any a0, any a1, any a2) { label_1: @@ -3314,7 +3059,6 @@ label_2: } slotNum = 0x406 -expectedProperty = 0x101 .language ECMAScript .function any .#~@ff=#SendableTestClass1(any a0, any a1, any a2) { label_1: diff --git a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_unsupported_compile_for_below_API11_asm_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_unsupported_compile_for_below_API11_asm_version-expected.txt index 6cb40f7fb7..6abb6478b6 100644 --- a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_unsupported_compile_for_below_API11_asm_version-expected.txt +++ b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_unsupported_compile_for_below_API11_asm_version-expected.txt @@ -1,5 +1,4 @@ slotNum = 0x406 -expectedProperty = 0x101 .language ECMAScript .function any .SendableTestClass1(any a0, any a1, any a2) { label_1: @@ -1546,7 +1545,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass1(any a0, any a1, any a2) { label_1: @@ -1559,7 +1557,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass10(any a0, any a1, any a2) { label_1: @@ -1572,7 +1569,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass100(any a0, any a1, any a2) { label_1: @@ -1585,7 +1581,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass101(any a0, any a1, any a2) { label_1: @@ -1598,7 +1593,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass102(any a0, any a1, any a2) { label_1: @@ -1611,7 +1605,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass103(any a0, any a1, any a2) { label_1: @@ -1624,7 +1617,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass104(any a0, any a1, any a2) { label_1: @@ -1637,7 +1629,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass105(any a0, any a1, any a2) { label_1: @@ -1650,7 +1641,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass106(any a0, any a1, any a2) { label_1: @@ -1663,7 +1653,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass107(any a0, any a1, any a2) { label_1: @@ -1676,7 +1665,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass108(any a0, any a1, any a2) { label_1: @@ -1689,7 +1677,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass109(any a0, any a1, any a2) { label_1: @@ -1702,7 +1689,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass11(any a0, any a1, any a2) { label_1: @@ -1715,7 +1701,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass110(any a0, any a1, any a2) { label_1: @@ -1728,7 +1713,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass111(any a0, any a1, any a2) { label_1: @@ -1741,7 +1725,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass112(any a0, any a1, any a2) { label_1: @@ -1754,7 +1737,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass113(any a0, any a1, any a2) { label_1: @@ -1767,7 +1749,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass114(any a0, any a1, any a2) { label_1: @@ -1780,7 +1761,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass115(any a0, any a1, any a2) { label_1: @@ -1793,7 +1773,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass116(any a0, any a1, any a2) { label_1: @@ -1806,7 +1785,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass117(any a0, any a1, any a2) { label_1: @@ -1819,7 +1797,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass118(any a0, any a1, any a2) { label_1: @@ -1832,7 +1809,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass119(any a0, any a1, any a2) { label_1: @@ -1845,7 +1821,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass12(any a0, any a1, any a2) { label_1: @@ -1858,7 +1833,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass120(any a0, any a1, any a2) { label_1: @@ -1871,7 +1845,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass121(any a0, any a1, any a2) { label_1: @@ -1884,7 +1857,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass122(any a0, any a1, any a2) { label_1: @@ -1897,7 +1869,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass123(any a0, any a1, any a2) { label_1: @@ -1910,7 +1881,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass124(any a0, any a1, any a2) { label_1: @@ -1923,7 +1893,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass125(any a0, any a1, any a2) { label_1: @@ -1936,7 +1905,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass126(any a0, any a1, any a2) { label_1: @@ -1949,7 +1917,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass127(any a0, any a1, any a2) { label_1: @@ -1962,7 +1929,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass128(any a0, any a1, any a2) { label_1: @@ -1975,7 +1941,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass129(any a0, any a1, any a2) { label_1: @@ -1988,7 +1953,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass13(any a0, any a1, any a2) { label_1: @@ -2001,7 +1965,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass130(any a0, any a1, any a2) { label_1: @@ -2014,7 +1977,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass131(any a0, any a1, any a2) { label_1: @@ -2027,7 +1989,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass132(any a0, any a1, any a2) { label_1: @@ -2040,7 +2001,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass133(any a0, any a1, any a2) { label_1: @@ -2053,7 +2013,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass134(any a0, any a1, any a2) { label_1: @@ -2066,7 +2025,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass135(any a0, any a1, any a2) { label_1: @@ -2079,7 +2037,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass136(any a0, any a1, any a2) { label_1: @@ -2092,7 +2049,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass137(any a0, any a1, any a2) { label_1: @@ -2105,7 +2061,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass138(any a0, any a1, any a2) { label_1: @@ -2118,7 +2073,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass139(any a0, any a1, any a2) { label_1: @@ -2131,7 +2085,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass14(any a0, any a1, any a2) { label_1: @@ -2144,7 +2097,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass140(any a0, any a1, any a2) { label_1: @@ -2157,7 +2109,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass141(any a0, any a1, any a2) { label_1: @@ -2170,7 +2121,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass142(any a0, any a1, any a2) { label_1: @@ -2183,7 +2133,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass143(any a0, any a1, any a2) { label_1: @@ -2196,7 +2145,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass144(any a0, any a1, any a2) { label_1: @@ -2209,7 +2157,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass145(any a0, any a1, any a2) { label_1: @@ -2222,7 +2169,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass146(any a0, any a1, any a2) { label_1: @@ -2235,7 +2181,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass147(any a0, any a1, any a2) { label_1: @@ -2248,7 +2193,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass148(any a0, any a1, any a2) { label_1: @@ -2261,7 +2205,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass149(any a0, any a1, any a2) { label_1: @@ -2274,7 +2217,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass15(any a0, any a1, any a2) { label_1: @@ -2287,7 +2229,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass150(any a0, any a1, any a2) { label_1: @@ -2300,7 +2241,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass151(any a0, any a1, any a2) { label_1: @@ -2313,7 +2253,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass152(any a0, any a1, any a2) { label_1: @@ -2326,7 +2265,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass153(any a0, any a1, any a2) { label_1: @@ -2339,7 +2277,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass154(any a0, any a1, any a2) { label_1: @@ -2352,7 +2289,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass155(any a0, any a1, any a2) { label_1: @@ -2365,7 +2301,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass156(any a0, any a1, any a2) { label_1: @@ -2378,7 +2313,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass157(any a0, any a1, any a2) { label_1: @@ -2391,7 +2325,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass158(any a0, any a1, any a2) { label_1: @@ -2404,7 +2337,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass159(any a0, any a1, any a2) { label_1: @@ -2417,7 +2349,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass16(any a0, any a1, any a2) { label_1: @@ -2430,7 +2361,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass160(any a0, any a1, any a2) { label_1: @@ -2443,7 +2373,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass161(any a0, any a1, any a2) { label_1: @@ -2456,7 +2385,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass162(any a0, any a1, any a2) { label_1: @@ -2469,7 +2397,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass163(any a0, any a1, any a2) { label_1: @@ -2482,7 +2409,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass164(any a0, any a1, any a2) { label_1: @@ -2495,7 +2421,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass165(any a0, any a1, any a2) { label_1: @@ -2508,7 +2433,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass166(any a0, any a1, any a2) { label_1: @@ -2521,7 +2445,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass167(any a0, any a1, any a2) { label_1: @@ -2534,7 +2457,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass168(any a0, any a1, any a2) { label_1: @@ -2547,7 +2469,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass169(any a0, any a1, any a2) { label_1: @@ -2560,7 +2481,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass17(any a0, any a1, any a2) { label_1: @@ -2573,7 +2493,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass170(any a0, any a1, any a2) { label_1: @@ -2586,7 +2505,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass171(any a0, any a1, any a2) { label_1: @@ -2599,7 +2517,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass172(any a0, any a1, any a2) { label_1: @@ -2612,7 +2529,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass173(any a0, any a1, any a2) { label_1: @@ -2625,7 +2541,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass174(any a0, any a1, any a2) { label_1: @@ -2638,7 +2553,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass175(any a0, any a1, any a2) { label_1: @@ -2651,7 +2565,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass176(any a0, any a1, any a2) { label_1: @@ -2664,7 +2577,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass177(any a0, any a1, any a2) { label_1: @@ -2677,7 +2589,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass178(any a0, any a1, any a2) { label_1: @@ -2690,7 +2601,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass179(any a0, any a1, any a2) { label_1: @@ -2703,7 +2613,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass18(any a0, any a1, any a2) { label_1: @@ -2716,7 +2625,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass180(any a0, any a1, any a2) { label_1: @@ -2729,7 +2637,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass181(any a0, any a1, any a2) { label_1: @@ -2742,7 +2649,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass182(any a0, any a1, any a2) { label_1: @@ -2755,7 +2661,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass183(any a0, any a1, any a2) { label_1: @@ -2768,7 +2673,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass184(any a0, any a1, any a2) { label_1: @@ -2781,7 +2685,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass185(any a0, any a1, any a2) { label_1: @@ -2794,7 +2697,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass186(any a0, any a1, any a2) { label_1: @@ -2807,7 +2709,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass187(any a0, any a1, any a2) { label_1: @@ -2820,7 +2721,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass188(any a0, any a1, any a2) { label_1: @@ -2833,7 +2733,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass189(any a0, any a1, any a2) { label_1: @@ -2846,7 +2745,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass19(any a0, any a1, any a2) { label_1: @@ -2859,7 +2757,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass190(any a0, any a1, any a2) { label_1: @@ -2872,7 +2769,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass191(any a0, any a1, any a2) { label_1: @@ -2885,7 +2781,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass192(any a0, any a1, any a2) { label_1: @@ -2898,7 +2793,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass193(any a0, any a1, any a2) { label_1: @@ -2911,7 +2805,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass194(any a0, any a1, any a2) { label_1: @@ -2924,7 +2817,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass195(any a0, any a1, any a2) { label_1: @@ -2937,7 +2829,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass196(any a0, any a1, any a2) { label_1: @@ -2950,7 +2841,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass197(any a0, any a1, any a2) { label_1: @@ -2963,7 +2853,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass198(any a0, any a1, any a2) { label_1: @@ -2976,7 +2865,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass199(any a0, any a1, any a2) { label_1: @@ -2989,7 +2877,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass2(any a0, any a1, any a2) { label_1: @@ -3002,7 +2889,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass20(any a0, any a1, any a2) { label_1: @@ -3015,7 +2901,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass200(any a0, any a1, any a2) { label_1: @@ -3028,7 +2913,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass201(any a0, any a1, any a2) { label_1: @@ -3041,7 +2925,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass202(any a0, any a1, any a2) { label_1: @@ -3054,7 +2937,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass203(any a0, any a1, any a2) { label_1: @@ -3067,7 +2949,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass204(any a0, any a1, any a2) { label_1: @@ -3080,7 +2961,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass205(any a0, any a1, any a2) { label_1: @@ -3093,7 +2973,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass206(any a0, any a1, any a2) { label_1: @@ -3106,7 +2985,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass207(any a0, any a1, any a2) { label_1: @@ -3119,7 +2997,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass208(any a0, any a1, any a2) { label_1: @@ -3132,7 +3009,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass209(any a0, any a1, any a2) { label_1: @@ -3145,7 +3021,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass21(any a0, any a1, any a2) { label_1: @@ -3158,7 +3033,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass210(any a0, any a1, any a2) { label_1: @@ -3171,7 +3045,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass211(any a0, any a1, any a2) { label_1: @@ -3184,7 +3057,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass212(any a0, any a1, any a2) { label_1: @@ -3197,7 +3069,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass213(any a0, any a1, any a2) { label_1: @@ -3210,7 +3081,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass214(any a0, any a1, any a2) { label_1: @@ -3223,7 +3093,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass215(any a0, any a1, any a2) { label_1: @@ -3236,7 +3105,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass216(any a0, any a1, any a2) { label_1: @@ -3249,7 +3117,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass217(any a0, any a1, any a2) { label_1: @@ -3262,7 +3129,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass218(any a0, any a1, any a2) { label_1: @@ -3275,7 +3141,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass219(any a0, any a1, any a2) { label_1: @@ -3288,7 +3153,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass22(any a0, any a1, any a2) { label_1: @@ -3301,7 +3165,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass220(any a0, any a1, any a2) { label_1: @@ -3314,7 +3177,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass221(any a0, any a1, any a2) { label_1: @@ -3327,7 +3189,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass222(any a0, any a1, any a2) { label_1: @@ -3340,7 +3201,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass223(any a0, any a1, any a2) { label_1: @@ -3353,7 +3213,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass224(any a0, any a1, any a2) { label_1: @@ -3366,7 +3225,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass225(any a0, any a1, any a2) { label_1: @@ -3379,7 +3237,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass226(any a0, any a1, any a2) { label_1: @@ -3392,7 +3249,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass227(any a0, any a1, any a2) { label_1: @@ -3405,7 +3261,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass228(any a0, any a1, any a2) { label_1: @@ -3418,7 +3273,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass229(any a0, any a1, any a2) { label_1: @@ -3431,7 +3285,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass23(any a0, any a1, any a2) { label_1: @@ -3444,7 +3297,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass230(any a0, any a1, any a2) { label_1: @@ -3457,7 +3309,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass231(any a0, any a1, any a2) { label_1: @@ -3470,7 +3321,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass232(any a0, any a1, any a2) { label_1: @@ -3483,7 +3333,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass233(any a0, any a1, any a2) { label_1: @@ -3496,7 +3345,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass234(any a0, any a1, any a2) { label_1: @@ -3509,7 +3357,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass235(any a0, any a1, any a2) { label_1: @@ -3522,7 +3369,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass236(any a0, any a1, any a2) { label_1: @@ -3535,7 +3381,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass237(any a0, any a1, any a2) { label_1: @@ -3548,7 +3393,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass238(any a0, any a1, any a2) { label_1: @@ -3561,7 +3405,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass239(any a0, any a1, any a2) { label_1: @@ -3574,7 +3417,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass24(any a0, any a1, any a2) { label_1: @@ -3587,7 +3429,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass240(any a0, any a1, any a2) { label_1: @@ -3600,7 +3441,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass241(any a0, any a1, any a2) { label_1: @@ -3613,7 +3453,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass242(any a0, any a1, any a2) { label_1: @@ -3626,7 +3465,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass243(any a0, any a1, any a2) { label_1: @@ -3639,7 +3477,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass244(any a0, any a1, any a2) { label_1: @@ -3652,7 +3489,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass245(any a0, any a1, any a2) { label_1: @@ -3665,7 +3501,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass246(any a0, any a1, any a2) { label_1: @@ -3678,7 +3513,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass247(any a0, any a1, any a2) { label_1: @@ -3691,7 +3525,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass248(any a0, any a1, any a2) { label_1: @@ -3704,7 +3537,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass249(any a0, any a1, any a2) { label_1: @@ -3717,7 +3549,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass25(any a0, any a1, any a2) { label_1: @@ -3730,7 +3561,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass250(any a0, any a1, any a2) { label_1: @@ -3743,7 +3573,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass251(any a0, any a1, any a2) { label_1: @@ -3756,7 +3585,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass252(any a0, any a1, any a2) { label_1: @@ -3769,7 +3597,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass253(any a0, any a1, any a2) { label_1: @@ -3782,7 +3609,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass254(any a0, any a1, any a2) { label_1: @@ -3795,7 +3621,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass255(any a0, any a1, any a2) { label_1: @@ -3808,7 +3633,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass26(any a0, any a1, any a2) { label_1: @@ -3821,7 +3645,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass27(any a0, any a1, any a2) { label_1: @@ -3834,7 +3657,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass28(any a0, any a1, any a2) { label_1: @@ -3847,7 +3669,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass29(any a0, any a1, any a2) { label_1: @@ -3860,7 +3681,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass3(any a0, any a1, any a2) { label_1: @@ -3873,7 +3693,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass30(any a0, any a1, any a2) { label_1: @@ -3886,7 +3705,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass31(any a0, any a1, any a2) { label_1: @@ -3899,7 +3717,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass32(any a0, any a1, any a2) { label_1: @@ -3912,7 +3729,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass33(any a0, any a1, any a2) { label_1: @@ -3925,7 +3741,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass34(any a0, any a1, any a2) { label_1: @@ -3938,7 +3753,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass35(any a0, any a1, any a2) { label_1: @@ -3951,7 +3765,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass36(any a0, any a1, any a2) { label_1: @@ -3964,7 +3777,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass37(any a0, any a1, any a2) { label_1: @@ -3977,7 +3789,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass38(any a0, any a1, any a2) { label_1: @@ -3990,7 +3801,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass39(any a0, any a1, any a2) { label_1: @@ -4003,7 +3813,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass4(any a0, any a1, any a2) { label_1: @@ -4016,7 +3825,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass40(any a0, any a1, any a2) { label_1: @@ -4029,7 +3837,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass41(any a0, any a1, any a2) { label_1: @@ -4042,7 +3849,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass42(any a0, any a1, any a2) { label_1: @@ -4055,7 +3861,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass43(any a0, any a1, any a2) { label_1: @@ -4068,7 +3873,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass44(any a0, any a1, any a2) { label_1: @@ -4081,7 +3885,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass45(any a0, any a1, any a2) { label_1: @@ -4094,7 +3897,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass46(any a0, any a1, any a2) { label_1: @@ -4107,7 +3909,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass47(any a0, any a1, any a2) { label_1: @@ -4120,7 +3921,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass48(any a0, any a1, any a2) { label_1: @@ -4133,7 +3933,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass49(any a0, any a1, any a2) { label_1: @@ -4146,7 +3945,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass5(any a0, any a1, any a2) { label_1: @@ -4159,7 +3957,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass50(any a0, any a1, any a2) { label_1: @@ -4172,7 +3969,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass51(any a0, any a1, any a2) { label_1: @@ -4185,7 +3981,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass52(any a0, any a1, any a2) { label_1: @@ -4198,7 +3993,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass53(any a0, any a1, any a2) { label_1: @@ -4211,7 +4005,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass54(any a0, any a1, any a2) { label_1: @@ -4224,7 +4017,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass55(any a0, any a1, any a2) { label_1: @@ -4237,7 +4029,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass56(any a0, any a1, any a2) { label_1: @@ -4250,7 +4041,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass57(any a0, any a1, any a2) { label_1: @@ -4263,7 +4053,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass58(any a0, any a1, any a2) { label_1: @@ -4276,7 +4065,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass59(any a0, any a1, any a2) { label_1: @@ -4289,7 +4077,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass6(any a0, any a1, any a2) { label_1: @@ -4302,7 +4089,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass60(any a0, any a1, any a2) { label_1: @@ -4315,7 +4101,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass61(any a0, any a1, any a2) { label_1: @@ -4328,7 +4113,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass62(any a0, any a1, any a2) { label_1: @@ -4341,7 +4125,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass63(any a0, any a1, any a2) { label_1: @@ -4354,7 +4137,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass64(any a0, any a1, any a2) { label_1: @@ -4367,7 +4149,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass65(any a0, any a1, any a2) { label_1: @@ -4380,7 +4161,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass66(any a0, any a1, any a2) { label_1: @@ -4393,7 +4173,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass67(any a0, any a1, any a2) { label_1: @@ -4406,7 +4185,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass68(any a0, any a1, any a2) { label_1: @@ -4419,7 +4197,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass69(any a0, any a1, any a2) { label_1: @@ -4432,7 +4209,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass7(any a0, any a1, any a2) { label_1: @@ -4445,7 +4221,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass70(any a0, any a1, any a2) { label_1: @@ -4458,7 +4233,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass71(any a0, any a1, any a2) { label_1: @@ -4471,7 +4245,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass72(any a0, any a1, any a2) { label_1: @@ -4484,7 +4257,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass73(any a0, any a1, any a2) { label_1: @@ -4497,7 +4269,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass74(any a0, any a1, any a2) { label_1: @@ -4510,7 +4281,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass75(any a0, any a1, any a2) { label_1: @@ -4523,7 +4293,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass76(any a0, any a1, any a2) { label_1: @@ -4536,7 +4305,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass77(any a0, any a1, any a2) { label_1: @@ -4549,7 +4317,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass78(any a0, any a1, any a2) { label_1: @@ -4562,7 +4329,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass79(any a0, any a1, any a2) { label_1: @@ -4575,7 +4341,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass8(any a0, any a1, any a2) { label_1: @@ -4588,7 +4353,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass80(any a0, any a1, any a2) { label_1: @@ -4601,7 +4365,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass81(any a0, any a1, any a2) { label_1: @@ -4614,7 +4377,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass82(any a0, any a1, any a2) { label_1: @@ -4627,7 +4389,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass83(any a0, any a1, any a2) { label_1: @@ -4640,7 +4401,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass84(any a0, any a1, any a2) { label_1: @@ -4653,7 +4413,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass85(any a0, any a1, any a2) { label_1: @@ -4666,7 +4425,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass86(any a0, any a1, any a2) { label_1: @@ -4679,7 +4437,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass87(any a0, any a1, any a2) { label_1: @@ -4692,7 +4449,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass88(any a0, any a1, any a2) { label_1: @@ -4705,7 +4461,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass89(any a0, any a1, any a2) { label_1: @@ -4718,7 +4473,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass9(any a0, any a1, any a2) { label_1: @@ -4731,7 +4485,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass90(any a0, any a1, any a2) { label_1: @@ -4744,7 +4497,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass91(any a0, any a1, any a2) { label_1: @@ -4757,7 +4509,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass92(any a0, any a1, any a2) { label_1: @@ -4770,7 +4521,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass93(any a0, any a1, any a2) { label_1: @@ -4783,7 +4533,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass94(any a0, any a1, any a2) { label_1: @@ -4796,7 +4545,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass95(any a0, any a1, any a2) { label_1: @@ -4809,7 +4557,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass96(any a0, any a1, any a2) { label_1: @@ -4822,7 +4569,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass97(any a0, any a1, any a2) { label_1: @@ -4835,7 +4581,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass98(any a0, any a1, any a2) { label_1: @@ -4848,7 +4593,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass99(any a0, any a1, any a2) { label_1: diff --git a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_unsupported_compile_for_below_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_unsupported_compile_for_below_API12beta3_asm_version-expected.txt index 50cd83163e..33c3a51f3e 100644 --- a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_unsupported_compile_for_below_API12beta3_asm_version-expected.txt +++ b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_unsupported_compile_for_below_API12beta3_asm_version-expected.txt @@ -1,5 +1,4 @@ slotNum = 0x406 -expectedProperty = 0x101 .language ECMAScript .function any .SendableTestClass1(any a0, any a1, any a2) { label_1: @@ -1546,7 +1545,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass1(any a0, any a1, any a2) { label_1: @@ -1559,7 +1557,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass10(any a0, any a1, any a2) { label_1: @@ -1572,7 +1569,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass100(any a0, any a1, any a2) { label_1: @@ -1585,7 +1581,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass101(any a0, any a1, any a2) { label_1: @@ -1598,7 +1593,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass102(any a0, any a1, any a2) { label_1: @@ -1611,7 +1605,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass103(any a0, any a1, any a2) { label_1: @@ -1624,7 +1617,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass104(any a0, any a1, any a2) { label_1: @@ -1637,7 +1629,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass105(any a0, any a1, any a2) { label_1: @@ -1650,7 +1641,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass106(any a0, any a1, any a2) { label_1: @@ -1663,7 +1653,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass107(any a0, any a1, any a2) { label_1: @@ -1676,7 +1665,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass108(any a0, any a1, any a2) { label_1: @@ -1689,7 +1677,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass109(any a0, any a1, any a2) { label_1: @@ -1702,7 +1689,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass11(any a0, any a1, any a2) { label_1: @@ -1715,7 +1701,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass110(any a0, any a1, any a2) { label_1: @@ -1728,7 +1713,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass111(any a0, any a1, any a2) { label_1: @@ -1741,7 +1725,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass112(any a0, any a1, any a2) { label_1: @@ -1754,7 +1737,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass113(any a0, any a1, any a2) { label_1: @@ -1767,7 +1749,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass114(any a0, any a1, any a2) { label_1: @@ -1780,7 +1761,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass115(any a0, any a1, any a2) { label_1: @@ -1793,7 +1773,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass116(any a0, any a1, any a2) { label_1: @@ -1806,7 +1785,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass117(any a0, any a1, any a2) { label_1: @@ -1819,7 +1797,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass118(any a0, any a1, any a2) { label_1: @@ -1832,7 +1809,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass119(any a0, any a1, any a2) { label_1: @@ -1845,7 +1821,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass12(any a0, any a1, any a2) { label_1: @@ -1858,7 +1833,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass120(any a0, any a1, any a2) { label_1: @@ -1871,7 +1845,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass121(any a0, any a1, any a2) { label_1: @@ -1884,7 +1857,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass122(any a0, any a1, any a2) { label_1: @@ -1897,7 +1869,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass123(any a0, any a1, any a2) { label_1: @@ -1910,7 +1881,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass124(any a0, any a1, any a2) { label_1: @@ -1923,7 +1893,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass125(any a0, any a1, any a2) { label_1: @@ -1936,7 +1905,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass126(any a0, any a1, any a2) { label_1: @@ -1949,7 +1917,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass127(any a0, any a1, any a2) { label_1: @@ -1962,7 +1929,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass128(any a0, any a1, any a2) { label_1: @@ -1975,7 +1941,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass129(any a0, any a1, any a2) { label_1: @@ -1988,7 +1953,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass13(any a0, any a1, any a2) { label_1: @@ -2001,7 +1965,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass130(any a0, any a1, any a2) { label_1: @@ -2014,7 +1977,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass131(any a0, any a1, any a2) { label_1: @@ -2027,7 +1989,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass132(any a0, any a1, any a2) { label_1: @@ -2040,7 +2001,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass133(any a0, any a1, any a2) { label_1: @@ -2053,7 +2013,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass134(any a0, any a1, any a2) { label_1: @@ -2066,7 +2025,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass135(any a0, any a1, any a2) { label_1: @@ -2079,7 +2037,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass136(any a0, any a1, any a2) { label_1: @@ -2092,7 +2049,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass137(any a0, any a1, any a2) { label_1: @@ -2105,7 +2061,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass138(any a0, any a1, any a2) { label_1: @@ -2118,7 +2073,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass139(any a0, any a1, any a2) { label_1: @@ -2131,7 +2085,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass14(any a0, any a1, any a2) { label_1: @@ -2144,7 +2097,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass140(any a0, any a1, any a2) { label_1: @@ -2157,7 +2109,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass141(any a0, any a1, any a2) { label_1: @@ -2170,7 +2121,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass142(any a0, any a1, any a2) { label_1: @@ -2183,7 +2133,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass143(any a0, any a1, any a2) { label_1: @@ -2196,7 +2145,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass144(any a0, any a1, any a2) { label_1: @@ -2209,7 +2157,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass145(any a0, any a1, any a2) { label_1: @@ -2222,7 +2169,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass146(any a0, any a1, any a2) { label_1: @@ -2235,7 +2181,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass147(any a0, any a1, any a2) { label_1: @@ -2248,7 +2193,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass148(any a0, any a1, any a2) { label_1: @@ -2261,7 +2205,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass149(any a0, any a1, any a2) { label_1: @@ -2274,7 +2217,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass15(any a0, any a1, any a2) { label_1: @@ -2287,7 +2229,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass150(any a0, any a1, any a2) { label_1: @@ -2300,7 +2241,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass151(any a0, any a1, any a2) { label_1: @@ -2313,7 +2253,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass152(any a0, any a1, any a2) { label_1: @@ -2326,7 +2265,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass153(any a0, any a1, any a2) { label_1: @@ -2339,7 +2277,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass154(any a0, any a1, any a2) { label_1: @@ -2352,7 +2289,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass155(any a0, any a1, any a2) { label_1: @@ -2365,7 +2301,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass156(any a0, any a1, any a2) { label_1: @@ -2378,7 +2313,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass157(any a0, any a1, any a2) { label_1: @@ -2391,7 +2325,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass158(any a0, any a1, any a2) { label_1: @@ -2404,7 +2337,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass159(any a0, any a1, any a2) { label_1: @@ -2417,7 +2349,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass16(any a0, any a1, any a2) { label_1: @@ -2430,7 +2361,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass160(any a0, any a1, any a2) { label_1: @@ -2443,7 +2373,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass161(any a0, any a1, any a2) { label_1: @@ -2456,7 +2385,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass162(any a0, any a1, any a2) { label_1: @@ -2469,7 +2397,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass163(any a0, any a1, any a2) { label_1: @@ -2482,7 +2409,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass164(any a0, any a1, any a2) { label_1: @@ -2495,7 +2421,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass165(any a0, any a1, any a2) { label_1: @@ -2508,7 +2433,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass166(any a0, any a1, any a2) { label_1: @@ -2521,7 +2445,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass167(any a0, any a1, any a2) { label_1: @@ -2534,7 +2457,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass168(any a0, any a1, any a2) { label_1: @@ -2547,7 +2469,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass169(any a0, any a1, any a2) { label_1: @@ -2560,7 +2481,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass17(any a0, any a1, any a2) { label_1: @@ -2573,7 +2493,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass170(any a0, any a1, any a2) { label_1: @@ -2586,7 +2505,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass171(any a0, any a1, any a2) { label_1: @@ -2599,7 +2517,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass172(any a0, any a1, any a2) { label_1: @@ -2612,7 +2529,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass173(any a0, any a1, any a2) { label_1: @@ -2625,7 +2541,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass174(any a0, any a1, any a2) { label_1: @@ -2638,7 +2553,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass175(any a0, any a1, any a2) { label_1: @@ -2651,7 +2565,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass176(any a0, any a1, any a2) { label_1: @@ -2664,7 +2577,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass177(any a0, any a1, any a2) { label_1: @@ -2677,7 +2589,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass178(any a0, any a1, any a2) { label_1: @@ -2690,7 +2601,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass179(any a0, any a1, any a2) { label_1: @@ -2703,7 +2613,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass18(any a0, any a1, any a2) { label_1: @@ -2716,7 +2625,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass180(any a0, any a1, any a2) { label_1: @@ -2729,7 +2637,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass181(any a0, any a1, any a2) { label_1: @@ -2742,7 +2649,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass182(any a0, any a1, any a2) { label_1: @@ -2755,7 +2661,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass183(any a0, any a1, any a2) { label_1: @@ -2768,7 +2673,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass184(any a0, any a1, any a2) { label_1: @@ -2781,7 +2685,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass185(any a0, any a1, any a2) { label_1: @@ -2794,7 +2697,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass186(any a0, any a1, any a2) { label_1: @@ -2807,7 +2709,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass187(any a0, any a1, any a2) { label_1: @@ -2820,7 +2721,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass188(any a0, any a1, any a2) { label_1: @@ -2833,7 +2733,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass189(any a0, any a1, any a2) { label_1: @@ -2846,7 +2745,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass19(any a0, any a1, any a2) { label_1: @@ -2859,7 +2757,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass190(any a0, any a1, any a2) { label_1: @@ -2872,7 +2769,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass191(any a0, any a1, any a2) { label_1: @@ -2885,7 +2781,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass192(any a0, any a1, any a2) { label_1: @@ -2898,7 +2793,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass193(any a0, any a1, any a2) { label_1: @@ -2911,7 +2805,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass194(any a0, any a1, any a2) { label_1: @@ -2924,7 +2817,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass195(any a0, any a1, any a2) { label_1: @@ -2937,7 +2829,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass196(any a0, any a1, any a2) { label_1: @@ -2950,7 +2841,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass197(any a0, any a1, any a2) { label_1: @@ -2963,7 +2853,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass198(any a0, any a1, any a2) { label_1: @@ -2976,7 +2865,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass199(any a0, any a1, any a2) { label_1: @@ -2989,7 +2877,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass2(any a0, any a1, any a2) { label_1: @@ -3002,7 +2889,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass20(any a0, any a1, any a2) { label_1: @@ -3015,7 +2901,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass200(any a0, any a1, any a2) { label_1: @@ -3028,7 +2913,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass201(any a0, any a1, any a2) { label_1: @@ -3041,7 +2925,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass202(any a0, any a1, any a2) { label_1: @@ -3054,7 +2937,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass203(any a0, any a1, any a2) { label_1: @@ -3067,7 +2949,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass204(any a0, any a1, any a2) { label_1: @@ -3080,7 +2961,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass205(any a0, any a1, any a2) { label_1: @@ -3093,7 +2973,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass206(any a0, any a1, any a2) { label_1: @@ -3106,7 +2985,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass207(any a0, any a1, any a2) { label_1: @@ -3119,7 +2997,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass208(any a0, any a1, any a2) { label_1: @@ -3132,7 +3009,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass209(any a0, any a1, any a2) { label_1: @@ -3145,7 +3021,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass21(any a0, any a1, any a2) { label_1: @@ -3158,7 +3033,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass210(any a0, any a1, any a2) { label_1: @@ -3171,7 +3045,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass211(any a0, any a1, any a2) { label_1: @@ -3184,7 +3057,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass212(any a0, any a1, any a2) { label_1: @@ -3197,7 +3069,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass213(any a0, any a1, any a2) { label_1: @@ -3210,7 +3081,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass214(any a0, any a1, any a2) { label_1: @@ -3223,7 +3093,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass215(any a0, any a1, any a2) { label_1: @@ -3236,7 +3105,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass216(any a0, any a1, any a2) { label_1: @@ -3249,7 +3117,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass217(any a0, any a1, any a2) { label_1: @@ -3262,7 +3129,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass218(any a0, any a1, any a2) { label_1: @@ -3275,7 +3141,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass219(any a0, any a1, any a2) { label_1: @@ -3288,7 +3153,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass22(any a0, any a1, any a2) { label_1: @@ -3301,7 +3165,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass220(any a0, any a1, any a2) { label_1: @@ -3314,7 +3177,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass221(any a0, any a1, any a2) { label_1: @@ -3327,7 +3189,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass222(any a0, any a1, any a2) { label_1: @@ -3340,7 +3201,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass223(any a0, any a1, any a2) { label_1: @@ -3353,7 +3213,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass224(any a0, any a1, any a2) { label_1: @@ -3366,7 +3225,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass225(any a0, any a1, any a2) { label_1: @@ -3379,7 +3237,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass226(any a0, any a1, any a2) { label_1: @@ -3392,7 +3249,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass227(any a0, any a1, any a2) { label_1: @@ -3405,7 +3261,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass228(any a0, any a1, any a2) { label_1: @@ -3418,7 +3273,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass229(any a0, any a1, any a2) { label_1: @@ -3431,7 +3285,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass23(any a0, any a1, any a2) { label_1: @@ -3444,7 +3297,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass230(any a0, any a1, any a2) { label_1: @@ -3457,7 +3309,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass231(any a0, any a1, any a2) { label_1: @@ -3470,7 +3321,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass232(any a0, any a1, any a2) { label_1: @@ -3483,7 +3333,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass233(any a0, any a1, any a2) { label_1: @@ -3496,7 +3345,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass234(any a0, any a1, any a2) { label_1: @@ -3509,7 +3357,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass235(any a0, any a1, any a2) { label_1: @@ -3522,7 +3369,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass236(any a0, any a1, any a2) { label_1: @@ -3535,7 +3381,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass237(any a0, any a1, any a2) { label_1: @@ -3548,7 +3393,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass238(any a0, any a1, any a2) { label_1: @@ -3561,7 +3405,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass239(any a0, any a1, any a2) { label_1: @@ -3574,7 +3417,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass24(any a0, any a1, any a2) { label_1: @@ -3587,7 +3429,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass240(any a0, any a1, any a2) { label_1: @@ -3600,7 +3441,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass241(any a0, any a1, any a2) { label_1: @@ -3613,7 +3453,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass242(any a0, any a1, any a2) { label_1: @@ -3626,7 +3465,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass243(any a0, any a1, any a2) { label_1: @@ -3639,7 +3477,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass244(any a0, any a1, any a2) { label_1: @@ -3652,7 +3489,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass245(any a0, any a1, any a2) { label_1: @@ -3665,7 +3501,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass246(any a0, any a1, any a2) { label_1: @@ -3678,7 +3513,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass247(any a0, any a1, any a2) { label_1: @@ -3691,7 +3525,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass248(any a0, any a1, any a2) { label_1: @@ -3704,7 +3537,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass249(any a0, any a1, any a2) { label_1: @@ -3717,7 +3549,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass25(any a0, any a1, any a2) { label_1: @@ -3730,7 +3561,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass250(any a0, any a1, any a2) { label_1: @@ -3743,7 +3573,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass251(any a0, any a1, any a2) { label_1: @@ -3756,7 +3585,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass252(any a0, any a1, any a2) { label_1: @@ -3769,7 +3597,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass253(any a0, any a1, any a2) { label_1: @@ -3782,7 +3609,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass254(any a0, any a1, any a2) { label_1: @@ -3795,7 +3621,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass255(any a0, any a1, any a2) { label_1: @@ -3808,7 +3633,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass26(any a0, any a1, any a2) { label_1: @@ -3821,7 +3645,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass27(any a0, any a1, any a2) { label_1: @@ -3834,7 +3657,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass28(any a0, any a1, any a2) { label_1: @@ -3847,7 +3669,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass29(any a0, any a1, any a2) { label_1: @@ -3860,7 +3681,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass3(any a0, any a1, any a2) { label_1: @@ -3873,7 +3693,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass30(any a0, any a1, any a2) { label_1: @@ -3886,7 +3705,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass31(any a0, any a1, any a2) { label_1: @@ -3899,7 +3717,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass32(any a0, any a1, any a2) { label_1: @@ -3912,7 +3729,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass33(any a0, any a1, any a2) { label_1: @@ -3925,7 +3741,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass34(any a0, any a1, any a2) { label_1: @@ -3938,7 +3753,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass35(any a0, any a1, any a2) { label_1: @@ -3951,7 +3765,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass36(any a0, any a1, any a2) { label_1: @@ -3964,7 +3777,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass37(any a0, any a1, any a2) { label_1: @@ -3977,7 +3789,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass38(any a0, any a1, any a2) { label_1: @@ -3990,7 +3801,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass39(any a0, any a1, any a2) { label_1: @@ -4003,7 +3813,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass4(any a0, any a1, any a2) { label_1: @@ -4016,7 +3825,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass40(any a0, any a1, any a2) { label_1: @@ -4029,7 +3837,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass41(any a0, any a1, any a2) { label_1: @@ -4042,7 +3849,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass42(any a0, any a1, any a2) { label_1: @@ -4055,7 +3861,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass43(any a0, any a1, any a2) { label_1: @@ -4068,7 +3873,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass44(any a0, any a1, any a2) { label_1: @@ -4081,7 +3885,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass45(any a0, any a1, any a2) { label_1: @@ -4094,7 +3897,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass46(any a0, any a1, any a2) { label_1: @@ -4107,7 +3909,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass47(any a0, any a1, any a2) { label_1: @@ -4120,7 +3921,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass48(any a0, any a1, any a2) { label_1: @@ -4133,7 +3933,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass49(any a0, any a1, any a2) { label_1: @@ -4146,7 +3945,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass5(any a0, any a1, any a2) { label_1: @@ -4159,7 +3957,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass50(any a0, any a1, any a2) { label_1: @@ -4172,7 +3969,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass51(any a0, any a1, any a2) { label_1: @@ -4185,7 +3981,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass52(any a0, any a1, any a2) { label_1: @@ -4198,7 +3993,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass53(any a0, any a1, any a2) { label_1: @@ -4211,7 +4005,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass54(any a0, any a1, any a2) { label_1: @@ -4224,7 +4017,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass55(any a0, any a1, any a2) { label_1: @@ -4237,7 +4029,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass56(any a0, any a1, any a2) { label_1: @@ -4250,7 +4041,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass57(any a0, any a1, any a2) { label_1: @@ -4263,7 +4053,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass58(any a0, any a1, any a2) { label_1: @@ -4276,7 +4065,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass59(any a0, any a1, any a2) { label_1: @@ -4289,7 +4077,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass6(any a0, any a1, any a2) { label_1: @@ -4302,7 +4089,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass60(any a0, any a1, any a2) { label_1: @@ -4315,7 +4101,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass61(any a0, any a1, any a2) { label_1: @@ -4328,7 +4113,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass62(any a0, any a1, any a2) { label_1: @@ -4341,7 +4125,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass63(any a0, any a1, any a2) { label_1: @@ -4354,7 +4137,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass64(any a0, any a1, any a2) { label_1: @@ -4367,7 +4149,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass65(any a0, any a1, any a2) { label_1: @@ -4380,7 +4161,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass66(any a0, any a1, any a2) { label_1: @@ -4393,7 +4173,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass67(any a0, any a1, any a2) { label_1: @@ -4406,7 +4185,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass68(any a0, any a1, any a2) { label_1: @@ -4419,7 +4197,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass69(any a0, any a1, any a2) { label_1: @@ -4432,7 +4209,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass7(any a0, any a1, any a2) { label_1: @@ -4445,7 +4221,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass70(any a0, any a1, any a2) { label_1: @@ -4458,7 +4233,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass71(any a0, any a1, any a2) { label_1: @@ -4471,7 +4245,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass72(any a0, any a1, any a2) { label_1: @@ -4484,7 +4257,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass73(any a0, any a1, any a2) { label_1: @@ -4497,7 +4269,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass74(any a0, any a1, any a2) { label_1: @@ -4510,7 +4281,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass75(any a0, any a1, any a2) { label_1: @@ -4523,7 +4293,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass76(any a0, any a1, any a2) { label_1: @@ -4536,7 +4305,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass77(any a0, any a1, any a2) { label_1: @@ -4549,7 +4317,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass78(any a0, any a1, any a2) { label_1: @@ -4562,7 +4329,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass79(any a0, any a1, any a2) { label_1: @@ -4575,7 +4341,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass8(any a0, any a1, any a2) { label_1: @@ -4588,7 +4353,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass80(any a0, any a1, any a2) { label_1: @@ -4601,7 +4365,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass81(any a0, any a1, any a2) { label_1: @@ -4614,7 +4377,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass82(any a0, any a1, any a2) { label_1: @@ -4627,7 +4389,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass83(any a0, any a1, any a2) { label_1: @@ -4640,7 +4401,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass84(any a0, any a1, any a2) { label_1: @@ -4653,7 +4413,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass85(any a0, any a1, any a2) { label_1: @@ -4666,7 +4425,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass86(any a0, any a1, any a2) { label_1: @@ -4679,7 +4437,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass87(any a0, any a1, any a2) { label_1: @@ -4692,7 +4449,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass88(any a0, any a1, any a2) { label_1: @@ -4705,7 +4461,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass89(any a0, any a1, any a2) { label_1: @@ -4718,7 +4473,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass9(any a0, any a1, any a2) { label_1: @@ -4731,7 +4485,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass90(any a0, any a1, any a2) { label_1: @@ -4744,7 +4497,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass91(any a0, any a1, any a2) { label_1: @@ -4757,7 +4509,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass92(any a0, any a1, any a2) { label_1: @@ -4770,7 +4521,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass93(any a0, any a1, any a2) { label_1: @@ -4783,7 +4533,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass94(any a0, any a1, any a2) { label_1: @@ -4796,7 +4545,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass95(any a0, any a1, any a2) { label_1: @@ -4809,7 +4557,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass96(any a0, any a1, any a2) { label_1: @@ -4822,7 +4569,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass97(any a0, any a1, any a2) { label_1: @@ -4835,7 +4581,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass98(any a0, any a1, any a2) { label_1: @@ -4848,7 +4593,6 @@ label_2: } slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .TopLevelSendableClass99(any a0, any a1, any a2) { label_1: diff --git a/es2panda/test/version_control/API12beta3/bytecode_feature/lazy_import_bytecode_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API12beta3/bytecode_feature/lazy_import_bytecode_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt index c16a17b509..22f60b0b50 100644 --- a/es2panda/test/version_control/API12beta3/bytecode_feature/lazy_import_bytecode_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt +++ b/es2panda/test/version_control/API12beta3/bytecode_feature/lazy_import_bytecode_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt @@ -1,5 +1,4 @@ slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@0=#SendableLazyLoading(any a0, any a1, any a2) { label_1: diff --git a/es2panda/test/version_control/API12beta3/bytecode_feature/lazy_import_bytecode_supported_compile_for_higher_or_equal_to_API16beta3_asm_version-expected.txt b/es2panda/test/version_control/API12beta3/bytecode_feature/lazy_import_bytecode_supported_compile_for_higher_or_equal_to_API16beta3_asm_version-expected.txt index c92d705a82..4eb3781c08 100644 --- a/es2panda/test/version_control/API12beta3/bytecode_feature/lazy_import_bytecode_supported_compile_for_higher_or_equal_to_API16beta3_asm_version-expected.txt +++ b/es2panda/test/version_control/API12beta3/bytecode_feature/lazy_import_bytecode_supported_compile_for_higher_or_equal_to_API16beta3_asm_version-expected.txt @@ -1,7 +1,6 @@ .language ECMAScript slotNum = 0x2 -expectedProperty = 0x1 .function any .#~@0=#SendableLazyLoading(any a0, any a1, any a2) { label_1: label_0: diff --git a/es2panda/test/version_control/API12beta3/bytecode_feature/wide_lazy_import_bytecode_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API12beta3/bytecode_feature/wide_lazy_import_bytecode_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt index 3222f27c48..851a53ce73 100644 --- a/es2panda/test/version_control/API12beta3/bytecode_feature/wide_lazy_import_bytecode_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt +++ b/es2panda/test/version_control/API12beta3/bytecode_feature/wide_lazy_import_bytecode_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt @@ -1,5 +1,4 @@ slotNum = 0x2 -expectedProperty = 0x1 .language ECMAScript .function any .#~@0=#WideSendableLazyLoading(any a0, any a1, any a2) { label_1: diff --git a/es2panda/test/version_control/API12beta3/bytecode_feature/wide_lazy_import_bytecode_supported_compile_for_higher_or_equal_to_API16beta3_asm_version-expected.txt b/es2panda/test/version_control/API12beta3/bytecode_feature/wide_lazy_import_bytecode_supported_compile_for_higher_or_equal_to_API16beta3_asm_version-expected.txt index 3b520c914c..568f9fd81e 100644 --- a/es2panda/test/version_control/API12beta3/bytecode_feature/wide_lazy_import_bytecode_supported_compile_for_higher_or_equal_to_API16beta3_asm_version-expected.txt +++ b/es2panda/test/version_control/API12beta3/bytecode_feature/wide_lazy_import_bytecode_supported_compile_for_higher_or_equal_to_API16beta3_asm_version-expected.txt @@ -1,7 +1,6 @@ .language ECMAScript slotNum = 0x2 -expectedProperty = 0x1 .function any .#~@0=#WideSendableLazyLoading(any a0, any a1, any a2) { label_1: label_0: diff --git a/es2panda/util/helpers.cpp b/es2panda/util/helpers.cpp index 2c2462cd92..67774a04d3 100644 --- a/es2panda/util/helpers.cpp +++ b/es2panda/util/helpers.cpp @@ -988,4 +988,8 @@ bool Helpers::IsSupportLazyImportDefaultVersion(int apiVersion) return !(apiVersion < LAZY_IMPORT_DEFAULT_MIN_SUPPORTED_API_VERSION); } +bool Helpers::IsEnableExpectedPropertyCountApiVersion(int apiVersion) +{ + return !(apiVersion < ENABLE_EXPECTED_PROPERTY_COUNT_MIN_SUPPORTED_API_VERSION); +} } // namespace panda::es2panda::util diff --git a/es2panda/util/helpers.h b/es2panda/util/helpers.h index 6ed116a475..365de482b8 100644 --- a/es2panda/util/helpers.h +++ b/es2panda/util/helpers.h @@ -181,6 +181,7 @@ public: static bool IsDefaultApiVersion(int apiVersion, std::string subApiVersion); static bool IsSupportLazyImportVersion(int apiVersion, std::string subApiVersion); static bool IsSupportLazyImportDefaultVersion(int apiVersion); + static bool IsEnableExpectedPropertyCountApiVersion(int apiVersion); static const uint32_t MAX_DOUBLE_DIGIT = 310; static const uint32_t MAX_DOUBLE_PRECISION_DIGIT = 17; @@ -220,6 +221,7 @@ public: static const int32_t SENDABLE_LAZY_LOADING_MIN_SUPPORTED_API_VERSION = 12; static const int8_t SUPER_CALL_OPT_MIN_SUPPORTED_API_VERSION = 18; static const int8_t SENDABLE_CLASS_USING_LOCAL_MODULE_VAR_MIN_SUPPORTED_API_VERSION = 18; + static const int8_t ENABLE_EXPECTED_PROPERTY_COUNT_MIN_SUPPORTED_API_VERSION = 18; static constexpr std::string_view SUB_API_VERSION_1 = "beta1"; static constexpr std::string_view SUB_API_VERSION_2 = "beta2"; static constexpr std::string_view DEFAULT_SUB_API_VERSION = SUB_API_VERSION_1; -- Gitee From 3b7e958fba4247ea526d3e17d469368654dcec79 Mon Sep 17 00:00:00 2001 From: Anna Antipina Date: Tue, 1 Apr 2025 18:28:43 +0300 Subject: [PATCH 100/268] Retain exported records in Module annotation Retain the exported module records (module, class=class/interface/enum) as class_ids in @Module annotation, so the runtime will be able to inspect it. Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBY3RV Testing: - ninja top_level_statements_test_gtests; - ninja all tests; Change-Id: I9ea747d9354b42bd9b56e977fda039b1128047d7 Signed-off-by: Anna Antipina --- ets2panda/compiler/core/ETSemitter.cpp | 23 + ets2panda/compiler/core/ETSemitter.h | 1 + .../ets/topLevelStmts/globalClassHandler.cpp | 43 +- .../ets/topLevelStmts/globalClassHandler.h | 4 +- ets2panda/compiler/scripts/signatures.yaml | 9 +- ets2panda/declgen_ets2ts/declgenEts2Ts.cpp | 3 - ets2panda/ir/base/classDefinition.h | 22 +- .../test/compiler/ets/116100-expected.txt | 34 - ...ditionalExpressionCallVoidNeg-expected.txt | 34 - .../compiler/ets/FunctionType2-expected.txt | 34 - .../compiler/ets/FunctionType4-expected.txt | 34 - ...ctMethodDeclaredInParentClass-expected.txt | 34 - ...actNewClassInstanceExpression-expected.txt | 34 - .../ets/ambient_declaration-expected.txt | 34 - ..._without_chaining_non_nullish-expected.txt | 34 - .../ets/array_with_null_type-expected.txt | 34 - .../array_with_undefined_type-expected.txt | 34 - .../ets/arrowFunctionCapture-expected.txt | 34 - .../ets/boxingConversion10-expected.txt | 34 - .../ets/boxingConversion2-expected.txt | 34 - .../ets/boxingConversion3-expected.txt | 34 - .../ets/boxingConversion5-expected.txt | 34 - .../ets/boxingConversion6-expected.txt | 34 - .../ets/boxingConversion7-expected.txt | 34 - .../ets/boxingConversion8-expected.txt | 34 - .../ets/boxingConversion9-expected.txt | 34 - .../boxingUnboxingExpressions-expected.txt | 34 - .../ets/catch-soft-keyword-expected.txt | 34 - .../compiler/ets/catchParamScope-expected.txt | 34 - .../ets/class_def_varargs_1-expected.txt | 34 - .../ets/class_def_varargs_2-expected.txt | 34 - .../ets/conversion-w-ASExpr-expected.txt | 34 - .../ets/conversion_w_functions-expected.txt | 34 - .../ets/delete-non-keyword-expected.txt | 34 - .../ets/dynamic-equality-expected.txt | 34 - .../compiler/ets/dynamicJsImport-expected.txt | 34 - .../compiler/ets/dynamicLambda-expected.txt | 34 - .../ets/dynamicLambdaJSValue-expected.txt | 34 - .../ets/dynamicLambdaJSValueCast-expected.txt | 34 - .../ets/dynamicObjectLiteral-expected.txt | 34 - .../compiler/ets/dynamic_call-expected.txt | 34 - .../ets/dynamic_instanceof_error-expected.txt | 34 - .../ensureNotNullArgNotNullable-expected.txt | 34 - ...ensureNotNullLocalNotNullable-expected.txt | 34 - ...nsureNotNullReturnNotNullable-expected.txt | 34 - ...as_class_member_getValue_call-expected.txt | 34 - .../compiler/ets/export_type-expected.txt | 34 - ...ed_conditional_expression_not-expected.txt | 34 - ...al_expression_not_return_type-expected.txt | 34 - .../test/compiler/ets/forUpdate-expected.txt | 34 - .../ets/forUpdateCharType-expected.txt | 34 - .../ets/from-soft-keyword-0-expected.txt | 34 - .../ets/from-soft-keyword-1-expected.txt | 34 - .../ets/from-soft-keyword-2-expected.txt | 34 - .../ets/func-ref-private-expected.txt | 34 - .../ets/functionPointerArray-expected.txt | 34 - .../ets/functionTypeToObject-expected.txt | 34 - .../ets/function_subtyping_1-expected.txt | 34 - ...with_ambiguous_rest_parameter-expected.txt | 34 - .../ets/generic_arrayaslist-expected.txt | 34 - .../generic_class_getter_setter-expected.txt | 34 - .../ets/generic_deadlock-expected.txt | 34 - ..._func_rest_param_spread_infer-expected.txt | 34 - .../ets/generic_function_call_1-expected.txt | 34 - .../ets/generic_function_call_3-expected.txt | 34 - .../ets/generic_function_call_4-expected.txt | 34 - .../ets/generic_function_call_5-expected.txt | 34 - .../ets/generic_function_call_7-expected.txt | 34 - .../ets/generic_override_1-expected.txt | 34 - .../ets/generic_override_2-expected.txt | 34 - .../ets/generic_override_3-expected.txt | 34 - .../ets/generic_typealias_1-expected.txt | 34 - .../ets/generic_typealias_6-expected.txt | 34 - .../ets/generic_typealias_7_neg-expected.txt | 34 - .../ets/generic_typealias_8-expected.txt | 34 - .../ets/generic_typealias_9-expected.txt | 34 - .../ets/generic_variance_1-expected.txt | 34 - ...nerics_class_recursive_type_1-expected.txt | 34 - .../generics_implicit_lambda1-expected.txt | 34 - .../ets/generics_instantiation_1-expected.txt | 34 - .../ets/generics_instantiation_2-expected.txt | 34 - .../ets/generics_instantiation_3-expected.txt | 34 - .../ets/generics_instantiation_4-expected.txt | 34 - .../generics_interface_bounds_1-expected.txt | 34 - .../generics_interface_bounds_2-expected.txt | 34 - ...nerics_primitive_type_param_1-expected.txt | 34 - .../ets/identifierReference14-expected.txt | 34 - .../ets/identifierReference4-expected.txt | 34 - .../ets/implicit-conversion-expected.txt | 34 - .../package_module_1-expected.txt | 34 - .../package_module_2-expected.txt | 34 - .../separate_module_1-expected.txt | 34 - .../package_module_1-expected.txt | 34 - .../package_module_2-expected.txt | 34 - .../separate_module_1-expected.txt | 34 - .../asyncfun_lambda_lib-expected.txt | 34 - .../asyncfunc_lambda_main-expected.txt | 34 - .../ets/import_tests/enum_export-expected.txt | 34 - .../ets/import_tests/enum_import-expected.txt | 34 - ...rt_class_with_getters_setters-expected.txt | 34 - .../generic_typealias_func_type-expected.txt | 34 - ...neric_typealias_func_type_lib-expected.txt | 34 - ...rt_class_with_getters_setters-expected.txt | 34 - ...imported_function_return_type-expected.txt | 34 - ...rted_function_return_type_lib-expected.txt | 34 - .../re-export_with_alias/export-expected.txt | 34 - .../import_aliased_re-export-expected.txt | 34 - .../re-export_with_alias-expected.txt | 34 - .../import_interface-expected.txt | 34 - .../import_selective_exported-expected.txt | 34 - .../selective_export-expected.txt | 34 - .../selective_export_function-expected.txt | 34 - .../selective_export_interface-expected.txt | 34 - .../selective_export_with_alias-expected.txt | 34 - ...selective_import_with_alias_1-expected.txt | 34 - ...selective_import_with_alias_2-expected.txt | 34 - .../compiler/ets/import_type-expected.txt | 34 - .../ets/inferTypeOfArray-expected.txt | 34 - .../instanceof_dyndecl_dynvalue-expected.txt | 260 +- .../instanceof_dyndecl_jsvalue-expected.txt | 510 ++- .../instanceof_dynvalue_dynvalue-expected.txt | 34 - .../instanceof_dynvalue_jsvalue-expected.txt | 34 - ...instanceof_etsobject_dynvalue-expected.txt | 34 - .../instanceof_etsobject_jsvalue-expected.txt | 34 - .../instanceof_jsvalue_dynvalue-expected.txt | 34 - .../instanceof_jsvalue_jsvalue-expected.txt | 34 - .../instanceof_object_dynvalue-expected.txt | 34 - .../instanceof_object_jsvalue-expected.txt | 34 - .../ets/instanceof_object_long-expected.txt | 34 - .../ets/instanceof_x_dyndecl-expected.txt | 260 +- .../ets/instanceof_x_etstype-expected.txt | 260 +- .../ets/instanceof_x_object-expected.txt | 260 +- ...erface_noreturn_type_function-expected.txt | 34 - .../ets/invalidCallInstruction-expected.txt | 34 - .../ets/invalidInheritance3-expected.txt | 34 - .../compiler/ets/lambdaFunction1-expected.txt | 34 - ...ambdaFunctionArrayDeclaration-expected.txt | 34 - .../ets/lambda_capturing-expected.txt | 34 - ...bda_cast_infer_type_narrowing-expected.txt | 34 - .../lambda_cast_infer_type_void-expected.txt | 34 - ...mbda_cast_infer_type_widening-expected.txt | 34 - .../lambda_cast_type_has_pramas-expected.txt | 34 - .../lambda_infer_type-expected.txt | 34 - ...a_infer_type_arrow_expression-expected.txt | 34 - ...type_arrow_expression_literal-expected.txt | 34 - .../lambda_infer_type_has_return-expected.txt | 34 - .../lambda_infer_type_param2-expected.txt | 34 - ...ambda_infer_type_return_array-expected.txt | 34 - ...mbda_infer_type_return_lambda-expected.txt | 34 - ...bda_infer_type_return_lambda1-expected.txt | 34 - ...type_return_lambda_expression-expected.txt | 34 - ...bda_infer_type_return_literal-expected.txt | 34 - ...ambda_infer_type_return_union-expected.txt | 34 - .../lambda_infer_type_scope-expected.txt | 34 - .../ets/lambda_unresolved_ref_1-expected.txt | 34 - .../ets/launch_expression-expected.txt | 34 - .../ets/loopWithinLambda-expected.txt | 34 - .../ets/lowering-interaction-expected.txt | 34 - .../ets/manyLocalsParamRegUsage-expected.txt | 34 - .../ets/memberExprInLambda-expected.txt | 34 - ...erExpressionFromStaticContext-expected.txt | 34 - ...and-interface-in-signatures_5-expected.txt | 34 - .../methodOverrideAsyncMethod-expected.txt | 34 - ...odOverrideCovariantReturnType-expected.txt | 34 - ...hodOverrideDifferentSignature-expected.txt | 34 - ...methodOverrideWithoutModifier-expected.txt | 34 - .../ets/multipleMethodOverride-expected.txt | 34 - .../n_nullableTypeInArgNotRef-expected.txt | 34 - .../n_nullableTypeInReturnNotRef-expected.txt | 34 - .../ets/n_nullableTypeNotRef-expected.txt | 34 - .../compiler/ets/native_toplevel-expected.txt | 34 - .../non-const-lambda-with-scopes-expected.txt | 34 - .../null_coalescing_generic_1-expected.txt | 34 - .../compiler/ets/nullableTuple-expected.txt | 34 - ...ullable_type_in_arithmeticdiv-expected.txt | 34 - ...llable_type_in_arithmeticplus-expected.txt | 34 - .../ets/objectLiteralInterface-expected.txt | 34 - .../ets/objectLiteralReadonlyKey-expected.txt | 34 - .../ets/overload_with_generics-expected.txt | 34 - .../test/compiler/ets/override-expected.txt | 34 - .../test/compiler/ets/override10-expected.txt | 34 - .../test/compiler/ets/override12-expected.txt | 34 - .../test/compiler/ets/override13-expected.txt | 34 - .../test/compiler/ets/override16-expected.txt | 34 - .../test/compiler/ets/override17-expected.txt | 34 - .../test/compiler/ets/override19-expected.txt | 34 - .../test/compiler/ets/override2-expected.txt | 34 - .../test/compiler/ets/override4-expected.txt | 34 - .../test/compiler/ets/override5-expected.txt | 34 - .../test/compiler/ets/override6-expected.txt | 34 - .../test/compiler/ets/override8-expected.txt | 34 - .../test/compiler/ets/override9-expected.txt | 34 - .../ets/parenthesizedType-expected.txt | 34 - .../compiler/ets/requiredType_1-expected.txt | 34 - .../compiler/ets/requiredType_11-expected.txt | 34 - .../compiler/ets/requiredType_4-expected.txt | 34 - .../compiler/ets/requiredType_5-expected.txt | 34 - .../compiler/ets/requiredType_9-expected.txt | 34 - .../ets/rethrowingCheck1-expected.txt | 34 - .../ets/rethrowingCheck4-expected.txt | 34 - .../rethrowingConstructorCheck3-expected.txt | 34 - .../ets/rethrowingFunctionCheck3-expected.txt | 34 - .../ets/rethrowingMethodCheck3-expected.txt | 34 - .../ets/returnTypeGenericArray-expected.txt | 34 - .../ets/switchStatementBoxing-expected.txt | 34 - ...tchStatementCorrectConversion-expected.txt | 34 - .../this_type_valid_return_type-expected.txt | 34 - .../ets/throwInCatchClause3-expected.txt | 34 - .../ets/throwInFinallyBlock1-expected.txt | 34 - .../throwInRethrowingFunction2-expected.txt | 34 - .../ets/throwInThrowingFunction-expected.txt | 34 - .../ets/throwInTryStatement-expected.txt | 34 - .../throwingFunctionAsParameter1-expected.txt | 34 - .../ets/throwingFunctionCheck2-expected.txt | 34 - .../ets/throwingFunctionCheck3-expected.txt | 34 - .../ets/throwingFunctionCheck6-expected.txt | 34 - .../ets/throwingFunctionType1-expected.txt | 34 - ...tryCatchErrorMissingParamType-expected.txt | 34 - .../ets/tryCatchMissingParamType-expected.txt | 34 - .../ets/tryDefaultCatches-expected.txt | 34 - .../compiler/ets/tuple_types_1-expected.txt | 34 - .../compiler/ets/tuple_types_12-expected.txt | 34 - .../compiler/ets/tuple_types_13-expected.txt | 34 - .../compiler/ets/tuple_types_14-expected.txt | 34 - .../compiler/ets/tuple_types_15-expected.txt | 34 - .../compiler/ets/tuple_types_16-expected.txt | 34 - .../compiler/ets/tuple_types_17-expected.txt | 34 - .../compiler/ets/tuple_types_18-expected.txt | 34 - .../compiler/ets/tuple_types_19-expected.txt | 34 - .../compiler/ets/tuple_types_7-expected.txt | 34 - .../test/compiler/ets/typeAlias-expected.txt | 34 - ...arReferenceFromStaticContext2-expected.txt | 34 - .../compiler/ets/union_types_1-expected.txt | 34 - .../compiler/ets/union_types_3-expected.txt | 34 - .../compiler/ets/union_types_5-expected.txt | 34 - .../ets/union_types_merging-expected.txt | 34 - .../parser/ets/AccessBinaryTrees-expected.txt | 34 - .../parser/ets/AccessFannkuch-expected.txt | 34 - .../test/parser/ets/AccessNBody-expected.txt | 34 - .../test/parser/ets/AccessNSieve-expected.txt | 34 - .../ets/Bitops3BitBitsInByte-expected.txt | 34 - .../parser/ets/BitopsBitsInByte-expected.txt | 34 - .../parser/ets/BitopsBitwiseAnd-expected.txt | 34 - .../parser/ets/BitopsNSieveBits-expected.txt | 34 - .../parser/ets/Boolean_bitwise-expected.txt | 34 - .../ets/ControlFlowRecursive-expected.txt | 34 - .../parser/ets/Dollar_dollar_1-expected.txt | 34 - .../parser/ets/Dollar_dollar_2-expected.txt | 34 - .../parser/ets/Dollar_dollar_3-expected.txt | 34 - .../parser/ets/Dollar_dollar_4-expected.txt | 34 - .../parser/ets/FunctionInSwitch-expected.txt | 34 - .../test/parser/ets/FunctionType-expected.txt | 34 - .../FunctionalTypeAsTypeArgument-expected.txt | 34 - .../ets/InferTypeParamFromParam1-expected.txt | 34 - .../ets/InferTypeParamFromParam3-expected.txt | 34 - .../test/parser/ets/MathCordic-expected.txt | 34 - .../parser/ets/MathPartialSums-expected.txt | 34 - .../parser/ets/MathSpectralNorm-expected.txt | 34 - .../test/parser/ets/Morph3d-expected.txt | 34 - ...ametersWithGenericReturnTypes-expected.txt | 34 - .../StaticFieldAndMethodSameName-expected.txt | 34 - ...dAndMethodSameNameInheritance-expected.txt | 34 - .../test/parser/ets/StringBase64-expected.txt | 34 - .../parser/ets/access_modifier_2-expected.txt | 34 - .../parser/ets/access_modifier_3-expected.txt | 34 - .../ets/ambient_call_signature-expected.txt | 34 - ...bient_declaration_final_class-expected.txt | 34 - .../parser/ets/ambient_indexer_1-expected.txt | 34 - .../parser/ets/ambient_indexer_6-expected.txt | 34 - .../ets/ambient_object_iterable-expected.txt | 34 - ets2panda/test/parser/ets/array-expected.txt | 34 - .../ets/arrayHoldingNullValue-expected.txt | 34 - .../ets/arrayLiteralReassign-expected.txt | 34 - .../array_creation_expression-expected.txt | 34 - ...sion_implicit_cast_assignment-expected.txt | 34 - ...pression_implicit_cast_return-expected.txt | 34 - .../test/parser/ets/array_new-expected.txt | 34 - .../ets/array_type_from_literal-expected.txt | 34 - ...s_expression_unary_expression-expected.txt | 34 - ets2panda/test/parser/ets/assert-expected.txt | 34 - ets2panda/test/parser/ets/assign-expected.txt | 34 - .../test/parser/ets/assign-func-expected.txt | 34 - ...ableFromMethodToNullableParam-expected.txt | 34 - .../assignNullableToNonNullable-expected.txt | 34 - ...ignNullableToNonNullableArray-expected.txt | 34 - ...ullableToNonNullableTypeAlias-expected.txt | 34 - .../test/parser/ets/assignments-expected.txt | 34 - .../ets/async_func_return_type-expected.txt | 34 - .../parser/ets/async_function-expected.txt | 34 - .../parser/ets/async_overload-expected.txt | 34 - .../parser/ets/async_with_lambda-expected.txt | 34 - .../ets/await_complex_promise-expected.txt | 34 - .../parser/ets/await_keyword-expected.txt | 34 - .../test/parser/ets/binary_op-expected.txt | 34 - .../parser/ets/binary_operations-expected.txt | 34 - ets2panda/test/parser/ets/blocks-expected.txt | 34 - .../parser/ets/blocks_scopes-expected.txt | 34 - .../test/parser/ets/boolean-expected.txt | 34 - .../test/parser/ets/boolean_cond-expected.txt | 34 - .../parser/ets/boolean_default-expected.txt | 34 - ets2panda/test/parser/ets/break-expected.txt | 34 - ...callFunctionWithNullableParam-expected.txt | 34 - ...erfaceMethodWithNullableParam-expected.txt | 34 - .../callMethodWithNullableParam-expected.txt | 34 - .../calling_superclass_methods-expected.txt | 34 - .../parser/ets/cast_const_union-expected.txt | 34 - .../parser/ets/cast_expressions-expected.txt | 34 - .../parser/ets/cast_expressions3-expected.txt | 34 - .../parser/ets/cast_expressions4-expected.txt | 34 - .../parser/ets/cast_expressions5-expected.txt | 34 - .../test/parser/ets/class_init-expected.txt | 34 - .../parser/ets/class_instance-expected.txt | 34 - .../ets/class_instance_creation-expected.txt | 34 - .../class_instance_import_alias-expected.txt | 34 - .../class_instance_initializer-expected.txt | 34 - ...terface_enum_only_top_level_4-expected.txt | 34 - .../ets/class_static_initializer-expected.txt | 34 - .../test/parser/ets/classes-expected.txt | 34 - .../parser/ets/comment_block-expected.txt | 34 - .../test/parser/ets/comment_line-expected.txt | 34 - .../conditionalExpressionType-expected.txt | 34 - ets2panda/test/parser/ets/const-expected.txt | 34 - .../constructorThrowsRethrows-expected.txt | 34 - .../ets/constructor_super_call1-expected.txt | 34 - .../ets/constructor_super_call3-expected.txt | 34 - .../parser/ets/constructor_test-expected.txt | 34 - ...uctor_with_optional_parameter-expected.txt | 34 - .../constructor_with_return_2-expected.txt | 34 - .../test/parser/ets/continue-expected.txt | 34 - .../test/parser/ets/conversions-expected.txt | 34 - .../test/parser/ets/decl_infer-expected.txt | 34 - ...eclare_ambient_const_variable-expected.txt | 34 - .../parser/ets/declare_class-expected.txt | 34 - .../test/parser/ets/declare_enum-expected.txt | 34 - .../test/parser/ets/declare_func-expected.txt | 34 - .../parser/ets/declare_iface-expected.txt | 34 - .../ets/default_parameter10-expected.txt | 34 - .../ets/default_parameter5-expected.txt | 34 - .../ets/default_parameter7-expected.txt | 34 - .../ets/default_parameter8-expected.txt | 34 - .../ets/default_parameter9-expected.txt | 34 - ..._implicitly_typed_return_void-expected.txt | 34 - .../dynamic_decl_import-expected.txt | 2770 ++++++++++++++++- .../dynamic_iface_decl_bad-expected.txt | 510 ++- .../dynamic_optional_decl-expected.txt | 34 - .../modules/instanceof-expected.txt | 34 - .../modules/module-expected.txt | 34 - .../test/parser/ets/empty_class-expected.txt | 34 - .../parser/ets/empty_statement-expected.txt | 34 - .../test/parser/ets/exports-expected.txt | 34 - ...rnal_cyclic_constructor_check-expected.txt | 34 - .../test/parser/ets/field_decl-expected.txt | 34 - .../parser/ets/final_empty_class-expected.txt | 34 - .../ets/float_pont_format_1-expected.txt | 34 - .../ets/float_pont_format_2-expected.txt | 34 - .../ets/float_pont_format_3-expected.txt | 34 - .../ets/float_pont_format_4-expected.txt | 34 - .../ets/float_pont_format_5-expected.txt | 34 - .../ets/float_pont_format_6-expected.txt | 34 - .../ets/float_pont_format_7-expected.txt | 34 - .../ets/float_pont_format_8-expected.txt | 34 - .../parser/ets/float_separator_1-expected.txt | 34 - .../folder_import_index/index-expected.txt | 34 - ets2panda/test/parser/ets/for_of-expected.txt | 34 - .../parser/ets/for_with_break-expected.txt | 34 - .../parser/ets/forofUnboxing-expected.txt | 34 - .../funcParamWithOptionalParam-expected.txt | 34 - .../test/parser/ets/function-expected.txt | 34 - .../ets/functionThrowsRethrows-expected.txt | 34 - .../ets/functionTypeThrows-expected.txt | 34 - ...unction_implicit_return_type5-expected.txt | 34 - ...unction_implicit_return_type6-expected.txt | 34 - ...unction_implicit_return_type8-expected.txt | 34 - ...unction_implicit_return_type9-expected.txt | 34 - .../ets/genericDefaultParam_1-expected.txt | 34 - .../ets/genericDefaultParam_3-expected.txt | 34 - .../parser/ets/generic_function-expected.txt | 34 - .../parser/ets/generic_resolve-expected.txt | 34 - .../test/parser/ets/generics_2-expected.txt | 34 - .../test/parser/ets/generics_3-expected.txt | 34 - .../test/parser/ets/generics_4-expected.txt | 34 - .../test/parser/ets/generics_5-expected.txt | 34 - .../test/parser/ets/generics_6-expected.txt | 34 - .../test/parser/ets/generics_7-expected.txt | 34 - .../ets/generics_recursive-expected.txt | 34 - ...erics_type_param_constraint_1-expected.txt | 34 - ...rics_type_param_constraint_10-expected.txt | 34 - ...rics_type_param_constraint_11-expected.txt | 34 - ...rics_type_param_constraint_12-expected.txt | 34 - ...erics_type_param_constraint_2-expected.txt | 34 - ...erics_type_param_constraint_3-expected.txt | 34 - ...erics_type_param_constraint_4-expected.txt | 34 - ...erics_type_param_constraint_5-expected.txt | 34 - ...erics_type_param_constraint_6-expected.txt | 34 - ...erics_type_param_constraint_7-expected.txt | 34 - ...erics_type_param_constraint_9-expected.txt | 34 - .../parser/ets/getterOverride-expected.txt | 34 - ...etter_setter_access_modifiers-expected.txt | 34 - .../globalVarInLambdaInStatic-expected.txt | 34 - .../ets/global_const_vars3-expected.txt | 34 - .../test/parser/ets/identifier-expected.txt | 34 - ets2panda/test/parser/ets/if-expected.txt | 34 - ets2panda/test/parser/ets/ifs-expected.txt | 34 - .../test/parser/ets/import_conts-expected.txt | 34 - .../parser/ets/import_folder-expected.txt | 34 - .../check_exported_2-expected.txt | 34 - .../check_exported_3-expected.txt | 34 - .../check_exported_default_class-expected.txt | 34 - .../import_tests/default_import-expected.txt | 34 - .../import_tests/diamond/test1-expected.txt | 34 - .../import_tests/diamond/test2-expected.txt | 34 - .../import_tests/diamond/test3-expected.txt | 34 - .../import_tests/diamond/test4-expected.txt | 34 - .../duplicated/classdef-expected.txt | 34 - .../duplicated/extdef-expected.txt | 34 - .../duplicated/extusedef-expected.txt | 34 - .../export_type_alias-expected.txt | 34 - .../separate_module-expected.txt | 34 - .../import_alias/export-expected.txt | 34 - .../import_alias/import_alias_1-expected.txt | 34 - ...ort_alias_and_without_alias_1-expected.txt | 34 - ...ort_alias_and_without_alias_2-expected.txt | 34 - ...ort_alias_and_without_alias_3-expected.txt | 34 - .../ets/import_tests/import_all-expected.txt | 34 - .../import_tests/import_all_3-expected.txt | 34 - .../import_all_alias_1-expected.txt | 34 - .../import_all_type_alias-expected.txt | 34 - .../import_diff_paths-expected.txt | 34 - .../import_extension-expected.txt | 34 - .../import_extension_1-expected.txt | 34 - .../import_extension_2-expected.txt | 34 - .../import_function_overload-expected.txt | 34 - .../import_interface_test-expected.txt | 34 - .../import_interface_test_1-expected.txt | 34 - .../import_interface_test_2-expected.txt | 34 - .../import_max_as_alias-expected.txt | 34 - .../import_tests/import_name_1-expected.txt | 34 - .../import_name_alias_1-expected.txt | 34 - .../imported_module_1-expected.txt | 34 - .../imported_module_2-expected.txt | 34 - .../import_relative_path-expected.txt | 34 - .../import_several_1-expected.txt | 34 - .../import_several_2-expected.txt | 34 - .../import_several_3-expected.txt | 34 - .../import_several_4-expected.txt | 34 - .../import_several_5-expected.txt | 34 - .../import_several_6-expected.txt | 34 - .../import_several_7-expected.txt | 34 - .../import_tests/import_ts_file-expected.txt | 34 - .../ets/import_tests/internals-expected.txt | 34 - .../modules/class_default_module-expected.txt | 34 - .../modules/default_export-expected.txt | 34 - .../missing_default_export-expected.txt | 34 - .../module1/src/export_file-expected.txt | 34 - .../module1/src/re_export_file-expected.txt | 34 - .../module2/src/import_file-expected.txt | 34 - .../module2/src/re_export_file_2-expected.txt | 34 - .../modules/test_lib1-expected.txt | 34 - .../modules/test_lib2-expected.txt | 34 - .../import1/import1-expected.txt | 34 - .../import2/import2-expected.txt | 34 - .../import_package_with_alias-expected.txt | 34 - .../package/package_module-expected.txt | 34 - .../packages/package_module_1-expected.txt | 34 - .../packages/package_module_2-expected.txt | 34 - .../package_module_1-expected.txt | 34 - .../package_module_1-expected.txt | 34 - .../subpackage/package_module_1-expected.txt | 34 - .../subpackage_module_1-expected.txt | 34 - .../subpackage_module_2-expected.txt | 34 - .../relative_import/Line-expected.txt | 34 - .../relative_import/Point-expected.txt | 34 - .../relative_import/alias1-expected.txt | 34 - .../relative_import/alias2-expected.txt | 34 - .../ets/import_tests/repeat-expected.txt | 34 - .../folder1/file1-expected.txt | 34 - .../folder2/file2-expected.txt | 34 - .../folder3/file3-expected.txt | 34 - .../ets/import_tests/type/type-expected.txt | 34 - .../parser/ets/index_expressions-expected.txt | 34 - ...overriding_method_return_type-expected.txt | 34 - .../ets/inferingEntryPointReturn-expected.txt | 34 - .../test/parser/ets/inheritance-expected.txt | 34 - .../test/parser/ets/inheritance2-expected.txt | 34 - .../test/parser/ets/instanceof-expected.txt | 34 - .../interfaceMethodWithOptional-expected.txt | 34 - ...ce_abstract_noreturn_function-expected.txt | 34 - ...interface_method_default_body-expected.txt | 34 - .../test/parser/ets/interfaces-expected.txt | 34 - .../parser/ets/internalParsing-expected.txt | 34 - .../ets/internalProtectedParsing-expected.txt | 34 - .../ets/labeledDoWhileStatement-expected.txt | 34 - .../ets/labeledForStatement-expected.txt | 34 - .../ets/labeledSwitchStatement-expected.txt | 34 - .../ets/labeledWhileStatement-expected.txt | 34 - ets2panda/test/parser/ets/lambda-expected.txt | 34 - .../parser/ets/lambda-lambda-expected.txt | 34 - .../lambda-type-inference-alias-expected.txt | 34 - ...da-type-inference-arg-no-type-expected.txt | 34 - .../ets/lambda-type-inference-expected.txt | 34 - ...da-type-inference-no-ret-type-expected.txt | 34 - ...a-type-inference-overloaded-2-expected.txt | 34 - ...a-type-inference-overloaded-3-expected.txt | 34 - ...bda-type-inference-overloaded-expected.txt | 34 - .../ets/lambdaAsFunctionParam-expected.txt | 34 - ...pressionWithoutBlockStatement-expected.txt | 34 - ...ockStatementCallAVoidFunction-expected.txt | 34 - ...sionWithoutBlockStatementVoid-expected.txt | 34 - ...atementWithFunctionParameters-expected.txt | 34 - .../ets/lambdaThrowsRethrows-expected.txt | 34 - .../ets/lambda_import_alias_1-2-expected.txt | 34 - .../ets/lambda_import_alias_1-3-expected.txt | 34 - .../ets/lambda_import_alias_1-expected.txt | 34 - .../ets/lambda_optional_param_1-expected.txt | 34 - ets2panda/test/parser/ets/launch-expected.txt | 34 - ...aunch_function_returning_void-expected.txt | 34 - .../test/parser/ets/launch_ret-expected.txt | 34 - .../test/parser/ets/launch_super-expected.txt | 34 - .../ets/launch_this_callee-expected.txt | 34 - .../launch_with_call_expression-expected.txt | 34 - .../test/parser/ets/literals-expected.txt | 34 - .../test/parser/ets/local-class-expected.txt | 34 - .../parser/ets/local-interface-expected.txt | 34 - .../ets/localClassIsPermitted-expected.txt | 34 - .../parser/ets/localTypeAlias-expected.txt | 34 - .../ets/main_entry_point_1-expected.txt | 34 - .../ets/main_entry_point_6-expected.txt | 34 - .../ets/main_entry_point_7-expected.txt | 34 - .../ets/main_entry_point_8-expected.txt | 34 - .../ets/main_entry_point_9-expected.txt | 34 - .../ets/methodThrowsRethrows-expected.txt | 34 - .../test/parser/ets/method_empty-expected.txt | 34 - .../ets/method_modifier_check_14-expected.txt | 34 - .../ets/method_modifier_check_8-expected.txt | 34 - .../ets/method_override_throw_1-expected.txt | 34 - ...ive_function_with_return_type-expected.txt | 34 - .../parser/ets/new_expressions-expected.txt | 34 - .../test/parser/ets/new_object_3-expected.txt | 34 - ets2panda/test/parser/ets/null-expected.txt | 34 - .../test/parser/ets/null_valid-expected.txt | 34 - .../ets/nullableGenericSignature-expected.txt | 34 - .../ets/nullable_union_array-expected.txt | 34 - ets2panda/test/parser/ets/object-expected.txt | 34 - .../ets/optional_field_class-expected.txt | 34 - .../ets/optional_field_interface-expected.txt | 34 - ...optional_field_interfaceUnion-expected.txt | 34 - .../ets/optional_field_variable-expected.txt | 34 - .../ets/optional_union_paramter-expected.txt | 34 - .../test/parser/ets/override-expected.txt | 34 - .../ets/overrideStaticFunc-expected.txt | 34 - .../parentheses_expression_value-expected.txt | 34 - .../parser/ets/predefined_types-expected.txt | 34 - .../parser/ets/promiseCasting-expected.txt | 34 - .../ets/proxyVoidGeneration-expected.txt | 34 - .../test/parser/ets/proxy_method-expected.txt | 34 - .../ets/re_export/diamond/A-expected.txt | 34 - .../ets/re_export/diamond/B-expected.txt | 34 - .../ets/re_export/diamond/B2-expected.txt | 34 - .../ets/re_export/diamond/C-expected.txt | 34 - .../ets/re_export/diamond/C2-expected.txt | 34 - .../ets/re_export/diamond/D-expected.txt | 34 - .../ets/re_export/diamond/D2-expected.txt | 34 - .../parser/ets/re_export/export-expected.txt | 34 - .../ets/re_export/export_2-expected.txt | 34 - .../ets/re_export/export_3-expected.txt | 34 - .../ets/re_export/folder/export-expected.txt | 34 - .../folder/folder2/export-expected.txt | 34 - .../re_export/folder/re_export_6-expected.txt | 34 - .../re_export/folder/re_export_7-expected.txt | 34 - .../re_export/folderIndex/index-expected.txt | 34 - .../re_export/folderIndex/test-expected.txt | 34 - .../re_export/folderIndex2/index-expected.txt | 34 - .../re_export/folderIndex2/key-expected.txt | 34 - .../re_export/folderIndex2/type-expected.txt | 34 - .../parser/ets/re_export/import-expected.txt | 34 - .../ets/re_export/import_10-expected.txt | 34 - .../ets/re_export/import_11-expected.txt | 34 - .../ets/re_export/import_12-expected.txt | 34 - .../ets/re_export/import_13-expected.txt | 34 - .../ets/re_export/import_14-expected.txt | 34 - .../ets/re_export/import_15-expected.txt | 34 - .../ets/re_export/import_2-expected.txt | 34 - .../ets/re_export/import_3-expected.txt | 34 - .../ets/re_export/import_6-expected.txt | 34 - .../ets/re_export/import_7-expected.txt | 34 - .../ets/re_export/import_8-expected.txt | 34 - .../ets/re_export/import_9-expected.txt | 34 - .../ets/re_export/import_index-expected.txt | 34 - .../ets/re_export/import_index_2-expected.txt | 34 - .../ets/re_export/import_index_3-expected.txt | 34 - .../ets/re_export/re_export-expected.txt | 34 - .../ets/re_export/re_export_10-expected.txt | 34 - .../ets/re_export/re_export_11-expected.txt | 34 - .../ets/re_export/re_export_12-expected.txt | 34 - .../ets/re_export/re_export_2-expected.txt | 34 - .../ets/re_export/re_export_3-expected.txt | 34 - .../ets/re_export/re_export_4-expected.txt | 34 - .../ets/re_export/re_export_5-expected.txt | 34 - .../ets/re_export/re_export_7-expected.txt | 34 - .../ets/re_export/re_export_8-expected.txt | 34 - .../ets/re_export/re_export_9-expected.txt | 34 - ...egression-target-type-context-expected.txt | 34 - .../parser/ets/rest_parameter_01-expected.txt | 34 - .../parser/ets/rest_parameter_02-expected.txt | 34 - .../parser/ets/rethrow-func-1-expected.txt | 34 - ets2panda/test/parser/ets/return-expected.txt | 34 - .../returnNullableFromFunction-expected.txt | 34 - .../ets/returnNullableFromMethod-expected.txt | 34 - .../test/parser/ets/scoped_decl-expected.txt | 34 - .../selective_export/import_1-expected.txt | 34 - .../selective_export/import_2-expected.txt | 34 - .../selective_export/import_3-expected.txt | 34 - .../selective_export/import_4-expected.txt | 34 - .../selective_export_1-expected.txt | 34 - .../selective_export_2-expected.txt | 34 - .../selective_export_3-expected.txt | 34 - .../selective_export_4-expected.txt | 34 - .../test/parser/ets/simple_types-expected.txt | 34 - .../static_function_override_1-expected.txt | 34 - .../static_function_override_2-expected.txt | 34 - .../static_function_override_3-expected.txt | 34 - ets2panda/test/parser/ets/string-expected.txt | 34 - .../parser/ets/string_template_1-expected.txt | 34 - .../parser/ets/string_template_2-expected.txt | 34 - .../parser/ets/string_template_3-expected.txt | 34 - .../parser/ets/string_template_4-expected.txt | 34 - ets2panda/test/parser/ets/switch-expected.txt | 34 - .../test/parser/ets/switch2-expected.txt | 34 - .../parser/ets/switch_alive_1-expected.txt | 34 - .../parser/ets/switch_alive_4-expected.txt | 34 - .../ets/switch_char_compare_num-expected.txt | 34 - .../ets/switch_enum_string_case-expected.txt | 34 - .../ets/switch_num_compare_char-expected.txt | 34 - .../ets/switch_readonly_member-expected.txt | 34 - ..._readonly_member_compare_char-expected.txt | 34 - ...eadonly_member_compare_char_2-expected.txt | 34 - .../test/parser/ets/ternary-expected.txt | 34 - .../ets/test-type-alias-call1-expected.txt | 34 - .../ets/test-type-alias-call2-expected.txt | 34 - .../ets/test-type-alias-call3-expected.txt | 34 - .../ets/test-type-alias-call4-expected.txt | 34 - .../ets/test-type-alias-call5-expected.txt | 34 - .../ets/test-type-alias-call6-expected.txt | 34 - .../ets/test-type-alias-call7-expected.txt | 34 - .../ets/test-type-alias-call8-expected.txt | 34 - .../parser/ets/test_interface-expected.txt | 34 - .../test/parser/ets/test_jsvalue-expected.txt | 34 - .../ets/test_jsvalue_get_double-expected.txt | 34 - .../test_jsvalue_get_property_1-expected.txt | 34 - .../test_jsvalue_get_property_2-expected.txt | 34 - .../ets/test_jsvalue_set_double-expected.txt | 34 - .../parser/ets/test_type_alias5-expected.txt | 34 - .../parser/ets/test_type_alias6-expected.txt | 34 - .../parser/ets/test_type_alias7-expected.txt | 34 - .../parser/ets/test_type_alias8-expected.txt | 34 - .../parser/ets/test_type_alias9-expected.txt | 34 - .../test/parser/ets/this_callee-expected.txt | 34 - .../parser/ets/this_cmp_object-expected.txt | 34 - .../parser/ets/this_equality-expected.txt | 34 - .../parser/ets/this_expression-expected.txt | 34 - ...ype_class_method_return_valid-expected.txt | 34 - .../throwsRethrowsAsVariables-expected.txt | 34 - ..._lambda_define_lambda_in_body-expected.txt | 34 - ...mbda_in_body_capture_variable-expected.txt | 34 - .../trailing_lambda_overload-expected.txt | 34 - .../trailing_lambda_overload_1-expected.txt | 34 - ...mbda_transform_trailing_block-expected.txt | 34 - .../trailing_lambda_type_alias-expected.txt | 34 - .../trailing_lambda_with_throw-expected.txt | 34 - .../ets/tryFinallyBlockOnly-expected.txt | 34 - .../parser/ets/tupleAsTypeParam1-expected.txt | 34 - .../parser/ets/tupleAsTypeParam2-expected.txt | 34 - .../ets/tupleIndexWithNumbers-expected.txt | 34 - .../test/parser/ets/tuple_type_1-expected.txt | 34 - .../test/parser/ets/type_alias_1-expected.txt | 34 - .../test/parser/ets/type_alias_2-expected.txt | 34 - .../test/parser/ets/type_cast-expected.txt | 34 - .../parser/ets/type_variance1-expected.txt | 34 - .../test/parser/ets/unary_op-expected.txt | 34 - .../parser/ets/unary_operations-expected.txt | 34 - ...finedNullObjectTypeAnnotation-expected.txt | 34 - .../ets/undefinedNullTypeAlias-expected.txt | 34 - ...nion_lowering_common_property-expected.txt | 34 - .../parser/ets/user_defined_1-expected.txt | 34 - .../parser/ets/user_defined_2-expected.txt | 34 - .../parser/ets/user_defined_22-expected.txt | 34 - .../parser/ets/user_defined_3-expected.txt | 34 - .../parser/ets/user_defined_4-expected.txt | 34 - .../parser/ets/user_defined_6-expected.txt | 34 - .../test/parser/ets/var_declare-expected.txt | 34 - .../variable_throw_function_1-expected.txt | 34 - ets2panda/test/parser/ets/void-expected.txt | 34 - .../parser/ets/voidAsTypeArg-expected.txt | 34 - .../test/unit/annotations/CMakeLists.txt | 3 + .../unit/annotations/annotations_module.cpp | 82 + .../unit/lowerings/top_level_statements.cpp | 98 +- .../e2p_test_plugin_after_bind-expected.txt | 20 - ets2panda/test/utils/asm_test.cpp | 34 + ets2panda/test/utils/asm_test.h | 3 + 699 files changed, 4868 insertions(+), 23393 deletions(-) create mode 100644 ets2panda/test/unit/annotations/annotations_module.cpp diff --git a/ets2panda/compiler/core/ETSemitter.cpp b/ets2panda/compiler/core/ETSemitter.cpp index d189de8096..64ae2b8a6a 100644 --- a/ets2panda/compiler/core/ETSemitter.cpp +++ b/ets2panda/compiler/core/ETSemitter.cpp @@ -598,6 +598,11 @@ void ETSEmitter::GenClassRecord(const ir::ClassDefinition *classDef, bool extern } std::vector annotations = GenAnnotations(classDef); + + if (classDef->IsNamespaceTransformed() || classDef->IsGlobalInitialized()) { + annotations.push_back(GenAnnotationModule(classDef)); + } + if (!annotations.empty()) { classRecord.metadata->AddAnnotations(annotations); } @@ -903,6 +908,24 @@ std::vector ETSEmitter::GenCustomAnnotations( return annotations; } +pandasm::AnnotationData ETSEmitter::GenAnnotationModule(const ir::ClassDefinition *classDef) +{ + std::vector exportedClasses {}; + + for (auto cls : classDef->ExportedClasses()) { + exportedClasses.emplace_back(pandasm::ScalarValue::Create( + pandasm::Type::FromName(cls->Definition()->InternalName().Utf8(), true))); + } + + GenAnnotationRecord(Signatures::ETS_ANNOTATION_MODULE); + pandasm::AnnotationData moduleAnno(Signatures::ETS_ANNOTATION_MODULE); + pandasm::AnnotationElement value( + Signatures::ANNOTATION_KEY_EXPORTED, + std::make_unique(pandasm::Value::Type::RECORD, std::move(exportedClasses))); + moduleAnno.AddElement(std::move(value)); + return moduleAnno; +} + pandasm::AnnotationData ETSEmitter::GenAnnotationSignature(const ir::ClassDefinition *classDef) { std::vector parts {}; diff --git a/ets2panda/compiler/core/ETSemitter.h b/ets2panda/compiler/core/ETSemitter.h index 441cc5bf76..937d81276a 100644 --- a/ets2panda/compiler/core/ETSemitter.h +++ b/ets2panda/compiler/core/ETSemitter.h @@ -111,6 +111,7 @@ private: void GenInterfaceMethodDefinition(const ir::MethodDefinition *methodDef, bool external); void GenClassInheritedFields(const checker::ETSObjectType *baseType, pandasm::Record &classRecord); pandasm::AnnotationData GenAnnotationSignature(const ir::ClassDefinition *classDef); + pandasm::AnnotationData GenAnnotationModule(const ir::ClassDefinition *classDef); pandasm::AnnotationData GenAnnotationEnclosingClass(std::string_view className); pandasm::AnnotationData GenAnnotationEnclosingMethod(const ir::MethodDefinition *methodDef); pandasm::AnnotationData GenAnnotationInnerClass(const ir::ClassDefinition *classDef, const ir::AstNode *parent); diff --git a/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.cpp b/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.cpp index 1b8e60ecaf..4e7c4e9e71 100644 --- a/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.cpp +++ b/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.cpp @@ -49,14 +49,33 @@ void GlobalClassHandler::AddStaticBlockToClass(ir::AstNode *node) } } -ir::AnnotationUsage *GlobalClassHandler::CreateModuleAnnotation(const lexer::SourceRange &range) +std::string AddToNamespaceChain(std::string chain, std::string name) { - auto *identModule = NodeAllocator::Alloc(allocator_, Signatures::MODULE_ANNOTATION, allocator_); - identModule->SetRange(range); - auto *annotationModule = NodeAllocator::Alloc(allocator_, identModule, allocator_); - annotationModule->AddModifier(ir::ModifierFlags::ANNOTATION_USAGE); - annotationModule->SetRange(range); - return annotationModule; + if (chain.empty()) { + return name; + } + if (name.empty()) { + return chain; + } + return chain + "." + name; +} + +void GlobalClassHandler::CollectNamespaceExportedClasses(ir::ClassDefinition *classDef) +{ + CollectExportedClasses(classDef, classDef->Body()); +} + +template +void GlobalClassHandler::CollectExportedClasses(ir::ClassDefinition *classDef, const ArenaVector &statements) +{ + for (const auto *statement : statements) { + if (!statement->IsExported()) { + continue; + } + if (statement->IsClassDeclaration()) { + classDef->AddToExportedClasses(statement->AsClassDeclaration()); + } + } } ir::ClassDeclaration *GlobalClassHandler::CreateTransformedClass(ir::ETSModule *ns) @@ -79,8 +98,6 @@ ir::ClassDeclaration *GlobalClassHandler::CreateTransformedClass(ir::ETSModule * annotations.push_back(clone); } - annotations.push_back(CreateModuleAnnotation(ns->Range())); - classDef->SetAnnotations(std::move(annotations)); return classDecl; } @@ -185,6 +202,7 @@ ir::ClassDeclaration *GlobalClassHandler::TransformNamespace(ir::ETSModule *ns, for (auto *cls : globalClasses) { globalClass->Body().emplace_back(cls); cls->SetParent(globalClass); + CollectNamespaceExportedClasses(cls->Definition()); } // Add rest statement, such as type declaration @@ -202,6 +220,7 @@ void GlobalClassHandler::CollectProgramGlobalClasses(parser::Program *program, A for (auto cls : classDecls) { program->Ast()->Statements().push_back(cls); cls->SetParent(program->Ast()); + CollectNamespaceExportedClasses(cls->Definition()); } } @@ -244,6 +263,8 @@ void GlobalClassHandler::SetupGlobalClass(const ArenaVector & CollectProgramGlobalClasses(globalProgram, namespaces); + CollectExportedClasses(globalClass, globalProgram->Ast()->Statements()); + // NOTE(vpukhov): stdlib checks are to be removed - do not extend the existing logic if (globalProgram->Kind() != parser::ScriptKind::STDLIB) { AddStaticBlockToClass(globalClass); @@ -483,10 +504,6 @@ ir::ClassDeclaration *GlobalClassHandler::CreateGlobalClass(const parser::Progra auto *classDecl = NodeAllocator::Alloc(allocator_, classDef, allocator_); classDecl->SetRange(rangeToStartOfFile); - auto *annotationModule = CreateModuleAnnotation(classDef->Range()); - annotationModule->SetParent(classDef); - classDef->Annotations().push_back(annotationModule); - return classDecl; } diff --git a/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.h b/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.h index ad42782eee..f4b14745c5 100644 --- a/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.h +++ b/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.h @@ -52,7 +52,9 @@ private: void CollectProgramGlobalClasses(parser::Program *program, ArenaVector namespaces); ir::ClassDeclaration *TransformNamespace(ir::ETSModule *ns, parser::Program *program); ir::ClassDeclaration *CreateTransformedClass(ir::ETSModule *ns); - ir::AnnotationUsage *CreateModuleAnnotation(const lexer::SourceRange &range); + template + void CollectExportedClasses(ir::ClassDefinition *classDef, const ArenaVector &statements); + void CollectNamespaceExportedClasses(ir::ClassDefinition *classDef); void SetupGlobalMethods(parser::Program *program, ArenaVector &&initStatements, ArenaVector &&initializerBlock, ir::ClassDefinition *globalClass, bool isDeclare); diff --git a/ets2panda/compiler/scripts/signatures.yaml b/ets2panda/compiler/scripts/signatures.yaml index 9a661e96c9..f80a307d37 100644 --- a/ets2panda/compiler/scripts/signatures.yaml +++ b/ets2panda/compiler/scripts/signatures.yaml @@ -66,9 +66,9 @@ defines: - name: ets.debug.export ref: DEBUG_EXPORT_ATTRIBUTE comment: ETS annotation type - - name: Module - ref: MODULE_ANNOTATION - comment: ETS annotation + - name: exported + ref: ANNOTATION_KEY_EXPORTED + comment: ETS annotation key - name: value ref: ANNOTATION_KEY_VALUE comment: ETS annotation key @@ -99,6 +99,9 @@ defines: - name: ets/annotation/Signature ref: ETS_ANNOTATION_SIGNATURE comment: Ets record + - name: ets/annotation/Module + ref: ETS_ANNOTATION_MODULE + comment: Ets record - name: ets/coroutine/Async ref: ETS_COROUTINE_ASYNC - name: ets/annotation/DynamicCall diff --git a/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp b/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp index 2f9c32175e..adc109a91a 100644 --- a/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp +++ b/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp @@ -901,9 +901,6 @@ void TSDeclGen::GenAnnotations(const T *node) GenSeparated( node->Annotations(), [this](ir::AnnotationUsage *anno) { - if (anno->GetBaseName()->Name() == compiler::Signatures::MODULE_ANNOTATION) { - return; - } OutDts("@", anno->GetBaseName()->Name()); GenAnnotationProperties(anno); OutEndlDts(); diff --git a/ets2panda/ir/base/classDefinition.h b/ets2panda/ir/base/classDefinition.h index 43f501035a..e17c5452c9 100644 --- a/ets2panda/ir/base/classDefinition.h +++ b/ets2panda/ir/base/classDefinition.h @@ -23,6 +23,7 @@ #include "ir/expressions/identifier.h" #include "ir/srcDump.h" #include "ir/statements/annotationUsage.h" +#include "ir/statements/classDeclaration.h" #include "util/language.h" namespace ark::es2panda::ir { @@ -94,7 +95,8 @@ public: capturedVars_(body_.get_allocator()), localVariableIsNeeded_(body_.get_allocator()), localIndex_(classCounter_++), - localPrefix_("$" + std::to_string(localIndex_)) + localPrefix_("$" + std::to_string(localIndex_)), + exportedClasses_(body_.get_allocator()) { } // CC-OFFNXT(G.FUN.01-CPP) solid logic @@ -109,7 +111,8 @@ public: capturedVars_(allocator->Adapter()), localVariableIsNeeded_(allocator->Adapter()), localIndex_(classCounter_++), - localPrefix_("$" + std::to_string(localIndex_)) + localPrefix_("$" + std::to_string(localIndex_)), + exportedClasses_(body_.get_allocator()) { } @@ -124,7 +127,8 @@ public: capturedVars_(allocator->Adapter()), localVariableIsNeeded_(allocator->Adapter()), localIndex_(classCounter_++), - localPrefix_("$" + std::to_string(localIndex_)) + localPrefix_("$" + std::to_string(localIndex_)), + exportedClasses_(body_.get_allocator()) { } @@ -469,6 +473,17 @@ public: modifiers_ &= ~(ClassDefinitionModifiers::CLASSDEFINITION_CHECKED); } + void AddToExportedClasses(const ir::ClassDeclaration *cls) + { + ES2PANDA_ASSERT(cls->IsExported()); + exportedClasses_.push_back(cls); + } + + [[nodiscard]] const ArenaVector &ExportedClasses() const noexcept + { + return exportedClasses_; + } + private: void CompileStaticFieldInitializers(compiler::PandaGen *pg, compiler::VReg classReg, const std::vector &staticComputedFieldKeys) const; @@ -495,6 +510,7 @@ private: static int classCounter_; const int localIndex_ {}; const std::string localPrefix_ {}; + ArenaVector exportedClasses_; }; } // namespace ark::es2panda::ir diff --git a/ets2panda/test/compiler/ets/116100-expected.txt b/ets2panda/test/compiler/ets/116100-expected.txt index 4d068cdd92..db59083ea5 100644 --- a/ets2panda/test/compiler/ets/116100-expected.txt +++ b/ets2panda/test/compiler/ets/116100-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "116100.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "116100.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "116100.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "116100.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/ConditionalExpressionCallVoidNeg-expected.txt b/ets2panda/test/compiler/ets/ConditionalExpressionCallVoidNeg-expected.txt index 500cbfbf6f..895378e780 100644 --- a/ets2panda/test/compiler/ets/ConditionalExpressionCallVoidNeg-expected.txt +++ b/ets2panda/test/compiler/ets/ConditionalExpressionCallVoidNeg-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "ConditionalExpressionCallVoidNeg.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "ConditionalExpressionCallVoidNeg.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "ConditionalExpressionCallVoidNeg.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "ConditionalExpressionCallVoidNeg.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/FunctionType2-expected.txt b/ets2panda/test/compiler/ets/FunctionType2-expected.txt index 84cdfaed84..5ce5b074f5 100644 --- a/ets2panda/test/compiler/ets/FunctionType2-expected.txt +++ b/ets2panda/test/compiler/ets/FunctionType2-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "FunctionType2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "FunctionType2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "FunctionType2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "FunctionType2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/FunctionType4-expected.txt b/ets2panda/test/compiler/ets/FunctionType4-expected.txt index 9aa2c3f75a..025b501c15 100644 --- a/ets2panda/test/compiler/ets/FunctionType4-expected.txt +++ b/ets2panda/test/compiler/ets/FunctionType4-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "FunctionType4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "FunctionType4.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "FunctionType4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "FunctionType4.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/abstractMethodDeclaredInParentClass-expected.txt b/ets2panda/test/compiler/ets/abstractMethodDeclaredInParentClass-expected.txt index 4662a0623a..6864a7a181 100644 --- a/ets2panda/test/compiler/ets/abstractMethodDeclaredInParentClass-expected.txt +++ b/ets2panda/test/compiler/ets/abstractMethodDeclaredInParentClass-expected.txt @@ -3025,40 +3025,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "abstractMethodDeclaredInParentClass.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "abstractMethodDeclaredInParentClass.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "abstractMethodDeclaredInParentClass.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "abstractMethodDeclaredInParentClass.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/abstractNewClassInstanceExpression-expected.txt b/ets2panda/test/compiler/ets/abstractNewClassInstanceExpression-expected.txt index d68af12577..7d401ea3ae 100644 --- a/ets2panda/test/compiler/ets/abstractNewClassInstanceExpression-expected.txt +++ b/ets2panda/test/compiler/ets/abstractNewClassInstanceExpression-expected.txt @@ -864,40 +864,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "abstractNewClassInstanceExpression.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "abstractNewClassInstanceExpression.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "abstractNewClassInstanceExpression.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "abstractNewClassInstanceExpression.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/ambient_declaration-expected.txt b/ets2panda/test/compiler/ets/ambient_declaration-expected.txt index a94eab8986..359dc043ad 100644 --- a/ets2panda/test/compiler/ets/ambient_declaration-expected.txt +++ b/ets2panda/test/compiler/ets/ambient_declaration-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "ambient_declaration.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "ambient_declaration.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "ambient_declaration.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "ambient_declaration.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/array_indexing_without_chaining_non_nullish-expected.txt b/ets2panda/test/compiler/ets/array_indexing_without_chaining_non_nullish-expected.txt index f6f5dfc552..e2238d5f36 100644 --- a/ets2panda/test/compiler/ets/array_indexing_without_chaining_non_nullish-expected.txt +++ b/ets2panda/test/compiler/ets/array_indexing_without_chaining_non_nullish-expected.txt @@ -178,40 +178,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "array_indexing_without_chaining_non_nullish.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "array_indexing_without_chaining_non_nullish.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "array_indexing_without_chaining_non_nullish.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "array_indexing_without_chaining_non_nullish.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/array_with_null_type-expected.txt b/ets2panda/test/compiler/ets/array_with_null_type-expected.txt index 5dbd906c13..46004b400e 100644 --- a/ets2panda/test/compiler/ets/array_with_null_type-expected.txt +++ b/ets2panda/test/compiler/ets/array_with_null_type-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "array_with_null_type.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "array_with_null_type.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "array_with_null_type.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "array_with_null_type.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/array_with_undefined_type-expected.txt b/ets2panda/test/compiler/ets/array_with_undefined_type-expected.txt index 8ab13bc98e..94882b3319 100644 --- a/ets2panda/test/compiler/ets/array_with_undefined_type-expected.txt +++ b/ets2panda/test/compiler/ets/array_with_undefined_type-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "array_with_undefined_type.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "array_with_undefined_type.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "array_with_undefined_type.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "array_with_undefined_type.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/arrowFunctionCapture-expected.txt b/ets2panda/test/compiler/ets/arrowFunctionCapture-expected.txt index f9bb146e43..772965af6f 100644 --- a/ets2panda/test/compiler/ets/arrowFunctionCapture-expected.txt +++ b/ets2panda/test/compiler/ets/arrowFunctionCapture-expected.txt @@ -924,40 +924,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "arrowFunctionCapture.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "arrowFunctionCapture.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "arrowFunctionCapture.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "arrowFunctionCapture.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/boxingConversion10-expected.txt b/ets2panda/test/compiler/ets/boxingConversion10-expected.txt index 84dc78f5eb..3dcfcb5693 100644 --- a/ets2panda/test/compiler/ets/boxingConversion10-expected.txt +++ b/ets2panda/test/compiler/ets/boxingConversion10-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "boxingConversion10.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "boxingConversion10.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "boxingConversion10.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "boxingConversion10.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/boxingConversion2-expected.txt b/ets2panda/test/compiler/ets/boxingConversion2-expected.txt index 95bbcdeda1..fd853951c7 100644 --- a/ets2panda/test/compiler/ets/boxingConversion2-expected.txt +++ b/ets2panda/test/compiler/ets/boxingConversion2-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "boxingConversion2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "boxingConversion2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "boxingConversion2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "boxingConversion2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/boxingConversion3-expected.txt b/ets2panda/test/compiler/ets/boxingConversion3-expected.txt index d8c478ed81..a8f8673a75 100644 --- a/ets2panda/test/compiler/ets/boxingConversion3-expected.txt +++ b/ets2panda/test/compiler/ets/boxingConversion3-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "boxingConversion3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "boxingConversion3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "boxingConversion3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "boxingConversion3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/boxingConversion5-expected.txt b/ets2panda/test/compiler/ets/boxingConversion5-expected.txt index ca8086bf91..52a1957148 100644 --- a/ets2panda/test/compiler/ets/boxingConversion5-expected.txt +++ b/ets2panda/test/compiler/ets/boxingConversion5-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "boxingConversion5.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "boxingConversion5.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "boxingConversion5.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "boxingConversion5.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/boxingConversion6-expected.txt b/ets2panda/test/compiler/ets/boxingConversion6-expected.txt index c2d838afb1..88a8b24639 100644 --- a/ets2panda/test/compiler/ets/boxingConversion6-expected.txt +++ b/ets2panda/test/compiler/ets/boxingConversion6-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "boxingConversion6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "boxingConversion6.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "boxingConversion6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "boxingConversion6.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/boxingConversion7-expected.txt b/ets2panda/test/compiler/ets/boxingConversion7-expected.txt index 4582ff7724..4ab4be70e0 100644 --- a/ets2panda/test/compiler/ets/boxingConversion7-expected.txt +++ b/ets2panda/test/compiler/ets/boxingConversion7-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "boxingConversion7.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "boxingConversion7.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "boxingConversion7.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "boxingConversion7.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/boxingConversion8-expected.txt b/ets2panda/test/compiler/ets/boxingConversion8-expected.txt index 6e12621e8a..081b1f8149 100644 --- a/ets2panda/test/compiler/ets/boxingConversion8-expected.txt +++ b/ets2panda/test/compiler/ets/boxingConversion8-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "boxingConversion8.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "boxingConversion8.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "boxingConversion8.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "boxingConversion8.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/boxingConversion9-expected.txt b/ets2panda/test/compiler/ets/boxingConversion9-expected.txt index e8c97235dc..ac43037040 100644 --- a/ets2panda/test/compiler/ets/boxingConversion9-expected.txt +++ b/ets2panda/test/compiler/ets/boxingConversion9-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "boxingConversion9.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "boxingConversion9.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "boxingConversion9.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "boxingConversion9.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/boxingUnboxingExpressions-expected.txt b/ets2panda/test/compiler/ets/boxingUnboxingExpressions-expected.txt index 5b7218b482..253a7e61b9 100644 --- a/ets2panda/test/compiler/ets/boxingUnboxingExpressions-expected.txt +++ b/ets2panda/test/compiler/ets/boxingUnboxingExpressions-expected.txt @@ -8361,40 +8361,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "boxingUnboxingExpressions.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "boxingUnboxingExpressions.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "boxingUnboxingExpressions.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "boxingUnboxingExpressions.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/catch-soft-keyword-expected.txt b/ets2panda/test/compiler/ets/catch-soft-keyword-expected.txt index 4d0a4dd016..88f8081fd9 100644 --- a/ets2panda/test/compiler/ets/catch-soft-keyword-expected.txt +++ b/ets2panda/test/compiler/ets/catch-soft-keyword-expected.txt @@ -454,40 +454,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "catch-soft-keyword.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "catch-soft-keyword.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "catch-soft-keyword.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "catch-soft-keyword.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/catchParamScope-expected.txt b/ets2panda/test/compiler/ets/catchParamScope-expected.txt index c7fe753c57..d0766f9f47 100644 --- a/ets2panda/test/compiler/ets/catchParamScope-expected.txt +++ b/ets2panda/test/compiler/ets/catchParamScope-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "catchParamScope.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "catchParamScope.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "catchParamScope.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "catchParamScope.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/class_def_varargs_1-expected.txt b/ets2panda/test/compiler/ets/class_def_varargs_1-expected.txt index 7ba996f89d..cf3d577a21 100644 --- a/ets2panda/test/compiler/ets/class_def_varargs_1-expected.txt +++ b/ets2panda/test/compiler/ets/class_def_varargs_1-expected.txt @@ -894,40 +894,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "class_def_varargs_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "class_def_varargs_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "class_def_varargs_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "class_def_varargs_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/class_def_varargs_2-expected.txt b/ets2panda/test/compiler/ets/class_def_varargs_2-expected.txt index 51a9e78c64..cdd96354db 100644 --- a/ets2panda/test/compiler/ets/class_def_varargs_2-expected.txt +++ b/ets2panda/test/compiler/ets/class_def_varargs_2-expected.txt @@ -290,40 +290,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "class_def_varargs_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "class_def_varargs_2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "class_def_varargs_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "class_def_varargs_2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/conversion-w-ASExpr-expected.txt b/ets2panda/test/compiler/ets/conversion-w-ASExpr-expected.txt index 31ce9f0447..e77bd71287 100644 --- a/ets2panda/test/compiler/ets/conversion-w-ASExpr-expected.txt +++ b/ets2panda/test/compiler/ets/conversion-w-ASExpr-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "conversion-w-ASExpr.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "conversion-w-ASExpr.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "conversion-w-ASExpr.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "conversion-w-ASExpr.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/conversion_w_functions-expected.txt b/ets2panda/test/compiler/ets/conversion_w_functions-expected.txt index 17d8bd8d98..af3444cb50 100644 --- a/ets2panda/test/compiler/ets/conversion_w_functions-expected.txt +++ b/ets2panda/test/compiler/ets/conversion_w_functions-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "conversion_w_functions.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "conversion_w_functions.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "conversion_w_functions.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "conversion_w_functions.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/delete-non-keyword-expected.txt b/ets2panda/test/compiler/ets/delete-non-keyword-expected.txt index b20ce9188b..61c9e38752 100644 --- a/ets2panda/test/compiler/ets/delete-non-keyword-expected.txt +++ b/ets2panda/test/compiler/ets/delete-non-keyword-expected.txt @@ -366,40 +366,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "delete-non-keyword.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "delete-non-keyword.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "delete-non-keyword.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "delete-non-keyword.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/dynamic-equality-expected.txt b/ets2panda/test/compiler/ets/dynamic-equality-expected.txt index eae396b7e6..6823886ef2 100644 --- a/ets2panda/test/compiler/ets/dynamic-equality-expected.txt +++ b/ets2panda/test/compiler/ets/dynamic-equality-expected.txt @@ -105,40 +105,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "dynamic-equality.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "dynamic-equality.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "dynamic-equality.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "dynamic-equality.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/dynamicJsImport-expected.txt b/ets2panda/test/compiler/ets/dynamicJsImport-expected.txt index cbc3cf965f..2ec39eb97f 100644 --- a/ets2panda/test/compiler/ets/dynamicJsImport-expected.txt +++ b/ets2panda/test/compiler/ets/dynamicJsImport-expected.txt @@ -187,40 +187,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "dynamicJsImport.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "dynamicJsImport.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "dynamicJsImport.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "dynamicJsImport.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/dynamicLambda-expected.txt b/ets2panda/test/compiler/ets/dynamicLambda-expected.txt index 60f92592f2..2a1ee711e3 100644 --- a/ets2panda/test/compiler/ets/dynamicLambda-expected.txt +++ b/ets2panda/test/compiler/ets/dynamicLambda-expected.txt @@ -105,40 +105,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "dynamicLambda.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "dynamicLambda.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "dynamicLambda.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "dynamicLambda.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/dynamicLambdaJSValue-expected.txt b/ets2panda/test/compiler/ets/dynamicLambdaJSValue-expected.txt index 438ffaf446..886a67ea3e 100644 --- a/ets2panda/test/compiler/ets/dynamicLambdaJSValue-expected.txt +++ b/ets2panda/test/compiler/ets/dynamicLambdaJSValue-expected.txt @@ -105,40 +105,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "dynamicLambdaJSValue.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "dynamicLambdaJSValue.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "dynamicLambdaJSValue.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "dynamicLambdaJSValue.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/dynamicLambdaJSValueCast-expected.txt b/ets2panda/test/compiler/ets/dynamicLambdaJSValueCast-expected.txt index 8decab2d58..bb11d9f297 100644 --- a/ets2panda/test/compiler/ets/dynamicLambdaJSValueCast-expected.txt +++ b/ets2panda/test/compiler/ets/dynamicLambdaJSValueCast-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "dynamicLambdaJSValueCast.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "dynamicLambdaJSValueCast.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "dynamicLambdaJSValueCast.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "dynamicLambdaJSValueCast.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/dynamicObjectLiteral-expected.txt b/ets2panda/test/compiler/ets/dynamicObjectLiteral-expected.txt index 26d6681b1b..1c085de7a1 100644 --- a/ets2panda/test/compiler/ets/dynamicObjectLiteral-expected.txt +++ b/ets2panda/test/compiler/ets/dynamicObjectLiteral-expected.txt @@ -105,40 +105,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "dynamicObjectLiteral.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "dynamicObjectLiteral.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "dynamicObjectLiteral.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "dynamicObjectLiteral.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/dynamic_call-expected.txt b/ets2panda/test/compiler/ets/dynamic_call-expected.txt index 831001cfbc..9dac896c72 100644 --- a/ets2panda/test/compiler/ets/dynamic_call-expected.txt +++ b/ets2panda/test/compiler/ets/dynamic_call-expected.txt @@ -105,40 +105,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "dynamic_call.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "dynamic_call.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "dynamic_call.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "dynamic_call.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/dynamic_instanceof_error-expected.txt b/ets2panda/test/compiler/ets/dynamic_instanceof_error-expected.txt index 553382706e..26cf8aaf57 100644 --- a/ets2panda/test/compiler/ets/dynamic_instanceof_error-expected.txt +++ b/ets2panda/test/compiler/ets/dynamic_instanceof_error-expected.txt @@ -105,40 +105,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "dynamic_instanceof_error.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "dynamic_instanceof_error.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "dynamic_instanceof_error.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "dynamic_instanceof_error.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/ensureNotNullArgNotNullable-expected.txt b/ets2panda/test/compiler/ets/ensureNotNullArgNotNullable-expected.txt index 8ed32227d7..e8bdf6bfde 100644 --- a/ets2panda/test/compiler/ets/ensureNotNullArgNotNullable-expected.txt +++ b/ets2panda/test/compiler/ets/ensureNotNullArgNotNullable-expected.txt @@ -134,40 +134,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "ensureNotNullArgNotNullable.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "ensureNotNullArgNotNullable.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "ensureNotNullArgNotNullable.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "ensureNotNullArgNotNullable.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/ensureNotNullLocalNotNullable-expected.txt b/ets2panda/test/compiler/ets/ensureNotNullLocalNotNullable-expected.txt index 050987b1b1..6baa69fe84 100644 --- a/ets2panda/test/compiler/ets/ensureNotNullLocalNotNullable-expected.txt +++ b/ets2panda/test/compiler/ets/ensureNotNullLocalNotNullable-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "ensureNotNullLocalNotNullable.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "ensureNotNullLocalNotNullable.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "ensureNotNullLocalNotNullable.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "ensureNotNullLocalNotNullable.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/ensureNotNullReturnNotNullable-expected.txt b/ets2panda/test/compiler/ets/ensureNotNullReturnNotNullable-expected.txt index 83978008cf..28be07a026 100644 --- a/ets2panda/test/compiler/ets/ensureNotNullReturnNotNullable-expected.txt +++ b/ets2panda/test/compiler/ets/ensureNotNullReturnNotNullable-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "ensureNotNullReturnNotNullable.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "ensureNotNullReturnNotNullable.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "ensureNotNullReturnNotNullable.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "ensureNotNullReturnNotNullable.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/enum_as_class_member_getValue_call-expected.txt b/ets2panda/test/compiler/ets/enum_as_class_member_getValue_call-expected.txt index 27cf62006c..be5a25a7d2 100644 --- a/ets2panda/test/compiler/ets/enum_as_class_member_getValue_call-expected.txt +++ b/ets2panda/test/compiler/ets/enum_as_class_member_getValue_call-expected.txt @@ -10842,40 +10842,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "enum_as_class_member_getValue_call.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "enum_as_class_member_getValue_call.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "enum_as_class_member_getValue_call.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "enum_as_class_member_getValue_call.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/export_type-expected.txt b/ets2panda/test/compiler/ets/export_type-expected.txt index dd4b65847e..cd258876a3 100644 --- a/ets2panda/test/compiler/ets/export_type-expected.txt +++ b/ets2panda/test/compiler/ets/export_type-expected.txt @@ -537,40 +537,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "export_type.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "export_type.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "export_type.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "export_type.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/extended_conditional_expression_not-expected.txt b/ets2panda/test/compiler/ets/extended_conditional_expression_not-expected.txt index b933c78d0c..ff6a2de361 100644 --- a/ets2panda/test/compiler/ets/extended_conditional_expression_not-expected.txt +++ b/ets2panda/test/compiler/ets/extended_conditional_expression_not-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "extended_conditional_expression_not.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "extended_conditional_expression_not.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "extended_conditional_expression_not.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "extended_conditional_expression_not.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/extended_conditional_expression_not_return_type-expected.txt b/ets2panda/test/compiler/ets/extended_conditional_expression_not_return_type-expected.txt index a4ffdaad6c..aa0afff24d 100644 --- a/ets2panda/test/compiler/ets/extended_conditional_expression_not_return_type-expected.txt +++ b/ets2panda/test/compiler/ets/extended_conditional_expression_not_return_type-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "extended_conditional_expression_not_return_type.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "extended_conditional_expression_not_return_type.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "extended_conditional_expression_not_return_type.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "extended_conditional_expression_not_return_type.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/forUpdate-expected.txt b/ets2panda/test/compiler/ets/forUpdate-expected.txt index 453ddd4f19..e5bcb79a17 100644 --- a/ets2panda/test/compiler/ets/forUpdate-expected.txt +++ b/ets2panda/test/compiler/ets/forUpdate-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "forUpdate.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "forUpdate.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "forUpdate.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "forUpdate.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/forUpdateCharType-expected.txt b/ets2panda/test/compiler/ets/forUpdateCharType-expected.txt index bc8512b026..6d585cce52 100644 --- a/ets2panda/test/compiler/ets/forUpdateCharType-expected.txt +++ b/ets2panda/test/compiler/ets/forUpdateCharType-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "forUpdateCharType.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "forUpdateCharType.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "forUpdateCharType.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "forUpdateCharType.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/from-soft-keyword-0-expected.txt b/ets2panda/test/compiler/ets/from-soft-keyword-0-expected.txt index 6a9edc303f..04b2dfe4ae 100644 --- a/ets2panda/test/compiler/ets/from-soft-keyword-0-expected.txt +++ b/ets2panda/test/compiler/ets/from-soft-keyword-0-expected.txt @@ -574,40 +574,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "from-soft-keyword-0.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "from-soft-keyword-0.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "from-soft-keyword-0.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "from-soft-keyword-0.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/from-soft-keyword-1-expected.txt b/ets2panda/test/compiler/ets/from-soft-keyword-1-expected.txt index 08494f9e6b..a72b40f301 100644 --- a/ets2panda/test/compiler/ets/from-soft-keyword-1-expected.txt +++ b/ets2panda/test/compiler/ets/from-soft-keyword-1-expected.txt @@ -88,40 +88,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "from-soft-keyword-1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "from-soft-keyword-1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "from-soft-keyword-1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "from-soft-keyword-1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/from-soft-keyword-2-expected.txt b/ets2panda/test/compiler/ets/from-soft-keyword-2-expected.txt index 7faf56eba1..3e6e2e5a19 100644 --- a/ets2panda/test/compiler/ets/from-soft-keyword-2-expected.txt +++ b/ets2panda/test/compiler/ets/from-soft-keyword-2-expected.txt @@ -291,40 +291,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "from-soft-keyword-2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "from-soft-keyword-2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "from-soft-keyword-2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "from-soft-keyword-2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/func-ref-private-expected.txt b/ets2panda/test/compiler/ets/func-ref-private-expected.txt index 84ee581d08..42e551d9da 100644 --- a/ets2panda/test/compiler/ets/func-ref-private-expected.txt +++ b/ets2panda/test/compiler/ets/func-ref-private-expected.txt @@ -538,40 +538,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "func-ref-private.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "func-ref-private.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "func-ref-private.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "func-ref-private.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/functionPointerArray-expected.txt b/ets2panda/test/compiler/ets/functionPointerArray-expected.txt index 32d0456f4f..4f4f6c5526 100644 --- a/ets2panda/test/compiler/ets/functionPointerArray-expected.txt +++ b/ets2panda/test/compiler/ets/functionPointerArray-expected.txt @@ -86,40 +86,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "functionPointerArray.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "functionPointerArray.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "functionPointerArray.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "functionPointerArray.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/functionTypeToObject-expected.txt b/ets2panda/test/compiler/ets/functionTypeToObject-expected.txt index 4cc2d41a08..bb46138b3a 100644 --- a/ets2panda/test/compiler/ets/functionTypeToObject-expected.txt +++ b/ets2panda/test/compiler/ets/functionTypeToObject-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "functionTypeToObject.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "functionTypeToObject.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "functionTypeToObject.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "functionTypeToObject.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/function_subtyping_1-expected.txt b/ets2panda/test/compiler/ets/function_subtyping_1-expected.txt index 6fa68d08ed..6773ef4311 100644 --- a/ets2panda/test/compiler/ets/function_subtyping_1-expected.txt +++ b/ets2panda/test/compiler/ets/function_subtyping_1-expected.txt @@ -379,40 +379,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "function_subtyping_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "function_subtyping_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "function_subtyping_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "function_subtyping_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/functions_with_ambiguous_rest_parameter-expected.txt b/ets2panda/test/compiler/ets/functions_with_ambiguous_rest_parameter-expected.txt index eb423dcd90..7687ad1010 100644 --- a/ets2panda/test/compiler/ets/functions_with_ambiguous_rest_parameter-expected.txt +++ b/ets2panda/test/compiler/ets/functions_with_ambiguous_rest_parameter-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "functions_with_ambiguous_rest_parameter.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "functions_with_ambiguous_rest_parameter.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "functions_with_ambiguous_rest_parameter.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "functions_with_ambiguous_rest_parameter.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/generic_arrayaslist-expected.txt b/ets2panda/test/compiler/ets/generic_arrayaslist-expected.txt index c9373edffe..5cc64ba8ad 100644 --- a/ets2panda/test/compiler/ets/generic_arrayaslist-expected.txt +++ b/ets2panda/test/compiler/ets/generic_arrayaslist-expected.txt @@ -24796,40 +24796,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_arrayaslist.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_arrayaslist.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_arrayaslist.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_arrayaslist.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/generic_class_getter_setter-expected.txt b/ets2panda/test/compiler/ets/generic_class_getter_setter-expected.txt index 3a3def4877..fb6cf3a2db 100644 --- a/ets2panda/test/compiler/ets/generic_class_getter_setter-expected.txt +++ b/ets2panda/test/compiler/ets/generic_class_getter_setter-expected.txt @@ -599,40 +599,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_class_getter_setter.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_class_getter_setter.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_class_getter_setter.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_class_getter_setter.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/generic_deadlock-expected.txt b/ets2panda/test/compiler/ets/generic_deadlock-expected.txt index 3d4363a3ed..8892d6af0d 100644 --- a/ets2panda/test/compiler/ets/generic_deadlock-expected.txt +++ b/ets2panda/test/compiler/ets/generic_deadlock-expected.txt @@ -878,40 +878,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_deadlock.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_deadlock.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_deadlock.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_deadlock.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/generic_func_rest_param_spread_infer-expected.txt b/ets2panda/test/compiler/ets/generic_func_rest_param_spread_infer-expected.txt index d6db2d6b93..e927c2a24d 100644 --- a/ets2panda/test/compiler/ets/generic_func_rest_param_spread_infer-expected.txt +++ b/ets2panda/test/compiler/ets/generic_func_rest_param_spread_infer-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_func_rest_param_spread_infer.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_func_rest_param_spread_infer.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_func_rest_param_spread_infer.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_func_rest_param_spread_infer.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/generic_function_call_1-expected.txt b/ets2panda/test/compiler/ets/generic_function_call_1-expected.txt index 18b8344f9c..103caf2507 100644 --- a/ets2panda/test/compiler/ets/generic_function_call_1-expected.txt +++ b/ets2panda/test/compiler/ets/generic_function_call_1-expected.txt @@ -178,40 +178,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_function_call_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_function_call_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_function_call_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_function_call_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/generic_function_call_3-expected.txt b/ets2panda/test/compiler/ets/generic_function_call_3-expected.txt index 74307327e2..38a6336d53 100644 --- a/ets2panda/test/compiler/ets/generic_function_call_3-expected.txt +++ b/ets2panda/test/compiler/ets/generic_function_call_3-expected.txt @@ -379,40 +379,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_function_call_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_function_call_3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_function_call_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_function_call_3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/generic_function_call_4-expected.txt b/ets2panda/test/compiler/ets/generic_function_call_4-expected.txt index 1b7ce0eddb..59b93fd893 100644 --- a/ets2panda/test/compiler/ets/generic_function_call_4-expected.txt +++ b/ets2panda/test/compiler/ets/generic_function_call_4-expected.txt @@ -382,40 +382,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_function_call_4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_function_call_4.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_function_call_4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_function_call_4.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/generic_function_call_5-expected.txt b/ets2panda/test/compiler/ets/generic_function_call_5-expected.txt index 9b2c40df24..419f8fd9d5 100644 --- a/ets2panda/test/compiler/ets/generic_function_call_5-expected.txt +++ b/ets2panda/test/compiler/ets/generic_function_call_5-expected.txt @@ -587,40 +587,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_function_call_5.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_function_call_5.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_function_call_5.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_function_call_5.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/generic_function_call_7-expected.txt b/ets2panda/test/compiler/ets/generic_function_call_7-expected.txt index f172839f1b..f9f6b3bff3 100644 --- a/ets2panda/test/compiler/ets/generic_function_call_7-expected.txt +++ b/ets2panda/test/compiler/ets/generic_function_call_7-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_function_call_7.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_function_call_7.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_function_call_7.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_function_call_7.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/generic_override_1-expected.txt b/ets2panda/test/compiler/ets/generic_override_1-expected.txt index b3df20b763..6b8a9da21b 100644 --- a/ets2panda/test/compiler/ets/generic_override_1-expected.txt +++ b/ets2panda/test/compiler/ets/generic_override_1-expected.txt @@ -2051,40 +2051,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_override_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_override_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_override_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_override_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/generic_override_2-expected.txt b/ets2panda/test/compiler/ets/generic_override_2-expected.txt index bfea00998e..b0fe92e8ab 100644 --- a/ets2panda/test/compiler/ets/generic_override_2-expected.txt +++ b/ets2panda/test/compiler/ets/generic_override_2-expected.txt @@ -2680,40 +2680,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_override_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_override_2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_override_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_override_2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/generic_override_3-expected.txt b/ets2panda/test/compiler/ets/generic_override_3-expected.txt index 6cfc4ea0e7..1eb35954d9 100644 --- a/ets2panda/test/compiler/ets/generic_override_3-expected.txt +++ b/ets2panda/test/compiler/ets/generic_override_3-expected.txt @@ -1960,40 +1960,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_override_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_override_3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_override_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_override_3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/generic_typealias_1-expected.txt b/ets2panda/test/compiler/ets/generic_typealias_1-expected.txt index c7de946078..bb55e4fe01 100644 --- a/ets2panda/test/compiler/ets/generic_typealias_1-expected.txt +++ b/ets2panda/test/compiler/ets/generic_typealias_1-expected.txt @@ -626,40 +626,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_typealias_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_typealias_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_typealias_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_typealias_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/generic_typealias_6-expected.txt b/ets2panda/test/compiler/ets/generic_typealias_6-expected.txt index cc6a6cfb0b..b48772350b 100644 --- a/ets2panda/test/compiler/ets/generic_typealias_6-expected.txt +++ b/ets2panda/test/compiler/ets/generic_typealias_6-expected.txt @@ -530,40 +530,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_typealias_6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_typealias_6.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_typealias_6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_typealias_6.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/generic_typealias_7_neg-expected.txt b/ets2panda/test/compiler/ets/generic_typealias_7_neg-expected.txt index e5345a409f..8f6727aa4f 100644 --- a/ets2panda/test/compiler/ets/generic_typealias_7_neg-expected.txt +++ b/ets2panda/test/compiler/ets/generic_typealias_7_neg-expected.txt @@ -151,40 +151,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_typealias_7_neg.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_typealias_7_neg.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_typealias_7_neg.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_typealias_7_neg.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/generic_typealias_8-expected.txt b/ets2panda/test/compiler/ets/generic_typealias_8-expected.txt index 2adc2e12dc..fc2c7877a2 100644 --- a/ets2panda/test/compiler/ets/generic_typealias_8-expected.txt +++ b/ets2panda/test/compiler/ets/generic_typealias_8-expected.txt @@ -306,40 +306,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_typealias_8.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_typealias_8.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_typealias_8.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_typealias_8.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/generic_typealias_9-expected.txt b/ets2panda/test/compiler/ets/generic_typealias_9-expected.txt index 5c784109bf..ee67f2d5ef 100644 --- a/ets2panda/test/compiler/ets/generic_typealias_9-expected.txt +++ b/ets2panda/test/compiler/ets/generic_typealias_9-expected.txt @@ -215,40 +215,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_typealias_9.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_typealias_9.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_typealias_9.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_typealias_9.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/generic_variance_1-expected.txt b/ets2panda/test/compiler/ets/generic_variance_1-expected.txt index 042329e59a..3fd3bc2906 100644 --- a/ets2panda/test/compiler/ets/generic_variance_1-expected.txt +++ b/ets2panda/test/compiler/ets/generic_variance_1-expected.txt @@ -789,40 +789,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_variance_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_variance_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_variance_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_variance_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/generics_class_recursive_type_1-expected.txt b/ets2panda/test/compiler/ets/generics_class_recursive_type_1-expected.txt index f9625fdaa4..15455cf8ca 100644 --- a/ets2panda/test/compiler/ets/generics_class_recursive_type_1-expected.txt +++ b/ets2panda/test/compiler/ets/generics_class_recursive_type_1-expected.txt @@ -8269,40 +8269,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_class_recursive_type_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_class_recursive_type_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_class_recursive_type_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_class_recursive_type_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/generics_implicit_lambda1-expected.txt b/ets2panda/test/compiler/ets/generics_implicit_lambda1-expected.txt index 26630d5333..8aad3e19bf 100644 --- a/ets2panda/test/compiler/ets/generics_implicit_lambda1-expected.txt +++ b/ets2panda/test/compiler/ets/generics_implicit_lambda1-expected.txt @@ -1232,40 +1232,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_implicit_lambda1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_implicit_lambda1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_implicit_lambda1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_implicit_lambda1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/generics_instantiation_1-expected.txt b/ets2panda/test/compiler/ets/generics_instantiation_1-expected.txt index 1d82b43d1e..311c0e2a9d 100644 --- a/ets2panda/test/compiler/ets/generics_instantiation_1-expected.txt +++ b/ets2panda/test/compiler/ets/generics_instantiation_1-expected.txt @@ -2307,40 +2307,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_instantiation_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_instantiation_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_instantiation_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_instantiation_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/generics_instantiation_2-expected.txt b/ets2panda/test/compiler/ets/generics_instantiation_2-expected.txt index 85e5c1fe1b..43a0768251 100644 --- a/ets2panda/test/compiler/ets/generics_instantiation_2-expected.txt +++ b/ets2panda/test/compiler/ets/generics_instantiation_2-expected.txt @@ -1410,40 +1410,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_instantiation_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_instantiation_2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_instantiation_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_instantiation_2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/generics_instantiation_3-expected.txt b/ets2panda/test/compiler/ets/generics_instantiation_3-expected.txt index f711954b5a..c253cd4a7d 100644 --- a/ets2panda/test/compiler/ets/generics_instantiation_3-expected.txt +++ b/ets2panda/test/compiler/ets/generics_instantiation_3-expected.txt @@ -725,40 +725,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_instantiation_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_instantiation_3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_instantiation_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_instantiation_3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/generics_instantiation_4-expected.txt b/ets2panda/test/compiler/ets/generics_instantiation_4-expected.txt index 3faeaa5a0b..88921ffe6d 100644 --- a/ets2panda/test/compiler/ets/generics_instantiation_4-expected.txt +++ b/ets2panda/test/compiler/ets/generics_instantiation_4-expected.txt @@ -2447,40 +2447,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_instantiation_4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_instantiation_4.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_instantiation_4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_instantiation_4.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/generics_interface_bounds_1-expected.txt b/ets2panda/test/compiler/ets/generics_interface_bounds_1-expected.txt index 2422bd8e30..41648a6b9e 100644 --- a/ets2panda/test/compiler/ets/generics_interface_bounds_1-expected.txt +++ b/ets2panda/test/compiler/ets/generics_interface_bounds_1-expected.txt @@ -1156,40 +1156,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_interface_bounds_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_interface_bounds_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_interface_bounds_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_interface_bounds_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/generics_interface_bounds_2-expected.txt b/ets2panda/test/compiler/ets/generics_interface_bounds_2-expected.txt index beaa2a0730..07b6fb741b 100644 --- a/ets2panda/test/compiler/ets/generics_interface_bounds_2-expected.txt +++ b/ets2panda/test/compiler/ets/generics_interface_bounds_2-expected.txt @@ -328,40 +328,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_interface_bounds_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_interface_bounds_2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_interface_bounds_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_interface_bounds_2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/generics_primitive_type_param_1-expected.txt b/ets2panda/test/compiler/ets/generics_primitive_type_param_1-expected.txt index 3247972ed2..bb1de93228 100644 --- a/ets2panda/test/compiler/ets/generics_primitive_type_param_1-expected.txt +++ b/ets2panda/test/compiler/ets/generics_primitive_type_param_1-expected.txt @@ -385,40 +385,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_primitive_type_param_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_primitive_type_param_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_primitive_type_param_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_primitive_type_param_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/identifierReference14-expected.txt b/ets2panda/test/compiler/ets/identifierReference14-expected.txt index 10f8607c4b..f0b7ebecc1 100644 --- a/ets2panda/test/compiler/ets/identifierReference14-expected.txt +++ b/ets2panda/test/compiler/ets/identifierReference14-expected.txt @@ -904,40 +904,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "identifierReference14.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "identifierReference14.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "identifierReference14.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "identifierReference14.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/identifierReference4-expected.txt b/ets2panda/test/compiler/ets/identifierReference4-expected.txt index f492e8eb78..5ca765a6cc 100644 --- a/ets2panda/test/compiler/ets/identifierReference4-expected.txt +++ b/ets2panda/test/compiler/ets/identifierReference4-expected.txt @@ -668,40 +668,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "identifierReference4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "identifierReference4.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "identifierReference4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "identifierReference4.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/implicit-conversion-expected.txt b/ets2panda/test/compiler/ets/implicit-conversion-expected.txt index c33545e1f5..9c26969875 100644 --- a/ets2panda/test/compiler/ets/implicit-conversion-expected.txt +++ b/ets2panda/test/compiler/ets/implicit-conversion-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "implicit-conversion.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "implicit-conversion.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "implicit-conversion.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "implicit-conversion.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/implicit_package_import/package_test_1/package_module_1-expected.txt b/ets2panda/test/compiler/ets/implicit_package_import/package_test_1/package_module_1-expected.txt index 6286bb82d8..221888de53 100644 --- a/ets2panda/test/compiler/ets/implicit_package_import/package_test_1/package_module_1-expected.txt +++ b/ets2panda/test/compiler/ets/implicit_package_import/package_test_1/package_module_1-expected.txt @@ -395,40 +395,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "package_module_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "package_module_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "package_module_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "package_module_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/implicit_package_import/package_test_1/package_module_2-expected.txt b/ets2panda/test/compiler/ets/implicit_package_import/package_test_1/package_module_2-expected.txt index 31ddd2d9c0..798f662e62 100644 --- a/ets2panda/test/compiler/ets/implicit_package_import/package_test_1/package_module_2-expected.txt +++ b/ets2panda/test/compiler/ets/implicit_package_import/package_test_1/package_module_2-expected.txt @@ -395,40 +395,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "package_module_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "package_module_2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "package_module_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "package_module_2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/implicit_package_import/package_test_1/separate_module_1-expected.txt b/ets2panda/test/compiler/ets/implicit_package_import/package_test_1/separate_module_1-expected.txt index d9adfd2f3a..3468422f01 100644 --- a/ets2panda/test/compiler/ets/implicit_package_import/package_test_1/separate_module_1-expected.txt +++ b/ets2panda/test/compiler/ets/implicit_package_import/package_test_1/separate_module_1-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "separate_module_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "separate_module_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "separate_module_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "separate_module_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/implicit_package_import/package_test_2/subpackage_1/package_module_1-expected.txt b/ets2panda/test/compiler/ets/implicit_package_import/package_test_2/subpackage_1/package_module_1-expected.txt index ef4aac9edc..a816ec7d5c 100644 --- a/ets2panda/test/compiler/ets/implicit_package_import/package_test_2/subpackage_1/package_module_1-expected.txt +++ b/ets2panda/test/compiler/ets/implicit_package_import/package_test_2/subpackage_1/package_module_1-expected.txt @@ -137,40 +137,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "package_module_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "package_module_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "package_module_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "package_module_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/implicit_package_import/package_test_2/subpackage_1/package_module_2-expected.txt b/ets2panda/test/compiler/ets/implicit_package_import/package_test_2/subpackage_1/package_module_2-expected.txt index f9ef1c8d9e..ed47d97cf6 100644 --- a/ets2panda/test/compiler/ets/implicit_package_import/package_test_2/subpackage_1/package_module_2-expected.txt +++ b/ets2panda/test/compiler/ets/implicit_package_import/package_test_2/subpackage_1/package_module_2-expected.txt @@ -137,40 +137,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "package_module_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "package_module_2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "package_module_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "package_module_2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/implicit_package_import/package_test_2/subpackage_2/separate_module_1-expected.txt b/ets2panda/test/compiler/ets/implicit_package_import/package_test_2/subpackage_2/separate_module_1-expected.txt index 867a2e5133..baacd60da4 100644 --- a/ets2panda/test/compiler/ets/implicit_package_import/package_test_2/subpackage_2/separate_module_1-expected.txt +++ b/ets2panda/test/compiler/ets/implicit_package_import/package_test_2/subpackage_2/separate_module_1-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "separate_module_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "separate_module_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "separate_module_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "separate_module_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/import_tests/asyncfun_lambda_lib-expected.txt b/ets2panda/test/compiler/ets/import_tests/asyncfun_lambda_lib-expected.txt index 062817aca7..61cf0f6153 100644 --- a/ets2panda/test/compiler/ets/import_tests/asyncfun_lambda_lib-expected.txt +++ b/ets2panda/test/compiler/ets/import_tests/asyncfun_lambda_lib-expected.txt @@ -1448,40 +1448,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "asyncfun_lambda_lib.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "asyncfun_lambda_lib.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "asyncfun_lambda_lib.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "asyncfun_lambda_lib.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/import_tests/asyncfunc_lambda_main-expected.txt b/ets2panda/test/compiler/ets/import_tests/asyncfunc_lambda_main-expected.txt index 09ce6068fd..0095437e63 100644 --- a/ets2panda/test/compiler/ets/import_tests/asyncfunc_lambda_main-expected.txt +++ b/ets2panda/test/compiler/ets/import_tests/asyncfunc_lambda_main-expected.txt @@ -351,40 +351,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "asyncfunc_lambda_main.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "asyncfunc_lambda_main.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "asyncfunc_lambda_main.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "asyncfunc_lambda_main.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/import_tests/enum_export-expected.txt b/ets2panda/test/compiler/ets/import_tests/enum_export-expected.txt index 26730a1901..b1c10c9087 100644 --- a/ets2panda/test/compiler/ets/import_tests/enum_export-expected.txt +++ b/ets2panda/test/compiler/ets/import_tests/enum_export-expected.txt @@ -12129,40 +12129,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "enum_export.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "enum_export.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "enum_export.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "enum_export.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/import_tests/enum_import-expected.txt b/ets2panda/test/compiler/ets/import_tests/enum_import-expected.txt index 0ce22ce3f5..234229fd33 100644 --- a/ets2panda/test/compiler/ets/import_tests/enum_import-expected.txt +++ b/ets2panda/test/compiler/ets/import_tests/enum_import-expected.txt @@ -203,40 +203,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "enum_import.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "enum_import.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "enum_import.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "enum_import.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/import_tests/export_class_with_getters_setters-expected.txt b/ets2panda/test/compiler/ets/import_tests/export_class_with_getters_setters-expected.txt index 093152b169..0ff68cff92 100644 --- a/ets2panda/test/compiler/ets/import_tests/export_class_with_getters_setters-expected.txt +++ b/ets2panda/test/compiler/ets/import_tests/export_class_with_getters_setters-expected.txt @@ -904,40 +904,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "export_class_with_getters_setters.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "export_class_with_getters_setters.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "export_class_with_getters_setters.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "export_class_with_getters_setters.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/import_tests/generic_typealias_func_type-expected.txt b/ets2panda/test/compiler/ets/import_tests/generic_typealias_func_type-expected.txt index d23e979afe..67e4ebce20 100644 --- a/ets2panda/test/compiler/ets/import_tests/generic_typealias_func_type-expected.txt +++ b/ets2panda/test/compiler/ets/import_tests/generic_typealias_func_type-expected.txt @@ -105,40 +105,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_typealias_func_type.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_typealias_func_type.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_typealias_func_type.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_typealias_func_type.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/import_tests/generic_typealias_func_type_lib-expected.txt b/ets2panda/test/compiler/ets/import_tests/generic_typealias_func_type_lib-expected.txt index c519e69ecd..4c0d8a449b 100644 --- a/ets2panda/test/compiler/ets/import_tests/generic_typealias_func_type_lib-expected.txt +++ b/ets2panda/test/compiler/ets/import_tests/generic_typealias_func_type_lib-expected.txt @@ -279,40 +279,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_typealias_func_type_lib.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_typealias_func_type_lib.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_typealias_func_type_lib.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_typealias_func_type_lib.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/import_tests/import_class_with_getters_setters-expected.txt b/ets2panda/test/compiler/ets/import_tests/import_class_with_getters_setters-expected.txt index e65d65947b..20e7f03505 100644 --- a/ets2panda/test/compiler/ets/import_tests/import_class_with_getters_setters-expected.txt +++ b/ets2panda/test/compiler/ets/import_tests/import_class_with_getters_setters-expected.txt @@ -154,40 +154,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_class_with_getters_setters.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_class_with_getters_setters.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_class_with_getters_setters.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_class_with_getters_setters.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/import_tests/infer_imported_function_return_type-expected.txt b/ets2panda/test/compiler/ets/import_tests/infer_imported_function_return_type-expected.txt index 3fc8b64454..b13fb9afe6 100644 --- a/ets2panda/test/compiler/ets/import_tests/infer_imported_function_return_type-expected.txt +++ b/ets2panda/test/compiler/ets/import_tests/infer_imported_function_return_type-expected.txt @@ -105,40 +105,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "infer_imported_function_return_type.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "infer_imported_function_return_type.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "infer_imported_function_return_type.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "infer_imported_function_return_type.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/import_tests/infer_imported_function_return_type_lib-expected.txt b/ets2panda/test/compiler/ets/import_tests/infer_imported_function_return_type_lib-expected.txt index 140e3f88be..d04e570c0f 100644 --- a/ets2panda/test/compiler/ets/import_tests/infer_imported_function_return_type_lib-expected.txt +++ b/ets2panda/test/compiler/ets/import_tests/infer_imported_function_return_type_lib-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "infer_imported_function_return_type_lib.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "infer_imported_function_return_type_lib.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "infer_imported_function_return_type_lib.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "infer_imported_function_return_type_lib.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/import_tests/re-export_with_alias/export-expected.txt b/ets2panda/test/compiler/ets/import_tests/re-export_with_alias/export-expected.txt index e850da7c29..937539ce2a 100644 --- a/ets2panda/test/compiler/ets/import_tests/re-export_with_alias/export-expected.txt +++ b/ets2panda/test/compiler/ets/import_tests/re-export_with_alias/export-expected.txt @@ -400,40 +400,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "export.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "export.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "export.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "export.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/import_tests/re-export_with_alias/import_aliased_re-export-expected.txt b/ets2panda/test/compiler/ets/import_tests/re-export_with_alias/import_aliased_re-export-expected.txt index fc4e872819..0748020cdb 100644 --- a/ets2panda/test/compiler/ets/import_tests/re-export_with_alias/import_aliased_re-export-expected.txt +++ b/ets2panda/test/compiler/ets/import_tests/re-export_with_alias/import_aliased_re-export-expected.txt @@ -236,40 +236,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_aliased_re-export.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_aliased_re-export.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_aliased_re-export.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_aliased_re-export.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/import_tests/re-export_with_alias/re-export_with_alias-expected.txt b/ets2panda/test/compiler/ets/import_tests/re-export_with_alias/re-export_with_alias-expected.txt index b0e0804dff..edfd5063db 100644 --- a/ets2panda/test/compiler/ets/import_tests/re-export_with_alias/re-export_with_alias-expected.txt +++ b/ets2panda/test/compiler/ets/import_tests/re-export_with_alias/re-export_with_alias-expected.txt @@ -266,40 +266,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "re-export_with_alias.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "re-export_with_alias.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "re-export_with_alias.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "re-export_with_alias.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/import_tests/selective_export_tests/import_interface-expected.txt b/ets2panda/test/compiler/ets/import_tests/selective_export_tests/import_interface-expected.txt index ba7227003f..99b6763f23 100644 --- a/ets2panda/test/compiler/ets/import_tests/selective_export_tests/import_interface-expected.txt +++ b/ets2panda/test/compiler/ets/import_tests/selective_export_tests/import_interface-expected.txt @@ -590,40 +590,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_interface.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_interface.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_interface.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_interface.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/import_tests/selective_export_tests/import_selective_exported-expected.txt b/ets2panda/test/compiler/ets/import_tests/selective_export_tests/import_selective_exported-expected.txt index 2c970792d9..503604c72b 100644 --- a/ets2panda/test/compiler/ets/import_tests/selective_export_tests/import_selective_exported-expected.txt +++ b/ets2panda/test/compiler/ets/import_tests/selective_export_tests/import_selective_exported-expected.txt @@ -170,40 +170,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_selective_exported.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_selective_exported.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_selective_exported.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_selective_exported.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/import_tests/selective_export_tests/selective_export-expected.txt b/ets2panda/test/compiler/ets/import_tests/selective_export_tests/selective_export-expected.txt index 95c0c5a9d6..8f2595b450 100644 --- a/ets2panda/test/compiler/ets/import_tests/selective_export_tests/selective_export-expected.txt +++ b/ets2panda/test/compiler/ets/import_tests/selective_export_tests/selective_export-expected.txt @@ -811,40 +811,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "selective_export.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "selective_export.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "selective_export.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "selective_export.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/import_tests/selective_export_tests/selective_export_function-expected.txt b/ets2panda/test/compiler/ets/import_tests/selective_export_tests/selective_export_function-expected.txt index 5949153514..191cade283 100644 --- a/ets2panda/test/compiler/ets/import_tests/selective_export_tests/selective_export_function-expected.txt +++ b/ets2panda/test/compiler/ets/import_tests/selective_export_tests/selective_export_function-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "selective_export_function.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "selective_export_function.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "selective_export_function.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "selective_export_function.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/import_tests/selective_export_tests/selective_export_interface-expected.txt b/ets2panda/test/compiler/ets/import_tests/selective_export_tests/selective_export_interface-expected.txt index 0d1753e124..2793feea08 100644 --- a/ets2panda/test/compiler/ets/import_tests/selective_export_tests/selective_export_interface-expected.txt +++ b/ets2panda/test/compiler/ets/import_tests/selective_export_tests/selective_export_interface-expected.txt @@ -121,40 +121,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "selective_export_interface.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "selective_export_interface.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "selective_export_interface.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "selective_export_interface.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/import_tests/selective_export_tests/selective_export_with_alias-expected.txt b/ets2panda/test/compiler/ets/import_tests/selective_export_tests/selective_export_with_alias-expected.txt index 6bf763f3bf..61b96e29de 100644 --- a/ets2panda/test/compiler/ets/import_tests/selective_export_tests/selective_export_with_alias-expected.txt +++ b/ets2panda/test/compiler/ets/import_tests/selective_export_tests/selective_export_with_alias-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "selective_export_with_alias.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "selective_export_with_alias.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "selective_export_with_alias.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "selective_export_with_alias.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/import_tests/selective_export_tests/selective_import_with_alias_1-expected.txt b/ets2panda/test/compiler/ets/import_tests/selective_export_tests/selective_import_with_alias_1-expected.txt index 234ff78b36..5b31ff5f4d 100644 --- a/ets2panda/test/compiler/ets/import_tests/selective_export_tests/selective_import_with_alias_1-expected.txt +++ b/ets2panda/test/compiler/ets/import_tests/selective_export_tests/selective_import_with_alias_1-expected.txt @@ -323,40 +323,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "selective_import_with_alias_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "selective_import_with_alias_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "selective_import_with_alias_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "selective_import_with_alias_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/import_tests/selective_export_tests/selective_import_with_alias_2-expected.txt b/ets2panda/test/compiler/ets/import_tests/selective_export_tests/selective_import_with_alias_2-expected.txt index 2386e88d13..88a32d0156 100644 --- a/ets2panda/test/compiler/ets/import_tests/selective_export_tests/selective_import_with_alias_2-expected.txt +++ b/ets2panda/test/compiler/ets/import_tests/selective_export_tests/selective_import_with_alias_2-expected.txt @@ -323,40 +323,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "selective_import_with_alias_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "selective_import_with_alias_2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "selective_import_with_alias_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "selective_import_with_alias_2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/import_type-expected.txt b/ets2panda/test/compiler/ets/import_type-expected.txt index c304037aa6..4624e649f5 100644 --- a/ets2panda/test/compiler/ets/import_type-expected.txt +++ b/ets2panda/test/compiler/ets/import_type-expected.txt @@ -421,40 +421,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_type.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_type.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_type.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_type.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/inferTypeOfArray-expected.txt b/ets2panda/test/compiler/ets/inferTypeOfArray-expected.txt index 52ce42f965..760183394c 100644 --- a/ets2panda/test/compiler/ets/inferTypeOfArray-expected.txt +++ b/ets2panda/test/compiler/ets/inferTypeOfArray-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "inferTypeOfArray.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "inferTypeOfArray.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "inferTypeOfArray.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "inferTypeOfArray.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/instanceof_dyndecl_dynvalue-expected.txt b/ets2panda/test/compiler/ets/instanceof_dyndecl_dynvalue-expected.txt index 6397f04d33..295ef18e62 100644 --- a/ets2panda/test/compiler/ets/instanceof_dyndecl_dynvalue-expected.txt +++ b/ets2panda/test/compiler/ets/instanceof_dyndecl_dynvalue-expected.txt @@ -14,7 +14,7 @@ }, "end": { "line": 20, - "column": 44, + "column": 41, "program": "instanceof_dyndecl_dynvalue.ets" } } @@ -78,7 +78,7 @@ }, "end": { "line": 20, - "column": 44, + "column": 41, "program": "instanceof_dyndecl_dynvalue.ets" } } @@ -187,40 +187,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "instanceof_dyndecl_dynvalue.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "instanceof_dyndecl_dynvalue.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "instanceof_dyndecl_dynvalue.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "instanceof_dyndecl_dynvalue.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", @@ -836,6 +802,61 @@ } } }, + { + "type": "ClassProperty", + "key": { + "type": "Identifier", + "name": "dynamic_import_tests_modules_instanceof1", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "accessibility": "public", + "static": true, + "readonly": true, + "declare": false, + "optional": false, + "computed": false, + "typeAnnotation": { + "type": "OpaqueType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "definite": false, + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, { "type": "ClassStaticBlock", "value": { @@ -1032,6 +1053,173 @@ "program": null } } + }, + { + "type": "ExpressionStatement", + "expression": { + "type": "AssignmentExpression", + "operator": "=", + "left": { + "type": "MemberExpression", + "object": { + "type": "Identifier", + "name": "$dynmodule", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "property": { + "type": "Identifier", + "name": "dynamic_import_tests_modules_instanceof1", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "computed": false, + "optional": false, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "right": { + "type": "CallExpression", + "callee": { + "type": "MemberExpression", + "object": { + "type": "Identifier", + "name": "JSRuntime", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "property": { + "type": "Identifier", + "name": "loadModule", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "computed": false, + "optional": false, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "arguments": [ + { + "type": "StringLiteral", + "value": "/home/anya/panda_reps/standalone_new/arkcompiler/runtime_core/static_core/tools/es2panda/test/parser/ets/dynamic_import_tests/modules/instanceof.ets", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + } + ], + "optional": false, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } } ], "loc": { diff --git a/ets2panda/test/compiler/ets/instanceof_dyndecl_jsvalue-expected.txt b/ets2panda/test/compiler/ets/instanceof_dyndecl_jsvalue-expected.txt index 2ec901bcb7..7bfcf12d59 100644 --- a/ets2panda/test/compiler/ets/instanceof_dyndecl_jsvalue-expected.txt +++ b/ets2panda/test/compiler/ets/instanceof_dyndecl_jsvalue-expected.txt @@ -105,40 +105,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "instanceof_dyndecl_jsvalue.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "instanceof_dyndecl_jsvalue.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "instanceof_dyndecl_jsvalue.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "instanceof_dyndecl_jsvalue.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", @@ -675,6 +641,482 @@ "program": "instanceof_dyndecl_jsvalue.ets" } } + }, + { + "type": "ClassDeclaration", + "definition": { + "id": { + "type": "Identifier", + "name": "$dynmodule", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "superClass": null, + "implements": [], + "body": [ + { + "type": "ClassProperty", + "key": { + "type": "Identifier", + "name": "dynamic_import_tests_modules_instanceof0", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "accessibility": "public", + "static": true, + "readonly": true, + "declare": false, + "optional": false, + "computed": false, + "typeAnnotation": { + "type": "OpaqueType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "definite": false, + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + { + "type": "ClassStaticBlock", + "value": { + "type": "FunctionExpression", + "function": { + "type": "ScriptFunction", + "id": { + "type": "Identifier", + "name": "", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "generator": false, + "async": false, + "expression": true, + "params": [], + "body": { + "type": "BlockStatement", + "statements": [ + { + "type": "ExpressionStatement", + "expression": { + "type": "AssignmentExpression", + "operator": "=", + "left": { + "type": "MemberExpression", + "object": { + "type": "Identifier", + "name": "$dynmodule", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "property": { + "type": "Identifier", + "name": "dynamic_import_tests_modules_instanceof0", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "computed": false, + "optional": false, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "right": { + "type": "CallExpression", + "callee": { + "type": "MemberExpression", + "object": { + "type": "Identifier", + "name": "JSRuntime", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "property": { + "type": "Identifier", + "name": "loadModule", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "computed": false, + "optional": false, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "arguments": [ + { + "type": "StringLiteral", + "value": "/home/anya/panda_reps/standalone_new/arkcompiler/runtime_core/static_core/tools/es2panda/test/parser/ets/dynamic_import_tests/modules/instanceof.ets", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + } + ], + "optional": false, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + } + ], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + { + "type": "MethodDefinition", + "key": { + "type": "Identifier", + "name": "init", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "kind": "method", + "accessibility": "public", + "static": true, + "optional": false, + "computed": false, + "value": { + "type": "FunctionExpression", + "function": { + "type": "ScriptFunction", + "id": { + "type": "Identifier", + "name": "init", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "generator": false, + "async": false, + "expression": false, + "params": [], + "returnType": { + "type": "OpaqueType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "body": { + "type": "BlockStatement", + "statements": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "overloads": [], + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + } + ], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } } ], "loc": { diff --git a/ets2panda/test/compiler/ets/instanceof_dynvalue_dynvalue-expected.txt b/ets2panda/test/compiler/ets/instanceof_dynvalue_dynvalue-expected.txt index 5d4706c78e..1b7d02a916 100644 --- a/ets2panda/test/compiler/ets/instanceof_dynvalue_dynvalue-expected.txt +++ b/ets2panda/test/compiler/ets/instanceof_dynvalue_dynvalue-expected.txt @@ -154,40 +154,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "instanceof_dynvalue_dynvalue.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "instanceof_dynvalue_dynvalue.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "instanceof_dynvalue_dynvalue.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "instanceof_dynvalue_dynvalue.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/instanceof_dynvalue_jsvalue-expected.txt b/ets2panda/test/compiler/ets/instanceof_dynvalue_jsvalue-expected.txt index ca744db92c..1b15d2d3f0 100644 --- a/ets2panda/test/compiler/ets/instanceof_dynvalue_jsvalue-expected.txt +++ b/ets2panda/test/compiler/ets/instanceof_dynvalue_jsvalue-expected.txt @@ -105,40 +105,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "instanceof_dynvalue_jsvalue.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "instanceof_dynvalue_jsvalue.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "instanceof_dynvalue_jsvalue.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "instanceof_dynvalue_jsvalue.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/instanceof_etsobject_dynvalue-expected.txt b/ets2panda/test/compiler/ets/instanceof_etsobject_dynvalue-expected.txt index 8d4202c4c5..aa447ef82e 100644 --- a/ets2panda/test/compiler/ets/instanceof_etsobject_dynvalue-expected.txt +++ b/ets2panda/test/compiler/ets/instanceof_etsobject_dynvalue-expected.txt @@ -105,40 +105,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "instanceof_etsobject_dynvalue.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "instanceof_etsobject_dynvalue.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "instanceof_etsobject_dynvalue.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "instanceof_etsobject_dynvalue.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/instanceof_etsobject_jsvalue-expected.txt b/ets2panda/test/compiler/ets/instanceof_etsobject_jsvalue-expected.txt index 11297e5d7b..58cc1902d3 100644 --- a/ets2panda/test/compiler/ets/instanceof_etsobject_jsvalue-expected.txt +++ b/ets2panda/test/compiler/ets/instanceof_etsobject_jsvalue-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "instanceof_etsobject_jsvalue.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "instanceof_etsobject_jsvalue.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "instanceof_etsobject_jsvalue.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "instanceof_etsobject_jsvalue.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/instanceof_jsvalue_dynvalue-expected.txt b/ets2panda/test/compiler/ets/instanceof_jsvalue_dynvalue-expected.txt index ea0f73eb33..085f13259f 100644 --- a/ets2panda/test/compiler/ets/instanceof_jsvalue_dynvalue-expected.txt +++ b/ets2panda/test/compiler/ets/instanceof_jsvalue_dynvalue-expected.txt @@ -105,40 +105,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "instanceof_jsvalue_dynvalue.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "instanceof_jsvalue_dynvalue.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "instanceof_jsvalue_dynvalue.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "instanceof_jsvalue_dynvalue.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/instanceof_jsvalue_jsvalue-expected.txt b/ets2panda/test/compiler/ets/instanceof_jsvalue_jsvalue-expected.txt index 0302f47669..ace3481dfc 100644 --- a/ets2panda/test/compiler/ets/instanceof_jsvalue_jsvalue-expected.txt +++ b/ets2panda/test/compiler/ets/instanceof_jsvalue_jsvalue-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "instanceof_jsvalue_jsvalue.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "instanceof_jsvalue_jsvalue.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "instanceof_jsvalue_jsvalue.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "instanceof_jsvalue_jsvalue.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/instanceof_object_dynvalue-expected.txt b/ets2panda/test/compiler/ets/instanceof_object_dynvalue-expected.txt index 16902d759d..b4880080b7 100644 --- a/ets2panda/test/compiler/ets/instanceof_object_dynvalue-expected.txt +++ b/ets2panda/test/compiler/ets/instanceof_object_dynvalue-expected.txt @@ -105,40 +105,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "instanceof_object_dynvalue.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "instanceof_object_dynvalue.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "instanceof_object_dynvalue.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "instanceof_object_dynvalue.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/instanceof_object_jsvalue-expected.txt b/ets2panda/test/compiler/ets/instanceof_object_jsvalue-expected.txt index 27d1e5fcea..420f8a4d23 100644 --- a/ets2panda/test/compiler/ets/instanceof_object_jsvalue-expected.txt +++ b/ets2panda/test/compiler/ets/instanceof_object_jsvalue-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "instanceof_object_jsvalue.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "instanceof_object_jsvalue.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "instanceof_object_jsvalue.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "instanceof_object_jsvalue.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/instanceof_object_long-expected.txt b/ets2panda/test/compiler/ets/instanceof_object_long-expected.txt index c910038c80..bab47a98ee 100644 --- a/ets2panda/test/compiler/ets/instanceof_object_long-expected.txt +++ b/ets2panda/test/compiler/ets/instanceof_object_long-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "instanceof_object_long.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "instanceof_object_long.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "instanceof_object_long.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "instanceof_object_long.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/instanceof_x_dyndecl-expected.txt b/ets2panda/test/compiler/ets/instanceof_x_dyndecl-expected.txt index f587c6f1ce..d44902f551 100644 --- a/ets2panda/test/compiler/ets/instanceof_x_dyndecl-expected.txt +++ b/ets2panda/test/compiler/ets/instanceof_x_dyndecl-expected.txt @@ -14,7 +14,7 @@ }, "end": { "line": 20, - "column": 49, + "column": 46, "program": "instanceof_x_dyndecl.ets" } } @@ -78,7 +78,7 @@ }, "end": { "line": 20, - "column": 49, + "column": 46, "program": "instanceof_x_dyndecl.ets" } } @@ -236,40 +236,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "instanceof_x_dyndecl.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "instanceof_x_dyndecl.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "instanceof_x_dyndecl.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "instanceof_x_dyndecl.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", @@ -2228,6 +2194,61 @@ } } }, + { + "type": "ClassProperty", + "key": { + "type": "Identifier", + "name": "dynamic_import_tests_modules_instanceof1", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "accessibility": "public", + "static": true, + "readonly": true, + "declare": false, + "optional": false, + "computed": false, + "typeAnnotation": { + "type": "OpaqueType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "definite": false, + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, { "type": "ClassStaticBlock", "value": { @@ -2424,6 +2445,173 @@ "program": null } } + }, + { + "type": "ExpressionStatement", + "expression": { + "type": "AssignmentExpression", + "operator": "=", + "left": { + "type": "MemberExpression", + "object": { + "type": "Identifier", + "name": "$dynmodule", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "property": { + "type": "Identifier", + "name": "dynamic_import_tests_modules_instanceof1", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "computed": false, + "optional": false, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "right": { + "type": "CallExpression", + "callee": { + "type": "MemberExpression", + "object": { + "type": "Identifier", + "name": "JSRuntime", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "property": { + "type": "Identifier", + "name": "loadModule", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "computed": false, + "optional": false, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "arguments": [ + { + "type": "StringLiteral", + "value": "/home/anya/panda_reps/standalone_new/arkcompiler/runtime_core/static_core/tools/es2panda/test/parser/ets/dynamic_import_tests/modules/instanceof.ets", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + } + ], + "optional": false, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } } ], "loc": { diff --git a/ets2panda/test/compiler/ets/instanceof_x_etstype-expected.txt b/ets2panda/test/compiler/ets/instanceof_x_etstype-expected.txt index 28cb84a32d..6a58368378 100644 --- a/ets2panda/test/compiler/ets/instanceof_x_etstype-expected.txt +++ b/ets2panda/test/compiler/ets/instanceof_x_etstype-expected.txt @@ -14,7 +14,7 @@ }, "end": { "line": 20, - "column": 49, + "column": 46, "program": "instanceof_x_etstype.ets" } } @@ -78,7 +78,7 @@ }, "end": { "line": 20, - "column": 49, + "column": 46, "program": "instanceof_x_etstype.ets" } } @@ -187,40 +187,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "instanceof_x_etstype.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "instanceof_x_etstype.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "instanceof_x_etstype.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "instanceof_x_etstype.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", @@ -2334,6 +2300,61 @@ } } }, + { + "type": "ClassProperty", + "key": { + "type": "Identifier", + "name": "dynamic_import_tests_modules_instanceof1", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "accessibility": "public", + "static": true, + "readonly": true, + "declare": false, + "optional": false, + "computed": false, + "typeAnnotation": { + "type": "OpaqueType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "definite": false, + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, { "type": "ClassStaticBlock", "value": { @@ -2530,6 +2551,173 @@ "program": null } } + }, + { + "type": "ExpressionStatement", + "expression": { + "type": "AssignmentExpression", + "operator": "=", + "left": { + "type": "MemberExpression", + "object": { + "type": "Identifier", + "name": "$dynmodule", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "property": { + "type": "Identifier", + "name": "dynamic_import_tests_modules_instanceof1", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "computed": false, + "optional": false, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "right": { + "type": "CallExpression", + "callee": { + "type": "MemberExpression", + "object": { + "type": "Identifier", + "name": "JSRuntime", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "property": { + "type": "Identifier", + "name": "loadModule", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "computed": false, + "optional": false, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "arguments": [ + { + "type": "StringLiteral", + "value": "/home/anya/panda_reps/standalone_new/arkcompiler/runtime_core/static_core/tools/es2panda/test/parser/ets/dynamic_import_tests/modules/instanceof.ets", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + } + ], + "optional": false, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } } ], "loc": { diff --git a/ets2panda/test/compiler/ets/instanceof_x_object-expected.txt b/ets2panda/test/compiler/ets/instanceof_x_object-expected.txt index c7771f79dd..2f04808c10 100644 --- a/ets2panda/test/compiler/ets/instanceof_x_object-expected.txt +++ b/ets2panda/test/compiler/ets/instanceof_x_object-expected.txt @@ -14,7 +14,7 @@ }, "end": { "line": 20, - "column": 49, + "column": 46, "program": "instanceof_x_object.ets" } } @@ -78,7 +78,7 @@ }, "end": { "line": 20, - "column": 49, + "column": 46, "program": "instanceof_x_object.ets" } } @@ -187,40 +187,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "instanceof_x_object.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "instanceof_x_object.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "instanceof_x_object.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "instanceof_x_object.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", @@ -2179,6 +2145,61 @@ } } }, + { + "type": "ClassProperty", + "key": { + "type": "Identifier", + "name": "dynamic_import_tests_modules_instanceof1", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "accessibility": "public", + "static": true, + "readonly": true, + "declare": false, + "optional": false, + "computed": false, + "typeAnnotation": { + "type": "OpaqueType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "definite": false, + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, { "type": "ClassStaticBlock", "value": { @@ -2375,6 +2396,173 @@ "program": null } } + }, + { + "type": "ExpressionStatement", + "expression": { + "type": "AssignmentExpression", + "operator": "=", + "left": { + "type": "MemberExpression", + "object": { + "type": "Identifier", + "name": "$dynmodule", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "property": { + "type": "Identifier", + "name": "dynamic_import_tests_modules_instanceof1", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "computed": false, + "optional": false, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "right": { + "type": "CallExpression", + "callee": { + "type": "MemberExpression", + "object": { + "type": "Identifier", + "name": "JSRuntime", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "property": { + "type": "Identifier", + "name": "loadModule", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "computed": false, + "optional": false, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "arguments": [ + { + "type": "StringLiteral", + "value": "/home/anya/panda_reps/standalone_new/arkcompiler/runtime_core/static_core/tools/es2panda/test/parser/ets/dynamic_import_tests/modules/instanceof.ets", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + } + ], + "optional": false, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } } ], "loc": { diff --git a/ets2panda/test/compiler/ets/interface_noreturn_type_function-expected.txt b/ets2panda/test/compiler/ets/interface_noreturn_type_function-expected.txt index b0bdfeb34d..1bc910d1e7 100644 --- a/ets2panda/test/compiler/ets/interface_noreturn_type_function-expected.txt +++ b/ets2panda/test/compiler/ets/interface_noreturn_type_function-expected.txt @@ -429,40 +429,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "interface_noreturn_type_function.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "interface_noreturn_type_function.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "interface_noreturn_type_function.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "interface_noreturn_type_function.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/invalidCallInstruction-expected.txt b/ets2panda/test/compiler/ets/invalidCallInstruction-expected.txt index efc1f4f6d2..618c51090b 100644 --- a/ets2panda/test/compiler/ets/invalidCallInstruction-expected.txt +++ b/ets2panda/test/compiler/ets/invalidCallInstruction-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "invalidCallInstruction.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "invalidCallInstruction.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "invalidCallInstruction.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "invalidCallInstruction.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/invalidInheritance3-expected.txt b/ets2panda/test/compiler/ets/invalidInheritance3-expected.txt index 1d89f0d132..89d140de9f 100644 --- a/ets2panda/test/compiler/ets/invalidInheritance3-expected.txt +++ b/ets2panda/test/compiler/ets/invalidInheritance3-expected.txt @@ -779,40 +779,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "invalidInheritance3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "invalidInheritance3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "invalidInheritance3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "invalidInheritance3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/lambdaFunction1-expected.txt b/ets2panda/test/compiler/ets/lambdaFunction1-expected.txt index 8ee8b70f5a..79e03cb456 100644 --- a/ets2panda/test/compiler/ets/lambdaFunction1-expected.txt +++ b/ets2panda/test/compiler/ets/lambdaFunction1-expected.txt @@ -792,40 +792,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambdaFunction1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambdaFunction1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambdaFunction1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambdaFunction1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/lambdaFunctionArrayDeclaration-expected.txt b/ets2panda/test/compiler/ets/lambdaFunctionArrayDeclaration-expected.txt index 17ceb1ce19..fe4dc9ee80 100644 --- a/ets2panda/test/compiler/ets/lambdaFunctionArrayDeclaration-expected.txt +++ b/ets2panda/test/compiler/ets/lambdaFunctionArrayDeclaration-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambdaFunctionArrayDeclaration.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambdaFunctionArrayDeclaration.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambdaFunctionArrayDeclaration.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambdaFunctionArrayDeclaration.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/lambda_capturing-expected.txt b/ets2panda/test/compiler/ets/lambda_capturing-expected.txt index 23f0b13a46..95324f7bff 100644 --- a/ets2panda/test/compiler/ets/lambda_capturing-expected.txt +++ b/ets2panda/test/compiler/ets/lambda_capturing-expected.txt @@ -134,40 +134,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_capturing.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_capturing.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_capturing.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_capturing.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/lambda_infer_type/lambda_cast_infer_type_narrowing-expected.txt b/ets2panda/test/compiler/ets/lambda_infer_type/lambda_cast_infer_type_narrowing-expected.txt index 52df06988a..adf317e566 100644 --- a/ets2panda/test/compiler/ets/lambda_infer_type/lambda_cast_infer_type_narrowing-expected.txt +++ b/ets2panda/test/compiler/ets/lambda_infer_type/lambda_cast_infer_type_narrowing-expected.txt @@ -1068,40 +1068,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_cast_infer_type_narrowing.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_cast_infer_type_narrowing.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_cast_infer_type_narrowing.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_cast_infer_type_narrowing.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/lambda_infer_type/lambda_cast_infer_type_void-expected.txt b/ets2panda/test/compiler/ets/lambda_infer_type/lambda_cast_infer_type_void-expected.txt index 2fdc5d0da3..e0b68b4ea0 100644 --- a/ets2panda/test/compiler/ets/lambda_infer_type/lambda_cast_infer_type_void-expected.txt +++ b/ets2panda/test/compiler/ets/lambda_infer_type/lambda_cast_infer_type_void-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_cast_infer_type_void.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_cast_infer_type_void.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_cast_infer_type_void.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_cast_infer_type_void.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/lambda_infer_type/lambda_cast_infer_type_widening-expected.txt b/ets2panda/test/compiler/ets/lambda_infer_type/lambda_cast_infer_type_widening-expected.txt index 463406cfea..9d0c4a664c 100644 --- a/ets2panda/test/compiler/ets/lambda_infer_type/lambda_cast_infer_type_widening-expected.txt +++ b/ets2panda/test/compiler/ets/lambda_infer_type/lambda_cast_infer_type_widening-expected.txt @@ -1114,40 +1114,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_cast_infer_type_widening.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_cast_infer_type_widening.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_cast_infer_type_widening.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_cast_infer_type_widening.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/lambda_infer_type/lambda_cast_type_has_pramas-expected.txt b/ets2panda/test/compiler/ets/lambda_infer_type/lambda_cast_type_has_pramas-expected.txt index 69efc6221b..52981c41e9 100644 --- a/ets2panda/test/compiler/ets/lambda_infer_type/lambda_cast_type_has_pramas-expected.txt +++ b/ets2panda/test/compiler/ets/lambda_infer_type/lambda_cast_type_has_pramas-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_cast_type_has_pramas.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_cast_type_has_pramas.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_cast_type_has_pramas.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_cast_type_has_pramas.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type-expected.txt b/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type-expected.txt index 7a2f2fa09f..50a8f9b7df 100644 --- a/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type-expected.txt +++ b/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_infer_type.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_infer_type.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_infer_type.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_infer_type.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_arrow_expression-expected.txt b/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_arrow_expression-expected.txt index aa8aa1b8c4..d76dc0af96 100644 --- a/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_arrow_expression-expected.txt +++ b/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_arrow_expression-expected.txt @@ -595,40 +595,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_arrow_expression.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_arrow_expression.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_arrow_expression.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_arrow_expression.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_arrow_expression_literal-expected.txt b/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_arrow_expression_literal-expected.txt index cc70598f00..acb76e09d4 100644 --- a/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_arrow_expression_literal-expected.txt +++ b/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_arrow_expression_literal-expected.txt @@ -548,40 +548,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_arrow_expression_literal.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_arrow_expression_literal.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_arrow_expression_literal.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_arrow_expression_literal.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_has_return-expected.txt b/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_has_return-expected.txt index e380e7a297..27526a0561 100644 --- a/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_has_return-expected.txt +++ b/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_has_return-expected.txt @@ -709,40 +709,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_has_return.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_has_return.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_has_return.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_has_return.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_param2-expected.txt b/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_param2-expected.txt index a6b62d2c4c..39e640a0ff 100644 --- a/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_param2-expected.txt +++ b/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_param2-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_param2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_param2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_param2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_param2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_return_array-expected.txt b/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_return_array-expected.txt index e1603e74ad..b141b8d467 100644 --- a/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_return_array-expected.txt +++ b/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_return_array-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_return_array.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_return_array.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_return_array.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_return_array.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_return_lambda-expected.txt b/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_return_lambda-expected.txt index 98f25b34d4..0e150addfb 100644 --- a/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_return_lambda-expected.txt +++ b/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_return_lambda-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_return_lambda.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_return_lambda.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_return_lambda.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_return_lambda.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_return_lambda1-expected.txt b/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_return_lambda1-expected.txt index b4177187ab..026159d3ce 100644 --- a/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_return_lambda1-expected.txt +++ b/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_return_lambda1-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_return_lambda1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_return_lambda1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_return_lambda1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_return_lambda1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_return_lambda_expression-expected.txt b/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_return_lambda_expression-expected.txt index e330504bae..54f0403fca 100644 --- a/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_return_lambda_expression-expected.txt +++ b/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_return_lambda_expression-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_return_lambda_expression.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_return_lambda_expression.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_return_lambda_expression.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_return_lambda_expression.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_return_literal-expected.txt b/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_return_literal-expected.txt index f445df641e..573e531158 100644 --- a/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_return_literal-expected.txt +++ b/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_return_literal-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_return_literal.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_return_literal.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_return_literal.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_return_literal.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_return_union-expected.txt b/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_return_union-expected.txt index 8f5814fba9..389e4d15b3 100644 --- a/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_return_union-expected.txt +++ b/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_return_union-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_return_union.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_return_union.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_return_union.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_return_union.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_scope-expected.txt b/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_scope-expected.txt index dd9ae6b964..cf65a444be 100644 --- a/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_scope-expected.txt +++ b/ets2panda/test/compiler/ets/lambda_infer_type/lambda_infer_type_scope-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_scope.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_scope.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_scope.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_infer_type_scope.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/lambda_unresolved_ref_1-expected.txt b/ets2panda/test/compiler/ets/lambda_unresolved_ref_1-expected.txt index 0a83d7d0df..53fc9494d5 100644 --- a/ets2panda/test/compiler/ets/lambda_unresolved_ref_1-expected.txt +++ b/ets2panda/test/compiler/ets/lambda_unresolved_ref_1-expected.txt @@ -741,40 +741,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_unresolved_ref_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_unresolved_ref_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_unresolved_ref_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_unresolved_ref_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/launch_expression-expected.txt b/ets2panda/test/compiler/ets/launch_expression-expected.txt index cd89afa987..4ed031a691 100644 --- a/ets2panda/test/compiler/ets/launch_expression-expected.txt +++ b/ets2panda/test/compiler/ets/launch_expression-expected.txt @@ -198,40 +198,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "launch_expression.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "launch_expression.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "launch_expression.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "launch_expression.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/loopWithinLambda-expected.txt b/ets2panda/test/compiler/ets/loopWithinLambda-expected.txt index 339b3c8131..2dffdc1e5b 100644 --- a/ets2panda/test/compiler/ets/loopWithinLambda-expected.txt +++ b/ets2panda/test/compiler/ets/loopWithinLambda-expected.txt @@ -467,40 +467,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "loopWithinLambda.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "loopWithinLambda.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "loopWithinLambda.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "loopWithinLambda.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/lowering-interaction-expected.txt b/ets2panda/test/compiler/ets/lowering-interaction-expected.txt index 325b197a15..25c277353b 100644 --- a/ets2panda/test/compiler/ets/lowering-interaction-expected.txt +++ b/ets2panda/test/compiler/ets/lowering-interaction-expected.txt @@ -1376,40 +1376,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lowering-interaction.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lowering-interaction.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lowering-interaction.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lowering-interaction.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/manyLocalsParamRegUsage-expected.txt b/ets2panda/test/compiler/ets/manyLocalsParamRegUsage-expected.txt index 974a41b880..368b383ee1 100644 --- a/ets2panda/test/compiler/ets/manyLocalsParamRegUsage-expected.txt +++ b/ets2panda/test/compiler/ets/manyLocalsParamRegUsage-expected.txt @@ -35325,40 +35325,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "manyLocalsParamRegUsage.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "manyLocalsParamRegUsage.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "manyLocalsParamRegUsage.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "manyLocalsParamRegUsage.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/memberExprInLambda-expected.txt b/ets2panda/test/compiler/ets/memberExprInLambda-expected.txt index c162e9d8a0..89277eab46 100644 --- a/ets2panda/test/compiler/ets/memberExprInLambda-expected.txt +++ b/ets2panda/test/compiler/ets/memberExprInLambda-expected.txt @@ -86,40 +86,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "memberExprInLambda.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "memberExprInLambda.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "memberExprInLambda.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "memberExprInLambda.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/memberExpressionFromStaticContext-expected.txt b/ets2panda/test/compiler/ets/memberExpressionFromStaticContext-expected.txt index 729d5e66af..77e24d2125 100644 --- a/ets2panda/test/compiler/ets/memberExpressionFromStaticContext-expected.txt +++ b/ets2panda/test/compiler/ets/memberExpressionFromStaticContext-expected.txt @@ -3005,40 +3005,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "memberExpressionFromStaticContext.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "memberExpressionFromStaticContext.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "memberExpressionFromStaticContext.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "memberExpressionFromStaticContext.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/method-resolution-class-and-interface-in-signatures_5-expected.txt b/ets2panda/test/compiler/ets/method-resolution-class-and-interface-in-signatures_5-expected.txt index 4a7c723f61..31d7c0bbe3 100644 --- a/ets2panda/test/compiler/ets/method-resolution-class-and-interface-in-signatures_5-expected.txt +++ b/ets2panda/test/compiler/ets/method-resolution-class-and-interface-in-signatures_5-expected.txt @@ -803,40 +803,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "method-resolution-class-and-interface-in-signatures_5.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "method-resolution-class-and-interface-in-signatures_5.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "method-resolution-class-and-interface-in-signatures_5.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "method-resolution-class-and-interface-in-signatures_5.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/methodOverrideAsyncMethod-expected.txt b/ets2panda/test/compiler/ets/methodOverrideAsyncMethod-expected.txt index c6b646f112..a3889c32e1 100644 --- a/ets2panda/test/compiler/ets/methodOverrideAsyncMethod-expected.txt +++ b/ets2panda/test/compiler/ets/methodOverrideAsyncMethod-expected.txt @@ -1250,40 +1250,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "methodOverrideAsyncMethod.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "methodOverrideAsyncMethod.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "methodOverrideAsyncMethod.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "methodOverrideAsyncMethod.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/methodOverrideCovariantReturnType-expected.txt b/ets2panda/test/compiler/ets/methodOverrideCovariantReturnType-expected.txt index 615d5713e9..cd642fce8c 100644 --- a/ets2panda/test/compiler/ets/methodOverrideCovariantReturnType-expected.txt +++ b/ets2panda/test/compiler/ets/methodOverrideCovariantReturnType-expected.txt @@ -2153,40 +2153,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "methodOverrideCovariantReturnType.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "methodOverrideCovariantReturnType.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "methodOverrideCovariantReturnType.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "methodOverrideCovariantReturnType.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/methodOverrideDifferentSignature-expected.txt b/ets2panda/test/compiler/ets/methodOverrideDifferentSignature-expected.txt index 098152e778..2f6c7b678c 100644 --- a/ets2panda/test/compiler/ets/methodOverrideDifferentSignature-expected.txt +++ b/ets2panda/test/compiler/ets/methodOverrideDifferentSignature-expected.txt @@ -1437,40 +1437,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "methodOverrideDifferentSignature.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "methodOverrideDifferentSignature.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "methodOverrideDifferentSignature.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "methodOverrideDifferentSignature.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/methodOverrideWithoutModifier-expected.txt b/ets2panda/test/compiler/ets/methodOverrideWithoutModifier-expected.txt index 5e50f1ffe1..864cd808e4 100644 --- a/ets2panda/test/compiler/ets/methodOverrideWithoutModifier-expected.txt +++ b/ets2panda/test/compiler/ets/methodOverrideWithoutModifier-expected.txt @@ -621,40 +621,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "methodOverrideWithoutModifier.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "methodOverrideWithoutModifier.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "methodOverrideWithoutModifier.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "methodOverrideWithoutModifier.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/multipleMethodOverride-expected.txt b/ets2panda/test/compiler/ets/multipleMethodOverride-expected.txt index 75b30d118d..1a388bd32d 100644 --- a/ets2panda/test/compiler/ets/multipleMethodOverride-expected.txt +++ b/ets2panda/test/compiler/ets/multipleMethodOverride-expected.txt @@ -1144,40 +1144,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "multipleMethodOverride.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "multipleMethodOverride.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "multipleMethodOverride.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "multipleMethodOverride.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/n_nullableTypeInArgNotRef-expected.txt b/ets2panda/test/compiler/ets/n_nullableTypeInArgNotRef-expected.txt index af25de422f..d751217bc9 100644 --- a/ets2panda/test/compiler/ets/n_nullableTypeInArgNotRef-expected.txt +++ b/ets2panda/test/compiler/ets/n_nullableTypeInArgNotRef-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "n_nullableTypeInArgNotRef.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "n_nullableTypeInArgNotRef.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "n_nullableTypeInArgNotRef.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "n_nullableTypeInArgNotRef.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/n_nullableTypeInReturnNotRef-expected.txt b/ets2panda/test/compiler/ets/n_nullableTypeInReturnNotRef-expected.txt index 3d33bda0cb..43fc249667 100644 --- a/ets2panda/test/compiler/ets/n_nullableTypeInReturnNotRef-expected.txt +++ b/ets2panda/test/compiler/ets/n_nullableTypeInReturnNotRef-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "n_nullableTypeInReturnNotRef.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "n_nullableTypeInReturnNotRef.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "n_nullableTypeInReturnNotRef.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "n_nullableTypeInReturnNotRef.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/n_nullableTypeNotRef-expected.txt b/ets2panda/test/compiler/ets/n_nullableTypeNotRef-expected.txt index ed32720e87..34b399bb68 100644 --- a/ets2panda/test/compiler/ets/n_nullableTypeNotRef-expected.txt +++ b/ets2panda/test/compiler/ets/n_nullableTypeNotRef-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "n_nullableTypeNotRef.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "n_nullableTypeNotRef.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "n_nullableTypeNotRef.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "n_nullableTypeNotRef.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/native_toplevel-expected.txt b/ets2panda/test/compiler/ets/native_toplevel-expected.txt index 113f768135..88d918fd56 100644 --- a/ets2panda/test/compiler/ets/native_toplevel-expected.txt +++ b/ets2panda/test/compiler/ets/native_toplevel-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "native_toplevel.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "native_toplevel.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "native_toplevel.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "native_toplevel.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/non-const-lambda-with-scopes-expected.txt b/ets2panda/test/compiler/ets/non-const-lambda-with-scopes-expected.txt index da32b6e0d2..6c210630f9 100644 --- a/ets2panda/test/compiler/ets/non-const-lambda-with-scopes-expected.txt +++ b/ets2panda/test/compiler/ets/non-const-lambda-with-scopes-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "non-const-lambda-with-scopes.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "non-const-lambda-with-scopes.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "non-const-lambda-with-scopes.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "non-const-lambda-with-scopes.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/null_coalescing_generic_1-expected.txt b/ets2panda/test/compiler/ets/null_coalescing_generic_1-expected.txt index cd1a78604c..e129c87f44 100644 --- a/ets2panda/test/compiler/ets/null_coalescing_generic_1-expected.txt +++ b/ets2panda/test/compiler/ets/null_coalescing_generic_1-expected.txt @@ -178,40 +178,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "null_coalescing_generic_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "null_coalescing_generic_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "null_coalescing_generic_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "null_coalescing_generic_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/nullableTuple-expected.txt b/ets2panda/test/compiler/ets/nullableTuple-expected.txt index 4e41a2e5c7..1b5b431a73 100644 --- a/ets2panda/test/compiler/ets/nullableTuple-expected.txt +++ b/ets2panda/test/compiler/ets/nullableTuple-expected.txt @@ -277,40 +277,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "nullableTuple.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "nullableTuple.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "nullableTuple.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "nullableTuple.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/nullable_type_in_arithmeticdiv-expected.txt b/ets2panda/test/compiler/ets/nullable_type_in_arithmeticdiv-expected.txt index f15287d771..15d582ab65 100644 --- a/ets2panda/test/compiler/ets/nullable_type_in_arithmeticdiv-expected.txt +++ b/ets2panda/test/compiler/ets/nullable_type_in_arithmeticdiv-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "nullable_type_in_arithmeticdiv.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "nullable_type_in_arithmeticdiv.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "nullable_type_in_arithmeticdiv.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "nullable_type_in_arithmeticdiv.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/nullable_type_in_arithmeticplus-expected.txt b/ets2panda/test/compiler/ets/nullable_type_in_arithmeticplus-expected.txt index 19187a07da..8ea7dac534 100644 --- a/ets2panda/test/compiler/ets/nullable_type_in_arithmeticplus-expected.txt +++ b/ets2panda/test/compiler/ets/nullable_type_in_arithmeticplus-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "nullable_type_in_arithmeticplus.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "nullable_type_in_arithmeticplus.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "nullable_type_in_arithmeticplus.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "nullable_type_in_arithmeticplus.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/objectLiteralInterface-expected.txt b/ets2panda/test/compiler/ets/objectLiteralInterface-expected.txt index 23920fd5d7..b801c25676 100644 --- a/ets2panda/test/compiler/ets/objectLiteralInterface-expected.txt +++ b/ets2panda/test/compiler/ets/objectLiteralInterface-expected.txt @@ -72,40 +72,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "objectLiteralInterface.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "objectLiteralInterface.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "objectLiteralInterface.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "objectLiteralInterface.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/objectLiteralReadonlyKey-expected.txt b/ets2panda/test/compiler/ets/objectLiteralReadonlyKey-expected.txt index c847674a8e..21e8d6b6f5 100644 --- a/ets2panda/test/compiler/ets/objectLiteralReadonlyKey-expected.txt +++ b/ets2panda/test/compiler/ets/objectLiteralReadonlyKey-expected.txt @@ -233,40 +233,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "objectLiteralReadonlyKey.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "objectLiteralReadonlyKey.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "objectLiteralReadonlyKey.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "objectLiteralReadonlyKey.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/overload_with_generics-expected.txt b/ets2panda/test/compiler/ets/overload_with_generics-expected.txt index be2033e620..f5ca8d7c55 100644 --- a/ets2panda/test/compiler/ets/overload_with_generics-expected.txt +++ b/ets2panda/test/compiler/ets/overload_with_generics-expected.txt @@ -790,40 +790,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "overload_with_generics.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "overload_with_generics.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "overload_with_generics.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "overload_with_generics.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/override-expected.txt b/ets2panda/test/compiler/ets/override-expected.txt index c0030aadee..6eeee8dd4f 100644 --- a/ets2panda/test/compiler/ets/override-expected.txt +++ b/ets2panda/test/compiler/ets/override-expected.txt @@ -1709,40 +1709,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "override.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "override.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "override.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "override.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/override10-expected.txt b/ets2panda/test/compiler/ets/override10-expected.txt index c7200a9ee7..538955d3af 100644 --- a/ets2panda/test/compiler/ets/override10-expected.txt +++ b/ets2panda/test/compiler/ets/override10-expected.txt @@ -896,40 +896,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "override10.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "override10.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "override10.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "override10.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/override12-expected.txt b/ets2panda/test/compiler/ets/override12-expected.txt index d44d8a352d..b36a9566bd 100644 --- a/ets2panda/test/compiler/ets/override12-expected.txt +++ b/ets2panda/test/compiler/ets/override12-expected.txt @@ -1607,40 +1607,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "override12.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "override12.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "override12.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "override12.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/override13-expected.txt b/ets2panda/test/compiler/ets/override13-expected.txt index 364b686a7a..5b4c925f6b 100644 --- a/ets2panda/test/compiler/ets/override13-expected.txt +++ b/ets2panda/test/compiler/ets/override13-expected.txt @@ -1009,40 +1009,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "override13.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "override13.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "override13.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "override13.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/override16-expected.txt b/ets2panda/test/compiler/ets/override16-expected.txt index 080c32e941..5947eedf22 100644 --- a/ets2panda/test/compiler/ets/override16-expected.txt +++ b/ets2panda/test/compiler/ets/override16-expected.txt @@ -685,40 +685,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "override16.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "override16.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "override16.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "override16.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/override17-expected.txt b/ets2panda/test/compiler/ets/override17-expected.txt index f3cfcd088e..fd757fd655 100644 --- a/ets2panda/test/compiler/ets/override17-expected.txt +++ b/ets2panda/test/compiler/ets/override17-expected.txt @@ -685,40 +685,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "override17.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "override17.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "override17.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "override17.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/override19-expected.txt b/ets2panda/test/compiler/ets/override19-expected.txt index a046419071..2ae88e9df9 100644 --- a/ets2panda/test/compiler/ets/override19-expected.txt +++ b/ets2panda/test/compiler/ets/override19-expected.txt @@ -717,40 +717,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "override19.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "override19.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "override19.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "override19.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/override2-expected.txt b/ets2panda/test/compiler/ets/override2-expected.txt index ba72ed1d35..d38e7aa40f 100644 --- a/ets2panda/test/compiler/ets/override2-expected.txt +++ b/ets2panda/test/compiler/ets/override2-expected.txt @@ -750,40 +750,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "override2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "override2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "override2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "override2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/override4-expected.txt b/ets2panda/test/compiler/ets/override4-expected.txt index d5d4ddf663..2948b976cb 100644 --- a/ets2panda/test/compiler/ets/override4-expected.txt +++ b/ets2panda/test/compiler/ets/override4-expected.txt @@ -798,40 +798,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "override4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "override4.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "override4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "override4.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/override5-expected.txt b/ets2panda/test/compiler/ets/override5-expected.txt index fcda6ff94f..35b7a674de 100644 --- a/ets2panda/test/compiler/ets/override5-expected.txt +++ b/ets2panda/test/compiler/ets/override5-expected.txt @@ -685,40 +685,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "override5.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "override5.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "override5.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "override5.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/override6-expected.txt b/ets2panda/test/compiler/ets/override6-expected.txt index 3eb1449bf2..030401332d 100644 --- a/ets2panda/test/compiler/ets/override6-expected.txt +++ b/ets2panda/test/compiler/ets/override6-expected.txt @@ -661,40 +661,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "override6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "override6.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "override6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "override6.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/override8-expected.txt b/ets2panda/test/compiler/ets/override8-expected.txt index a5bc8882b4..81577b0a0a 100644 --- a/ets2panda/test/compiler/ets/override8-expected.txt +++ b/ets2panda/test/compiler/ets/override8-expected.txt @@ -612,40 +612,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "override8.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "override8.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "override8.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "override8.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/override9-expected.txt b/ets2panda/test/compiler/ets/override9-expected.txt index face0ae917..006de229cb 100644 --- a/ets2panda/test/compiler/ets/override9-expected.txt +++ b/ets2panda/test/compiler/ets/override9-expected.txt @@ -724,40 +724,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "override9.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "override9.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "override9.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "override9.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/parenthesizedType-expected.txt b/ets2panda/test/compiler/ets/parenthesizedType-expected.txt index a38a064445..e28bad53eb 100644 --- a/ets2panda/test/compiler/ets/parenthesizedType-expected.txt +++ b/ets2panda/test/compiler/ets/parenthesizedType-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "parenthesizedType.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "parenthesizedType.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "parenthesizedType.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "parenthesizedType.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/requiredType_1-expected.txt b/ets2panda/test/compiler/ets/requiredType_1-expected.txt index 61bfd17692..02e43c739e 100644 --- a/ets2panda/test/compiler/ets/requiredType_1-expected.txt +++ b/ets2panda/test/compiler/ets/requiredType_1-expected.txt @@ -313,40 +313,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "requiredType_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "requiredType_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "requiredType_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "requiredType_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/requiredType_11-expected.txt b/ets2panda/test/compiler/ets/requiredType_11-expected.txt index 732f158b71..90d3b08f06 100644 --- a/ets2panda/test/compiler/ets/requiredType_11-expected.txt +++ b/ets2panda/test/compiler/ets/requiredType_11-expected.txt @@ -652,40 +652,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "requiredType_11.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "requiredType_11.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "requiredType_11.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "requiredType_11.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/requiredType_4-expected.txt b/ets2panda/test/compiler/ets/requiredType_4-expected.txt index 41b63b0ce7..a6e74b9ae0 100644 --- a/ets2panda/test/compiler/ets/requiredType_4-expected.txt +++ b/ets2panda/test/compiler/ets/requiredType_4-expected.txt @@ -313,40 +313,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "requiredType_4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "requiredType_4.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "requiredType_4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "requiredType_4.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/requiredType_5-expected.txt b/ets2panda/test/compiler/ets/requiredType_5-expected.txt index d210fe0bec..95c93ffdd8 100644 --- a/ets2panda/test/compiler/ets/requiredType_5-expected.txt +++ b/ets2panda/test/compiler/ets/requiredType_5-expected.txt @@ -463,40 +463,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "requiredType_5.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "requiredType_5.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "requiredType_5.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "requiredType_5.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/requiredType_9-expected.txt b/ets2panda/test/compiler/ets/requiredType_9-expected.txt index 849a8dd4f2..578e4d7ad2 100644 --- a/ets2panda/test/compiler/ets/requiredType_9-expected.txt +++ b/ets2panda/test/compiler/ets/requiredType_9-expected.txt @@ -922,40 +922,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "requiredType_9.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "requiredType_9.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "requiredType_9.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "requiredType_9.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/rethrowingCheck1-expected.txt b/ets2panda/test/compiler/ets/rethrowingCheck1-expected.txt index 915ac9c329..c971b8965f 100644 --- a/ets2panda/test/compiler/ets/rethrowingCheck1-expected.txt +++ b/ets2panda/test/compiler/ets/rethrowingCheck1-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrowingCheck1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrowingCheck1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/rethrowingCheck4-expected.txt b/ets2panda/test/compiler/ets/rethrowingCheck4-expected.txt index a326711571..ffd83cec5b 100644 --- a/ets2panda/test/compiler/ets/rethrowingCheck4-expected.txt +++ b/ets2panda/test/compiler/ets/rethrowingCheck4-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrowingCheck4.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrowingCheck4.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/rethrowingConstructorCheck3-expected.txt b/ets2panda/test/compiler/ets/rethrowingConstructorCheck3-expected.txt index 2067391a08..1a0939cc0c 100644 --- a/ets2panda/test/compiler/ets/rethrowingConstructorCheck3-expected.txt +++ b/ets2panda/test/compiler/ets/rethrowingConstructorCheck3-expected.txt @@ -245,40 +245,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrowingConstructorCheck3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrowingConstructorCheck3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/rethrowingFunctionCheck3-expected.txt b/ets2panda/test/compiler/ets/rethrowingFunctionCheck3-expected.txt index 9bb871666b..811fac12b9 100644 --- a/ets2panda/test/compiler/ets/rethrowingFunctionCheck3-expected.txt +++ b/ets2panda/test/compiler/ets/rethrowingFunctionCheck3-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrowingFunctionCheck3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrowingFunctionCheck3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/rethrowingMethodCheck3-expected.txt b/ets2panda/test/compiler/ets/rethrowingMethodCheck3-expected.txt index 52e6bea785..270f5b7066 100644 --- a/ets2panda/test/compiler/ets/rethrowingMethodCheck3-expected.txt +++ b/ets2panda/test/compiler/ets/rethrowingMethodCheck3-expected.txt @@ -365,40 +365,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrowingMethodCheck3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/returnTypeGenericArray-expected.txt b/ets2panda/test/compiler/ets/returnTypeGenericArray-expected.txt index 1d99a5eb06..8bce692450 100644 --- a/ets2panda/test/compiler/ets/returnTypeGenericArray-expected.txt +++ b/ets2panda/test/compiler/ets/returnTypeGenericArray-expected.txt @@ -965,40 +965,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "returnTypeGenericArray.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "returnTypeGenericArray.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "returnTypeGenericArray.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "returnTypeGenericArray.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/switchStatementBoxing-expected.txt b/ets2panda/test/compiler/ets/switchStatementBoxing-expected.txt index 516f90ed32..2b5107c89e 100644 --- a/ets2panda/test/compiler/ets/switchStatementBoxing-expected.txt +++ b/ets2panda/test/compiler/ets/switchStatementBoxing-expected.txt @@ -610,40 +610,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "switchStatementBoxing.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "switchStatementBoxing.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "switchStatementBoxing.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "switchStatementBoxing.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/switchStatementCorrectConversion-expected.txt b/ets2panda/test/compiler/ets/switchStatementCorrectConversion-expected.txt index d0694d6504..9fff8c798d 100644 --- a/ets2panda/test/compiler/ets/switchStatementCorrectConversion-expected.txt +++ b/ets2panda/test/compiler/ets/switchStatementCorrectConversion-expected.txt @@ -987,40 +987,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "switchStatementCorrectConversion.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "switchStatementCorrectConversion.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "switchStatementCorrectConversion.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "switchStatementCorrectConversion.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/this_type_valid_return_type-expected.txt b/ets2panda/test/compiler/ets/this_type_valid_return_type-expected.txt index 7452144a1d..a0b005774d 100644 --- a/ets2panda/test/compiler/ets/this_type_valid_return_type-expected.txt +++ b/ets2panda/test/compiler/ets/this_type_valid_return_type-expected.txt @@ -330,40 +330,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "this_type_valid_return_type.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "this_type_valid_return_type.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "this_type_valid_return_type.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "this_type_valid_return_type.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/throwInCatchClause3-expected.txt b/ets2panda/test/compiler/ets/throwInCatchClause3-expected.txt index 4adb806e51..ddcae8fdbf 100644 --- a/ets2panda/test/compiler/ets/throwInCatchClause3-expected.txt +++ b/ets2panda/test/compiler/ets/throwInCatchClause3-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwInCatchClause3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwInCatchClause3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwInCatchClause3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwInCatchClause3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/throwInFinallyBlock1-expected.txt b/ets2panda/test/compiler/ets/throwInFinallyBlock1-expected.txt index 4ec770c682..4ec5b9214d 100644 --- a/ets2panda/test/compiler/ets/throwInFinallyBlock1-expected.txt +++ b/ets2panda/test/compiler/ets/throwInFinallyBlock1-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwInFinallyBlock1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwInFinallyBlock1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwInFinallyBlock1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwInFinallyBlock1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/throwInRethrowingFunction2-expected.txt b/ets2panda/test/compiler/ets/throwInRethrowingFunction2-expected.txt index c0c5532cf4..0206339f32 100644 --- a/ets2panda/test/compiler/ets/throwInRethrowingFunction2-expected.txt +++ b/ets2panda/test/compiler/ets/throwInRethrowingFunction2-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwInRethrowingFunction2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwInRethrowingFunction2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwInRethrowingFunction2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwInRethrowingFunction2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/throwInThrowingFunction-expected.txt b/ets2panda/test/compiler/ets/throwInThrowingFunction-expected.txt index 7f6ea6a060..a677bd13a0 100644 --- a/ets2panda/test/compiler/ets/throwInThrowingFunction-expected.txt +++ b/ets2panda/test/compiler/ets/throwInThrowingFunction-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwInThrowingFunction.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwInThrowingFunction.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwInThrowingFunction.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwInThrowingFunction.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/throwInTryStatement-expected.txt b/ets2panda/test/compiler/ets/throwInTryStatement-expected.txt index d56f831977..5b455dceb8 100644 --- a/ets2panda/test/compiler/ets/throwInTryStatement-expected.txt +++ b/ets2panda/test/compiler/ets/throwInTryStatement-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwInTryStatement.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwInTryStatement.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwInTryStatement.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwInTryStatement.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/throwingFunctionAsParameter1-expected.txt b/ets2panda/test/compiler/ets/throwingFunctionAsParameter1-expected.txt index 3f2b872673..1b05a374db 100644 --- a/ets2panda/test/compiler/ets/throwingFunctionAsParameter1-expected.txt +++ b/ets2panda/test/compiler/ets/throwingFunctionAsParameter1-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwingFunctionAsParameter1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwingFunctionAsParameter1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/throwingFunctionCheck2-expected.txt b/ets2panda/test/compiler/ets/throwingFunctionCheck2-expected.txt index 145591dfc4..cc12ad55a9 100644 --- a/ets2panda/test/compiler/ets/throwingFunctionCheck2-expected.txt +++ b/ets2panda/test/compiler/ets/throwingFunctionCheck2-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/throwingFunctionCheck3-expected.txt b/ets2panda/test/compiler/ets/throwingFunctionCheck3-expected.txt index 90d0e9fa34..d9f11899d8 100644 --- a/ets2panda/test/compiler/ets/throwingFunctionCheck3-expected.txt +++ b/ets2panda/test/compiler/ets/throwingFunctionCheck3-expected.txt @@ -301,40 +301,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/throwingFunctionCheck6-expected.txt b/ets2panda/test/compiler/ets/throwingFunctionCheck6-expected.txt index 5287514601..767d95af48 100644 --- a/ets2panda/test/compiler/ets/throwingFunctionCheck6-expected.txt +++ b/ets2panda/test/compiler/ets/throwingFunctionCheck6-expected.txt @@ -379,40 +379,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck6.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/throwingFunctionType1-expected.txt b/ets2panda/test/compiler/ets/throwingFunctionType1-expected.txt index 6326ffbd54..123a8379e0 100644 --- a/ets2panda/test/compiler/ets/throwingFunctionType1-expected.txt +++ b/ets2panda/test/compiler/ets/throwingFunctionType1-expected.txt @@ -87,40 +87,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwingFunctionType1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwingFunctionType1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/tryCatchErrorMissingParamType-expected.txt b/ets2panda/test/compiler/ets/tryCatchErrorMissingParamType-expected.txt index 6778942c16..7baee8c0dd 100644 --- a/ets2panda/test/compiler/ets/tryCatchErrorMissingParamType-expected.txt +++ b/ets2panda/test/compiler/ets/tryCatchErrorMissingParamType-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tryCatchErrorMissingParamType.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tryCatchErrorMissingParamType.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tryCatchErrorMissingParamType.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tryCatchErrorMissingParamType.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/tryCatchMissingParamType-expected.txt b/ets2panda/test/compiler/ets/tryCatchMissingParamType-expected.txt index 5395ba6eac..8738b66242 100644 --- a/ets2panda/test/compiler/ets/tryCatchMissingParamType-expected.txt +++ b/ets2panda/test/compiler/ets/tryCatchMissingParamType-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tryCatchMissingParamType.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tryCatchMissingParamType.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tryCatchMissingParamType.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tryCatchMissingParamType.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/tryDefaultCatches-expected.txt b/ets2panda/test/compiler/ets/tryDefaultCatches-expected.txt index 496ae55255..0e37bee20e 100644 --- a/ets2panda/test/compiler/ets/tryDefaultCatches-expected.txt +++ b/ets2panda/test/compiler/ets/tryDefaultCatches-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tryDefaultCatches.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tryDefaultCatches.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tryDefaultCatches.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tryDefaultCatches.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/tuple_types_1-expected.txt b/ets2panda/test/compiler/ets/tuple_types_1-expected.txt index b3c0d6aa20..fadce663bb 100644 --- a/ets2panda/test/compiler/ets/tuple_types_1-expected.txt +++ b/ets2panda/test/compiler/ets/tuple_types_1-expected.txt @@ -940,40 +940,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tuple_types_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tuple_types_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tuple_types_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tuple_types_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/tuple_types_12-expected.txt b/ets2panda/test/compiler/ets/tuple_types_12-expected.txt index 28c3758a12..9b89de5c95 100644 --- a/ets2panda/test/compiler/ets/tuple_types_12-expected.txt +++ b/ets2panda/test/compiler/ets/tuple_types_12-expected.txt @@ -702,40 +702,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tuple_types_12.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tuple_types_12.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tuple_types_12.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tuple_types_12.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/tuple_types_13-expected.txt b/ets2panda/test/compiler/ets/tuple_types_13-expected.txt index 69bf100c26..5b79c55a7e 100644 --- a/ets2panda/test/compiler/ets/tuple_types_13-expected.txt +++ b/ets2panda/test/compiler/ets/tuple_types_13-expected.txt @@ -213,40 +213,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tuple_types_13.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tuple_types_13.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tuple_types_13.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tuple_types_13.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/tuple_types_14-expected.txt b/ets2panda/test/compiler/ets/tuple_types_14-expected.txt index d471f35ec5..f3a64301f4 100644 --- a/ets2panda/test/compiler/ets/tuple_types_14-expected.txt +++ b/ets2panda/test/compiler/ets/tuple_types_14-expected.txt @@ -733,40 +733,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tuple_types_14.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tuple_types_14.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tuple_types_14.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tuple_types_14.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/tuple_types_15-expected.txt b/ets2panda/test/compiler/ets/tuple_types_15-expected.txt index dd6d9362ae..c98e4fad3e 100644 --- a/ets2panda/test/compiler/ets/tuple_types_15-expected.txt +++ b/ets2panda/test/compiler/ets/tuple_types_15-expected.txt @@ -134,40 +134,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tuple_types_15.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tuple_types_15.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tuple_types_15.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tuple_types_15.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/tuple_types_16-expected.txt b/ets2panda/test/compiler/ets/tuple_types_16-expected.txt index 37e21b771f..5d5e3315b1 100644 --- a/ets2panda/test/compiler/ets/tuple_types_16-expected.txt +++ b/ets2panda/test/compiler/ets/tuple_types_16-expected.txt @@ -562,40 +562,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tuple_types_16.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tuple_types_16.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tuple_types_16.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tuple_types_16.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/tuple_types_17-expected.txt b/ets2panda/test/compiler/ets/tuple_types_17-expected.txt index cdba099378..ac7cf64b2e 100644 --- a/ets2panda/test/compiler/ets/tuple_types_17-expected.txt +++ b/ets2panda/test/compiler/ets/tuple_types_17-expected.txt @@ -198,40 +198,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tuple_types_17.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tuple_types_17.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tuple_types_17.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tuple_types_17.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/tuple_types_18-expected.txt b/ets2panda/test/compiler/ets/tuple_types_18-expected.txt index 1177733504..7c58b43190 100644 --- a/ets2panda/test/compiler/ets/tuple_types_18-expected.txt +++ b/ets2panda/test/compiler/ets/tuple_types_18-expected.txt @@ -245,40 +245,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tuple_types_18.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tuple_types_18.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tuple_types_18.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tuple_types_18.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/tuple_types_19-expected.txt b/ets2panda/test/compiler/ets/tuple_types_19-expected.txt index 6de694f10d..17e090cb81 100644 --- a/ets2panda/test/compiler/ets/tuple_types_19-expected.txt +++ b/ets2panda/test/compiler/ets/tuple_types_19-expected.txt @@ -1815,40 +1815,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tuple_types_19.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tuple_types_19.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tuple_types_19.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tuple_types_19.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/tuple_types_7-expected.txt b/ets2panda/test/compiler/ets/tuple_types_7-expected.txt index 3d4f0dfc02..f4972d8cea 100644 --- a/ets2panda/test/compiler/ets/tuple_types_7-expected.txt +++ b/ets2panda/test/compiler/ets/tuple_types_7-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tuple_types_7.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tuple_types_7.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tuple_types_7.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tuple_types_7.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/typeAlias-expected.txt b/ets2panda/test/compiler/ets/typeAlias-expected.txt index 4683c6ea69..ed6e1c5f5a 100644 --- a/ets2panda/test/compiler/ets/typeAlias-expected.txt +++ b/ets2panda/test/compiler/ets/typeAlias-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "typeAlias.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "typeAlias.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "typeAlias.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "typeAlias.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/typeVarReferenceFromStaticContext2-expected.txt b/ets2panda/test/compiler/ets/typeVarReferenceFromStaticContext2-expected.txt index be172fdbe9..6c94e48e83 100644 --- a/ets2panda/test/compiler/ets/typeVarReferenceFromStaticContext2-expected.txt +++ b/ets2panda/test/compiler/ets/typeVarReferenceFromStaticContext2-expected.txt @@ -636,40 +636,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "typeVarReferenceFromStaticContext2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "typeVarReferenceFromStaticContext2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "typeVarReferenceFromStaticContext2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "typeVarReferenceFromStaticContext2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/union_types_1-expected.txt b/ets2panda/test/compiler/ets/union_types_1-expected.txt index 827791f9a5..f1d4160763 100644 --- a/ets2panda/test/compiler/ets/union_types_1-expected.txt +++ b/ets2panda/test/compiler/ets/union_types_1-expected.txt @@ -1034,40 +1034,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "union_types_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "union_types_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "union_types_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "union_types_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/union_types_3-expected.txt b/ets2panda/test/compiler/ets/union_types_3-expected.txt index 0b6e704019..05a22f4805 100644 --- a/ets2panda/test/compiler/ets/union_types_3-expected.txt +++ b/ets2panda/test/compiler/ets/union_types_3-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "union_types_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "union_types_3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "union_types_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "union_types_3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/union_types_5-expected.txt b/ets2panda/test/compiler/ets/union_types_5-expected.txt index 069a5c85ac..b41bdcb77c 100644 --- a/ets2panda/test/compiler/ets/union_types_5-expected.txt +++ b/ets2panda/test/compiler/ets/union_types_5-expected.txt @@ -992,40 +992,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "union_types_5.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "union_types_5.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "union_types_5.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "union_types_5.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/compiler/ets/union_types_merging-expected.txt b/ets2panda/test/compiler/ets/union_types_merging-expected.txt index d0a258d40d..614396b8ae 100644 --- a/ets2panda/test/compiler/ets/union_types_merging-expected.txt +++ b/ets2panda/test/compiler/ets/union_types_merging-expected.txt @@ -1941,40 +1941,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "union_types_merging.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "union_types_merging.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "union_types_merging.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "union_types_merging.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/AccessBinaryTrees-expected.txt b/ets2panda/test/parser/ets/AccessBinaryTrees-expected.txt index a74777149e..59013f92d3 100644 --- a/ets2panda/test/parser/ets/AccessBinaryTrees-expected.txt +++ b/ets2panda/test/parser/ets/AccessBinaryTrees-expected.txt @@ -5431,40 +5431,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "AccessBinaryTrees.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "AccessBinaryTrees.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "AccessBinaryTrees.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "AccessBinaryTrees.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/AccessFannkuch-expected.txt b/ets2panda/test/parser/ets/AccessFannkuch-expected.txt index 871a9c126a..9decd56bc8 100644 --- a/ets2panda/test/parser/ets/AccessFannkuch-expected.txt +++ b/ets2panda/test/parser/ets/AccessFannkuch-expected.txt @@ -5916,40 +5916,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "AccessFannkuch.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "AccessFannkuch.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "AccessFannkuch.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "AccessFannkuch.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/AccessNBody-expected.txt b/ets2panda/test/parser/ets/AccessNBody-expected.txt index 722f9f5074..89f0a71ed2 100644 --- a/ets2panda/test/parser/ets/AccessNBody-expected.txt +++ b/ets2panda/test/parser/ets/AccessNBody-expected.txt @@ -17130,40 +17130,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "AccessNBody.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "AccessNBody.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "AccessNBody.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "AccessNBody.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/AccessNSieve-expected.txt b/ets2panda/test/parser/ets/AccessNSieve-expected.txt index c327d0af67..25b17403f2 100644 --- a/ets2panda/test/parser/ets/AccessNSieve-expected.txt +++ b/ets2panda/test/parser/ets/AccessNSieve-expected.txt @@ -3419,40 +3419,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "AccessNSieve.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "AccessNSieve.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "AccessNSieve.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "AccessNSieve.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/Bitops3BitBitsInByte-expected.txt b/ets2panda/test/parser/ets/Bitops3BitBitsInByte-expected.txt index f471a30da1..978b8c3d6e 100644 --- a/ets2panda/test/parser/ets/Bitops3BitBitsInByte-expected.txt +++ b/ets2panda/test/parser/ets/Bitops3BitBitsInByte-expected.txt @@ -2251,40 +2251,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "Bitops3BitBitsInByte.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "Bitops3BitBitsInByte.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "Bitops3BitBitsInByte.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "Bitops3BitBitsInByte.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/BitopsBitsInByte-expected.txt b/ets2panda/test/parser/ets/BitopsBitsInByte-expected.txt index 6542adc6cb..19b23b72af 100644 --- a/ets2panda/test/parser/ets/BitopsBitsInByte-expected.txt +++ b/ets2panda/test/parser/ets/BitopsBitsInByte-expected.txt @@ -1993,40 +1993,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "BitopsBitsInByte.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "BitopsBitsInByte.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "BitopsBitsInByte.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "BitopsBitsInByte.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/BitopsBitwiseAnd-expected.txt b/ets2panda/test/parser/ets/BitopsBitwiseAnd-expected.txt index 3de4efb575..26c14b0b75 100644 --- a/ets2panda/test/parser/ets/BitopsBitwiseAnd-expected.txt +++ b/ets2panda/test/parser/ets/BitopsBitwiseAnd-expected.txt @@ -984,40 +984,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "BitopsBitwiseAnd.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "BitopsBitwiseAnd.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "BitopsBitwiseAnd.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "BitopsBitwiseAnd.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/BitopsNSieveBits-expected.txt b/ets2panda/test/parser/ets/BitopsNSieveBits-expected.txt index 72ba66e731..ba26034244 100644 --- a/ets2panda/test/parser/ets/BitopsNSieveBits-expected.txt +++ b/ets2panda/test/parser/ets/BitopsNSieveBits-expected.txt @@ -3670,40 +3670,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "BitopsNSieveBits.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "BitopsNSieveBits.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "BitopsNSieveBits.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "BitopsNSieveBits.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/Boolean_bitwise-expected.txt b/ets2panda/test/parser/ets/Boolean_bitwise-expected.txt index cf8040c7f9..987ba7181c 100644 --- a/ets2panda/test/parser/ets/Boolean_bitwise-expected.txt +++ b/ets2panda/test/parser/ets/Boolean_bitwise-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "Boolean_bitwise.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "Boolean_bitwise.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "Boolean_bitwise.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "Boolean_bitwise.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/ControlFlowRecursive-expected.txt b/ets2panda/test/parser/ets/ControlFlowRecursive-expected.txt index 328ebd754a..a2e875bc56 100644 --- a/ets2panda/test/parser/ets/ControlFlowRecursive-expected.txt +++ b/ets2panda/test/parser/ets/ControlFlowRecursive-expected.txt @@ -3969,40 +3969,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "ControlFlowRecursive.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "ControlFlowRecursive.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "ControlFlowRecursive.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "ControlFlowRecursive.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/Dollar_dollar_1-expected.txt b/ets2panda/test/parser/ets/Dollar_dollar_1-expected.txt index 259c3b5d6c..aea061a7ea 100644 --- a/ets2panda/test/parser/ets/Dollar_dollar_1-expected.txt +++ b/ets2panda/test/parser/ets/Dollar_dollar_1-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "Dollar_dollar_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "Dollar_dollar_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "Dollar_dollar_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "Dollar_dollar_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/Dollar_dollar_2-expected.txt b/ets2panda/test/parser/ets/Dollar_dollar_2-expected.txt index 572223c87f..76f3c0ef7f 100644 --- a/ets2panda/test/parser/ets/Dollar_dollar_2-expected.txt +++ b/ets2panda/test/parser/ets/Dollar_dollar_2-expected.txt @@ -1069,40 +1069,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "Dollar_dollar_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "Dollar_dollar_2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "Dollar_dollar_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "Dollar_dollar_2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/Dollar_dollar_3-expected.txt b/ets2panda/test/parser/ets/Dollar_dollar_3-expected.txt index 11abcabbb5..071680734f 100644 --- a/ets2panda/test/parser/ets/Dollar_dollar_3-expected.txt +++ b/ets2panda/test/parser/ets/Dollar_dollar_3-expected.txt @@ -178,40 +178,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "Dollar_dollar_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "Dollar_dollar_3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "Dollar_dollar_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "Dollar_dollar_3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/Dollar_dollar_4-expected.txt b/ets2panda/test/parser/ets/Dollar_dollar_4-expected.txt index 53eafcd69d..4ff5791c51 100644 --- a/ets2panda/test/parser/ets/Dollar_dollar_4-expected.txt +++ b/ets2panda/test/parser/ets/Dollar_dollar_4-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "Dollar_dollar_4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "Dollar_dollar_4.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "Dollar_dollar_4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "Dollar_dollar_4.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/FunctionInSwitch-expected.txt b/ets2panda/test/parser/ets/FunctionInSwitch-expected.txt index d3cc1fc191..98281fa216 100644 --- a/ets2panda/test/parser/ets/FunctionInSwitch-expected.txt +++ b/ets2panda/test/parser/ets/FunctionInSwitch-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "FunctionInSwitch.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "FunctionInSwitch.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "FunctionInSwitch.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "FunctionInSwitch.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/FunctionType-expected.txt b/ets2panda/test/parser/ets/FunctionType-expected.txt index 19e8b6da10..04d5fe044f 100644 --- a/ets2panda/test/parser/ets/FunctionType-expected.txt +++ b/ets2panda/test/parser/ets/FunctionType-expected.txt @@ -507,40 +507,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "FunctionType.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "FunctionType.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "FunctionType.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "FunctionType.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/FunctionalTypeAsTypeArgument-expected.txt b/ets2panda/test/parser/ets/FunctionalTypeAsTypeArgument-expected.txt index 09d4f5c4ff..d2da9e851f 100644 --- a/ets2panda/test/parser/ets/FunctionalTypeAsTypeArgument-expected.txt +++ b/ets2panda/test/parser/ets/FunctionalTypeAsTypeArgument-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "FunctionalTypeAsTypeArgument.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "FunctionalTypeAsTypeArgument.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "FunctionalTypeAsTypeArgument.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "FunctionalTypeAsTypeArgument.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/InferTypeParamFromParam1-expected.txt b/ets2panda/test/parser/ets/InferTypeParamFromParam1-expected.txt index 43b40fe4b0..15c3c280b2 100644 --- a/ets2panda/test/parser/ets/InferTypeParamFromParam1-expected.txt +++ b/ets2panda/test/parser/ets/InferTypeParamFromParam1-expected.txt @@ -1830,40 +1830,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "InferTypeParamFromParam1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "InferTypeParamFromParam1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "InferTypeParamFromParam1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "InferTypeParamFromParam1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/InferTypeParamFromParam3-expected.txt b/ets2panda/test/parser/ets/InferTypeParamFromParam3-expected.txt index 2605e113e0..3847671d30 100644 --- a/ets2panda/test/parser/ets/InferTypeParamFromParam3-expected.txt +++ b/ets2panda/test/parser/ets/InferTypeParamFromParam3-expected.txt @@ -2050,40 +2050,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "InferTypeParamFromParam3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "InferTypeParamFromParam3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "InferTypeParamFromParam3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "InferTypeParamFromParam3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/MathCordic-expected.txt b/ets2panda/test/parser/ets/MathCordic-expected.txt index c9c4eefdc9..e710f817a0 100644 --- a/ets2panda/test/parser/ets/MathCordic-expected.txt +++ b/ets2panda/test/parser/ets/MathCordic-expected.txt @@ -5962,40 +5962,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "MathCordic.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "MathCordic.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "MathCordic.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "MathCordic.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/MathPartialSums-expected.txt b/ets2panda/test/parser/ets/MathPartialSums-expected.txt index 5e220a50ba..5f16c7c110 100644 --- a/ets2panda/test/parser/ets/MathPartialSums-expected.txt +++ b/ets2panda/test/parser/ets/MathPartialSums-expected.txt @@ -5448,40 +5448,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "MathPartialSums.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "MathPartialSums.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "MathPartialSums.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "MathPartialSums.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/MathSpectralNorm-expected.txt b/ets2panda/test/parser/ets/MathSpectralNorm-expected.txt index 8b5e4572f0..f39c3acc52 100644 --- a/ets2panda/test/parser/ets/MathSpectralNorm-expected.txt +++ b/ets2panda/test/parser/ets/MathSpectralNorm-expected.txt @@ -6655,40 +6655,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "MathSpectralNorm.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "MathSpectralNorm.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "MathSpectralNorm.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "MathSpectralNorm.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/Morph3d-expected.txt b/ets2panda/test/parser/ets/Morph3d-expected.txt index 69211fc1b3..fed3e6b8de 100644 --- a/ets2panda/test/parser/ets/Morph3d-expected.txt +++ b/ets2panda/test/parser/ets/Morph3d-expected.txt @@ -4218,40 +4218,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "Morph3d.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "Morph3d.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "Morph3d.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "Morph3d.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/OptionalParametersWithGenericReturnTypes-expected.txt b/ets2panda/test/parser/ets/OptionalParametersWithGenericReturnTypes-expected.txt index 4830da9f97..ecafbddd82 100644 --- a/ets2panda/test/parser/ets/OptionalParametersWithGenericReturnTypes-expected.txt +++ b/ets2panda/test/parser/ets/OptionalParametersWithGenericReturnTypes-expected.txt @@ -1166,40 +1166,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "OptionalParametersWithGenericReturnTypes.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "OptionalParametersWithGenericReturnTypes.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "OptionalParametersWithGenericReturnTypes.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "OptionalParametersWithGenericReturnTypes.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/StaticFieldAndMethodSameName-expected.txt b/ets2panda/test/parser/ets/StaticFieldAndMethodSameName-expected.txt index aee7dd9541..8f31f8f169 100644 --- a/ets2panda/test/parser/ets/StaticFieldAndMethodSameName-expected.txt +++ b/ets2panda/test/parser/ets/StaticFieldAndMethodSameName-expected.txt @@ -402,40 +402,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "StaticFieldAndMethodSameName.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "StaticFieldAndMethodSameName.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "StaticFieldAndMethodSameName.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "StaticFieldAndMethodSameName.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/StaticFieldAndMethodSameNameInheritance-expected.txt b/ets2panda/test/parser/ets/StaticFieldAndMethodSameNameInheritance-expected.txt index 924fb2a4a7..25d1ccb545 100644 --- a/ets2panda/test/parser/ets/StaticFieldAndMethodSameNameInheritance-expected.txt +++ b/ets2panda/test/parser/ets/StaticFieldAndMethodSameNameInheritance-expected.txt @@ -603,40 +603,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "StaticFieldAndMethodSameNameInheritance.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "StaticFieldAndMethodSameNameInheritance.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "StaticFieldAndMethodSameNameInheritance.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "StaticFieldAndMethodSameNameInheritance.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/StringBase64-expected.txt b/ets2panda/test/parser/ets/StringBase64-expected.txt index 9fb9ae9198..05a3ec5df1 100644 --- a/ets2panda/test/parser/ets/StringBase64-expected.txt +++ b/ets2panda/test/parser/ets/StringBase64-expected.txt @@ -11233,40 +11233,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "StringBase64.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "StringBase64.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "StringBase64.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "StringBase64.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/access_modifier_2-expected.txt b/ets2panda/test/parser/ets/access_modifier_2-expected.txt index 07b91f6b1f..156dc7a974 100644 --- a/ets2panda/test/parser/ets/access_modifier_2-expected.txt +++ b/ets2panda/test/parser/ets/access_modifier_2-expected.txt @@ -299,40 +299,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "access_modifier_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "access_modifier_2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "access_modifier_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "access_modifier_2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/access_modifier_3-expected.txt b/ets2panda/test/parser/ets/access_modifier_3-expected.txt index f146650324..ece74807b3 100644 --- a/ets2panda/test/parser/ets/access_modifier_3-expected.txt +++ b/ets2panda/test/parser/ets/access_modifier_3-expected.txt @@ -233,40 +233,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "access_modifier_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "access_modifier_3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "access_modifier_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "access_modifier_3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/ambient_call_signature-expected.txt b/ets2panda/test/parser/ets/ambient_call_signature-expected.txt index 0255cc77e6..6b165ea86e 100644 --- a/ets2panda/test/parser/ets/ambient_call_signature-expected.txt +++ b/ets2panda/test/parser/ets/ambient_call_signature-expected.txt @@ -396,40 +396,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "ambient_call_signature.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "ambient_call_signature.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "ambient_call_signature.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "ambient_call_signature.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/ambient_declaration_final_class-expected.txt b/ets2panda/test/parser/ets/ambient_declaration_final_class-expected.txt index 7cd7a29100..ade760ffa5 100644 --- a/ets2panda/test/parser/ets/ambient_declaration_final_class-expected.txt +++ b/ets2panda/test/parser/ets/ambient_declaration_final_class-expected.txt @@ -178,40 +178,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "ambient_declaration_final_class.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "ambient_declaration_final_class.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "ambient_declaration_final_class.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "ambient_declaration_final_class.ets" - } - } - } - ], "body": [], "loc": { "start": { diff --git a/ets2panda/test/parser/ets/ambient_indexer_1-expected.txt b/ets2panda/test/parser/ets/ambient_indexer_1-expected.txt index 6104cb85c6..a53827c724 100644 --- a/ets2panda/test/parser/ets/ambient_indexer_1-expected.txt +++ b/ets2panda/test/parser/ets/ambient_indexer_1-expected.txt @@ -661,40 +661,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "ambient_indexer_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "ambient_indexer_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "ambient_indexer_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "ambient_indexer_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/ambient_indexer_6-expected.txt b/ets2panda/test/parser/ets/ambient_indexer_6-expected.txt index 8935451bd1..030e8a4584 100644 --- a/ets2panda/test/parser/ets/ambient_indexer_6-expected.txt +++ b/ets2panda/test/parser/ets/ambient_indexer_6-expected.txt @@ -661,40 +661,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "ambient_indexer_6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "ambient_indexer_6.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "ambient_indexer_6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "ambient_indexer_6.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/ambient_object_iterable-expected.txt b/ets2panda/test/parser/ets/ambient_object_iterable-expected.txt index 7fce996934..9bb43d667e 100644 --- a/ets2panda/test/parser/ets/ambient_object_iterable-expected.txt +++ b/ets2panda/test/parser/ets/ambient_object_iterable-expected.txt @@ -1111,40 +1111,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "ambient_object_iterable.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "ambient_object_iterable.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "ambient_object_iterable.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "ambient_object_iterable.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/array-expected.txt b/ets2panda/test/parser/ets/array-expected.txt index d57d4dc542..53adeda6bd 100644 --- a/ets2panda/test/parser/ets/array-expected.txt +++ b/ets2panda/test/parser/ets/array-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "array.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "array.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "array.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "array.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/arrayHoldingNullValue-expected.txt b/ets2panda/test/parser/ets/arrayHoldingNullValue-expected.txt index 08e55a573e..dafbf1b908 100644 --- a/ets2panda/test/parser/ets/arrayHoldingNullValue-expected.txt +++ b/ets2panda/test/parser/ets/arrayHoldingNullValue-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "arrayHoldingNullValue.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "arrayHoldingNullValue.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "arrayHoldingNullValue.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "arrayHoldingNullValue.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/arrayLiteralReassign-expected.txt b/ets2panda/test/parser/ets/arrayLiteralReassign-expected.txt index 024597387e..a183381a4c 100644 --- a/ets2panda/test/parser/ets/arrayLiteralReassign-expected.txt +++ b/ets2panda/test/parser/ets/arrayLiteralReassign-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "arrayLiteralReassign.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "arrayLiteralReassign.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "arrayLiteralReassign.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "arrayLiteralReassign.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/array_creation_expression-expected.txt b/ets2panda/test/parser/ets/array_creation_expression-expected.txt index 955a33169f..aba5881ca7 100644 --- a/ets2panda/test/parser/ets/array_creation_expression-expected.txt +++ b/ets2panda/test/parser/ets/array_creation_expression-expected.txt @@ -1067,40 +1067,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "array_creation_expression.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "array_creation_expression.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "array_creation_expression.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "array_creation_expression.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/array_expression_implicit_cast_assignment-expected.txt b/ets2panda/test/parser/ets/array_expression_implicit_cast_assignment-expected.txt index 88b2c7ce74..8bf12dce66 100644 --- a/ets2panda/test/parser/ets/array_expression_implicit_cast_assignment-expected.txt +++ b/ets2panda/test/parser/ets/array_expression_implicit_cast_assignment-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "array_expression_implicit_cast_assignment.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "array_expression_implicit_cast_assignment.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "array_expression_implicit_cast_assignment.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "array_expression_implicit_cast_assignment.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/array_expression_implicit_cast_return-expected.txt b/ets2panda/test/parser/ets/array_expression_implicit_cast_return-expected.txt index 2f7b424caa..3dfc86e4c0 100644 --- a/ets2panda/test/parser/ets/array_expression_implicit_cast_return-expected.txt +++ b/ets2panda/test/parser/ets/array_expression_implicit_cast_return-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "array_expression_implicit_cast_return.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "array_expression_implicit_cast_return.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "array_expression_implicit_cast_return.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "array_expression_implicit_cast_return.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/array_new-expected.txt b/ets2panda/test/parser/ets/array_new-expected.txt index f2e90749f3..e14e6cf7b6 100644 --- a/ets2panda/test/parser/ets/array_new-expected.txt +++ b/ets2panda/test/parser/ets/array_new-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "array_new.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "array_new.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "array_new.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "array_new.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/array_type_from_literal-expected.txt b/ets2panda/test/parser/ets/array_type_from_literal-expected.txt index f8cba5ad25..551a2ad27d 100644 --- a/ets2panda/test/parser/ets/array_type_from_literal-expected.txt +++ b/ets2panda/test/parser/ets/array_type_from_literal-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "array_type_from_literal.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "array_type_from_literal.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "array_type_from_literal.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "array_type_from_literal.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/as_expression_unary_expression-expected.txt b/ets2panda/test/parser/ets/as_expression_unary_expression-expected.txt index 9d30970a18..b375b4963c 100644 --- a/ets2panda/test/parser/ets/as_expression_unary_expression-expected.txt +++ b/ets2panda/test/parser/ets/as_expression_unary_expression-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "as_expression_unary_expression.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "as_expression_unary_expression.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "as_expression_unary_expression.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "as_expression_unary_expression.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/assert-expected.txt b/ets2panda/test/parser/ets/assert-expected.txt index 9a00f8d011..223e74ab3f 100644 --- a/ets2panda/test/parser/ets/assert-expected.txt +++ b/ets2panda/test/parser/ets/assert-expected.txt @@ -874,40 +874,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "assert.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "assert.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "assert.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "assert.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/assign-expected.txt b/ets2panda/test/parser/ets/assign-expected.txt index 85e07ada0f..b6142a4897 100644 --- a/ets2panda/test/parser/ets/assign-expected.txt +++ b/ets2panda/test/parser/ets/assign-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "assign.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "assign.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "assign.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "assign.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/assign-func-expected.txt b/ets2panda/test/parser/ets/assign-func-expected.txt index dfcdb8f1d7..0f098d527b 100644 --- a/ets2panda/test/parser/ets/assign-func-expected.txt +++ b/ets2panda/test/parser/ets/assign-func-expected.txt @@ -412,40 +412,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "assign-func.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "assign-func.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "assign-func.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "assign-func.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/assignNullableFromMethodToNullableParam-expected.txt b/ets2panda/test/parser/ets/assignNullableFromMethodToNullableParam-expected.txt index 9ef19b1918..bd4085763f 100644 --- a/ets2panda/test/parser/ets/assignNullableFromMethodToNullableParam-expected.txt +++ b/ets2panda/test/parser/ets/assignNullableFromMethodToNullableParam-expected.txt @@ -442,40 +442,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "assignNullableFromMethodToNullableParam.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "assignNullableFromMethodToNullableParam.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "assignNullableFromMethodToNullableParam.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "assignNullableFromMethodToNullableParam.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/assignNullableToNonNullable-expected.txt b/ets2panda/test/parser/ets/assignNullableToNonNullable-expected.txt index cc83a876d5..ef02e1816a 100644 --- a/ets2panda/test/parser/ets/assignNullableToNonNullable-expected.txt +++ b/ets2panda/test/parser/ets/assignNullableToNonNullable-expected.txt @@ -178,40 +178,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "assignNullableToNonNullable.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "assignNullableToNonNullable.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "assignNullableToNonNullable.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "assignNullableToNonNullable.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/assignNullableToNonNullableArray-expected.txt b/ets2panda/test/parser/ets/assignNullableToNonNullableArray-expected.txt index 639443b444..d9a354f514 100644 --- a/ets2panda/test/parser/ets/assignNullableToNonNullableArray-expected.txt +++ b/ets2panda/test/parser/ets/assignNullableToNonNullableArray-expected.txt @@ -178,40 +178,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "assignNullableToNonNullableArray.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "assignNullableToNonNullableArray.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "assignNullableToNonNullableArray.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "assignNullableToNonNullableArray.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/assignNullableToNonNullableTypeAlias-expected.txt b/ets2panda/test/parser/ets/assignNullableToNonNullableTypeAlias-expected.txt index 8e612c173f..3d1ab2fb66 100644 --- a/ets2panda/test/parser/ets/assignNullableToNonNullableTypeAlias-expected.txt +++ b/ets2panda/test/parser/ets/assignNullableToNonNullableTypeAlias-expected.txt @@ -289,40 +289,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "assignNullableToNonNullableTypeAlias.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "assignNullableToNonNullableTypeAlias.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "assignNullableToNonNullableTypeAlias.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "assignNullableToNonNullableTypeAlias.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/assignments-expected.txt b/ets2panda/test/parser/ets/assignments-expected.txt index 61c0fc0d7b..960e551480 100644 --- a/ets2panda/test/parser/ets/assignments-expected.txt +++ b/ets2panda/test/parser/ets/assignments-expected.txt @@ -1915,40 +1915,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "assignments.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "assignments.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "assignments.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "assignments.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/async_func_return_type-expected.txt b/ets2panda/test/parser/ets/async_func_return_type-expected.txt index 5f7abf1a05..8124a42ce8 100644 --- a/ets2panda/test/parser/ets/async_func_return_type-expected.txt +++ b/ets2panda/test/parser/ets/async_func_return_type-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "async_func_return_type.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "async_func_return_type.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "async_func_return_type.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "async_func_return_type.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/async_function-expected.txt b/ets2panda/test/parser/ets/async_function-expected.txt index f15275ce2f..c1469202d4 100644 --- a/ets2panda/test/parser/ets/async_function-expected.txt +++ b/ets2panda/test/parser/ets/async_function-expected.txt @@ -459,40 +459,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "async_function.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "async_function.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "async_function.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "async_function.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/async_overload-expected.txt b/ets2panda/test/parser/ets/async_overload-expected.txt index d2764377ea..59d04c9e13 100644 --- a/ets2panda/test/parser/ets/async_overload-expected.txt +++ b/ets2panda/test/parser/ets/async_overload-expected.txt @@ -916,40 +916,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "async_overload.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "async_overload.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "async_overload.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "async_overload.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/async_with_lambda-expected.txt b/ets2panda/test/parser/ets/async_with_lambda-expected.txt index f22d63d617..caaaa0ae22 100644 --- a/ets2panda/test/parser/ets/async_with_lambda-expected.txt +++ b/ets2panda/test/parser/ets/async_with_lambda-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "async_with_lambda.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "async_with_lambda.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "async_with_lambda.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "async_with_lambda.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/await_complex_promise-expected.txt b/ets2panda/test/parser/ets/await_complex_promise-expected.txt index a5561197f6..3b622031da 100644 --- a/ets2panda/test/parser/ets/await_complex_promise-expected.txt +++ b/ets2panda/test/parser/ets/await_complex_promise-expected.txt @@ -230,40 +230,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "await_complex_promise.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "await_complex_promise.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "await_complex_promise.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "await_complex_promise.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/await_keyword-expected.txt b/ets2panda/test/parser/ets/await_keyword-expected.txt index ec35251add..561f3d03fa 100644 --- a/ets2panda/test/parser/ets/await_keyword-expected.txt +++ b/ets2panda/test/parser/ets/await_keyword-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "await_keyword.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "await_keyword.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "await_keyword.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "await_keyword.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/binary_op-expected.txt b/ets2panda/test/parser/ets/binary_op-expected.txt index 182ab2004d..6ee5608b7e 100644 --- a/ets2panda/test/parser/ets/binary_op-expected.txt +++ b/ets2panda/test/parser/ets/binary_op-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "binary_op.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "binary_op.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "binary_op.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "binary_op.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/binary_operations-expected.txt b/ets2panda/test/parser/ets/binary_operations-expected.txt index 501839d4f5..b720e56330 100644 --- a/ets2panda/test/parser/ets/binary_operations-expected.txt +++ b/ets2panda/test/parser/ets/binary_operations-expected.txt @@ -3098,40 +3098,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "binary_operations.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "binary_operations.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "binary_operations.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "binary_operations.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/blocks-expected.txt b/ets2panda/test/parser/ets/blocks-expected.txt index c60b758011..8e49225a66 100644 --- a/ets2panda/test/parser/ets/blocks-expected.txt +++ b/ets2panda/test/parser/ets/blocks-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "blocks.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "blocks.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "blocks.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "blocks.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/blocks_scopes-expected.txt b/ets2panda/test/parser/ets/blocks_scopes-expected.txt index 976de9c02d..e2b72d6192 100644 --- a/ets2panda/test/parser/ets/blocks_scopes-expected.txt +++ b/ets2panda/test/parser/ets/blocks_scopes-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "blocks_scopes.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "blocks_scopes.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "blocks_scopes.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "blocks_scopes.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/boolean-expected.txt b/ets2panda/test/parser/ets/boolean-expected.txt index ed1ac1e8b3..152eb7b11c 100644 --- a/ets2panda/test/parser/ets/boolean-expected.txt +++ b/ets2panda/test/parser/ets/boolean-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "boolean.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "boolean.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "boolean.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "boolean.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/boolean_cond-expected.txt b/ets2panda/test/parser/ets/boolean_cond-expected.txt index e75cfcb4e9..5ede97c316 100644 --- a/ets2panda/test/parser/ets/boolean_cond-expected.txt +++ b/ets2panda/test/parser/ets/boolean_cond-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "boolean_cond.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "boolean_cond.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "boolean_cond.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "boolean_cond.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/boolean_default-expected.txt b/ets2panda/test/parser/ets/boolean_default-expected.txt index 85bb67456c..fe91f0889b 100644 --- a/ets2panda/test/parser/ets/boolean_default-expected.txt +++ b/ets2panda/test/parser/ets/boolean_default-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "boolean_default.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "boolean_default.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "boolean_default.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "boolean_default.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/break-expected.txt b/ets2panda/test/parser/ets/break-expected.txt index 217ae2e60a..894613545d 100644 --- a/ets2panda/test/parser/ets/break-expected.txt +++ b/ets2panda/test/parser/ets/break-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "break.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "break.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "break.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "break.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/callFunctionWithNullableParam-expected.txt b/ets2panda/test/parser/ets/callFunctionWithNullableParam-expected.txt index db60226adc..c7299e7b67 100644 --- a/ets2panda/test/parser/ets/callFunctionWithNullableParam-expected.txt +++ b/ets2panda/test/parser/ets/callFunctionWithNullableParam-expected.txt @@ -178,40 +178,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "callFunctionWithNullableParam.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "callFunctionWithNullableParam.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "callFunctionWithNullableParam.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "callFunctionWithNullableParam.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/callInterfaceMethodWithNullableParam-expected.txt b/ets2panda/test/parser/ets/callInterfaceMethodWithNullableParam-expected.txt index 220683963f..9fdfdd0562 100644 --- a/ets2panda/test/parser/ets/callInterfaceMethodWithNullableParam-expected.txt +++ b/ets2panda/test/parser/ets/callInterfaceMethodWithNullableParam-expected.txt @@ -677,40 +677,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "callInterfaceMethodWithNullableParam.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "callInterfaceMethodWithNullableParam.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "callInterfaceMethodWithNullableParam.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "callInterfaceMethodWithNullableParam.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/callMethodWithNullableParam-expected.txt b/ets2panda/test/parser/ets/callMethodWithNullableParam-expected.txt index 1ffa1c5ad4..bde159a6ec 100644 --- a/ets2panda/test/parser/ets/callMethodWithNullableParam-expected.txt +++ b/ets2panda/test/parser/ets/callMethodWithNullableParam-expected.txt @@ -379,40 +379,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "callMethodWithNullableParam.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "callMethodWithNullableParam.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "callMethodWithNullableParam.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "callMethodWithNullableParam.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/calling_superclass_methods-expected.txt b/ets2panda/test/parser/ets/calling_superclass_methods-expected.txt index 04c13cd665..230b38802f 100644 --- a/ets2panda/test/parser/ets/calling_superclass_methods-expected.txt +++ b/ets2panda/test/parser/ets/calling_superclass_methods-expected.txt @@ -688,40 +688,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "calling_superclass_methods.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "calling_superclass_methods.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "calling_superclass_methods.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "calling_superclass_methods.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/cast_const_union-expected.txt b/ets2panda/test/parser/ets/cast_const_union-expected.txt index 4f62838db3..50812cab20 100644 --- a/ets2panda/test/parser/ets/cast_const_union-expected.txt +++ b/ets2panda/test/parser/ets/cast_const_union-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "cast_const_union.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "cast_const_union.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "cast_const_union.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "cast_const_union.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/cast_expressions-expected.txt b/ets2panda/test/parser/ets/cast_expressions-expected.txt index ebd04d05f6..c7ca64e2b7 100644 --- a/ets2panda/test/parser/ets/cast_expressions-expected.txt +++ b/ets2panda/test/parser/ets/cast_expressions-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "cast_expressions.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "cast_expressions.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "cast_expressions.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "cast_expressions.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/cast_expressions3-expected.txt b/ets2panda/test/parser/ets/cast_expressions3-expected.txt index c103271b9d..9f0475e40e 100644 --- a/ets2panda/test/parser/ets/cast_expressions3-expected.txt +++ b/ets2panda/test/parser/ets/cast_expressions3-expected.txt @@ -692,40 +692,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "cast_expressions3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "cast_expressions3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "cast_expressions3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "cast_expressions3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/cast_expressions4-expected.txt b/ets2panda/test/parser/ets/cast_expressions4-expected.txt index 432388c975..abe24eaa45 100644 --- a/ets2panda/test/parser/ets/cast_expressions4-expected.txt +++ b/ets2panda/test/parser/ets/cast_expressions4-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "cast_expressions4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "cast_expressions4.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "cast_expressions4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "cast_expressions4.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/cast_expressions5-expected.txt b/ets2panda/test/parser/ets/cast_expressions5-expected.txt index a3ff3f525f..bc09d5b685 100644 --- a/ets2panda/test/parser/ets/cast_expressions5-expected.txt +++ b/ets2panda/test/parser/ets/cast_expressions5-expected.txt @@ -670,40 +670,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "cast_expressions5.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "cast_expressions5.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "cast_expressions5.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "cast_expressions5.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/class_init-expected.txt b/ets2panda/test/parser/ets/class_init-expected.txt index e3875b6336..a3a99d1115 100644 --- a/ets2panda/test/parser/ets/class_init-expected.txt +++ b/ets2panda/test/parser/ets/class_init-expected.txt @@ -446,40 +446,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "class_init.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "class_init.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "class_init.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "class_init.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/class_instance-expected.txt b/ets2panda/test/parser/ets/class_instance-expected.txt index fe94ba7419..e8c78b56b7 100644 --- a/ets2panda/test/parser/ets/class_instance-expected.txt +++ b/ets2panda/test/parser/ets/class_instance-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "class_instance.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "class_instance.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "class_instance.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "class_instance.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/class_instance_creation-expected.txt b/ets2panda/test/parser/ets/class_instance_creation-expected.txt index 7bb44b9d66..e1b669124b 100644 --- a/ets2panda/test/parser/ets/class_instance_creation-expected.txt +++ b/ets2panda/test/parser/ets/class_instance_creation-expected.txt @@ -1067,40 +1067,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "class_instance_creation.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "class_instance_creation.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "class_instance_creation.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "class_instance_creation.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/class_instance_import_alias-expected.txt b/ets2panda/test/parser/ets/class_instance_import_alias-expected.txt index d65a8379f0..af67a5ec66 100644 --- a/ets2panda/test/parser/ets/class_instance_import_alias-expected.txt +++ b/ets2panda/test/parser/ets/class_instance_import_alias-expected.txt @@ -88,40 +88,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "class_instance_import_alias.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "class_instance_import_alias.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "class_instance_import_alias.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "class_instance_import_alias.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/class_instance_initializer-expected.txt b/ets2panda/test/parser/ets/class_instance_initializer-expected.txt index 75453bdb6d..e1b5d92d37 100644 --- a/ets2panda/test/parser/ets/class_instance_initializer-expected.txt +++ b/ets2panda/test/parser/ets/class_instance_initializer-expected.txt @@ -3431,40 +3431,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "class_instance_initializer.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "class_instance_initializer.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "class_instance_initializer.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "class_instance_initializer.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/class_interface_enum_only_top_level_4-expected.txt b/ets2panda/test/parser/ets/class_interface_enum_only_top_level_4-expected.txt index 93c7908003..877b11b3cb 100644 --- a/ets2panda/test/parser/ets/class_interface_enum_only_top_level_4-expected.txt +++ b/ets2panda/test/parser/ets/class_interface_enum_only_top_level_4-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "class_interface_enum_only_top_level_4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "class_interface_enum_only_top_level_4.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "class_interface_enum_only_top_level_4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "class_interface_enum_only_top_level_4.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/class_static_initializer-expected.txt b/ets2panda/test/parser/ets/class_static_initializer-expected.txt index eca9102e00..524a1ac1b9 100644 --- a/ets2panda/test/parser/ets/class_static_initializer-expected.txt +++ b/ets2panda/test/parser/ets/class_static_initializer-expected.txt @@ -795,40 +795,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "class_static_initializer.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "class_static_initializer.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "class_static_initializer.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "class_static_initializer.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/classes-expected.txt b/ets2panda/test/parser/ets/classes-expected.txt index 67f65f50c9..36eb887b8e 100644 --- a/ets2panda/test/parser/ets/classes-expected.txt +++ b/ets2panda/test/parser/ets/classes-expected.txt @@ -689,40 +689,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "classes.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "classes.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "classes.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "classes.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/comment_block-expected.txt b/ets2panda/test/parser/ets/comment_block-expected.txt index 8620d29ca4..5d584272a8 100644 --- a/ets2panda/test/parser/ets/comment_block-expected.txt +++ b/ets2panda/test/parser/ets/comment_block-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "comment_block.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "comment_block.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "comment_block.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "comment_block.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/comment_line-expected.txt b/ets2panda/test/parser/ets/comment_line-expected.txt index a0188b91f8..6359231213 100644 --- a/ets2panda/test/parser/ets/comment_line-expected.txt +++ b/ets2panda/test/parser/ets/comment_line-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "comment_line.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "comment_line.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "comment_line.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "comment_line.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/conditionalExpressionType-expected.txt b/ets2panda/test/parser/ets/conditionalExpressionType-expected.txt index e007a01361..5d2945240a 100644 --- a/ets2panda/test/parser/ets/conditionalExpressionType-expected.txt +++ b/ets2panda/test/parser/ets/conditionalExpressionType-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "conditionalExpressionType.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "conditionalExpressionType.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "conditionalExpressionType.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "conditionalExpressionType.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/const-expected.txt b/ets2panda/test/parser/ets/const-expected.txt index 9035ac6def..d4eb5c420c 100644 --- a/ets2panda/test/parser/ets/const-expected.txt +++ b/ets2panda/test/parser/ets/const-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "const.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "const.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "const.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "const.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/constructorThrowsRethrows-expected.txt b/ets2panda/test/parser/ets/constructorThrowsRethrows-expected.txt index 8a0a76080c..b4ef5220f5 100644 --- a/ets2panda/test/parser/ets/constructorThrowsRethrows-expected.txt +++ b/ets2panda/test/parser/ets/constructorThrowsRethrows-expected.txt @@ -497,40 +497,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "constructorThrowsRethrows.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "constructorThrowsRethrows.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "constructorThrowsRethrows.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "constructorThrowsRethrows.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/constructor_super_call1-expected.txt b/ets2panda/test/parser/ets/constructor_super_call1-expected.txt index 49cebe990c..a4bad5265d 100644 --- a/ets2panda/test/parser/ets/constructor_super_call1-expected.txt +++ b/ets2panda/test/parser/ets/constructor_super_call1-expected.txt @@ -715,40 +715,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "constructor_super_call1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "constructor_super_call1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "constructor_super_call1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "constructor_super_call1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/constructor_super_call3-expected.txt b/ets2panda/test/parser/ets/constructor_super_call3-expected.txt index 69aca95035..2f33fcc0e0 100644 --- a/ets2panda/test/parser/ets/constructor_super_call3-expected.txt +++ b/ets2panda/test/parser/ets/constructor_super_call3-expected.txt @@ -429,40 +429,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "constructor_super_call3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "constructor_super_call3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "constructor_super_call3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "constructor_super_call3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/constructor_test-expected.txt b/ets2panda/test/parser/ets/constructor_test-expected.txt index e5a14152e5..1f51245e9f 100644 --- a/ets2panda/test/parser/ets/constructor_test-expected.txt +++ b/ets2panda/test/parser/ets/constructor_test-expected.txt @@ -1167,40 +1167,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "constructor_test.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "constructor_test.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "constructor_test.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "constructor_test.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/constructor_with_optional_parameter-expected.txt b/ets2panda/test/parser/ets/constructor_with_optional_parameter-expected.txt index bc89510f7d..abe99b5e5c 100644 --- a/ets2panda/test/parser/ets/constructor_with_optional_parameter-expected.txt +++ b/ets2panda/test/parser/ets/constructor_with_optional_parameter-expected.txt @@ -576,40 +576,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "constructor_with_optional_parameter.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "constructor_with_optional_parameter.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "constructor_with_optional_parameter.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "constructor_with_optional_parameter.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/constructor_with_return_2-expected.txt b/ets2panda/test/parser/ets/constructor_with_return_2-expected.txt index 4e37776ca0..362d6bee8a 100644 --- a/ets2panda/test/parser/ets/constructor_with_return_2-expected.txt +++ b/ets2panda/test/parser/ets/constructor_with_return_2-expected.txt @@ -347,40 +347,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "constructor_with_return_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "constructor_with_return_2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "constructor_with_return_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "constructor_with_return_2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/continue-expected.txt b/ets2panda/test/parser/ets/continue-expected.txt index 3d3529d13a..f6b62c2104 100644 --- a/ets2panda/test/parser/ets/continue-expected.txt +++ b/ets2panda/test/parser/ets/continue-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "continue.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "continue.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "continue.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "continue.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/conversions-expected.txt b/ets2panda/test/parser/ets/conversions-expected.txt index 04933dbb3f..de9e873fde 100644 --- a/ets2panda/test/parser/ets/conversions-expected.txt +++ b/ets2panda/test/parser/ets/conversions-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "conversions.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "conversions.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "conversions.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "conversions.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/decl_infer-expected.txt b/ets2panda/test/parser/ets/decl_infer-expected.txt index 17e4f40df0..d019542239 100644 --- a/ets2panda/test/parser/ets/decl_infer-expected.txt +++ b/ets2panda/test/parser/ets/decl_infer-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "decl_infer.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "decl_infer.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "decl_infer.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "decl_infer.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/declare_ambient_const_variable-expected.txt b/ets2panda/test/parser/ets/declare_ambient_const_variable-expected.txt index 74f8366f6c..823de09dd3 100644 --- a/ets2panda/test/parser/ets/declare_ambient_const_variable-expected.txt +++ b/ets2panda/test/parser/ets/declare_ambient_const_variable-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "declare_ambient_const_variable.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "declare_ambient_const_variable.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "declare_ambient_const_variable.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "declare_ambient_const_variable.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/declare_class-expected.txt b/ets2panda/test/parser/ets/declare_class-expected.txt index b75400f8b1..0021db53e2 100644 --- a/ets2panda/test/parser/ets/declare_class-expected.txt +++ b/ets2panda/test/parser/ets/declare_class-expected.txt @@ -660,40 +660,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "declare_class.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "declare_class.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "declare_class.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "declare_class.ets" - } - } - } - ], "body": [], "loc": { "start": { diff --git a/ets2panda/test/parser/ets/declare_enum-expected.txt b/ets2panda/test/parser/ets/declare_enum-expected.txt index e2aaf71412..49e9b1c524 100644 --- a/ets2panda/test/parser/ets/declare_enum-expected.txt +++ b/ets2panda/test/parser/ets/declare_enum-expected.txt @@ -2624,40 +2624,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "declare_enum.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "declare_enum.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "declare_enum.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "declare_enum.ets" - } - } - } - ], "body": [], "loc": { "start": { diff --git a/ets2panda/test/parser/ets/declare_func-expected.txt b/ets2panda/test/parser/ets/declare_func-expected.txt index 8a0b75ddac..90ec31f3de 100644 --- a/ets2panda/test/parser/ets/declare_func-expected.txt +++ b/ets2panda/test/parser/ets/declare_func-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "declare_func.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "declare_func.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "declare_func.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "declare_func.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/declare_iface-expected.txt b/ets2panda/test/parser/ets/declare_iface-expected.txt index d64dcbbb71..6b06a3207e 100644 --- a/ets2panda/test/parser/ets/declare_iface-expected.txt +++ b/ets2panda/test/parser/ets/declare_iface-expected.txt @@ -721,40 +721,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "declare_iface.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "declare_iface.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "declare_iface.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "declare_iface.ets" - } - } - } - ], "body": [], "loc": { "start": { diff --git a/ets2panda/test/parser/ets/default_parameter10-expected.txt b/ets2panda/test/parser/ets/default_parameter10-expected.txt index 957d925677..d83e99d04d 100644 --- a/ets2panda/test/parser/ets/default_parameter10-expected.txt +++ b/ets2panda/test/parser/ets/default_parameter10-expected.txt @@ -410,40 +410,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "default_parameter10.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "default_parameter10.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "default_parameter10.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "default_parameter10.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/default_parameter5-expected.txt b/ets2panda/test/parser/ets/default_parameter5-expected.txt index 800988f4c6..9ab9f2a7d4 100644 --- a/ets2panda/test/parser/ets/default_parameter5-expected.txt +++ b/ets2panda/test/parser/ets/default_parameter5-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "default_parameter5.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "default_parameter5.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "default_parameter5.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "default_parameter5.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/default_parameter7-expected.txt b/ets2panda/test/parser/ets/default_parameter7-expected.txt index ce02eae678..26b683a46f 100644 --- a/ets2panda/test/parser/ets/default_parameter7-expected.txt +++ b/ets2panda/test/parser/ets/default_parameter7-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "default_parameter7.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "default_parameter7.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "default_parameter7.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "default_parameter7.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/default_parameter8-expected.txt b/ets2panda/test/parser/ets/default_parameter8-expected.txt index c4893d75e6..ec5ead42f2 100644 --- a/ets2panda/test/parser/ets/default_parameter8-expected.txt +++ b/ets2panda/test/parser/ets/default_parameter8-expected.txt @@ -2568,40 +2568,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "default_parameter8.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "default_parameter8.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "default_parameter8.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "default_parameter8.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/default_parameter9-expected.txt b/ets2panda/test/parser/ets/default_parameter9-expected.txt index 5fe716c005..6ad71697a7 100644 --- a/ets2panda/test/parser/ets/default_parameter9-expected.txt +++ b/ets2panda/test/parser/ets/default_parameter9-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "default_parameter9.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "default_parameter9.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "default_parameter9.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "default_parameter9.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/default_parameter_implicitly_typed_return_void-expected.txt b/ets2panda/test/parser/ets/default_parameter_implicitly_typed_return_void-expected.txt index 467ec02d0c..190b9c3fe6 100644 --- a/ets2panda/test/parser/ets/default_parameter_implicitly_typed_return_void-expected.txt +++ b/ets2panda/test/parser/ets/default_parameter_implicitly_typed_return_void-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "default_parameter_implicitly_typed_return_void.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "default_parameter_implicitly_typed_return_void.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "default_parameter_implicitly_typed_return_void.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "default_parameter_implicitly_typed_return_void.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/dynamic_import_tests/dynamic_decl_import-expected.txt b/ets2panda/test/parser/ets/dynamic_import_tests/dynamic_decl_import-expected.txt index 7f5a47d9e0..05fee0aa19 100644 --- a/ets2panda/test/parser/ets/dynamic_import_tests/dynamic_decl_import-expected.txt +++ b/ets2panda/test/parser/ets/dynamic_import_tests/dynamic_decl_import-expected.txt @@ -203,40 +203,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "dynamic_decl_import.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "dynamic_decl_import.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "dynamic_decl_import.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "dynamic_decl_import.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", @@ -1949,6 +1915,2742 @@ "program": "dynamic_decl_import.ets" } } + }, + { + "type": "ClassDeclaration", + "definition": { + "id": { + "type": "Identifier", + "name": "$jsnew", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "superClass": null, + "implements": [], + "body": [ + { + "type": "ClassProperty", + "key": { + "type": "Identifier", + "name": "qname_start_from", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "accessibility": "private", + "static": true, + "readonly": true, + "declare": false, + "optional": false, + "computed": false, + "typeAnnotation": { + "type": "ETSPrimitiveType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "definite": false, + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + { + "type": "ClassStaticBlock", + "value": { + "type": "FunctionExpression", + "function": { + "type": "ScriptFunction", + "id": { + "type": "Identifier", + "name": "", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "generator": false, + "async": false, + "expression": true, + "params": [], + "body": { + "type": "BlockStatement", + "statements": [ + { + "type": "ExpressionStatement", + "expression": { + "type": "CallExpression", + "callee": { + "type": "MemberExpression", + "object": { + "type": "Identifier", + "name": "JSRuntime", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "property": { + "type": "Identifier", + "name": "__initJSNewClass", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "computed": false, + "optional": false, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "arguments": [], + "optional": false, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + } + ], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + { + "type": "MethodDefinition", + "key": { + "type": "Identifier", + "name": "$_invoke", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "kind": "method", + "accessibility": "public", + "static": true, + "optional": false, + "computed": false, + "value": { + "type": "FunctionExpression", + "function": { + "type": "ScriptFunction", + "id": { + "type": "Identifier", + "name": "$_invoke", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "generator": false, + "async": false, + "expression": false, + "params": [ + { + "type": "ETSParameterExpression", + "name": { + "type": "Identifier", + "name": "obj", + "typeAnnotation": { + "type": "OpaqueType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + { + "type": "ETSParameterExpression", + "name": { + "type": "Identifier", + "name": "qname_start", + "typeAnnotation": { + "type": "ETSPrimitiveType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + { + "type": "ETSParameterExpression", + "name": { + "type": "Identifier", + "name": "qname_len", + "typeAnnotation": { + "type": "ETSPrimitiveType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + { + "type": "ETSParameterExpression", + "name": { + "type": "Identifier", + "name": "p0", + "typeAnnotation": { + "type": "OpaqueType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + { + "type": "ETSParameterExpression", + "name": { + "type": "Identifier", + "name": "p1", + "typeAnnotation": { + "type": "OpaqueType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + } + ], + "returnType": { + "type": "OpaqueType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "overloads": [], + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + } + ], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + { + "type": "ClassDeclaration", + "definition": { + "id": { + "type": "Identifier", + "name": "$jscall", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "superClass": null, + "implements": [], + "body": [ + { + "type": "ClassProperty", + "key": { + "type": "Identifier", + "name": "qname_start_from", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "accessibility": "private", + "static": true, + "readonly": true, + "declare": false, + "optional": false, + "computed": false, + "typeAnnotation": { + "type": "ETSPrimitiveType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "definite": false, + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + { + "type": "ClassStaticBlock", + "value": { + "type": "FunctionExpression", + "function": { + "type": "ScriptFunction", + "id": { + "type": "Identifier", + "name": "", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "generator": false, + "async": false, + "expression": true, + "params": [], + "body": { + "type": "BlockStatement", + "statements": [ + { + "type": "ExpressionStatement", + "expression": { + "type": "CallExpression", + "callee": { + "type": "MemberExpression", + "object": { + "type": "Identifier", + "name": "JSRuntime", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "property": { + "type": "Identifier", + "name": "__initJSCallClass", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "computed": false, + "optional": false, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "arguments": [], + "optional": false, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + } + ], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + { + "type": "MethodDefinition", + "key": { + "type": "Identifier", + "name": "$_invoke", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "kind": "method", + "accessibility": "public", + "static": true, + "optional": false, + "computed": false, + "value": { + "type": "FunctionExpression", + "function": { + "type": "ScriptFunction", + "id": { + "type": "Identifier", + "name": "$_invoke", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "generator": false, + "async": false, + "expression": false, + "params": [ + { + "type": "ETSParameterExpression", + "name": { + "type": "Identifier", + "name": "obj", + "typeAnnotation": { + "type": "OpaqueType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + { + "type": "ETSParameterExpression", + "name": { + "type": "Identifier", + "name": "qname_start", + "typeAnnotation": { + "type": "ETSPrimitiveType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + { + "type": "ETSParameterExpression", + "name": { + "type": "Identifier", + "name": "qname_len", + "typeAnnotation": { + "type": "ETSPrimitiveType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + { + "type": "ETSParameterExpression", + "name": { + "type": "Identifier", + "name": "p0", + "typeAnnotation": { + "type": "OpaqueType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + } + ], + "returnType": { + "type": "OpaqueType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "overloads": [ + { + "type": "MethodDefinition", + "key": { + "type": "Identifier", + "name": "$_invoke", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "kind": "method", + "accessibility": "public", + "static": true, + "optional": false, + "computed": false, + "value": { + "type": "FunctionExpression", + "function": { + "type": "ScriptFunction", + "id": { + "type": "Identifier", + "name": "$_invoke", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "generator": false, + "async": false, + "expression": false, + "params": [ + { + "type": "ETSParameterExpression", + "name": { + "type": "Identifier", + "name": "obj", + "typeAnnotation": { + "type": "OpaqueType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + { + "type": "ETSParameterExpression", + "name": { + "type": "Identifier", + "name": "qname_start", + "typeAnnotation": { + "type": "ETSPrimitiveType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + { + "type": "ETSParameterExpression", + "name": { + "type": "Identifier", + "name": "qname_len", + "typeAnnotation": { + "type": "ETSPrimitiveType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + } + ], + "returnType": { + "type": "OpaqueType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "overloads": [], + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + { + "type": "MethodDefinition", + "key": { + "type": "Identifier", + "name": "$_invoke", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "kind": "method", + "accessibility": "public", + "static": true, + "optional": false, + "computed": false, + "value": { + "type": "FunctionExpression", + "function": { + "type": "ScriptFunction", + "id": { + "type": "Identifier", + "name": "$_invoke", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "generator": false, + "async": false, + "expression": false, + "params": [ + { + "type": "ETSParameterExpression", + "name": { + "type": "Identifier", + "name": "obj", + "typeAnnotation": { + "type": "OpaqueType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + { + "type": "ETSParameterExpression", + "name": { + "type": "Identifier", + "name": "qname_start", + "typeAnnotation": { + "type": "ETSPrimitiveType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + { + "type": "ETSParameterExpression", + "name": { + "type": "Identifier", + "name": "qname_len", + "typeAnnotation": { + "type": "ETSPrimitiveType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + { + "type": "ETSParameterExpression", + "name": { + "type": "Identifier", + "name": "p0", + "typeAnnotation": { + "type": "OpaqueType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + } + ], + "returnType": { + "type": "OpaqueType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "overloads": [], + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + } + ], + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + { + "type": "MethodDefinition", + "key": { + "type": "Identifier", + "name": "$_invoke", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "kind": "method", + "accessibility": "public", + "static": true, + "optional": false, + "computed": false, + "value": { + "type": "FunctionExpression", + "function": { + "type": "ScriptFunction", + "id": { + "type": "Identifier", + "name": "$_invoke", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "generator": false, + "async": false, + "expression": false, + "params": [ + { + "type": "ETSParameterExpression", + "name": { + "type": "Identifier", + "name": "obj", + "typeAnnotation": { + "type": "OpaqueType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + { + "type": "ETSParameterExpression", + "name": { + "type": "Identifier", + "name": "qname_start", + "typeAnnotation": { + "type": "ETSPrimitiveType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + { + "type": "ETSParameterExpression", + "name": { + "type": "Identifier", + "name": "qname_len", + "typeAnnotation": { + "type": "ETSPrimitiveType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + } + ], + "returnType": { + "type": "OpaqueType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "overloads": [], + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + { + "type": "MethodDefinition", + "key": { + "type": "Identifier", + "name": "$_invoke", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "kind": "method", + "accessibility": "public", + "static": true, + "optional": false, + "computed": false, + "value": { + "type": "FunctionExpression", + "function": { + "type": "ScriptFunction", + "id": { + "type": "Identifier", + "name": "$_invoke", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "generator": false, + "async": false, + "expression": false, + "params": [ + { + "type": "ETSParameterExpression", + "name": { + "type": "Identifier", + "name": "obj", + "typeAnnotation": { + "type": "OpaqueType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + { + "type": "ETSParameterExpression", + "name": { + "type": "Identifier", + "name": "qname_start", + "typeAnnotation": { + "type": "ETSPrimitiveType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + { + "type": "ETSParameterExpression", + "name": { + "type": "Identifier", + "name": "qname_len", + "typeAnnotation": { + "type": "ETSPrimitiveType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + { + "type": "ETSParameterExpression", + "name": { + "type": "Identifier", + "name": "p0", + "typeAnnotation": { + "type": "OpaqueType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + } + ], + "returnType": { + "type": "OpaqueType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "overloads": [], + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + } + ], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + { + "type": "ClassDeclaration", + "definition": { + "id": { + "type": "Identifier", + "name": "$dynmodule", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "superClass": null, + "implements": [], + "body": [ + { + "type": "ClassProperty", + "key": { + "type": "Identifier", + "name": "dynamic_import_tests_modules_module0", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "accessibility": "public", + "static": true, + "readonly": true, + "declare": false, + "optional": false, + "computed": false, + "typeAnnotation": { + "type": "OpaqueType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "definite": false, + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + { + "type": "ClassStaticBlock", + "value": { + "type": "FunctionExpression", + "function": { + "type": "ScriptFunction", + "id": { + "type": "Identifier", + "name": "", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "generator": false, + "async": false, + "expression": true, + "params": [], + "body": { + "type": "BlockStatement", + "statements": [ + { + "type": "ExpressionStatement", + "expression": { + "type": "AssignmentExpression", + "operator": "=", + "left": { + "type": "MemberExpression", + "object": { + "type": "Identifier", + "name": "$dynmodule", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "property": { + "type": "Identifier", + "name": "dynamic_import_tests_modules_module0", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "computed": false, + "optional": false, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "right": { + "type": "CallExpression", + "callee": { + "type": "MemberExpression", + "object": { + "type": "Identifier", + "name": "JSRuntime", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "property": { + "type": "Identifier", + "name": "loadModule", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "computed": false, + "optional": false, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "arguments": [ + { + "type": "StringLiteral", + "value": "/home/anya/panda_reps/standalone_new/arkcompiler/runtime_core/static_core/tools/es2panda/test/parser/ets/dynamic_import_tests/modules/module.ets", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + } + ], + "optional": false, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + } + ], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + { + "type": "MethodDefinition", + "key": { + "type": "Identifier", + "name": "init", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "kind": "method", + "accessibility": "public", + "static": true, + "optional": false, + "computed": false, + "value": { + "type": "FunctionExpression", + "function": { + "type": "ScriptFunction", + "id": { + "type": "Identifier", + "name": "init", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "generator": false, + "async": false, + "expression": false, + "params": [], + "returnType": { + "type": "OpaqueType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "body": { + "type": "BlockStatement", + "statements": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "overloads": [], + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + } + ], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } } ], "loc": { diff --git a/ets2panda/test/parser/ets/dynamic_import_tests/dynamic_iface_decl_bad-expected.txt b/ets2panda/test/parser/ets/dynamic_import_tests/dynamic_iface_decl_bad-expected.txt index 0b8c775413..7bf0cdf315 100644 --- a/ets2panda/test/parser/ets/dynamic_import_tests/dynamic_iface_decl_bad-expected.txt +++ b/ets2panda/test/parser/ets/dynamic_import_tests/dynamic_iface_decl_bad-expected.txt @@ -105,40 +105,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "dynamic_iface_decl_bad.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "dynamic_iface_decl_bad.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "dynamic_iface_decl_bad.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "dynamic_iface_decl_bad.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", @@ -596,6 +562,482 @@ "program": "dynamic_iface_decl_bad.ets" } } + }, + { + "type": "ClassDeclaration", + "definition": { + "id": { + "type": "Identifier", + "name": "$dynmodule", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "superClass": null, + "implements": [], + "body": [ + { + "type": "ClassProperty", + "key": { + "type": "Identifier", + "name": "dynamic_import_tests_modules_module0", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "accessibility": "public", + "static": true, + "readonly": true, + "declare": false, + "optional": false, + "computed": false, + "typeAnnotation": { + "type": "OpaqueType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "definite": false, + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + { + "type": "ClassStaticBlock", + "value": { + "type": "FunctionExpression", + "function": { + "type": "ScriptFunction", + "id": { + "type": "Identifier", + "name": "", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "generator": false, + "async": false, + "expression": true, + "params": [], + "body": { + "type": "BlockStatement", + "statements": [ + { + "type": "ExpressionStatement", + "expression": { + "type": "AssignmentExpression", + "operator": "=", + "left": { + "type": "MemberExpression", + "object": { + "type": "Identifier", + "name": "$dynmodule", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "property": { + "type": "Identifier", + "name": "dynamic_import_tests_modules_module0", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "computed": false, + "optional": false, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "right": { + "type": "CallExpression", + "callee": { + "type": "MemberExpression", + "object": { + "type": "Identifier", + "name": "JSRuntime", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "property": { + "type": "Identifier", + "name": "loadModule", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "computed": false, + "optional": false, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "arguments": [ + { + "type": "StringLiteral", + "value": "/home/anya/panda_reps/standalone_new/arkcompiler/runtime_core/static_core/tools/es2panda/test/parser/ets/dynamic_import_tests/modules/module.ets", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + } + ], + "optional": false, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + } + ], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + { + "type": "MethodDefinition", + "key": { + "type": "Identifier", + "name": "init", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "kind": "method", + "accessibility": "public", + "static": true, + "optional": false, + "computed": false, + "value": { + "type": "FunctionExpression", + "function": { + "type": "ScriptFunction", + "id": { + "type": "Identifier", + "name": "init", + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "generator": false, + "async": false, + "expression": false, + "params": [], + "returnType": { + "type": "OpaqueType", + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "body": { + "type": "BlockStatement", + "statements": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "overloads": [], + "decorators": [], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + } + ], + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } + }, + "loc": { + "start": { + "line": 1, + "column": 1, + "program": null + }, + "end": { + "line": 1, + "column": 1, + "program": null + } + } } ], "loc": { diff --git a/ets2panda/test/parser/ets/dynamic_import_tests/dynamic_optional_decl-expected.txt b/ets2panda/test/parser/ets/dynamic_import_tests/dynamic_optional_decl-expected.txt index 81f8725d29..b15e5f1c09 100644 --- a/ets2panda/test/parser/ets/dynamic_import_tests/dynamic_optional_decl-expected.txt +++ b/ets2panda/test/parser/ets/dynamic_import_tests/dynamic_optional_decl-expected.txt @@ -154,40 +154,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "dynamic_optional_decl.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "dynamic_optional_decl.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "dynamic_optional_decl.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "dynamic_optional_decl.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/dynamic_import_tests/modules/instanceof-expected.txt b/ets2panda/test/parser/ets/dynamic_import_tests/modules/instanceof-expected.txt index bed3a52eba..0a0f28326b 100644 --- a/ets2panda/test/parser/ets/dynamic_import_tests/modules/instanceof-expected.txt +++ b/ets2panda/test/parser/ets/dynamic_import_tests/modules/instanceof-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "instanceof.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "instanceof.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "instanceof.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "instanceof.ets" - } - } - } - ], "body": [], "loc": { "start": { diff --git a/ets2panda/test/parser/ets/dynamic_import_tests/modules/module-expected.txt b/ets2panda/test/parser/ets/dynamic_import_tests/modules/module-expected.txt index ae27338c9c..2f142b5f61 100644 --- a/ets2panda/test/parser/ets/dynamic_import_tests/modules/module-expected.txt +++ b/ets2panda/test/parser/ets/dynamic_import_tests/modules/module-expected.txt @@ -1333,40 +1333,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "module.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "module.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "module.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "module.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/empty_class-expected.txt b/ets2panda/test/parser/ets/empty_class-expected.txt index 501ac546a7..f5870a749a 100644 --- a/ets2panda/test/parser/ets/empty_class-expected.txt +++ b/ets2panda/test/parser/ets/empty_class-expected.txt @@ -178,40 +178,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "empty_class.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "empty_class.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "empty_class.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "empty_class.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/empty_statement-expected.txt b/ets2panda/test/parser/ets/empty_statement-expected.txt index d3a0317f98..94c8bbdbc0 100644 --- a/ets2panda/test/parser/ets/empty_statement-expected.txt +++ b/ets2panda/test/parser/ets/empty_statement-expected.txt @@ -880,40 +880,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "empty_statement.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "empty_statement.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "empty_statement.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "empty_statement.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/exports-expected.txt b/ets2panda/test/parser/ets/exports-expected.txt index 47a122d24c..774017d3bb 100644 --- a/ets2panda/test/parser/ets/exports-expected.txt +++ b/ets2panda/test/parser/ets/exports-expected.txt @@ -274,40 +274,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "exports.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "exports.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "exports.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "exports.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/external_cyclic_constructor_check-expected.txt b/ets2panda/test/parser/ets/external_cyclic_constructor_check-expected.txt index 42a9c1d15d..4cee1d6d40 100644 --- a/ets2panda/test/parser/ets/external_cyclic_constructor_check-expected.txt +++ b/ets2panda/test/parser/ets/external_cyclic_constructor_check-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "external_cyclic_constructor_check.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "external_cyclic_constructor_check.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "external_cyclic_constructor_check.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "external_cyclic_constructor_check.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/field_decl-expected.txt b/ets2panda/test/parser/ets/field_decl-expected.txt index 7cf0822cd3..0ac292d2ba 100644 --- a/ets2panda/test/parser/ets/field_decl-expected.txt +++ b/ets2panda/test/parser/ets/field_decl-expected.txt @@ -753,40 +753,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "field_decl.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "field_decl.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "field_decl.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "field_decl.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/final_empty_class-expected.txt b/ets2panda/test/parser/ets/final_empty_class-expected.txt index 897ecc678f..81ad39aa37 100644 --- a/ets2panda/test/parser/ets/final_empty_class-expected.txt +++ b/ets2panda/test/parser/ets/final_empty_class-expected.txt @@ -178,40 +178,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "final_empty_class.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "final_empty_class.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "final_empty_class.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "final_empty_class.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/float_pont_format_1-expected.txt b/ets2panda/test/parser/ets/float_pont_format_1-expected.txt index 60b0bd89fd..8fe9b1e996 100644 --- a/ets2panda/test/parser/ets/float_pont_format_1-expected.txt +++ b/ets2panda/test/parser/ets/float_pont_format_1-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "float_pont_format_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "float_pont_format_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "float_pont_format_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "float_pont_format_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/float_pont_format_2-expected.txt b/ets2panda/test/parser/ets/float_pont_format_2-expected.txt index 998ce94b76..850d7b2cc2 100644 --- a/ets2panda/test/parser/ets/float_pont_format_2-expected.txt +++ b/ets2panda/test/parser/ets/float_pont_format_2-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "float_pont_format_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "float_pont_format_2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "float_pont_format_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "float_pont_format_2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/float_pont_format_3-expected.txt b/ets2panda/test/parser/ets/float_pont_format_3-expected.txt index 34b202049a..21d98fea12 100644 --- a/ets2panda/test/parser/ets/float_pont_format_3-expected.txt +++ b/ets2panda/test/parser/ets/float_pont_format_3-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "float_pont_format_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "float_pont_format_3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "float_pont_format_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "float_pont_format_3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/float_pont_format_4-expected.txt b/ets2panda/test/parser/ets/float_pont_format_4-expected.txt index 3cb0db5383..db9f5816e9 100644 --- a/ets2panda/test/parser/ets/float_pont_format_4-expected.txt +++ b/ets2panda/test/parser/ets/float_pont_format_4-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "float_pont_format_4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "float_pont_format_4.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "float_pont_format_4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "float_pont_format_4.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/float_pont_format_5-expected.txt b/ets2panda/test/parser/ets/float_pont_format_5-expected.txt index 8c5622f4b6..5624b9cbb9 100644 --- a/ets2panda/test/parser/ets/float_pont_format_5-expected.txt +++ b/ets2panda/test/parser/ets/float_pont_format_5-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "float_pont_format_5.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "float_pont_format_5.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "float_pont_format_5.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "float_pont_format_5.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/float_pont_format_6-expected.txt b/ets2panda/test/parser/ets/float_pont_format_6-expected.txt index 28bc0ec2a7..3a786d9c44 100644 --- a/ets2panda/test/parser/ets/float_pont_format_6-expected.txt +++ b/ets2panda/test/parser/ets/float_pont_format_6-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "float_pont_format_6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "float_pont_format_6.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "float_pont_format_6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "float_pont_format_6.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/float_pont_format_7-expected.txt b/ets2panda/test/parser/ets/float_pont_format_7-expected.txt index 8919c9b1c7..a913834768 100644 --- a/ets2panda/test/parser/ets/float_pont_format_7-expected.txt +++ b/ets2panda/test/parser/ets/float_pont_format_7-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "float_pont_format_7.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "float_pont_format_7.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "float_pont_format_7.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "float_pont_format_7.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/float_pont_format_8-expected.txt b/ets2panda/test/parser/ets/float_pont_format_8-expected.txt index a9670bf902..f492de68b9 100644 --- a/ets2panda/test/parser/ets/float_pont_format_8-expected.txt +++ b/ets2panda/test/parser/ets/float_pont_format_8-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "float_pont_format_8.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "float_pont_format_8.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "float_pont_format_8.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "float_pont_format_8.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/float_separator_1-expected.txt b/ets2panda/test/parser/ets/float_separator_1-expected.txt index ab9bbcb38c..6457c93362 100644 --- a/ets2panda/test/parser/ets/float_separator_1-expected.txt +++ b/ets2panda/test/parser/ets/float_separator_1-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "float_separator_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "float_separator_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "float_separator_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "float_separator_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/folder_import_index/index-expected.txt b/ets2panda/test/parser/ets/folder_import_index/index-expected.txt index 84d59f60fd..785feb50d8 100644 --- a/ets2panda/test/parser/ets/folder_import_index/index-expected.txt +++ b/ets2panda/test/parser/ets/folder_import_index/index-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "index.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "index.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "index.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "index.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/for_of-expected.txt b/ets2panda/test/parser/ets/for_of-expected.txt index 7339c6f997..296002c190 100644 --- a/ets2panda/test/parser/ets/for_of-expected.txt +++ b/ets2panda/test/parser/ets/for_of-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "for_of.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "for_of.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "for_of.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "for_of.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/for_with_break-expected.txt b/ets2panda/test/parser/ets/for_with_break-expected.txt index 4bae476c1d..25c3039b12 100644 --- a/ets2panda/test/parser/ets/for_with_break-expected.txt +++ b/ets2panda/test/parser/ets/for_with_break-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "for_with_break.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "for_with_break.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "for_with_break.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "for_with_break.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/forofUnboxing-expected.txt b/ets2panda/test/parser/ets/forofUnboxing-expected.txt index f0c300e6f1..94bc987884 100644 --- a/ets2panda/test/parser/ets/forofUnboxing-expected.txt +++ b/ets2panda/test/parser/ets/forofUnboxing-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "forofUnboxing.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "forofUnboxing.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "forofUnboxing.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "forofUnboxing.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/funcParamWithOptionalParam-expected.txt b/ets2panda/test/parser/ets/funcParamWithOptionalParam-expected.txt index 9dbf22528a..edab393734 100644 --- a/ets2panda/test/parser/ets/funcParamWithOptionalParam-expected.txt +++ b/ets2panda/test/parser/ets/funcParamWithOptionalParam-expected.txt @@ -290,40 +290,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "funcParamWithOptionalParam.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "funcParamWithOptionalParam.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "funcParamWithOptionalParam.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "funcParamWithOptionalParam.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/function-expected.txt b/ets2panda/test/parser/ets/function-expected.txt index 9868a88112..eb48d84352 100644 --- a/ets2panda/test/parser/ets/function-expected.txt +++ b/ets2panda/test/parser/ets/function-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "function.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "function.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "function.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "function.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/functionThrowsRethrows-expected.txt b/ets2panda/test/parser/ets/functionThrowsRethrows-expected.txt index 0120cbfd93..4d1c381ee1 100644 --- a/ets2panda/test/parser/ets/functionThrowsRethrows-expected.txt +++ b/ets2panda/test/parser/ets/functionThrowsRethrows-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "functionThrowsRethrows.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "functionThrowsRethrows.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/functionTypeThrows-expected.txt b/ets2panda/test/parser/ets/functionTypeThrows-expected.txt index 3bd94bd73b..072678965d 100644 --- a/ets2panda/test/parser/ets/functionTypeThrows-expected.txt +++ b/ets2panda/test/parser/ets/functionTypeThrows-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "functionTypeThrows.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "functionTypeThrows.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "functionTypeThrows.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "functionTypeThrows.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/function_implicit_return_type5-expected.txt b/ets2panda/test/parser/ets/function_implicit_return_type5-expected.txt index fd3c4fb889..3600cede6a 100644 --- a/ets2panda/test/parser/ets/function_implicit_return_type5-expected.txt +++ b/ets2panda/test/parser/ets/function_implicit_return_type5-expected.txt @@ -316,40 +316,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "function_implicit_return_type5.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "function_implicit_return_type5.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "function_implicit_return_type5.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "function_implicit_return_type5.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/function_implicit_return_type6-expected.txt b/ets2panda/test/parser/ets/function_implicit_return_type6-expected.txt index 593fa91b78..4c8c6eb29b 100644 --- a/ets2panda/test/parser/ets/function_implicit_return_type6-expected.txt +++ b/ets2panda/test/parser/ets/function_implicit_return_type6-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "function_implicit_return_type6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "function_implicit_return_type6.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "function_implicit_return_type6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "function_implicit_return_type6.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/function_implicit_return_type8-expected.txt b/ets2panda/test/parser/ets/function_implicit_return_type8-expected.txt index f6d9bcb309..4714961b87 100644 --- a/ets2panda/test/parser/ets/function_implicit_return_type8-expected.txt +++ b/ets2panda/test/parser/ets/function_implicit_return_type8-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "function_implicit_return_type8.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "function_implicit_return_type8.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "function_implicit_return_type8.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "function_implicit_return_type8.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/function_implicit_return_type9-expected.txt b/ets2panda/test/parser/ets/function_implicit_return_type9-expected.txt index a4462069f8..b9502a4e99 100644 --- a/ets2panda/test/parser/ets/function_implicit_return_type9-expected.txt +++ b/ets2panda/test/parser/ets/function_implicit_return_type9-expected.txt @@ -363,40 +363,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "function_implicit_return_type9.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "function_implicit_return_type9.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "function_implicit_return_type9.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "function_implicit_return_type9.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/genericDefaultParam_1-expected.txt b/ets2panda/test/parser/ets/genericDefaultParam_1-expected.txt index 0a0e0245b5..54083cdaef 100644 --- a/ets2panda/test/parser/ets/genericDefaultParam_1-expected.txt +++ b/ets2panda/test/parser/ets/genericDefaultParam_1-expected.txt @@ -1592,40 +1592,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "genericDefaultParam_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "genericDefaultParam_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "genericDefaultParam_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "genericDefaultParam_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/genericDefaultParam_3-expected.txt b/ets2panda/test/parser/ets/genericDefaultParam_3-expected.txt index eb7f758d66..dba63f9984 100644 --- a/ets2panda/test/parser/ets/genericDefaultParam_3-expected.txt +++ b/ets2panda/test/parser/ets/genericDefaultParam_3-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "genericDefaultParam_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "genericDefaultParam_3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "genericDefaultParam_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "genericDefaultParam_3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/generic_function-expected.txt b/ets2panda/test/parser/ets/generic_function-expected.txt index bf8117a25f..7259f200d0 100644 --- a/ets2panda/test/parser/ets/generic_function-expected.txt +++ b/ets2panda/test/parser/ets/generic_function-expected.txt @@ -290,40 +290,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_function.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_function.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_function.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_function.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/generic_resolve-expected.txt b/ets2panda/test/parser/ets/generic_resolve-expected.txt index 3dec4cc80a..d3b80a2c42 100644 --- a/ets2panda/test/parser/ets/generic_resolve-expected.txt +++ b/ets2panda/test/parser/ets/generic_resolve-expected.txt @@ -1365,40 +1365,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_resolve.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_resolve.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generic_resolve.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generic_resolve.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/generics_2-expected.txt b/ets2panda/test/parser/ets/generics_2-expected.txt index b990e08aad..8249c4cb80 100644 --- a/ets2panda/test/parser/ets/generics_2-expected.txt +++ b/ets2panda/test/parser/ets/generics_2-expected.txt @@ -1477,40 +1477,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/generics_3-expected.txt b/ets2panda/test/parser/ets/generics_3-expected.txt index c236d59af0..420b5968fa 100644 --- a/ets2panda/test/parser/ets/generics_3-expected.txt +++ b/ets2panda/test/parser/ets/generics_3-expected.txt @@ -259,40 +259,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/generics_4-expected.txt b/ets2panda/test/parser/ets/generics_4-expected.txt index 2cdbf80fc8..be1b9816a8 100644 --- a/ets2panda/test/parser/ets/generics_4-expected.txt +++ b/ets2panda/test/parser/ets/generics_4-expected.txt @@ -291,40 +291,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_4.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_4.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/generics_5-expected.txt b/ets2panda/test/parser/ets/generics_5-expected.txt index 11cdf6c52f..246ddfa0a4 100644 --- a/ets2panda/test/parser/ets/generics_5-expected.txt +++ b/ets2panda/test/parser/ets/generics_5-expected.txt @@ -227,40 +227,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_5.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_5.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_5.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_5.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/generics_6-expected.txt b/ets2panda/test/parser/ets/generics_6-expected.txt index 766006a59c..2cfd7603b0 100644 --- a/ets2panda/test/parser/ets/generics_6-expected.txt +++ b/ets2panda/test/parser/ets/generics_6-expected.txt @@ -463,40 +463,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_6.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_6.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/generics_7-expected.txt b/ets2panda/test/parser/ets/generics_7-expected.txt index 31071ab8c2..4df7ac16fa 100644 --- a/ets2panda/test/parser/ets/generics_7-expected.txt +++ b/ets2panda/test/parser/ets/generics_7-expected.txt @@ -463,40 +463,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_7.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_7.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_7.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_7.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/generics_recursive-expected.txt b/ets2panda/test/parser/ets/generics_recursive-expected.txt index 16137aae7c..d12bab3228 100644 --- a/ets2panda/test/parser/ets/generics_recursive-expected.txt +++ b/ets2panda/test/parser/ets/generics_recursive-expected.txt @@ -3110,40 +3110,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_recursive.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_recursive.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_recursive.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_recursive.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/generics_type_param_constraint_1-expected.txt b/ets2panda/test/parser/ets/generics_type_param_constraint_1-expected.txt index cf9d430a5f..ee6dbbddaa 100644 --- a/ets2panda/test/parser/ets/generics_type_param_constraint_1-expected.txt +++ b/ets2panda/test/parser/ets/generics_type_param_constraint_1-expected.txt @@ -338,40 +338,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/generics_type_param_constraint_10-expected.txt b/ets2panda/test/parser/ets/generics_type_param_constraint_10-expected.txt index 2278fb7e08..4d3683d337 100644 --- a/ets2panda/test/parser/ets/generics_type_param_constraint_10-expected.txt +++ b/ets2panda/test/parser/ets/generics_type_param_constraint_10-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_10.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_10.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_10.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_10.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/generics_type_param_constraint_11-expected.txt b/ets2panda/test/parser/ets/generics_type_param_constraint_11-expected.txt index 22459de1e9..008accd3f1 100644 --- a/ets2panda/test/parser/ets/generics_type_param_constraint_11-expected.txt +++ b/ets2panda/test/parser/ets/generics_type_param_constraint_11-expected.txt @@ -1115,40 +1115,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_11.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_11.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_11.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_11.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/generics_type_param_constraint_12-expected.txt b/ets2panda/test/parser/ets/generics_type_param_constraint_12-expected.txt index ad4fd202f0..e939edf546 100644 --- a/ets2panda/test/parser/ets/generics_type_param_constraint_12-expected.txt +++ b/ets2panda/test/parser/ets/generics_type_param_constraint_12-expected.txt @@ -1074,40 +1074,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_12.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_12.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_12.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_12.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/generics_type_param_constraint_2-expected.txt b/ets2panda/test/parser/ets/generics_type_param_constraint_2-expected.txt index 928a2986aa..3e279d79a3 100644 --- a/ets2panda/test/parser/ets/generics_type_param_constraint_2-expected.txt +++ b/ets2panda/test/parser/ets/generics_type_param_constraint_2-expected.txt @@ -232,40 +232,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/generics_type_param_constraint_3-expected.txt b/ets2panda/test/parser/ets/generics_type_param_constraint_3-expected.txt index 65b85878ff..0c8ae7c3b3 100644 --- a/ets2panda/test/parser/ets/generics_type_param_constraint_3-expected.txt +++ b/ets2panda/test/parser/ets/generics_type_param_constraint_3-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/generics_type_param_constraint_4-expected.txt b/ets2panda/test/parser/ets/generics_type_param_constraint_4-expected.txt index e4ca0a5d56..ae119ef2ff 100644 --- a/ets2panda/test/parser/ets/generics_type_param_constraint_4-expected.txt +++ b/ets2panda/test/parser/ets/generics_type_param_constraint_4-expected.txt @@ -622,40 +622,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_4.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_4.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/generics_type_param_constraint_5-expected.txt b/ets2panda/test/parser/ets/generics_type_param_constraint_5-expected.txt index 8254fba30b..01493e7a88 100644 --- a/ets2panda/test/parser/ets/generics_type_param_constraint_5-expected.txt +++ b/ets2panda/test/parser/ets/generics_type_param_constraint_5-expected.txt @@ -918,40 +918,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_5.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_5.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_5.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_5.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/generics_type_param_constraint_6-expected.txt b/ets2panda/test/parser/ets/generics_type_param_constraint_6-expected.txt index ce209704a3..6020eed9e9 100644 --- a/ets2panda/test/parser/ets/generics_type_param_constraint_6-expected.txt +++ b/ets2panda/test/parser/ets/generics_type_param_constraint_6-expected.txt @@ -370,40 +370,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_6.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_6.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/generics_type_param_constraint_7-expected.txt b/ets2panda/test/parser/ets/generics_type_param_constraint_7-expected.txt index 68da51bc46..2b3d80beb9 100644 --- a/ets2panda/test/parser/ets/generics_type_param_constraint_7-expected.txt +++ b/ets2panda/test/parser/ets/generics_type_param_constraint_7-expected.txt @@ -338,40 +338,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_7.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_7.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_7.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_7.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/generics_type_param_constraint_9-expected.txt b/ets2panda/test/parser/ets/generics_type_param_constraint_9-expected.txt index a68b85635f..2e9f5872ee 100644 --- a/ets2panda/test/parser/ets/generics_type_param_constraint_9-expected.txt +++ b/ets2panda/test/parser/ets/generics_type_param_constraint_9-expected.txt @@ -807,40 +807,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_9.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_9.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_9.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "generics_type_param_constraint_9.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/getterOverride-expected.txt b/ets2panda/test/parser/ets/getterOverride-expected.txt index d0f4bfaf4b..e223479634 100644 --- a/ets2panda/test/parser/ets/getterOverride-expected.txt +++ b/ets2panda/test/parser/ets/getterOverride-expected.txt @@ -613,40 +613,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "getterOverride.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "getterOverride.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "getterOverride.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "getterOverride.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/getter_setter_access_modifiers-expected.txt b/ets2panda/test/parser/ets/getter_setter_access_modifiers-expected.txt index 8fbef5c9ed..25155cb553 100644 --- a/ets2panda/test/parser/ets/getter_setter_access_modifiers-expected.txt +++ b/ets2panda/test/parser/ets/getter_setter_access_modifiers-expected.txt @@ -1965,40 +1965,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "getter_setter_access_modifiers.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "getter_setter_access_modifiers.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "getter_setter_access_modifiers.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "getter_setter_access_modifiers.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/globalVarInLambdaInStatic-expected.txt b/ets2panda/test/parser/ets/globalVarInLambdaInStatic-expected.txt index c8f594842a..08a8f0e8bb 100644 --- a/ets2panda/test/parser/ets/globalVarInLambdaInStatic-expected.txt +++ b/ets2panda/test/parser/ets/globalVarInLambdaInStatic-expected.txt @@ -956,40 +956,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "globalVarInLambdaInStatic.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "globalVarInLambdaInStatic.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "globalVarInLambdaInStatic.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "globalVarInLambdaInStatic.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/global_const_vars3-expected.txt b/ets2panda/test/parser/ets/global_const_vars3-expected.txt index 360b8aef03..0353208900 100644 --- a/ets2panda/test/parser/ets/global_const_vars3-expected.txt +++ b/ets2panda/test/parser/ets/global_const_vars3-expected.txt @@ -531,40 +531,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "global_const_vars3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "global_const_vars3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "global_const_vars3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "global_const_vars3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/identifier-expected.txt b/ets2panda/test/parser/ets/identifier-expected.txt index 634e81407c..6769831643 100644 --- a/ets2panda/test/parser/ets/identifier-expected.txt +++ b/ets2panda/test/parser/ets/identifier-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "identifier.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "identifier.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "identifier.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "identifier.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/if-expected.txt b/ets2panda/test/parser/ets/if-expected.txt index 0da4a587bc..5191a792b8 100644 --- a/ets2panda/test/parser/ets/if-expected.txt +++ b/ets2panda/test/parser/ets/if-expected.txt @@ -3022,40 +3022,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "if.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "if.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "if.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "if.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/ifs-expected.txt b/ets2panda/test/parser/ets/ifs-expected.txt index a074772a70..2718e28ed7 100644 --- a/ets2panda/test/parser/ets/ifs-expected.txt +++ b/ets2panda/test/parser/ets/ifs-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "ifs.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "ifs.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "ifs.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "ifs.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_conts-expected.txt b/ets2panda/test/parser/ets/import_conts-expected.txt index ce8a79ea77..8254df01f7 100644 --- a/ets2panda/test/parser/ets/import_conts-expected.txt +++ b/ets2panda/test/parser/ets/import_conts-expected.txt @@ -252,40 +252,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_conts.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_conts.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_conts.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_conts.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_folder-expected.txt b/ets2panda/test/parser/ets/import_folder-expected.txt index 9de65377ef..9e34c3fef4 100644 --- a/ets2panda/test/parser/ets/import_folder-expected.txt +++ b/ets2panda/test/parser/ets/import_folder-expected.txt @@ -88,40 +88,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_folder.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_folder.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_folder.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_folder.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/check_exported_2-expected.txt b/ets2panda/test/parser/ets/import_tests/check_exported_2-expected.txt index 3b29f0f918..e102397efd 100644 --- a/ets2panda/test/parser/ets/import_tests/check_exported_2-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/check_exported_2-expected.txt @@ -88,40 +88,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "check_exported_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "check_exported_2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "check_exported_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "check_exported_2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/check_exported_3-expected.txt b/ets2panda/test/parser/ets/import_tests/check_exported_3-expected.txt index 9d8be056c3..2e90889a67 100644 --- a/ets2panda/test/parser/ets/import_tests/check_exported_3-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/check_exported_3-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "check_exported_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "check_exported_3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "check_exported_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "check_exported_3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/check_exported_default_class-expected.txt b/ets2panda/test/parser/ets/import_tests/check_exported_default_class-expected.txt index ae3209395c..298a6f3d02 100644 --- a/ets2panda/test/parser/ets/import_tests/check_exported_default_class-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/check_exported_default_class-expected.txt @@ -88,40 +88,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "check_exported_default_class.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "check_exported_default_class.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "check_exported_default_class.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "check_exported_default_class.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/default_import-expected.txt b/ets2panda/test/parser/ets/import_tests/default_import-expected.txt index bd3cf2db15..b21ecc8295 100644 --- a/ets2panda/test/parser/ets/import_tests/default_import-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/default_import-expected.txt @@ -88,40 +88,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "default_import.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "default_import.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "default_import.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "default_import.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/diamond/test1-expected.txt b/ets2panda/test/parser/ets/import_tests/diamond/test1-expected.txt index d206b1b2b9..310273526f 100644 --- a/ets2panda/test/parser/ets/import_tests/diamond/test1-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/diamond/test1-expected.txt @@ -187,40 +187,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/diamond/test2-expected.txt b/ets2panda/test/parser/ets/import_tests/diamond/test2-expected.txt index fb58025c74..7addb00967 100644 --- a/ets2panda/test/parser/ets/import_tests/diamond/test2-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/diamond/test2-expected.txt @@ -105,40 +105,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/diamond/test3-expected.txt b/ets2panda/test/parser/ets/import_tests/diamond/test3-expected.txt index 9c90792f6b..af733650c9 100644 --- a/ets2panda/test/parser/ets/import_tests/diamond/test3-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/diamond/test3-expected.txt @@ -105,40 +105,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/diamond/test4-expected.txt b/ets2panda/test/parser/ets/import_tests/diamond/test4-expected.txt index 9b415c0172..ae9ea1042b 100644 --- a/ets2panda/test/parser/ets/import_tests/diamond/test4-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/diamond/test4-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test4.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test4.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/duplicated/classdef-expected.txt b/ets2panda/test/parser/ets/import_tests/duplicated/classdef-expected.txt index aaed83bac7..45ab948105 100644 --- a/ets2panda/test/parser/ets/import_tests/duplicated/classdef-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/duplicated/classdef-expected.txt @@ -178,40 +178,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "classdef.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "classdef.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "classdef.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "classdef.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/duplicated/extdef-expected.txt b/ets2panda/test/parser/ets/import_tests/duplicated/extdef-expected.txt index 96a8085659..0989c4685e 100644 --- a/ets2panda/test/parser/ets/import_tests/duplicated/extdef-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/duplicated/extdef-expected.txt @@ -105,40 +105,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "extdef.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "extdef.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "extdef.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "extdef.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/duplicated/extusedef-expected.txt b/ets2panda/test/parser/ets/import_tests/duplicated/extusedef-expected.txt index e39395a490..75b4a52596 100644 --- a/ets2panda/test/parser/ets/import_tests/duplicated/extusedef-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/duplicated/extusedef-expected.txt @@ -105,40 +105,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "extusedef.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "extusedef.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "extusedef.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "extusedef.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/export_type_alias-expected.txt b/ets2panda/test/parser/ets/import_tests/export_type_alias-expected.txt index e76e89049c..06d45cc4bd 100644 --- a/ets2panda/test/parser/ets/import_tests/export_type_alias-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/export_type_alias-expected.txt @@ -304,40 +304,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "export_type_alias.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "export_type_alias.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "export_type_alias.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "export_type_alias.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/folderWithoutIndexOrPackage/separate_module-expected.txt b/ets2panda/test/parser/ets/import_tests/folderWithoutIndexOrPackage/separate_module-expected.txt index 22b116782a..fbcfef566b 100644 --- a/ets2panda/test/parser/ets/import_tests/folderWithoutIndexOrPackage/separate_module-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/folderWithoutIndexOrPackage/separate_module-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "separate_module.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "separate_module.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "separate_module.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "separate_module.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/import_alias/export-expected.txt b/ets2panda/test/parser/ets/import_tests/import_alias/export-expected.txt index 8c69d07e4a..26bd73fa07 100644 --- a/ets2panda/test/parser/ets/import_tests/import_alias/export-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/import_alias/export-expected.txt @@ -545,40 +545,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "export.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "export.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "export.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "export.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/import_alias/import_alias_1-expected.txt b/ets2panda/test/parser/ets/import_tests/import_alias/import_alias_1-expected.txt index b1cfc1e8ca..4b4b585589 100644 --- a/ets2panda/test/parser/ets/import_tests/import_alias/import_alias_1-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/import_alias/import_alias_1-expected.txt @@ -88,40 +88,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_alias_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_alias_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_alias_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_alias_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/import_alias_and_without_alias_1-expected.txt b/ets2panda/test/parser/ets/import_tests/import_alias_and_without_alias_1-expected.txt index 868f3fe857..48779566b1 100644 --- a/ets2panda/test/parser/ets/import_tests/import_alias_and_without_alias_1-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/import_alias_and_without_alias_1-expected.txt @@ -170,40 +170,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_alias_and_without_alias_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_alias_and_without_alias_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_alias_and_without_alias_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_alias_and_without_alias_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/import_alias_and_without_alias_2-expected.txt b/ets2panda/test/parser/ets/import_tests/import_alias_and_without_alias_2-expected.txt index 2519966845..b8ea87e11f 100644 --- a/ets2panda/test/parser/ets/import_tests/import_alias_and_without_alias_2-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/import_alias_and_without_alias_2-expected.txt @@ -252,40 +252,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_alias_and_without_alias_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_alias_and_without_alias_2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_alias_and_without_alias_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_alias_and_without_alias_2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/import_alias_and_without_alias_3-expected.txt b/ets2panda/test/parser/ets/import_tests/import_alias_and_without_alias_3-expected.txt index 0162f6fc1b..c7f2811655 100644 --- a/ets2panda/test/parser/ets/import_tests/import_alias_and_without_alias_3-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/import_alias_and_without_alias_3-expected.txt @@ -252,40 +252,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_alias_and_without_alias_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_alias_and_without_alias_3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_alias_and_without_alias_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_alias_and_without_alias_3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/import_all-expected.txt b/ets2panda/test/parser/ets/import_tests/import_all-expected.txt index b2918d592e..be878c9f40 100755 --- a/ets2panda/test/parser/ets/import_tests/import_all-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/import_all-expected.txt @@ -153,40 +153,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_all.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_all.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_all.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_all.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/import_all_3-expected.txt b/ets2panda/test/parser/ets/import_tests/import_all_3-expected.txt index 02172d4ee6..54bfc27c40 100644 --- a/ets2panda/test/parser/ets/import_tests/import_all_3-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/import_all_3-expected.txt @@ -88,40 +88,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_all_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_all_3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_all_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_all_3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/import_all_alias_1-expected.txt b/ets2panda/test/parser/ets/import_tests/import_all_alias_1-expected.txt index 71cf7b0b9b..b048ff97aa 100644 --- a/ets2panda/test/parser/ets/import_tests/import_all_alias_1-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/import_all_alias_1-expected.txt @@ -88,40 +88,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_all_alias_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_all_alias_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_all_alias_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_all_alias_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/import_all_type_alias-expected.txt b/ets2panda/test/parser/ets/import_tests/import_all_type_alias-expected.txt index 4d8cf0ac9a..68fb4cac40 100644 --- a/ets2panda/test/parser/ets/import_tests/import_all_type_alias-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/import_all_type_alias-expected.txt @@ -88,40 +88,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_all_type_alias.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_all_type_alias.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_all_type_alias.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_all_type_alias.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/import_diff_paths-expected.txt b/ets2panda/test/parser/ets/import_tests/import_diff_paths-expected.txt index fb689356eb..813b3fb1ba 100644 --- a/ets2panda/test/parser/ets/import_tests/import_diff_paths-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/import_diff_paths-expected.txt @@ -187,40 +187,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_diff_paths.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_diff_paths.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_diff_paths.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_diff_paths.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/import_extension/import_extension-expected.txt b/ets2panda/test/parser/ets/import_tests/import_extension/import_extension-expected.txt index 5db624fe5a..971b99fd70 100644 --- a/ets2panda/test/parser/ets/import_tests/import_extension/import_extension-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/import_extension/import_extension-expected.txt @@ -187,40 +187,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_extension.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_extension.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_extension.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_extension.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/import_extension/import_extension_1-expected.txt b/ets2panda/test/parser/ets/import_tests/import_extension/import_extension_1-expected.txt index 9d5f573f70..4dbe29d09c 100644 --- a/ets2panda/test/parser/ets/import_tests/import_extension/import_extension_1-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/import_extension/import_extension_1-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_extension_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_extension_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_extension_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_extension_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/import_extension/import_extension_2-expected.txt b/ets2panda/test/parser/ets/import_tests/import_extension/import_extension_2-expected.txt index 74d44f589f..a6b21c9fce 100644 --- a/ets2panda/test/parser/ets/import_tests/import_extension/import_extension_2-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/import_extension/import_extension_2-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_extension_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_extension_2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_extension_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_extension_2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/import_function_overload-expected.txt b/ets2panda/test/parser/ets/import_tests/import_function_overload-expected.txt index ba2f99e358..43bc9c4d8f 100644 --- a/ets2panda/test/parser/ets/import_tests/import_function_overload-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/import_function_overload-expected.txt @@ -105,40 +105,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_function_overload.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_function_overload.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_function_overload.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_function_overload.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/import_interface_test-expected.txt b/ets2panda/test/parser/ets/import_tests/import_interface_test-expected.txt index 2edbe742e5..5bc0500823 100644 --- a/ets2panda/test/parser/ets/import_tests/import_interface_test-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/import_interface_test-expected.txt @@ -558,40 +558,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_interface_test.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_interface_test.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_interface_test.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_interface_test.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/import_interface_test_1-expected.txt b/ets2panda/test/parser/ets/import_tests/import_interface_test_1-expected.txt index 25906641fd..579475c53e 100644 --- a/ets2panda/test/parser/ets/import_tests/import_interface_test_1-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/import_interface_test_1-expected.txt @@ -178,40 +178,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_interface_test_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_interface_test_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_interface_test_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_interface_test_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/import_interface_test_2-expected.txt b/ets2panda/test/parser/ets/import_tests/import_interface_test_2-expected.txt index 83d1ad8343..451905f99c 100644 --- a/ets2panda/test/parser/ets/import_tests/import_interface_test_2-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/import_interface_test_2-expected.txt @@ -476,40 +476,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_interface_test_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_interface_test_2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_interface_test_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_interface_test_2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/import_max_as_alias-expected.txt b/ets2panda/test/parser/ets/import_tests/import_max_as_alias-expected.txt index f90ac8478f..a22980af7b 100644 --- a/ets2panda/test/parser/ets/import_tests/import_max_as_alias-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/import_max_as_alias-expected.txt @@ -105,40 +105,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_max_as_alias.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_max_as_alias.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_max_as_alias.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_max_as_alias.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/import_name_1-expected.txt b/ets2panda/test/parser/ets/import_tests/import_name_1-expected.txt index 06fec81fb7..3499dcfc7f 100755 --- a/ets2panda/test/parser/ets/import_tests/import_name_1-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/import_name_1-expected.txt @@ -203,40 +203,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_name_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_name_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_name_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_name_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/import_name_alias_1-expected.txt b/ets2panda/test/parser/ets/import_tests/import_name_alias_1-expected.txt index 6a9fee2c6e..699ce235c2 100755 --- a/ets2panda/test/parser/ets/import_tests/import_name_alias_1-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/import_name_alias_1-expected.txt @@ -203,40 +203,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_name_alias_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_name_alias_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_name_alias_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_name_alias_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/import_name_conflicts/imported_module_1-expected.txt b/ets2panda/test/parser/ets/import_tests/import_name_conflicts/imported_module_1-expected.txt index dd796e2d0b..2e79b56dc3 100644 --- a/ets2panda/test/parser/ets/import_tests/import_name_conflicts/imported_module_1-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/import_name_conflicts/imported_module_1-expected.txt @@ -388,40 +388,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "imported_module_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "imported_module_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "imported_module_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "imported_module_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/import_name_conflicts/imported_module_2-expected.txt b/ets2panda/test/parser/ets/import_tests/import_name_conflicts/imported_module_2-expected.txt index 8a943aad19..0f0b798931 100644 --- a/ets2panda/test/parser/ets/import_tests/import_name_conflicts/imported_module_2-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/import_name_conflicts/imported_module_2-expected.txt @@ -388,40 +388,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "imported_module_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "imported_module_2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "imported_module_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "imported_module_2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/import_relative_path-expected.txt b/ets2panda/test/parser/ets/import_tests/import_relative_path-expected.txt index 232ea6c2cf..9b428c9359 100755 --- a/ets2panda/test/parser/ets/import_tests/import_relative_path-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/import_relative_path-expected.txt @@ -88,40 +88,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_relative_path.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_relative_path.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_relative_path.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_relative_path.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/import_several_1-expected.txt b/ets2panda/test/parser/ets/import_tests/import_several_1-expected.txt index f777e0c621..edb6fdc92f 100755 --- a/ets2panda/test/parser/ets/import_tests/import_several_1-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/import_several_1-expected.txt @@ -269,40 +269,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_several_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_several_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_several_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_several_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/import_several_2-expected.txt b/ets2panda/test/parser/ets/import_tests/import_several_2-expected.txt index c192825029..01ca05519b 100755 --- a/ets2panda/test/parser/ets/import_tests/import_several_2-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/import_several_2-expected.txt @@ -154,40 +154,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_several_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_several_2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_several_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_several_2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/import_several_3-expected.txt b/ets2panda/test/parser/ets/import_tests/import_several_3-expected.txt index f5991c6b98..c3b5aca811 100755 --- a/ets2panda/test/parser/ets/import_tests/import_several_3-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/import_several_3-expected.txt @@ -170,40 +170,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_several_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_several_3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_several_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_several_3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/import_several_4-expected.txt b/ets2panda/test/parser/ets/import_tests/import_several_4-expected.txt index 04a6536a8a..e976815b59 100644 --- a/ets2panda/test/parser/ets/import_tests/import_several_4-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/import_several_4-expected.txt @@ -170,40 +170,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_several_4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_several_4.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_several_4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_several_4.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/import_several_5-expected.txt b/ets2panda/test/parser/ets/import_tests/import_several_5-expected.txt index a3d207dce5..46b8037c4a 100755 --- a/ets2panda/test/parser/ets/import_tests/import_several_5-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/import_several_5-expected.txt @@ -170,40 +170,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_several_5.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_several_5.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_several_5.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_several_5.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/import_several_6-expected.txt b/ets2panda/test/parser/ets/import_tests/import_several_6-expected.txt index 9058b0a910..416b7f399c 100644 --- a/ets2panda/test/parser/ets/import_tests/import_several_6-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/import_several_6-expected.txt @@ -170,40 +170,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_several_6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_several_6.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_several_6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_several_6.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/import_several_7-expected.txt b/ets2panda/test/parser/ets/import_tests/import_several_7-expected.txt index a52b745a00..1a2800e166 100755 --- a/ets2panda/test/parser/ets/import_tests/import_several_7-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/import_several_7-expected.txt @@ -252,40 +252,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_several_7.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_several_7.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_several_7.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_several_7.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/import_ts_file-expected.txt b/ets2panda/test/parser/ets/import_tests/import_ts_file-expected.txt index 8da3fb09cf..3904e7e7ee 100644 --- a/ets2panda/test/parser/ets/import_tests/import_ts_file-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/import_ts_file-expected.txt @@ -105,40 +105,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_ts_file.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_ts_file.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_ts_file.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_ts_file.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/internals-expected.txt b/ets2panda/test/parser/ets/import_tests/internals-expected.txt index 9a5f2a2c86..4a28ca1e14 100644 --- a/ets2panda/test/parser/ets/import_tests/internals-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/internals-expected.txt @@ -539,40 +539,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "internals.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "internals.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "internals.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "internals.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/modules/class_default_module-expected.txt b/ets2panda/test/parser/ets/import_tests/modules/class_default_module-expected.txt index 39b58715e3..ea653065a6 100644 --- a/ets2panda/test/parser/ets/import_tests/modules/class_default_module-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/modules/class_default_module-expected.txt @@ -178,40 +178,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "class_default_module.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "class_default_module.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "class_default_module.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "class_default_module.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/modules/default_export-expected.txt b/ets2panda/test/parser/ets/import_tests/modules/default_export-expected.txt index be8dc6e85f..a14dec67cf 100644 --- a/ets2panda/test/parser/ets/import_tests/modules/default_export-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/modules/default_export-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "default_export.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "default_export.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "default_export.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "default_export.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/modules/missing_default_export-expected.txt b/ets2panda/test/parser/ets/import_tests/modules/missing_default_export-expected.txt index 421aecc8cc..8ea40b2a5b 100644 --- a/ets2panda/test/parser/ets/import_tests/modules/missing_default_export-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/modules/missing_default_export-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "missing_default_export.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "missing_default_export.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "missing_default_export.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "missing_default_export.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/modules/module1/src/export_file-expected.txt b/ets2panda/test/parser/ets/import_tests/modules/module1/src/export_file-expected.txt index e9f8bc4904..51dad8f55e 100644 --- a/ets2panda/test/parser/ets/import_tests/modules/module1/src/export_file-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/modules/module1/src/export_file-expected.txt @@ -102,40 +102,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "export_file.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "export_file.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "export_file.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "export_file.ets" - } - } - } - ], "body": [], "loc": { "start": { diff --git a/ets2panda/test/parser/ets/import_tests/modules/module1/src/re_export_file-expected.txt b/ets2panda/test/parser/ets/import_tests/modules/module1/src/re_export_file-expected.txt index c77d001687..2f47549c03 100644 --- a/ets2panda/test/parser/ets/import_tests/modules/module1/src/re_export_file-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/modules/module1/src/re_export_file-expected.txt @@ -120,40 +120,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "re_export_file.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "re_export_file.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "re_export_file.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "re_export_file.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/modules/module2/src/import_file-expected.txt b/ets2panda/test/parser/ets/import_tests/modules/module2/src/import_file-expected.txt index 27b839d255..35f9aeb745 100644 --- a/ets2panda/test/parser/ets/import_tests/modules/module2/src/import_file-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/modules/module2/src/import_file-expected.txt @@ -105,40 +105,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_file.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_file.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_file.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_file.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/modules/module2/src/re_export_file_2-expected.txt b/ets2panda/test/parser/ets/import_tests/modules/module2/src/re_export_file_2-expected.txt index edccc0fb4e..3c5cf52b91 100644 --- a/ets2panda/test/parser/ets/import_tests/modules/module2/src/re_export_file_2-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/modules/module2/src/re_export_file_2-expected.txt @@ -120,40 +120,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "re_export_file_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "re_export_file_2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "re_export_file_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "re_export_file_2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/modules/test_lib1-expected.txt b/ets2panda/test/parser/ets/import_tests/modules/test_lib1-expected.txt index fc3892cbdd..00ac903d15 100644 --- a/ets2panda/test/parser/ets/import_tests/modules/test_lib1-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/modules/test_lib1-expected.txt @@ -178,40 +178,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test_lib1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test_lib1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test_lib1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test_lib1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/modules/test_lib2-expected.txt b/ets2panda/test/parser/ets/import_tests/modules/test_lib2-expected.txt index 7f735aec9c..c9903696aa 100644 --- a/ets2panda/test/parser/ets/import_tests/modules/test_lib2-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/modules/test_lib2-expected.txt @@ -105,40 +105,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test_lib2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test_lib2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test_lib2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test_lib2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/packages/aliasWithoutAlias/import1/import1-expected.txt b/ets2panda/test/parser/ets/import_tests/packages/aliasWithoutAlias/import1/import1-expected.txt index 912f41c9df..f977566c95 100644 --- a/ets2panda/test/parser/ets/import_tests/packages/aliasWithoutAlias/import1/import1-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/packages/aliasWithoutAlias/import1/import1-expected.txt @@ -151,40 +151,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/packages/aliasWithoutAlias/import2/import2-expected.txt b/ets2panda/test/parser/ets/import_tests/packages/aliasWithoutAlias/import2/import2-expected.txt index 5ae16ba400..a62db9b7c2 100644 --- a/ets2panda/test/parser/ets/import_tests/packages/aliasWithoutAlias/import2/import2-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/packages/aliasWithoutAlias/import2/import2-expected.txt @@ -151,40 +151,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/packages/import_package_with_alias/import_package_with_alias-expected.txt b/ets2panda/test/parser/ets/import_tests/packages/import_package_with_alias/import_package_with_alias-expected.txt index 06e9d2f75d..5ddf6d66a2 100644 --- a/ets2panda/test/parser/ets/import_tests/packages/import_package_with_alias/import_package_with_alias-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/packages/import_package_with_alias/import_package_with_alias-expected.txt @@ -88,40 +88,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_package_with_alias.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_package_with_alias.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_package_with_alias.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_package_with_alias.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/packages/import_package_with_alias/package/package_module-expected.txt b/ets2panda/test/parser/ets/import_tests/packages/import_package_with_alias/package/package_module-expected.txt index 03819abd36..75cec07cb7 100644 --- a/ets2panda/test/parser/ets/import_tests/packages/import_package_with_alias/package/package_module-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/packages/import_package_with_alias/package/package_module-expected.txt @@ -55,40 +55,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "package_module.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "package_module.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "package_module.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "package_module.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/packages/package_module_1-expected.txt b/ets2panda/test/parser/ets/import_tests/packages/package_module_1-expected.txt index c516fe31e5..b200321200 100755 --- a/ets2panda/test/parser/ets/import_tests/packages/package_module_1-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/packages/package_module_1-expected.txt @@ -87,40 +87,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "package_module_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "package_module_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "package_module_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "package_module_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/packages/package_module_2-expected.txt b/ets2panda/test/parser/ets/import_tests/packages/package_module_2-expected.txt index 06983d15e2..b1d61276d9 100755 --- a/ets2panda/test/parser/ets/import_tests/packages/package_module_2-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/packages/package_module_2-expected.txt @@ -87,40 +87,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "package_module_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "package_module_2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "package_module_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "package_module_2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/packages/subpackage-1/package_module_1-expected.txt b/ets2panda/test/parser/ets/import_tests/packages/subpackage-1/package_module_1-expected.txt index 2e018cfa70..e25f40ef08 100644 --- a/ets2panda/test/parser/ets/import_tests/packages/subpackage-1/package_module_1-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/packages/subpackage-1/package_module_1-expected.txt @@ -119,40 +119,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "package_module_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "package_module_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "package_module_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "package_module_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/packages/subpackage-2/package_module_1-expected.txt b/ets2panda/test/parser/ets/import_tests/packages/subpackage-2/package_module_1-expected.txt index faed71de21..36d18749fb 100644 --- a/ets2panda/test/parser/ets/import_tests/packages/subpackage-2/package_module_1-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/packages/subpackage-2/package_module_1-expected.txt @@ -119,40 +119,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "package_module_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "package_module_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "package_module_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "package_module_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/packages/subpackage/package_module_1-expected.txt b/ets2panda/test/parser/ets/import_tests/packages/subpackage/package_module_1-expected.txt index 943d6415c4..2388032930 100644 --- a/ets2panda/test/parser/ets/import_tests/packages/subpackage/package_module_1-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/packages/subpackage/package_module_1-expected.txt @@ -119,40 +119,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "package_module_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "package_module_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "package_module_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "package_module_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/packages/var-duplication/subpackage_module_1-expected.txt b/ets2panda/test/parser/ets/import_tests/packages/var-duplication/subpackage_module_1-expected.txt index f17b659ea5..f1c13672b8 100755 --- a/ets2panda/test/parser/ets/import_tests/packages/var-duplication/subpackage_module_1-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/packages/var-duplication/subpackage_module_1-expected.txt @@ -119,40 +119,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "subpackage_module_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "subpackage_module_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "subpackage_module_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "subpackage_module_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/packages/var-duplication/subpackage_module_2-expected.txt b/ets2panda/test/parser/ets/import_tests/packages/var-duplication/subpackage_module_2-expected.txt index 4a8394e434..7630965a4f 100755 --- a/ets2panda/test/parser/ets/import_tests/packages/var-duplication/subpackage_module_2-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/packages/var-duplication/subpackage_module_2-expected.txt @@ -119,40 +119,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "subpackage_module_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "subpackage_module_2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "subpackage_module_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "subpackage_module_2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/relative_import/Line-expected.txt b/ets2panda/test/parser/ets/import_tests/relative_import/Line-expected.txt index 02e2a98f92..c0ef3b9777 100644 --- a/ets2panda/test/parser/ets/import_tests/relative_import/Line-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/relative_import/Line-expected.txt @@ -789,40 +789,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "Line.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "Line.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "Line.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "Line.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/relative_import/Point-expected.txt b/ets2panda/test/parser/ets/import_tests/relative_import/Point-expected.txt index e92093a854..32b77957aa 100644 --- a/ets2panda/test/parser/ets/import_tests/relative_import/Point-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/relative_import/Point-expected.txt @@ -990,40 +990,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "Point.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "Point.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "Point.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "Point.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/relative_import/alias1-expected.txt b/ets2panda/test/parser/ets/import_tests/relative_import/alias1-expected.txt index a0c46fa4ca..6d280e0677 100644 --- a/ets2panda/test/parser/ets/import_tests/relative_import/alias1-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/relative_import/alias1-expected.txt @@ -88,40 +88,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "alias1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "alias1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "alias1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "alias1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/relative_import/alias2-expected.txt b/ets2panda/test/parser/ets/import_tests/relative_import/alias2-expected.txt index f24ff30d90..932b2116bf 100644 --- a/ets2panda/test/parser/ets/import_tests/relative_import/alias2-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/relative_import/alias2-expected.txt @@ -284,40 +284,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "alias2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "alias2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "alias2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "alias2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/repeat-expected.txt b/ets2panda/test/parser/ets/import_tests/repeat-expected.txt index 186c68673b..e16b9ca6c1 100644 --- a/ets2panda/test/parser/ets/import_tests/repeat-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/repeat-expected.txt @@ -545,40 +545,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "repeat.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "repeat.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "repeat.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "repeat.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/subsequent_relative_imports/folder1/file1-expected.txt b/ets2panda/test/parser/ets/import_tests/subsequent_relative_imports/folder1/file1-expected.txt index d0ad5d66da..edfa30e973 100644 --- a/ets2panda/test/parser/ets/import_tests/subsequent_relative_imports/folder1/file1-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/subsequent_relative_imports/folder1/file1-expected.txt @@ -105,40 +105,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "file1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "file1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "file1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "file1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/subsequent_relative_imports/folder2/file2-expected.txt b/ets2panda/test/parser/ets/import_tests/subsequent_relative_imports/folder2/file2-expected.txt index 6b8d75ba71..ae41b07fae 100644 --- a/ets2panda/test/parser/ets/import_tests/subsequent_relative_imports/folder2/file2-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/subsequent_relative_imports/folder2/file2-expected.txt @@ -260,40 +260,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "file2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "file2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "file2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "file2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/subsequent_relative_imports/folder3/file3-expected.txt b/ets2panda/test/parser/ets/import_tests/subsequent_relative_imports/folder3/file3-expected.txt index f7e13e81c0..26be6a1da2 100644 --- a/ets2panda/test/parser/ets/import_tests/subsequent_relative_imports/folder3/file3-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/subsequent_relative_imports/folder3/file3-expected.txt @@ -178,40 +178,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "file3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "file3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "file3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "file3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/import_tests/type/type-expected.txt b/ets2panda/test/parser/ets/import_tests/type/type-expected.txt index 495dfc41c9..fa52821c44 100644 --- a/ets2panda/test/parser/ets/import_tests/type/type-expected.txt +++ b/ets2panda/test/parser/ets/import_tests/type/type-expected.txt @@ -178,40 +178,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "type.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "type.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "type.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "type.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/index_expressions-expected.txt b/ets2panda/test/parser/ets/index_expressions-expected.txt index 1aac5e18dc..263d1ae04a 100644 --- a/ets2panda/test/parser/ets/index_expressions-expected.txt +++ b/ets2panda/test/parser/ets/index_expressions-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "index_expressions.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "index_expressions.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "index_expressions.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "index_expressions.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/infer_overriding_method_return_type-expected.txt b/ets2panda/test/parser/ets/infer_overriding_method_return_type-expected.txt index f1aa0952bb..852c67f26d 100644 --- a/ets2panda/test/parser/ets/infer_overriding_method_return_type-expected.txt +++ b/ets2panda/test/parser/ets/infer_overriding_method_return_type-expected.txt @@ -654,40 +654,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "infer_overriding_method_return_type.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "infer_overriding_method_return_type.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "infer_overriding_method_return_type.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "infer_overriding_method_return_type.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/inferingEntryPointReturn-expected.txt b/ets2panda/test/parser/ets/inferingEntryPointReturn-expected.txt index 96179792ba..aa6f1d6f60 100644 --- a/ets2panda/test/parser/ets/inferingEntryPointReturn-expected.txt +++ b/ets2panda/test/parser/ets/inferingEntryPointReturn-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "inferingEntryPointReturn.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "inferingEntryPointReturn.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "inferingEntryPointReturn.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "inferingEntryPointReturn.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/inheritance-expected.txt b/ets2panda/test/parser/ets/inheritance-expected.txt index 7da63bfe6b..b90a53a851 100644 --- a/ets2panda/test/parser/ets/inheritance-expected.txt +++ b/ets2panda/test/parser/ets/inheritance-expected.txt @@ -1268,40 +1268,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "inheritance.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "inheritance.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "inheritance.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "inheritance.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/inheritance2-expected.txt b/ets2panda/test/parser/ets/inheritance2-expected.txt index 848109f219..be20d9b53d 100644 --- a/ets2panda/test/parser/ets/inheritance2-expected.txt +++ b/ets2panda/test/parser/ets/inheritance2-expected.txt @@ -781,40 +781,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "inheritance2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "inheritance2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "inheritance2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "inheritance2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/instanceof-expected.txt b/ets2panda/test/parser/ets/instanceof-expected.txt index d76d29d33a..e7afcbf701 100644 --- a/ets2panda/test/parser/ets/instanceof-expected.txt +++ b/ets2panda/test/parser/ets/instanceof-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "instanceof.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "instanceof.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "instanceof.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "instanceof.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/interfaceMethodWithOptional-expected.txt b/ets2panda/test/parser/ets/interfaceMethodWithOptional-expected.txt index 85cb67771c..9c36d34371 100644 --- a/ets2panda/test/parser/ets/interfaceMethodWithOptional-expected.txt +++ b/ets2panda/test/parser/ets/interfaceMethodWithOptional-expected.txt @@ -259,40 +259,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "interfaceMethodWithOptional.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "interfaceMethodWithOptional.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "interfaceMethodWithOptional.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "interfaceMethodWithOptional.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/interface_abstract_noreturn_function-expected.txt b/ets2panda/test/parser/ets/interface_abstract_noreturn_function-expected.txt index e90744a04b..df6360ab42 100644 --- a/ets2panda/test/parser/ets/interface_abstract_noreturn_function-expected.txt +++ b/ets2panda/test/parser/ets/interface_abstract_noreturn_function-expected.txt @@ -163,40 +163,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "interface_abstract_noreturn_function.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "interface_abstract_noreturn_function.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "interface_abstract_noreturn_function.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "interface_abstract_noreturn_function.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/interface_method_default_body-expected.txt b/ets2panda/test/parser/ets/interface_method_default_body-expected.txt index 345adff508..dc4d7d30ae 100644 --- a/ets2panda/test/parser/ets/interface_method_default_body-expected.txt +++ b/ets2panda/test/parser/ets/interface_method_default_body-expected.txt @@ -856,40 +856,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "interface_method_default_body.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "interface_method_default_body.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "interface_method_default_body.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "interface_method_default_body.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/interfaces-expected.txt b/ets2panda/test/parser/ets/interfaces-expected.txt index 4289919bfb..2a1b0fcc27 100644 --- a/ets2panda/test/parser/ets/interfaces-expected.txt +++ b/ets2panda/test/parser/ets/interfaces-expected.txt @@ -1232,40 +1232,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "interfaces.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "interfaces.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "interfaces.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "interfaces.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/internalParsing-expected.txt b/ets2panda/test/parser/ets/internalParsing-expected.txt index 881001494d..a5ed8a2713 100644 --- a/ets2panda/test/parser/ets/internalParsing-expected.txt +++ b/ets2panda/test/parser/ets/internalParsing-expected.txt @@ -700,40 +700,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "internalParsing.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "internalParsing.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "internalParsing.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "internalParsing.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/internalProtectedParsing-expected.txt b/ets2panda/test/parser/ets/internalProtectedParsing-expected.txt index b2bba426a8..d1e05bda1b 100644 --- a/ets2panda/test/parser/ets/internalProtectedParsing-expected.txt +++ b/ets2panda/test/parser/ets/internalProtectedParsing-expected.txt @@ -937,40 +937,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "internalProtectedParsing.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "internalProtectedParsing.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "internalProtectedParsing.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "internalProtectedParsing.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/labeledDoWhileStatement-expected.txt b/ets2panda/test/parser/ets/labeledDoWhileStatement-expected.txt index 2b8b790169..4c37f7a531 100644 --- a/ets2panda/test/parser/ets/labeledDoWhileStatement-expected.txt +++ b/ets2panda/test/parser/ets/labeledDoWhileStatement-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "labeledDoWhileStatement.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "labeledDoWhileStatement.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "labeledDoWhileStatement.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "labeledDoWhileStatement.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/labeledForStatement-expected.txt b/ets2panda/test/parser/ets/labeledForStatement-expected.txt index 00488b344c..bb8876b63c 100644 --- a/ets2panda/test/parser/ets/labeledForStatement-expected.txt +++ b/ets2panda/test/parser/ets/labeledForStatement-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "labeledForStatement.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "labeledForStatement.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "labeledForStatement.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "labeledForStatement.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/labeledSwitchStatement-expected.txt b/ets2panda/test/parser/ets/labeledSwitchStatement-expected.txt index a79f02caeb..4b46c8ed84 100644 --- a/ets2panda/test/parser/ets/labeledSwitchStatement-expected.txt +++ b/ets2panda/test/parser/ets/labeledSwitchStatement-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "labeledSwitchStatement.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "labeledSwitchStatement.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "labeledSwitchStatement.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "labeledSwitchStatement.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/labeledWhileStatement-expected.txt b/ets2panda/test/parser/ets/labeledWhileStatement-expected.txt index df23e910f8..a5074ba198 100644 --- a/ets2panda/test/parser/ets/labeledWhileStatement-expected.txt +++ b/ets2panda/test/parser/ets/labeledWhileStatement-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "labeledWhileStatement.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "labeledWhileStatement.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "labeledWhileStatement.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "labeledWhileStatement.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/lambda-expected.txt b/ets2panda/test/parser/ets/lambda-expected.txt index edcfe9c6e1..a0c5ccf1d3 100644 --- a/ets2panda/test/parser/ets/lambda-expected.txt +++ b/ets2panda/test/parser/ets/lambda-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/lambda-lambda-expected.txt b/ets2panda/test/parser/ets/lambda-lambda-expected.txt index b6c12d7754..6490826b5d 100644 --- a/ets2panda/test/parser/ets/lambda-lambda-expected.txt +++ b/ets2panda/test/parser/ets/lambda-lambda-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda-lambda.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda-lambda.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda-lambda.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda-lambda.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/lambda-type-inference-alias-expected.txt b/ets2panda/test/parser/ets/lambda-type-inference-alias-expected.txt index f1037d412f..6b44d7a554 100644 --- a/ets2panda/test/parser/ets/lambda-type-inference-alias-expected.txt +++ b/ets2panda/test/parser/ets/lambda-type-inference-alias-expected.txt @@ -213,40 +213,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda-type-inference-alias.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda-type-inference-alias.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda-type-inference-alias.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda-type-inference-alias.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/lambda-type-inference-arg-no-type-expected.txt b/ets2panda/test/parser/ets/lambda-type-inference-arg-no-type-expected.txt index 84cf9cde09..150923b4a7 100644 --- a/ets2panda/test/parser/ets/lambda-type-inference-arg-no-type-expected.txt +++ b/ets2panda/test/parser/ets/lambda-type-inference-arg-no-type-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda-type-inference-arg-no-type.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda-type-inference-arg-no-type.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda-type-inference-arg-no-type.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda-type-inference-arg-no-type.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/lambda-type-inference-expected.txt b/ets2panda/test/parser/ets/lambda-type-inference-expected.txt index 14ee82017c..677295a425 100644 --- a/ets2panda/test/parser/ets/lambda-type-inference-expected.txt +++ b/ets2panda/test/parser/ets/lambda-type-inference-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda-type-inference.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda-type-inference.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda-type-inference.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda-type-inference.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/lambda-type-inference-no-ret-type-expected.txt b/ets2panda/test/parser/ets/lambda-type-inference-no-ret-type-expected.txt index 4c7d62bf87..43937f2c21 100644 --- a/ets2panda/test/parser/ets/lambda-type-inference-no-ret-type-expected.txt +++ b/ets2panda/test/parser/ets/lambda-type-inference-no-ret-type-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda-type-inference-no-ret-type.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda-type-inference-no-ret-type.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda-type-inference-no-ret-type.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda-type-inference-no-ret-type.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/lambda-type-inference-overloaded-2-expected.txt b/ets2panda/test/parser/ets/lambda-type-inference-overloaded-2-expected.txt index ac01ecc2ef..c630d0ee9c 100644 --- a/ets2panda/test/parser/ets/lambda-type-inference-overloaded-2-expected.txt +++ b/ets2panda/test/parser/ets/lambda-type-inference-overloaded-2-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda-type-inference-overloaded-2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda-type-inference-overloaded-2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda-type-inference-overloaded-2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda-type-inference-overloaded-2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/lambda-type-inference-overloaded-3-expected.txt b/ets2panda/test/parser/ets/lambda-type-inference-overloaded-3-expected.txt index 2aeb15d4d1..e5fc5b698a 100644 --- a/ets2panda/test/parser/ets/lambda-type-inference-overloaded-3-expected.txt +++ b/ets2panda/test/parser/ets/lambda-type-inference-overloaded-3-expected.txt @@ -1148,40 +1148,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda-type-inference-overloaded-3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda-type-inference-overloaded-3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda-type-inference-overloaded-3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda-type-inference-overloaded-3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/lambda-type-inference-overloaded-expected.txt b/ets2panda/test/parser/ets/lambda-type-inference-overloaded-expected.txt index 949ff031e6..59c102cdb8 100644 --- a/ets2panda/test/parser/ets/lambda-type-inference-overloaded-expected.txt +++ b/ets2panda/test/parser/ets/lambda-type-inference-overloaded-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda-type-inference-overloaded.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda-type-inference-overloaded.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda-type-inference-overloaded.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda-type-inference-overloaded.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/lambdaAsFunctionParam-expected.txt b/ets2panda/test/parser/ets/lambdaAsFunctionParam-expected.txt index c68d26196f..b77017596c 100644 --- a/ets2panda/test/parser/ets/lambdaAsFunctionParam-expected.txt +++ b/ets2panda/test/parser/ets/lambdaAsFunctionParam-expected.txt @@ -634,40 +634,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambdaAsFunctionParam.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambdaAsFunctionParam.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambdaAsFunctionParam.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambdaAsFunctionParam.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/lambdaExpressionWithoutBlockStatement-expected.txt b/ets2panda/test/parser/ets/lambdaExpressionWithoutBlockStatement-expected.txt index 564ca5326e..0574d6b087 100644 --- a/ets2panda/test/parser/ets/lambdaExpressionWithoutBlockStatement-expected.txt +++ b/ets2panda/test/parser/ets/lambdaExpressionWithoutBlockStatement-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambdaExpressionWithoutBlockStatement.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambdaExpressionWithoutBlockStatement.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambdaExpressionWithoutBlockStatement.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambdaExpressionWithoutBlockStatement.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/lambdaExpressionWithoutBlockStatementCallAVoidFunction-expected.txt b/ets2panda/test/parser/ets/lambdaExpressionWithoutBlockStatementCallAVoidFunction-expected.txt index a4bbf17b2f..1f25f4c85d 100644 --- a/ets2panda/test/parser/ets/lambdaExpressionWithoutBlockStatementCallAVoidFunction-expected.txt +++ b/ets2panda/test/parser/ets/lambdaExpressionWithoutBlockStatementCallAVoidFunction-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambdaExpressionWithoutBlockStatementCallAVoidFunction.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambdaExpressionWithoutBlockStatementCallAVoidFunction.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambdaExpressionWithoutBlockStatementCallAVoidFunction.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambdaExpressionWithoutBlockStatementCallAVoidFunction.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/lambdaExpressionWithoutBlockStatementVoid-expected.txt b/ets2panda/test/parser/ets/lambdaExpressionWithoutBlockStatementVoid-expected.txt index 64429a5f01..67e9abfc7f 100644 --- a/ets2panda/test/parser/ets/lambdaExpressionWithoutBlockStatementVoid-expected.txt +++ b/ets2panda/test/parser/ets/lambdaExpressionWithoutBlockStatementVoid-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambdaExpressionWithoutBlockStatementVoid.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambdaExpressionWithoutBlockStatementVoid.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambdaExpressionWithoutBlockStatementVoid.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambdaExpressionWithoutBlockStatementVoid.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/lambdaExpressionWithoutBlockStatementWithFunctionParameters-expected.txt b/ets2panda/test/parser/ets/lambdaExpressionWithoutBlockStatementWithFunctionParameters-expected.txt index 6fc7d55d59..7e1877d4d1 100644 --- a/ets2panda/test/parser/ets/lambdaExpressionWithoutBlockStatementWithFunctionParameters-expected.txt +++ b/ets2panda/test/parser/ets/lambdaExpressionWithoutBlockStatementWithFunctionParameters-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambdaExpressionWithoutBlockStatementWithFunctionParameters.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambdaExpressionWithoutBlockStatementWithFunctionParameters.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambdaExpressionWithoutBlockStatementWithFunctionParameters.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambdaExpressionWithoutBlockStatementWithFunctionParameters.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/lambdaThrowsRethrows-expected.txt b/ets2panda/test/parser/ets/lambdaThrowsRethrows-expected.txt index 1cbd45f79f..dc195cfcfa 100644 --- a/ets2panda/test/parser/ets/lambdaThrowsRethrows-expected.txt +++ b/ets2panda/test/parser/ets/lambdaThrowsRethrows-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambdaThrowsRethrows.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/lambda_import_alias_1-2-expected.txt b/ets2panda/test/parser/ets/lambda_import_alias_1-2-expected.txt index fdbe7c1609..7ed7954420 100644 --- a/ets2panda/test/parser/ets/lambda_import_alias_1-2-expected.txt +++ b/ets2panda/test/parser/ets/lambda_import_alias_1-2-expected.txt @@ -199,40 +199,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_import_alias_1-2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_import_alias_1-2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_import_alias_1-2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_import_alias_1-2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/lambda_import_alias_1-3-expected.txt b/ets2panda/test/parser/ets/lambda_import_alias_1-3-expected.txt index a19b75562b..d4342619d3 100644 --- a/ets2panda/test/parser/ets/lambda_import_alias_1-3-expected.txt +++ b/ets2panda/test/parser/ets/lambda_import_alias_1-3-expected.txt @@ -178,40 +178,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_import_alias_1-3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_import_alias_1-3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_import_alias_1-3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_import_alias_1-3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/lambda_import_alias_1-expected.txt b/ets2panda/test/parser/ets/lambda_import_alias_1-expected.txt index 8e49a38030..e640881cb6 100644 --- a/ets2panda/test/parser/ets/lambda_import_alias_1-expected.txt +++ b/ets2panda/test/parser/ets/lambda_import_alias_1-expected.txt @@ -88,40 +88,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_import_alias_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_import_alias_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_import_alias_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_import_alias_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/lambda_optional_param_1-expected.txt b/ets2panda/test/parser/ets/lambda_optional_param_1-expected.txt index eae7e13666..cf1ddbd9f3 100644 --- a/ets2panda/test/parser/ets/lambda_optional_param_1-expected.txt +++ b/ets2panda/test/parser/ets/lambda_optional_param_1-expected.txt @@ -433,40 +433,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_optional_param_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_optional_param_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambda_optional_param_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambda_optional_param_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/launch-expected.txt b/ets2panda/test/parser/ets/launch-expected.txt index c289beb987..344e98e437 100755 --- a/ets2panda/test/parser/ets/launch-expected.txt +++ b/ets2panda/test/parser/ets/launch-expected.txt @@ -642,40 +642,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "launch.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "launch.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "launch.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "launch.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/launch_function_returning_void-expected.txt b/ets2panda/test/parser/ets/launch_function_returning_void-expected.txt index df3937236b..703c564d18 100644 --- a/ets2panda/test/parser/ets/launch_function_returning_void-expected.txt +++ b/ets2panda/test/parser/ets/launch_function_returning_void-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "launch_function_returning_void.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "launch_function_returning_void.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "launch_function_returning_void.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "launch_function_returning_void.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/launch_ret-expected.txt b/ets2panda/test/parser/ets/launch_ret-expected.txt index 245cebb3a4..b0f2431a67 100644 --- a/ets2panda/test/parser/ets/launch_ret-expected.txt +++ b/ets2panda/test/parser/ets/launch_ret-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "launch_ret.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "launch_ret.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "launch_ret.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "launch_ret.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/launch_super-expected.txt b/ets2panda/test/parser/ets/launch_super-expected.txt index e5fedb878a..e919060344 100755 --- a/ets2panda/test/parser/ets/launch_super-expected.txt +++ b/ets2panda/test/parser/ets/launch_super-expected.txt @@ -718,40 +718,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "launch_super.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "launch_super.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "launch_super.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "launch_super.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/launch_this_callee-expected.txt b/ets2panda/test/parser/ets/launch_this_callee-expected.txt index 792f47433a..2239e093e4 100755 --- a/ets2panda/test/parser/ets/launch_this_callee-expected.txt +++ b/ets2panda/test/parser/ets/launch_this_callee-expected.txt @@ -1433,40 +1433,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "launch_this_callee.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "launch_this_callee.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "launch_this_callee.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "launch_this_callee.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/launch_with_call_expression-expected.txt b/ets2panda/test/parser/ets/launch_with_call_expression-expected.txt index 7f792ce7ad..8044ab4471 100644 --- a/ets2panda/test/parser/ets/launch_with_call_expression-expected.txt +++ b/ets2panda/test/parser/ets/launch_with_call_expression-expected.txt @@ -284,40 +284,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "launch_with_call_expression.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "launch_with_call_expression.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "launch_with_call_expression.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "launch_with_call_expression.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/literals-expected.txt b/ets2panda/test/parser/ets/literals-expected.txt index 0695f9b2e5..5dffbbbbf6 100644 --- a/ets2panda/test/parser/ets/literals-expected.txt +++ b/ets2panda/test/parser/ets/literals-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "literals.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "literals.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "literals.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "literals.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/local-class-expected.txt b/ets2panda/test/parser/ets/local-class-expected.txt index 1e942932aa..8b51c20764 100644 --- a/ets2panda/test/parser/ets/local-class-expected.txt +++ b/ets2panda/test/parser/ets/local-class-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "local-class.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "local-class.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "local-class.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "local-class.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/local-interface-expected.txt b/ets2panda/test/parser/ets/local-interface-expected.txt index b57fa54949..0644552646 100644 --- a/ets2panda/test/parser/ets/local-interface-expected.txt +++ b/ets2panda/test/parser/ets/local-interface-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "local-interface.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "local-interface.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "local-interface.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "local-interface.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/localClassIsPermitted-expected.txt b/ets2panda/test/parser/ets/localClassIsPermitted-expected.txt index 09f26707f2..0995504c47 100644 --- a/ets2panda/test/parser/ets/localClassIsPermitted-expected.txt +++ b/ets2panda/test/parser/ets/localClassIsPermitted-expected.txt @@ -416,40 +416,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "localClassIsPermitted.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "localClassIsPermitted.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "localClassIsPermitted.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "localClassIsPermitted.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/localTypeAlias-expected.txt b/ets2panda/test/parser/ets/localTypeAlias-expected.txt index 17a49eaa60..5e09636f3b 100644 --- a/ets2panda/test/parser/ets/localTypeAlias-expected.txt +++ b/ets2panda/test/parser/ets/localTypeAlias-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "localTypeAlias.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "localTypeAlias.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "localTypeAlias.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "localTypeAlias.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/main_entry_point_1-expected.txt b/ets2panda/test/parser/ets/main_entry_point_1-expected.txt index 858179267f..94f1e5a503 100644 --- a/ets2panda/test/parser/ets/main_entry_point_1-expected.txt +++ b/ets2panda/test/parser/ets/main_entry_point_1-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "main_entry_point_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "main_entry_point_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "main_entry_point_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "main_entry_point_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/main_entry_point_6-expected.txt b/ets2panda/test/parser/ets/main_entry_point_6-expected.txt index a504afc2e4..79e1381c50 100644 --- a/ets2panda/test/parser/ets/main_entry_point_6-expected.txt +++ b/ets2panda/test/parser/ets/main_entry_point_6-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "main_entry_point_6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "main_entry_point_6.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "main_entry_point_6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "main_entry_point_6.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/main_entry_point_7-expected.txt b/ets2panda/test/parser/ets/main_entry_point_7-expected.txt index e07e26bd4a..2f96192fae 100644 --- a/ets2panda/test/parser/ets/main_entry_point_7-expected.txt +++ b/ets2panda/test/parser/ets/main_entry_point_7-expected.txt @@ -565,40 +565,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "main_entry_point_7.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "main_entry_point_7.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "main_entry_point_7.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "main_entry_point_7.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/main_entry_point_8-expected.txt b/ets2panda/test/parser/ets/main_entry_point_8-expected.txt index 663fe2d682..38fb238cae 100644 --- a/ets2panda/test/parser/ets/main_entry_point_8-expected.txt +++ b/ets2panda/test/parser/ets/main_entry_point_8-expected.txt @@ -102,40 +102,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "main_entry_point_8.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "main_entry_point_8.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "main_entry_point_8.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "main_entry_point_8.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/main_entry_point_9-expected.txt b/ets2panda/test/parser/ets/main_entry_point_9-expected.txt index dde066a938..e485fe44f4 100644 --- a/ets2panda/test/parser/ets/main_entry_point_9-expected.txt +++ b/ets2panda/test/parser/ets/main_entry_point_9-expected.txt @@ -118,40 +118,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "main_entry_point_9.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "main_entry_point_9.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "main_entry_point_9.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "main_entry_point_9.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/methodThrowsRethrows-expected.txt b/ets2panda/test/parser/ets/methodThrowsRethrows-expected.txt index cf7fa60a78..093b36752f 100644 --- a/ets2panda/test/parser/ets/methodThrowsRethrows-expected.txt +++ b/ets2panda/test/parser/ets/methodThrowsRethrows-expected.txt @@ -582,40 +582,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "methodThrowsRethrows.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "methodThrowsRethrows.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/method_empty-expected.txt b/ets2panda/test/parser/ets/method_empty-expected.txt index a4c9dd8748..3157560667 100644 --- a/ets2panda/test/parser/ets/method_empty-expected.txt +++ b/ets2panda/test/parser/ets/method_empty-expected.txt @@ -638,40 +638,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "method_empty.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "method_empty.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "method_empty.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "method_empty.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/method_modifier_check_14-expected.txt b/ets2panda/test/parser/ets/method_modifier_check_14-expected.txt index 4abf82afef..a72193ec3b 100644 --- a/ets2panda/test/parser/ets/method_modifier_check_14-expected.txt +++ b/ets2panda/test/parser/ets/method_modifier_check_14-expected.txt @@ -283,40 +283,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "method_modifier_check_14.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "method_modifier_check_14.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "method_modifier_check_14.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "method_modifier_check_14.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/method_modifier_check_8-expected.txt b/ets2panda/test/parser/ets/method_modifier_check_8-expected.txt index 19632c78dd..d255a51765 100644 --- a/ets2panda/test/parser/ets/method_modifier_check_8-expected.txt +++ b/ets2panda/test/parser/ets/method_modifier_check_8-expected.txt @@ -283,40 +283,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "method_modifier_check_8.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "method_modifier_check_8.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "method_modifier_check_8.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "method_modifier_check_8.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/method_override_throw_1-expected.txt b/ets2panda/test/parser/ets/method_override_throw_1-expected.txt index b813966285..c04044c9c4 100644 --- a/ets2panda/test/parser/ets/method_override_throw_1-expected.txt +++ b/ets2panda/test/parser/ets/method_override_throw_1-expected.txt @@ -2319,40 +2319,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "method_override_throw_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "method_override_throw_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/native_function_with_return_type-expected.txt b/ets2panda/test/parser/ets/native_function_with_return_type-expected.txt index d3e6387391..f5983b0409 100644 --- a/ets2panda/test/parser/ets/native_function_with_return_type-expected.txt +++ b/ets2panda/test/parser/ets/native_function_with_return_type-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "native_function_with_return_type.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "native_function_with_return_type.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "native_function_with_return_type.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "native_function_with_return_type.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/new_expressions-expected.txt b/ets2panda/test/parser/ets/new_expressions-expected.txt index 0f15d45a94..d7870311d6 100644 --- a/ets2panda/test/parser/ets/new_expressions-expected.txt +++ b/ets2panda/test/parser/ets/new_expressions-expected.txt @@ -179,40 +179,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "new_expressions.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "new_expressions.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "new_expressions.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "new_expressions.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/new_object_3-expected.txt b/ets2panda/test/parser/ets/new_object_3-expected.txt index 88ed3c5f6f..02a6235f92 100644 --- a/ets2panda/test/parser/ets/new_object_3-expected.txt +++ b/ets2panda/test/parser/ets/new_object_3-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "new_object_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "new_object_3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "new_object_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "new_object_3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/null-expected.txt b/ets2panda/test/parser/ets/null-expected.txt index 538e1607db..c436378ae1 100644 --- a/ets2panda/test/parser/ets/null-expected.txt +++ b/ets2panda/test/parser/ets/null-expected.txt @@ -178,40 +178,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "null.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "null.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "null.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "null.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/null_valid-expected.txt b/ets2panda/test/parser/ets/null_valid-expected.txt index 530f61b046..f4d0b80cdb 100644 --- a/ets2panda/test/parser/ets/null_valid-expected.txt +++ b/ets2panda/test/parser/ets/null_valid-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "null_valid.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "null_valid.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "null_valid.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "null_valid.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/nullableGenericSignature-expected.txt b/ets2panda/test/parser/ets/nullableGenericSignature-expected.txt index cd7cc74a09..c168acc981 100644 --- a/ets2panda/test/parser/ets/nullableGenericSignature-expected.txt +++ b/ets2panda/test/parser/ets/nullableGenericSignature-expected.txt @@ -852,40 +852,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "nullableGenericSignature.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "nullableGenericSignature.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "nullableGenericSignature.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "nullableGenericSignature.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/nullable_union_array-expected.txt b/ets2panda/test/parser/ets/nullable_union_array-expected.txt index 44638a5900..c81a9133f3 100644 --- a/ets2panda/test/parser/ets/nullable_union_array-expected.txt +++ b/ets2panda/test/parser/ets/nullable_union_array-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "nullable_union_array.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "nullable_union_array.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "nullable_union_array.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "nullable_union_array.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/object-expected.txt b/ets2panda/test/parser/ets/object-expected.txt index 1e62905800..636e38a147 100644 --- a/ets2panda/test/parser/ets/object-expected.txt +++ b/ets2panda/test/parser/ets/object-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "object.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "object.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "object.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "object.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/optional_field_class-expected.txt b/ets2panda/test/parser/ets/optional_field_class-expected.txt index 4a660454d0..14f6564279 100644 --- a/ets2panda/test/parser/ets/optional_field_class-expected.txt +++ b/ets2panda/test/parser/ets/optional_field_class-expected.txt @@ -416,40 +416,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "optional_field_class.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "optional_field_class.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "optional_field_class.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "optional_field_class.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/optional_field_interface-expected.txt b/ets2panda/test/parser/ets/optional_field_interface-expected.txt index 3175a5747c..4268a4dfc3 100644 --- a/ets2panda/test/parser/ets/optional_field_interface-expected.txt +++ b/ets2panda/test/parser/ets/optional_field_interface-expected.txt @@ -1349,40 +1349,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "optional_field_interface.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "optional_field_interface.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "optional_field_interface.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "optional_field_interface.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/optional_field_interfaceUnion-expected.txt b/ets2panda/test/parser/ets/optional_field_interfaceUnion-expected.txt index 8fddd788bc..2009728353 100644 --- a/ets2panda/test/parser/ets/optional_field_interfaceUnion-expected.txt +++ b/ets2panda/test/parser/ets/optional_field_interfaceUnion-expected.txt @@ -1712,40 +1712,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "optional_field_interfaceUnion.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "optional_field_interfaceUnion.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "optional_field_interfaceUnion.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "optional_field_interfaceUnion.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/optional_field_variable-expected.txt b/ets2panda/test/parser/ets/optional_field_variable-expected.txt index c28003d792..11f5da843f 100644 --- a/ets2panda/test/parser/ets/optional_field_variable-expected.txt +++ b/ets2panda/test/parser/ets/optional_field_variable-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "optional_field_variable.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "optional_field_variable.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "optional_field_variable.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "optional_field_variable.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/optional_union_paramter-expected.txt b/ets2panda/test/parser/ets/optional_union_paramter-expected.txt index de12c48130..386fb92893 100644 --- a/ets2panda/test/parser/ets/optional_union_paramter-expected.txt +++ b/ets2panda/test/parser/ets/optional_union_paramter-expected.txt @@ -619,40 +619,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "optional_union_paramter.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "optional_union_paramter.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "optional_union_paramter.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "optional_union_paramter.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/override-expected.txt b/ets2panda/test/parser/ets/override-expected.txt index 03d8bef3f5..8ef43867c1 100644 --- a/ets2panda/test/parser/ets/override-expected.txt +++ b/ets2panda/test/parser/ets/override-expected.txt @@ -1231,40 +1231,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "override.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "override.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "override.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "override.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/overrideStaticFunc-expected.txt b/ets2panda/test/parser/ets/overrideStaticFunc-expected.txt index db9a60fa01..3c52f8c03c 100644 --- a/ets2panda/test/parser/ets/overrideStaticFunc-expected.txt +++ b/ets2panda/test/parser/ets/overrideStaticFunc-expected.txt @@ -792,40 +792,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "overrideStaticFunc.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "overrideStaticFunc.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "overrideStaticFunc.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "overrideStaticFunc.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/parentheses_expression_value-expected.txt b/ets2panda/test/parser/ets/parentheses_expression_value-expected.txt index 8ad8861a8d..06f443f4b1 100644 --- a/ets2panda/test/parser/ets/parentheses_expression_value-expected.txt +++ b/ets2panda/test/parser/ets/parentheses_expression_value-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "parentheses_expression_value.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "parentheses_expression_value.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "parentheses_expression_value.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "parentheses_expression_value.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/predefined_types-expected.txt b/ets2panda/test/parser/ets/predefined_types-expected.txt index 1f7b74f91d..7d6959d452 100644 --- a/ets2panda/test/parser/ets/predefined_types-expected.txt +++ b/ets2panda/test/parser/ets/predefined_types-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "predefined_types.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "predefined_types.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "predefined_types.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "predefined_types.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/promiseCasting-expected.txt b/ets2panda/test/parser/ets/promiseCasting-expected.txt index 52e0927748..2ec0b8557c 100644 --- a/ets2panda/test/parser/ets/promiseCasting-expected.txt +++ b/ets2panda/test/parser/ets/promiseCasting-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "promiseCasting.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "promiseCasting.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "promiseCasting.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "promiseCasting.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/proxyVoidGeneration-expected.txt b/ets2panda/test/parser/ets/proxyVoidGeneration-expected.txt index 8b0a277007..1174c0556c 100644 --- a/ets2panda/test/parser/ets/proxyVoidGeneration-expected.txt +++ b/ets2panda/test/parser/ets/proxyVoidGeneration-expected.txt @@ -933,40 +933,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "proxyVoidGeneration.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "proxyVoidGeneration.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "proxyVoidGeneration.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "proxyVoidGeneration.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/proxy_method-expected.txt b/ets2panda/test/parser/ets/proxy_method-expected.txt index 4c3b5eceae..3f6fd781d4 100644 --- a/ets2panda/test/parser/ets/proxy_method-expected.txt +++ b/ets2panda/test/parser/ets/proxy_method-expected.txt @@ -577,40 +577,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "proxy_method.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "proxy_method.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "proxy_method.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "proxy_method.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/diamond/A-expected.txt b/ets2panda/test/parser/ets/re_export/diamond/A-expected.txt index ff55665e5f..615f5ec208 100644 --- a/ets2panda/test/parser/ets/re_export/diamond/A-expected.txt +++ b/ets2panda/test/parser/ets/re_export/diamond/A-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "A.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "A.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "A.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "A.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/diamond/B-expected.txt b/ets2panda/test/parser/ets/re_export/diamond/B-expected.txt index 422ecbae90..696c8558c3 100644 --- a/ets2panda/test/parser/ets/re_export/diamond/B-expected.txt +++ b/ets2panda/test/parser/ets/re_export/diamond/B-expected.txt @@ -120,40 +120,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "B.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "B.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "B.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "B.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/diamond/B2-expected.txt b/ets2panda/test/parser/ets/re_export/diamond/B2-expected.txt index 62712365dd..ce3d378573 100644 --- a/ets2panda/test/parser/ets/re_export/diamond/B2-expected.txt +++ b/ets2panda/test/parser/ets/re_export/diamond/B2-expected.txt @@ -120,40 +120,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "B2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "B2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "B2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "B2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/diamond/C-expected.txt b/ets2panda/test/parser/ets/re_export/diamond/C-expected.txt index b8eec2a2ad..6e85e269d6 100644 --- a/ets2panda/test/parser/ets/re_export/diamond/C-expected.txt +++ b/ets2panda/test/parser/ets/re_export/diamond/C-expected.txt @@ -120,40 +120,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "C.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "C.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "C.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "C.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/diamond/C2-expected.txt b/ets2panda/test/parser/ets/re_export/diamond/C2-expected.txt index bd4d24e6da..89615244b9 100644 --- a/ets2panda/test/parser/ets/re_export/diamond/C2-expected.txt +++ b/ets2panda/test/parser/ets/re_export/diamond/C2-expected.txt @@ -120,40 +120,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "C2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "C2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "C2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "C2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/diamond/D-expected.txt b/ets2panda/test/parser/ets/re_export/diamond/D-expected.txt index 1f85bac726..87ef6e7f53 100644 --- a/ets2panda/test/parser/ets/re_export/diamond/D-expected.txt +++ b/ets2panda/test/parser/ets/re_export/diamond/D-expected.txt @@ -153,40 +153,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "D.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "D.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "D.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "D.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/diamond/D2-expected.txt b/ets2panda/test/parser/ets/re_export/diamond/D2-expected.txt index c2cbb73613..9fe8f42c76 100644 --- a/ets2panda/test/parser/ets/re_export/diamond/D2-expected.txt +++ b/ets2panda/test/parser/ets/re_export/diamond/D2-expected.txt @@ -153,40 +153,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "D2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "D2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "D2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "D2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/export-expected.txt b/ets2panda/test/parser/ets/re_export/export-expected.txt index 31fcf8d152..c10cf4198c 100644 --- a/ets2panda/test/parser/ets/re_export/export-expected.txt +++ b/ets2panda/test/parser/ets/re_export/export-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "export.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "export.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "export.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "export.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/export_2-expected.txt b/ets2panda/test/parser/ets/re_export/export_2-expected.txt index dde19dc455..a78d3223db 100644 --- a/ets2panda/test/parser/ets/re_export/export_2-expected.txt +++ b/ets2panda/test/parser/ets/re_export/export_2-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "export_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "export_2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "export_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "export_2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/export_3-expected.txt b/ets2panda/test/parser/ets/re_export/export_3-expected.txt index 1720414890..990e3c747c 100644 --- a/ets2panda/test/parser/ets/re_export/export_3-expected.txt +++ b/ets2panda/test/parser/ets/re_export/export_3-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "export_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "export_3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "export_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "export_3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/folder/export-expected.txt b/ets2panda/test/parser/ets/re_export/folder/export-expected.txt index 31fcf8d152..c10cf4198c 100644 --- a/ets2panda/test/parser/ets/re_export/folder/export-expected.txt +++ b/ets2panda/test/parser/ets/re_export/folder/export-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "export.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "export.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "export.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "export.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/folder/folder2/export-expected.txt b/ets2panda/test/parser/ets/re_export/folder/folder2/export-expected.txt index 31fcf8d152..c10cf4198c 100644 --- a/ets2panda/test/parser/ets/re_export/folder/folder2/export-expected.txt +++ b/ets2panda/test/parser/ets/re_export/folder/folder2/export-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "export.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "export.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "export.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "export.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/folder/re_export_6-expected.txt b/ets2panda/test/parser/ets/re_export/folder/re_export_6-expected.txt index 4d2ee8557a..10e735b0e9 100644 --- a/ets2panda/test/parser/ets/re_export/folder/re_export_6-expected.txt +++ b/ets2panda/test/parser/ets/re_export/folder/re_export_6-expected.txt @@ -103,40 +103,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "re_export_6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "re_export_6.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "re_export_6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "re_export_6.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/folder/re_export_7-expected.txt b/ets2panda/test/parser/ets/re_export/folder/re_export_7-expected.txt index 2e046adf2f..e00178f99c 100644 --- a/ets2panda/test/parser/ets/re_export/folder/re_export_7-expected.txt +++ b/ets2panda/test/parser/ets/re_export/folder/re_export_7-expected.txt @@ -103,40 +103,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "re_export_7.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "re_export_7.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "re_export_7.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "re_export_7.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/folderIndex/index-expected.txt b/ets2panda/test/parser/ets/re_export/folderIndex/index-expected.txt index cc60a07658..5a0839b190 100644 --- a/ets2panda/test/parser/ets/re_export/folderIndex/index-expected.txt +++ b/ets2panda/test/parser/ets/re_export/folderIndex/index-expected.txt @@ -120,40 +120,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "index.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "index.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "index.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "index.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/folderIndex/test-expected.txt b/ets2panda/test/parser/ets/re_export/folderIndex/test-expected.txt index 91b143592c..a429b641b1 100644 --- a/ets2panda/test/parser/ets/re_export/folderIndex/test-expected.txt +++ b/ets2panda/test/parser/ets/re_export/folderIndex/test-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/folderIndex2/index-expected.txt b/ets2panda/test/parser/ets/re_export/folderIndex2/index-expected.txt index d34d0b4607..01b819fb79 100644 --- a/ets2panda/test/parser/ets/re_export/folderIndex2/index-expected.txt +++ b/ets2panda/test/parser/ets/re_export/folderIndex2/index-expected.txt @@ -217,40 +217,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "index.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "index.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "index.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "index.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/folderIndex2/key-expected.txt b/ets2panda/test/parser/ets/re_export/folderIndex2/key-expected.txt index d5a1ff2a2b..adce9c43d8 100644 --- a/ets2panda/test/parser/ets/re_export/folderIndex2/key-expected.txt +++ b/ets2panda/test/parser/ets/re_export/folderIndex2/key-expected.txt @@ -539,40 +539,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "key.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "key.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "key.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "key.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/folderIndex2/type-expected.txt b/ets2panda/test/parser/ets/re_export/folderIndex2/type-expected.txt index 8e917a2342..5771878865 100644 --- a/ets2panda/test/parser/ets/re_export/folderIndex2/type-expected.txt +++ b/ets2panda/test/parser/ets/re_export/folderIndex2/type-expected.txt @@ -102,40 +102,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "type.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "type.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "type.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "type.ets" - } - } - } - ], "body": [], "loc": { "start": { diff --git a/ets2panda/test/parser/ets/re_export/import-expected.txt b/ets2panda/test/parser/ets/re_export/import-expected.txt index 5d381b1947..c4555cef6a 100644 --- a/ets2panda/test/parser/ets/re_export/import-expected.txt +++ b/ets2panda/test/parser/ets/re_export/import-expected.txt @@ -88,40 +88,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/import_10-expected.txt b/ets2panda/test/parser/ets/re_export/import_10-expected.txt index 62143ea482..2b576345b7 100644 --- a/ets2panda/test/parser/ets/re_export/import_10-expected.txt +++ b/ets2panda/test/parser/ets/re_export/import_10-expected.txt @@ -105,40 +105,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_10.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_10.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_10.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_10.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/import_11-expected.txt b/ets2panda/test/parser/ets/re_export/import_11-expected.txt index 52bde5a1d3..ea9d0aaa0d 100644 --- a/ets2panda/test/parser/ets/re_export/import_11-expected.txt +++ b/ets2panda/test/parser/ets/re_export/import_11-expected.txt @@ -105,40 +105,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_11.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_11.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_11.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_11.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/import_12-expected.txt b/ets2panda/test/parser/ets/re_export/import_12-expected.txt index d4901eddca..26aac25beb 100644 --- a/ets2panda/test/parser/ets/re_export/import_12-expected.txt +++ b/ets2panda/test/parser/ets/re_export/import_12-expected.txt @@ -105,40 +105,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_12.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_12.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_12.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_12.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/import_13-expected.txt b/ets2panda/test/parser/ets/re_export/import_13-expected.txt index 2ddc505122..071835ff81 100644 --- a/ets2panda/test/parser/ets/re_export/import_13-expected.txt +++ b/ets2panda/test/parser/ets/re_export/import_13-expected.txt @@ -88,40 +88,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_13.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_13.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_13.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_13.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/import_14-expected.txt b/ets2panda/test/parser/ets/re_export/import_14-expected.txt index 6682a76675..baf95e0b3b 100644 --- a/ets2panda/test/parser/ets/re_export/import_14-expected.txt +++ b/ets2panda/test/parser/ets/re_export/import_14-expected.txt @@ -88,40 +88,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_14.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_14.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_14.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_14.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/import_15-expected.txt b/ets2panda/test/parser/ets/re_export/import_15-expected.txt index 0b257f1e0b..c8d44adc39 100644 --- a/ets2panda/test/parser/ets/re_export/import_15-expected.txt +++ b/ets2panda/test/parser/ets/re_export/import_15-expected.txt @@ -88,40 +88,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_15.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_15.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_15.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_15.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/import_2-expected.txt b/ets2panda/test/parser/ets/re_export/import_2-expected.txt index 67297d50a0..415dd9dd6e 100644 --- a/ets2panda/test/parser/ets/re_export/import_2-expected.txt +++ b/ets2panda/test/parser/ets/re_export/import_2-expected.txt @@ -88,40 +88,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/import_3-expected.txt b/ets2panda/test/parser/ets/re_export/import_3-expected.txt index 024320aeb2..f7d16ecb3c 100644 --- a/ets2panda/test/parser/ets/re_export/import_3-expected.txt +++ b/ets2panda/test/parser/ets/re_export/import_3-expected.txt @@ -105,40 +105,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/import_6-expected.txt b/ets2panda/test/parser/ets/re_export/import_6-expected.txt index 14f32a904f..89385a92b7 100644 --- a/ets2panda/test/parser/ets/re_export/import_6-expected.txt +++ b/ets2panda/test/parser/ets/re_export/import_6-expected.txt @@ -88,40 +88,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_6.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_6.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/import_7-expected.txt b/ets2panda/test/parser/ets/re_export/import_7-expected.txt index e3f89ab4d4..61bdc33e1d 100644 --- a/ets2panda/test/parser/ets/re_export/import_7-expected.txt +++ b/ets2panda/test/parser/ets/re_export/import_7-expected.txt @@ -88,40 +88,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_7.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_7.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_7.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_7.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/import_8-expected.txt b/ets2panda/test/parser/ets/re_export/import_8-expected.txt index 883248e34d..a2ec621913 100644 --- a/ets2panda/test/parser/ets/re_export/import_8-expected.txt +++ b/ets2panda/test/parser/ets/re_export/import_8-expected.txt @@ -88,40 +88,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_8.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_8.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_8.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_8.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/import_9-expected.txt b/ets2panda/test/parser/ets/re_export/import_9-expected.txt index 7d623ce3ba..147783e0d9 100644 --- a/ets2panda/test/parser/ets/re_export/import_9-expected.txt +++ b/ets2panda/test/parser/ets/re_export/import_9-expected.txt @@ -105,40 +105,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_9.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_9.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_9.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_9.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/import_index-expected.txt b/ets2panda/test/parser/ets/re_export/import_index-expected.txt index 5e16944853..2152c6a9d0 100644 --- a/ets2panda/test/parser/ets/re_export/import_index-expected.txt +++ b/ets2panda/test/parser/ets/re_export/import_index-expected.txt @@ -88,40 +88,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_index.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_index.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_index.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_index.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/import_index_2-expected.txt b/ets2panda/test/parser/ets/re_export/import_index_2-expected.txt index 464a303478..671af9dde7 100644 --- a/ets2panda/test/parser/ets/re_export/import_index_2-expected.txt +++ b/ets2panda/test/parser/ets/re_export/import_index_2-expected.txt @@ -105,40 +105,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_index_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_index_2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_index_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_index_2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/import_index_3-expected.txt b/ets2panda/test/parser/ets/re_export/import_index_3-expected.txt index e7fd3585d4..53043501ef 100644 --- a/ets2panda/test/parser/ets/re_export/import_index_3-expected.txt +++ b/ets2panda/test/parser/ets/re_export/import_index_3-expected.txt @@ -154,40 +154,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_index_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_index_3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_index_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_index_3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/re_export-expected.txt b/ets2panda/test/parser/ets/re_export/re_export-expected.txt index e6324f4846..f16ec402b7 100644 --- a/ets2panda/test/parser/ets/re_export/re_export-expected.txt +++ b/ets2panda/test/parser/ets/re_export/re_export-expected.txt @@ -103,40 +103,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "re_export.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "re_export.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "re_export.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "re_export.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/re_export_10-expected.txt b/ets2panda/test/parser/ets/re_export/re_export_10-expected.txt index 23c8a0f406..8cf2f783ef 100644 --- a/ets2panda/test/parser/ets/re_export/re_export_10-expected.txt +++ b/ets2panda/test/parser/ets/re_export/re_export_10-expected.txt @@ -103,40 +103,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "re_export_10.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "re_export_10.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "re_export_10.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "re_export_10.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/re_export_11-expected.txt b/ets2panda/test/parser/ets/re_export/re_export_11-expected.txt index 1fcb79c6aa..85b263f83b 100644 --- a/ets2panda/test/parser/ets/re_export/re_export_11-expected.txt +++ b/ets2panda/test/parser/ets/re_export/re_export_11-expected.txt @@ -200,40 +200,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "re_export_11.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "re_export_11.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "re_export_11.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "re_export_11.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/re_export_12-expected.txt b/ets2panda/test/parser/ets/re_export/re_export_12-expected.txt index 612beebafa..2b7521bf96 100644 --- a/ets2panda/test/parser/ets/re_export/re_export_12-expected.txt +++ b/ets2panda/test/parser/ets/re_export/re_export_12-expected.txt @@ -183,40 +183,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "re_export_12.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "re_export_12.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "re_export_12.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "re_export_12.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/re_export_2-expected.txt b/ets2panda/test/parser/ets/re_export/re_export_2-expected.txt index a75c38c167..d1693124bb 100644 --- a/ets2panda/test/parser/ets/re_export/re_export_2-expected.txt +++ b/ets2panda/test/parser/ets/re_export/re_export_2-expected.txt @@ -120,40 +120,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "re_export_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "re_export_2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "re_export_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "re_export_2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/re_export_3-expected.txt b/ets2panda/test/parser/ets/re_export/re_export_3-expected.txt index 6a9368a318..25da675026 100644 --- a/ets2panda/test/parser/ets/re_export/re_export_3-expected.txt +++ b/ets2panda/test/parser/ets/re_export/re_export_3-expected.txt @@ -120,40 +120,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "re_export_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "re_export_3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "re_export_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "re_export_3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/re_export_4-expected.txt b/ets2panda/test/parser/ets/re_export/re_export_4-expected.txt index cb83b0c0ac..1921e61a4d 100644 --- a/ets2panda/test/parser/ets/re_export/re_export_4-expected.txt +++ b/ets2panda/test/parser/ets/re_export/re_export_4-expected.txt @@ -217,40 +217,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "re_export_4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "re_export_4.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "re_export_4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "re_export_4.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/re_export_5-expected.txt b/ets2panda/test/parser/ets/re_export/re_export_5-expected.txt index 82c25c96f2..b7a59b0bdb 100644 --- a/ets2panda/test/parser/ets/re_export/re_export_5-expected.txt +++ b/ets2panda/test/parser/ets/re_export/re_export_5-expected.txt @@ -183,40 +183,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "re_export_5.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "re_export_5.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "re_export_5.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "re_export_5.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/re_export_7-expected.txt b/ets2panda/test/parser/ets/re_export/re_export_7-expected.txt index 717243b0ae..347afbe778 100644 --- a/ets2panda/test/parser/ets/re_export/re_export_7-expected.txt +++ b/ets2panda/test/parser/ets/re_export/re_export_7-expected.txt @@ -200,40 +200,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "re_export_7.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "re_export_7.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "re_export_7.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "re_export_7.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/re_export_8-expected.txt b/ets2panda/test/parser/ets/re_export/re_export_8-expected.txt index 1224b4b452..eafe5f6b54 100644 --- a/ets2panda/test/parser/ets/re_export/re_export_8-expected.txt +++ b/ets2panda/test/parser/ets/re_export/re_export_8-expected.txt @@ -120,40 +120,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "re_export_8.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "re_export_8.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "re_export_8.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "re_export_8.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/re_export/re_export_9-expected.txt b/ets2panda/test/parser/ets/re_export/re_export_9-expected.txt index be9512b1ef..993f53396b 100644 --- a/ets2panda/test/parser/ets/re_export/re_export_9-expected.txt +++ b/ets2panda/test/parser/ets/re_export/re_export_9-expected.txt @@ -120,40 +120,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "re_export_9.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "re_export_9.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "re_export_9.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "re_export_9.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/regression-target-type-context-expected.txt b/ets2panda/test/parser/ets/regression-target-type-context-expected.txt index 4b57ce8f7b..13fefb7ff7 100644 --- a/ets2panda/test/parser/ets/regression-target-type-context-expected.txt +++ b/ets2panda/test/parser/ets/regression-target-type-context-expected.txt @@ -1511,40 +1511,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "regression-target-type-context.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "regression-target-type-context.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "regression-target-type-context.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "regression-target-type-context.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/rest_parameter_01-expected.txt b/ets2panda/test/parser/ets/rest_parameter_01-expected.txt index 1e9997f7d2..698fcb4c8c 100644 --- a/ets2panda/test/parser/ets/rest_parameter_01-expected.txt +++ b/ets2panda/test/parser/ets/rest_parameter_01-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rest_parameter_01.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rest_parameter_01.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rest_parameter_01.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rest_parameter_01.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/rest_parameter_02-expected.txt b/ets2panda/test/parser/ets/rest_parameter_02-expected.txt index 790996ccb2..94bce1e624 100644 --- a/ets2panda/test/parser/ets/rest_parameter_02-expected.txt +++ b/ets2panda/test/parser/ets/rest_parameter_02-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rest_parameter_02.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rest_parameter_02.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rest_parameter_02.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rest_parameter_02.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/rethrow-func-1-expected.txt b/ets2panda/test/parser/ets/rethrow-func-1-expected.txt index ccb337ee56..76388e85f7 100644 --- a/ets2panda/test/parser/ets/rethrow-func-1-expected.txt +++ b/ets2panda/test/parser/ets/rethrow-func-1-expected.txt @@ -87,40 +87,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrow-func-1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrow-func-1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/return-expected.txt b/ets2panda/test/parser/ets/return-expected.txt index 49c69a9d63..d9feaa60ff 100644 --- a/ets2panda/test/parser/ets/return-expected.txt +++ b/ets2panda/test/parser/ets/return-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "return.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "return.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "return.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "return.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/returnNullableFromFunction-expected.txt b/ets2panda/test/parser/ets/returnNullableFromFunction-expected.txt index b29d86e4e4..9f3ab9a53f 100644 --- a/ets2panda/test/parser/ets/returnNullableFromFunction-expected.txt +++ b/ets2panda/test/parser/ets/returnNullableFromFunction-expected.txt @@ -178,40 +178,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "returnNullableFromFunction.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "returnNullableFromFunction.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "returnNullableFromFunction.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "returnNullableFromFunction.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/returnNullableFromMethod-expected.txt b/ets2panda/test/parser/ets/returnNullableFromMethod-expected.txt index 560c80cced..805c5a6ddb 100644 --- a/ets2panda/test/parser/ets/returnNullableFromMethod-expected.txt +++ b/ets2panda/test/parser/ets/returnNullableFromMethod-expected.txt @@ -556,40 +556,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "returnNullableFromMethod.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "returnNullableFromMethod.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "returnNullableFromMethod.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "returnNullableFromMethod.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/scoped_decl-expected.txt b/ets2panda/test/parser/ets/scoped_decl-expected.txt index 06c75ffdea..043975b70e 100644 --- a/ets2panda/test/parser/ets/scoped_decl-expected.txt +++ b/ets2panda/test/parser/ets/scoped_decl-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "scoped_decl.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "scoped_decl.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "scoped_decl.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "scoped_decl.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/selective_export/import_1-expected.txt b/ets2panda/test/parser/ets/selective_export/import_1-expected.txt index e14e377372..2e0577fb37 100644 --- a/ets2panda/test/parser/ets/selective_export/import_1-expected.txt +++ b/ets2panda/test/parser/ets/selective_export/import_1-expected.txt @@ -88,40 +88,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/selective_export/import_2-expected.txt b/ets2panda/test/parser/ets/selective_export/import_2-expected.txt index 5b7297f219..18ee277c6a 100644 --- a/ets2panda/test/parser/ets/selective_export/import_2-expected.txt +++ b/ets2panda/test/parser/ets/selective_export/import_2-expected.txt @@ -88,40 +88,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/selective_export/import_3-expected.txt b/ets2panda/test/parser/ets/selective_export/import_3-expected.txt index 3fed2ef29d..15c116300d 100644 --- a/ets2panda/test/parser/ets/selective_export/import_3-expected.txt +++ b/ets2panda/test/parser/ets/selective_export/import_3-expected.txt @@ -88,40 +88,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/selective_export/import_4-expected.txt b/ets2panda/test/parser/ets/selective_export/import_4-expected.txt index 6773576eca..65e3fa5157 100644 --- a/ets2panda/test/parser/ets/selective_export/import_4-expected.txt +++ b/ets2panda/test/parser/ets/selective_export/import_4-expected.txt @@ -88,40 +88,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_4.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "import_4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "import_4.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/selective_export/selective_export_1-expected.txt b/ets2panda/test/parser/ets/selective_export/selective_export_1-expected.txt index 601f9e7943..f2aa382e52 100644 --- a/ets2panda/test/parser/ets/selective_export/selective_export_1-expected.txt +++ b/ets2panda/test/parser/ets/selective_export/selective_export_1-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "selective_export_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "selective_export_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "selective_export_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "selective_export_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/selective_export/selective_export_2-expected.txt b/ets2panda/test/parser/ets/selective_export/selective_export_2-expected.txt index ca8627f456..3e7e0d9c4b 100644 --- a/ets2panda/test/parser/ets/selective_export/selective_export_2-expected.txt +++ b/ets2panda/test/parser/ets/selective_export/selective_export_2-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "selective_export_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "selective_export_2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "selective_export_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "selective_export_2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/selective_export/selective_export_3-expected.txt b/ets2panda/test/parser/ets/selective_export/selective_export_3-expected.txt index 78f495a95b..59533da4d3 100644 --- a/ets2panda/test/parser/ets/selective_export/selective_export_3-expected.txt +++ b/ets2panda/test/parser/ets/selective_export/selective_export_3-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "selective_export_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "selective_export_3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "selective_export_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "selective_export_3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/selective_export/selective_export_4-expected.txt b/ets2panda/test/parser/ets/selective_export/selective_export_4-expected.txt index 384b9321cd..148a80d194 100644 --- a/ets2panda/test/parser/ets/selective_export/selective_export_4-expected.txt +++ b/ets2panda/test/parser/ets/selective_export/selective_export_4-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "selective_export_4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "selective_export_4.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "selective_export_4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "selective_export_4.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/simple_types-expected.txt b/ets2panda/test/parser/ets/simple_types-expected.txt index 3fb6093b7e..02ebb2a181 100644 --- a/ets2panda/test/parser/ets/simple_types-expected.txt +++ b/ets2panda/test/parser/ets/simple_types-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "simple_types.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "simple_types.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "simple_types.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "simple_types.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/static_function_override_1-expected.txt b/ets2panda/test/parser/ets/static_function_override_1-expected.txt index 6c22623123..5de5aa2765 100644 --- a/ets2panda/test/parser/ets/static_function_override_1-expected.txt +++ b/ets2panda/test/parser/ets/static_function_override_1-expected.txt @@ -621,40 +621,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "static_function_override_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "static_function_override_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "static_function_override_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "static_function_override_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/static_function_override_2-expected.txt b/ets2panda/test/parser/ets/static_function_override_2-expected.txt index dd1d6f89d3..72db14fe32 100644 --- a/ets2panda/test/parser/ets/static_function_override_2-expected.txt +++ b/ets2panda/test/parser/ets/static_function_override_2-expected.txt @@ -621,40 +621,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "static_function_override_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "static_function_override_2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "static_function_override_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "static_function_override_2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/static_function_override_3-expected.txt b/ets2panda/test/parser/ets/static_function_override_3-expected.txt index e60640ace6..4f6abf5bb8 100644 --- a/ets2panda/test/parser/ets/static_function_override_3-expected.txt +++ b/ets2panda/test/parser/ets/static_function_override_3-expected.txt @@ -621,40 +621,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "static_function_override_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "static_function_override_3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "static_function_override_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "static_function_override_3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/string-expected.txt b/ets2panda/test/parser/ets/string-expected.txt index 80908fa403..cd9fbe932b 100644 --- a/ets2panda/test/parser/ets/string-expected.txt +++ b/ets2panda/test/parser/ets/string-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "string.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "string.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "string.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "string.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/string_template_1-expected.txt b/ets2panda/test/parser/ets/string_template_1-expected.txt index 41c7f35d06..2de1927709 100644 --- a/ets2panda/test/parser/ets/string_template_1-expected.txt +++ b/ets2panda/test/parser/ets/string_template_1-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "string_template_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "string_template_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "string_template_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "string_template_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/string_template_2-expected.txt b/ets2panda/test/parser/ets/string_template_2-expected.txt index 647221586b..2574c1b4a2 100644 --- a/ets2panda/test/parser/ets/string_template_2-expected.txt +++ b/ets2panda/test/parser/ets/string_template_2-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "string_template_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "string_template_2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "string_template_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "string_template_2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/string_template_3-expected.txt b/ets2panda/test/parser/ets/string_template_3-expected.txt index 5d02887d3b..b0c8377dd3 100644 --- a/ets2panda/test/parser/ets/string_template_3-expected.txt +++ b/ets2panda/test/parser/ets/string_template_3-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "string_template_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "string_template_3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "string_template_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "string_template_3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/string_template_4-expected.txt b/ets2panda/test/parser/ets/string_template_4-expected.txt index dede298625..17b8cf3405 100644 --- a/ets2panda/test/parser/ets/string_template_4-expected.txt +++ b/ets2panda/test/parser/ets/string_template_4-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "string_template_4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "string_template_4.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "string_template_4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "string_template_4.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/switch-expected.txt b/ets2panda/test/parser/ets/switch-expected.txt index 507a6441f8..f3c60add8c 100644 --- a/ets2panda/test/parser/ets/switch-expected.txt +++ b/ets2panda/test/parser/ets/switch-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "switch.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "switch.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "switch.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "switch.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/switch2-expected.txt b/ets2panda/test/parser/ets/switch2-expected.txt index b58d4bc7a1..f2edf57641 100644 --- a/ets2panda/test/parser/ets/switch2-expected.txt +++ b/ets2panda/test/parser/ets/switch2-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "switch2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "switch2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "switch2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "switch2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/switch_alive_1-expected.txt b/ets2panda/test/parser/ets/switch_alive_1-expected.txt index f3b50bed3f..b353cc3ed5 100644 --- a/ets2panda/test/parser/ets/switch_alive_1-expected.txt +++ b/ets2panda/test/parser/ets/switch_alive_1-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "switch_alive_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "switch_alive_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "switch_alive_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "switch_alive_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/switch_alive_4-expected.txt b/ets2panda/test/parser/ets/switch_alive_4-expected.txt index 41471abb22..ffc2d56df5 100644 --- a/ets2panda/test/parser/ets/switch_alive_4-expected.txt +++ b/ets2panda/test/parser/ets/switch_alive_4-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "switch_alive_4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "switch_alive_4.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "switch_alive_4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "switch_alive_4.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/switch_char_compare_num-expected.txt b/ets2panda/test/parser/ets/switch_char_compare_num-expected.txt index 8d5e872d0c..dd1cbe89ce 100644 --- a/ets2panda/test/parser/ets/switch_char_compare_num-expected.txt +++ b/ets2panda/test/parser/ets/switch_char_compare_num-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "switch_char_compare_num.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "switch_char_compare_num.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "switch_char_compare_num.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "switch_char_compare_num.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/switch_enum_string_case-expected.txt b/ets2panda/test/parser/ets/switch_enum_string_case-expected.txt index 6c09ac3917..3230c41cac 100644 --- a/ets2panda/test/parser/ets/switch_enum_string_case-expected.txt +++ b/ets2panda/test/parser/ets/switch_enum_string_case-expected.txt @@ -4851,40 +4851,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "switch_enum_string_case.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "switch_enum_string_case.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "switch_enum_string_case.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "switch_enum_string_case.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/switch_num_compare_char-expected.txt b/ets2panda/test/parser/ets/switch_num_compare_char-expected.txt index 405f139eb6..4ac04baf6c 100644 --- a/ets2panda/test/parser/ets/switch_num_compare_char-expected.txt +++ b/ets2panda/test/parser/ets/switch_num_compare_char-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "switch_num_compare_char.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "switch_num_compare_char.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "switch_num_compare_char.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "switch_num_compare_char.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/switch_readonly_member-expected.txt b/ets2panda/test/parser/ets/switch_readonly_member-expected.txt index 6172839605..c9dceaf4f6 100644 --- a/ets2panda/test/parser/ets/switch_readonly_member-expected.txt +++ b/ets2panda/test/parser/ets/switch_readonly_member-expected.txt @@ -445,40 +445,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "switch_readonly_member.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "switch_readonly_member.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "switch_readonly_member.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "switch_readonly_member.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/switch_readonly_member_compare_char-expected.txt b/ets2panda/test/parser/ets/switch_readonly_member_compare_char-expected.txt index 21a80a6b99..f8f43cea1a 100644 --- a/ets2panda/test/parser/ets/switch_readonly_member_compare_char-expected.txt +++ b/ets2panda/test/parser/ets/switch_readonly_member_compare_char-expected.txt @@ -445,40 +445,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "switch_readonly_member_compare_char.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "switch_readonly_member_compare_char.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "switch_readonly_member_compare_char.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "switch_readonly_member_compare_char.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/switch_readonly_member_compare_char_2-expected.txt b/ets2panda/test/parser/ets/switch_readonly_member_compare_char_2-expected.txt index 697100275d..e6f846ba4c 100644 --- a/ets2panda/test/parser/ets/switch_readonly_member_compare_char_2-expected.txt +++ b/ets2panda/test/parser/ets/switch_readonly_member_compare_char_2-expected.txt @@ -445,40 +445,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "switch_readonly_member_compare_char_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "switch_readonly_member_compare_char_2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "switch_readonly_member_compare_char_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "switch_readonly_member_compare_char_2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/ternary-expected.txt b/ets2panda/test/parser/ets/ternary-expected.txt index eb955d1937..9e8ae9dcaa 100644 --- a/ets2panda/test/parser/ets/ternary-expected.txt +++ b/ets2panda/test/parser/ets/ternary-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "ternary.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "ternary.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "ternary.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "ternary.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/test-type-alias-call1-expected.txt b/ets2panda/test/parser/ets/test-type-alias-call1-expected.txt index d09009bddf..8ac00a419b 100644 --- a/ets2panda/test/parser/ets/test-type-alias-call1-expected.txt +++ b/ets2panda/test/parser/ets/test-type-alias-call1-expected.txt @@ -712,40 +712,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test-type-alias-call1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test-type-alias-call1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test-type-alias-call1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test-type-alias-call1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/test-type-alias-call2-expected.txt b/ets2panda/test/parser/ets/test-type-alias-call2-expected.txt index cd41118774..b5a969e767 100644 --- a/ets2panda/test/parser/ets/test-type-alias-call2-expected.txt +++ b/ets2panda/test/parser/ets/test-type-alias-call2-expected.txt @@ -870,40 +870,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test-type-alias-call2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test-type-alias-call2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test-type-alias-call2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test-type-alias-call2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/test-type-alias-call3-expected.txt b/ets2panda/test/parser/ets/test-type-alias-call3-expected.txt index 2fa1a8d769..89111efb1c 100644 --- a/ets2panda/test/parser/ets/test-type-alias-call3-expected.txt +++ b/ets2panda/test/parser/ets/test-type-alias-call3-expected.txt @@ -714,40 +714,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test-type-alias-call3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test-type-alias-call3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test-type-alias-call3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test-type-alias-call3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/test-type-alias-call4-expected.txt b/ets2panda/test/parser/ets/test-type-alias-call4-expected.txt index 91feabdc8b..392a44864a 100644 --- a/ets2panda/test/parser/ets/test-type-alias-call4-expected.txt +++ b/ets2panda/test/parser/ets/test-type-alias-call4-expected.txt @@ -714,40 +714,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test-type-alias-call4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test-type-alias-call4.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test-type-alias-call4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test-type-alias-call4.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/test-type-alias-call5-expected.txt b/ets2panda/test/parser/ets/test-type-alias-call5-expected.txt index dbc7530f39..39628d2def 100644 --- a/ets2panda/test/parser/ets/test-type-alias-call5-expected.txt +++ b/ets2panda/test/parser/ets/test-type-alias-call5-expected.txt @@ -934,40 +934,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test-type-alias-call5.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test-type-alias-call5.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test-type-alias-call5.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test-type-alias-call5.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/test-type-alias-call6-expected.txt b/ets2panda/test/parser/ets/test-type-alias-call6-expected.txt index 65888eb960..9da14f69eb 100644 --- a/ets2panda/test/parser/ets/test-type-alias-call6-expected.txt +++ b/ets2panda/test/parser/ets/test-type-alias-call6-expected.txt @@ -1013,40 +1013,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test-type-alias-call6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test-type-alias-call6.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test-type-alias-call6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test-type-alias-call6.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/test-type-alias-call7-expected.txt b/ets2panda/test/parser/ets/test-type-alias-call7-expected.txt index aebfb3cf18..cbd58d6eb9 100644 --- a/ets2panda/test/parser/ets/test-type-alias-call7-expected.txt +++ b/ets2panda/test/parser/ets/test-type-alias-call7-expected.txt @@ -134,40 +134,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test-type-alias-call7.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test-type-alias-call7.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test-type-alias-call7.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test-type-alias-call7.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/test-type-alias-call8-expected.txt b/ets2panda/test/parser/ets/test-type-alias-call8-expected.txt index f6fd83b46d..e8be79828e 100644 --- a/ets2panda/test/parser/ets/test-type-alias-call8-expected.txt +++ b/ets2panda/test/parser/ets/test-type-alias-call8-expected.txt @@ -683,40 +683,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test-type-alias-call8.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test-type-alias-call8.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test-type-alias-call8.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test-type-alias-call8.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/test_interface-expected.txt b/ets2panda/test/parser/ets/test_interface-expected.txt index 1c6ea9dc12..468b940760 100644 --- a/ets2panda/test/parser/ets/test_interface-expected.txt +++ b/ets2panda/test/parser/ets/test_interface-expected.txt @@ -1005,40 +1005,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test_interface.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test_interface.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test_interface.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test_interface.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/test_jsvalue-expected.txt b/ets2panda/test/parser/ets/test_jsvalue-expected.txt index af1bad5f4c..55691eb571 100644 --- a/ets2panda/test/parser/ets/test_jsvalue-expected.txt +++ b/ets2panda/test/parser/ets/test_jsvalue-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test_jsvalue.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test_jsvalue.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test_jsvalue.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test_jsvalue.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/test_jsvalue_get_double-expected.txt b/ets2panda/test/parser/ets/test_jsvalue_get_double-expected.txt index 91bd204790..b22f06abda 100644 --- a/ets2panda/test/parser/ets/test_jsvalue_get_double-expected.txt +++ b/ets2panda/test/parser/ets/test_jsvalue_get_double-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test_jsvalue_get_double.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test_jsvalue_get_double.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test_jsvalue_get_double.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test_jsvalue_get_double.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/test_jsvalue_get_property_1-expected.txt b/ets2panda/test/parser/ets/test_jsvalue_get_property_1-expected.txt index 78277ec6e4..3b7cba9750 100644 --- a/ets2panda/test/parser/ets/test_jsvalue_get_property_1-expected.txt +++ b/ets2panda/test/parser/ets/test_jsvalue_get_property_1-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test_jsvalue_get_property_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test_jsvalue_get_property_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test_jsvalue_get_property_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test_jsvalue_get_property_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/test_jsvalue_get_property_2-expected.txt b/ets2panda/test/parser/ets/test_jsvalue_get_property_2-expected.txt index 246427ada5..3ad1716413 100644 --- a/ets2panda/test/parser/ets/test_jsvalue_get_property_2-expected.txt +++ b/ets2panda/test/parser/ets/test_jsvalue_get_property_2-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test_jsvalue_get_property_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test_jsvalue_get_property_2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test_jsvalue_get_property_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test_jsvalue_get_property_2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/test_jsvalue_set_double-expected.txt b/ets2panda/test/parser/ets/test_jsvalue_set_double-expected.txt index cb7cd687c5..004962b3a5 100644 --- a/ets2panda/test/parser/ets/test_jsvalue_set_double-expected.txt +++ b/ets2panda/test/parser/ets/test_jsvalue_set_double-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test_jsvalue_set_double.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test_jsvalue_set_double.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test_jsvalue_set_double.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test_jsvalue_set_double.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/test_type_alias5-expected.txt b/ets2panda/test/parser/ets/test_type_alias5-expected.txt index f3baaa92af..a68c4a110b 100644 --- a/ets2panda/test/parser/ets/test_type_alias5-expected.txt +++ b/ets2panda/test/parser/ets/test_type_alias5-expected.txt @@ -70,40 +70,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test_type_alias5.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test_type_alias5.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test_type_alias5.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test_type_alias5.ets" - } - } - } - ], "body": [], "loc": { "start": { diff --git a/ets2panda/test/parser/ets/test_type_alias6-expected.txt b/ets2panda/test/parser/ets/test_type_alias6-expected.txt index 400503aef8..3107be32be 100644 --- a/ets2panda/test/parser/ets/test_type_alias6-expected.txt +++ b/ets2panda/test/parser/ets/test_type_alias6-expected.txt @@ -70,40 +70,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test_type_alias6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test_type_alias6.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test_type_alias6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test_type_alias6.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/test_type_alias7-expected.txt b/ets2panda/test/parser/ets/test_type_alias7-expected.txt index 5c91161ea4..c573847b4c 100644 --- a/ets2panda/test/parser/ets/test_type_alias7-expected.txt +++ b/ets2panda/test/parser/ets/test_type_alias7-expected.txt @@ -70,40 +70,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test_type_alias7.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test_type_alias7.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test_type_alias7.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test_type_alias7.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/test_type_alias8-expected.txt b/ets2panda/test/parser/ets/test_type_alias8-expected.txt index 5a0d1d8275..9419cab876 100644 --- a/ets2panda/test/parser/ets/test_type_alias8-expected.txt +++ b/ets2panda/test/parser/ets/test_type_alias8-expected.txt @@ -102,40 +102,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test_type_alias8.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test_type_alias8.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test_type_alias8.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test_type_alias8.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/test_type_alias9-expected.txt b/ets2panda/test/parser/ets/test_type_alias9-expected.txt index 27ab790383..bce025d138 100644 --- a/ets2panda/test/parser/ets/test_type_alias9-expected.txt +++ b/ets2panda/test/parser/ets/test_type_alias9-expected.txt @@ -149,40 +149,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test_type_alias9.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test_type_alias9.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "test_type_alias9.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "test_type_alias9.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/this_callee-expected.txt b/ets2panda/test/parser/ets/this_callee-expected.txt index 6bbb8f604b..c457dda06c 100644 --- a/ets2panda/test/parser/ets/this_callee-expected.txt +++ b/ets2panda/test/parser/ets/this_callee-expected.txt @@ -1275,40 +1275,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "this_callee.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "this_callee.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "this_callee.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "this_callee.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/this_cmp_object-expected.txt b/ets2panda/test/parser/ets/this_cmp_object-expected.txt index 677245e0a3..68323c16cd 100644 --- a/ets2panda/test/parser/ets/this_cmp_object-expected.txt +++ b/ets2panda/test/parser/ets/this_cmp_object-expected.txt @@ -585,40 +585,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "this_cmp_object.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "this_cmp_object.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "this_cmp_object.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "this_cmp_object.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/this_equality-expected.txt b/ets2panda/test/parser/ets/this_equality-expected.txt index cfd450b08b..282156505c 100644 --- a/ets2panda/test/parser/ets/this_equality-expected.txt +++ b/ets2panda/test/parser/ets/this_equality-expected.txt @@ -441,40 +441,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "this_equality.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "this_equality.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "this_equality.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "this_equality.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/this_expression-expected.txt b/ets2panda/test/parser/ets/this_expression-expected.txt index 67b05e149a..2dad6ed7aa 100644 --- a/ets2panda/test/parser/ets/this_expression-expected.txt +++ b/ets2panda/test/parser/ets/this_expression-expected.txt @@ -398,40 +398,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "this_expression.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "this_expression.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "this_expression.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "this_expression.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/this_type_class_method_return_valid-expected.txt b/ets2panda/test/parser/ets/this_type_class_method_return_valid-expected.txt index 2dd20b490a..09196a9800 100644 --- a/ets2panda/test/parser/ets/this_type_class_method_return_valid-expected.txt +++ b/ets2panda/test/parser/ets/this_type_class_method_return_valid-expected.txt @@ -378,40 +378,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "this_type_class_method_return_valid.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "this_type_class_method_return_valid.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "this_type_class_method_return_valid.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "this_type_class_method_return_valid.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/throwsRethrowsAsVariables-expected.txt b/ets2panda/test/parser/ets/throwsRethrowsAsVariables-expected.txt index e560472a60..3e02fd2143 100644 --- a/ets2panda/test/parser/ets/throwsRethrowsAsVariables-expected.txt +++ b/ets2panda/test/parser/ets/throwsRethrowsAsVariables-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwsRethrowsAsVariables.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwsRethrowsAsVariables.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/trailing_lambda_tests/trailing_lambda_define_lambda_in_body-expected.txt b/ets2panda/test/parser/ets/trailing_lambda_tests/trailing_lambda_define_lambda_in_body-expected.txt index 829a91cca4..d48d221b31 100644 --- a/ets2panda/test/parser/ets/trailing_lambda_tests/trailing_lambda_define_lambda_in_body-expected.txt +++ b/ets2panda/test/parser/ets/trailing_lambda_tests/trailing_lambda_define_lambda_in_body-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "trailing_lambda_define_lambda_in_body.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "trailing_lambda_define_lambda_in_body.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "trailing_lambda_define_lambda_in_body.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "trailing_lambda_define_lambda_in_body.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/trailing_lambda_tests/trailing_lambda_define_lambda_in_body_capture_variable-expected.txt b/ets2panda/test/parser/ets/trailing_lambda_tests/trailing_lambda_define_lambda_in_body_capture_variable-expected.txt index f3db4b2b9f..b39d9d47b3 100644 --- a/ets2panda/test/parser/ets/trailing_lambda_tests/trailing_lambda_define_lambda_in_body_capture_variable-expected.txt +++ b/ets2panda/test/parser/ets/trailing_lambda_tests/trailing_lambda_define_lambda_in_body_capture_variable-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "trailing_lambda_define_lambda_in_body_capture_variable.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "trailing_lambda_define_lambda_in_body_capture_variable.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "trailing_lambda_define_lambda_in_body_capture_variable.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "trailing_lambda_define_lambda_in_body_capture_variable.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/trailing_lambda_tests/trailing_lambda_overload-expected.txt b/ets2panda/test/parser/ets/trailing_lambda_tests/trailing_lambda_overload-expected.txt index 6946a0644a..c4d7a62427 100644 --- a/ets2panda/test/parser/ets/trailing_lambda_tests/trailing_lambda_overload-expected.txt +++ b/ets2panda/test/parser/ets/trailing_lambda_tests/trailing_lambda_overload-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "trailing_lambda_overload.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "trailing_lambda_overload.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "trailing_lambda_overload.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "trailing_lambda_overload.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/trailing_lambda_tests/trailing_lambda_overload_1-expected.txt b/ets2panda/test/parser/ets/trailing_lambda_tests/trailing_lambda_overload_1-expected.txt index 77b61783f7..16492ab381 100644 --- a/ets2panda/test/parser/ets/trailing_lambda_tests/trailing_lambda_overload_1-expected.txt +++ b/ets2panda/test/parser/ets/trailing_lambda_tests/trailing_lambda_overload_1-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "trailing_lambda_overload_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "trailing_lambda_overload_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "trailing_lambda_overload_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "trailing_lambda_overload_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/trailing_lambda_tests/trailing_lambda_transform_trailing_block-expected.txt b/ets2panda/test/parser/ets/trailing_lambda_tests/trailing_lambda_transform_trailing_block-expected.txt index 1d7dd000af..66508e10ca 100644 --- a/ets2panda/test/parser/ets/trailing_lambda_tests/trailing_lambda_transform_trailing_block-expected.txt +++ b/ets2panda/test/parser/ets/trailing_lambda_tests/trailing_lambda_transform_trailing_block-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "trailing_lambda_transform_trailing_block.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "trailing_lambda_transform_trailing_block.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "trailing_lambda_transform_trailing_block.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "trailing_lambda_transform_trailing_block.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/trailing_lambda_tests/trailing_lambda_type_alias-expected.txt b/ets2panda/test/parser/ets/trailing_lambda_tests/trailing_lambda_type_alias-expected.txt index 43bc93bd91..06a0e752e6 100644 --- a/ets2panda/test/parser/ets/trailing_lambda_tests/trailing_lambda_type_alias-expected.txt +++ b/ets2panda/test/parser/ets/trailing_lambda_tests/trailing_lambda_type_alias-expected.txt @@ -86,40 +86,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "trailing_lambda_type_alias.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "trailing_lambda_type_alias.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "trailing_lambda_type_alias.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "trailing_lambda_type_alias.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/trailing_lambda_tests/trailing_lambda_with_throw-expected.txt b/ets2panda/test/parser/ets/trailing_lambda_tests/trailing_lambda_with_throw-expected.txt index d003416a3f..edeeb7a594 100644 --- a/ets2panda/test/parser/ets/trailing_lambda_tests/trailing_lambda_with_throw-expected.txt +++ b/ets2panda/test/parser/ets/trailing_lambda_tests/trailing_lambda_with_throw-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "trailing_lambda_with_throw.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/tryFinallyBlockOnly-expected.txt b/ets2panda/test/parser/ets/tryFinallyBlockOnly-expected.txt index 0f1a0ee84d..efc7059279 100644 --- a/ets2panda/test/parser/ets/tryFinallyBlockOnly-expected.txt +++ b/ets2panda/test/parser/ets/tryFinallyBlockOnly-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tryFinallyBlockOnly.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tryFinallyBlockOnly.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tryFinallyBlockOnly.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tryFinallyBlockOnly.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/tupleAsTypeParam1-expected.txt b/ets2panda/test/parser/ets/tupleAsTypeParam1-expected.txt index 53cbb7400e..50de24d7b5 100644 --- a/ets2panda/test/parser/ets/tupleAsTypeParam1-expected.txt +++ b/ets2panda/test/parser/ets/tupleAsTypeParam1-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tupleAsTypeParam1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tupleAsTypeParam1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tupleAsTypeParam1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tupleAsTypeParam1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/tupleAsTypeParam2-expected.txt b/ets2panda/test/parser/ets/tupleAsTypeParam2-expected.txt index 76b23fc597..7c884b4221 100644 --- a/ets2panda/test/parser/ets/tupleAsTypeParam2-expected.txt +++ b/ets2panda/test/parser/ets/tupleAsTypeParam2-expected.txt @@ -525,40 +525,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tupleAsTypeParam2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tupleAsTypeParam2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tupleAsTypeParam2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tupleAsTypeParam2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/tupleIndexWithNumbers-expected.txt b/ets2panda/test/parser/ets/tupleIndexWithNumbers-expected.txt index 96f58b0175..f72997ce91 100644 --- a/ets2panda/test/parser/ets/tupleIndexWithNumbers-expected.txt +++ b/ets2panda/test/parser/ets/tupleIndexWithNumbers-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tupleIndexWithNumbers.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tupleIndexWithNumbers.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tupleIndexWithNumbers.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tupleIndexWithNumbers.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/tuple_type_1-expected.txt b/ets2panda/test/parser/ets/tuple_type_1-expected.txt index 080fbd068c..753dcbb963 100644 --- a/ets2panda/test/parser/ets/tuple_type_1-expected.txt +++ b/ets2panda/test/parser/ets/tuple_type_1-expected.txt @@ -262,40 +262,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tuple_type_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tuple_type_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "tuple_type_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "tuple_type_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/type_alias_1-expected.txt b/ets2panda/test/parser/ets/type_alias_1-expected.txt index 2e88908dfb..3f45f7ab1c 100644 --- a/ets2panda/test/parser/ets/type_alias_1-expected.txt +++ b/ets2panda/test/parser/ets/type_alias_1-expected.txt @@ -102,40 +102,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "type_alias_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "type_alias_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "type_alias_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "type_alias_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/type_alias_2-expected.txt b/ets2panda/test/parser/ets/type_alias_2-expected.txt index 62e22a68e2..b651565da5 100644 --- a/ets2panda/test/parser/ets/type_alias_2-expected.txt +++ b/ets2panda/test/parser/ets/type_alias_2-expected.txt @@ -379,40 +379,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "type_alias_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "type_alias_2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "type_alias_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "type_alias_2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/type_cast-expected.txt b/ets2panda/test/parser/ets/type_cast-expected.txt index 9900fe58cd..a721015acb 100644 --- a/ets2panda/test/parser/ets/type_cast-expected.txt +++ b/ets2panda/test/parser/ets/type_cast-expected.txt @@ -793,40 +793,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "type_cast.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "type_cast.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "type_cast.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "type_cast.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/type_variance1-expected.txt b/ets2panda/test/parser/ets/type_variance1-expected.txt index 6de37ebd6c..6163f42e70 100644 --- a/ets2panda/test/parser/ets/type_variance1-expected.txt +++ b/ets2panda/test/parser/ets/type_variance1-expected.txt @@ -2005,40 +2005,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "type_variance1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "type_variance1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "type_variance1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "type_variance1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/unary_op-expected.txt b/ets2panda/test/parser/ets/unary_op-expected.txt index f02b6cdbc8..10516d0b64 100644 --- a/ets2panda/test/parser/ets/unary_op-expected.txt +++ b/ets2panda/test/parser/ets/unary_op-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "unary_op.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "unary_op.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "unary_op.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "unary_op.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/unary_operations-expected.txt b/ets2panda/test/parser/ets/unary_operations-expected.txt index 70609e3d2e..a9ba27db68 100644 --- a/ets2panda/test/parser/ets/unary_operations-expected.txt +++ b/ets2panda/test/parser/ets/unary_operations-expected.txt @@ -1288,40 +1288,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "unary_operations.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "unary_operations.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "unary_operations.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "unary_operations.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/undefinedNullObjectTypeAnnotation-expected.txt b/ets2panda/test/parser/ets/undefinedNullObjectTypeAnnotation-expected.txt index 4cb5338db7..78996b58f8 100644 --- a/ets2panda/test/parser/ets/undefinedNullObjectTypeAnnotation-expected.txt +++ b/ets2panda/test/parser/ets/undefinedNullObjectTypeAnnotation-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "undefinedNullObjectTypeAnnotation.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "undefinedNullObjectTypeAnnotation.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "undefinedNullObjectTypeAnnotation.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "undefinedNullObjectTypeAnnotation.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/undefinedNullTypeAlias-expected.txt b/ets2panda/test/parser/ets/undefinedNullTypeAlias-expected.txt index 8eb33934b1..4b3e2ea068 100644 --- a/ets2panda/test/parser/ets/undefinedNullTypeAlias-expected.txt +++ b/ets2panda/test/parser/ets/undefinedNullTypeAlias-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "undefinedNullTypeAlias.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "undefinedNullTypeAlias.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "undefinedNullTypeAlias.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "undefinedNullTypeAlias.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/union_lowering_common_property-expected.txt b/ets2panda/test/parser/ets/union_lowering_common_property-expected.txt index cc5e27a018..e8fc70c1a2 100644 --- a/ets2panda/test/parser/ets/union_lowering_common_property-expected.txt +++ b/ets2panda/test/parser/ets/union_lowering_common_property-expected.txt @@ -682,40 +682,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "union_lowering_common_property.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "union_lowering_common_property.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "union_lowering_common_property.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "union_lowering_common_property.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/user_defined_1-expected.txt b/ets2panda/test/parser/ets/user_defined_1-expected.txt index caf22ff02c..f8859d89fc 100644 --- a/ets2panda/test/parser/ets/user_defined_1-expected.txt +++ b/ets2panda/test/parser/ets/user_defined_1-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "user_defined_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "user_defined_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "user_defined_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "user_defined_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/user_defined_2-expected.txt b/ets2panda/test/parser/ets/user_defined_2-expected.txt index b3d63c5a1d..bbf7d8f479 100644 --- a/ets2panda/test/parser/ets/user_defined_2-expected.txt +++ b/ets2panda/test/parser/ets/user_defined_2-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "user_defined_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "user_defined_2.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "user_defined_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "user_defined_2.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/user_defined_22-expected.txt b/ets2panda/test/parser/ets/user_defined_22-expected.txt index 7c8109d86d..51cd61406c 100644 --- a/ets2panda/test/parser/ets/user_defined_22-expected.txt +++ b/ets2panda/test/parser/ets/user_defined_22-expected.txt @@ -360,40 +360,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "user_defined_22.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "user_defined_22.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "user_defined_22.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "user_defined_22.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/user_defined_3-expected.txt b/ets2panda/test/parser/ets/user_defined_3-expected.txt index 59833fcae9..858f5aa777 100644 --- a/ets2panda/test/parser/ets/user_defined_3-expected.txt +++ b/ets2panda/test/parser/ets/user_defined_3-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "user_defined_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "user_defined_3.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "user_defined_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "user_defined_3.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/user_defined_4-expected.txt b/ets2panda/test/parser/ets/user_defined_4-expected.txt index 340ff644fe..7336d1d411 100644 --- a/ets2panda/test/parser/ets/user_defined_4-expected.txt +++ b/ets2panda/test/parser/ets/user_defined_4-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "user_defined_4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "user_defined_4.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "user_defined_4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "user_defined_4.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/user_defined_6-expected.txt b/ets2panda/test/parser/ets/user_defined_6-expected.txt index d3285daa26..8d2467b61a 100644 --- a/ets2panda/test/parser/ets/user_defined_6-expected.txt +++ b/ets2panda/test/parser/ets/user_defined_6-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "user_defined_6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "user_defined_6.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "user_defined_6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "user_defined_6.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/var_declare-expected.txt b/ets2panda/test/parser/ets/var_declare-expected.txt index 4fb4378ee5..e6c6ab3282 100644 --- a/ets2panda/test/parser/ets/var_declare-expected.txt +++ b/ets2panda/test/parser/ets/var_declare-expected.txt @@ -802,40 +802,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "var_declare.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "var_declare.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "var_declare.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "var_declare.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/variable_throw_function_1-expected.txt b/ets2panda/test/parser/ets/variable_throw_function_1-expected.txt index 0fe1d01f9d..68ebafcd7a 100644 --- a/ets2panda/test/parser/ets/variable_throw_function_1-expected.txt +++ b/ets2panda/test/parser/ets/variable_throw_function_1-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "variable_throw_function_1.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "variable_throw_function_1.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/void-expected.txt b/ets2panda/test/parser/ets/void-expected.txt index 8bcec14a9c..45431713d7 100644 --- a/ets2panda/test/parser/ets/void-expected.txt +++ b/ets2panda/test/parser/ets/void-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "void.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "void.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "void.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "void.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/parser/ets/voidAsTypeArg-expected.txt b/ets2panda/test/parser/ets/voidAsTypeArg-expected.txt index 6504393055..8b60ada366 100644 --- a/ets2panda/test/parser/ets/voidAsTypeArg-expected.txt +++ b/ets2panda/test/parser/ets/voidAsTypeArg-expected.txt @@ -23,40 +23,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "voidAsTypeArg.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "voidAsTypeArg.ets" - } - } - }, - "properties": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "voidAsTypeArg.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "voidAsTypeArg.ets" - } - } - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/unit/annotations/CMakeLists.txt b/ets2panda/test/unit/annotations/CMakeLists.txt index ece2c84083..025d3b8bd5 100644 --- a/ets2panda/test/unit/annotations/CMakeLists.txt +++ b/ets2panda/test/unit/annotations/CMakeLists.txt @@ -34,4 +34,7 @@ ets2panda_add_gtest(annotations_retention_policy ) ets2panda_add_gtest(annotations_for_namespace CPP_SOURCES annotations_for_namespace.cpp +) +ets2panda_add_gtest(annotations_module + CPP_SOURCES annotations_module.cpp ) \ No newline at end of file diff --git a/ets2panda/test/unit/annotations/annotations_module.cpp b/ets2panda/test/unit/annotations/annotations_module.cpp new file mode 100644 index 0000000000..9039c308a0 --- /dev/null +++ b/ets2panda/test/unit/annotations/annotations_module.cpp @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include +#include +#include "assembly-program.h" +#include "test/unit/annotations/annotations_emit_test.h" + +namespace ark::es2panda::compiler::test { + +class ModuleAnnotations : public AnnotationEmitTest { +public: + ModuleAnnotations() = default; + + ~ModuleAnnotations() override = default; + + void RunAnnotationEmitTest(const std::string_view text, const std::function &test) + { + auto program = GetCurrentProgram(text); + ASSERT_NE(program, nullptr); + + test(program.get()); + } + +private: + NO_COPY_SEMANTIC(ModuleAnnotations); + NO_MOVE_SEMANTIC(ModuleAnnotations); +}; + +TEST_F(ModuleAnnotations, module_annotation) +{ + std::string_view text = R"( + class A {} + export class ExportedClass {} + namespace B {} + export namespace ExportedNamespace {} + )"; + + auto test = [this](pandasm::Program *program) { + AnnotationEmitTest::CheckModuleAnnotation(program, "ETSGLOBAL", true, {"ExportedClass", "ExportedNamespace"}); + AnnotationEmitTest::CheckModuleAnnotation(program, "ExportedClass", false); + AnnotationEmitTest::CheckModuleAnnotation(program, "ExportedNamespace", true, {}); + }; + RunAnnotationEmitTest(text, test); +} + +TEST_F(ModuleAnnotations, module_annotation_nested) +{ + std::string_view text = R"( + export namespace ExportedNamespace { + class A {} + export class B {} + namespace C {} + export namespace D { + export class A {} + } + } + )"; + + auto test = [this](pandasm::Program *program) { + AnnotationEmitTest::CheckModuleAnnotation(program, "ETSGLOBAL", true, {"ExportedNamespace"}); + AnnotationEmitTest::CheckModuleAnnotation(program, "ExportedNamespace", true, + {"ExportedNamespace.B", "ExportedNamespace.D"}); + AnnotationEmitTest::CheckModuleAnnotation(program, "ExportedNamespace.D", true, {"ExportedNamespace.D.A"}); + }; + RunAnnotationEmitTest(text, test); +} + +} // namespace ark::es2panda::compiler::test \ No newline at end of file diff --git a/ets2panda/test/unit/lowerings/top_level_statements.cpp b/ets2panda/test/unit/lowerings/top_level_statements.cpp index a971de7225..88ef617443 100644 --- a/ets2panda/test/unit/lowerings/top_level_statements.cpp +++ b/ets2panda/test/unit/lowerings/top_level_statements.cpp @@ -27,16 +27,12 @@ TEST_F(LoweringTest, TestTopLevelStmtsSyntheticModuleGlobalClass) CONTEXT(ES2PANDA_STATE_LOWERED, text) { const auto *const ast = GetAst(); - auto *classDef = ast->FindChild( - [](ir::AstNode *child) { return child->IsClassDefinition() && child->AsClassDefinition()->IsGlobal(); }); + [[maybe_unused]] auto *classDef = ast->FindChild([](ir::AstNode *child) { + return child->IsClassDefinition() && + (child->AsClassDefinition()->InternalName().Mutf8() == "dummy.ETSGLOBAL"); + }); ASSERT(classDef != nullptr); - bool foundModuleAnnotation = false; - for (auto *anno : classDef->AsClassDefinition()->Annotations()) { - if (anno->Expr()->AsIdentifier()->Name() == "Module") { - foundModuleAnnotation = true; - } - } - ASSERT_TRUE(foundModuleAnnotation); + ASSERT(classDef->AsClassDefinition()->IsGlobalInitialized()); } } @@ -51,18 +47,84 @@ TEST_F(LoweringTest, TestTopLevelStmtsSyntheticModuleClass) CONTEXT(ES2PANDA_STATE_LOWERED, text) { const auto *const ast = GetAst(); - auto *classDef = ast->FindChild([](ir::AstNode *child) { - return child->IsClassDefinition() && - ((child->AsClassDefinition()->Modifiers() & ir::ClassDefinitionModifiers::CLASS_DECL) != 0U); + [[maybe_unused]] auto *classDef = ast->FindChild([](ir::AstNode *child) { + return child->IsClassDefinition() && (child->AsClassDefinition()->InternalName().Mutf8() == "dummy.X"); }); ASSERT(classDef != nullptr); - bool foundModuleAnnotation = false; - for (auto *anno : classDef->AsClassDefinition()->Annotations()) { - if (anno->Expr()->AsIdentifier()->Name() == "Module") { - foundModuleAnnotation = true; - } + ASSERT(classDef->AsClassDefinition()->IsNamespaceTransformed()); + } +} + +TEST_F(LoweringTest, TestTopLevelStmtsExportedClass) +{ + char const *text = R"( + export class A {} + class B {} + )"; + + CONTEXT(ES2PANDA_STATE_LOWERED, text) + { + const auto *const ast = GetAst(); + auto *classDef = ast->FindChild([](ir::AstNode *child) { + return child->IsClassDefinition() && child->AsClassDefinition()->IsGlobalInitialized(); + }); + ASSERT_NE(classDef, nullptr); + + const auto &exportedClasses = classDef->AsClassDefinition()->ExportedClasses(); + ASSERT_EQ(exportedClasses.size(), 1); + ASSERT_TRUE(exportedClasses[0]->IsExported()); + ASSERT_EQ(exportedClasses[0]->Definition()->InternalName().Mutf8(), "dummy.A"); + } +} + +TEST_F(LoweringTest, TestTopLevelStmtsExportedNamespace) +{ + char const *text = R"( + export namespace A {} + namespace B {} + )"; + + CONTEXT(ES2PANDA_STATE_LOWERED, text) + { + const auto *const ast = GetAst(); + auto *classDef = ast->FindChild([](ir::AstNode *child) { + return child->IsClassDefinition() && child->AsClassDefinition()->IsGlobalInitialized(); + }); + ASSERT_NE(classDef, nullptr); + + const auto &exportedClasses = classDef->AsClassDefinition()->ExportedClasses(); + ASSERT_EQ(exportedClasses.size(), 1); + ASSERT_TRUE(exportedClasses[0]->IsExported()); + ASSERT_EQ(exportedClasses[0]->Definition()->InternalName().Mutf8(), "dummy.A"); + } +} + +TEST_F(LoweringTest, TestTopLevelStmtsExportedNamespaceNested) +{ + char const *text = R"( + export namespace A { + export namespace B {} + namespace C {} + export class D {} + class E {} } - ASSERT_TRUE(foundModuleAnnotation); + )"; + + CONTEXT(ES2PANDA_STATE_LOWERED, text) + { + const auto *const ast = GetAst(); + auto *classDef = ast->FindChild([](ir::AstNode *child) { + return child->IsClassDefinition() && child->AsClassDefinition()->IsNamespaceTransformed(); + }); + ASSERT(classDef != nullptr); + + const auto &exportedClasses = classDef->AsClassDefinition()->ExportedClasses(); + constexpr uint32_t EXPORTED_CLASSES_NUM = 2; + ASSERT_EQ(exportedClasses.size(), EXPORTED_CLASSES_NUM); + ASSERT_TRUE(exportedClasses[0]->IsExported()); + ASSERT_TRUE(exportedClasses[1]->IsExported()); + ASSERT_EQ(exportedClasses[0]->Definition()->InternalName().Mutf8(), "dummy.A.B"); + ASSERT_EQ(exportedClasses[1]->Definition()->InternalName().Mutf8(), "dummy.A.D"); } } diff --git a/ets2panda/test/unit/plugin/e2p_test_plugin_after_bind-expected.txt b/ets2panda/test/unit/plugin/e2p_test_plugin_after_bind-expected.txt index 9980fd7b66..825ed8e0f0 100644 --- a/ets2panda/test/unit/plugin/e2p_test_plugin_after_bind-expected.txt +++ b/ets2panda/test/unit/plugin/e2p_test_plugin_after_bind-expected.txt @@ -11,16 +11,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [] - }, - "properties": [] - } - ], "body": [ { "type": "MethodDefinition", @@ -615,16 +605,6 @@ }, "superClass": null, "implements": [], - "annotations": [ - { - "expr_": { - "type": "Identifier", - "name": "Module", - "decorators": [] - }, - "properties": [] - } - ], "body": [ { "type": "MethodDefinition", diff --git a/ets2panda/test/utils/asm_test.cpp b/ets2panda/test/utils/asm_test.cpp index 9b51817a84..230cb5cd58 100644 --- a/ets2panda/test/utils/asm_test.cpp +++ b/ets2panda/test/utils/asm_test.cpp @@ -137,6 +137,40 @@ void AsmTest::CheckRecordAnnotations(ark::pandasm::Program *program, const std:: } } +void AsmTest::CheckModuleAnnotation(ark::pandasm::Program *program, const std::string &recordName, bool isModule, + const std::vector &expectedAnnotations) +{ + const auto &recordTable = program->recordTable; + ASSERT_FALSE(recordTable.empty()) << "No records found in the program."; + auto found = recordTable.find(recordName); + ASSERT_NE(found, recordTable.end()); + + auto annotations = found->second.metadata->GetAnnotations(); + auto it = std::find_if(annotations.begin(), annotations.end(), [](const ark::pandasm::AnnotationData &annotation) { + return annotation.GetName() == std::string {ark::es2panda::compiler::Signatures::ETS_ANNOTATION_MODULE}; + }); + if (isModule) { + ASSERT_NE(it, annotations.end()) << recordName << " missing expected annotation: " + << ark::es2panda::compiler::Signatures::ETS_ANNOTATION_MODULE; + } else { + ASSERT_EQ(it, annotations.end()) << recordName << " has annotation: " + << ark::es2panda::compiler::Signatures::ETS_ANNOTATION_MODULE + << ", but shouldn't"; + return; + } + ASSERT_EQ(it->GetElements().size(), 1); + const auto &element = it->GetElements()[0]; + ASSERT_EQ(element.GetName(), std::string {ark::es2panda::compiler::Signatures::ANNOTATION_KEY_EXPORTED}) + << recordName << "module annotation missing element " + << ark::es2panda::compiler::Signatures::ANNOTATION_KEY_EXPORTED; + + for (const auto &val : element.GetValue()->GetAsArray()->GetValues()) { + auto name = val.GetValue().GetName(); + auto foundExpected = std::find(expectedAnnotations.begin(), expectedAnnotations.end(), name); + ASSERT_NE(foundExpected, expectedAnnotations.end()) << "Value mismatch for " + name; + } +} + void AsmTest::CheckRecordWithoutAnnotations(ark::pandasm::Program *program, const std::string &recordName, bool isModule) { diff --git a/ets2panda/test/utils/asm_test.h b/ets2panda/test/utils/asm_test.h index 5dcef0c1e0..e58fde52fd 100644 --- a/ets2panda/test/utils/asm_test.h +++ b/ets2panda/test/utils/asm_test.h @@ -71,6 +71,9 @@ public: void CheckRecordAnnotations(ark::pandasm::Program *program, const std::string &recordName, const AnnotationMap &expectedAnnotations); + void CheckModuleAnnotation(ark::pandasm::Program *program, const std::string &recordName, bool isModule, + const std::vector &expectedAnnotations = {}); + void CheckRecordWithoutAnnotations(ark::pandasm::Program *program, const std::string &recordName, bool isModule = false); -- Gitee From 2f0ee722ff2eb3d05d1aa7f48944e23e8347c778 Mon Sep 17 00:00:00 2001 From: Zhelyapov Aleksey Date: Tue, 11 Mar 2025 19:38:40 +0300 Subject: [PATCH 101/268] Provide compiler options, arktsconfig plugin API Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBNQGE Signed-off-by: Zhelyapov Aleksey Change-Id: If5679163e149099e1e38f0f4242f3b33388267f5 --- ets2panda/public/CMakeLists.txt | 6 + ets2panda/public/cppToCTypes.yaml | 260 ++++++++++++++---- ets2panda/public/es2panda_lib.cpp | 34 ++- ets2panda/public/es2panda_lib.h | 12 + ets2panda/public/es2panda_lib.idl.erb | 13 + ets2panda/public/es2panda_lib.rb | 83 +++--- ets2panda/public/es2panda_lib_impl.inc.erb | 4 +- ets2panda/public/headers_parser/cpp_parser.py | 18 +- .../public/headers_parser/line_iterator.py | 13 +- .../public/headers_parser/parse_using.py | 18 +- ets2panda/public/ignoredAllowed.yaml | 13 +- ets2panda/test/unit/plugin/CMakeLists.txt | 1 + .../plugin_proceed_to_state_arktsconfig.cpp | 67 +++++ .../plugin_conversion_rule_part_iii.cpp | 4 +- ets2panda/util/options.h | 26 +- 15 files changed, 440 insertions(+), 132 deletions(-) create mode 100644 ets2panda/test/unit/plugin/plugin_proceed_to_state_arktsconfig.cpp diff --git a/ets2panda/public/CMakeLists.txt b/ets2panda/public/CMakeLists.txt index b887bce27e..487f24869d 100644 --- a/ets2panda/public/CMakeLists.txt +++ b/ets2panda/public/CMakeLists.txt @@ -27,6 +27,7 @@ set(ES2PANDA_API set (HEADERS_TO_BE_PARSED ${ES2PANDA_ROOT}/varbinder/variableFlags.h ${GENERATED_DIR}/options.h + ${ES2PANDA_ROOT}/util/options.h ${ES2PANDA_ROOT}/lexer/regexp/regexp.h ${ES2PANDA_ROOT}/util/language.h ${GENERATED_DIR}/tokenType.h @@ -289,11 +290,14 @@ set (HEADERS_TO_BE_PARSED ${ES2PANDA_ROOT}/es2panda.h ${ES2PANDA_ROOT}/ast_verifier/ASTVerifier.h ${ES2PANDA_ROOT}/util/importPathManager.h + ${ES2PANDA_ROOT}/util/path.h + ${ES2PANDA_ROOT}/util/arktsconfig.h ) set (ES2PANDA_API_GENERATED ${LIBGEN_DIR}/gen/headers/checker/types/typeMapping.yaml ${LIBGEN_DIR}/gen/headers/options.yaml + ${LIBGEN_DIR}/gen/headers/util/options.yaml ${LIBGEN_DIR}/gen/headers/ir/astNodeMapping.yaml ${LIBGEN_DIR}/gen/headers/varbinder/variableFlags.yaml ${LIBGEN_DIR}/gen/headers/ir/typed.yaml @@ -556,6 +560,8 @@ set (ES2PANDA_API_GENERATED ${LIBGEN_DIR}/gen/headers/parser/program/program.yaml ${LIBGEN_DIR}/gen/headers/ast_verifier/ASTVerifier.yaml ${LIBGEN_DIR}/gen/headers/util/importPathManager.yaml + ${LIBGEN_DIR}/gen/headers/util/path.yaml + ${LIBGEN_DIR}/gen/headers/util/arktsconfig.yaml ) diff --git a/ets2panda/public/cppToCTypes.yaml b/ets2panda/public/cppToCTypes.yaml index abc68ed739..42f4006ec8 100644 --- a/ets2panda/public/cppToCTypes.yaml +++ b/ets2panda/public/cppToCTypes.yaml @@ -416,11 +416,11 @@ change_types: \tauto resultSet = " end: ";\n \t*|return_args.0.name| = resultSet|accessor|size();\n - \tauto res = ctxAllocator->New<|new_args.0.type.const| |new_args.0.type.name| |new_args.0.type.ptr_depth - 1||new_args.0.type.ref_depth|[]>(*|return_args.0.name|);\n + \tauto apiRes = ctxAllocator->New<|new_args.0.type.const| |new_args.0.type.name| |new_args.0.type.ptr_depth - 1||new_args.0.type.ref_depth|[]>(*|return_args.0.name|);\n \tsize_t i = 0;\n \tfor (auto elem : resultSet) {\n \t\tauto toPush = |reverse_template_nested_expression_1_start|(elem)|reverse_template_nested_expression_1_end|;\n - \t\tres[i] = reinterpret_cast<|new_args.0.type.const| |new_args.0.type.name| |new_args.0.type.ptr_depth - 1||new_args.0.type.ref_depth|>(toPush);\n + \t\tapiRes[i++] = reinterpret_cast<|new_args.0.type.const| |new_args.0.type.name| |new_args.0.type.ptr_depth - 1||new_args.0.type.ref_depth|>(toPush);\n \t}" - es2panda_arg: @@ -462,11 +462,11 @@ change_types: \tauto resultSet = " end: ";\n \t*|return_args.0.name| = resultSet|accessor|size();\n - \tauto res = ctxAllocator->New<|new_args.0.type.const| |new_args.0.type.name| |new_args.0.type.ptr_depth - 1||new_args.0.type.ref_depth|[]>(*|return_args.0.name|);\n + \tauto apiRes = ctxAllocator->New<|new_args.0.type.const| |new_args.0.type.name| |new_args.0.type.ptr_depth - 1||new_args.0.type.ref_depth|[]>(*|return_args.0.name|);\n \tsize_t i = 0;\n \tfor (auto elem : resultSet) {\n \t\tauto toPush = |reverse_template_nested_expression_1_start|(elem)|reverse_template_nested_expression_1_end|;\n - \t\tres[i] = reinterpret_cast<|new_args.0.type.const| |new_args.0.type.name| |new_args.0.type.ptr_depth - 1||new_args.0.type.ref_depth|>(toPush);\n + \t\tres[i++] = reinterpret_cast<|new_args.0.type.const| |new_args.0.type.name| |new_args.0.type.ptr_depth - 1||new_args.0.type.ref_depth|>(toPush);\n \t}" - es2panda_arg: @@ -634,11 +634,11 @@ change_types: \tauto resultMap = " end: ";\n \t*|return_args.1.name| = resultMap|accessor|size();\n - \tauto res = ctxAllocator->New<|new_args.0.type.const| |new_args.0.type.name| |new_args.0.type.ptr_depth - 1||new_args.0.type.ref_depth|[]>(*|return_args.1.name|);\n + \tauto apiRes = ctxAllocator->New<|new_args.0.type.const| |new_args.0.type.name| |new_args.0.type.ptr_depth - 1||new_args.0.type.ref_depth|[]>(*|return_args.1.name|);\n \t*|return_args.0.name| = ctxAllocator->New<|new_args.1.type.const| |new_args.1.type.name| |new_args.1.type.ptr_depth - 1||new_args.1.type.ref_depth|[]>(*|return_args.1.name|);\n \tsize_t i = 0;\n \tfor (auto [key, value] : resultMap) {\n - \t\tres[i] = |reverse_template_nested_expression_1_start|(key)|reverse_template_nested_expression_1_end|;\n + \t\tapiRes[i] = |reverse_template_nested_expression_1_start|(key)|reverse_template_nested_expression_1_end|;\n \t\t(*|return_args.0.name|)[i] = |reverse_template_nested_expression_2_start|(value)|reverse_template_nested_expression_2_end|;\n \t\t++i;\n \t}" @@ -694,11 +694,11 @@ change_types: \tauto resultMap = " end: ";\n \t*|return_args.1.name| = resultMap|accessor|size();\n - \tauto res = ctxAllocator->New<|new_args.0.type.const| |new_args.0.type.name| |new_args.0.type.ptr_depth - 1||new_args.0.type.ref_depth|[]>(*|return_args.1.name|);\n + \tauto apiRes = ctxAllocator->New<|new_args.0.type.const| |new_args.0.type.name| |new_args.0.type.ptr_depth - 1||new_args.0.type.ref_depth|[]>(*|return_args.1.name|);\n \t*|return_args.0.name| = ctxAllocator->New<|new_args.1.type.const| |new_args.1.type.name| |new_args.1.type.ptr_depth - 1||new_args.1.type.ref_depth|[]>(*|return_args.1.name|);\n \tsize_t i = 0;\n \tfor (auto [key, value] : (*resultMap)) {\n - \t\tres[i] = |reverse_template_nested_expression_1_start|(key)|reverse_template_nested_expression_1_end|;\n + \t\tapiRes[i] = |reverse_template_nested_expression_1_start|(key)|reverse_template_nested_expression_1_end|;\n \t\t(*|return_args.0.name|)[i] = |reverse_template_nested_expression_2_start|(value)|reverse_template_nested_expression_2_end|;\n \t\t++i;\n \t}" @@ -1175,7 +1175,7 @@ change_types: namespace: 'checker::' cast: expression: >- - auto |arg_name|E2p = + auto &|arg_name|E2p = *(reinterpret_cast(|arg_name|)); var_name: '|arg_name|E2p' @@ -2289,7 +2289,7 @@ change_types: namespace: 'lexer::' cast: expression: >- - auto |arg_name|E2p = *reinterpret_cast(|arg_name|); + auto &|arg_name|E2p = *reinterpret_cast(|arg_name|); reverse_cast: start: >- reinterpret_cast( @@ -2344,7 +2344,7 @@ change_types: namespace: 'lexer::' cast: expression: >- - auto |arg_name|E2p = *reinterpret_cast(|arg_name|); + auto &|arg_name|E2p = *reinterpret_cast(|arg_name|); reverse_cast: start: >- reinterpret_cast( @@ -2378,7 +2378,7 @@ change_types: name: es2panda_ErrorLogger ptr_depth: 1 start: >- - (reinterpret_cast(ast))-> + (reinterpret_cast(ast))-> constructor_cast: start: >- ctxAllocator->New( @@ -2399,7 +2399,7 @@ change_types: namespace: 'util::' cast: expression: >- - auto |arg_name|E2p = *reinterpret_cast(|arg_name|); + auto &|arg_name|E2p = *(reinterpret_cast(|arg_name|)); var_name: '|arg_name|E2p' - es2panda_arg: @@ -2449,7 +2449,7 @@ change_types: namespace: 'compiler::' cast: expression: >- - auto |arg_name|E2p = *reinterpret_cast(|arg_name|); + auto &|arg_name|E2p = *reinterpret_cast(|arg_name|); reverse_cast: start: >- reinterpret_cast( @@ -2504,7 +2504,7 @@ change_types: namespace: 'compiler::' cast: expression: >- - auto |arg_name|E2p = *reinterpret_cast(|arg_name|); + auto &|arg_name|E2p = *reinterpret_cast(|arg_name|); reverse_cast: start: >- reinterpret_cast( @@ -3005,7 +3005,7 @@ change_types: namespace: 'checker::' cast: expression: >- - auto |arg_name|E2p = + auto &|arg_name|E2p = *(reinterpret_cast(|arg_name|)); reverse_cast: start: >- @@ -3014,34 +3014,6 @@ change_types: end: ) var_name: '|arg_name|E2p' - - es2panda_arg: - name: '|arg_name|' - type: - name: 'CompilerOptions' - max_ptr_depth: 1 - min_ptr_depth: 1 - new_args: - cast: - expression: >- - auto |arg_name|E2p = - &(reinterpret_cast(context)->config->options->CompilerOptions()); - call_cast: - start: >- - (reinterpret_cast(context)->config->options->CompilerOptions(). - var_name: '|arg_name|E2p' - - - es2panda_arg: - name: '|arg_name|' - type: - name: 'CompilerOptions' - max_ptr_depth: 0 - new_args: - cast: - expression: >- - auto |arg_name|E2p = - reinterpret_cast(context)->config->options->CompilerOptions(); - var_name: '|arg_name|E2p' - - es2panda_arg: name: '|arg_name|' type: @@ -3089,7 +3061,7 @@ change_types: namespace: 'checker::' cast: expression: >- - auto |arg_name|E2p = + auto &|arg_name|E2p = *(reinterpret_cast(|arg_name|)); var_name: '|arg_name|E2p' @@ -3259,7 +3231,7 @@ change_types: namespace: 'compiler::ast_verifier::' cast: expression: >- - auto |arg_name|E2p = + auto &|arg_name|E2p = *(reinterpret_cast(|arg_name|)); var_name: '|arg_name|E2p' @@ -3310,7 +3282,7 @@ change_types: namespace: 'compiler::ast_verifier::' cast: expression: >- - auto |arg_name|E2p = + auto &|arg_name|E2p = *(reinterpret_cast(|arg_name|)); var_name: '|arg_name|E2p' @@ -3361,7 +3333,7 @@ change_types: namespace: 'compiler::ast_verifier::' cast: expression: >- - auto |arg_name|E2p = + auto &|arg_name|E2p = *(reinterpret_cast(|arg_name|)); reverse_cast: start: >- @@ -3793,7 +3765,7 @@ change_types: |arg_name|E2p->specifier = |arg_name|specifier;\n |arg_name|E2p->variable = |arg_name|variable;\n" reverse_cast: - start: DynamicImportDataToE2p(reinterpret_cast(context)->allocator, + start: DynamicImportDataToE2pPtr(reinterpret_cast(context)->allocator, end: ) var_name: "|arg_name|E2p" @@ -3823,6 +3795,59 @@ change_types: end: ) var_name: "|arg_name|E2p" + - es2panda_arg: + name: '|arg_name|' + type: + name: OverloadInfo + namespace: ir + max_ptr_depth: 1 + min_ptr_depth: 1 + new_args: + - name: '|arg_name|' + type: + name: es2panda_OverloadInfo + ptr_depth: 1 + namespace: 'ir::' + cast: + expression: "\ + auto |arg_name|E2p = reinterpret_cast(context)->allocator->New(); + |arg_name|E2p->minArg = |arg_name|->minArg;\n + |arg_name|E2p->maxArg = |arg_name|->maxArg;\n + |arg_name|E2p->needHelperOverload = |arg_name|->needHelperOverload;\n + |arg_name|E2p->isDeclare = |arg_name|->isDeclare;\n + |arg_name|E2p->hasRestVar = |arg_name|->hasRestVar;\n + |arg_name|E2p->returnVoid = |arg_name|->returnVoid;\n" + reverse_cast: + start: OverloadInfoToE2pPtr(reinterpret_cast(context)->allocator, + end: ) + var_name: "|arg_name|E2p" + + - es2panda_arg: + name: '|arg_name|' + type: + name: OverloadInfo + namespace: ir + max_ptr_depth: 0 + new_args: + - name: '|arg_name|' + type: + name: es2panda_OverloadInfo + ptr_depth: 0 + namespace: 'ir::' + cast: + expression: "\ + ir::OverloadInfo |arg_name|E2p; + |arg_name|E2p.minArg = |arg_name|.minArg;\n + |arg_name|E2p.maxArg = |arg_name|.maxArg;\n + |arg_name|E2p.needHelperOverload = |arg_name|.needHelperOverload;\n + |arg_name|E2p.isDeclare = |arg_name|.isDeclare;\n + |arg_name|E2p.hasRestVar = |arg_name|.hasRestVar;\n + |arg_name|E2p.returnVoid = |arg_name|.returnVoid;\n" + reverse_cast: + start: OverloadInfoToE2p( + end: ) + var_name: "|arg_name|E2p" + - es2panda_arg: name: '|arg_name|' type: @@ -3883,3 +3908,140 @@ change_types: ctxAllocator->New( end: ) var_name: '|arg_name|E2p' + + - es2panda_arg: + name: '|arg_name|' + type: + name: Path + namespace: util + max_ptr_depth: 0 + new_args: + - type: + name: es2panda_Path + ptr_depth: 1 + name: '|arg_name|' + cast: + expression: >- + auto &|arg_name|E2p = + *(reinterpret_cast(|arg_name|)); + reverse_cast: + start: >- + reinterpret_cast(reinterpret_cast(context)->allocator-> + New + end: ) + var_name: '|arg_name|E2p' + + - es2panda_arg: + name: '|arg_name|' + type: + name: Path + namespace: util + min_ptr_depth: 1 + new_args: + - type: + name: 'es2panda_Path' + ptr_depth: '|es2panda_arg.type.ptr_depth_int|' + name: '|arg_name|' + cast: + expression: >- + auto |es2panda_arg.type.ptr_depth||arg_name|E2p = + reinterpret_cast(|arg_name|); + reverse_cast: + start: >- + reinterpret_cast + call_cast: + call_var: + name: classInstance + type: + name: es2panda_Path + ptr_depth: 1 + start: >- + (reinterpret_cast(classInstance))-> + constructor_cast: + start: >- + ctxAllocator->New( + end: ) + var_name: '|arg_name|E2p' + + - es2panda_arg: + name: '|arg_name|' + type: + name: 'Options' + namespace: 'gen' + min_ptr_depth: 1 + new_args: + - type: + name: 'es2panda_Options' + ptr_depth: '|es2panda_arg.type.ptr_depth_int|' + name: '|arg_name|' + cast: + expression: >- + auto |es2panda_arg.type.ptr_depth||arg_name|E2p = + reinterpret_cast(|arg_name|); + reverse_cast: + start: >- + reinterpret_cast + call_cast: + call_var: + name: classInstance + type: + name: es2panda_Options + ptr_depth: 1 + start: >- + (reinterpret_cast(classInstance))-> + constructor_cast: + start: >- + ctxAllocator->New( + end: ) + var_name: '|arg_name|E2p' + + - es2panda_arg: + name: '|arg_name|' + type: + name: 'Options' + namespace: 'util' + min_ptr_depth: 1 + new_args: + - type: + name: 'es2panda_Options' + ptr_depth: '|es2panda_arg.type.ptr_depth_int|' + name: '|arg_name|' + cast: + expression: >- + auto |es2panda_arg.type.ptr_depth||arg_name|E2p = + reinterpret_cast(|arg_name|); + reverse_cast: + start: >- + reinterpret_cast + call_cast: + call_var: + name: classInstance + type: + name: es2panda_Options + ptr_depth: 1 + start: >- + (reinterpret_cast(classInstance))-> + constructor_cast: + start: >- + ctxAllocator->New( + end: ) + var_name: '|arg_name|E2p' + + - es2panda_arg: + name: '|arg_name|' + type: + name: arg_list_t + namespace: gen + max_ptr_depth: 0 + new_args: + - name: '|arg_name|' + type: + name: vector + namespace: std + ref_depth: 2 + template_args: + - type: + name: string + namespace: std + cast: + reverse_cast: {} diff --git a/ets2panda/public/es2panda_lib.cpp b/ets2panda/public/es2panda_lib.cpp index 85aba29870..bc6c735e7f 100644 --- a/ets2panda/public/es2panda_lib.cpp +++ b/ets2panda/public/es2panda_lib.cpp @@ -151,7 +151,7 @@ __attribute__((unused)) es2panda_variantDoubleCharArrayBool EnumMemberResultToEs // NOLINTEND(cppcoreguidelines-pro-type-union-access) } -__attribute__((unused)) es2panda_DynamicImportData *DynamicImportDataToE2p( +__attribute__((unused)) es2panda_DynamicImportData *DynamicImportDataToE2pPtr( ArenaAllocator *allocator, const varbinder::DynamicImportData *dynamicImportData) { auto import = reinterpret_cast(dynamicImportData->import); @@ -177,6 +177,31 @@ __attribute__((unused)) es2panda_DynamicImportData DynamicImportDataToE2p( return es2pandaDynamicImportData; } +__attribute__((unused)) es2panda_OverloadInfo *OverloadInfoToE2pPtr(ArenaAllocator *allocator, + const ir::OverloadInfo *overloadInfo) +{ + auto es2pandaOverloadInfo = allocator->New(); + es2pandaOverloadInfo->minArg = overloadInfo->minArg; + es2pandaOverloadInfo->maxArg = overloadInfo->maxArg; + es2pandaOverloadInfo->needHelperOverload = overloadInfo->needHelperOverload; + es2pandaOverloadInfo->isDeclare = overloadInfo->isDeclare; + es2pandaOverloadInfo->hasRestVar = overloadInfo->hasRestVar; + es2pandaOverloadInfo->returnVoid = overloadInfo->returnVoid; + return es2pandaOverloadInfo; +} + +__attribute__((unused)) es2panda_OverloadInfo OverloadInfoToE2p(const ir::OverloadInfo overloadInfo) +{ + es2panda_OverloadInfo es2pandaOverloadInfo; + es2pandaOverloadInfo.minArg = overloadInfo.minArg; + es2pandaOverloadInfo.maxArg = overloadInfo.maxArg; + es2pandaOverloadInfo.needHelperOverload = overloadInfo.needHelperOverload; + es2pandaOverloadInfo.isDeclare = overloadInfo.isDeclare; + es2pandaOverloadInfo.hasRestVar = overloadInfo.hasRestVar; + es2pandaOverloadInfo.returnVoid = overloadInfo.returnVoid; + return es2pandaOverloadInfo; +} + __attribute__((unused)) char const *ArenaStrdup(ArenaAllocator *allocator, char const *src) { size_t len = strlen(src); @@ -223,6 +248,12 @@ extern "C" void DestroyConfig(es2panda_Config *config) delete cfg; } +extern "C" const es2panda_Options *ConfigGetOptions(es2panda_Config *config) +{ + auto options = reinterpret_cast(config)->options; + return reinterpret_cast(options); +} + static void CompileJob(public_lib::Context *context, varbinder::FunctionScope *scope, compiler::ProgramElement *programElement) { @@ -776,6 +807,7 @@ es2panda_Impl g_impl = { CreateConfig, DestroyConfig, + ConfigGetOptions, CreateContextFromFile, CreateContextFromString, ProceedToState, diff --git a/ets2panda/public/es2panda_lib.h b/ets2panda/public/es2panda_lib.h index fd81b6825a..abb337215d 100644 --- a/ets2panda/public/es2panda_lib.h +++ b/ets2panda/public/es2panda_lib.h @@ -100,6 +100,8 @@ typedef struct es2panda_ImportPathManager es2panda_ImportPathManager; typedef struct es2panda_DiagnosticKind es2panda_DiagnosticKind; typedef struct es2panda_DiagnosticMessageParams es2panda_DiagnosticMessageParams; typedef struct es2panda_DiagnosticStorage es2panda_DiagnosticStorage; +typedef struct es2panda_Path es2panda_Path; +typedef struct es2panda_Options es2panda_Options; typedef void (*NodeTraverser)(es2panda_AstNode *); typedef es2panda_AstNode *(*NodeTransformer)(es2panda_AstNode *); typedef bool (*NodePredicate)(es2panda_AstNode *); @@ -117,6 +119,15 @@ typedef struct es2panda_DynamicImportData { es2panda_Variable *variable; } es2panda_DynamicImportData; +typedef struct es2panda_OverloadInfo { + uint32_t minArg; + size_t maxArg; + bool needHelperOverload; + bool isDeclare; + bool hasRestVar; + bool returnVoid; +} es2panda_OverloadInfo; + enum es2panda_ContextState { ES2PANDA_STATE_NEW, ES2PANDA_STATE_PARSED, @@ -138,6 +149,7 @@ struct CAPI_EXPORT es2panda_Impl { es2panda_Config *(*CreateConfig)(int argc, char const *const *argv); void (*DestroyConfig)(es2panda_Config *config); + const es2panda_Options *(*ConfigGetOptions)(es2panda_Config *config); es2panda_Context *(*CreateContextFromFile)(es2panda_Config *config, char const *source_file_name); es2panda_Context *(*CreateContextFromString)(es2panda_Config *config, const char *source, char const *file_name); diff --git a/ets2panda/public/es2panda_lib.idl.erb b/ets2panda/public/es2panda_lib.idl.erb index b2e0a9335c..a6262004b5 100644 --- a/ets2panda/public/es2panda_lib.idl.erb +++ b/ets2panda/public/es2panda_lib.idl.erb @@ -56,6 +56,9 @@ typedef (String or f64 or boolean) es2panda_variantDoubleCharArrayBool; [Entity=Class] interface es2panda_IRNode {}; [Entity=Class] interface es2panda_ErrorLogger {}; [Entity=Class] interface es2panda_VerificationContext {}; +[Entity=Class] interface es2panda_ImportPathManager {}; +[Entity=Class] interface es2panda_Path {}; +[Entity=Class] interface es2panda_Options {}; interface NodeTraverser { @@ -102,6 +105,15 @@ interface es2panda_DynamicImportData { attribute Variable variable; }; +interface es2panda_OverloadInfo { + attribute u32 minArg; + attribute u32 maxArg; + attribute boolean needHelperOverload; + attribute boolean isDeclare; + attribute boolean hasRestVar; + attribute boolean returnVoid; +}; + dictionary es2panda_ContextState { i32 ES2PANDA_STATE_NEW = 0; i32 ES2PANDA_STATE_PARSED = 1; @@ -138,6 +150,7 @@ typedef u64 Es2panda<%= name %>; interface es2panda_Impl { es2panda_Config CreateConfig(i32 argc, sequence argv); void DestroyConfig(es2panda_Config config); + const es2panda_Options ConfigGetOptions(es2panda_Config config); es2panda_Context CreateContextFromFile(es2panda_Config config, String source_file_name); es2panda_Context CreateContextFromString(es2panda_Config config, String source, String file_name); diff --git a/ets2panda/public/es2panda_lib.rb b/ets2panda/public/es2panda_lib.rb index c1cfbf060a..bea7bab2a7 100644 --- a/ets2panda/public/es2panda_lib.rb +++ b/ets2panda/public/es2panda_lib.rb @@ -1097,6 +1097,10 @@ module Es2pandaLibApi type = 'AST Verifier functions' elsif class_base_namespace == 'util' type = 'Import path manager' + elsif class_base_namespace == 'gen' + type = 'Compiler options' + elsif class_base_namespace == 'es2panda' + type = 'Arkts config' else raise "Unsupported class type for stats class name: \"" + class_name + "\" class namespace: \"" + class_base_namespace + "\"" @@ -1207,6 +1211,9 @@ module Es2pandaLibApi CheckMessage Program ImportPathManager + Options + ArkTsConfig + Path ] end @@ -1306,6 +1313,9 @@ module Es2pandaLibApi es2panda_AstVerifier es2panda_VerifierMessage es2panda_ImportPathManager + es2panda_Options + es2panda_Path + es2panda_OverloadInfo ] end @@ -1351,6 +1361,19 @@ module Es2pandaLibApi res end + def extract_classes_in_namespace(data, namespace_name, &is_class_needed) + @classes[namespace_name] = {} unless @classes[namespace_name] + data[namespace_name]&.class_definitions&.each do |class_definition| + if is_class_needed.call(class_definition.name) + class_data = ClassData.new(class_definition&.public) + class_data.class_base_namespace = namespace_name + class_data.extends_classname = extends_to_idl(class_definition.extends) + class_data.template_extends = [] + @classes[namespace_name][class_definition.name] = class_data + end + end + end + def wrap_data(data) return unless data @@ -1408,52 +1431,18 @@ module Es2pandaLibApi @classes['ir'][class_definition.name] = class_data end - @classes['checker'] = {} unless @classes['checker'] - data['checker']&.class_definitions&.each do |class_definition| - if @ast_types.include?(class_definition.name) || ast_type_additional_children.include?(class_definition.name) || - additional_classes_to_generate.include?(class_definition.name) - class_data = ClassData.new(class_definition&.public) - class_data.class_base_namespace = 'checker' - class_data.extends_classname = extends_to_idl(class_definition.extends) - class_data.template_extends = [] - @classes['checker'][class_definition.name] = class_data - end - end - - @classes['varbinder'] = {} unless @classes['varbinder'] - data['varbinder']&.class_definitions&.each do |class_definition| - if scopes.include?(class_definition.name) || declarations.include?(class_definition.name) || - ast_variables.find { |x| x[1] == class_definition.name } || - additional_classes_to_generate.include?(class_definition.name) - class_data = ClassData.new(class_definition&.public) - class_data.class_base_namespace = 'varbinder' - class_data.extends_classname = extends_to_idl(class_definition.extends) - class_data.template_extends = [] - @classes['varbinder'][class_definition.name] = class_data - end - end - - @classes['parser'] = {} unless @classes['parser'] - data['parser']&.class_definitions&.each do |class_definition| - if additional_classes_to_generate.include?(class_definition.name) - class_data = ClassData.new(class_definition&.public) - class_data.class_base_namespace = 'parser' - class_data.extends_classname = extends_to_idl(class_definition.extends) - class_data.template_extends = [] - @classes['parser'][class_definition.name] = class_data - end - end - - @classes['util'] = {} unless @classes['util'] - data['util']&.class_definitions&.each do |class_definition| - if additional_classes_to_generate.include?(class_definition.name) - class_data = ClassData.new(class_definition&.public) - class_data.class_base_namespace = 'util' - class_data.extends_classname = extends_to_idl(class_definition.extends) - class_data.template_extends = [] - @classes['util'][class_definition.name] = class_data - end - end + extract_classes_in_namespace(data, 'checker') { |class_name| + @ast_types.include?(class_name) || ast_type_additional_children.include?(class_name) || + additional_classes_to_generate.include?(class_name) + } + extract_classes_in_namespace(data, 'varbinder') { |class_name| + scopes.include?(class_name) || declarations.include?(class_name) || + ast_variables.find { |x| x[1] == class_name } || additional_classes_to_generate.include?(class_name) + } + extract_classes_in_namespace(data, 'parser') { |class_name| additional_classes_to_generate.include?(class_name) } + extract_classes_in_namespace(data, 'util') { |class_name| additional_classes_to_generate.include?(class_name) } + extract_classes_in_namespace(data, 'gen') { |class_name| additional_classes_to_generate.include?(class_name) } + extract_classes_in_namespace(data, 'es2panda') { |class_name| additional_classes_to_generate.include?(class_name) } @classes['ast_verifier'] = {} unless @classes['ast_verifier'] data['ast_verifier']&.class_definitions&.each do |class_definition| @@ -1472,7 +1461,7 @@ module Es2pandaLibApi :additional_classes_to_generate, :ast_type_additional_children, :scopes, :ast_variables, :deep_to_h, :no_usings_replace_info, :declarations, :check_template_type_presents, :structs, :additional_containers, :stat_add_constructor_type, :stat_add_method_type, :check_class_type, - :extends_to_idl, :template_extends, :template_extends_classes + :extends_to_idl, :template_extends, :template_extends_classes, :extract_classes_in_namespace end def Gen.on_require(data) diff --git a/ets2panda/public/es2panda_lib_impl.inc.erb b/ets2panda/public/es2panda_lib_impl.inc.erb index c2aece82c3..e2ecc21172 100644 --- a/ets2panda/public/es2panda_lib_impl.inc.erb +++ b/ets2panda/public/es2panda_lib_impl.inc.erb @@ -186,7 +186,7 @@ char const *AstNodeName(es2panda_AstNode *ast) return "Unknown AstNode"; } -// NOLINTBEGIN(performance-for-range-copy) +// NOLINTBEGIN(performance-for-range-copy, readability-identifier-naming) % Es2pandaLibApi::classes&.each do |namespaceName, namespaceClasses| % namespaceClasses&.each do |className, classData| @@ -306,5 +306,5 @@ then structData.call_cast["call_var_str"] end %>/*return_args:*/<%= method_info[ % Es2pandaLibApi::print_stats -// NOLINTEND(performance-for-range-copy) +// NOLINTEND(performance-for-range-copy, readability-identifier-naming) // NOLINTEND(cppcoreguidelines-pro-bounds-pointer-arithmetic, readability-non-const-parameter) \ No newline at end of file diff --git a/ets2panda/public/headers_parser/cpp_parser.py b/ets2panda/public/headers_parser/cpp_parser.py index e69579d3cf..7d33d64f98 100644 --- a/ets2panda/public/headers_parser/cpp_parser.py +++ b/ets2panda/public/headers_parser/cpp_parser.py @@ -58,6 +58,10 @@ class CppParser: elif self.it.is_template(): self.it.end, self.template = parse_template_prefix(self.it.data, self.it.start) + elif self.it.is_using(): + self.it.end, self.parsed = parse_using(self.it.data, self.it.start) + self.res_append_in_modifier("usings") + elif self.it.is_namespace(): self.it.end, self.parsed = parse_namespace(self.it.data, self.it.start) self.res_update() @@ -70,10 +74,6 @@ class CppParser: self.it.end, self.parsed = parse_struct(self.it.data, self.it.start) self.res_append("structs") - elif self.it.is_using(): - self.it.end, self.parsed = parse_using(self.it.data, self.it.start) - self.res_append_in_modifier("usings") - elif self.it.is_define_macro(): self.it.end, self.parsed = parse_define_macros(self.it.data, self.it.start) self.res_append("macros") @@ -130,10 +130,10 @@ class CppParser: return raise RuntimeError("Unreachable") - if key not in self.res[self.current_modifier]: # CC-OFF(G.TYP.07) dict key exist - self.res[self.current_modifier][key] = [] # CC-OFF(G.TYP.07) dict key exist + if key not in self.res[self.current_modifier]: # CC-OFF(G.TYP.07) dict key exist + self.res[self.current_modifier][key] = [] # CC-OFF(G.TYP.07) dict key exist - self.res[self.current_modifier][key].append(deep_copy(self.parsed)) # CC-OFF(G.TYP.07) dict key exist + self.res[self.current_modifier][key].append(deep_copy(self.parsed)) # CC-OFF(G.TYP.07) dict key exist def res_update(self) -> None: if self.parsed: @@ -165,11 +165,11 @@ class CppParser: return # Constructor - if self.parsed["name"] == self.parent_class_name: # CC-OFF(G.TYP.07) dict key exist + if self.parsed["name"] == self.parent_class_name: # CC-OFF(G.TYP.07) dict key exist self.res_append_in_modifier("constructors") # Destructor - elif self.parsed["name"] == "~" + self.parent_class_name: # CC-OFF(G.TYP.07) dict key exist + elif self.parsed["name"] == "~" + self.parent_class_name: # CC-OFF(G.TYP.07) dict key exist self.res_append_in_modifier("destructors") # Method diff --git a/ets2panda/public/headers_parser/line_iterator.py b/ets2panda/public/headers_parser/line_iterator.py index 1a66aa5bc9..734799fb44 100644 --- a/ets2panda/public/headers_parser/line_iterator.py +++ b/ets2panda/public/headers_parser/line_iterator.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 # coding=utf-8 # -# Copyright (c) 2024 Huawei Device Co., Ltd. +# Copyright (c) 2024-2025 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -61,9 +61,10 @@ class LineIterator: # pylint: disable=C0115 def is_skip_line(self) -> bool: return ( - self.current_line.find("#ifndef") != -1 + self.current_line.find("#if") != -1 # if, ifdef, ifndef + or self.current_line.find("#el") != -1 # else, elif or self.current_line.find("#undef") != -1 - or self.current_line.find("#endif") != -1 + or self.current_line.find("#end") != -1 ) def is_template(self) -> bool: @@ -79,7 +80,11 @@ class LineIterator: # pylint: disable=C0115 return self.current_line.find("struct ") != -1 def is_using(self) -> bool: - return self.current_line.find("using ") != -1 + return ( + self.current_line.find("using ") != -1 + or self.current_line.find("namespace ") != -1 + and self.current_line.find("=") != -1 + ) def is_define_macro(self) -> bool: return self.current_line.find("#define ") != -1 diff --git a/ets2panda/public/headers_parser/parse_using.py b/ets2panda/public/headers_parser/parse_using.py index 3287f61618..7db27fbf23 100644 --- a/ets2panda/public/headers_parser/parse_using.py +++ b/ets2panda/public/headers_parser/parse_using.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 # coding=utf-8 # -# Copyright (c) 2024 Huawei Device Co., Ltd. +# Copyright (c) 2024-2025 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -23,7 +23,19 @@ from parse_arguments import parse_type def parse_using(data: str, start: int = 0) -> Tuple[int, Dict]: res: Dict[str, Any] = {} - start_of_name = find_first_not_restricted_character(" ", data, data.find("using ", start) + len("using ")) + using_pos = data.find("using ", start) + if using_pos == -1: + using_pos = len(data) + + namespace_pos = data.find("namespace ", start) + if namespace_pos == -1: + namespace_pos = len(data) + + if using_pos < namespace_pos: + start_of_name = find_first_not_restricted_character(" ", data, using_pos + len("using ")) + else: + start_of_name = find_first_not_restricted_character(" ", data, namespace_pos + len("namespace ")) + end_of_name = find_first_of_characters(" =;\n", data, start_of_name) res["name"] = data[start_of_name:end_of_name] @@ -38,6 +50,6 @@ def parse_using(data: str, start: int = 0) -> Tuple[int, Dict]: var_end = len(data) value = parse_type(data[var_start:var_end].strip(" ;=")) - res["type"] = value # NOTE(morlovsky): Not doing res["value"] = parse_argument(value) + res["type"] = value # NOTE(morlovsky): Not doing res["value"] = parse_argument(value) return var_end, res diff --git a/ets2panda/public/ignoredAllowed.yaml b/ets2panda/public/ignoredAllowed.yaml index 0833906292..59992aa8d1 100644 --- a/ets2panda/public/ignoredAllowed.yaml +++ b/ets2panda/public/ignoredAllowed.yaml @@ -104,7 +104,12 @@ ignored_list: - name: ScriptExtension - name: function namespace: std + - name: path + namespace: fs - name: ImportData + - name: PathsMap + - name: Level + namespace: Logger # Method and constructors will not be generated if c++ postfix contains any element listed below @@ -181,8 +186,11 @@ ignored_list: name: function namespace: std - type: - name: Path - namespace: 'util' + name: DiagnosticMessageParams + namespace: util + - type: + name: PandArgParser + namespace: gen - type: name: T - type: @@ -242,3 +250,4 @@ allowed_list: - ClassDefinition - StringView - TypeNode + - ArkTsConfig diff --git a/ets2panda/test/unit/plugin/CMakeLists.txt b/ets2panda/test/unit/plugin/CMakeLists.txt index b8836c09e9..3456abfeb2 100644 --- a/ets2panda/test/unit/plugin/CMakeLists.txt +++ b/ets2panda/test/unit/plugin/CMakeLists.txt @@ -59,6 +59,7 @@ set(PLUGIN_TESTS # "plugin_proceed_to_state_run_verifier compile.ets ${COMPILE_MODE} cpp ${EXECUTABLE_PLUGIN}" "plugin_proceed_to_state_ast_node_check compile.ets ${COMPILE_MODE} cpp ${EXECUTABLE_PLUGIN}" "plugin_proceed_to_state_resolve_path compile.ets ${COMPILE_MODE} cpp ${EXECUTABLE_PLUGIN}" + "plugin_proceed_to_state_arktsconfig compile.ets ${COMPILE_MODE} cpp ${EXECUTABLE_PLUGIN}" "plugin_proceed_to_state_find_method_decl compile.ets ${COMPILE_MODE} cpp ${EXECUTABLE_PLUGIN}" "plugin_proceed_to_state_find_identifier_decl compile.ets ${COMPILE_MODE} cpp ${EXECUTABLE_PLUGIN}" "plugin_proceed_to_state_find_import_ident_decl import.ets ${COMPILE_MODE} cpp ${EXECUTABLE_PLUGIN}" diff --git a/ets2panda/test/unit/plugin/plugin_proceed_to_state_arktsconfig.cpp b/ets2panda/test/unit/plugin/plugin_proceed_to_state_arktsconfig.cpp new file mode 100644 index 0000000000..13d5b32218 --- /dev/null +++ b/ets2panda/test/unit/plugin/plugin_proceed_to_state_arktsconfig.cpp @@ -0,0 +1,67 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include "util.h" +#include "public/es2panda_lib.h" + +// NOLINTBEGIN + +static es2panda_Impl *impl = nullptr; +static auto source = std::string("function main() { 1 + 2 }"); + +int main(int argc, char **argv) +{ + if (argc < MIN_ARGC) { + return 1; + } + + if (GetImpl() == nullptr) { + return NULLPTR_IMPL_ERROR_CODE; + } + impl = GetImpl(); + const char **args = const_cast(&(argv[1])); + auto config = impl->CreateConfig(argc - 1, args); + auto context = impl->CreateContextFromString(config, source.data(), argv[argc - 1]); + if (context == nullptr) { + std::cerr << "FAILED TO CREATE CONTEXT" << std::endl; + return NULLPTR_CONTEXT_ERROR_CODE; + } + + impl->ProceedToState(context, ES2PANDA_STATE_PARSED); + CheckForErrors("PARSE", context); + + auto outDir = impl->ArkTsConfigOutDirConst( + context, + impl->OptionsUtilArkTSConfigConst(context, const_cast(impl->ConfigGetOptions(config)))); + if (strstr(outDir, "bin") == nullptr) { + return TEST_ERROR_CODE; + } + + if (impl->ContextState(context) == ES2PANDA_STATE_ERROR) { + return PROCEED_ERROR_CODE; + } + impl->DestroyContext(context); + impl->DestroyConfig(config); + + return 0; +} + +// NOLINTEND diff --git a/ets2panda/test/unit/plugin_conversion_rule/plugin_conversion_rule_part_iii.cpp b/ets2panda/test/unit/plugin_conversion_rule/plugin_conversion_rule_part_iii.cpp index 5678a362f5..7c111a02bf 100644 --- a/ets2panda/test/unit/plugin_conversion_rule/plugin_conversion_rule_part_iii.cpp +++ b/ets2panda/test/unit/plugin_conversion_rule/plugin_conversion_rule_part_iii.cpp @@ -198,7 +198,7 @@ TEST_F(PluginConversionRuleUnitTest, SourcePositionInputParameter) extern "C" void AstNodeSetStart([[maybe_unused]] es2panda_Context *context, es2panda_AstNode *classInstance, [[maybe_unused]] es2panda_SourcePosition *start/*return_args:*/) { - auto startE2p = *reinterpret_cast(start); + auto &startE2p = *reinterpret_cast(start); ((reinterpret_cast< ir::AstNode *>(classInstance))->SetStart(startE2p)); })"}; @@ -247,7 +247,7 @@ TEST_F(PluginConversionRuleUnitTest, VRegInputParameter) [[maybe_unused]] es2panda_VReg *objReg/*return_args:*/) { auto *pgE2p = reinterpret_cast(pg); - auto objRegE2p = *reinterpret_cast(objReg); + auto &objRegE2p = *reinterpret_cast(objReg); ((reinterpret_cast(classInstance))->CompileToReg(pgE2p, objRegE2p)); })"}; diff --git a/ets2panda/util/options.h b/ets2panda/util/options.h index c9ac36f995..42467a5ee5 100644 --- a/ets2panda/util/options.h +++ b/ets2panda/util/options.h @@ -59,17 +59,17 @@ public: // NOTE(dkofanov): Replace this getter with something that does 'std::move(parserInputContents_)' as currently it // encourages copying of 'parserInputContents_' data. - auto CStrParserInputContents() const + std::pair CStrParserInputContents() const { return std::pair {parserInputContents_.c_str(), parserInputContents_.size()}; } - const auto &ArkTSConfig() const + const std::shared_ptr &ArkTSConfig() const { return arktsConfig_; } - auto LogLevel() const + Logger::Level LogLevel() const { return logLevel_; } @@ -81,7 +81,7 @@ public: : CompilationMode::PROJECT; } - auto GetCompilationMode() const + CompilationMode GetCompilationMode() const { return compilationMode_; } @@ -105,7 +105,7 @@ public: return evalMode_ == eval_mode::FUNCTION; } - auto SourceFileName() const + std::string SourceFileName() const { return inputFile_.GetValue(); } @@ -115,36 +115,36 @@ public: return extension_ != ScriptExtension::ETS; } - const auto &GetAstVerifierWarnings() const + const std::array &GetAstVerifierWarnings() const { return verifierWarnings_; } - const auto &GetAstVerifierErrors() const + const std::array &GetAstVerifierErrors() const { return verifierErrors_; } - const auto &GetSkipPhases() const + const std::set &GetSkipPhases() const { return skipPhases_; } - const auto &GetDumpBeforePhases() const + const std::set &GetDumpBeforePhases() const { return dumpBeforePhases_; } - const auto &GetDumpEtsSrcBeforePhases() const + const std::set &GetDumpEtsSrcBeforePhases() const { return dumpEtsSrcBeforePhases_; } - const auto &GetDumpAfterPhases() const + const std::set &GetDumpAfterPhases() const { return dumpAfterPhases_; } - const auto &GetDumpEtsSrcAfterPhases() const + const std::set &GetDumpEtsSrcAfterPhases() const { return dumpEtsSrcAfterPhases_; } - const auto &GetEtsWarningCollection() const + const std::vector &GetEtsWarningCollection() const { return etsWarningCollection_; } -- Gitee From 99cbacca8cd4b3acbb2bf171a4b145a9733e4449 Mon Sep 17 00:00:00 2001 From: daizihan Date: Fri, 18 Apr 2025 18:04:33 +0800 Subject: [PATCH 102/268] Fix oom in baseanalyzer with big switch Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC2AVH?from=project-issue Signed-off-by: daizihan --- ets2panda/checker/ets/baseAnalyzer.cpp | 1 + ets2panda/test/runtime/ets/big_switch.ets | 1224 +++++++++++++++++++++ 2 files changed, 1225 insertions(+) create mode 100644 ets2panda/test/runtime/ets/big_switch.ets diff --git a/ets2panda/checker/ets/baseAnalyzer.cpp b/ets2panda/checker/ets/baseAnalyzer.cpp index 8fdf75f037..8e0feca8c0 100644 --- a/ets2panda/checker/ets/baseAnalyzer.cpp +++ b/ets2panda/checker/ets/baseAnalyzer.cpp @@ -92,6 +92,7 @@ LivenessStatus BaseAnalyzer::ResolveContinues(const ir::AstNode *node) template LivenessStatus BaseAnalyzer::ResolveBreaks(const ir::AstNode *node) { + oldPendingExits_.clear(); return ResolveJump(node, ir::AstNodeType::BREAK_STATEMENT); } diff --git a/ets2panda/test/runtime/ets/big_switch.ets b/ets2panda/test/runtime/ets/big_switch.ets new file mode 100644 index 0000000000..af9b8b2c75 --- /dev/null +++ b/ets2panda/test/runtime/ets/big_switch.ets @@ -0,0 +1,1224 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +function main() { + let res = false; + switch (0) { + case 0: + switch (1) { + case 1: + res = true + break; + case 2: + break; + default: + throw Error('Bad overload'); + } + break; + case 1: + break; + case 2: + break; + case 3: + break; + case 4: + break; + case 5: + break; + case 6: + break; + case 7: + break; + case 8: + break; + case 9: + break; + case 10: + break; + case 11: + break; + case 12: + break; + case 13: + break; + case 14: + break; + case 15: + break; + case 16: + break; + case 17: + break; + case 18: + break; + case 19: + break; + case 20: + switch (1) { + case 1: + break; + case 2: + break; + default: + throw Error('Bad overload'); + } + break; + case 21: + break; + case 22: + break; + case 23: + break; + case 24: + break; + case 25: + break; + case 26: + break; + case 27: + break; + case 28: + break; + case 29: + break; + case 30: + break; + case 31: + break; + case 32: + break; + case 33: + break; + case 34: + break; + case 35: + break; + case 36: + break; + case 37: + break; + case 38: + break; + case 39: + break; + case 40: + switch (1) { + case 1: + break; + case 2: + break; + default: + throw Error('Bad overload'); + } + break; + case 41: + break; + case 42: + break; + case 43: + break; + case 44: + break; + case 45: + break; + case 46: + break; + case 47: + break; + case 48: + break; + case 49: + break; + case 50: + break; + case 51: + break; + case 52: + break; + case 53: + break; + case 54: + break; + case 55: + break; + case 56: + break; + case 57: + break; + case 58: + break; + case 59: + break; + case 60: + switch (1) { + case 1: + break; + case 2: + break; + default: + throw Error('Bad overload'); + } + break; + case 61: + break; + case 62: + break; + case 63: + break; + case 64: + break; + case 65: + break; + case 66: + break; + case 67: + break; + case 68: + break; + case 69: + break; + case 70: + break; + case 71: + break; + case 72: + break; + case 73: + break; + case 74: + break; + case 75: + break; + case 76: + break; + case 77: + break; + case 78: + break; + case 79: + break; + case 80: + switch (1) { + case 1: + break; + case 2: + break; + default: + throw Error('Bad overload'); + } + break; + case 81: + break; + case 82: + break; + case 83: + break; + case 84: + break; + case 85: + break; + case 86: + break; + case 87: + break; + case 88: + break; + case 89: + break; + case 90: + break; + case 91: + break; + case 92: + break; + case 93: + break; + case 94: + break; + case 95: + break; + case 96: + break; + case 97: + break; + case 98: + break; + case 99: + break; + case 100: + switch (1) { + case 1: + break; + case 2: + break; + default: + throw Error('Bad overload'); + } + break; + case 101: + break; + case 102: + break; + case 103: + break; + case 104: + break; + case 105: + break; + case 106: + break; + case 107: + break; + case 108: + break; + case 109: + break; + case 110: + break; + case 111: + break; + case 112: + break; + case 113: + break; + case 114: + break; + case 115: + break; + case 116: + break; + case 117: + break; + case 118: + break; + case 119: + break; + case 120: + switch (1) { + case 1: + break; + case 2: + break; + default: + throw Error('Bad overload'); + } + break; + case 121: + break; + case 122: + break; + case 123: + break; + case 124: + break; + case 125: + break; + case 126: + break; + case 127: + break; + case 128: + break; + case 129: + break; + case 130: + break; + case 131: + break; + case 132: + break; + case 133: + break; + case 134: + break; + case 135: + break; + case 136: + break; + case 137: + break; + case 138: + break; + case 139: + break; + case 140: + switch (1) { + case 1: + break; + case 2: + break; + default: + throw Error('Bad overload'); + } + break; + case 141: + break; + case 142: + break; + case 143: + break; + case 144: + break; + case 145: + break; + case 146: + break; + case 147: + break; + case 148: + break; + case 149: + break; + case 150: + break; + case 151: + break; + case 152: + break; + case 153: + break; + case 154: + break; + case 155: + break; + case 156: + break; + case 157: + break; + case 158: + break; + case 159: + break; + case 160: + switch (1) { + case 1: + break; + case 2: + break; + default: + throw Error('Bad overload'); + } + break; + case 161: + break; + case 162: + break; + case 163: + break; + case 164: + break; + case 165: + break; + case 166: + break; + case 167: + break; + case 168: + break; + case 169: + break; + case 170: + break; + case 171: + break; + case 172: + break; + case 173: + break; + case 174: + break; + case 175: + break; + case 176: + break; + case 177: + break; + case 178: + break; + case 179: + break; + case 180: + switch (1) { + case 1: + break; + case 2: + break; + default: + throw Error('Bad overload'); + } + break; + case 181: + break; + case 182: + break; + case 183: + break; + case 184: + break; + case 185: + break; + case 186: + break; + case 187: + break; + case 188: + break; + case 189: + break; + case 190: + break; + case 191: + break; + case 192: + break; + case 193: + break; + case 194: + break; + case 195: + break; + case 196: + break; + case 197: + break; + case 198: + break; + case 199: + break; + case 200: + switch (1) { + case 1: + break; + case 2: + break; + default: + throw Error('Bad overload'); + } + break; + case 201: + break; + case 202: + break; + case 203: + break; + case 204: + break; + case 205: + break; + case 206: + break; + case 207: + break; + case 208: + break; + case 209: + break; + case 210: + break; + case 211: + break; + case 212: + break; + case 213: + break; + case 214: + break; + case 215: + break; + case 216: + break; + case 217: + break; + case 218: + break; + case 219: + break; + case 220: + switch (1) { + case 1: + break; + case 2: + break; + default: + throw Error('Bad overload'); + } + break; + case 221: + break; + case 222: + break; + case 223: + break; + case 224: + break; + case 225: + break; + case 226: + break; + case 227: + break; + case 228: + break; + case 229: + break; + case 230: + break; + case 231: + break; + case 232: + break; + case 233: + break; + case 234: + break; + case 235: + break; + case 236: + break; + case 237: + break; + case 238: + break; + case 239: + break; + case 240: + switch (1) { + case 1: + break; + case 2: + break; + default: + throw Error('Bad overload'); + } + break; + case 241: + break; + case 242: + break; + case 243: + break; + case 244: + break; + case 245: + break; + case 246: + break; + case 247: + break; + case 248: + break; + case 249: + break; + case 250: + break; + case 251: + break; + case 252: + break; + case 253: + break; + case 254: + break; + case 255: + break; + case 256: + break; + case 257: + break; + case 258: + break; + case 259: + break; + case 260: + switch (1) { + case 1: + break; + case 2: + break; + default: + throw Error('Bad overload'); + } + break; + case 261: + break; + case 262: + break; + case 263: + break; + case 264: + break; + case 265: + break; + case 266: + break; + case 267: + break; + case 268: + break; + case 269: + break; + case 270: + break; + case 271: + break; + case 272: + break; + case 273: + break; + case 274: + break; + case 275: + break; + case 276: + break; + case 277: + break; + case 278: + break; + case 279: + break; + case 280: + switch (1) { + case 1: + break; + case 2: + break; + default: + throw Error('Bad overload'); + } + break; + case 281: + break; + case 282: + break; + case 283: + break; + case 284: + break; + case 285: + break; + case 286: + break; + case 287: + break; + case 288: + break; + case 289: + break; + case 290: + break; + case 291: + break; + case 292: + break; + case 293: + break; + case 294: + break; + case 295: + break; + case 296: + break; + case 297: + break; + case 298: + break; + case 299: + break; + case 300: + switch (1) { + case 1: + break; + case 2: + break; + default: + throw Error('Bad overload'); + } + break; + case 301: + break; + case 302: + break; + case 303: + break; + case 304: + break; + case 305: + break; + case 306: + break; + case 307: + break; + case 308: + break; + case 309: + break; + case 310: + break; + case 311: + break; + case 312: + break; + case 313: + break; + case 314: + break; + case 315: + break; + case 316: + break; + case 317: + break; + case 318: + break; + case 319: + break; + case 320: + switch (1) { + case 1: + break; + case 2: + break; + default: + throw Error('Bad overload'); + } + break; + case 321: + break; + case 322: + break; + case 323: + break; + case 324: + break; + case 325: + break; + case 326: + break; + case 327: + break; + case 328: + break; + case 329: + break; + case 330: + break; + case 331: + break; + case 332: + break; + case 333: + break; + case 334: + break; + case 335: + break; + case 336: + break; + case 337: + break; + case 338: + break; + case 339: + break; + case 340: + switch (1) { + case 1: + break; + case 2: + break; + default: + throw Error('Bad overload'); + } + break; + case 341: + break; + case 342: + break; + case 343: + break; + case 344: + break; + case 345: + break; + case 346: + break; + case 347: + break; + case 348: + break; + case 349: + break; + case 350: + break; + case 351: + break; + case 352: + break; + case 353: + break; + case 354: + break; + case 355: + break; + case 356: + break; + case 357: + break; + case 358: + break; + case 359: + break; + case 360: + switch (1) { + case 1: + break; + case 2: + break; + default: + throw Error('Bad overload'); + } + break; + case 361: + break; + case 362: + break; + case 363: + break; + case 364: + break; + case 365: + break; + case 366: + break; + case 367: + break; + case 368: + break; + case 369: + break; + case 370: + break; + case 371: + break; + case 372: + break; + case 373: + break; + case 374: + break; + case 375: + break; + case 376: + break; + case 377: + break; + case 378: + break; + case 379: + break; + case 380: + switch (1) { + case 1: + break; + case 2: + break; + default: + throw Error('Bad overload'); + } + break; + case 381: + break; + case 382: + break; + case 383: + break; + case 384: + break; + case 385: + break; + case 386: + break; + case 387: + break; + case 388: + break; + case 389: + break; + case 390: + break; + case 391: + break; + case 392: + break; + case 393: + break; + case 394: + break; + case 395: + break; + case 396: + break; + case 397: + break; + case 398: + break; + case 399: + break; + case 400: + switch (1) { + case 1: + break; + case 2: + break; + default: + throw Error('Bad overload'); + } + break; + case 401: + break; + case 402: + break; + case 403: + break; + case 404: + break; + case 405: + break; + case 406: + break; + case 407: + break; + case 408: + break; + case 409: + break; + case 410: + break; + case 411: + break; + case 412: + break; + case 413: + break; + case 414: + break; + case 415: + break; + case 416: + break; + case 417: + break; + case 418: + break; + case 419: + break; + case 420: + switch (1) { + case 1: + break; + case 2: + break; + default: + throw Error('Bad overload'); + } + break; + case 421: + break; + case 422: + break; + case 423: + break; + case 424: + break; + case 425: + break; + case 426: + break; + case 427: + break; + case 428: + break; + case 429: + break; + case 430: + break; + case 431: + break; + case 432: + break; + case 433: + break; + case 434: + break; + case 435: + break; + case 436: + break; + case 437: + break; + case 438: + break; + case 439: + break; + case 440: + switch (1) { + case 1: + break; + case 2: + break; + default: + throw Error('Bad overload'); + } + break; + case 441: + break; + case 442: + break; + case 443: + break; + case 444: + break; + case 445: + break; + case 446: + break; + case 447: + break; + case 448: + break; + case 449: + break; + case 450: + break; + case 451: + break; + case 452: + break; + case 453: + break; + case 454: + break; + case 455: + break; + case 456: + break; + case 457: + break; + case 458: + break; + case 459: + break; + case 460: + switch (1) { + case 1: + break; + case 2: + break; + default: + throw Error('Bad overload'); + } + break; + case 461: + break; + case 462: + break; + case 463: + break; + case 464: + break; + case 465: + break; + case 466: + break; + case 467: + break; + case 468: + break; + case 469: + break; + case 470: + break; + case 471: + break; + case 472: + break; + case 473: + break; + case 474: + break; + case 475: + break; + case 476: + break; + case 477: + break; + case 478: + break; + case 479: + break; + case 480: + switch (1) { + case 1: + break; + case 2: + break; + default: + throw Error('Bad overload'); + } + break; + case 481: + break; + case 482: + break; + case 483: + break; + case 484: + break; + case 485: + break; + case 486: + break; + case 487: + break; + case 488: + break; + case 489: + break; + case 490: + break; + case 491: + break; + case 492: + break; + case 493: + break; + case 494: + break; + case 495: + break; + case 496: + break; + case 497: + break; + case 498: + break; + case 499: + break; + default: + break; + } + assertTrue(res) +} \ No newline at end of file -- Gitee From 7d5f501b2f9eca13b8869b121d28437f81672c6e Mon Sep 17 00:00:00 2001 From: Zhelyapov Aleksey Date: Mon, 7 Apr 2025 16:05:25 +0300 Subject: [PATCH 103/268] Provided c_types for classes in IDL Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBYDG4 Signed-off-by: Zhelyapov Aleksey Change-Id: I1a0bb47097be2b30eb28b668e578d5b76215c6b7 --- ets2panda/public/es2panda_lib.cpp | 10 +- ets2panda/public/es2panda_lib.h | 12 +- ets2panda/public/es2panda_lib.idl.erb | 94 +++-- ets2panda/public/es2panda_lib.rb | 366 +++++++++++------- .../unit/plugin/plugin_check_manual_capi.cpp | 16 +- 5 files changed, 288 insertions(+), 210 deletions(-) diff --git a/ets2panda/public/es2panda_lib.cpp b/ets2panda/public/es2panda_lib.cpp index bc6c735e7f..4d549eb26c 100644 --- a/ets2panda/public/es2panda_lib.cpp +++ b/ets2panda/public/es2panda_lib.cpp @@ -573,7 +573,7 @@ extern "C" void AstNodeForEach(es2panda_AstNode *ast, void (*func)(es2panda_AstN } #define SET_NUMBER_LITERAL_IMPL(name, type) \ - extern "C" bool SetNumberLiteral##name(es2panda_AstNode *node, type new_value) \ + extern "C" bool NumberLiteralSet##name(es2panda_AstNode *node, type new_value) \ { \ auto &n = reinterpret_cast(node)->Number(); \ if (!n.Is##name()) { \ @@ -818,10 +818,10 @@ es2panda_Impl g_impl = { ExternalSourceName, ExternalSourcePrograms, AstNodeForEach, - SetNumberLiteralInt, - SetNumberLiteralLong, - SetNumberLiteralDouble, - SetNumberLiteralFloat, + NumberLiteralSetInt, + NumberLiteralSetLong, + NumberLiteralSetDouble, + NumberLiteralSetFloat, CreateNumberLiteral, UpdateNumberLiteral, CreateNumberLiteral, diff --git a/ets2panda/public/es2panda_lib.h b/ets2panda/public/es2panda_lib.h index abb337215d..ced577b988 100644 --- a/ets2panda/public/es2panda_lib.h +++ b/ets2panda/public/es2panda_lib.h @@ -164,14 +164,14 @@ struct CAPI_EXPORT es2panda_Impl { es2panda_Program **(*ExternalSourcePrograms)(es2panda_ExternalSource *e_source, size_t *len_p); void (*AstNodeForEach)(es2panda_AstNode *ast, void (*func)(es2panda_AstNode *, void *), void *arg); -#define SET_NUMBER_LITERAL_DECL(name, type) bool (*SetNumberLiteral##name)(es2panda_AstNode * node, type new_value) +#define NUMBER_LITERAL_SET_DECL(name, type) bool (*NumberLiteralSet##name)(es2panda_AstNode * node, type new_value) - SET_NUMBER_LITERAL_DECL(Int, int32_t); - SET_NUMBER_LITERAL_DECL(Long, int64_t); - SET_NUMBER_LITERAL_DECL(Double, double); - SET_NUMBER_LITERAL_DECL(Float, float); + NUMBER_LITERAL_SET_DECL(Int, int32_t); + NUMBER_LITERAL_SET_DECL(Long, int64_t); + NUMBER_LITERAL_SET_DECL(Double, double); + NUMBER_LITERAL_SET_DECL(Float, float); -#undef SET_NUMBER_LITERAL_DECL +#undef NUMBER_LITERAL_SET_DECL #define CREATE_UPDATE_NUMBER_LITERAL_IMPL(num, type) \ es2panda_AstNode *(*CreateNumberLiteral##num)(es2panda_Context * ctx, type value); \ diff --git a/ets2panda/public/es2panda_lib.idl.erb b/ets2panda/public/es2panda_lib.idl.erb index a6262004b5..ddf23446c3 100644 --- a/ets2panda/public/es2panda_lib.idl.erb +++ b/ets2panda/public/es2panda_lib.idl.erb @@ -62,47 +62,47 @@ typedef (String or f64 or boolean) es2panda_variantDoubleCharArrayBool; interface NodeTraverser { - void Do(AstNode e2p_node); + void Do(ir.AstNode e2p_node); }; interface NodeTransformer { - AstNode Do(AstNode e2p_node); + ir.AstNode Do(ir.AstNode e2p_node); }; interface NodePredicate { - boolean Do(AstNode e2p_node); + boolean Do(ir.AstNode e2p_node); }; interface PropertyProcessor { - Variable Do(Variable e2p_variable, Type e2p_type); + varbinder.Variable Do(varbinder.Variable e2p_variable, checker.Type e2p_type); }; interface PropertyTraverser { - void Do(Variable e2p_variable); + void Do(varbinder.Variable e2p_variable); }; interface ClassBuilder { - void Do(sequence e2p_node, u32 size); + void Do(sequence e2p_node, u32 size); }; interface MethodBuilder { - void Do(sequence statements, u32 sizeStatements, sequence expression, - u32 sizeExpression, sequence e2p_type); + void Do(sequence statements, u32 sizeStatements, sequence expression, + u32 sizeExpression, sequence e2p_type); }; interface ClassInitializerBuilder { - void Do(sequence statements, u32 sizeStatements, sequence expression, + void Do(sequence statements, u32 sizeStatements, sequence expression, u32 sizeExpression); }; interface AstNodeForEachFunction { - void Do(AstNode node, VoidPtr arg); + void Do(ir.AstNode node, VoidPtr arg); }; interface es2panda_DynamicImportData { - attribute AstNode import_node; - attribute AstNode specifier; - attribute Variable variable; + attribute ir.ETSImportDeclaration import_node; + attribute ir.AstNode specifier; + attribute varbinder.Variable variable; }; interface es2panda_OverloadInfo { @@ -161,27 +161,10 @@ interface es2panda_Impl { String ContextErrorMessage(es2panda_Context context); es2panda_Program ContextProgram(es2panda_Context context); - AstNode ProgramAst(es2panda_Program program); - sequence ProgramExternalSources(es2panda_Program program, sequence len_p); String ExternalSourceName(es2panda_ExternalSource e_source); sequence ExternalSourcePrograms(es2panda_ExternalSource e_source, sequence len_p); - void AstNodeForEach(AstNode ast, AstNodeForEachFunction func, VoidPtr arg); - - boolean SetNumberLiteralInt(AstNode node, i32 new_value); - boolean SetNumberLiteralLong(AstNode node, i64 new_value); - boolean SetNumberLiteralDouble(AstNode node, f64 new_value); - boolean SetNumberLiteralFloat(AstNode node, f32 new_value); - - AstNode CreateNumberLiteral(es2panda_Context ctx, i32 value); - AstNode CreateNumberLiteral1(es2panda_Context ctx, i64 value); - AstNode CreateNumberLiteral2(es2panda_Context ctx, f64 value); - AstNode CreateNumberLiteral3(es2panda_Context ctx, f32 value); - - AstNode UpdateNumberLiteral(es2panda_Context ctx, AstNode original, i32 value); - AstNode UpdateNumberLiteral1(es2panda_Context ctx, AstNode original, i64 value); - AstNode UpdateNumberLiteral2(es2panda_Context ctx, AstNode original, f64 value); - AstNode UpdateNumberLiteral3(es2panda_Context ctx, AstNode original, f32 value); + void AstNodeForEach(ir.AstNode ast, AstNodeForEachFunction func, VoidPtr arg); VoidPtr AllocMemory(es2panda_Context context, u32 numberOfElements, u32 sizeOfElement); @@ -195,49 +178,77 @@ interface es2panda_Impl { void LogTypeError(es2panda_Context context, String errorMsg, es2panda_SourcePosition pos); void LogWarning(es2panda_Context context, String warnMsg, es2panda_SourcePosition pos); void LogSyntaxError(es2panda_Context context, String errorMsg, es2panda_SourcePosition pos); - Scope AstNodeFindNearestScope(es2panda_Context ctx, AstNode node); - Scope AstNodeRebind(es2panda_Context ctx, AstNode node); - void AstNodeRecheck(es2panda_Context ctx, AstNode node); + varbinder.Scope AstNodeFindNearestScope(es2panda_Context ctx, ir.AstNode node); + varbinder.Scope AstNodeRebind(es2panda_Context ctx, ir.AstNode node); + void AstNodeRecheck(es2panda_Context ctx, ir.AstNode node); Es2pandaEnum Es2pandaEnumFromString(es2panda_Context ctx, String str); String Es2pandaEnumToString(es2panda_Context ctx, Es2pandaEnum id); - AstNode DeclarationFromIdentifier(es2panda_Context ctx, Identifier node); + ir.AstNode DeclarationFromIdentifier(es2panda_Context ctx, ir.Identifier node); + ir.AstNode FirstDeclarationByNameFromNode(es2panda_Context ctx, ir.AstNode node, String name); + ir.AstNode FirstDeclarationByNameFromProgram(es2panda_Context ctx, es2panda_Program program, String name); + sequence AllDeclarationsByNameFromNode(es2panda_Context ctx, ir.AstNode node, String name); + sequence AllDeclarationsByNameFromProgram(es2panda_Context ctx, es2panda_Program program, String name); void InsertETSImportDeclarationAndParse(es2panda_Context context, es2panda_Program program, ETSImportDeclaration node); % Es2pandaLibApi::ast_nodes&.each do |ast_node| % if ast_node != 'AstNode' && ast_node != 'TypeNode' - boolean Is<%= ast_node %>(AstNode ast); + boolean Is<%= ast_node %>(ir.AstNode ast); % end % end % Es2pandaLibApi::scopes&.each do |scope| % if scope != 'Scope' - boolean ScopeIs<%= scope %>(Scope scope); + boolean ScopeIs<%= scope %>(varbinder.Scope scope); % end % end % Es2pandaLibApi::ast_types&.each do |type| % if type != 'Type' - boolean TypeIs<%= type %>(Type type); + boolean TypeIs<%= type %>(checker.Type type); % end % end % Es2pandaLibApi::ast_variables&.each do |variable| % if variable[1] != 'Variable' - boolean VariableIs<%= variable[1] %>(Variable variable); + boolean VariableIs<%= variable[1] %>(varbinder.Variable variable); % end % end - String AstNodeName(AstNode ast); + String AstNodeName(ir.AstNode ast); }; +namespace ir { + +[Entity=Class, c_type=es2panda_AstNode] interface NumberLiteral: Literal { + ir.AstNode Create(es2panda_Context ctx, i32 value); + ir.AstNode Create1(es2panda_Context ctx, i64 value); + ir.AstNode Create2(es2panda_Context ctx, f64 value); + ir.AstNode Create3(es2panda_Context ctx, f32 value); + + ir.AstNode Update(es2panda_Context ctx, ir.AstNode original, i32 value); + ir.AstNode Update1(es2panda_Context ctx, ir.AstNode original, i64 value); + ir.AstNode Update2(es2panda_Context ctx, ir.AstNode original, f64 value); + ir.AstNode Update3(es2panda_Context ctx, ir.AstNode original, f32 value); + + boolean SetInt(ir.AstNode node, i32 new_value); + boolean SetLong(ir.AstNode node, i64 new_value); + boolean SetDouble(ir.AstNode node, f64 new_value); + boolean SetFloat(ir.AstNode node, f32 new_value); +}; + +}; // namespace ir + + % Es2pandaLibApi::classes&.each do |namespaceName, namespaceClasses| +namespace <%= namespaceName %> { + % namespaceClasses&.each do |className, classData| [Entity=Class<%= classData.ast_node_type_value ? ", Es2pandaAstNodeType=#{classData.ast_node_type_value}" : '' -%>, cpp_namespace=<%= namespaceName %>] interface <%= className %><%= +%><%= classData.class_c_type %>] interface <%= className %><%= ": #{classData.extends_classname}" if classData && classData.extends_classname %> { % classData.class_constructors&.each_with_index do |constructor, index| @@ -273,4 +284,5 @@ interface es2panda_Impl { }; % end # namespaceClasses +}; // namespace <%= namespaceName %> % end # classes diff --git a/ets2panda/public/es2panda_lib.rb b/ets2panda/public/es2panda_lib.rb index bea7bab2a7..6a9ba96525 100644 --- a/ets2panda/public/es2panda_lib.rb +++ b/ets2panda/public/es2panda_lib.rb @@ -39,7 +39,7 @@ module Es2pandaLibApi # Flags @need_var_cast = false - def check_ptr_depth(change_type, ptr_depth) + def self.check_ptr_depth(change_type, ptr_depth) !((change_type.es2panda_arg['min_ptr_depth'] && ptr_depth < change_type.es2panda_arg['min_ptr_depth']) || (change_type.es2panda_arg['max_ptr_depth'] && ptr_depth > change_type.es2panda_arg['max_ptr_depth'])) end @@ -54,32 +54,33 @@ module Es2pandaLibApi type['ref_depth'] = 0 if type.respond_to?('ref_depth') end - def const - @const = 'const' if @es2panda_arg['type'].respond_to?('prefix') && - @es2panda_arg['type']['prefix'].include?('const') || - @es2panda_arg['type'].respond_to?('other_modifiers') && - @es2panda_arg['type']['other_modifiers'].include?('const') || - @es2panda_arg['type'].respond_to?('const') && - @es2panda_arg['type']['const']&.include?('const') + def self.const(es2panda_arg) + return 'const' if es2panda_arg['type'].respond_to?('prefix') && + es2panda_arg['type']['prefix'].include?('const') || + es2panda_arg['type'].respond_to?('other_modifiers') && + es2panda_arg['type']['other_modifiers'].include?('const') || + es2panda_arg['type'].respond_to?('const') && + es2panda_arg['type']['const']&.include?('const') end - def set_const_modifier(args, value) + def self.set_const_modifier(args, value) args&.map do |arg| unless arg['type']&.respond_to?('const') && arg['type']&.respond_to?('ptr_depth') && arg['type']&.ptr_depth&.positive? - arg['type']['const'] = const || '' + arg['type']['const'] = value || '' end end end def stop_modify_idl_arg - @is_ast_node || @is_ast_node_add_children || @is_ast_type || @is_ast_type_add_children || @is_var_type || @is_scope_type || @is_decl_type + @is_ast_node || @is_ast_node_add_children || @is_ast_type || @is_ast_type_add_children || @is_var_type || + @is_scope_type || @is_decl_type end def modify_template_nested_arg(arg, base_namespace, idl_mode = false) arg['type'] = ClassData.add_base_namespace(arg['type'], base_namespace) tmp = Arg.new(arg, base_namespace) - raise "Unsupported double+ nested complex types: #{arg_info.to_s}\n" if tmp.lib_args.length > 1 + raise "Unsupported double+ nested complex types: #{arg}\n" if tmp.lib_args.length > 1 return nil if tmp.lib_args.nil? || tmp.lib_args[0].nil? return arg if idl_mode && tmp.stop_modify_idl_arg @@ -89,131 +90,180 @@ module Es2pandaLibApi tmp.lib_args[0] end - def unsupported_type_msg() - ptr_depth = @es2panda_arg['type'].ptr_depth || 0 - namespace = @es2panda_arg['type'].namespace + def self.unsupported_type_msg(es2panda_arg) + ptr_depth = es2panda_arg['type'].ptr_depth || 0 + namespace = es2panda_arg['type'].namespace "'#{namespace ? "#{namespace}::" : ''}"\ - "#{@es2panda_arg['type'].name}"\ - "#{' ' * [1, ptr_depth].min + '*' * (ptr_depth)}'" + "#{es2panda_arg['type'].name}"\ + "#{' ' * [1, ptr_depth].min + '*' * ptr_depth}'" end - def initialize(arg_info, base_namespace) - @@primitive_types ||= Es2pandaLibApi.primitive_types - @es2panda_arg = arg_info + def self.is_ast_node(es2panda_arg) + Es2pandaLibApi.ast_nodes.include?(es2panda_arg['type'].name) && + (!es2panda_arg['type']['namespace'] || es2panda_arg['type']['namespace'] == 'ir') + end - @es2panda_arg['const'] = const - @base_namespace = base_namespace + def self.is_ast_node_add_children(es2panda_arg) + Es2pandaLibApi.ast_node_additional_children.include?(es2panda_arg['type'].name) && + (!es2panda_arg['type']['namespace'] || es2panda_arg['type']['namespace'] == 'ir') + end + + def self.is_ast_type(es2panda_arg) + Es2pandaLibApi.ast_types.include?(es2panda_arg['type'].name) && + (!es2panda_arg['type']['namespace'] || es2panda_arg['type']['namespace'] == 'checker') + end + + def self.is_ast_type_add_children(es2panda_arg) + Es2pandaLibApi.ast_type_additional_children.include?(es2panda_arg['type'].name) && + (!es2panda_arg['type']['namespace'] || + es2panda_arg['type']['namespace'] == 'checker') + end + + def self.is_var_type(es2panda_arg) + Es2pandaLibApi.ast_variables.any? { |variable| variable[1] == es2panda_arg['type'].name } && + (!es2panda_arg['type']['namespace'] || es2panda_arg['type']['namespace'] == 'varbinder') + end + + def self.is_enum_type(es2panda_arg) + Es2pandaLibApi.enums.include?(es2panda_arg['type'].name) + end + + def self.is_scope_type(es2panda_arg) + Es2pandaLibApi.scopes.include?(es2panda_arg['type'].name) && + (!es2panda_arg['type']['namespace'] || es2panda_arg['type']['namespace'] == 'varbinder') + end + + def self.is_decl_type(es2panda_arg) + Es2pandaLibApi.declarations.include?(es2panda_arg['type'].name) && + (!es2panda_arg['type']['namespace'] || es2panda_arg['type']['namespace'] == 'varbinder') + end + + def self.is_code_gen(es2panda_arg) + Es2pandaLibApi.code_gen_children.include?(es2panda_arg['type'].name) && + (!es2panda_arg['type']['namespace'] || es2panda_arg['type']['namespace'] == 'compiler') + end + def self.get_change_type_info(es2panda_arg) found_change_type_link = Es2pandaLibApi.change_types.find do |x| - x.es2panda_arg.type.respond_to?('name') && x.es2panda_arg.type.name == @es2panda_arg['type']['name'] && + x.es2panda_arg.type.respond_to?('name') && x.es2panda_arg.type.name == es2panda_arg['type']['name'] && (!x.es2panda_arg.type.respond_to?('namespace') || - x.es2panda_arg.type.namespace == @es2panda_arg['type'].namespace) && + x.es2panda_arg.type.namespace == es2panda_arg['type'].namespace) && (!x.es2panda_arg.type.respond_to?('current_class') || - x.es2panda_arg.type['current_class'] == @es2panda_arg['type']['current_class']) && - check_ptr_depth(x, @es2panda_arg['type']['ptr_depth'] || 0) + x.es2panda_arg.type['current_class'] == es2panda_arg['type']['current_class']) && + Arg.check_ptr_depth(x, es2panda_arg['type']['ptr_depth'] || 0) end - unless found_change_type_link - @is_ast_node = Es2pandaLibApi.ast_nodes.include?(@es2panda_arg['type'].name) && - (!@es2panda_arg['type']['namespace'] || @es2panda_arg['type']['namespace'] == 'ir') - @is_ast_node_add_children = Es2pandaLibApi.ast_node_additional_children.include?(@es2panda_arg['type'].name) && - (!@es2panda_arg['type']['namespace'] || @es2panda_arg['type']['namespace'] == 'ir') - @is_ast_type = Es2pandaLibApi.ast_types.include?(@es2panda_arg['type'].name) && - (!@es2panda_arg['type']['namespace'] || @es2panda_arg['type']['namespace'] == 'checker') - @is_ast_type_add_children = Es2pandaLibApi.ast_type_additional_children.include?(@es2panda_arg['type'].name) && - (!@es2panda_arg['type']['namespace'] || - @es2panda_arg['type']['namespace'] == 'checker') - @is_var_type = Es2pandaLibApi.ast_variables.any? { |variable| variable[1] == @es2panda_arg['type'].name } && - (!@es2panda_arg['type']['namespace'] || @es2panda_arg['type']['namespace'] == 'varbinder') - @is_enum_type = Es2pandaLibApi.enums.include?(@es2panda_arg['type'].name) - @is_scope_type = Es2pandaLibApi.scopes.include?(@es2panda_arg['type'].name) && - (!@es2panda_arg['type']['namespace'] || @es2panda_arg['type']['namespace'] == 'varbinder') - @is_decl_type = Es2pandaLibApi.declarations.include?(@es2panda_arg['type'].name) && - (!@es2panda_arg['type']['namespace'] || @es2panda_arg['type']['namespace'] == 'varbinder') - @is_code_gen = Es2pandaLibApi.code_gen_children.include?(@es2panda_arg['type'].name) && - (!@es2panda_arg['type']['namespace'] || @es2panda_arg['type']['namespace'] == 'compiler') - - if @is_ast_type - found_change_type_link = Es2pandaLibApi.change_types.find do |x| - x.es2panda_arg.type == '|AstType|' && check_ptr_depth(x, @es2panda_arg['type'].ptr_depth || 0) - end - end + return found_change_type_link if found_change_type_link - if @is_ast_type_add_children - found_change_type_link = Es2pandaLibApi.change_types.find do |x| - x.es2panda_arg.type == - '|AstTypeAdditionalChildren|' && check_ptr_depth(x, @es2panda_arg['type'].ptr_depth || 0) - end + if Arg.is_ast_type(es2panda_arg) + found_change_type_link = Es2pandaLibApi.change_types.find do |x| + x.es2panda_arg.type == '|AstType|' && Arg.check_ptr_depth(x, es2panda_arg['type'].ptr_depth || 0) end + end - if @is_ast_node - found_change_type_link = Es2pandaLibApi.change_types.find do |x| - x.es2panda_arg.type == '|AstNode|' && check_ptr_depth(x, @es2panda_arg['type'].ptr_depth || 0) - end + if Arg.is_ast_type_add_children(es2panda_arg) + found_change_type_link = Es2pandaLibApi.change_types.find do |x| + x.es2panda_arg.type == + '|AstTypeAdditionalChildren|' && Arg.check_ptr_depth(x, es2panda_arg['type'].ptr_depth || 0) end + end - if @is_ast_node_add_children - found_change_type_link = Es2pandaLibApi.change_types.find do |x| - x.es2panda_arg.type == - '|AstNodeAdditionalChildren|' && check_ptr_depth(x, @es2panda_arg['type'].ptr_depth || 0) - end + if Arg.is_ast_node(es2panda_arg) + found_change_type_link = Es2pandaLibApi.change_types.find do |x| + x.es2panda_arg.type == '|AstNode|' && Arg.check_ptr_depth(x, es2panda_arg['type'].ptr_depth || 0) end + end - if @is_var_type - found_change_type_link = Es2pandaLibApi.change_types.find do |x| - x.es2panda_arg.type == '|Variable|' && check_ptr_depth(x, @es2panda_arg['type'].ptr_depth || 0) - end + if Arg.is_ast_node_add_children(es2panda_arg) + found_change_type_link = Es2pandaLibApi.change_types.find do |x| + x.es2panda_arg.type == + '|AstNodeAdditionalChildren|' && Arg.check_ptr_depth(x, es2panda_arg['type'].ptr_depth || 0) end + end - if @is_enum_type - found_change_type_link = Es2pandaLibApi.change_types.find do |x| - x.es2panda_arg.type == '|Enum|' && check_ptr_depth(x, @es2panda_arg['type'].ptr_depth || 0) - end + if Arg.is_var_type(es2panda_arg) + found_change_type_link = Es2pandaLibApi.change_types.find do |x| + x.es2panda_arg.type == '|Variable|' && Arg.check_ptr_depth(x, es2panda_arg['type'].ptr_depth || 0) end + end - if @is_scope_type - found_change_type_link = Es2pandaLibApi.change_types.find do |x| - x.es2panda_arg.type == '|Scope|' && check_ptr_depth(x, @es2panda_arg['type'].ptr_depth || 0) - end + if Arg.is_enum_type(es2panda_arg) + found_change_type_link = Es2pandaLibApi.change_types.find do |x| + x.es2panda_arg.type == '|Enum|' && Arg.check_ptr_depth(x, es2panda_arg['type'].ptr_depth || 0) end + end - if @is_decl_type - found_change_type_link = Es2pandaLibApi.change_types.find do |x| - x.es2panda_arg.type == '|Declaration|' && check_ptr_depth(x, @es2panda_arg['type'].ptr_depth || 0) - end + if Arg.is_scope_type(es2panda_arg) + found_change_type_link = Es2pandaLibApi.change_types.find do |x| + x.es2panda_arg.type == '|Scope|' && Arg.check_ptr_depth(x, es2panda_arg['type'].ptr_depth || 0) end + end - if @is_code_gen - found_change_type_link = Es2pandaLibApi.change_types.find do |x| - x.es2panda_arg.type == '|CodeGen|' && check_ptr_depth(x, @es2panda_arg['type'].ptr_depth || 0) - end + if Arg.is_decl_type(es2panda_arg) + found_change_type_link = Es2pandaLibApi.change_types.find do |x| + x.es2panda_arg.type == '|Declaration|' && Arg.check_ptr_depth(x, es2panda_arg['type'].ptr_depth || 0) end end - unless found_change_type_link || @@primitive_types.include?(@es2panda_arg['type'].name) - raise "Unsupported type: #{unsupported_type_msg}" + if Arg.is_code_gen(es2panda_arg) + found_change_type_link = Es2pandaLibApi.change_types.find do |x| + x.es2panda_arg.type == '|CodeGen|' && Arg.check_ptr_depth(x, es2panda_arg['type'].ptr_depth || 0) + end end - ptr_depth = @es2panda_arg['type']['ptr_depth'] || 0 + found_change_type_link + end - if found_change_type_link && !check_ptr_depth(found_change_type_link, ptr_depth) - raise "Invalid ptr depth for type: #{unsupported_type_msg}" + def self.check_is_type_supported(found_change_type_link, es2panda_arg) + unless found_change_type_link || Es2pandaLibApi.primitive_types.include?(es2panda_arg['type'].name) + return "Unsupported type: #{Arg.unsupported_type_msg(es2panda_arg)}" end - if found_change_type_link && @es2panda_arg['name'] == 'returnType' && + if found_change_type_link && !Arg.check_ptr_depth(found_change_type_link, es2panda_arg['type']['ptr_depth'] || 0) + return "Invalid ptr depth for type: #{Arg.unsupported_type_msg(es2panda_arg)}" + end + + if found_change_type_link && es2panda_arg['name'] == 'returnType' && !found_change_type_link.cast.respond_to?('reverse_cast') - raise "Unsupported return type: #{unsupported_type_msg}" + return "Unsupported return type: #{Arg.unsupported_type_msg(es2panda_arg)}" end - if found_change_type_link && @es2panda_arg['name'] == 'callType' && + if found_change_type_link && es2panda_arg['name'] == 'callType' && !found_change_type_link.cast.respond_to?('call_cast') - raise "Unsupported call type: #{unsupported_type_msg}" + return "Unsupported call type: #{Arg.unsupported_type_msg(es2panda_arg)}" end - if found_change_type_link && @es2panda_arg['name'] == 'constructorType' && + if found_change_type_link && es2panda_arg['name'] == 'constructorType' && !found_change_type_link.cast.respond_to?('constructor_cast') - raise "Unsupported constructor type: #{unsupported_type_msg}" + "Unsupported constructor type: #{Arg.unsupported_type_msg(es2panda_arg)}" end + end + + def self.get_change_type_info_with_err_msg(es2panda_arg) + found_change_type_link = Arg.get_change_type_info(es2panda_arg) + err_msg = Arg.check_is_type_supported(found_change_type_link, es2panda_arg) + [found_change_type_link, err_msg] + end + + def initialize(arg_info, base_namespace) + found_change_type_link, err_msg = Arg.get_change_type_info_with_err_msg(arg_info) + raise err_msg unless err_msg.nil? + + @@primitive_types ||= Es2pandaLibApi.primitive_types + @es2panda_arg = arg_info + @const = Arg.const(arg_info) + @es2panda_arg['const'] = @const + @base_namespace = base_namespace + + @is_ast_node = Arg.is_ast_node(es2panda_arg) + @is_ast_node_add_children = Arg.is_ast_node_add_children(es2panda_arg) + @is_ast_type = Arg.is_ast_type(es2panda_arg) + @is_ast_type_add_children = Arg.is_ast_type_add_children(es2panda_arg) + @is_var_type = Arg.is_var_type(es2panda_arg) + @is_enum_type = Arg.is_enum_type(es2panda_arg) + @is_scope_type = Arg.is_scope_type(es2panda_arg) + @is_decl_type = Arg.is_decl_type(es2panda_arg) + @is_code_gen = Arg.is_code_gen(es2panda_arg) if found_change_type_link found_change_type = Marshal.load(Marshal.dump(found_change_type_link)) @@ -250,11 +300,11 @@ module Es2pandaLibApi 'type' => ClassData.add_base_namespace(template_arg_raw['type'], base_namespace) }, base_namespace) - raise "Unsupported double+ nested complex types: #{@es2panda_arg.to_s}\n" if template_arg.lib_args.length > 1 + raise "Unsupported double+ nested complex types: #{@es2panda_arg}\n" if template_arg.lib_args.length > 1 unless template_arg_raw['type']['const'].nil? - template_arg.set_const_modifier(@lib_args, 'const') - template_arg.set_const_modifier(@idl_args, 'const') + Arg.set_const_modifier(@lib_args, 'const') + Arg.set_const_modifier(@idl_args, 'const') end template_args += [template_arg] @@ -337,8 +387,8 @@ module Es2pandaLibApi return unless @es2panda_arg['name'] == 'returnType' - set_const_modifier(@lib_args, const) - set_const_modifier(@idl_args, const) + Arg.set_const_modifier(@lib_args, @const) + Arg.set_const_modifier(@idl_args, @const) end def check_allowed_type(arg) @@ -350,15 +400,16 @@ module Es2pandaLibApi def nested_arg_transform return unless @lib_args && @lib_args.size == 1 && !check_allowed_type(@lib_args[0]) - set_const_modifier(@lib_args, const) - set_const_modifier(@idl_args, const) + Arg.set_const_modifier(@lib_args, @const) + Arg.set_const_modifier(@idl_args, @const) tmp = Arg.new(@lib_args[0], @base_namespace) @lib_args = tmp.lib_args @idl_args = tmp.idl_args @lib_cast = tmp.lib_cast @return_args = tmp.return_args @idl_return_args = tmp.idl_return_args - return unless !tmp.check_allowed_type(@lib_args[0]) + return if tmp.check_allowed_type(@lib_args[0]) + nested_arg_transform end @@ -403,7 +454,7 @@ module Es2pandaLibApi elsif placeholder.end_with?('const|') value = '' else - raise "Unknown int found for placeholder '#{placeholder}', value: #{value.to_s}\n" + raise "Unknown int found for placeholder '#{placeholder}', value: #{value}\n" end end value @@ -456,6 +507,7 @@ module Es2pandaLibApi attr_reader :lib_cast attr_reader :return_args attr_reader :idl_return_args + attr_reader :const def lib_args_to_str @lib_args.map do |lib_arg| @@ -508,10 +560,10 @@ module Es2pandaLibApi 'uint64_t' => 'u64', 'float' => 'f32', 'double' => 'f64', - 'sequence' => 'String', + 'sequence' => 'String' } - c_type = type['name'] + c_type = type['namespace'] && type['namespace'] != 'std' ? "#{type['namespace']}.#{type['name']}" : type['name'] res_sequence_len = @@replace_to_idl_types.key?(c_type) ? (type['ptr_depth'] || 0) : ((type['ptr_depth'] || 1) - 1) res = res_sequence_len.times.reduce(c_type) { |acc, _| "sequence<#{@@replace_to_idl_types[acc] || acc}>" } @@replace_to_idl_types[res] || res @@ -607,7 +659,7 @@ module Es2pandaLibApi return '' unless @idl_return_args @idl_return_args - .select { |arg| arg['name'] != 'returnTypeLen' } + .reject { |arg| arg['name'] == 'returnTypeLen' } .map { |arg| ", #{Arg.arg_to_idl(arg)}" } .join('') end @@ -633,7 +685,7 @@ module Es2pandaLibApi attr_accessor :ast_node_type_value def class_name - Es2pandaLibApi.classes&.each do |namespace_name, namespace_classes| + Es2pandaLibApi.classes&.each do |_namespace_name, namespace_classes| if namespace_classes&.find { |_name, data| data == self } return namespace_classes&.find { |_name, data| data == self }[0] end @@ -641,9 +693,24 @@ module Es2pandaLibApi if Es2pandaLibApi.structs.find { |_name, data| data == self }[0] return Es2pandaLibApi.structs.find { |_name, data| data == self }[0] end + raise 'Unknown class name' end + def class_c_type + change_type_info, err_msg = Arg.get_change_type_info_with_err_msg( + { + 'name' => 'class_c_type', + 'type' => OpenStruct.new({ 'name' => class_name, 'ptr_depth' => 1, 'namespace' => @class_base_namespace }) + } + ) + + return '' if err_msg + + c_type = change_type_info.dig('new_args', 0, 'type', 'name') + ", c_type=#{c_type}" unless c_type.nil? # In some cases new_args = []. E.g. Checker type. + end + def call_cast name = class_name class_type = Type.new(add_base_namespace(OpenStruct.new({ 'name' => name, 'ptr_depth' => 1 })), @@ -703,16 +770,16 @@ module Es2pandaLibApi end def self.add_base_namespace(type, base_namespace) - type['namespace'] = base_namespace unless type.respond_to?('namespace') && !type['namespace'].empty? + type['namespace'] ||= base_namespace unless Es2pandaLibApi.primitive_types.include?(type['name']) type end def error_catch_log(mode, function, err, func_new_name) Es2pandaLibApi.stat_add_unsupported_type(err.message) if err.message.include?('Unsupported type') if mode == 'struct_getter' - Es2pandaLibApi.log('warning', "Error: '#{err.message}'"); + Es2pandaLibApi.log('warning', "Error: '#{err.message}'") Es2pandaLibApi.log('debug', "Field name: #{function.name}\nField type:\n---\n"\ - "#{function.type.to_s}\n---\n\n") + "#{function.type}\n---\n\n") Es2pandaLibApi.log('backtrace', err.backtrace.join("\n"), "\n\n") Es2pandaLibApi.stat_add_method(0, class_name, class_base_namespace, func_new_name) return @@ -759,8 +826,8 @@ module Es2pandaLibApi Es2pandaLibApi.log('info', "Supported constructor for class '#{class_name}'\n") res << { 'overload' => get_new_method_name(constructor_overload, '', ''), - 'idl_overload' => get_new_method_name(idl_constructor_overload, '', '', true), - 'args' => args, 'raw_decl' => constructor.raw_declaration } + 'idl_overload' => get_new_method_name(idl_constructor_overload, '', '', true), + 'args' => args, 'raw_decl' => constructor.raw_declaration } end else Es2pandaLibApi.log('info', "Banned constructor for class '#{class_name}'\n") @@ -780,16 +847,15 @@ module Es2pandaLibApi return false unless Es2pandaLibApi.check_template_type_presents(arg.type) end Es2pandaLibApi.ignored_info['constructors']['call_class']&.each do |call_class| - return false if (call_class['name'] == class_name) + return false if call_class['name'] == class_name end Es2pandaLibApi.ignored_info['template_names']&.each do |template_name| - return false if constructor.respond_to?('template') && (constructor['template'].include?(template_name['name'])) + return false if constructor.respond_to?('template') && constructor['template'].include?(template_name['name']) end # NOTE(nikozer) Need to ban ast verifier default condtructor, will be removed later - if class_name == "ASTVerifier" && constructor.args&.size == 0 - return false - end - return true + return false if class_name == 'ASTVerifier' && constructor.args&.size == 0 + + true end def check_no_gen_method(method) @@ -806,33 +872,36 @@ module Es2pandaLibApi return false unless Es2pandaLibApi.check_template_type_presents(arg.type) end Es2pandaLibApi.ignored_info['return_type']&.each do |return_type| - return false if (method.return_type['name'] == return_type['name'] && (!return_type.respond_to?('namespace') || - return_type['namespace'] == method.return_type['namespace'])) + return false if method.return_type['name'] == return_type['name'] && (!return_type.respond_to?('namespace') || + return_type['namespace'] == method.return_type['namespace']) end Es2pandaLibApi.ignored_info['methods']['call_class']&.each do |call_class| - return false if (call_class['name'] == class_name) + return false if call_class['name'] == class_name end return false unless Es2pandaLibApi.check_template_type_presents(method.return_type) + Es2pandaLibApi.ignored_info['template_names']&.each do |template_name| - return false if method.respond_to?('template') && (method['template'].include?(template_name['name'])) + return false if method.respond_to?('template') && method['template'].include?(template_name['name']) end - return true + true end def check_no_get_field(field) Es2pandaLibApi.ignored_info['return_type']&.each do |return_type| - return false if (field.type['name'] == return_type['name'] && (!return_type.respond_to?('namespace') || - return_type['namespace'] == field.type['namespace'])) + return false if field.type['name'] == return_type['name'] && (!return_type.respond_to?('namespace') || + return_type['namespace'] == field.type['namespace']) end Es2pandaLibApi.ignored_info['methods']['call_class']&.each do |call_class| - return false if (call_class['name'] == class_name) + return false if call_class['name'] == class_name end return false unless Es2pandaLibApi.check_template_type_presents(field.type) - return true + + true end def get_return_expr(return_type, call_cast, consts, method, args, function_type) raise 'Unsupported function type' unless %w[method struct_getter].include?(function_type) + return_expr = '' const, const_return = consts @@ -865,18 +934,18 @@ module Es2pandaLibApi return_expr end - def check_for_same_class_name() + def check_for_same_class_name res = false class_name_for_check = class_name - Es2pandaLibApi.classes&.each do |namespace_name, namespace_classes| + Es2pandaLibApi.classes&.each do |_namespace_name, namespace_classes| res |= namespace_classes&.find { |_name, data| data != self && _name == class_name_for_check } end - return res + res end def get_new_method_name(function_overload, name, const, skip_namespace_overload = false) - function_name = if (check_for_same_class_name && !skip_namespace_overload) then class_base_namespace.capitalize - else '' end + name + (const != '' ? 'Const' : '') + function_name = if check_for_same_class_name && !skip_namespace_overload then class_base_namespace.capitalize + else '' end + name + (const != '' ? 'Const' : '') overload_name = function_name if function_overload.include?(function_name) @@ -912,6 +981,7 @@ module Es2pandaLibApi usings = usings_map methods = dig(:methods) return res unless methods + template_extends.each do |template_extend| methods += Es2pandaLibApi.classes['ir'][template_extend]['methods'] end @@ -1014,13 +1084,12 @@ module Es2pandaLibApi @type_stat_log = false def log(debug_level, *args) - if debug_level == 'info' && @info_log print args.join('').to_s elsif debug_level == 'debug' && @debug_log print args.join('').to_s elsif debug_level == 'warning' && @warning_log - print "WARNING:[e2p_api_generator]: #{args.join('').to_s}" + print "WARNING:[e2p_api_generator]: #{args.join('')}" elsif debug_level == 'backtrace' && @backtrace_log print args.join('').to_s elsif debug_level == 'stat' && @stat_log @@ -1062,11 +1131,11 @@ module Es2pandaLibApi return false unless Es2pandaLibApi.allowed_info['template_types'].include?(template_arg.type.name) if template_arg.type.respond_to?('template_args') - Es2pandaLibApi.log('warning', "Unexpected nested template args in type!"); + Es2pandaLibApi.log('warning', 'Unexpected nested template args in type!') return false end end - return true + true end def check_class_type(class_name, class_base_namespace) @@ -1102,8 +1171,8 @@ module Es2pandaLibApi elsif class_base_namespace == 'es2panda' type = 'Arkts config' else - raise "Unsupported class type for stats class name: \"" + - class_name + "\" class namespace: \"" + class_base_namespace + "\"" + raise 'Unsupported class type for stats class name: "' + + class_name + '" class namespace: "' + class_base_namespace + '"' end type end @@ -1131,17 +1200,13 @@ module Es2pandaLibApi def stat_add_method(support, class_name, class_base_namespace, func_new_name) @all_methods += 1 @supported_methods += support - if support == 1 - stat_add_method_type(class_name, class_base_namespace, func_new_name) - end + stat_add_method_type(class_name, class_base_namespace, func_new_name) if support == 1 end def stat_add_constructor(support, class_name, class_base_namespace, constructor_new_name) @all_constructors += 1 @supported_constructors += support - if support == 1 - stat_add_constructor_type(class_name, class_base_namespace, constructor_new_name) - end + stat_add_constructor_type(class_name, class_base_namespace, constructor_new_name) if support == 1 end def stat_add_class(support, class_name) @@ -1163,8 +1228,7 @@ module Es2pandaLibApi "#{(@supported_constructors / @all_constructors * 100).round(2)} % )\n"\ " - Classes: #{@classes_with_supported_constructor.size} / #{@all_classes.size} ( "\ "#{(@classes_with_supported_constructor.size.to_f / @all_classes.size * 100).round(2)} % )\n"\ - "--------------\n" - ) + "--------------\n") end def ast_variables @@ -1344,9 +1408,10 @@ module Es2pandaLibApi def extends_to_idl(extends) return nil unless extends && !extends.include?(',') + if extends.include?('std::') - Es2pandaLibApi.log('warning', "Unsupported inheritance from '#{extends}'\n") - return nil + Es2pandaLibApi.log('warning', "Unsupported inheritance from '#{extends}'\n") + return nil end extends.gsub(/[<>]/, ' ').split.last.split('::').last @@ -1355,6 +1420,7 @@ module Es2pandaLibApi def template_extends(extends) res = [] return res unless extends + template_extends_classes.each do |extend| res << extend if extends.include?(extend) end diff --git a/ets2panda/test/unit/plugin/plugin_check_manual_capi.cpp b/ets2panda/test/unit/plugin/plugin_check_manual_capi.cpp index 341c119d4d..72332b1a0b 100644 --- a/ets2panda/test/unit/plugin/plugin_check_manual_capi.cpp +++ b/ets2panda/test/unit/plugin/plugin_check_manual_capi.cpp @@ -40,10 +40,10 @@ * es2panda_AstNode *(*UpdateNumberLiteral1)(es2panda_Context *ctx, es2panda_AstNode *original, int64_t value); * es2panda_AstNode *(*UpdateNumberLiteral2)(es2panda_Context *ctx, es2panda_AstNode *original, double value); * es2panda_AstNode *(*UpdateNumberLiteral3)(es2panda_Context *ctx, es2panda_AstNode *original, float value); - * bool(*SetNumberLiteralInt)(es2panda_AstNode *node, int32_t new_value); - * bool(*SetNumberLiteralLong)(es2panda_AstNode *node, int64_t new_value); - * bool(*SetNumberLiteralDouble)(es2panda_AstNode *node, double new_value); - * bool(*SetNumberLiteralFloat)(es2panda_AstNode *node, float new_value); + * bool(*NumberLiteralSetInt)(es2panda_AstNode *node, int32_t new_value); + * bool(*NumberLiteralSetLong)(es2panda_AstNode *node, int64_t new_value); + * bool(*NumberLiteralSetDouble)(es2panda_AstNode *node, double new_value); + * bool(*NumberLiteralSetFloat)(es2panda_AstNode *node, float new_value); * char *(*)(es2panda_Context *, Es2pandaEnum); * Es2pandaEnum (*)(es2panda_Context *, const char *); * void(*DestroyContext)(es2panda_Context *context); @@ -142,10 +142,10 @@ bool CheckNumberLiteral(es2panda_Context *ctx) return false; } - bool setInt32Result = g_impl->SetNumberLiteralInt(updatedInt32AstNode, 8); - bool setInt64Result = g_impl->SetNumberLiteralLong(updatedInt64AstNode, 9); - bool setDoubleResult = g_impl->SetNumberLiteralDouble(updatedDoubleAstNode, 10.0); - bool setFloatResult = g_impl->SetNumberLiteralFloat(updatedFloatAstNode, 11.0); + bool setInt32Result = g_impl->NumberLiteralSetInt(updatedInt32AstNode, 8); + bool setInt64Result = g_impl->NumberLiteralSetLong(updatedInt64AstNode, 9); + bool setDoubleResult = g_impl->NumberLiteralSetDouble(updatedDoubleAstNode, 10.0); + bool setFloatResult = g_impl->NumberLiteralSetFloat(updatedFloatAstNode, 11.0); return setInt32Result && setInt64Result && setDoubleResult && setFloatResult; } -- Gitee From 91c6ae2bf2f99af32d676a9d3b55532724af0ba2 Mon Sep 17 00:00:00 2001 From: oh-rgx Date: Wed, 23 Apr 2025 11:28:43 +0800 Subject: [PATCH 104/268] Modify the checkList Issue: #IC39US Signed-off-by: oh-rgx --- .gitee/PULL_REQUEST_TEMPLATE.zh-CN.md | 49 +++++++-------------------- 1 file changed, 12 insertions(+), 37 deletions(-) diff --git a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md index 2ab6c79989..f3d6c5e20a 100644 --- a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md +++ b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md @@ -16,47 +16,22 @@ ### 测试结果(测试截图直接贴在对应测试项,主干已知问题需明确引入pr/责任人) -#### 当前GGW中未添加的测试套(请在本地进行验证) -1.Fuzz编译测试 -``` -./build.sh --product-name rk3568 --build-target arkcompiler/runtime_core/tests/fuzztest:fuzztest -``` - -2."runtime_core/libpandabase/tests:host_unittest" -release模式: -``` -./build.sh --product-name rk3568 --build-target runtime_core_host_unittest -``` -debug模式: -``` -./build.sh --product-name rk3568 --build-target runtime_core_host_unittest --gn-args is_debug=true -``` - #### 功能测试(除仅涉及文本外必测项)[wiki](https://gitee.com/openharmony/arkcompiler_ets_frontend/wikis/%E4%BB%A3%E7%A0%81%E6%8F%90%E4%BA%A4%E8%A6%81%E6%B1%82%E5%8F%8A%E6%B5%8B%E8%AF%95%E9%AA%8C%E8%AF%81%E6%B5%81%E7%A8%8B) -1. test262测试 - - [ ] 已通过 - - [ ] 不涉及,无需验证 - -2. ut测试 - - [ ] 已通过 - - [ ] 不涉及,无需验证 - -3. verifier测试 - - [ ] 已通过 - - [ ] 不涉及,无需验证 +1. es2abc测试用例(Debug模式) +- [ ] 已通过 +- [ ] 不涉及,无需验证 -#### 独立编译测试(涉及BUILD.gn改动时必测项)[wiki](https://gitee.com/ark_standalone_build/docs#arkcompiler%E5%BC%80%E5%8F%91%E6%8C%87%E5%AF%BC) -1. test262 release - - [ ] 已通过 - - [ ] 不涉及,无需验证 +2. Verifier测试 +- [ ] 已通过 +- [ ] 不涉及,无需验证 -2. ut release - - [ ] 已通过 - - [ ] 不涉及,无需验证 +3. 64位RK编译 +- [ ] 已通过 +- [ ] 不涉及,无需验证 -3. ut debug - - [ ] 已通过 - - [ ] 不涉及,无需验证 +4. 编译mac平台sdk +- [ ] 已通过 +- [ ] 不涉及,无需验证 #### 混淆测试(涉及arkguard改动时必测项)[wiki](https://gitee.com/openharmony/arkcompiler_ets_frontend/wikis/%E6%B7%B7%E6%B7%86%E6%B5%8B%E8%AF%95%E9%AA%8C%E8%AF%81%E6%B5%81%E7%A8%8B?sort_id=11451209) 1. 单元测试 -- Gitee From a9cfb61d4518e46a28d72f0859b0f20021c2d926 Mon Sep 17 00:00:00 2001 From: beratagaca_9a91 Date: Thu, 17 Apr 2025 14:32:44 +0300 Subject: [PATCH 105/268] Title:CTE-Implementing interface properties Issue: IC372X Test: Build Signed-off-by: beratagaca_9a91 --- ets2panda/checker/ETSchecker.h | 1 + ets2panda/checker/ets/object.cpp | 34 +++++++++++++++++++++++++ ets2panda/util/diagnostic/semantic.yaml | 4 +++ 3 files changed, 39 insertions(+) diff --git a/ets2panda/checker/ETSchecker.h b/ets2panda/checker/ETSchecker.h index 44ed5a9c1c..105c66d5c8 100644 --- a/ets2panda/checker/ETSchecker.h +++ b/ets2panda/checker/ETSchecker.h @@ -253,6 +253,7 @@ public: void CheckValidInheritance(ETSObjectType *classType, ir::ClassDefinition *classDef); void CheckProperties(ETSObjectType *classType, ir::ClassDefinition *classDef, varbinder::LocalVariable *it, varbinder::LocalVariable *found, ETSObjectType *interfaceFound); + void CheckReadonlyClassPropertyInImplementedInterface(ETSObjectType *classType, varbinder::LocalVariable *field); void TransformProperties(ETSObjectType *classType); void CheckGetterSetterProperties(ETSObjectType *classType); void AddElementsToModuleObject(ETSObjectType *moduleObj, const util::StringView &str); diff --git a/ets2panda/checker/ets/object.cpp b/ets2panda/checker/ets/object.cpp index bca2ab9e3c..0c5bac9d03 100644 --- a/ets2panda/checker/ets/object.cpp +++ b/ets2panda/checker/ets/object.cpp @@ -2250,6 +2250,39 @@ void ETSChecker::CheckProperties(ETSObjectType *classType, ir::ClassDefinition * classDef->Super()->Start()); } +void ETSChecker::CheckReadonlyClassPropertyInImplementedInterface(ETSObjectType *classType, + varbinder::LocalVariable *field) +{ + const auto searchFlag = PropertySearchFlags::SEARCH_ALL | PropertySearchFlags::SEARCH_IN_BASE | + PropertySearchFlags::SEARCH_IN_INTERFACES | + PropertySearchFlags::DISALLOW_SYNTHETIC_METHOD_CREATION; + const auto &interfaceList = GetInterfaces(classType); + if (field == nullptr || field->Declaration() == nullptr || field->Declaration()->Node() == nullptr || + !field->Declaration()->Node()->IsClassProperty() || + !field->Declaration()->Node()->AsClassProperty()->IsReadonly()) { + return; + } + + for (auto *interface : interfaceList) { + ES2PANDA_ASSERT(interface != nullptr); + auto *propertyFound = interface->GetProperty(field->Name(), searchFlag); + if (propertyFound == nullptr) { + continue; + } + + ES2PANDA_ASSERT(propertyFound->TsType() != nullptr); + if (!propertyFound->TsType()->IsETSFunctionType()) { + continue; + } + + auto setter = propertyFound->TsType()->AsETSFunctionType()->FindSetter(); + if (setter != nullptr) { + LogError(diagnostic::INTERFACE_PROPERTY_REQUIRES_SETTER, {interface->Name(), field->Name()}, + field->Declaration()->Node()->Start()); + } + } +} + void ETSChecker::TransformProperties(ETSObjectType *classType) { auto propertyList = classType->Fields(); @@ -2266,6 +2299,7 @@ void ETSChecker::TransformProperties(ETSObjectType *classType) if (!field->HasFlag(varbinder::VariableFlags::PUBLIC)) { LogError(diagnostic::INTERFACE_PROP_NOT_PUBLIC, {}, field->Declaration()->Node()->Start()); } + CheckReadonlyClassPropertyInImplementedInterface(classType, field); classType->RemoveProperty(field); // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) GenerateGetterSetterPropertyAndMethod(originalProp, classType); diff --git a/ets2panda/util/diagnostic/semantic.yaml b/ets2panda/util/diagnostic/semantic.yaml index 34150bda7d..c26a225e8c 100644 --- a/ets2panda/util/diagnostic/semantic.yaml +++ b/ets2panda/util/diagnostic/semantic.yaml @@ -1126,3 +1126,7 @@ semantic: - name: NOT_ALLOWED_THIS_IN_ARRAY_TYPE id: 283 message: "A 'this' cannot be used as type of array." + +- name: INTERFACE_PROPERTY_REQUIRES_SETTER + id: 284 + message: "Cannot implement interface {}: property '{}' must have a setter, but the implementation is readonly" -- Gitee From 91c406768a7b4b82aab6ef0bd9bcdae74ec548f9 Mon Sep 17 00:00:00 2001 From: ElevenDuan Date: Fri, 18 Apr 2025 21:34:16 +0800 Subject: [PATCH 106/268] Fix compile abc file failed Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC2BZS?from=project-issue Change-Id: Ib22a1e0217d0b448a9f56a881de0515a1afeb76a Signed-off-by: ElevenDuan --- es2panda/compiler/core/compileQueue.cpp | 3 +- .../abc2program/update-version/base.ts | 21 ++++ .../update-version/compileContextInfo.json | 12 +++ .../abc2program/update-version/expected.txt | 101 ++++++++++++++++++ es2panda/test/runner.py | 66 ++++++++++++ 5 files changed, 202 insertions(+), 1 deletion(-) create mode 100644 es2panda/test/compiler/abc2program/update-version/base.ts create mode 100644 es2panda/test/compiler/abc2program/update-version/compileContextInfo.json create mode 100644 es2panda/test/compiler/abc2program/update-version/expected.txt diff --git a/es2panda/compiler/core/compileQueue.cpp b/es2panda/compiler/core/compileQueue.cpp index c882b086dd..5abe071217 100644 --- a/es2panda/compiler/core/compileQueue.cpp +++ b/es2panda/compiler/core/compileQueue.cpp @@ -281,7 +281,7 @@ void CompileAbcClassJob::UpdateDynamicImport(panda::pandasm::Program *prog, const std::map &pkgContextInfo) { for (auto &[name, function] : prog->function_table) { - util::VisitDyanmicImports(function, [this, pkgContextInfo](std::string &ohmurl) { + util::VisitDyanmicImports(function, [this, &prog, pkgContextInfo](std::string &ohmurl) { if (this->options_.compileContextInfo.needModifyRecord) { this->UpdateBundleNameOfOhmurl(ohmurl); } @@ -289,6 +289,7 @@ void CompileAbcClassJob::UpdateDynamicImport(panda::pandasm::Program *prog, if (newOhmurl == ohmurl) { return; } + prog->strings.insert(newOhmurl); this->SetOhmurlBeenChanged(true); ohmurl = newOhmurl; }); diff --git a/es2panda/test/compiler/abc2program/update-version/base.ts b/es2panda/test/compiler/abc2program/update-version/base.ts new file mode 100644 index 0000000000..62cf898c38 --- /dev/null +++ b/es2panda/test/compiler/abc2program/update-version/base.ts @@ -0,0 +1,21 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { test } from '@normalized:N&&&package/src/main/test&1.0.0'; + +test(); + +import('@normalized:N&&&package/src/main/other&1.0.0').then(()=>{ +}); diff --git a/es2panda/test/compiler/abc2program/update-version/compileContextInfo.json b/es2panda/test/compiler/abc2program/update-version/compileContextInfo.json new file mode 100644 index 0000000000..1d3cedb7c4 --- /dev/null +++ b/es2panda/test/compiler/abc2program/update-version/compileContextInfo.json @@ -0,0 +1,12 @@ +{ + "compileEntries": [ + ], + "projectRootPath": "", + "pkgContextInfo": { + "package": { + "packageName": "package", + "version": "2.0.0" + } + }, + "hspPkgNames": [] +} \ No newline at end of file diff --git a/es2panda/test/compiler/abc2program/update-version/expected.txt b/es2panda/test/compiler/abc2program/update-version/expected.txt new file mode 100644 index 0000000000..da32b0ac80 --- /dev/null +++ b/es2panda/test/compiler/abc2program/update-version/expected.txt @@ -0,0 +1,101 @@ + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x0 +.language ECMAScript +.function any original.#*#(any a0, any a1, any a2) { + returnundefined +} + +slotNum = 0x7 +.language ECMAScript +.function any original.func_main_0(any a0, any a1, any a2) { + newlexenv 0x2 + lda a1 + stlexvar 0x0, 0x0 + lda a2 + stlexvar 0x0, 0x1 + ldexternalmodulevar 0x0 + sta v0 + throw.undefinedifholewithname test + lda v0 + callarg0 0x0 + lda.str @normalized:N&&&package/src/main/other&2.0.0 + dynamicimport + sta v0 + ldobjbyname 0x2, then + sta v1 + definefunc 0x4, original.#*#, 0x0 + sta v2 + lda v1 + callthis1 0x5, v0, v2 + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot original_686 +------------------------------------ +slot original_690 +{ + index: 0 + tag: 2 + val: 1 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&&&package/src/main/test&2.0.0 +}, +{ + index: 2 + tag: 2 + val: 1 +}, +{ + index: 3 + tag: 5 + val: test +}, +{ + index: 4 + tag: 5 + val: test +}, +{ + index: 5 + tag: 9 + val: 0 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +{ + index: 8 + tag: 2 + val: 0 +}, +{ + index: 9 + tag: 2 + val: 0 +}, +======> strings <====== +"@normalized:N&&&package/src/main/other&1.0.0"; "@normalized:N&&&package/src/main/other&2.0.0"; "original.#*#"; "test"; "then"; diff --git a/es2panda/test/runner.py b/es2panda/test/runner.py index 14bb308dd6..f378d108c3 100755 --- a/es2panda/test/runner.py +++ b/es2panda/test/runner.py @@ -601,6 +601,10 @@ class CompilerRunner(Runner): test_path = path.join(self.test_root, directory) for project in os.listdir(test_path): self.tests.append(CompilerProtobinTest(path.join(test_path, project), flags)) + elif directory.endswith("abc2program"): + test_path = path.join(self.test_root, directory) + for project in os.listdir(test_path): + self.tests.append(CompilerAbcFileTest(path.join(test_path, project), flags)) else: glob_expression = path.join( self.test_root, directory, "**/*.%s" % (extension)) @@ -716,6 +720,64 @@ class CompilerTest(Test): return self +class CompilerAbcFileTest(Test): + def __init__(self, test_dir, flags): + Test.__init__(self, test_dir, flags) + self.test_dir = test_dir + self.generated_path = os.path.join(self.test_dir, "gen") + if not path.exists(self.generated_path): + os.makedirs(self.generated_path) + self.original_abc_path = os.path.join(self.generated_path, "original.abc") + self.output_path = os.path.join(self.generated_path, "result.abc") + self.original_test = os.path.join(self.test_dir, "base.ts") + self.expected_path = os.path.join(self.test_dir, "expected.txt") + + def remove_test_build(self, runner): + if path.exists(self.generated_path): + shutil.rmtree(self.generated_path) + + def gen_abc(self, runner, test_path, output_path, flags): + es2abc_cmd = runner.cmd_prefix + [runner.es2panda] + es2abc_cmd.extend(['%s%s' % ("--output=", output_path)]) + es2abc_cmd.extend(flags) + es2abc_cmd.append(test_path) + process = run_subprocess_with_beta3(self, es2abc_cmd) + out, err = process.communicate() + if err: + self.passed = False + self.error = err.decode("utf-8", errors="ignore") + self.remove_test_build(runner) + return self + + def run(self, runner): + new_flags = self.flags + # Generate 'abc' from the source file + self.gen_abc(runner, self.original_test, self.original_abc_path, new_flags) + # Generate 'abc' from the abc file + new_flags = self.flags + compile_context_info_path = path.join(self.test_dir, "compileContextInfo.json") + if path.exists(compile_context_info_path): + new_flags.append("%s%s" % ("--compile-context-info=", compile_context_info_path)) + es2abc_cmd = runner.cmd_prefix + [runner.es2panda] + es2abc_cmd.append('%s%s' % ("--output=", self.output_path)) + es2abc_cmd.append(self.original_abc_path) + es2abc_cmd.extend(new_flags) + process = run_subprocess_with_beta3(self, es2abc_cmd) + out, err = process.communicate() + self.output = out.decode("utf-8", errors="ignore") + err.decode("utf-8", errors="ignore") + try: + with open(self.expected_path, 'r') as fp: + expected = fp.read() + self.passed = expected == self.output and process.returncode in [0, 1] + except Exception: + self.passed = False + if not self.passed: + self.remove_test_build(runner) + return self + self.remove_test_build(runner) + return self + + class CompilerProtobinTest(Test): def __init__(self, test_dir, flags): Test.__init__(self, test_dir, flags) @@ -2730,6 +2792,10 @@ def add_directory_for_compiler(runners, args): compiler_test_infos.append(CompilerTestInfo("compiler/merge_hap/projects", "ts", ["--merge-abc", "--dump-assembly", "--enable-abc-input", "--dump-literal-buffer", "--dump-string", "--abc-class-threads=4"])) + compiler_test_infos.append(CompilerTestInfo("compiler/abc2program", "ts", + ["--merge-abc", "--module", "--dump-assembly", "--enable-abc-input", + "--dump-literal-buffer", "--dump-string", "--source-file=source.ts", + "--module-record-field-name=source"])) if args.enable_arkguard: prepare_for_obfuscation(compiler_test_infos, runner.test_root) -- Gitee From f8ef3cbd2b9ebf0b240b3d6cbb8f16464e8e37a9 Mon Sep 17 00:00:00 2001 From: xuxinjie4 Date: Fri, 18 Apr 2025 19:51:20 +0800 Subject: [PATCH 107/268] Fix type infer bug Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC29UO?from=project-issue Signed-off-by: xuxinjie4 --- ets2panda/checker/ETSAnalyzerHelpers.cpp | 1 + .../ast/compiler/ets/Incorrect_arrow_func.ets | 21 +++++++++++++++++++ 2 files changed, 22 insertions(+) create mode 100644 ets2panda/test/ast/compiler/ets/Incorrect_arrow_func.ets diff --git a/ets2panda/checker/ETSAnalyzerHelpers.cpp b/ets2panda/checker/ETSAnalyzerHelpers.cpp index 5e2d1d5f89..d9d2bb1167 100644 --- a/ets2panda/checker/ETSAnalyzerHelpers.cpp +++ b/ets2panda/checker/ETSAnalyzerHelpers.cpp @@ -676,6 +676,7 @@ void InferReturnType(ETSChecker *checker, ir::ScriptFunction *containingFunc, ch funcReturnType = stArgument == nullptr ? checker->GlobalVoidType() : checker->GetNonConstantType(stArgument->Check(checker)); if (funcReturnType->IsTypeError()) { + containingFunc->Signature()->RemoveSignatureFlag(checker::SignatureFlags::NEED_RETURN_TYPE); return; } diff --git a/ets2panda/test/ast/compiler/ets/Incorrect_arrow_func.ets b/ets2panda/test/ast/compiler/ets/Incorrect_arrow_func.ets new file mode 100644 index 0000000000..0833b29c81 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/Incorrect_arrow_func.ets @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +let f = ()=>int {} +f() + +/* @@? 16:13 Error TypeError: Unresolved reference int */ +/* @@? 16:13 Error TypeError: Unexpected return value, enclosing method return type is void. */ +/* @@? 16:17 Error SyntaxError: Unexpected token '{'. */ -- Gitee From 90d56b9edbdc621c0a2f7bca15fc750082120995 Mon Sep 17 00:00:00 2001 From: Khil Sergey Date: Mon, 14 Apr 2025 07:17:36 +0300 Subject: [PATCH 108/268] Fix clang tidy Issue:#IC0WUH Signed-off-by: Khil Sergey --- ets2panda/declgen_ets2ts/declgenEts2Ts.cpp | 42 ++++++++++------------ ets2panda/test/unit/plugin/util.cpp | 16 +++++---- ets2panda/test/unit/plugin/util.h | 2 +- 3 files changed, 30 insertions(+), 30 deletions(-) diff --git a/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp b/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp index 2f9c32175e..678bb882cd 100644 --- a/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp +++ b/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp @@ -32,7 +32,6 @@ #include "ir/ts/tsTypeAliasDeclaration.h" #include "ir/ts/tsTypeParameter.h" -/* CC-OFFNXT(G.PRE.01) Disabled check still occasionally triggered in CI */ #define DEBUG_PRINT 0 namespace ark::es2panda::declgen_ets2ts { @@ -397,9 +396,9 @@ bool TSDeclGen::HandleObjectType(const checker::Type *checkerType) std::string typeStr = checkerType->ToString(); if (typeStr == "Boolean") { OutDts("boolean"); - } else if (stringTypes_.count(typeStr)) { + } else if (stringTypes_.count(typeStr) != 0U) { OutDts("string"); - } else if (numberTypes_.count(typeStr)) { + } else if (numberTypes_.count(typeStr) != 0U) { OutDts("number"); } else if (typeStr == "BigInt") { OutDts("bigint"); @@ -652,26 +651,26 @@ void TSDeclGen::ProcessFunctionReturnTypeRef(const checker::Signature *sig, cons void TSDeclGen::GenUnionType(const checker::ETSUnionType *unionType) { state_.inUnionBodyStack.push(true); - const auto originTypes = unionType->ConstituentTypes(); + const auto &originTypes = unionType->ConstituentTypes(); bool hasNumber = false; bool hasString = false; std::vector filteredTypes; - for (std::size_t i = 0; i < originTypes.size(); ++i) { - std::string typeStr = originTypes[i]->ToString(); - if (stringTypes_.count(typeStr)) { + for (auto originType : originTypes) { + std::string typeStr = originType->ToString(); + if (stringTypes_.count(typeStr) != 0U) { if (hasString) { continue; } - filteredTypes.push_back(originTypes[i]); + filteredTypes.push_back(originType); hasString = true; - } else if (numberTypes_.count(typeStr)) { + } else if (numberTypes_.count(typeStr) != 0U) { if (hasNumber) { continue; } - filteredTypes.push_back(originTypes[i]); + filteredTypes.push_back(originType); hasNumber = true; } else { - filteredTypes.push_back(originTypes[i]); + filteredTypes.push_back(originType); } } GenSeparated( @@ -716,7 +715,7 @@ bool TSDeclGen::HandleSpecificObjectTypes(const checker::ETSObjectType *objectTy void TSDeclGen::HandleTypeArgument(checker::Type *arg, const std::string &typeStr) { - if (typeStr == "Promise" && arg && arg->HasTypeFlag(checker::TypeFlag::ETS_UNDEFINED)) { + if (typeStr == "Promise" && arg != nullptr && arg->HasTypeFlag(checker::TypeFlag::ETS_UNDEFINED)) { OutDts("void"); } else if (arg != nullptr) { if (!state_.currentTypeAliasName.empty() && !arg->HasTypeFlag(checker::TypeFlag::ETS_TYPE_PARAMETER)) { @@ -788,9 +787,9 @@ void TSDeclGen::GenTypeParameters(const ir::TSTypeParameterInstantiation *typePa GenSeparated(typeParams->Params(), [this](ir::TypeNode *param) { if (param->IsETSTypeReference()) { const auto paramName = param->AsETSTypeReference()->Part()->Name()->AsIdentifier()->Name().Mutf8(); - if (stringTypes_.count(paramName)) { + if (stringTypes_.count(paramName) != 0U) { OutDts("string"); - } else if (numberTypes_.count(paramName)) { + } else if (numberTypes_.count(paramName) != 0U) { OutDts("number"); } else if (paramName == "NullPointerError") { OutDts("Error"); @@ -917,7 +916,7 @@ void TSDeclGen::GenAnnotationProperties(const ir::AnnotationUsage *anno) return; } - const auto properties = anno->Properties(); + const auto &properties = anno->Properties(); if (properties.size() == 1 && properties.at(0)->AsClassProperty()->Id()->Name() == compiler::Signatures::ANNOTATION_KEY_VALUE) { OutDts("("); @@ -1013,13 +1012,10 @@ void TSDeclGen::GenImportDeclaration(const ir::ETSImportDeclaration *importDecla std::vector TSDeclGen::FilterValidImportSpecifiers(const ArenaVector &specifiers) { std::vector importSpecifiers; - for (std::size_t i = 0; i < specifiers.size(); i++) { - const auto local = specifiers[i]->AsImportSpecifier()->Local()->Name().Mutf8(); - if (specifiers[i]->AsImportSpecifier()->IsRemovable()) { - continue; - } + for (auto specifier : specifiers) { + const auto local = specifier->AsImportSpecifier()->Local()->Name().Mutf8(); if (importSet_.find(local) != importSet_.end()) { - importSpecifiers.push_back(specifiers[i]); + importSpecifiers.push_back(specifier); } } return importSpecifiers; @@ -1278,9 +1274,9 @@ void TSDeclGen::GenPartName(std::string &partName) { if (partName == "Boolean") { partName = "boolean"; - } else if (stringTypes_.count(partName)) { + } else if (stringTypes_.count(partName) != 0U) { partName = "string"; - } else if (numberTypes_.count(partName)) { + } else if (numberTypes_.count(partName) != 0U) { partName = "number"; } else if (partName == "ESObject") { partName = "ESObject"; diff --git a/ets2panda/test/unit/plugin/util.cpp b/ets2panda/test/unit/plugin/util.cpp index adfdf1f81e..898ad85fa3 100644 --- a/ets2panda/test/unit/plugin/util.cpp +++ b/ets2panda/test/unit/plugin/util.cpp @@ -19,6 +19,7 @@ #include #include #include +#include "macros.h" static es2panda_Impl *g_implPtr = nullptr; @@ -75,7 +76,7 @@ void AppendStatementToProgram(es2panda_Context *context, es2panda_AstNode *progr auto impl = GetImpl(); size_t sizeOfStatements = 0; auto *statements = impl->BlockStatementStatements(context, program, &sizeOfStatements); - es2panda_AstNode **newStatements = + auto **newStatements = static_cast(impl->AllocMemory(context, sizeOfStatements + 1, sizeof(es2panda_AstNode *))); for (size_t i = 0; i < sizeOfStatements; i++) { newStatements[i] = statements[i]; @@ -90,7 +91,7 @@ void PrependStatementToProgram(es2panda_Context *context, es2panda_AstNode *prog auto impl = GetImpl(); size_t sizeOfStatements = 0; auto *statements = impl->BlockStatementStatements(context, program, &sizeOfStatements); - es2panda_AstNode **newStatements = + auto **newStatements = static_cast(impl->AllocMemory(context, sizeOfStatements + 1, sizeof(es2panda_AstNode *))); for (size_t i = 0; i < sizeOfStatements; i++) { newStatements[i + 1] = statements[i]; @@ -184,7 +185,7 @@ int RunAllStagesWithTestFunction(ProccedToStatePluginTestData &data) } g_implPtr->ProceedToState(context, state); CheckForErrors(GetPhaseName(state), context); - for (auto testFunc : data.testFunctions[state]) { + for (const auto &testFunc : data.testFunctions[state]) { if (!testFunc(context)) { DestroyTest(context, config); return TEST_ERROR_CODE; @@ -201,12 +202,12 @@ int RunAllStagesWithTestFunction(ProccedToStatePluginTestData &data) } int Test(es2panda_Context *context, es2panda_Impl *impl, int stage, - std::function handle) + const std::function &handle) { impl->ProceedToState(context, ES2PANDA_STATE_PARSED); CheckForErrors("PARSE", context); es2panda_AstNode *ast = impl->ProgramAst(context, impl->ContextProgram(context)); - if (!ast) { + if (ast == nullptr) { return TEST_ERROR_CODE; } switch (stage) { @@ -228,6 +229,9 @@ int Test(es2panda_Context *context, es2panda_Impl *impl, int stage, CheckForErrors("LOWERED", context); break; } + default: { + UNREACHABLE(); + } } if (impl->ContextState(context) == ES2PANDA_STATE_ERROR) { return PROCEED_ERROR_CODE; @@ -247,4 +251,4 @@ int Test(es2panda_Context *context, es2panda_Impl *impl, int stage, } impl->DestroyContext(context); return 0; -} \ No newline at end of file +} diff --git a/ets2panda/test/unit/plugin/util.h b/ets2panda/test/unit/plugin/util.h index ba30c32c4d..4bfae76fba 100644 --- a/ets2panda/test/unit/plugin/util.h +++ b/ets2panda/test/unit/plugin/util.h @@ -59,6 +59,6 @@ void AppendStatementToProgram(es2panda_Context *context, es2panda_AstNode *progr void PrependStatementToProgram(es2panda_Context *context, es2panda_AstNode *program, es2panda_AstNode *newStatement); int Test(es2panda_Context *context, es2panda_Impl *impl, int stage, - std::function handle); + const std::function &handle); #endif -- Gitee From 77abad677d775195719d2691e179c5c7f1bd4216 Mon Sep 17 00:00:00 2001 From: molotkovmikhail Date: Fri, 14 Feb 2025 15:31:42 +0800 Subject: [PATCH 109/268] Update then signatur Update then signatur Issue: https://gitee.com/openharmony/arkcompiler_runtime_core/issues/IBMC22 Testing: `ninja tests` Change-Id: I146c2a5e2850dbd86f18f3f536441c2d7043957c Signed-off-by: molotkovmikhail --- ets2panda/scripts/arkui.properties | 2 +- ets2panda/test/runtime/ets/ThrowStatementCloneFunction.ets | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/ets2panda/scripts/arkui.properties b/ets2panda/scripts/arkui.properties index aab7f71e6c..cbe2883b04 100644 --- a/ets2panda/scripts/arkui.properties +++ b/ets2panda/scripts/arkui.properties @@ -1,3 +1,3 @@ ARKUI_DEV_REPO=https://gitee.com/rri_opensource/koala_projects.git -ARKUI_DEV_BRANCH=panda_rev_7 +ARKUI_DEV_BRANCH=panda_rev_7-1-type-error ARKUI_DEST=koala-sig diff --git a/ets2panda/test/runtime/ets/ThrowStatementCloneFunction.ets b/ets2panda/test/runtime/ets/ThrowStatementCloneFunction.ets index dc16545ec6..a17d795587 100644 --- a/ets2panda/test/runtime/ets/ThrowStatementCloneFunction.ets +++ b/ets2panda/test/runtime/ets/ThrowStatementCloneFunction.ets @@ -14,13 +14,13 @@ */ let error = new Error(); -let p = new Promise((resolve: (value: string) => void, reject: (error: Object) => void) => { +let p = new Promise((resolve: (value: string) => void, reject: (error: Error) => void) => { throw error; }); p.then((value: string): void => { console.log("Test failed. The promise should not be fulfilled."); -}, (err: Object): void => { +}, (err: Error): void => { if (err !== error) { return; } -- Gitee From 5e6ff133a864e3d44837a26cf7ef8f9400a40671 Mon Sep 17 00:00:00 2001 From: guanmingyue Date: Thu, 24 Apr 2025 19:03:00 +0800 Subject: [PATCH 110/268] Update kfl 0423 Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC3C97 Signed-off-by: guanmingyue --- test/workload/ignored-third_lib_js-release-x64-jit.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/workload/ignored-third_lib_js-release-x64-jit.txt b/test/workload/ignored-third_lib_js-release-x64-jit.txt index 573a56debb..743b88c5fd 100644 --- a/test/workload/ignored-third_lib_js-release-x64-jit.txt +++ b/test/workload/ignored-third_lib_js-release-x64-jit.txt @@ -1 +1,3 @@ # Known failures list for third_lib_js - release-x64-jit +#18340 +Drools_test -- Gitee From 80f9cf50105e2ff9e2ad2cb9cce31d7b5adcfb8c Mon Sep 17 00:00:00 2001 From: dengwenjun Date: Thu, 24 Apr 2025 20:55:57 +0800 Subject: [PATCH 111/268] =?UTF-8?q?=E7=8B=AC=E7=AB=8B=E7=BC=96=E8=AF=91?= =?UTF-8?q?=E4=BB=93=E8=BF=81=E7=A7=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1.删掉toolchain目录下的build目录; 2.将build目录迁移到ark_standalone_build代码仓中的build仓中,并对相关的脚本进行修改; 3.修改ark_standalone_build代码仓中的manifest仓中的arkcompiler.xml和openharmony.xml文件; 4.修改arkcompiler_ets_runtime、arkcompiler_toolchain、arkcompiler_ets_frontend、arkcompiler_runtime_core仓中的相关文件; Issue:https://gitee.com/openharmony/arkcompiler_toolchain/issues/IC3RD3?from=project-issue Signed-off-by: dengwenjun --- ets_frontend_config.gni | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ets_frontend_config.gni b/ets_frontend_config.gni index 2c0ece9f9a..67b7c47488 100644 --- a/ets_frontend_config.gni +++ b/ets_frontend_config.gni @@ -21,7 +21,7 @@ if (!ark_standalone_build) { toolchain_ohos = "$build_root/toolchain/ohos:ohos_clang_arm64" import("$build_root/ohos.gni") } else { - ark_third_party_root = "//arkcompiler/toolchain/build/third_party_gn" + ark_third_party_root = "//build/third_party_gn" import("$build_root/ark.gni") } import("$build_root/test.gni") -- Gitee From 9d2d55f00b4ac236bc0d563ecbe738a2c40a77d3 Mon Sep 17 00:00:00 2001 From: xuxinjie4 Date: Mon, 21 Apr 2025 20:03:19 +0800 Subject: [PATCH 112/268] Fix keyof bug Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC2VHB?from=project-issue Signed-off-by: xuxinjie4 --- ets2panda/checker/ETSchecker.h | 1 + ets2panda/checker/ets/typeCreation.cpp | 72 ++++++++++++++------------ 2 files changed, 40 insertions(+), 33 deletions(-) diff --git a/ets2panda/checker/ETSchecker.h b/ets2panda/checker/ETSchecker.h index 105c66d5c8..34b1adcbdb 100644 --- a/ets2panda/checker/ETSchecker.h +++ b/ets2panda/checker/ETSchecker.h @@ -292,6 +292,7 @@ public: return CreateETSUnionType(Span(constituentTypes)); } Type *CreateUnionFromKeyofType(ETSObjectType *const type); + void ProcessTypeMembers(ETSObjectType *type, ArenaVector &literals); ETSAsyncFuncReturnType *CreateETSAsyncFuncReturnTypeFromPromiseType(ETSObjectType *promiseType); ETSAsyncFuncReturnType *CreateETSAsyncFuncReturnTypeFromBaseType(Type *baseType); ETSTypeAliasType *CreateETSTypeAliasType(util::StringView name, const ir::AstNode *declNode, diff --git a/ets2panda/checker/ets/typeCreation.cpp b/ets2panda/checker/ets/typeCreation.cpp index a462d3f992..86de973cb9 100644 --- a/ets2panda/checker/ets/typeCreation.cpp +++ b/ets2panda/checker/ets/typeCreation.cpp @@ -426,56 +426,62 @@ ETSObjectType *ETSChecker::CreatePromiseOf(Type *type) return promiseType->Substitute(Relation(), substitution); } -Type *ETSChecker::CreateUnionFromKeyofType(ETSObjectType *const type) +static bool IsInValidKeyofTypeNode(ir::AstNode *node) { - ArenaVector stringLiterals(Allocator()->Adapter()); + return (node->Modifiers() & ir::ModifierFlags::PRIVATE) != 0 || + (node->Modifiers() & ir::ModifierFlags::PROTECTED) != 0; +} - std::deque superTypes; - superTypes.push_back(type); - auto addToUnion = [this, &stringLiterals](checker::ETSObjectType *it) { - if (it == GlobalETSObjectType()) { - return; - } - for (auto *method : it->Methods()) { - if (method->HasFlag(varbinder::VariableFlags::PRIVATE) || - method->HasFlag(varbinder::VariableFlags::PROTECTED)) { +void ETSChecker::ProcessTypeMembers(ETSObjectType *type, ArenaVector &literals) +{ + if (type == GlobalETSObjectType()) { + return; + } + + for (auto *method : type->Methods()) { + auto *methodDef = method->Declaration()->Node()->AsMethodDefinition(); + for (auto *overload : methodDef->Overloads()) { + if (IsInValidKeyofTypeNode(overload)) { continue; } - stringLiterals.push_back(this->CreateETSStringLiteralType(method->Name())); + literals.push_back(CreateETSStringLiteralType(overload->Key()->Variable()->Name())); } - for (auto *field : it->Fields()) { - if (field->HasFlag(varbinder::VariableFlags::PRIVATE) || - field->HasFlag(varbinder::VariableFlags::PROTECTED)) { - continue; - } - stringLiterals.push_back(this->CreateETSStringLiteralType(field->Name())); + if (!IsInValidKeyofTypeNode(method->Declaration()->Node())) { + literals.push_back(CreateETSStringLiteralType(method->Name())); } - }; + } - auto addObjToDeque = [&superTypes](checker::ETSObjectType *it) { - if (it->SuperType() != nullptr) { - superTypes.push_back(it->SuperType()); + for (auto *field : type->Fields()) { + if (IsInValidKeyofTypeNode(field->Declaration()->Node())) { + continue; } - if (it->Interfaces().empty()) { - return; + literals.push_back(CreateETSStringLiteralType(field->Name())); + } +} + +Type *ETSChecker::CreateUnionFromKeyofType(ETSObjectType *const type) +{ + ArenaVector stringLiterals(Allocator()->Adapter()); + std::deque superTypes; + superTypes.push_back(type); + auto enqueueSupers = [&](ETSObjectType *currentType) { + if (currentType->SuperType() != nullptr) { + superTypes.push_back(currentType->SuperType()); } - for (auto inteface : it->Interfaces()) { - superTypes.push_back(inteface); + for (auto interface : currentType->Interfaces()) { + superTypes.push_back(interface); } }; while (!superTypes.empty()) { - auto *extendsObject = superTypes.front(); + auto *currentType = superTypes.front(); superTypes.pop_front(); - addToUnion(extendsObject); - addObjToDeque(extendsObject); - } - if (stringLiterals.empty()) { - return GlobalETSNeverType(); + ProcessTypeMembers(currentType, stringLiterals); + enqueueSupers(currentType); } - return CreateETSUnionType(std::move(stringLiterals)); + return stringLiterals.empty() ? GlobalETSNeverType() : CreateETSUnionType(std::move(stringLiterals)); } ETSAsyncFuncReturnType *ETSChecker::CreateETSAsyncFuncReturnTypeFromPromiseType(ETSObjectType *promiseType) -- Gitee From fbb49b29ae9e82842439927643405def09102d5f Mon Sep 17 00:00:00 2001 From: xuxinjie4 Date: Mon, 21 Apr 2025 22:09:36 +0800 Subject: [PATCH 113/268] Fix a bug that access to common union method Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC2VI4?from=project-issue Signed-off-by: xuxinjie4 --- ets2panda/compiler/lowering/ets/unionLowering.cpp | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/ets2panda/compiler/lowering/ets/unionLowering.cpp b/ets2panda/compiler/lowering/ets/unionLowering.cpp index 80fe82ec8c..72f53743f8 100644 --- a/ets2panda/compiler/lowering/ets/unionLowering.cpp +++ b/ets2panda/compiler/lowering/ets/unionLowering.cpp @@ -82,22 +82,19 @@ static std::tuple CreateNamedA auto allocator = checker->Allocator(); auto unionType = checker->GetApparentType(checker->GetNonNullishType(expr->Object()->TsType()))->AsETSUnionType(); auto *const accessClass = GetUnionAccessClass(checker, varbinder, GetAccessClassName(unionType)); - auto methodType = expr->TsType()->AsETSFunctionType(); - auto methodName = methodType->Name(); + auto methodName = expr->TsType()->AsETSFunctionType()->Name(); // Create method name for synthetic class auto *methodIdent = checker->AllocNode(methodName, allocator); // Create the synthetic function node - auto *sig = methodType->CallSignatures().front(); + auto *sig = expr->Parent()->AsCallExpression()->Signature(); ArenaVector params {allocator->Adapter()}; for (auto param : sig->Function()->Params()) { params.emplace_back(param->Clone(allocator, nullptr)->AsETSParameterExpression()); } - auto returnTypeAnno = sig->Function()->ReturnTypeAnnotation() != nullptr - ? sig->Function()->ReturnTypeAnnotation()->Clone(allocator, nullptr) - : checker->AllocNode(sig->ReturnType(), allocator); + auto returnTypeAnno = checker->AllocNode(sig->ReturnType(), allocator); auto *func = checker->AllocNode( allocator, ir::ScriptFunction::ScriptFunctionData { -- Gitee From 35496b4150a1f0dd4ba4bf7993ccce3ebaf33b14 Mon Sep 17 00:00:00 2001 From: hecunmao Date: Fri, 25 Apr 2025 10:25:35 +0800 Subject: [PATCH 114/268] =?UTF-8?q?=E5=B1=8F=E8=94=BD=E7=94=B1=E4=BA=8EICU?= =?UTF-8?q?=20=E7=89=88=E6=9C=AC=E6=9B=B4=E6=96=B0=E5=AF=BC=E8=87=B4?= =?UTF-8?q?=E7=94=A8=E4=BE=8B=E5=A4=B1=E8=B4=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC3U5W Signed-off-by: hecunmao Change-Id: Id092a5c37c510e1a7e5a600ab0e52a945c1feb74 --- test262/intl_skip_tests.json | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test262/intl_skip_tests.json b/test262/intl_skip_tests.json index a417e22f1b..88fbfd1932 100644 --- a/test262/intl_skip_tests.json +++ b/test262/intl_skip_tests.json @@ -28,6 +28,8 @@ "intl402/NumberFormat/prototype/formatToParts/main.js", "intl402/NumberFormat/currency-digits.js", "intl402/NumberFormat/prototype/format/numbering-systems.js", + "intl402/NumberFormat/prototype/formatToParts/unit.js", + "intl402/Intl/getCanonicalLocales/unicode-ext-canonicalize-timezone.js", "intl402/Intl/getCanonicalLocales/unicode-ext-canonicalize-yes-to-true.js", "intl402/Intl/getCanonicalLocales/canonicalized-tags.js" ] -- Gitee From abe563fcae8fc1023d0fc78fe23fa63a3714d7c0 Mon Sep 17 00:00:00 2001 From: dongchao Date: Mon, 14 Apr 2025 17:04:29 +0800 Subject: [PATCH 115/268] Fix declgen_ets2ts bugs Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC31FC Signed-off-by: kanghonglin Signed-off-by: dongchao Change-Id: I3820e2e7bb665d37e72a875721b85fe02b36a6be --- ets2panda/declgen_ets2ts/declgenEts2Ts.cpp | 506 ++++++++++++------ ets2panda/declgen_ets2ts/declgenEts2Ts.h | 20 +- .../declgen-ets2ts-runtime-ignored.txt | 12 +- 3 files changed, 364 insertions(+), 174 deletions(-) diff --git a/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp b/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp index 2f9c32175e..723a200ade 100644 --- a/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp +++ b/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp @@ -22,6 +22,7 @@ #include "ir/base/scriptFunction.h" #include "ir/ets/etsImportDeclaration.h" #include "ir/ets/etsReExportDeclaration.h" +#include "ir/ets/etsTuple.h" #include "ir/expressions/identifier.h" #include "ir/expressions/literals/numberLiteral.h" #include "ir/module/importSpecifier.h" @@ -86,6 +87,10 @@ void TSDeclGen::ProcessTypeAliasDependencies(const ir::TSTypeAliasDeclaration *t const auto name = typeAliasDecl->Id()->Name().Mutf8(); const auto *aliasedType = typeAliasDecl->TypeAnnotation()->GetType(checker_); const auto typeFlag = checker::ETSChecker::ETSType(aliasedType); + const auto *parent = typeAliasDecl->Id()->Parent(); + if (!parent->IsExported() && !parent->IsExportedType() && !parent->IsDefaultExported()) { + return; + } if (typeFlag == checker::TypeFlag::ETS_OBJECT || typeFlag == checker::TypeFlag::ETS_DYNAMIC_TYPE) { auto objectType = aliasedType->AsETSObjectType(); if (objectType->IsETSStringType() || objectType->IsETSBigIntType() || objectType->IsETSUnboxableObject() || @@ -120,8 +125,9 @@ void TSDeclGen::ProcessTypeAnnotationDependencies(const ir::TypeNode *typeAnnota GenSeparated( typeParams->Params(), [this](ir::TypeNode *param) { - if (param->IsETSTypeReference()) { + if (param->IsETSTypeReference() && param->AsETSTypeReference()->Part()->Name()->IsIdentifier()) { const auto paramName = param->AsETSTypeReference()->Part()->Name()->AsIdentifier()->Name().Mutf8(); + importSet_.insert(paramName); indirectDependencyObjects_.insert(paramName); } }, @@ -134,6 +140,10 @@ void TSDeclGen::ProcessClassDependencies(const ir::ClassDeclaration *classDecl) if (classDef->Ident()->Name().Mutf8().find('#') != std::string::npos) { return; } + + if (!classDef->IsExported() && !classDef->IsExportedType() && !classDef->IsDefaultExported()) { + return; + } state_.super = classDef->Super(); if (state_.super != nullptr) { @@ -211,6 +221,7 @@ void TSDeclGen::AddObjectDependencies(const util::StringView &typeName, const st if (typeName.Empty()) { return; } + importSet_.insert(typeName.Mutf8()); indirectDependencyObjects_.insert(typeName.Mutf8()); if (!alias.empty()) { typeAliasMap_[alias] = typeName.Mutf8(); @@ -523,42 +534,17 @@ void TSDeclGen::ProcessFuncParameter(varbinder::LocalVariable *param) const auto *expr = paramDeclNode->AsETSParameterExpression(); OutDts(expr->IsOptional() ? "?" : ""); OutDts(": "); - ProcessParameterTypeAnnotation(expr, paramType); -} -void TSDeclGen::ProcessParameterTypeAnnotation(const ir::ETSParameterExpression *expr, const checker::Type *paramType) -{ const auto *typeAnnotation = expr->TypeAnnotation(); if (typeAnnotation == nullptr) { GenType(paramType); return; } - if (expr->IsOptional()) { GenType(typeAnnotation->TsType()); return; } - - if (typeAnnotation->IsETSTypeReference()) { - auto etsTypeRef = typeAnnotation->AsETSTypeReference(); - if (paramType->IsETSFunctionType() && etsTypeRef->Part()->Name()->IsIdentifier()) { - auto name = etsTypeRef->Part()->Name()->AsIdentifier()->Name(); - indirectDependencyObjects_.insert(name.Mutf8()); - OutDts(name); - } else if (etsTypeRef->Part()->Name()->IsTSQualifiedName() && - etsTypeRef->Part()->Name()->AsTSQualifiedName()->Left()->IsIdentifier()) { - auto qualifiedName = etsTypeRef->Part()->Name()->AsTSQualifiedName(); - auto leftName = qualifiedName->Left()->AsIdentifier()->Name(); - auto rightName = qualifiedName->Right()->AsIdentifier()->Name(); - indirectDependencyObjects_.insert(leftName.Mutf8()); - importSet_.insert(leftName.Mutf8()); - OutDts(leftName, ".", rightName); - } else { - GenType(paramType); - } - } else { - GenType(paramType); - } + ProcessTypeAnnotationType(typeAnnotation, paramType); } void TSDeclGen::ProcessFuncParameters(const checker::Signature *sig) @@ -612,41 +598,26 @@ void TSDeclGen::ProcessFunctionReturnType(const checker::Signature *sig) returnStatements.at(0)->Argument()->IsETSNewClassInstanceExpression()) { auto newExpr = returnStatements.at(0)->Argument()->AsETSNewClassInstanceExpression(); if (newExpr->GetTypeRef() != nullptr && newExpr->GetTypeRef()->IsETSTypeReference()) { - ProcessFunctionReturnTypeRef(sig, newExpr->GetTypeRef()->AsETSTypeReference()); + ProcessETSTypeReferenceType(newExpr->GetTypeRef()->AsETSTypeReference(), sig->ReturnType()); return; } } const auto returnTypeAnnotation = sig->Function()->ReturnTypeAnnotation(); if (returnTypeAnnotation != nullptr) { - if (returnTypeAnnotation->IsTSThisType()) { - OutDts("this"); - return; - } - if (returnTypeAnnotation->IsETSTypeReference()) { - ProcessFunctionReturnTypeRef(sig, returnTypeAnnotation->AsETSTypeReference()); - return; - } + ProcessTypeAnnotationType(returnTypeAnnotation, sig->ReturnType()); + return; } - GenType(sig->ReturnType()); -} -void TSDeclGen::ProcessFunctionReturnTypeRef(const checker::Signature *sig, const ir::ETSTypeReference *expr) -{ - if (sig->ReturnType()->IsETSFunctionType()) { - auto funcName = expr->Part()->Name()->AsIdentifier()->Name(); - OutDts(funcName); - indirectDependencyObjects_.insert(funcName.Mutf8()); - } else if (expr->Part()->Name()->IsTSQualifiedName()) { - auto qualiFiedName = expr->Part()->Name()->AsTSQualifiedName(); - auto leftName = qualiFiedName->Left()->AsIdentifier()->Name(); - auto rightName = qualiFiedName->Right()->AsIdentifier()->Name(); - OutDts(leftName, ".", rightName); - indirectDependencyObjects_.insert(leftName.Mutf8()); - importSet_.insert(leftName.Mutf8()); - } else { - GenType(sig->ReturnType()); + const auto param = sig->Function()->Params(); + if (!param.empty() && param.size() == 1 && param.at(0)->IsETSParameterExpression() && + param.at(0)->AsETSParameterExpression()->Ident()->TypeAnnotation() != nullptr && + sig->HasSignatureFlag(checker::SignatureFlags::SETTER)) { + ProcessTypeAnnotationType(param.at(0)->AsETSParameterExpression()->Ident()->TypeAnnotation(), + sig->Params()[0]->TsType()); + return; } + GenType(sig->ReturnType()); } void TSDeclGen::GenUnionType(const checker::ETSUnionType *unionType) @@ -750,6 +721,7 @@ void TSDeclGen::GenObjectType(const checker::ETSObjectType *objectType) } else { OutDts(typeStr); } + importSet_.insert(typeStr); indirectDependencyObjects_.insert(typeStr); } @@ -769,6 +741,10 @@ void TSDeclGen::GenTypeParameters(const ir::TSTypeParameterDeclaration *typePara OutDts("<"); GenSeparated(typeParams->Params(), [this](ir::TSTypeParameter *param) { OutDts(param->Name()->Name()); + if (param->DefaultType() != nullptr) { + OutDts(" = "); + GenType(param->DefaultType()->GetType(checker_)); + } auto *constraint = param->Constraint(); if (constraint != nullptr) { OutDts(" extends "); @@ -972,44 +948,75 @@ void TSDeclGen::GenImportDeclaration(const ir::ETSImportDeclaration *importDecla auto source = importDeclaration->Source()->Str().Mutf8(); source = RemoveModuleExtensionName(source); const auto specifierFirst = specifiers[0]; + const auto typeStr = importDeclaration->IsTypeKind() ? "type " : ""; if (specifierFirst->IsImportNamespaceSpecifier()) { - const auto local = specifierFirst->AsImportNamespaceSpecifier()->Local()->Name(); - if (importSet_.find(local.Mutf8()) == importSet_.end()) { - return; - } - OutDts("import * as ", local, " from \"", source, "\";"); - OutTs("import * as ", local, " from \"", source, "\";"); + GenNamespaceImport(specifierFirst, source); + } else if (specifierFirst->IsImportDefaultSpecifier()) { + GenDefaultImport(specifierFirst, source, typeStr); } else if (specifierFirst->IsImportSpecifier()) { - auto importSpecifiers = FilterValidImportSpecifiers(specifiers); - if (importSpecifiers.empty()) { - return; - } - OutDts("import { "); - OutTs("import { "); - GenSeparated( - importSpecifiers, - [this, &importDeclaration](ir::AstNode *specifier) { - if (!specifier->IsImportSpecifier()) { - LogError(diagnostic::IMPORT_SPECIFIERS_SUPPORT, {}, importDeclaration->Start()); - } - const auto local = specifier->AsImportSpecifier()->Local()->Name().Mutf8(); - const auto imported = specifier->AsImportSpecifier()->Imported()->Name().Mutf8(); - if (local != imported) { - OutDts(imported, " as ", local); - OutTs(imported, " as ", local); - } else { - OutDts(local); - OutTs(local); - } - }, - ",", true); - OutDts(" } from \"", source, "\";"); - OutTs(" } from \"", source, "\";"); + GenNamedImports(importDeclaration, specifiers, source, typeStr); } OutEndlDts(); OutEndlTs(); } +void TSDeclGen::GenNamespaceImport(const ir::AstNode *specifier, const std::string &source) +{ + const auto local = specifier->AsImportNamespaceSpecifier()->Local()->Name(); + if (importSet_.find(local.Mutf8()) == importSet_.end()) { + return; + } + OutDts("import * as ", local, " from \"", source, "\";"); + OutTs("import * as ", local, " from \"", source, "\";"); +} + +void TSDeclGen::GenDefaultImport(const ir::AstNode *specifier, const std::string &source, const std::string &typeStr) +{ + const auto local = specifier->AsImportDefaultSpecifier()->Local()->Name(); + if (importSet_.find(local.Mutf8()) == importSet_.end()) { + return; + } + OutDts("import ", typeStr, local, " from \"", source, "\";"); + OutTs("import ", typeStr, local, " from \"", source, "\";"); +} + +void TSDeclGen::GenNamedImports(const ir::ETSImportDeclaration *importDeclaration, + const ArenaVector &specifiers, const std::string &source, + const std::string &typeStr) +{ + auto importSpecifiers = FilterValidImportSpecifiers(specifiers); + if (importSpecifiers.empty()) { + return; + } + + OutDts("import ", typeStr, "{ "); + OutTs("import ", typeStr, "{ "); + + GenSeparated( + importSpecifiers, + [this, &importDeclaration](ir::AstNode *specifier) { GenSingleNamedImport(specifier, importDeclaration); }, + ", ", true); + + OutDts(" } from \"", source, "\";"); + OutTs(" } from \"", source, "\";"); +} + +void TSDeclGen::GenSingleNamedImport(ir::AstNode *specifier, const ir::ETSImportDeclaration *importDeclaration) +{ + if (!specifier->IsImportSpecifier()) { + LogError(diagnostic::IMPORT_SPECIFIERS_SUPPORT, {}, importDeclaration->Start()); + } + const auto local = specifier->AsImportSpecifier()->Local()->Name().Mutf8(); + const auto imported = specifier->AsImportSpecifier()->Imported()->Name().Mutf8(); + if (local != imported) { + OutDts(imported, " as ", local); + OutTs(imported, " as ", local); + } else { + OutDts(local); + OutTs(local); + } +} + std::vector TSDeclGen::FilterValidImportSpecifiers(const ArenaVector &specifiers) { std::vector importSpecifiers; @@ -1090,6 +1097,118 @@ std::string TSDeclGen::ReplaceETSGLOBAL(const std::string &typeName) return globalDesc_; } +void TSDeclGen::ProcessETSTypeReferenceType(const ir::ETSTypeReference *typeReference, const checker::Type *checkerType) +{ + auto typePart = typeReference->Part(); + auto partName = typePart->GetIdent()->Name().Mutf8(); + importSet_.insert(partName); + if (typePart->TypeParams() != nullptr && typePart->TypeParams()->IsTSTypeParameterInstantiation()) { + if (partName == "FixedArray") { + GenSeparated(typePart->TypeParams()->Params(), + [this](ir::TypeNode *param) { ProcessTypeAnnotationType(param, param->GetType(checker_)); }); + OutDts("[]"); + return; + } + OutDts(partName); + OutDts("<"); + GenSeparated(typePart->TypeParams()->Params(), + [this](ir::TypeNode *param) { ProcessTypeAnnotationType(param, param->GetType(checker_)); }); + OutDts(">"); + } else if (typePart->Name()->IsTSQualifiedName() && typePart->Name()->AsTSQualifiedName()->Name() != nullptr) { + const auto qualifiedName = typePart->Name()->AsTSQualifiedName()->Name().Mutf8(); + std::istringstream stream(qualifiedName.data()); + std::string segment; + while (std::getline(stream, segment, '.')) { + importSet_.insert(segment); + indirectDependencyObjects_.insert(segment); + } + OutDts(qualifiedName); + } else if (checkerType != nullptr && checkerType->IsETSFunctionType()) { + indirectDependencyObjects_.insert(partName); + OutDts(partName); + } else { + GenPartName(partName); + indirectDependencyObjects_.insert(partName); + OutDts(partName); + } +} + +bool TSDeclGen::ProcessTypeAnnotationSpecificTypes(const checker::Type *checkerType) +{ + if (checkerType == nullptr) { + return false; + } + + importSet_.insert(checkerType->ToString()); + if (HandleBasicTypes(checkerType)) { + return true; + } + switch (checker::ETSChecker::ETSType(checkerType)) { + case checker::TypeFlag::ETS_VOID: + case checker::TypeFlag::ETS_NULL: + case checker::TypeFlag::ETS_UNDEFINED: + case checker::TypeFlag::ETS_BOOLEAN: + case checker::TypeFlag::ETS_TYPE_PARAMETER: + case checker::TypeFlag::ETS_NONNULLISH: + case checker::TypeFlag::ETS_PARTIAL_TYPE_PARAMETER: + case checker::TypeFlag::ETS_NEVER: + case checker::TypeFlag::ETS_READONLY: + OutDts(checkerType->ToString()); + return true; + default: + return false; + } + return false; +} + +void TSDeclGen::ProcessTypeAnnotationType(const ir::TypeNode *typeAnnotation, const checker::Type *checkerType) +{ + auto *aliasedType = const_cast(typeAnnotation)->GetType(checker_); + + if (typeAnnotation->IsTSThisType()) { + OutDts("this"); + return; + } + if (typeAnnotation->IsETSStringLiteralType()) { + importSet_.insert(aliasedType->ToString()); + OutDts(aliasedType->ToString()); + return; + } + if (typeAnnotation->IsETSTypeReference()) { + if (ProcessTypeAnnotationSpecificTypes(checkerType)) { + return; + } + if (checkerType != nullptr && + typeAnnotation->AsETSTypeReference()->Part()->GetIdent()->Name().Is("NullishType")) { + OutDts(typeAnnotation->Parent()->IsTSArrayType() ? "(" : ""); + GenType(checkerType); + OutDts(typeAnnotation->Parent()->IsTSArrayType() ? ")" : ""); + return; + } + ProcessETSTypeReferenceType(typeAnnotation->AsETSTypeReference(), checkerType); + return; + } + if (typeAnnotation->IsETSTuple()) { + OutDts("["); + GenSeparated( + typeAnnotation->AsETSTuple()->GetTupleTypeAnnotationsList(), + [this](ir::TypeNode *arg) { ProcessTypeAnnotationType(arg, arg->GetType(checker_)); }, " , "); + OutDts("]"); + return; + } + if (typeAnnotation->IsTSArrayType() && typeAnnotation->AsTSArrayType()->ElementType() != nullptr) { + auto *elementType = typeAnnotation->AsTSArrayType()->ElementType(); + auto *elementCheckerType = const_cast(elementType)->GetType(checker_); + bool needParentheses = !elementType->IsETSTypeReference() && elementCheckerType->IsETSUnionType(); + OutDts(needParentheses ? "(" : ""); + ProcessTypeAnnotationType(elementType, elementCheckerType); + OutDts(needParentheses ? ")" : ""); + OutDts("[]"); + return; + } + checkerType != nullptr ? GenType(checkerType) : GenType(aliasedType); +} + void TSDeclGen::GenTypeAliasDeclaration(const ir::TSTypeAliasDeclaration *typeAlias) { const auto name = typeAlias->Id()->Name().Mutf8(); @@ -1099,38 +1218,29 @@ void TSDeclGen::GenTypeAliasDeclaration(const ir::TSTypeAliasDeclaration *typeAl if (!ShouldEmitDeclarationSymbol(typeAlias->Id())) { return; } - const auto typeAnnotation = typeAlias->TypeAnnotation(); - const auto *aliasedType = typeAnnotation->GetType(checker_); GenAnnotations(typeAlias); - if (classNode_.isIndirect) { + if (classNode_.isIndirect || state_.inNamespace || typeAlias->IsDefaultExported()) { OutDts("type ", name); } else { OutDts("export type ", name); } GenTypeParameters(typeAlias->TypeParams()); OutDts(" = "); - if (typeAnnotation->IsETSTypeReference() && typeAnnotation->AsETSTypeReference()->Part()->Name()->IsIdentifier()) { - const auto part = typeAnnotation->AsETSTypeReference()->Part(); - const auto partName = part->Name()->AsIdentifier()->Name(); - importSet_.insert(partName.Mutf8()); - OutDts(partName.Is("Exception") ? "Error" : partName); - const auto partParams = part->TypeParams(); - if (partParams != nullptr) { - GenTypeParameters(partParams->AsTSTypeParameterInstantiation()); - } - } else if (typeAnnotation->IsETSStringLiteralType()) { - importSet_.insert(aliasedType->ToString()); - OutDts(aliasedType->ToString()); - } else { - GenType(aliasedType); - } + ProcessTypeAnnotationType(typeAlias->TypeAnnotation()); OutDts(";"); OutEndlDts(); + if (typeAlias->IsDefaultExported()) { + OutDts("export default ", name, ";"); + OutEndlDts(); + } auto typeName = typeAliasMap_[name]; const auto classDesc = ReplaceETSGLOBAL(typeName); OutTs("const ", name, " = (globalThis as any).Panda.getClass('", classDesc, "');"); OutEndlTs(); + if (state_.inNamespace) { + return; + } OutTs("export { ", name, " };"); OutEndlTs(); } @@ -1177,9 +1287,11 @@ void TSDeclGen::GenInterfaceDeclaration(const ir::TSInterfaceDeclaration *interf } GenAnnotations(interfaceDecl); if (classNode_.isIndirect) { - OutDts("declare interface ", interfaceName); + OutDts(state_.isInterfaceInNamespace ? "interface " : "declare interface ", interfaceName); + } else if (!interfaceDecl->IsDefaultExported()) { + OutDts(state_.isInterfaceInNamespace ? "interface " : "export declare interface ", interfaceName); } else { - OutDts("export declare interface ", interfaceName); + OutDts(state_.isInterfaceInNamespace ? "interface " : "export default interface ", interfaceName); } GenTypeParameters(interfaceDecl->TypeParams()); @@ -1252,17 +1364,35 @@ bool TSDeclGen::ShouldSkipClassDeclaration(const std::string_view &className) co void TSDeclGen::EmitClassDeclaration(const ir::ClassDefinition *classDef, const std::string_view &className) { if (classDef->IsNamespaceTransformed()) { - OutDts(classNode_.indentLevel > 1 ? "namespace " : "export declare namespace ", className); + if (classDef->IsDefaultExported()) { + OutDts("declare namespace ", className); + } else { + OutDts(classNode_.indentLevel > 1 ? "namespace " : "export declare namespace ", className); + } OutTs("export namespace ", className, " {"); } else if (classDef->IsEnumTransformed()) { - OutDts(classNode_.indentLevel > 1 ? "enum " : "export declare enum ", className); + if (classDef->IsDefaultExported()) { + OutDts("declare enum ", className); + } else { + OutDts(classNode_.indentLevel > 1 ? "enum " : "export declare enum ", className); + } OutTs("export const enum ", className, " {"); } else if (classDef->IsFromStruct()) { - OutDts("export declare struct ", className); + if (classDef->IsDefaultExported()) { + OutDts("declare struct ", className); + } else { + OutDts(classNode_.indentLevel > 1 ? "struct " : "export declare struct ", className); + } } else if (classNode_.isIndirect) { OutDts("declare class ", className); } else if (classDef->IsAbstract()) { - OutDts("export declare abstract class ", className); + if (classDef->IsDefaultExported()) { + OutDts("export default abstract class ", className); + } else { + OutDts("export declare abstract class ", className); + } + } else if (classDef->IsDefaultExported()) { + OutDts("export default class ", className); } else { OutDts(classNode_.indentLevel > 1 ? "class " : "export declare class ", className); } @@ -1286,6 +1416,8 @@ void TSDeclGen::GenPartName(std::string &partName) partName = "ESObject"; } else if (partName == "BigInt") { partName = "bigint"; + } else if (partName == "Exception" || partName == "NullPointerError") { + partName = "Error"; } } @@ -1311,7 +1443,7 @@ void TSDeclGen::HandleClassDeclarationTypeInfo(const ir::ClassDefinition *classD const auto *super = classDef->Super(); state_.super = super; - if (super != nullptr) { + if (super != nullptr && !classDef->IsEnumTransformed()) { OutDts(" extends "); GenType(super->TsType()); } @@ -1351,6 +1483,15 @@ void TSDeclGen::ProcessClassBody(const ir::ClassDefinition *classDef) state_.inEnum = true; GenPropDeclaration(prop->AsClassProperty()); } + } else if (prop->IsTSInterfaceDeclaration()) { + state_.isInterfaceInNamespace = true; + OutDts(GetIndent()); + GenInterfaceDeclaration(prop->AsTSInterfaceDeclaration()); + state_.isInterfaceInNamespace = false; + } else if (prop->IsTSTypeAliasDeclaration()) { + OutDts(GetIndent()); + OutTs(GetIndent()); + GenTypeAliasDeclaration(prop->AsTSTypeAliasDeclaration()); } else if (prop->IsMethodDefinition()) { ProcessMethodDefinition(prop->AsMethodDefinition(), processedMethods); } else if (prop->IsClassProperty()) { @@ -1367,6 +1508,7 @@ void TSDeclGen::ProcessClassBody(const ir::ClassDefinition *classDef) OutTs(indent); classNode_.indentLevel++; GenClassDeclaration(prop->AsClassDeclaration()); + state_.isClassInNamespace = false; } else if (prop->IsClassDeclaration() && classDef->IsFromStruct()) { GenClassDeclaration(prop->AsClassDeclaration()); } @@ -1415,7 +1557,15 @@ void TSDeclGen::GenClassDeclaration(const ir::ClassDeclaration *classDecl) return; } ES2PANDA_ASSERT(classNode_.indentLevel != static_cast(-1)); - CloseClassBlock(false); + if (!state_.isClassInNamespace || state_.inEnum) { + state_.inEnum = false; + CloseClassBlock(false); + } + } + if ((classDef->IsNamespaceTransformed() || classDef->IsEnumTransformed() || classDef->IsFromStruct()) && + classDef->IsDefaultExported()) { + OutDts("export default ", className, ";"); + OutEndlDts(); } } @@ -1466,16 +1616,32 @@ void TSDeclGen::EmitMethodGlueCode(const std::string &methodName, const ir::Iden void TSDeclGen::GenMethodDeclaration(const ir::MethodDefinition *methodDef) { + if (ShouldSkipMethodDeclaration(methodDef)) { + return; + } const auto methodIdent = GetKeyIdent(methodDef->Key()); const auto methodName = methodIdent->Name().Mutf8(); - if (ShouldSkipMethodDeclaration(methodDef)) { + if (GenMethodDeclarationPrefix(methodDef, methodIdent, methodName)) { return; } + GenMethodSignature(methodDef, methodIdent, methodName); + + OutDts(";"); + OutEndlDts(); +} + +bool TSDeclGen::GenMethodDeclarationPrefix(const ir::MethodDefinition *methodDef, const ir::Identifier *methodIdent, + const std::string &methodName) +{ if (state_.inGlobalClass) { if (!ShouldEmitDeclarationSymbol(methodIdent)) { - return; + return true; + } + if (methodDef->IsDefaultExported()) { + OutDts("export default function "); + } else { + OutDts("export declare function "); } - OutDts("export declare function "); } else { if (!methodDef->Function()->Annotations().empty()) { ProcessIndent(); @@ -1494,8 +1660,21 @@ void TSDeclGen::GenMethodDeclaration(const ir::MethodDefinition *methodDef) } if (methodDef->IsSetter()) { OutDts("set "); + } + return false; +} + +void TSDeclGen::GenMethodSignature(const ir::MethodDefinition *methodDef, const ir::Identifier *methodIdent, + const std::string &methodName) +{ + if (methodDef->IsSetter()) { OutDts(methodName, "(value: "); - GenType(methodDef->TsType()->AsETSFunctionType()->CallSignatures()[0]->Params()[0]->TsType()); + const auto *sig = methodDef->TsType()->AsETSFunctionType()->CallSignatures()[0]; + if (sig->HasFunction()) { + ProcessFunctionReturnType(sig); + } else { + GenType(sig->Params()[0]->TsType()); + } OutDts(")"); } else { DebugPrint(" GenMethodDeclaration: " + methodName); @@ -1512,8 +1691,6 @@ void TSDeclGen::GenMethodDeclaration(const ir::MethodDefinition *methodDef) GenFunctionType(methodDef->TsType()->AsETSFunctionType(), methodDef); } } - OutDts(";"); - OutEndlDts(); } void TSDeclGen::EmitPropGlueCode(const ir::ClassProperty *classProp, const std::string &propName) @@ -1524,17 +1701,33 @@ void TSDeclGen::EmitPropGlueCode(const ir::ClassProperty *classProp, const std:: } else { propAccess = " = (globalThis as any).Panda.getClass('" + state_.currentClassDescriptor + "')." + propName + ";"; } - const bool isConst = classProp->IsConst(); const bool isDefaultExported = classProp->IsDefaultExported(); - - OutTs(isConst ? "export const " : "export let ", propName, propAccess); + if (isDefaultExported) { + OutTs(isConst ? "const " : "let ", propName, propAccess); + OutEndlTs(); + OutTs("export default ", propName, ";"); + } else { + OutTs(isConst ? "export const " : "export let ", propName, propAccess); + } OutEndlTs(); +} - if (!isConst && isDefaultExported) { - OutTs("export default ", propName, ";"); - OutEndlTs(); +void TSDeclGen::ProcessClassPropertyType(const ir::ClassProperty *classProp) +{ + auto value = classProp->AsClassProperty()->Value(); + if (value != nullptr && value->IsETSNewClassInstanceExpression() && + value->AsETSNewClassInstanceExpression()->GetTypeRef() != nullptr && + value->AsETSNewClassInstanceExpression()->GetTypeRef()->IsETSTypeReference()) { + auto typeReference = classProp->Value()->AsETSNewClassInstanceExpression()->GetTypeRef()->AsETSTypeReference(); + ProcessETSTypeReferenceType(typeReference); + return; + } + if (classProp->TypeAnnotation() != nullptr) { + ProcessTypeAnnotationType(classProp->TypeAnnotation(), classProp->TsType()); + return; } + GenType(classProp->TsType()); } void TSDeclGen::GenPropDeclaration(const ir::ClassProperty *classProp) @@ -1561,6 +1754,15 @@ void TSDeclGen::GenPropDeclaration(const ir::ClassProperty *classProp) DebugPrint(" GenPropDeclaration: " + propName); + ProcessClassPropDeclaration(classProp); + + if (classNode_.hasNestedClass || state_.inNamespace) { + EmitPropGlueCode(classProp, propName); + } +} + +void TSDeclGen::ProcessClassPropDeclaration(const ir::ClassProperty *classProp) +{ ProcessIndent(); if (!state_.inInterface && (!state_.inNamespace || state_.isClassInNamespace) && !classNode_.isStruct) { GenPropAccessor(classProp, "get "); @@ -1576,16 +1778,17 @@ void TSDeclGen::GenPropDeclaration(const ir::ClassProperty *classProp) if (!classNode_.isStruct) { GenModifier(classProp, true); } + const auto propName = GetKeyIdent(classProp->Key())->Name().Mutf8(); OutDts(propName); OutDts(": "); - classProp->IsStatic() ? OutDts("any") : GenType(classProp->TsType()); + if (!state_.inNamespace) { + classProp->IsStatic() ? OutDts("any") : GenType(classProp->TsType()); + } else { + ProcessClassPropertyType(classProp); + } OutDts(";"); OutEndlDts(); } - - if (classNode_.hasNestedClass || state_.inNamespace) { - EmitPropGlueCode(classProp, propName); - } } void TSDeclGen::GenPropAccessor(const ir::ClassProperty *classProp, const std::string &accessorKind) @@ -1600,31 +1803,16 @@ void TSDeclGen::GenPropAccessor(const ir::ClassProperty *classProp, const std::s GenModifier(classProp); const auto propName = GetKeyIdent(classProp->Key())->Name().Mutf8(); - if (accessorKind == "set ") { - OutDts(accessorKind + propName + "(value: "); - GenType(classProp->TsType()); - OutDts(");"); + OutDts(accessorKind, propName, accessorKind == "set " ? "(value: " : "(): "); + if (classProp->TypeAnnotation() != nullptr) { + ProcessTypeAnnotationType(classProp->TypeAnnotation(), classProp->TsType()); } else { - OutDts(accessorKind + propName + "(): "); GenType(classProp->TsType()); - OutDts(";"); } + OutDts(accessorKind == "set " ? ");" : ";"); OutEndlDts(); } -void TSDeclGen::GenGenericParameter(const ir::ClassProperty *globalVar) -{ - if (globalVar->TsType() != nullptr && globalVar->TsType()->IsETSObjectType()) { - std::string typeStr = globalVar->TsType()->AsETSObjectType()->Name().Mutf8(); - const auto &typeArgs = globalVar->TsType()->AsETSObjectType()->TypeArguments(); - if (!typeArgs.empty()) { - OutDts("<"); - GenSeparated(typeArgs, [this, typeStr](checker::Type *arg) { HandleTypeArgument(arg, typeStr); }); - OutDts(">"); - } - } -} - void TSDeclGen::GenGlobalVarDeclaration(const ir::ClassProperty *globalVar) { if (!globalVar->IsExported() && !globalVar->IsDefaultExported() && !declgenOptions_.exportAll) { @@ -1634,29 +1822,23 @@ void TSDeclGen::GenGlobalVarDeclaration(const ir::ClassProperty *globalVar) const auto symbol = GetKeyIdent(globalVar->Key()); const auto varName = symbol->Name().Mutf8(); const bool isConst = globalVar->IsConst(); + const bool isDefaultExported = globalVar->IsDefaultExported(); DebugPrint("GenGlobalVarDeclaration: " + varName); GenAnnotations(globalVar); - OutDts(isConst ? "export declare const " : "export declare let ", varName, ": "); - if (globalVar->TypeAnnotation() != nullptr && globalVar->TypeAnnotation()->IsETSStringLiteralType()) { - const auto *aliasedType = globalVar->TypeAnnotation()->GetType(checker_); - importSet_.insert(aliasedType->ToString()); - OutDts(aliasedType->ToString()); - } else if (globalVar->TypeAnnotation() != nullptr && globalVar->TypeAnnotation()->IsETSTypeReference()) { - const auto part = globalVar->TypeAnnotation()->AsETSTypeReference()->Part(); - if (part->Name()->IsIdentifier()) { - auto partName = part->Name()->AsIdentifier()->Name().Mutf8(); - importSet_.insert(partName); - GenPartName(partName); - indirectDependencyObjects_.insert(partName); - OutDts(partName); - GenGenericParameter(globalVar); - } + + if (isDefaultExported) { + OutDts(isConst ? "declare const " : "declare let ", varName, ": "); } else { - GenType(globalVar->TsType()); + OutDts(isConst ? "export declare const " : "export declare let ", varName, ": "); } + ProcessClassPropertyType(globalVar); OutDts(";"); OutEndlDts(); + if (isDefaultExported) { + OutDts("export default ", varName, ";"); + OutEndlDts(); + } EmitPropGlueCode(globalVar, varName); } diff --git a/ets2panda/declgen_ets2ts/declgenEts2Ts.h b/ets2panda/declgen_ets2ts/declgenEts2Ts.h index e4219fe2c8..bbd5a7cafc 100644 --- a/ets2panda/declgen_ets2ts/declgenEts2Ts.h +++ b/ets2panda/declgen_ets2ts/declgenEts2Ts.h @@ -97,21 +97,34 @@ private: void GenType(const checker::Type *checkerType); void GenFunctionType(const checker::ETSFunctionType *functionType, const ir::MethodDefinition *methodDef = nullptr); void ProcessFunctionReturnType(const checker::Signature *sig); - void ProcessFunctionReturnTypeRef(const checker::Signature *sig, const ir::ETSTypeReference *expr); + void ProcessETSTypeReferenceType(const ir::ETSTypeReference *typeReference, + const checker::Type *checkerType = nullptr); + bool ProcessTypeAnnotationSpecificTypes(const checker::Type *checkerType); + void ProcessTypeAnnotationType(const ir::TypeNode *typeAnnotation, const checker::Type *checkerType = nullptr); void GenObjectType(const checker::ETSObjectType *objectType); void GenUnionType(const checker::ETSUnionType *unionType); void GenTupleType(const checker::ETSTupleType *tupleType); void GenImportDeclaration(const ir::ETSImportDeclaration *importDeclaration); + void GenNamespaceImport(const ir::AstNode *specifier, const std::string &source); + void GenDefaultImport(const ir::AstNode *specifier, const std::string &source, const std::string &typeStr); + void GenNamedImports(const ir::ETSImportDeclaration *importDeclaration, + const ArenaVector &specifiers, const std::string &source, + const std::string &typeStr); + void GenSingleNamedImport(ir::AstNode *specifier, const ir::ETSImportDeclaration *importDeclaration); void GenReExportDeclaration(const ir::ETSReExportDeclaration *reExportDeclaration); void GenTypeAliasDeclaration(const ir::TSTypeAliasDeclaration *typeAlias); void GenEnumDeclaration(const ir::ClassProperty *enumMember); void GenInterfaceDeclaration(const ir::TSInterfaceDeclaration *interfaceDecl); void GenClassDeclaration(const ir::ClassDeclaration *classDecl); void GenMethodDeclaration(const ir::MethodDefinition *methodDef); + bool GenMethodDeclarationPrefix(const ir::MethodDefinition *methodDef, const ir::Identifier *methodIdent, + const std::string &methodName); + void GenMethodSignature(const ir::MethodDefinition *methodDef, const ir::Identifier *methodIdent, + const std::string &methodName); void GenPropDeclaration(const ir::ClassProperty *classProp); + void ProcessClassPropDeclaration(const ir::ClassProperty *classProp); void GenPropAccessor(const ir::ClassProperty *classProp, const std::string &accessorKind); - void GenGenericParameter(const ir::ClassProperty *globalVar); void GenGlobalVarDeclaration(const ir::ClassProperty *globalVar); void GenLiteral(const ir::Literal *literal); @@ -141,7 +154,7 @@ private: void ProcessParamDefaultToMap(const ir::Statement *stmt); void ProcessFuncParameter(varbinder::LocalVariable *param); void ProcessFuncParameters(const checker::Signature *sig); - void ProcessParameterTypeAnnotation(const ir::ETSParameterExpression *expr, const checker::Type *paramType); + void ProcessClassPropertyType(const ir::ClassProperty *classProp); std::vector FilterValidImportSpecifiers(const ArenaVector &specifiers); std::string ReplaceETSGLOBAL(const std::string &typeName); std::string GetIndent() const; @@ -226,6 +239,7 @@ private: bool inNamespace {false}; bool inEnum {false}; bool isClassInNamespace {false}; + bool isInterfaceInNamespace {false}; std::string currentClassDescriptor {}; std::stack inUnionBodyStack {}; std::string currentTypeAliasName; diff --git a/ets2panda/test/test-lists/declgenets2ts/ets-runtime/declgen-ets2ts-runtime-ignored.txt b/ets2panda/test/test-lists/declgenets2ts/ets-runtime/declgen-ets2ts-runtime-ignored.txt index c78b49ead4..ae21317722 100644 --- a/ets2panda/test/test-lists/declgenets2ts/ets-runtime/declgen-ets2ts-runtime-ignored.txt +++ b/ets2panda/test/test-lists/declgenets2ts/ets-runtime/declgen-ets2ts-runtime-ignored.txt @@ -7,22 +7,20 @@ funcRefWithRestArguments.ets struct-identifier.ets struct-init2.ets type_param_in_union.ets -#FailKind.TSC_FAIL - 71 tests: -AliasClass.ets -ArrowFunctionWithNestedNameSpace.ets +#FailKind.TSC_FAIL - 65 tests: +AliasUnion.ets ClassNewInstance.ets Enum7.ets GenericBridges_01.ets GenericBridges_02.ets RecordKeyTypeCheck.ets +RecursiveTypeAlias10.ets RecursiveTypeAlias8.ets -annotation_tests/AnnotationForArrayType.ets annotation_tests/AnnotationForClass.ets annotation_tests/AnnotationForClassProperty.ets annotation_tests/AnnotationForInterface.ets annotation_tests/AnnotationForMethod.ets annotation_tests/AnnotationForTypeAliaDecl.ets -annotation_tests/AnnotationForTypesInArray.ets annotation_tests/AnnotationForTypesInClass.ets annotation_tests/AnnotationForTypesInInterface.ets annotation_tests/AnnotationForVariableDecl.ets @@ -47,7 +45,6 @@ annotation_tests/annotationUsage_scope_check02.ets annotation_tests/annotationUsage_scope_check03.ets classGetterSetter.ets class_implements_interface.ets -function_type_with_receiver/extensionFunctionTypeGeneric.ets function_type_with_receiver/validReturnThisOfExtensionFunction.ets generic_constraint_implicit.ets generics_1.ets @@ -64,7 +61,6 @@ inherited_getter_setter_implementation_2.ets interfacePropertyTypeAnnotationWithParameter.ets interface_prop.ets interface_with_optional_property_cycle_import/class_file.ets -lambda_with_receiver/lambda_with_receiver_generics1.ets lambda_with_receiver/lambda_with_receiver_generics_return_this_rotate.ets lambda_with_receiver/lambda_with_receiver_return_this3.ets lambda_with_receiver/lambda_with_receiver_trailing_in_function_return_this_rotate.ets @@ -72,9 +68,7 @@ multiple_inheritance.ets multiple_inheritance_2.ets namespace_tests/namespace_execution_statements_test02.ets namespace_tests/namespace_with_annotations.ets -override_for_partial_01.ets override_for_partial_02.ets -qualified-type-name.ets readonly_simple_form_pos.ets simple_form_pos.ets static-invoke.ets -- Gitee From 18302eb849164f1d320f3baef1e05d57edfc21fd Mon Sep 17 00:00:00 2001 From: "584648456@qq.com" Date: Sat, 5 Apr 2025 21:23:32 +0800 Subject: [PATCH 116/268] Title:bug fix optional parameter Description(optional): Added validation that there cannot be optional parameters before the required parameters of the function Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC3XQE Signed-off-by: semon <584648456@qq.com> --- ets2panda/parser/parserImpl.cpp | 13 +++++++++ .../test/ast/compiler/ets/param_sort_1.ets | 17 +++++++++++ .../test/ast/compiler/ets/param_sort_2.ets | 17 +++++++++++ .../test/ast/compiler/ets/param_sort_3.ets | 17 +++++++++++ .../ets/FixedArray/MultipleParserErrors.ets | 2 +- .../default_parameters_multi_error.ets | 2 +- .../ast/parser/ets/MultipleParserErrors.ets | 2 +- ets2panda/test/runtime/ets/param_sort.ets | 28 +++++++++++++++++++ 8 files changed, 95 insertions(+), 3 deletions(-) create mode 100644 ets2panda/test/ast/compiler/ets/param_sort_1.ets create mode 100644 ets2panda/test/ast/compiler/ets/param_sort_2.ets create mode 100644 ets2panda/test/ast/compiler/ets/param_sort_3.ets create mode 100644 ets2panda/test/runtime/ets/param_sort.ets diff --git a/ets2panda/parser/parserImpl.cpp b/ets2panda/parser/parserImpl.cpp index 60c777ff06..f854396682 100644 --- a/ets2panda/parser/parserImpl.cpp +++ b/ets2panda/parser/parserImpl.cpp @@ -880,6 +880,19 @@ ArenaVector ParserImpl::ParseFunctionParams() if (parameter == nullptr) { return false; } + bool seenOptional = false; + for (auto const param : params) { + if (param->IsETSParameterExpression() && param->AsETSParameterExpression()->IsOptional()) { + seenOptional = true; + break; + } + } + + if (seenOptional && !(parameter->IsETSParameterExpression() && + (parameter->AsETSParameterExpression()->IsOptional() || + parameter->AsETSParameterExpression()->RestParameter() != nullptr))) { + LogError(diagnostic::REQUIRED_PARAM_AFTER_OPTIONAL, {}, parameter->Start()); + } if (parameter->IsETSParameterExpression() && parameter->AsETSParameterExpression()->Ident()->IsReceiver() && !params.empty()) { diff --git a/ets2panda/test/ast/compiler/ets/param_sort_1.ets b/ets2panda/test/ast/compiler/ets/param_sort_1.ets new file mode 100644 index 0000000000..bba3a5f570 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/param_sort_1.ets @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function foo(p1: int, p2?: int, /* @@ label */p3: int) { } + +/* @@@ label Error SyntaxError: A required parameter cannot follow an optional parameter. */ \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/param_sort_2.ets b/ets2panda/test/ast/compiler/ets/param_sort_2.ets new file mode 100644 index 0000000000..17b9a79e2e --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/param_sort_2.ets @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function foo(p1: boolean, p2?: int, /* @@ label */p3: string) { } + +/* @@@ label Error SyntaxError: A required parameter cannot follow an optional parameter. */ \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/param_sort_3.ets b/ets2panda/test/ast/compiler/ets/param_sort_3.ets new file mode 100644 index 0000000000..8a38d4cdac --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/param_sort_3.ets @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function foo(p1: int, p2: int = 44, /* @@ label */p3: int) { } + +/* @@@ label Error SyntaxError: A required parameter cannot follow an optional parameter. */ \ No newline at end of file diff --git a/ets2panda/test/ast/parser/ets/FixedArray/MultipleParserErrors.ets b/ets2panda/test/ast/parser/ets/FixedArray/MultipleParserErrors.ets index f5772aef2e..c4f781e768 100644 --- a/ets2panda/test/ast/parser/ets/FixedArray/MultipleParserErrors.ets +++ b/ets2panda/test/ast/parser/ets/FixedArray/MultipleParserErrors.ets @@ -18,7 +18,7 @@ function foo(param? : Object) for (let i? of "blablabla") { } } -function foo(a : int = 10, b : int, c : int = 15) : int +function foo(b : int, a : int = 10, c : int = 15) : int { return a + b; } diff --git a/ets2panda/test/ast/parser/ets/FixedArray/default_parameters_multi_error.ets b/ets2panda/test/ast/parser/ets/FixedArray/default_parameters_multi_error.ets index 90383e9969..f69963fdb3 100644 --- a/ets2panda/test/ast/parser/ets/FixedArray/default_parameters_multi_error.ets +++ b/ets2panda/test/ast/parser/ets/FixedArray/default_parameters_multi_error.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -function foo(a : int = 10, b : int, c : int = 15) : int +function foo(b : int, a : int = 10, c : int = 15) : int { return a + b; } diff --git a/ets2panda/test/ast/parser/ets/MultipleParserErrors.ets b/ets2panda/test/ast/parser/ets/MultipleParserErrors.ets index 2da22547a5..dd1d47c018 100644 --- a/ets2panda/test/ast/parser/ets/MultipleParserErrors.ets +++ b/ets2panda/test/ast/parser/ets/MultipleParserErrors.ets @@ -18,7 +18,7 @@ function foo(param? : Object) for (let i? of "blablabla") { } } -function foo(a : int = 10, b : int, c : int = 15) : int +function foo(b : int, a : int = 10, c : int = 15) : int { return a + b; } diff --git a/ets2panda/test/runtime/ets/param_sort.ets b/ets2panda/test/runtime/ets/param_sort.ets new file mode 100644 index 0000000000..4570ab4a74 --- /dev/null +++ b/ets2panda/test/runtime/ets/param_sort.ets @@ -0,0 +1,28 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http: //www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +function foo1(p1: int, p2?: int, p3: int = 22) { } + +function foo2(p1: int, p2: int =44 , p3: int = 55) { } + +function foo3(p1: int, p2: int = 44, p3?: int) { } + + +function main(){ + foo1(1, 1, 1); + foo2(1, 1, 1); + foo3(1, 1, 1); + +} \ No newline at end of file -- Gitee From fafa167e1e7c820d2c15e5551915479d9ba2d33c Mon Sep 17 00:00:00 2001 From: zenghang Date: Fri, 25 Apr 2025 15:11:09 +0800 Subject: [PATCH 117/268] add declgenV1OutPath to DependentModuleConfig Issue: IC3Y3P Signed-off-by: zenghang Change-Id: I52989520d2f66469d8b5da5edffdaf34c0d78043 --- ets2panda/driver/build_system/src/build/base_mode.ts | 4 ++-- ets2panda/driver/build_system/src/types.ts | 8 +++++--- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/ets2panda/driver/build_system/src/build/base_mode.ts b/ets2panda/driver/build_system/src/build/base_mode.ts index c5a21def02..20ab3bd4bf 100644 --- a/ets2panda/driver/build_system/src/build/base_mode.ts +++ b/ets2panda/driver/build_system/src/build/base_mode.ts @@ -366,8 +366,8 @@ export abstract class BaseMode { compileFileInfos: [], dynamicDepModuleInfos: new Map(), staticDepModuleInfos: new Map(), - declgenV1OutPath: undefined, - declgenBridgeCodePath: undefined, + declgenV1OutPath: module.declgenV1OutPath, + declgenBridgeCodePath: module.declgenBridgeCodePath, language: module.language, declFilesPath: module.declFilesPath, dependencies: module.dependencies diff --git a/ets2panda/driver/build_system/src/types.ts b/ets2panda/driver/build_system/src/types.ts index 521244be66..df1e17e366 100644 --- a/ets2panda/driver/build_system/src/types.ts +++ b/ets2panda/driver/build_system/src/types.ts @@ -100,9 +100,11 @@ export interface DependentModuleConfig { modulePath: string; sourceRoots: string[]; entryFile: string; - language: string, - declFilesPath?: string, - dependencies?: string[] + language: string; + declFilesPath?: string; + dependencies?: string[]; + declgenV1OutPath?: string; + declgenBridgeCodePath?: string; } export interface BuildConfig extends BuildBaseConfig, DeclgenConfig, LoggerConfig, ModuleConfig, PathConfig { -- Gitee From 320fb76378dae80b932f1511623b8e81586d3f57 Mon Sep 17 00:00:00 2001 From: lijincheng Date: Fri, 25 Apr 2025 16:49:34 +0800 Subject: [PATCH 118/268] Cherry pick to 0411 1.cherry pick to 0411 Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC3ZLS Signed-off-by: lijincheng --- ets2panda/checker/ets/assignAnalyzer.cpp | 34 +++++++++++++++++-- .../ets/ambient_interface/use_interface.ets | 2 +- .../ast/parser/ets/FixedArray/array_type.ets | 4 +-- ets2panda/test/ast/parser/ets/array_type.ets | 4 +-- ets2panda/util/diagnostic/semantic.yaml | 4 +++ 5 files changed, 40 insertions(+), 8 deletions(-) diff --git a/ets2panda/checker/ets/assignAnalyzer.cpp b/ets2panda/checker/ets/assignAnalyzer.cpp index 21d8514aec..d47d219f10 100644 --- a/ets2panda/checker/ets/assignAnalyzer.cpp +++ b/ets2panda/checker/ets/assignAnalyzer.cpp @@ -1294,6 +1294,26 @@ varbinder::Variable *AssignAnalyzer::GetBoundVariable(const ir::AstNode *node) return ret; } +static const ir::AstNode *CheckInterfaceProp(const ark::es2panda::ir::AstNode *const node, + const ir::ClassDefinition *classDef) +{ + util::StringView methodName = node->AsMethodDefinition()->Key()->AsIdentifier()->Name(); + // the property from interface should start with to distinguish from its getter/setter. + std::string interfaceProp = std::string("") + std::string(methodName.Utf8()); + for (const auto it : classDef->Body()) { + // Check if there is corresponding class property in the same class. + if (it->IsClassProperty() && !it->IsStatic()) { + const auto *prop = it->AsClassProperty(); + auto *propIdentifier = prop->Key()->AsIdentifier(); + if (propIdentifier->Name().Is(interfaceProp)) { + // Use property node as declNode to ensure obtaining NodeId and add it to inits. + return prop; + } + } + } + return nullptr; +} + const ir::AstNode *AssignAnalyzer::GetDeclaringNode(const ir::AstNode *node) { if (node->IsClassProperty() || node->IsVariableDeclarator()) { @@ -1322,6 +1342,15 @@ const ir::AstNode *AssignAnalyzer::GetDeclaringNode(const ir::AstNode *node) } } + if (ret != nullptr) { + // if declNode is a getter/setter method, actual node initialized should be a class proterty node. + if ((ret->Modifiers() & ir::ModifierFlags::GETTER_SETTER) != 0U) { + if (const auto *interfaceProp = CheckInterfaceProp(ret, classDef_); interfaceProp != nullptr) { + ret = interfaceProp; + } + } + } + return ret; } @@ -1431,12 +1460,11 @@ void AssignAnalyzer::CheckInit(const ir::AstNode *node) std::stringstream ss; if (node->IsClassProperty()) { - ss << "Property '" << name << "' might not have been initialized."; + checker_->LogError(diagnostic::PROPERTY_MAYBE_MISSING_INIT, {name}, pos); } else { ss << Capitalize(type) << " '" << name << "' is used before being assigned."; + Warning(ss.str(), pos); } - - Warning(ss.str(), pos); } } } diff --git a/ets2panda/test/ast/compiler/ets/ambient_interface/use_interface.ets b/ets2panda/test/ast/compiler/ets/ambient_interface/use_interface.ets index b31e32cf0a..04da0b06fb 100644 --- a/ets2panda/test/ast/compiler/ets/ambient_interface/use_interface.ets +++ b/ets2panda/test/ast/compiler/ets/ambient_interface/use_interface.ets @@ -23,4 +23,4 @@ class B { } } -/* @@@ label Warning Warning: Property 'a' might not have been initialized. */ +/* @@@ label Error TypeError: Property 'a' might not have been initialized. */ diff --git a/ets2panda/test/ast/parser/ets/FixedArray/array_type.ets b/ets2panda/test/ast/parser/ets/FixedArray/array_type.ets index 61f88fea8f..39c8b1c969 100644 --- a/ets2panda/test/ast/parser/ets/FixedArray/array_type.ets +++ b/ets2panda/test/ast/parser/ets/FixedArray/array_type.ets @@ -24,8 +24,8 @@ class array_type { } } +/* @@@ label Error TypeError: Property 'a' might not have been initialized. */ +/* @@@ label1 Error TypeError: Property 'f' might not have been initialized. */ /* @@@ label2 Error TypeError: Function with a non void return type must return a value. */ /* @@@ label3 Error TypeError: Function with a non void return type must return a value. */ -/* @@@ label Warning Warning: Property 'a' might not have been initialized. */ -/* @@@ label1 Warning Warning: Property 'f' might not have been initialized. */ diff --git a/ets2panda/test/ast/parser/ets/array_type.ets b/ets2panda/test/ast/parser/ets/array_type.ets index 32dcb5a981..98f7711690 100644 --- a/ets2panda/test/ast/parser/ets/array_type.ets +++ b/ets2panda/test/ast/parser/ets/array_type.ets @@ -24,8 +24,8 @@ class array_type { } } +/* @@@ label Error TypeError: Property 'a' might not have been initialized. */ +/* @@@ label1 Error TypeError: Property 'f' might not have been initialized. */ /* @@@ label2 Error TypeError: Function with a non void return type must return a value. */ /* @@@ label3 Error TypeError: Function with a non void return type must return a value. */ -/* @@@ label Warning Warning: Property 'a' might not have been initialized. */ -/* @@@ label1 Warning Warning: Property 'f' might not have been initialized. */ diff --git a/ets2panda/util/diagnostic/semantic.yaml b/ets2panda/util/diagnostic/semantic.yaml index c26a225e8c..5b948bf06f 100644 --- a/ets2panda/util/diagnostic/semantic.yaml +++ b/ets2panda/util/diagnostic/semantic.yaml @@ -1130,3 +1130,7 @@ semantic: - name: INTERFACE_PROPERTY_REQUIRES_SETTER id: 284 message: "Cannot implement interface {}: property '{}' must have a setter, but the implementation is readonly" + +- name: PROPERTY_MAYBE_MISSING_INIT + id: 285 + message: "Property '{}' might not have been initialized." \ No newline at end of file -- Gitee From 2cfa862e13ccfbb167ec47649ac893c4f58f8e20 Mon Sep 17 00:00:00 2001 From: c00513733 Date: Thu, 17 Apr 2025 14:39:52 +0800 Subject: [PATCH 119/268] Support collect hms sdk Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC47M1 Signed-off-by: c00513733 Change-Id: I6a6e1908896f58b18302691c89d68bcd3d6c97c2 --- .../src/build/generate_arktsconfig.ts | 24 ++++++++++++------- ets2panda/driver/build_system/src/types.ts | 1 + 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/ets2panda/driver/build_system/src/build/generate_arktsconfig.ts b/ets2panda/driver/build_system/src/build/generate_arktsconfig.ts index e05fec759a..fbd7d8791c 100644 --- a/ets2panda/driver/build_system/src/build/generate_arktsconfig.ts +++ b/ets2panda/driver/build_system/src/build/generate_arktsconfig.ts @@ -34,8 +34,7 @@ import { } from '../types'; import { LANGUAGE_VERSION, - PANDA_SDK_PATH_FROM_SDK, - SYSTEM_SDK_PATH_FROM_SDK + SYSTEM_SDK_PATH_FROM_SDK, } from '../pre_define'; interface DynamicPathItem { @@ -60,6 +59,7 @@ export class ArkTSConfigGenerator { private stdlibStdPath: string; private stdlibEscompatPath: string; private systemSdkPath: string; + private externalApiPaths: string[]; private moduleInfos: Map; private pathSection: Record; @@ -72,6 +72,7 @@ export class ArkTSConfigGenerator { this.stdlibStdPath = path.resolve(pandaStdlibPath, 'std'); this.stdlibEscompatPath = path.resolve(pandaStdlibPath, 'escompat'); this.systemSdkPath = path.resolve(buildConfig.buildSdkPath, SYSTEM_SDK_PATH_FROM_SDK); + this.externalApiPaths = buildConfig.externalApiPaths; this.moduleInfos = moduleInfos; this.pathSection = {}; @@ -118,14 +119,21 @@ export class ArkTSConfigGenerator { } } - let apiPath: string = path.resolve(this.systemSdkPath, 'api'); - fs.existsSync(apiPath) ? traverse(apiPath) : this.logger.printWarn(`sdk path ${apiPath} not exist.`); + if (this.externalApiPaths && this.externalApiPaths.length !== 0) { + this.externalApiPaths.forEach((sdkPath: string) => { + fs.existsSync(sdkPath) ? traverse(sdkPath) : this.logger.printWarn(`sdk path ${sdkPath} not exist.`); + }); + } else { + // Search openharmony sdk only, we keep them for ci compatibility. + let apiPath: string = path.resolve(this.systemSdkPath, 'api'); + fs.existsSync(apiPath) ? traverse(apiPath) : this.logger.printWarn(`sdk path ${apiPath} not exist.`); - let arktsPath: string = path.resolve(this.systemSdkPath, 'arkts'); - fs.existsSync(arktsPath) ? traverse(arktsPath) : this.logger.printWarn(`sdk path ${arktsPath} not exist.`); + let arktsPath: string = path.resolve(this.systemSdkPath, 'arkts'); + fs.existsSync(arktsPath) ? traverse(arktsPath) : this.logger.printWarn(`sdk path ${arktsPath} not exist.`); - let kitsPath: string = path.resolve(this.systemSdkPath, 'kits'); - fs.existsSync(kitsPath) ? traverse(kitsPath) : this.logger.printWarn(`sdk path ${kitsPath} not exist.`); + let kitsPath: string = path.resolve(this.systemSdkPath, 'kits'); + fs.existsSync(kitsPath) ? traverse(kitsPath) : this.logger.printWarn(`sdk path ${kitsPath} not exist.`); + } } private getPathSection(): Record { diff --git a/ets2panda/driver/build_system/src/types.ts b/ets2panda/driver/build_system/src/types.ts index 521244be66..974b10a31b 100644 --- a/ets2panda/driver/build_system/src/types.ts +++ b/ets2panda/driver/build_system/src/types.ts @@ -80,6 +80,7 @@ export interface PathConfig { buildSdkPath: string; pandaSdkPath?: string; // path to panda sdk lib/bin, for local test pandaStdlibPath?: string; // path to panda sdk stdlib, for local test + externalApiPaths: string[]; abcLinkerPath?: string; } -- Gitee From c2aa8e19c22d9f84c51a9d8ebc3f0f297c5df6c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=A9=AC=E5=BF=97=E4=BC=9F?= Date: Sun, 27 Apr 2025 11:05:03 +0800 Subject: [PATCH 120/268] Drop kfl MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC4971?from=project-issue Signed-off-by: 马志伟 --- test/workload/ignored-third_lib_js-release-x64-jit.txt | 2 -- 1 file changed, 2 deletions(-) diff --git a/test/workload/ignored-third_lib_js-release-x64-jit.txt b/test/workload/ignored-third_lib_js-release-x64-jit.txt index 743b88c5fd..573a56debb 100644 --- a/test/workload/ignored-third_lib_js-release-x64-jit.txt +++ b/test/workload/ignored-third_lib_js-release-x64-jit.txt @@ -1,3 +1 @@ # Known failures list for third_lib_js - release-x64-jit -#18340 -Drools_test -- Gitee From 04c0dc154813f49a86fc90e6c050241c2664556a Mon Sep 17 00:00:00 2001 From: dongchao Date: Wed, 23 Apr 2025 10:45:49 +0800 Subject: [PATCH 121/268] Fix declgen_ets2ts bugs Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC4CJF Signed-off-by: kanghonglin Signed-off-by: dongchao Change-Id: Ie05ef8e4ca1ebccd4234672f769be76df8babc18 --- ets2panda/declgen_ets2ts/declgenEts2Ts.cpp | 166 +++++++++++------- ets2panda/declgen_ets2ts/declgenEts2Ts.h | 16 +- .../declgen-ets2ts-runtime-ignored.txt | 35 +--- 3 files changed, 119 insertions(+), 98 deletions(-) diff --git a/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp b/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp index 32b38f003f..8cdf9344ac 100644 --- a/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp +++ b/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp @@ -23,6 +23,7 @@ #include "ir/ets/etsImportDeclaration.h" #include "ir/ets/etsReExportDeclaration.h" #include "ir/ets/etsTuple.h" +#include "ir/ets/etsUnionType.h" #include "ir/expressions/identifier.h" #include "ir/expressions/literals/numberLiteral.h" #include "ir/module/importSpecifier.h" @@ -622,31 +623,45 @@ void TSDeclGen::ProcessFunctionReturnType(const checker::Signature *sig) void TSDeclGen::GenUnionType(const checker::ETSUnionType *unionType) { state_.inUnionBodyStack.push(true); - const auto &originTypes = unionType->ConstituentTypes(); + std::vector filteredTypes = FilterUnionTypes(unionType->ConstituentTypes()); + GenSeparated( + filteredTypes, [this](checker::Type *arg) { GenType(arg); }, " | "); + state_.inUnionBodyStack.pop(); +} + +template +std::vector TSDeclGen::FilterUnionTypes(const ArenaVector &originTypes) +{ + if (originTypes.empty()) { + return {}; + } bool hasNumber = false; bool hasString = false; - std::vector filteredTypes; + std::vector filteredTypes; for (auto originType : originTypes) { std::string typeStr = originType->ToString(); + if constexpr (std::is_same_v) { + if (originType->IsTSThisType()) { + filteredTypes.push_back(originType); + continue; + } + typeStr = originType->GetType(checker_)->ToString(); + typeStr[0] = std::toupper(typeStr[0]); + } if (stringTypes_.count(typeStr) != 0U) { if (hasString) { continue; } - filteredTypes.push_back(originType); hasString = true; } else if (numberTypes_.count(typeStr) != 0U) { if (hasNumber) { continue; } - filteredTypes.push_back(originType); hasNumber = true; - } else { - filteredTypes.push_back(originType); } + filteredTypes.push_back(originType); } - GenSeparated( - filteredTypes, [this](checker::Type *arg) { GenType(arg); }, " | "); - state_.inUnionBodyStack.pop(); + return filteredTypes; } void TSDeclGen::GenTupleType(const checker::ETSTupleType *tupleType) @@ -740,46 +755,22 @@ void TSDeclGen::GenTypeParameters(const ir::TSTypeParameterDeclaration *typePara OutDts("<"); GenSeparated(typeParams->Params(), [this](ir::TSTypeParameter *param) { OutDts(param->Name()->Name()); - if (param->DefaultType() != nullptr) { - OutDts(" = "); - GenType(param->DefaultType()->GetType(checker_)); - } auto *constraint = param->Constraint(); if (constraint != nullptr) { OutDts(" extends "); GenType(constraint->GetType(checker_)); } + auto *defaultType = param->DefaultType(); + if (defaultType != nullptr) { + OutDts(" = "); + defaultType->IsETSTypeReference() ? ProcessETSTypeReferenceType(defaultType->AsETSTypeReference()) + : GenType(defaultType->TsType()); + } }); OutDts(">"); } } -void TSDeclGen::GenTypeParameters(const ir::TSTypeParameterInstantiation *typeParams) -{ - if (typeParams == nullptr) { - return; - } - OutDts("<"); - GenSeparated(typeParams->Params(), [this](ir::TypeNode *param) { - if (param->IsETSTypeReference()) { - const auto paramName = param->AsETSTypeReference()->Part()->Name()->AsIdentifier()->Name().Mutf8(); - if (stringTypes_.count(paramName) != 0U) { - OutDts("string"); - } else if (numberTypes_.count(paramName) != 0U) { - OutDts("number"); - } else if (paramName == "NullPointerError") { - OutDts("Error"); - } else { - importSet_.insert(paramName); - OutDts(paramName); - } - } else { - GenType(param->GetType(checker_)); - } - }); - OutDts(">"); -} - void TSDeclGen::GenExport(const ir::Identifier *symbol) { const auto symbolName = symbol->Name().Mutf8(); @@ -876,6 +867,9 @@ void TSDeclGen::GenAnnotations(const T *node) GenSeparated( node->Annotations(), [this](ir::AnnotationUsage *anno) { + if (annotationList_.count(anno->GetBaseName()->Name().Mutf8()) == 0U) { + return; + } OutDts("@", anno->GetBaseName()->Name()); GenAnnotationProperties(anno); OutEndlDts(); @@ -1162,46 +1156,78 @@ void TSDeclGen::ProcessTypeAnnotationType(const ir::TypeNode *typeAnnotation, co OutDts("this"); return; } + if (typeAnnotation->IsETSPrimitiveType() && + typeAnnotation->AsETSPrimitiveType()->GetPrimitiveType() == ir::PrimitiveType::VOID) { + OutDts("void"); + return; + } if (typeAnnotation->IsETSStringLiteralType()) { importSet_.insert(aliasedType->ToString()); OutDts(aliasedType->ToString()); return; } if (typeAnnotation->IsETSTypeReference()) { - if (ProcessTypeAnnotationSpecificTypes(checkerType)) { - return; - } - if (checkerType != nullptr && - typeAnnotation->AsETSTypeReference()->Part()->GetIdent()->Name().Is("NullishType")) { - OutDts(typeAnnotation->Parent()->IsTSArrayType() ? "(" : ""); - GenType(checkerType); - OutDts(typeAnnotation->Parent()->IsTSArrayType() ? ")" : ""); - return; - } - ProcessETSTypeReferenceType(typeAnnotation->AsETSTypeReference(), checkerType); + ProcessETSTypeReference(typeAnnotation, checkerType); return; } if (typeAnnotation->IsETSTuple()) { - OutDts("["); - GenSeparated( - typeAnnotation->AsETSTuple()->GetTupleTypeAnnotationsList(), - [this](ir::TypeNode *arg) { ProcessTypeAnnotationType(arg, arg->GetType(checker_)); }, " , "); - OutDts("]"); + ProcessETSTuple(typeAnnotation->AsETSTuple()); + return; + } + if (typeAnnotation->IsETSUnionType()) { + ProcessETSUnionType(typeAnnotation->AsETSUnionType()); return; } if (typeAnnotation->IsTSArrayType() && typeAnnotation->AsTSArrayType()->ElementType() != nullptr) { - auto *elementType = typeAnnotation->AsTSArrayType()->ElementType(); - auto *elementCheckerType = const_cast(elementType)->GetType(checker_); - bool needParentheses = !elementType->IsETSTypeReference() && elementCheckerType->IsETSUnionType(); - OutDts(needParentheses ? "(" : ""); - ProcessTypeAnnotationType(elementType, elementCheckerType); - OutDts(needParentheses ? ")" : ""); - OutDts("[]"); + ProcessTSArrayType(typeAnnotation->AsTSArrayType()); return; } checkerType != nullptr ? GenType(checkerType) : GenType(aliasedType); } +void TSDeclGen::ProcessETSTypeReference(const ir::TypeNode *typeAnnotation, const checker::Type *checkerType) +{ + if (ProcessTypeAnnotationSpecificTypes(checkerType)) { + return; + } + if (checkerType != nullptr && typeAnnotation->AsETSTypeReference()->Part()->GetIdent()->Name().Is("NullishType")) { + OutDts(typeAnnotation->Parent()->IsTSArrayType() ? "(" : ""); + GenType(checkerType); + OutDts(typeAnnotation->Parent()->IsTSArrayType() ? ")" : ""); + return; + } + ProcessETSTypeReferenceType(typeAnnotation->AsETSTypeReference(), checkerType); +} + +void TSDeclGen::ProcessETSTuple(const ir::ETSTuple *etsTuple) +{ + OutDts("["); + GenSeparated( + etsTuple->GetTupleTypeAnnotationsList(), + [this](ir::TypeNode *arg) { ProcessTypeAnnotationType(arg, arg->GetType(checker_)); }, " , "); + OutDts("]"); +} + +void TSDeclGen::ProcessETSUnionType(const ir::ETSUnionType *etsUnionType) +{ + state_.inUnionBodyStack.push(true); + std::vector filteredTypes = FilterUnionTypes(etsUnionType->Types()); + GenSeparated( + filteredTypes, [this](ir::TypeNode *arg) { ProcessTypeAnnotationType(arg, arg->GetType(checker_)); }, " | "); + state_.inUnionBodyStack.pop(); +} + +void TSDeclGen::ProcessTSArrayType(const ir::TSArrayType *tsArrayType) +{ + auto *elementType = tsArrayType->ElementType(); + auto *elementCheckerType = const_cast(elementType)->GetType(checker_); + bool needParentheses = !elementType->IsETSTypeReference() && elementCheckerType->IsETSUnionType(); + OutDts(needParentheses ? "(" : ""); + ProcessTypeAnnotationType(elementType, elementCheckerType); + OutDts(needParentheses ? ")" : ""); + OutDts("[]"); +} + void TSDeclGen::GenTypeAliasDeclaration(const ir::TSTypeAliasDeclaration *typeAlias) { const auto name = typeAlias->Id()->Name().Mutf8(); @@ -1219,7 +1245,7 @@ void TSDeclGen::GenTypeAliasDeclaration(const ir::TSTypeAliasDeclaration *typeAl } GenTypeParameters(typeAlias->TypeParams()); OutDts(" = "); - ProcessTypeAnnotationType(typeAlias->TypeAnnotation()); + ProcessTypeAnnotationType(typeAlias->TypeAnnotation(), typeAlias->TypeAnnotation()->GetType(checker_)); OutDts(";"); OutEndlDts(); if (typeAlias->IsDefaultExported()) { @@ -1438,7 +1464,7 @@ void TSDeclGen::HandleClassDeclarationTypeInfo(const ir::ClassDefinition *classD state_.super = super; if (super != nullptr && !classDef->IsEnumTransformed()) { OutDts(" extends "); - GenType(super->TsType()); + HandleClassInherit(super); } const auto &interfaces = classDef->TsType()->AsETSObjectType()->Interfaces(); @@ -1446,12 +1472,24 @@ void TSDeclGen::HandleClassDeclarationTypeInfo(const ir::ClassDefinition *classD OutDts(" implements "); ES2PANDA_ASSERT(classDef->TsType()->IsETSObjectType()); GenSeparated(interfaces, [this](checker::ETSObjectType *interface) { GenType(interface); }); + } else if (!classDef->Implements().empty()) { + OutDts(" implements "); + GenSeparated(classDef->Implements(), [this](ir::TSClassImplements *impl) { HandleClassInherit(impl->Expr()); }); } OutDts(" {"); OutEndlDts(); } +void TSDeclGen::HandleClassInherit(const ir::Expression *expr) +{ + if (!expr->TsType()->IsTypeError()) { + GenType(expr->TsType()); + } else if (expr->IsETSTypeReference()) { + ProcessETSTypeReferenceType(expr->AsETSTypeReference()); + } +} + void TSDeclGen::EmitClassGlueCode(const ir::ClassDefinition *classDef, const std::string &className) { if (classNode_.isIndirect) { diff --git a/ets2panda/declgen_ets2ts/declgenEts2Ts.h b/ets2panda/declgen_ets2ts/declgenEts2Ts.h index bbd5a7cafc..005c75ce3e 100644 --- a/ets2panda/declgen_ets2ts/declgenEts2Ts.h +++ b/ets2panda/declgen_ets2ts/declgenEts2Ts.h @@ -101,10 +101,18 @@ private: const checker::Type *checkerType = nullptr); bool ProcessTypeAnnotationSpecificTypes(const checker::Type *checkerType); void ProcessTypeAnnotationType(const ir::TypeNode *typeAnnotation, const checker::Type *checkerType = nullptr); + void ProcessETSTypeReference(const ir::TypeNode *typeAnnotation, const checker::Type *checkerType); + void ProcessETSTuple(const ir::ETSTuple *etsTuple); + void ProcessETSUnionType(const ir::ETSUnionType *etsUnionType); + void ProcessTSArrayType(const ir::TSArrayType *tsArrayType); + void GenObjectType(const checker::ETSObjectType *objectType); void GenUnionType(const checker::ETSUnionType *unionType); void GenTupleType(const checker::ETSTupleType *tupleType); + template + std::vector FilterUnionTypes(const ArenaVector &originTypes); + void GenImportDeclaration(const ir::ETSImportDeclaration *importDeclaration); void GenNamespaceImport(const ir::AstNode *specifier, const std::string &source); void GenDefaultImport(const ir::AstNode *specifier, const std::string &source, const std::string &typeStr); @@ -137,7 +145,6 @@ private: void GenAnnotationPropertyValue(ir::Expression *value); void GenTypeParameters(const ir::TSTypeParameterDeclaration *typeParams); - void GenTypeParameters(const ir::TSTypeParameterInstantiation *typeParams); void GenExport(const ir::Identifier *symbol); void GenExport(const ir::Identifier *symbol, const std::string &alias); void GenDefaultExport(const ir::Identifier *symbol); @@ -150,6 +157,7 @@ private: bool ShouldSkipMethodDeclaration(const ir::MethodDefinition *methodDef); bool ShouldSkipClassDeclaration(const std::string_view &className) const; void HandleClassDeclarationTypeInfo(const ir::ClassDefinition *classDef, const std::string_view &className); + void HandleClassInherit(const ir::Expression *expr); void ProcessClassBody(const ir::ClassDefinition *classDef); void ProcessParamDefaultToMap(const ir::Statement *stmt); void ProcessFuncParameter(varbinder::LocalVariable *param); @@ -256,6 +264,12 @@ private: const std::unordered_set numberTypes_ = {"Long", "Float", "Double", "Byte", "Short", "Int", "Number"}; const std::unordered_set stringTypes_ = {"Char", "String"}; + const std::unordered_set annotationList_ = { + "Component", "Builder", "LocalBuilder", "BuilderParam", "Styles", "Extend", "AnimatableExtend", + "Require", "Reusable", "State", "Prop", "Link", "Provide", "Consume", + "Observed", "ObjectLink", "Watch", "Track", "ObservedV2", "Trace", "ComponentV2", + "Local", "Param", "Once", "Event", "Provider", "Consumer", "Monitor", + "Computed", "Type"}; const std::set extensions_ = {".sts", ".ets", ".ts", ".js"}; std::stringstream outputDts_; diff --git a/ets2panda/test/test-lists/declgenets2ts/ets-runtime/declgen-ets2ts-runtime-ignored.txt b/ets2panda/test/test-lists/declgenets2ts/ets-runtime/declgen-ets2ts-runtime-ignored.txt index ae21317722..c2369f6c00 100644 --- a/ets2panda/test/test-lists/declgenets2ts/ets-runtime/declgen-ets2ts-runtime-ignored.txt +++ b/ets2panda/test/test-lists/declgenets2ts/ets-runtime/declgen-ets2ts-runtime-ignored.txt @@ -7,42 +7,13 @@ funcRefWithRestArguments.ets struct-identifier.ets struct-init2.ets type_param_in_union.ets -#FailKind.TSC_FAIL - 65 tests: -AliasUnion.ets +#FailKind.TSC_FAIL - 34 tests: ClassNewInstance.ets Enum7.ets GenericBridges_01.ets GenericBridges_02.ets +InterfacePrivateMethod.ets RecordKeyTypeCheck.ets -RecursiveTypeAlias10.ets -RecursiveTypeAlias8.ets -annotation_tests/AnnotationForClass.ets -annotation_tests/AnnotationForClassProperty.ets -annotation_tests/AnnotationForInterface.ets -annotation_tests/AnnotationForMethod.ets -annotation_tests/AnnotationForTypeAliaDecl.ets -annotation_tests/AnnotationForTypesInClass.ets -annotation_tests/AnnotationForTypesInInterface.ets -annotation_tests/AnnotationForVariableDecl.ets -annotation_tests/AnnotationNoNeedToSetProperties01.ets -annotation_tests/AnnotationNoNeedToSetProperties02.ets -annotation_tests/AnnotationNoNeedToSetProperties03.ets -annotation_tests/AnnotationsFieldType01.ets -annotation_tests/AnnotationsFieldType02.ets -annotation_tests/AnnotationsFieldType03.ets -annotation_tests/AnnotationsFieldType04.ets -annotation_tests/EmitAnnotationToBytecode.ets -annotation_tests/Muti-AnnotationsDefineAndUseForClass.ets -annotation_tests/annotationForNamespace.ets -annotation_tests/annotationUsageSingleFileds01.ets -annotation_tests/annotationUsageSingleFileds02.ets -annotation_tests/annotationUsageSingleFileds03.ets -annotation_tests/annotationUsageSingleFileds04.ets -annotation_tests/annotationUsageSingleFileds05.ets -annotation_tests/annotationUsageSingleFileds06.ets -annotation_tests/annotationUsageSingleFileds07.ets -annotation_tests/annotationUsage_scope_check02.ets -annotation_tests/annotationUsage_scope_check03.ets classGetterSetter.ets class_implements_interface.ets function_type_with_receiver/validReturnThisOfExtensionFunction.ets @@ -66,8 +37,6 @@ lambda_with_receiver/lambda_with_receiver_return_this3.ets lambda_with_receiver/lambda_with_receiver_trailing_in_function_return_this_rotate.ets multiple_inheritance.ets multiple_inheritance_2.ets -namespace_tests/namespace_execution_statements_test02.ets -namespace_tests/namespace_with_annotations.ets override_for_partial_02.ets readonly_simple_form_pos.ets simple_form_pos.ets -- Gitee From 11fc675ef0e25e49bcbcecdca2e898cd380c8239 Mon Sep 17 00:00:00 2001 From: ElevenDuan Date: Mon, 28 Apr 2025 09:10:25 +0800 Subject: [PATCH 122/268] fix code check Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC4HN9?from=project-issue Change-Id: Iddb4a0b37cbfbc218d7c1475bf406a388f4700b5 Signed-off-by: ElevenDuan --- es2panda/binder/binder.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/es2panda/binder/binder.cpp b/es2panda/binder/binder.cpp index 156999be59..612e64e4b0 100644 --- a/es2panda/binder/binder.cpp +++ b/es2panda/binder/binder.cpp @@ -844,6 +844,7 @@ void Binder::ResolveReference(const ir::AstNode *parent, ir::AstNode *childNode) if (Program()->Extension() == ScriptExtension::TS && (Program()->TargetApiVersion() < 11 || (!prop->IsStatic() && !prop->IsPrivate()))) { const ir::ScriptFunction *ctor = util::Helpers::GetContainingConstructor(prop); + CHECK_NOT_NULL(ctor); auto scopeCtx = LexicalScope::Enter(this, ctor->Scope()); ResolveReferences(childNode); break; -- Gitee From 676ef2607edf4b136eaf7a0077d922fd1274275b Mon Sep 17 00:00:00 2001 From: wangyuxin Date: Sun, 13 Apr 2025 14:59:15 +0800 Subject: [PATCH 123/268] Support declare type alias MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC3ZAT Reason: export declare type typeA = string | boolean; 1. In CheckDeclare, we throw a syntax error for the type keyword. 2. In ParseTopLevelStatement, we don't handle type aliases properly and treat all declared identifiers as namespaces. Description: 1. According to spec,we type alias in ambientDeclaration 2. In CheckDeclare, add support for the type keyword. 3. In ParseTopLevelStatement, separate the handling of namespaces and type aliases. Signed-off-by: wangyuxin --- ets2panda/parser/ETSparser.cpp | 1 + ets2panda/parser/ETSparserStatements.cpp | 2 +- .../ast/compiler/ets/declareType_neg_1.ets | 23 +++++ .../ast/compiler/ets/declareType_neg_2.ets | 25 ++++++ .../ast/compiler/ets/declareType_neg_3.ets | 26 ++++++ .../ast/compiler/ets/declareType_neg_4.ets | 25 ++++++ .../compiler/ets/declareType_neg_export.ets | 17 ++++ .../compiler/ets/declareType_neg_import.ets | 20 +++++ .../runtime/ets/declareTypeAlias_generic.ets | 84 ++++++++++++++++++ .../ets/declareTypeAlias_specified.ets | 86 +++++++++++++++++++ .../runtime/ets/import_declare_type_alias.ets | 28 ++++++ .../srcdumper/srcdumper-ets-ignored.txt | 1 + 12 files changed, 337 insertions(+), 1 deletion(-) create mode 100644 ets2panda/test/ast/compiler/ets/declareType_neg_1.ets create mode 100644 ets2panda/test/ast/compiler/ets/declareType_neg_2.ets create mode 100644 ets2panda/test/ast/compiler/ets/declareType_neg_3.ets create mode 100644 ets2panda/test/ast/compiler/ets/declareType_neg_4.ets create mode 100644 ets2panda/test/ast/compiler/ets/declareType_neg_export.ets create mode 100644 ets2panda/test/ast/compiler/ets/declareType_neg_import.ets create mode 100644 ets2panda/test/runtime/ets/declareTypeAlias_generic.ets create mode 100644 ets2panda/test/runtime/ets/declareTypeAlias_specified.ets create mode 100644 ets2panda/test/runtime/ets/import_declare_type_alias.ets diff --git a/ets2panda/parser/ETSparser.cpp b/ets2panda/parser/ETSparser.cpp index 8d27e8a06c..a49f604b1b 100644 --- a/ets2panda/parser/ETSparser.cpp +++ b/ets2panda/parser/ETSparser.cpp @@ -1847,6 +1847,7 @@ void ETSParser::CheckDeclare() case lexer::TokenType::KEYW_ABSTRACT: case lexer::TokenType::KEYW_FINAL: case lexer::TokenType::KEYW_INTERFACE: + case lexer::TokenType::KEYW_TYPE: case lexer::TokenType::KEYW_ASYNC: { return; } diff --git a/ets2panda/parser/ETSparserStatements.cpp b/ets2panda/parser/ETSparserStatements.cpp index 1638ca80d6..e50e64f2c5 100644 --- a/ets2panda/parser/ETSparserStatements.cpp +++ b/ets2panda/parser/ETSparserStatements.cpp @@ -223,7 +223,7 @@ ir::Statement *ETSParser::ParseTopLevelDeclStatement(StatementParsingFlags flags result = ParseTopLevelAnnotation(memberModifiers); break; case lexer::TokenType::LITERAL_IDENT: { - if (((memberModifiers & ir::ModifierFlags::DECLARE) != 0U) || IsNamespaceDecl()) { + if (IsNamespaceDecl()) { return ParseNamespaceStatement(memberModifiers); } result = ParseIdentKeyword(); diff --git a/ets2panda/test/ast/compiler/ets/declareType_neg_1.ets b/ets2panda/test/ast/compiler/ets/declareType_neg_1.ets new file mode 100644 index 0000000000..0d5dab8c8a --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/declareType_neg_1.ets @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +declare const type typeA = int; + +/* @@? 16:20 Error SyntaxError: Variable must be initialized or it's type must be declared. */ +/* @@? 16:20 Error SyntaxError: Variable must be initialized or it's type must be declared. */ +/* @@? 16:20 Error SyntaxError: Unexpected token 'typeA'. */ +/* @@? 16:20 Error TypeError: Unresolved reference typeA */ +/* @@? 16:28 Error TypeError: Unresolved reference int */ + diff --git a/ets2panda/test/ast/compiler/ets/declareType_neg_2.ets b/ets2panda/test/ast/compiler/ets/declareType_neg_2.ets new file mode 100644 index 0000000000..2a64b2993b --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/declareType_neg_2.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +interface Issue { + title : string + description : string +} +declare type type_utility = Partial; + +let a : type_utility = {description : 1234} + +/* @@? 22:39 Error TypeError: Type 'int' is not compatible with type 'String|undefined' at property 'description' */ + diff --git a/ets2panda/test/ast/compiler/ets/declareType_neg_3.ets b/ets2panda/test/ast/compiler/ets/declareType_neg_3.ets new file mode 100644 index 0000000000..ee618b7cbe --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/declareType_neg_3.ets @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +interface Issue { + title?: string + description?: string +} +declare type type_utility = Required; + +let a : type_utility = {title : "declare type alias test"} + + +/* @@? 22:24 Error TypeError: Class property 'description' needs to be initialized for Required. */ + diff --git a/ets2panda/test/ast/compiler/ets/declareType_neg_4.ets b/ets2panda/test/ast/compiler/ets/declareType_neg_4.ets new file mode 100644 index 0000000000..08f526f763 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/declareType_neg_4.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +declare type type_array_1 = Array; +declare type type_array_2 = T[]; +declare type type_array_alias = Array> | type_array_2 + +let a : int[] = [1,2,3] +let b : type_array_alias = a; + + +/* @@? 21:37 Error TypeError: Type 'int[]' cannot be assigned to type 'Array>|String[]' */ + diff --git a/ets2panda/test/ast/compiler/ets/declareType_neg_export.ets b/ets2panda/test/ast/compiler/ets/declareType_neg_export.ets new file mode 100644 index 0000000000..d17bf7578a --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/declareType_neg_export.ets @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export default declare type typeA = T[] | Array + diff --git a/ets2panda/test/ast/compiler/ets/declareType_neg_import.ets b/ets2panda/test/ast/compiler/ets/declareType_neg_import.ets new file mode 100644 index 0000000000..d98c0d56f3 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/declareType_neg_import.ets @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import typeA from './declareType_neg_export' +let a : typeA = new Array() + + +/* @@? 16:22 Error TypeError: Type 'Array' cannot be assigned to type 'Int[]|Array' */ + diff --git a/ets2panda/test/runtime/ets/declareTypeAlias_generic.ets b/ets2panda/test/runtime/ets/declareTypeAlias_generic.ets new file mode 100644 index 0000000000..02d839bc3b --- /dev/null +++ b/ets2panda/test/runtime/ets/declareTypeAlias_generic.ets @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Union +export declare type type_union = T | boolean; + + +// Array +export declare type type_array_1 = Array; +declare type type_array_2 = T[]; + + +// Array + Union +export declare type type_union_array_1 = Array | Array +declare type type_union_array_2 = Array + + +// Array + Type Alias +export declare type type_array_alias_1 = Array> +declare type type_array_alias_2 = Array> | type_union +declare type type_array_alias_3 = Array> | type_array_2 + + +// Tuple +declare type type_tuple_1 = [T, U, R] +declare type type_tuple_2 = [T, Array, R] +declare type type_tuple_3 = [T, [U, R], P] +declare type type_tuple_4 = [T, U[], R] + +// Tuple + Union +declare type type_tuple_union_1 = [string, T | null, number] +declare type type_tuple_union_2 = [string, Array | boolean, number] +declare type type_tuple_union_3 = [string, T, number] | Array | [string, T, number] +declare type type_tuple_union_4 = [string, T, number] | (T | undefined)[] + +// Tuple + Type Alias +declare type type_tuple_alias_1 = [T, U | null, type_union_array_1] +declare type type_tuple_alias_2 = [string, Array | boolean, type_union_array_1] +declare type type_tuple_alias_3 = [string, U, R] | Array | [string, boolean, number] | type_tuple_union_4 +declare type type_tuple_alias_4 = [string, boolean, number] | (boolean | undefined)[] | type_tuple_union_3 + + +// Utility +interface Issue { + title : T + description : T +} + +interface Issue2 { + title?: T + description?: string +} +declare type type_utility_1 = Required>; +declare type type_utility_2 = Readonly>; +declare type type_utility_3 = Record; + + +function main() { + let type_union_var : type_union = "name" + let type_array_var : type_array_1 = new Array() + let type_union_array_var : type_union_array_1 = new Array() + let type_array_alias_var : type_array_alias_1 = new Array() + let type_tuple_var : type_tuple_1 = ["name", true, 2] + let type_tuple_union_var : type_tuple_union_2 = ["name", true, 2] + let type_tuple_alias__var : type_tuple_alias_1 = ["name", null, new Array] + let type_utility_1_var : type_utility_1 = {title: "type alias", description: "test for type alias"} + let type_utility_2_var : type_utility_2 = {title: "type alias", description: "test for type alias"} + let type_utility_3_var : type_utility_3 = { + 1 : new Object() + } +} + diff --git a/ets2panda/test/runtime/ets/declareTypeAlias_specified.ets b/ets2panda/test/runtime/ets/declareTypeAlias_specified.ets new file mode 100644 index 0000000000..374b81f2c6 --- /dev/null +++ b/ets2panda/test/runtime/ets/declareTypeAlias_specified.ets @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Union +export declare type type_union = string | boolean; + + +// Array +export declare type type_array_1 = Array; +declare type type_array_2 = boolean[]; + + +// Array + Union +export declare type type_union_array_1 = Array | Array +declare type type_union_array_2 = Array + + +// Array + Type Alias +export declare type type_array_alias_1 = Array +declare type type_array_alias_2 = Array | type_union +declare type type_array_alias_3 = Array | type_array_2 + + +// Tuple +declare type type_tuple_1 = [string, boolean, number] +declare type type_tuple_2 = [string, Array, number] +declare type type_tuple_3 = [string, [string, boolean], number] +declare type type_tuple_4 = [string, boolean[], number] + +// Tuple + Union +declare type type_tuple_union_1 = [string, boolean | null, number] +declare type type_tuple_union_2 = [string, Array | boolean, number] +declare type type_tuple_union_3 = [string, boolean, number] | Array | [string, null, number] +declare type type_tuple_union_4 = [string, boolean, number] | (boolean | undefined)[] + +// Tuple + Type Alias +declare type type_tuple_alias_1 = [string, boolean | null, type_union_array_1] +declare type type_tuple_alias_2 = [string, Array | boolean, type_union_array_1] +declare type type_tuple_alias_3 = [string, boolean, number] | Array | [string, null, number] | type_tuple_union_4 +declare type type_tuple_alias_4 = [string, boolean, number] | (boolean | undefined)[] | type_tuple_union_3 + + +// Utility +interface Issue { + title : string + description : string +} +declare type type_utility_1 = Partial; + +interface Issue2 { + title?: string + description?: string +} +declare type type_utility_2 = Required; +declare type type_utility_3 = Readonly; +declare type type_utility_4 = Record; + + +function main() { + let type_union_var : type_union = "name" + let type_array_var : type_array_1 = new Array() + let type_union_array_var : type_union_array_1 = new Array() + let type_array_alias_var : type_array_alias_1 = new Array() + let type_tuple_var : type_tuple_1 = ["name", true, 2] + let type_tuple_union_var : type_tuple_union_2 = ["name", new Array, 2] + let type_tuple_alias__var : type_tuple_alias_1 = ["name", null, new Array] + let type_utility_1_var : type_utility_1 = {} + let type_utility_2_var : type_utility_2 = {title: "type alias", description: "test for type alias"} + let type_utility_3_var : type_utility_3 = {title: "type alias", description: "test for type alias"} + let type_utility_4_var : type_utility_4 = { + 1 : new Object() + } +} + diff --git a/ets2panda/test/runtime/ets/import_declare_type_alias.ets b/ets2panda/test/runtime/ets/import_declare_type_alias.ets new file mode 100644 index 0000000000..eaf3883587 --- /dev/null +++ b/ets2panda/test/runtime/ets/import_declare_type_alias.ets @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {type_union, type_array_1 as type_array, type_union_array_1 as type_union_array, type_array_alias_1 as type_array_alias} from './declareTypeAlias_generic.ets' + +function main() { + let type_union_var : type_union = "name" + let type_array_var : type_array = new Array() + let type_union_array_var : type_union_array = new Array() + let type_array_alias_var : type_array_alias = new Array() + assertEQ((typeof type_union_var), string); + assertEQ((typeof type_array_var), object); + assertEQ((typeof type_union_array_var), object); + assertEQ((typeof type_array_alias_var), object); +} + diff --git a/ets2panda/test/test-lists/srcdumper/srcdumper-ets-ignored.txt b/ets2panda/test/test-lists/srcdumper/srcdumper-ets-ignored.txt index a7b0d3ba76..c44899c0eb 100644 --- a/ets2panda/test/test-lists/srcdumper/srcdumper-ets-ignored.txt +++ b/ets2panda/test/test-lists/srcdumper/srcdumper-ets-ignored.txt @@ -152,6 +152,7 @@ parser/ets/array_creation_expression.ets runtime/ets/re_export/export/reexport_elements1.ets runtime/ets/re_export/export/reexport_elements2.ets runtime/ets/re_export/import.ets +runtime/ets/import_declare_type_alias.ets # FailKind.ES2PANDA_FAIL runtime/ets/StringFasta.ets -- Gitee From 92d64be2bc22c1c125f00490eda12e06acad34ad Mon Sep 17 00:00:00 2001 From: wangyuxin Date: Wed, 9 Apr 2025 14:27:57 +0800 Subject: [PATCH 124/268] Fix segv of circular inheritance Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC47G4 Reason: interface I1 extends I2 { foo1():void; } interface I2 extends I1 { foo2():void; } class cls implements I1 { foo1():void {} foo2():void {} } 1. During the InterfacePropertyDeclarationsPhase, when updating class properties, we collect properties from the super interfaces by calling CollectSuperInterfaceProperties. 2. In CollectSuperInterfaceProperties, we continue to collect properties from the super interfaces of the current interface. 3. A circular dependency between interfaces leads to an endless loop. Description: 1. We use visitedInerfaces_ in OptionalInterfacePropertyCollector to avoid collecting duplicate interface properties. 2. Before processing a class, call InitVisitedInferfaces to initialize the visited interfaces record. In CollectSuperInterfaceProperties, we first check whether the current class's interface has been processed. If it hasn't, we exit the function; otherwise, we add it to the set. Signed-off-by: wangyuxin --- .../ets/interfacePropertyDeclarations.cpp | 6 ++++ .../ets/interfacePropertyDeclarations.h | 12 +++++++ .../ast/compiler/ets/circular_inheritance.ets | 30 ++++++++++++++++ .../ets/circular_inheritance_class.ets | 34 +++++++++++++++++++ 4 files changed, 82 insertions(+) create mode 100644 ets2panda/test/ast/compiler/ets/circular_inheritance.ets create mode 100644 ets2panda/test/ast/compiler/ets/circular_inheritance_class.ets diff --git a/ets2panda/compiler/lowering/ets/interfacePropertyDeclarations.cpp b/ets2panda/compiler/lowering/ets/interfacePropertyDeclarations.cpp index e03613933b..01327be62a 100644 --- a/ets2panda/compiler/lowering/ets/interfacePropertyDeclarations.cpp +++ b/ets2panda/compiler/lowering/ets/interfacePropertyDeclarations.cpp @@ -262,6 +262,10 @@ ir::Expression *InterfacePropertyDeclarationsPhase::UpdateInterfaceProperties(ch void InterfacePropertyDeclarationsPhase::CollectSuperInterfaceProperties(InterfacePropertyType &implInterfaceProperties, const std::string &interId) { + if (GetPropCollector().IsVisitedInterface(interId)) { + return; + } + if (GetPropCollector().IsInterfaceHasProperty(interId)) { InterfacePropertyType &properties = GetPropCollector().GetInterfaceProperty(interId); implInterfaceProperties.insert(properties.begin(), properties.end()); @@ -281,6 +285,8 @@ void InterfacePropertyDeclarationsPhase::UpdateClassProperties(checker::ETSCheck } InterfacePropertyType implInterfaceProperties = {}; + + GetPropCollector().InitVisitedInterfaces(); for (const auto &implement : klass->Implements()) { std::string interId = implement->Expr()->AsETSTypeReference()->Part()->Name()->ToString(); CollectSuperInterfaceProperties(implInterfaceProperties, interId); diff --git a/ets2panda/compiler/lowering/ets/interfacePropertyDeclarations.h b/ets2panda/compiler/lowering/ets/interfacePropertyDeclarations.h index 23366a2f1d..db30031d94 100644 --- a/ets2panda/compiler/lowering/ets/interfacePropertyDeclarations.h +++ b/ets2panda/compiler/lowering/ets/interfacePropertyDeclarations.h @@ -22,6 +22,7 @@ namespace ark::es2panda::compiler { using InterfacePropertyType = std::unordered_set; using InterfacePropertyMapType = std::unordered_map; +using VisitedInterfacesOfClass = std::unordered_set; class OptionalInterfacePropertyCollector { public: @@ -87,10 +88,21 @@ public: return interfaceParents_.count(interId) != 0U; } + bool IsVisitedInterface(const std::string &interId) + { + return !visitedInterfaces_.insert(interId).second; + } + + void InitVisitedInterfaces() + { + visitedInterfaces_.clear(); + } + private: std::string interfaceId_ {}; InterfacePropertyMapType interfaceProperties_ {}; InterfacePropertyMapType interfaceParents_ {}; + VisitedInterfacesOfClass visitedInterfaces_ {}; }; class InterfacePropertyDeclarationsPhase : public PhaseForDeclarations { diff --git a/ets2panda/test/ast/compiler/ets/circular_inheritance.ets b/ets2panda/test/ast/compiler/ets/circular_inheritance.ets new file mode 100644 index 0000000000..3039b89682 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/circular_inheritance.ets @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +interface I1 extends I2 { + foo1():void; +} + +interface I2 extends I1 { + foo2():void; +} + +class cls implements I1 { + foo1():void {} + foo2():void {} +} + +/* @@? 16:11 Error TypeError: Cyclic inheritance involving I1. */ + diff --git a/ets2panda/test/ast/compiler/ets/circular_inheritance_class.ets b/ets2panda/test/ast/compiler/ets/circular_inheritance_class.ets new file mode 100644 index 0000000000..d6f8d2deb5 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/circular_inheritance_class.ets @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class A extends B { + foo1():int{} +} + +class B extends A { + foo2():int{} +} + +class C extends A { + foo1(){ + return 1; + } + foo2(){ + return 2; + } +} + +/* @@? 16:7 Error TypeError: Cyclic inheritance involving A. */ + -- Gitee From 53092edc143cce8afad2d04d6fbb182ddf8bd7f7 Mon Sep 17 00:00:00 2001 From: liaokangkang Date: Mon, 21 Apr 2025 09:42:17 +0800 Subject: [PATCH 125/268] Fix async function return type inference MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC31XK Description: The return type of the async function is not a Promise Tests: all tests passed Signed-off-by:menjiaheng --- ets2panda/checker/ETSAnalyzer.cpp | 77 ++++++++++++++----- ets2panda/checker/ETSchecker.h | 2 +- ets2panda/checker/ets/helpers.cpp | 6 +- .../ir/ets/etsNewArrayInstanceExpression.h | 16 ++++ .../etsNewMultiDimArrayInstanceExpression.h | 16 ++++ .../ir/expressions/arrowFunctionExpression.h | 11 +++ .../ets/async_function_return_type.ets | 28 +++++++ 7 files changed, 133 insertions(+), 23 deletions(-) create mode 100644 ets2panda/test/runtime/ets/async_function_return_type.ets diff --git a/ets2panda/checker/ETSAnalyzer.cpp b/ets2panda/checker/ETSAnalyzer.cpp index ecb6af26f9..fddcfb94bd 100644 --- a/ets2panda/checker/ETSAnalyzer.cpp +++ b/ets2panda/checker/ETSAnalyzer.cpp @@ -854,6 +854,29 @@ checker::Type *ETSAnalyzer::Check(ir::ArrayExpression *expr) const return expr->TsType(); } +void TryInferPreferredType(ir::ArrowFunctionExpression *expr, checker::Type *preferredType, ETSChecker *checker) +{ + if (!preferredType->IsETSUnionType()) { + if (preferredType->IsETSArrowType() && + !preferredType->AsETSFunctionType()->CallSignaturesOfMethodOrArrow().empty()) { + checker->TryInferTypeForLambdaTypeAlias(expr, preferredType->AsETSFunctionType()); + checker->BuildFunctionSignature(expr->Function(), false); + } + return; + } + + for (auto &ct : preferredType->AsETSUnionType()->ConstituentTypes()) { + if (!ct->IsETSArrowType() || ct->AsETSFunctionType()->CallSignaturesOfMethodOrArrow().empty()) { + continue; + } + checker->TryInferTypeForLambdaTypeAlias(expr, ct->AsETSFunctionType()); + checker->BuildFunctionSignature(expr->Function(), false); + if (expr->Function()->Signature() != nullptr) { + return; + } + } +} + checker::Type *ETSAnalyzer::Check(ir::ArrowFunctionExpression *expr) const { ETSChecker *checker = GetETSChecker(); @@ -893,7 +916,13 @@ checker::Type *ETSAnalyzer::Check(ir::ArrowFunctionExpression *expr) const checker->AddStatus(checker::CheckerStatus::IN_LAMBDA); checker->Context().SetContainingLambda(expr); - checker->BuildFunctionSignature(expr->Function(), false); + auto preferredType = expr->GetPreferredType(); + if (preferredType != nullptr) { + TryInferPreferredType(expr, preferredType, checker); + } else { + checker->BuildFunctionSignature(expr->Function(), false); + } + if (expr->Function()->Signature() == nullptr) { return checker->InvalidateType(expr); } @@ -1030,6 +1059,33 @@ checker::Type *ETSAnalyzer::Check(ir::AssignmentExpression *const expr) const return expr->SetTsType(smartType); } +static checker::Type *HandleSubstitution(ETSChecker *checker, ir::AssignmentExpression *expr, Type *const leftType) +{ + bool possibleInferredTypeOfArray = leftType->IsETSArrayType() || leftType->IsETSResizableArrayType() || + leftType->IsETSTupleType() || leftType->IsETSUnionType(); + if (expr->Right()->IsArrayExpression() && possibleInferredTypeOfArray) { + checker->ModifyPreferredType(expr->Right()->AsArrayExpression(), leftType); + } + + if (expr->Right()->IsETSNewArrayInstanceExpression()) { + expr->Right()->AsETSNewArrayInstanceExpression()->SetPreferredType(leftType); + } + + if (expr->Right()->IsETSNewMultiDimArrayInstanceExpression()) { + expr->Right()->AsETSNewMultiDimArrayInstanceExpression()->SetPreferredType(leftType); + } + + if (expr->Right()->IsObjectExpression()) { + expr->Right()->AsObjectExpression()->SetPreferredType(leftType); + } + + if (expr->Right()->IsArrowFunctionExpression() && (leftType->IsETSArrowType() || leftType->IsETSUnionType())) { + expr->Right()->AsArrowFunctionExpression()->SetPreferredType(leftType); + } + + return expr->Right()->Check(checker); +} + std::tuple ETSAnalyzer::CheckAssignmentExprOperatorType(ir::AssignmentExpression *expr, Type *const leftType) const { @@ -1059,24 +1115,7 @@ std::tuple ETSAnalyzer::CheckAssignmentExprOperatorTyp break; } case lexer::TokenType::PUNCTUATOR_SUBSTITUTION: { - if (leftType->IsETSArrayType() && expr->Right()->IsArrayExpression()) { - checker->ModifyPreferredType(expr->Right()->AsArrayExpression(), leftType); - } - - if (leftType->IsETSTupleType() && expr->Right()->IsArrayExpression()) { - checker->ModifyPreferredType(expr->Right()->AsArrayExpression(), leftType); - } - - if (expr->Right()->IsObjectExpression()) { - expr->Right()->AsObjectExpression()->SetPreferredType(leftType); - } - - if (expr->Right()->IsArrowFunctionExpression() && leftType->IsETSArrowType() && - !leftType->AsETSFunctionType()->CallSignaturesOfMethodOrArrow().empty()) { - checker->TryInferTypeForLambdaTypeAlias(expr, leftType->AsETSFunctionType()); - } - - sourceType = expr->Right()->Check(checker); + sourceType = HandleSubstitution(checker, expr, leftType); break; } default: { diff --git a/ets2panda/checker/ETSchecker.h b/ets2panda/checker/ETSchecker.h index 105c66d5c8..37d3ad0de7 100644 --- a/ets2panda/checker/ETSchecker.h +++ b/ets2panda/checker/ETSchecker.h @@ -384,7 +384,7 @@ public: void InferTypesForLambda(ir::ScriptFunction *lambda, ir::ETSFunctionType *calleeType, Signature *maybeSubstitutedFunctionSig = nullptr); void InferTypesForLambda(ir::ScriptFunction *lambda, Signature *signature); - void TryInferTypeForLambdaTypeAlias(ir::AssignmentExpression *expr, ETSFunctionType *calleeType); + void TryInferTypeForLambdaTypeAlias(ir::ArrowFunctionExpression *expr, ETSFunctionType *calleeType); bool TypeInference(Signature *signature, const ArenaVector &arguments, TypeRelationFlag flags = TypeRelationFlag::NONE); bool CheckLambdaTypeAnnotation(ir::AstNode *typeAnnotation, ir::ArrowFunctionExpression *arrowFuncExpr, diff --git a/ets2panda/checker/ets/helpers.cpp b/ets2panda/checker/ets/helpers.cpp index 0ecd59533b..dd7a2b1e7f 100644 --- a/ets2panda/checker/ets/helpers.cpp +++ b/ets2panda/checker/ets/helpers.cpp @@ -2493,12 +2493,12 @@ void ETSChecker::ModifyPreferredType(ir::ArrayExpression *const arrayExpr, Type } } -void ETSChecker::TryInferTypeForLambdaTypeAlias(ir::AssignmentExpression *expr, ETSFunctionType *calleeType) +void ETSChecker::TryInferTypeForLambdaTypeAlias(ir::ArrowFunctionExpression *expr, ETSFunctionType *calleeType) { - ES2PANDA_ASSERT(expr->Right()->IsArrowFunctionExpression()); + ES2PANDA_ASSERT(expr->IsArrowFunctionExpression()); ES2PANDA_ASSERT(calleeType->IsETSArrowType()); - ir::ScriptFunction *const lambda = expr->Right()->AsArrowFunctionExpression()->Function(); + ir::ScriptFunction *const lambda = expr->AsArrowFunctionExpression()->Function(); auto *signature = calleeType->CallSignaturesOfMethodOrArrow()[0]; if (signature->Params().size() >= lambda->Params().size() && NeedTypeInference(lambda)) { diff --git a/ets2panda/ir/ets/etsNewArrayInstanceExpression.h b/ets2panda/ir/ets/etsNewArrayInstanceExpression.h index 17e30503df..331c9d6afb 100644 --- a/ets2panda/ir/ets/etsNewArrayInstanceExpression.h +++ b/ets2panda/ir/ets/etsNewArrayInstanceExpression.h @@ -74,6 +74,21 @@ public: return defaultConstructorSignature_; } + void SetPreferredType(checker::Type *preferredType) noexcept + { + preferredType_ = preferredType; + } + + [[nodiscard]] checker::Type *GetPreferredType() noexcept + { + return preferredType_; + } + + [[nodiscard]] checker::Type const *GetPreferredType() const noexcept + { + return preferredType_; + } + void SetDimension(ir::Expression *dimension) noexcept { dimension_ = dimension; @@ -113,6 +128,7 @@ private: ir::TypeNode *typeReference_; ir::Expression *dimension_; checker::Signature *defaultConstructorSignature_ {}; + checker::Type *preferredType_ {}; }; } // namespace ark::es2panda::ir diff --git a/ets2panda/ir/ets/etsNewMultiDimArrayInstanceExpression.h b/ets2panda/ir/ets/etsNewMultiDimArrayInstanceExpression.h index 87d697c67e..1751b400b0 100644 --- a/ets2panda/ir/ets/etsNewMultiDimArrayInstanceExpression.h +++ b/ets2panda/ir/ets/etsNewMultiDimArrayInstanceExpression.h @@ -78,6 +78,21 @@ public: return signature_; } + [[nodiscard]] checker::Type *GetPreferredType() noexcept + { + return preferredType_; + } + + [[nodiscard]] checker::Type const *GetPreferredType() const noexcept + { + return preferredType_; + } + + void SetPreferredType(checker::Type *preferredType) noexcept + { + preferredType_ = preferredType; + } + void SetSignature(checker::Signature *signature) noexcept { signature_ = signature; @@ -110,6 +125,7 @@ private: ir::TypeNode *typeReference_; ArenaVector dimensions_; checker::Signature *signature_ {}; + checker::Type *preferredType_ {}; }; } // namespace ark::es2panda::ir diff --git a/ets2panda/ir/expressions/arrowFunctionExpression.h b/ets2panda/ir/expressions/arrowFunctionExpression.h index ff6a756d44..2550cc7e0d 100644 --- a/ets2panda/ir/expressions/arrowFunctionExpression.h +++ b/ets2panda/ir/expressions/arrowFunctionExpression.h @@ -51,6 +51,16 @@ public: return func_; } + void SetPreferredType(checker::Type *preferredType) noexcept + { + preferredType_ = preferredType; + } + + [[nodiscard]] checker::Type *GetPreferredType() noexcept + { + return preferredType_; + } + [[nodiscard]] ArrowFunctionExpression *Clone(ArenaAllocator *allocator, AstNode *parent) override; void TransformChildren(const NodeTransformer &cb, std::string_view transformationName) override; @@ -72,6 +82,7 @@ public: private: ScriptFunction *func_; + checker::Type *preferredType_ {}; }; } // namespace ark::es2panda::ir diff --git a/ets2panda/test/runtime/ets/async_function_return_type.ets b/ets2panda/test/runtime/ets/async_function_return_type.ets new file mode 100644 index 0000000000..7e596a0f9e --- /dev/null +++ b/ets2panda/test/runtime/ets/async_function_return_type.ets @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class Person{ + name:string; + fetchData?:()=>Promise; + + constructor(name:string){ + this.name = name; + } +} + +function main(){ + const bob = new Person("Bob"); + bob.fetchData = async () => "Data fetched"; +} \ No newline at end of file -- Gitee From 72a36612f08c292fce3ba38257d1ab78023bc2c7 Mon Sep 17 00:00:00 2001 From: liushitong Date: Sun, 27 Apr 2025 10:15:44 +0800 Subject: [PATCH 126/268] [LSP]: Add update function for bindings Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC4VWD Signed-off-by: liushitong --- ets2panda/bindings/src/lsp_helper.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/ets2panda/bindings/src/lsp_helper.ts b/ets2panda/bindings/src/lsp_helper.ts index 544fbc2a42..e9ea9a2fd5 100644 --- a/ets2panda/bindings/src/lsp_helper.ts +++ b/ets2panda/bindings/src/lsp_helper.ts @@ -30,6 +30,8 @@ import { unpackString } from './private'; import { Es2pandaContextState } from './generated/Es2pandaEnums'; import { BuildConfig } from './types'; import { PluginDriver, PluginHook } from './ui_plugins_driver'; +import { ModuleDescriptor } from './buildConfigGenerate'; +import { generateArkTsConfigByModules } from './arktsConfigGenerate'; import * as fs from 'fs'; import * as path from 'path'; @@ -42,6 +44,7 @@ function initBuildEnv(): void { export class Lsp { private pandaLibPath: string; + private projectPath: string; private fileNameToArktsconfig: Record; // Map private moduleToBuildConfig: Record; // Map private getFileContent: (filePath: string) => string; @@ -49,6 +52,7 @@ export class Lsp { constructor(projectPath: string, getContentCallback?: (filePath: string) => string) { initBuildEnv(); this.pandaLibPath = path.resolve(__dirname, '../../ets2panda/lib'); + this.projectPath = projectPath; let compileFileInfoPath = path.join(projectPath, '.idea', '.deveco', 'lsp_compileFileInfos.json'); this.fileNameToArktsconfig = JSON.parse(fs.readFileSync(compileFileInfoPath, 'utf-8')); let buildConfigPath = path.join(projectPath, '.idea', '.deveco', 'lsp_build_config.json'); @@ -56,6 +60,14 @@ export class Lsp { this.getFileContent = getContentCallback || ((path) => fs.readFileSync(path, 'utf8')); } + updateConfig(buildSdkPath: string, modules?: ModuleDescriptor[]): void { + generateArkTsConfigByModules(buildSdkPath, this.projectPath, modules); + let compileFileInfoPath = path.join(this.projectPath, '.idea', '.deveco', 'lsp_compileFileInfos.json'); + this.fileNameToArktsconfig = JSON.parse(fs.readFileSync(compileFileInfoPath, 'utf-8')); + let buildConfigPath = path.join(this.projectPath, '.idea', '.deveco', 'lsp_build_config.json'); + this.moduleToBuildConfig = JSON.parse(fs.readFileSync(buildConfigPath, 'utf-8')); + } + getDefinitionAtPosition(filename: String, offset: number): LspDefinitionData { let lspDriverHelper = new LspDriverHelper(); let filePath = path.resolve(filename.valueOf()); -- Gitee From 5872a9fd3637abf8c18e4cdf2b34609739077a82 Mon Sep 17 00:00:00 2001 From: xingshunxiang Date: Sat, 19 Apr 2025 17:16:11 +0800 Subject: [PATCH 127/268] Cherry-pick Several PR to branch 0411 Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC4G5H?from=project-issue Description: Cherry-pick 5357 5312 to branch 0411 Reason: Cherry-pick 5357 5312 to branch 0411 Tests: ninja tests passed tests/tests-u-runner/runner.sh --ets-cts --show-progress --build-dir x64.release --processes=all passed tests/tests-u-runner/runner.sh --ets-func-tests --show-progress --build-dir x64.release --processes=all passed tests/tests-u-runner/runner.sh --astchecker --show-progress --build-dir x64.release --processes=all passed tests/tests-u-runner/runner.sh --ets-runtime --show-progress --build-dir x64.release --processes=all passed tests/tests-u-runner/runner.sh --parser --no-js --show-progress --build-dir x64.release --processes=all passed Signed-off-by: xingshunxiang --- ets2panda/checker/ets/typeCheckingHelpers.cpp | 9 ++- .../compiler/lowering/ets/lambdaLowering.cpp | 13 +++-- ...bda-type-inference-overloaded-expected.txt | 2 - .../test/runtime/ets/FixFunctionCall.ets | 26 +++++++++ .../ets/recheck_test/recheck_test1.ets | 57 +++++++++++++++++++ 5 files changed, 99 insertions(+), 8 deletions(-) create mode 100644 ets2panda/test/runtime/ets/FixFunctionCall.ets create mode 100644 ets2panda/test/runtime/ets/recheck_test/recheck_test1.ets diff --git a/ets2panda/checker/ets/typeCheckingHelpers.cpp b/ets2panda/checker/ets/typeCheckingHelpers.cpp index df6f4d399a..770eaf8603 100644 --- a/ets2panda/checker/ets/typeCheckingHelpers.cpp +++ b/ets2panda/checker/ets/typeCheckingHelpers.cpp @@ -1358,12 +1358,17 @@ bool ETSChecker::CheckLambdaAssignable(ir::Expression *param, ir::ScriptFunction if (!typeAnn->IsETSFunctionType()) { // the surrounding function is made so we can *bypass* the typecheck in the "inference" context, // however the body of the function has to be checked in any case - lambda->Parent()->Check(this); if (typeAnn->IsETSUnionType()) { + lambda->Parent()->Check(this); return CheckLambdaAssignableUnion(typeAnn, lambda); } + Type *paramType = param->AsETSParameterExpression()->Ident()->TsType(); - return paramType->IsETSObjectType() && Relation()->IsSupertypeOf(paramType, GlobalBuiltinFunctionType()); + if (paramType->IsETSObjectType() && Relation()->IsSupertypeOf(paramType, GlobalBuiltinFunctionType())) { + lambda->Parent()->Check(this); + return true; + } + return false; } ir::ETSFunctionType *calleeType = typeAnn->AsETSFunctionType(); diff --git a/ets2panda/compiler/lowering/ets/lambdaLowering.cpp b/ets2panda/compiler/lowering/ets/lambdaLowering.cpp index 546ed9e39f..1f4fc3dedb 100644 --- a/ets2panda/compiler/lowering/ets/lambdaLowering.cpp +++ b/ets2panda/compiler/lowering/ets/lambdaLowering.cpp @@ -1134,6 +1134,13 @@ static bool IsEnumFunctionCall(const ir::Identifier *const id) return false; } +static bool IsValidFunctionDeclVar(const varbinder::Variable *const var) +{ + // Note: If a function is accessor, then no need to build lambda class. + return var != nullptr && var->Declaration() != nullptr && var->Declaration()->IsFunctionDecl() && + !var->TsType()->HasTypeFlag(checker::TypeFlag::GETTER_SETTER); +} + static ir::AstNode *BuildLambdaClassWhenNeeded(public_lib::Context *ctx, ir::AstNode *node) { if (node->IsArrowFunctionExpression()) { @@ -1146,8 +1153,7 @@ static ir::AstNode *BuildLambdaClassWhenNeeded(public_lib::Context *ctx, ir::Ast // We are running this lowering only for ETS files // so it is correct to pass ETS extension here to isReference() if (id->IsReference(ScriptExtension::ETS) && id->TsType() != nullptr && id->TsType()->IsETSFunctionType() && - var != nullptr && var->Declaration() != nullptr && var->Declaration()->IsFunctionDecl() && - !IsInCalleePosition(id) && !IsEnumFunctionCall(id)) { + !IsInCalleePosition(id) && !IsEnumFunctionCall(id) && IsValidFunctionDeclVar(var)) { return ConvertFunctionReference(ctx, id); } } @@ -1161,8 +1167,7 @@ static ir::AstNode *BuildLambdaClassWhenNeeded(public_lib::Context *ctx, ir::Ast checker::PropertySearchFlags::SEARCH_INSTANCE_METHOD | checker::PropertySearchFlags::SEARCH_STATIC_METHOD | checker::PropertySearchFlags::DISALLOW_SYNTHETIC_METHOD_CREATION); - if (var != nullptr && var->Declaration()->IsFunctionDecl() && - !var->TsType()->HasTypeFlag(checker::TypeFlag::GETTER_SETTER) && !IsInCalleePosition(mexpr)) { + if (IsValidFunctionDeclVar(var) && !IsInCalleePosition(mexpr)) { return ConvertFunctionReference(ctx, mexpr); } } diff --git a/ets2panda/test/parser/ets/lambda-type-inference-overloaded-expected.txt b/ets2panda/test/parser/ets/lambda-type-inference-overloaded-expected.txt index 59c102cdb8..e8ff142dfa 100644 --- a/ets2panda/test/parser/ets/lambda-type-inference-overloaded-expected.txt +++ b/ets2panda/test/parser/ets/lambda-type-inference-overloaded-expected.txt @@ -1644,5 +1644,3 @@ } } TypeError: Reference to foo is ambiguous [lambda-type-inference-overloaded.ets:28:5] -TypeError: The type of parameter 'x' cannot be inferred [lambda-type-inference-overloaded.ets:31:10] -TypeError: The type of parameter 'y' cannot be inferred [lambda-type-inference-overloaded.ets:31:13] diff --git a/ets2panda/test/runtime/ets/FixFunctionCall.ets b/ets2panda/test/runtime/ets/FixFunctionCall.ets new file mode 100644 index 0000000000..d33f420a54 --- /dev/null +++ b/ets2panda/test/runtime/ets/FixFunctionCall.ets @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export type AsyncCallback = (err: T, data: T) => void; + +function getBundleInfo(userId?: number):void {} +function getBundleInfo(callback: AsyncCallback): void { + callback(666, 66); +} + +getBundleInfo((err, data) => { + assertEQ(err, 666); + assertEQ(data, 66) +}); diff --git a/ets2panda/test/runtime/ets/recheck_test/recheck_test1.ets b/ets2panda/test/runtime/ets/recheck_test/recheck_test1.ets new file mode 100644 index 0000000000..6b983fabea --- /dev/null +++ b/ets2panda/test/runtime/ets/recheck_test/recheck_test1.ets @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* The test code is the lowering result of the code: + interface test { + testFoo: () => string; + } + + function ff(): string { + return "1111" + } + + class ExpectExtend { + public tst: test | null; + extendstst() { + const tst: test = { + testFoo : ff, + }; + this.tst = tst; + } +*/ + +function ff(): string { + return "1111"; +} + +interface test { + set testFoo(testFoo: (()=> string)) + get testFoo(): (()=> string) +} + +class ExpectExtend { + public tst: test; + public extendstst() { + const tst: test = { + testFoo: ff, + }; + (this).tst = tst; + } + public constructor(tst: test) { + this.tst = tst + } +} + +assertEQ(true, true); -- Gitee From 21c90b0e5f0fa300dc1ebc6b5cf62964a73adab9 Mon Sep 17 00:00:00 2001 From: Laszlo Lango Date: Thu, 3 Apr 2025 14:03:42 +0200 Subject: [PATCH 128/268] Fix soft keywords: instanceof, typeof Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBYNZP Change-Id: Icbc492c3f8d0cf64cbac8fadc1a9d29b563a0b91 Signed-off-by: Laszlo Lango --- ets2panda/lexer/scripts/keywords.yaml | 8 +++++--- ets2panda/parser/ETSparserExpressions.cpp | 8 +++++--- ets2panda/parser/expressionParser.cpp | 20 +++++++++---------- ets2panda/parser/parserImpl.h | 3 +-- .../test/ast/parser/ets/user_defined_14.ets | 5 +---- .../test/ast/parser/ets/user_defined_19.ets | 2 -- .../test/ast/parser/ets/user_defined_26.ets | 18 +++++++++++++++++ .../test/ast/parser/ets/user_defined_27.ets | 20 +++++++++++++++++++ 8 files changed, 60 insertions(+), 24 deletions(-) create mode 100644 ets2panda/test/ast/parser/ets/user_defined_26.ets create mode 100644 ets2panda/test/ast/parser/ets/user_defined_27.ets diff --git a/ets2panda/lexer/scripts/keywords.yaml b/ets2panda/lexer/scripts/keywords.yaml index ee78e7b0e3..bb6362567a 100644 --- a/ets2panda/lexer/scripts/keywords.yaml +++ b/ets2panda/lexer/scripts/keywords.yaml @@ -271,7 +271,8 @@ keywords: - name: 'instanceof' token: KEYW_INSTANCEOF - keyword: [as, js, ets, ts] + keyword: [as, js, ts] + keyword_like: [ets] flags: [binary] - name: 'int' @@ -466,8 +467,9 @@ keywords: - name: 'typeof' token: KEYW_TYPEOF - keyword: [js, ets, ts] - flags: [unary, reserved_type_name, definable_type_name] + keyword: [js, ts] + keyword_like: [ets] + flags: [unary] - name: 'u8' token: KEYW_U8 diff --git a/ets2panda/parser/ETSparserExpressions.cpp b/ets2panda/parser/ETSparserExpressions.cpp index 53117acfb4..56641ea031 100644 --- a/ets2panda/parser/ETSparserExpressions.cpp +++ b/ets2panda/parser/ETSparserExpressions.cpp @@ -125,6 +125,10 @@ ir::Expression *ETSParser::ParseUnaryOrPrefixUpdateExpression(ExpressionParseFla { auto tokenFlags = lexer::NextTokenFlags::NONE; lexer::TokenType operatorType = Lexer()->GetToken().Type(); + if (operatorType == lexer::TokenType::LITERAL_IDENT && + Lexer()->GetToken().KeywordType() == lexer::TokenType::KEYW_TYPEOF) { + operatorType = lexer::TokenType::KEYW_TYPEOF; + } switch (operatorType) { case lexer::TokenType::PUNCTUATOR_MINUS: @@ -161,8 +165,6 @@ ir::Expression *ETSParser::ParseUnaryOrPrefixUpdateExpression(ExpressionParseFla } } - lexer::SourcePosition end = argument->End(); - ir::Expression *returnExpr = nullptr; if (lexer::Token::IsUpdateToken(operatorType)) { returnExpr = AllocNode(argument, operatorType, true); @@ -174,7 +176,7 @@ ir::Expression *ETSParser::ParseUnaryOrPrefixUpdateExpression(ExpressionParseFla returnExpr = AllocNode(argument, operatorType); } - returnExpr->SetRange({start, end}); + returnExpr->SetRange({start, argument->End()}); return returnExpr; } diff --git a/ets2panda/parser/expressionParser.cpp b/ets2panda/parser/expressionParser.cpp index 4e33145164..a14402f5d8 100644 --- a/ets2panda/parser/expressionParser.cpp +++ b/ets2panda/parser/expressionParser.cpp @@ -592,12 +592,13 @@ ir::Expression *ParserImpl::ParseAssignmentExpression(ir::Expression *lhsExpress conditionalExpr->SetRange({lhsExpression->Start(), alternate->End()}); return conditionalExpr; } - case lexer::TokenType::PUNCTUATOR_ARROW: + case lexer::TokenType::PUNCTUATOR_ARROW: { if (lexer_->GetToken().NewLine()) { LogError(diagnostic::EXPECTED_EXPRESSION_GOT_ARROW); } return ParseArrowFunctionExpression(lhsExpression, nullptr, nullptr, false); + } case lexer::TokenType::PUNCTUATOR_SUBSTITUTION: { ValidateAssignmentTarget(flags, lhsExpression); @@ -605,12 +606,17 @@ ir::Expression *ParserImpl::ParseAssignmentExpression(ir::Expression *lhsExpress ir::Expression *assignmentExpression = ParseExpression(CarryPatternFlags(flags)); return CreateBinaryAssignmentExpression(assignmentExpression, lhsExpression, tokenType); } - case lexer::TokenType::KEYW_AS: + case lexer::TokenType::KEYW_AS: { if (auto asExpression = ParsePotentialAsExpression(lhsExpression); asExpression != nullptr) { return ParseAssignmentExpression(asExpression); } break; + } default: { + if (tokenType == lexer::TokenType::LITERAL_IDENT && + lexer_->GetToken().KeywordType() == lexer::TokenType::KEYW_INSTANCEOF) { + tokenType = lexer::TokenType::KEYW_INSTANCEOF; + } auto expression = ParseAssignmentBinaryExpression(tokenType, lhsExpression, flags); if (expression == nullptr) { expression = ParseAssignmentEqualExpression(tokenType, lhsExpression, flags); @@ -663,7 +669,7 @@ ir::Expression *ParserImpl::ParseAssignmentBinaryExpression(const lexer::TokenTy case lexer::TokenType::PUNCTUATOR_MOD: case lexer::TokenType::KEYW_INSTANCEOF: case lexer::TokenType::PUNCTUATOR_EXPONENTIATION: { - return ParseAssignmentExpression(ParseBinaryExpression(lhsExpression)); + return ParseAssignmentExpression(ParseBinaryExpression(lhsExpression, tokenType)); } default: break; @@ -1295,9 +1301,8 @@ static ir::Expression *FindAndAmendChildExpression(ir::Expression *expression, c return shouldBeAmended ? expression : parentExpression; } -ir::Expression *ParserImpl::ParseBinaryExpression(ir::Expression *left, ExpressionParseFlags flags) +ir::Expression *ParserImpl::ParseBinaryExpression(ir::Expression *left, const lexer::TokenType operatorType) { - lexer::TokenType operatorType = lexer_->GetToken().Type(); ES2PANDA_ASSERT(lexer::Token::IsBinaryToken(operatorType)); if (operatorType == lexer::TokenType::PUNCTUATOR_EXPONENTIATION) { @@ -1308,11 +1313,6 @@ ir::Expression *ParserImpl::ParseBinaryExpression(ir::Expression *left, Expressi lexer_->NextToken(); - ExpressionParseFlags newFlags = ExpressionParseFlags::DISALLOW_YIELD; - if ((operatorType == lexer::TokenType::KEYW_INSTANCEOF) || ((flags & ExpressionParseFlags::INSTANCEOF) != 0)) { - newFlags |= ExpressionParseFlags::INSTANCEOF; - } - ir::Expression *rightExpr = ParseExpressionOrTypeAnnotation(operatorType, ExpressionParseFlags::DISALLOW_YIELD); ir::ConditionalExpression *conditionalExpr = nullptr; if (rightExpr->IsConditionalExpression() && !rightExpr->IsGrouped()) { diff --git a/ets2panda/parser/parserImpl.h b/ets2panda/parser/parserImpl.h index 6ff5404d23..d64de90591 100644 --- a/ets2panda/parser/parserImpl.h +++ b/ets2panda/parser/parserImpl.h @@ -126,8 +126,7 @@ protected: // ExpressionParser.Cpp ir::Expression *ParseKeywordExpression(); - ir::Expression *ParseBinaryExpression(ir::Expression *left, - ExpressionParseFlags flags = ExpressionParseFlags::NO_OPTS); + ir::Expression *ParseBinaryExpression(ir::Expression *left, const lexer::TokenType operatorType); void ValidateUpdateExpression(ir::Expression *returnExpression, bool isChainExpression); ir::Expression *ParseMemberExpression(bool ignoreCallExpression = false, ExpressionParseFlags flags = ExpressionParseFlags::NO_OPTS); diff --git a/ets2panda/test/ast/parser/ets/user_defined_14.ets b/ets2panda/test/ast/parser/ets/user_defined_14.ets index 96e8945c06..a52c018c99 100644 --- a/ets2panda/test/ast/parser/ets/user_defined_14.ets +++ b/ets2panda/test/ast/parser/ets/user_defined_14.ets @@ -13,9 +13,6 @@ * limitations under the License. */ -class /* @@ label */typeof{ +class typeof{ a : string = "15"; } - -/* @@@ label Error SyntaxError: Cannot be used as user-defined type. */ -/* @@@ label Error SyntaxError: Identifier expected, got 'typeof'. */ diff --git a/ets2panda/test/ast/parser/ets/user_defined_19.ets b/ets2panda/test/ast/parser/ets/user_defined_19.ets index 2223fffb29..0da8937318 100644 --- a/ets2panda/test/ast/parser/ets/user_defined_19.ets +++ b/ets2panda/test/ast/parser/ets/user_defined_19.ets @@ -17,6 +17,4 @@ struct typeof{ a : string = "15"; } -/* @@? 16:8 Error SyntaxError: Cannot be used as user-defined type. */ -/* @@? 16:8 Error SyntaxError: Identifier expected, got 'typeof'. */ /* @@? 16:1 Error TypeError: Structs are only used to define UI components, it should be translated at 'plugin after parser' phase. */ diff --git a/ets2panda/test/ast/parser/ets/user_defined_26.ets b/ets2panda/test/ast/parser/ets/user_defined_26.ets new file mode 100644 index 0000000000..19aeb05f0b --- /dev/null +++ b/ets2panda/test/ast/parser/ets/user_defined_26.ets @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class instanceof{ + a : string = "15"; +} diff --git a/ets2panda/test/ast/parser/ets/user_defined_27.ets b/ets2panda/test/ast/parser/ets/user_defined_27.ets new file mode 100644 index 0000000000..73cfa2236b --- /dev/null +++ b/ets2panda/test/ast/parser/ets/user_defined_27.ets @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +struct instanceof{ + a : string = "15"; +} + +/* @@? 16:1 Error TypeError: Structs are only used to define UI components, it should be translated at 'plugin after parser' phase. */ -- Gitee From 2409f6dc241de20420903232e6050894c8a31411 Mon Sep 17 00:00:00 2001 From: Gabor Aron Takacs Date: Mon, 10 Mar 2025 11:52:32 +0100 Subject: [PATCH 129/268] Support tuple as rest parameter Fixes #22692 and #20774 internal issues. Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBW6FD Change-Id: Ibd7520701afeba1fc4714479da1476fe7b76a84d Signed-off-by: Gabor Aron Takacs --- ets2panda/BUILD.gn | 1 + ets2panda/CMakeLists.txt | 1 + ets2panda/checker/ets/function.cpp | 15 +- ets2panda/compiler/core/ETSCompiler.cpp | 4 +- .../lowering/ets/restTupleLowering.cpp | 335 ++++++++++++++++++ .../compiler/lowering/ets/restTupleLowering.h | 35 ++ ets2panda/compiler/lowering/phase.cpp | 5 + ets2panda/parser/ETSparser.cpp | 5 +- .../ets/FixedArray/MultipleParserErrors.ets | 10 +- .../ast/parser/ets/MultipleParserErrors.ets | 10 +- .../test/ast/parser/ets/rest_parameter_05.ets | 22 ++ .../test/ast/parser/ets/rest_parameter_06.ets | 22 ++ .../test/ast/parser/ets/rest_parameter_07.ets | 22 ++ .../test/ast/parser/ets/rest_parameter_08.ets | 28 ++ ets2panda/test/runtime/ets/RestTuple1.ets | 41 +++ ets2panda/test/runtime/ets/RestTuple2.ets | 45 +++ ets2panda/test/runtime/ets/RestTuple3.ets | 44 +++ ets2panda/test/runtime/ets/RestTuple4.ets | 45 +++ ets2panda/util/diagnostic/syntax.yaml | 4 +- 19 files changed, 672 insertions(+), 22 deletions(-) create mode 100644 ets2panda/compiler/lowering/ets/restTupleLowering.cpp create mode 100644 ets2panda/compiler/lowering/ets/restTupleLowering.h create mode 100644 ets2panda/test/ast/parser/ets/rest_parameter_05.ets create mode 100644 ets2panda/test/ast/parser/ets/rest_parameter_06.ets create mode 100644 ets2panda/test/ast/parser/ets/rest_parameter_07.ets create mode 100644 ets2panda/test/ast/parser/ets/rest_parameter_08.ets create mode 100644 ets2panda/test/runtime/ets/RestTuple1.ets create mode 100644 ets2panda/test/runtime/ets/RestTuple2.ets create mode 100644 ets2panda/test/runtime/ets/RestTuple3.ets create mode 100644 ets2panda/test/runtime/ets/RestTuple4.ets diff --git a/ets2panda/BUILD.gn b/ets2panda/BUILD.gn index 34b9c0abc5..0ec4b9be63 100644 --- a/ets2panda/BUILD.gn +++ b/ets2panda/BUILD.gn @@ -232,6 +232,7 @@ libes2panda_sources = [ "compiler/lowering/ets/partialExportClassGen.cpp", "compiler/lowering/ets/promiseVoid.cpp", "compiler/lowering/ets/recordLowering.cpp", + "compiler/lowering/ets/restTupleLowering.cpp", "compiler/lowering/ets/setJumpTarget.cpp", "compiler/lowering/ets/spreadLowering.cpp", "compiler/lowering/ets/stringComparison.cpp", diff --git a/ets2panda/CMakeLists.txt b/ets2panda/CMakeLists.txt index 6b8ea34844..d8edd6d041 100644 --- a/ets2panda/CMakeLists.txt +++ b/ets2panda/CMakeLists.txt @@ -262,6 +262,7 @@ set(ES2PANDA_LIB_SRC compiler/lowering/ets/defaultParametersInConstructorLowering.cpp compiler/lowering/ets/defaultParametersLowering.cpp compiler/lowering/ets/lambdaLowering.cpp + compiler/lowering/ets/restTupleLowering.cpp compiler/lowering/ets/spreadLowering.cpp compiler/lowering/ets/localClassLowering.cpp compiler/lowering/ets/objectIndexAccess.cpp diff --git a/ets2panda/checker/ets/function.cpp b/ets2panda/checker/ets/function.cpp index 63f1e8aa74..1128c8aa1d 100644 --- a/ets2panda/checker/ets/function.cpp +++ b/ets2panda/checker/ets/function.cpp @@ -369,8 +369,6 @@ bool ETSChecker::IsValidRestArgument(ir::Expression *const argument, Signature * const auto argumentType = argument->Check(this); auto *targetType = substitutedSig->RestVar()->TsType(); if (targetType->IsETSTupleType()) { - // NOTE (mmartin): check tuple assignability for rest arguments - LogTypeError("Tuple types for rest arguments are not yet implemented", argument->Start()); return false; } @@ -388,12 +386,16 @@ bool ETSChecker::IsValidRestArgument(ir::Expression *const argument, Signature * } bool ETSChecker::ValidateSignatureRestParams(Signature *substitutedSig, const ArenaVector &arguments, - TypeRelationFlag flags, bool reportError, const bool unique) + TypeRelationFlag flags, bool reportError, + [[maybe_unused]] const bool unique) { size_t const argumentCount = arguments.size(); auto const commonArity = std::min(substitutedSig->ArgCount(), argumentCount); auto const restCount = argumentCount - commonArity; + if (argumentCount == commonArity && substitutedSig->RestVar()->TsType()->IsETSTupleType()) { + return false; + } for (size_t index = commonArity; index < argumentCount; ++index) { auto &argument = arguments[index]; @@ -415,7 +417,7 @@ bool ETSChecker::ValidateSignatureRestParams(Signature *substitutedSig, const Ar Type *targetType = substitutedSig->RestVar()->TsType(); // backing out of check that results in a signature mismatch would be difficult // so only attempt it if there is only one candidate signature - if (unique && restArgument->IsArrayExpression()) { + if (restArgument->IsArrayExpression()) { restArgument->AsArrayExpression()->SetPreferredType(targetType); } auto const argumentType = restArgument->Check(this); @@ -426,6 +428,9 @@ bool ETSChecker::ValidateSignatureRestParams(Signature *substitutedSig, const Ar substitutedSig->RestVar()->TsType(), "' at index ", index + 1}, flags); if (!invocationCtx.IsInvocable()) { + if (restArgument->IsArrayExpression()) { + ModifyPreferredType(restArgument->AsArrayExpression(), nullptr); + } return false; } } @@ -473,7 +478,7 @@ Signature *ETSChecker::ValidateSignature( } // Check rest parameter(s) if any exists - if (!hasRestParameter || count >= argCount) { + if (!hasRestParameter || (count >= argCount && !signature->RestVar()->TsType()->IsETSTupleType())) { return signature; } if (!ValidateSignatureRestParams(signature, arguments, flags, reportError, unique)) { diff --git a/ets2panda/compiler/core/ETSCompiler.cpp b/ets2panda/compiler/core/ETSCompiler.cpp index 273562d68e..6d35e72cd0 100644 --- a/ets2panda/compiler/core/ETSCompiler.cpp +++ b/ets2panda/compiler/core/ETSCompiler.cpp @@ -236,7 +236,7 @@ static void ConvertRestArguments(checker::ETSChecker *const checker, const ir::E if (i < argumentCount && expr->GetArguments()[i]->IsSpreadElement()) { arguments[i] = expr->GetArguments()[i]->AsSpreadElement()->Argument(); - } else { + } else if (!expr->GetSignature()->RestVar()->TsType()->IsETSTupleType()) { ArenaVector elements(checker->Allocator()->Adapter()); for (; i < argumentCount; ++i) { elements.emplace_back(expr->GetArguments()[i]); @@ -676,7 +676,7 @@ static void ConvertRestArguments(checker::ETSChecker *const checker, const ir::C } else if (i < argumentCount && expr->Arguments()[i]->IsTSAsExpression() && expr->Arguments()[i]->AsTSAsExpression()->Expr()->Type() == ir::AstNodeType::SPREAD_ELEMENT) { arguments[i] = expr->Arguments()[i]->AsTSAsExpression()->Expr()->AsSpreadElement()->Argument(); - } else { + } else if (!signature->RestVar()->TsType()->IsETSTupleType()) { ArenaVector elements(checker->Allocator()->Adapter()); for (; i < argumentCount; ++i) { elements.emplace_back(expr->Arguments()[i]); diff --git a/ets2panda/compiler/lowering/ets/restTupleLowering.cpp b/ets2panda/compiler/lowering/ets/restTupleLowering.cpp new file mode 100644 index 0000000000..3f323e94b6 --- /dev/null +++ b/ets2panda/compiler/lowering/ets/restTupleLowering.cpp @@ -0,0 +1,335 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "restTupleLowering.h" +#include "checker/ETSchecker.h" +#include "ir/base/scriptFunction.h" +#include "compiler/lowering/util.h" +#include "checker/types/type.h" +#include "varbinder/ETSBinder.h" +#include "varbinder/variable.h" +#include "compiler/lowering/scopesInit/scopesInitPhase.h" + +namespace ark::es2panda::compiler { + +using AstNodePtr = ir::AstNode *; + +bool MethodDefinitionHasRestTuple(const ir::AstNode *def) +{ + auto pred = [](const auto *param) { + return param->IsETSParameterExpression() && param->AsETSParameterExpression()->IsRestParameter() && + param->AsETSParameterExpression()->TypeAnnotation() && + param->AsETSParameterExpression()->TypeAnnotation()->IsETSTuple(); + }; + + bool isScriptFunction = def->IsMethodDefinition() && (def->AsMethodDefinition()->Value() != nullptr) && + def->AsMethodDefinition()->Value()->AsFunctionExpression()->Function()->IsScriptFunction(); + if (isScriptFunction) { + auto params = + def->AsMethodDefinition()->Value()->AsFunctionExpression()->Function()->AsScriptFunction()->Params(); + return std::any_of(params.begin(), params.end(), pred); + } + return false; +} + +bool IsClassDefinitionWithTupleRest(ir::AstNode *node) +{ + bool isClassDefinition = node->IsClassDefinition(); + if (isClassDefinition) { + auto definitions = node->AsClassDefinition()->Body(); + return std::any_of(definitions.begin(), definitions.end(), + [](const auto *def) { return MethodDefinitionHasRestTuple(def); }); + } + + return false; +} + +ir::Expression *CreateMemberOrThisExpression(public_lib::Context *ctx, ir::Expression *funcExpr, + ir::AstNode *definition) +{ + auto *checker = ctx->checker->AsETSChecker(); + auto *allocator = ctx->allocator; + + if (definition->IsConstructor()) { + return checker->AllocNode(); + } + + auto scriptFunc = funcExpr->AsFunctionExpression()->Function()->AsScriptFunction(); + + ir::Expression *ident = nullptr; + + if (definition->AsMethodDefinition()->IsStatic()) { + auto *parentClass = util::Helpers::FindAncestorGivenByType(definition, ir::AstNodeType::CLASS_DEFINITION); + ES2PANDA_ASSERT(parentClass != nullptr); + ident = parentClass->AsClassDefinition()->Ident()->AsIdentifier()->Clone(allocator, parentClass->Parent()); + } else { + ident = checker->AllocNode(); + } + + auto *newPropertyId = scriptFunc->Id()->Clone(allocator, nullptr); + auto *memberExpr = checker->AllocNode( + ident, newPropertyId, ir::MemberExpressionKind::PROPERTY_ACCESS, false, false); + newPropertyId->SetParent(memberExpr); + + return memberExpr; +} + +ir::CallExpression *CreateNewCallExpression(public_lib::Context *ctx, ir::Expression *funcExpr, ir::AstNode *definition, + ir::TSAsExpression *asExpression) +{ + auto *checker = ctx->checker->AsETSChecker(); + auto *allocator = ctx->allocator; + + ArenaVector callArguments({}, checker->Allocator()->Adapter()); + for (auto arg : funcExpr->AsFunctionExpression()->Function()->AsScriptFunction()->Params()) { + if (!arg->AsETSParameterExpression()->IsRestParameter()) { + auto *id = arg->AsETSParameterExpression()->Ident()->Clone(allocator, nullptr); + id->SetTsTypeAnnotation(nullptr); + callArguments.push_back(id); + } else { + auto spreadElement = + checker->AllocNode(ir::AstNodeType::SPREAD_ELEMENT, allocator, asExpression); + asExpression->SetParent(spreadElement); + callArguments.push_back(spreadElement); + } + } + + // Create member expression if method is not a constructor + ir::Expression *memberExpr = CreateMemberOrThisExpression(ctx, funcExpr, definition); + + auto *newCallExpr = checker->AllocNode(memberExpr, std::move(callArguments), nullptr, false); + + if (definition->IsConstructor()) { + memberExpr->SetParent(newCallExpr); + } + for (auto *arg : newCallExpr->Arguments()) { + arg->SetParent(newCallExpr); + } + + return newCallExpr; +} + +ArenaVector CreateFunctionRestParams(public_lib::Context *ctx, ir::AstNode *funcExpr) +{ + auto *checker = ctx->checker->AsETSChecker(); + auto *allocator = ctx->allocator; + + ArenaVector params {allocator->Adapter()}; + for (auto param : funcExpr->AsFunctionExpression()->Function()->AsScriptFunction()->Params()) { + if (param->AsETSParameterExpression()->IsRestParameter()) { + for (auto tupleTypeAnno : + param->AsETSParameterExpression()->TypeAnnotation()->AsETSTuple()->GetTupleTypeAnnotationsList()) { + ir::Identifier *id = Gensym(allocator); + auto *newParam = checker->AsETSChecker()->AllocNode(id, false, allocator); + auto newAnnotation = tupleTypeAnno->Clone(allocator, id); + id->SetParent(newParam); + id->SetTsTypeAnnotation(newAnnotation); + params.push_back(newParam); + } + } + } + return params; +} + +ArenaVector CreateFunctionNormalParams(public_lib::Context *ctx, ir::AstNode *funcExpr) +{ + auto *allocator = ctx->allocator; + + ArenaVector params {allocator->Adapter()}; + for (auto param : funcExpr->AsFunctionExpression()->Function()->AsScriptFunction()->Params()) { + if (!param->AsETSParameterExpression()->IsRestParameter()) { + auto newParam = param->AsETSParameterExpression()->Clone(allocator, nullptr); + params.push_back(newParam); + } + } + return params; +} + +ArenaVector MergeParams(public_lib::Context *ctx, + const ArenaVector &newNormalParams, + const ArenaVector &newRestParams) +{ + auto *allocator = ctx->allocator; + + ArenaVector params {allocator->Adapter()}; + for (auto newNormalParam : newNormalParams) { + params.push_back(newNormalParam); + } + for (auto newRestParam : newRestParams) { + params.push_back(newRestParam); + } + return params; +} + +ir::ArrayExpression *CreateArrayExpression(public_lib::Context *ctx, const ArenaVector &newRestParams) +{ + auto *checker = ctx->checker->AsETSChecker(); + auto *allocator = ctx->allocator; + + ArenaVector elementsInit(checker->Allocator()->Adapter()); + ArenaVector elements(checker->Allocator()->Adapter()); + + auto *arrayExpr = checker->AllocNode(std::move(elementsInit), checker->Allocator()); + for (auto tupleElementAnno : newRestParams) { + auto &tupleElementName = tupleElementAnno->AsETSParameterExpression()->Ident()->AsIdentifier()->Name(); + ir::Expression *arg = checker->AllocNode(tupleElementName, allocator); + arg->SetParent(arrayExpr); + elements.push_back(arg); + } + arrayExpr->SetElements(std::move(elements)); + return arrayExpr; +} + +ir::ScriptFunction *CreateNewScriptFunction(public_lib::Context *ctx, ir::ScriptFunction *scriptFunc, + ArenaVector newParams) +{ + auto *checker = ctx->checker->AsETSChecker(); + auto *allocator = ctx->allocator; + + ArenaVector statements(allocator->Adapter()); + auto *body = checker->AllocNode(allocator, std::move(statements)); + ir::TypeNode *newReturnTypeAnno = nullptr; + if (scriptFunc->ReturnTypeAnnotation() != nullptr) { + newReturnTypeAnno = scriptFunc->ReturnTypeAnnotation()->Clone(allocator, nullptr); + } + + auto *newScriptFunc = checker->AllocNode( + checker->Allocator(), + ir::ScriptFunction::ScriptFunctionData { + body, ir::FunctionSignature(scriptFunc->TypeParams(), std::move(newParams), newReturnTypeAnno), + scriptFunc->Flags()}); + newScriptFunc->AddModifier(scriptFunc->AsScriptFunction()->Modifiers()); + + if (newReturnTypeAnno != nullptr) { + newReturnTypeAnno->SetParent(newScriptFunc); + } + + for (auto param : newScriptFunc->AsScriptFunction()->Params()) { + param->SetParent(newScriptFunc); + } + + ir::Identifier *newScriptFuncId = scriptFunc->Id()->Clone(allocator, newScriptFunc); + newScriptFunc->SetIdent(newScriptFuncId); + + return newScriptFunc; +} + +ir::VariableDeclaration *CreateNewVariableDeclaration(public_lib::Context *ctx, ir::ETSParameterExpression *restParam, + ir::ArrayExpression *newTuple) +{ + auto *checker = ctx->checker->AsETSChecker(); + auto *allocator = ctx->allocator; + + util::StringView tupleIdentName = restParam->Ident()->Name(); + auto *newId = checker->AllocNode(tupleIdentName, allocator); + ir::TypeNode *typeAnnotation = restParam->TypeAnnotation()->Clone(allocator, newId); + newId->SetTsTypeAnnotation(typeAnnotation); + newTuple->SetParent(typeAnnotation); + + auto *const declarator = + checker->AllocNode(ir::VariableDeclaratorFlag::LET, newId, newTuple); + newId->SetParent(declarator); + ArenaVector declarators(checker->Allocator()->Adapter()); + declarators.push_back(declarator); + + auto *const declaration = checker->AllocNode( + ir::VariableDeclaration::VariableDeclarationKind::LET, checker->Allocator(), std::move(declarators)); + declarator->SetParent(declaration); + return declaration; +} + +ArenaVector CreateReturnOrExpressionStatement(public_lib::Context *ctx, ir::ScriptFunction *scriptFunc, + ir::CallExpression *callExpr) +{ + auto *checker = ctx->checker->AsETSChecker(); + + ArenaVector statements(checker->Allocator()->Adapter()); + + if (scriptFunc->ReturnTypeAnnotation() != nullptr) { + auto returnStatement = checker->AllocNode(callExpr); + statements.insert(statements.end(), returnStatement); + } else { + auto expressionStatement = checker->AllocNode(callExpr); + statements.insert(statements.end(), expressionStatement); + callExpr->SetParent(expressionStatement); + } + return statements; +} + +void CreateNewMethodDefinition(public_lib::Context *ctx, ir::AstNode *node) +{ + auto *checker = ctx->checker->AsETSChecker(); + auto *allocator = ctx->allocator; + + for (auto definition : node->AsClassDefinition()->Body()) { + if (definition->IsMethodDefinition() && MethodDefinitionHasRestTuple(definition->AsMethodDefinition())) { + auto funcExpr = definition->AsMethodDefinition()->Value(); + ir::ETSParameterExpression *restParam = funcExpr->AsFunctionExpression() + ->Function() + ->AsScriptFunction() + ->Params() + .back() + ->AsETSParameterExpression(); + ir::ScriptFunction *scriptFunc = funcExpr->AsFunctionExpression()->Function()->AsScriptFunction(); + + ArenaVector newNormalParams = CreateFunctionNormalParams(ctx, funcExpr); + ArenaVector newRestParams = CreateFunctionRestParams(ctx, funcExpr); + ArenaVector mergedParams = MergeParams(ctx, newNormalParams, newRestParams); + + ir::ScriptFunction *newScriptFunc = CreateNewScriptFunction(ctx, scriptFunc, mergedParams); + + ir::ArrayExpression *const newArrayExpr = CreateArrayExpression(ctx, newRestParams); + + ir::TypeNode *newTypeAnnotation = restParam->TypeAnnotation()->Clone(allocator, nullptr); + + auto *asExpression = checker->AllocNode(newArrayExpr, newTypeAnnotation, false); + + auto *callExpr = CreateNewCallExpression(ctx, funcExpr, definition, asExpression); + + ArenaVector statements = CreateReturnOrExpressionStatement(ctx, scriptFunc, callExpr); + + // Build new script function + newScriptFunc->AsScriptFunction()->Body()->AsBlockStatement()->SetStatements(std::move(statements)); + + // Build new functionExpression + auto *function = checker->AllocNode(newScriptFunc); + + newTypeAnnotation->SetParent(asExpression); + newArrayExpr->SetParent(asExpression); + function->SetParent(funcExpr->Parent()); + + // Build new methodDefinition + auto *const methodDef = definition->AsMethodDefinition()->Clone(allocator, definition->Parent()); + methodDef->SetValue(function); + + node->AsClassDefinition()->Body().push_back(methodDef); + } + } +} + +bool RestTupleConstructionPhase::PerformForModule(public_lib::Context *ctx, parser::Program *program) +{ + program->Ast()->TransformChildrenRecursively( + [ctx](ir::AstNode *const node) -> AstNodePtr { + if (IsClassDefinitionWithTupleRest(node)) { + CreateNewMethodDefinition(ctx, node); + } + return node; + }, + Name()); + return true; +} + +} // namespace ark::es2panda::compiler diff --git a/ets2panda/compiler/lowering/ets/restTupleLowering.h b/ets2panda/compiler/lowering/ets/restTupleLowering.h new file mode 100644 index 0000000000..f0641a0d13 --- /dev/null +++ b/ets2panda/compiler/lowering/ets/restTupleLowering.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ES2PANDA_COMPILER_LOWERING_REST_TUPLE_LOWERING_H +#define ES2PANDA_COMPILER_LOWERING_REST_TUPLE_LOWERING_H + +#include "compiler/lowering/phase.h" + +namespace ark::es2panda::compiler { + +class RestTupleConstructionPhase : public PhaseForBodies { +public: + std::string_view Name() const override + { + return "RestTupleConstructionPhase"; + } + + bool PerformForModule(public_lib::Context *ctx, parser::Program *program) override; +}; + +} // namespace ark::es2panda::compiler + +#endif diff --git a/ets2panda/compiler/lowering/phase.cpp b/ets2panda/compiler/lowering/phase.cpp index 6d153cc3e6..59834228e5 100644 --- a/ets2panda/compiler/lowering/phase.cpp +++ b/ets2panda/compiler/lowering/phase.cpp @@ -28,6 +28,7 @@ #include "compiler/lowering/ets/defaultParametersLowering.h" #include "compiler/lowering/ets/enumLowering.h" #include "compiler/lowering/ets/enumPostCheckLowering.h" +#include "compiler/lowering/ets/restTupleLowering.h" #include "compiler/lowering/ets/expandBrackets.h" #include "compiler/lowering/ets/expressionLambdaLowering.h" #include "compiler/lowering/ets/extensionAccessorLowering.h" @@ -78,6 +79,7 @@ static ConstStringToCharLowering g_constStringToCharLowering; static InterfacePropertyDeclarationsPhase g_interfacePropDeclPhase; // NOLINT(fuchsia-statically-constructed-objects) static EnumLoweringPhase g_enumLoweringPhase; static EnumPostCheckLoweringPhase g_enumPostCheckLoweringPhase; +static RestTupleConstructionPhase g_restTupleConstructionPhase; static SpreadConstructionPhase g_spreadConstructionPhase; static ExtensionAccessorPhase g_extensionAccessorPhase; static ExpressionLambdaConstructionPhase g_expressionLambdaConstructionPhase; @@ -124,6 +126,7 @@ static InitScopesPhaseJs g_initScopesPhaseJs; std::vector GetETSPhaseList() { // clang-format off + // NOLINTBEGIN return { &g_pluginsAfterParse, &g_stringConstantsLowering, @@ -133,6 +136,7 @@ std::vector GetETSPhaseList() &g_defaultParametersInConstructorLowering, &g_defaultParametersLowering, &g_ambientLowering, + &g_restTupleConstructionPhase, &g_initScopesPhaseEts, &g_optionalLowering, &g_promiseVoidInferencePhase, @@ -173,6 +177,7 @@ std::vector GetETSPhaseList() &g_genericBridgesLowering, &g_pluginsAfterLowerings, // pluginsAfterLowerings has to come at the very end, nothing should go after it }; + // NOLINTEND // clang-format on } diff --git a/ets2panda/parser/ETSparser.cpp b/ets2panda/parser/ETSparser.cpp index 8d27e8a06c..9dd83078e8 100644 --- a/ets2panda/parser/ETSparser.cpp +++ b/ets2panda/parser/ETSparser.cpp @@ -1420,9 +1420,8 @@ ir::Expression *ETSParser::ParseFunctionParameter() // and resolve "{key: string}" as function body, so skip invalid types SkipInvalidType(); } else if (paramIdent->IsRestElement() && !typeAnnotation->IsTSArrayType() && - !IsFixedArrayTypeNode(typeAnnotation)) { - // NOTE (mmartin): implement tuple types for rest parameters - LogError(diagnostic::ONLY_ARRAY_FOR_REST); + !IsFixedArrayTypeNode(typeAnnotation) && !typeAnnotation->IsETSTuple()) { + LogError(diagnostic::ONLY_ARRAY_OR_TUPLE_FOR_REST); } typeAnnotation->SetParent(paramIdent); paramIdent->SetTsTypeAnnotation(typeAnnotation); diff --git a/ets2panda/test/ast/parser/ets/FixedArray/MultipleParserErrors.ets b/ets2panda/test/ast/parser/ets/FixedArray/MultipleParserErrors.ets index c4f781e768..558fbe032a 100644 --- a/ets2panda/test/ast/parser/ets/FixedArray/MultipleParserErrors.ets +++ b/ets2panda/test/ast/parser/ets/FixedArray/MultipleParserErrors.ets @@ -170,9 +170,9 @@ function main(): void { /* @@? 28:29 Error TypeError: Native, Abstract and Declare methods cannot have body. */ /* @@? 34:14 Error SyntaxError: The modifier for a constructor should be limited to access modifiers (private, internal, protected, public), and 'native' modifiers. */ /* @@? 37:41 Error SyntaxError: Only 'throws' can be used with function types. */ -/* @@? 39:14 Error SyntaxError: Unexpected token, expected an identifier. */ /* @@? 39:14 Error SyntaxError: Parameter declaration should have an explicit type annotation. */ /* @@? 39:14 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 39:14 Error SyntaxError: Unexpected token, expected an identifier. */ /* @@? 39:24 Error SyntaxError: Unexpected token 'int'. */ /* @@? 39:24 Error TypeError: Unresolved reference int */ /* @@? 39:27 Error SyntaxError: Unexpected token ')'. */ @@ -205,8 +205,8 @@ function main(): void { /* @@? 52:12 Error TypeError: Unresolved reference q */ /* @@? 52:12 Error TypeError: All return statements in the function should be empty or have a value. */ /* @@? 52:23 Error TypeError: Unresolved reference p */ -/* @@? 55:26 Error SyntaxError: Rest parameter should be of an array type. */ -/* @@? 59:23 Error SyntaxError: Rest parameter should be of an array type. */ +/* @@? 55:26 Error SyntaxError: Rest parameter should be either array or tuple type. */ +/* @@? 59:23 Error SyntaxError: Rest parameter should be either array or tuple type. */ /* @@? 63:26 Error SyntaxError: Parameter declaration should have an explicit type annotation. */ /* @@? 67:7 Error TypeError: Variable 'A' has already been declared. */ /* @@? 68:3 Error SyntaxError: Unexpected token. A constructor, method, accessor, or property was expected. */ @@ -219,8 +219,8 @@ function main(): void { /* @@? 84:3 Error SyntaxError: Unexpected token. A constructor, method, accessor, or property was expected. */ /* @@? 92:7 Error TypeError: Variable 'A' has already been declared. */ /* @@? 93:3 Error SyntaxError: Unexpected token. A constructor, method, accessor, or property was expected. */ -/* @@? 103:25 Error SyntaxError: Rest parameter should be of an array type. */ -/* @@? 104:32 Error SyntaxError: Rest parameter should be of an array type. */ +/* @@? 103:25 Error SyntaxError: Rest parameter should be either array or tuple type. */ +/* @@? 104:32 Error SyntaxError: Rest parameter should be either array or tuple type. */ /* @@? 115:26 Error SyntaxError: Unexpected token 'case'. */ /* @@? 115:26 Error SyntaxError: Unexpected token 'case'. */ /* @@? 115:26 Error SyntaxError: Unexpected token, expected ',' or ')'. */ diff --git a/ets2panda/test/ast/parser/ets/MultipleParserErrors.ets b/ets2panda/test/ast/parser/ets/MultipleParserErrors.ets index dd1d47c018..7b052e2990 100644 --- a/ets2panda/test/ast/parser/ets/MultipleParserErrors.ets +++ b/ets2panda/test/ast/parser/ets/MultipleParserErrors.ets @@ -170,9 +170,9 @@ function main(): void { /* @@? 28:29 Error TypeError: Native, Abstract and Declare methods cannot have body. */ /* @@? 34:14 Error SyntaxError: The modifier for a constructor should be limited to access modifiers (private, internal, protected, public), and 'native' modifiers. */ /* @@? 37:41 Error SyntaxError: Only 'throws' can be used with function types. */ -/* @@? 39:14 Error SyntaxError: Unexpected token, expected an identifier. */ /* @@? 39:14 Error SyntaxError: Parameter declaration should have an explicit type annotation. */ /* @@? 39:14 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 39:14 Error SyntaxError: Unexpected token, expected an identifier. */ /* @@? 39:24 Error SyntaxError: Unexpected token 'int'. */ /* @@? 39:24 Error TypeError: Unresolved reference int */ /* @@? 39:27 Error SyntaxError: Unexpected token ')'. */ @@ -203,8 +203,8 @@ function main(): void { /* @@? 52:12 Error TypeError: Unresolved reference q */ /* @@? 52:12 Error TypeError: All return statements in the function should be empty or have a value. */ /* @@? 52:23 Error TypeError: Unresolved reference p */ -/* @@? 55:26 Error SyntaxError: Rest parameter should be of an array type. */ -/* @@? 59:23 Error SyntaxError: Rest parameter should be of an array type. */ +/* @@? 55:26 Error SyntaxError: Rest parameter should be either array or tuple type. */ +/* @@? 59:23 Error SyntaxError: Rest parameter should be either array or tuple type. */ /* @@? 63:26 Error SyntaxError: Parameter declaration should have an explicit type annotation. */ /* @@? 67:7 Error TypeError: Variable 'A' has already been declared. */ /* @@? 68:3 Error SyntaxError: Unexpected token. A constructor, method, accessor, or property was expected. */ @@ -217,8 +217,8 @@ function main(): void { /* @@? 84:3 Error SyntaxError: Unexpected token. A constructor, method, accessor, or property was expected. */ /* @@? 92:7 Error TypeError: Variable 'A' has already been declared. */ /* @@? 93:3 Error SyntaxError: Unexpected token. A constructor, method, accessor, or property was expected. */ -/* @@? 103:25 Error SyntaxError: Rest parameter should be of an array type. */ -/* @@? 104:32 Error SyntaxError: Rest parameter should be of an array type. */ +/* @@? 103:25 Error SyntaxError: Rest parameter should be either array or tuple type. */ +/* @@? 104:32 Error SyntaxError: Rest parameter should be either array or tuple type. */ /* @@? 115:26 Error SyntaxError: Unexpected token, expected an identifier. */ /* @@? 115:26 Error SyntaxError: Parameter declaration should have an explicit type annotation. */ /* @@? 115:26 Error SyntaxError: Unexpected token, expected ',' or ')'. */ diff --git a/ets2panda/test/ast/parser/ets/rest_parameter_05.ets b/ets2panda/test/ast/parser/ets/rest_parameter_05.ets new file mode 100644 index 0000000000..07cdd8b2df --- /dev/null +++ b/ets2panda/test/ast/parser/ets/rest_parameter_05.ets @@ -0,0 +1,22 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable low or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +function sum(...numbers: [number, number, number]): number { + return numbers[0] + numbers[1] + numbers[2] +} + +/* @@ label */sum() + +/* @@@ label Error TypeError: No matching call signature */ diff --git a/ets2panda/test/ast/parser/ets/rest_parameter_06.ets b/ets2panda/test/ast/parser/ets/rest_parameter_06.ets new file mode 100644 index 0000000000..969c4fc10f --- /dev/null +++ b/ets2panda/test/ast/parser/ets/rest_parameter_06.ets @@ -0,0 +1,22 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable low or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +function sum(...numbers: [number, number, number]): number { + return numbers[0] + numbers[1] + numbers[2] +} + +/* @@ label */sum(10, 20, 30, 40) + +/* @@@ label Error TypeError: No matching call signature for sum(int, int, int, int) */ diff --git a/ets2panda/test/ast/parser/ets/rest_parameter_07.ets b/ets2panda/test/ast/parser/ets/rest_parameter_07.ets new file mode 100644 index 0000000000..922f5eeac9 --- /dev/null +++ b/ets2panda/test/ast/parser/ets/rest_parameter_07.ets @@ -0,0 +1,22 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable low or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +function sum(...numbers: [number, number, number]): number { + return numbers[0] + numbers[1] + numbers[2] +} + +/* @@ label1 */sum(10, 20, /* @@ label2 */"one") + +/* @@@ label1 Error TypeError: No matching call signature for sum(int, int, "one") */ diff --git a/ets2panda/test/ast/parser/ets/rest_parameter_08.ets b/ets2panda/test/ast/parser/ets/rest_parameter_08.ets new file mode 100644 index 0000000000..9d88285846 --- /dev/null +++ b/ets2panda/test/ast/parser/ets/rest_parameter_08.ets @@ -0,0 +1,28 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable low or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +function sum(a: int, ...numbers: [number, number, number]): number { + return numbers[0] + numbers[1] + numbers[2] +} + +/* @@ label1 */sum() +/* @@ label2 */sum(11) +/* @@ label3 */sum(11,12,13) +/* @@ label4 */sum(11,12,13,15,16) + +/* @@@ label1 Error TypeError: No matching call signature */ +/* @@@ label2 Error TypeError: No matching call signature for sum(int) */ +/* @@@ label3 Error TypeError: No matching call signature for sum(int, int, int) */ +/* @@@ label4 Error TypeError: No matching call signature for sum(int, int, int, int, int) */ diff --git a/ets2panda/test/runtime/ets/RestTuple1.ets b/ets2panda/test/runtime/ets/RestTuple1.ets new file mode 100644 index 0000000000..a52a0ea36c --- /dev/null +++ b/ets2panda/test/runtime/ets/RestTuple1.ets @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +function sum(...numbers: [number, number, number]): number { + return numbers[0] + numbers[1] + numbers[2] +} + +function sum2(a: int, ...numbers: [number, number, number]): number { + return a + numbers[0] + numbers[1] + numbers[2] +} + +function main() { + let tuple : [number, number, number] = [30, 40, 50] + let res = sum(10, 20, 30) + let res2 = sum2(10, 20, 30, 40) + + let res3 = sum(...tuple) + let res4 = sum2(10, ...tuple) + + let res5 = sum(...([30, 40, 50] as [number, number, number])) + let res6 = sum2(10, ...([30, 40, 50] as [number, number, number])) + + assertEQ(res, 60) + assertEQ(res2, 100) + assertEQ(res3, 120) + assertEQ(res4, 130) + assertEQ(res5, 120) + assertEQ(res6, 130) +} diff --git a/ets2panda/test/runtime/ets/RestTuple2.ets b/ets2panda/test/runtime/ets/RestTuple2.ets new file mode 100644 index 0000000000..0cca1c9527 --- /dev/null +++ b/ets2panda/test/runtime/ets/RestTuple2.ets @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class A { + sum(...numbers: [number, number, number]): number { + return numbers[0] + numbers[1] + numbers[2] + } + + sum2(a: int, ...numbers: [number, number, number]): number { + return a + numbers[0] + numbers[1] + numbers[2] + } +} + +function main() { + let tuple : [number, number, number] = [30, 40, 50] + let a = new A() + + let res = a.sum(10, 20, 30) + let res2 = a.sum2(10, 20, 30, 40) + + let res3 = a.sum(...tuple) + let res4 = a.sum2(10, ...tuple) + + let res5 = a.sum(...([30, 40, 50] as [number, number, number])) + let res6 = a.sum2(10, ...([30, 40, 50] as [number, number, number])) + + assertEQ(res, 60) + assertEQ(res2, 100) + assertEQ(res3, 120) + assertEQ(res4, 130) + assertEQ(res5, 120) + assertEQ(res6, 130) +} diff --git a/ets2panda/test/runtime/ets/RestTuple3.ets b/ets2panda/test/runtime/ets/RestTuple3.ets new file mode 100644 index 0000000000..02bad1d566 --- /dev/null +++ b/ets2panda/test/runtime/ets/RestTuple3.ets @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class A { + static sum(...numbers: [number, number, number]): number { + return numbers[0] + numbers[1] + numbers[2] + } + + static sum2(a: int, ...numbers: [number, number, number]): number { + return a + numbers[0] + numbers[1] + numbers[2] + } +} + +function main() { + let tuple : [number, number, number] = [30, 40, 50] + + let res = A.sum(10, 20, 30) + let res2 = A.sum2(10, 20, 30, 40) + + let res3 = A.sum(...tuple) + let res4 = A.sum2(10, ...tuple) + + let res5 = A.sum(...([30, 40, 50] as [number, number, number])) + let res6 = A.sum2(10, ...([30, 40, 50] as [number, number, number])) + + assertEQ(res, 60) + assertEQ(res2, 100) + assertEQ(res3, 120) + assertEQ(res4, 130) + assertEQ(res5, 120) + assertEQ(res6, 130) +} diff --git a/ets2panda/test/runtime/ets/RestTuple4.ets b/ets2panda/test/runtime/ets/RestTuple4.ets new file mode 100644 index 0000000000..4a4f8e30d9 --- /dev/null +++ b/ets2panda/test/runtime/ets/RestTuple4.ets @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class A { + public field : number + constructor(...numbers: [number, number, number]) { + this.field = numbers[0] + numbers[1] + numbers[2] + } + + constructor(a: int, ...numbers: [number, number, number]) { + this.field = a + numbers[0] + numbers[1] + numbers[2] + } +} + +function main() { + let tuple : [number, number, number] = [30, 40, 50] + + let res : A = new A(10, 20, 30) + let res2 : A = new A(10, 20, 30, 40) + + let res3 : A = new A(...tuple) + let res4 : A = new A(10, ...tuple) + + let res5 : A = new A(...([30, 40, 50] as [number, number, number])) + let res6 : A = new A(10, ...([30, 40, 50] as [number, number, number])) + + assertEQ(res.field, 60) + assertEQ(res2.field, 100) + assertEQ(res3.field, 120) + assertEQ(res4.field, 130) + assertEQ(res5.field, 120) + assertEQ(res6.field, 130) +} diff --git a/ets2panda/util/diagnostic/syntax.yaml b/ets2panda/util/diagnostic/syntax.yaml index 421782b176..0cac3b2b88 100644 --- a/ets2panda/util/diagnostic/syntax.yaml +++ b/ets2panda/util/diagnostic/syntax.yaml @@ -780,9 +780,9 @@ syntax: id: 192 message: "Rest parameter cannot have the default value." -- name: ONLY_ARRAY_FOR_REST +- name: ONLY_ARRAY_OR_TUPLE_FOR_REST id: 193 - message: "Rest parameter should be of an array type." + message: "Rest parameter should be either array or tuple type." - name: EXPLICIT_PARAM_TYPE id: 194 -- Gitee From 5f5e6fd89bf39f9f44eb8fc04d3a11ea76a083d4 Mon Sep 17 00:00:00 2001 From: Martin Sajti Date: Fri, 14 Mar 2025 13:42:15 +0100 Subject: [PATCH 130/268] Change the runtime behaviour of tuple types Tuple types now will be a distinguishable type in the runtime. They were represented as arrays before, this patch change this to refer to their respective wrapper class in stdlib. Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBWTWO Internal issue: #22738 Test: build, runtime tests, cts tests Change-Id: If066c7e3e4b342eb395ac48ddad46fa299abd848 Signed-off-by: Martin Sajti --- ets2panda/BUILD.gn | 1 - ets2panda/CMakeLists.txt | 1 - ets2panda/checker/ETSAnalyzer.cpp | 257 +++++++-------- ets2panda/checker/ETSAnalyzerHelpers.cpp | 25 ++ ets2panda/checker/ETSAnalyzerHelpers.h | 2 + ets2panda/checker/ETSchecker.cpp | 25 +- ets2panda/checker/ETSchecker.h | 4 +- ets2panda/checker/ets/helpers.cpp | 27 +- ets2panda/checker/ets/object.cpp | 15 +- ets2panda/checker/ets/validateHelpers.cpp | 2 +- ets2panda/checker/types/ets/etsArrayType.cpp | 17 +- ets2panda/checker/types/ets/etsTupleType.cpp | 41 ++- ets2panda/checker/types/ets/etsTupleType.h | 52 +-- ets2panda/checker/types/ets/etsUnionType.cpp | 7 +- ets2panda/checker/types/globalTypesHolder.cpp | 29 ++ ets2panda/checker/types/globalTypesHolder.h | 24 ++ ets2panda/compiler/base/lreference.cpp | 17 +- ets2panda/compiler/core/ETSCompiler.cpp | 67 ++-- ets2panda/compiler/core/ETSCompiler.h | 2 + ets2panda/compiler/core/ETSGen.cpp | 119 ++----- ets2panda/compiler/core/ETSGen.h | 6 +- .../compiler/lowering/ets/spreadLowering.cpp | 104 +++++- .../compiler/lowering/ets/tupleLowering.cpp | 305 ------------------ ets2panda/compiler/lowering/phase.cpp | 9 +- ets2panda/compiler/scripts/signatures.yaml | 55 ++++ ets2panda/docs/lowering-phases.md | 12 - ets2panda/ir/ets/etsTuple.cpp | 14 +- ets2panda/ir/expressions/arrayExpression.cpp | 21 +- ets2panda/ir/expressions/memberExpression.cpp | 88 +++-- ets2panda/ir/expressions/memberExpression.h | 3 +- .../annotationDecl_bad_initializer08.ets | 8 +- .../annotationUsage_bad_param09.ets | 8 +- .../ets/FixedArray/tuple_types_1_neg.ets | 2 +- .../ets/FixedArray/tuple_types_9_neg.ets | 1 - .../annotationDecl_bad_initializer08.ets | 8 +- .../annotationUsage_bad_param09.ets | 8 +- .../ets/default_param_tuple_infer.ets} | 30 +- .../ets/tuple_generic_function_param.ets | 18 ++ .../ast/compiler/ets/tuple_types_1_neg.ets | 2 +- .../ast/compiler/ets/tuple_types_9_neg.ets | 3 +- .../ets/variance_typeparam_transmit.ets | 17 +- .../compiler/ets/variance_typeparam_tuple.ets | 23 +- .../Readonly-with-ArrayType-test2.ets | 4 +- .../Readonly-with-ArrayType-test3.ets | 2 +- .../readonly-parameter-test2.ets | 2 +- .../readonly-parameter-test5.ets | 4 +- ets2panda/test/runtime/ets/AliasTuple.ets | 2 +- .../function_param_tuple_array_expr_infer.ets | 25 ++ .../test/runtime/ets/tuple_types_runtime.ets | 11 +- ets2panda/util/diagnostic/semantic.yaml | 2 +- 50 files changed, 737 insertions(+), 794 deletions(-) delete mode 100644 ets2panda/compiler/lowering/ets/tupleLowering.cpp rename ets2panda/{compiler/lowering/ets/tupleLowering.h => test/ast/compiler/ets/default_param_tuple_infer.ets} (45%) create mode 100644 ets2panda/test/ast/compiler/ets/tuple_generic_function_param.ets create mode 100644 ets2panda/test/runtime/ets/function_param_tuple_array_expr_infer.ets diff --git a/ets2panda/BUILD.gn b/ets2panda/BUILD.gn index 0ec4b9be63..7542df6a82 100644 --- a/ets2panda/BUILD.gn +++ b/ets2panda/BUILD.gn @@ -242,7 +242,6 @@ libes2panda_sources = [ "compiler/lowering/ets/topLevelStmts/globalDeclTransformer.cpp", "compiler/lowering/ets/topLevelStmts/importExportDecls.cpp", "compiler/lowering/ets/topLevelStmts/topLevelStmts.cpp", - "compiler/lowering/ets/tupleLowering.cpp", "compiler/lowering/ets/unionLowering.cpp", "compiler/lowering/phase.cpp", "compiler/lowering/plugin_phase.cpp", diff --git a/ets2panda/CMakeLists.txt b/ets2panda/CMakeLists.txt index d8edd6d041..57b60df30b 100644 --- a/ets2panda/CMakeLists.txt +++ b/ets2panda/CMakeLists.txt @@ -274,7 +274,6 @@ set(ES2PANDA_LIB_SRC compiler/lowering/ets/bigintLowering.cpp compiler/lowering/ets/constStringToCharLowering.cpp compiler/lowering/ets/recordLowering.cpp - compiler/lowering/ets/tupleLowering.cpp compiler/lowering/ets/unionLowering.cpp compiler/lowering/ets/optionalArgumentsLowering.cpp compiler/lowering/ets/optionalLowering.cpp diff --git a/ets2panda/checker/ETSAnalyzer.cpp b/ets2panda/checker/ETSAnalyzer.cpp index ecb6af26f9..a1e8265d06 100644 --- a/ets2panda/checker/ETSAnalyzer.cpp +++ b/ets2panda/checker/ETSAnalyzer.cpp @@ -278,22 +278,27 @@ checker::Type *ETSAnalyzer::Check([[maybe_unused]] ir::Property *expr) const checker::Type *ETSAnalyzer::Check(ir::SpreadElement *expr) const { + if (expr->TsType() != nullptr) { + return expr->TsType(); + } + ETSChecker *checker = GetETSChecker(); Type *exprType = expr->AsSpreadElement()->Argument()->Check(checker); if (exprType->IsETSResizableArrayType()) { return expr->SetTsType(exprType->AsETSObjectType()->TypeArguments().front()); } + if (!exprType->IsETSArrayType() && !exprType->IsETSTupleType()) { if (!exprType->IsTypeError()) { // Don't duplicate error messages for the same error checker->LogError(diagnostic::SPREAD_OF_INVALID_TYPE, {exprType}, expr->Start()); } - return expr->SetTsType(checker->GlobalTypeError()); + return checker->InvalidateType(expr); } - checker::Type *const elementType = exprType->IsETSTupleType() ? exprType->AsETSTupleType()->GetLubType() - : exprType->AsETSArrayType()->ElementType(); + checker::Type *const elementType = + exprType->IsETSArrayType() ? exprType->AsETSArrayType()->ElementType() : exprType; return expr->SetTsType(elementType); } @@ -611,104 +616,68 @@ checker::Type *ETSAnalyzer::GetPreferredType(ir::ArrayExpression *expr) const return expr->preferredType_; } -struct ArrayTargetTypes { - checker::Type *arrayType; - checker::Type *possibleTupleType; -}; - -static bool CheckArrayElementForTupleAssignment(ETSChecker *checker, checker::Type *elementType, - ArrayTargetTypes &targetElementTypes, - ir::Expression *const currentElement) +static void AddSpreadElementTypes(ETSChecker *checker, ir::SpreadElement *const element, + ArenaVector> &elementTypes) { - // NOTE (mmartin): Need to find out the semantics behind this function, and refactor it even more in the future or - // remove it - const bool isTargetArray = targetElementTypes.arrayType->IsETSArrayType(); - const bool arrayExpressionAssignedToArrayType = isTargetArray && currentElement->IsArrayExpression(); - const Type *const targetArrayElementType = - isTargetArray ? targetElementTypes.arrayType->AsETSArrayType()->ElementType() : nullptr; + Type *const spreadType = element->Check(checker); - const bool hasTupleTargetType = targetElementTypes.possibleTupleType != nullptr; - bool needElementTypecheck = (isTargetArray && targetArrayElementType->IsETSArrayType() && hasTupleTargetType); - if (!needElementTypecheck) { - needElementTypecheck = - !arrayExpressionAssignedToArrayType && - !checker::AssignmentContext(checker->Relation(), currentElement, elementType, targetElementTypes.arrayType, - currentElement->Start(), {}, TypeRelationFlag::NO_THROW) - .IsAssignable(); + if (spreadType->IsTypeError()) { + // error recovery + return; } - if (needElementTypecheck) { - auto *const targetType = - hasTupleTargetType ? targetElementTypes.possibleTupleType : targetElementTypes.arrayType; - - bool isNodeErroneous = !hasTupleTargetType; - if (hasTupleTargetType) { - isNodeErroneous = !arrayExpressionAssignedToArrayType && - !checker::AssignmentContext(checker->Relation(), currentElement, elementType, targetType, - currentElement->Start(), {}, TypeRelationFlag::NO_THROW) - .IsAssignable(); - } - - if (isNodeErroneous) { - checker->LogError(diagnostic::ARRAY_ELEMENT_UNASSIGNABLE, {elementType, targetType}, - currentElement->Start()); + Type *const spreadArgumentType = element->Argument()->TsType(); - return false; + if (spreadArgumentType->IsETSTupleType()) { + for (Type *type : spreadArgumentType->AsETSTupleType()->GetTupleTypesList()) { + elementTypes.emplace_back(type, element); } + } else if (spreadArgumentType->IsETSArrayType()) { + elementTypes.emplace_back(spreadArgumentType->AsETSArrayType()->ElementType(), element); + } else { + ES2PANDA_ASSERT(spreadArgumentType->IsETSResizableArrayType()); + elementTypes.emplace_back(spreadArgumentType->AsETSObjectType()->TypeArguments().front(), element); } - - return true; } -static bool AddSpreadElementTypes(ETSChecker *checker, ir::Expression *const element, - ArenaVector> &elementTypes, bool isPreferredTuple) +static bool ValidArrayExprSizeForTupleSize(ETSChecker *checker, Type *possibleTupleType, + ir::Expression *possibleArrayExpr) { - Type *elementType = element->Check(checker); - Type *argumentType = element->AsSpreadElement()->Argument()->Check(checker); - - if (argumentType->IsETSTupleType()) { - for (Type *type : argumentType->AsETSTupleType()->GetTupleTypesList()) { - elementTypes.emplace_back(type, element); - } + if (!possibleArrayExpr->IsArrayExpression() || !possibleTupleType->IsETSTupleType()) { return true; } - if (!argumentType->IsETSTupleType() && isPreferredTuple) { - checker->LogError(diagnostic::INVALID_SPREAD_IN_TUPLE, {argumentType}, element->Start()); - elementTypes.emplace_back(elementType, element); - return false; - } - - elementTypes.emplace_back(elementType, element); - return true; + return checker->IsArrayExprSizeValidForTuple(possibleArrayExpr->AsArrayExpression(), + possibleTupleType->AsETSTupleType()); } -static ArenaVector> GetElementTypes(ir::ArrayExpression *expr, ETSChecker *checker, - const bool isPreferredTuple, bool &checkResult) +static ArenaVector> GetElementTypes(ETSChecker *checker, ir::ArrayExpression *expr) { ArenaVector> elementTypes(checker->Allocator()->Adapter()); for (std::size_t idx = 0; idx < expr->Elements().size(); ++idx) { ir::Expression *const element = expr->Elements()[idx]; - if (element->IsArrayExpression() && - !expr->TrySetPreferredTypeForNestedArrayExpr(checker, element->AsArrayExpression(), idx)) { - elementTypes.emplace_back(checker->GlobalTypeError(), element); + if (element->IsSpreadElement()) { + AddSpreadElementTypes(checker, element->AsSpreadElement(), elementTypes); continue; } - if (element->IsSpreadElement()) { - if (!AddSpreadElementTypes(checker, element, elementTypes, isPreferredTuple)) { - checkResult = false; - } + auto *const exprPreferredType = expr->GetPreferredType(); + + if (expr->GetPreferredType()->IsETSTupleType() && + idx < expr->GetPreferredType()->AsETSTupleType()->GetTupleSize() && + !ValidArrayExprSizeForTupleSize(checker, exprPreferredType->AsETSTupleType()->GetTypeAtIndex(idx), + element)) { + elementTypes.emplace_back(checker->GlobalTypeError(), element); continue; } - if (element->IsObjectExpression()) { - auto *const exprPreferredType = expr->GetPreferredType(); - checker->SetPreferredTypeIfPossible(element, exprPreferredType->IsETSTupleType() - ? exprPreferredType->AsETSTupleType()->GetTypeAtIndex(idx) - : exprPreferredType->AsETSArrayType()->ElementType()); + if (element->IsArrayExpression() || element->IsObjectExpression()) { + auto *const targetPreferredType = exprPreferredType->IsETSTupleType() + ? exprPreferredType->AsETSTupleType()->GetTypeAtIndex(idx) + : exprPreferredType->AsETSArrayType()->ElementType(); + ETSChecker::SetPreferredTypeIfPossible(element, targetPreferredType); } elementTypes.emplace_back(element->Check(checker), element); @@ -717,9 +686,8 @@ static ArenaVector> GetElementTypes(ir::Arra return elementTypes; } -static bool CheckElement(ETSChecker *checker, const ir::ArrayExpression *const arrayExpr, - ArenaVector> arrayExprElementTypes, - ArrayTargetTypes &targetElementTypes, std::size_t idx) +static bool CheckElement(ETSChecker *checker, Type *const preferredType, + ArenaVector> arrayExprElementTypes, std::size_t idx) { auto [elementType, currentElement] = arrayExprElementTypes[idx]; @@ -727,8 +695,10 @@ static bool CheckElement(ETSChecker *checker, const ir::ArrayExpression *const a return true; } - if (!elementType->IsETSArrayType() && arrayExpr->GetPreferredType()->IsETSTupleType()) { - const auto *const tupleType = arrayExpr->GetPreferredType()->AsETSTupleType(); + Type *targetType = nullptr; + + if (preferredType->IsETSTupleType()) { + const auto *const tupleType = preferredType->AsETSTupleType(); if (tupleType->GetTupleSize() != arrayExprElementTypes.size()) { return false; } @@ -746,30 +716,74 @@ static bool CheckElement(ETSChecker *checker, const ir::ArrayExpression *const a return false; } - elementType = compareType; + const CastingContext castCtx( + checker->Relation(), {"this cast should never fail"}, + CastingContext::ConstructorData {currentElement, compareType, checker->MaybeBoxType(compareType), + currentElement->Start(), TypeRelationFlag::NO_THROW}); + + targetType = compareType; + } else { + targetType = preferredType->AsETSArrayType()->ElementType(); } - if (targetElementTypes.arrayType == elementType) { - return true; + auto ctx = AssignmentContext(checker->Relation(), currentElement, elementType, targetType, currentElement->Start(), + {}, TypeRelationFlag::NO_THROW); + if (!ctx.IsAssignable()) { + checker->LogError(diagnostic::ARRAY_ELEMENT_INIT_TYPE_INCOMPAT, {idx, elementType, targetType}, + currentElement->Start()); + return false; } - return CheckArrayElementForTupleAssignment(checker, elementType, targetElementTypes, currentElement); + return true; } -// CC-OFFNXT(huge_depth[C++]) solid logic -static bool CheckArrayExpressionElements(ir::ArrayExpression *arrayExpr, ETSChecker *checker, - ArrayTargetTypes &targetElementTypes, bool isPreferredTuple) +static ETSArrayType *InferPreferredTypeFromElements(ETSChecker *checker, ir::ArrayExpression *arrayExpr) { - bool checkResult = true; + ArenaVector arrayExpressionElementTypes(checker->Allocator()->Adapter()); + for (auto *const element : arrayExpr->Elements()) { + auto *elementType = *element->Check(checker); + if (element->IsSpreadElement() && elementType->IsETSTupleType()) { + for (auto *typeFromTuple : elementType->AsETSTupleType()->GetTupleTypesList()) { + arrayExpressionElementTypes.emplace_back(typeFromTuple); + } + + continue; + } - const ArenaVector> arrayExprElementTypes = - GetElementTypes(arrayExpr, checker, isPreferredTuple, checkResult); + if (element->IsSpreadElement() && elementType->IsETSArrayType()) { + elementType = elementType->AsETSArrayType()->ElementType(); + } + + arrayExpressionElementTypes.emplace_back(elementType); + } + + // NOTE (smartin): fix union type normalization. Currently for primitive types like a 'char | char' type, it will be + // normalized to 'Char'. However it shouldn't be boxed, and be kept as 'char'. For a quick fix, if all types are + // primitive, then after making the union type, explicitly unbox it. + if (std::all_of(arrayExpressionElementTypes.begin(), arrayExpressionElementTypes.end(), + [](Type *const typeOfElement) { return typeOfElement->IsETSPrimitiveType(); })) { + return checker->CreateETSArrayType(checker->GetNonConstantType( + checker->MaybeUnboxType(checker->CreateETSUnionType(std::move(arrayExpressionElementTypes))))); + } + + // NOTE (smartin): optimize element access on constant array expressions (note is here, because the constant value + // will be present on the type) + return checker->CreateETSArrayType( + checker->GetNonConstantType(checker->CreateETSUnionType(std::move(arrayExpressionElementTypes)))); +} + +static bool CheckArrayExpressionElements(ETSChecker *checker, ir::ArrayExpression *arrayExpr) +{ + const ArenaVector> arrayExprElementTypes = GetElementTypes(checker, arrayExpr); + + bool allElementsAssignable = !std::any_of(arrayExprElementTypes.begin(), arrayExprElementTypes.end(), + [](auto &pair) { return pair.first->IsTypeError(); }); for (std::size_t idx = 0; idx < arrayExprElementTypes.size(); ++idx) { - checkResult &= CheckElement(checker, arrayExpr, arrayExprElementTypes, targetElementTypes, idx); + allElementsAssignable &= CheckElement(checker, arrayExpr->GetPreferredType(), arrayExprElementTypes, idx); } - return checkResult; + return allElementsAssignable; } void ETSAnalyzer::GetUnionPreferredType(ir::ArrayExpression *expr) const @@ -806,38 +820,17 @@ checker::Type *ETSAnalyzer::Check(ir::ArrayExpression *expr) const } } - if (expr->GetPreferredType() != nullptr && !expr->GetPreferredType()->IsETSArrayType() && - !expr->GetPreferredType()->IsETSTupleType() && - !checker->Relation()->IsSupertypeOf(expr->preferredType_, checker->GlobalETSObjectType())) { - checker->LogError(diagnostic::UNEXPECTED_ARRAY, {expr->preferredType_}, expr->Start()); + if (!IsArrayExpressionValidInitializerForType(checker, expr->GetPreferredType())) { + checker->LogError(diagnostic::UNEXPECTED_ARRAY, {expr->GetPreferredType()}, expr->Start()); return checker->InvalidateType(expr); } if (!expr->Elements().empty()) { if (expr->GetPreferredType() == nullptr || expr->GetPreferredType() == checker->GlobalETSObjectType()) { - /* - * NOTE(SM): If elements has different types - * should calculated as union of types from each element, - * otherwise don't properly work with array from union type - */ - expr->SetPreferredType( - checker->CreateETSArrayType(checker->GetNonConstantType(expr->Elements().front()->Check(checker)))); + expr->SetPreferredType(InferPreferredTypeFromElements(checker, expr)); } - auto *const preferredType = expr->GetPreferredType(); - - // NOTE(aakmaev): Need to rework type inference of array literal (#19096 internal issue) - const bool isPreferredTuple = preferredType->IsETSTupleType(); - - Type *const arrayTargetElementType = - isPreferredTuple ? preferredType->AsETSTupleType()->GetLubType() - : checker->GetNonConstantType(preferredType->AsETSArrayType()->ElementType()); - - Type *const possibleTupleTargetType = - isPreferredTuple ? preferredType->AsETSTupleType()->GetLubType() : nullptr; - - ArrayTargetTypes targetElementTypes {arrayTargetElementType, possibleTupleTargetType}; - if (!CheckArrayExpressionElements(expr, checker, targetElementTypes, isPreferredTuple)) { + if (!CheckArrayExpressionElements(checker, expr)) { return checker->InvalidateType(expr); } } @@ -847,10 +840,13 @@ checker::Type *ETSAnalyzer::Check(ir::ArrayExpression *expr) const } expr->SetTsType(expr->GetPreferredType()); - const auto *const arrayType = expr->TsType()->IsETSTupleType() - ? expr->TsType()->AsETSTupleType()->GetHolderArrayType() - : expr->TsType()->AsETSArrayType(); - checker->CreateBuiltinArraySignature(arrayType, arrayType->Rank()); + + if (!expr->TsType()->IsETSTupleType()) { + ES2PANDA_ASSERT(expr->TsType()->IsETSArrayType()); + const auto *const arrayType = expr->TsType()->AsETSArrayType(); + checker->CreateBuiltinArraySignature(arrayType, arrayType->Rank()); + } + return expr->TsType(); } @@ -989,7 +985,7 @@ checker::Type *ETSAnalyzer::Check(ir::AssignmentExpression *const expr) const checker->WarnForEndlessLoopInGetterSetter(expr->Left()->AsMemberExpression()); } - auto const leftType = expr->Left()->Check(checker); + const auto leftType = expr->Left()->Check(checker); if (IsInvalidArrayMemberAssignment(expr, checker)) { expr->SetTsType(checker->GlobalTypeError()); @@ -1015,6 +1011,8 @@ checker::Type *ETSAnalyzer::Check(ir::AssignmentExpression *const expr) const return expr->SetTsType(leftType); } + CastPossibleTupleOnRHS(checker, expr); + checker::Type *smartType = rightType; if (!leftType->IsTypeError()) { if (auto ctx = checker::AssignmentContext( @@ -1330,9 +1328,6 @@ checker::Type *ETSAnalyzer::GetCallExpressionReturnType(ir::CallExpression *expr auto *const signature = expr->Signature(); if (signature->RestVar() != nullptr && signature->RestVar()->TsType()->IsETSArrayType()) { auto *elementType = signature->RestVar()->TsType()->AsETSArrayType()->ElementType(); - if (elementType->IsETSTupleType()) { - elementType = elementType->AsETSTupleType()->GetLubType(); - } auto *const arrayType = checker->CreateETSArrayType(elementType)->AsETSArrayType(); checker->CreateBuiltinArraySignature(arrayType, arrayType->Rank()); } @@ -1400,6 +1395,7 @@ checker::Type *ETSAnalyzer::Check(ir::CallExpression *expr) const } else { expr->SetUncheckedType(checker->GuaranteedTypeForUncheckedCallReturn(expr->Signature())); } + if (expr->UncheckedType() != nullptr) { ES2PANDA_ASSERT(expr->UncheckedType()->IsETSReferenceType()); checker->ComputeApparentType(returnType); @@ -1656,7 +1652,7 @@ checker::Type *ETSAnalyzer::CheckDynamic(ir::ObjectExpression *expr) const return expr->PreferredType(); } -static bool ValidatePreferredType(ir::ObjectExpression *expr, ETSChecker *checker) +static bool ValidatePreferredType(ETSChecker *checker, ir::ObjectExpression *expr) { auto preferredType = expr->PreferredType(); if (preferredType == nullptr) { @@ -1698,7 +1694,7 @@ checker::Type *ETSAnalyzer::Check(ir::ObjectExpression *expr) const return expr->TsType(); } - if (!ValidatePreferredType(expr, checker)) { + if (!ValidatePreferredType(checker, expr)) { expr->SetTsType(checker->GlobalTypeError()); return expr->TsType(); } @@ -2869,9 +2865,6 @@ checker::Type *ETSAnalyzer::Check(ir::TSArrayType *node) const node->SetTsType(node->GetType(checker)); const auto *arrayType = node->TsType()->AsETSArrayType(); - if (arrayType->IsETSTupleType()) { - arrayType = arrayType->AsETSTupleType()->GetHolderArrayType(); - } checker->CreateBuiltinArraySignature(arrayType, arrayType->Rank()); return node->TsType(); } @@ -2923,10 +2916,8 @@ checker::Type *ETSAnalyzer::Check(ir::TSAsExpression *expr) const // Make sure the array type symbol gets created for the assembler to be able to emit checkcast. // Because it might not exist, if this particular array type was never created explicitly. - if (!expr->isUncheckedCast_ && (targetType->IsETSArrayType() || targetType->IsETSTupleType())) { - const auto *const targetArrayType = targetType->IsETSTupleType() - ? targetType->AsETSTupleType()->GetHolderArrayType() - : targetType->AsETSArrayType(); + if (!expr->isUncheckedCast_ && targetType->IsETSArrayType()) { + const auto *const targetArrayType = targetType->AsETSArrayType(); checker->CreateBuiltinArraySignature(targetArrayType, targetArrayType->Rank()); } diff --git a/ets2panda/checker/ETSAnalyzerHelpers.cpp b/ets2panda/checker/ETSAnalyzerHelpers.cpp index 83e9dc2a44..fd362f6f4a 100644 --- a/ets2panda/checker/ETSAnalyzerHelpers.cpp +++ b/ets2panda/checker/ETSAnalyzerHelpers.cpp @@ -711,6 +711,31 @@ void InferReturnType(ETSChecker *checker, ir::ScriptFunction *containingFunc, ch } } +bool IsArrayExpressionValidInitializerForType(ETSChecker *checker, const Type *const arrayExprPreferredType) +{ + const auto validForTarget = arrayExprPreferredType == nullptr // preferred type will be inferred from elements + || arrayExprPreferredType->IsETSArrayType() // valid for array type + || arrayExprPreferredType->IsETSTupleType() // valid for tuple type + || checker->Relation()->IsSupertypeOf(arrayExprPreferredType, // valid for 'Object' + checker->GlobalETSObjectType()); + + return validForTarget; +} + +void CastPossibleTupleOnRHS(ETSChecker *checker, ir::AssignmentExpression *expr) +{ + if (expr->Left()->IsMemberExpression() && + expr->Left()->AsMemberExpression()->Object()->TsType()->IsETSTupleType() && + expr->OperatorType() == lexer::TokenType::PUNCTUATOR_SUBSTITUTION) { + auto *storedTupleType = expr->Left()->AsMemberExpression()->Object()->TsType(); + + const checker::CastingContext tupleCast( + checker->Relation(), {"this cast should never fail"}, + checker::CastingContext::ConstructorData {expr->Right(), expr->Right()->TsType(), storedTupleType, + expr->Right()->Start(), TypeRelationFlag::NO_THROW}); + } +} + void ProcessReturnStatements(ETSChecker *checker, ir::ScriptFunction *containingFunc, checker::Type *&funcReturnType, ir::ReturnStatement *st, ir::Expression *stArgument) { diff --git a/ets2panda/checker/ETSAnalyzerHelpers.h b/ets2panda/checker/ETSAnalyzerHelpers.h index 708af01086..23b7493cd3 100644 --- a/ets2panda/checker/ETSAnalyzerHelpers.h +++ b/ets2panda/checker/ETSAnalyzerHelpers.h @@ -58,6 +58,8 @@ bool CheckReturnType(ETSChecker *checker, checker::Type *funcReturnType, checker ir::Expression *stArgument, ir::ScriptFunction *containingFunc); void InferReturnType(ETSChecker *checker, ir::ScriptFunction *containingFunc, checker::Type *&funcReturnType, ir::Expression *stArgument); +bool IsArrayExpressionValidInitializerForType(ETSChecker *checker, const Type *arrayExprPreferredType); +void CastPossibleTupleOnRHS(ETSChecker *checker, ir::AssignmentExpression *expr); void ProcessReturnStatements(ETSChecker *checker, ir::ScriptFunction *containingFunc, checker::Type *&funcReturnType, ir::ReturnStatement *st, ir::Expression *stArgument); bool CheckReturnTypeNecessity(ir::MethodDefinition *node); diff --git a/ets2panda/checker/ETSchecker.cpp b/ets2panda/checker/ETSchecker.cpp index 4beac88821..3bb826b613 100644 --- a/ets2panda/checker/ETSchecker.cpp +++ b/ets2panda/checker/ETSchecker.cpp @@ -151,6 +151,7 @@ static constexpr std::string_view BUILTINS_TO_INIT[] = { compiler::Signatures::BUILTIN_FUNCTIONR14_CLASS, compiler::Signatures::BUILTIN_FUNCTIONR15_CLASS, compiler::Signatures::BUILTIN_FUNCTIONR16_CLASS, + compiler::Signatures::BUILTIN_FUNCTIONN_CLASS, compiler::Signatures::BUILTIN_LAMBDAR0_CLASS, compiler::Signatures::BUILTIN_LAMBDAR1_CLASS, compiler::Signatures::BUILTIN_LAMBDAR2_CLASS, @@ -168,8 +169,25 @@ static constexpr std::string_view BUILTINS_TO_INIT[] = { compiler::Signatures::BUILTIN_LAMBDAR14_CLASS, compiler::Signatures::BUILTIN_LAMBDAR15_CLASS, compiler::Signatures::BUILTIN_LAMBDAR16_CLASS, - compiler::Signatures::BUILTIN_FUNCTIONN_CLASS, compiler::Signatures::BUILTIN_LAMBDAN_CLASS, + compiler::Signatures::BUILTIN_TUPLE0_CLASS, + compiler::Signatures::BUILTIN_TUPLE1_CLASS, + compiler::Signatures::BUILTIN_TUPLE2_CLASS, + compiler::Signatures::BUILTIN_TUPLE3_CLASS, + compiler::Signatures::BUILTIN_TUPLE4_CLASS, + compiler::Signatures::BUILTIN_TUPLE5_CLASS, + compiler::Signatures::BUILTIN_TUPLE6_CLASS, + compiler::Signatures::BUILTIN_TUPLE7_CLASS, + compiler::Signatures::BUILTIN_TUPLE8_CLASS, + compiler::Signatures::BUILTIN_TUPLE9_CLASS, + compiler::Signatures::BUILTIN_TUPLE10_CLASS, + compiler::Signatures::BUILTIN_TUPLE11_CLASS, + compiler::Signatures::BUILTIN_TUPLE12_CLASS, + compiler::Signatures::BUILTIN_TUPLE13_CLASS, + compiler::Signatures::BUILTIN_TUPLE14_CLASS, + compiler::Signatures::BUILTIN_TUPLE15_CLASS, + compiler::Signatures::BUILTIN_TUPLE16_CLASS, + compiler::Signatures::BUILTIN_TUPLEN_CLASS, }; // clang-format on @@ -508,6 +526,11 @@ ETSObjectType *ETSChecker::GlobalBuiltinLambdaType(size_t nargs, bool hasRest) c return AsETSObjectType(&GlobalTypesHolder::GlobalLambdaBuiltinType, nargs, hasRest); } +ETSObjectType *ETSChecker::GlobalBuiltinTupleType(size_t nargs) const +{ + return AsETSObjectType(&GlobalTypesHolder::GlobalTupleBuiltinType, nargs); +} + size_t ETSChecker::GlobalBuiltinFunctionTypeVariadicThreshold() const { return GetGlobalTypesHolder()->VariadicFunctionTypeThreshold(); diff --git a/ets2panda/checker/ETSchecker.h b/ets2panda/checker/ETSchecker.h index 42cac90ac1..42c4a3e529 100644 --- a/ets2panda/checker/ETSchecker.h +++ b/ets2panda/checker/ETSchecker.h @@ -144,6 +144,8 @@ public: ETSObjectType *GlobalBuiltinLambdaType(size_t nargs, bool hasRest) const; size_t GlobalBuiltinFunctionTypeVariadicThreshold() const; + ETSObjectType *GlobalBuiltinTupleType(size_t nargs) const; + ETSObjectType *GlobalBuiltinDynamicType(Language lang) const; GlobalArraySignatureMap &GlobalArrayTypes(); @@ -190,7 +192,7 @@ public: void ResolveDeclaredMembersOfObject(const Type *type); std::optional GetTupleElementAccessValue(const Type *type); bool ValidateArrayIndex(ir::Expression *expr, bool relaxed = false); - bool ValidateTupleIndex(const ETSTupleType *tuple, ir::MemberExpression *expr); + bool ValidateTupleIndex(const ETSTupleType *tuple, ir::MemberExpression *expr, bool reportError = true); bool ValidateTupleIndexFromEtsObject(const ETSTupleType *const tuple, ir::MemberExpression *expr); ETSObjectType *CheckThisOrSuperAccess(ir::Expression *node, ETSObjectType *classType, std::string_view msg); void CreateTypeForClassOrInterfaceTypeParameters(ETSObjectType *type); diff --git a/ets2panda/checker/ets/helpers.cpp b/ets2panda/checker/ets/helpers.cpp index 0ecd59533b..b9e2439a12 100644 --- a/ets2panda/checker/ets/helpers.cpp +++ b/ets2panda/checker/ets/helpers.cpp @@ -524,12 +524,25 @@ void ETSChecker::ResolveReturnStatement(checker::Type *funcReturnType, checker:: checker::Type *ETSChecker::CheckArrayElements(ir::ArrayExpression *init) { ArenaVector elementTypes(Allocator()->Adapter()); - for (auto e : init->AsArrayExpression()->Elements()) { - Type *eType = e->Check(this); - if (eType->HasTypeFlag(TypeFlag::TYPE_ERROR)) { - return eType; + for (auto *elementNode : init->AsArrayExpression()->Elements()) { + Type *elementType = elementNode->Check(this); + if (elementType->IsTypeError()) { + return elementType; } - elementTypes.push_back(GetNonConstantType(eType)); + + if (elementNode->IsSpreadElement() && elementType->IsETSTupleType()) { + for (auto *typeFromTuple : elementType->AsETSTupleType()->GetTupleTypesList()) { + elementTypes.emplace_back(typeFromTuple); + } + + continue; + } + + if (elementNode->IsSpreadElement() && elementType->IsETSArrayType()) { + elementType = elementType->AsETSArrayType()->ElementType(); + } + + elementTypes.push_back(GetNonConstantType(elementType)); } if (elementTypes.empty()) { @@ -538,13 +551,13 @@ checker::Type *ETSChecker::CheckArrayElements(ir::ArrayExpression *init) } auto const isNumeric = [](checker::Type *ct) { return ct->HasTypeFlag(TypeFlag::ETS_CONVERTIBLE_TO_NUMERIC); }; auto const isChar = [](checker::Type *ct) { return ct->HasTypeFlag(TypeFlag::CHAR); }; - auto const elementType = + auto *const arrayElementType = std::all_of(elementTypes.begin(), elementTypes.end(), isNumeric) ? std::all_of(elementTypes.begin(), elementTypes.end(), isChar) ? GlobalCharType() : GlobalDoubleType() : CreateETSUnionType(std::move(elementTypes)); // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) - return Allocator()->New(elementType); + return Allocator()->New(arrayElementType); } void ETSChecker::InferAliasLambdaType(ir::TypeNode *localTypeAnnotation, ir::ArrowFunctionExpression *init) diff --git a/ets2panda/checker/ets/object.cpp b/ets2panda/checker/ets/object.cpp index 0c5bac9d03..ac0075b8ac 100644 --- a/ets2panda/checker/ets/object.cpp +++ b/ets2panda/checker/ets/object.cpp @@ -1530,7 +1530,8 @@ std::optional ETSChecker::GetTupleElementAccessValue(const Type *co } } -bool ETSChecker::ValidateTupleIndex(const ETSTupleType *const tuple, ir::MemberExpression *const expr) +bool ETSChecker::ValidateTupleIndex(const ETSTupleType *const tuple, ir::MemberExpression *const expr, + const bool reportError) { auto const expressionType = expr->Property()->Check(this); auto const *const unboxedExpressionType = MaybeUnboxInRelation(expressionType); @@ -1546,18 +1547,24 @@ bool ETSChecker::ValidateTupleIndex(const ETSTupleType *const tuple, ir::MemberE if (exprType->IsETSObjectType() && (unboxedExpressionType != nullptr)) { return ValidateTupleIndexFromEtsObject(tuple, expr); } - LogError(diagnostic::TUPLE_INDEX_NONCONST, {}, expr->Property()->Start()); + if (reportError) { + LogError(diagnostic::TUPLE_INDEX_NONCONST, {}, expr->Property()->Start()); + } return false; } if (!exprType->HasTypeFlag(TypeFlag::ETS_ARRAY_INDEX | TypeFlag::LONG)) { - LogError(diagnostic::TUPLE_INDEX_NOT_INT, {}, expr->Property()->Start()); + if (reportError) { + LogError(diagnostic::TUPLE_INDEX_NOT_INT, {}, expr->Property()->Start()); + } return false; } auto exprValue = GetTupleElementAccessValue(exprType); if (!exprValue.has_value() || (*exprValue >= tuple->GetTupleSize())) { - LogError(diagnostic::TUPLE_INDEX_OOB, {}, expr->Property()->Start()); + if (reportError) { + LogError(diagnostic::TUPLE_INDEX_OOB, {}, expr->Property()->Start()); + } return false; } diff --git a/ets2panda/checker/ets/validateHelpers.cpp b/ets2panda/checker/ets/validateHelpers.cpp index 9ed7084e35..9f757c57a7 100644 --- a/ets2panda/checker/ets/validateHelpers.cpp +++ b/ets2panda/checker/ets/validateHelpers.cpp @@ -304,7 +304,7 @@ bool ETSChecker::IsArrayExprSizeValidForTuple(const ir::ArrayExpression *const a } if (size != tuple->GetTupleSize()) { - LogError(diagnostic::TUPLE_TOO_FEW_ELEMS, {size, tuple->GetTupleSize()}, arrayExpr->Start()); + LogError(diagnostic::TUPLE_WRONG_NUMBER_OF_ELEMS, {size, tuple->GetTupleSize()}, arrayExpr->Start()); return false; } diff --git a/ets2panda/checker/types/ets/etsArrayType.cpp b/ets2panda/checker/types/ets/etsArrayType.cpp index 5a52ef15c3..9325edf156 100644 --- a/ets2panda/checker/types/ets/etsArrayType.cpp +++ b/ets2panda/checker/types/ets/etsArrayType.cpp @@ -60,21 +60,10 @@ void ETSArrayType::ToDebugInfoType(std::stringstream &ss) const uint32_t ETSArrayType::Rank() const { - const auto arrayHasNestedLevels = [](const Type *const iter) { - if (!iter->IsETSArrayType() && !iter->IsETSTupleType()) { - return false; - } - - const auto *const nestedElementType = - iter->IsETSArrayType() ? iter->AsETSArrayType()->ElementType() : iter->AsETSTupleType()->GetLubType(); - - return nestedElementType != iter; - }; - uint32_t rank = 1; - auto *iter = element_; - while (arrayHasNestedLevels(iter)) { - iter = iter->IsETSArrayType() ? iter->AsETSArrayType()->ElementType() : iter->AsETSTupleType()->GetLubType(); + const auto *iter = element_; + while (iter->IsETSArrayType() && iter->AsETSArrayType()->ElementType() != iter) { + iter = iter->AsETSArrayType()->ElementType(); rank++; } diff --git a/ets2panda/checker/types/ets/etsTupleType.cpp b/ets2panda/checker/types/ets/etsTupleType.cpp index 60b2c20e27..fc5c9a9aec 100644 --- a/ets2panda/checker/types/ets/etsTupleType.cpp +++ b/ets2panda/checker/types/ets/etsTupleType.cpp @@ -41,22 +41,26 @@ void ETSTupleType::ToString(std::stringstream &ss, bool precise) const void ETSTupleType::ToAssemblerType(std::stringstream &ss) const { - GetHolderArrayType()->ToAssemblerType(ss); -} - -void ETSTupleType::ToAssemblerTypeWithRank(std::stringstream &ss) const -{ - GetHolderArrayType()->ToAssemblerTypeWithRank(ss); + wrapperType_->ToAssemblerType(ss); } void ETSTupleType::ToDebugInfoType(std::stringstream &ss) const { - GetHolderArrayType()->ToDebugInfoType(ss); -} + if (HasTypeFlag(TypeFlag::READONLY)) { + ss << "readonly "; + } -uint32_t ETSTupleType::Rank() const -{ - return GetHolderArrayType()->Rank(); + ss << "["; + + for (auto it = typeList_.begin(); it != typeList_.end(); it++) { + (*it)->ToDebugInfoType(ss); + + if (std::next(it) != typeList_.end()) { + ss << ", "; + } + } + + ss << "]"; } Type *ETSTupleType::GetTypeAtIndex(const TupleSizeType index) const @@ -130,9 +134,7 @@ Type *ETSTupleType::Substitute(TypeRelation *relation, const Substitution *subst newTypeList.emplace_back(tupleTypeListElement->Substitute(relation, substitution)); } - auto *newElementType = ir::ETSTuple::GetHolderTypeForTuple(checker, newTypeList); - auto *holderArrayType = checker->CreateETSArrayType(newElementType, HasTypeFlag(TypeFlag::READONLY)); - return checker->Allocator()->New(std::move(newTypeList), newElementType, holderArrayType); + return checker->Allocator()->New(checker, std::move(newTypeList)); } void ETSTupleType::IsSubtypeOf(TypeRelation *const relation, Type *target) @@ -145,8 +147,6 @@ void ETSTupleType::IsSubtypeOf(TypeRelation *const relation, Type *target) void ETSTupleType::Cast(TypeRelation *const relation, Type *const target) { - // NOTE(mmartin): Might be not the correct casting rules, as these aren't defined yet - if (!(target->IsETSTupleType() || target->IsETSArrayType())) { conversion::Forbidden(relation); return; @@ -194,11 +194,8 @@ void ETSTupleType::Cast(TypeRelation *const relation, Type *const target) Type *ETSTupleType::Instantiate([[maybe_unused]] ArenaAllocator *allocator, [[maybe_unused]] TypeRelation *relation, [[maybe_unused]] GlobalTypesHolder *globalTypes) { - auto *const instantiatedLubType = GetLubType()->Instantiate(allocator, relation, globalTypes); - auto *const instantiatedArrayType = - GetHolderArrayType()->Instantiate(allocator, relation, globalTypes)->AsETSArrayType(); - auto *const tupleType = - allocator->New(GetTupleTypesList(), instantiatedLubType, instantiatedArrayType); + auto *const checker = relation->GetChecker()->AsETSChecker(); + auto *const tupleType = allocator->New(checker, GetTupleTypesList()); tupleType->typeFlags_ = typeFlags_; return tupleType; } @@ -206,7 +203,7 @@ Type *ETSTupleType::Instantiate([[maybe_unused]] ArenaAllocator *allocator, [[ma void ETSTupleType::CheckVarianceRecursively(TypeRelation *relation, VarianceFlag varianceFlag) { for (auto const &ctype : typeList_) { - relation->CheckVarianceRecursively(ctype, relation->TransferVariant(varianceFlag, VarianceFlag::COVARIANT)); + relation->CheckVarianceRecursively(ctype, relation->TransferVariant(varianceFlag, VarianceFlag::INVARIANT)); } } diff --git a/ets2panda/checker/types/ets/etsTupleType.h b/ets2panda/checker/types/ets/etsTupleType.h index 73b85a888b..31aca83175 100644 --- a/ets2panda/checker/types/ets/etsTupleType.h +++ b/ets2panda/checker/types/ets/etsTupleType.h @@ -16,6 +16,7 @@ #ifndef ES2PANDA_COMPILER_CHECKER_TYPES_ETS_TUPLE_TYPE_H #define ES2PANDA_COMPILER_CHECKER_TYPES_ETS_TUPLE_TYPE_H +#include "checker/ETSchecker.h" #include "checker/types/type.h" namespace ark::es2panda::checker { @@ -24,49 +25,17 @@ class ETSTupleType : public Type { using TupleSizeType = std::size_t; public: - explicit ETSTupleType(ArenaAllocator *const allocator, Type *const lubType, ETSArrayType *const holderArrayType) - : Type(checker::TypeFlag::ETS_TUPLE), - typeList_(allocator->Adapter()), - lubType_(lubType), - holderArrayType_(holderArrayType) - { - typeFlags_ |= TypeFlag::ETS_TUPLE; - } - - explicit ETSTupleType(ArenaAllocator *const allocator, const TupleSizeType size, Type *const lubType, - ETSArrayType *const holderArrayType) - : Type(checker::TypeFlag::ETS_TUPLE), - typeList_(allocator->Adapter()), - lubType_(lubType), - holderArrayType_(holderArrayType), - size_(size) - { - typeFlags_ |= TypeFlag::ETS_TUPLE; - } - - explicit ETSTupleType(const ArenaVector &typeList, Type *const lubType, ETSArrayType *const holderArrayType) + explicit ETSTupleType(ETSChecker *checker, const ArenaVector &typeList) : Type(checker::TypeFlag::ETS_TUPLE), typeList_(typeList), - lubType_(lubType), - holderArrayType_(holderArrayType), - size_(typeList.size()) + wrapperType_(checker->GlobalBuiltinTupleType(typeList_.size())->AsETSObjectType()) { typeFlags_ |= TypeFlag::ETS_TUPLE; } - [[nodiscard]] Type *GetLubType() const - { - return lubType_; - } - [[nodiscard]] TupleSizeType GetTupleSize() const { - return size_; - } - - [[nodiscard]] ETSArrayType *GetHolderArrayType() const - { - return holderArrayType_; + return typeList_.size(); } [[nodiscard]] ArenaVector const &GetTupleTypesList() const @@ -79,6 +48,11 @@ public: return {false, false}; } + [[nodiscard]] ETSObjectType *GetWrapperType() const + { + return wrapperType_; + } + [[nodiscard]] Type *GetTypeAtIndex(TupleSizeType index) const; void ToString(std::stringstream &ss, bool precise) const override; @@ -93,15 +67,11 @@ public: void CheckVarianceRecursively(TypeRelation *relation, VarianceFlag varianceFlag) override; void ToAssemblerType(std::stringstream &ss) const override; - void ToAssemblerTypeWithRank(std::stringstream &ss) const override; void ToDebugInfoType(std::stringstream &ss) const override; - uint32_t Rank() const override; private: - ArenaVector const typeList_; - Type *const lubType_ {}; - ETSArrayType *const holderArrayType_ {}; - TupleSizeType size_ {0}; + const ArenaVector typeList_; + ETSObjectType *wrapperType_; }; } // namespace ark::es2panda::checker diff --git a/ets2panda/checker/types/ets/etsUnionType.cpp b/ets2panda/checker/types/ets/etsUnionType.cpp index 9d9ef30ac6..fc29b8b98b 100644 --- a/ets2panda/checker/types/ets/etsUnionType.cpp +++ b/ets2panda/checker/types/ets/etsUnionType.cpp @@ -140,7 +140,12 @@ void ETSUnionType::RelationTarget(TypeRelation *relation, Type *source, RelFN co if (std::any_of(constituentTypes_.begin(), constituentTypes_.end(), [relation, refsource, relFn](auto *t) { return relFn(relation, refsource, t); })) { if (refsource != source) { - relation->GetNode()->SetBoxingUnboxingFlags(checker->GetBoxingFlag(refsource)); + // Some nodes can have both boxing and unboxing flags set. When applying them, first the unboxing happens + // (then a possible primitive conversion), and boxing at last. + // NOTE (smartin): when boxing/unboxing is moved to a lowering, review this part of the code + const auto mergedBoxingFlags = + relation->GetNode()->GetBoxingUnboxingFlags() | checker->GetBoxingFlag(refsource); + relation->GetNode()->SetBoxingUnboxingFlags(mergedBoxingFlags); } relation->Result(true); return; diff --git a/ets2panda/checker/types/globalTypesHolder.cpp b/ets2panda/checker/types/globalTypesHolder.cpp index 841df6f076..2644c1b719 100644 --- a/ets2panda/checker/types/globalTypesHolder.cpp +++ b/ets2panda/checker/types/globalTypesHolder.cpp @@ -86,6 +86,19 @@ void GlobalTypesHolder::AddFunctionTypes(ArenaAllocator *allocator) builtinNameMappings_.emplace("LambdaN", GlobalTypeId::ETS_FUNCTIONN_CLASS); } +void GlobalTypesHolder::AddTupleTypes(ArenaAllocator *allocator) +{ + auto addTypes = [this, allocator](const std::string &name, GlobalTypeId from, GlobalTypeId to) { + for (size_t id = static_cast(from), nargs = 0; id <= static_cast(to); id++, nargs++) { + builtinNameMappings_.emplace(util::UString(name + std::to_string(nargs), allocator).View(), + static_cast(id)); + } + }; + + addTypes("Tuple", GlobalTypeId::ETS_TUPLE0_CLASS, GlobalTypeId::ETS_TUPLE16_CLASS); + builtinNameMappings_.emplace("TupleN", GlobalTypeId::ETS_TUPLEN_CLASS); +} + void GlobalTypesHolder::AddTSSpecificTypes(ArenaAllocator *allocator) { globalTypes_[static_cast(GlobalTypeId::NUMBER)] = allocator->New(); @@ -201,6 +214,9 @@ GlobalTypesHolder::GlobalTypesHolder(ArenaAllocator *allocator) // Function types AddFunctionTypes(allocator); + // Tuple types + AddTupleTypes(allocator); + // ETS interop js specific types builtinNameMappings_.emplace("JSRuntime", GlobalTypeId::ETS_INTEROP_JSRUNTIME_BUILTIN); builtinNameMappings_.emplace("JSValue", GlobalTypeId::ETS_INTEROP_JSVALUE_BUILTIN); @@ -665,6 +681,19 @@ Type *GlobalTypesHolder::GlobalLambdaBuiltinType(size_t nargs, bool hasRest) return globalTypes_.at(static_cast(GlobalTypeId::ETS_LAMBDAN_CLASS)); } +size_t GlobalTypesHolder::VariadicTupleTypeThreshold() +{ + return static_cast(GlobalTypeId::ETS_TUPLEN_CLASS) - static_cast(GlobalTypeId::ETS_TUPLE0_CLASS); +} + +Type *GlobalTypesHolder::GlobalTupleBuiltinType(size_t nargs) +{ + const auto tupleClassIdPos = nargs < VariadicTupleTypeThreshold() + ? static_cast(GlobalTypeId::ETS_TUPLE0_CLASS) + nargs + : static_cast(GlobalTypeId::ETS_TUPLEN_CLASS); + return globalTypes_.at(tupleClassIdPos); +} + Type *GlobalTypesHolder::GlobalTypeError() { return globalTypes_.at(static_cast(GlobalTypeId::TYPE_ERROR)); diff --git a/ets2panda/checker/types/globalTypesHolder.h b/ets2panda/checker/types/globalTypesHolder.h index 5d5344d99f..39a9a1319a 100644 --- a/ets2panda/checker/types/globalTypesHolder.h +++ b/ets2panda/checker/types/globalTypesHolder.h @@ -185,6 +185,25 @@ enum class GlobalTypeId : std::size_t { ETS_LAMBDAR15_CLASS, ETS_LAMBDAR16_CLASS, + ETS_TUPLE0_CLASS, + ETS_TUPLE1_CLASS, + ETS_TUPLE2_CLASS, + ETS_TUPLE3_CLASS, + ETS_TUPLE4_CLASS, + ETS_TUPLE5_CLASS, + ETS_TUPLE6_CLASS, + ETS_TUPLE7_CLASS, + ETS_TUPLE8_CLASS, + ETS_TUPLE9_CLASS, + ETS_TUPLE10_CLASS, + ETS_TUPLE11_CLASS, + ETS_TUPLE12_CLASS, + ETS_TUPLE13_CLASS, + ETS_TUPLE14_CLASS, + ETS_TUPLE15_CLASS, + ETS_TUPLE16_CLASS, + ETS_TUPLEN_CLASS, + TYPE_ERROR, COUNT, @@ -205,6 +224,7 @@ public: void AddEtsSpecificBuiltinTypes(); void AddTSSpecificTypes(ArenaAllocator *allocator); void AddFunctionTypes(ArenaAllocator *allocator); + void AddTupleTypes(ArenaAllocator *allocator); // TS specific types Type *GlobalNumberType(); @@ -292,6 +312,10 @@ public: Type *GlobalFunctionBuiltinType(size_t nargs, bool hasRest); Type *GlobalLambdaBuiltinType(size_t nargs, bool hasRest); + // Tuple types + Type *GlobalTupleBuiltinType(size_t nargs); + size_t VariadicTupleTypeThreshold(); + // ETS escompat layer Type *GlobalArrayBuiltinType(); Type *GlobalAssertionErrorBuiltinType(); diff --git a/ets2panda/compiler/base/lreference.cpp b/ets2panda/compiler/base/lreference.cpp index e51a2a0b39..2b0f685dd5 100644 --- a/ets2panda/compiler/base/lreference.cpp +++ b/ets2panda/compiler/base/lreference.cpp @@ -287,11 +287,16 @@ void ETSLReference::SetValueComputed(const ir::MemberExpression *memberExpr) con } if (objectType->IsETSTupleType()) { - etsg_->StoreTupleElement(Node(), baseReg_, propReg_, objectType->AsETSTupleType()->GetLubType()); - } else { - etsg_->StoreArrayElement(Node(), baseReg_, propReg_, - etsg_->GetVRegType(baseReg_)->AsETSArrayType()->ElementType()); + ES2PANDA_ASSERT(memberExpr->GetTupleIndexValue().has_value()); + + std::size_t indexValue = *memberExpr->GetTupleIndexValue(); + etsg_->StoreTupleElement(Node(), baseReg_, objectType->AsETSTupleType()->GetTypeAtIndex(indexValue), + indexValue); + return; } + + ES2PANDA_ASSERT(objectType->IsETSArrayType()); + etsg_->StoreArrayElement(Node(), baseReg_, propReg_, etsg_->GetVRegType(baseReg_)->AsETSArrayType()->ElementType()); } void ETSLReference::SetValueGetterSetter(const ir::MemberExpression *memberExpr) const @@ -318,9 +323,7 @@ void ETSLReference::SetValue() const } const auto *const memberExpr = Node()->AsMemberExpression(); - const auto *const memberExprTsType = memberExpr->Object()->TsType()->IsETSTupleType() - ? memberExpr->Object()->TsType()->AsETSTupleType()->GetLubType() - : memberExpr->TsType(); + const auto *const memberExprTsType = memberExpr->TsType(); if (!memberExpr->IsIgnoreBox()) { etsg_->ApplyConversion(Node(), memberExprTsType); diff --git a/ets2panda/compiler/core/ETSCompiler.cpp b/ets2panda/compiler/core/ETSCompiler.cpp index 6d35e72cd0..efe0fbb8cb 100644 --- a/ets2panda/compiler/core/ETSCompiler.cpp +++ b/ets2panda/compiler/core/ETSCompiler.cpp @@ -367,21 +367,29 @@ void ETSCompiler::Compile([[maybe_unused]] const ir::ETSWildcardType *node) cons ES2PANDA_UNREACHABLE(); } -void ETSCompiler::Compile(const ir::ArrayExpression *expr) const +void ETSCompiler::CompileTupleCreation(const ir::ArrayExpression *tupleInitializer) const +{ + ETSGen *etsg = GetETSGen(); + + etsg->InitObject(tupleInitializer, + tupleInitializer->TsType()->AsETSTupleType()->GetWrapperType()->ConstructSignatures().front(), + tupleInitializer->Elements()); + etsg->SetAccumulatorType(tupleInitializer->TsType()); +} + +void ETSCompiler::CompileArrayCreation(const ir::ArrayExpression *expr) const { ETSGen *etsg = GetETSGen(); - const compiler::RegScope rs(etsg); const auto arr = etsg->AllocReg(); const auto dim = etsg->AllocReg(); - const auto *const arrayExprType = - expr->TsType()->IsETSTupleType() ? expr->TsType()->AsETSTupleType()->GetHolderArrayType() : expr->TsType(); + const auto *const arrayExprType = expr->TsType(); const compiler::TargetTypeContext ttctx(etsg, etsg->Checker()->GlobalIntType()); etsg->LoadAccumulatorInt(expr, static_cast(expr->Elements().size())); etsg->StoreAccumulator(expr, dim); - etsg->NewArray(expr, arr, dim, arrayExprType); + etsg->NewArray(expr, arr, dim, expr->TsType()); const auto indexReg = etsg->AllocReg(); auto const *const elementType = arrayExprType->AsETSArrayType()->ElementType(); @@ -397,10 +405,8 @@ void ETSCompiler::Compile(const ir::ArrayExpression *expr) const if (expression->TsType()->IsETSArrayType()) { etsg->StoreArrayElement(expr, arr, indexReg, expression->TsType()); - } else if (expr->TsType()->IsETSTupleType()) { - etsg->StoreTupleElement(expr, arr, indexReg, expr->TsType()->AsETSTupleType()->GetLubType()); } else { - etsg->StoreArrayElement(expr, arr, indexReg, expr->TsType()->AsETSArrayType()->ElementType()); + etsg->StoreArrayElement(expr, arr, indexReg, arrayExprType->AsETSArrayType()->ElementType()); } } @@ -408,12 +414,24 @@ void ETSCompiler::Compile(const ir::ArrayExpression *expr) const ES2PANDA_ASSERT(etsg->Checker()->Relation()->IsIdenticalTo(etsg->GetAccumulatorType(), arrayExprType)); } +void ETSCompiler::Compile(const ir::ArrayExpression *expr) const +{ + ETSGen *etsg = GetETSGen(); + const compiler::RegScope rs(etsg); + + if (expr->TsType()->IsETSTupleType()) { + CompileTupleCreation(expr); + } else { + CompileArrayCreation(expr); + } +} + void ETSCompiler::Compile(const ir::AssignmentExpression *expr) const { ETSGen *etsg = GetETSGen(); // All other operations are handled in OpAssignmentLowering ES2PANDA_ASSERT(expr->OperatorType() == lexer::TokenType::PUNCTUATOR_SUBSTITUTION); - auto *const exprType = expr->TsType(); + const auto *const exprType = expr->TsType(); compiler::RegScope rs(etsg); auto lref = compiler::ETSLReference::Create(etsg, expr->Left(), false); @@ -863,6 +881,17 @@ void ETSCompiler::Compile(const ir::Identifier *expr) const etsg->SetAccumulatorType(smartType); } +static void LoadETSDynamicTypeFromMemberExpr(compiler::ETSGen *etsg, const ir::MemberExpression *expr, + compiler::VReg objReg) +{ + if (etsg->Checker()->AsETSChecker()->Relation()->IsSupertypeOf(etsg->Checker()->GlobalBuiltinETSStringType(), + expr->Property()->TsType())) { + etsg->LoadPropertyDynamic(expr, expr->TsType(), objReg, expr->Property()); + } else { + etsg->LoadElementDynamic(expr, objReg); + } +} + bool ETSCompiler::CompileComputed(compiler::ETSGen *etsg, const ir::MemberExpression *expr) { if (!expr->IsComputed()) { @@ -883,18 +912,16 @@ bool ETSCompiler::CompileComputed(compiler::ETSGen *etsg, const ir::MemberExpres auto ttctx = compiler::TargetTypeContext(etsg, expr->TsType()); - if (objectType->IsETSDynamicType()) { - if (etsg->Checker()->AsETSChecker()->Relation()->IsSupertypeOf(etsg->Checker()->GlobalBuiltinETSStringType(), - expr->Property()->TsType())) { - etsg->LoadPropertyDynamic(expr, expr->TsType(), objReg, expr->Property()); - } else { - etsg->LoadElementDynamic(expr, objReg); - } - } else if (objectType->IsETSArrayType()) { - etsg->LoadArrayElement(expr, objReg); + if (objectType->IsETSTupleType()) { + ES2PANDA_ASSERT(expr->GetTupleIndexValue().has_value()); + auto indexValue = *expr->GetTupleIndexValue(); + auto *tupleElementType = objectType->AsETSTupleType()->GetTypeAtIndex(indexValue); + etsg->LoadTupleElement(expr, objReg, tupleElementType, indexValue); + } else if (objectType->IsETSDynamicType()) { + LoadETSDynamicTypeFromMemberExpr(etsg, expr, objReg); } else { - ES2PANDA_ASSERT(objectType->IsETSTupleType()); - etsg->LoadTupleElement(expr, objReg); + ES2PANDA_ASSERT(objectType->IsETSArrayType()); + etsg->LoadArrayElement(expr, objReg); } etsg->GuardUncheckedType(expr, expr->UncheckedType(), expr->TsType()); diff --git a/ets2panda/compiler/core/ETSCompiler.h b/ets2panda/compiler/core/ETSCompiler.h index 466212c550..94cd1e8f35 100644 --- a/ets2panda/compiler/core/ETSCompiler.h +++ b/ets2panda/compiler/core/ETSCompiler.h @@ -42,6 +42,8 @@ private: void EmitCall(const ir::CallExpression *expr, compiler::VReg &calleeReg, checker::Signature *signature) const; bool HandleArrayTypeLengthProperty(const ir::MemberExpression *expr, ETSGen *etsg) const; bool HandleStaticProperties(const ir::MemberExpression *expr, ETSGen *etsg) const; + void CompileArrayCreation(const ir::ArrayExpression *expr) const; + void CompileTupleCreation(const ir::ArrayExpression *tupleInitializer) const; static bool CompileComputed(compiler::ETSGen *etsg, const ir::MemberExpression *expr); diff --git a/ets2panda/compiler/core/ETSGen.cpp b/ets2panda/compiler/core/ETSGen.cpp index bd54574e12..30b7bcf5e1 100644 --- a/ets2panda/compiler/core/ETSGen.cpp +++ b/ets2panda/compiler/core/ETSGen.cpp @@ -833,7 +833,6 @@ void ETSGen::TestIsInstanceConstituent(const ir::AstNode *const node, std::tuple case checker::TypeFlag::ETS_ARRAY: case checker::TypeFlag::ETS_TUPLE: case checker::TypeFlag::FUNCTION: { - // NOTE (mmartin): remove tuple, after runtime representation has changed Sa().Emit(node, ToAssemblerType(target)); BranchIfTrue(node, ifTrue); break; @@ -3172,100 +3171,33 @@ void ETSGen::StoreArrayElement(const ir::AstNode *node, VReg objectReg, VReg ind SetAccumulatorType(elementType); } -void ETSGen::LoadTupleElement(const ir::AstNode *node, VReg objectReg) +util::StringView ETSGen::GetTupleMemberNameForIndex(const std::size_t index) const { - auto *elementType = GetVRegType(objectReg)->AsETSTupleType()->GetLubType(); - if (elementType->IsETSReferenceType()) { - Ra().Emit(node, objectReg); - SetAccumulatorType(elementType); - return; - } - switch (checker::ETSChecker::ETSType(elementType)) { - case checker::TypeFlag::ETS_BOOLEAN: - case checker::TypeFlag::BYTE: { - Ra().Emit(node, objectReg); - break; - } - case checker::TypeFlag::CHAR: { - Ra().Emit(node, objectReg); - break; - } - case checker::TypeFlag::SHORT: { - Ra().Emit(node, objectReg); - break; - } - case checker::TypeFlag::ETS_STRING_ENUM: - [[fallthrough]]; - case checker::TypeFlag::ETS_INT_ENUM: - case checker::TypeFlag::INT: { - Ra().Emit(node, objectReg); - break; - } - case checker::TypeFlag::LONG: { - Ra().Emit(node, objectReg); - break; - } - case checker::TypeFlag::FLOAT: { - Ra().Emit(node, objectReg); - break; - } - case checker::TypeFlag::DOUBLE: { - Ra().Emit(node, objectReg); - break; - } + return util::UString("$" + std::to_string(index), Allocator()).View(); +} - default: { - ES2PANDA_UNREACHABLE(); - } - } +void ETSGen::LoadTupleElement(const ir::AstNode *node, VReg objectReg, const checker::Type *elementType, + std::size_t index) +{ + ES2PANDA_ASSERT(GetVRegType(objectReg)->IsETSTupleType()); + const auto propName = FormClassPropReference(GetVRegType(objectReg)->AsETSTupleType()->GetWrapperType(), + GetTupleMemberNameForIndex(index)); - SetAccumulatorType(elementType); + // NOTE (smartin): remove after generics without type erasure is possible + const auto *const boxedElementType = Checker()->MaybeBoxType(elementType); + LoadProperty(node, boxedElementType, objectReg, propName); } -void ETSGen::StoreTupleElement(const ir::AstNode *node, VReg objectReg, VReg index, const checker::Type *elementType) +void ETSGen::StoreTupleElement(const ir::AstNode *node, VReg objectReg, const checker::Type *elementType, + std::size_t index) { - if (elementType->IsETSReferenceType()) { - Ra().Emit(node, objectReg, index); - SetAccumulatorType(elementType); - return; - } - switch (checker::ETSChecker::ETSType(elementType)) { - case checker::TypeFlag::ETS_BOOLEAN: - case checker::TypeFlag::BYTE: { - Ra().Emit(node, objectReg, index); - break; - } - case checker::TypeFlag::CHAR: - case checker::TypeFlag::SHORT: { - Ra().Emit(node, objectReg, index); - break; - } - case checker::TypeFlag::ETS_STRING_ENUM: - [[fallthrough]]; - case checker::TypeFlag::ETS_INT_ENUM: - case checker::TypeFlag::INT: { - Ra().Emit(node, objectReg, index); - break; - } - case checker::TypeFlag::LONG: { - Ra().Emit(node, objectReg, index); - break; - } - case checker::TypeFlag::FLOAT: { - Ra().Emit(node, objectReg, index); - break; - } - case checker::TypeFlag::DOUBLE: { - Ra().Emit(node, objectReg, index); - break; - } - - default: { - ES2PANDA_UNREACHABLE(); - } - } + ES2PANDA_ASSERT(GetVRegType(objectReg)->IsETSTupleType()); + const auto *const tupleType = GetVRegType(objectReg)->AsETSTupleType(); + SetVRegType(objectReg, tupleType->GetWrapperType()); - SetAccumulatorType(elementType); + // NOTE (smartin): remove after generics without type erasure is possible + const auto *const boxedElementType = Checker()->MaybeBoxType(elementType); + StoreProperty(node, boxedElementType, objectReg, GetTupleMemberNameForIndex(index)); } template @@ -3449,10 +3381,13 @@ void ETSGen::SetAccumulatorTargetType(const ir::AstNode *node, checker::TypeFlag template void ETSGen::LoadAccumulatorNumber(const ir::AstNode *node, T number, checker::TypeFlag targetType) { - auto typeKind = targetType_ && (!targetType_->IsETSObjectType() && !targetType_->IsETSUnionType() && - !targetType_->IsETSArrayType() && !targetType_->IsETSTupleType()) - ? checker::ETSChecker::TypeKind(targetType_) - : targetType; + // NOTE (smartin): refactor this to do at a more appropriate place + const bool isContextTargetTypeValid = + targetType_ != nullptr && + (!targetType_->IsETSObjectType() && !targetType_->IsETSUnionType() && !targetType_->IsETSArrayType() && + !targetType_->IsETSTupleType() && !targetType_->IsETSTypeParameter()); + + auto typeKind = isContextTargetTypeValid ? checker::ETSChecker::TypeKind(targetType_) : targetType; SetAccumulatorTargetType(node, typeKind, number); diff --git a/ets2panda/compiler/core/ETSGen.h b/ets2panda/compiler/core/ETSGen.h index 02f2b0a348..5fe6373d75 100644 --- a/ets2panda/compiler/core/ETSGen.h +++ b/ets2panda/compiler/core/ETSGen.h @@ -234,8 +234,10 @@ public: void LoadArrayElement(const ir::AstNode *node, VReg objectReg); void StoreArrayElement(const ir::AstNode *node, VReg objectReg, VReg index, const checker::Type *elementType); - void LoadTupleElement(const ir::AstNode *node, VReg objectReg); - void StoreTupleElement(const ir::AstNode *node, VReg objectReg, VReg index, const checker::Type *elementType); + util::StringView GetTupleMemberNameForIndex(std::size_t index) const; + void LoadTupleElement(const ir::AstNode *node, VReg objectReg, const checker::Type *elementType, std::size_t index); + void StoreTupleElement(const ir::AstNode *node, VReg objectReg, const checker::Type *elementType, + std::size_t index); template void MoveImmediateToRegister(const ir::AstNode *node, VReg reg, const checker::TypeFlag valueType, T const value); diff --git a/ets2panda/compiler/lowering/ets/spreadLowering.cpp b/ets2panda/compiler/lowering/ets/spreadLowering.cpp index 50cbb454a6..e1f70d5e9e 100644 --- a/ets2panda/compiler/lowering/ets/spreadLowering.cpp +++ b/ets2panda/compiler/lowering/ets/spreadLowering.cpp @@ -65,7 +65,7 @@ ir::Identifier *CreateNewArrayLengthStatement(public_lib::Context *ctx, ir::Arra lengthString << "let @@I" << (argumentCount++) << " : int = " << normalElementCount << " + "; for (auto *const spaId : spreadArrayIds) { if (spaId->TsType() != nullptr && spaId->TsType()->IsETSTupleType()) { - lengthString << "(" << spaId->TsType()->AsETSTupleType()->GetTupleTypesList().size() << ") + "; + lengthString << "(" << spaId->TsType()->AsETSTupleType()->GetTupleSize() << ") + "; } else { lengthString << "(@@I" << (argumentCount++) << ".length as int) + "; nodesWaitingInsert.emplace_back(spaId->Clone(allocator, nullptr)); @@ -86,10 +86,7 @@ static ir::Identifier *CreateNewArrayDeclareStatement(public_lib::Context *ctx, auto *const allocator = ctx->allocator; auto *const parser = ctx->parser->AsETSParser(); ir::Identifier *newArrayId = Gensym(allocator); - checker::Type *arrayElementType = array->TsType()->IsETSArrayType() - ? array->TsType()->AsETSArrayType()->ElementType() - : array->TsType()->AsETSTupleType()->GetLubType(); - checker::Type *newArrayElementType = arrayElementType; + checker::Type *arrayElementType = array->TsType()->AsETSArrayType()->ElementType(); // NOTE: If arrayElementType is ETSUnionType(String|Int) or ETSObjectType(private constructor) or ..., we cannot // use "new Type[]" to declare an array, so we generate a new UnionType "arrayElementType|null" to solve @@ -99,21 +96,86 @@ static ir::Identifier *CreateNewArrayDeclareStatement(public_lib::Context *ctx, // But now cast Expression doesn't support built-in array (cast fatherType[] to sonType[]), so "newArrayName // as arrayType" should be added after cast Expression is implemented completely. // Related issue: #issue20162 - if (checker->IsReferenceType(arrayElementType)) { - newArrayElementType = checker->CreateETSUnionType({arrayElementType, checker->GlobalETSUndefinedType()}); + if (checker::ETSChecker::IsReferenceType(arrayElementType)) { + arrayElementType = checker->CreateETSUnionType({arrayElementType, checker->GlobalETSUndefinedType()}); } std::stringstream newArrayDeclareStr; - newArrayDeclareStr << "let @@I1: @@T2[] = new @@T3[@@I4];" << std::endl; + newArrayDeclareStr << "let @@I1: (@@T2)[] = new (@@T3)[@@I4];" << std::endl; ir::Statement *newArrayDeclareSt = parser->CreateFormattedStatement( - newArrayDeclareStr.str(), newArrayId->Clone(allocator, nullptr), newArrayElementType, newArrayElementType, + newArrayDeclareStr.str(), newArrayId->Clone(allocator, nullptr), arrayElementType, arrayElementType, newArrayLengthId->Clone(allocator, nullptr)); statements.emplace_back(newArrayDeclareSt); return newArrayId; } +static std::string GenerateNewTupleInitList(ArenaAllocator *allocator, ir::ArrayExpression *array, + std::vector &elementNodes) +{ + std::string tupleInitList {}; + + for (auto *element : array->Elements()) { + if (element->IsSpreadElement()) { + // Only a tuple type can be spread into a new tuple type + ES2PANDA_ASSERT(element->AsSpreadElement()->Argument()->TsType()->IsETSTupleType()); + auto *const argumentTupleType = element->AsSpreadElement()->Argument()->TsType()->AsETSTupleType(); + + // NOTE (smartin): make a distinct variable for the spread argument. Now if the argument is a function call + // (that returns a tuple), it'll run every time when inserted into the new initializer. It should however + // run once, and index the element from that result. + + for (std::size_t idx = 0; idx < argumentTupleType->GetTupleSize(); idx++) { + tupleInitList += + "@@E" + std::to_string(elementNodes.size() + 1) + "[" + std::to_string(idx) + "]" + ", "; + elementNodes.emplace_back(element->Clone(allocator, nullptr)->AsSpreadElement()->Argument()); + } + } else { + tupleInitList += "@@E" + std::to_string(elementNodes.size() + 1) + ", "; + elementNodes.emplace_back(element->Clone(allocator, nullptr)); + } + } + + tupleInitList.pop_back(); + return tupleInitList; +} + +static ir::Expression *GenerateTupleInitExpr(public_lib::Context *ctx, ir::ArrayExpression *array) +{ + auto *const parser = ctx->parser->AsETSParser(); + auto *const allocator = ctx->allocator; + + std::vector arrayExprElementNodes {}; + std::stringstream newTupleExpr; + + newTupleExpr << "["; + newTupleExpr << GenerateNewTupleInitList(allocator, array, arrayExprElementNodes); + newTupleExpr << "];"; + + return parser->CreateFormattedExpression(newTupleExpr.str(), arrayExprElementNodes); +} + +static ir::Identifier *CreateNewTupleDeclareStatement(public_lib::Context *ctx, ir::ArrayExpression *array, + ArenaVector &statements) +{ + auto *const allocator = ctx->allocator; + auto *const parser = ctx->parser->AsETSParser(); + ir::Identifier *newTupleId = Gensym(allocator); + checker::ETSTupleType *tupleType = array->TsType()->AsETSTupleType(); + + std::stringstream newArrayDeclareStr; + newArrayDeclareStr << "let @@I1: (@@T2) = (@@E3);" << std::endl; + + ir::Expression *tupleCreationExpr = GenerateTupleInitExpr(ctx, array); + + ir::Statement *newTupleInitStmt = parser->CreateFormattedStatement( + newArrayDeclareStr.str(), newTupleId->Clone(allocator, nullptr), tupleType, tupleCreationExpr); + statements.emplace_back(newTupleInitStmt); + + return newTupleId; +} + static ir::Statement *CreateSpreadArrIteratorStatement(public_lib::Context *ctx, ir::ArrayExpression *array, ir::Identifier *spreadArrIterator) { @@ -244,7 +306,7 @@ static void CreateNewArrayElementsAssignStatement(public_lib::Context *ctx, ir:: * ... * newArray; */ -static ir::BlockExpression *CreateLoweredExpression(public_lib::Context *ctx, ir::ArrayExpression *array) +static ir::BlockExpression *CreateLoweredExpressionForArray(public_lib::Context *ctx, ir::ArrayExpression *array) { auto *const checker = ctx->checker->AsETSChecker(); auto *const parser = ctx->parser->AsETSParser(); @@ -267,6 +329,23 @@ static ir::BlockExpression *CreateLoweredExpression(public_lib::Context *ctx, ir return checker->AllocNode(std::move(statements)); } +/* + * NOTE: Expand the SpreadExpr to BlockExpr, the rules as follows : + * let newTuple: typeOfNewTuple = new std.core.TupleN(normalExpr1, ..., normalExprN); + */ +static ir::BlockExpression *CreateLoweredExpressionForTuple(public_lib::Context *ctx, ir::ArrayExpression *array) +{ + auto *const checker = ctx->checker->AsETSChecker(); + auto *const parser = ctx->parser->AsETSParser(); + auto *const allocator = ctx->allocator; + + ArenaVector statements(allocator->Adapter()); + ir::Identifier *newTupleId = CreateNewTupleDeclareStatement(ctx, array, statements); + + statements.emplace_back(parser->CreateFormattedStatement("@@I1;", newTupleId->Clone(allocator, nullptr))); + return checker->AllocNode(std::move(statements)); +} + bool SpreadConstructionPhase::PerformForModule(public_lib::Context *ctx, parser::Program *program) { checker::ETSChecker *const checker = ctx->checker->AsETSChecker(); @@ -280,7 +359,10 @@ bool SpreadConstructionPhase::PerformForModule(public_lib::Context *ctx, parser: auto scopeCtx = varbinder::LexicalScope::Enter(checker->VarBinder(), NearestScope(node)); - ir::BlockExpression *blockExpression = CreateLoweredExpression(ctx, node->AsArrayExpression()); + const auto *const arrayExprType = node->AsArrayExpression()->TsType(); + ir::BlockExpression *blockExpression = + arrayExprType->IsETSArrayType() ? CreateLoweredExpressionForArray(ctx, node->AsArrayExpression()) + : CreateLoweredExpressionForTuple(ctx, node->AsArrayExpression()); blockExpression->SetParent(node->Parent()); // NOTE: this blockExpression is a kind of formatted-dummy code, which is invisible to users, diff --git a/ets2panda/compiler/lowering/ets/tupleLowering.cpp b/ets2panda/compiler/lowering/ets/tupleLowering.cpp deleted file mode 100644 index 90c1d4ed7c..0000000000 --- a/ets2panda/compiler/lowering/ets/tupleLowering.cpp +++ /dev/null @@ -1,305 +0,0 @@ -/** - * Copyright (c) 2023-2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "tupleLowering.h" - -#include "checker/ETSchecker.h" -#include "checker/types/ets/etsTupleType.h" -#include "compiler/lowering/util.h" -#include "ir/expressions/assignmentExpression.h" -#include "ir/expressions/identifier.h" -#include "ir/expressions/memberExpression.h" -#include "ir/expressions/sequenceExpression.h" -#include "ir/expressions/updateExpression.h" -#include "ir/opaqueTypeNode.h" -#include "ir/statements/blockStatement.h" -#include "ir/ts/tsAsExpression.h" - -namespace ark::es2panda::compiler { -class TupleUpdateConverter { -public: - TupleUpdateConverter(checker::ETSChecker *const checker, ir::UpdateExpression *const update) - : checker_(checker), update_(update) - { - } - - std::optional CheckUpdateArgument() - { - auto *const argument = update_->Argument(); - const bool isArgumentMemberExpression = argument->IsMemberExpression(); - auto *const argumentType = - isArgumentMemberExpression ? argument->AsMemberExpression()->Object()->TsType() : nullptr; - - if ((argumentType == nullptr) || (!argumentType->IsETSTupleType())) { - return std::nullopt; - } - return {argumentType}; - } - - checker::Type *SetArgumentType(checker::Type *const argumentType) - { - auto *const savedType = argument_->TsType(); - argument_->SetTsType(argumentType->AsETSTupleType()->GetLubType()); - return savedType; - } - - void ComputeTypes(checker::Type *const argumentType) - { - tupleTypeAtIdx_ = argumentType->AsETSTupleType()->GetTypeAtIndex( - // After the checker, we are guranteed that the index is correct. - *checker_->GetTupleElementAccessValue(argument_->AsMemberExpression()->Property()->TsType())); - - tupleElementTypeNode_ = checker_->AllocNode(argumentType->AsETSTupleType()->GetLubType(), - checker_->Allocator()); - tupleTypeAtIdxNode_ = checker_->AllocNode(tupleTypeAtIdx_, checker_->Allocator()); - } - - ArenaVector GenerateExpressions() - { - // Clone argument of update expression (conversion flag might be added to it, so we need to duplicate it to not - // make - // conversions on 'line 3', that belongs to 'line 1' ) - auto [memberExpr, argumentClone] = CloneArgument(argument_); - // -------------- - - // Generate temporary symbols - auto [gensym, tmpVar] = GenerateSymbol(tupleTypeAtIdx_); - auto [gensym2, tmpVar2] = GenerateSymbol(tupleTypeAtIdx_); - // -------------- - // make node: let gensym = tuple[n] as ; - auto *const gensymTsAs = checker_->AllocNode(argumentClone, tupleTypeAtIdxNode_, false); - auto *const tupleAsType = checker_->AllocNode( - gensym, gensymTsAs, lexer::TokenType::PUNCTUATOR_SUBSTITUTION); - // -------------- - - // make node: let gensym2 = (gensym)++; - auto *identClone = gensym->Clone(checker_->Allocator(), nullptr); - identClone->SetTsType(tmpVar->TsType()); - auto *gensymUpdate = - checker_->AllocNode(identClone, update_->OperatorType(), update_->IsPrefix()); - auto *const gensym2Assignment = checker_->AllocNode( - gensym2, gensymUpdate, lexer::TokenType::PUNCTUATOR_SUBSTITUTION); - // -------------- - - // make node: tuple[n] = (gensym as ) as ; - identClone = gensym->Clone(checker_->Allocator(), nullptr); - identClone->SetTsType(tmpVar->TsType()); - auto *gensymAs = checker_->AllocNode( - identClone, tupleTypeAtIdxNode_->Clone(checker_->Allocator(), nullptr), false); - auto *gensymAsTupleTypeAtIdx = checker_->AllocNode(gensymAs, tupleElementTypeNode_, false); - auto *const tupleAssignment = checker_->AllocNode( - argument_, gensymAsTupleTypeAtIdx, lexer::TokenType::PUNCTUATOR_SUBSTITUTION); - // -------------- - - // make node: gensym2 as ; - identClone = gensym2->Clone(checker_->Allocator(), nullptr); - identClone->SetTsType(tmpVar2->TsType()); - auto *const finalTupleNode = checker_->AllocNode( - identClone, tupleTypeAtIdxNode_->Clone(checker_->Allocator(), nullptr), false); - // -------------- - - // Construct sequence expression order - ArenaVector expressionList(checker_->Allocator()->Adapter()); - expressionList.push_back(tupleAsType); - expressionList.push_back(gensym2Assignment); - expressionList.push_back(tupleAssignment); - expressionList.push_back(finalTupleNode); - // -------------- - - return expressionList; - } - -private: - std::tuple GenerateSymbol(checker::Type *const type) const - { - auto *gensym = Gensym(checker_->Allocator()); - auto [variable, _] = NearestScope(update_)->AddDecl( - checker_->Allocator(), gensym->Name(), varbinder::VariableFlags::LOCAL); - gensym->SetVariable(variable); - variable->SetTsType(type); - gensym->SetTsType(type); - return std::make_tuple(gensym, variable->AsLocalVariable()); - } - - std::tuple CloneArgument( - ir::Expression *const argument) const - { - auto *const memberExpr = argument->AsMemberExpression(); - auto *const argumentClone = memberExpr->Clone(checker_->Allocator(), memberExpr->Parent()); - argumentClone->Object()->SetTsType(memberExpr->Object()->TsType()); - if (argumentClone->Object()->IsIdentifier()) { - argumentClone->Object()->AsIdentifier()->SetVariable(memberExpr->Object()->AsIdentifier()->Variable()); - } - argumentClone->Property()->SetTsType(memberExpr->Property()->TsType()); - if (argumentClone->Property()->IsIdentifier()) { - argumentClone->Property()->AsIdentifier()->SetVariable(memberExpr->Property()->AsIdentifier()->Variable()); - } - argumentClone->SetTsType(memberExpr->TsType()); - return std::make_tuple(memberExpr, argumentClone); - }; - - checker::ETSChecker *const checker_; - ir::UpdateExpression *const update_; - ir::Expression *const argument_ {nullptr}; - checker::Type *tupleTypeAtIdx_ {nullptr}; - ir::OpaqueTypeNode *tupleElementTypeNode_ {nullptr}; - ir::OpaqueTypeNode *tupleTypeAtIdxNode_ {nullptr}; -}; - -static ir::Expression *ConvertTupleUpdate(checker::ETSChecker *const checker, ir::UpdateExpression *const update) -{ - // Converts `tuple[n]++` to - // ``` - // let gensym = tuple[n] as ; // line 1 - // let gensym2 = (gensym)++; // line 2 - // tuple[n] = (gensym as ) as ; // line 3 - // gensym2 as ; // line 4 - // ``` - // Notes: - // --- - // Because we can modify only 1 expression in the lowering (we don't want to add statements to the enclosing block), - // the expressions will be in a wrapper SequenceExpression - // --- - // At line 3 the double as expression is needed. If we simply write `gensym as `, then a - // boxing flag may be put on the `gensym` identifier node. It'll be boxed in 'line 2' instead of 'line 3', which - // cause error. If we put another as expression inside (which won't do any conversion, because the type of `gensym` - // is already ), the boxing flag will be on the as expression, instead of the identifier, so - // the identifier node won't be unboxed at 'line 2'. - - auto converter = TupleUpdateConverter {checker, update}; - - // Check if argument of update expression is tuple - auto const argumentType = converter.CheckUpdateArgument(); - if (!argumentType) { - return update; - } - // -------------- - - // Set tuple type to Object (because we'll need implicit boxing) - auto *const savedType = converter.SetArgumentType(*argumentType); - // -------------- - - // Compute necessary types and OpaqueTypeNodes - converter.ComputeTypes(*argumentType); - // -------------- - - auto expressions = converter.GenerateExpressions(); - - // Check the new sequence expression - auto *const sequenceExpr = checker->AllocNode(std::move(expressions)); - sequenceExpr->SetParent(update->Parent()); - sequenceExpr->Check(checker); - // -------------- - - // Set back TsType of argument (not necessarily needed now, but there can be a phase later, that need to get the - // right type of it) - [[maybe_unused]] auto _ = converter.SetArgumentType(savedType); - // -------------- - - return sequenceExpr; -} - -static ir::AssignmentExpression *ConvertTupleAssignment(checker::ETSChecker *const checker, - ir::AssignmentExpression *const assignment) -{ - // Converts `tuple[n] = variable;` to - // `tuple[n] = ((variable as ) as )` - // This lowering is necessary to handle `an unboxing conversion followed by a widening primitive - // conversion`, eg. when `tuple[n]` has type of `int`, and assignment::right_ has type of `Short`. Because every - // type is stored as the LUB type in the tuple (which can be Object), then the following conversions need to be done - // for this case: Short->short->int->Int->Object which can't be made implicitly, hence lowering is needed - - // Check if the left side of an assignment expression is a tuple element access - auto *const left = assignment->Left(); - auto *const leftObjectType = left->AsMemberExpression()->Object()->TsType(); - - if ((leftObjectType == nullptr) || (!leftObjectType->IsETSTupleType())) { - return assignment; - } - // -------------- - - // Set tuple type to (because we may need implicit boxing) - auto *const savedLeftType = left->TsType(); - left->SetTsType(leftObjectType->AsETSTupleType()->GetLubType()); - // -------------- - - // Compute necessary types and OpaqueTypeNodes - auto *const elementTypeTypeNode = - checker->AllocNode(leftObjectType->AsETSTupleType()->GetLubType(), checker->Allocator()); - auto *const tupleTypeAtIdxTypeNode = checker->AllocNode(savedLeftType, checker->Allocator()); - // -------------- - - // make node: tuple[n] = ((variable as ) as ) - auto *const tsAsExpressionLeft = - checker->AllocNode(assignment->Right(), tupleTypeAtIdxTypeNode, false); - - auto *const tsAsExpression = checker->AllocNode(tsAsExpressionLeft, elementTypeTypeNode, false); - auto *const newAssignment = - checker->AllocNode(left, tsAsExpression, assignment->OperatorType()); - // -------------- - - // Check the new assignment - newAssignment->SetParent(assignment->Parent()); - newAssignment->Check(checker); - left->SetTsType(savedLeftType); - // -------------- - - return newAssignment; -} - -bool TupleLowering::PerformForModule(public_lib::Context *const ctx, parser::Program *const program) -{ - checker::ETSChecker *const checker = ctx->checker->AsETSChecker(); - - program->Ast()->TransformChildrenRecursively( - // CC-OFFNXT(G.FMT.14-CPP) project code style - [checker](ir::AstNode *const ast) -> ir::AstNode * { - // Check if node is an 'assignment expression', with a member expression on the left (potentially tuple) - if (ast->IsAssignmentExpression() && ast->AsAssignmentExpression()->Left()->IsMemberExpression()) { - return ConvertTupleAssignment(checker, ast->AsAssignmentExpression()); - } - - // Check if node is an 'update expression', with a member expression as an argument (potentially tuple) - if (ast->IsUpdateExpression() && ast->AsUpdateExpression()->Argument()->IsMemberExpression()) { - return ConvertTupleUpdate(checker, ast->AsUpdateExpression()); - } - - return ast; - }, - Name()); - - return true; -} - -bool TupleLowering::PostconditionForModule([[maybe_unused]] public_lib::Context *const ctx, - const parser::Program *const program) -{ - return !program->Ast()->IsAnyChild([](const ir::AstNode *const ast) { - const bool isLeftMemberExpr = - ast->IsAssignmentExpression() && ast->AsAssignmentExpression()->Left()->IsMemberExpression(); - const bool isLeftTuple = - isLeftMemberExpr - ? (ast->AsAssignmentExpression()->Left()->AsMemberExpression()->TsType() != nullptr) && - ast->AsAssignmentExpression()->Left()->AsMemberExpression()->TsType()->IsETSTupleType() - : false; - // Check if there is an 'assignment expression' with a 'member expression' on it's left, which is a tuple. If - // yes, then the right hand side must be a type of the element type. - return isLeftMemberExpr && isLeftTuple && - (ast->AsAssignmentExpression()->Right()->TsType() == - ast->AsAssignmentExpression()->Left()->AsMemberExpression()->TsType()->AsETSTupleType()->GetLubType()); - }); -} - -} // namespace ark::es2panda::compiler diff --git a/ets2panda/compiler/lowering/phase.cpp b/ets2panda/compiler/lowering/phase.cpp index 59834228e5..2afb9fd65f 100644 --- a/ets2panda/compiler/lowering/phase.cpp +++ b/ets2panda/compiler/lowering/phase.cpp @@ -14,11 +14,12 @@ */ #include "phase.h" +#include "checker/checker.h" #include "compiler/lowering/checkerPhase.h" #include "compiler/lowering/ets/asyncMethodLowering.h" #include "compiler/lowering/ets/bigintLowering.h" -#include "compiler/lowering/ets/boxingForLocals.h" #include "compiler/lowering/ets/boxedTypeLowering.h" +#include "compiler/lowering/ets/boxingForLocals.h" #include "compiler/lowering/ets/capturedVariables.h" #include "compiler/lowering/ets/constStringToCharLowering.h" #include "compiler/lowering/ets/constantExpressionLowering.h" @@ -40,9 +41,9 @@ #include "compiler/lowering/ets/objectIndexAccess.h" #include "compiler/lowering/ets/objectIterator.h" #include "compiler/lowering/ets/objectLiteralLowering.h" +#include "compiler/lowering/ets/opAssignment.h" #include "compiler/lowering/ets/optionalArgumentsLowering.h" #include "compiler/lowering/ets/optionalLowering.h" -#include "compiler/lowering/ets/opAssignment.h" #include "compiler/lowering/ets/packageImplicitImport.h" #include "compiler/lowering/ets/partialExportClassGen.h" #include "compiler/lowering/ets/promiseVoid.h" @@ -53,7 +54,6 @@ #include "compiler/lowering/ets/stringConstantsLowering.h" #include "compiler/lowering/ets/stringConstructorLowering.h" #include "compiler/lowering/ets/topLevelStmts/topLevelStmts.h" -#include "compiler/lowering/ets/tupleLowering.h" #include "compiler/lowering/ets/unionLowering.h" #include "compiler/lowering/plugin_phase.h" #include "compiler/lowering/resolveIdentifiers.h" @@ -63,7 +63,6 @@ #include "lexer/token/sourceLocation.h" #include "public/es2panda_lib.h" #include "util/options.h" -#include "checker/checker.h" namespace ark::es2panda::compiler { @@ -91,7 +90,6 @@ static ObjectIndexLowering g_objectIndexLowering; static ObjectIteratorLowering g_objectIteratorLowering; static ObjectLiteralLowering g_objectLiteralLowering; static InterfaceObjectLiteralLowering g_interfaceObjectLiteralLowering; -static TupleLowering g_tupleLowering; // Can be only applied after checking phase, and OP_ASSIGNMENT_LOWERING phase static UnionLowering g_unionLowering; static OptionalLowering g_optionalLowering; static ExpandBracketsPhase g_expandBracketsPhase; @@ -164,7 +162,6 @@ std::vector GetETSPhaseList() &g_objectIndexLowering, &g_objectIteratorLowering, &g_lambdaConversionPhase, - &g_tupleLowering, &g_unionLowering, &g_expandBracketsPhase, &g_localClassLowering, diff --git a/ets2panda/compiler/scripts/signatures.yaml b/ets2panda/compiler/scripts/signatures.yaml index f80a307d37..ffc327cc47 100644 --- a/ets2panda/compiler/scripts/signatures.yaml +++ b/ets2panda/compiler/scripts/signatures.yaml @@ -570,6 +570,61 @@ builtins: package: PKG_STD_CORE ref: BUILTIN_LAMBDAR16 + - name: Tuple0 + package: PKG_STD_CORE + ref: BUILTIN_TUPLE0 + - name: Tuple1 + package: PKG_STD_CORE + ref: BUILTIN_TUPLE1 + - name: Tuple2 + package: PKG_STD_CORE + ref: BUILTIN_TUPLE2 + - name: Tuple3 + package: PKG_STD_CORE + ref: BUILTIN_TUPLE3 + - name: Tuple4 + package: PKG_STD_CORE + ref: BUILTIN_TUPLE4 + - name: Tuple5 + package: PKG_STD_CORE + ref: BUILTIN_TUPLE5 + - name: Tuple6 + package: PKG_STD_CORE + ref: BUILTIN_TUPLE6 + - name: Tuple7 + package: PKG_STD_CORE + ref: BUILTIN_TUPLE7 + - name: Tuple8 + package: PKG_STD_CORE + ref: BUILTIN_TUPLE8 + - name: Tuple9 + package: PKG_STD_CORE + ref: BUILTIN_TUPLE9 + - name: Tuple10 + package: PKG_STD_CORE + ref: BUILTIN_TUPLE10 + - name: Tuple11 + package: PKG_STD_CORE + ref: BUILTIN_TUPLE11 + - name: Tuple12 + package: PKG_STD_CORE + ref: BUILTIN_TUPLE12 + - name: Tuple13 + package: PKG_STD_CORE + ref: BUILTIN_TUPLE13 + - name: Tuple14 + package: PKG_STD_CORE + ref: BUILTIN_TUPLE14 + - name: Tuple15 + package: PKG_STD_CORE + ref: BUILTIN_TUPLE15 + - name: Tuple16 + package: PKG_STD_CORE + ref: BUILTIN_TUPLE16 + - name: TupleN + package: PKG_STD_CORE + ref: BUILTIN_TUPLEN + signatures: - callee: BUILTIN_OBJECT method_name: $CTOR diff --git a/ets2panda/docs/lowering-phases.md b/ets2panda/docs/lowering-phases.md index f42dbf2289..321c7c7d9d 100644 --- a/ets2panda/docs/lowering-phases.md +++ b/ets2panda/docs/lowering-phases.md @@ -466,18 +466,6 @@ the `for of` loop converts to } ``` -- `TupleLowering` inserts explicit conversions needed to support tuples. -(The reason is that tuples are represented as arrays of the LUB type of their elements, -and sometimes implicit conversions do not work) -``` - let t: [string, short] = ["oh", 11]; - t[1] = 12; -``` -The last assignment changes to -``` - t[1] = 12 as Short as String|Short; -``` - - `UnionLowering` does two things: 1. processes field access to union 1. cast to primitive type diff --git a/ets2panda/ir/ets/etsTuple.cpp b/ets2panda/ir/ets/etsTuple.cpp index ff18faae77..a9ee2ee9d5 100644 --- a/ets2panda/ir/ets/etsTuple.cpp +++ b/ets2panda/ir/ets/etsTuple.cpp @@ -110,6 +110,13 @@ checker::Type *ETSTuple::GetType(checker::ETSChecker *const checker) } checker->CheckAnnotations(Annotations()); + // NOTE (smartin): Remove, when TupleN is handled in codegen + constexpr uint8_t MAX_TUPLE_ARITY = 16; + if (GetTupleTypeAnnotationsList().size() > MAX_TUPLE_ARITY) { + checker->LogError(diagnostic::TUPLEN_NOT_IMPLEMENTED, {}, Start()); + return checker->InvalidateType(this); + } + ArenaVector typeList(checker->Allocator()->Adapter()); for (auto *const typeAnnotation : GetTupleTypeAnnotationsList()) { @@ -117,15 +124,12 @@ checker::Type *ETSTuple::GetType(checker::ETSChecker *const checker) typeList.emplace_back(checkedType); } - auto *lubType = GetHolderTypeForTuple(checker, typeList); - checker::ETSTupleType *tupleType = - checker->Allocator() - ->New(typeList, lubType, checker->CreateETSArrayType(lubType)) - ->AsETSTupleType(); + auto *tupleType = checker->Allocator()->New(checker, typeList); if (IsReadonlyType()) { tupleType = checker->GetReadonlyType(tupleType)->AsETSTupleType(); } + SetTsType(tupleType); return TsType(); } diff --git a/ets2panda/ir/expressions/arrayExpression.cpp b/ets2panda/ir/expressions/arrayExpression.cpp index 23ad522af5..9bb2b78f8b 100644 --- a/ets2panda/ir/expressions/arrayExpression.cpp +++ b/ets2panda/ir/expressions/arrayExpression.cpp @@ -358,21 +358,21 @@ bool ArrayExpression::TrySetPreferredTypeForNestedArrayExpr(checker::ETSChecker checker->IsArrayExprSizeValidForTuple(nestedArrayExpr, possibleTupleType->AsETSTupleType()); }; - if (preferredType_->IsETSTupleType()) { + if (GetPreferredType()->IsETSTupleType()) { + if (idx >= preferredType_->AsETSTupleType()->GetTupleSize()) { + return false; + } auto *const typeInTupleAtIdx = preferredType_->AsETSTupleType()->GetTypeAtIndex(idx); nestedArrayExpr->SetPreferredType(typeInTupleAtIdx); return doesArrayExprFitInTuple(typeInTupleAtIdx); } - if (preferredType_->IsETSArrayType()) { + if (GetPreferredType()->IsETSArrayType()) { auto *const arrayElementType = preferredType_->AsETSArrayType()->ElementType(); - if (!doesArrayExprFitInTuple(arrayElementType)) { - return false; - } - nestedArrayExpr->SetPreferredType(arrayElementType); - return true; + + return doesArrayExprFitInTuple(arrayElementType); } if (nestedArrayExpr->GetPreferredType() == nullptr) { @@ -419,9 +419,12 @@ void ArrayExpression::SetPreferredTypeBasedOnFuncParam(checker::ETSChecker *chec } param = possiblePreferredType.value(); + if (param->IsETSTupleType()) { + preferredType_ = param; + return; + } - auto *elementType = - param->IsETSArrayType() ? param->AsETSArrayType()->ElementType() : param->AsETSTupleType()->GetLubType(); + auto *elementType = param->AsETSArrayType()->ElementType(); bool isAssignable = true; for (auto *const elem : elements_) { diff --git a/ets2panda/ir/expressions/memberExpression.cpp b/ets2panda/ir/expressions/memberExpression.cpp index 6e89594587..ed9ba81c10 100644 --- a/ets2panda/ir/expressions/memberExpression.cpp +++ b/ets2panda/ir/expressions/memberExpression.cpp @@ -254,7 +254,11 @@ checker::Type *MemberExpression::AdjustType(checker::ETSChecker *checker, checke } else if (IsComputed() && objType->IsETSArrayType()) { // access erased array or tuple type uncheckedType_ = checker->GuaranteedTypeForUncheckedCast(objType->AsETSArrayType()->ElementType(), type); } else if (IsComputed() && objType->IsETSTupleType()) { - uncheckedType_ = checker->GuaranteedTypeForUncheckedCast(objType->AsETSTupleType()->GetLubType(), type); + if (!checker->ValidateTupleIndex(objType->AsETSTupleType(), this, false)) { + // error recovery + return checker->InvalidateType(this); + } + uncheckedType_ = checker->GetApparentType(checker->MaybeBoxType(GetTypeOfTupleElement(checker, objType))); } else if (objType->IsETSUnionType()) { uncheckedType_ = checker->GuaranteedTypeForUnionFieldAccess(this, objType->AsETSUnionType()); } else if (checker->IsExtensionAccessorFunctionType(type)) { @@ -272,13 +276,43 @@ checker::Type *MemberExpression::SetAndAdjustType(checker::ETSChecker *checker, SetObjectType(objectType); auto [resType, resVar] = ResolveObjectMember(checker); if (resType == nullptr) { - SetTsType(checker->GlobalTypeError()); - return checker->GlobalTypeError(); + return checker->InvalidateType(this); } SetPropVar(resVar); return AdjustType(checker, resType); } +std::optional MemberExpression::GetTupleIndexValue() const +{ + auto *propType = property_->TsType(); + if (object_->TsType() == nullptr || !object_->TsType()->IsETSTupleType() || + !propType->HasTypeFlag(checker::TypeFlag::CONSTANT | checker::TypeFlag::ETS_CONVERTIBLE_TO_NUMERIC)) { + return std::nullopt; + } + + if (propType->IsByteType()) { + return propType->AsByteType()->GetValue(); + } + + if (propType->IsShortType()) { + return propType->AsShortType()->GetValue(); + } + + if (propType->IsIntType()) { + return propType->AsIntType()->GetValue(); + } + + if (propType->IsLongType()) { + if (auto val = propType->AsLongType()->GetValue(); + val <= std::numeric_limits::max() && val >= std::numeric_limits::min()) { + return static_cast(val); + } + return std::nullopt; + } + + ES2PANDA_UNREACHABLE(); +} + bool MemberExpression::CheckArrayIndexValue(checker::ETSChecker *checker) const { std::size_t index; @@ -292,7 +326,9 @@ bool MemberExpression::CheckArrayIndexValue(checker::ETSChecker *checker) const return false; } index = static_cast(value); - } else if (number.IsReal()) { + } else { + ES2PANDA_ASSERT(number.IsReal()); + double value = number.GetDouble(); double fraction = std::modf(value, &value); if (value < 0.0 || fraction >= std::numeric_limits::epsilon()) { @@ -300,8 +336,6 @@ bool MemberExpression::CheckArrayIndexValue(checker::ETSChecker *checker) const return false; } index = static_cast(value); - } else { - ES2PANDA_UNREACHABLE(); } if (object_->IsArrayExpression() && object_->AsArrayExpression()->Elements().size() <= index) { @@ -374,7 +408,7 @@ checker::Type *MemberExpression::CheckIndexAccessMethod(checker::ETSChecker *che return signature->ReturnType(); } -checker::Type *MemberExpression::CheckTupleAccessMethod(checker::ETSChecker *checker, checker::Type *baseType) +checker::Type *MemberExpression::GetTypeOfTupleElement(checker::ETSChecker *checker, checker::Type *baseType) { ES2PANDA_ASSERT(baseType->IsETSTupleType()); checker::Type *type = nullptr; @@ -389,19 +423,20 @@ checker::Type *MemberExpression::CheckTupleAccessMethod(checker::ETSChecker *che if (!idxIfAny.has_value()) { return nullptr; } - auto *const tupleTypeAtIdx = baseType->AsETSTupleType()->GetTypeAtIndex(*idxIfAny); - if ((!Parent()->IsAssignmentExpression() || Parent()->AsAssignmentExpression()->Left() != this) && - (!Parent()->IsUpdateExpression())) { - // Error never should be thrown by this call, because LUB of types can be converted to any type which - // LUB was calculated by casting - const checker::CastingContext cast( - checker->Relation(), {"Tuple type couldn't be converted "}, - checker::CastingContext::ConstructorData {this, baseType->AsETSTupleType()->GetLubType(), tupleTypeAtIdx, - Start()}); - } + return baseType->AsETSTupleType()->GetTypeAtIndex(*idxIfAny); +} - return tupleTypeAtIdx; +static void CastTupleElementFromClassMemberType(checker::ETSChecker *checker, + ir::MemberExpression *tupleElementAccessor, checker::Type *baseType) +{ + auto *typeOfTuple = tupleElementAccessor->GetTypeOfTupleElement(checker, baseType); + auto *storedTupleType = checker->MaybeBoxType(typeOfTuple); + + const checker::CastingContext tupleCast( + checker->Relation(), {"this cast should never fail"}, + checker::CastingContext::ConstructorData {tupleElementAccessor, storedTupleType, typeOfTuple, + tupleElementAccessor->Start(), checker::TypeRelationFlag::NO_THROW}); } checker::Type *MemberExpression::CheckComputed(checker::ETSChecker *checker, checker::Type *baseType) @@ -430,15 +465,24 @@ checker::Type *MemberExpression::CheckComputed(checker::ETSChecker *checker, che } if (baseType->IsETSTupleType()) { - auto *dflt = baseType->AsETSTupleType()->GetLubType(); if (!checker->ValidateTupleIndex(baseType->AsETSTupleType(), this)) { // error reported to log - return dflt; + return baseType; } + if (Parent()->IsAssignmentExpression() && Parent()->AsAssignmentExpression()->Left() == this) { + // NOTE (smartin): When an assignment to a tuple type happens, see it as the boxed (stored) type of the + // element. This can be removed, when generics without type erasure is possible + auto *typeOfTuple = GetTypeOfTupleElement(checker, baseType); + auto *storedTupleType = checker->MaybeBoxType(typeOfTuple); + return storedTupleType; + } + + CastTupleElementFromClassMemberType(checker, this, baseType); + // NOTE: apply capture conversion on this type - auto *res = CheckTupleAccessMethod(checker, baseType); - return (res == nullptr) ? dflt : res; + auto *res = GetTypeOfTupleElement(checker, baseType); + return (res == nullptr) ? baseType : res; } if (baseType->IsETSObjectType()) { diff --git a/ets2panda/ir/expressions/memberExpression.h b/ets2panda/ir/expressions/memberExpression.h index 2a8ee863c6..fa2c4d5361 100644 --- a/ets2panda/ir/expressions/memberExpression.h +++ b/ets2panda/ir/expressions/memberExpression.h @@ -202,6 +202,8 @@ public: [[nodiscard]] bool IsPrivateReference() const noexcept; [[nodiscard]] MemberExpression *Clone(ArenaAllocator *allocator, AstNode *parent) override; + std::optional GetTupleIndexValue() const; + checker::Type *GetTypeOfTupleElement(checker::ETSChecker *checker, checker::Type *baseType); void TransformChildren(const NodeTransformer &cb, std::string_view transformationName) override; void Iterate(const NodeTraverser &cb) const override; @@ -250,7 +252,6 @@ private: bool CheckArrayIndexValue(checker::ETSChecker *checker) const; checker::Type *CheckIndexAccessMethod(checker::ETSChecker *checker); - checker::Type *CheckTupleAccessMethod(checker::ETSChecker *checker, checker::Type *baseType); void LoadRhs(compiler::PandaGen *pg) const; diff --git a/ets2panda/test/ast/compiler/ets/FixedArray/annotation_tests/annotationDecl_bad_initializer08.ets b/ets2panda/test/ast/compiler/ets/FixedArray/annotation_tests/annotationDecl_bad_initializer08.ets index 096ea205fb..3de0187673 100644 --- a/ets2panda/test/ast/compiler/ets/FixedArray/annotation_tests/annotationDecl_bad_initializer08.ets +++ b/ets2panda/test/ast/compiler/ets/FixedArray/annotation_tests/annotationDecl_bad_initializer08.ets @@ -26,8 +26,8 @@ enum Size{S, M, L, XL, XXL} /* @@? 20:29 Error TypeError: Type 'int' cannot be assigned to type 'String' */ /* @@? 21:30 Error TypeError: Type '"false"' cannot be assigned to type 'boolean' */ -/* @@? 22:39 Error TypeError: Array element type 'double' is not assignable to explicit type 'int' */ -/* @@? 22:44 Error TypeError: Array element type 'double' is not assignable to explicit type 'int' */ +/* @@? 22:39 Error TypeError: Array element at index 0 with type 'double' is not compatible with the target array element type 'int' */ +/* @@? 22:44 Error TypeError: Array element at index 1 with type 'double' is not compatible with the target array element type 'int' */ /* @@? 23:28 Error TypeError: Type 'Size' cannot be assigned to type 'Color' */ -/* @@? 24:40 Error TypeError: Array element type 'Color' is not assignable to explicit type 'Size' */ -/* @@? 24:53 Error TypeError: Array element type 'Color' is not assignable to explicit type 'Size' */ +/* @@? 24:40 Error TypeError: Array element at index 0 with type 'Color' is not compatible with the target array element type 'Size' */ +/* @@? 24:53 Error TypeError: Array element at index 1 with type 'Color' is not compatible with the target array element type 'Size' */ diff --git a/ets2panda/test/ast/compiler/ets/FixedArray/annotation_tests/annotationUsage_bad_param09.ets b/ets2panda/test/ast/compiler/ets/FixedArray/annotation_tests/annotationUsage_bad_param09.ets index c0abf7fe95..dc97fe475c 100644 --- a/ets2panda/test/ast/compiler/ets/FixedArray/annotation_tests/annotationUsage_bad_param09.ets +++ b/ets2panda/test/ast/compiler/ets/FixedArray/annotation_tests/annotationUsage_bad_param09.ets @@ -37,8 +37,8 @@ class B{ /* @@? 29:24 Error TypeError: Type 'int' cannot be assigned to type 'String' */ /* @@? 30:24 Error TypeError: Type '"false"' cannot be assigned to type 'boolean' */ -/* @@? 31:25 Error TypeError: Array element type 'double' is not assignable to explicit type 'int' */ -/* @@? 31:30 Error TypeError: Array element type 'double' is not assignable to explicit type 'int' */ +/* @@? 31:25 Error TypeError: Array element at index 0 with type 'double' is not compatible with the target array element type 'int' */ +/* @@? 31:30 Error TypeError: Array element at index 1 with type 'double' is not compatible with the target array element type 'int' */ /* @@? 32:24 Error TypeError: Type 'Size' cannot be assigned to type 'Color' */ -/* @@? 33:25 Error TypeError: Array element type 'Color' is not assignable to explicit type 'Size' */ -/* @@? 33:38 Error TypeError: Array element type 'Color' is not assignable to explicit type 'Size' */ +/* @@? 33:25 Error TypeError: Array element at index 0 with type 'Color' is not compatible with the target array element type 'Size' */ +/* @@? 33:38 Error TypeError: Array element at index 1 with type 'Color' is not compatible with the target array element type 'Size' */ diff --git a/ets2panda/test/ast/compiler/ets/FixedArray/tuple_types_1_neg.ets b/ets2panda/test/ast/compiler/ets/FixedArray/tuple_types_1_neg.ets index 9d8ca3b430..c29473759b 100644 --- a/ets2panda/test/ast/compiler/ets/FixedArray/tuple_types_1_neg.ets +++ b/ets2panda/test/ast/compiler/ets/FixedArray/tuple_types_1_neg.ets @@ -18,4 +18,4 @@ function main(): void { const array: (number|boolean) [] = tuple } -/* @@? 18:40 Error TypeError: Type '[Double, Double, Boolean]' cannot be assigned to type '(Double|Boolean)[]' */ +/* @@? 18:40 Error TypeError: Type '[double, double, boolean]' cannot be assigned to type '(Double|Boolean)[]' */ diff --git a/ets2panda/test/ast/compiler/ets/FixedArray/tuple_types_9_neg.ets b/ets2panda/test/ast/compiler/ets/FixedArray/tuple_types_9_neg.ets index 60e525d2b8..de7338a66b 100644 --- a/ets2panda/test/ast/compiler/ets/FixedArray/tuple_types_9_neg.ets +++ b/ets2panda/test/ast/compiler/ets/FixedArray/tuple_types_9_neg.ets @@ -32,4 +32,3 @@ function main(): void { /* @@? 18:47 Error SyntaxError: Unexpected token ']'. */ /* @@? 18:47 Error SyntaxError: Unexpected token ']'. */ /* @@? 18:49 Error SyntaxError: Unexpected token '='. */ -/* @@? 18:55 Error TypeError: Array element type '"a"' is not assignable to explicit type 'int' */ diff --git a/ets2panda/test/ast/compiler/ets/annotation_tests/annotationDecl_bad_initializer08.ets b/ets2panda/test/ast/compiler/ets/annotation_tests/annotationDecl_bad_initializer08.ets index e58f365ee0..97418d3a03 100644 --- a/ets2panda/test/ast/compiler/ets/annotation_tests/annotationDecl_bad_initializer08.ets +++ b/ets2panda/test/ast/compiler/ets/annotation_tests/annotationDecl_bad_initializer08.ets @@ -26,8 +26,8 @@ enum Size{S, M, L, XL, XXL} /* @@? 20:29 Error TypeError: Type 'int' cannot be assigned to type 'String' */ /* @@? 21:30 Error TypeError: Type '"false"' cannot be assigned to type 'boolean' */ -/* @@? 22:39 Error TypeError: Array element type 'double' is not assignable to explicit type 'int' */ -/* @@? 22:44 Error TypeError: Array element type 'double' is not assignable to explicit type 'int' */ +/* @@? 22:39 Error TypeError: Array element at index 0 with type 'double' is not compatible with the target array element type 'int' */ +/* @@? 22:44 Error TypeError: Array element at index 1 with type 'double' is not compatible with the target array element type 'int' */ /* @@? 23:28 Error TypeError: Type 'Size' cannot be assigned to type 'Color' */ -/* @@? 24:40 Error TypeError: Array element type 'Color' is not assignable to explicit type 'Size' */ -/* @@? 24:53 Error TypeError: Array element type 'Color' is not assignable to explicit type 'Size' */ +/* @@? 24:40 Error TypeError: Array element at index 0 with type 'Color' is not compatible with the target array element type 'Size' */ +/* @@? 24:53 Error TypeError: Array element at index 1 with type 'Color' is not compatible with the target array element type 'Size' */ diff --git a/ets2panda/test/ast/compiler/ets/annotation_tests/annotationUsage_bad_param09.ets b/ets2panda/test/ast/compiler/ets/annotation_tests/annotationUsage_bad_param09.ets index fbf5947300..ef17b83b2b 100644 --- a/ets2panda/test/ast/compiler/ets/annotation_tests/annotationUsage_bad_param09.ets +++ b/ets2panda/test/ast/compiler/ets/annotation_tests/annotationUsage_bad_param09.ets @@ -37,8 +37,8 @@ class B{ /* @@? 29:24 Error TypeError: Type 'int' cannot be assigned to type 'String' */ /* @@? 30:24 Error TypeError: Type '"false"' cannot be assigned to type 'boolean' */ -/* @@? 31:25 Error TypeError: Array element type 'double' is not assignable to explicit type 'int' */ -/* @@? 31:30 Error TypeError: Array element type 'double' is not assignable to explicit type 'int' */ +/* @@? 31:25 Error TypeError: Array element at index 0 with type 'double' is not compatible with the target array element type 'int' */ +/* @@? 31:30 Error TypeError: Array element at index 1 with type 'double' is not compatible with the target array element type 'int' */ /* @@? 32:24 Error TypeError: Type 'Size' cannot be assigned to type 'Color' */ -/* @@? 33:25 Error TypeError: Array element type 'Color' is not assignable to explicit type 'Size' */ -/* @@? 33:38 Error TypeError: Array element type 'Color' is not assignable to explicit type 'Size' */ +/* @@? 33:25 Error TypeError: Array element at index 0 with type 'Color' is not compatible with the target array element type 'Size' */ +/* @@? 33:38 Error TypeError: Array element at index 1 with type 'Color' is not compatible with the target array element type 'Size' */ diff --git a/ets2panda/compiler/lowering/ets/tupleLowering.h b/ets2panda/test/ast/compiler/ets/default_param_tuple_infer.ets similarity index 45% rename from ets2panda/compiler/lowering/ets/tupleLowering.h rename to ets2panda/test/ast/compiler/ets/default_param_tuple_infer.ets index 16d2b76406..e2be2398ae 100644 --- a/ets2panda/compiler/lowering/ets/tupleLowering.h +++ b/ets2panda/test/ast/compiler/ets/default_param_tuple_infer.ets @@ -1,5 +1,5 @@ -/** - * Copyright (c) 2023-2024 Huawei Device Co., Ltd. +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,24 +13,12 @@ * limitations under the License. */ -#ifndef ES2PANDA_COMPILER_LOWERING_TUPLE_LOWERING_H -#define ES2PANDA_COMPILER_LOWERING_TUPLE_LOWERING_H +type TupleAlias = [ number, string ] -#include "compiler/lowering/phase.h" +function handleTupleAlias_notCast(tuple: TupleAlias = [ 1, 'string' ]) {} +function handleTupleAdHoc_notCast(tuple: [ number, string ] = [ 1, 'string' ]) {} +function handleByte_notCast(arg: byte = 1): byte { return arg; } -namespace ark::es2panda::compiler { - -class TupleLowering : public PhaseForBodies { -public: - std::string_view Name() const override - { - return "TupleLowering"; - } - - bool PerformForModule(public_lib::Context *ctx, parser::Program *program) override; - bool PostconditionForModule(public_lib::Context *ctx, const parser::Program *program) override; -}; - -} // namespace ark::es2panda::compiler - -#endif // ES2PANDA_COMPILER_LOWERING_TUPLE_LOWERING_H +function handleTupleAlias_cast(tuple: TupleAlias = [ 1, 'string' ] as TupleAlias) {} +function handleTupleAdHoc_cast(tuple: [ number, string ] = [ 1, 'string' ] as [ number, string ]) {} +function handleByte_cast(arg: byte = 1 as byte): byte { return arg; } diff --git a/ets2panda/test/ast/compiler/ets/tuple_generic_function_param.ets b/ets2panda/test/ast/compiler/ets/tuple_generic_function_param.ets new file mode 100644 index 0000000000..541ffd049e --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/tuple_generic_function_param.ets @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +function foo(a: T[]): void {} + +foo<[int, string]>([[1, "a"]]) diff --git a/ets2panda/test/ast/compiler/ets/tuple_types_1_neg.ets b/ets2panda/test/ast/compiler/ets/tuple_types_1_neg.ets index 9d8ca3b430..c29473759b 100644 --- a/ets2panda/test/ast/compiler/ets/tuple_types_1_neg.ets +++ b/ets2panda/test/ast/compiler/ets/tuple_types_1_neg.ets @@ -18,4 +18,4 @@ function main(): void { const array: (number|boolean) [] = tuple } -/* @@? 18:40 Error TypeError: Type '[Double, Double, Boolean]' cannot be assigned to type '(Double|Boolean)[]' */ +/* @@? 18:40 Error TypeError: Type '[double, double, boolean]' cannot be assigned to type '(Double|Boolean)[]' */ diff --git a/ets2panda/test/ast/compiler/ets/tuple_types_9_neg.ets b/ets2panda/test/ast/compiler/ets/tuple_types_9_neg.ets index 866c00616f..0a18e7020b 100644 --- a/ets2panda/test/ast/compiler/ets/tuple_types_9_neg.ets +++ b/ets2panda/test/ast/compiler/ets/tuple_types_9_neg.ets @@ -28,5 +28,4 @@ function main(): void { /* @@? 18:37 Error SyntaxError: Unexpected token ']'. */ /* @@? 18:37 Error SyntaxError: Unexpected token ']'. */ /* @@? 18:39 Error SyntaxError: Unexpected token '='. */ -/* @@? 18:45 Error TypeError: Array element type '"a"' is not assignable to explicit type 'int' */ -/* @@@ label Error TypeError: Type '[Double, String, *ERROR_TYPE*]' cannot be assigned to type '[Double, String, Int]' */ +/* @@@ label Error TypeError: Type '[double, String, *ERROR_TYPE*]' cannot be assigned to type '[double, String, Int]' */ diff --git a/ets2panda/test/ast/compiler/ets/variance_typeparam_transmit.ets b/ets2panda/test/ast/compiler/ets/variance_typeparam_transmit.ets index a4b8860eac..9c96f4d421 100644 --- a/ets2panda/test/ast/compiler/ets/variance_typeparam_transmit.ets +++ b/ets2panda/test/ast/compiler/ets/variance_typeparam_transmit.ets @@ -19,19 +19,20 @@ class B {} class A123{ readonly readonlyfield1:InB; - readonly readonlyfield2:/* @@ label1 */InB; //CTE + readonly readonlyfield2:/* @@ label1 */InB; //CTE readonly readonlyfield3:InB; readonly readonlyfield4:InB; - readonly readonlyfield5:InB<[T1,T3,number]>; - readonly readonlyfield7:/* @@ label2 */OutB; //CTE + readonly readonlyfield5:/* @@ label2 */InB<[T1,T3,number]>; //CTE + readonly readonlyfield7:/* @@ label3 */OutB; //CTE readonly readonlyfield8:OutB; readonly readonlyfield9:OutB; - readonly readonlyfield10:/* @@ label3 */B; //CTE - readonly readonlyfield11:/* @@ label4 */B; //CTE + readonly readonlyfield10:/* @@ label4 */B; //CTE + readonly readonlyfield11:/* @@ label5 */B; //CTE readonly readonlyfield12:B; } /* @@@ label1 Error TypeError: Type Parameter 'T2' is declared as 'out' but occurs in 'in' position. */ -/* @@@ label2 Error TypeError: Type Parameter 'T1' is declared as 'in' but occurs in 'out' position. */ -/* @@@ label3 Error TypeError: Type Parameter 'T1' is declared as 'in' but occurs in 'invariant' position. */ -/* @@@ label4 Error TypeError: Type Parameter 'T2' is declared as 'out' but occurs in 'invariant' position. */ +/* @@@ label2 Error TypeError: Type Parameter 'T1' is declared as 'in' but occurs in 'invariant' position. */ +/* @@@ label3 Error TypeError: Type Parameter 'T1' is declared as 'in' but occurs in 'out' position. */ +/* @@@ label4 Error TypeError: Type Parameter 'T1' is declared as 'in' but occurs in 'invariant' position. */ +/* @@@ label5 Error TypeError: Type Parameter 'T2' is declared as 'out' but occurs in 'invariant' position. */ diff --git a/ets2panda/test/ast/compiler/ets/variance_typeparam_tuple.ets b/ets2panda/test/ast/compiler/ets/variance_typeparam_tuple.ets index bfa550babc..374aa69fb3 100644 --- a/ets2panda/test/ast/compiler/ets/variance_typeparam_tuple.ets +++ b/ets2panda/test/ast/compiler/ets/variance_typeparam_tuple.ets @@ -18,14 +18,14 @@ class A{ field2:/* @@ label2 */[number,T2,string]; //CTE field3:[number,T3,string]; readonly readonlyfield1:/* @@ label3 */[number,T1,string]; //CTE - readonly readonlyfield2:[number,T2,string]; + readonly readonlyfield2:/* @@ label4 */[number,T2,string]; //CTE readonly readonlyfield3:[number,T3,string]; - returnTypeFunc1():/* @@ label4 */[number,T1,string]{ //CTE + returnTypeFunc1():/* @@ label5 */[number,T1,string]{ //CTE return this.readonlyfield1; } - returnTypeFunc2():[number,T2,string]{ + returnTypeFunc2():/* @@ label6 */[number,T2,string]{ //CTE return this.readonlyfield2; } @@ -33,13 +33,16 @@ class A{ return this.readonlyfield3; } - paramsFunc1(a:[number,T1,string]){} - paramsFunc2(a:/* @@ label5 */[number,T2,string]){} //CTE + paramsFunc1(a:/* @@ label7 */[number,T1,string]){} //CTE + paramsFunc2(a:/* @@ label8 */[number,T2,string]){} //CTE paramsFunc3(a:[number,T3,string]){} } -/* @@@ label1 Error TypeError: Type Parameter 'T1' is declared as 'in' but occurs in 'invariant' position. */ -/* @@@ label2 Error TypeError: Type Parameter 'T2' is declared as 'out' but occurs in 'invariant' position. */ -/* @@@ label3 Error TypeError: Type Parameter 'T1' is declared as 'in' but occurs in 'out' position. */ -/* @@@ label4 Error TypeError: Type Parameter 'T1' is declared as 'in' but occurs in 'out' position. */ -/* @@@ label5 Error TypeError: Type Parameter 'T2' is declared as 'out' but occurs in 'in' position. */ +/* @@@ label1 Error TypeError: Type Parameter 'T1' is declared as 'in' but occurs in 'invariant' position. */ +/* @@@ label2 Error TypeError: Type Parameter 'T2' is declared as 'out' but occurs in 'invariant' position. */ +/* @@@ label3 Error TypeError: Type Parameter 'T1' is declared as 'in' but occurs in 'invariant' position. */ +/* @@@ label4 Error TypeError: Type Parameter 'T2' is declared as 'out' but occurs in 'invariant' position. */ +/* @@@ label5 Error TypeError: Type Parameter 'T1' is declared as 'in' but occurs in 'invariant' position. */ +/* @@@ label6 Error TypeError: Type Parameter 'T2' is declared as 'out' but occurs in 'invariant' position. */ +/* @@@ label7 Error TypeError: Type Parameter 'T1' is declared as 'in' but occurs in 'invariant' position. */ +/* @@@ label8 Error TypeError: Type Parameter 'T2' is declared as 'out' but occurs in 'invariant' position. */ diff --git a/ets2panda/test/ast/parser/ets/readonly-parameter-test/Readonly-with-ArrayType-test2.ets b/ets2panda/test/ast/parser/ets/readonly-parameter-test/Readonly-with-ArrayType-test2.ets index 7656872082..7fbea40572 100644 --- a/ets2panda/test/ast/parser/ets/readonly-parameter-test/Readonly-with-ArrayType-test2.ets +++ b/ets2panda/test/ast/parser/ets/readonly-parameter-test/Readonly-with-ArrayType-test2.ets @@ -19,5 +19,5 @@ function foo (p: [int, string]) { let x: Readonly<[int, string]> = [] /* @@ label */foo(/* @@ label1 */x) -/* @@@ label1 Error TypeError: Type 'readonly [Int, String]' is not compatible with type '[Int, String]' at index 1 */ -/* @@@ label Error TypeError: No matching call signature for foo(readonly [Int, String]) */ +/* @@@ label1 Error TypeError: Type 'readonly [int, String]' is not compatible with type '[int, String]' at index 1 */ +/* @@@ label Error TypeError: No matching call signature for foo(readonly [int, String]) */ diff --git a/ets2panda/test/ast/parser/ets/readonly-parameter-test/Readonly-with-ArrayType-test3.ets b/ets2panda/test/ast/parser/ets/readonly-parameter-test/Readonly-with-ArrayType-test3.ets index 1d321b90e4..0953054d47 100644 --- a/ets2panda/test/ast/parser/ets/readonly-parameter-test/Readonly-with-ArrayType-test3.ets +++ b/ets2panda/test/ast/parser/ets/readonly-parameter-test/Readonly-with-ArrayType-test3.ets @@ -17,4 +17,4 @@ function foo (x: Readonly<[int, string]>) { let y: [int, string] = /* @@ label */x } -/* @@@ label Error TypeError: Type 'readonly [Int, String]' cannot be assigned to type '[Int, String]' */ +/* @@@ label Error TypeError: Type 'readonly [int, String]' cannot be assigned to type '[int, String]' */ diff --git a/ets2panda/test/ast/parser/ets/readonly-parameter-test/readonly-parameter-test2.ets b/ets2panda/test/ast/parser/ets/readonly-parameter-test/readonly-parameter-test2.ets index 12e4c37fed..fd6e6d8419 100644 --- a/ets2panda/test/ast/parser/ets/readonly-parameter-test/readonly-parameter-test2.ets +++ b/ets2panda/test/ast/parser/ets/readonly-parameter-test/readonly-parameter-test2.ets @@ -18,4 +18,4 @@ function foo (x: readonly [int, string]) { let y: [int, string] = /* @@ label */x } -/* @@@ label Error TypeError: Type 'readonly [Int, String]' cannot be assigned to type '[Int, String]' */ +/* @@@ label Error TypeError: Type 'readonly [int, String]' cannot be assigned to type '[int, String]' */ diff --git a/ets2panda/test/ast/parser/ets/readonly-parameter-test/readonly-parameter-test5.ets b/ets2panda/test/ast/parser/ets/readonly-parameter-test/readonly-parameter-test5.ets index 5d92154dab..448f5ebcdb 100644 --- a/ets2panda/test/ast/parser/ets/readonly-parameter-test/readonly-parameter-test5.ets +++ b/ets2panda/test/ast/parser/ets/readonly-parameter-test/readonly-parameter-test5.ets @@ -19,5 +19,5 @@ function foo (p: [int, string]) { let x: readonly [int, string] = [] /* @@ label */foo(/* @@ label1 */x) -/* @@@ label1 Error TypeError: Type 'readonly [Int, String]' is not compatible with type '[Int, String]' at index 1 */ -/* @@@ label Error TypeError: No matching call signature for foo(readonly [Int, String]) */ +/* @@@ label1 Error TypeError: Type 'readonly [int, String]' is not compatible with type '[int, String]' at index 1 */ +/* @@@ label Error TypeError: No matching call signature for foo(readonly [int, String]) */ diff --git a/ets2panda/test/runtime/ets/AliasTuple.ets b/ets2panda/test/runtime/ets/AliasTuple.ets index 73cd48b2f3..e02c0cef30 100644 --- a/ets2panda/test/runtime/ets/AliasTuple.ets +++ b/ets2panda/test/runtime/ets/AliasTuple.ets @@ -30,7 +30,7 @@ function main() { let v1: [double] = [new Int(1)]; // [double] let v2: [double, Int] = [new Double(2), new Int(3)]; // [Double, Int] - let v3: Alias1Tuple = [new Int(4)]; // [double] + let v3: Alias1Tuple = [new Int(4)]; // [double] let v4: Alias2Tuple = [new Double(5), new Int(6)]; // [Double, Int] let v5: Alias3Tuple = [new C(7), 8]; // [C, Double] diff --git a/ets2panda/test/runtime/ets/function_param_tuple_array_expr_infer.ets b/ets2panda/test/runtime/ets/function_param_tuple_array_expr_infer.ets new file mode 100644 index 0000000000..6d164f81fd --- /dev/null +++ b/ets2panda/test/runtime/ets/function_param_tuple_array_expr_infer.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +function foo(a: [byte, int, long]) { + assertEQ(a[0], 3) + assertEQ(a[1], 42) + assertEQ(a[2], -9223372036854775808) +} + +function main() { + // call context, tuple of primitives + foo([0b11, 42, -9223372036854775808]) +} diff --git a/ets2panda/test/runtime/ets/tuple_types_runtime.ets b/ets2panda/test/runtime/ets/tuple_types_runtime.ets index 800c51c4d1..ea92f4de2f 100644 --- a/ets2panda/test/runtime/ets/tuple_types_runtime.ets +++ b/ets2panda/test/runtime/ets/tuple_types_runtime.ets @@ -56,13 +56,10 @@ function main(): void { const sum = tup_3[0][1][0] + tup_3[1][1][0] + tup_3[1][1][1] + tup_3[2][1][0] + tup_3[2][1][1] + tup_3[2][1][2]; assertEQ(sum, 1660); - // Runs correctly, but fails on verifier - // It sees the type of `tup_3[0][0]` as an `Object`, what it really is an Array type. - - // tup_3[0][0][0]++; - // assertEQ(tup_3[0][0][0], 14) - // tup_3[0][0][0] = 4; - // assertEQ(tup_3[0][0][0], 4) + tup_3[0][0][0]++; + assertEQ(tup_3[0][0][0], 14) + tup_3[0][0][0] = 4; + assertEQ(tup_3[0][0][0], 4) let int_update: [int] = [42]; assertEQ(int_update[0], 42) diff --git a/ets2panda/util/diagnostic/semantic.yaml b/ets2panda/util/diagnostic/semantic.yaml index 5b948bf06f..93c85d69cf 100644 --- a/ets2panda/util/diagnostic/semantic.yaml +++ b/ets2panda/util/diagnostic/semantic.yaml @@ -927,7 +927,7 @@ semantic: id: 230 message: "Annotation missing '@' symbol before annotation name." -- name: TUPLE_TOO_FEW_ELEMS +- name: TUPLE_WRONG_NUMBER_OF_ELEMS id: 231 message: "Initializer has {} elements, but tuple requires {}" -- Gitee From 1334b9292f5ea0c0f6191c89774bf1a04295aebc Mon Sep 17 00:00:00 2001 From: Robert Sipka Date: Thu, 3 Apr 2025 17:40:56 +0200 Subject: [PATCH 131/268] Fix for predefined types Predefined types cannot be used as valid identifiers Issue: #IBYOA4 Fixes 22987 internal issue Change-Id: I3c0511358dc6dbbbb1ca3c2989ea661915da4c63 Signed-off-by: Robert Sipka --- ets2panda/lexer/lexer.cpp | 20 +++--- ets2panda/lexer/scripts/keywords.yaml | 67 ++++++++++++++++++- ets2panda/lexer/scripts/tokens.yaml | 1 + ets2panda/lexer/templates/keywords.h.erb | 2 +- ets2panda/lexer/templates/token.inl.erb | 5 +- ets2panda/lexer/token/token.h | 1 + ets2panda/parser/ETSparser.cpp | 4 +- ets2panda/parser/parserImpl.cpp | 9 ++- .../test/ast/parser/ets/ambient_indexer_2.ets | 1 + .../annotationDecl_parser_bad_token02.ets | 4 +- .../annotationDecl_parser_bad_token03.ets | 6 +- .../parser/ets/non-ambient_call_signature.ets | 1 + .../test/ast/parser/ets/user_defined_10.ets | 3 +- .../test/ast/parser/ets/user_defined_11.ets | 3 +- .../parser/ets/cast_expressions4-expected.txt | 28 ++++---- .../test/parser/ets/cast_expressions4.ets | 2 +- ets2panda/test/runtime/ets/array-object.ets | 16 ++--- .../ets/optional-chaining-lazy-evaluation.ets | 8 +-- ets2panda/util/diagnostic/syntax.yaml | 32 +++++++++ 19 files changed, 161 insertions(+), 52 deletions(-) diff --git a/ets2panda/lexer/lexer.cpp b/ets2panda/lexer/lexer.cpp index 6ecd74e5bf..8bb2698446 100644 --- a/ets2panda/lexer/lexer.cpp +++ b/ets2panda/lexer/lexer.cpp @@ -1483,24 +1483,15 @@ void Lexer::NextToken(Keywords *kws) } case LEX_CHAR_DOLLAR_SIGN: case LEX_CHAR_UPPERCASE_A: - case LEX_CHAR_UPPERCASE_B: - case LEX_CHAR_UPPERCASE_C: - case LEX_CHAR_UPPERCASE_D: case LEX_CHAR_UPPERCASE_E: - case LEX_CHAR_UPPERCASE_F: case LEX_CHAR_UPPERCASE_G: case LEX_CHAR_UPPERCASE_H: - case LEX_CHAR_UPPERCASE_I: case LEX_CHAR_UPPERCASE_J: case LEX_CHAR_UPPERCASE_K: - case LEX_CHAR_UPPERCASE_L: case LEX_CHAR_UPPERCASE_M: - case LEX_CHAR_UPPERCASE_N: - case LEX_CHAR_UPPERCASE_O: case LEX_CHAR_UPPERCASE_P: case LEX_CHAR_UPPERCASE_Q: case LEX_CHAR_UPPERCASE_R: - case LEX_CHAR_UPPERCASE_S: case LEX_CHAR_UPPERCASE_T: case LEX_CHAR_UPPERCASE_U: case LEX_CHAR_UPPERCASE_V: @@ -1570,7 +1561,16 @@ void Lexer::NextToken(Keywords *kws) case LEX_CHAR_LOWERCASE_W: case LEX_CHAR_LOWERCASE_X: case LEX_CHAR_LOWERCASE_Y: - case LEX_CHAR_LOWERCASE_Z: { + case LEX_CHAR_LOWERCASE_Z: + case LEX_CHAR_UPPERCASE_B: + case LEX_CHAR_UPPERCASE_C: + case LEX_CHAR_UPPERCASE_D: + case LEX_CHAR_UPPERCASE_F: + case LEX_CHAR_UPPERCASE_I: + case LEX_CHAR_UPPERCASE_L: + case LEX_CHAR_UPPERCASE_N: + case LEX_CHAR_UPPERCASE_O: + case LEX_CHAR_UPPERCASE_S: { kws->ScanKeyword(cp); break; } diff --git a/ets2panda/lexer/scripts/keywords.yaml b/ets2panda/lexer/scripts/keywords.yaml index bb6362567a..5d1af91329 100644 --- a/ets2panda/lexer/scripts/keywords.yaml +++ b/ets2panda/lexer/scripts/keywords.yaml @@ -65,11 +65,21 @@ keywords: keyword_like: [ets, ts] flags: [definable_type_name] + - name: 'Bigint' + token: KEYW_BUILTIN_BIGINT + keyword_like: [ets] + flags: [predefined_type] + - name: 'boolean' token: KEYW_BOOLEAN keyword_like: [ets, js, ts] flags: [reserved_type_name, definable_type_name] + - name: 'Boolean' + token: KEYW_BUILTIN_BOOLEAN + keyword_like: [ets] + flags: [predefined_type] + - name: 'break' token: KEYW_BREAK keyword: [js, ts, as, ets] @@ -80,6 +90,11 @@ keywords: keyword_like: [ets] flags: [reserved_type_name, definable_type_name] + - name: 'Byte' + token: KEYW_BUILTIN_BYTE + keyword_like: [ets] + flags: [predefined_type] + - name: 'case' token: KEYW_CASE keyword: [js, ts, as, ets] @@ -95,6 +110,11 @@ keywords: keyword_like: [ets] flags: [reserved_type_name, definable_type_name] + - name: 'Char' + token: KEYW_BUILTIN_CHAR + keyword_like: [ets] + flags: [predefined_type] + - name: 'class' token: KEYW_CLASS keyword: [js, ts, as, ets] @@ -144,6 +164,11 @@ keywords: keyword_like: [ets] flags: [reserved_type_name, definable_type_name] + - name: 'Double' + token: KEYW_BUILTIN_DOUBLE + keyword_like: [ets] + flags: [predefined_type] + - name: 'else' token: KEYW_ELSE keyword: [js, ts, as, ets] @@ -200,6 +225,11 @@ keywords: keyword_like: [ets] flags: [reserved_type_name, definable_type_name] + - name: 'Float' + token: KEYW_BUILTIN_FLOAT + keyword_like: [ets] + flags: [predefined_type] + - name: 'for' token: KEYW_FOR keyword: [as, js, ets, ts] @@ -280,6 +310,11 @@ keywords: keyword_like: [ets] flags: [reserved_type_name, definable_type_name] + - name: 'Int' + token: KEYW_BUILTIN_INT + keyword_like: [ets] + flags: [predefined_type] + - name: 'interface' token: KEYW_INTERFACE keyword: [js, as, ets, ts] @@ -310,6 +345,11 @@ keywords: keyword_like: [ets] flags: [reserved_type_name, definable_type_name] + - name: 'Long' + token: KEYW_BUILTIN_LONG + keyword_like: [ets] + flags: [predefined_type] + - name: 'meta' token: KEYW_META keyword_like: [js, ts] @@ -344,12 +384,23 @@ keywords: - name: 'number' token: KEYW_NUMBER keyword_like: [ets, ts] - flags: [definable_type_name] + flags: [definable_type_name, predefined_type] + + # issue 25066 + # - name: 'Number' + # token: KEYW_BUILTIN_NUMBER + # keyword_like: [ets] + # flags: [predefined_type] - name: 'object' token: KEYW_OBJECT - keyword_like: [ts] - flags: [reserved_type_name] + keyword_like: [ets, ts] + flags: [reserved_type_name, predefined_type] + + - name: 'Object' + token: KEYW_BUILTIN_OBJECT + keyword_like: [ets] + flags: [predefined_type] - name: 'of' token: KEYW_OF @@ -413,6 +464,11 @@ keywords: keyword_like: [ets] flags: [reserved_type_name, definable_type_name] + - name: 'Short' + token: KEYW_BUILTIN_SHORT + keyword_like: [ets] + flags: [predefined_type] + - name: 'static' token: KEYW_STATIC keyword: [js, as, ets, ts] @@ -422,6 +478,11 @@ keywords: keyword_like: [ets, ts] flags: [definable_type_name] + - name: 'String' + token: KEYW_BUILTIN_STRING + keyword_like: [ets] + flags: [predefined_type] + - name: 'struct' token: KEYW_STRUCT keyword_like: [ets] diff --git a/ets2panda/lexer/scripts/tokens.yaml b/ets2panda/lexer/scripts/tokens.yaml index 5c946bf518..39b8764ff7 100644 --- a/ets2panda/lexer/scripts/tokens.yaml +++ b/ets2panda/lexer/scripts/tokens.yaml @@ -247,3 +247,4 @@ flags: unary: Unary operation reserved_type_name: TypeScript reserved type name definable_type_name: Words which cannot be used as user-defined type names but are not otherwise restricted + predefined_type: Predefined types which are hard keywords, and cannot be used as identifiers diff --git a/ets2panda/lexer/templates/keywords.h.erb b/ets2panda/lexer/templates/keywords.h.erb index b65c9ec812..97f76fe537 100644 --- a/ets2panda/lexer/templates/keywords.h.erb +++ b/ets2panda/lexer/templates/keywords.h.erb @@ -44,7 +44,7 @@ public: } void ScanKeyword(char32_t cp) override { - ES2PANDA_ASSERT(cp >= 'a' && cp <= 'z'); + ES2PANDA_ASSERT((cp >= 'a' && cp <= 'z') || (cp >= 'A' && cp <= 'Z')); switch(cp) { % desc['all_word_starts'].each do |cp| case '<%=cp%>': Scan_<%=cp%>(); break; diff --git a/ets2panda/lexer/templates/token.inl.erb b/ets2panda/lexer/templates/token.inl.erb index 8c4262f2d4..d9541f6a1e 100644 --- a/ets2panda/lexer/templates/token.inl.erb +++ b/ets2panda/lexer/templates/token.inl.erb @@ -75,4 +75,7 @@ bool Token::IsBinaryLvalueToken(TokenType type) % genSwitch['type', Tokens::tokens, 'binary_lvalue'] } - +bool Token::IsPredefinedType() const +{ +% genSwitch['keywordType_', Keywords::keywords, 'predefined_type'] +} diff --git a/ets2panda/lexer/token/token.h b/ets2panda/lexer/token/token.h index 2f9ef0b194..35d27885f8 100644 --- a/ets2panda/lexer/token/token.h +++ b/ets2panda/lexer/token/token.h @@ -142,6 +142,7 @@ public: bool IsKeyword() const; bool IsReservedTypeName() const; bool IsDefinableTypeName() const; + bool IsPredefinedType() const; static bool IsBinaryToken(TokenType type); static bool IsBinaryLvalueToken(TokenType type); diff --git a/ets2panda/parser/ETSparser.cpp b/ets2panda/parser/ETSparser.cpp index 9dd83078e8..56de720ef0 100644 --- a/ets2panda/parser/ETSparser.cpp +++ b/ets2panda/parser/ETSparser.cpp @@ -634,7 +634,7 @@ ir::TSTypeAliasDeclaration *ETSParser::ParseTypeAliasDeclaration() lexer::SourcePosition typeStart = Lexer()->GetToken().Start(); Lexer()->NextToken(); // eat type keyword - if (Lexer()->GetToken().IsReservedTypeName()) { + if (Lexer()->GetToken().IsReservedTypeName() && !util::Helpers::IsStdLib(GetProgram())) { LogError(diagnostic::TYPE_ALIAS_INVALID_NAME, {TokenToString(Lexer()->GetToken().KeywordType())}); } @@ -1779,7 +1779,7 @@ ir::TSTypeParameter *ETSParser::ParseTypeParameter([[maybe_unused]] TypeAnnotati } } auto saveLoc = Lexer()->GetToken().Start(); - auto *paramIdent = ExpectIdentifier(); + auto *paramIdent = ExpectIdentifier(false, false, *options); ir::TypeNode *constraint = nullptr; if (Lexer()->GetToken().Type() == lexer::TokenType::KEYW_EXTENDS) { diff --git a/ets2panda/parser/parserImpl.cpp b/ets2panda/parser/parserImpl.cpp index f854396682..b1cbdefa5b 100644 --- a/ets2panda/parser/parserImpl.cpp +++ b/ets2panda/parser/parserImpl.cpp @@ -1235,11 +1235,18 @@ ir::Identifier *ParserImpl::ExpectIdentifier([[maybe_unused]] bool isReference, } } + auto const &tokenStart = token.Start(); + if (token.IsPredefinedType() && !util::Helpers::IsStdLib(program_) && + ((options & TypeAnnotationParsingOptions::ADD_TYPE_PARAMETER_BINDING) == 0)) { + LogError(diagnostic::PREDEFINED_TYPE_AS_IDENTIFIER, {token.Ident()}, tokenStart); + lexer_->NextToken(); + return AllocBrokenExpression(tokenStart); + } + if (token.IsDefinableTypeName() && isUserDefinedType) { LogError(diagnostic::NOT_ALLOWED_USER_DEFINED_TYPE); } - auto const &tokenStart = token.Start(); util::StringView tokenName {}; if (tokenType == lexer::TokenType::LITERAL_IDENT) { diff --git a/ets2panda/test/ast/parser/ets/ambient_indexer_2.ets b/ets2panda/test/ast/parser/ets/ambient_indexer_2.ets index 345790b76a..7b5c41ba88 100644 --- a/ets2panda/test/ast/parser/ets/ambient_indexer_2.ets +++ b/ets2panda/test/ast/parser/ets/ambient_indexer_2.ets @@ -23,6 +23,7 @@ function main() { /* @@? 17:6 Error SyntaxError: Unexpected token 'index'. */ /* @@? 17:12 Error SyntaxError: Unexpected token ':'. */ +/* @@? 17:14 Error SyntaxError: number is a predefined type, cannot be used as an identifier */ /* @@? 17:20 Error SyntaxError: Field type annotation expected. */ /* @@? 17:20 Error SyntaxError: Unexpected token ']'. */ /* @@? 17:22 Error SyntaxError: Unexpected token ':'. */ diff --git a/ets2panda/test/ast/parser/ets/annotations_tests/annotationDecl_parser_bad_token02.ets b/ets2panda/test/ast/parser/ets/annotations_tests/annotationDecl_parser_bad_token02.ets index 0034ba7e50..999e7e6953 100644 --- a/ets2panda/test/ast/parser/ets/annotations_tests/annotationDecl_parser_bad_token02.ets +++ b/ets2panda/test/ast/parser/ets/annotations_tests/annotationDecl_parser_bad_token02.ets @@ -19,6 +19,8 @@ } /* @@? 18:18 Error SyntaxError: Identifier expected, got ':'. */ -/* @@? 19:1 Error SyntaxError: Missing type annotation for property 'number'. */ +/* @@? 18:20 Error SyntaxError: number is a predefined type, cannot be used as an identifier */ +/* @@? 18:20 Error SyntaxError: number is a predefined type, cannot be used as an identifier */ +/* @@? 19:1 Error SyntaxError: Identifier expected, got '}'. */ /* @@? 18:5 Error TypeError: Unresolved reference testProperty2 */ /* @@? 18:5 Error TypeError: Invalid value for annotation field, expected a constant literal. */ diff --git a/ets2panda/test/ast/parser/ets/annotations_tests/annotationDecl_parser_bad_token03.ets b/ets2panda/test/ast/parser/ets/annotations_tests/annotationDecl_parser_bad_token03.ets index 5fa3741fd0..7f8809336f 100644 --- a/ets2panda/test/ast/parser/ets/annotations_tests/annotationDecl_parser_bad_token03.ets +++ b/ets2panda/test/ast/parser/ets/annotations_tests/annotationDecl_parser_bad_token03.ets @@ -15,9 +15,11 @@ @interface MyAnno { testProperty1: string = testProperty2/* @@ label1 */: number -/* @@ label3 */} +} /* @@@ label1 Error SyntaxError: Identifier expected, got ':'. */ -/* @@@ label3 Error SyntaxError: Missing type annotation for property 'number'. */ +/* @@? 17:35 Error SyntaxError: number is a predefined type, cannot be used as an identifier */ +/* @@? 17:35 Error SyntaxError: number is a predefined type, cannot be used as an identifier */ +/* @@? 18:1 Error SyntaxError: Identifier expected, got '}'. */ /* @@? 17:5 Error TypeError: Unresolved reference testProperty2 */ /* @@? 17:5 Error TypeError: Invalid value for annotation field, expected a constant literal. */ diff --git a/ets2panda/test/ast/parser/ets/non-ambient_call_signature.ets b/ets2panda/test/ast/parser/ets/non-ambient_call_signature.ets index 0b389ebc8c..a2ab27116b 100644 --- a/ets2panda/test/ast/parser/ets/non-ambient_call_signature.ets +++ b/ets2panda/test/ast/parser/ets/non-ambient_call_signature.ets @@ -20,4 +20,5 @@ class A{ /* @@@ label Error SyntaxError: Unexpected token '('. */ /* @@@ label1 Error SyntaxError: Unexpected token ')'. */ /* @@@ label2 Error SyntaxError: Unexpected token ':'. */ +/* @@? 17:60 Error SyntaxError: number is a predefined type, cannot be used as an identifier */ /* @@@ label3 Error SyntaxError: Field type annotation expected. */ diff --git a/ets2panda/test/ast/parser/ets/user_defined_10.ets b/ets2panda/test/ast/parser/ets/user_defined_10.ets index f34b440d7b..3f505ccfbd 100644 --- a/ets2panda/test/ast/parser/ets/user_defined_10.ets +++ b/ets2panda/test/ast/parser/ets/user_defined_10.ets @@ -17,6 +17,5 @@ struct number{ a : string = "15"; } -/* @@? 16:8 Error SyntaxError: Cannot be used as user-defined type. */ /* @@? 16:1 Error TypeError: Structs are only used to define UI components, it should be translated at 'plugin after parser' phase. */ -/* @@? 1:3 Error TypeError: Variable 'number' is already defined with different type. */ +/* @@? 16:8 Error SyntaxError: number is a predefined type, cannot be used as an identifier */ diff --git a/ets2panda/test/ast/parser/ets/user_defined_11.ets b/ets2panda/test/ast/parser/ets/user_defined_11.ets index 685fc998d6..e04f80779f 100644 --- a/ets2panda/test/ast/parser/ets/user_defined_11.ets +++ b/ets2panda/test/ast/parser/ets/user_defined_11.ets @@ -17,5 +17,4 @@ class /* @@ label */number{ a : string = "15"; } -/* @@@ label Error SyntaxError: Cannot be used as user-defined type. */ -/* @@? 1:3 Error TypeError: Variable 'number' is already defined with different type. */ +/* @@? 16:21 Error SyntaxError: number is a predefined type, cannot be used as an identifier */ diff --git a/ets2panda/test/parser/ets/cast_expressions4-expected.txt b/ets2panda/test/parser/ets/cast_expressions4-expected.txt index abe24eaa45..c8928bab12 100644 --- a/ets2panda/test/parser/ets/cast_expressions4-expected.txt +++ b/ets2panda/test/parser/ets/cast_expressions4-expected.txt @@ -919,7 +919,7 @@ "type": "VariableDeclarator", "id": { "type": "Identifier", - "name": "object", + "name": "obj", "decorators": [], "loc": { "start": { @@ -929,7 +929,7 @@ }, "end": { "line": 21, - "column": 13, + "column": 10, "program": "cast_expressions4.ets" } } @@ -943,12 +943,12 @@ "loc": { "start": { "line": 21, - "column": 16, + "column": 13, "program": "cast_expressions4.ets" }, "end": { "line": 21, - "column": 21, + "column": 18, "program": "cast_expressions4.ets" } } @@ -964,12 +964,12 @@ "loc": { "start": { "line": 21, - "column": 25, + "column": 22, "program": "cast_expressions4.ets" }, "end": { "line": 21, - "column": 31, + "column": 28, "program": "cast_expressions4.ets" } } @@ -977,12 +977,12 @@ "loc": { "start": { "line": 21, - "column": 25, + "column": 22, "program": "cast_expressions4.ets" }, "end": { "line": 21, - "column": 32, + "column": 29, "program": "cast_expressions4.ets" } } @@ -990,12 +990,12 @@ "loc": { "start": { "line": 21, - "column": 25, + "column": 22, "program": "cast_expressions4.ets" }, "end": { "line": 21, - "column": 32, + "column": 29, "program": "cast_expressions4.ets" } } @@ -1003,12 +1003,12 @@ "loc": { "start": { "line": 21, - "column": 16, + "column": 13, "program": "cast_expressions4.ets" }, "end": { "line": 21, - "column": 21, + "column": 18, "program": "cast_expressions4.ets" } } @@ -1021,7 +1021,7 @@ }, "end": { "line": 21, - "column": 21, + "column": 18, "program": "cast_expressions4.ets" } } @@ -1036,7 +1036,7 @@ }, "end": { "line": 21, - "column": 32, + "column": 29, "program": "cast_expressions4.ets" } } diff --git a/ets2panda/test/parser/ets/cast_expressions4.ets b/ets2panda/test/parser/ets/cast_expressions4.ets index 6b855e849c..558abf8a36 100644 --- a/ets2panda/test/parser/ets/cast_expressions4.ets +++ b/ets2panda/test/parser/ets/cast_expressions4.ets @@ -18,5 +18,5 @@ function widening_array_test(): void { let objects: Object[] = ints as Object[]; let ints2: Int[] = objects as Int[]; - let object = ints2 as Object; + let obj = ints2 as Object; } diff --git a/ets2panda/test/runtime/ets/array-object.ets b/ets2panda/test/runtime/ets/array-object.ets index c8f34ec660..f0555dda36 100644 --- a/ets2panda/test/runtime/ets/array-object.ets +++ b/ets2panda/test/runtime/ets/array-object.ets @@ -14,33 +14,33 @@ */ function main(): void { - let arr1: Int[] = [1,2,3,4,5]; - let arr2: int[] = [1,2,3,4,5]; - let object_array: Object[] = arr1 as Object[]; - let object: Object = arr1 as Object; + let arr1: FixedArray = [1,2,3,4,5]; + let arr2: FixedArray = [1,2,3,4,5]; + let object_array: FixedArray = arr1 as FixedArray; + let obj: Object = arr1 as Object; // TypeError: Cannot access property of non-object or non-enum type // arr1.toString(); // arr2.toString(); // object_array.toString(); - object.toString(); + obj.toString(); // TypeError: Cannot access property of non-object or non-enum type // arr1.$_hashCode(); // arr2.$_hashCode(); // object_array.$_hashCode(); - object.$_hashCode(); + obj.$_hashCode(); assertEQ(arr1, arr1) assertEQ(arr1, object_array) - assertEQ(arr1, object) + assertEQ(arr1, obj) assertNE(arr1, arr2) // Cannot cast type 'int[]' to 'Object[]' // let object_array2: Object[] = arr2 as Object[]; -// assertEQ(object.equals(arr2 as Object), false) +// assertEQ(obj.equals(arr2 as Object), false) assertEQ(arr2, arr2) assertNE(arr2, new int[5]) diff --git a/ets2panda/test/runtime/ets/optional-chaining-lazy-evaluation.ets b/ets2panda/test/runtime/ets/optional-chaining-lazy-evaluation.ets index 4287ef3191..a8d4b83a3b 100644 --- a/ets2panda/test/runtime/ets/optional-chaining-lazy-evaluation.ets +++ b/ets2panda/test/runtime/ets/optional-chaining-lazy-evaluation.ets @@ -26,14 +26,14 @@ function main(): void { let x: int = 0; let potentiallyNullObj: Int[] | null = foo1(); - let number: Int | undefined = potentiallyNullObj?.[x++] ?? 2; - assertEQ(number, 2) + let numb: Int | undefined = potentiallyNullObj?.[x++] ?? 2; + assertEQ(numb, 2) assertEQ(x, 0) // 0 as x was not incremented let obj: Int[] | null = foo2(); - number = obj?.[x++]; + numb = obj?.[x++]; let a : Int = 11; - assertEQ(number, a) + assertEQ(numb, a) assertEQ(x, 1) // 1 as x was incremented } diff --git a/ets2panda/util/diagnostic/syntax.yaml b/ets2panda/util/diagnostic/syntax.yaml index 0cac3b2b88..60d0b0da2e 100644 --- a/ets2panda/util/diagnostic/syntax.yaml +++ b/ets2panda/util/diagnostic/syntax.yaml @@ -1159,3 +1159,35 @@ syntax: - name: RETURN_WITH_VALUE id: 287 message: "Unexpected return value." + +- name: INVALID_INIT_IN_PACKAGE + id: 288 + message: "Non-constant initializer of Package should be apply in Initializer Block." + +- name: PACKAGE_MULTIPLE_STATIC_BLOCK + id: 289 + message: "static block cannot apply to multi-files for one package" + +- name: CONSTANT_MULTI_INITIALIZED_IN_STATIC_BLOCK + id: 290 + message: "package constant property initialization can only be applied once in static block" + +- name: INVALID_PACKAGE_TOP_LEVEL_STMT + id: 291 + message: "Invalid package toplevel statement" + +- name: ONLY_CONSTANT_ALLOWED + id: 292 + message: "Only constant expression is expected in the field" + +- name: ENUM_OR_ANNOTATION_DIVIDE_BY_ZERO + id: 293 + message: "Division by zero are not allowed in Enum or Annotation" + +- name: MISSING_INIT_FOR_CONST_PACKAGE_PROP + id: 294 + message: "Missing initialization for const package property" + +- name: PREDEFINED_TYPE_AS_IDENTIFIER + id: 295 + message: "{} is a predefined type, cannot be used as an identifier" -- Gitee From e61d862708e4cc3c2024ee15d1c1ad9d8e47d1ea Mon Sep 17 00:00:00 2001 From: Peter Pronai Date: Mon, 3 Mar 2025 13:57:21 +0000 Subject: [PATCH 132/268] Remove more LogTypeError uses Only one remaining is the one in `plugin_phase.cpp`. Fixes #22423 internal issue. Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBT8SY Change-Id: I7a6392b8bad3c7900cf93c4c4f77c3fcce40bb80 Signed-off-by: Peter Pronai --- ets2panda/checker/ETSAnalyzer.cpp | 45 ++-- ets2panda/checker/ETSAnalyzerHelpers.cpp | 18 +- ets2panda/checker/ETSchecker.cpp | 25 +- ets2panda/checker/ETSchecker.h | 18 +- ets2panda/checker/TSAnalyzer.cpp | 31 +-- ets2panda/checker/checker.cpp | 51 ++-- ets2panda/checker/checker.h | 41 +--- ets2panda/checker/ets/castingContext.cpp | 6 +- ets2panda/checker/ets/castingContext.h | 3 +- ets2panda/checker/ets/function.cpp | 25 +- ets2panda/checker/ets/helpers.cpp | 16 +- ets2panda/checker/ets/object.cpp | 6 +- ets2panda/checker/ets/typeCheckingHelpers.cpp | 19 +- ets2panda/checker/ets/typeRelationContext.cpp | 2 +- ets2panda/checker/ets/typeRelationContext.h | 8 +- ets2panda/checker/ets/validateHelpers.cpp | 21 +- ets2panda/checker/ts/destructuringContext.cpp | 7 +- ets2panda/checker/ts/helpers.cpp | 6 +- ets2panda/checker/ts/object.cpp | 20 +- ets2panda/checker/typeChecker/TypeChecker.h | 5 - .../checker/types/ets/etsTypeParameter.cpp | 17 +- ets2panda/checker/types/typeRelation.cpp | 9 +- ets2panda/checker/types/typeRelation.h | 6 +- ets2panda/ir/expressions/arrayExpression.cpp | 4 +- ets2panda/ir/expressions/memberExpression.cpp | 6 +- ets2panda/ir/statements/forOfStatement.cpp | 2 +- .../ir/statements/switchCaseStatement.cpp | 19 +- .../ets/instanceof_with_not_object_type.ets | 2 +- .../ets/dynamic_instanceof_error-expected.txt | 2 +- ets2panda/util/diagnostic.h | 5 + ets2panda/util/diagnostic/semantic.yaml | 232 +++++++++++++++++- 31 files changed, 416 insertions(+), 261 deletions(-) diff --git a/ets2panda/checker/ETSAnalyzer.cpp b/ets2panda/checker/ETSAnalyzer.cpp index a1e8265d06..9cd41a50ad 100644 --- a/ets2panda/checker/ETSAnalyzer.cpp +++ b/ets2panda/checker/ETSAnalyzer.cpp @@ -438,13 +438,13 @@ static checker::Type *CheckInstantiatedNewType(ETSChecker *checker, ir::ETSNewCl return checker->InvalidateType(expr->GetTypeRef()); } if (calleeType->IsETSUnionType()) { - return checker->TypeError(expr->GetTypeRef(), "The union type is not constructible.", expr->Start()); + return checker->TypeError(expr->GetTypeRef(), diagnostic::UNION_NONCONSTRUCTIBLE, expr->Start()); } if (!ir::ETSNewClassInstanceExpression::TypeIsAllowedForInstantiation(calleeType)) { - return checker->TypeError(expr->GetTypeRef(), {"Type '", calleeType, "' is not constructible."}, expr->Start()); + return checker->TypeError(expr->GetTypeRef(), diagnostic::CALLEE_NONCONSTRUCTIBLE, {calleeType}, expr->Start()); } if (!calleeType->IsETSObjectType()) { - return checker->TypeError(expr->GetTypeRef(), "This expression is not constructible.", expr->Start()); + return checker->TypeError(expr->GetTypeRef(), diagnostic::EXPR_NONCONSTRUCTIBLE, {}, expr->Start()); } auto calleeObj = calleeType->AsETSObjectType(); @@ -710,14 +710,14 @@ static bool CheckElement(ETSChecker *checker, Type *const preferredType, } auto ctx = AssignmentContext(checker->Relation(), currentElement, elementType, compareType, - currentElement->Start(), {}, TypeRelationFlag::NO_THROW); + currentElement->Start(), std::nullopt, TypeRelationFlag::NO_THROW); if (!ctx.IsAssignable()) { checker->LogError(diagnostic::TUPLE_UNASSIGNABLE_ARRAY, {idx}, currentElement->Start()); return false; } const CastingContext castCtx( - checker->Relation(), {"this cast should never fail"}, + checker->Relation(), diagnostic::CAST_FAIL_UNREACHABLE, {}, CastingContext::ConstructorData {currentElement, compareType, checker->MaybeBoxType(compareType), currentElement->Start(), TypeRelationFlag::NO_THROW}); @@ -836,7 +836,7 @@ checker::Type *ETSAnalyzer::Check(ir::ArrayExpression *expr) const } if (expr->GetPreferredType() == nullptr) { - return checker->TypeError(expr, "Can't resolve array type", expr->Start()); + return checker->TypeError(expr, diagnostic::UNRESOLVABLE_ARRAY, expr->Start()); } expr->SetTsType(expr->GetPreferredType()); @@ -1015,11 +1015,9 @@ checker::Type *ETSAnalyzer::Check(ir::AssignmentExpression *const expr) const checker::Type *smartType = rightType; if (!leftType->IsTypeError()) { - if (auto ctx = checker::AssignmentContext( - // CC-OFFNXT(G.FMT.06-CPP) project code style - checker->Relation(), relationNode, rightType, leftType, expr->Right()->Start(), - // CC-OFFNXT(G.FMT.06-CPP) project code style - {"Type '", rightType, "' cannot be assigned to type '", leftType, "'"}); + if (const auto ctx = checker::AssignmentContext(checker->Relation(), relationNode, rightType, leftType, + expr->Right()->Start(), + {{diagnostic::INVALID_ASSIGNMNENT, {rightType, leftType}}}); ctx.IsAssignable()) { smartType = GetSmartType(expr, leftType, rightType); } @@ -1097,8 +1095,7 @@ checker::Type *ETSAnalyzer::Check(ir::AwaitExpression *expr) const // Check the argument type of await expression if (!argType->IsETSObjectType() || (argType->AsETSObjectType()->GetOriginalBaseType() != checker->GlobalBuiltinPromiseType())) { - return checker->TypeError(expr, "'await' expressions require Promise object as argument.", - expr->Argument()->Start()); + return checker->TypeError(expr, diagnostic::AWAITED_NOT_PROMISE, expr->Argument()->Start()); } Type *type = argType->AsETSObjectType()->TypeArguments().at(0); @@ -1488,12 +1485,12 @@ static Type *TransformTypeForMethodReference(ETSChecker *checker, ir::Expression } if (type->AsETSFunctionType()->CallSignatures().at(0)->HasSignatureFlag(SignatureFlags::PRIVATE)) { - checker->LogTypeError("Private method is used as value", getUseSite()); + checker->LogError(diagnostic::PRIVATE_METHOD_AS_VALUE, getUseSite()); return checker->GlobalTypeError(); } if (type->AsETSFunctionType()->CallSignatures().size() > 1) { - checker->LogTypeError("Overloaded method is used as value", getUseSite()); + checker->LogError(diagnostic::OVERLOADED_METHOD_AS_VALUE, getUseSite()); return checker->GlobalTypeError(); } return type->AsETSFunctionType()->MethodToArrow(checker); @@ -1556,9 +1553,8 @@ std::pair SearchReExportsType(ETSObjectType * static void TypeErrorOnMissingProperty(ir::MemberExpression *expr, checker::Type *baseType, checker::ETSChecker *checker) { - std::ignore = checker->TypeError( - expr, {"Property '", expr->Property()->AsIdentifier()->Name(), "' does not exist on type '", baseType, "'"}, - expr->Object()->Start()); + std::ignore = checker->TypeError(expr, diagnostic::PROPERTY_NONEXISTENT, + {expr->Property()->AsIdentifier()->Name(), baseType}, expr->Object()->Start()); } checker::Type *ETSAnalyzer::ResolveMemberExpressionByBaseType(ETSChecker *checker, checker::Type *baseType, @@ -1735,7 +1731,7 @@ checker::Type *ETSAnalyzer::Check(ir::ObjectExpression *expr) const } } if (!haveEmptyConstructor) { - return checker->TypeError(expr, {"type ", objType->Name(), " has no parameterless constructor"}, expr->Start()); + return checker->TypeError(expr, diagnostic::NO_PARAMLESS_CTOR, {objType->Name()}, expr->Start()); } CheckObjectExprProps(expr, checker::PropertySearchFlags::SEARCH_INSTANCE_FIELD | @@ -1789,9 +1785,8 @@ void ETSAnalyzer::CheckObjectExprProps(const ir::ObjectExpression *expr, checker key->SetTsType(propType); value->SetTsType(value->Check(checker)); - checker::AssignmentContext( - checker->Relation(), value, value->TsType(), propType, value->Start(), - {"Type '", value->TsType(), "' is not compatible with type '", propType, "' at property '", pname, "'"}); + checker::AssignmentContext(checker->Relation(), value, value->TsType(), propType, value->Start(), + {{diagnostic::PROP_INCOMPAT, {value->TsType(), propType, pname}}}); } if (objType->HasObjectFlag(ETSObjectFlags::REQUIRED)) { @@ -2899,11 +2894,11 @@ checker::Type *ETSAnalyzer::Check(ir::TSAsExpression *expr) const } if (sourceType->DefinitelyETSNullish() && !targetType->PossiblyETSNullish()) { - return checker->TypeError(expr, "Cannot cast 'null' or 'undefined' to non-nullish type.", expr->Start()); + return checker->TypeError(expr, diagnostic::NULLISH_CAST_TO_NONNULLISH, expr->Start()); } const checker::CastingContext ctx( - checker->Relation(), {"Cannot cast type '", sourceType, "' to '", targetType, "'"}, + checker->Relation(), diagnostic::INVALID_CAST, {sourceType, targetType}, checker::CastingContext::ConstructorData {expr->Expr(), sourceType, targetType, expr->Expr()->Start()}); if (sourceType->IsETSDynamicType() && targetType->IsLambdaObject()) { @@ -2922,7 +2917,7 @@ checker::Type *ETSAnalyzer::Check(ir::TSAsExpression *expr) const } if (targetType == checker->GetGlobalTypesHolder()->GlobalETSNeverType()) { - return checker->TypeError(expr, "Cast to 'never' is prohibited", expr->Start()); + return checker->TypeError(expr, diagnostic::CAST_TO_NEVER, expr->Start()); } checker->ComputeApparentType(targetType); diff --git a/ets2panda/checker/ETSAnalyzerHelpers.cpp b/ets2panda/checker/ETSAnalyzerHelpers.cpp index fd362f6f4a..473909a8d1 100644 --- a/ets2panda/checker/ETSAnalyzerHelpers.cpp +++ b/ets2panda/checker/ETSAnalyzerHelpers.cpp @@ -596,11 +596,9 @@ checker::Type *GetIteratorType(ETSChecker *checker, checker::Type *elemType, ir: auto *decl = variable->Declaration(); if (decl->IsConstDecl() || decl->IsReadonlyDecl()) { - const auto errorMsg = + const auto &errorMsg = decl->IsConstDecl() ? diagnostic::INVALID_CONST_ASSIGNMENT : diagnostic::INVALID_READONLY_ASSIGNMENT; - // NOTE(pronaip): see memory corruption issue in 23053, replace with LogError once resolved - checker->LogTypeError({errorMsg.Message().substr(0, errorMsg.Message().size() - 2), variable->Name()}, - decl->Node()->Start()); + checker->LogError(errorMsg, {variable->Name()}, decl->Node()->Start()); } iterType = left->AsIdentifier()->TsType(); } else if (left->IsVariableDeclaration()) { @@ -636,7 +634,7 @@ bool CheckReturnType(ETSChecker *checker, checker::Type *funcReturnType, checker return false; } if (!checker::AssignmentContext(checker->Relation(), stArgument, argumentType, funcReturnType, - stArgument->Start(), {}, + stArgument->Start(), std::nullopt, checker::TypeRelationFlag::DIRECT_RETURN | checker::TypeRelationFlag::NO_THROW) // CC-OFFNXT(G.FMT.02) project code style .IsAssignable()) { @@ -649,7 +647,8 @@ bool CheckReturnType(ETSChecker *checker, checker::Type *funcReturnType, checker if (containingFunc->IsAsyncFunc() && funcReturnType->IsETSObjectType() && funcReturnType->AsETSObjectType()->GetOriginalBaseType() == checker->GlobalBuiltinPromiseType()) { auto promiseArg = funcReturnType->AsETSObjectType()->TypeArguments()[0]; - checker::AssignmentContext(checker->Relation(), stArgument, argumentType, promiseArg, stArgument->Start(), {}, + checker::AssignmentContext(checker->Relation(), stArgument, argumentType, promiseArg, stArgument->Start(), + std::nullopt, checker::TypeRelationFlag::DIRECT_RETURN | checker::TypeRelationFlag::NO_THROW); if (checker->Relation()->IsTrue()) { return true; @@ -657,7 +656,8 @@ bool CheckReturnType(ETSChecker *checker, checker::Type *funcReturnType, checker } if (!checker::AssignmentContext(checker->Relation(), stArgument, argumentType, funcReturnType, stArgument->Start(), - {}, checker::TypeRelationFlag::DIRECT_RETURN | checker::TypeRelationFlag::NO_THROW) + std::nullopt, + checker::TypeRelationFlag::DIRECT_RETURN | checker::TypeRelationFlag::NO_THROW) // CC-OFFNXT(G.FMT.02) project code style .IsAssignable()) { checker->LogError(diagnostic::ARROW_TYPE_MISMATCH, {argumentType, funcReturnType}, stArgument->Start()); @@ -691,7 +691,7 @@ void InferReturnType(ETSChecker *checker, ir::ScriptFunction *containingFunc, ch auto *argumentType = arrowFunc->TsType(); funcReturnType = typeAnnotation->GetType(checker); if (!checker::AssignmentContext(checker->Relation(), arrowFunc, argumentType, funcReturnType, - stArgument->Start(), {}, + stArgument->Start(), std::nullopt, checker::TypeRelationFlag::DIRECT_RETURN | checker::TypeRelationFlag::NO_THROW) // CC-OFFNXT(G.FMT.02) project code style .IsAssignable()) { @@ -730,7 +730,7 @@ void CastPossibleTupleOnRHS(ETSChecker *checker, ir::AssignmentExpression *expr) auto *storedTupleType = expr->Left()->AsMemberExpression()->Object()->TsType(); const checker::CastingContext tupleCast( - checker->Relation(), {"this cast should never fail"}, + checker->Relation(), diagnostic::CAST_FAIL_UNREACHABLE, {}, checker::CastingContext::ConstructorData {expr->Right(), expr->Right()->TsType(), storedTupleType, expr->Right()->Start(), TypeRelationFlag::NO_THROW}); } diff --git a/ets2panda/checker/ETSchecker.cpp b/ets2panda/checker/ETSchecker.cpp index 3bb826b613..122718064b 100644 --- a/ets2panda/checker/ETSchecker.cpp +++ b/ets2panda/checker/ETSchecker.cpp @@ -592,30 +592,29 @@ Type *ETSChecker::InvalidateType(ir::Typed *node) return node->SetTsType(GlobalTypeError()); } -Type *ETSChecker::TypeError(ir::Typed *node, std::string_view message, const lexer::SourcePosition &at) +Type *ETSChecker::TypeError(ir::Typed *node, const diagnostic::DiagnosticKind &diagKind, + const lexer::SourcePosition &at) { - LogTypeError(message, at); - return InvalidateType(node); + return TypeError(node, diagKind, util::DiagnosticMessageParams {}, at); } -Type *ETSChecker::TypeError(ir::Typed *node, const util::DiagnosticMessageParams &list, - const lexer::SourcePosition &at) +Type *ETSChecker::TypeError(ir::Typed *node, const diagnostic::DiagnosticKind &diagKind, + const util::DiagnosticMessageParams &list, const lexer::SourcePosition &at) { - LogTypeError(list, at); + LogError(diagKind, list, at); return InvalidateType(node); } -Type *ETSChecker::TypeError(varbinder::Variable *var, std::string_view message, const lexer::SourcePosition &at) +Type *ETSChecker::TypeError(varbinder::Variable *var, const diagnostic::DiagnosticKind &diagKind, + const lexer::SourcePosition &at) { - LogTypeError(message, at); - var->SetTsType(GlobalTypeError()); - return var->TsType(); + return TypeError(var, diagKind, {}, at); } -Type *ETSChecker::TypeError(varbinder::Variable *var, const util::DiagnosticMessageParams &list, - const lexer::SourcePosition &at) +Type *ETSChecker::TypeError(varbinder::Variable *var, const diagnostic::DiagnosticKind &diagKind, + const util::DiagnosticMessageParams &list, const lexer::SourcePosition &at) { - LogTypeError(list, at); + LogError(diagKind, list, at); var->SetTsType(GlobalTypeError()); return var->TsType(); } diff --git a/ets2panda/checker/ETSchecker.h b/ets2panda/checker/ETSchecker.h index 42c4a3e529..cd809667d0 100644 --- a/ets2panda/checker/ETSchecker.h +++ b/ets2panda/checker/ETSchecker.h @@ -16,6 +16,7 @@ #ifndef ES2PANDA_CHECKER_ETS_CHECKER_H #define ES2PANDA_CHECKER_ETS_CHECKER_H +#include #include #include "checker/checker.h" @@ -70,7 +71,9 @@ using FunctionalInterfaceMap = ArenaUnorderedMap; using DynamicCallNamesMap = ArenaMap, uint32_t>; using ConstraintCheckRecord = std::tuple *, const Substitution *, lexer::SourcePosition>; -using DiagnosticInfo = std::pair, util::DiagnosticMessageParams>; +// can't use util::DiagnosticWithParams because std::optional can't contain references +using MaybeDiagnosticInfo = + std::optional>; class ETSChecker final : public Checker { public: @@ -153,13 +156,14 @@ public: Type *GlobalTypeError() const; [[nodiscard]] Type *InvalidateType(ir::Typed *node); - [[nodiscard]] Type *TypeError(ir::Typed *node, std::string_view message, + [[nodiscard]] Type *TypeError(ir::Typed *node, const diagnostic::DiagnosticKind &diagKind, const lexer::SourcePosition &at); - [[nodiscard]] Type *TypeError(ir::Typed *node, const util::DiagnosticMessageParams &list, - const lexer::SourcePosition &at); - [[nodiscard]] Type *TypeError(varbinder::Variable *var, std::string_view message, const lexer::SourcePosition &at); - [[nodiscard]] Type *TypeError(varbinder::Variable *var, const util::DiagnosticMessageParams &list, + [[nodiscard]] Type *TypeError(ir::Typed *node, const diagnostic::DiagnosticKind &diagKind, + const util::DiagnosticMessageParams &list, const lexer::SourcePosition &at); + [[nodiscard]] Type *TypeError(varbinder::Variable *var, const diagnostic::DiagnosticKind &diagKind, const lexer::SourcePosition &at); + [[nodiscard]] Type *TypeError(varbinder::Variable *var, const diagnostic::DiagnosticKind &diagKind, + const util::DiagnosticMessageParams &list, const lexer::SourcePosition &at); void InitializeBuiltins(varbinder::ETSBinder *varbinder); void InitializeBuiltin(varbinder::Variable *var, const util::StringView &name); @@ -500,7 +504,7 @@ public: bool NeedToVerifySignatureVisibility(Signature *signature, const lexer::SourcePosition &pos); void ValidateSignatureAccessibility(ETSObjectType *callee, const ir::CallExpression *callExpr, Signature *signature, const lexer::SourcePosition &pos, - const DiagnosticInfo &errorInfo = {std::nullopt, {}}); + const MaybeDiagnosticInfo &maybeErrorInfo = std::nullopt); void CheckCapturedVariables(); void CheckCapturedVariableInSubnodes(ir::AstNode *node, varbinder::Variable *var); void CheckCapturedVariable(ir::AstNode *node, varbinder::Variable *var); diff --git a/ets2panda/checker/TSAnalyzer.cpp b/ets2panda/checker/TSAnalyzer.cpp index 25a4cf6789..cfaad3f534 100644 --- a/ets2panda/checker/TSAnalyzer.cpp +++ b/ets2panda/checker/TSAnalyzer.cpp @@ -1253,9 +1253,8 @@ checker::Type *TSAnalyzer::Check(ir::ReturnStatement *st) const returnType = checker->CheckTypeCached(st->Argument()); } - checker->IsTypeAssignableTo(returnType, funcReturnType, - {"Type '", returnType, "' is not assignable to type '", funcReturnType, "'."}, - st->Start()); + checker->IsTypeAssignableTo(returnType, funcReturnType, diagnostic::INVALID_ASSIGNMNENT_2, + {returnType, funcReturnType}, st->Start()); } return nullptr; @@ -1356,11 +1355,8 @@ static void CheckSimpleVariableDeclaration(checker::TSChecker *checker, ir::Vari } if (previousType != nullptr) { - checker->IsTypeIdenticalTo(bindingVar->TsType(), previousType, - {"Subsequent variable declaration must have the same type. Variable '", - bindingVar->Name(), "' must be of type '", previousType, "', but here has type '", - bindingVar->TsType(), "'."}, - declarator->Id()->Start()); + checker->IsTypeIdenticalTo(bindingVar->TsType(), previousType, diagnostic::DIFFERENT_SUBSEQ_DECL, + {bindingVar->Name(), previousType, bindingVar->TsType()}, declarator->Id()->Start()); } checker->RemoveStatus(checker::CheckerStatus::IN_CONST_CONTEXT); @@ -1498,12 +1494,8 @@ checker::Type *TSAnalyzer::Check(ir::TSAsExpression *expr) const checker::Type *exprType = checker->GetBaseTypeOfLiteralType(expr->Expr()->Check(checker)); checker::Type *targetType = expr->TypeAnnotation()->GetType(checker); - checker->IsTypeComparableTo( - targetType, exprType, - {"Conversion of type '", exprType, "' to type '", targetType, - "' may be a mistake because neither type sufficiently overlaps with the other. If this was ", - "intentional, convert the expression to 'unknown' first."}, - expr->Start()); + checker->IsTypeComparableTo(targetType, exprType, diagnostic::DISJOINT_CONVERSION, {exprType, targetType}, + expr->Start()); return targetType; } @@ -1940,10 +1932,8 @@ static void CheckInheritedPropertiesAreIdentical(checker::TSChecker *checker, ch } else if (res->second.second != type) { checker::Type *sourceType = checker->GetTypeOfVariable(inheritedProp); checker::Type *targetType = checker->GetTypeOfVariable(res->second.first); - checker->IsTypeIdenticalTo(sourceType, targetType, - {"Interface '", type, "' cannot simultaneously extend types '", - res->second.second, "' and '", base->AsInterfaceType(), "'."}, - locInfo); + checker->IsTypeIdenticalTo(sourceType, targetType, diagnostic::IFACE_MULTIPLE_EXTENSION, + {type, res->second.second, base->AsInterfaceType()}, locInfo); } } } @@ -1971,9 +1961,8 @@ checker::Type *TSAnalyzer::Check(ir::TSInterfaceDeclaration *st) const CheckInheritedPropertiesAreIdentical(checker, resolvedInterface, st->Id()->Start()); for (auto *base : resolvedInterface->Bases()) { - checker->IsTypeAssignableTo( - resolvedInterface, base, - {"Interface '", st->Id()->Name(), "' incorrectly extends interface '", base, "'"}, st->Id()->Start()); + checker->IsTypeAssignableTo(resolvedInterface, base, diagnostic::IFACE_INVALID_EXTENDS, + {st->Id()->Name(), base}, st->Id()->Start()); } checker->CheckIndexConstraints(resolvedInterface); diff --git a/ets2panda/checker/checker.cpp b/ets2panda/checker/checker.cpp index b5c962d1d2..79ca7ea099 100644 --- a/ets2panda/checker/checker.cpp +++ b/ets2panda/checker/checker.cpp @@ -42,9 +42,9 @@ void Checker::LogError(const diagnostic::DiagnosticKind &diagnostic, diagnosticEngine_.LogDiagnostic(diagnostic, diagnosticParams, pos); } -void Checker::LogTypeError(const util::DiagnosticMessageParams &list, const lexer::SourcePosition &pos) +void Checker::LogError(const diagnostic::DiagnosticKind &diagnostic, const lexer::SourcePosition &pos) { - diagnosticEngine_.LogSemanticError(list, pos); + LogError(diagnostic, {}, pos); } void Checker::LogTypeError(std::string_view message, const lexer::SourcePosition &pos) @@ -79,24 +79,21 @@ bool Checker::IsTypeIdenticalTo(Type *source, Type *target) return relation_->IsIdenticalTo(source, target); } -bool Checker::IsTypeIdenticalTo(Type *source, Type *target, const std::string &errMsg, - const lexer::SourcePosition &errPos) +bool Checker::IsTypeIdenticalTo(Type *source, Type *target, const diagnostic::DiagnosticKind &diagKind, + const util::DiagnosticMessageParams &diagParams, const lexer::SourcePosition &errPos) { if (!IsTypeIdenticalTo(source, target)) { - relation_->RaiseError(errMsg, errPos); + relation_->GetChecker()->LogError(diagKind, diagParams, errPos); + return false; } return true; } -bool Checker::IsTypeIdenticalTo(Type *source, Type *target, const util::DiagnosticMessageParams &list, +bool Checker::IsTypeIdenticalTo(Type *source, Type *target, const diagnostic::DiagnosticKind &diagKind, const lexer::SourcePosition &errPos) { - if (!IsTypeIdenticalTo(source, target)) { - relation_->RaiseError(list, errPos); - } - - return true; + return IsTypeIdenticalTo(source, target, diagKind, {}, errPos); } bool Checker::IsTypeAssignableTo(Type *source, Type *target) @@ -104,21 +101,11 @@ bool Checker::IsTypeAssignableTo(Type *source, Type *target) return relation_->IsAssignableTo(source, target); } -bool Checker::IsTypeAssignableTo(Type *source, Type *target, const std::string &errMsg, - const lexer::SourcePosition &errPos) +bool Checker::IsTypeAssignableTo(Type *source, Type *target, const diagnostic::DiagnosticKind &diagKind, + const util::DiagnosticMessageParams &list, const lexer::SourcePosition &errPos) { if (!IsTypeAssignableTo(source, target)) { - relation_->RaiseError(errMsg, errPos); - } - - return true; -} - -bool Checker::IsTypeAssignableTo(Type *source, Type *target, const util::DiagnosticMessageParams &list, - const lexer::SourcePosition &errPos) -{ - if (!IsTypeAssignableTo(source, target)) { - relation_->RaiseError(list, errPos); + relation_->RaiseError(diagKind, list, errPos); } return true; @@ -129,21 +116,11 @@ bool Checker::IsTypeComparableTo(Type *source, Type *target) return relation_->IsComparableTo(source, target); } -bool Checker::IsTypeComparableTo(Type *source, Type *target, const std::string &errMsg, - const lexer::SourcePosition &errPos) -{ - if (!IsTypeComparableTo(source, target)) { - relation_->RaiseError(errMsg, errPos); - } - - return true; -} - -bool Checker::IsTypeComparableTo(Type *source, Type *target, const util::DiagnosticMessageParams &list, - const lexer::SourcePosition &errPos) +bool Checker::IsTypeComparableTo(Type *source, Type *target, const diagnostic::DiagnosticKind &diagKind, + const util::DiagnosticMessageParams &list, const lexer::SourcePosition &errPos) { if (!IsTypeComparableTo(source, target)) { - relation_->RaiseError(list, errPos); + relation_->RaiseError(diagKind, list, errPos); } return true; diff --git a/ets2panda/checker/checker.h b/ets2panda/checker/checker.h index e4ee6da08a..6720cd4f13 100644 --- a/ets2panda/checker/checker.h +++ b/ets2panda/checker/checker.h @@ -169,23 +169,22 @@ public: const util::DiagnosticMessageParams &diagnosticParams = {}); void LogError(const diagnostic::DiagnosticKind &diagnostic, const util::DiagnosticMessageParams &diagnosticParams, const lexer::SourcePosition &pos); + void LogError(const diagnostic::DiagnosticKind &diagnostic, const lexer::SourcePosition &pos); void LogTypeError(std::string_view message, const lexer::SourcePosition &pos); - void LogTypeError(const util::DiagnosticMessageParams &list, const lexer::SourcePosition &pos); void Warning(std::string_view message, const lexer::SourcePosition &pos) const; void ReportWarning(const util::DiagnosticMessageParams &list, const lexer::SourcePosition &pos); bool IsTypeIdenticalTo(Type *source, Type *target); - bool IsTypeIdenticalTo(Type *source, Type *target, const std::string &errMsg, const lexer::SourcePosition &errPos); - bool IsTypeIdenticalTo(Type *source, Type *target, const util::DiagnosticMessageParams &list, + bool IsTypeIdenticalTo(Type *source, Type *target, const diagnostic::DiagnosticKind &diagKind, + const util::DiagnosticMessageParams &diagParams, const lexer::SourcePosition &errPos); + bool IsTypeIdenticalTo(Type *source, Type *target, const diagnostic::DiagnosticKind &diagKind, const lexer::SourcePosition &errPos); bool IsTypeAssignableTo(Type *source, Type *target); - bool IsTypeAssignableTo(Type *source, Type *target, const std::string &errMsg, const lexer::SourcePosition &errPos); - bool IsTypeAssignableTo(Type *source, Type *target, const util::DiagnosticMessageParams &list, - const lexer::SourcePosition &errPos); + bool IsTypeAssignableTo(Type *source, Type *target, const diagnostic::DiagnosticKind &diagKind, + const util::DiagnosticMessageParams &list, const lexer::SourcePosition &errPos); bool IsTypeComparableTo(Type *source, Type *target); - bool IsTypeComparableTo(Type *source, Type *target, const std::string &errMsg, const lexer::SourcePosition &errPos); - bool IsTypeComparableTo(Type *source, Type *target, const util::DiagnosticMessageParams &list, - const lexer::SourcePosition &errPos); + bool IsTypeComparableTo(Type *source, Type *target, const diagnostic::DiagnosticKind &diagKind, + const util::DiagnosticMessageParams &list, const lexer::SourcePosition &errPos); bool AreTypesComparable(Type *source, Type *target); bool IsTypeEqualityComparableTo(Type *source, Type *target); bool IsAllTypesAssignableTo(Type *source, Type *target); @@ -263,29 +262,15 @@ private: class TypeStackElement { public: - explicit TypeStackElement(Checker *checker, void *element, const util::DiagnosticMessageParams &list, + explicit TypeStackElement(Checker *checker, void *element, const std::optional &diag, const lexer::SourcePosition &pos, bool isRecursive = false) - : checker_(checker), element_(element), hasErrorChecker_(false), isRecursive_(isRecursive), cleanup_(true) + : checker_(checker), element_(element), isRecursive_(isRecursive) { if (!checker->typeStack_.insert({element, nullptr}).second) { if (isRecursive_) { cleanup_ = false; } else { - checker_->LogTypeError(list, pos); - element_ = nullptr; - } - } - } - - explicit TypeStackElement(Checker *checker, void *element, std::string_view err, const lexer::SourcePosition &pos, - bool isRecursive = false) - : checker_(checker), element_(element), hasErrorChecker_(false), isRecursive_(isRecursive), cleanup_(true) - { - if (!checker->typeStack_.insert({element, nullptr}).second) { - if (isRecursive_) { - cleanup_ = false; - } else { - checker_->LogTypeError(err, pos); + checker_->LogError(diag->kind, diag->params, pos); element_ = nullptr; } } @@ -325,9 +310,9 @@ public: private: Checker *checker_; void *element_; - bool hasErrorChecker_; + bool hasErrorChecker_ {false}; bool isRecursive_; - bool cleanup_; + bool cleanup_ {true}; }; template diff --git a/ets2panda/checker/ets/castingContext.cpp b/ets2panda/checker/ets/castingContext.cpp index 3c91223fdc..0f1c377aaa 100644 --- a/ets2panda/checker/ets/castingContext.cpp +++ b/ets2panda/checker/ets/castingContext.cpp @@ -18,8 +18,8 @@ #include "checker/ETSchecker.h" namespace ark::es2panda::checker { -CastingContext::CastingContext(TypeRelation *relation, const util::DiagnosticMessageParams &list, - ConstructorData &&data) +CastingContext::CastingContext(TypeRelation *relation, const diagnostic::DiagnosticKind &diagKind, + const util::DiagnosticMessageParams &list, ConstructorData &&data) { flags_ |= data.extraFlags; @@ -35,7 +35,7 @@ CastingContext::CastingContext(TypeRelation *relation, const util::DiagnosticMes relation->Result(true); } if (!relation->IsTrue() && (flags_ & TypeRelationFlag::NO_THROW) == 0) { - relation->RaiseError(list, data.pos); + relation->RaiseError(diagKind, list, data.pos); } } diff --git a/ets2panda/checker/ets/castingContext.h b/ets2panda/checker/ets/castingContext.h index 0226ec6be7..a023f88eb4 100644 --- a/ets2panda/checker/ets/castingContext.h +++ b/ets2panda/checker/ets/castingContext.h @@ -31,7 +31,8 @@ public: }; // NOLINTEND(cppcoreguidelines-pro-type-member-init) - CastingContext(TypeRelation *relation, const util::DiagnosticMessageParams &list, ConstructorData &&data); + CastingContext(TypeRelation *relation, const diagnostic::DiagnosticKind &diagKind, + const util::DiagnosticMessageParams &list, ConstructorData &&data); [[nodiscard]] bool UncheckedCast() const noexcept; diff --git a/ets2panda/checker/ets/function.cpp b/ets2panda/checker/ets/function.cpp index 1128c8aa1d..c2bd9bd6c6 100644 --- a/ets2panda/checker/ets/function.cpp +++ b/ets2panda/checker/ets/function.cpp @@ -356,9 +356,9 @@ bool ETSChecker::ValidateSignatureInvocationContext(Signature *substitutedSig, i flags |= TypeRelationFlag::ONLY_CHECK_WIDENING; - auto const invocationCtx = checker::InvocationContext( - Relation(), argument, argumentType, targetType, argument->Start(), - {"Type '", argumentType, "' is not compatible with type '", targetType, "' at index ", index + 1}, flags); + auto const invocationCtx = + checker::InvocationContext(Relation(), argument, argumentType, targetType, argument->Start(), + {{diagnostic::TYPE_MISMATCH_AT_IDX, {argumentType, targetType, index + 1}}}, flags); return invocationCtx.IsInvocable() || CheckOptionalLambdaFunction(argument, substitutedSig, index); } @@ -376,11 +376,9 @@ bool ETSChecker::IsValidRestArgument(ir::Expression *const argument, Signature * if (substitutedSig->OwnerVar() == nullptr) { targetType = MaybeBoxType(targetType); } - auto const invocationCtx = - checker::InvocationContext(Relation(), argument, argumentType, targetType, argument->Start(), - {"Type '", argumentType, "' is not compatible with rest parameter type '", - targetType, "' at index ", index + 1}, - flags); + auto const invocationCtx = checker::InvocationContext( + Relation(), argument, argumentType, targetType, argument->Start(), + {{diagnostic::REST_PARAM_INCOMPAT_AT, {argumentType, targetType, index + 1}}}, flags); return invocationCtx.IsInvocable(); } @@ -424,8 +422,7 @@ bool ETSChecker::ValidateSignatureRestParams(Signature *substitutedSig, const Ar auto const invocationCtx = checker::InvocationContext( Relation(), restArgument, argumentType, substitutedSig->RestVar()->TsType(), argument->Start(), - {"Type '", argumentType, "' is not compatible with rest parameter type '", - substitutedSig->RestVar()->TsType(), "' at index ", index + 1}, + {{diagnostic::REST_PARAM_INCOMPAT_AT, {argumentType, substitutedSig->RestVar()->TsType(), index + 1}}}, flags); if (!invocationCtx.IsInvocable()) { if (restArgument->IsArrayExpression()) { @@ -1607,7 +1604,7 @@ bool ETSChecker::NeedToVerifySignatureVisibility(Signature *signature, const lex void ETSChecker::ValidateSignatureAccessibility(ETSObjectType *callee, const ir::CallExpression *callExpr, Signature *signature, const lexer::SourcePosition &pos, - const DiagnosticInfo &errorInfo) + const MaybeDiagnosticInfo &maybeErrorInfo) { if (!NeedToVerifySignatureVisibility(signature, pos)) { return; @@ -1643,12 +1640,12 @@ void ETSChecker::ValidateSignatureAccessibility(ETSObjectType *callee, const ir: return; } - const auto [diagnostic, diagnosticParams] = errorInfo; - if (diagnostic == std::nullopt) { + if (!maybeErrorInfo.has_value()) { LogError(diagnostic::SIG_INVISIBLE, {signature->Function()->Id()->Name(), signature}, pos); return; } - LogError(diagnostic.value(), diagnosticParams, pos); + const auto [diagnostic, diagnosticParams] = *maybeErrorInfo; + LogError(diagnostic, diagnosticParams, pos); } void ETSChecker::CheckCapturedVariable(ir::AstNode *const node, varbinder::Variable *const var) diff --git a/ets2panda/checker/ets/helpers.cpp b/ets2panda/checker/ets/helpers.cpp index b9e2439a12..02e6fe3efe 100644 --- a/ets2panda/checker/ets/helpers.cpp +++ b/ets2panda/checker/ets/helpers.cpp @@ -127,7 +127,7 @@ void ETSChecker::WrongContextErrorClassifyByType(ir::Identifier *ident) break; default: - LogTypeError({"Identifier '", ident->Name(), "' is used in wrong context."}, ident->Start()); + LogError(diagnostic::ID_WRONG_CTX, {ident->Name()}, ident->Start()); return; } LogError(diagnostic::ID_IN_WRONG_CTX, {identCategoryName.c_str(), ident->Name()}, ident->Start()); @@ -759,10 +759,10 @@ static void CheckRecordType(ir::Expression *init, checker::Type *annotationType, checker::AssignmentContext( checker->Relation(), p->Key(), keyType, typeArguments[0], p->Key()->Start(), - {"Type '", keyType, "' is not compatible with type '", typeArguments[0], "' at index 1"}); + util::DiagnosticWithParams {diagnostic::TYPE_MISMATCH_AT_IDX, {keyType, typeArguments[0], size_t(1)}}); checker::AssignmentContext( checker->Relation(), p->Value(), valueType, typeArguments[1], p->Value()->Start(), - {"Type '", valueType, "' is not compatible with type '", typeArguments[1], "' at index 2"}); + util::DiagnosticWithParams {diagnostic::TYPE_MISMATCH_AT_IDX, {valueType, typeArguments[1], size_t(2)}}); } } @@ -814,7 +814,7 @@ checker::Type *ETSChecker::CheckVariableDeclaration(ir::Identifier *ident, ir::T if (typeAnnotation != nullptr) { CheckRecordType(init, annotationType, this); AssignmentContext(Relation(), init, initType, annotationType, init->Start(), - {"Type '", initType, "' cannot be assigned to type '", annotationType, "'"}); + {{diagnostic::INVALID_ASSIGNMNENT, {initType, annotationType}}}); if (!Relation()->IsTrue()) { return annotationType; } @@ -1713,7 +1713,7 @@ void ETSChecker::SetrModuleObjectTsType(ir::Identifier *local, checker::ETSObjec Type *ETSChecker::GetReferencedTypeFromBase([[maybe_unused]] Type *baseType, [[maybe_unused]] ir::Expression *name) { - return TypeError(name, "Invalid type reference.", name->Start()); + return TypeError(name, diagnostic::INVALID_TYPE_REF, name->Start()); } Type *ETSChecker::GetReferencedTypeBase(ir::Expression *name) @@ -2054,7 +2054,7 @@ static bool IsValidSwitchType(checker::Type *caseType) void CheckEnumCaseUnqualified(ETSChecker *checker, ir::Expression const *const caseTest) { if (!caseTest->IsMemberExpression()) { - checker->LogTypeError("Enum switch case must be unqualified name of an enum constant", caseTest->Start()); + checker->LogError(diagnostic::SWITCH_ENUM_NOT_UNQUALIFIED_ENUM_CONST, {}, caseTest->Start()); return; } @@ -2067,12 +2067,12 @@ void CheckEnumCaseUnqualified(ETSChecker *checker, ir::Expression const *const c } else if (baseObject->IsMemberExpression()) { enumName = baseObject->AsMemberExpression()->Property()->AsIdentifier()->Name(); } else { - checker->LogTypeError("Enum switch case must be unqualified name of an enum constant", caseTest->Start()); + checker->LogError(diagnostic::SWITCH_ENUM_NOT_UNQUALIFIED_ENUM_CONST, {}, caseTest->Start()); } auto enumType = caseTest->TsType()->AsETSObjectType(); if (enumName != enumType->Name()) { - checker->LogTypeError("Enum switch case must be unqualified name of an enum constant", caseTest->Start()); + checker->LogError(diagnostic::SWITCH_ENUM_NOT_UNQUALIFIED_ENUM_CONST, {}, caseTest->Start()); } } diff --git a/ets2panda/checker/ets/object.cpp b/ets2panda/checker/ets/object.cpp index ac0075b8ac..9dbe6a10d1 100644 --- a/ets2panda/checker/ets/object.cpp +++ b/ets2panda/checker/ets/object.cpp @@ -140,7 +140,7 @@ bool ETSChecker::ComputeSuperType(ETSObjectType *type) } auto *classDef = type->GetDeclNode()->AsClassDefinition(); - TypeStackElement tse(this, type, {"Cyclic inheritance involving ", type->Name(), "."}, classDef->Ident()->Start()); + TypeStackElement tse(this, type, {{diagnostic::CYCLIC_INHERITANCE, {type->Name()}}}, classDef->Ident()->Start()); if (tse.HasTypeError()) { type->AddObjectFlag(ETSObjectFlags::RESOLVED_SUPER); return false; @@ -230,7 +230,7 @@ void ETSChecker::GetInterfacesOfInterface(ETSObjectType *type) auto *declNode = type->GetDeclNode()->AsTSInterfaceDeclaration(); - TypeStackElement tse(this, type, {"Cyclic inheritance involving ", type->Name(), "."}, declNode->Id()->Start()); + TypeStackElement tse(this, type, {{diagnostic::CYCLIC_INHERITANCE, {type->Name()}}}, declNode->Id()->Start()); if (tse.HasTypeError()) { type->AddObjectFlag(ETSObjectFlags::RESOLVED_INTERFACES); declNode->SetTsType(GlobalTypeError()); @@ -1648,7 +1648,7 @@ void ETSChecker::CheckCyclicConstructorCall(Signature *signature) auto *funcBody = signature->Function()->Body()->AsBlockStatement(); - TypeStackElement tse(this, signature, "Recursive constructor invocation", signature->Function()->Start()); + TypeStackElement tse(this, signature, {{diagnostic::RECURSIVE_CTOR}}, signature->Function()->Start()); if (tse.HasTypeError()) { return; } diff --git a/ets2panda/checker/ets/typeCheckingHelpers.cpp b/ets2panda/checker/ets/typeCheckingHelpers.cpp index fe27aa19ca..ac716180f2 100644 --- a/ets2panda/checker/ets/typeCheckingHelpers.cpp +++ b/ets2panda/checker/ets/typeCheckingHelpers.cpp @@ -480,8 +480,12 @@ static Type *GetTypeFromVarLikeVariableDeclaration(ETSChecker *checker, varbinde if (var->Declaration()->Node()->IsIdentifier()) { declNode = declNode->Parent(); } - util::DiagnosticMessageParams err = {"Circular dependency detected for identifier: ", var->Declaration()->Name()}; - TypeStackElement tse(checker, var->Declaration(), err, declNode->Start()); + TypeStackElement tse( + checker, var->Declaration(), + // OHOS CC thinks initializer lists are statement blocks... + // CC-OFFNXT(G.FMT.03-CPP) project code style + {{diagnostic::CIRCULAR_DEPENDENCY, util::DiagnosticMessageParams {var->Declaration()->Name()}}}, + declNode->Start()); if (tse.HasTypeError()) { var->SetTsType(checker->GlobalTypeError()); return checker->GlobalTypeError(); @@ -731,8 +735,7 @@ Type *ETSChecker::GetTypeFromTypeAliasReference(varbinder::Variable *var) std::unordered_set typeAliases; auto isAllowedRecursion = IsAllowedTypeAliasRecursion(aliasTypeNode, typeAliases); - TypeStackElement tse(this, aliasTypeNode, "Circular type alias reference", aliasTypeNode->Start(), - isAllowedRecursion); + TypeStackElement tse(this, aliasTypeNode, {{diagnostic::CYCLIC_ALIAS}}, aliasTypeNode->Start(), isAllowedRecursion); if (tse.HasTypeError()) { var->SetTsType(GlobalTypeError()); @@ -795,7 +798,7 @@ Type *ETSChecker::GetTypeFromTypeParameterReference(varbinder::LocalVariable *va if ((var->Declaration()->Node()->AsTSTypeParameter()->Parent()->Parent()->IsClassDefinition() || var->Declaration()->Node()->AsTSTypeParameter()->Parent()->Parent()->IsTSInterfaceDeclaration()) && HasStatus(CheckerStatus::IN_STATIC_CONTEXT)) { - return TypeError(var, {"Cannot make a static reference to the non-static type ", var->Name()}, pos); + return TypeError(var, diagnostic::STATIC_REF_TO_NONSTATIC, {var->Name()}, pos); } return var->TsType(); @@ -1436,7 +1439,7 @@ bool ETSChecker::CheckLambdaTypeAnnotation(ir::AstNode *typeAnnotation, functionFlags |= TypeRelationFlag::NO_THROW; checker::InvocationContext invocationCtx(Relation(), arrowFuncExpr, argumentType, parameterType, - arrowFuncExpr->Start(), {}, functionFlags); + arrowFuncExpr->Start(), std::nullopt, functionFlags); return invocationCtx.IsInvocable(); }; @@ -1526,14 +1529,14 @@ bool ETSChecker::TypeInference(Signature *signature, const ArenaVectorCheck(this); - LogError(diagnostic::LAMBDA_TYPE_MISMATCH, {argumentType, parameterType, index + 1}, + LogError(diagnostic::TYPE_MISMATCH_AT_IDX, {argumentType, parameterType, index + 1}, arrowFuncExpr->Start()); rc = false; } else if ((lambda->Signature() != nullptr) && !lambda->HasReturnStatement()) { // Need to check void return type here if there are no return statement(s) in the body. // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) if (!AssignmentContext(Relation(), AllocNode(Allocator()), GlobalVoidType(), - lambda->Signature()->ReturnType(), lambda->Start(), {}, + lambda->Signature()->ReturnType(), lambda->Start(), std::nullopt, checker::TypeRelationFlag::DIRECT_RETURN | checker::TypeRelationFlag::NO_THROW) .IsAssignable()) { // CC-OFF(G.FMT.02-CPP) project code style LogError(diagnostic::ARROW_TYPE_MISMATCH, {GlobalVoidType(), lambda->Signature()->ReturnType()}, diff --git a/ets2panda/checker/ets/typeRelationContext.cpp b/ets2panda/checker/ets/typeRelationContext.cpp index 408ddcb599..039b1ce024 100644 --- a/ets2panda/checker/ets/typeRelationContext.cpp +++ b/ets2panda/checker/ets/typeRelationContext.cpp @@ -30,7 +30,7 @@ bool AssignmentContext::ValidateArrayTypeInitializerByElement(TypeRelation *rela if (!AssignmentContext(relation, currentArrayElem, currentArrayElem->Check(relation->GetChecker()->AsETSChecker()), target->ElementType(), - currentArrayElem->Start(), {}, TypeRelationFlag::NO_THROW) + currentArrayElem->Start(), std::nullopt, TypeRelationFlag::NO_THROW) // CC-OFFNXT(G.FMT.06-CPP,G.FMT.02-CPP) project code style .IsAssignable()) { relation->GetChecker()->LogError(diagnostic::ARRAY_ELEMENT_INIT_TYPE_INCOMPAT, diff --git a/ets2panda/checker/ets/typeRelationContext.h b/ets2panda/checker/ets/typeRelationContext.h index 3a3f2b1d38..ef6c5017f9 100644 --- a/ets2panda/checker/ets/typeRelationContext.h +++ b/ets2panda/checker/ets/typeRelationContext.h @@ -25,7 +25,7 @@ class AssignmentContext { public: // CC-OFFNXT(G.FUN.01-CPP) solid logic AssignmentContext(TypeRelation *relation, ir::Expression *node, Type *source, Type *target, - const lexer::SourcePosition &pos, const util::DiagnosticMessageParams &list, + const lexer::SourcePosition &pos, std::optional diag = std::nullopt, TypeRelationFlag flags = TypeRelationFlag::NONE) { flags_ |= ((flags & TypeRelationFlag::NO_BOXING) != 0) ? TypeRelationFlag::NONE : TypeRelationFlag::BOXING; @@ -69,7 +69,7 @@ public: } if (!relation->IsTrue() && (flags_ & TypeRelationFlag::NO_THROW) == 0) { - relation->RaiseError(list, pos); + relation->RaiseError(diag->kind, diag->params, pos); } relation->SetNode(nullptr); @@ -93,7 +93,7 @@ class InvocationContext { public: // CC-OFFNXT(G.FUN.01-CPP) solid logic InvocationContext(TypeRelation *relation, ir::Expression *node, Type *source, Type *target, - const lexer::SourcePosition &pos, const util::DiagnosticMessageParams &list, + const lexer::SourcePosition &pos, const std::optional &diag, TypeRelationFlag initialFlags = TypeRelationFlag::NONE) { flags_ |= @@ -122,7 +122,7 @@ public: if (!relation->IsTrue()) { invocable_ = false; if ((initialFlags & TypeRelationFlag::NO_THROW) == 0) { - relation->RaiseError(list, pos); + relation->RaiseError(diag->kind, diag->params, pos); } return; } diff --git a/ets2panda/checker/ets/validateHelpers.cpp b/ets2panda/checker/ets/validateHelpers.cpp index 9f757c57a7..593e04c1e2 100644 --- a/ets2panda/checker/ets/validateHelpers.cpp +++ b/ets2panda/checker/ets/validateHelpers.cpp @@ -47,7 +47,7 @@ void ETSChecker::ValidatePropertyAccess(varbinder::Variable *var, ETSObjectType return; } - std::ignore = TypeError(var, {"Property ", var->Name(), " is not visible here."}, pos); + std::ignore = TypeError(var, diagnostic::PROP_INVISIBLE, {var->Name()}, pos); } } @@ -56,8 +56,7 @@ void ETSChecker::ValidateCallExpressionIdentifier(ir::Identifier *const ident, T if (ident->Variable()->HasFlag(varbinder::VariableFlags::CLASS_OR_INTERFACE) && ident->Parent()->AsCallExpression()->Callee() != ident) { std::ignore = - TypeError(ident->Variable(), {"Class or interface '", ident->ToString(), "' cannot be used as object"}, - ident->Start()); + TypeError(ident->Variable(), diagnostic::CLASS_OR_IFACE_AS_OBJ, {ident->ToString()}, ident->Start()); } if (ident->Parent()->AsCallExpression()->Callee() != ident) { @@ -67,8 +66,7 @@ void ETSChecker::ValidateCallExpressionIdentifier(ir::Identifier *const ident, T ES2PANDA_ASSERT(ident->Variable() != nullptr); if (ident->Variable()->Declaration()->Node() != nullptr && ident->Variable()->Declaration()->Node()->IsImportNamespaceSpecifier()) { - std::ignore = TypeError( - ident->Variable(), {"Namespace style identifier ", ident->ToString(), " is not callable."}, ident->Start()); + std::ignore = TypeError(ident->Variable(), diagnostic::NAMESPACE_CALL, {ident->ToString()}, ident->Start()); } if (type->IsETSFunctionType() || type->IsETSDynamicType()) { return; @@ -78,7 +76,7 @@ void ETSChecker::ValidateCallExpressionIdentifier(ir::Identifier *const ident, T return; } - std::ignore = TypeError(ident->Variable(), "This expression is not callable.", ident->Start()); + std::ignore = TypeError(ident->Variable(), diagnostic::EXPR_NOT_CALLABLE, {}, ident->Start()); } void ETSChecker::ValidateNewClassInstanceIdentifier(ir::Identifier *const ident) @@ -88,7 +86,7 @@ void ETSChecker::ValidateNewClassInstanceIdentifier(ir::Identifier *const ident) if (ident->Parent()->AsETSNewClassInstanceExpression()->GetTypeRef() == ident && !resolved->HasFlag(varbinder::VariableFlags::CLASS_OR_INTERFACE) && !resolved->TsType()->IsTypeError()) { - LogTypeError({"Invalid reference '", ident->Name(), "'."}, ident->Start()); + LogError(diagnostic::REF_INVALID, {ident->Name()}, ident->Start()); } } @@ -131,9 +129,8 @@ bool ETSChecker::ValidateBinaryExpressionIdentifier(ir::Identifier *const ident, bool isFinished = false; if (binaryExpr->OperatorType() == lexer::TokenType::KEYW_INSTANCEOF && binaryExpr->Left() == ident) { if (!IsReferenceType(type)) { - std::ignore = TypeError(ident->Variable(), - {R"(Using the "instance of" operator with non-object type ")", ident->Name(), "\""}, - ident->Start()); + std::ignore = + TypeError(ident->Variable(), diagnostic::INSTANCEOF_NONOBJECT, {ident->Name()}, ident->Start()); } isFinished = true; } @@ -208,12 +205,12 @@ void ETSChecker::ValidateUnaryOperatorOperand(varbinder::Variable *variable) std::string_view fieldType = variable->Declaration()->IsConstDecl() ? "constant" : "readonly"; if (HasStatus(CheckerStatus::IN_CONSTRUCTOR | CheckerStatus::IN_STATIC_BLOCK) && !variable->HasFlag(varbinder::VariableFlags::EXPLICIT_INIT_REQUIRED)) { - std::ignore = TypeError(variable, {"Cannot reassign ", fieldType, " ", variable->Name()}, + std::ignore = TypeError(variable, diagnostic::FIELD_REASSIGNMENT, {fieldType, variable->Name()}, variable->Declaration()->Node()->Start()); return; } if (!HasStatus(CheckerStatus::IN_CONSTRUCTOR | CheckerStatus::IN_STATIC_BLOCK)) { - std::ignore = TypeError(variable, {"Cannot assign to a ", fieldType, " variable ", variable->Name()}, + std::ignore = TypeError(variable, diagnostic::FIELD_ASSIGN_TYPE_MISMATCH, {fieldType, variable->Name()}, variable->Declaration()->Node()->Start()); } } diff --git a/ets2panda/checker/ts/destructuringContext.cpp b/ets2panda/checker/ts/destructuringContext.cpp index fae375a1ba..95f65a54bb 100644 --- a/ets2panda/checker/ts/destructuringContext.cpp +++ b/ets2panda/checker/ts/destructuringContext.cpp @@ -80,11 +80,8 @@ void DestructuringContext::SetInferredTypeForVariable(varbinder::Variable *var, } if (var->TsType() != nullptr) { - checker_->IsTypeIdenticalTo(var->TsType(), inferredType, - {"Subsequent variable declaration must have the same type. Variable '", var->Name(), - "' must be of type '", var->TsType(), "', but here has type '", inferredType, - "'."}, - loc); + checker_->IsTypeIdenticalTo(var->TsType(), inferredType, diagnostic::DIFFERENT_SUBSEQ_DECL, + {var->Name(), var->TsType(), inferredType}, loc); return; } diff --git a/ets2panda/checker/ts/helpers.cpp b/ets2panda/checker/ts/helpers.cpp index 1762795939..9c2455f558 100644 --- a/ets2panda/checker/ts/helpers.cpp +++ b/ets2panda/checker/ts/helpers.cpp @@ -483,9 +483,7 @@ Type *TSChecker::GetTypeOfVariable(varbinder::Variable *var) varbinder::Decl *decl = var->Declaration(); - util::DiagnosticMessageParams params {"'", var->Name(), "' is referenced directly or indirectly in its ", - "own initializer ot type annotation."}; - TypeStackElement tse(this, decl->Node(), params, decl->Node()->Start()); + TypeStackElement tse(this, decl->Node(), {{diagnostic::CYCLIC_VAR_REF, {var->Name()}}}, decl->Node()->Start()); if (tse.HasTypeError()) { return GlobalErrorType(); } @@ -516,7 +514,7 @@ Type *TSChecker::GetTypeFromTypeAliasReference(ir::TSTypeReference *node, varbin return resolvedType; } - TypeStackElement tse(this, var, {"Type alias ", var->Name(), " circularly refences itself"}, node->Start()); + TypeStackElement tse(this, var, {{diagnostic::CYCLIC_ALIAS_2, {var->Name()}}}, node->Start()); if (tse.HasTypeError()) { return GlobalErrorType(); } diff --git a/ets2panda/checker/ts/object.cpp b/ets2panda/checker/ts/object.cpp index 35bfe5f05b..d0b36c61dc 100644 --- a/ets2panda/checker/ts/object.cpp +++ b/ets2panda/checker/ts/object.cpp @@ -55,10 +55,8 @@ void TSChecker::CheckIndexConstraints(Type *type) for (auto *it : properties) { if (it->HasFlag(varbinder::VariableFlags::NUMERIC_NAME)) { Type *propType = GetTypeOfVariable(it); - IsTypeAssignableTo(propType, numberInfo->GetType(), - {"Property '", it->Name(), "' of type '", propType, - "' is not assignable to numeric index type '", numberInfo->GetType(), "'."}, - it->Declaration()->Node()->Start()); + IsTypeAssignableTo(propType, numberInfo->GetType(), diagnostic::PROP_ASSIGN_TO_NUMERIC_INDEX, + {it->Name(), propType, numberInfo->GetType()}, it->Declaration()->Node()->Start()); } } } @@ -66,10 +64,8 @@ void TSChecker::CheckIndexConstraints(Type *type) if (stringInfo != nullptr) { for (auto *it : properties) { Type *propType = GetTypeOfVariable(it); - IsTypeAssignableTo(propType, stringInfo->GetType(), - {"Property '", it->Name(), "' of type '", propType, - "' is not assignable to string index type '", stringInfo->GetType(), "'."}, - it->Declaration()->Node()->Start()); + IsTypeAssignableTo(propType, stringInfo->GetType(), diagnostic::PROP_ASSIGN_TO_STRING_INDEX, + {it->Name(), propType, stringInfo->GetType()}, it->Declaration()->Node()->Start()); } if (numberInfo != nullptr && !IsTypeAssignableTo(numberInfo->GetType(), stringInfo->GetType())) { @@ -442,7 +438,7 @@ ArenaVector TSChecker::GetBaseTypes(InterfaceType *type) ES2PANDA_ASSERT(type->Variable() && type->Variable()->Declaration()->IsInterfaceDecl()); varbinder::InterfaceDecl *decl = type->Variable()->Declaration()->AsInterfaceDecl(); - TypeStackElement tse(this, type, {"Type ", type->Name(), " recursively references itself as a base type."}, + TypeStackElement tse(this, type, {{diagnostic::RECURSIVE_EXTENSION, {type->Name()}}}, decl->Node()->AsTSInterfaceDeclaration()->Id()->Start()); if (tse.HasTypeError()) { type->Bases().clear(); @@ -540,10 +536,8 @@ bool TSChecker::ValidateInterfaceMemberRedeclaration(ObjectType *type, varbinder Type *targetType = GetTypeOfVariable(prop); Type *sourceType = GetTypeOfVariable(found); - IsTypeIdenticalTo(targetType, sourceType, - {"Subsequent property declarations must have the same type. Property ", prop->Name(), - " must be of type ", sourceType, ", but here has type ", targetType, "."}, - locInfo); + IsTypeIdenticalTo(targetType, sourceType, diagnostic::DIFFERENT_SUBSEQ_PROP_DECL, + {prop->Name(), sourceType, targetType}, locInfo); return false; } } // namespace ark::es2panda::checker diff --git a/ets2panda/checker/typeChecker/TypeChecker.h b/ets2panda/checker/typeChecker/TypeChecker.h index 239db9c7ff..802f884a5c 100644 --- a/ets2panda/checker/typeChecker/TypeChecker.h +++ b/ets2panda/checker/typeChecker/TypeChecker.h @@ -37,11 +37,6 @@ public: protected: explicit TypeChecker(Checker *checker) : checker_(checker) {} - void LogTypeError(const util::DiagnosticMessageParams &list, const lexer::SourcePosition &pos) - { - checker_->LogTypeError(list, pos); - } - void LogError(const diagnostic::DiagnosticKind &diagnostic, const util::DiagnosticMessageParams &diagnosticParams, const lexer::SourcePosition &pos) { diff --git a/ets2panda/checker/types/ets/etsTypeParameter.cpp b/ets2panda/checker/types/ets/etsTypeParameter.cpp index dc06935a79..518a42441b 100644 --- a/ets2panda/checker/types/ets/etsTypeParameter.cpp +++ b/ets2panda/checker/types/ets/etsTypeParameter.cpp @@ -101,25 +101,22 @@ void ETSTypeParameter::CheckVarianceRecursively([[maybe_unused]] TypeRelation *r } if (varianceFlag == VarianceFlag::INVARIANT) { - relation->GetChecker()->LogTypeError({"Type Parameter '", declNode_->Name()->Name(), "' is declared as", - declNode_->IsOut() ? " 'out'" : " 'in'", - " but occurs in 'invariant' position."}, - relation->GetNode()->Start()); + relation->GetChecker()->LogError(diagnostic::VARIANT_PARAM_INVARIAN_USE, + {declNode_->Name()->Name(), declNode_->IsOut() ? " 'out'" : " 'in'"}, + relation->GetNode()->Start()); relation->Result(false); return; } if (varianceFlag == VarianceFlag::COVARIANT && !declNode_->IsOut()) { - relation->GetChecker()->LogTypeError( - {"Type Parameter '", declNode_->Name()->Name(), "' is declared as 'in' but occurs in 'out' position."}, - relation->GetNode()->Start()); + relation->GetChecker()->LogError(diagnostic::VARIANCE_TPARAM_IN_OUT, {declNode_->Name()->Name()}, + relation->GetNode()->Start()); relation->Result(false); } if (varianceFlag == VarianceFlag::CONTRAVARIANT && !declNode_->IsIn()) { - relation->GetChecker()->LogTypeError( - {"Type Parameter '", declNode_->Name()->Name(), "' is declared as 'out' but occurs in 'in' position."}, - relation->GetNode()->Start()); + relation->GetChecker()->LogError(diagnostic::VARIANCE_TPARAM_OUT_IN, {declNode_->Name()->Name()}, + relation->GetNode()->Start()); relation->Result(false); } } diff --git a/ets2panda/checker/types/typeRelation.cpp b/ets2panda/checker/types/typeRelation.cpp index 88ed2fd951..5f59255974 100644 --- a/ets2panda/checker/types/typeRelation.cpp +++ b/ets2panda/checker/types/typeRelation.cpp @@ -275,13 +275,14 @@ VarianceFlag TypeRelation::TransferVariant(VarianceFlag variance, VarianceFlag p return variance == VarianceFlag::CONTRAVARIANT ? VarianceFlag::COVARIANT : VarianceFlag::CONTRAVARIANT; } -void TypeRelation::RaiseError(const std::string &errMsg, const lexer::SourcePosition &loc) const +void TypeRelation::RaiseError(const diagnostic::DiagnosticKind &kind, const lexer::SourcePosition &loc) const { - checker_->LogTypeError(errMsg, loc); + RaiseError(kind, {}, loc); } -void TypeRelation::RaiseError(const util::DiagnosticMessageParams &list, const lexer::SourcePosition &loc) const +void TypeRelation::RaiseError(const diagnostic::DiagnosticKind &kind, const util::DiagnosticMessageParams &list, + const lexer::SourcePosition &loc) const { - checker_->LogTypeError(list, loc); + checker_->LogError(kind, list, loc); } } // namespace ark::es2panda::checker diff --git a/ets2panda/checker/types/typeRelation.h b/ets2panda/checker/types/typeRelation.h index 489132498b..4fadbde95e 100644 --- a/ets2panda/checker/types/typeRelation.h +++ b/ets2panda/checker/types/typeRelation.h @@ -303,8 +303,10 @@ public: bool SignatureIsSupertypeOf(Signature *super, Signature *sub); bool CheckVarianceRecursively(Type *type, VarianceFlag varianceFlag); VarianceFlag TransferVariant(VarianceFlag variance, VarianceFlag posVariance); - void RaiseError(const std::string &errMsg, const lexer::SourcePosition &loc) const; - void RaiseError(const util::DiagnosticMessageParams &list, const lexer::SourcePosition &loc) const; + + void RaiseError(const diagnostic::DiagnosticKind &kind, const lexer::SourcePosition &loc) const; + void RaiseError(const diagnostic::DiagnosticKind &kind, const util::DiagnosticMessageParams &list, + const lexer::SourcePosition &loc) const; void LogError(const util::DiagnosticMessageParams &list, const lexer::SourcePosition &loc) const; bool Result(bool res) diff --git a/ets2panda/ir/expressions/arrayExpression.cpp b/ets2panda/ir/expressions/arrayExpression.cpp index 9bb2b78f8b..685ecef76c 100644 --- a/ets2panda/ir/expressions/arrayExpression.cpp +++ b/ets2panda/ir/expressions/arrayExpression.cpp @@ -429,8 +429,8 @@ void ArrayExpression::SetPreferredTypeBasedOnFuncParam(checker::ETSChecker *chec for (auto *const elem : elements_) { checker->SetPreferredTypeIfPossible(elem, elementType); - auto assignCtx = checker::AssignmentContext(checker->Relation(), elem, elem->Check(checker), elementType, - elem->Start(), {""}, checker::TypeRelationFlag::NO_THROW | flags); + checker::AssignmentContext assignCtx(checker->Relation(), elem, elem->Check(checker), elementType, + elem->Start(), std::nullopt, checker::TypeRelationFlag::NO_THROW | flags); isAssignable &= assignCtx.IsAssignable(); } diff --git a/ets2panda/ir/expressions/memberExpression.cpp b/ets2panda/ir/expressions/memberExpression.cpp index ed9ba81c10..14f43a1d25 100644 --- a/ets2panda/ir/expressions/memberExpression.cpp +++ b/ets2panda/ir/expressions/memberExpression.cpp @@ -238,7 +238,7 @@ checker::Type *MemberExpression::CheckUnionMember(checker::ETSChecker *checker, auto *const unionType = baseType->AsETSUnionType(); if (object_->Variable() != nullptr && object_->Variable()->Declaration() != nullptr && object_->Variable()->Declaration()->IsTypeAliasDecl()) { - checker->LogTypeError("Static union member expression cannot be interpreted.", Start()); + checker->LogError(diagnostic::STATIC_UNION, {}, Start()); return checker->GlobalTypeError(); } auto *const commonPropType = TraverseUnionMember(checker, unionType); @@ -386,7 +386,7 @@ checker::Type *MemberExpression::CheckIndexAccessMethod(checker::ETSChecker *che return nullptr; } checker->ValidateSignatureAccessibility(objType_, nullptr, signature, Start(), - {diagnostic::INVISIBLE_INDEX_ACCESSOR, {}}); + {{diagnostic::INVISIBLE_INDEX_ACCESSOR, {}}}); ES2PANDA_ASSERT(signature->Function() != nullptr); @@ -434,7 +434,7 @@ static void CastTupleElementFromClassMemberType(checker::ETSChecker *checker, auto *storedTupleType = checker->MaybeBoxType(typeOfTuple); const checker::CastingContext tupleCast( - checker->Relation(), {"this cast should never fail"}, + checker->Relation(), diagnostic::CAST_FAIL_UNREACHABLE, {}, checker::CastingContext::ConstructorData {tupleElementAccessor, storedTupleType, typeOfTuple, tupleElementAccessor->Start(), checker::TypeRelationFlag::NO_THROW}); } diff --git a/ets2panda/ir/statements/forOfStatement.cpp b/ets2panda/ir/statements/forOfStatement.cpp index 06725ec45a..5426ff6b50 100644 --- a/ets2panda/ir/statements/forOfStatement.cpp +++ b/ets2panda/ir/statements/forOfStatement.cpp @@ -170,7 +170,7 @@ checker::Type *ForOfStatement::CheckIteratorMethodForObject(checker::ETSChecker return nullptr; } checker->ValidateSignatureAccessibility(sourceType, nullptr, signature, position, - {diagnostic::INVISIBLE_ITERATOR, {}}); + {{diagnostic::INVISIBLE_ITERATOR, {}}}); ES2PANDA_ASSERT(signature->Function() != nullptr); diff --git a/ets2panda/ir/statements/switchCaseStatement.cpp b/ets2panda/ir/statements/switchCaseStatement.cpp index eec65df177..f81b7c5409 100644 --- a/ets2panda/ir/statements/switchCaseStatement.cpp +++ b/ets2panda/ir/statements/switchCaseStatement.cpp @@ -111,14 +111,17 @@ void SwitchCaseStatement::CheckAndTestCase(checker::ETSChecker *checker, checker } else if (caseType->IsETSEnumType() || comparedExprType->IsETSEnumType()) { validCaseType = checker->Relation()->IsIdenticalTo(caseType, comparedExprType); } else { - if (!checker::AssignmentContext( - // CC-OFFNXT(G.FMT.06-CPP) project code style - checker->Relation(), node, caseType, unboxedDiscType, test_->Start(), {}, - (comparedExprType->IsETSObjectType() ? checker::TypeRelationFlag::NO_WIDENING - : checker::TypeRelationFlag::NO_UNBOXING) | - // CC-OFFNXT(G.FMT.02) project code style - checker::TypeRelationFlag::NO_BOXING | checker::TypeRelationFlag::NO_THROW) - .IsAssignable()) { + const checker::AssignmentContext ctx { + checker->Relation(), + node, + caseType, + unboxedDiscType, + test_->Start(), + std::nullopt, + (comparedExprType->IsETSObjectType() ? checker::TypeRelationFlag::NO_WIDENING + : checker::TypeRelationFlag::NO_UNBOXING) | + checker::TypeRelationFlag::NO_BOXING | checker::TypeRelationFlag::NO_THROW}; + if (!ctx.IsAssignable()) { checker->LogError(diagnostic::SWITCH_CASE_TYPE_INCOMPARABLE, {caseType, comparedExprType}, test_->Start()); return; diff --git a/ets2panda/test/ast/parser/ets/instanceof_with_not_object_type.ets b/ets2panda/test/ast/parser/ets/instanceof_with_not_object_type.ets index ea2b734177..3e3263a001 100644 --- a/ets2panda/test/ast/parser/ets/instanceof_with_not_object_type.ets +++ b/ets2panda/test/ast/parser/ets/instanceof_with_not_object_type.ets @@ -25,4 +25,4 @@ function main() } /* @@@ label Error TypeError: Cannot find type 'a'. */ -/* @@? 24:5 Error TypeError: Using the "instance of" operator with non-object type "b" */ +/* @@? 24:5 Error TypeError: Using the 'instance of' operator with non-object type 'b' */ diff --git a/ets2panda/test/compiler/ets/dynamic_instanceof_error-expected.txt b/ets2panda/test/compiler/ets/dynamic_instanceof_error-expected.txt index 26cf8aaf57..92e773df20 100644 --- a/ets2panda/test/compiler/ets/dynamic_instanceof_error-expected.txt +++ b/ets2panda/test/compiler/ets/dynamic_instanceof_error-expected.txt @@ -1153,5 +1153,5 @@ } } } -TypeError: Using the "instance of" operator with non-object type "a" [dynamic_instanceof_error.ets:24:11] +TypeError: Using the 'instance of' operator with non-object type 'a' [dynamic_instanceof_error.ets:24:11] TypeError: Right-hand side of instanceof expression must represent a type. [dynamic_instanceof_error.ets:24:11] diff --git a/ets2panda/util/diagnostic.h b/ets2panda/util/diagnostic.h index bc0be56c5a..50a7a9a120 100644 --- a/ets2panda/util/diagnostic.h +++ b/ets2panda/util/diagnostic.h @@ -118,6 +118,11 @@ using DiagnosticMessageElement = const checker::Type *const, const checker::Signature *const>; using DiagnosticMessageParams = std::vector; +struct DiagnosticWithParams { + const diagnostic::DiagnosticKind &kind; // NOLINT(readability-identifier-naming) + const DiagnosticMessageParams params = {}; // NOLINT(readability-identifier-naming) +}; + // NOLINTNEXTLINE(fuchsia-multiple-inheritance) class ThrowableDiagnostic : public DiagnosticBase, public std::exception { public: diff --git a/ets2panda/util/diagnostic/semantic.yaml b/ets2panda/util/diagnostic/semantic.yaml index 93c85d69cf..1d2b8db7e1 100644 --- a/ets2panda/util/diagnostic/semantic.yaml +++ b/ets2panda/util/diagnostic/semantic.yaml @@ -192,7 +192,7 @@ semantic: id: 45 message: "The parameter '{}' does not match any declared property in the annotation '{}'." -- name: LAMBDA_TYPE_MISMATCH +- name: TYPE_MISMATCH_AT_IDX id: 46 message: "Type '{}' is not compatible with type '{}' at index {}" @@ -1107,13 +1107,13 @@ semantic: id: 278 message: "Local class '{}' shouldn't have native methods/constructors" -- name: UNION_METHOD_SIGNATURE +- name: TUPLEN_NOT_IMPLEMENTED id: 279 - message: "Union constituent types should have only one common method signature." + message: "Tuple types with arity >16 are not yet implemented" -- name: TUPLEN_NOT_IMPLEMENTED +- name: UNION_METHOD_SIGNATURE id: 280 - message: "Tuple types with arity >16 are not yet implemented" + message: "Union constituent types should have only one common method signature." - name: NOT_ALLOWED_THIS_IN_UNION_TYPE id: 281 @@ -1127,10 +1127,226 @@ semantic: id: 283 message: "A 'this' cannot be used as type of array." -- name: INTERFACE_PROPERTY_REQUIRES_SETTER +- name: TYPE_FROM_UNION_TYPE_UNSUPPORTED id: 284 + message: "Acquiring types for union types is not supported." + +- name: TYPE_FROM_UNRESOLVABLE_TYPE + id: 285 + message: "Unable to resolve type." + +- name: TYPE_FROM_TUPLE_TYPE_UNSUPPORTED + id: 286 + message: "Acquiring types for tuple types is not supported." + +- name: TYPE_FROM_STRING_LITERAL_TYPE_UNSUPPORTED + id: 287 + message: "Acquiring types for string literal types is not supported." + +- name: STATIC_REF_TO_NONSTATIC + id: 288 + message: "Cannot make a static reference to the non-static type {}" + +- name: EXPR_NOT_CALLABLE + id: 289 + message: "This expression is not callable." + +- name: CALLEE_NONCONSTRUCTIBLE + id: 290 + message: "Type '{}' is not constructible." + +- name: NO_PARAMLESS_CTOR + id: 291 + message: "type {} has no parameterless constructor" + +- name: EXPR_NONCONSTRUCTIBLE + id: 292 + message: "This expression is not constructible." + +- name: PROP_INVISIBLE + id: 293 + message: "Property {} is not visible here." + +- name: CLASS_OR_IFACE_AS_OBJ + id: 294 + message: "Class or interface '{}' cannot be used as object" + +- name: NAMESPACE_CALL + id: 295 + message: "Namespace style identifier {} is not callable." + +- name: INSTANCEOF_NONOBJECT + id: 296 + message: "Using the 'instance of' operator with non-object type '{}'" + +- name: FIELD_REASSIGNMENT + id: 297 + message: "Cannot reassign {} {}" + +- name: FIELD_ASSIGN_TYPE_MISMATCH + id: 298 + message: "Cannot assign to a {} variable {}" + +- name: INVALID_TYPE_REF + id: 299 + message: "Invalid type reference." + +- name: UNION_NONCONSTRUCTIBLE + id: 300 + message: "The union type is not constructible." + +- name: UNRESOLVABLE_ARRAY + id: 301 + message: "Can't resolve array type" + +- name: IMPORT_ARG_NOT_STRING + id: 302 + message: "'import' expressions require string as argument." + +- name: AWAITED_NOT_PROMISE + id: 303 + message: "'await' expressions require Promise object as argument." + +- name: NULLISH_CAST_TO_NONNULLISH + id: 304 + message: "Cannot cast 'null' or 'undefined' to non-nullish type." + +- name: CAST_TO_NEVER + id: 305 + message: "Cast to 'never' is prohibited" + +- name: PRIVATE_METHOD_AS_VALUE + id: 306 + message: "Private method is used as value" + +- name: OVERLOADED_METHOD_AS_VALUE + id: 307 + message: "Overloaded method is used as value" + +- name: CIRCULAR_DEPENDENCY + id: 308 + message: "Circular dependency detected for identifier: {}" + +- name: RECURSIVE_CTOR + id: 309 + message: "Recursive constructor invocation" + +- name: CYCLIC_INHERITANCE + id: 310 + message: "Cyclic inheritance involving {}." + +- name: CYCLIC_ALIAS + id: 311 + message: "Circular type alias reference" + +- name: RECURSIVE_EXTENSION + id: 312 + message: "Type {} recursively references itself as a base type." + +- name: CYCLIC_ALIAS_2 + id: 313 + message: "Type alias {} circularly refences itself" + +- name: CYCLIC_VAR_REF + id: 314 + message: "'{}' is referenced directly or indirectly in its own initializer ot type annotation." + +- name: IFACE_MULTIPLE_EXTENSION + id: 315 + message: "Interface '{}' cannot simultaneously extend types '{}' and '{}'." + +- name: DIFFERENT_SUBSEQ_DECL + id: 316 + message: "Subsequent variable declaration must have the same type. Variable '{}' must be of type '{}', but here has type '{}'." + +- name: DIFFERENT_SUBSEQ_PROP_DECL + id: 317 + message: "Subsequent variable declaration must have the same type. Variable '{}' must be of type '{}', but here has type '{}'." + +- name: INVALID_ASSIGNMNENT + id: 318 + message: "Type '{}' cannot be assigned to type '{}'" + +- name: PROP_INCOMPAT + id: 319 + message: "Type '{}' is not compatible with type '{}' at property '{}'" + +- name: IFACE_INVALID_EXTENDS + id: 320 + message: "Interface '{}' incorrectly extends interface '{}'" + +- name: INVALID_ASSIGNMNENT_2 + id: 321 + message: "Type '{}' is not assignable to type '{}'." + +- name: DISJOINT_CONVERSION + id: 322 + message: "Conversion of type '{}' to type '{}' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first." + +- name: REST_PARAM_INCOMPAT_AT + id: 323 + message: "Type '{}' is not compatible with rest parameter type '{}' at index {}" + +- name: PROP_ASSIGN_TO_NUMERIC_INDEX + id: 324 + message: "Property '{}' of type '{}' is not assignable to numeric index type '{}'." + +- name: TUPLE_CONVERSION_FAILURE + id: 325 + message: "Tuple type couldn't be converted " + +- name: INVALID_CAST + id: 326 + message: "Cannot cast type '{}' to '{}'" + +- name: PROP_ASSIGN_TO_STRING_INDEX + id: 327 + message: "Property '{}' of type '{}' is not assignable to string index type '{}'." + +- name: UNIMPLEMENTED_REST_TUPLE + id: 328 + message: "Tuple types for rest arguments are not yet implemented" + +- name: REF_INVALID + id: 329 + message: "Invalid reference '{}'." + +- name: ID_WRONG_CTX + id: 330 + message: "Identifier '{}' is used in wrong context." + +- name: VARIANT_PARAM_INVARIAN_USE + id: 331 + message: "Type Parameter '{}' is declared as{} but occurs in 'invariant' position." + +- name: VARIANCE_TPARAM_IN_OUT + id: 332 + message: "Type Parameter '{}' is declared as 'in' but occurs in 'out' position." + +- name: VARIANCE_TPARAM_OUT_IN + id: 333 + message: "Type Parameter '{}' is declared as 'out' but occurs in 'in' position." + +- name: SWITCH_ENUM_NOT_UNQUALIFIED_ENUM_CONST + id: 334 + message: "Enum switch case must be unqualified name of an enum constant" + +- name: STATIC_UNION + id: 335 + message: "Static union member expression cannot be interpreted." + +- name: CAST_FAIL_UNREACHABLE + id: 336 + message: "this cast should never fail" + +- name: INTERFACE_PROPERTY_REQUIRES_SETTER + id: 337 message: "Cannot implement interface {}: property '{}' must have a setter, but the implementation is readonly" +- name: READONLY_PROPERTY_REASSIGN + id: 338 + message: "The 'Readonly' property cannot be reassigned." + - name: PROPERTY_MAYBE_MISSING_INIT - id: 285 - message: "Property '{}' might not have been initialized." \ No newline at end of file + id: 339 + message: "Property '{}' might not have been initialized." -- Gitee From f190ec1b17cfc695551a9f4fecffe358bee4f254 Mon Sep 17 00:00:00 2001 From: zhangkai366 Date: Tue, 29 Apr 2025 15:33:09 +0800 Subject: [PATCH 133/268] Fix the codecheck problem Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC4XFD Test: grammar&test Signed-off-by: zhangkai366 Change-Id: I09fc61eb1a101740e0e362a21464465c6fc10a86 --- arkguard/tools/timesum.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/arkguard/tools/timesum.py b/arkguard/tools/timesum.py index b75ed50f6b..d7515007b4 100644 --- a/arkguard/tools/timesum.py +++ b/arkguard/tools/timesum.py @@ -143,8 +143,8 @@ def re_gen_ts_and_dur(data_with_parent): os.remove('data.json') flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL modes = stat.S_IWUSR | stat.S_IRUSR - with os.fdopen(os.open('data.json', flags, modes), 'w') as f: - json.dump(flattened, f, indent=2) + with os.fdopen(os.open('data.json', flags, modes), 'w') as file: + json.dump(flattened, file, indent=2) return groups @@ -165,8 +165,8 @@ def group_by_parent(data): if __name__ == "__main__": # Load input data from a JSON file with open("timePerformanceData.json", "r") as f: - data = json.load(f) + datas = json.load(f) # Generate parent information for each event - data_with_parent = gen_parent(data) + data_with_parents = gen_parent(datas) # Regenerate timestamps and durations based on parent relationships - re_gen_ts_and_dur(data_with_parent) + re_gen_ts_and_dur(data_with_parents) -- Gitee From d1cca80dc1e26164da501aca17ec551a56cfc912 Mon Sep 17 00:00:00 2001 From: fcc Date: Thu, 10 Apr 2025 14:50:35 +0800 Subject: [PATCH 134/268] Fix parsing of unary minus expression when minus operator follows a parenthes, the parsing is incorrect. Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC01GM Signed-off-by: fcc --- ets2panda/parser/ETSparser.h | 2 ++ ets2panda/parser/ETSparserExpressions.cpp | 33 +++++++++++-------- .../test/runtime/ets/UnaryExpression.ets | 20 +++++++++++ 3 files changed, 42 insertions(+), 13 deletions(-) diff --git a/ets2panda/parser/ETSparser.h b/ets2panda/parser/ETSparser.h index 7c33a7d5a2..e6e1a76c00 100644 --- a/ets2panda/parser/ETSparser.h +++ b/ets2panda/parser/ETSparser.h @@ -413,6 +413,8 @@ private: ir::Expression *ParseFunctionReceiver(); ir::AnnotatedExpression *GetAnnotatedExpressionFromParam(); ir::Expression *ResolveArgumentUnaryExpr(ExpressionParseFlags flags); + ir::Expression *CreateUnaryExpressionFromArgument(ir::Expression *argument, lexer::TokenType operatorType, + char32_t beginningChar); // NOLINTNEXTLINE(google-default-arguments) ir::Expression *ParseUnaryOrPrefixUpdateExpression( ExpressionParseFlags flags = ExpressionParseFlags::NO_OPTS) override; diff --git a/ets2panda/parser/ETSparserExpressions.cpp b/ets2panda/parser/ETSparserExpressions.cpp index 56641ea031..4ba354bbae 100644 --- a/ets2panda/parser/ETSparserExpressions.cpp +++ b/ets2panda/parser/ETSparserExpressions.cpp @@ -120,6 +120,24 @@ ir::Expression *ETSParser::ResolveArgumentUnaryExpr(ExpressionParseFlags flags) } } +ir::Expression *ETSParser::CreateUnaryExpressionFromArgument(ir::Expression *argument, lexer::TokenType operatorType, + char32_t beginningChar) +{ + ir::Expression *returnExpr = nullptr; + if (lexer::Token::IsUpdateToken(operatorType)) { + returnExpr = AllocNode(argument, operatorType, true); + } else if (operatorType == lexer::TokenType::KEYW_TYPEOF) { + returnExpr = AllocNode(argument); + } else if (operatorType == lexer::TokenType::PUNCTUATOR_MINUS && argument->IsNumberLiteral()) { + bool argBeginWithDigitOrDot = (beginningChar >= '0' && beginningChar <= '9') || (beginningChar == '.'); + returnExpr = argBeginWithDigitOrDot ? argument : AllocNode(argument, operatorType); + } else { + returnExpr = AllocNode(argument, operatorType); + } + + return returnExpr; +} + // NOLINTNEXTLINE(google-default-arguments) ir::Expression *ETSParser::ParseUnaryOrPrefixUpdateExpression(ExpressionParseFlags flags) { @@ -150,11 +168,11 @@ ir::Expression *ETSParser::ParseUnaryOrPrefixUpdateExpression(ExpressionParseFla } } + char32_t beginningChar = Lexer()->Lookahead(); auto start = Lexer()->GetToken().Start(); Lexer()->NextToken(tokenFlags); ir::Expression *argument = ResolveArgumentUnaryExpr(flags); - if (argument == nullptr) { return nullptr; } @@ -165,19 +183,8 @@ ir::Expression *ETSParser::ParseUnaryOrPrefixUpdateExpression(ExpressionParseFla } } - ir::Expression *returnExpr = nullptr; - if (lexer::Token::IsUpdateToken(operatorType)) { - returnExpr = AllocNode(argument, operatorType, true); - } else if (operatorType == lexer::TokenType::KEYW_TYPEOF) { - returnExpr = AllocNode(argument); - } else if (operatorType == lexer::TokenType::PUNCTUATOR_MINUS) { - returnExpr = !argument->IsNumberLiteral() ? AllocNode(argument, operatorType) : argument; - } else { - returnExpr = AllocNode(argument, operatorType); - } - + ir::Expression *returnExpr = CreateUnaryExpressionFromArgument(argument, operatorType, beginningChar); returnExpr->SetRange({start, argument->End()}); - return returnExpr; } diff --git a/ets2panda/test/runtime/ets/UnaryExpression.ets b/ets2panda/test/runtime/ets/UnaryExpression.ets index 7ab4310943..9e62a100e6 100644 --- a/ets2panda/test/runtime/ets/UnaryExpression.ets +++ b/ets2panda/test/runtime/ets/UnaryExpression.ets @@ -97,4 +97,24 @@ function main(): void { assertEQ(+c, 60.0) assertEQ(-c, -60.0) } + + { + let a = -(-1); + assertEQ(a, 1); + + let b = -(1); + assertEQ(b, -1); + + let c = - -1; + assertEQ(c, 1); + + let d = +(1); + assertEQ(d, 1); + + let e = +(-1); + assertEQ(e, -1); + + let f = + -1; + assertEQ(f, -1); + } } -- Gitee From d32d723e87b133ddde601800d0f6c09d71c6e084 Mon Sep 17 00:00:00 2001 From: zhangziye Date: Tue, 22 Apr 2025 14:39:53 +0800 Subject: [PATCH 135/268] etssdk use GN template Issue: #IC4FQK Signed-off-by: zhangziye --- ets2panda/CMakeLists.txt | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/ets2panda/CMakeLists.txt b/ets2panda/CMakeLists.txt index 57b60df30b..bd09554954 100644 --- a/ets2panda/CMakeLists.txt +++ b/ets2panda/CMakeLists.txt @@ -48,8 +48,27 @@ if(PANDA_WITH_ETS) " \"paths\": {\n" " \"std\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}stdlib${DELIM}std\"],\n" " \"escompat\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}stdlib${DELIM}escompat\"],\n" - " \"api\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api\"],\n" - " \"arkts\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}arkts\"],\n" + " \"@ohos.buffer\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.buffer.ets\"],\n" + " \"@ohos.util.ArrayList\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.util.ArrayList.ets\"],\n" + " \"@ohos.util.Deque\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.util.Deque.ets\"],\n" + " \"@ohos.util.HashMap\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.util.HashMap.ets\"],\n" + " \"@ohos.util.HashSet\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.util.HashSet.ets\"],\n" + " \"@ohos.util.json\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.util.json.ets\"],\n" + " \"@ohos.util.LightWeightMap\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.util.LightWeightMap.ets\"],\n" + " \"@ohos.util.LightWeightSet\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.util.LightWeightSet.ets\"],\n" + " \"@ohos.util.LinkedList\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.util.LinkedList.ets\"],\n" + " \"@ohos.util.List\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.util.List.ets\"],\n" + " \"@ohos.util.PlainArray\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.util.PlainArray.ets\"],\n" + " \"@ohos.util.Queue\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.util.Queue.ets\"],\n" + " \"@ohos.util.Stack\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.util.Stack.ets\"],\n" + " \"@ohos.util\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.util.ets\"],\n" + " \"@ohos.util.TreeMap\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.util.TreeMap.ets\"],\n" + " \"@ohos.util.TreeSet\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.util.TreeSet.ets\"],\n" + " \"@ohos.uri\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.uri.ets\"],\n" + " \"@ohos.url\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.url.ets\"],\n" + " \"@ohos.xml\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.xml.ets\"],\n" + " \"@ohos.base\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.base.ets\"],\n" + " \"@arkts.math.Decimal\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}arkts${DELIM}@arkts.math.Decimal.ets\"],\n" " \"import_tests\": [\"${CMAKE_CURRENT_SOURCE_DIR}/test/parser/ets/import_tests\"]\n" " },\n" " \"dynamicPaths\": {\n" -- Gitee From a09ac5bd71eae6022a25e6265510227b481cb5d8 Mon Sep 17 00:00:00 2001 From: kaanfurkancakiroglu Date: Wed, 30 Apr 2025 13:34:54 +0300 Subject: [PATCH 136/268] Title:CTE-abstract/nonabstract method overrides Issue: IC2G03 Test: Build Signed-off-by: kaanfurkancakiroglu --- ets2panda/checker/ets/function.cpp | 14 ++++++++++++++ ets2panda/checker/resolveResult.h | 1 + ets2panda/compiler/lowering/ets/unionLowering.cpp | 2 +- 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/ets2panda/checker/ets/function.cpp b/ets2panda/checker/ets/function.cpp index 63f1e8aa74..0076c79890 100644 --- a/ets2panda/checker/ets/function.cpp +++ b/ets2panda/checker/ets/function.cpp @@ -1393,6 +1393,16 @@ OverrideErrorCode ETSChecker::CheckOverride(Signature *signature, Signature *oth return OverrideErrorCode::OVERRIDDEN_FINAL; } + auto *ownerNode = signature->Owner()->GetDeclNode(); + auto *superNode = other->Owner()->GetDeclNode(); + bool bothRealClasses = (ownerNode != nullptr) && ownerNode->IsClassDefinition() && (superNode != nullptr) && + superNode->IsClassDefinition() && signature->Owner()->HasObjectFlag(ETSObjectFlags::CLASS) && + other->Owner()->HasObjectFlag(ETSObjectFlags::CLASS); + if (bothRealClasses && signature->HasSignatureFlag(SignatureFlags::ABSTRACT) && + !other->HasSignatureFlag(SignatureFlags::ABSTRACT)) { + return OverrideErrorCode::ABSTRACT_OVERRIDES_CONCRETE; + } + if (!other->ReturnType()->IsETSTypeParameter()) { if (!IsReturnTypeSubstitutable(signature, other)) { return OverrideErrorCode::INCOMPATIBLE_RETURN; @@ -1464,6 +1474,10 @@ void ETSChecker::ReportOverrideError(Signature *signature, Signature *overridden "overridden method."; break; } + case OverrideErrorCode::ABSTRACT_OVERRIDES_CONCRETE: { + reason = "an abstract method cannot override a non-abstract instance method."; + break; + } default: { ES2PANDA_UNREACHABLE(); } diff --git a/ets2panda/checker/resolveResult.h b/ets2panda/checker/resolveResult.h index 2c91fd4b3e..a2c09a86b6 100644 --- a/ets2panda/checker/resolveResult.h +++ b/ets2panda/checker/resolveResult.h @@ -24,6 +24,7 @@ enum class OverrideErrorCode { INCOMPATIBLE_TYPEPARAM, OVERRIDDEN_WEAKER, OVERRIDDEN_INTERNAL, + ABSTRACT_OVERRIDES_CONCRETE, }; enum class ResolvedKind { diff --git a/ets2panda/compiler/lowering/ets/unionLowering.cpp b/ets2panda/compiler/lowering/ets/unionLowering.cpp index 80fe82ec8c..69da602a6c 100644 --- a/ets2panda/compiler/lowering/ets/unionLowering.cpp +++ b/ets2panda/compiler/lowering/ets/unionLowering.cpp @@ -104,7 +104,7 @@ static std::tuple CreateNamedA // CC-OFFNXT(G.FMT.02-CPP) project code style nullptr, ir::FunctionSignature(nullptr, std::move(params), returnTypeAnno), // CC-OFFNXT(G.FMT.02-CPP) project code style - ir::ScriptFunctionFlags::METHOD, ir::ModifierFlags::PUBLIC | ir::ModifierFlags::ABSTRACT}); + ir::ScriptFunctionFlags::METHOD, ir::ModifierFlags::PUBLIC}); func->SetIdent(methodIdent->Clone(allocator, nullptr)); // Create the synthetic function node -- Gitee From 88cd1bfc64a5bae1759ba9a19a64618bce2b98af Mon Sep 17 00:00:00 2001 From: ElevenDuan Date: Wed, 30 Apr 2025 20:22:10 +0800 Subject: [PATCH 137/268] Add bytecode har test project Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC59KK?from=project-issue Change-Id: I353e5c3c589ff4d3544f96c6c6a58cb3e26164f5 Signed-off-by: ElevenDuan --- .../bytecodehar_test/.gitignore | 12 ++ .../bytecodehar_test/AppScope/app.json5 | 25 ++++ .../resources/base/element/string.json | 8 ++ .../bytecodehar_test/build-profile.json5 | 72 +++++++++++ .../bytecodehar_test/bytecode_har/.gitignore | 6 + .../bytecode_har/BuildProfile.ets | 32 +++++ .../bytecodehar_test/bytecode_har/Index.ets | 19 +++ .../bytecode_har/build-profile.json5 | 51 ++++++++ .../bytecode_har/consumer-rules.txt | 0 .../bytecode_har/hvigorfile.ts | 21 ++++ .../bytecode_har/obfuscation-rules.txt | 23 ++++ .../bytecode_har/oh-package.json5 | 27 ++++ .../src/main/ets/components/MainPage.ets | 58 +++++++++ .../src/main/ets/components/Second.ets | 48 +++++++ .../src/main/ets/components/test.ets | 18 +++ .../src/main/ets/workers/Worker.ets | 48 +++++++ .../bytecode_har/src/main/module.json5 | 27 ++++ .../main/resources/base/element/float.json | 8 ++ .../main/resources/base/element/string.json | 8 ++ .../resources/base/profile/router_map.json | 9 ++ .../src/ohosTest/ets/test/Ability.test.ets | 50 ++++++++ .../src/ohosTest/ets/test/List.test.ets | 20 +++ .../bytecode_har/src/ohosTest/module.json5 | 28 +++++ .../bytecode_har/src/test/List.test.ets | 20 +++ .../bytecode_har/src/test/LocalUnit.test.ets | 48 +++++++ .../bytecodehar_test/bytecode_har1/.gitignore | 6 + .../bytecode_har1/BuildProfile.ets | 32 +++++ .../bytecodehar_test/bytecode_har1/Index.ets | 19 +++ .../bytecode_har1/build-profile.json5 | 51 ++++++++ .../bytecode_har1/consumer-rules.txt | 0 .../bytecode_har1/hvigorfile.ts | 21 ++++ .../bytecode_har1/obfuscation-rules.txt | 23 ++++ .../bytecode_har1/oh-package.json5 | 24 ++++ .../main/ets/components/BytecodeHar1Page.ets | 35 ++++++ .../src/main/ets/components/MainPage.ets | 38 ++++++ .../src/main/ets/components/test.ets | 18 +++ .../src/main/ets/workers/Workers.ets | 48 +++++++ .../bytecode_har1/src/main/module.json5 | 27 ++++ .../main/resources/base/element/float.json | 8 ++ .../main/resources/base/element/string.json | 8 ++ .../resources/base/profile/router_map.json | 9 ++ .../src/ohosTest/ets/test/Ability.test.ets | 50 ++++++++ .../src/ohosTest/ets/test/List.test.ets | 20 +++ .../bytecode_har1/src/ohosTest/module.json5 | 28 +++++ .../bytecode_har1/src/test/List.test.ets | 20 +++ .../bytecode_har1/src/test/LocalUnit.test.ets | 48 +++++++ .../bytecodehar_test/code-linter.json5 | 47 +++++++ .../bytecodehar_test/entry/.gitignore | 6 + .../entry/build-profile.json5 | 43 +++++++ .../bytecodehar_test/entry/hvigorfile.ts | 21 ++++ .../entry/obfuscation-rules.txt | 23 ++++ .../bytecodehar_test/entry/oh-package.json5 | 30 +++++ .../main/ets/entryability/EntryAbility.ets | 59 +++++++++ .../entrybackupability/EntryBackupAbility.ets | 31 +++++ .../entry/src/main/ets/pages/Index.ets | 117 ++++++++++++++++++ .../entry/src/main/ets/pages/test.ets | 18 +++ .../entry/src/main/module.json5 | 67 ++++++++++ .../main/resources/base/element/color.json | 8 ++ .../main/resources/base/element/float.json | 8 ++ .../main/resources/base/element/string.json | 16 +++ .../resources/base/profile/backup_config.json | 3 + .../resources/base/profile/main_pages.json | 5 + .../main/resources/dark/element/color.json | 8 ++ .../entry/src/mock/mock-config.json5 | 17 +++ .../src/ohosTest/ets/test/Ability.test.ets | 50 ++++++++ .../entry/src/ohosTest/ets/test/List.test.ets | 20 +++ .../entry/src/ohosTest/module.json5 | 28 +++++ .../entry/src/test/List.test.ets | 20 +++ .../entry/src/test/LocalUnit.test.ets | 48 +++++++ .../hvigor/hvigor-config.json5 | 37 ++++++ .../bytecodehar_test/hvigorfile.ts | 21 ++++ .../bytecodehar_test/oh-package.json5 | 25 ++++ .../bytecodehar_test/source_har/.gitignore | 6 + .../source_har/BuildProfile.ets | 32 +++++ .../bytecodehar_test/source_har/Index.ets | 25 ++++ .../source_har/build-profile.json5 | 47 +++++++ .../source_har/consumer-rules.txt | 0 .../bytecodehar_test/source_har/hvigorfile.ts | 21 ++++ .../source_har/obfuscation-rules.txt | 23 ++++ .../source_har/oh-package.json5 | 24 ++++ .../src/main/ets/components/MainPage.ets | 34 +++++ .../source_har/src/main/module.json5 | 26 ++++ .../main/resources/base/element/float.json | 8 ++ .../main/resources/base/element/string.json | 8 ++ .../src/ohosTest/ets/test/Ability.test.ets | 50 ++++++++ .../src/ohosTest/ets/test/List.test.ets | 20 +++ .../source_har/src/ohosTest/module.json5 | 28 +++++ .../source_har/src/test/List.test.ets | 20 +++ .../source_har/src/test/LocalUnit.test.ets | 48 +++++++ .../bytecodehar_test/source_har1/.gitignore | 6 + .../bytecodehar_test/source_har1/Index.ets | 41 ++++++ .../source_har1/build-profile.json5 | 46 +++++++ .../source_har1/consumer-rules.txt | 0 .../source_har1/hvigorfile.ts | 21 ++++ .../source_har1/obfuscation-rules.txt | 23 ++++ .../source_har1/oh-package.json5 | 27 ++++ .../src/main/ets/components/MainPage.ets | 34 +++++ .../source_har1/src/main/module.json5 | 26 ++++ .../main/resources/base/element/float.json | 8 ++ .../main/resources/base/element/string.json | 8 ++ .../src/ohosTest/ets/test/Ability.test.ets | 50 ++++++++ .../src/ohosTest/ets/test/List.test.ets | 20 +++ .../source_har1/src/ohosTest/module.json5 | 28 +++++ .../source_har1/src/test/List.test.ets | 20 +++ .../source_har1/src/test/LocalUnit.test.ets | 48 +++++++ 105 files changed, 2821 insertions(+) create mode 100644 test/sdk_test_projects/bytecodehar_test/.gitignore create mode 100644 test/sdk_test_projects/bytecodehar_test/AppScope/app.json5 create mode 100644 test/sdk_test_projects/bytecodehar_test/AppScope/resources/base/element/string.json create mode 100644 test/sdk_test_projects/bytecodehar_test/build-profile.json5 create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har/.gitignore create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har/BuildProfile.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har/Index.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har/build-profile.json5 create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har/consumer-rules.txt create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har/hvigorfile.ts create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har/obfuscation-rules.txt create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har/oh-package.json5 create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har/src/main/ets/components/MainPage.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har/src/main/ets/components/Second.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har/src/main/ets/components/test.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har/src/main/ets/workers/Worker.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har/src/main/module.json5 create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har/src/main/resources/base/element/float.json create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har/src/main/resources/base/element/string.json create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har/src/main/resources/base/profile/router_map.json create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har/src/ohosTest/ets/test/Ability.test.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har/src/ohosTest/ets/test/List.test.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har/src/ohosTest/module.json5 create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har/src/test/List.test.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har/src/test/LocalUnit.test.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har1/.gitignore create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har1/BuildProfile.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har1/Index.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har1/build-profile.json5 create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har1/consumer-rules.txt create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har1/hvigorfile.ts create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har1/obfuscation-rules.txt create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har1/oh-package.json5 create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/main/ets/components/BytecodeHar1Page.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/main/ets/components/MainPage.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/main/ets/components/test.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/main/ets/workers/Workers.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/main/module.json5 create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/main/resources/base/element/float.json create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/main/resources/base/element/string.json create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/main/resources/base/profile/router_map.json create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/ohosTest/ets/test/Ability.test.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/ohosTest/ets/test/List.test.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/ohosTest/module.json5 create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/test/List.test.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/test/LocalUnit.test.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/code-linter.json5 create mode 100644 test/sdk_test_projects/bytecodehar_test/entry/.gitignore create mode 100644 test/sdk_test_projects/bytecodehar_test/entry/build-profile.json5 create mode 100644 test/sdk_test_projects/bytecodehar_test/entry/hvigorfile.ts create mode 100644 test/sdk_test_projects/bytecodehar_test/entry/obfuscation-rules.txt create mode 100644 test/sdk_test_projects/bytecodehar_test/entry/oh-package.json5 create mode 100644 test/sdk_test_projects/bytecodehar_test/entry/src/main/ets/entryability/EntryAbility.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/entry/src/main/ets/pages/Index.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/entry/src/main/ets/pages/test.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/entry/src/main/module.json5 create mode 100644 test/sdk_test_projects/bytecodehar_test/entry/src/main/resources/base/element/color.json create mode 100644 test/sdk_test_projects/bytecodehar_test/entry/src/main/resources/base/element/float.json create mode 100644 test/sdk_test_projects/bytecodehar_test/entry/src/main/resources/base/element/string.json create mode 100644 test/sdk_test_projects/bytecodehar_test/entry/src/main/resources/base/profile/backup_config.json create mode 100644 test/sdk_test_projects/bytecodehar_test/entry/src/main/resources/base/profile/main_pages.json create mode 100644 test/sdk_test_projects/bytecodehar_test/entry/src/main/resources/dark/element/color.json create mode 100644 test/sdk_test_projects/bytecodehar_test/entry/src/mock/mock-config.json5 create mode 100644 test/sdk_test_projects/bytecodehar_test/entry/src/ohosTest/ets/test/Ability.test.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/entry/src/ohosTest/ets/test/List.test.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/entry/src/ohosTest/module.json5 create mode 100644 test/sdk_test_projects/bytecodehar_test/entry/src/test/List.test.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/entry/src/test/LocalUnit.test.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/hvigor/hvigor-config.json5 create mode 100644 test/sdk_test_projects/bytecodehar_test/hvigorfile.ts create mode 100644 test/sdk_test_projects/bytecodehar_test/oh-package.json5 create mode 100644 test/sdk_test_projects/bytecodehar_test/source_har/.gitignore create mode 100644 test/sdk_test_projects/bytecodehar_test/source_har/BuildProfile.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/source_har/Index.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/source_har/build-profile.json5 create mode 100644 test/sdk_test_projects/bytecodehar_test/source_har/consumer-rules.txt create mode 100644 test/sdk_test_projects/bytecodehar_test/source_har/hvigorfile.ts create mode 100644 test/sdk_test_projects/bytecodehar_test/source_har/obfuscation-rules.txt create mode 100644 test/sdk_test_projects/bytecodehar_test/source_har/oh-package.json5 create mode 100644 test/sdk_test_projects/bytecodehar_test/source_har/src/main/ets/components/MainPage.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/source_har/src/main/module.json5 create mode 100644 test/sdk_test_projects/bytecodehar_test/source_har/src/main/resources/base/element/float.json create mode 100644 test/sdk_test_projects/bytecodehar_test/source_har/src/main/resources/base/element/string.json create mode 100644 test/sdk_test_projects/bytecodehar_test/source_har/src/ohosTest/ets/test/Ability.test.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/source_har/src/ohosTest/ets/test/List.test.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/source_har/src/ohosTest/module.json5 create mode 100644 test/sdk_test_projects/bytecodehar_test/source_har/src/test/List.test.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/source_har/src/test/LocalUnit.test.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/source_har1/.gitignore create mode 100644 test/sdk_test_projects/bytecodehar_test/source_har1/Index.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/source_har1/build-profile.json5 create mode 100644 test/sdk_test_projects/bytecodehar_test/source_har1/consumer-rules.txt create mode 100644 test/sdk_test_projects/bytecodehar_test/source_har1/hvigorfile.ts create mode 100644 test/sdk_test_projects/bytecodehar_test/source_har1/obfuscation-rules.txt create mode 100644 test/sdk_test_projects/bytecodehar_test/source_har1/oh-package.json5 create mode 100644 test/sdk_test_projects/bytecodehar_test/source_har1/src/main/ets/components/MainPage.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/source_har1/src/main/module.json5 create mode 100644 test/sdk_test_projects/bytecodehar_test/source_har1/src/main/resources/base/element/float.json create mode 100644 test/sdk_test_projects/bytecodehar_test/source_har1/src/main/resources/base/element/string.json create mode 100644 test/sdk_test_projects/bytecodehar_test/source_har1/src/ohosTest/ets/test/Ability.test.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/source_har1/src/ohosTest/ets/test/List.test.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/source_har1/src/ohosTest/module.json5 create mode 100644 test/sdk_test_projects/bytecodehar_test/source_har1/src/test/List.test.ets create mode 100644 test/sdk_test_projects/bytecodehar_test/source_har1/src/test/LocalUnit.test.ets diff --git a/test/sdk_test_projects/bytecodehar_test/.gitignore b/test/sdk_test_projects/bytecodehar_test/.gitignore new file mode 100644 index 0000000000..d2ff20141c --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/.gitignore @@ -0,0 +1,12 @@ +/node_modules +/oh_modules +/local.properties +/.idea +**/build +/.hvigor +.cxx +/.clangd +/.clang-format +/.clang-tidy +**/.test +/.appanalyzer \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/AppScope/app.json5 b/test/sdk_test_projects/bytecodehar_test/AppScope/app.json5 new file mode 100644 index 0000000000..c414205cbb --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/AppScope/app.json5 @@ -0,0 +1,25 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "app": { + "bundleName": "com.example.bytecodehar_test", + "vendor": "example", + "versionCode": 1000000, + "versionName": "1.0.0", + "icon": "$media:app_icon", + "label": "$string:app_name" + } +} diff --git a/test/sdk_test_projects/bytecodehar_test/AppScope/resources/base/element/string.json b/test/sdk_test_projects/bytecodehar_test/AppScope/resources/base/element/string.json new file mode 100644 index 0000000000..4622d41090 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/AppScope/resources/base/element/string.json @@ -0,0 +1,8 @@ +{ + "string": [ + { + "name": "app_name", + "value": "bytecodehar_test" + } + ] +} diff --git a/test/sdk_test_projects/bytecodehar_test/build-profile.json5 b/test/sdk_test_projects/bytecodehar_test/build-profile.json5 new file mode 100644 index 0000000000..ed8847dca0 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/build-profile.json5 @@ -0,0 +1,72 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "app": { + "signingConfigs": [], + "products": [ + { + "name": "default", + "signingConfig": "default", + "compatibleSdkVersion": "5.0.2(14)", + "runtimeOS": "HarmonyOS", + "buildOption": { + "strictMode": { + "caseSensitiveCheck": true, + "useNormalizedOHMUrl": true + } + } + } + ], + "buildModeSet": [ + { + "name": "debug", + }, + { + "name": "release" + } + ] + }, + "modules": [ + { + "name": "entry", + "srcPath": "./entry", + "targets": [ + { + "name": "default", + "applyToProducts": [ + "default" + ] + } + ] + }, + { + "name": "bytecode_har", + "srcPath": "./bytecode_har", + }, + { + "name": "bytecode_har1", + "srcPath": "./bytecode_har1", + }, + { + "name": "source_har", + "srcPath": "./source_har", + }, + { + "name": "source_har1", + "srcPath": "./source_har1", + } + ] +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har/.gitignore b/test/sdk_test_projects/bytecodehar_test/bytecode_har/.gitignore new file mode 100644 index 0000000000..e2713a2779 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har/.gitignore @@ -0,0 +1,6 @@ +/node_modules +/oh_modules +/.preview +/build +/.cxx +/.test \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har/BuildProfile.ets b/test/sdk_test_projects/bytecodehar_test/bytecode_har/BuildProfile.ets new file mode 100644 index 0000000000..2235f87d8f --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har/BuildProfile.ets @@ -0,0 +1,32 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Use these variables when you tailor your ArkTS code. They must be of the const type. + */ +export const HAR_VERSION = '1.0.0'; +export const BUILD_MODE_NAME = 'debug'; +export const DEBUG = true; +export const TARGET_NAME = 'default'; + +/** + * BuildProfile Class is used only for compatibility purposes. + */ +export default class BuildProfile { + static readonly HAR_VERSION = HAR_VERSION; + static readonly BUILD_MODE_NAME = BUILD_MODE_NAME; + static readonly DEBUG = DEBUG; + static readonly TARGET_NAME = TARGET_NAME; +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har/Index.ets b/test/sdk_test_projects/bytecodehar_test/bytecode_har/Index.ets new file mode 100644 index 0000000000..2b7c3e5569 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har/Index.ets @@ -0,0 +1,19 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { MainPage } from './src/main/ets/components/MainPage'; +export function bcharTest() { + console.log("bcharTest"); +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har/build-profile.json5 b/test/sdk_test_projects/bytecodehar_test/bytecode_har/build-profile.json5 new file mode 100644 index 0000000000..edc0970329 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har/build-profile.json5 @@ -0,0 +1,51 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "apiType": "stageMode", + "buildOption": { + "sourceOption": { + "workers": [ + './src/main/ets/workers/Worker.ets' + ] + } + }, + "buildOptionSet": [ + { + "name": "release", + "arkOptions": { + "obfuscation": { + "ruleOptions": { + "enable": false, + "files": [ + "./obfuscation-rules.txt" + ] + }, + "consumerFiles": [ + "./consumer-rules.txt" + ] + } + }, + }, + ], + "targets": [ + { + "name": "default" + }, + { + "name": "ohosTest" + } + ] +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har/consumer-rules.txt b/test/sdk_test_projects/bytecodehar_test/bytecode_har/consumer-rules.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har/hvigorfile.ts b/test/sdk_test_projects/bytecodehar_test/bytecode_har/hvigorfile.ts new file mode 100644 index 0000000000..194f648a98 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har/hvigorfile.ts @@ -0,0 +1,21 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { harTasks } from '@ohos/hvigor-ohos-plugin'; + +export default { + system: harTasks, /* Built-in plugin of Hvigor. It cannot be modified. */ + plugins:[] /* Custom plugin to extend the functionality of Hvigor. */ +} diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har/obfuscation-rules.txt b/test/sdk_test_projects/bytecodehar_test/bytecode_har/obfuscation-rules.txt new file mode 100644 index 0000000000..272efb6ca3 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har/obfuscation-rules.txt @@ -0,0 +1,23 @@ +# Define project specific obfuscation rules here. +# You can include the obfuscation configuration files in the current module's build-profile.json5. +# +# For more details, see +# https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/source-obfuscation-V5 + +# Obfuscation options: +# -disable-obfuscation: disable all obfuscations +# -enable-property-obfuscation: obfuscate the property names +# -enable-toplevel-obfuscation: obfuscate the names in the global scope +# -compact: remove unnecessary blank spaces and all line feeds +# -remove-log: remove all console.* statements +# -print-namecache: print the name cache that contains the mapping from the old names to new names +# -apply-namecache: reuse the given cache file + +# Keep options: +# -keep-property-name: specifies property names that you want to keep +# -keep-global-name: specifies names that you want to keep in the global scope + +-enable-property-obfuscation +-enable-toplevel-obfuscation +-enable-filename-obfuscation +-enable-export-obfuscation \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har/oh-package.json5 b/test/sdk_test_projects/bytecodehar_test/bytecode_har/oh-package.json5 new file mode 100644 index 0000000000..4baf6de769 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har/oh-package.json5 @@ -0,0 +1,27 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "name": "bytecode_har", + "version": "1.0.0", + "description": "Please describe the basic information.", + "main": "Index.ets", + "author": "", + "license": "Apache-2.0", + "dependencies": { + "source_har": "file:./source_har.har", + "bytecode_har1": "file:./bytecode_har1.har" + } +} diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/main/ets/components/MainPage.ets b/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/main/ets/components/MainPage.ets new file mode 100644 index 0000000000..f2fd166264 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/main/ets/components/MainPage.ets @@ -0,0 +1,58 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {sourceHarTest} from "source_har"; +import {bytecodeHar1Test} from "bytecode_har1"; +import {test} from "bytecode_har/ets/components/test"; +test(); + +@Component +export struct MainPage { + @State message: string = 'dispatch source Har'; + @State bytecideMessage: string = 'Initial state'; + + build() { + Row() { + Column() { + Button(this.message) + .fontSize(25) + .fontWeight(FontWeight.Bold) + .onClick(()=>{ + sourceHarTest(); + import("source_har").then((obj: ESObject)=>{ + console.log("dynamic import source_har"); + obj.sourceHarTest(); + }) + }) + Button("bytecode har1 test") + .fontSize(25) + .fontWeight(FontWeight.Bold) + .onClick(()=>{ + sourceHarTest(); + import("bytecode_har1").then((obj: ESObject)=>{ + console.log("dynamic import source_har"); + obj.bytecodeHar1Test(); + this.bytecideMessage = "byteciode har1 test executed" + }) + }) + Text(this.bytecideMessage) + .fontSize(25) + .fontWeight(FontWeight.Bold) + } + .width('100%') + } + .height('100%') + } +} diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/main/ets/components/Second.ets b/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/main/ets/components/Second.ets new file mode 100644 index 0000000000..d27b669bc0 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/main/ets/components/Second.ets @@ -0,0 +1,48 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@Builder +export function SecondPageBuilder() { + Second() +} + +@Component +export struct Second { + pageStack: NavPathStack = new NavPathStack(); + @State message: string = 'SecondPage'; + @State bytecideMessage: string = 'Initial state'; + + build() { + NavDestination() { + Column() { + Text(this.message) + .fontSize(25) + .fontWeight(FontWeight.Bold) + .fontColor(Color.Red) + Text("push to bytecode har1") + .fontSize(25) + .fontWeight(FontWeight.Bold) + .fontColor(Color.Red) + .onClick(()=>{ + this.pageStack.pushPathByName("BytecodeHar1Page", null, false); + }) + } + } + .title('SecondPage') + .onReady((context: NavDestinationContext)=>{ + this.pageStack = context.pathStack; + }); + } +} diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/main/ets/components/test.ets b/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/main/ets/components/test.ets new file mode 100644 index 0000000000..d1fd9fe658 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/main/ets/components/test.ets @@ -0,0 +1,18 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export function test() { + console.log("test"); +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/main/ets/workers/Worker.ets b/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/main/ets/workers/Worker.ets new file mode 100644 index 0000000000..d5e2461619 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/main/ets/workers/Worker.ets @@ -0,0 +1,48 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ErrorEvent, JSON, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS'; + +const workerPort: ThreadWorkerGlobalScope = worker.workerPort; +let i = 0; +/** + * Defines the event handler to be called when the worker thread receives a message sent by the host thread. + * The event handler is executed in the worker thread. + * + * @param event message data + */ +workerPort.onmessage = (event: MessageEvents) => { + console.log('bytecode har recevived entry on Message success', JSON.stringify(event)); + i++; + workerPort.postMessage(`bytecode har post message: ${i}`); +}; + +/** + * Defines the event handler to be called when the worker receives a message that cannot be deserialized. + * The event handler is executed in the worker thread. + * + * @param event message data + */ +workerPort.onmessageerror = (event: MessageEvents) => { +}; + +/** + * Defines the event handler to be called when an exception occurs during worker execution. + * The event handler is executed in the worker thread. + * + * @param event error message + */ +workerPort.onerror = (event: ErrorEvent) => { +}; \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/main/module.json5 b/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/main/module.json5 new file mode 100644 index 0000000000..e13a1c188b --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/main/module.json5 @@ -0,0 +1,27 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "module": { + "name": "bytecode_har", + "type": "har", + "deviceTypes": [ + "default", + "tablet", + "2in1" + ], + "routerMap": "$profile:router_map" + } +} diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/main/resources/base/element/float.json b/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/main/resources/base/element/float.json new file mode 100644 index 0000000000..33ea22304f --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/main/resources/base/element/float.json @@ -0,0 +1,8 @@ +{ + "float": [ + { + "name": "page_text_font_size", + "value": "50fp" + } + ] +} diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/main/resources/base/element/string.json b/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/main/resources/base/element/string.json new file mode 100644 index 0000000000..f51a9c8461 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/main/resources/base/element/string.json @@ -0,0 +1,8 @@ +{ + "string": [ + { + "name": "page_show", + "value": "page from package" + } + ] +} diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/main/resources/base/profile/router_map.json b/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/main/resources/base/profile/router_map.json new file mode 100644 index 0000000000..31ba4575a1 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/main/resources/base/profile/router_map.json @@ -0,0 +1,9 @@ +{ + "routerMap": [ + { + "name": "SecondPage", + "pageSourceFile": "src/main/ets/components/Second.ets", + "buildFunction": "SecondPageBuilder" + } + ] +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/ohosTest/ets/test/Ability.test.ets b/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/ohosTest/ets/test/Ability.test.ets new file mode 100644 index 0000000000..bc35f7c995 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/ohosTest/ets/test/Ability.test.ets @@ -0,0 +1,50 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { hilog } from '@kit.PerformanceAnalysisKit'; +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium'; + +export default function abilityTest() { + describe('ActsAbilityTest', () => { + // Defines a test suite. Two parameters are supported: test suite name and test suite function. + beforeAll(() => { + // Presets an action, which is performed only once before all test cases of the test suite start. + // This API supports only one parameter: preset action function. + }) + beforeEach(() => { + // Presets an action, which is performed before each unit test case starts. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: preset action function. + }) + afterEach(() => { + // Presets a clear action, which is performed after each unit test case ends. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: clear action function. + }) + afterAll(() => { + // Presets a clear action, which is performed after all test cases of the test suite end. + // This API supports only one parameter: clear action function. + }) + it('assertContain', 0, () => { + // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function. + hilog.info(0x0000, 'testTag', '%{public}s', 'it begin'); + let a = 'abc'; + let b = 'b'; + // Defines a variety of assertion methods, which are used to declare expected boolean conditions. + expect(a).assertContain(b); + expect(a).assertEqual(a); + }) + }) +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/ohosTest/ets/test/List.test.ets b/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/ohosTest/ets/test/List.test.ets new file mode 100644 index 0000000000..683e5df1cd --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/ohosTest/ets/test/List.test.ets @@ -0,0 +1,20 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import abilityTest from './Ability.test'; + +export default function testsuite() { + abilityTest(); +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/ohosTest/module.json5 b/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/ohosTest/module.json5 new file mode 100644 index 0000000000..d665314458 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/ohosTest/module.json5 @@ -0,0 +1,28 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "module": { + "name": "bytecode_har_test", + "type": "feature", + "deviceTypes": [ + "default", + "tablet", + "2in1" + ], + "deliveryWithInstall": true, + "installationFree": false + } +} diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/test/List.test.ets b/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/test/List.test.ets new file mode 100644 index 0000000000..4d92bb1fb8 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/test/List.test.ets @@ -0,0 +1,20 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import localUnitTest from './LocalUnit.test'; + +export default function testsuite() { + localUnitTest(); +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/test/LocalUnit.test.ets b/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/test/LocalUnit.test.ets new file mode 100644 index 0000000000..555ba8084b --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har/src/test/LocalUnit.test.ets @@ -0,0 +1,48 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium'; + +export default function localUnitTest() { + describe('localUnitTest', () => { + // Defines a test suite. Two parameters are supported: test suite name and test suite function. + beforeAll(() => { + // Presets an action, which is performed only once before all test cases of the test suite start. + // This API supports only one parameter: preset action function. + }); + beforeEach(() => { + // Presets an action, which is performed before each unit test case starts. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: preset action function. + }); + afterEach(() => { + // Presets a clear action, which is performed after each unit test case ends. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: clear action function. + }); + afterAll(() => { + // Presets a clear action, which is performed after all test cases of the test suite end. + // This API supports only one parameter: clear action function. + }); + it('assertContain', 0, () => { + // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function. + let a = 'abc'; + let b = 'b'; + // Defines a variety of assertion methods, which are used to declare expected boolean conditions. + expect(a).assertContain(b); + expect(a).assertEqual(a); + }); + }); +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har1/.gitignore b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/.gitignore new file mode 100644 index 0000000000..e2713a2779 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/.gitignore @@ -0,0 +1,6 @@ +/node_modules +/oh_modules +/.preview +/build +/.cxx +/.test \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har1/BuildProfile.ets b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/BuildProfile.ets new file mode 100644 index 0000000000..2235f87d8f --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/BuildProfile.ets @@ -0,0 +1,32 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Use these variables when you tailor your ArkTS code. They must be of the const type. + */ +export const HAR_VERSION = '1.0.0'; +export const BUILD_MODE_NAME = 'debug'; +export const DEBUG = true; +export const TARGET_NAME = 'default'; + +/** + * BuildProfile Class is used only for compatibility purposes. + */ +export default class BuildProfile { + static readonly HAR_VERSION = HAR_VERSION; + static readonly BUILD_MODE_NAME = BUILD_MODE_NAME; + static readonly DEBUG = DEBUG; + static readonly TARGET_NAME = TARGET_NAME; +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har1/Index.ets b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/Index.ets new file mode 100644 index 0000000000..972fa9fc7b --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/Index.ets @@ -0,0 +1,19 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { MainPage } from './src/main/ets/components/MainPage'; +export function bytecodeHar1Test() { + console.log("bytecode har1 test"); +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har1/build-profile.json5 b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/build-profile.json5 new file mode 100644 index 0000000000..faeced45ce --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/build-profile.json5 @@ -0,0 +1,51 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "apiType": "stageMode", + "buildOption": { + "sourceOption": { + "workers": [ + './src/main/ets/workers/Workers.ets' + ] + } + }, + "buildOptionSet": [ + { + "name": "release", + "arkOptions": { + "obfuscation": { + "ruleOptions": { + "enable": false, + "files": [ + "./obfuscation-rules.txt" + ] + }, + "consumerFiles": [ + "./consumer-rules.txt" + ] + } + }, + }, + ], + "targets": [ + { + "name": "default" + }, + { + "name": "ohosTest" + } + ] +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har1/consumer-rules.txt b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/consumer-rules.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har1/hvigorfile.ts b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/hvigorfile.ts new file mode 100644 index 0000000000..194f648a98 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/hvigorfile.ts @@ -0,0 +1,21 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { harTasks } from '@ohos/hvigor-ohos-plugin'; + +export default { + system: harTasks, /* Built-in plugin of Hvigor. It cannot be modified. */ + plugins:[] /* Custom plugin to extend the functionality of Hvigor. */ +} diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har1/obfuscation-rules.txt b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/obfuscation-rules.txt new file mode 100644 index 0000000000..272efb6ca3 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/obfuscation-rules.txt @@ -0,0 +1,23 @@ +# Define project specific obfuscation rules here. +# You can include the obfuscation configuration files in the current module's build-profile.json5. +# +# For more details, see +# https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/source-obfuscation-V5 + +# Obfuscation options: +# -disable-obfuscation: disable all obfuscations +# -enable-property-obfuscation: obfuscate the property names +# -enable-toplevel-obfuscation: obfuscate the names in the global scope +# -compact: remove unnecessary blank spaces and all line feeds +# -remove-log: remove all console.* statements +# -print-namecache: print the name cache that contains the mapping from the old names to new names +# -apply-namecache: reuse the given cache file + +# Keep options: +# -keep-property-name: specifies property names that you want to keep +# -keep-global-name: specifies names that you want to keep in the global scope + +-enable-property-obfuscation +-enable-toplevel-obfuscation +-enable-filename-obfuscation +-enable-export-obfuscation \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har1/oh-package.json5 b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/oh-package.json5 new file mode 100644 index 0000000000..a062721df4 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/oh-package.json5 @@ -0,0 +1,24 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "name": "bytecode_har1", + "version": "1.0.0", + "description": "Please describe the basic information.", + "main": "Index.ets", + "author": "", + "license": "Apache-2.0", + "dependencies": {} +} diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/main/ets/components/BytecodeHar1Page.ets b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/main/ets/components/BytecodeHar1Page.ets new file mode 100644 index 0000000000..a9081250ad --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/main/ets/components/BytecodeHar1Page.ets @@ -0,0 +1,35 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@Builder +export function BytecodeHar1PageBuilder() { + BytecodeHar1Page() +} +@Component +export struct BytecodeHar1Page { + @State message: string = 'BytecodeHar1Page'; + + build() { + NavDestination() { + Column() { + Text(this.message) + .fontSize($r('app.float.page_text_font_size')) + .fontWeight(FontWeight.Bold) + } + } + .title("BytecodeHar1Page") + .height('100%') + } +} diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/main/ets/components/MainPage.ets b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/main/ets/components/MainPage.ets new file mode 100644 index 0000000000..274df9cee6 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/main/ets/components/MainPage.ets @@ -0,0 +1,38 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {test} from "./test"; +test(); +import("./test").then((obj: ESObject)=>{ + console.log(obj); + obj.test() +}) + +@Component +export struct MainPage { + @State message: string = 'Hello World'; + + build() { + Row() { + Column() { + Text(this.message) + .fontSize($r('app.float.page_text_font_size')) + .fontWeight(FontWeight.Bold) + } + .width('100%') + } + .height('100%') + } +} diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/main/ets/components/test.ets b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/main/ets/components/test.ets new file mode 100644 index 0000000000..21b3db2731 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/main/ets/components/test.ets @@ -0,0 +1,18 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export function test() { + console.log("this is bytecodehar1 test") +} diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/main/ets/workers/Workers.ets b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/main/ets/workers/Workers.ets new file mode 100644 index 0000000000..e3e7b9d8fa --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/main/ets/workers/Workers.ets @@ -0,0 +1,48 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ErrorEvent, JSON, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS'; + +const workerPort: ThreadWorkerGlobalScope = worker.workerPort; +let i = 0; +/** + * Defines the event handler to be called when the worker thread receives a message sent by the host thread. + * The event handler is executed in the worker thread. + * + * @param event message data + */ +workerPort.onmessage = (event: MessageEvents) => { + console.log('bytecode har1 received entry on message success:', JSON.stringify(event)); + i++; + workerPort.postMessage(`bytecode har2 post message:' ${i}`); +}; + +/** + * Defines the event handler to be called when the worker receives a message that cannot be deserialized. + * The event handler is executed in the worker thread. + * + * @param event message data + */ +workerPort.onmessageerror = (event: MessageEvents) => { +}; + +/** + * Defines the event handler to be called when an exception occurs during worker execution. + * The event handler is executed in the worker thread. + * + * @param event error message + */ +workerPort.onerror = (event: ErrorEvent) => { +}; diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/main/module.json5 b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/main/module.json5 new file mode 100644 index 0000000000..21fa9fdef9 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/main/module.json5 @@ -0,0 +1,27 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "module": { + "name": "bytecode_har1", + "type": "har", + "deviceTypes": [ + "default", + "tablet", + "2in1" + ], + "routerMap": "$profile:router_map" + } +} diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/main/resources/base/element/float.json b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/main/resources/base/element/float.json new file mode 100644 index 0000000000..33ea22304f --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/main/resources/base/element/float.json @@ -0,0 +1,8 @@ +{ + "float": [ + { + "name": "page_text_font_size", + "value": "50fp" + } + ] +} diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/main/resources/base/element/string.json b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/main/resources/base/element/string.json new file mode 100644 index 0000000000..f51a9c8461 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/main/resources/base/element/string.json @@ -0,0 +1,8 @@ +{ + "string": [ + { + "name": "page_show", + "value": "page from package" + } + ] +} diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/main/resources/base/profile/router_map.json b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/main/resources/base/profile/router_map.json new file mode 100644 index 0000000000..a16c711da4 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/main/resources/base/profile/router_map.json @@ -0,0 +1,9 @@ +{ + "routerMap": [ + { + "name": "BytecodeHar1Page", + "pageSourceFile": "src/main/ets/components/BytecodeHar1Page.ets", + "buildFunction": "BytecodeHar1PageBuilder" + } + ] +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/ohosTest/ets/test/Ability.test.ets b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/ohosTest/ets/test/Ability.test.ets new file mode 100644 index 0000000000..bc35f7c995 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/ohosTest/ets/test/Ability.test.ets @@ -0,0 +1,50 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { hilog } from '@kit.PerformanceAnalysisKit'; +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium'; + +export default function abilityTest() { + describe('ActsAbilityTest', () => { + // Defines a test suite. Two parameters are supported: test suite name and test suite function. + beforeAll(() => { + // Presets an action, which is performed only once before all test cases of the test suite start. + // This API supports only one parameter: preset action function. + }) + beforeEach(() => { + // Presets an action, which is performed before each unit test case starts. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: preset action function. + }) + afterEach(() => { + // Presets a clear action, which is performed after each unit test case ends. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: clear action function. + }) + afterAll(() => { + // Presets a clear action, which is performed after all test cases of the test suite end. + // This API supports only one parameter: clear action function. + }) + it('assertContain', 0, () => { + // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function. + hilog.info(0x0000, 'testTag', '%{public}s', 'it begin'); + let a = 'abc'; + let b = 'b'; + // Defines a variety of assertion methods, which are used to declare expected boolean conditions. + expect(a).assertContain(b); + expect(a).assertEqual(a); + }) + }) +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/ohosTest/ets/test/List.test.ets b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/ohosTest/ets/test/List.test.ets new file mode 100644 index 0000000000..683e5df1cd --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/ohosTest/ets/test/List.test.ets @@ -0,0 +1,20 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import abilityTest from './Ability.test'; + +export default function testsuite() { + abilityTest(); +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/ohosTest/module.json5 b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/ohosTest/module.json5 new file mode 100644 index 0000000000..929339ece6 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/ohosTest/module.json5 @@ -0,0 +1,28 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "module": { + "name": "bytecode_har1_test", + "type": "feature", + "deviceTypes": [ + "default", + "tablet", + "2in1" + ], + "deliveryWithInstall": true, + "installationFree": false + } +} diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/test/List.test.ets b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/test/List.test.ets new file mode 100644 index 0000000000..4d92bb1fb8 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/test/List.test.ets @@ -0,0 +1,20 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import localUnitTest from './LocalUnit.test'; + +export default function testsuite() { + localUnitTest(); +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/test/LocalUnit.test.ets b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/test/LocalUnit.test.ets new file mode 100644 index 0000000000..555ba8084b --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/bytecode_har1/src/test/LocalUnit.test.ets @@ -0,0 +1,48 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium'; + +export default function localUnitTest() { + describe('localUnitTest', () => { + // Defines a test suite. Two parameters are supported: test suite name and test suite function. + beforeAll(() => { + // Presets an action, which is performed only once before all test cases of the test suite start. + // This API supports only one parameter: preset action function. + }); + beforeEach(() => { + // Presets an action, which is performed before each unit test case starts. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: preset action function. + }); + afterEach(() => { + // Presets a clear action, which is performed after each unit test case ends. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: clear action function. + }); + afterAll(() => { + // Presets a clear action, which is performed after all test cases of the test suite end. + // This API supports only one parameter: clear action function. + }); + it('assertContain', 0, () => { + // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function. + let a = 'abc'; + let b = 'b'; + // Defines a variety of assertion methods, which are used to declare expected boolean conditions. + expect(a).assertContain(b); + expect(a).assertEqual(a); + }); + }); +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/code-linter.json5 b/test/sdk_test_projects/bytecodehar_test/code-linter.json5 new file mode 100644 index 0000000000..b83cb20573 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/code-linter.json5 @@ -0,0 +1,47 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "files": [ + "**/*.ets" + ], + "ignore": [ + "**/src/ohosTest/**/*", + "**/src/test/**/*", + "**/src/mock/**/*", + "**/node_modules/**/*", + "**/oh_modules/**/*", + "**/build/**/*", + "**/.preview/**/*" + ], + "ruleSet": [ + "plugin:@performance/recommended", + "plugin:@typescript-eslint/recommended" + ], + "rules": { + "@security/no-unsafe-aes": "error", + "@security/no-unsafe-hash": "error", + "@security/no-unsafe-mac": "warn", + "@security/no-unsafe-dh": "error", + "@security/no-unsafe-dsa": "error", + "@security/no-unsafe-ecdsa": "error", + "@security/no-unsafe-rsa-encrypt": "error", + "@security/no-unsafe-rsa-sign": "error", + "@security/no-unsafe-rsa-key": "error", + "@security/no-unsafe-dsa-key": "error", + "@security/no-unsafe-dh-key": "error", + "@security/no-unsafe-3des": "error" + } +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/entry/.gitignore b/test/sdk_test_projects/bytecodehar_test/entry/.gitignore new file mode 100644 index 0000000000..e2713a2779 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/entry/.gitignore @@ -0,0 +1,6 @@ +/node_modules +/oh_modules +/.preview +/build +/.cxx +/.test \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/entry/build-profile.json5 b/test/sdk_test_projects/bytecodehar_test/entry/build-profile.json5 new file mode 100644 index 0000000000..43057f9f4c --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/entry/build-profile.json5 @@ -0,0 +1,43 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "apiType": "stageMode", + "buildOption": { + }, + "buildOptionSet": [ + { + "name": "release", + "arkOptions": { + "obfuscation": { + "ruleOptions": { + "enable": false, + "files": [ + "./obfuscation-rules.txt" + ] + } + } + } + }, + ], + "targets": [ + { + "name": "default" + }, + { + "name": "ohosTest", + } + ] +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/entry/hvigorfile.ts b/test/sdk_test_projects/bytecodehar_test/entry/hvigorfile.ts new file mode 100644 index 0000000000..8df8885cb2 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/entry/hvigorfile.ts @@ -0,0 +1,21 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { hapTasks } from '@ohos/hvigor-ohos-plugin'; + +export default { + system: hapTasks, /* Built-in plugin of Hvigor. It cannot be modified. */ + plugins:[] /* Custom plugin to extend the functionality of Hvigor. */ +} diff --git a/test/sdk_test_projects/bytecodehar_test/entry/obfuscation-rules.txt b/test/sdk_test_projects/bytecodehar_test/entry/obfuscation-rules.txt new file mode 100644 index 0000000000..272efb6ca3 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/entry/obfuscation-rules.txt @@ -0,0 +1,23 @@ +# Define project specific obfuscation rules here. +# You can include the obfuscation configuration files in the current module's build-profile.json5. +# +# For more details, see +# https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/source-obfuscation-V5 + +# Obfuscation options: +# -disable-obfuscation: disable all obfuscations +# -enable-property-obfuscation: obfuscate the property names +# -enable-toplevel-obfuscation: obfuscate the names in the global scope +# -compact: remove unnecessary blank spaces and all line feeds +# -remove-log: remove all console.* statements +# -print-namecache: print the name cache that contains the mapping from the old names to new names +# -apply-namecache: reuse the given cache file + +# Keep options: +# -keep-property-name: specifies property names that you want to keep +# -keep-global-name: specifies names that you want to keep in the global scope + +-enable-property-obfuscation +-enable-toplevel-obfuscation +-enable-filename-obfuscation +-enable-export-obfuscation \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/entry/oh-package.json5 b/test/sdk_test_projects/bytecodehar_test/entry/oh-package.json5 new file mode 100644 index 0000000000..1953e3fb41 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/entry/oh-package.json5 @@ -0,0 +1,30 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "name": "entry", + "version": "1.0.0", + "description": "Please describe the basic information.", + "main": "", + "author": "", + "license": "", + "dependencies": { + "bytecode_har" : "file:./bytecode_har.har", + "bytecode_har1" : "file:./bytecode_har1.har", + "source_har" : "file:../source_har", + "source_har1": "file:../source_har1" + } +} + diff --git a/test/sdk_test_projects/bytecodehar_test/entry/src/main/ets/entryability/EntryAbility.ets b/test/sdk_test_projects/bytecodehar_test/entry/src/main/ets/entryability/EntryAbility.ets new file mode 100644 index 0000000000..4d04abce31 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/entry/src/main/ets/entryability/EntryAbility.ets @@ -0,0 +1,59 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { AbilityConstant, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit'; +import { hilog } from '@kit.PerformanceAnalysisKit'; +import { window } from '@kit.ArkUI'; + +const DOMAIN = 0x0000; + +export default class EntryAbility extends UIAbility { + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { + this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET); + hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onCreate'); + } + + onDestroy(): void { + hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onDestroy'); + } + + onWindowStageCreate(windowStage: window.WindowStage): void { + // Main window is created, set main page for this ability + hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); + + windowStage.loadContent('pages/Index', (err) => { + if (err.code) { + hilog.error(DOMAIN, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err)); + return; + } + hilog.info(DOMAIN, 'testTag', 'Succeeded in loading the content.'); + }); + } + + onWindowStageDestroy(): void { + // Main window is destroyed, release UI related resources + hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageDestroy'); + } + + onForeground(): void { + // Ability has brought to foreground + hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onForeground'); + } + + onBackground(): void { + // Ability has back to background + hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onBackground'); + } +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets b/test/sdk_test_projects/bytecodehar_test/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets new file mode 100644 index 0000000000..fc0108ed40 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets @@ -0,0 +1,31 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { hilog } from '@kit.PerformanceAnalysisKit'; +import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit'; + +const DOMAIN = 0x0000; + +export default class EntryBackupAbility extends BackupExtensionAbility { + async onBackup() { + hilog.info(DOMAIN, 'testTag', 'onBackup ok'); + await Promise.resolve(); + } + + async onRestore(bundleVersion: BundleVersion) { + hilog.info(DOMAIN, 'testTag', 'onRestore ok %{public}s', JSON.stringify(bundleVersion)); + await Promise.resolve(); + } +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/entry/src/main/ets/pages/Index.ets b/test/sdk_test_projects/bytecodehar_test/entry/src/main/ets/pages/Index.ets new file mode 100644 index 0000000000..13b9f114d1 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/entry/src/main/ets/pages/Index.ets @@ -0,0 +1,117 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import worker from '@ohos.worker'; +import {MainPage} from "bytecode_har" +import {sourceHarTest} from "source_har" +import {bycodeHar1Test} from "bytecode_har1" +import {sourceHarDispatchbcHarTest} from "source_har1" +import promptAction from '@ohos.promptAction' +import {test} from "entry/ets/pages/test" +test() + +console.log("hap dispatch test") +sourceHarTest(); +import ("source_har").then((obj :ESObject)=>{ + console.log("dynamic import source_har") + obj.sourceHarTest(); +}) + +bycodeHar1Test(); +import ("bytecode_har1").then((obj :ESObject)=>{ + console.log("dynamic import bytecodehar2") + obj.bycodeHar1Test(); +}) +@Entry +@Component +struct Index { + @State message: string = 'Hello World'; + pageStack : NavPathStack = new NavPathStack(); + workerInstance?: worker.ThreadWorker; + workerInstance1?: worker.ThreadWorker; + createWorkerThread() { + this.workerInstance = new worker.ThreadWorker("@bytecode_har/ets/workers/Worker.ets"); + this.workerInstance.onmessage = (e) => { + console.log("receive bytecodehar thread message success", e.data); + promptAction.showToast({ + message: "bytecodehar" + e.data, + duration: 2000 + }); + } + this.workerInstance1 = new worker.ThreadWorker("@bytecode_har1/ets/workers/Workers.ets"); + this.workerInstance1.onmessage = (e) => { + console.log("receive bytecodehar thread message success", e.data); + promptAction.showToast({ + message: "bytecodehar2" + e.data, + duration: 2000 + }); + } + } + + aboutToAppear(): void { + this.createWorkerThread(); + } + + build() { + Navigation(this.pageStack) { + Button("push Second Page1111") + .fontWeight(FontWeight.Bold) + .fontSize(25) + .alignRules({ + center: { anchor: 'container', align: VerticalAlign.Center }, + middle: { anchor: 'container', align: HorizontalAlign.Center } + }) + .onClick(()=>{ + this.pageStack.pushPathByName("SecondPage", null, false); + }) + + Button("dispatch bchar worker") + .fontWeight(FontWeight.Bold) + .fontSize(25) + .alignRules({ + center: { anchor: '__container__', align: VerticalAlign.Center }, + middle: { anchor: '__container__', align: HorizontalAlign.Center } + }) + .onClick(()=>{ + this.workerInstance?.postMessage(" hap to bytecodehar thread begin"); + }) + Button("dispatch bchar2 worker") + .fontWeight(FontWeight.Bold) + .fontSize(25) + .alignRules({ + center: { anchor: '__container__', align: VerticalAlign.Center }, + middle: { anchor: '__container__', align: HorizontalAlign.Center } + }) + .onClick(()=>{ + this.workerInstance1?.postMessage(" hap to bytecodehar2 thread begin"); + }) + Button("dispatch sourcehar1 test") + .fontWeight(FontWeight.Bold) + .fontSize(25) + .alignRules({ + center: { anchor: '__container__', align: VerticalAlign.Center }, + middle: { anchor: '__container__', align: HorizontalAlign.Center } + }) + + .onClick(()=>{ + sourceHarDispatchbcHarTest() + }) + MainPage() + } + .title("Entry Page") + .height('100%') + .width('100%') + } +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/entry/src/main/ets/pages/test.ets b/test/sdk_test_projects/bytecodehar_test/entry/src/main/ets/pages/test.ets new file mode 100644 index 0000000000..c595bc91b6 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/entry/src/main/ets/pages/test.ets @@ -0,0 +1,18 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export function test() { + console.log("1111"); +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/entry/src/main/module.json5 b/test/sdk_test_projects/bytecodehar_test/entry/src/main/module.json5 new file mode 100644 index 0000000000..496f8feb49 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/entry/src/main/module.json5 @@ -0,0 +1,67 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "module": { + "name": "entry", + "type": "entry", + "description": "$string:module_desc", + "mainElement": "EntryAbility", + "deviceTypes": [ + "phone", + "tablet", + "2in1" + ], + "deliveryWithInstall": true, + "installationFree": false, + "pages": "$profile:main_pages", + "abilities": [ + { + "name": "EntryAbility", + "srcEntry": "./ets/entryability/EntryAbility.ets", + "description": "$string:EntryAbility_desc", + "icon": "$media:layered_image", + "label": "$string:EntryAbility_label", + "startWindowIcon": "$media:startIcon", + "startWindowBackground": "$color:start_window_background", + "exported": true, + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ] + } + ], + "extensionAbilities": [ + { + "name": "EntryBackupAbility", + "srcEntry": "./ets/entrybackupability/EntryBackupAbility.ets", + "type": "backup", + "exported": false, + "metadata": [ + { + "name": "ohos.extension.backup", + "resource": "$profile:backup_config" + } + ], + } + ] + } +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/entry/src/main/resources/base/element/color.json b/test/sdk_test_projects/bytecodehar_test/entry/src/main/resources/base/element/color.json new file mode 100644 index 0000000000..d66f9a7d4a --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/entry/src/main/resources/base/element/color.json @@ -0,0 +1,8 @@ +{ + "color": [ + { + "name": "start_window_background", + "value": "#FFFFFF" + } + ] +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/entry/src/main/resources/base/element/float.json b/test/sdk_test_projects/bytecodehar_test/entry/src/main/resources/base/element/float.json new file mode 100644 index 0000000000..a8a5d404dc --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/entry/src/main/resources/base/element/float.json @@ -0,0 +1,8 @@ +{ + "float": [ + { + "name": "page_text_font_size", + "value": "50fp" + } + ] +} diff --git a/test/sdk_test_projects/bytecodehar_test/entry/src/main/resources/base/element/string.json b/test/sdk_test_projects/bytecodehar_test/entry/src/main/resources/base/element/string.json new file mode 100644 index 0000000000..f94595515a --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/entry/src/main/resources/base/element/string.json @@ -0,0 +1,16 @@ +{ + "string": [ + { + "name": "module_desc", + "value": "module description" + }, + { + "name": "EntryAbility_desc", + "value": "description" + }, + { + "name": "EntryAbility_label", + "value": "label" + } + ] +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/entry/src/main/resources/base/profile/backup_config.json b/test/sdk_test_projects/bytecodehar_test/entry/src/main/resources/base/profile/backup_config.json new file mode 100644 index 0000000000..d742c2f96e --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/entry/src/main/resources/base/profile/backup_config.json @@ -0,0 +1,3 @@ +{ + "allowToBackupRestore": true +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/entry/src/main/resources/base/profile/main_pages.json b/test/sdk_test_projects/bytecodehar_test/entry/src/main/resources/base/profile/main_pages.json new file mode 100644 index 0000000000..1898d94f58 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/entry/src/main/resources/base/profile/main_pages.json @@ -0,0 +1,5 @@ +{ + "src": [ + "pages/Index" + ] +} diff --git a/test/sdk_test_projects/bytecodehar_test/entry/src/main/resources/dark/element/color.json b/test/sdk_test_projects/bytecodehar_test/entry/src/main/resources/dark/element/color.json new file mode 100644 index 0000000000..438d5bc43b --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/entry/src/main/resources/dark/element/color.json @@ -0,0 +1,8 @@ +{ + "color": [ + { + "name": "start_window_background", + "value": "#000000" + } + ] +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/entry/src/mock/mock-config.json5 b/test/sdk_test_projects/bytecodehar_test/entry/src/mock/mock-config.json5 new file mode 100644 index 0000000000..e263e74743 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/entry/src/mock/mock-config.json5 @@ -0,0 +1,17 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/entry/src/ohosTest/ets/test/Ability.test.ets b/test/sdk_test_projects/bytecodehar_test/entry/src/ohosTest/ets/test/Ability.test.ets new file mode 100644 index 0000000000..bc35f7c995 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/entry/src/ohosTest/ets/test/Ability.test.ets @@ -0,0 +1,50 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { hilog } from '@kit.PerformanceAnalysisKit'; +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium'; + +export default function abilityTest() { + describe('ActsAbilityTest', () => { + // Defines a test suite. Two parameters are supported: test suite name and test suite function. + beforeAll(() => { + // Presets an action, which is performed only once before all test cases of the test suite start. + // This API supports only one parameter: preset action function. + }) + beforeEach(() => { + // Presets an action, which is performed before each unit test case starts. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: preset action function. + }) + afterEach(() => { + // Presets a clear action, which is performed after each unit test case ends. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: clear action function. + }) + afterAll(() => { + // Presets a clear action, which is performed after all test cases of the test suite end. + // This API supports only one parameter: clear action function. + }) + it('assertContain', 0, () => { + // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function. + hilog.info(0x0000, 'testTag', '%{public}s', 'it begin'); + let a = 'abc'; + let b = 'b'; + // Defines a variety of assertion methods, which are used to declare expected boolean conditions. + expect(a).assertContain(b); + expect(a).assertEqual(a); + }) + }) +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/entry/src/ohosTest/ets/test/List.test.ets b/test/sdk_test_projects/bytecodehar_test/entry/src/ohosTest/ets/test/List.test.ets new file mode 100644 index 0000000000..683e5df1cd --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/entry/src/ohosTest/ets/test/List.test.ets @@ -0,0 +1,20 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import abilityTest from './Ability.test'; + +export default function testsuite() { + abilityTest(); +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/entry/src/ohosTest/module.json5 b/test/sdk_test_projects/bytecodehar_test/entry/src/ohosTest/module.json5 new file mode 100644 index 0000000000..b361ba491c --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/entry/src/ohosTest/module.json5 @@ -0,0 +1,28 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "module": { + "name": "entry_test", + "type": "feature", + "deviceTypes": [ + "phone", + "tablet", + "2in1" + ], + "deliveryWithInstall": true, + "installationFree": false + } +} diff --git a/test/sdk_test_projects/bytecodehar_test/entry/src/test/List.test.ets b/test/sdk_test_projects/bytecodehar_test/entry/src/test/List.test.ets new file mode 100644 index 0000000000..4d92bb1fb8 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/entry/src/test/List.test.ets @@ -0,0 +1,20 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import localUnitTest from './LocalUnit.test'; + +export default function testsuite() { + localUnitTest(); +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/entry/src/test/LocalUnit.test.ets b/test/sdk_test_projects/bytecodehar_test/entry/src/test/LocalUnit.test.ets new file mode 100644 index 0000000000..555ba8084b --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/entry/src/test/LocalUnit.test.ets @@ -0,0 +1,48 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium'; + +export default function localUnitTest() { + describe('localUnitTest', () => { + // Defines a test suite. Two parameters are supported: test suite name and test suite function. + beforeAll(() => { + // Presets an action, which is performed only once before all test cases of the test suite start. + // This API supports only one parameter: preset action function. + }); + beforeEach(() => { + // Presets an action, which is performed before each unit test case starts. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: preset action function. + }); + afterEach(() => { + // Presets a clear action, which is performed after each unit test case ends. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: clear action function. + }); + afterAll(() => { + // Presets a clear action, which is performed after all test cases of the test suite end. + // This API supports only one parameter: clear action function. + }); + it('assertContain', 0, () => { + // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function. + let a = 'abc'; + let b = 'b'; + // Defines a variety of assertion methods, which are used to declare expected boolean conditions. + expect(a).assertContain(b); + expect(a).assertEqual(a); + }); + }); +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/hvigor/hvigor-config.json5 b/test/sdk_test_projects/bytecodehar_test/hvigor/hvigor-config.json5 new file mode 100644 index 0000000000..47b3a60e59 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/hvigor/hvigor-config.json5 @@ -0,0 +1,37 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "modelVersion": "5.0.2", + "dependencies": { + }, + "execution": { + // "analyze": "normal", /* Define the build analyze mode. Value: [ "normal" | "advanced" | false ]. Default: "normal" */ + // "daemon": true, /* Enable daemon compilation. Value: [ true | false ]. Default: true */ + // "incremental": true, /* Enable incremental compilation. Value: [ true | false ]. Default: true */ + // "parallel": true, /* Enable parallel compilation. Value: [ true | false ]. Default: true */ + // "typeCheck": false, /* Enable typeCheck. Value: [ true | false ]. Default: false */ + }, + "logging": { + // "level": "info" /* Define the log level. Value: [ "debug" | "info" | "warn" | "error" ]. Default: "info" */ + }, + "debugging": { + // "stacktrace": false /* Disable stacktrace compilation. Value: [ true | false ]. Default: false */ + }, + "nodeOptions": { + // "maxOldSpaceSize": 8192 /* Enable nodeOptions maxOldSpaceSize compilation. Unit M. Used for the daemon process. Default: 8192*/ + // "exposeGC": true /* Enable to trigger garbage collection explicitly. Default: true*/ + } +} diff --git a/test/sdk_test_projects/bytecodehar_test/hvigorfile.ts b/test/sdk_test_projects/bytecodehar_test/hvigorfile.ts new file mode 100644 index 0000000000..d2d14bd72b --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/hvigorfile.ts @@ -0,0 +1,21 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { appTasks } from '@ohos/hvigor-ohos-plugin'; + +export default { + system: appTasks, /* Built-in plugin of Hvigor. It cannot be modified. */ + plugins:[] /* Custom plugin to extend the functionality of Hvigor. */ +} diff --git a/test/sdk_test_projects/bytecodehar_test/oh-package.json5 b/test/sdk_test_projects/bytecodehar_test/oh-package.json5 new file mode 100644 index 0000000000..1ec7d87507 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/oh-package.json5 @@ -0,0 +1,25 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "modelVersion": "5.0.2", + "description": "Please describe the basic information.", + "dependencies": { + }, + "devDependencies": { + "@ohos/hypium": "1.0.21", + "@ohos/hamock": "1.0.0" + } +} diff --git a/test/sdk_test_projects/bytecodehar_test/source_har/.gitignore b/test/sdk_test_projects/bytecodehar_test/source_har/.gitignore new file mode 100644 index 0000000000..e2713a2779 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/source_har/.gitignore @@ -0,0 +1,6 @@ +/node_modules +/oh_modules +/.preview +/build +/.cxx +/.test \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/source_har/BuildProfile.ets b/test/sdk_test_projects/bytecodehar_test/source_har/BuildProfile.ets new file mode 100644 index 0000000000..2235f87d8f --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/source_har/BuildProfile.ets @@ -0,0 +1,32 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Use these variables when you tailor your ArkTS code. They must be of the const type. + */ +export const HAR_VERSION = '1.0.0'; +export const BUILD_MODE_NAME = 'debug'; +export const DEBUG = true; +export const TARGET_NAME = 'default'; + +/** + * BuildProfile Class is used only for compatibility purposes. + */ +export default class BuildProfile { + static readonly HAR_VERSION = HAR_VERSION; + static readonly BUILD_MODE_NAME = BUILD_MODE_NAME; + static readonly DEBUG = DEBUG; + static readonly TARGET_NAME = TARGET_NAME; +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/source_har/Index.ets b/test/sdk_test_projects/bytecodehar_test/source_har/Index.ets new file mode 100644 index 0000000000..92c1b0dfa9 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/source_har/Index.ets @@ -0,0 +1,25 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {promptAction} from '@kit.ArkUI'; +export { MainPage } from './src/main/ets/components/MainPage'; + +export function sourceHarTest() { + console.log("source har success"); + promptAction.showToast({ + message: "sourcehar test success", + duration: 2000 + }); +} diff --git a/test/sdk_test_projects/bytecodehar_test/source_har/build-profile.json5 b/test/sdk_test_projects/bytecodehar_test/source_har/build-profile.json5 new file mode 100644 index 0000000000..1e7b34cf78 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/source_har/build-profile.json5 @@ -0,0 +1,47 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "apiType": "stageMode", + "buildOption": { + "arkOptions": {"byteCodeHar": false} + }, + "buildOptionSet": [ + { + "name": "release", + "arkOptions": { + "obfuscation": { + "ruleOptions": { + "enable": false, + "files": [ + "./obfuscation-rules.txt" + ] + }, + "consumerFiles": [ + "./consumer-rules.txt" + ] + } + }, + }, + ], + "targets": [ + { + "name": "default" + }, + { + "name": "ohosTest" + } + ] +} diff --git a/test/sdk_test_projects/bytecodehar_test/source_har/consumer-rules.txt b/test/sdk_test_projects/bytecodehar_test/source_har/consumer-rules.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/test/sdk_test_projects/bytecodehar_test/source_har/hvigorfile.ts b/test/sdk_test_projects/bytecodehar_test/source_har/hvigorfile.ts new file mode 100644 index 0000000000..194f648a98 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/source_har/hvigorfile.ts @@ -0,0 +1,21 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { harTasks } from '@ohos/hvigor-ohos-plugin'; + +export default { + system: harTasks, /* Built-in plugin of Hvigor. It cannot be modified. */ + plugins:[] /* Custom plugin to extend the functionality of Hvigor. */ +} diff --git a/test/sdk_test_projects/bytecodehar_test/source_har/obfuscation-rules.txt b/test/sdk_test_projects/bytecodehar_test/source_har/obfuscation-rules.txt new file mode 100644 index 0000000000..272efb6ca3 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/source_har/obfuscation-rules.txt @@ -0,0 +1,23 @@ +# Define project specific obfuscation rules here. +# You can include the obfuscation configuration files in the current module's build-profile.json5. +# +# For more details, see +# https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/source-obfuscation-V5 + +# Obfuscation options: +# -disable-obfuscation: disable all obfuscations +# -enable-property-obfuscation: obfuscate the property names +# -enable-toplevel-obfuscation: obfuscate the names in the global scope +# -compact: remove unnecessary blank spaces and all line feeds +# -remove-log: remove all console.* statements +# -print-namecache: print the name cache that contains the mapping from the old names to new names +# -apply-namecache: reuse the given cache file + +# Keep options: +# -keep-property-name: specifies property names that you want to keep +# -keep-global-name: specifies names that you want to keep in the global scope + +-enable-property-obfuscation +-enable-toplevel-obfuscation +-enable-filename-obfuscation +-enable-export-obfuscation \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/source_har/oh-package.json5 b/test/sdk_test_projects/bytecodehar_test/source_har/oh-package.json5 new file mode 100644 index 0000000000..c5e4bdeba6 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/source_har/oh-package.json5 @@ -0,0 +1,24 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "name": "source_har", + "version": "1.0.0", + "description": "Please describe the basic information.", + "main": "Index.ets", + "author": "", + "license": "Apache-2.0", + "dependencies": {} +} diff --git a/test/sdk_test_projects/bytecodehar_test/source_har/src/main/ets/components/MainPage.ets b/test/sdk_test_projects/bytecodehar_test/source_har/src/main/ets/components/MainPage.ets new file mode 100644 index 0000000000..3a90f0b7c2 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/source_har/src/main/ets/components/MainPage.ets @@ -0,0 +1,34 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@Component +export struct MainPage { + @State message: string = 'Hello World'; + + build() { + Row() { + Column() { + Text(this.message) + .fontSize($r('app.float.page_text_font_size')) + .fontWeight(FontWeight.Bold) + .onClick(() => { + this.message = 'Welcome'; + }) + } + .width('100%') + } + .height('100%') + } +} diff --git a/test/sdk_test_projects/bytecodehar_test/source_har/src/main/module.json5 b/test/sdk_test_projects/bytecodehar_test/source_har/src/main/module.json5 new file mode 100644 index 0000000000..9d233c98b8 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/source_har/src/main/module.json5 @@ -0,0 +1,26 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "module": { + "name": "source_har", + "type": "har", + "deviceTypes": [ + "default", + "tablet", + "2in1" + ] + } +} diff --git a/test/sdk_test_projects/bytecodehar_test/source_har/src/main/resources/base/element/float.json b/test/sdk_test_projects/bytecodehar_test/source_har/src/main/resources/base/element/float.json new file mode 100644 index 0000000000..33ea22304f --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/source_har/src/main/resources/base/element/float.json @@ -0,0 +1,8 @@ +{ + "float": [ + { + "name": "page_text_font_size", + "value": "50fp" + } + ] +} diff --git a/test/sdk_test_projects/bytecodehar_test/source_har/src/main/resources/base/element/string.json b/test/sdk_test_projects/bytecodehar_test/source_har/src/main/resources/base/element/string.json new file mode 100644 index 0000000000..f51a9c8461 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/source_har/src/main/resources/base/element/string.json @@ -0,0 +1,8 @@ +{ + "string": [ + { + "name": "page_show", + "value": "page from package" + } + ] +} diff --git a/test/sdk_test_projects/bytecodehar_test/source_har/src/ohosTest/ets/test/Ability.test.ets b/test/sdk_test_projects/bytecodehar_test/source_har/src/ohosTest/ets/test/Ability.test.ets new file mode 100644 index 0000000000..bc35f7c995 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/source_har/src/ohosTest/ets/test/Ability.test.ets @@ -0,0 +1,50 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { hilog } from '@kit.PerformanceAnalysisKit'; +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium'; + +export default function abilityTest() { + describe('ActsAbilityTest', () => { + // Defines a test suite. Two parameters are supported: test suite name and test suite function. + beforeAll(() => { + // Presets an action, which is performed only once before all test cases of the test suite start. + // This API supports only one parameter: preset action function. + }) + beforeEach(() => { + // Presets an action, which is performed before each unit test case starts. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: preset action function. + }) + afterEach(() => { + // Presets a clear action, which is performed after each unit test case ends. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: clear action function. + }) + afterAll(() => { + // Presets a clear action, which is performed after all test cases of the test suite end. + // This API supports only one parameter: clear action function. + }) + it('assertContain', 0, () => { + // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function. + hilog.info(0x0000, 'testTag', '%{public}s', 'it begin'); + let a = 'abc'; + let b = 'b'; + // Defines a variety of assertion methods, which are used to declare expected boolean conditions. + expect(a).assertContain(b); + expect(a).assertEqual(a); + }) + }) +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/source_har/src/ohosTest/ets/test/List.test.ets b/test/sdk_test_projects/bytecodehar_test/source_har/src/ohosTest/ets/test/List.test.ets new file mode 100644 index 0000000000..683e5df1cd --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/source_har/src/ohosTest/ets/test/List.test.ets @@ -0,0 +1,20 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import abilityTest from './Ability.test'; + +export default function testsuite() { + abilityTest(); +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/source_har/src/ohosTest/module.json5 b/test/sdk_test_projects/bytecodehar_test/source_har/src/ohosTest/module.json5 new file mode 100644 index 0000000000..1484454919 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/source_har/src/ohosTest/module.json5 @@ -0,0 +1,28 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "module": { + "name": "source_har_test", + "type": "feature", + "deviceTypes": [ + "default", + "tablet", + "2in1" + ], + "deliveryWithInstall": true, + "installationFree": false + } +} diff --git a/test/sdk_test_projects/bytecodehar_test/source_har/src/test/List.test.ets b/test/sdk_test_projects/bytecodehar_test/source_har/src/test/List.test.ets new file mode 100644 index 0000000000..4d92bb1fb8 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/source_har/src/test/List.test.ets @@ -0,0 +1,20 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import localUnitTest from './LocalUnit.test'; + +export default function testsuite() { + localUnitTest(); +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/source_har/src/test/LocalUnit.test.ets b/test/sdk_test_projects/bytecodehar_test/source_har/src/test/LocalUnit.test.ets new file mode 100644 index 0000000000..555ba8084b --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/source_har/src/test/LocalUnit.test.ets @@ -0,0 +1,48 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium'; + +export default function localUnitTest() { + describe('localUnitTest', () => { + // Defines a test suite. Two parameters are supported: test suite name and test suite function. + beforeAll(() => { + // Presets an action, which is performed only once before all test cases of the test suite start. + // This API supports only one parameter: preset action function. + }); + beforeEach(() => { + // Presets an action, which is performed before each unit test case starts. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: preset action function. + }); + afterEach(() => { + // Presets a clear action, which is performed after each unit test case ends. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: clear action function. + }); + afterAll(() => { + // Presets a clear action, which is performed after all test cases of the test suite end. + // This API supports only one parameter: clear action function. + }); + it('assertContain', 0, () => { + // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function. + let a = 'abc'; + let b = 'b'; + // Defines a variety of assertion methods, which are used to declare expected boolean conditions. + expect(a).assertContain(b); + expect(a).assertEqual(a); + }); + }); +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/source_har1/.gitignore b/test/sdk_test_projects/bytecodehar_test/source_har1/.gitignore new file mode 100644 index 0000000000..e2713a2779 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/source_har1/.gitignore @@ -0,0 +1,6 @@ +/node_modules +/oh_modules +/.preview +/build +/.cxx +/.test \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/source_har1/Index.ets b/test/sdk_test_projects/bytecodehar_test/source_har1/Index.ets new file mode 100644 index 0000000000..2b88e07854 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/source_har1/Index.ets @@ -0,0 +1,41 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {bchar1Test} from "bytecode_har" +import {bytecodeHar1Test} from "bytecode_har1" +import { promptAction } from "@kit.ArkUI"; + +export { MainPage } from './src/main/ets/components/MainPage' +export function sourceHarDispatchbcHarTest() { + bchar1Test(); + import ("bytecode_har").then((obj :ESObject)=>{ + console.log("sourcehar1 dynamic import bytecodehar") + promptAction.showToast({ + message: "sourcehar1 dynamic import bytecodehar", + duration: 2000 + }); + obj.bchar1Test(); + }) + + bytecodeHar1Test(); + import ("bytecode_har1").then((obj :ESObject)=>{ + console.log("dynamic import bytecodehar1") + promptAction.showToast({ + message: "dynamic import bytecodehar1", + duration: 2000 + }); + obj.bytecodeHar1Test(); + }) +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/source_har1/build-profile.json5 b/test/sdk_test_projects/bytecodehar_test/source_har1/build-profile.json5 new file mode 100644 index 0000000000..6b7940f3b3 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/source_har1/build-profile.json5 @@ -0,0 +1,46 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "apiType": "stageMode", + "buildOption": { + }, + "buildOptionSet": [ + { + "name": "release", + "arkOptions": { + "obfuscation": { + "ruleOptions": { + "enable": false, + "files": [ + "./obfuscation-rules.txt" + ] + }, + "consumerFiles": [ + "./consumer-rules.txt" + ] + } + }, + }, + ], + "targets": [ + { + "name": "default" + }, + { + "name": "ohosTest" + } + ] +} diff --git a/test/sdk_test_projects/bytecodehar_test/source_har1/consumer-rules.txt b/test/sdk_test_projects/bytecodehar_test/source_har1/consumer-rules.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/test/sdk_test_projects/bytecodehar_test/source_har1/hvigorfile.ts b/test/sdk_test_projects/bytecodehar_test/source_har1/hvigorfile.ts new file mode 100644 index 0000000000..194f648a98 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/source_har1/hvigorfile.ts @@ -0,0 +1,21 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { harTasks } from '@ohos/hvigor-ohos-plugin'; + +export default { + system: harTasks, /* Built-in plugin of Hvigor. It cannot be modified. */ + plugins:[] /* Custom plugin to extend the functionality of Hvigor. */ +} diff --git a/test/sdk_test_projects/bytecodehar_test/source_har1/obfuscation-rules.txt b/test/sdk_test_projects/bytecodehar_test/source_har1/obfuscation-rules.txt new file mode 100644 index 0000000000..272efb6ca3 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/source_har1/obfuscation-rules.txt @@ -0,0 +1,23 @@ +# Define project specific obfuscation rules here. +# You can include the obfuscation configuration files in the current module's build-profile.json5. +# +# For more details, see +# https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/source-obfuscation-V5 + +# Obfuscation options: +# -disable-obfuscation: disable all obfuscations +# -enable-property-obfuscation: obfuscate the property names +# -enable-toplevel-obfuscation: obfuscate the names in the global scope +# -compact: remove unnecessary blank spaces and all line feeds +# -remove-log: remove all console.* statements +# -print-namecache: print the name cache that contains the mapping from the old names to new names +# -apply-namecache: reuse the given cache file + +# Keep options: +# -keep-property-name: specifies property names that you want to keep +# -keep-global-name: specifies names that you want to keep in the global scope + +-enable-property-obfuscation +-enable-toplevel-obfuscation +-enable-filename-obfuscation +-enable-export-obfuscation \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/source_har1/oh-package.json5 b/test/sdk_test_projects/bytecodehar_test/source_har1/oh-package.json5 new file mode 100644 index 0000000000..d22ad47bdd --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/source_har1/oh-package.json5 @@ -0,0 +1,27 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "name": "source_har1", + "version": "1.0.0", + "description": "Please describe the basic information.", + "main": "Index.ets", + "author": "", + "license": "Apache-2.0", + "dependencies": { + "bytecode_har": "file:../entry/bytecode_har.har", + "bytecode_har1": "file:../entry/bytecode_har1.har" + } +} diff --git a/test/sdk_test_projects/bytecodehar_test/source_har1/src/main/ets/components/MainPage.ets b/test/sdk_test_projects/bytecodehar_test/source_har1/src/main/ets/components/MainPage.ets new file mode 100644 index 0000000000..3a90f0b7c2 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/source_har1/src/main/ets/components/MainPage.ets @@ -0,0 +1,34 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@Component +export struct MainPage { + @State message: string = 'Hello World'; + + build() { + Row() { + Column() { + Text(this.message) + .fontSize($r('app.float.page_text_font_size')) + .fontWeight(FontWeight.Bold) + .onClick(() => { + this.message = 'Welcome'; + }) + } + .width('100%') + } + .height('100%') + } +} diff --git a/test/sdk_test_projects/bytecodehar_test/source_har1/src/main/module.json5 b/test/sdk_test_projects/bytecodehar_test/source_har1/src/main/module.json5 new file mode 100644 index 0000000000..65639bcf59 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/source_har1/src/main/module.json5 @@ -0,0 +1,26 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "module": { + "name": "source_har1", + "type": "har", + "deviceTypes": [ + "default", + "tablet", + "2in1" + ] + } +} diff --git a/test/sdk_test_projects/bytecodehar_test/source_har1/src/main/resources/base/element/float.json b/test/sdk_test_projects/bytecodehar_test/source_har1/src/main/resources/base/element/float.json new file mode 100644 index 0000000000..33ea22304f --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/source_har1/src/main/resources/base/element/float.json @@ -0,0 +1,8 @@ +{ + "float": [ + { + "name": "page_text_font_size", + "value": "50fp" + } + ] +} diff --git a/test/sdk_test_projects/bytecodehar_test/source_har1/src/main/resources/base/element/string.json b/test/sdk_test_projects/bytecodehar_test/source_har1/src/main/resources/base/element/string.json new file mode 100644 index 0000000000..f51a9c8461 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/source_har1/src/main/resources/base/element/string.json @@ -0,0 +1,8 @@ +{ + "string": [ + { + "name": "page_show", + "value": "page from package" + } + ] +} diff --git a/test/sdk_test_projects/bytecodehar_test/source_har1/src/ohosTest/ets/test/Ability.test.ets b/test/sdk_test_projects/bytecodehar_test/source_har1/src/ohosTest/ets/test/Ability.test.ets new file mode 100644 index 0000000000..bc35f7c995 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/source_har1/src/ohosTest/ets/test/Ability.test.ets @@ -0,0 +1,50 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { hilog } from '@kit.PerformanceAnalysisKit'; +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium'; + +export default function abilityTest() { + describe('ActsAbilityTest', () => { + // Defines a test suite. Two parameters are supported: test suite name and test suite function. + beforeAll(() => { + // Presets an action, which is performed only once before all test cases of the test suite start. + // This API supports only one parameter: preset action function. + }) + beforeEach(() => { + // Presets an action, which is performed before each unit test case starts. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: preset action function. + }) + afterEach(() => { + // Presets a clear action, which is performed after each unit test case ends. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: clear action function. + }) + afterAll(() => { + // Presets a clear action, which is performed after all test cases of the test suite end. + // This API supports only one parameter: clear action function. + }) + it('assertContain', 0, () => { + // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function. + hilog.info(0x0000, 'testTag', '%{public}s', 'it begin'); + let a = 'abc'; + let b = 'b'; + // Defines a variety of assertion methods, which are used to declare expected boolean conditions. + expect(a).assertContain(b); + expect(a).assertEqual(a); + }) + }) +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/source_har1/src/ohosTest/ets/test/List.test.ets b/test/sdk_test_projects/bytecodehar_test/source_har1/src/ohosTest/ets/test/List.test.ets new file mode 100644 index 0000000000..683e5df1cd --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/source_har1/src/ohosTest/ets/test/List.test.ets @@ -0,0 +1,20 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import abilityTest from './Ability.test'; + +export default function testsuite() { + abilityTest(); +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/source_har1/src/ohosTest/module.json5 b/test/sdk_test_projects/bytecodehar_test/source_har1/src/ohosTest/module.json5 new file mode 100644 index 0000000000..f5e54081cd --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/source_har1/src/ohosTest/module.json5 @@ -0,0 +1,28 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "module": { + "name": "source_har1_test", + "type": "feature", + "deviceTypes": [ + "default", + "tablet", + "2in1" + ], + "deliveryWithInstall": true, + "installationFree": false + } +} diff --git a/test/sdk_test_projects/bytecodehar_test/source_har1/src/test/List.test.ets b/test/sdk_test_projects/bytecodehar_test/source_har1/src/test/List.test.ets new file mode 100644 index 0000000000..4d92bb1fb8 --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/source_har1/src/test/List.test.ets @@ -0,0 +1,20 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import localUnitTest from './LocalUnit.test'; + +export default function testsuite() { + localUnitTest(); +} \ No newline at end of file diff --git a/test/sdk_test_projects/bytecodehar_test/source_har1/src/test/LocalUnit.test.ets b/test/sdk_test_projects/bytecodehar_test/source_har1/src/test/LocalUnit.test.ets new file mode 100644 index 0000000000..555ba8084b --- /dev/null +++ b/test/sdk_test_projects/bytecodehar_test/source_har1/src/test/LocalUnit.test.ets @@ -0,0 +1,48 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium'; + +export default function localUnitTest() { + describe('localUnitTest', () => { + // Defines a test suite. Two parameters are supported: test suite name and test suite function. + beforeAll(() => { + // Presets an action, which is performed only once before all test cases of the test suite start. + // This API supports only one parameter: preset action function. + }); + beforeEach(() => { + // Presets an action, which is performed before each unit test case starts. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: preset action function. + }); + afterEach(() => { + // Presets a clear action, which is performed after each unit test case ends. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: clear action function. + }); + afterAll(() => { + // Presets a clear action, which is performed after all test cases of the test suite end. + // This API supports only one parameter: clear action function. + }); + it('assertContain', 0, () => { + // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function. + let a = 'abc'; + let b = 'b'; + // Defines a variety of assertion methods, which are used to declare expected boolean conditions. + expect(a).assertContain(b); + expect(a).assertEqual(a); + }); + }); +} \ No newline at end of file -- Gitee From 591104251bcf18f97d8775ced0c04cfaa8dc899e Mon Sep 17 00:00:00 2001 From: Lyupa Anastasia Date: Wed, 23 Apr 2025 16:36:00 +0300 Subject: [PATCH 138/268] Fix codecheck 20250423 Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC3HEQ Change-Id: Ib6105bfa32132fa38646871d31f2aab5279a9370 Signed-off-by: Lyupa Anastasia --- ets2panda/checker/ets/assignAnalyzer.h | 2 +- ets2panda/public/headers_parser/supported_types.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ets2panda/checker/ets/assignAnalyzer.h b/ets2panda/checker/ets/assignAnalyzer.h index 3e7f664d51..73148898bf 100644 --- a/ets2panda/checker/ets/assignAnalyzer.h +++ b/ets2panda/checker/ets/assignAnalyzer.h @@ -144,7 +144,7 @@ private: void NewVar(const ir::AstNode *node); void LetInit(const ir::AstNode *node); void CheckInit(const ir::AstNode *node); - void Split(bool setToNull); + void Split(const bool setToNull); void Merge(); void CheckPendingExits(); NodeId GetNodeId(const ir::AstNode *node) const; diff --git a/ets2panda/public/headers_parser/supported_types.py b/ets2panda/public/headers_parser/supported_types.py index 50b417c028..6e6f805b62 100644 --- a/ets2panda/public/headers_parser/supported_types.py +++ b/ets2panda/public/headers_parser/supported_types.py @@ -303,7 +303,7 @@ def need_to_gen(function: dict) -> bool: for ban in no_gen_keywords["postfix"]: # CC-OFF(G.TYP.07) dict key exist if function["postfix"].find(ban) != -1: return False - for name_start in no_gen_keywords["name_starts_with"]: # CC-OFF(G.TYP.07) dict key exist + for name_start in no_gen_keywords["name_starts_with"]: # CC-OFF(G.TYP.07) dict key exist if function["name"].startswith(name_start): return False if "return_type" in function: -- Gitee From 5473f8cfc1240d82936f9d512f2cd8bf88a02599 Mon Sep 17 00:00:00 2001 From: Dmitry Pimenov Date: Fri, 18 Apr 2025 18:15:09 +0300 Subject: [PATCH 139/268] The 'this' return type can override a supertype Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC2C9I Change-Id: Ia99418305fa83093ddaf85e0ca5f2bfa3266b255 Signed-off-by: Dmitry Pimenov --- ets2panda/checker/ets/function.cpp | 2 +- .../this_type_invalid_return_type.ets | 0 .../this_type_overridden_by_child_class.ets | 27 +++++++++++++ .../ets/return_this_type_over_child_class.ets | 39 +++++++++++++++++++ 4 files changed, 67 insertions(+), 1 deletion(-) rename ets2panda/test/ast/compiler/ets/{ => return_this}/this_type_invalid_return_type.ets (100%) create mode 100644 ets2panda/test/ast/compiler/ets/return_this/this_type_overridden_by_child_class.ets create mode 100644 ets2panda/test/runtime/ets/return_this_type_over_child_class.ets diff --git a/ets2panda/checker/ets/function.cpp b/ets2panda/checker/ets/function.cpp index 51526229ee..71b78ade7f 100644 --- a/ets2panda/checker/ets/function.cpp +++ b/ets2panda/checker/ets/function.cpp @@ -1760,7 +1760,7 @@ bool ETSChecker::IsReturnTypeSubstitutable(Signature *const s1, Signature *const // If the overridden method (s2) has a 'this' return type, then the overriding method (s1) must also have it. bool s1HasThisType = hasThisReturnType(s1); bool s2HasThisType = hasThisReturnType(s2); - if (s1HasThisType != s2HasThisType) { + if (!s1HasThisType && s2HasThisType) { return false; } diff --git a/ets2panda/test/ast/compiler/ets/this_type_invalid_return_type.ets b/ets2panda/test/ast/compiler/ets/return_this/this_type_invalid_return_type.ets similarity index 100% rename from ets2panda/test/ast/compiler/ets/this_type_invalid_return_type.ets rename to ets2panda/test/ast/compiler/ets/return_this/this_type_invalid_return_type.ets diff --git a/ets2panda/test/ast/compiler/ets/return_this/this_type_overridden_by_child_class.ets b/ets2panda/test/ast/compiler/ets/return_this/this_type_overridden_by_child_class.ets new file mode 100644 index 0000000000..ad094e2acc --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/return_this/this_type_overridden_by_child_class.ets @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +interface I { + foo(): this; +} + +abstract class A implements I { + foo/* @@ label */(): A { + return this; + } +} + +/* @@@ label Error TypeError: foo(): A in A cannot override foo(): I in I because overriding return type is not compatible with the other return type. */ +/* @@@ label Error TypeError: Method foo(): A in A not overriding any method */ diff --git a/ets2panda/test/runtime/ets/return_this_type_over_child_class.ets b/ets2panda/test/runtime/ets/return_this_type_over_child_class.ets new file mode 100644 index 0000000000..ad541951b8 --- /dev/null +++ b/ets2panda/test/runtime/ets/return_this_type_over_child_class.ets @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +interface IButton { + getTitle(): string; + setTitle(t: string): IButton; +} + +class Button implements IButton { + title: string = ""; + + getTitle(): string { + return this.title; + } + + setTitle(t: string): this { + this.title = t; + return this; + } +} + +function main() { + let b = new Button().setTitle("🍆"); + + assertTrue(b instanceof Button) + assertEQ(b.getTitle(), "🍆") +} -- Gitee From ad619a01fdf351ca416a974856dc6fce858a0a4e Mon Sep 17 00:00:00 2001 From: Maxim Bolshov Date: Thu, 24 Apr 2025 23:53:05 +0300 Subject: [PATCH 140/268] Remove erroneous const from IDL Issue: #IC3SI0 Testing: ninja es2panda-plugin-test Change-Id: I5b034ab501562762ced3c564fdd133a96adb74e0 Signed-off-by: Maxim Bolshov --- ets2panda/public/es2panda_lib.idl.erb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ets2panda/public/es2panda_lib.idl.erb b/ets2panda/public/es2panda_lib.idl.erb index ddf23446c3..d036b8ec2e 100644 --- a/ets2panda/public/es2panda_lib.idl.erb +++ b/ets2panda/public/es2panda_lib.idl.erb @@ -150,7 +150,7 @@ typedef u64 Es2panda<%= name %>; interface es2panda_Impl { es2panda_Config CreateConfig(i32 argc, sequence argv); void DestroyConfig(es2panda_Config config); - const es2panda_Options ConfigGetOptions(es2panda_Config config); + es2panda_Options ConfigGetOptions(es2panda_Config config); es2panda_Context CreateContextFromFile(es2panda_Config config, String source_file_name); es2panda_Context CreateContextFromString(es2panda_Config config, String source, String file_name); -- Gitee From 68e9eb5956a1185cbac58254278d8832fb069b14 Mon Sep 17 00:00:00 2001 From: Gabor Aron Takacs Date: Wed, 9 Apr 2025 11:23:13 +0200 Subject: [PATCH 141/268] Support tuple as rest parameter in generic func Fixes #24979 internal issue. Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC0F9I Change-Id: If8462f455db15417bf6f499fb9f0f98094939745 Signed-off-by: Gabor Aron Takacs --- .../lowering/ets/restTupleLowering.cpp | 112 ++++++++++++++---- .../test/ast/parser/ets/rest_parameter_09.ets | 25 ++++ .../test/ast/parser/ets/rest_parameter_10.ets | 25 ++++ .../test/ast/parser/ets/rest_parameter_11.ets | 25 ++++ .../test/ast/parser/ets/rest_parameter_12.ets | 29 +++++ .../test/ast/parser/ets/rest_parameter_13.ets | 39 ++++++ ets2panda/test/runtime/ets/RestTuple5.ets | 41 +++++++ ets2panda/test/runtime/ets/RestTuple6.ets | 43 +++++++ ets2panda/test/runtime/ets/RestTuple7.ets | 43 +++++++ ets2panda/test/runtime/ets/RestTuple8.ets | 45 +++++++ 10 files changed, 404 insertions(+), 23 deletions(-) create mode 100644 ets2panda/test/ast/parser/ets/rest_parameter_09.ets create mode 100644 ets2panda/test/ast/parser/ets/rest_parameter_10.ets create mode 100644 ets2panda/test/ast/parser/ets/rest_parameter_11.ets create mode 100644 ets2panda/test/ast/parser/ets/rest_parameter_12.ets create mode 100644 ets2panda/test/ast/parser/ets/rest_parameter_13.ets create mode 100644 ets2panda/test/runtime/ets/RestTuple5.ets create mode 100644 ets2panda/test/runtime/ets/RestTuple6.ets create mode 100644 ets2panda/test/runtime/ets/RestTuple7.ets create mode 100644 ets2panda/test/runtime/ets/RestTuple8.ets diff --git a/ets2panda/compiler/lowering/ets/restTupleLowering.cpp b/ets2panda/compiler/lowering/ets/restTupleLowering.cpp index 3f323e94b6..ea2e2ac25d 100644 --- a/ets2panda/compiler/lowering/ets/restTupleLowering.cpp +++ b/ets2panda/compiler/lowering/ets/restTupleLowering.cpp @@ -81,11 +81,37 @@ ir::Expression *CreateMemberOrThisExpression(public_lib::Context *ctx, ir::Expre auto *newPropertyId = scriptFunc->Id()->Clone(allocator, nullptr); auto *memberExpr = checker->AllocNode( ident, newPropertyId, ir::MemberExpressionKind::PROPERTY_ACCESS, false, false); - newPropertyId->SetParent(memberExpr); return memberExpr; } +ir::TSTypeParameterInstantiation *CreateTypeParameterInstantiation(public_lib::Context *ctx, + ir::TSTypeParameterDeclaration *paramDeclaration) +{ + auto const allocator = ctx->allocator; + + if (paramDeclaration == nullptr || paramDeclaration->Params().empty()) { + return nullptr; + } + ArenaVector selfParams(allocator->Adapter()); + ir::ETSTypeReferencePart *referencePart = nullptr; + + for (const auto ¶m : paramDeclaration->Params()) { + auto *identRef = util::NodeAllocator::ForceSetParent( + allocator, param->AsTSTypeParameter()->Name()->Name(), allocator); + + referencePart = util::NodeAllocator::ForceSetParent(allocator, identRef, nullptr, + nullptr, allocator); + + auto *typeReference = + util::NodeAllocator::ForceSetParent(allocator, referencePart, allocator); + + selfParams.push_back(typeReference); + } + + return util::NodeAllocator::ForceSetParent(allocator, std::move(selfParams)); +} + ir::CallExpression *CreateNewCallExpression(public_lib::Context *ctx, ir::Expression *funcExpr, ir::AstNode *definition, ir::TSAsExpression *asExpression) { @@ -101,7 +127,6 @@ ir::CallExpression *CreateNewCallExpression(public_lib::Context *ctx, ir::Expres } else { auto spreadElement = checker->AllocNode(ir::AstNodeType::SPREAD_ELEMENT, allocator, asExpression); - asExpression->SetParent(spreadElement); callArguments.push_back(spreadElement); } } @@ -109,11 +134,19 @@ ir::CallExpression *CreateNewCallExpression(public_lib::Context *ctx, ir::Expres // Create member expression if method is not a constructor ir::Expression *memberExpr = CreateMemberOrThisExpression(ctx, funcExpr, definition); - auto *newCallExpr = checker->AllocNode(memberExpr, std::move(callArguments), nullptr, false); - - if (definition->IsConstructor()) { - memberExpr->SetParent(newCallExpr); + ir::TSTypeParameterInstantiation *typeParamInst = nullptr; + if (funcExpr->AsFunctionExpression()->Function()->AsScriptFunction()->TypeParams() != nullptr) { + auto typeParams = funcExpr->AsFunctionExpression() + ->Function() + ->AsScriptFunction() + ->TypeParams() + ->AsTSTypeParameterDeclaration(); + typeParamInst = CreateTypeParameterInstantiation(ctx, typeParams); } + + auto *newCallExpr = + checker->AllocNode(memberExpr, std::move(callArguments), typeParamInst, false); + for (auto *arg : newCallExpr->Arguments()) { arg->SetParent(newCallExpr); } @@ -134,7 +167,6 @@ ArenaVector CreateFunctionRestParams(public_lib::Context *ctx, ir::Identifier *id = Gensym(allocator); auto *newParam = checker->AsETSChecker()->AllocNode(id, false, allocator); auto newAnnotation = tupleTypeAnno->Clone(allocator, id); - id->SetParent(newParam); id->SetTsTypeAnnotation(newAnnotation); params.push_back(newParam); } @@ -192,6 +224,32 @@ ir::ArrayExpression *CreateArrayExpression(public_lib::Context *ctx, const Arena return arrayExpr; } +ir::TSTypeParameterDeclaration *CreateNewParameterDeclaration(public_lib::Context *ctx, + ir::TSTypeParameterDeclaration *paramDeclaration) +{ + auto const allocator = ctx->allocator; + if (paramDeclaration == nullptr || paramDeclaration->Params().empty()) { + return nullptr; + } + + ArenaVector typeParams(allocator->Adapter()); + + auto parentParams = paramDeclaration->Params(); + std::for_each(parentParams.begin(), parentParams.end(), [&typeParams, allocator](ir::TSTypeParameter *par) { + ir::Identifier *ident = par->Name()->Clone(allocator, nullptr)->AsIdentifier(); + auto *constraint = + par->Constraint() != nullptr ? par->Constraint()->Clone(allocator, nullptr)->AsTypeNode() : nullptr; + auto *defaultType = + par->DefaultType() != nullptr ? par->DefaultType()->Clone(allocator, nullptr)->AsTypeNode() : nullptr; + auto *typeParam = util::NodeAllocator::ForceSetParent(allocator, ident, constraint, + defaultType, allocator); + typeParams.push_back(typeParam); + }); + size_t paramsSize = typeParams.size(); + return util::NodeAllocator::ForceSetParent(allocator, std::move(typeParams), + paramsSize); +} + ir::ScriptFunction *CreateNewScriptFunction(public_lib::Context *ctx, ir::ScriptFunction *scriptFunc, ArenaVector newParams) { @@ -204,21 +262,20 @@ ir::ScriptFunction *CreateNewScriptFunction(public_lib::Context *ctx, ir::Script if (scriptFunc->ReturnTypeAnnotation() != nullptr) { newReturnTypeAnno = scriptFunc->ReturnTypeAnnotation()->Clone(allocator, nullptr); } + auto *newParamDeclaration = CreateNewParameterDeclaration(ctx, scriptFunc->TypeParams()); auto *newScriptFunc = checker->AllocNode( checker->Allocator(), ir::ScriptFunction::ScriptFunctionData { - body, ir::FunctionSignature(scriptFunc->TypeParams(), std::move(newParams), newReturnTypeAnno), + body, ir::FunctionSignature(newParamDeclaration, std::move(newParams), newReturnTypeAnno), scriptFunc->Flags()}); newScriptFunc->AddModifier(scriptFunc->AsScriptFunction()->Modifiers()); - if (newReturnTypeAnno != nullptr) { - newReturnTypeAnno->SetParent(newScriptFunc); - } - - for (auto param : newScriptFunc->AsScriptFunction()->Params()) { - param->SetParent(newScriptFunc); + ArenaVector annotationUsages {allocator->Adapter()}; + for (auto *annotationUsage : scriptFunc->Annotations()) { + annotationUsages.push_back(annotationUsage->Clone(allocator, newScriptFunc)->AsAnnotationUsage()); } + newScriptFunc->SetAnnotations(std::move(annotationUsages)); ir::Identifier *newScriptFuncId = scriptFunc->Id()->Clone(allocator, newScriptFunc); newScriptFunc->SetIdent(newScriptFuncId); @@ -240,13 +297,11 @@ ir::VariableDeclaration *CreateNewVariableDeclaration(public_lib::Context *ctx, auto *const declarator = checker->AllocNode(ir::VariableDeclaratorFlag::LET, newId, newTuple); - newId->SetParent(declarator); ArenaVector declarators(checker->Allocator()->Adapter()); declarators.push_back(declarator); auto *const declaration = checker->AllocNode( ir::VariableDeclaration::VariableDeclarationKind::LET, checker->Allocator(), std::move(declarators)); - declarator->SetParent(declaration); return declaration; } @@ -268,7 +323,22 @@ ArenaVector CreateReturnOrExpressionStatement(public_lib::Conte return statements; } -void CreateNewMethodDefinition(public_lib::Context *ctx, ir::AstNode *node) +ir::MethodDefinition *CreateNewMethodDefinition(public_lib::Context *ctx, ir::MethodDefinition *definition, + ir::FunctionExpression *function) +{ + auto *checker = ctx->checker->AsETSChecker(); + auto *allocator = ctx->allocator; + + auto *methodKey = definition->AsMethodDefinition()->Key()->AsIdentifier()->Clone(allocator, nullptr); + auto *const methodDef = + checker->AllocNode(definition->AsMethodDefinition()->Kind(), methodKey, function, + definition->AsMethodDefinition()->Modifiers(), allocator, false); + methodDef->SetParent(definition->Parent()); + + return methodDef; +} + +void CreateNewMethod(public_lib::Context *ctx, ir::AstNode *node) { auto *checker = ctx->checker->AsETSChecker(); auto *allocator = ctx->allocator; @@ -305,14 +375,10 @@ void CreateNewMethodDefinition(public_lib::Context *ctx, ir::AstNode *node) // Build new functionExpression auto *function = checker->AllocNode(newScriptFunc); - - newTypeAnnotation->SetParent(asExpression); - newArrayExpr->SetParent(asExpression); function->SetParent(funcExpr->Parent()); // Build new methodDefinition - auto *const methodDef = definition->AsMethodDefinition()->Clone(allocator, definition->Parent()); - methodDef->SetValue(function); + auto *const methodDef = CreateNewMethodDefinition(ctx, definition->AsMethodDefinition(), function); node->AsClassDefinition()->Body().push_back(methodDef); } @@ -324,7 +390,7 @@ bool RestTupleConstructionPhase::PerformForModule(public_lib::Context *ctx, pars program->Ast()->TransformChildrenRecursively( [ctx](ir::AstNode *const node) -> AstNodePtr { if (IsClassDefinitionWithTupleRest(node)) { - CreateNewMethodDefinition(ctx, node); + CreateNewMethod(ctx, node); } return node; }, diff --git a/ets2panda/test/ast/parser/ets/rest_parameter_09.ets b/ets2panda/test/ast/parser/ets/rest_parameter_09.ets new file mode 100644 index 0000000000..db49515272 --- /dev/null +++ b/ets2panda/test/ast/parser/ets/rest_parameter_09.ets @@ -0,0 +1,25 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable low or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +class A {} +class B {} + +class C { + foo(...p: [A, B]) {} +} + +/* @@ label */(new C()).foo() + +/* @@@ label Error TypeError: No matching call signature */ diff --git a/ets2panda/test/ast/parser/ets/rest_parameter_10.ets b/ets2panda/test/ast/parser/ets/rest_parameter_10.ets new file mode 100644 index 0000000000..29860c3449 --- /dev/null +++ b/ets2panda/test/ast/parser/ets/rest_parameter_10.ets @@ -0,0 +1,25 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable low or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +class A {} +class B {} + +class C { + foo(...p: [A, B]) {} +} + +/* @@ label */(new C()).foo(new A) + +/* @@@ label Error TypeError: No matching call signature for foo(A) */ diff --git a/ets2panda/test/ast/parser/ets/rest_parameter_11.ets b/ets2panda/test/ast/parser/ets/rest_parameter_11.ets new file mode 100644 index 0000000000..2d79df71a7 --- /dev/null +++ b/ets2panda/test/ast/parser/ets/rest_parameter_11.ets @@ -0,0 +1,25 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable low or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +class A {} +class B {} + +class C { + foo(...p: [A, B]) {} +} + +/* @@ label */(new C()).foo(new A, new B, new B) + +/* @@@ label Error TypeError: No matching call signature for foo(A, B, B) */ diff --git a/ets2panda/test/ast/parser/ets/rest_parameter_12.ets b/ets2panda/test/ast/parser/ets/rest_parameter_12.ets new file mode 100644 index 0000000000..7f8d2e5e4d --- /dev/null +++ b/ets2panda/test/ast/parser/ets/rest_parameter_12.ets @@ -0,0 +1,29 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable low or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +class A {} +class B {} + +class C { + static foo(...p: [A, B]) {} +} + +/* @@ label1 */C.foo() +/* @@ label2 */C.foo(new A) +/* @@ label3 */C.foo(new A, new B, new B) + +/* @@@ label1 Error TypeError: No matching call signature */ +/* @@@ label2 Error TypeError: No matching call signature for foo(A) */ +/* @@@ label3 Error TypeError: No matching call signature for foo(A, B, B) */ diff --git a/ets2panda/test/ast/parser/ets/rest_parameter_13.ets b/ets2panda/test/ast/parser/ets/rest_parameter_13.ets new file mode 100644 index 0000000000..70ae141ee7 --- /dev/null +++ b/ets2panda/test/ast/parser/ets/rest_parameter_13.ets @@ -0,0 +1,39 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable low or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +class A {} +class B {} + +class C { + public field : boolean + + constructor(...p: [A, B]) { + this.field = p[0] == p[1] + } + + constructor(a: int, ...p: [A, B]) { + this.field = p[0] == p[1] + } +} + +function main() { + /* @@ label1 */new C + /* @@ label2 */new C(new A) + /* @@ label3 */new C(new A, new B, new B) +} + +/* @@@ label1 Error TypeError: No matching construct signature */ +/* @@@ label2 Error TypeError: No matching construct signature for rest_parameter_13.C(A) */ +/* @@@ label3 Error TypeError: No matching construct signature for rest_parameter_13.C(A, B, B) */ diff --git a/ets2panda/test/runtime/ets/RestTuple5.ets b/ets2panda/test/runtime/ets/RestTuple5.ets new file mode 100644 index 0000000000..888b16c712 --- /dev/null +++ b/ets2panda/test/runtime/ets/RestTuple5.ets @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class A {} +class B {} + +function foo(...p: [A, B]): boolean { + return p[0] == p[1] +} + +function moo(a:int, ...p: [A, B]): boolean { + return p[0] == p[1] +} + +function main() { + let a1: [A, B] = [new A, new B] + + assertTrue(foo(...a1) == false) + assertTrue(moo(12, ...a1) == false) + + assertTrue(foo(...[new A, new B]) == false) + assertTrue(moo(12, ...[new A, new B]) == false) + + assertTrue(foo(...[new A, new B] as [A, B]) == false) + assertTrue(moo(12, ...[new A, new B] as [A, B]) == false) + + assertTrue(foo(new A, new B) == false) + assertTrue(moo(12, new A, new B) == false) +} diff --git a/ets2panda/test/runtime/ets/RestTuple6.ets b/ets2panda/test/runtime/ets/RestTuple6.ets new file mode 100644 index 0000000000..5fc918e8e6 --- /dev/null +++ b/ets2panda/test/runtime/ets/RestTuple6.ets @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class A {} +class B {} + +class C { + foo(...p: [A, B]): boolean { + return p[0] == p[1] + } + + moo(a:int, ...p: [A, B]): boolean { + return p[0] == p[1] + } +} + +function main() { + let a1: [A, B] = [new A, new B] + + assertTrue((new C()).foo(...a1) == false) + assertTrue((new C()).moo(12, ...a1) == false) + + assertTrue((new C()).foo(...[new A, new B]) == false) + assertTrue((new C()).moo(12, ...[new A, new B]) == false) + + assertTrue((new C()).foo(...[new A, new B] as [A, B]) == false) + assertTrue((new C()).moo(12, ...[new A, new B] as [A, B]) == false) + + assertTrue((new C()).foo(new A, new B) == false) + assertTrue((new C()).moo(12, new A, new B) == false) +} diff --git a/ets2panda/test/runtime/ets/RestTuple7.ets b/ets2panda/test/runtime/ets/RestTuple7.ets new file mode 100644 index 0000000000..4368052ce6 --- /dev/null +++ b/ets2panda/test/runtime/ets/RestTuple7.ets @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class A {} +class B {} + +class C { + static foo(...p: [A, B]): boolean { + return p[0] == p[1] + } + + static moo(a:int, ...p: [A, B]): boolean { + return p[0] == p[1] + } +} + +function main() { + let a1: [A, B] = [new A, new B] + + assertTrue(C.foo(...a1) == false) + assertTrue(C.moo(12, ...a1) == false) + + assertTrue(C.foo(...[new A, new B]) == false) + assertTrue(C.moo(12, ...[new A, new B]) == false) + + assertTrue(C.foo(...[new A, new B] as [A, B]) == false) + assertTrue(C.moo(12, ...[new A, new B] as [A, B]) == false) + + assertTrue(C.foo(new A, new B) == false) + assertTrue(C.moo(12, new A, new B) == false) +} diff --git a/ets2panda/test/runtime/ets/RestTuple8.ets b/ets2panda/test/runtime/ets/RestTuple8.ets new file mode 100644 index 0000000000..3a802df408 --- /dev/null +++ b/ets2panda/test/runtime/ets/RestTuple8.ets @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class A {} +class B {} + +class C { + public field : boolean + + constructor(...p: [A, B]) { + this.field = p[0] == p[1] + } + + constructor(a: int, ...p: [A, B]) { + this.field = p[0] == p[1] + } +} + +function main() { + let a1: [A, B] = [new A, new B] + + assertTrue((new C(...a1)).field == false) + assertTrue((new C(22, ...a1)).field == false) + + assertTrue((new C(...[new A, new B])).field == false) + assertTrue((new C(22, ...[new A, new B])).field == false) + + assertTrue((new C(...[new A, new B] as [A, B])).field == false) + assertTrue((new C(22, ...[new A, new B] as [A, B])).field == false) + + assertTrue((new C(new A, new B)).field == false) + assertTrue((new C(22, new A, new B)).field == false) +} -- Gitee From 294a91d0832fac9bf0f839b65d7775ccc0fd26f0 Mon Sep 17 00:00:00 2001 From: ElevenDuan Date: Mon, 5 May 2025 17:32:40 +0800 Subject: [PATCH 142/268] Modify the enabled version of lazy default import Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC5IFF?from=project-issue Change-Id: Idc85b891c95d603c8230e03888e2f8dcdc43a45a Signed-off-by: ElevenDuan --- es2panda/parser/parserImpl.h | 2 +- es2panda/parser/statementParser.cpp | 38 +- .../language/import/lazy-import-expected.txt | 1 - .../beta2/import-lazy-beta2-2-expected.txt | 4 +- .../api12/beta3/import-lazy-2-expected.txt | 2 - .../beta3/import-lazy-defalut-1-expected.txt | 0 .../api12/beta3/import-lazy-defalut-1.js | 16 + .../beta3/import-lazy-defalut-2-expected.txt | 1 + .../api12/beta3/import-lazy-defalut-2.js | 16 + es2panda/test/runner.py | 12 +- ...or_equal_to_API18_asm_version-expected.txt | 73 + ...or_equal_to_API18_asm_version-expected.txt | 103 + ...or_equal_to_API18_asm_version-expected.txt | 88 + ...or_equal_to_API18_asm_version-expected.txt | 55 + ...or_equal_to_API18_asm_version-expected.txt | 95 + ...or_equal_to_API18_asm_version-expected.txt | 75 + ...or_equal_to_API18_asm_version-expected.txt | 45 + ...or_equal_to_API18_asm_version-expected.txt | 55 + ...or_equal_to_API18_asm_version-expected.txt | 5907 +++++++++++++++++ ...or_equal_to_API18_asm_version-expected.txt | 50 + .../import_target/import_target.ts | 2 + ...or_equal_to_API18_asm_version-expected.txt | 42 + .../bytecode_feature/lazy_import_bytecode.ts | 5 +- ...ual_to_API12beta3_asm_version-expected.txt | 9 +- ...or_equal_to_API18_asm_version-expected.txt | 49 + ...ode_supported_runtime_version-expected.txt | 1 + ...or_equal_to_API18_asm_version-expected.txt | 40 + .../import_target/import_target.ts | 5 + .../API12beta3/syntax_feature/lazy_import.ts | 2 +- ...ort_supported_compile_version-expected.txt | 45 +- es2panda/util/helpers.cpp | 5 - es2panda/util/helpers.h | 2 - 32 files changed, 6790 insertions(+), 55 deletions(-) create mode 100644 es2panda/test/parser/js/language/import/syntax/api12/beta3/import-lazy-defalut-1-expected.txt create mode 100644 es2panda/test/parser/js/language/import/syntax/api12/beta3/import-lazy-defalut-1.js create mode 100644 es2panda/test/parser/js/language/import/syntax/api12/beta3/import-lazy-defalut-2-expected.txt create mode 100644 es2panda/test/parser/js/language/import/syntax/api12/beta3/import-lazy-defalut-2.js create mode 100644 es2panda/test/version_control/API11/bytecode_feature/class_init_callinit_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt create mode 100644 es2panda/test/version_control/API11/bytecode_feature/class_private_property_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt create mode 100644 es2panda/test/version_control/API11/bytecode_feature/computed_property_name_as_class_key_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt create mode 100644 es2panda/test/version_control/API11/bytecode_feature/define_ld_sendable_class_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt create mode 100644 es2panda/test/version_control/API11/bytecode_feature/in_obj_syntax_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt create mode 100644 es2panda/test/version_control/API11/bytecode_feature/public_field_replace_set_semantics_as_define_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt create mode 100644 es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt create mode 100644 es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt create mode 100644 es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt create mode 100644 es2panda/test/version_control/API12beta3/bytecode_feature/define_property_by_name_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt create mode 100644 es2panda/test/version_control/API12beta3/bytecode_feature/istrue_isfalse_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt create mode 100644 es2panda/test/version_control/API12beta3/bytecode_feature/lazy_import_bytecode_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt create mode 100644 es2panda/test/version_control/API12beta3/bytecode_feature/wide_lazy_import_bytecode_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt diff --git a/es2panda/parser/parserImpl.h b/es2panda/parser/parserImpl.h index a69af8e055..cf51697667 100644 --- a/es2panda/parser/parserImpl.h +++ b/es2panda/parser/parserImpl.h @@ -602,7 +602,7 @@ private: ir::VariableDeclaration *ParseContextualLet(VariableParsingFlags flags, StatementParsingFlags stmFlags = StatementParsingFlags::ALLOW_LEXICAL, bool isDeclare = false); - void VerifySupportLazyImportVersion(bool isNamedImport); + void VerifySupportLazyImportVersion(); util::StringView GetNamespaceExportInternalName() { diff --git a/es2panda/parser/statementParser.cpp b/es2panda/parser/statementParser.cpp index 3a0b46e5ca..a5f16176d7 100644 --- a/es2panda/parser/statementParser.cpp +++ b/es2panda/parser/statementParser.cpp @@ -3186,30 +3186,18 @@ ir::AstNode *ParserImpl::ParseImportSpecifiers(ArenaVector *speci return nullptr; } -void ParserImpl::VerifySupportLazyImportVersion(bool isNamedImport) -{ - if (isNamedImport) { - if (!util::Helpers::IsSupportLazyImportVersion(program_.TargetApiVersion(), - program_.GetTargetApiSubVersion())) { - std::string errMessage = "Current configuration does not support using lazy import. Lazy import can be " - "used in the beta3 version of API 12 or higher versions.\n" - "Solutions: > Check the compatibleSdkVersion and compatibleSdkVersionStage in build-profile.json5." - "> If compatibleSdkVersion is set to API 12, then compatibleSdkVersionStage needs to be configured " - "as beta3." - "> If you're running es2abc in commandline without IDE, please check whether target-api-version and " - "target-api-sub-version options are correctly configured."; - ThrowSyntaxError(errMessage); - } - } else { - if (!util::Helpers::IsSupportLazyImportDefaultVersion(program_.TargetApiVersion())) { - std::string errMessage = "Current configuration does not support using lazy import default." - "Lazy import can be used in the version of API 18 or higher versions.\n" - "Solutions: > Check the compatibleSdkVersion in build-profile.json5." - "> If compatibleSdkVersion is set to API 18." - "> If you're running es2abc in commandline without IDE, please check whether target-api-version " - "options are correctly configured."; - ThrowSyntaxError(errMessage); - } +void ParserImpl::VerifySupportLazyImportVersion() +{ + if (!util::Helpers::IsSupportLazyImportVersion(program_.TargetApiVersion(), + program_.GetTargetApiSubVersion())) { + std::string errMessage = "Current configuration does not support using lazy import. Lazy import can be " + "used in the beta3 version of API 12 or higher versions.\n" + "Solutions: > Check the compatibleSdkVersion and compatibleSdkVersionStage in build-profile.json5." + "> If compatibleSdkVersion is set to API 12, then compatibleSdkVersionStage needs to be configured " + "as beta3." + "> If you're running es2abc in commandline without IDE, please check whether target-api-version and " + "target-api-sub-version options are correctly configured."; + ThrowSyntaxError(errMessage); } } @@ -3246,7 +3234,7 @@ ir::Statement *ParserImpl::ParseImportDeclaration(StatementParsingFlags flags) lexer_->GetToken().KeywordType() != lexer::TokenType::KEYW_TYPE) && lexer_->GetToken().KeywordType() != lexer::TokenType::KEYW_FROM; if (isNamedImport || isDefaultImport) { - VerifySupportLazyImportVersion(isNamedImport); + VerifySupportLazyImportVersion(); isLazy = true; } else { lexer_->Rewind(savedPos); diff --git a/es2panda/test/parser/js/language/import/lazy-import-expected.txt b/es2panda/test/parser/js/language/import/lazy-import-expected.txt index 4954838d6c..d8b751d51e 100644 --- a/es2panda/test/parser/js/language/import/lazy-import-expected.txt +++ b/es2panda/test/parser/js/language/import/lazy-import-expected.txt @@ -1,5 +1,4 @@ slotNum = 0x6 -expectedProperty = 0x3 .language ECMAScript .function any .#~A=#A(any a0, any a1, any a2) { label_1: diff --git a/es2panda/test/parser/js/language/import/syntax/api12/beta2/import-lazy-beta2-2-expected.txt b/es2panda/test/parser/js/language/import/syntax/api12/beta2/import-lazy-beta2-2-expected.txt index a5a0f51d28..592aff13d0 100644 --- a/es2panda/test/parser/js/language/import/syntax/api12/beta2/import-lazy-beta2-2-expected.txt +++ b/es2panda/test/parser/js/language/import/syntax/api12/beta2/import-lazy-beta2-2-expected.txt @@ -1,2 +1,2 @@ -SyntaxError: Current configuration does not support using lazy import default.Lazy import can be used in the version of API 18 or higher versions. -Solutions: > Check the compatibleSdkVersion in build-profile.json5.> If compatibleSdkVersion is set to API 18.> If you're running es2abc in commandline without IDE, please check whether target-api-version options are correctly configured. [import-lazy-beta2-2.js:16:13] +SyntaxError: Current configuration does not support using lazy import. Lazy import can be used in the beta3 version of API 12 or higher versions. +Solutions: > Check the compatibleSdkVersion and compatibleSdkVersionStage in build-profile.json5.> If compatibleSdkVersion is set to API 12, then compatibleSdkVersionStage needs to be configured as beta3.> If you're running es2abc in commandline without IDE, please check whether target-api-version and target-api-sub-version options are correctly configured. [import-lazy-beta2-2.js:16:13] diff --git a/es2panda/test/parser/js/language/import/syntax/api12/beta3/import-lazy-2-expected.txt b/es2panda/test/parser/js/language/import/syntax/api12/beta3/import-lazy-2-expected.txt index aeccb2f589..e69de29bb2 100644 --- a/es2panda/test/parser/js/language/import/syntax/api12/beta3/import-lazy-2-expected.txt +++ b/es2panda/test/parser/js/language/import/syntax/api12/beta3/import-lazy-2-expected.txt @@ -1,2 +0,0 @@ -SyntaxError: Current configuration does not support using lazy import default.Lazy import can be used in the version of API 18 or higher versions. -Solutions: > Check the compatibleSdkVersion in build-profile.json5.> If compatibleSdkVersion is set to API 18.> If you're running es2abc in commandline without IDE, please check whether target-api-version options are correctly configured. [import-lazy-2.js:16:13] diff --git a/es2panda/test/parser/js/language/import/syntax/api12/beta3/import-lazy-defalut-1-expected.txt b/es2panda/test/parser/js/language/import/syntax/api12/beta3/import-lazy-defalut-1-expected.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/es2panda/test/parser/js/language/import/syntax/api12/beta3/import-lazy-defalut-1.js b/es2panda/test/parser/js/language/import/syntax/api12/beta3/import-lazy-defalut-1.js new file mode 100644 index 0000000000..1be0190971 --- /dev/null +++ b/es2panda/test/parser/js/language/import/syntax/api12/beta3/import-lazy-defalut-1.js @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import lazy a from './a' \ No newline at end of file diff --git a/es2panda/test/parser/js/language/import/syntax/api12/beta3/import-lazy-defalut-2-expected.txt b/es2panda/test/parser/js/language/import/syntax/api12/beta3/import-lazy-defalut-2-expected.txt new file mode 100644 index 0000000000..d9309c1890 --- /dev/null +++ b/es2panda/test/parser/js/language/import/syntax/api12/beta3/import-lazy-defalut-2-expected.txt @@ -0,0 +1 @@ +SyntaxError: Unexpected token. [import-lazy-defalut-2.js:16:13] diff --git a/es2panda/test/parser/js/language/import/syntax/api12/beta3/import-lazy-defalut-2.js b/es2panda/test/parser/js/language/import/syntax/api12/beta3/import-lazy-defalut-2.js new file mode 100644 index 0000000000..9311c81e83 --- /dev/null +++ b/es2panda/test/parser/js/language/import/syntax/api12/beta3/import-lazy-defalut-2.js @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import lazy type {a} from './a' \ No newline at end of file diff --git a/es2panda/test/runner.py b/es2panda/test/runner.py index f378d108c3..abaaaab0ba 100755 --- a/es2panda/test/runner.py +++ b/es2panda/test/runner.py @@ -2293,10 +2293,13 @@ class TestVersionControl(Test): api_name = "" # Higher than the specific API version, expected results may differ if target_api_version != "" and specific_api_version != "": - if self.compare_two_versions(target_api_version, specific_api_version) >= 0: - api_name = "for_higher_or_equal_to_%s_" % (specific_api_version) + if self.compare_two_versions(target_api_version, "API18") >= 0: + api_name = "for_higher_or_equal_to_%s_" % "API18" else: - api_name = "for_below_%s_" % (specific_api_version) + if self.compare_two_versions(target_api_version, specific_api_version) >= 0: + api_name = "for_higher_or_equal_to_%s_" % (specific_api_version) + else: + api_name = "for_below_%s_" % (specific_api_version) if dump_type == "ast": dump_type = "" elif dump_type == "asm": @@ -2676,7 +2679,8 @@ def add_directory_for_regression(runners, args): runner.add_directory("parser/js/language/import/syntax/api12/beta2", "js", ["--parse-only", "--module", "--target-api-version=12", "--target-api-sub-version=beta2"]) runner.add_directory("parser/js/language/import", "ts", - ["--dump-assembly", "--dump-literal-buffer", "--module", "--target-api-version=18"]) + ["--dump-assembly", "--dump-literal-buffer", "--module", "--target-api-version=12", + "--target-api-sub-version=beta3"]) runner.add_directory("parser/sendable_class", "ts", ["--dump-assembly", "--dump-literal-buffer", "--module", "--target-api-sub-version=beta3"]) runner.add_directory("parser/sendable_class/api12beta2", "ts", diff --git a/es2panda/test/version_control/API11/bytecode_feature/class_init_callinit_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt b/es2panda/test/version_control/API11/bytecode_feature/class_init_callinit_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt new file mode 100644 index 0000000000..13a6183890 --- /dev/null +++ b/es2panda/test/version_control/API11/bytecode_feature/class_init_callinit_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt @@ -0,0 +1,73 @@ +slotNum = 0x4 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~A=#A(any a0, any a1, any a2, any a3) { +label_1: +label_0: + ldlexvar 0x0, 0x0 + callruntime.callinit 0x0, a2 + lda a3 + stobjbyname 0x2, a, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .#~A>#instance_initializer(any a0, any a1, any a2) { +label_1: +label_0: + lda.str a + definepropertybyname 0x0, a, a2 + returnundefined +label_2: +} + +slotNum = 0xb +.language ECMAScript +.function any .func_main_0(any a0, any a1, any a2) { + nop +label_7: +label_0: + newlexenv 0x1 +label_2: +label_4: + ldhole + sta v1 + defineclasswithbuffer 0x0, .#~A=#A, _2, 0x1, v1 + sta v1 + ldobjbyname 0x1, prototype + definemethod 0x3, .#~A>#instance_initializer, 0x0 + stlexvar 0x0, 0x0 +label_3: +end_label_3: + jmp label_1 +label_9: + sta v0 +label_6: + poplexenv + lda v0 + throw +label_1: + poplexenv + lda.str b + sta v0 + mov v2, v1 + mov v3, v0 + newobjrange 0x4, 0x2, v2 + sta v0 + tryldglobalbyname 0x6, print + sta v1 + lda v0 + ldobjbyname 0x7, a + sta v0 + lda v1 + callarg1 0x9, v0 + returnundefined +label_8: +} + +.catchall label_2, end_label_3, label_9 + + diff --git a/es2panda/test/version_control/API11/bytecode_feature/class_private_property_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt b/es2panda/test/version_control/API11/bytecode_feature/class_private_property_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt new file mode 100644 index 0000000000..a4e2f5e25d --- /dev/null +++ b/es2panda/test/version_control/API11/bytecode_feature/class_private_property_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt @@ -0,0 +1,103 @@ +slotNum = 0x4 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@0=#TestPrivateProperty(any a0, any a1, any a2, any a3) { +label_1: +label_0: + ldlexvar 0x0, 0x1 + callruntime.callinit 0x0, a2 + lda a3 + stprivateproperty 0x2, 0x0, 0x0, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .#~@0>#getPrivateField(any a0, any a1, any a2) { +label_1: +label_0: + lda a2 + ldprivateproperty 0x0, 0x0, 0x0 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .#~@0>#instance_initializer(any a0, any a1, any a2) { +label_1: +label_0: + ldundefined + callruntime.defineprivateproperty 0x0, 0x0, 0x0, a2 + returnundefined +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .#~@0>#setPrivateField(any a0, any a1, any a2, any a3) { +label_1: +label_0: + lda a3 + stprivateproperty 0x0, 0x0, 0x0, a2 + returnundefined +label_2: +} + +slotNum = 0x11 +.language ECMAScript +.function any .func_main_0(any a0, any a1, any a2) { + nop +label_7: +label_0: + newlexenv 0x2 +label_2: +label_4: + ldhole + sta v1 + defineclasswithbuffer 0x0, .#~@0=#TestPrivateProperty, _2, 0x1, v1 + sta v1 + ldobjbyname 0x1, prototype + definemethod 0x3, .#~@0>#instance_initializer, 0x0 + stlexvar 0x0, 0x1 + callruntime.createprivateproperty 0x1, _3 +label_3: +end_label_3: + jmp label_1 +label_9: + sta v0 +label_6: + poplexenv + lda v0 + throw +label_1: + poplexenv + ldai 0xa + sta v0 + mov v3, v1 + mov v4, v0 + newobjrange 0x4, 0x2, v3 + sta v0 + ldobjbyname 0x6, setPrivateField + sta v1 + ldai 0x14 + sta v2 + lda v1 + callthis1 0x8, v0, v2 + tryldglobalbyname 0xa, print + sta v1 + lda v0 + ldobjbyname 0xb, getPrivateField + callthis0 0xd, v0 + sta v0 + lda v1 + callarg1 0xf, v0 + returnundefined +label_8: +} + +.catchall label_2, end_label_3, label_9 + + diff --git a/es2panda/test/version_control/API11/bytecode_feature/computed_property_name_as_class_key_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt b/es2panda/test/version_control/API11/bytecode_feature/computed_property_name_as_class_key_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt new file mode 100644 index 0000000000..e7087b0c6e --- /dev/null +++ b/es2panda/test/version_control/API11/bytecode_feature/computed_property_name_as_class_key_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt @@ -0,0 +1,88 @@ +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~A=#A(any a0, any a1, any a2) { +label_1: +label_0: + ldlexvar 0x0, 0x1 + callruntime.callinit 0x0, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .#~A>#instance_initializer(any a0, any a1, any a2) { +label_1: +label_0: + ldlexvar 0x0, 0x0 + sta v0 + ldlexvar 0x1, 0x0 + sta v1 + throw.undefinedifholewithname a + lda v1 + callruntime.definefieldbyvalue 0x0, v0, a2 + returnundefined +label_2: +} + +slotNum = 0xc +.language ECMAScript +.function any .func_main_0(any a0, any a1, any a2) { + nop +label_7: +label_0: + newlexenv 0x1 + lda.str a + sta v0 + lda.str b + add2 0x0, v0 + stlexvar 0x0, 0x0 + newlexenv 0x2 +label_2: +label_4: + ldhole + sta v1 + ldlexvar 0x1, 0x0 + sta v2 + throw.undefinedifholewithname a + lda v2 + callruntime.topropertykey + stlexvar 0x0, 0x0 + defineclasswithbuffer 0x1, .#~A=#A, _2, 0x0, v1 + sta v1 + ldobjbyname 0x2, prototype + definemethod 0x4, .#~A>#instance_initializer, 0x0 + stlexvar 0x0, 0x1 +label_3: +end_label_3: + jmp label_1 +label_9: + sta v0 +label_6: + poplexenv + lda v0 + throw +label_1: + poplexenv + mov v3, v1 + newobjrange 0x5, 0x1, v3 + sta v0 + tryldglobalbyname 0x7, print + sta v1 + ldlexvar 0x0, 0x0 + sta v2 + throw.undefinedifholewithname a + lda v2 + ldobjbyvalue 0x8, v0 + sta v0 + lda v1 + callarg1 0xa, v0 + returnundefined +label_8: +} + +.catchall label_2, end_label_3, label_9 + + diff --git a/es2panda/test/version_control/API11/bytecode_feature/define_ld_sendable_class_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt b/es2panda/test/version_control/API11/bytecode_feature/define_ld_sendable_class_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt new file mode 100644 index 0000000000..67e2e6c37a --- /dev/null +++ b/es2panda/test/version_control/API11/bytecode_feature/define_ld_sendable_class_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt @@ -0,0 +1,55 @@ +slotNum = 0x1 +.language ECMAScript +.function any .#&#X(any a0, any a1, any a2, any a3) { +label_1: +label_0: + newlexenv 0x1 + ldhole + sta v0 + callruntime.definesendableclass 0x0, .#&X~@0=#TestTypeA, _3, 0x0, v0 + stlexvar 0x0, 0x0 + returnundefined +label_2: +} + +slotNum = 0x6 +expectedProperty = 0x2 +.language ECMAScript +.function any .#&X~@0=#TestTypeA(any a0, any a1, any a2) { +label_1: +label_0: + lda.str A + stobjbyname 0x0, name, a2 + callruntime.ldsendableclass 0x0 + sta v0 + mov v1, v0 + newobjrange 0x2, 0x1, v1 + stobjbyname 0x4, test, a2 + lda a2 + return +label_2: +} + +slotNum = 0x4 +.language ECMAScript +.function any .func_main_0(any a0, any a1, any a2) { +label_4: +label_0: + ldundefined + sta v0 + definefunc 0x0, .#&#X, 0x1 + sta v1 + lda v0 + callruntime.istrue 0x1 + jnez label_3 +label_2: + createemptyobject + sta v0 +label_3: + lda v1 + callarg1 0x2, v0 + returnundefined +label_5: +} + + diff --git a/es2panda/test/version_control/API11/bytecode_feature/in_obj_syntax_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt b/es2panda/test/version_control/API11/bytecode_feature/in_obj_syntax_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt new file mode 100644 index 0000000000..4493a6c93d --- /dev/null +++ b/es2panda/test/version_control/API11/bytecode_feature/in_obj_syntax_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt @@ -0,0 +1,95 @@ +slotNum = 0x3 +.language ECMAScript +.function any .#~@0<#getPrivateProperty(any a0, any a1, any a2, any a3) { +label_3: +label_0: + lda a3 + testin 0x0, 0x0, 0x0 + callruntime.isfalse 0x2 + jnez label_1 +label_2: + ldtrue + return +label_1: + ldfalse + return +label_4: +} + +slotNum = 0x4 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@0=#InObjSyntax(any a0, any a1, any a2, any a3) { +label_1: +label_0: + ldlexvar 0x0, 0x1 + callruntime.callinit 0x0, a2 + lda a3 + stprivateproperty 0x2, 0x0, 0x0, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .#~@0>#instance_initializer(any a0, any a1, any a2) { +label_1: +label_0: + lda.str private + callruntime.defineprivateproperty 0x0, 0x0, 0x0, a2 + returnundefined +label_2: +} + +slotNum = 0xd +.language ECMAScript +.function any .func_main_0(any a0, any a1, any a2) { + nop +label_7: +label_0: + newlexenv 0x2 +label_2: +label_4: + ldhole + sta v1 + defineclasswithbuffer 0x0, .#~@0=#InObjSyntax, _2, 0x1, v1 + sta v1 + ldobjbyname 0x1, prototype + definemethod 0x3, .#~@0>#instance_initializer, 0x0 + stlexvar 0x0, 0x1 + callruntime.createprivateproperty 0x1, _3 +label_3: +end_label_3: + jmp label_1 +label_9: + sta v0 +label_6: + poplexenv + lda v0 + throw +label_1: + poplexenv + tryldglobalbyname 0x4, print + sta v0 + lda v1 + ldobjbyname 0x5, getPrivateProperty + sta v2 + lda.str foo + sta v3 + mov v4, v1 + mov v5, v3 + newobjrange 0x7, 0x2, v4 + sta v3 + lda v2 + callthis1 0x9, v1, v3 + sta v1 + lda v0 + callarg1 0xb, v1 + returnundefined +label_8: +} + +.catchall label_2, end_label_3, label_9 + + diff --git a/es2panda/test/version_control/API11/bytecode_feature/public_field_replace_set_semantics_as_define_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt b/es2panda/test/version_control/API11/bytecode_feature/public_field_replace_set_semantics_as_define_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt new file mode 100644 index 0000000000..aa00c9181c --- /dev/null +++ b/es2panda/test/version_control/API11/bytecode_feature/public_field_replace_set_semantics_as_define_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt @@ -0,0 +1,75 @@ +slotNum = 0x2 +expectedProperty = 0x3 +.language ECMAScript +.function any .#~A=#A(any a0, any a1, any a2) { +label_1: +label_0: + ldlexvar 0x0, 0x1 + callruntime.callinit 0x0, a2 + lda a2 + return +label_2: +} + +slotNum = 0x6 +.language ECMAScript +.function any .#~A>#instance_initializer(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + callruntime.definefieldbyindex 0x0, 0x1, a2 + ldlexvar 0x0, 0x0 + sta v0 + lda.str a + callruntime.definefieldbyvalue 0x2, v0, a2 + ldlexvar 0x1, 0x0 + sta v0 + throw.undefinedifholewithname a + lda v0 + definepropertybyname 0x4, b, a2 + returnundefined +label_2: +} + +slotNum = 0x4 +.language ECMAScript +.function any .func_main_0(any a0, any a1, any a2) { + nop +label_7: +label_0: + newlexenv 0x1 + lda.str a + stlexvar 0x0, 0x0 + newlexenv 0x2 +label_2: +label_4: + ldhole + sta v1 + ldlexvar 0x1, 0x0 + sta v2 + throw.undefinedifholewithname a + lda v2 + callruntime.topropertykey + stlexvar 0x0, 0x0 + defineclasswithbuffer 0x0, .#~A=#A, _2, 0x0, v1 + ldobjbyname 0x1, prototype + definemethod 0x3, .#~A>#instance_initializer, 0x0 + stlexvar 0x0, 0x1 +label_3: +end_label_3: + jmp label_1 +label_9: + sta v0 +label_6: + poplexenv + lda v0 + throw +label_1: + poplexenv + returnundefined +label_8: +} + +.catchall label_2, end_label_3, label_9 + + diff --git a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt new file mode 100644 index 0000000000..048d8311b3 --- /dev/null +++ b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt @@ -0,0 +1,45 @@ +slotNum = 0x4 +expectedProperty = 0x2 +.language ECMAScript +.function any .#~@0=#SendableLazyLoading(any a0, any a1, any a2) { +label_1: +label_0: + callruntime.ldsendableexternalmodulevar 0x0 + sta v0 + throw.undefinedifholewithname a1 + lda v0 + stobjbyname 0x0, name, a2 + callruntime.wideldsendableexternalmodulevar 0xad + sta v0 + throw.undefinedifholewithname a255 + lda v0 + stobjbyname 0x2, name1, a2 + lda a2 + return +label_2: +} + +slotNum = 0x8 +.language ECMAScript +.function any .func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + ldhole + sta v0 + callruntime.definesendableclass 0x0, .#~@0=#SendableLazyLoading, _3, 0x0, v0 + sta v0 + mov v2, v0 + newobjrange 0x1, 0x1, v2 + sta v0 + tryldglobalbyname 0x3, print + sta v1 + lda v0 + ldobjbyname 0x4, name + sta v0 + lda v1 + callarg1 0x6, v0 + returnundefined +label_2: +} + + diff --git a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt new file mode 100644 index 0000000000..eb03275011 --- /dev/null +++ b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt @@ -0,0 +1,55 @@ +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@0=#TopLevelSendableClass1(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0xa +expectedProperty = 0x2 +.language ECMAScript +.function any .#~@1=#SendableTestClass1(any a0, any a1, any a2) { +label_1: +label_0: + callruntime.ldsendablevar 0x0, 0x0 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass1 + mov v1, v0 + newobjrange 0x0, 0x1, v1 + stobjbyname 0x2, a1, a2 + lda a2 + ldobjbyname 0x4, a1 + ldobjbyname 0x6, o + stobjbyname 0x8, u, a2 + lda a2 + return +label_2: +} + +slotNum = 0x4 +.language ECMAScript +.function any .func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + callruntime.newsendableenv 0x1 + ldhole + sta v0 + callruntime.definesendableclass 0x0, .#~@0=#TopLevelSendableClass1, _3, 0x0, v0 + callruntime.stsendablevar 0x0, 0x0 + ldhole + sta v0 + callruntime.definesendableclass 0x1, .#~@1=#SendableTestClass1, _5, 0x0, v0 + sta v0 + mov v1, v0 + newobjrange 0x2, 0x1, v1 + returnundefined +label_2: +} + + diff --git a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt new file mode 100644 index 0000000000..4eb345368c --- /dev/null +++ b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt @@ -0,0 +1,5907 @@ +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@0=#TopLevelSendableClass1(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@10=#TopLevelSendableClass17(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@11=#TopLevelSendableClass18(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@12=#TopLevelSendableClass19(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@13=#TopLevelSendableClass20(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@14=#TopLevelSendableClass21(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@15=#TopLevelSendableClass22(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@16=#TopLevelSendableClass23(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@17=#TopLevelSendableClass24(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@18=#TopLevelSendableClass25(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@19=#TopLevelSendableClass26(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@1=#TopLevelSendableClass2(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@1a=#TopLevelSendableClass27(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@1b=#TopLevelSendableClass28(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@1c=#TopLevelSendableClass29(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@1d=#TopLevelSendableClass30(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@1e=#TopLevelSendableClass31(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@1f=#TopLevelSendableClass32(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@20=#TopLevelSendableClass33(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@21=#TopLevelSendableClass34(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@22=#TopLevelSendableClass35(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@23=#TopLevelSendableClass36(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@24=#TopLevelSendableClass37(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@25=#TopLevelSendableClass38(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@26=#TopLevelSendableClass39(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@27=#TopLevelSendableClass40(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@28=#TopLevelSendableClass41(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@29=#TopLevelSendableClass42(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@2=#TopLevelSendableClass3(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@2a=#TopLevelSendableClass43(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@2b=#TopLevelSendableClass44(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@2c=#TopLevelSendableClass45(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@2d=#TopLevelSendableClass46(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@2e=#TopLevelSendableClass47(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@2f=#TopLevelSendableClass48(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@30=#TopLevelSendableClass49(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@31=#TopLevelSendableClass50(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@32=#TopLevelSendableClass51(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@33=#TopLevelSendableClass52(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@34=#TopLevelSendableClass53(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@35=#TopLevelSendableClass54(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@36=#TopLevelSendableClass55(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@37=#TopLevelSendableClass56(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@38=#TopLevelSendableClass57(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@39=#TopLevelSendableClass58(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@3=#TopLevelSendableClass4(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@3a=#TopLevelSendableClass59(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@3b=#TopLevelSendableClass60(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@3c=#TopLevelSendableClass61(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@3d=#TopLevelSendableClass62(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@3e=#TopLevelSendableClass63(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@3f=#TopLevelSendableClass64(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@40=#TopLevelSendableClass65(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@41=#TopLevelSendableClass66(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@42=#TopLevelSendableClass67(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@43=#TopLevelSendableClass68(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@44=#TopLevelSendableClass69(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@45=#TopLevelSendableClass70(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@46=#TopLevelSendableClass71(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@47=#TopLevelSendableClass72(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@48=#TopLevelSendableClass73(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@49=#TopLevelSendableClass74(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@4=#TopLevelSendableClass5(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@4a=#TopLevelSendableClass75(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@4b=#TopLevelSendableClass76(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@4c=#TopLevelSendableClass77(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@4d=#TopLevelSendableClass78(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@4e=#TopLevelSendableClass79(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@4f=#TopLevelSendableClass80(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@50=#TopLevelSendableClass81(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@51=#TopLevelSendableClass82(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@52=#TopLevelSendableClass83(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@53=#TopLevelSendableClass84(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@54=#TopLevelSendableClass85(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@55=#TopLevelSendableClass86(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@56=#TopLevelSendableClass87(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@57=#TopLevelSendableClass88(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@58=#TopLevelSendableClass89(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@59=#TopLevelSendableClass90(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@5=#TopLevelSendableClass6(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@5a=#TopLevelSendableClass91(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@5b=#TopLevelSendableClass92(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@5c=#TopLevelSendableClass93(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@5d=#TopLevelSendableClass94(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@5e=#TopLevelSendableClass95(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@5f=#TopLevelSendableClass96(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@60=#TopLevelSendableClass97(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@61=#TopLevelSendableClass98(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@62=#TopLevelSendableClass99(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@63=#TopLevelSendableClass100(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@64=#TopLevelSendableClass101(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@65=#TopLevelSendableClass102(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@66=#TopLevelSendableClass103(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@67=#TopLevelSendableClass104(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@68=#TopLevelSendableClass105(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@69=#TopLevelSendableClass106(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@6=#TopLevelSendableClass7(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@6a=#TopLevelSendableClass107(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@6b=#TopLevelSendableClass108(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@6c=#TopLevelSendableClass109(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@6d=#TopLevelSendableClass110(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@6e=#TopLevelSendableClass111(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@6f=#TopLevelSendableClass112(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@70=#TopLevelSendableClass113(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@71=#TopLevelSendableClass114(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@72=#TopLevelSendableClass115(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@73=#TopLevelSendableClass116(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@74=#TopLevelSendableClass117(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@75=#TopLevelSendableClass118(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@76=#TopLevelSendableClass119(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@77=#TopLevelSendableClass120(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@78=#TopLevelSendableClass121(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@79=#TopLevelSendableClass122(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@7=#TopLevelSendableClass8(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@7a=#TopLevelSendableClass123(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@7b=#TopLevelSendableClass124(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@7c=#TopLevelSendableClass125(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@7d=#TopLevelSendableClass126(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@7e=#TopLevelSendableClass127(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@7f=#TopLevelSendableClass128(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@80=#TopLevelSendableClass129(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@81=#TopLevelSendableClass130(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@82=#TopLevelSendableClass131(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@83=#TopLevelSendableClass132(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@84=#TopLevelSendableClass133(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@85=#TopLevelSendableClass134(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@86=#TopLevelSendableClass135(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@87=#TopLevelSendableClass136(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@88=#TopLevelSendableClass137(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@89=#TopLevelSendableClass138(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@8=#TopLevelSendableClass9(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@8a=#TopLevelSendableClass139(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@8b=#TopLevelSendableClass140(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@8c=#TopLevelSendableClass141(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@8d=#TopLevelSendableClass142(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@8e=#TopLevelSendableClass143(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@8f=#TopLevelSendableClass144(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@90=#TopLevelSendableClass145(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@91=#TopLevelSendableClass146(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@92=#TopLevelSendableClass147(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@93=#TopLevelSendableClass148(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@94=#TopLevelSendableClass149(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@95=#TopLevelSendableClass150(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@96=#TopLevelSendableClass151(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@97=#TopLevelSendableClass152(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@98=#TopLevelSendableClass153(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@99=#TopLevelSendableClass154(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@9=#TopLevelSendableClass10(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@9a=#TopLevelSendableClass155(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@9b=#TopLevelSendableClass156(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@9c=#TopLevelSendableClass157(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@9d=#TopLevelSendableClass158(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@9e=#TopLevelSendableClass159(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@9f=#TopLevelSendableClass160(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@a0=#TopLevelSendableClass161(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@a1=#TopLevelSendableClass162(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@a2=#TopLevelSendableClass163(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@a3=#TopLevelSendableClass164(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@a4=#TopLevelSendableClass165(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@a5=#TopLevelSendableClass166(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@a6=#TopLevelSendableClass167(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@a7=#TopLevelSendableClass168(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@a8=#TopLevelSendableClass169(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@a9=#TopLevelSendableClass170(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@a=#TopLevelSendableClass11(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@aa=#TopLevelSendableClass171(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@ab=#TopLevelSendableClass172(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@ac=#TopLevelSendableClass173(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@ad=#TopLevelSendableClass174(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@ae=#TopLevelSendableClass175(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@af=#TopLevelSendableClass176(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@b0=#TopLevelSendableClass177(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@b1=#TopLevelSendableClass178(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@b2=#TopLevelSendableClass179(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@b3=#TopLevelSendableClass180(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@b4=#TopLevelSendableClass181(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@b5=#TopLevelSendableClass182(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@b6=#TopLevelSendableClass183(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@b7=#TopLevelSendableClass184(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@b8=#TopLevelSendableClass185(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@b9=#TopLevelSendableClass186(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@b=#TopLevelSendableClass12(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@ba=#TopLevelSendableClass187(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@bb=#TopLevelSendableClass188(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@bc=#TopLevelSendableClass189(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@bd=#TopLevelSendableClass190(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@be=#TopLevelSendableClass191(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@bf=#TopLevelSendableClass192(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@c0=#TopLevelSendableClass193(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@c1=#TopLevelSendableClass194(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@c2=#TopLevelSendableClass195(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@c3=#TopLevelSendableClass196(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@c4=#TopLevelSendableClass197(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@c5=#TopLevelSendableClass198(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@c6=#TopLevelSendableClass199(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@c7=#TopLevelSendableClass200(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@c8=#TopLevelSendableClass201(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@c9=#TopLevelSendableClass202(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@c=#TopLevelSendableClass13(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@ca=#TopLevelSendableClass203(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@cb=#TopLevelSendableClass204(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@cc=#TopLevelSendableClass205(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@cd=#TopLevelSendableClass206(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@ce=#TopLevelSendableClass207(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@cf=#TopLevelSendableClass208(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@d0=#TopLevelSendableClass209(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@d1=#TopLevelSendableClass210(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@d2=#TopLevelSendableClass211(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@d3=#TopLevelSendableClass212(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@d4=#TopLevelSendableClass213(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@d5=#TopLevelSendableClass214(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@d6=#TopLevelSendableClass215(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@d7=#TopLevelSendableClass216(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@d8=#TopLevelSendableClass217(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@d9=#TopLevelSendableClass218(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@d=#TopLevelSendableClass14(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@da=#TopLevelSendableClass219(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@db=#TopLevelSendableClass220(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@dc=#TopLevelSendableClass221(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@dd=#TopLevelSendableClass222(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@de=#TopLevelSendableClass223(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@df=#TopLevelSendableClass224(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@e0=#TopLevelSendableClass225(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@e1=#TopLevelSendableClass226(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@e2=#TopLevelSendableClass227(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@e3=#TopLevelSendableClass228(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@e4=#TopLevelSendableClass229(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@e5=#TopLevelSendableClass230(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@e6=#TopLevelSendableClass231(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@e7=#TopLevelSendableClass232(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@e8=#TopLevelSendableClass233(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@e9=#TopLevelSendableClass234(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@e=#TopLevelSendableClass15(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@ea=#TopLevelSendableClass235(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@eb=#TopLevelSendableClass236(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@ec=#TopLevelSendableClass237(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@ed=#TopLevelSendableClass238(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@ee=#TopLevelSendableClass239(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@ef=#TopLevelSendableClass240(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@f0=#TopLevelSendableClass241(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@f1=#TopLevelSendableClass242(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@f2=#TopLevelSendableClass243(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@f3=#TopLevelSendableClass244(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@f4=#TopLevelSendableClass245(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@f5=#TopLevelSendableClass246(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@f6=#TopLevelSendableClass247(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@f7=#TopLevelSendableClass248(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@f8=#TopLevelSendableClass249(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@f9=#TopLevelSendableClass250(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@f=#TopLevelSendableClass16(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@fa=#TopLevelSendableClass251(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@fb=#TopLevelSendableClass252(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@fc=#TopLevelSendableClass253(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@fd=#TopLevelSendableClass254(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@fe=#TopLevelSendableClass255(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x406 +expectedProperty = 0x101 +.language ECMAScript +.function any .#~@ff=#SendableTestClass1(any a0, any a1, any a2) { +label_1: +label_0: + callruntime.ldsendablevar 0x0, 0x0 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass1 + mov v1, v0 + newobjrange 0x0, 0x1, v1 + stobjbyname 0x2, a1, a2 + callruntime.ldsendablevar 0x0, 0x1 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass2 + mov v1, v0 + newobjrange 0x4, 0x1, v1 + stobjbyname 0x6, a2, a2 + callruntime.ldsendablevar 0x0, 0x2 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass3 + mov v1, v0 + newobjrange 0x8, 0x1, v1 + stobjbyname 0xa, a3, a2 + callruntime.ldsendablevar 0x0, 0x3 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass4 + mov v1, v0 + newobjrange 0xc, 0x1, v1 + stobjbyname 0xe, a4, a2 + callruntime.ldsendablevar 0x0, 0x4 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass5 + mov v1, v0 + newobjrange 0x10, 0x1, v1 + stobjbyname 0x12, a5, a2 + callruntime.ldsendablevar 0x0, 0x5 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass6 + mov v1, v0 + newobjrange 0x14, 0x1, v1 + stobjbyname 0x16, a6, a2 + callruntime.ldsendablevar 0x0, 0x6 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass7 + mov v1, v0 + newobjrange 0x18, 0x1, v1 + stobjbyname 0x1a, a7, a2 + callruntime.ldsendablevar 0x0, 0x7 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass8 + mov v1, v0 + newobjrange 0x1c, 0x1, v1 + stobjbyname 0x1e, a8, a2 + callruntime.ldsendablevar 0x0, 0x8 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass9 + mov v1, v0 + newobjrange 0x20, 0x1, v1 + stobjbyname 0x22, a9, a2 + callruntime.ldsendablevar 0x0, 0x9 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass10 + mov v1, v0 + newobjrange 0x24, 0x1, v1 + stobjbyname 0x26, a10, a2 + callruntime.ldsendablevar 0x0, 0xa + sta v0 + throw.undefinedifholewithname TopLevelSendableClass11 + mov v1, v0 + newobjrange 0x28, 0x1, v1 + stobjbyname 0x2a, a11, a2 + callruntime.ldsendablevar 0x0, 0xb + sta v0 + throw.undefinedifholewithname TopLevelSendableClass12 + mov v1, v0 + newobjrange 0x2c, 0x1, v1 + stobjbyname 0x2e, a12, a2 + callruntime.ldsendablevar 0x0, 0xc + sta v0 + throw.undefinedifholewithname TopLevelSendableClass13 + mov v1, v0 + newobjrange 0x30, 0x1, v1 + stobjbyname 0x32, a13, a2 + callruntime.ldsendablevar 0x0, 0xd + sta v0 + throw.undefinedifholewithname TopLevelSendableClass14 + mov v1, v0 + newobjrange 0x34, 0x1, v1 + stobjbyname 0x36, a14, a2 + callruntime.ldsendablevar 0x0, 0xe + sta v0 + throw.undefinedifholewithname TopLevelSendableClass15 + mov v1, v0 + newobjrange 0x38, 0x1, v1 + stobjbyname 0x3a, a15, a2 + callruntime.ldsendablevar 0x0, 0xf + sta v0 + throw.undefinedifholewithname TopLevelSendableClass16 + mov v1, v0 + newobjrange 0x3c, 0x1, v1 + stobjbyname 0x3e, a16, a2 + callruntime.ldsendablevar 0x0, 0x10 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass17 + mov v1, v0 + newobjrange 0x40, 0x1, v1 + stobjbyname 0x42, a17, a2 + callruntime.ldsendablevar 0x0, 0x11 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass18 + mov v1, v0 + newobjrange 0x44, 0x1, v1 + stobjbyname 0x46, a18, a2 + callruntime.ldsendablevar 0x0, 0x12 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass19 + mov v1, v0 + newobjrange 0x48, 0x1, v1 + stobjbyname 0x4a, a19, a2 + callruntime.ldsendablevar 0x0, 0x13 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass20 + mov v1, v0 + newobjrange 0x4c, 0x1, v1 + stobjbyname 0x4e, a20, a2 + callruntime.ldsendablevar 0x0, 0x14 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass21 + mov v1, v0 + newobjrange 0x50, 0x1, v1 + stobjbyname 0x52, a21, a2 + callruntime.ldsendablevar 0x0, 0x15 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass22 + mov v1, v0 + newobjrange 0x54, 0x1, v1 + stobjbyname 0x56, a22, a2 + callruntime.ldsendablevar 0x0, 0x16 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass23 + mov v1, v0 + newobjrange 0x58, 0x1, v1 + stobjbyname 0x5a, a23, a2 + callruntime.ldsendablevar 0x0, 0x17 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass24 + mov v1, v0 + newobjrange 0x5c, 0x1, v1 + stobjbyname 0x5e, a24, a2 + callruntime.ldsendablevar 0x0, 0x18 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass25 + mov v1, v0 + newobjrange 0x60, 0x1, v1 + stobjbyname 0x62, a25, a2 + callruntime.ldsendablevar 0x0, 0x19 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass26 + mov v1, v0 + newobjrange 0x64, 0x1, v1 + stobjbyname 0x66, a26, a2 + callruntime.ldsendablevar 0x0, 0x1a + sta v0 + throw.undefinedifholewithname TopLevelSendableClass27 + mov v1, v0 + newobjrange 0x68, 0x1, v1 + stobjbyname 0x6a, a27, a2 + callruntime.ldsendablevar 0x0, 0x1b + sta v0 + throw.undefinedifholewithname TopLevelSendableClass28 + mov v1, v0 + newobjrange 0x6c, 0x1, v1 + stobjbyname 0x6e, a28, a2 + callruntime.ldsendablevar 0x0, 0x1c + sta v0 + throw.undefinedifholewithname TopLevelSendableClass29 + mov v1, v0 + newobjrange 0x70, 0x1, v1 + stobjbyname 0x72, a29, a2 + callruntime.ldsendablevar 0x0, 0x1d + sta v0 + throw.undefinedifholewithname TopLevelSendableClass30 + mov v1, v0 + newobjrange 0x74, 0x1, v1 + stobjbyname 0x76, a30, a2 + callruntime.ldsendablevar 0x0, 0x1e + sta v0 + throw.undefinedifholewithname TopLevelSendableClass31 + mov v1, v0 + newobjrange 0x78, 0x1, v1 + stobjbyname 0x7a, a31, a2 + callruntime.ldsendablevar 0x0, 0x1f + sta v0 + throw.undefinedifholewithname TopLevelSendableClass32 + mov v1, v0 + newobjrange 0x7c, 0x1, v1 + stobjbyname 0x7e, a32, a2 + callruntime.ldsendablevar 0x0, 0x20 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass33 + mov v1, v0 + newobjrange 0x80, 0x1, v1 + stobjbyname 0x82, a33, a2 + callruntime.ldsendablevar 0x0, 0x21 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass34 + mov v1, v0 + newobjrange 0x84, 0x1, v1 + stobjbyname 0x86, a34, a2 + callruntime.ldsendablevar 0x0, 0x22 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass35 + mov v1, v0 + newobjrange 0x88, 0x1, v1 + stobjbyname 0x8a, a35, a2 + callruntime.ldsendablevar 0x0, 0x23 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass36 + mov v1, v0 + newobjrange 0x8c, 0x1, v1 + stobjbyname 0x8e, a36, a2 + callruntime.ldsendablevar 0x0, 0x24 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass37 + mov v1, v0 + newobjrange 0x90, 0x1, v1 + stobjbyname 0x92, a37, a2 + callruntime.ldsendablevar 0x0, 0x25 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass38 + mov v1, v0 + newobjrange 0x94, 0x1, v1 + stobjbyname 0x96, a38, a2 + callruntime.ldsendablevar 0x0, 0x26 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass39 + mov v1, v0 + newobjrange 0x98, 0x1, v1 + stobjbyname 0x9a, a39, a2 + callruntime.ldsendablevar 0x0, 0x27 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass40 + mov v1, v0 + newobjrange 0x9c, 0x1, v1 + stobjbyname 0x9e, a40, a2 + callruntime.ldsendablevar 0x0, 0x28 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass41 + mov v1, v0 + newobjrange 0xa0, 0x1, v1 + stobjbyname 0xa2, a41, a2 + callruntime.ldsendablevar 0x0, 0x29 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass42 + mov v1, v0 + newobjrange 0xa4, 0x1, v1 + stobjbyname 0xa6, a42, a2 + callruntime.ldsendablevar 0x0, 0x2a + sta v0 + throw.undefinedifholewithname TopLevelSendableClass43 + mov v1, v0 + newobjrange 0xa8, 0x1, v1 + stobjbyname 0xaa, a43, a2 + callruntime.ldsendablevar 0x0, 0x2b + sta v0 + throw.undefinedifholewithname TopLevelSendableClass44 + mov v1, v0 + newobjrange 0xac, 0x1, v1 + stobjbyname 0xae, a44, a2 + callruntime.ldsendablevar 0x0, 0x2c + sta v0 + throw.undefinedifholewithname TopLevelSendableClass45 + mov v1, v0 + newobjrange 0xb0, 0x1, v1 + stobjbyname 0xb2, a45, a2 + callruntime.ldsendablevar 0x0, 0x2d + sta v0 + throw.undefinedifholewithname TopLevelSendableClass46 + mov v1, v0 + newobjrange 0xb4, 0x1, v1 + stobjbyname 0xb6, a46, a2 + callruntime.ldsendablevar 0x0, 0x2e + sta v0 + throw.undefinedifholewithname TopLevelSendableClass47 + mov v1, v0 + newobjrange 0xb8, 0x1, v1 + stobjbyname 0xba, a47, a2 + callruntime.ldsendablevar 0x0, 0x2f + sta v0 + throw.undefinedifholewithname TopLevelSendableClass48 + mov v1, v0 + newobjrange 0xbc, 0x1, v1 + stobjbyname 0xbe, a48, a2 + callruntime.ldsendablevar 0x0, 0x30 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass49 + mov v1, v0 + newobjrange 0xc0, 0x1, v1 + stobjbyname 0xc2, a49, a2 + callruntime.ldsendablevar 0x0, 0x31 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass50 + mov v1, v0 + newobjrange 0xc4, 0x1, v1 + stobjbyname 0xc6, a50, a2 + callruntime.ldsendablevar 0x0, 0x32 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass51 + mov v1, v0 + newobjrange 0xc8, 0x1, v1 + stobjbyname 0xca, a51, a2 + callruntime.ldsendablevar 0x0, 0x33 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass52 + mov v1, v0 + newobjrange 0xcc, 0x1, v1 + stobjbyname 0xce, a52, a2 + callruntime.ldsendablevar 0x0, 0x34 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass53 + mov v1, v0 + newobjrange 0xd0, 0x1, v1 + stobjbyname 0xd2, a53, a2 + callruntime.ldsendablevar 0x0, 0x35 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass54 + mov v1, v0 + newobjrange 0xd4, 0x1, v1 + stobjbyname 0xd6, a54, a2 + callruntime.ldsendablevar 0x0, 0x36 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass55 + mov v1, v0 + newobjrange 0xd8, 0x1, v1 + stobjbyname 0xda, a55, a2 + callruntime.ldsendablevar 0x0, 0x37 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass56 + mov v1, v0 + newobjrange 0xdc, 0x1, v1 + stobjbyname 0xde, a56, a2 + callruntime.ldsendablevar 0x0, 0x38 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass57 + mov v1, v0 + newobjrange 0xe0, 0x1, v1 + stobjbyname 0xe2, a57, a2 + callruntime.ldsendablevar 0x0, 0x39 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass58 + mov v1, v0 + newobjrange 0xe4, 0x1, v1 + stobjbyname 0xe6, a58, a2 + callruntime.ldsendablevar 0x0, 0x3a + sta v0 + throw.undefinedifholewithname TopLevelSendableClass59 + mov v1, v0 + newobjrange 0xe8, 0x1, v1 + stobjbyname 0xea, a59, a2 + callruntime.ldsendablevar 0x0, 0x3b + sta v0 + throw.undefinedifholewithname TopLevelSendableClass60 + mov v1, v0 + newobjrange 0xec, 0x1, v1 + stobjbyname 0xee, a60, a2 + callruntime.ldsendablevar 0x0, 0x3c + sta v0 + throw.undefinedifholewithname TopLevelSendableClass61 + mov v1, v0 + newobjrange 0xf0, 0x1, v1 + stobjbyname 0xf2, a61, a2 + callruntime.ldsendablevar 0x0, 0x3d + sta v0 + throw.undefinedifholewithname TopLevelSendableClass62 + mov v1, v0 + newobjrange 0xf4, 0x1, v1 + stobjbyname 0xf6, a62, a2 + callruntime.ldsendablevar 0x0, 0x3e + sta v0 + throw.undefinedifholewithname TopLevelSendableClass63 + mov v1, v0 + newobjrange 0xf8, 0x1, v1 + stobjbyname 0xfa, a63, a2 + callruntime.ldsendablevar 0x0, 0x3f + sta v0 + throw.undefinedifholewithname TopLevelSendableClass64 + mov v1, v0 + newobjrange 0xfc, 0x1, v1 + stobjbyname 0x100, a64, a2 + callruntime.ldsendablevar 0x0, 0x40 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass65 + mov v1, v0 + newobjrange 0x102, 0x1, v1 + stobjbyname 0x104, a65, a2 + callruntime.ldsendablevar 0x0, 0x41 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass66 + mov v1, v0 + newobjrange 0x106, 0x1, v1 + stobjbyname 0x108, a66, a2 + callruntime.ldsendablevar 0x0, 0x42 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass67 + mov v1, v0 + newobjrange 0x10a, 0x1, v1 + stobjbyname 0x10c, a67, a2 + callruntime.ldsendablevar 0x0, 0x43 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass68 + mov v1, v0 + newobjrange 0x10e, 0x1, v1 + stobjbyname 0x110, a68, a2 + callruntime.ldsendablevar 0x0, 0x44 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass69 + mov v1, v0 + newobjrange 0x112, 0x1, v1 + stobjbyname 0x114, a69, a2 + callruntime.ldsendablevar 0x0, 0x45 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass70 + mov v1, v0 + newobjrange 0x116, 0x1, v1 + stobjbyname 0x118, a70, a2 + callruntime.ldsendablevar 0x0, 0x46 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass71 + mov v1, v0 + newobjrange 0x11a, 0x1, v1 + stobjbyname 0x11c, a71, a2 + callruntime.ldsendablevar 0x0, 0x47 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass72 + mov v1, v0 + newobjrange 0x11e, 0x1, v1 + stobjbyname 0x120, a72, a2 + callruntime.ldsendablevar 0x0, 0x48 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass73 + mov v1, v0 + newobjrange 0x122, 0x1, v1 + stobjbyname 0x124, a73, a2 + callruntime.ldsendablevar 0x0, 0x49 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass74 + mov v1, v0 + newobjrange 0x126, 0x1, v1 + stobjbyname 0x128, a74, a2 + callruntime.ldsendablevar 0x0, 0x4a + sta v0 + throw.undefinedifholewithname TopLevelSendableClass75 + mov v1, v0 + newobjrange 0x12a, 0x1, v1 + stobjbyname 0x12c, a75, a2 + callruntime.ldsendablevar 0x0, 0x4b + sta v0 + throw.undefinedifholewithname TopLevelSendableClass76 + mov v1, v0 + newobjrange 0x12e, 0x1, v1 + stobjbyname 0x130, a76, a2 + callruntime.ldsendablevar 0x0, 0x4c + sta v0 + throw.undefinedifholewithname TopLevelSendableClass77 + mov v1, v0 + newobjrange 0x132, 0x1, v1 + stobjbyname 0x134, a77, a2 + callruntime.ldsendablevar 0x0, 0x4d + sta v0 + throw.undefinedifholewithname TopLevelSendableClass78 + mov v1, v0 + newobjrange 0x136, 0x1, v1 + stobjbyname 0x138, a78, a2 + callruntime.ldsendablevar 0x0, 0x4e + sta v0 + throw.undefinedifholewithname TopLevelSendableClass79 + mov v1, v0 + newobjrange 0x13a, 0x1, v1 + stobjbyname 0x13c, a79, a2 + callruntime.ldsendablevar 0x0, 0x4f + sta v0 + throw.undefinedifholewithname TopLevelSendableClass80 + mov v1, v0 + newobjrange 0x13e, 0x1, v1 + stobjbyname 0x140, a80, a2 + callruntime.ldsendablevar 0x0, 0x50 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass81 + mov v1, v0 + newobjrange 0x142, 0x1, v1 + stobjbyname 0x144, a81, a2 + callruntime.ldsendablevar 0x0, 0x51 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass82 + mov v1, v0 + newobjrange 0x146, 0x1, v1 + stobjbyname 0x148, a82, a2 + callruntime.ldsendablevar 0x0, 0x52 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass83 + mov v1, v0 + newobjrange 0x14a, 0x1, v1 + stobjbyname 0x14c, a83, a2 + callruntime.ldsendablevar 0x0, 0x53 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass84 + mov v1, v0 + newobjrange 0x14e, 0x1, v1 + stobjbyname 0x150, a84, a2 + callruntime.ldsendablevar 0x0, 0x54 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass85 + mov v1, v0 + newobjrange 0x152, 0x1, v1 + stobjbyname 0x154, a85, a2 + callruntime.ldsendablevar 0x0, 0x55 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass86 + mov v1, v0 + newobjrange 0x156, 0x1, v1 + stobjbyname 0x158, a86, a2 + callruntime.ldsendablevar 0x0, 0x56 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass87 + mov v1, v0 + newobjrange 0x15a, 0x1, v1 + stobjbyname 0x15c, a87, a2 + callruntime.ldsendablevar 0x0, 0x57 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass88 + mov v1, v0 + newobjrange 0x15e, 0x1, v1 + stobjbyname 0x160, a88, a2 + callruntime.ldsendablevar 0x0, 0x58 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass89 + mov v1, v0 + newobjrange 0x162, 0x1, v1 + stobjbyname 0x164, a89, a2 + callruntime.ldsendablevar 0x0, 0x59 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass90 + mov v1, v0 + newobjrange 0x166, 0x1, v1 + stobjbyname 0x168, a90, a2 + callruntime.ldsendablevar 0x0, 0x5a + sta v0 + throw.undefinedifholewithname TopLevelSendableClass91 + mov v1, v0 + newobjrange 0x16a, 0x1, v1 + stobjbyname 0x16c, a91, a2 + callruntime.ldsendablevar 0x0, 0x5b + sta v0 + throw.undefinedifholewithname TopLevelSendableClass92 + mov v1, v0 + newobjrange 0x16e, 0x1, v1 + stobjbyname 0x170, a92, a2 + callruntime.ldsendablevar 0x0, 0x5c + sta v0 + throw.undefinedifholewithname TopLevelSendableClass93 + mov v1, v0 + newobjrange 0x172, 0x1, v1 + stobjbyname 0x174, a93, a2 + callruntime.ldsendablevar 0x0, 0x5d + sta v0 + throw.undefinedifholewithname TopLevelSendableClass94 + mov v1, v0 + newobjrange 0x176, 0x1, v1 + stobjbyname 0x178, a94, a2 + callruntime.ldsendablevar 0x0, 0x5e + sta v0 + throw.undefinedifholewithname TopLevelSendableClass95 + mov v1, v0 + newobjrange 0x17a, 0x1, v1 + stobjbyname 0x17c, a95, a2 + callruntime.ldsendablevar 0x0, 0x5f + sta v0 + throw.undefinedifholewithname TopLevelSendableClass96 + mov v1, v0 + newobjrange 0x17e, 0x1, v1 + stobjbyname 0x180, a96, a2 + callruntime.ldsendablevar 0x0, 0x60 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass97 + mov v1, v0 + newobjrange 0x182, 0x1, v1 + stobjbyname 0x184, a97, a2 + callruntime.ldsendablevar 0x0, 0x61 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass98 + mov v1, v0 + newobjrange 0x186, 0x1, v1 + stobjbyname 0x188, a98, a2 + callruntime.ldsendablevar 0x0, 0x62 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass99 + mov v1, v0 + newobjrange 0x18a, 0x1, v1 + stobjbyname 0x18c, a99, a2 + callruntime.ldsendablevar 0x0, 0x63 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass100 + mov v1, v0 + newobjrange 0x18e, 0x1, v1 + stobjbyname 0x190, a100, a2 + callruntime.ldsendablevar 0x0, 0x64 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass101 + mov v1, v0 + newobjrange 0x192, 0x1, v1 + stobjbyname 0x194, a101, a2 + callruntime.ldsendablevar 0x0, 0x65 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass102 + mov v1, v0 + newobjrange 0x196, 0x1, v1 + stobjbyname 0x198, a102, a2 + callruntime.ldsendablevar 0x0, 0x66 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass103 + mov v1, v0 + newobjrange 0x19a, 0x1, v1 + stobjbyname 0x19c, a103, a2 + callruntime.ldsendablevar 0x0, 0x67 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass104 + mov v1, v0 + newobjrange 0x19e, 0x1, v1 + stobjbyname 0x1a0, a104, a2 + callruntime.ldsendablevar 0x0, 0x68 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass105 + mov v1, v0 + newobjrange 0x1a2, 0x1, v1 + stobjbyname 0x1a4, a105, a2 + callruntime.ldsendablevar 0x0, 0x69 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass106 + mov v1, v0 + newobjrange 0x1a6, 0x1, v1 + stobjbyname 0x1a8, a106, a2 + callruntime.ldsendablevar 0x0, 0x6a + sta v0 + throw.undefinedifholewithname TopLevelSendableClass107 + mov v1, v0 + newobjrange 0x1aa, 0x1, v1 + stobjbyname 0x1ac, a107, a2 + callruntime.ldsendablevar 0x0, 0x6b + sta v0 + throw.undefinedifholewithname TopLevelSendableClass108 + mov v1, v0 + newobjrange 0x1ae, 0x1, v1 + stobjbyname 0x1b0, a108, a2 + callruntime.ldsendablevar 0x0, 0x6c + sta v0 + throw.undefinedifholewithname TopLevelSendableClass109 + mov v1, v0 + newobjrange 0x1b2, 0x1, v1 + stobjbyname 0x1b4, a109, a2 + callruntime.ldsendablevar 0x0, 0x6d + sta v0 + throw.undefinedifholewithname TopLevelSendableClass110 + mov v1, v0 + newobjrange 0x1b6, 0x1, v1 + stobjbyname 0x1b8, a110, a2 + callruntime.ldsendablevar 0x0, 0x6e + sta v0 + throw.undefinedifholewithname TopLevelSendableClass111 + mov v1, v0 + newobjrange 0x1ba, 0x1, v1 + stobjbyname 0x1bc, a111, a2 + callruntime.ldsendablevar 0x0, 0x6f + sta v0 + throw.undefinedifholewithname TopLevelSendableClass112 + mov v1, v0 + newobjrange 0x1be, 0x1, v1 + stobjbyname 0x1c0, a112, a2 + callruntime.ldsendablevar 0x0, 0x70 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass113 + mov v1, v0 + newobjrange 0x1c2, 0x1, v1 + stobjbyname 0x1c4, a113, a2 + callruntime.ldsendablevar 0x0, 0x71 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass114 + mov v1, v0 + newobjrange 0x1c6, 0x1, v1 + stobjbyname 0x1c8, a114, a2 + callruntime.ldsendablevar 0x0, 0x72 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass115 + mov v1, v0 + newobjrange 0x1ca, 0x1, v1 + stobjbyname 0x1cc, a115, a2 + callruntime.ldsendablevar 0x0, 0x73 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass116 + mov v1, v0 + newobjrange 0x1ce, 0x1, v1 + stobjbyname 0x1d0, a116, a2 + callruntime.ldsendablevar 0x0, 0x74 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass117 + mov v1, v0 + newobjrange 0x1d2, 0x1, v1 + stobjbyname 0x1d4, a117, a2 + callruntime.ldsendablevar 0x0, 0x75 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass118 + mov v1, v0 + newobjrange 0x1d6, 0x1, v1 + stobjbyname 0x1d8, a118, a2 + callruntime.ldsendablevar 0x0, 0x76 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass119 + mov v1, v0 + newobjrange 0x1da, 0x1, v1 + stobjbyname 0x1dc, a119, a2 + callruntime.ldsendablevar 0x0, 0x77 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass120 + mov v1, v0 + newobjrange 0x1de, 0x1, v1 + stobjbyname 0x1e0, a120, a2 + callruntime.ldsendablevar 0x0, 0x78 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass121 + mov v1, v0 + newobjrange 0x1e2, 0x1, v1 + stobjbyname 0x1e4, a121, a2 + callruntime.ldsendablevar 0x0, 0x79 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass122 + mov v1, v0 + newobjrange 0x1e6, 0x1, v1 + stobjbyname 0x1e8, a122, a2 + callruntime.ldsendablevar 0x0, 0x7a + sta v0 + throw.undefinedifholewithname TopLevelSendableClass123 + mov v1, v0 + newobjrange 0x1ea, 0x1, v1 + stobjbyname 0x1ec, a123, a2 + callruntime.ldsendablevar 0x0, 0x7b + sta v0 + throw.undefinedifholewithname TopLevelSendableClass124 + mov v1, v0 + newobjrange 0x1ee, 0x1, v1 + stobjbyname 0x1f0, a124, a2 + callruntime.ldsendablevar 0x0, 0x7c + sta v0 + throw.undefinedifholewithname TopLevelSendableClass125 + mov v1, v0 + newobjrange 0x1f2, 0x1, v1 + stobjbyname 0x1f4, a125, a2 + callruntime.ldsendablevar 0x0, 0x7d + sta v0 + throw.undefinedifholewithname TopLevelSendableClass126 + mov v1, v0 + newobjrange 0x1f6, 0x1, v1 + stobjbyname 0x1f8, a126, a2 + callruntime.ldsendablevar 0x0, 0x7e + sta v0 + throw.undefinedifholewithname TopLevelSendableClass127 + mov v1, v0 + newobjrange 0x1fa, 0x1, v1 + stobjbyname 0x1fc, a127, a2 + callruntime.ldsendablevar 0x0, 0x7f + sta v0 + throw.undefinedifholewithname TopLevelSendableClass128 + mov v1, v0 + newobjrange 0x1fe, 0x1, v1 + stobjbyname 0x200, a128, a2 + callruntime.wideldsendablevar 0x0, 0x80 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass129 + mov v1, v0 + newobjrange 0x202, 0x1, v1 + stobjbyname 0x204, a129, a2 + callruntime.wideldsendablevar 0x0, 0x81 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass130 + mov v1, v0 + newobjrange 0x206, 0x1, v1 + stobjbyname 0x208, a130, a2 + callruntime.wideldsendablevar 0x0, 0x82 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass131 + mov v1, v0 + newobjrange 0x20a, 0x1, v1 + stobjbyname 0x20c, a131, a2 + callruntime.wideldsendablevar 0x0, 0x83 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass132 + mov v1, v0 + newobjrange 0x20e, 0x1, v1 + stobjbyname 0x210, a132, a2 + callruntime.wideldsendablevar 0x0, 0x84 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass133 + mov v1, v0 + newobjrange 0x212, 0x1, v1 + stobjbyname 0x214, a133, a2 + callruntime.wideldsendablevar 0x0, 0x85 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass134 + mov v1, v0 + newobjrange 0x216, 0x1, v1 + stobjbyname 0x218, a134, a2 + callruntime.wideldsendablevar 0x0, 0x86 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass135 + mov v1, v0 + newobjrange 0x21a, 0x1, v1 + stobjbyname 0x21c, a135, a2 + callruntime.wideldsendablevar 0x0, 0x87 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass136 + mov v1, v0 + newobjrange 0x21e, 0x1, v1 + stobjbyname 0x220, a136, a2 + callruntime.wideldsendablevar 0x0, 0x88 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass137 + mov v1, v0 + newobjrange 0x222, 0x1, v1 + stobjbyname 0x224, a137, a2 + callruntime.wideldsendablevar 0x0, 0x89 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass138 + mov v1, v0 + newobjrange 0x226, 0x1, v1 + stobjbyname 0x228, a138, a2 + callruntime.wideldsendablevar 0x0, 0x8a + sta v0 + throw.undefinedifholewithname TopLevelSendableClass139 + mov v1, v0 + newobjrange 0x22a, 0x1, v1 + stobjbyname 0x22c, a139, a2 + callruntime.wideldsendablevar 0x0, 0x8b + sta v0 + throw.undefinedifholewithname TopLevelSendableClass140 + mov v1, v0 + newobjrange 0x22e, 0x1, v1 + stobjbyname 0x230, a140, a2 + callruntime.wideldsendablevar 0x0, 0x8c + sta v0 + throw.undefinedifholewithname TopLevelSendableClass141 + mov v1, v0 + newobjrange 0x232, 0x1, v1 + stobjbyname 0x234, a141, a2 + callruntime.wideldsendablevar 0x0, 0x8d + sta v0 + throw.undefinedifholewithname TopLevelSendableClass142 + mov v1, v0 + newobjrange 0x236, 0x1, v1 + stobjbyname 0x238, a142, a2 + callruntime.wideldsendablevar 0x0, 0x8e + sta v0 + throw.undefinedifholewithname TopLevelSendableClass143 + mov v1, v0 + newobjrange 0x23a, 0x1, v1 + stobjbyname 0x23c, a143, a2 + callruntime.wideldsendablevar 0x0, 0x8f + sta v0 + throw.undefinedifholewithname TopLevelSendableClass144 + mov v1, v0 + newobjrange 0x23e, 0x1, v1 + stobjbyname 0x240, a144, a2 + callruntime.wideldsendablevar 0x0, 0x90 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass145 + mov v1, v0 + newobjrange 0x242, 0x1, v1 + stobjbyname 0x244, a145, a2 + callruntime.wideldsendablevar 0x0, 0x91 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass146 + mov v1, v0 + newobjrange 0x246, 0x1, v1 + stobjbyname 0x248, a146, a2 + callruntime.wideldsendablevar 0x0, 0x92 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass147 + mov v1, v0 + newobjrange 0x24a, 0x1, v1 + stobjbyname 0x24c, a147, a2 + callruntime.wideldsendablevar 0x0, 0x93 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass148 + mov v1, v0 + newobjrange 0x24e, 0x1, v1 + stobjbyname 0x250, a148, a2 + callruntime.wideldsendablevar 0x0, 0x94 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass149 + mov v1, v0 + newobjrange 0x252, 0x1, v1 + stobjbyname 0x254, a149, a2 + callruntime.wideldsendablevar 0x0, 0x95 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass150 + mov v1, v0 + newobjrange 0x256, 0x1, v1 + stobjbyname 0x258, a150, a2 + callruntime.wideldsendablevar 0x0, 0x96 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass151 + mov v1, v0 + newobjrange 0x25a, 0x1, v1 + stobjbyname 0x25c, a151, a2 + callruntime.wideldsendablevar 0x0, 0x97 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass152 + mov v1, v0 + newobjrange 0x25e, 0x1, v1 + stobjbyname 0x260, a152, a2 + callruntime.wideldsendablevar 0x0, 0x98 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass153 + mov v1, v0 + newobjrange 0x262, 0x1, v1 + stobjbyname 0x264, a153, a2 + callruntime.wideldsendablevar 0x0, 0x99 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass154 + mov v1, v0 + newobjrange 0x266, 0x1, v1 + stobjbyname 0x268, a154, a2 + callruntime.wideldsendablevar 0x0, 0x9a + sta v0 + throw.undefinedifholewithname TopLevelSendableClass155 + mov v1, v0 + newobjrange 0x26a, 0x1, v1 + stobjbyname 0x26c, a155, a2 + callruntime.wideldsendablevar 0x0, 0x9b + sta v0 + throw.undefinedifholewithname TopLevelSendableClass156 + mov v1, v0 + newobjrange 0x26e, 0x1, v1 + stobjbyname 0x270, a156, a2 + callruntime.wideldsendablevar 0x0, 0x9c + sta v0 + throw.undefinedifholewithname TopLevelSendableClass157 + mov v1, v0 + newobjrange 0x272, 0x1, v1 + stobjbyname 0x274, a157, a2 + callruntime.wideldsendablevar 0x0, 0x9d + sta v0 + throw.undefinedifholewithname TopLevelSendableClass158 + mov v1, v0 + newobjrange 0x276, 0x1, v1 + stobjbyname 0x278, a158, a2 + callruntime.wideldsendablevar 0x0, 0x9e + sta v0 + throw.undefinedifholewithname TopLevelSendableClass159 + mov v1, v0 + newobjrange 0x27a, 0x1, v1 + stobjbyname 0x27c, a159, a2 + callruntime.wideldsendablevar 0x0, 0x9f + sta v0 + throw.undefinedifholewithname TopLevelSendableClass160 + mov v1, v0 + newobjrange 0x27e, 0x1, v1 + stobjbyname 0x280, a160, a2 + callruntime.wideldsendablevar 0x0, 0xa0 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass161 + mov v1, v0 + newobjrange 0x282, 0x1, v1 + stobjbyname 0x284, a161, a2 + callruntime.wideldsendablevar 0x0, 0xa1 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass162 + mov v1, v0 + newobjrange 0x286, 0x1, v1 + stobjbyname 0x288, a162, a2 + callruntime.wideldsendablevar 0x0, 0xa2 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass163 + mov v1, v0 + newobjrange 0x28a, 0x1, v1 + stobjbyname 0x28c, a163, a2 + callruntime.wideldsendablevar 0x0, 0xa3 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass164 + mov v1, v0 + newobjrange 0x28e, 0x1, v1 + stobjbyname 0x290, a164, a2 + callruntime.wideldsendablevar 0x0, 0xa4 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass165 + mov v1, v0 + newobjrange 0x292, 0x1, v1 + stobjbyname 0x294, a165, a2 + callruntime.wideldsendablevar 0x0, 0xa5 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass166 + mov v1, v0 + newobjrange 0x296, 0x1, v1 + stobjbyname 0x298, a166, a2 + callruntime.wideldsendablevar 0x0, 0xa6 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass167 + mov v1, v0 + newobjrange 0x29a, 0x1, v1 + stobjbyname 0x29c, a167, a2 + callruntime.wideldsendablevar 0x0, 0xa7 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass168 + mov v1, v0 + newobjrange 0x29e, 0x1, v1 + stobjbyname 0x2a0, a168, a2 + callruntime.wideldsendablevar 0x0, 0xa8 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass169 + mov v1, v0 + newobjrange 0x2a2, 0x1, v1 + stobjbyname 0x2a4, a169, a2 + callruntime.wideldsendablevar 0x0, 0xa9 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass170 + mov v1, v0 + newobjrange 0x2a6, 0x1, v1 + stobjbyname 0x2a8, a170, a2 + callruntime.wideldsendablevar 0x0, 0xaa + sta v0 + throw.undefinedifholewithname TopLevelSendableClass171 + mov v1, v0 + newobjrange 0x2aa, 0x1, v1 + stobjbyname 0x2ac, a171, a2 + callruntime.wideldsendablevar 0x0, 0xab + sta v0 + throw.undefinedifholewithname TopLevelSendableClass172 + mov v1, v0 + newobjrange 0x2ae, 0x1, v1 + stobjbyname 0x2b0, a172, a2 + callruntime.wideldsendablevar 0x0, 0xac + sta v0 + throw.undefinedifholewithname TopLevelSendableClass173 + mov v1, v0 + newobjrange 0x2b2, 0x1, v1 + stobjbyname 0x2b4, a173, a2 + callruntime.wideldsendablevar 0x0, 0xad + sta v0 + throw.undefinedifholewithname TopLevelSendableClass174 + mov v1, v0 + newobjrange 0x2b6, 0x1, v1 + stobjbyname 0x2b8, a174, a2 + callruntime.wideldsendablevar 0x0, 0xae + sta v0 + throw.undefinedifholewithname TopLevelSendableClass175 + mov v1, v0 + newobjrange 0x2ba, 0x1, v1 + stobjbyname 0x2bc, a175, a2 + callruntime.wideldsendablevar 0x0, 0xaf + sta v0 + throw.undefinedifholewithname TopLevelSendableClass176 + mov v1, v0 + newobjrange 0x2be, 0x1, v1 + stobjbyname 0x2c0, a176, a2 + callruntime.wideldsendablevar 0x0, 0xb0 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass177 + mov v1, v0 + newobjrange 0x2c2, 0x1, v1 + stobjbyname 0x2c4, a177, a2 + callruntime.wideldsendablevar 0x0, 0xb1 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass178 + mov v1, v0 + newobjrange 0x2c6, 0x1, v1 + stobjbyname 0x2c8, a178, a2 + callruntime.wideldsendablevar 0x0, 0xb2 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass179 + mov v1, v0 + newobjrange 0x2ca, 0x1, v1 + stobjbyname 0x2cc, a179, a2 + callruntime.wideldsendablevar 0x0, 0xb3 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass180 + mov v1, v0 + newobjrange 0x2ce, 0x1, v1 + stobjbyname 0x2d0, a180, a2 + callruntime.wideldsendablevar 0x0, 0xb4 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass181 + mov v1, v0 + newobjrange 0x2d2, 0x1, v1 + stobjbyname 0x2d4, a181, a2 + callruntime.wideldsendablevar 0x0, 0xb5 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass182 + mov v1, v0 + newobjrange 0x2d6, 0x1, v1 + stobjbyname 0x2d8, a182, a2 + callruntime.wideldsendablevar 0x0, 0xb6 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass183 + mov v1, v0 + newobjrange 0x2da, 0x1, v1 + stobjbyname 0x2dc, a183, a2 + callruntime.wideldsendablevar 0x0, 0xb7 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass184 + mov v1, v0 + newobjrange 0x2de, 0x1, v1 + stobjbyname 0x2e0, a184, a2 + callruntime.wideldsendablevar 0x0, 0xb8 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass185 + mov v1, v0 + newobjrange 0x2e2, 0x1, v1 + stobjbyname 0x2e4, a185, a2 + callruntime.wideldsendablevar 0x0, 0xb9 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass186 + mov v1, v0 + newobjrange 0x2e6, 0x1, v1 + stobjbyname 0x2e8, a186, a2 + callruntime.wideldsendablevar 0x0, 0xba + sta v0 + throw.undefinedifholewithname TopLevelSendableClass187 + mov v1, v0 + newobjrange 0x2ea, 0x1, v1 + stobjbyname 0x2ec, a187, a2 + callruntime.wideldsendablevar 0x0, 0xbb + sta v0 + throw.undefinedifholewithname TopLevelSendableClass188 + mov v1, v0 + newobjrange 0x2ee, 0x1, v1 + stobjbyname 0x2f0, a188, a2 + callruntime.wideldsendablevar 0x0, 0xbc + sta v0 + throw.undefinedifholewithname TopLevelSendableClass189 + mov v1, v0 + newobjrange 0x2f2, 0x1, v1 + stobjbyname 0x2f4, a189, a2 + callruntime.wideldsendablevar 0x0, 0xbd + sta v0 + throw.undefinedifholewithname TopLevelSendableClass190 + mov v1, v0 + newobjrange 0x2f6, 0x1, v1 + stobjbyname 0x2f8, a190, a2 + callruntime.wideldsendablevar 0x0, 0xbe + sta v0 + throw.undefinedifholewithname TopLevelSendableClass191 + mov v1, v0 + newobjrange 0x2fa, 0x1, v1 + stobjbyname 0x2fc, a191, a2 + callruntime.wideldsendablevar 0x0, 0xbf + sta v0 + throw.undefinedifholewithname TopLevelSendableClass192 + mov v1, v0 + newobjrange 0x2fe, 0x1, v1 + stobjbyname 0x300, a192, a2 + callruntime.wideldsendablevar 0x0, 0xc0 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass193 + mov v1, v0 + newobjrange 0x302, 0x1, v1 + stobjbyname 0x304, a193, a2 + callruntime.wideldsendablevar 0x0, 0xc1 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass194 + mov v1, v0 + newobjrange 0x306, 0x1, v1 + stobjbyname 0x308, a194, a2 + callruntime.wideldsendablevar 0x0, 0xc2 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass195 + mov v1, v0 + newobjrange 0x30a, 0x1, v1 + stobjbyname 0x30c, a195, a2 + callruntime.wideldsendablevar 0x0, 0xc3 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass196 + mov v1, v0 + newobjrange 0x30e, 0x1, v1 + stobjbyname 0x310, a196, a2 + callruntime.wideldsendablevar 0x0, 0xc4 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass197 + mov v1, v0 + newobjrange 0x312, 0x1, v1 + stobjbyname 0x314, a197, a2 + callruntime.wideldsendablevar 0x0, 0xc5 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass198 + mov v1, v0 + newobjrange 0x316, 0x1, v1 + stobjbyname 0x318, a198, a2 + callruntime.wideldsendablevar 0x0, 0xc6 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass199 + mov v1, v0 + newobjrange 0x31a, 0x1, v1 + stobjbyname 0x31c, a199, a2 + callruntime.wideldsendablevar 0x0, 0xc7 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass200 + mov v1, v0 + newobjrange 0x31e, 0x1, v1 + stobjbyname 0x320, a200, a2 + callruntime.wideldsendablevar 0x0, 0xc8 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass201 + mov v1, v0 + newobjrange 0x322, 0x1, v1 + stobjbyname 0x324, a201, a2 + callruntime.wideldsendablevar 0x0, 0xc9 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass202 + mov v1, v0 + newobjrange 0x326, 0x1, v1 + stobjbyname 0x328, a202, a2 + callruntime.wideldsendablevar 0x0, 0xca + sta v0 + throw.undefinedifholewithname TopLevelSendableClass203 + mov v1, v0 + newobjrange 0x32a, 0x1, v1 + stobjbyname 0x32c, a203, a2 + callruntime.wideldsendablevar 0x0, 0xcb + sta v0 + throw.undefinedifholewithname TopLevelSendableClass204 + mov v1, v0 + newobjrange 0x32e, 0x1, v1 + stobjbyname 0x330, a204, a2 + callruntime.wideldsendablevar 0x0, 0xcc + sta v0 + throw.undefinedifholewithname TopLevelSendableClass205 + mov v1, v0 + newobjrange 0x332, 0x1, v1 + stobjbyname 0x334, a205, a2 + callruntime.wideldsendablevar 0x0, 0xcd + sta v0 + throw.undefinedifholewithname TopLevelSendableClass206 + mov v1, v0 + newobjrange 0x336, 0x1, v1 + stobjbyname 0x338, a206, a2 + callruntime.wideldsendablevar 0x0, 0xce + sta v0 + throw.undefinedifholewithname TopLevelSendableClass207 + mov v1, v0 + newobjrange 0x33a, 0x1, v1 + stobjbyname 0x33c, a207, a2 + callruntime.wideldsendablevar 0x0, 0xcf + sta v0 + throw.undefinedifholewithname TopLevelSendableClass208 + mov v1, v0 + newobjrange 0x33e, 0x1, v1 + stobjbyname 0x340, a208, a2 + callruntime.wideldsendablevar 0x0, 0xd0 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass209 + mov v1, v0 + newobjrange 0x342, 0x1, v1 + stobjbyname 0x344, a209, a2 + callruntime.wideldsendablevar 0x0, 0xd1 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass210 + mov v1, v0 + newobjrange 0x346, 0x1, v1 + stobjbyname 0x348, a210, a2 + callruntime.wideldsendablevar 0x0, 0xd2 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass211 + mov v1, v0 + newobjrange 0x34a, 0x1, v1 + stobjbyname 0x34c, a211, a2 + callruntime.wideldsendablevar 0x0, 0xd3 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass212 + mov v1, v0 + newobjrange 0x34e, 0x1, v1 + stobjbyname 0x350, a212, a2 + callruntime.wideldsendablevar 0x0, 0xd4 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass213 + mov v1, v0 + newobjrange 0x352, 0x1, v1 + stobjbyname 0x354, a213, a2 + callruntime.wideldsendablevar 0x0, 0xd5 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass214 + mov v1, v0 + newobjrange 0x356, 0x1, v1 + stobjbyname 0x358, a214, a2 + callruntime.wideldsendablevar 0x0, 0xd6 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass215 + mov v1, v0 + newobjrange 0x35a, 0x1, v1 + stobjbyname 0x35c, a215, a2 + callruntime.wideldsendablevar 0x0, 0xd7 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass216 + mov v1, v0 + newobjrange 0x35e, 0x1, v1 + stobjbyname 0x360, a216, a2 + callruntime.wideldsendablevar 0x0, 0xd8 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass217 + mov v1, v0 + newobjrange 0x362, 0x1, v1 + stobjbyname 0x364, a217, a2 + callruntime.wideldsendablevar 0x0, 0xd9 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass218 + mov v1, v0 + newobjrange 0x366, 0x1, v1 + stobjbyname 0x368, a218, a2 + callruntime.wideldsendablevar 0x0, 0xda + sta v0 + throw.undefinedifholewithname TopLevelSendableClass219 + mov v1, v0 + newobjrange 0x36a, 0x1, v1 + stobjbyname 0x36c, a219, a2 + callruntime.wideldsendablevar 0x0, 0xdb + sta v0 + throw.undefinedifholewithname TopLevelSendableClass220 + mov v1, v0 + newobjrange 0x36e, 0x1, v1 + stobjbyname 0x370, a220, a2 + callruntime.wideldsendablevar 0x0, 0xdc + sta v0 + throw.undefinedifholewithname TopLevelSendableClass221 + mov v1, v0 + newobjrange 0x372, 0x1, v1 + stobjbyname 0x374, a221, a2 + callruntime.wideldsendablevar 0x0, 0xdd + sta v0 + throw.undefinedifholewithname TopLevelSendableClass222 + mov v1, v0 + newobjrange 0x376, 0x1, v1 + stobjbyname 0x378, a222, a2 + callruntime.wideldsendablevar 0x0, 0xde + sta v0 + throw.undefinedifholewithname TopLevelSendableClass223 + mov v1, v0 + newobjrange 0x37a, 0x1, v1 + stobjbyname 0x37c, a223, a2 + callruntime.wideldsendablevar 0x0, 0xdf + sta v0 + throw.undefinedifholewithname TopLevelSendableClass224 + mov v1, v0 + newobjrange 0x37e, 0x1, v1 + stobjbyname 0x380, a224, a2 + callruntime.wideldsendablevar 0x0, 0xe0 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass225 + mov v1, v0 + newobjrange 0x382, 0x1, v1 + stobjbyname 0x384, a225, a2 + callruntime.wideldsendablevar 0x0, 0xe1 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass226 + mov v1, v0 + newobjrange 0x386, 0x1, v1 + stobjbyname 0x388, a226, a2 + callruntime.wideldsendablevar 0x0, 0xe2 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass227 + mov v1, v0 + newobjrange 0x38a, 0x1, v1 + stobjbyname 0x38c, a227, a2 + callruntime.wideldsendablevar 0x0, 0xe3 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass228 + mov v1, v0 + newobjrange 0x38e, 0x1, v1 + stobjbyname 0x390, a228, a2 + callruntime.wideldsendablevar 0x0, 0xe4 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass229 + mov v1, v0 + newobjrange 0x392, 0x1, v1 + stobjbyname 0x394, a229, a2 + callruntime.wideldsendablevar 0x0, 0xe5 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass230 + mov v1, v0 + newobjrange 0x396, 0x1, v1 + stobjbyname 0x398, a230, a2 + callruntime.wideldsendablevar 0x0, 0xe6 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass231 + mov v1, v0 + newobjrange 0x39a, 0x1, v1 + stobjbyname 0x39c, a231, a2 + callruntime.wideldsendablevar 0x0, 0xe7 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass232 + mov v1, v0 + newobjrange 0x39e, 0x1, v1 + stobjbyname 0x3a0, a232, a2 + callruntime.wideldsendablevar 0x0, 0xe8 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass233 + mov v1, v0 + newobjrange 0x3a2, 0x1, v1 + stobjbyname 0x3a4, a233, a2 + callruntime.wideldsendablevar 0x0, 0xe9 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass234 + mov v1, v0 + newobjrange 0x3a6, 0x1, v1 + stobjbyname 0x3a8, a234, a2 + callruntime.wideldsendablevar 0x0, 0xea + sta v0 + throw.undefinedifholewithname TopLevelSendableClass235 + mov v1, v0 + newobjrange 0x3aa, 0x1, v1 + stobjbyname 0x3ac, a235, a2 + callruntime.wideldsendablevar 0x0, 0xeb + sta v0 + throw.undefinedifholewithname TopLevelSendableClass236 + mov v1, v0 + newobjrange 0x3ae, 0x1, v1 + stobjbyname 0x3b0, a236, a2 + callruntime.wideldsendablevar 0x0, 0xec + sta v0 + throw.undefinedifholewithname TopLevelSendableClass237 + mov v1, v0 + newobjrange 0x3b2, 0x1, v1 + stobjbyname 0x3b4, a237, a2 + callruntime.wideldsendablevar 0x0, 0xed + sta v0 + throw.undefinedifholewithname TopLevelSendableClass238 + mov v1, v0 + newobjrange 0x3b6, 0x1, v1 + stobjbyname 0x3b8, a238, a2 + callruntime.wideldsendablevar 0x0, 0xee + sta v0 + throw.undefinedifholewithname TopLevelSendableClass239 + mov v1, v0 + newobjrange 0x3ba, 0x1, v1 + stobjbyname 0x3bc, a239, a2 + callruntime.wideldsendablevar 0x0, 0xef + sta v0 + throw.undefinedifholewithname TopLevelSendableClass240 + mov v1, v0 + newobjrange 0x3be, 0x1, v1 + stobjbyname 0x3c0, a240, a2 + callruntime.wideldsendablevar 0x0, 0xf0 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass241 + mov v1, v0 + newobjrange 0x3c2, 0x1, v1 + stobjbyname 0x3c4, a241, a2 + callruntime.wideldsendablevar 0x0, 0xf1 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass242 + mov v1, v0 + newobjrange 0x3c6, 0x1, v1 + stobjbyname 0x3c8, a242, a2 + callruntime.wideldsendablevar 0x0, 0xf2 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass243 + mov v1, v0 + newobjrange 0x3ca, 0x1, v1 + stobjbyname 0x3cc, a243, a2 + callruntime.wideldsendablevar 0x0, 0xf3 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass244 + mov v1, v0 + newobjrange 0x3ce, 0x1, v1 + stobjbyname 0x3d0, a244, a2 + callruntime.wideldsendablevar 0x0, 0xf4 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass245 + mov v1, v0 + newobjrange 0x3d2, 0x1, v1 + stobjbyname 0x3d4, a245, a2 + callruntime.wideldsendablevar 0x0, 0xf5 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass246 + mov v1, v0 + newobjrange 0x3d6, 0x1, v1 + stobjbyname 0x3d8, a246, a2 + callruntime.wideldsendablevar 0x0, 0xf6 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass247 + mov v1, v0 + newobjrange 0x3da, 0x1, v1 + stobjbyname 0x3dc, a247, a2 + callruntime.wideldsendablevar 0x0, 0xf7 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass248 + mov v1, v0 + newobjrange 0x3de, 0x1, v1 + stobjbyname 0x3e0, a248, a2 + callruntime.wideldsendablevar 0x0, 0xf8 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass249 + mov v1, v0 + newobjrange 0x3e2, 0x1, v1 + stobjbyname 0x3e4, a249, a2 + callruntime.wideldsendablevar 0x0, 0xf9 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass250 + mov v1, v0 + newobjrange 0x3e6, 0x1, v1 + stobjbyname 0x3e8, a250, a2 + callruntime.wideldsendablevar 0x0, 0xfa + sta v0 + throw.undefinedifholewithname TopLevelSendableClass251 + mov v1, v0 + newobjrange 0x3ea, 0x1, v1 + stobjbyname 0x3ec, a251, a2 + callruntime.wideldsendablevar 0x0, 0xfb + sta v0 + throw.undefinedifholewithname TopLevelSendableClass252 + mov v1, v0 + newobjrange 0x3ee, 0x1, v1 + stobjbyname 0x3f0, a252, a2 + callruntime.wideldsendablevar 0x0, 0xfc + sta v0 + throw.undefinedifholewithname TopLevelSendableClass253 + mov v1, v0 + newobjrange 0x3f2, 0x1, v1 + stobjbyname 0x3f4, a253, a2 + callruntime.wideldsendablevar 0x0, 0xfd + sta v0 + throw.undefinedifholewithname TopLevelSendableClass254 + mov v1, v0 + newobjrange 0x3f6, 0x1, v1 + stobjbyname 0x3f8, a254, a2 + callruntime.wideldsendablevar 0x0, 0xfe + sta v0 + throw.undefinedifholewithname TopLevelSendableClass255 + mov v1, v0 + newobjrange 0x3fa, 0x1, v1 + stobjbyname 0x3fc, a255, a2 + lda a2 + ldobjbyname 0x3fe, a1 + ldobjbyname 0x400, o + stobjbyname 0x402, u, a2 + lda.str wide_sendable_test + stobjbyname 0x404, v, a2 + lda a2 + return +label_2: +} + +slotNum = 0x108 +.language ECMAScript +.function any .func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + callruntime.widenewsendableenv 0xff + ldhole + sta v0 + callruntime.definesendableclass 0x2, .#~@0=#TopLevelSendableClass1, _3, 0x0, v0 + callruntime.stsendablevar 0x0, 0x0 + ldhole + sta v0 + callruntime.definesendableclass 0x3, .#~@1=#TopLevelSendableClass2, _5, 0x0, v0 + callruntime.stsendablevar 0x0, 0x1 + ldhole + sta v0 + callruntime.definesendableclass 0x4, .#~@2=#TopLevelSendableClass3, _7, 0x0, v0 + callruntime.stsendablevar 0x0, 0x2 + ldhole + sta v0 + callruntime.definesendableclass 0x5, .#~@3=#TopLevelSendableClass4, _9, 0x0, v0 + callruntime.stsendablevar 0x0, 0x3 + ldhole + sta v0 + callruntime.definesendableclass 0x6, .#~@4=#TopLevelSendableClass5, _11, 0x0, v0 + callruntime.stsendablevar 0x0, 0x4 + ldhole + sta v0 + callruntime.definesendableclass 0x7, .#~@5=#TopLevelSendableClass6, _13, 0x0, v0 + callruntime.stsendablevar 0x0, 0x5 + ldhole + sta v0 + callruntime.definesendableclass 0x8, .#~@6=#TopLevelSendableClass7, _15, 0x0, v0 + callruntime.stsendablevar 0x0, 0x6 + ldhole + sta v0 + callruntime.definesendableclass 0x9, .#~@7=#TopLevelSendableClass8, _17, 0x0, v0 + callruntime.stsendablevar 0x0, 0x7 + ldhole + sta v0 + callruntime.definesendableclass 0xa, .#~@8=#TopLevelSendableClass9, _19, 0x0, v0 + callruntime.stsendablevar 0x0, 0x8 + ldhole + sta v0 + callruntime.definesendableclass 0xb, .#~@9=#TopLevelSendableClass10, _21, 0x0, v0 + callruntime.stsendablevar 0x0, 0x9 + ldhole + sta v0 + callruntime.definesendableclass 0xc, .#~@a=#TopLevelSendableClass11, _23, 0x0, v0 + callruntime.stsendablevar 0x0, 0xa + ldhole + sta v0 + callruntime.definesendableclass 0xd, .#~@b=#TopLevelSendableClass12, _25, 0x0, v0 + callruntime.stsendablevar 0x0, 0xb + ldhole + sta v0 + callruntime.definesendableclass 0xe, .#~@c=#TopLevelSendableClass13, _27, 0x0, v0 + callruntime.stsendablevar 0x0, 0xc + ldhole + sta v0 + callruntime.definesendableclass 0xf, .#~@d=#TopLevelSendableClass14, _29, 0x0, v0 + callruntime.stsendablevar 0x0, 0xd + ldhole + sta v0 + callruntime.definesendableclass 0x10, .#~@e=#TopLevelSendableClass15, _31, 0x0, v0 + callruntime.stsendablevar 0x0, 0xe + ldhole + sta v0 + callruntime.definesendableclass 0x11, .#~@f=#TopLevelSendableClass16, _33, 0x0, v0 + callruntime.stsendablevar 0x0, 0xf + ldhole + sta v0 + callruntime.definesendableclass 0x12, .#~@10=#TopLevelSendableClass17, _35, 0x0, v0 + callruntime.stsendablevar 0x0, 0x10 + ldhole + sta v0 + callruntime.definesendableclass 0x13, .#~@11=#TopLevelSendableClass18, _37, 0x0, v0 + callruntime.stsendablevar 0x0, 0x11 + ldhole + sta v0 + callruntime.definesendableclass 0x14, .#~@12=#TopLevelSendableClass19, _39, 0x0, v0 + callruntime.stsendablevar 0x0, 0x12 + ldhole + sta v0 + callruntime.definesendableclass 0x15, .#~@13=#TopLevelSendableClass20, _41, 0x0, v0 + callruntime.stsendablevar 0x0, 0x13 + ldhole + sta v0 + callruntime.definesendableclass 0x16, .#~@14=#TopLevelSendableClass21, _43, 0x0, v0 + callruntime.stsendablevar 0x0, 0x14 + ldhole + sta v0 + callruntime.definesendableclass 0x17, .#~@15=#TopLevelSendableClass22, _45, 0x0, v0 + callruntime.stsendablevar 0x0, 0x15 + ldhole + sta v0 + callruntime.definesendableclass 0x18, .#~@16=#TopLevelSendableClass23, _47, 0x0, v0 + callruntime.stsendablevar 0x0, 0x16 + ldhole + sta v0 + callruntime.definesendableclass 0x19, .#~@17=#TopLevelSendableClass24, _49, 0x0, v0 + callruntime.stsendablevar 0x0, 0x17 + ldhole + sta v0 + callruntime.definesendableclass 0x1a, .#~@18=#TopLevelSendableClass25, _51, 0x0, v0 + callruntime.stsendablevar 0x0, 0x18 + ldhole + sta v0 + callruntime.definesendableclass 0x1b, .#~@19=#TopLevelSendableClass26, _53, 0x0, v0 + callruntime.stsendablevar 0x0, 0x19 + ldhole + sta v0 + callruntime.definesendableclass 0x1c, .#~@1a=#TopLevelSendableClass27, _55, 0x0, v0 + callruntime.stsendablevar 0x0, 0x1a + ldhole + sta v0 + callruntime.definesendableclass 0x1d, .#~@1b=#TopLevelSendableClass28, _57, 0x0, v0 + callruntime.stsendablevar 0x0, 0x1b + ldhole + sta v0 + callruntime.definesendableclass 0x1e, .#~@1c=#TopLevelSendableClass29, _59, 0x0, v0 + callruntime.stsendablevar 0x0, 0x1c + ldhole + sta v0 + callruntime.definesendableclass 0x1f, .#~@1d=#TopLevelSendableClass30, _61, 0x0, v0 + callruntime.stsendablevar 0x0, 0x1d + ldhole + sta v0 + callruntime.definesendableclass 0x20, .#~@1e=#TopLevelSendableClass31, _63, 0x0, v0 + callruntime.stsendablevar 0x0, 0x1e + ldhole + sta v0 + callruntime.definesendableclass 0x21, .#~@1f=#TopLevelSendableClass32, _65, 0x0, v0 + callruntime.stsendablevar 0x0, 0x1f + ldhole + sta v0 + callruntime.definesendableclass 0x22, .#~@20=#TopLevelSendableClass33, _67, 0x0, v0 + callruntime.stsendablevar 0x0, 0x20 + ldhole + sta v0 + callruntime.definesendableclass 0x23, .#~@21=#TopLevelSendableClass34, _69, 0x0, v0 + callruntime.stsendablevar 0x0, 0x21 + ldhole + sta v0 + callruntime.definesendableclass 0x24, .#~@22=#TopLevelSendableClass35, _71, 0x0, v0 + callruntime.stsendablevar 0x0, 0x22 + ldhole + sta v0 + callruntime.definesendableclass 0x25, .#~@23=#TopLevelSendableClass36, _73, 0x0, v0 + callruntime.stsendablevar 0x0, 0x23 + ldhole + sta v0 + callruntime.definesendableclass 0x26, .#~@24=#TopLevelSendableClass37, _75, 0x0, v0 + callruntime.stsendablevar 0x0, 0x24 + ldhole + sta v0 + callruntime.definesendableclass 0x27, .#~@25=#TopLevelSendableClass38, _77, 0x0, v0 + callruntime.stsendablevar 0x0, 0x25 + ldhole + sta v0 + callruntime.definesendableclass 0x28, .#~@26=#TopLevelSendableClass39, _79, 0x0, v0 + callruntime.stsendablevar 0x0, 0x26 + ldhole + sta v0 + callruntime.definesendableclass 0x29, .#~@27=#TopLevelSendableClass40, _81, 0x0, v0 + callruntime.stsendablevar 0x0, 0x27 + ldhole + sta v0 + callruntime.definesendableclass 0x2a, .#~@28=#TopLevelSendableClass41, _83, 0x0, v0 + callruntime.stsendablevar 0x0, 0x28 + ldhole + sta v0 + callruntime.definesendableclass 0x2b, .#~@29=#TopLevelSendableClass42, _85, 0x0, v0 + callruntime.stsendablevar 0x0, 0x29 + ldhole + sta v0 + callruntime.definesendableclass 0x2c, .#~@2a=#TopLevelSendableClass43, _87, 0x0, v0 + callruntime.stsendablevar 0x0, 0x2a + ldhole + sta v0 + callruntime.definesendableclass 0x2d, .#~@2b=#TopLevelSendableClass44, _89, 0x0, v0 + callruntime.stsendablevar 0x0, 0x2b + ldhole + sta v0 + callruntime.definesendableclass 0x2e, .#~@2c=#TopLevelSendableClass45, _91, 0x0, v0 + callruntime.stsendablevar 0x0, 0x2c + ldhole + sta v0 + callruntime.definesendableclass 0x2f, .#~@2d=#TopLevelSendableClass46, _93, 0x0, v0 + callruntime.stsendablevar 0x0, 0x2d + ldhole + sta v0 + callruntime.definesendableclass 0x30, .#~@2e=#TopLevelSendableClass47, _95, 0x0, v0 + callruntime.stsendablevar 0x0, 0x2e + ldhole + sta v0 + callruntime.definesendableclass 0x31, .#~@2f=#TopLevelSendableClass48, _97, 0x0, v0 + callruntime.stsendablevar 0x0, 0x2f + ldhole + sta v0 + callruntime.definesendableclass 0x32, .#~@30=#TopLevelSendableClass49, _99, 0x0, v0 + callruntime.stsendablevar 0x0, 0x30 + ldhole + sta v0 + callruntime.definesendableclass 0x33, .#~@31=#TopLevelSendableClass50, _101, 0x0, v0 + callruntime.stsendablevar 0x0, 0x31 + ldhole + sta v0 + callruntime.definesendableclass 0x34, .#~@32=#TopLevelSendableClass51, _103, 0x0, v0 + callruntime.stsendablevar 0x0, 0x32 + ldhole + sta v0 + callruntime.definesendableclass 0x35, .#~@33=#TopLevelSendableClass52, _105, 0x0, v0 + callruntime.stsendablevar 0x0, 0x33 + ldhole + sta v0 + callruntime.definesendableclass 0x36, .#~@34=#TopLevelSendableClass53, _107, 0x0, v0 + callruntime.stsendablevar 0x0, 0x34 + ldhole + sta v0 + callruntime.definesendableclass 0x37, .#~@35=#TopLevelSendableClass54, _109, 0x0, v0 + callruntime.stsendablevar 0x0, 0x35 + ldhole + sta v0 + callruntime.definesendableclass 0x38, .#~@36=#TopLevelSendableClass55, _111, 0x0, v0 + callruntime.stsendablevar 0x0, 0x36 + ldhole + sta v0 + callruntime.definesendableclass 0x39, .#~@37=#TopLevelSendableClass56, _113, 0x0, v0 + callruntime.stsendablevar 0x0, 0x37 + ldhole + sta v0 + callruntime.definesendableclass 0x3a, .#~@38=#TopLevelSendableClass57, _115, 0x0, v0 + callruntime.stsendablevar 0x0, 0x38 + ldhole + sta v0 + callruntime.definesendableclass 0x3b, .#~@39=#TopLevelSendableClass58, _117, 0x0, v0 + callruntime.stsendablevar 0x0, 0x39 + ldhole + sta v0 + callruntime.definesendableclass 0x3c, .#~@3a=#TopLevelSendableClass59, _119, 0x0, v0 + callruntime.stsendablevar 0x0, 0x3a + ldhole + sta v0 + callruntime.definesendableclass 0x3d, .#~@3b=#TopLevelSendableClass60, _121, 0x0, v0 + callruntime.stsendablevar 0x0, 0x3b + ldhole + sta v0 + callruntime.definesendableclass 0x3e, .#~@3c=#TopLevelSendableClass61, _123, 0x0, v0 + callruntime.stsendablevar 0x0, 0x3c + ldhole + sta v0 + callruntime.definesendableclass 0x3f, .#~@3d=#TopLevelSendableClass62, _125, 0x0, v0 + callruntime.stsendablevar 0x0, 0x3d + ldhole + sta v0 + callruntime.definesendableclass 0x40, .#~@3e=#TopLevelSendableClass63, _127, 0x0, v0 + callruntime.stsendablevar 0x0, 0x3e + ldhole + sta v0 + callruntime.definesendableclass 0x41, .#~@3f=#TopLevelSendableClass64, _129, 0x0, v0 + callruntime.stsendablevar 0x0, 0x3f + ldhole + sta v0 + callruntime.definesendableclass 0x42, .#~@40=#TopLevelSendableClass65, _131, 0x0, v0 + callruntime.stsendablevar 0x0, 0x40 + ldhole + sta v0 + callruntime.definesendableclass 0x43, .#~@41=#TopLevelSendableClass66, _133, 0x0, v0 + callruntime.stsendablevar 0x0, 0x41 + ldhole + sta v0 + callruntime.definesendableclass 0x44, .#~@42=#TopLevelSendableClass67, _135, 0x0, v0 + callruntime.stsendablevar 0x0, 0x42 + ldhole + sta v0 + callruntime.definesendableclass 0x45, .#~@43=#TopLevelSendableClass68, _137, 0x0, v0 + callruntime.stsendablevar 0x0, 0x43 + ldhole + sta v0 + callruntime.definesendableclass 0x46, .#~@44=#TopLevelSendableClass69, _139, 0x0, v0 + callruntime.stsendablevar 0x0, 0x44 + ldhole + sta v0 + callruntime.definesendableclass 0x47, .#~@45=#TopLevelSendableClass70, _141, 0x0, v0 + callruntime.stsendablevar 0x0, 0x45 + ldhole + sta v0 + callruntime.definesendableclass 0x48, .#~@46=#TopLevelSendableClass71, _143, 0x0, v0 + callruntime.stsendablevar 0x0, 0x46 + ldhole + sta v0 + callruntime.definesendableclass 0x49, .#~@47=#TopLevelSendableClass72, _145, 0x0, v0 + callruntime.stsendablevar 0x0, 0x47 + ldhole + sta v0 + callruntime.definesendableclass 0x4a, .#~@48=#TopLevelSendableClass73, _147, 0x0, v0 + callruntime.stsendablevar 0x0, 0x48 + ldhole + sta v0 + callruntime.definesendableclass 0x4b, .#~@49=#TopLevelSendableClass74, _149, 0x0, v0 + callruntime.stsendablevar 0x0, 0x49 + ldhole + sta v0 + callruntime.definesendableclass 0x4c, .#~@4a=#TopLevelSendableClass75, _151, 0x0, v0 + callruntime.stsendablevar 0x0, 0x4a + ldhole + sta v0 + callruntime.definesendableclass 0x4d, .#~@4b=#TopLevelSendableClass76, _153, 0x0, v0 + callruntime.stsendablevar 0x0, 0x4b + ldhole + sta v0 + callruntime.definesendableclass 0x4e, .#~@4c=#TopLevelSendableClass77, _155, 0x0, v0 + callruntime.stsendablevar 0x0, 0x4c + ldhole + sta v0 + callruntime.definesendableclass 0x4f, .#~@4d=#TopLevelSendableClass78, _157, 0x0, v0 + callruntime.stsendablevar 0x0, 0x4d + ldhole + sta v0 + callruntime.definesendableclass 0x50, .#~@4e=#TopLevelSendableClass79, _159, 0x0, v0 + callruntime.stsendablevar 0x0, 0x4e + ldhole + sta v0 + callruntime.definesendableclass 0x51, .#~@4f=#TopLevelSendableClass80, _161, 0x0, v0 + callruntime.stsendablevar 0x0, 0x4f + ldhole + sta v0 + callruntime.definesendableclass 0x52, .#~@50=#TopLevelSendableClass81, _163, 0x0, v0 + callruntime.stsendablevar 0x0, 0x50 + ldhole + sta v0 + callruntime.definesendableclass 0x53, .#~@51=#TopLevelSendableClass82, _165, 0x0, v0 + callruntime.stsendablevar 0x0, 0x51 + ldhole + sta v0 + callruntime.definesendableclass 0x54, .#~@52=#TopLevelSendableClass83, _167, 0x0, v0 + callruntime.stsendablevar 0x0, 0x52 + ldhole + sta v0 + callruntime.definesendableclass 0x55, .#~@53=#TopLevelSendableClass84, _169, 0x0, v0 + callruntime.stsendablevar 0x0, 0x53 + ldhole + sta v0 + callruntime.definesendableclass 0x56, .#~@54=#TopLevelSendableClass85, _171, 0x0, v0 + callruntime.stsendablevar 0x0, 0x54 + ldhole + sta v0 + callruntime.definesendableclass 0x57, .#~@55=#TopLevelSendableClass86, _173, 0x0, v0 + callruntime.stsendablevar 0x0, 0x55 + ldhole + sta v0 + callruntime.definesendableclass 0x58, .#~@56=#TopLevelSendableClass87, _175, 0x0, v0 + callruntime.stsendablevar 0x0, 0x56 + ldhole + sta v0 + callruntime.definesendableclass 0x59, .#~@57=#TopLevelSendableClass88, _177, 0x0, v0 + callruntime.stsendablevar 0x0, 0x57 + ldhole + sta v0 + callruntime.definesendableclass 0x5a, .#~@58=#TopLevelSendableClass89, _179, 0x0, v0 + callruntime.stsendablevar 0x0, 0x58 + ldhole + sta v0 + callruntime.definesendableclass 0x5b, .#~@59=#TopLevelSendableClass90, _181, 0x0, v0 + callruntime.stsendablevar 0x0, 0x59 + ldhole + sta v0 + callruntime.definesendableclass 0x5c, .#~@5a=#TopLevelSendableClass91, _183, 0x0, v0 + callruntime.stsendablevar 0x0, 0x5a + ldhole + sta v0 + callruntime.definesendableclass 0x5d, .#~@5b=#TopLevelSendableClass92, _185, 0x0, v0 + callruntime.stsendablevar 0x0, 0x5b + ldhole + sta v0 + callruntime.definesendableclass 0x5e, .#~@5c=#TopLevelSendableClass93, _187, 0x0, v0 + callruntime.stsendablevar 0x0, 0x5c + ldhole + sta v0 + callruntime.definesendableclass 0x5f, .#~@5d=#TopLevelSendableClass94, _189, 0x0, v0 + callruntime.stsendablevar 0x0, 0x5d + ldhole + sta v0 + callruntime.definesendableclass 0x60, .#~@5e=#TopLevelSendableClass95, _191, 0x0, v0 + callruntime.stsendablevar 0x0, 0x5e + ldhole + sta v0 + callruntime.definesendableclass 0x61, .#~@5f=#TopLevelSendableClass96, _193, 0x0, v0 + callruntime.stsendablevar 0x0, 0x5f + ldhole + sta v0 + callruntime.definesendableclass 0x62, .#~@60=#TopLevelSendableClass97, _195, 0x0, v0 + callruntime.stsendablevar 0x0, 0x60 + ldhole + sta v0 + callruntime.definesendableclass 0x63, .#~@61=#TopLevelSendableClass98, _197, 0x0, v0 + callruntime.stsendablevar 0x0, 0x61 + ldhole + sta v0 + callruntime.definesendableclass 0x64, .#~@62=#TopLevelSendableClass99, _199, 0x0, v0 + callruntime.stsendablevar 0x0, 0x62 + ldhole + sta v0 + callruntime.definesendableclass 0x65, .#~@63=#TopLevelSendableClass100, _201, 0x0, v0 + callruntime.stsendablevar 0x0, 0x63 + ldhole + sta v0 + callruntime.definesendableclass 0x66, .#~@64=#TopLevelSendableClass101, _203, 0x0, v0 + callruntime.stsendablevar 0x0, 0x64 + ldhole + sta v0 + callruntime.definesendableclass 0x67, .#~@65=#TopLevelSendableClass102, _205, 0x0, v0 + callruntime.stsendablevar 0x0, 0x65 + ldhole + sta v0 + callruntime.definesendableclass 0x68, .#~@66=#TopLevelSendableClass103, _207, 0x0, v0 + callruntime.stsendablevar 0x0, 0x66 + ldhole + sta v0 + callruntime.definesendableclass 0x69, .#~@67=#TopLevelSendableClass104, _209, 0x0, v0 + callruntime.stsendablevar 0x0, 0x67 + ldhole + sta v0 + callruntime.definesendableclass 0x6a, .#~@68=#TopLevelSendableClass105, _211, 0x0, v0 + callruntime.stsendablevar 0x0, 0x68 + ldhole + sta v0 + callruntime.definesendableclass 0x6b, .#~@69=#TopLevelSendableClass106, _213, 0x0, v0 + callruntime.stsendablevar 0x0, 0x69 + ldhole + sta v0 + callruntime.definesendableclass 0x6c, .#~@6a=#TopLevelSendableClass107, _215, 0x0, v0 + callruntime.stsendablevar 0x0, 0x6a + ldhole + sta v0 + callruntime.definesendableclass 0x6d, .#~@6b=#TopLevelSendableClass108, _217, 0x0, v0 + callruntime.stsendablevar 0x0, 0x6b + ldhole + sta v0 + callruntime.definesendableclass 0x6e, .#~@6c=#TopLevelSendableClass109, _219, 0x0, v0 + callruntime.stsendablevar 0x0, 0x6c + ldhole + sta v0 + callruntime.definesendableclass 0x6f, .#~@6d=#TopLevelSendableClass110, _221, 0x0, v0 + callruntime.stsendablevar 0x0, 0x6d + ldhole + sta v0 + callruntime.definesendableclass 0x70, .#~@6e=#TopLevelSendableClass111, _223, 0x0, v0 + callruntime.stsendablevar 0x0, 0x6e + ldhole + sta v0 + callruntime.definesendableclass 0x71, .#~@6f=#TopLevelSendableClass112, _225, 0x0, v0 + callruntime.stsendablevar 0x0, 0x6f + ldhole + sta v0 + callruntime.definesendableclass 0x72, .#~@70=#TopLevelSendableClass113, _227, 0x0, v0 + callruntime.stsendablevar 0x0, 0x70 + ldhole + sta v0 + callruntime.definesendableclass 0x73, .#~@71=#TopLevelSendableClass114, _229, 0x0, v0 + callruntime.stsendablevar 0x0, 0x71 + ldhole + sta v0 + callruntime.definesendableclass 0x74, .#~@72=#TopLevelSendableClass115, _231, 0x0, v0 + callruntime.stsendablevar 0x0, 0x72 + ldhole + sta v0 + callruntime.definesendableclass 0x75, .#~@73=#TopLevelSendableClass116, _233, 0x0, v0 + callruntime.stsendablevar 0x0, 0x73 + ldhole + sta v0 + callruntime.definesendableclass 0x76, .#~@74=#TopLevelSendableClass117, _235, 0x0, v0 + callruntime.stsendablevar 0x0, 0x74 + ldhole + sta v0 + callruntime.definesendableclass 0x77, .#~@75=#TopLevelSendableClass118, _237, 0x0, v0 + callruntime.stsendablevar 0x0, 0x75 + ldhole + sta v0 + callruntime.definesendableclass 0x78, .#~@76=#TopLevelSendableClass119, _239, 0x0, v0 + callruntime.stsendablevar 0x0, 0x76 + ldhole + sta v0 + callruntime.definesendableclass 0x79, .#~@77=#TopLevelSendableClass120, _241, 0x0, v0 + callruntime.stsendablevar 0x0, 0x77 + ldhole + sta v0 + callruntime.definesendableclass 0x7a, .#~@78=#TopLevelSendableClass121, _243, 0x0, v0 + callruntime.stsendablevar 0x0, 0x78 + ldhole + sta v0 + callruntime.definesendableclass 0x7b, .#~@79=#TopLevelSendableClass122, _245, 0x0, v0 + callruntime.stsendablevar 0x0, 0x79 + ldhole + sta v0 + callruntime.definesendableclass 0x7c, .#~@7a=#TopLevelSendableClass123, _247, 0x0, v0 + callruntime.stsendablevar 0x0, 0x7a + ldhole + sta v0 + callruntime.definesendableclass 0x7d, .#~@7b=#TopLevelSendableClass124, _249, 0x0, v0 + callruntime.stsendablevar 0x0, 0x7b + ldhole + sta v0 + callruntime.definesendableclass 0x7e, .#~@7c=#TopLevelSendableClass125, _251, 0x0, v0 + callruntime.stsendablevar 0x0, 0x7c + ldhole + sta v0 + callruntime.definesendableclass 0x7f, .#~@7d=#TopLevelSendableClass126, _253, 0x0, v0 + callruntime.stsendablevar 0x0, 0x7d + ldhole + sta v0 + callruntime.definesendableclass 0x80, .#~@7e=#TopLevelSendableClass127, _255, 0x0, v0 + callruntime.stsendablevar 0x0, 0x7e + ldhole + sta v0 + callruntime.definesendableclass 0x81, .#~@7f=#TopLevelSendableClass128, _257, 0x0, v0 + callruntime.stsendablevar 0x0, 0x7f + ldhole + sta v0 + callruntime.definesendableclass 0x82, .#~@80=#TopLevelSendableClass129, _259, 0x0, v0 + callruntime.widestsendablevar 0x0, 0x80 + ldhole + sta v0 + callruntime.definesendableclass 0x83, .#~@81=#TopLevelSendableClass130, _261, 0x0, v0 + callruntime.widestsendablevar 0x0, 0x81 + ldhole + sta v0 + callruntime.definesendableclass 0x84, .#~@82=#TopLevelSendableClass131, _263, 0x0, v0 + callruntime.widestsendablevar 0x0, 0x82 + ldhole + sta v0 + callruntime.definesendableclass 0x85, .#~@83=#TopLevelSendableClass132, _265, 0x0, v0 + callruntime.widestsendablevar 0x0, 0x83 + ldhole + sta v0 + callruntime.definesendableclass 0x86, .#~@84=#TopLevelSendableClass133, _267, 0x0, v0 + callruntime.widestsendablevar 0x0, 0x84 + ldhole + sta v0 + callruntime.definesendableclass 0x87, .#~@85=#TopLevelSendableClass134, _269, 0x0, v0 + callruntime.widestsendablevar 0x0, 0x85 + ldhole + sta v0 + callruntime.definesendableclass 0x88, .#~@86=#TopLevelSendableClass135, _271, 0x0, v0 + callruntime.widestsendablevar 0x0, 0x86 + ldhole + sta v0 + callruntime.definesendableclass 0x89, .#~@87=#TopLevelSendableClass136, _273, 0x0, v0 + callruntime.widestsendablevar 0x0, 0x87 + ldhole + sta v0 + callruntime.definesendableclass 0x8a, .#~@88=#TopLevelSendableClass137, _275, 0x0, v0 + callruntime.widestsendablevar 0x0, 0x88 + ldhole + sta v0 + callruntime.definesendableclass 0x8b, .#~@89=#TopLevelSendableClass138, _277, 0x0, v0 + callruntime.widestsendablevar 0x0, 0x89 + ldhole + sta v0 + callruntime.definesendableclass 0x8c, .#~@8a=#TopLevelSendableClass139, _279, 0x0, v0 + callruntime.widestsendablevar 0x0, 0x8a + ldhole + sta v0 + callruntime.definesendableclass 0x8d, .#~@8b=#TopLevelSendableClass140, _281, 0x0, v0 + callruntime.widestsendablevar 0x0, 0x8b + ldhole + sta v0 + callruntime.definesendableclass 0x8e, .#~@8c=#TopLevelSendableClass141, _283, 0x0, v0 + callruntime.widestsendablevar 0x0, 0x8c + ldhole + sta v0 + callruntime.definesendableclass 0x8f, .#~@8d=#TopLevelSendableClass142, _285, 0x0, v0 + callruntime.widestsendablevar 0x0, 0x8d + ldhole + sta v0 + callruntime.definesendableclass 0x90, .#~@8e=#TopLevelSendableClass143, _287, 0x0, v0 + callruntime.widestsendablevar 0x0, 0x8e + ldhole + sta v0 + callruntime.definesendableclass 0x91, .#~@8f=#TopLevelSendableClass144, _289, 0x0, v0 + callruntime.widestsendablevar 0x0, 0x8f + ldhole + sta v0 + callruntime.definesendableclass 0x92, .#~@90=#TopLevelSendableClass145, _291, 0x0, v0 + callruntime.widestsendablevar 0x0, 0x90 + ldhole + sta v0 + callruntime.definesendableclass 0x93, .#~@91=#TopLevelSendableClass146, _293, 0x0, v0 + callruntime.widestsendablevar 0x0, 0x91 + ldhole + sta v0 + callruntime.definesendableclass 0x94, .#~@92=#TopLevelSendableClass147, _295, 0x0, v0 + callruntime.widestsendablevar 0x0, 0x92 + ldhole + sta v0 + callruntime.definesendableclass 0x95, .#~@93=#TopLevelSendableClass148, _297, 0x0, v0 + callruntime.widestsendablevar 0x0, 0x93 + ldhole + sta v0 + callruntime.definesendableclass 0x96, .#~@94=#TopLevelSendableClass149, _299, 0x0, v0 + callruntime.widestsendablevar 0x0, 0x94 + ldhole + sta v0 + callruntime.definesendableclass 0x97, .#~@95=#TopLevelSendableClass150, _301, 0x0, v0 + callruntime.widestsendablevar 0x0, 0x95 + ldhole + sta v0 + callruntime.definesendableclass 0x98, .#~@96=#TopLevelSendableClass151, _303, 0x0, v0 + callruntime.widestsendablevar 0x0, 0x96 + ldhole + sta v0 + callruntime.definesendableclass 0x99, .#~@97=#TopLevelSendableClass152, _305, 0x0, v0 + callruntime.widestsendablevar 0x0, 0x97 + ldhole + sta v0 + callruntime.definesendableclass 0x9a, .#~@98=#TopLevelSendableClass153, _307, 0x0, v0 + callruntime.widestsendablevar 0x0, 0x98 + ldhole + sta v0 + callruntime.definesendableclass 0x9b, .#~@99=#TopLevelSendableClass154, _309, 0x0, v0 + callruntime.widestsendablevar 0x0, 0x99 + ldhole + sta v0 + callruntime.definesendableclass 0x9c, .#~@9a=#TopLevelSendableClass155, _311, 0x0, v0 + callruntime.widestsendablevar 0x0, 0x9a + ldhole + sta v0 + callruntime.definesendableclass 0x9d, .#~@9b=#TopLevelSendableClass156, _313, 0x0, v0 + callruntime.widestsendablevar 0x0, 0x9b + ldhole + sta v0 + callruntime.definesendableclass 0x9e, .#~@9c=#TopLevelSendableClass157, _315, 0x0, v0 + callruntime.widestsendablevar 0x0, 0x9c + ldhole + sta v0 + callruntime.definesendableclass 0x9f, .#~@9d=#TopLevelSendableClass158, _317, 0x0, v0 + callruntime.widestsendablevar 0x0, 0x9d + ldhole + sta v0 + callruntime.definesendableclass 0xa0, .#~@9e=#TopLevelSendableClass159, _319, 0x0, v0 + callruntime.widestsendablevar 0x0, 0x9e + ldhole + sta v0 + callruntime.definesendableclass 0xa1, .#~@9f=#TopLevelSendableClass160, _321, 0x0, v0 + callruntime.widestsendablevar 0x0, 0x9f + ldhole + sta v0 + callruntime.definesendableclass 0xa2, .#~@a0=#TopLevelSendableClass161, _323, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xa0 + ldhole + sta v0 + callruntime.definesendableclass 0xa3, .#~@a1=#TopLevelSendableClass162, _325, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xa1 + ldhole + sta v0 + callruntime.definesendableclass 0xa4, .#~@a2=#TopLevelSendableClass163, _327, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xa2 + ldhole + sta v0 + callruntime.definesendableclass 0xa5, .#~@a3=#TopLevelSendableClass164, _329, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xa3 + ldhole + sta v0 + callruntime.definesendableclass 0xa6, .#~@a4=#TopLevelSendableClass165, _331, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xa4 + ldhole + sta v0 + callruntime.definesendableclass 0xa7, .#~@a5=#TopLevelSendableClass166, _333, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xa5 + ldhole + sta v0 + callruntime.definesendableclass 0xa8, .#~@a6=#TopLevelSendableClass167, _335, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xa6 + ldhole + sta v0 + callruntime.definesendableclass 0xa9, .#~@a7=#TopLevelSendableClass168, _337, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xa7 + ldhole + sta v0 + callruntime.definesendableclass 0xaa, .#~@a8=#TopLevelSendableClass169, _339, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xa8 + ldhole + sta v0 + callruntime.definesendableclass 0xab, .#~@a9=#TopLevelSendableClass170, _341, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xa9 + ldhole + sta v0 + callruntime.definesendableclass 0xac, .#~@aa=#TopLevelSendableClass171, _343, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xaa + ldhole + sta v0 + callruntime.definesendableclass 0xad, .#~@ab=#TopLevelSendableClass172, _345, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xab + ldhole + sta v0 + callruntime.definesendableclass 0xae, .#~@ac=#TopLevelSendableClass173, _347, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xac + ldhole + sta v0 + callruntime.definesendableclass 0xaf, .#~@ad=#TopLevelSendableClass174, _349, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xad + ldhole + sta v0 + callruntime.definesendableclass 0xb0, .#~@ae=#TopLevelSendableClass175, _351, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xae + ldhole + sta v0 + callruntime.definesendableclass 0xb1, .#~@af=#TopLevelSendableClass176, _353, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xaf + ldhole + sta v0 + callruntime.definesendableclass 0xb2, .#~@b0=#TopLevelSendableClass177, _355, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xb0 + ldhole + sta v0 + callruntime.definesendableclass 0xb3, .#~@b1=#TopLevelSendableClass178, _357, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xb1 + ldhole + sta v0 + callruntime.definesendableclass 0xb4, .#~@b2=#TopLevelSendableClass179, _359, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xb2 + ldhole + sta v0 + callruntime.definesendableclass 0xb5, .#~@b3=#TopLevelSendableClass180, _361, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xb3 + ldhole + sta v0 + callruntime.definesendableclass 0xb6, .#~@b4=#TopLevelSendableClass181, _363, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xb4 + ldhole + sta v0 + callruntime.definesendableclass 0xb7, .#~@b5=#TopLevelSendableClass182, _365, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xb5 + ldhole + sta v0 + callruntime.definesendableclass 0xb8, .#~@b6=#TopLevelSendableClass183, _367, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xb6 + ldhole + sta v0 + callruntime.definesendableclass 0xb9, .#~@b7=#TopLevelSendableClass184, _369, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xb7 + ldhole + sta v0 + callruntime.definesendableclass 0xba, .#~@b8=#TopLevelSendableClass185, _371, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xb8 + ldhole + sta v0 + callruntime.definesendableclass 0xbb, .#~@b9=#TopLevelSendableClass186, _373, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xb9 + ldhole + sta v0 + callruntime.definesendableclass 0xbc, .#~@ba=#TopLevelSendableClass187, _375, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xba + ldhole + sta v0 + callruntime.definesendableclass 0xbd, .#~@bb=#TopLevelSendableClass188, _377, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xbb + ldhole + sta v0 + callruntime.definesendableclass 0xbe, .#~@bc=#TopLevelSendableClass189, _379, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xbc + ldhole + sta v0 + callruntime.definesendableclass 0xbf, .#~@bd=#TopLevelSendableClass190, _381, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xbd + ldhole + sta v0 + callruntime.definesendableclass 0xc0, .#~@be=#TopLevelSendableClass191, _383, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xbe + ldhole + sta v0 + callruntime.definesendableclass 0xc1, .#~@bf=#TopLevelSendableClass192, _385, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xbf + ldhole + sta v0 + callruntime.definesendableclass 0xc2, .#~@c0=#TopLevelSendableClass193, _387, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xc0 + ldhole + sta v0 + callruntime.definesendableclass 0xc3, .#~@c1=#TopLevelSendableClass194, _389, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xc1 + ldhole + sta v0 + callruntime.definesendableclass 0xc4, .#~@c2=#TopLevelSendableClass195, _391, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xc2 + ldhole + sta v0 + callruntime.definesendableclass 0xc5, .#~@c3=#TopLevelSendableClass196, _393, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xc3 + ldhole + sta v0 + callruntime.definesendableclass 0xc6, .#~@c4=#TopLevelSendableClass197, _395, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xc4 + ldhole + sta v0 + callruntime.definesendableclass 0xc7, .#~@c5=#TopLevelSendableClass198, _397, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xc5 + ldhole + sta v0 + callruntime.definesendableclass 0xc8, .#~@c6=#TopLevelSendableClass199, _399, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xc6 + ldhole + sta v0 + callruntime.definesendableclass 0xc9, .#~@c7=#TopLevelSendableClass200, _401, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xc7 + ldhole + sta v0 + callruntime.definesendableclass 0xca, .#~@c8=#TopLevelSendableClass201, _403, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xc8 + ldhole + sta v0 + callruntime.definesendableclass 0xcb, .#~@c9=#TopLevelSendableClass202, _405, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xc9 + ldhole + sta v0 + callruntime.definesendableclass 0xcc, .#~@ca=#TopLevelSendableClass203, _407, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xca + ldhole + sta v0 + callruntime.definesendableclass 0xcd, .#~@cb=#TopLevelSendableClass204, _409, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xcb + ldhole + sta v0 + callruntime.definesendableclass 0xce, .#~@cc=#TopLevelSendableClass205, _411, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xcc + ldhole + sta v0 + callruntime.definesendableclass 0xcf, .#~@cd=#TopLevelSendableClass206, _413, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xcd + ldhole + sta v0 + callruntime.definesendableclass 0xd0, .#~@ce=#TopLevelSendableClass207, _415, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xce + ldhole + sta v0 + callruntime.definesendableclass 0xd1, .#~@cf=#TopLevelSendableClass208, _417, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xcf + ldhole + sta v0 + callruntime.definesendableclass 0xd2, .#~@d0=#TopLevelSendableClass209, _419, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xd0 + ldhole + sta v0 + callruntime.definesendableclass 0xd3, .#~@d1=#TopLevelSendableClass210, _421, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xd1 + ldhole + sta v0 + callruntime.definesendableclass 0xd4, .#~@d2=#TopLevelSendableClass211, _423, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xd2 + ldhole + sta v0 + callruntime.definesendableclass 0xd5, .#~@d3=#TopLevelSendableClass212, _425, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xd3 + ldhole + sta v0 + callruntime.definesendableclass 0xd6, .#~@d4=#TopLevelSendableClass213, _427, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xd4 + ldhole + sta v0 + callruntime.definesendableclass 0xd7, .#~@d5=#TopLevelSendableClass214, _429, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xd5 + ldhole + sta v0 + callruntime.definesendableclass 0xd8, .#~@d6=#TopLevelSendableClass215, _431, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xd6 + ldhole + sta v0 + callruntime.definesendableclass 0xd9, .#~@d7=#TopLevelSendableClass216, _433, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xd7 + ldhole + sta v0 + callruntime.definesendableclass 0xda, .#~@d8=#TopLevelSendableClass217, _435, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xd8 + ldhole + sta v0 + callruntime.definesendableclass 0xdb, .#~@d9=#TopLevelSendableClass218, _437, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xd9 + ldhole + sta v0 + callruntime.definesendableclass 0xdc, .#~@da=#TopLevelSendableClass219, _439, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xda + ldhole + sta v0 + callruntime.definesendableclass 0xdd, .#~@db=#TopLevelSendableClass220, _441, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xdb + ldhole + sta v0 + callruntime.definesendableclass 0xde, .#~@dc=#TopLevelSendableClass221, _443, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xdc + ldhole + sta v0 + callruntime.definesendableclass 0xdf, .#~@dd=#TopLevelSendableClass222, _445, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xdd + ldhole + sta v0 + callruntime.definesendableclass 0xe0, .#~@de=#TopLevelSendableClass223, _447, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xde + ldhole + sta v0 + callruntime.definesendableclass 0xe1, .#~@df=#TopLevelSendableClass224, _449, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xdf + ldhole + sta v0 + callruntime.definesendableclass 0xe2, .#~@e0=#TopLevelSendableClass225, _451, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xe0 + ldhole + sta v0 + callruntime.definesendableclass 0xe3, .#~@e1=#TopLevelSendableClass226, _453, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xe1 + ldhole + sta v0 + callruntime.definesendableclass 0xe4, .#~@e2=#TopLevelSendableClass227, _455, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xe2 + ldhole + sta v0 + callruntime.definesendableclass 0xe5, .#~@e3=#TopLevelSendableClass228, _457, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xe3 + ldhole + sta v0 + callruntime.definesendableclass 0xe6, .#~@e4=#TopLevelSendableClass229, _459, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xe4 + ldhole + sta v0 + callruntime.definesendableclass 0xe7, .#~@e5=#TopLevelSendableClass230, _461, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xe5 + ldhole + sta v0 + callruntime.definesendableclass 0xe8, .#~@e6=#TopLevelSendableClass231, _463, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xe6 + ldhole + sta v0 + callruntime.definesendableclass 0xe9, .#~@e7=#TopLevelSendableClass232, _465, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xe7 + ldhole + sta v0 + callruntime.definesendableclass 0xea, .#~@e8=#TopLevelSendableClass233, _467, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xe8 + ldhole + sta v0 + callruntime.definesendableclass 0xeb, .#~@e9=#TopLevelSendableClass234, _469, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xe9 + ldhole + sta v0 + callruntime.definesendableclass 0xec, .#~@ea=#TopLevelSendableClass235, _471, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xea + ldhole + sta v0 + callruntime.definesendableclass 0xed, .#~@eb=#TopLevelSendableClass236, _473, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xeb + ldhole + sta v0 + callruntime.definesendableclass 0xee, .#~@ec=#TopLevelSendableClass237, _475, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xec + ldhole + sta v0 + callruntime.definesendableclass 0xef, .#~@ed=#TopLevelSendableClass238, _477, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xed + ldhole + sta v0 + callruntime.definesendableclass 0xf0, .#~@ee=#TopLevelSendableClass239, _479, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xee + ldhole + sta v0 + callruntime.definesendableclass 0xf1, .#~@ef=#TopLevelSendableClass240, _481, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xef + ldhole + sta v0 + callruntime.definesendableclass 0xf2, .#~@f0=#TopLevelSendableClass241, _483, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xf0 + ldhole + sta v0 + callruntime.definesendableclass 0xf3, .#~@f1=#TopLevelSendableClass242, _485, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xf1 + ldhole + sta v0 + callruntime.definesendableclass 0xf4, .#~@f2=#TopLevelSendableClass243, _487, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xf2 + ldhole + sta v0 + callruntime.definesendableclass 0xf5, .#~@f3=#TopLevelSendableClass244, _489, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xf3 + ldhole + sta v0 + callruntime.definesendableclass 0xf6, .#~@f4=#TopLevelSendableClass245, _491, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xf4 + ldhole + sta v0 + callruntime.definesendableclass 0xf7, .#~@f5=#TopLevelSendableClass246, _493, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xf5 + ldhole + sta v0 + callruntime.definesendableclass 0xf8, .#~@f6=#TopLevelSendableClass247, _495, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xf6 + ldhole + sta v0 + callruntime.definesendableclass 0xf9, .#~@f7=#TopLevelSendableClass248, _497, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xf7 + ldhole + sta v0 + callruntime.definesendableclass 0xfa, .#~@f8=#TopLevelSendableClass249, _499, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xf8 + ldhole + sta v0 + callruntime.definesendableclass 0xfb, .#~@f9=#TopLevelSendableClass250, _501, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xf9 + ldhole + sta v0 + callruntime.definesendableclass 0xfc, .#~@fa=#TopLevelSendableClass251, _503, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xfa + ldhole + sta v0 + callruntime.definesendableclass 0xfd, .#~@fb=#TopLevelSendableClass252, _505, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xfb + ldhole + sta v0 + callruntime.definesendableclass 0xfe, .#~@fc=#TopLevelSendableClass253, _507, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xfc + ldhole + sta v0 + callruntime.definesendableclass 0x100, .#~@fd=#TopLevelSendableClass254, _509, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xfd + ldhole + sta v0 + callruntime.definesendableclass 0x101, .#~@fe=#TopLevelSendableClass255, _511, 0x0, v0 + callruntime.widestsendablevar 0x0, 0xfe + ldhole + sta v0 + callruntime.definesendableclass 0x102, .#~@ff=#SendableTestClass1, _513, 0x0, v0 + sta v0 + mov v2, v0 + newobjrange 0x103, 0x1, v2 + sta v0 + tryldglobalbyname 0x105, print + sta v1 + lda v0 + ldobjbyname 0x106, v + sta v0 + lda v1 + callarg1 0x0, v0 + returnundefined +label_2: +} + + diff --git a/es2panda/test/version_control/API12beta3/bytecode_feature/define_property_by_name_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt b/es2panda/test/version_control/API12beta3/bytecode_feature/define_property_by_name_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt new file mode 100644 index 0000000000..85b14f1a81 --- /dev/null +++ b/es2panda/test/version_control/API12beta3/bytecode_feature/define_property_by_name_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt @@ -0,0 +1,50 @@ +slotNum = 0x4 +.language ECMAScript +.function any .#~@0=#PropertyByName(any a0, any a1, any a2, any a3, any a4) { +label_1: +label_0: + lda a3 + stobjbyname 0x0, name, a2 + lda a4 + stobjbyname 0x2, age, a2 + lda a2 + return +label_2: +} + +slotNum = 0xa +.language ECMAScript +.function any .#~@0>#init(any a0, any a1, any a2) { +label_1: +label_0: + tryldglobalbyname 0x0, Object + sta v0 + ldobjbyname 0x1, defineProperty + sta v1 + lda.str name + sta v2 + createobjectwithbuffer 0x3, _2 + sta v3 + lda a2 + ldobjbyname 0x4, name + definepropertybyname 0x6, value, v3 + lda v1 + callthis3 0x8, v0, a2, v2, v3 + returnundefined +label_2: +} + +slotNum = 0x3 +.language ECMAScript +.function any .func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + ldhole + sta v0 + defineclasswithbuffer 0x0, .#~@0=#PropertyByName, _3, 0x2, v0 + ldobjbyname 0x1, prototype + returnundefined +label_2: +} + + diff --git a/es2panda/test/version_control/API12beta3/bytecode_feature/import_target/import_target.ts b/es2panda/test/version_control/API12beta3/bytecode_feature/import_target/import_target.ts index 28f0f7ccd6..7621af1e5d 100644 --- a/es2panda/test/version_control/API12beta3/bytecode_feature/import_target/import_target.ts +++ b/es2panda/test/version_control/API12beta3/bytecode_feature/import_target/import_target.ts @@ -14,6 +14,8 @@ * limitations under the License. */ +const defaultImportValue = 'a0'; +export default defaultImportValue; export const a1 = 'a1'; export const a2 = 'a2'; export const a3 = 'a3'; diff --git a/es2panda/test/version_control/API12beta3/bytecode_feature/istrue_isfalse_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt b/es2panda/test/version_control/API12beta3/bytecode_feature/istrue_isfalse_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt new file mode 100644 index 0000000000..674e91d583 --- /dev/null +++ b/es2panda/test/version_control/API12beta3/bytecode_feature/istrue_isfalse_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt @@ -0,0 +1,42 @@ +slotNum = 0x9 +.language ECMAScript +.function any .func_main_0(any a0, any a1, any a2) { +label_8: +label_0: + ldtrue + sta v0 + callruntime.isfalse 0x0 + jnez label_1 +label_2: + tryldglobalbyname 0x1, print + sta v0 + lda.str true + sta v1 + lda v0 + callarg1 0x2, v1 + jmp label_3 +label_1: + lda v0 + callruntime.istrue 0x4 + jnez label_4 +label_5: + ldtrue + jmp label_6 +label_4: + ldfalse +label_6: + callruntime.isfalse 0x5 + jnez label_3 +label_7: + tryldglobalbyname 0x6, print + sta v0 + lda.str false + sta v1 + lda v0 + callarg1 0x7, v1 +label_3: + returnundefined +label_9: +} + + diff --git a/es2panda/test/version_control/API12beta3/bytecode_feature/lazy_import_bytecode.ts b/es2panda/test/version_control/API12beta3/bytecode_feature/lazy_import_bytecode.ts index c6d38d659c..af97b159cc 100644 --- a/es2panda/test/version_control/API12beta3/bytecode_feature/lazy_import_bytecode.ts +++ b/es2panda/test/version_control/API12beta3/bytecode_feature/lazy_import_bytecode.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -import lazy { a1, a2 } from 'import_target/import_target' +import lazy defaultImportValue, { a1, a2 } from 'import_target/import_target'; class SendableLazyLoading { name: string = a1; @@ -23,4 +23,5 @@ class SendableLazyLoading { } let a: SendableLazyLoading = new SendableLazyLoading(); let b: string = a2; -print(a.name); \ No newline at end of file +print(a.name); +print(defaultImportValue); \ No newline at end of file diff --git a/es2panda/test/version_control/API12beta3/bytecode_feature/lazy_import_bytecode_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API12beta3/bytecode_feature/lazy_import_bytecode_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt index 22f60b0b50..fffe779103 100644 --- a/es2panda/test/version_control/API12beta3/bytecode_feature/lazy_import_bytecode_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt +++ b/es2panda/test/version_control/API12beta3/bytecode_feature/lazy_import_bytecode_supported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt @@ -13,7 +13,7 @@ label_0: label_2: } -slotNum = 0x8 +slotNum = 0xb .language ECMAScript .function any .func_main_0(any a0, any a1, any a2) { label_1: @@ -34,6 +34,13 @@ label_0: sta v0 lda v1 callarg1 0x6, v0 + tryldglobalbyname 0x8, print + sta v0 + callruntime.ldlazymodulevar 0x2 + sta v1 + throw.undefinedifholewithname defaultImportValue + lda v0 + callarg1 0x9, v1 returnundefined label_2: } diff --git a/es2panda/test/version_control/API12beta3/bytecode_feature/lazy_import_bytecode_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt b/es2panda/test/version_control/API12beta3/bytecode_feature/lazy_import_bytecode_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt new file mode 100644 index 0000000000..3e0604bf53 --- /dev/null +++ b/es2panda/test/version_control/API12beta3/bytecode_feature/lazy_import_bytecode_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt @@ -0,0 +1,49 @@ +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@0=#SendableLazyLoading(any a0, any a1, any a2) { +label_1: +label_0: + callruntime.ldlazysendablemodulevar 0x0 + sta v0 + throw.undefinedifholewithname a1 + lda v0 + stobjbyname 0x0, name, a2 + lda a2 + return +label_2: +} + +slotNum = 0xb +.language ECMAScript +.function any .func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + ldhole + sta v0 + callruntime.definesendableclass 0x0, .#~@0=#SendableLazyLoading, _4, 0x0, v0 + sta v0 + mov v2, v0 + newobjrange 0x1, 0x1, v2 + sta v0 + callruntime.ldlazymodulevar 0x1 + throw.undefinedifholewithname a2 + tryldglobalbyname 0x3, print + sta v1 + lda v0 + ldobjbyname 0x4, name + sta v0 + lda v1 + callarg1 0x6, v0 + tryldglobalbyname 0x8, print + sta v0 + callruntime.ldlazymodulevar 0x2 + sta v1 + throw.undefinedifholewithname defaultImportValue + lda v0 + callarg1 0x9, v1 + returnundefined +label_2: +} + + diff --git a/es2panda/test/version_control/API12beta3/bytecode_feature/lazy_import_bytecode_supported_runtime_version-expected.txt b/es2panda/test/version_control/API12beta3/bytecode_feature/lazy_import_bytecode_supported_runtime_version-expected.txt index da0f8ed91a..6e9673b4de 100644 --- a/es2panda/test/version_control/API12beta3/bytecode_feature/lazy_import_bytecode_supported_runtime_version-expected.txt +++ b/es2panda/test/version_control/API12beta3/bytecode_feature/lazy_import_bytecode_supported_runtime_version-expected.txt @@ -1 +1,2 @@ a1 +a0 diff --git a/es2panda/test/version_control/API12beta3/bytecode_feature/wide_lazy_import_bytecode_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt b/es2panda/test/version_control/API12beta3/bytecode_feature/wide_lazy_import_bytecode_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt new file mode 100644 index 0000000000..3222f27c48 --- /dev/null +++ b/es2panda/test/version_control/API12beta3/bytecode_feature/wide_lazy_import_bytecode_supported_compile_for_higher_or_equal_to_API18_asm_version-expected.txt @@ -0,0 +1,40 @@ +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any .#~@0=#WideSendableLazyLoading(any a0, any a1, any a2) { +label_1: +label_0: + callruntime.wideldlazysendablemodulevar 0xad + sta v0 + throw.undefinedifholewithname a255 + lda v0 + stobjbyname 0x0, name1, a2 + lda a2 + return +label_2: +} + +slotNum = 0x9 +.language ECMAScript +.function any .func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + ldhole + sta v0 + callruntime.definesendableclass 0x0, .#~@0=#WideSendableLazyLoading, _4, 0x0, v0 + sta v0 + mov v2, v0 + newobjrange 0x1, 0x1, v2 + sta v0 + callruntime.wideldlazymodulevar 0xae + sta v1 + throw.undefinedifholewithname a256 + tryldglobalbyname 0x3, print + callarg1 0x4, v0 + tryldglobalbyname 0x6, print + callarg1 0x7, v1 + returnundefined +label_2: +} + + diff --git a/es2panda/test/version_control/API12beta3/syntax_feature/import_target/import_target.ts b/es2panda/test/version_control/API12beta3/syntax_feature/import_target/import_target.ts index 4e0ec5ce3a..6b52c1d49d 100644 --- a/es2panda/test/version_control/API12beta3/syntax_feature/import_target/import_target.ts +++ b/es2panda/test/version_control/API12beta3/syntax_feature/import_target/import_target.ts @@ -17,4 +17,9 @@ export function lazyImportFunc(resolve) { print("lazy ImportFunc called"); resolve(1); +} + +export default function defaultImportFunc(resolve) { + print("lazy ImportFunc called"); + resolve(1); } \ No newline at end of file diff --git a/es2panda/test/version_control/API12beta3/syntax_feature/lazy_import.ts b/es2panda/test/version_control/API12beta3/syntax_feature/lazy_import.ts index 985261dcad..d3081c17aa 100644 --- a/es2panda/test/version_control/API12beta3/syntax_feature/lazy_import.ts +++ b/es2panda/test/version_control/API12beta3/syntax_feature/lazy_import.ts @@ -13,5 +13,5 @@ * limitations under the License. */ -import lazy { lazyImportFunc } from 'import_target/import_target' +import lazy defaultImportFunc, { lazyImportFunc } from 'import_target/import_target' print("lazy import"); \ No newline at end of file diff --git a/es2panda/test/version_control/API12beta3/syntax_feature/lazy_import_supported_compile_version-expected.txt b/es2panda/test/version_control/API12beta3/syntax_feature/lazy_import_supported_compile_version-expected.txt index bacfd1f3f0..cdf751cc03 100644 --- a/es2panda/test/version_control/API12beta3/syntax_feature/lazy_import_supported_compile_version-expected.txt +++ b/es2panda/test/version_control/API12beta3/syntax_feature/lazy_import_supported_compile_version-expected.txt @@ -9,15 +9,42 @@ "loc": { "start": { "line": 16, - "column": 37 + "column": 56 }, "end": { "line": 16, - "column": 66 + "column": 85 } } }, "specifiers": [ + { + "type": "ImportDefaultSpecifier", + "local": { + "type": "Identifier", + "name": "defaultImportFunc", + "loc": { + "start": { + "line": 16, + "column": 13 + }, + "end": { + "line": 16, + "column": 30 + } + } + }, + "loc": { + "start": { + "line": 16, + "column": 13 + }, + "end": { + "line": 16, + "column": 30 + } + } + }, { "type": "ImportSpecifier", "local": { @@ -26,11 +53,11 @@ "loc": { "start": { "line": 16, - "column": 15 + "column": 34 }, "end": { "line": 16, - "column": 29 + "column": 48 } } }, @@ -40,11 +67,11 @@ "loc": { "start": { "line": 16, - "column": 15 + "column": 34 }, "end": { "line": 16, - "column": 29 + "column": 48 } } }, @@ -52,11 +79,11 @@ "loc": { "start": { "line": 16, - "column": 15 + "column": 34 }, "end": { "line": 16, - "column": 29 + "column": 48 } } } @@ -69,7 +96,7 @@ }, "end": { "line": 16, - "column": 66 + "column": 85 } } }, diff --git a/es2panda/util/helpers.cpp b/es2panda/util/helpers.cpp index 67774a04d3..fcc643dfb3 100644 --- a/es2panda/util/helpers.cpp +++ b/es2panda/util/helpers.cpp @@ -983,11 +983,6 @@ bool Helpers::IsSupportLazyImportVersion(int apiVersion, std::string subApiVersi (subApiVersion == SUB_API_VERSION_1 || subApiVersion == SUB_API_VERSION_2))); } -bool Helpers::IsSupportLazyImportDefaultVersion(int apiVersion) -{ - return !(apiVersion < LAZY_IMPORT_DEFAULT_MIN_SUPPORTED_API_VERSION); -} - bool Helpers::IsEnableExpectedPropertyCountApiVersion(int apiVersion) { return !(apiVersion < ENABLE_EXPECTED_PROPERTY_COUNT_MIN_SUPPORTED_API_VERSION); diff --git a/es2panda/util/helpers.h b/es2panda/util/helpers.h index 365de482b8..67b31ec16d 100644 --- a/es2panda/util/helpers.h +++ b/es2panda/util/helpers.h @@ -180,7 +180,6 @@ public: const std::map> &resolveDepsRelation); static bool IsDefaultApiVersion(int apiVersion, std::string subApiVersion); static bool IsSupportLazyImportVersion(int apiVersion, std::string subApiVersion); - static bool IsSupportLazyImportDefaultVersion(int apiVersion); static bool IsEnableExpectedPropertyCountApiVersion(int apiVersion); static const uint32_t MAX_DOUBLE_DIGIT = 310; @@ -217,7 +216,6 @@ public: ABC_TO_PROGRAM_MIN_SUPPORTED_BYTECODE_VERSION {12, 0, 2, 0}; static const int32_t SENDABLE_FUNCTION_MIN_SUPPORTED_API_VERSION = 12; static const int32_t LAZY_IMPORT_MIN_SUPPORTED_API_VERSION = 12; - static const int32_t LAZY_IMPORT_DEFAULT_MIN_SUPPORTED_API_VERSION = 18; static const int32_t SENDABLE_LAZY_LOADING_MIN_SUPPORTED_API_VERSION = 12; static const int8_t SUPER_CALL_OPT_MIN_SUPPORTED_API_VERSION = 18; static const int8_t SENDABLE_CLASS_USING_LOCAL_MODULE_VAR_MIN_SUPPORTED_API_VERSION = 18; -- Gitee From e9bd6dcb85eefc33908b2733da43ba1120f081c1 Mon Sep 17 00:00:00 2001 From: liushitong Date: Thu, 3 Apr 2025 10:54:17 +0800 Subject: [PATCH 143/268] [LSP]: add testing framework for bindings Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC5LWC Signed-off-by: liushitong --- ets2panda/bindings/.gitignore | 4 + ets2panda/bindings/.prettierignore | 1 + ets2panda/bindings/BUILD.gn | 1 + ets2panda/bindings/native/src/lsp.cpp | 14 + ets2panda/bindings/package.json | 5 +- .../bindings/src/Es2pandaNativeModule.ts | 12 +- ets2panda/bindings/src/InteropNativeModule.ts | 2 +- ets2panda/bindings/src/Platform.ts | 5 +- ets2panda/bindings/src/Wrapper.ts | 4 +- ets2panda/bindings/src/arrays.ts | 34 +- ets2panda/bindings/src/buildConfigGenerate.ts | 2 +- ets2panda/bindings/src/global.ts | 9 +- ets2panda/bindings/src/loadLibraries.ts | 7 +- ets2panda/bindings/src/lspNode.ts | 4 +- ets2panda/bindings/src/lsp_helper.ts | 14 +- ets2panda/bindings/src/private.ts | 1 + ets2panda/bindings/src/strings.ts | 10 +- ets2panda/bindings/test/README.md | 64 +++ .../expected/getCompletionAtPosition.json | 372 ++++++++++++ .../test/expected/getCurrentTokenValue.json | 6 + .../expected/getDefinitionAtPosition.json | 52 ++ .../test/expected/getDocumentHighlights.json | 317 +++++++++++ .../test/expected/getFileReferences.json | 26 + .../test/expected/getQuickInfoAtPosition.json | 107 ++++ .../expected/getReferencesAtPosition.json | 53 ++ .../test/expected/getSemanticDiagnostics.json | 75 +++ .../expected/getSuggestionDiagnostics.json | 534 ++++++++++++++++++ .../expected/getSyntacticDiagnostics.json | 295 ++++++++++ .../test/expected/toLineColumnOffset.json | 10 + ets2panda/bindings/test/prepare.ps1 | 110 ++++ ets2panda/bindings/test/prepare.sh | 74 +++ ets2panda/bindings/test/run_tests.ts | 278 +++++++++ ets2panda/bindings/test/testcases/cases.json | 225 ++++++++ .../getCompletionsAtPosition1.ets | 26 + .../getCompletionsAtPosition10.ets | 21 + .../getCompletionsAtPosition11.ets | 20 + .../getCompletionsAtPosition12.ets | 22 + .../getCompletionsAtPosition13.ets | 19 + .../getCompletionsAtPosition14.ets | 19 + .../getCompletionsAtPosition2.ets | 27 + .../getCompletionsAtPosition3.ets | 32 ++ .../getCompletionsAtPosition4.ets | 29 + .../getCompletionsAtPosition5.ets | 21 + .../getCompletionsAtPosition6.ets | 21 + .../getCompletionsAtPosition7.ets | 20 + .../getCompletionsAtPosition8.ets | 16 + .../getCompletionsAtPosition9.ets | 16 + .../getCurrentTokenValue1.ets | 16 + .../getCurrentTokenValue2.ets | 16 + .../getCurrentTokenValue3.ets | 16 + .../getCurrentTokenValue4.ets | 16 + .../getDefinitionAtPosition1.ets | 18 + .../getDefinitionAtPosition10.ets | 19 + .../getDefinitionAtPosition11.ets | 18 + .../getDefinitionAtPosition12.ets | 16 + .../getDefinitionAtPosition13.ets | 17 + .../getDefinitionAtPosition14.ets | 16 + .../getDefinitionAtPosition15.ets | 18 + .../getDefinitionAtPosition16.ets | 19 + .../getDefinitionAtPosition17.ets | 18 + .../getDefinitionAtPosition18.ets | 47 ++ .../getDefinitionAtPosition2.ets | 17 + .../getDefinitionAtPosition3.ets | 23 + .../getDefinitionAtPosition4.ets | 18 + .../getDefinitionAtPosition5.ets | 17 + .../getDefinitionAtPosition6.ets | 19 + .../getDefinitionAtPosition7.ets | 18 + .../getDefinitionAtPosition8.ets | 18 + .../getDefinitionAtPosition9.ets | 17 + .../getDocumentHighlights1.ets | 18 + .../getDocumentHighlights2.ets | 21 + .../getDocumentHighlights3.ets | 26 + .../getDocumentHighlights4.ets | 26 + .../getDocumentHighlights5.ets | 26 + .../getDocumentHighlights6.ets | 23 + .../getDocumentHighlights7.ets | 24 + .../getFileReferences/getFileReferences1.ets | 19 + .../getFileReferences1_export.ets | 21 + .../getQuickInfoAtPosition1.ets | 16 + .../getQuickInfoAtPosition2.ets | 18 + .../getQuickInfoAtPosition3.ets | 17 + .../getReferencesAtPosition1.ets | 16 + .../getReferencesAtPosition2.ets | 23 + .../getReferencesAtPosition3.ets | 17 + .../getReferencesAtPosition4.ets | 16 + .../getReferencesAtPosition5.ets | 17 + .../getSemanticDiagnostics1.ets | 20 + .../getSemanticDiagnostics2.ets | 20 + .../getSuggestionDiagnostics1.ets | 22 + .../getSyntacticDiagnostics1.ets | 20 + .../getSyntacticDiagnostics2.ets | 20 + .../toLineColumnOffset1.ets | 18 + ets2panda/bindings/test/tsconfig.json | 21 + 93 files changed, 3897 insertions(+), 41 deletions(-) create mode 100644 ets2panda/bindings/test/README.md create mode 100644 ets2panda/bindings/test/expected/getCompletionAtPosition.json create mode 100644 ets2panda/bindings/test/expected/getCurrentTokenValue.json create mode 100644 ets2panda/bindings/test/expected/getDefinitionAtPosition.json create mode 100644 ets2panda/bindings/test/expected/getDocumentHighlights.json create mode 100644 ets2panda/bindings/test/expected/getFileReferences.json create mode 100644 ets2panda/bindings/test/expected/getQuickInfoAtPosition.json create mode 100644 ets2panda/bindings/test/expected/getReferencesAtPosition.json create mode 100644 ets2panda/bindings/test/expected/getSemanticDiagnostics.json create mode 100644 ets2panda/bindings/test/expected/getSuggestionDiagnostics.json create mode 100644 ets2panda/bindings/test/expected/getSyntacticDiagnostics.json create mode 100644 ets2panda/bindings/test/expected/toLineColumnOffset.json create mode 100644 ets2panda/bindings/test/prepare.ps1 create mode 100755 ets2panda/bindings/test/prepare.sh create mode 100644 ets2panda/bindings/test/run_tests.ts create mode 100644 ets2panda/bindings/test/testcases/cases.json create mode 100644 ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition1.ets create mode 100644 ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition10.ets create mode 100644 ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition11.ets create mode 100644 ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition12.ets create mode 100644 ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition13.ets create mode 100644 ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition14.ets create mode 100644 ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition2.ets create mode 100644 ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition3.ets create mode 100644 ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition4.ets create mode 100644 ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition5.ets create mode 100644 ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition6.ets create mode 100644 ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition7.ets create mode 100644 ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition8.ets create mode 100644 ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition9.ets create mode 100644 ets2panda/bindings/test/testcases/getCurrentTokenValue/getCurrentTokenValue1.ets create mode 100644 ets2panda/bindings/test/testcases/getCurrentTokenValue/getCurrentTokenValue2.ets create mode 100644 ets2panda/bindings/test/testcases/getCurrentTokenValue/getCurrentTokenValue3.ets create mode 100644 ets2panda/bindings/test/testcases/getCurrentTokenValue/getCurrentTokenValue4.ets create mode 100644 ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition1.ets create mode 100644 ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition10.ets create mode 100644 ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition11.ets create mode 100644 ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition12.ets create mode 100644 ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition13.ets create mode 100644 ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition14.ets create mode 100644 ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition15.ets create mode 100644 ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition16.ets create mode 100644 ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition17.ets create mode 100644 ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition18.ets create mode 100644 ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition2.ets create mode 100644 ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition3.ets create mode 100644 ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition4.ets create mode 100644 ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition5.ets create mode 100644 ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition6.ets create mode 100644 ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition7.ets create mode 100644 ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition8.ets create mode 100644 ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition9.ets create mode 100644 ets2panda/bindings/test/testcases/getDocumentHighlights/getDocumentHighlights1.ets create mode 100644 ets2panda/bindings/test/testcases/getDocumentHighlights/getDocumentHighlights2.ets create mode 100644 ets2panda/bindings/test/testcases/getDocumentHighlights/getDocumentHighlights3.ets create mode 100644 ets2panda/bindings/test/testcases/getDocumentHighlights/getDocumentHighlights4.ets create mode 100644 ets2panda/bindings/test/testcases/getDocumentHighlights/getDocumentHighlights5.ets create mode 100644 ets2panda/bindings/test/testcases/getDocumentHighlights/getDocumentHighlights6.ets create mode 100644 ets2panda/bindings/test/testcases/getDocumentHighlights/getDocumentHighlights7.ets create mode 100644 ets2panda/bindings/test/testcases/getFileReferences/getFileReferences1.ets create mode 100644 ets2panda/bindings/test/testcases/getFileReferences/getFileReferences1_export.ets create mode 100644 ets2panda/bindings/test/testcases/getQuickInfoAtPosition/getQuickInfoAtPosition1.ets create mode 100644 ets2panda/bindings/test/testcases/getQuickInfoAtPosition/getQuickInfoAtPosition2.ets create mode 100644 ets2panda/bindings/test/testcases/getQuickInfoAtPosition/getQuickInfoAtPosition3.ets create mode 100644 ets2panda/bindings/test/testcases/getReferencesAtPosition/getReferencesAtPosition1.ets create mode 100644 ets2panda/bindings/test/testcases/getReferencesAtPosition/getReferencesAtPosition2.ets create mode 100644 ets2panda/bindings/test/testcases/getReferencesAtPosition/getReferencesAtPosition3.ets create mode 100644 ets2panda/bindings/test/testcases/getReferencesAtPosition/getReferencesAtPosition4.ets create mode 100644 ets2panda/bindings/test/testcases/getReferencesAtPosition/getReferencesAtPosition5.ets create mode 100644 ets2panda/bindings/test/testcases/getSemanticDiagnostics/getSemanticDiagnostics1.ets create mode 100644 ets2panda/bindings/test/testcases/getSemanticDiagnostics/getSemanticDiagnostics2.ets create mode 100644 ets2panda/bindings/test/testcases/getSuggestionDiagnostics/getSuggestionDiagnostics1.ets create mode 100644 ets2panda/bindings/test/testcases/getSyntacticDiagnostics/getSyntacticDiagnostics1.ets create mode 100644 ets2panda/bindings/test/testcases/getSyntacticDiagnostics/getSyntacticDiagnostics2.ets create mode 100644 ets2panda/bindings/test/testcases/toLineColumnOffset/toLineColumnOffset1.ets create mode 100644 ets2panda/bindings/test/tsconfig.json diff --git a/ets2panda/bindings/.gitignore b/ets2panda/bindings/.gitignore index 615082737b..f6853a729b 100644 --- a/ets2panda/bindings/.gitignore +++ b/ets2panda/bindings/.gitignore @@ -1,4 +1,8 @@ node_modules/* dist/* +dist-test/* package-lock.json tsconfig.tsbuildinfo +ets/ +ets2panda +.idea/ \ No newline at end of file diff --git a/ets2panda/bindings/.prettierignore b/ets2panda/bindings/.prettierignore index 752fdaad79..2f3613c277 100644 --- a/ets2panda/bindings/.prettierignore +++ b/ets2panda/bindings/.prettierignore @@ -20,3 +20,4 @@ node_modules/** **.json **.js **.md +**.ets diff --git a/ets2panda/bindings/BUILD.gn b/ets2panda/bindings/BUILD.gn index 5db6f1d96d..e6dbc5c5f4 100644 --- a/ets2panda/bindings/BUILD.gn +++ b/ets2panda/bindings/BUILD.gn @@ -75,6 +75,7 @@ shared_library("ts_bindings") { } if (is_linux) { + libs = [ "stdc++fs" ] cflags_cc = [ "-std=c++17", "-Wall", diff --git a/ets2panda/bindings/native/src/lsp.cpp b/ets2panda/bindings/native/src/lsp.cpp index 254eaf869e..7f9c2e23ef 100644 --- a/ets2panda/bindings/native/src/lsp.cpp +++ b/ets2panda/bindings/native/src/lsp.cpp @@ -436,6 +436,20 @@ KNativePointer impl_getTextSpan(KNativePointer quickInfoPtr) } TS_INTEROP_1(getTextSpan, KNativePointer, KNativePointer) +KNativePointer impl_getHighlightTextSpan(KNativePointer highlightPtr) +{ + auto *highlight = reinterpret_cast(highlightPtr); + return new TextSpan(highlight->textSpan_); +} +TS_INTEROP_1(getHighlightTextSpan, KNativePointer, KNativePointer) + +KNativePointer impl_getHighlightContextSpan(KNativePointer highlightPtr) +{ + auto *highlight = reinterpret_cast(highlightPtr); + return new TextSpan(highlight->contextSpan_); +} +TS_INTEROP_1(getHighlightContextSpan, KNativePointer, KNativePointer) + KNativePointer impl_getHighlightFileName(KNativePointer highlightPtr) { auto *highlight = reinterpret_cast(highlightPtr); diff --git a/ets2panda/bindings/package.json b/ets2panda/bindings/package.json index 193f7b1b8a..92d680af8d 100644 --- a/ets2panda/bindings/package.json +++ b/ets2panda/bindings/package.json @@ -12,7 +12,10 @@ }, "main": "dist/index.js", "scripts": { - "test": "echo \"Error: no test specified\" && exit 1", + "test:clean": "rimraf dist-test", + "test:compile": "tsc --build --verbose test/tsconfig.json", + "test:build": "npm run test:clean && npm run test:compile", + "test": "npm run test:build && node dist-test/test/run_tests.js ./test", "compile": "tsc --build --verbose tsconfig.json", "clean": "rimraf dist tsconfig.tsbuildinfo package-lock.json", "run": "npm run clean && npm run compile", diff --git a/ets2panda/bindings/src/Es2pandaNativeModule.ts b/ets2panda/bindings/src/Es2pandaNativeModule.ts index 89ed6a70f7..643cb0b3d4 100644 --- a/ets2panda/bindings/src/Es2pandaNativeModule.ts +++ b/ets2panda/bindings/src/Es2pandaNativeModule.ts @@ -316,6 +316,14 @@ export class Es2pandaNativeModule { throw new Error('Not implemented'); } + _getHighlightTextSpan(ptr: KNativePointer): KPtr { + throw new Error('Not implemented'); + } + + _getHighlightContextSpan(ptr: KNativePointer): KPtr { + throw new Error('Not implemented'); + } + _getHighlightFileName(ptr: KNativePointer): KPtr { throw new Error('Not implemented'); } @@ -459,7 +467,7 @@ export function initGeneratedEs2panda(): GeneratedEs2pandaNativeModule { export function initPublicEs2panda(): Es2pandaNativeModule { let libPath = process.env.BINDINGS_PATH; - if (libPath == undefined) { + if (libPath === undefined) { libPath = path.resolve(__dirname, '../public.node'); } else { libPath = path.join(libPath, 'public.node'); @@ -475,7 +483,7 @@ export function initPublicEs2panda(): Es2pandaNativeModule { export function initPublicGeneratedEs2panda(): GeneratedEs2pandaNativeModule { let libPath = process.env.BINDINGS_PATH; - if (libPath == undefined) { + if (libPath === undefined) { libPath = path.resolve(__dirname, '../public.node'); } else { libPath = path.join(libPath, 'public.node'); diff --git a/ets2panda/bindings/src/InteropNativeModule.ts b/ets2panda/bindings/src/InteropNativeModule.ts index 3531703067..35eac9b806 100644 --- a/ets2panda/bindings/src/InteropNativeModule.ts +++ b/ets2panda/bindings/src/InteropNativeModule.ts @@ -75,7 +75,7 @@ export function initInterop(): InteropNativeModule { export function initPublicInterop(): InteropNativeModule { let libPath = process.env.BINDINGS_PATH; - if (libPath == undefined) { + if (libPath === undefined) { libPath = path.resolve(__dirname, '../public.node'); } else { libPath = path.join(libPath, 'public.node'); diff --git a/ets2panda/bindings/src/Platform.ts b/ets2panda/bindings/src/Platform.ts index 37c2159d2e..b0e3fa192f 100644 --- a/ets2panda/bindings/src/Platform.ts +++ b/ets2panda/bindings/src/Platform.ts @@ -56,6 +56,7 @@ export abstract class ArrayDecoder { // TODO: the semicolons after methods in these interfaces are to // workaround ArkTS compiler parser bug export interface CallbackRegistry { + // CC-OFFNXT(no_explicit_any) project code style registerCallback(callback: any, obj: any): KPointer; } @@ -66,7 +67,9 @@ export interface PlatformDefinedData { } export function withStringResult(ptr: KPointer): string | undefined { - if (isNullPtr(ptr)) return undefined; + if (isNullPtr(ptr)) { + return undefined; + } let managedString = new NativeString(ptr); let result = managedString?.toString(); managedString?.close(); diff --git a/ets2panda/bindings/src/Wrapper.ts b/ets2panda/bindings/src/Wrapper.ts index 66c17e8918..26d9ac15f6 100644 --- a/ets2panda/bindings/src/Wrapper.ts +++ b/ets2panda/bindings/src/Wrapper.ts @@ -19,11 +19,11 @@ export function isNullPtr(value: KPointer): boolean { return value === nullptr; } -export function ptrToString(ptr: KPointer) { +export function ptrToString(ptr: KPointer): string { return `0x${ptr!.toString(16).padStart(8, '0')}`; } -export function isSamePtr(a: KPointer, b: KPointer) { +export function isSamePtr(a: KPointer, b: KPointer): boolean { return a === b; } diff --git a/ets2panda/bindings/src/arrays.ts b/ets2panda/bindings/src/arrays.ts index 54d05cb613..d0fe749945 100644 --- a/ets2panda/bindings/src/arrays.ts +++ b/ets2panda/bindings/src/arrays.ts @@ -46,18 +46,22 @@ function withArray(data: C | undefined, exec: ExecWithL return exec(data ?? null, data?.length ?? 0); } -export function withPtrArray(data: BigUint64Array, access: Access, exec: ExecWithLength) { +export function withPtrArray( + data: BigUint64Array, + access: Access, + exec: ExecWithLength +): R { return exec(data ?? null, data?.length ?? 0); // TODO rethink } export function toPtrArray(data: Array | undefined): BigUint64Array { - if (data == undefined || data.length === 0) { + if (data === undefined || data.length === 0) { return new BigUint64Array(0); } const array = new BigUint64Array(data.length); for (let i = 0; i < data.length; i++) { let item = data[i]; - array[i] = item != undefined ? (item.ptr as bigint) : nullptr; + array[i] = item !== undefined ? (item.ptr as bigint) : nullptr; } return array; } @@ -69,7 +73,7 @@ export function fromPtrArray(array: PtrArray, factory: (ptr: const result = new Array(array.length); for (let i = 0; i < array.length; i++) { let ptr = array[i]; - if (ptr == nullptr) { + if (ptr === nullptr) { result[i] = undefined; } else { result[i] = factory(ptr); @@ -89,49 +93,49 @@ export function withInt8Array( data: Int8Array | undefined, access: Access, exec: ExecWithLength -) { +): T { return withArray(data, exec); } export function withUint16Array( data: Uint16Array | undefined, access: Access, exec: ExecWithLength -) { +): T { return withArray(data, exec); } export function withInt16Array( data: Int16Array | undefined, access: Access, exec: ExecWithLength -) { +): T { return withArray(data, exec); } export function withUint32Array( data: Uint32Array | undefined, access: Access, exec: ExecWithLength -) { +): T { return withArray(data, exec); } export function withInt32Array( data: Int32Array | undefined, access: Access, exec: ExecWithLength -) { +): T { return withArray(data, exec); } export function withFloat32Array( data: Float32Array | undefined, access: Access, exec: ExecWithLength -) { +): T { return withArray(data, exec); } export function withFloat64Array( data: Float64Array | undefined, access: Access, exec: ExecWithLength -) { +): T { return withArray(data, exec); } export function wasmHeap(): ArrayBuffer { @@ -143,11 +147,11 @@ export enum Access { WRITE = 2, // 1 << 1, READWRITE = 3 // READ | WRITE } -export function isRead(access: Access) { - return access & Access.READ; +export function isRead(access: Access): boolean { + return !!(access & Access.READ); } -export function isWrite(access: Access) { - return access & Access.WRITE; +export function isWrite(access: Access): boolean { + return !!(access & Access.WRITE); } export type Exec = (pointer: P) => R; diff --git a/ets2panda/bindings/src/buildConfigGenerate.ts b/ets2panda/bindings/src/buildConfigGenerate.ts index fa34184ed1..4d1b1c34d1 100644 --- a/ets2panda/bindings/src/buildConfigGenerate.ts +++ b/ets2panda/bindings/src/buildConfigGenerate.ts @@ -50,7 +50,7 @@ function parseJson5(filePath: string): Json5Object { return JSON5.parse(cleanedContent) as Json5Object; } catch (error) { console.error(`Error parsing ${filePath}:`, error); - process.exit(1); + return {} as Json5Object; } } diff --git a/ets2panda/bindings/src/global.ts b/ets2panda/bindings/src/global.ts index 9578770a53..2c99dce5ca 100644 --- a/ets2panda/bindings/src/global.ts +++ b/ets2panda/bindings/src/global.ts @@ -26,6 +26,7 @@ import { Es2pandaNativeModule as GeneratedEs2pandaNativeModule } from './generat import { initInterop, InteropNativeModule, initPublicInterop } from './InteropNativeModule'; import { Context } from './types'; +// CC-OFFNXT(G.NAM.01) project code style export class global { public static filePath: string = './examples/input/main.ets'; @@ -92,12 +93,16 @@ export class global { private static _interop: InteropNativeModule | undefined = undefined; private static _interopPublic: InteropNativeModule | undefined = undefined; public static get interop(): InteropNativeModule { - if (this._interop === undefined) this._interop = initInterop(); + if (this._interop === undefined) { + this._interop = initInterop(); + } return this._interop; } public static get interopPublic(): InteropNativeModule { - if (this._interopPublic === undefined) this._interopPublic = initPublicInterop(); + if (this._interopPublic === undefined) { + this._interopPublic = initPublicInterop(); + } return this._interopPublic; } } diff --git a/ets2panda/bindings/src/loadLibraries.ts b/ets2panda/bindings/src/loadLibraries.ts index 44e6d1c60e..f58ec7714a 100644 --- a/ets2panda/bindings/src/loadLibraries.ts +++ b/ets2panda/bindings/src/loadLibraries.ts @@ -18,23 +18,26 @@ import * as path from 'path'; const nativeModuleLibraries: Map = new Map(); export function loadNativeLibrary(name: string): Record { + // CC-OFFNXT(no_explicit_any) project code style if ((globalThis as any).requireNapi) { + // CC-OFFNXT(no_explicit_any) project code style return (globalThis as any).requireNapi(name, true); } else { const suffixedName = name.endsWith('.node') ? name : `${name}.node`; if (process.platform === 'win32') { return require(suffixedName); } else { + // CC-OFFNXT(no_eval) project code style return eval(`let exports = {}; process.dlopen({ exports }, require.resolve("${suffixedName}"), 2); exports`); } } } -export function registerNativeModuleLibraryName(nativeModule: string, libraryName: string) { +export function registerNativeModuleLibraryName(nativeModule: string, libraryName: string): void { nativeModuleLibraries.set(nativeModule, libraryName); } -export function loadNativeModuleLibrary(moduleName: string, module?: object) { +export function loadNativeModuleLibrary(moduleName: string, module?: object): void { if (!module) { throw new Error(' argument is required and optional only for compatibility with ArkTS'); } diff --git a/ets2panda/bindings/src/lspNode.ts b/ets2panda/bindings/src/lspNode.ts index 4126a58541..7bb465f526 100644 --- a/ets2panda/bindings/src/lspNode.ts +++ b/ets2panda/bindings/src/lspNode.ts @@ -238,8 +238,8 @@ export class LspHighlightSpan extends LspNode { constructor(peer: KNativePointer) { super(peer); this.fileName = unpackString(global.es2panda._getHighlightFileName(peer)); - this.textSpan = new LspTextSpan(global.es2panda._getTextSpan(peer)); - this.contextSpan = new LspTextSpan(global.es2panda._getTextSpan(peer)); + this.textSpan = new LspTextSpan(global.es2panda._getHighlightTextSpan(peer)); + this.contextSpan = new LspTextSpan(global.es2panda._getHighlightContextSpan(peer)); this.kind = global.es2panda._getHighlightKind(peer); } readonly fileName: String; diff --git a/ets2panda/bindings/src/lsp_helper.ts b/ets2panda/bindings/src/lsp_helper.ts index e9ea9a2fd5..48bbf71c16 100644 --- a/ets2panda/bindings/src/lsp_helper.ts +++ b/ets2panda/bindings/src/lsp_helper.ts @@ -57,7 +57,7 @@ export class Lsp { this.fileNameToArktsconfig = JSON.parse(fs.readFileSync(compileFileInfoPath, 'utf-8')); let buildConfigPath = path.join(projectPath, '.idea', '.deveco', 'lsp_build_config.json'); this.moduleToBuildConfig = JSON.parse(fs.readFileSync(buildConfigPath, 'utf-8')); - this.getFileContent = getContentCallback || ((path) => fs.readFileSync(path, 'utf8')); + this.getFileContent = getContentCallback || ((path: string): string => fs.readFileSync(path, 'utf8')); } updateConfig(buildSdkPath: string, modules?: ModuleDescriptor[]): void { @@ -147,12 +147,12 @@ export class Lsp { getFileReferences(filename: String): LspReferenceData[] { let lspDriverHelper = new LspDriverHelper(); - let filePath = path.resolve(filename.valueOf()); - let arktsconfig = this.fileNameToArktsconfig[filePath]; + let searchFilePath = path.resolve(filename.valueOf()); + let arktsconfig = this.fileNameToArktsconfig[searchFilePath]; let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; - let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); - const source = this.getFileContent(filePath).replace(/\r\n/g, '\n'); - let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); + let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, searchFilePath, this.pandaLibPath); + const source = this.getFileContent(searchFilePath).replace(/\r\n/g, '\n'); + let localCtx = lspDriverHelper.createCtx(source, searchFilePath, localCfg); PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); PluginDriver.getInstance().runPluginHook(PluginHook.PARSED); @@ -175,7 +175,7 @@ export class Lsp { lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); PluginDriver.getInstance().runPluginHook(PluginHook.PARSED); lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED); - let ptr = global.es2panda._getFileReferences(filePath, localCtx, isPackageModule); + let ptr = global.es2panda._getFileReferences(searchFilePath, localCtx, isPackageModule); let refs = new LspReferences(ptr); PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); lspDriverHelper.destroyContext(localCtx); diff --git a/ets2panda/bindings/src/private.ts b/ets2panda/bindings/src/private.ts index 0392b1006c..777aad9066 100644 --- a/ets2panda/bindings/src/private.ts +++ b/ets2panda/bindings/src/private.ts @@ -39,6 +39,7 @@ export function unpackNode(peer: KNativePointer): T | undefin if (peer === nullptr) { return undefined; } + return undefined; } export function unpackNodeArray(nodesPtr: KNativePointer): readonly T[] { diff --git a/ets2panda/bindings/src/strings.ts b/ets2panda/bindings/src/strings.ts index cf3cac9e86..ff72c1626e 100644 --- a/ets2panda/bindings/src/strings.ts +++ b/ets2panda/bindings/src/strings.ts @@ -32,7 +32,7 @@ export class CustomTextEncoder { static readonly HeaderLen: int32 = Int32Array.BYTES_PER_ELEMENT; constructor( - encoder: SystemTextEncoder | undefined = typeof TextEncoder != 'undefined' ? new TextEncoder() : undefined + encoder: SystemTextEncoder | undefined = typeof TextEncoder !== 'undefined' ? new TextEncoder() : undefined ) { this.encoder = encoder; } @@ -181,13 +181,13 @@ export class CustomTextDecoder { if (lead < 0x80) { count = 1; value = elem; - } else if (lead >> 5 == 0x6) { + } else if (lead >> 5 === 0x6) { value = ((elem << 6) & 0x7ff) + (input[index + 1] & 0x3f); count = 2; - } else if (lead >> 4 == 0xe) { + } else if (lead >> 4 === 0xe) { value = ((elem << 12) & 0xffff) + ((input[index + 1] << 6) & 0xfff) + (input[index + 2] & 0x3f); count = 3; - } else if (lead >> 3 == 0x1e) { + } else if (lead >> 3 === 0x1e) { value = ((elem << 18) & 0x1fffff) + ((input[index + 1] << 12) & 0x3ffff) + @@ -196,7 +196,7 @@ export class CustomTextDecoder { count = 4; } codePoints[cpIndex++] = value; - if (cpIndex == cpSize) { + if (cpIndex === cpSize) { cpIndex = 0; result += String.fromCodePoint(...codePoints); } diff --git a/ets2panda/bindings/test/README.md b/ets2panda/bindings/test/README.md new file mode 100644 index 0000000000..76f2db4389 --- /dev/null +++ b/ets2panda/bindings/test/README.md @@ -0,0 +1,64 @@ +### How to run bindings test? + +```Bash +cd /path/to/bindings + +### check environment, replace the path base on your machine +# if you are using Linux shell +bash test/prepare.sh +# or if you are using Windows shell +powershell -f test/prepare.ps1 + +### run test +npm install +npm run test + +### restore the path to the original state +bash test/prepare.sh --restore +# or +powershell -f test/prepare.ps1 --restore +``` + +#### tips +1. If you want to update a lot of expected results, you can use `node dist-test/test/run_tests.js ./test --update` + +### testcase directory structure +. +├── expected +│   ├── exampleFuncName.json +└── testcases +    ├── .idea +    │   └── .deveco +    │   ├── exampleFuncName +    │   │   └── arktsconfig.json +    │   ├── lsp_build_config.json +    │   └── lsp_compileFileInfos.json +    ├── cases.json +    └── exampleFuncName +       └── exampleFuncName1.ets + +case.json: +```json +{ + "testName": { + "expectedFilePath": "/path/to/expected.json", + "1": [ "param1", "param2" ], // lsp will call lsp.testName(param1, param2) + "2": [ "param1", "param2" ] + } +} +``` + +#### How to add a new test case? +1. add exampleFuncName2.ets file in `testcases/exampleFuncName` +2. add parameters in `testcases/cases.json` +3. add expected result in `expected/exampleFuncName.json` + +#### How to add a new test function? +1. add exampleFuncName2 directory in `testcases` +2. add exampleFuncName2 field in `testcases/cases.json` +3. add exampleFuncName2.json in `expected` +4. add a new test case according to the above steps + +⚠️⚠️⚠️ +Before push your code, please make sure that the path formats in all JSON files under the testcases directory are correct. +Incorrect path formats will render the function of prepare.sh ineffective, and manually handling the paths can be quite annoying. \ No newline at end of file diff --git a/ets2panda/bindings/test/expected/getCompletionAtPosition.json b/ets2panda/bindings/test/expected/getCompletionAtPosition.json new file mode 100644 index 0000000000..cfb523e800 --- /dev/null +++ b/ets2panda/bindings/test/expected/getCompletionAtPosition.json @@ -0,0 +1,372 @@ +{ + "1": { + "entries": [ + { + "name": "namespace", + "sortText": "15", + "insertText": "", + "kind": 14, + "data": null + }, + { + "name": "native", + "sortText": "15", + "insertText": "", + "kind": 14, + "data": null + }, + { + "name": "never", + "sortText": "15", + "insertText": "", + "kind": 14, + "data": null + }, + { + "name": "new", + "sortText": "15", + "insertText": "", + "kind": 14, + "data": null + }, + { + "name": "null", + "sortText": "15", + "insertText": "", + "kind": 14, + "data": null + }, + { + "name": "num1", + "sortText": "15", + "insertText": "", + "kind": 3, + "data": null + }, + { + "name": "num2", + "sortText": "15", + "insertText": "", + "kind": 3, + "data": null + }, + { + "name": "number", + "sortText": "15", + "insertText": "", + "kind": 14, + "data": null + } + ] + }, + "2": { + "entries": [ + { + "name": "aaa", + "sortText": "15", + "insertText": "", + "kind": 6, + "data": null + }, + { + "name": "abb", + "sortText": "15", + "insertText": "", + "kind": 21, + "data": null + }, + { + "name": "abstract", + "sortText": "15", + "insertText": "", + "kind": 14, + "data": null + }, + { + "name": "any", + "sortText": "15", + "insertText": "", + "kind": 14, + "data": null + }, + { + "name": "anyref", + "sortText": "15", + "insertText": "", + "kind": 14, + "data": null + }, + { + "name": "arguments", + "sortText": "15", + "insertText": "", + "kind": 14, + "data": null + }, + { + "name": "as", + "sortText": "15", + "insertText": "", + "kind": 14, + "data": null + }, + { + "name": "asserts", + "sortText": "15", + "insertText": "", + "kind": 14, + "data": null + }, + { + "name": "async", + "sortText": "15", + "insertText": "", + "kind": 14, + "data": null + }, + { + "name": "await", + "sortText": "15", + "insertText": "", + "kind": 14, + "data": null + }, + { + "name": "axx", + "sortText": "15", + "insertText": "", + "kind": 3, + "data": null + } + ] + }, + "3": { + "entries": [ + { + "name": "baa", + "sortText": "15", + "insertText": "", + "kind": 6, + "data": null + }, + { + "name": "bbb", + "sortText": "15", + "insertText": "", + "kind": 6, + "data": null + }, + { + "name": "bcc", + "sortText": "15", + "insertText": "", + "kind": 6, + "data": null + }, + { + "name": "bigint", + "sortText": "15", + "insertText": "", + "kind": 14, + "data": null + }, + { + "name": "boolean", + "sortText": "15", + "insertText": "", + "kind": 14, + "data": null + }, + { + "name": "break", + "sortText": "15", + "insertText": "", + "kind": 14, + "data": null + }, + { + "name": "bxx", + "sortText": "15", + "insertText": "", + "kind": 3, + "data": null + }, + { + "name": "byte", + "sortText": "15", + "insertText": "", + "kind": 14, + "data": null + } + ] + }, + "4": { + "entries": [ + { + "name": "baa", + "sortText": "15", + "insertText": "", + "kind": 6, + "data": null + }, + { + "name": "bbb", + "sortText": "15", + "insertText": "", + "kind": 6, + "data": null + }, + { + "name": "bigint", + "sortText": "15", + "insertText": "", + "kind": 14, + "data": null + }, + { + "name": "boolean", + "sortText": "15", + "insertText": "", + "kind": 14, + "data": null + }, + { + "name": "break", + "sortText": "15", + "insertText": "", + "kind": 14, + "data": null + }, + { + "name": "bxx", + "sortText": "15", + "insertText": "", + "kind": 3, + "data": null + }, + { + "name": "byte", + "sortText": "15", + "insertText": "", + "kind": 14, + "data": null + } + ] + }, + "5": { + "entries": [ + { + "name": "myProp", + "sortText": "14", + "insertText": "", + "kind": 10, + "data": null + } + ] + }, + "6": { + "entries": [ + { + "name": "classInSpace", + "sortText": "13", + "insertText": "", + "kind": 7, + "data": null + } + ] + }, + "7": { + "entries": [ + { + "name": "Red", + "sortText": "13", + "insertText": "", + "kind": 20, + "data": null + } + ] + }, + "8": { + "entries": [] + }, + "9": { + "entries": [ + { + "name": "number", + "sortText": "15", + "insertText": "", + "kind": 14, + "data": null + } + ] + }, + "10": { + "entries": [ + { + "name": "classInSpace", + "sortText": "13", + "insertText": "", + "kind": 7, + "data": null + } + ] + }, + "11": { + "entries": [ + { + "name": "Blue", + "sortText": "13", + "insertText": "", + "kind": 20, + "data": null + }, + { + "name": "Red", + "sortText": "13", + "insertText": "", + "kind": 20, + "data": null + } + ] + }, + "12": { + "entries": [ + { + "name": "myProp", + "sortText": "14", + "insertText": "", + "kind": 10, + "data": null + }, + { + "name": "prop", + "sortText": "14", + "insertText": "", + "kind": 10, + "data": null + } + ] + }, + "13": { + "entries": [ + { + "name": "key", + "sortText": "17", + "insertText": "", + "kind": 2, + "data": null + } + ] + }, + "14": { + "entries": [ + { + "name": "key", + "sortText": "17", + "insertText": "", + "kind": 2, + "data": null + } + ] + } +} \ No newline at end of file diff --git a/ets2panda/bindings/test/expected/getCurrentTokenValue.json b/ets2panda/bindings/test/expected/getCurrentTokenValue.json new file mode 100644 index 0000000000..2efc1c7dcc --- /dev/null +++ b/ets2panda/bindings/test/expected/getCurrentTokenValue.json @@ -0,0 +1,6 @@ +{ + "1": "ab", + "2": "ab", + "3": "ab", + "4": "ab" +} \ No newline at end of file diff --git a/ets2panda/bindings/test/expected/getDefinitionAtPosition.json b/ets2panda/bindings/test/expected/getDefinitionAtPosition.json new file mode 100644 index 0000000000..74bd51b3c2 --- /dev/null +++ b/ets2panda/bindings/test/expected/getDefinitionAtPosition.json @@ -0,0 +1,52 @@ +{ + "1": { + "fileName": "getDefinitionAtPosition1.ets", + "start": 625, + "length": 1 + }, + "2": { + "fileName": "getDefinitionAtPosition3.ets", + "start": 618, + "length": 1 + }, + "3": { + "fileName": "getDefinitionAtPosition4.ets", + "start": 625, + "length": 1 + }, + "4": { + "fileName": "getDefinitionAtPosition6.ets", + "start": 626, + "length": 3 + }, + "5": { + "fileName": "getDefinitionAtPosition8.ets", + "start": 625, + "length": 1 + }, + "6": { + "fileName": "getDefinitionAtPosition10.ets", + "start": 626, + "length": 3 + }, + "7": { + "fileName": "getDefinitionAtPosition12.ets", + "start": 620, + "length": 1 + }, + "8": { + "fileName": "getDefinitionAtPosition14.ets", + "start": 626, + "length": 1 + }, + "9": { + "fileName": "getDefinitionAtPosition16.ets", + "start": 622, + "length": 3 + }, + "10": { + "fileName": "text.d.ets", + "start": 7586, + "length": 4 + } +} \ No newline at end of file diff --git a/ets2panda/bindings/test/expected/getDocumentHighlights.json b/ets2panda/bindings/test/expected/getDocumentHighlights.json new file mode 100644 index 0000000000..49190c9ce2 --- /dev/null +++ b/ets2panda/bindings/test/expected/getDocumentHighlights.json @@ -0,0 +1,317 @@ +{ + "1": { + "documentHighlights": [ + { + "fileName": "getDocumentHighlights1.ets", + "highlightSpans": [ + { + "fileName": "getDocumentHighlights1.ets", + "textSpan": { + "start": 613, + "length": 3 + }, + "contextSpan": { + "start": 0, + "length": 0 + }, + "kind": 3 + }, + { + "fileName": "getDocumentHighlights1.ets", + "textSpan": { + "start": 634, + "length": 3 + }, + "contextSpan": { + "start": 0, + "length": 0 + }, + "kind": 2 + }, + { + "fileName": "getDocumentHighlights1.ets", + "textSpan": { + "start": 661, + "length": 3 + }, + "contextSpan": { + "start": 0, + "length": 0 + }, + "kind": 2 + } + ] + } + ] + }, + "2": { + "documentHighlights": [ + { + "fileName": "getDocumentHighlights2.ets", + "highlightSpans": [ + { + "fileName": "getDocumentHighlights2.ets", + "textSpan": { + "start": 628, + "length": 3 + }, + "contextSpan": { + "start": 0, + "length": 0 + }, + "kind": 3 + }, + { + "fileName": "getDocumentHighlights2.ets", + "textSpan": { + "start": 655, + "length": 3 + }, + "contextSpan": { + "start": 0, + "length": 0 + }, + "kind": 2 + }, + { + "fileName": "getDocumentHighlights2.ets", + "textSpan": { + "start": 716, + "length": 3 + }, + "contextSpan": { + "start": 0, + "length": 0 + }, + "kind": 2 + } + ] + } + ] + }, + "3": { + "documentHighlights": [ + { + "fileName": "getDocumentHighlights3.ets", + "highlightSpans": [ + { + "fileName": "getDocumentHighlights3.ets", + "textSpan": { + "start": 615, + "length": 3 + }, + "contextSpan": { + "start": 0, + "length": 0 + }, + "kind": 3 + }, + { + "fileName": "getDocumentHighlights3.ets", + "textSpan": { + "start": 660, + "length": 3 + }, + "contextSpan": { + "start": 0, + "length": 0 + }, + "kind": 2 + }, + { + "fileName": "getDocumentHighlights3.ets", + "textSpan": { + "start": 718, + "length": 3 + }, + "contextSpan": { + "start": 0, + "length": 0 + }, + "kind": 2 + } + ] + } + ] + }, + "4": { + "documentHighlights": [ + { + "fileName": "getDocumentHighlights4.ets", + "highlightSpans": [ + { + "fileName": "getDocumentHighlights4.ets", + "textSpan": { + "start": 625, + "length": 3 + }, + "contextSpan": { + "start": 0, + "length": 0 + }, + "kind": 3 + }, + { + "fileName": "getDocumentHighlights4.ets", + "textSpan": { + "start": 672, + "length": 3 + }, + "contextSpan": { + "start": 0, + "length": 0 + }, + "kind": 2 + }, + { + "fileName": "getDocumentHighlights4.ets", + "textSpan": { + "start": 741, + "length": 3 + }, + "contextSpan": { + "start": 0, + "length": 0 + }, + "kind": 2 + }, + { + "fileName": "getDocumentHighlights4.ets", + "textSpan": { + "start": 752, + "length": 3 + }, + "contextSpan": { + "start": 0, + "length": 0 + }, + "kind": 2 + } + ] + } + ] + }, + "5": { + "documentHighlights": [ + { + "fileName": "getDocumentHighlights5.ets", + "highlightSpans": [ + { + "fileName": "getDocumentHighlights5.ets", + "textSpan": { + "start": 618, + "length": 3 + }, + "contextSpan": { + "start": 0, + "length": 0 + }, + "kind": 3 + }, + { + "fileName": "getDocumentHighlights5.ets", + "textSpan": { + "start": 696, + "length": 3 + }, + "contextSpan": { + "start": 0, + "length": 0 + }, + "kind": 2 + }, + { + "fileName": "getDocumentHighlights5.ets", + "textSpan": { + "start": 740, + "length": 3 + }, + "contextSpan": { + "start": 0, + "length": 0 + }, + "kind": 2 + } + ] + } + ] + }, + "6": { + "documentHighlights": [ + { + "fileName": "getDocumentHighlights6.ets", + "highlightSpans": [ + { + "fileName": "getDocumentHighlights6.ets", + "textSpan": { + "start": 615, + "length": 8 + }, + "contextSpan": { + "start": 0, + "length": 0 + }, + "kind": 3 + }, + { + "fileName": "getDocumentHighlights6.ets", + "textSpan": { + "start": 653, + "length": 8 + }, + "contextSpan": { + "start": 0, + "length": 0 + }, + "kind": 2 + } + ] + } + ] + }, + "7": { + "documentHighlights": [ + { + "fileName": "getDocumentHighlights7.ets", + "highlightSpans": [ + { + "fileName": "getDocumentHighlights7.ets", + "textSpan": { + "start": 618, + "length": 3 + }, + "contextSpan": { + "start": 0, + "length": 0 + }, + "kind": 3 + }, + { + "fileName": "getDocumentHighlights7.ets", + "textSpan": { + "start": 732, + "length": 3 + }, + "contextSpan": { + "start": 0, + "length": 0 + }, + "kind": 2 + }, + { + "fileName": "getDocumentHighlights7.ets", + "textSpan": { + "start": 745, + "length": 3 + }, + "contextSpan": { + "start": 0, + "length": 0 + }, + "kind": 2 + } + ] + } + ] + } +} \ No newline at end of file diff --git a/ets2panda/bindings/test/expected/getFileReferences.json b/ets2panda/bindings/test/expected/getFileReferences.json new file mode 100644 index 0000000000..270729c437 --- /dev/null +++ b/ets2panda/bindings/test/expected/getFileReferences.json @@ -0,0 +1,26 @@ +{ + "1": [ + { + "fileName": "getFileReferences1.ets", + "start": 625, + "length": 29 + }, + { + "fileName": "getFileReferences1.ets", + "start": 672, + "length": 29 + } + ], + "2": [ + { + "fileName": "getFileReferences2.ets", + "start": 625, + "length": 29 + }, + { + "fileName": "getFileReferences2.ets", + "start": 672, + "length": 29 + } + ] +} \ No newline at end of file diff --git a/ets2panda/bindings/test/expected/getQuickInfoAtPosition.json b/ets2panda/bindings/test/expected/getQuickInfoAtPosition.json new file mode 100644 index 0000000000..d8dd458714 --- /dev/null +++ b/ets2panda/bindings/test/expected/getQuickInfoAtPosition.json @@ -0,0 +1,107 @@ +{ + "1": { + "kind": "", + "kindModifier": "static public readonly", + "textSpan": { + "start": 626, + "length": 1 + }, + "fileName": "getQuickInfoAtPosition1.ets", + "displayParts": [ + { + "text": "MyStrings", + "kind": "enumName" + }, + { + "text": ".", + "kind": "punctuation" + }, + { + "text": "A", + "kind": "enumMember" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "=", + "kind": "operator" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "\"", + "kind": "punctuation" + }, + { + "text": "hello", + "kind": "text" + }, + { + "text": "\"", + "kind": "punctuation" + } + ] + }, + "2": { + "kind": "class", + "kindModifier": "", + "textSpan": { + "start": 615, + "length": 7 + }, + "fileName": "getQuickInfoAtPosition2.ets", + "displayParts": [ + { + "text": "class", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "MyClass", + "kind": "className" + } + ] + }, + "3": { + "kind": "property", + "kindModifier": "public abstract", + "textSpan": { + "start": 661, + "length": 3 + }, + "fileName": "getQuickInfoAtPosition3.ets", + "displayParts": [ + { + "text": "objI", + "kind": "interface" + }, + { + "text": ".", + "kind": "punctuation" + }, + { + "text": "key", + "kind": "property" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "string", + "kind": "returnType" + } + ] + } +} \ No newline at end of file diff --git a/ets2panda/bindings/test/expected/getReferencesAtPosition.json b/ets2panda/bindings/test/expected/getReferencesAtPosition.json new file mode 100644 index 0000000000..526e1ac256 --- /dev/null +++ b/ets2panda/bindings/test/expected/getReferencesAtPosition.json @@ -0,0 +1,53 @@ +{ + "1": [ + { + "fileName": "getReferencesAtPosition1.ets", + "start": 613, + "length": 1 + } + ], + "2": [ + { + "fileName": "getReferencesAtPosition2.ets", + "start": 620, + "length": 1 + }, + { + "fileName": "getReferencesAtPosition2.ets", + "start": 635, + "length": 1 + }, + { + "fileName": "getReferencesAtPosition2.ets", + "start": 665, + "length": 1 + }, + { + "fileName": "getReferencesAtPosition3.ets", + "start": 617, + "length": 1 + }, + { + "fileName": "getReferencesAtPosition3.ets", + "start": 667, + "length": 1 + } + ], + "3": [ + { + "fileName": "getReferencesAtPosition4.ets", + "start": 625, + "length": 1 + }, + { + "fileName": "getReferencesAtPosition5.ets", + "start": 617, + "length": 1 + }, + { + "fileName": "getReferencesAtPosition5.ets", + "start": 655, + "length": 1 + } + ] +} \ No newline at end of file diff --git a/ets2panda/bindings/test/expected/getSemanticDiagnostics.json b/ets2panda/bindings/test/expected/getSemanticDiagnostics.json new file mode 100644 index 0000000000..679a81c056 --- /dev/null +++ b/ets2panda/bindings/test/expected/getSemanticDiagnostics.json @@ -0,0 +1,75 @@ +{ + "1": { + "diagnostics": [] + }, + "2": { + "diagnostics": [ + { + "message": "Type '\"1\"' is not compatible with type 'double' at index 1", + "source": "\"1\"", + "range": { + "start": { + "line": 20, + "character": 5 + }, + "end": { + "line": 20, + "character": 8 + } + }, + "tags": [], + "relatedInfo": [], + "code": 1, + "data": 0, + "severity": 1, + "codeDescription": { + "href": "test code description" + } + }, + { + "message": "No matching call signature for add(\"1\", int)", + "source": "add", + "range": { + "start": { + "line": 20, + "character": 1 + }, + "end": { + "line": 20, + "character": 4 + } + }, + "tags": [], + "relatedInfo": [], + "code": 1, + "data": 0, + "severity": 1, + "codeDescription": { + "href": "test code description" + } + }, + { + "message": "Type '\"hello\"' cannot be assigned to type 'double'", + "source": "\"hello\"", + "range": { + "start": { + "line": 16, + "character": 19 + }, + "end": { + "line": 16, + "character": 26 + } + }, + "tags": [], + "relatedInfo": [], + "code": 1, + "data": 0, + "severity": 1, + "codeDescription": { + "href": "test code description" + } + } + ] + } +} \ No newline at end of file diff --git a/ets2panda/bindings/test/expected/getSuggestionDiagnostics.json b/ets2panda/bindings/test/expected/getSuggestionDiagnostics.json new file mode 100644 index 0000000000..cd3d78acf8 --- /dev/null +++ b/ets2panda/bindings/test/expected/getSuggestionDiagnostics.json @@ -0,0 +1,534 @@ +{ + "1": { + "diagnostics": [ + { + "message": "This_may_be_converted_to_an_async_function", + "source": "", + "range": { + "start": { + "line": 15, + "character": 609 + }, + "end": { + "line": 17, + "character": 661 + } + }, + "tags": [], + "relatedInfo": [], + "code": 0, + "data": 0, + "severity": 4, + "codeDescription": { + "href": "" + } + }, + { + "message": "This_may_be_converted_to_an_async_function", + "source": "", + "range": { + "start": { + "line": 15, + "character": 609 + }, + "end": { + "line": 17, + "character": 661 + } + }, + "tags": [], + "relatedInfo": [], + "code": 0, + "data": 0, + "severity": 4, + "codeDescription": { + "href": "" + } + }, + { + "message": "This_may_be_converted_to_an_async_function", + "source": "", + "range": { + "start": { + "line": 15, + "character": 609 + }, + "end": { + "line": 17, + "character": 661 + } + }, + "tags": [], + "relatedInfo": [], + "code": 0, + "data": 0, + "severity": 4, + "codeDescription": { + "href": "" + } + }, + { + "message": "This_may_be_converted_to_an_async_function", + "source": "", + "range": { + "start": { + "line": 15, + "character": 609 + }, + "end": { + "line": 17, + "character": 661 + } + }, + "tags": [], + "relatedInfo": [], + "code": 0, + "data": 0, + "severity": 4, + "codeDescription": { + "href": "" + } + }, + { + "message": "This_may_be_converted_to_an_async_function", + "source": "", + "range": { + "start": { + "line": 15, + "character": 618 + }, + "end": { + "line": 17, + "character": 661 + } + }, + "tags": [], + "relatedInfo": [], + "code": 0, + "data": 0, + "severity": 4, + "codeDescription": { + "href": "" + } + }, + { + "message": "This_may_be_converted_to_an_async_function", + "source": "", + "range": { + "start": { + "line": 15, + "character": 618 + }, + "end": { + "line": 17, + "character": 661 + } + }, + "tags": [], + "relatedInfo": [], + "code": 0, + "data": 0, + "severity": 4, + "codeDescription": { + "href": "" + } + }, + { + "message": "This_may_be_converted_to_an_async_function", + "source": "", + "range": { + "start": { + "line": 15, + "character": 618 + }, + "end": { + "line": 17, + "character": 661 + } + }, + "tags": [], + "relatedInfo": [], + "code": 0, + "data": 0, + "severity": 4, + "codeDescription": { + "href": "" + } + }, + { + "message": "This_may_be_converted_to_an_async_function", + "source": "", + "range": { + "start": { + "line": 15, + "character": 618 + }, + "end": { + "line": 17, + "character": 661 + } + }, + "tags": [], + "relatedInfo": [], + "code": 0, + "data": 0, + "severity": 4, + "codeDescription": { + "href": "" + } + }, + { + "message": "This_may_be_converted_to_an_async_function", + "source": "", + "range": { + "start": { + "line": 15, + "character": 618 + }, + "end": { + "line": 17, + "character": 661 + } + }, + "tags": [], + "relatedInfo": [], + "code": 0, + "data": 0, + "severity": 4, + "codeDescription": { + "href": "" + } + }, + { + "message": "This_may_be_converted_to_an_async_function", + "source": "", + "range": { + "start": { + "line": 15, + "character": 618 + }, + "end": { + "line": 17, + "character": 661 + } + }, + "tags": [], + "relatedInfo": [], + "code": 0, + "data": 0, + "severity": 4, + "codeDescription": { + "href": "" + } + }, + { + "message": "This_may_be_converted_to_an_async_function", + "source": "", + "range": { + "start": { + "line": 15, + "character": 618 + }, + "end": { + "line": 17, + "character": 661 + } + }, + "tags": [], + "relatedInfo": [], + "code": 0, + "data": 0, + "severity": 4, + "codeDescription": { + "href": "" + } + }, + { + "message": "This_may_be_converted_to_an_async_function", + "source": "", + "range": { + "start": { + "line": 15, + "character": 618 + }, + "end": { + "line": 17, + "character": 661 + } + }, + "tags": [], + "relatedInfo": [], + "code": 0, + "data": 0, + "severity": 4, + "codeDescription": { + "href": "" + } + }, + { + "message": "This_may_be_converted_to_an_async_function", + "source": "", + "range": { + "start": { + "line": 18, + "character": 662 + }, + "end": { + "line": 20, + "character": 717 + } + }, + "tags": [], + "relatedInfo": [], + "code": 0, + "data": 0, + "severity": 4, + "codeDescription": { + "href": "" + } + }, + { + "message": "This_may_be_converted_to_an_async_function", + "source": "", + "range": { + "start": { + "line": 18, + "character": 662 + }, + "end": { + "line": 20, + "character": 717 + } + }, + "tags": [], + "relatedInfo": [], + "code": 0, + "data": 0, + "severity": 4, + "codeDescription": { + "href": "" + } + }, + { + "message": "This_may_be_converted_to_an_async_function", + "source": "", + "range": { + "start": { + "line": 18, + "character": 662 + }, + "end": { + "line": 20, + "character": 717 + } + }, + "tags": [], + "relatedInfo": [], + "code": 0, + "data": 0, + "severity": 4, + "codeDescription": { + "href": "" + } + }, + { + "message": "This_may_be_converted_to_an_async_function", + "source": "", + "range": { + "start": { + "line": 18, + "character": 662 + }, + "end": { + "line": 20, + "character": 717 + } + }, + "tags": [], + "relatedInfo": [], + "code": 0, + "data": 0, + "severity": 4, + "codeDescription": { + "href": "" + } + }, + { + "message": "This_may_be_converted_to_an_async_function", + "source": "", + "range": { + "start": { + "line": 18, + "character": 671 + }, + "end": { + "line": 20, + "character": 717 + } + }, + "tags": [], + "relatedInfo": [], + "code": 0, + "data": 0, + "severity": 4, + "codeDescription": { + "href": "" + } + }, + { + "message": "This_may_be_converted_to_an_async_function", + "source": "", + "range": { + "start": { + "line": 18, + "character": 671 + }, + "end": { + "line": 20, + "character": 717 + } + }, + "tags": [], + "relatedInfo": [], + "code": 0, + "data": 0, + "severity": 4, + "codeDescription": { + "href": "" + } + }, + { + "message": "This_may_be_converted_to_an_async_function", + "source": "", + "range": { + "start": { + "line": 18, + "character": 671 + }, + "end": { + "line": 20, + "character": 717 + } + }, + "tags": [], + "relatedInfo": [], + "code": 0, + "data": 0, + "severity": 4, + "codeDescription": { + "href": "" + } + }, + { + "message": "This_may_be_converted_to_an_async_function", + "source": "", + "range": { + "start": { + "line": 18, + "character": 671 + }, + "end": { + "line": 20, + "character": 717 + } + }, + "tags": [], + "relatedInfo": [], + "code": 0, + "data": 0, + "severity": 4, + "codeDescription": { + "href": "" + } + }, + { + "message": "This_may_be_converted_to_an_async_function", + "source": "", + "range": { + "start": { + "line": 18, + "character": 671 + }, + "end": { + "line": 20, + "character": 717 + } + }, + "tags": [], + "relatedInfo": [], + "code": 0, + "data": 0, + "severity": 4, + "codeDescription": { + "href": "" + } + }, + { + "message": "This_may_be_converted_to_an_async_function", + "source": "", + "range": { + "start": { + "line": 18, + "character": 671 + }, + "end": { + "line": 20, + "character": 717 + } + }, + "tags": [], + "relatedInfo": [], + "code": 0, + "data": 0, + "severity": 4, + "codeDescription": { + "href": "" + } + }, + { + "message": "This_may_be_converted_to_an_async_function", + "source": "", + "range": { + "start": { + "line": 18, + "character": 671 + }, + "end": { + "line": 20, + "character": 717 + } + }, + "tags": [], + "relatedInfo": [], + "code": 0, + "data": 0, + "severity": 4, + "codeDescription": { + "href": "" + } + }, + { + "message": "This_may_be_converted_to_an_async_function", + "source": "", + "range": { + "start": { + "line": 18, + "character": 671 + }, + "end": { + "line": 20, + "character": 717 + } + }, + "tags": [], + "relatedInfo": [], + "code": 0, + "data": 0, + "severity": 4, + "codeDescription": { + "href": "" + } + } + ] + } +} \ No newline at end of file diff --git a/ets2panda/bindings/test/expected/getSyntacticDiagnostics.json b/ets2panda/bindings/test/expected/getSyntacticDiagnostics.json new file mode 100644 index 0000000000..2ed128d561 --- /dev/null +++ b/ets2panda/bindings/test/expected/getSyntacticDiagnostics.json @@ -0,0 +1,295 @@ +{ + "1": { + "diagnostics": [] + }, + "2": { + "diagnostics": [ + { + "message": "Unexpected token 'add'.", + "source": "add", + "range": { + "start": { + "line": 16, + "character": 9 + }, + "end": { + "line": 16, + "character": 12 + } + }, + "tags": [], + "relatedInfo": [], + "code": 1, + "data": 0, + "severity": 1, + "codeDescription": { + "href": "test code description" + } + }, + { + "message": "Unexpected token, expected ',' or ')'.", + "source": "*ERROR_LITERAL*", + "range": { + "start": { + "line": 16, + "character": 14 + }, + "end": { + "line": 16, + "character": 15 + } + }, + "tags": [], + "relatedInfo": [], + "code": 1, + "data": 0, + "severity": 1, + "codeDescription": { + "href": "test code description" + } + }, + { + "message": "Unexpected token ':'.", + "source": "*ERROR_LITERAL*", + "range": { + "start": { + "line": 16, + "character": 14 + }, + "end": { + "line": 16, + "character": 15 + } + }, + "tags": [], + "relatedInfo": [], + "code": 1, + "data": 0, + "severity": 1, + "codeDescription": { + "href": "test code description" + } + }, + { + "message": "Unexpected token ':'.", + "source": "*ERROR_LITERAL*", + "range": { + "start": { + "line": 16, + "character": 14 + }, + "end": { + "line": 16, + "character": 15 + } + }, + "tags": [], + "relatedInfo": [], + "code": 1, + "data": 0, + "severity": 1, + "codeDescription": { + "href": "test code description" + } + }, + { + "message": "Unexpected token ':'.", + "source": "*ERROR_LITERAL*", + "range": { + "start": { + "line": 16, + "character": 14 + }, + "end": { + "line": 16, + "character": 15 + } + }, + "tags": [], + "relatedInfo": [], + "code": 1, + "data": 0, + "severity": 1, + "codeDescription": { + "href": "test code description" + } + }, + { + "message": "Unexpected token ','.", + "source": "*ERROR_LITERAL*", + "range": { + "start": { + "line": 16, + "character": 22 + }, + "end": { + "line": 16, + "character": 23 + } + }, + "tags": [], + "relatedInfo": [], + "code": 1, + "data": 0, + "severity": 1, + "codeDescription": { + "href": "test code description" + } + }, + { + "message": "Unexpected token ','.", + "source": "*ERROR_LITERAL*", + "range": { + "start": { + "line": 16, + "character": 22 + }, + "end": { + "line": 16, + "character": 23 + } + }, + "tags": [], + "relatedInfo": [], + "code": 1, + "data": 0, + "severity": 1, + "codeDescription": { + "href": "test code description" + } + }, + { + "message": "Unexpected token ','.", + "source": "*ERROR_LITERAL*", + "range": { + "start": { + "line": 16, + "character": 22 + }, + "end": { + "line": 16, + "character": 23 + } + }, + "tags": [], + "relatedInfo": [], + "code": 1, + "data": 0, + "severity": 1, + "codeDescription": { + "href": "test code description" + } + }, + { + "message": "Label must be followed by a loop statement.", + "source": "", + "range": { + "start": { + "line": 16, + "character": 27 + }, + "end": { + "line": 16, + "character": 33 + } + }, + "tags": [], + "relatedInfo": [], + "code": 1, + "data": 0, + "severity": 1, + "codeDescription": { + "href": "test code description" + } + }, + { + "message": "Unexpected token ')'.", + "source": "*ERROR_LITERAL*", + "range": { + "start": { + "line": 16, + "character": 33 + }, + "end": { + "line": 16, + "character": 34 + } + }, + "tags": [], + "relatedInfo": [], + "code": 1, + "data": 0, + "severity": 1, + "codeDescription": { + "href": "test code description" + } + }, + { + "message": "Unexpected token ')'.", + "source": "*ERROR_LITERAL*", + "range": { + "start": { + "line": 16, + "character": 33 + }, + "end": { + "line": 16, + "character": 34 + } + }, + "tags": [], + "relatedInfo": [], + "code": 1, + "data": 0, + "severity": 1, + "codeDescription": { + "href": "test code description" + } + }, + { + "message": "Unexpected token ')'.", + "source": "*ERROR_LITERAL*", + "range": { + "start": { + "line": 16, + "character": 33 + }, + "end": { + "line": 16, + "character": 34 + } + }, + "tags": [], + "relatedInfo": [], + "code": 1, + "data": 0, + "severity": 1, + "codeDescription": { + "href": "test code description" + } + }, + { + "message": "return keyword should be used in function body.", + "source": "return ((a) + (b));", + "range": { + "start": { + "line": 17, + "character": 5 + }, + "end": { + "line": 17, + "character": 18 + } + }, + "tags": [], + "relatedInfo": [], + "code": 1, + "data": 0, + "severity": 1, + "codeDescription": { + "href": "test code description" + } + } + ] + } +} \ No newline at end of file diff --git a/ets2panda/bindings/test/expected/toLineColumnOffset.json b/ets2panda/bindings/test/expected/toLineColumnOffset.json new file mode 100644 index 0000000000..df135e0084 --- /dev/null +++ b/ets2panda/bindings/test/expected/toLineColumnOffset.json @@ -0,0 +1,10 @@ +{ + "1": { + "line": 0, + "character": 0 + }, + "2": { + "line": 17, + "character": 642 + } +} \ No newline at end of file diff --git a/ets2panda/bindings/test/prepare.ps1 b/ets2panda/bindings/test/prepare.ps1 new file mode 100644 index 0000000000..e2954bfe84 --- /dev/null +++ b/ets2panda/bindings/test/prepare.ps1 @@ -0,0 +1,110 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# This script will replace the old paths with the new ones in all files within the testcases directory. + +$ErrorActionPreference = "Stop" + +$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path + +# Check if the 'ets' directory exists in ScriptDir +if (-not (Test-Path -Path "$ScriptDir\ets" -PathType Container)) { + Write-Error "Error: 'ets' directory not found in $ScriptDir." + Write-Error "Please make sure the 'ets' directory exists before running bindings test." + exit 1 +} + +$RestoreMode = 0 +if ($args.Count -gt 0 -and $args[0] -eq "--restore") { + $RestoreMode = 1 +} + +$OldPath = "path/to/bindings/test" + +$TestcasesDir = "$ScriptDir\testcases" + +if ($RestoreMode -eq 1) { + Write-Host "Restoring path '$ScriptDir' back to '$OldPath' in files..." +} +else { + Write-Host "Replacing path '$OldPath' with '$ScriptDir' in files..." +} + +function Process-Directory { + param ( + [string] $directory + ) + + if (-not (Test-Path -Path $directory -PathType Container)) { + Write-Host "Directory $directory does not exist. Skipping." + return + } + + Write-Host "Processing directory: $directory" + + $jsonFiles = Get-ChildItem -Path $directory -Filter "*.json" -File -Recurse + + foreach ($file in $jsonFiles) { + Write-Host "Processing file: $($file.FullName)" + $content = Get-Content -Path $file.FullName -Raw + + $scriptDirJson = $ScriptDir -replace '\\', '/' + + if ($RestoreMode -eq 1) { + $newContent = $content -replace [regex]::Escape($scriptDirJson), $OldPath + } + else { + $newContent = $content -replace [regex]::Escape($OldPath), $scriptDirJson + } + + Set-Content -Path $file.FullName -Value $newContent -NoNewline + } +} + +Process-Directory -directory $TestcasesDir + +if ($RestoreMode -eq 1) { + if (Test-Path -Path "$ScriptDir\..\ets2panda") { + Remove-Item -Path "$ScriptDir\..\ets2panda" -Recurse -Force + } + Write-Host "Path restoration completed." +} +else { + $sourceDir = "$ScriptDir\ets\ets1.2\build-tools\ets2panda" + $destinationDir = "$ScriptDir\..\ets2panda" + + # Check if source directory exists + if (-not (Test-Path -Path $sourceDir -PathType Container)) { + Write-Error "Source directory '$sourceDir' does not exist." + exit 1 + } + + # Remove destination directory if it exists + if (Test-Path -Path $destinationDir) { + Remove-Item -Path $destinationDir -Recurse -Force + } + + # Copy directory + try { + Copy-Item -Path $sourceDir -Destination $destinationDir -Recurse -Force + Write-Host "Directory copied successfully from '$sourceDir' to '$destinationDir'." + Write-Host "Path replacement completed." + } + catch { + Write-Error "Failed to copy directory." + Write-Error $_.Exception.Message + exit 1 + } +} + +exit 0 \ No newline at end of file diff --git a/ets2panda/bindings/test/prepare.sh b/ets2panda/bindings/test/prepare.sh new file mode 100755 index 0000000000..4b8f9c4d6f --- /dev/null +++ b/ets2panda/bindings/test/prepare.sh @@ -0,0 +1,74 @@ +#!/usr/bin/env bash + +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# This script will replace the old paths with the new ones in all files within the testcases directory. + +set -eo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +# Check if the 'ets' directory exists in SCRIPT_DIR +if [ ! -d "${SCRIPT_DIR}/ets" ]; then + echo "Error: 'ets' directory not found in ${SCRIPT_DIR}." + echo "Please make sure the 'ets' directory exists before running bindings test." + exit 1 +fi + +RESTORE_MODE=0 +if [ "$1" == "--restore" ]; then + RESTORE_MODE=1 +fi + +OLD_PATH="path/to/bindings/test" + +TESTCASES_DIR="${SCRIPT_DIR}/testcases" + +if [ $RESTORE_MODE -eq 1 ]; then + echo "Restoring path '${SCRIPT_DIR}' back to '${OLD_PATH}' in files..." +else + echo "Replacing path '${OLD_PATH}' with '${SCRIPT_DIR}' in files..." +fi + +process_directory() { + local dir=$1 + + if [ ! -d "$dir" ]; then + echo "Directory $dir does not exist. Skipping." + return + fi + + echo "Processing directory: $dir" + + find "$dir" -type f -name "*.json" | while read -r file; do + echo "Processing file: $file" + if [ $RESTORE_MODE -eq 1 ]; then + sed -i "s|${SCRIPT_DIR}|${OLD_PATH}|g" "$file" + else + sed -i "s|${OLD_PATH}|${SCRIPT_DIR}|g" "$file" + fi + done +} + +process_directory "$TESTCASES_DIR" + +if [ $RESTORE_MODE -eq 1 ]; then + rm "${SCRIPT_DIR}/../ets2panda" + echo "Path restoration completed." +else + ln -s "${SCRIPT_DIR}/ets/ets1.2/build-tools/ets2panda" "${SCRIPT_DIR}/../ets2panda" + echo "Path replacement completed." +fi + +exit 0 diff --git a/ets2panda/bindings/test/run_tests.ts b/ets2panda/bindings/test/run_tests.ts new file mode 100644 index 0000000000..3eeb124ee0 --- /dev/null +++ b/ets2panda/bindings/test/run_tests.ts @@ -0,0 +1,278 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import path from 'path'; +import fs from 'fs'; +import { + Lsp, + LspDefinitionData, + LspCompletionInfo, + LspDiagsNode, + ModuleDescriptor, + generateArkTsConfigByModules +} from '../src/index'; + +interface TestConfig { + expectedFilePath: string; + // CC-OFFNXT(no_explicit_any) project code style + [key: string]: Array | string; +} + +interface TestCases { + [testName: string]: TestConfig; +} + +let updateMode = false; + +function checkEnvironment(testDir: string): void { + const testCasesFilePath = path.join(testDir, 'testcases', 'cases.json'); + if (!fs.existsSync(testCasesFilePath)) { + console.error(`Test cases file not found: ${testCasesFilePath}`); + process.exit(1); + } +} + +function getModules(projectRoot: string): ModuleDescriptor[] { + const testCases = JSON.parse(fs.readFileSync(path.join(projectRoot, 'cases.json'), 'utf-8')) as TestCases; + return Object.keys(testCases).map((name) => { + const modulePath = path.join(projectRoot, name); + return { + arktsversion: '1.2', + name, + moduleType: 'har', + srcPath: modulePath + } as ModuleDescriptor; + }); +} + +// CC-OFFNXT(no_explicit_any) project code style +function getExpectedResult(filePath: string): any { + try { + return JSON.parse(fs.readFileSync(filePath, 'utf-8')); + } catch (err) { + console.error(`Failed to read expected result from ${filePath}: ${err}`); + return null; + } +} + +function sortCompletions(completionResult: LspCompletionInfo): LspCompletionInfo { + if (!completionResult || !completionResult.entries || !Array.isArray(completionResult.entries)) { + return completionResult; + } + + // Sort entries by name + completionResult.entries.sort((a, b) => { + const nameA = a.name.toString().toLowerCase(); + const nameB = b.name.toString().toLowerCase(); + return nameA.localeCompare(nameB); + }); + + return completionResult; +} + +function sortDiagnostics(diags: LspDiagsNode): LspDiagsNode { + if (!diags || !diags.diagnostics || !Array.isArray(diags.diagnostics)) { + return diags; + } + + diags.diagnostics.sort((a, b) => { + if (a.range.start.line !== b.range.start.line) { + return a.range.start.line - b.range.start.line; + } + + if (a.range.start.character !== b.range.start.character) { + return a.range.start.character - b.range.start.character; + } + + if (a.range.end.line !== b.range.end.line) { + return a.range.end.line - b.range.end.line; + } + + return a.range.end.character - b.range.end.character; + }); + + return diags; +} + +// CC-OFFNXT(no_explicit_any) project code style +function sortActualResult(testName: string, res: any): any { + if (testName === 'getCompletionAtPosition') { + return sortCompletions(res as LspCompletionInfo); + } + if (testName === 'getSuggestionDiagnostics') { + return sortDiagnostics(res as LspDiagsNode); + } + return res; +} + +// CC-OFFNXT(no_explicit_any) project code style +function normalizeData(obj: any): any { + if (Array.isArray(obj)) { + return obj.map(normalizeData); + } else if (obj && typeof obj === 'object') { + const newObj = { ...obj }; + if ('peer' in newObj) { + delete newObj.peer; // do not compare peer + } + if (newObj.fileName) { + newObj.fileName = path.basename(newObj.fileName); + } + for (const key of Object.keys(newObj)) { + newObj[key] = normalizeData(newObj[key]); + } + return newObj; + } + return obj; +} + +// CC-OFFNXT(no_explicit_any) project code style +function compareResultsHelper(testName: string, actual: any, expected: any): boolean { + const normalizedActual = normalizeData(actual); + + const actualJSON = JSON.stringify(normalizedActual, null, 2); + const expectedJSON = JSON.stringify(expected, null, 2); + + if (actualJSON === expectedJSON) { + console.log(`[${testName}] ✅ Passed`); + return true; + } else { + console.log(`[${testName}] ❌ Failed`); + console.log(`Expected: ${expectedJSON}`); + console.log(`Actual: ${actualJSON}`); + } + return false; +} + +function findTextDefinitionPosition(sourceCode: string): number { + const textDefinitionPattern = /export\s+declare\s+function\s+Text\(/; + const match = textDefinitionPattern.exec(sourceCode); + if (match) { + const functionTextPattern = /function\s+Text\(/; + const subMatch = functionTextPattern.exec(sourceCode.substring(match.index)); + if (subMatch) { + const positionOfT = match.index + subMatch.index + 'function '.length; + return positionOfT; + } + } + throw new Error('Could not find Text definition in source code'); +} + +function compareGetDefinitionResult( + testName: string, + index: string, + actual: any, + expected: Record +) { + // This is the definition info for the UI component. + // File in the SDK might changed, so the offset needs to be checked dynamically. + if (expected['fileName'] === 'text.d.ets') { + const actualDef = actual as LspDefinitionData; + const fileName = actualDef.fileName as string; + const fileContent = fs.readFileSync(fileName, 'utf8'); + const expectedStart = findTextDefinitionPosition(fileContent); + const expectedResult = { + ...expected, + start: expectedStart + }; + return compareResultsHelper(`${testName}:${index}`, actual, expectedResult); + } + return compareResultsHelper(`${testName}:${index}`, actual, expected); +} + +// CC-OFFNXT(no_explicit_any) project code style +function compareResults(testName: string, index: string, actual: any, expected: any) { + if (testName === 'getDefinitionAtPosition') { + return compareGetDefinitionResult(testName, index, actual, expected); + } + return compareResultsHelper(`${testName}:${index}`, actual, expected); +} + +function runTests(testDir: string, lsp: Lsp) { + console.log('Running tests...'); + const testCases = JSON.parse(fs.readFileSync(path.join(testDir, 'testcases', 'cases.json'), 'utf-8')) as TestCases; + if (!testCases) { + console.error('Failed to load test cases'); + return; + } + + let failedList: string[] = []; + for (const [testName, testConfig] of Object.entries(testCases)) { + const { expectedFilePath, ...testCaseVariants } = testConfig; + const expectedResult = getExpectedResult(expectedFilePath); + if (expectedResult === null) { + console.error(`[${testName}] Skipped (expected result not found)`); + continue; + } + // CC-OFFNXT(no_explicit_any) project code style + if (typeof (lsp as any)[testName] !== 'function') { + console.error(`[${testName}] ❌ Error: Method "${testName}" not found on Lsp object`); + continue; + } + + for (const [index, params] of Object.entries(testCaseVariants)) { + let pass = false; + let actualResult = null; + try { + // CC-OFFNXT(no_explicit_any) project code style + actualResult = (lsp as any)[testName](...params); + actualResult = sortActualResult(testName, actualResult); + pass = compareResults(testName, index, actualResult, expectedResult[index]); + } catch (error) { + console.error(`[${testName}:${index}] ❌ Error: ${error}`); + } + if (!pass) { + failedList.push(`${testName}:${index}`); + } + if (!pass && updateMode) { + console.log(`Updating expected result for ${testName}:${index}`); + expectedResult[index] = normalizeData(actualResult); + } + } + if (updateMode) { + fs.writeFileSync(expectedFilePath, JSON.stringify(expectedResult, null, 2)); + } + console.log(`Finished test: ${testName}`); + console.log('-----------------------------------'); + } + console.log('Tests completed.'); + if (failedList.length > 0) { + console.log('❌ Failed tests:'); + failedList.forEach((failedCase) => { + console.log(`- ${failedCase}`); + }); + } +} + +if (require.main === module) { + if (process.argv.length < 3) { + console.error('Usage: node run_tests.js '); + process.exit(1); + } + // If update flag is passed, update the expected result files + if (process.argv[3] && process.argv[3] === '--update') { + updateMode = true; + } + const testDir = path.resolve(process.argv[2]); + checkEnvironment(testDir); + const buildSdkPath = path.join(testDir, 'ets', 'ets1.2'); + const projectRoot = path.join(testDir, 'testcases'); + const modules = getModules(projectRoot); + + generateArkTsConfigByModules(buildSdkPath, projectRoot, modules); + const lsp = new Lsp(projectRoot); + + process.env.BINDINGS_PATH = path.join(buildSdkPath, 'build-tools', 'bindings'); + runTests(testDir, lsp); +} diff --git a/ets2panda/bindings/test/testcases/cases.json b/ets2panda/bindings/test/testcases/cases.json new file mode 100644 index 0000000000..6e708b1425 --- /dev/null +++ b/ets2panda/bindings/test/testcases/cases.json @@ -0,0 +1,225 @@ +{ + "getDefinitionAtPosition": { + "expectedFilePath": "path/to/bindings/test/expected/getDefinitionAtPosition.json", + "1": [ + "path/to/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition2.ets", + 655 + ], + "2": [ + "path/to/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition3.ets", + 662 + ], + "3": [ + "path/to/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition5.ets", + 664 + ], + "4": [ + "path/to/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition7.ets", + 683 + ], + "5": [ + "path/to/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition9.ets", + 666 + ], + "6": [ + "path/to/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition11.ets", + 675 + ], + "7": [ + "path/to/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition13.ets", + 664 + ], + "8": [ + "path/to/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition15.ets", + 617 + ], + "9": [ + "path/to/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition17.ets", + 677 + ], + "10": [ + "path/to/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition18.ets", + 930 + ] + }, + "getSemanticDiagnostics": { + "expectedFilePath": "path/to/bindings/test/expected/getSemanticDiagnostics.json", + "1": [ + "path/to/bindings/test/testcases/getSemanticDiagnostics/getSemanticDiagnostics1.ets" + ], + "2": [ + "path/to/bindings/test/testcases/getSemanticDiagnostics/getSemanticDiagnostics2.ets" + ] + }, + "getCurrentTokenValue": { + "expectedFilePath": "path/to/bindings/test/expected/getCurrentTokenValue.json", + "1": [ + "path/to/bindings/test/testcases/getCurrentTokenValue/getCurrentTokenValue1.ets", + 611 + ], + "2": [ + "path/to/bindings/test/testcases/getCurrentTokenValue/getCurrentTokenValue2.ets", + 612 + ], + "3": [ + "path/to/bindings/test/testcases/getCurrentTokenValue/getCurrentTokenValue3.ets", + 612 + ], + "4": [ + "path/to/bindings/test/testcases/getCurrentTokenValue/getCurrentTokenValue4.ets", + 611 + ] + }, + "getFileReferences": { + "expectedFilePath": "path/to/bindings/test/expected/getFileReferences.json", + "1": [ + "path/to/bindings/test/testcases/getFileReferences/getFileReferences1_export.ets" + ] + }, + "getReferencesAtPosition": { + "expectedFilePath": "path/to/bindings/test/expected/getReferencesAtPosition.json", + "1": [ + "path/to/bindings/test/testcases/getReferencesAtPosition/getReferencesAtPosition1.ets", + 613 + ], + "2": [ + "path/to/bindings/test/testcases/getReferencesAtPosition/getReferencesAtPosition2.ets", + 635 + ], + "3": [ + "path/to/bindings/test/testcases/getReferencesAtPosition/getReferencesAtPosition4.ets", + 625 + ] + }, + "getSyntacticDiagnostics": { + "expectedFilePath": "path/to/bindings/test/expected/getSyntacticDiagnostics.json", + "1": [ + "path/to/bindings/test/testcases/getSyntacticDiagnostics/getSyntacticDiagnostics1.ets" + ], + "2": [ + "path/to/bindings/test/testcases/getSyntacticDiagnostics/getSyntacticDiagnostics2.ets" + ] + }, + "getSuggestionDiagnostics": { + "expectedFilePath": "path/to/bindings/test/expected/getSuggestionDiagnostics.json", + "1": [ + "path/to/bindings/test/testcases/getSuggestionDiagnostics/getSuggestionDiagnostics1.ets" + ] + }, + "getQuickInfoAtPosition": { + "expectedFilePath": "path/to/bindings/test/expected/getQuickInfoAtPosition.json", + "1": [ + "path/to/bindings/test/testcases/getQuickInfoAtPosition/getQuickInfoAtPosition1.ets", + 626 + ], + "2": [ + "path/to/bindings/test/testcases/getQuickInfoAtPosition/getQuickInfoAtPosition2.ets", + 618 + ], + "3": [ + "path/to/bindings/test/testcases/getQuickInfoAtPosition/getQuickInfoAtPosition3.ets", + 663 + ] + }, + "getDocumentHighlights": { + "expectedFilePath": "path/to/bindings/test/expected/getDocumentHighlights.json", + "1": [ + "path/to/bindings/test/testcases/getDocumentHighlights/getDocumentHighlights1.ets", + 614 + ], + "2": [ + "path/to/bindings/test/testcases/getDocumentHighlights/getDocumentHighlights2.ets", + 717 + ], + "3": [ + "path/to/bindings/test/testcases/getDocumentHighlights/getDocumentHighlights3.ets", + 616 + ], + "4": [ + "path/to/bindings/test/testcases/getDocumentHighlights/getDocumentHighlights4.ets", + 626 + ], + "5": [ + "path/to/bindings/test/testcases/getDocumentHighlights/getDocumentHighlights5.ets", + 619 + ], + "6": [ + "path/to/bindings/test/testcases/getDocumentHighlights/getDocumentHighlights6.ets", + 657 + ], + "7": [ + "path/to/bindings/test/testcases/getDocumentHighlights/getDocumentHighlights7.ets", + 733 + ] + }, + "getCompletionAtPosition": { + "expectedFilePath": "path/to/bindings/test/expected/getCompletionAtPosition.json", + "1": [ + "path/to/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition1.ets", + 705 + ], + "2": [ + "path/to/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition2.ets", + 735 + ], + "3": [ + "path/to/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition3.ets", + 789 + ], + "4": [ + "path/to/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition4.ets", + 767 + ], + "5": [ + "path/to/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition5.ets", + 728 + ], + "6": [ + "path/to/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition6.ets", + 718 + ], + "7": [ + "path/to/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition7.ets", + 683 + ], + "8": [ + "path/to/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition8.ets", + 614 + ], + "9": [ + "path/to/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition9.ets", + 619 + ], + "10": [ + "path/to/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition10.ets", + 712 + ], + "11": [ + "path/to/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition11.ets", + 682 + ], + "12": [ + "path/to/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition12.ets", + 720 + ], + "13": [ + "path/to/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition13.ets", + 658 + ], + "14": [ + "path/to/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition14.ets", + 659 + ] + }, + "toLineColumnOffset": { + "expectedFilePath": "path/to/bindings/test/expected/toLineColumnOffset.json", + "1": [ + "path/to/bindings/test/testcases/toLineColumnOffset/toLineColumnOffset1.ets", + 0 + ], + "2": [ + "path/to/bindings/test/testcases/toLineColumnOffset/toLineColumnOffset1.ets", + 642 + ] + } +} \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition1.ets b/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition1.ets new file mode 100644 index 0000000000..1d4247831e --- /dev/null +++ b/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition1.ets @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +function num1() { + return 1; +} + +function num2() { + return 2; +} + +console.log(1); + +let a = n \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition10.ets b/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition10.ets new file mode 100644 index 0000000000..b563112f61 --- /dev/null +++ b/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition10.ets @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +namespace space { + export class classInSpace { + public c: number = 2; + } +} +let numOfSpace: space. diff --git a/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition11.ets b/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition11.ets new file mode 100644 index 0000000000..d5f9f2ac62 --- /dev/null +++ b/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition11.ets @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +enum Color { + Red = "red", + Blue = "blue" +} +let myColor: Color = Color. \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition12.ets b/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition12.ets new file mode 100644 index 0000000000..87e6b926de --- /dev/null +++ b/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition12.ets @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class MyClass { + public myProp: number = 0; + public prop: number = 0; +} +let obj = new MyClass(); +let p = obj. +let a = 1; \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition13.ets b/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition13.ets new file mode 100644 index 0000000000..47153d4576 --- /dev/null +++ b/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition13.ets @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +interface Inner { key : string; } +let i: Inner +i. +let a = 1; \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition14.ets b/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition14.ets new file mode 100644 index 0000000000..e69f51bc2b --- /dev/null +++ b/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition14.ets @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +interface Inner { key : string; } +let i: Inner +i.k +let a = 1; \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition2.ets b/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition2.ets new file mode 100644 index 0000000000..740efcba7c --- /dev/null +++ b/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition2.ets @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +let aaa = 123; +const abb = 333; + +function axx() { + return 444; +} + +function foo() { + let bbb = 222; + let ccc = bbb + a + return bbb + ccc; +} \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition3.ets b/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition3.ets new file mode 100644 index 0000000000..e1b6f9cd79 --- /dev/null +++ b/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition3.ets @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class Foo { + bar: number = 1; +} + +let foo = new Foo(); +foo.bar = 2; +let baa = 3; +let bbb = 4; + +function bxx() { + return 5; +} + +function fxx() { + let bcc = 6; + let axx = b +} \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition4.ets b/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition4.ets new file mode 100644 index 0000000000..36b649df57 --- /dev/null +++ b/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition4.ets @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class Foo { + bar: number = 1; +} + +let foo = new Foo(); +foo.bar = 2; +let baa = 3; +let bbb = 4; + +function bxx() { + let bcc = 6; + return 5; +} +let axx = b \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition5.ets b/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition5.ets new file mode 100644 index 0000000000..a73540ca9d --- /dev/null +++ b/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition5.ets @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class MyClass1 { + public myProp: number = 0; + public prop: number = 1; +} +let obj1 = new MyClass1() +let prop = obj1.yp \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition6.ets b/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition6.ets new file mode 100644 index 0000000000..8cf5346413 --- /dev/null +++ b/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition6.ets @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +namespace space { + export class classInSpace { + public c: number = 2; + } +} +let numOfSpace: space.classi \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition7.ets b/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition7.ets new file mode 100644 index 0000000000..b53589f4f3 --- /dev/null +++ b/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition7.ets @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +enum Color { + Red = "red", + Blue = "blue" +} +let myColor: Color = Color.R \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition8.ets b/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition8.ets new file mode 100644 index 0000000000..3409ce460c --- /dev/null +++ b/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition8.ets @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition9.ets b/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition9.ets new file mode 100644 index 0000000000..a0e0c15f46 --- /dev/null +++ b/ets2panda/bindings/test/testcases/getCompletionAtPosition/getCompletionsAtPosition9.ets @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +let a: num \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getCurrentTokenValue/getCurrentTokenValue1.ets b/ets2panda/bindings/test/testcases/getCurrentTokenValue/getCurrentTokenValue1.ets new file mode 100644 index 0000000000..e1b4fa850d --- /dev/null +++ b/ets2panda/bindings/test/testcases/getCurrentTokenValue/getCurrentTokenValue1.ets @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +ab \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getCurrentTokenValue/getCurrentTokenValue2.ets b/ets2panda/bindings/test/testcases/getCurrentTokenValue/getCurrentTokenValue2.ets new file mode 100644 index 0000000000..b3752d9f81 --- /dev/null +++ b/ets2panda/bindings/test/testcases/getCurrentTokenValue/getCurrentTokenValue2.ets @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +"ab" \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getCurrentTokenValue/getCurrentTokenValue3.ets b/ets2panda/bindings/test/testcases/getCurrentTokenValue/getCurrentTokenValue3.ets new file mode 100644 index 0000000000..884bb23fd4 --- /dev/null +++ b/ets2panda/bindings/test/testcases/getCurrentTokenValue/getCurrentTokenValue3.ets @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'ab' \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getCurrentTokenValue/getCurrentTokenValue4.ets b/ets2panda/bindings/test/testcases/getCurrentTokenValue/getCurrentTokenValue4.ets new file mode 100644 index 0000000000..d6df2324cf --- /dev/null +++ b/ets2panda/bindings/test/testcases/getCurrentTokenValue/getCurrentTokenValue4.ets @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +abc \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition1.ets b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition1.ets new file mode 100644 index 0000000000..15c179144e --- /dev/null +++ b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition1.ets @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export function A(a:number, b:number): number { + return a + b; +} \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition10.ets b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition10.ets new file mode 100644 index 0000000000..dd50405e8c --- /dev/null +++ b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition10.ets @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export class A { +Foo(a:number, b:number): number { + return a + b; +}}; \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition11.ets b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition11.ets new file mode 100644 index 0000000000..09e0ac8b85 --- /dev/null +++ b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition11.ets @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {A} from './getDefinitionAtPosition10'; +let a = new A(); +a.Foo(1, 2); \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition12.ets b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition12.ets new file mode 100644 index 0000000000..c527ffc723 --- /dev/null +++ b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition12.ets @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export let a = 1; \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition13.ets b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition13.ets new file mode 100644 index 0000000000..2b7fd87814 --- /dev/null +++ b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition13.ets @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {a} from './getDefinitionAtPosition12'; +let b = a; \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition14.ets b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition14.ets new file mode 100644 index 0000000000..be0a8b1601 --- /dev/null +++ b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition14.ets @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export interface I {} \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition15.ets b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition15.ets new file mode 100644 index 0000000000..179cd69d8b --- /dev/null +++ b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition15.ets @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {I} from './getDefinitionAtPosition14'; +import * as All from './getDefinitionAtPosition14'; +class A implements All.I {}; \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition16.ets b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition16.ets new file mode 100644 index 0000000000..e0aea4f53a --- /dev/null +++ b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition16.ets @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export class Foo { +Foo(a:number, b:number): number { + return a + b; +}} \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition17.ets b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition17.ets new file mode 100644 index 0000000000..dc857dfeb2 --- /dev/null +++ b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition17.ets @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as All from './getDefinitionAtPosition16'; +let a = new All.Foo(); +a.Foo(1, 2); \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition18.ets b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition18.ets new file mode 100644 index 0000000000..c54a0d1535 --- /dev/null +++ b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition18.ets @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement"; +import { Text, Column, Component, Button, ClickEvent } from "@ohos.arkui.component"; + +import hilog from '@ohos.hilog'; + +@Component +export struct MyStateSample { + message: string = "Click"; + + build() { + Column(undefined) { + Text("Hello World") + .fontSize(20) + Button(this.message) + .backgroundColor("#FFFF00FF") + .onClick((e: ClickEvent) => { + hilog.info(0x0000, 'testTag', 'On Click'); + }) + Child() + } + } +} + +@Component +export struct Child { + stateVar: string = "Child"; + + build() { + Text(this.stateVar) + .fontSize(50) + } +} diff --git a/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition2.ets b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition2.ets new file mode 100644 index 0000000000..ff644354c7 --- /dev/null +++ b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition2.ets @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {A} from './getDefinitionAtPosition1'; +A(1, 2); \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition3.ets b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition3.ets new file mode 100644 index 0000000000..dbe14c69b8 --- /dev/null +++ b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition3.ets @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +function A(a:number, b:number) { + return a + b; +} +A(1, 2); +function A(a:number) { + return a; +} +A(1); diff --git a/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition4.ets b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition4.ets new file mode 100644 index 0000000000..15c179144e --- /dev/null +++ b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition4.ets @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export function A(a:number, b:number): number { + return a + b; +} \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition5.ets b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition5.ets new file mode 100644 index 0000000000..1598eef8a4 --- /dev/null +++ b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition5.ets @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as All from './getDefinitionAtPosition4'; +All.A(1, 2); \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition6.ets b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition6.ets new file mode 100644 index 0000000000..ef8ffe33f4 --- /dev/null +++ b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition6.ets @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export class A { +Foo(a:number, b:number): number { + return a + b; +}} \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition7.ets b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition7.ets new file mode 100644 index 0000000000..a49397300d --- /dev/null +++ b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition7.ets @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as All from './getDefinitionAtPosition6'; +let a = new All.A(); +a.Foo(1, 2); \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition8.ets b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition8.ets new file mode 100644 index 0000000000..b414cf820f --- /dev/null +++ b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition8.ets @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export enum A { +a, +b} \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition9.ets b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition9.ets new file mode 100644 index 0000000000..45f00993e7 --- /dev/null +++ b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition9.ets @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as All from './getDefinitionAtPosition8'; +All.A.a; \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getDocumentHighlights/getDocumentHighlights1.ets b/ets2panda/bindings/test/testcases/getDocumentHighlights/getDocumentHighlights1.ets new file mode 100644 index 0000000000..76a3f0cf46 --- /dev/null +++ b/ets2panda/bindings/test/testcases/getDocumentHighlights/getDocumentHighlights1.ets @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +let aaa = 123; +let bbb = aaa + 111; +let ccc = bbb + aaa + 234; \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getDocumentHighlights/getDocumentHighlights2.ets b/ets2panda/bindings/test/testcases/getDocumentHighlights/getDocumentHighlights2.ets new file mode 100644 index 0000000000..ded0ce5404 --- /dev/null +++ b/ets2panda/bindings/test/testcases/getDocumentHighlights/getDocumentHighlights2.ets @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +let aaa = 123; +let bbb = aaa + 111; +let ccc = bbb + aaa + 234; +function f1(aaa: number) { + return aaa + bbb; +} \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getDocumentHighlights/getDocumentHighlights3.ets b/ets2panda/bindings/test/testcases/getDocumentHighlights/getDocumentHighlights3.ets new file mode 100644 index 0000000000..ce627f2bb7 --- /dev/null +++ b/ets2panda/bindings/test/testcases/getDocumentHighlights/getDocumentHighlights3.ets @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class Foo { + aaa: number = 0; +} + +let foo1 = new Foo(); +foo1.aaa = 222 + +function f2() { + let foo2 = new Foo(); + return foo2.aaa + foo1.aaa; +} diff --git a/ets2panda/bindings/test/testcases/getDocumentHighlights/getDocumentHighlights4.ets b/ets2panda/bindings/test/testcases/getDocumentHighlights/getDocumentHighlights4.ets new file mode 100644 index 0000000000..ce627f2bb7 --- /dev/null +++ b/ets2panda/bindings/test/testcases/getDocumentHighlights/getDocumentHighlights4.ets @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class Foo { + aaa: number = 0; +} + +let foo1 = new Foo(); +foo1.aaa = 222 + +function f2() { + let foo2 = new Foo(); + return foo2.aaa + foo1.aaa; +} diff --git a/ets2panda/bindings/test/testcases/getDocumentHighlights/getDocumentHighlights5.ets b/ets2panda/bindings/test/testcases/getDocumentHighlights/getDocumentHighlights5.ets new file mode 100644 index 0000000000..a287d390a9 --- /dev/null +++ b/ets2panda/bindings/test/testcases/getDocumentHighlights/getDocumentHighlights5.ets @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +function add(x: number, y: number) { + return x + y; +} + +function five() { + return add(2, 3); +} + +class Bar { + six: number = add(2, 4); +} diff --git a/ets2panda/bindings/test/testcases/getDocumentHighlights/getDocumentHighlights6.ets b/ets2panda/bindings/test/testcases/getDocumentHighlights/getDocumentHighlights6.ets new file mode 100644 index 0000000000..f90546953c --- /dev/null +++ b/ets2panda/bindings/test/testcases/getDocumentHighlights/getDocumentHighlights6.ets @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class ListNode { + value: T; + next: ListNode | null = null; + + constructor(value: T) { + this.value = value; + } +} \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getDocumentHighlights/getDocumentHighlights7.ets b/ets2panda/bindings/test/testcases/getDocumentHighlights/getDocumentHighlights7.ets new file mode 100644 index 0000000000..978e4efd6d --- /dev/null +++ b/ets2panda/bindings/test/testcases/getDocumentHighlights/getDocumentHighlights7.ets @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +function fib(n: number) { + if (n === 0) { + return 0; + } + if (n === 1) { + return 1; + } + return fib(n - 1) + fib(n - 2); +} \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getFileReferences/getFileReferences1.ets b/ets2panda/bindings/test/testcases/getFileReferences/getFileReferences1.ets new file mode 100644 index 0000000000..45206d98aa --- /dev/null +++ b/ets2panda/bindings/test/testcases/getFileReferences/getFileReferences1.ets @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {A} from "./getFileReferences1_export"; +import {B} from "./getFileReferences1_export"; +A(1, 2); +B(1, 2); \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getFileReferences/getFileReferences1_export.ets b/ets2panda/bindings/test/testcases/getFileReferences/getFileReferences1_export.ets new file mode 100644 index 0000000000..77c482b8ce --- /dev/null +++ b/ets2panda/bindings/test/testcases/getFileReferences/getFileReferences1_export.ets @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export function A(a:number, b:number): number { + return a + b; +} +export function B(a:number, b:number): number { + return a + b; +} \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getQuickInfoAtPosition/getQuickInfoAtPosition1.ets b/ets2panda/bindings/test/testcases/getQuickInfoAtPosition/getQuickInfoAtPosition1.ets new file mode 100644 index 0000000000..f50e4bfbd5 --- /dev/null +++ b/ets2panda/bindings/test/testcases/getQuickInfoAtPosition/getQuickInfoAtPosition1.ets @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +enum MyStrings { A = 'hello' }; \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getQuickInfoAtPosition/getQuickInfoAtPosition2.ets b/ets2panda/bindings/test/testcases/getQuickInfoAtPosition/getQuickInfoAtPosition2.ets new file mode 100644 index 0000000000..a788974547 --- /dev/null +++ b/ets2panda/bindings/test/testcases/getQuickInfoAtPosition/getQuickInfoAtPosition2.ets @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class MyClass { + public myProp: number = 0; +} \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getQuickInfoAtPosition/getQuickInfoAtPosition3.ets b/ets2panda/bindings/test/testcases/getQuickInfoAtPosition/getQuickInfoAtPosition3.ets new file mode 100644 index 0000000000..ab0913585d --- /dev/null +++ b/ets2panda/bindings/test/testcases/getQuickInfoAtPosition/getQuickInfoAtPosition3.ets @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +interface objI { key : string; } +let obj : objI = { key:"valueaaaaaaaaa," } \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getReferencesAtPosition/getReferencesAtPosition1.ets b/ets2panda/bindings/test/testcases/getReferencesAtPosition/getReferencesAtPosition1.ets new file mode 100644 index 0000000000..3a56d3e05d --- /dev/null +++ b/ets2panda/bindings/test/testcases/getReferencesAtPosition/getReferencesAtPosition1.ets @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +let a = 1;; \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getReferencesAtPosition/getReferencesAtPosition2.ets b/ets2panda/bindings/test/testcases/getReferencesAtPosition/getReferencesAtPosition2.ets new file mode 100644 index 0000000000..1ae5e4a076 --- /dev/null +++ b/ets2panda/bindings/test/testcases/getReferencesAtPosition/getReferencesAtPosition2.ets @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export let a = 1; +let b = a; +function C() { + let c = a; +}; +function D() { + let a = 1; +}; \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getReferencesAtPosition/getReferencesAtPosition3.ets b/ets2panda/bindings/test/testcases/getReferencesAtPosition/getReferencesAtPosition3.ets new file mode 100644 index 0000000000..e0a302229e --- /dev/null +++ b/ets2panda/bindings/test/testcases/getReferencesAtPosition/getReferencesAtPosition3.ets @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {a} from './getReferencesAtPosition2'; +console.log(a); \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getReferencesAtPosition/getReferencesAtPosition4.ets b/ets2panda/bindings/test/testcases/getReferencesAtPosition/getReferencesAtPosition4.ets new file mode 100644 index 0000000000..494046b0c3 --- /dev/null +++ b/ets2panda/bindings/test/testcases/getReferencesAtPosition/getReferencesAtPosition4.ets @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export function A(){}; \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getReferencesAtPosition/getReferencesAtPosition5.ets b/ets2panda/bindings/test/testcases/getReferencesAtPosition/getReferencesAtPosition5.ets new file mode 100644 index 0000000000..55b0a4e86a --- /dev/null +++ b/ets2panda/bindings/test/testcases/getReferencesAtPosition/getReferencesAtPosition5.ets @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {A} from './getReferencesAtPosition4'; +A(); \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getSemanticDiagnostics/getSemanticDiagnostics1.ets b/ets2panda/bindings/test/testcases/getSemanticDiagnostics/getSemanticDiagnostics1.ets new file mode 100644 index 0000000000..7f2a3720c4 --- /dev/null +++ b/ets2panda/bindings/test/testcases/getSemanticDiagnostics/getSemanticDiagnostics1.ets @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +function add(a: number, b: number) { + return a + b; +} +let n = 333; +let res = add(n, n); \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getSemanticDiagnostics/getSemanticDiagnostics2.ets b/ets2panda/bindings/test/testcases/getSemanticDiagnostics/getSemanticDiagnostics2.ets new file mode 100644 index 0000000000..859d052f4d --- /dev/null +++ b/ets2panda/bindings/test/testcases/getSemanticDiagnostics/getSemanticDiagnostics2.ets @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +const a: number = "hello"; +function add(a: number, b: number): number { + return a + b; +} +add("1", 2); \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getSuggestionDiagnostics/getSuggestionDiagnostics1.ets b/ets2panda/bindings/test/testcases/getSuggestionDiagnostics/getSuggestionDiagnostics1.ets new file mode 100644 index 0000000000..cc976ab41f --- /dev/null +++ b/ets2panda/bindings/test/testcases/getSuggestionDiagnostics/getSuggestionDiagnostics1.ets @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +function fetchData(){ +return Promise.resolve("h") +;} +function processData(){ +return fetchData().finally(); +}; +processData(); diff --git a/ets2panda/bindings/test/testcases/getSyntacticDiagnostics/getSyntacticDiagnostics1.ets b/ets2panda/bindings/test/testcases/getSyntacticDiagnostics/getSyntacticDiagnostics1.ets new file mode 100644 index 0000000000..7f2a3720c4 --- /dev/null +++ b/ets2panda/bindings/test/testcases/getSyntacticDiagnostics/getSyntacticDiagnostics1.ets @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +function add(a: number, b: number) { + return a + b; +} +let n = 333; +let res = add(n, n); \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/getSyntacticDiagnostics/getSyntacticDiagnostics2.ets b/ets2panda/bindings/test/testcases/getSyntacticDiagnostics/getSyntacticDiagnostics2.ets new file mode 100644 index 0000000000..6131061452 --- /dev/null +++ b/ets2panda/bindings/test/testcases/getSyntacticDiagnostics/getSyntacticDiagnostics2.ets @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +functon add(a: number, b: number) { + return a + b; +} +let n = 333; +let res = add(n, n); \ No newline at end of file diff --git a/ets2panda/bindings/test/testcases/toLineColumnOffset/toLineColumnOffset1.ets b/ets2panda/bindings/test/testcases/toLineColumnOffset/toLineColumnOffset1.ets new file mode 100644 index 0000000000..e7cfca2ae5 --- /dev/null +++ b/ets2panda/bindings/test/testcases/toLineColumnOffset/toLineColumnOffset1.ets @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +interface X +{ name: string}; +let variable: X = { name: 'Test' }; diff --git a/ets2panda/bindings/test/tsconfig.json b/ets2panda/bindings/test/tsconfig.json new file mode 100644 index 0000000000..72faeb9bec --- /dev/null +++ b/ets2panda/bindings/test/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "rootDir": "..", + "outDir": "../dist-test", + "types": [ + "node" + ] + }, + "include": [ + "./**/*.ts", + "../src/**/*.ts" + ], + "exclude": [ + "../node_modules", + "../dist", + "../dist-test", + "./ets", + "./testcases", + ] +} \ No newline at end of file -- Gitee From d298589d725abd26a90a790a1c3bee74df579d2b Mon Sep 17 00:00:00 2001 From: Boglarka Date: Mon, 7 Apr 2025 14:43:13 +0200 Subject: [PATCH 144/268] Inheritance does not work between interfaces Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBOVNC Reason: Couldn't find default implementations in some cases. Description: Adding missing logic to interface method inheritance Change-Id: Iee3093513edbe51a830ed9d09afae1af14991962 Signed-off-by: Haag Boglarka --- ets2panda/checker/ETSchecker.h | 9 +- ets2panda/checker/ets/function.cpp | 9 +- ets2panda/checker/ets/helpers.cpp | 7 +- ets2panda/checker/ets/object.cpp | 89 +++++++++++++------ ets2panda/checker/types/ets/etsObjectType.cpp | 56 +++++++++--- .../multiple_interface_inheritance_n_1.sts | 35 ++++++++ .../multiple_interface_inheritance_n_2.sts | 35 ++++++++ .../multiple_interface_inheritance_n_3.sts | 32 +++++++ .../ets/multiple_interface_inheritance_1.sts | 35 ++++++++ .../ets/multiple_interface_inheritance_2.sts | 35 ++++++++ .../ets/multiple_interface_inheritance_3.sts | 45 ++++++++++ .../ets/multiple_interface_inheritance_4.sts | 41 +++++++++ 12 files changed, 381 insertions(+), 47 deletions(-) create mode 100644 ets2panda/test/ast/compiler/ets/multiple_interface_inheritance_n_1.sts create mode 100644 ets2panda/test/ast/compiler/ets/multiple_interface_inheritance_n_2.sts create mode 100644 ets2panda/test/ast/compiler/ets/multiple_interface_inheritance_n_3.sts create mode 100644 ets2panda/test/runtime/ets/multiple_interface_inheritance_1.sts create mode 100644 ets2panda/test/runtime/ets/multiple_interface_inheritance_2.sts create mode 100644 ets2panda/test/runtime/ets/multiple_interface_inheritance_3.sts create mode 100644 ets2panda/test/runtime/ets/multiple_interface_inheritance_4.sts diff --git a/ets2panda/checker/ETSchecker.h b/ets2panda/checker/ETSchecker.h index 5c9c003d5a..d21b0eb41b 100644 --- a/ets2panda/checker/ETSchecker.h +++ b/ets2panda/checker/ETSchecker.h @@ -201,9 +201,10 @@ public: ETSObjectType *CheckThisOrSuperAccess(ir::Expression *node, ETSObjectType *classType, std::string_view msg); void CreateTypeForClassOrInterfaceTypeParameters(ETSObjectType *type); ETSTypeParameter *SetUpParameterType(ir::TSTypeParameter *param); - void CheckIfOverrideIsValidInInterface(ETSObjectType *classType, Signature *sig, ir::ScriptFunction *func); + void GetInterfacesOfClass(ETSObjectType *type, ArenaVector &interfaces); + void CheckIfOverrideIsValidInInterface(ETSObjectType *classType, Signature *sig, Signature *sigFunc); void CheckFunctionRedeclarationInInterface(ETSObjectType *classType, ArenaVector &similarSignatures, - ir::ScriptFunction *func); + Signature *sigFunc); void ValidateAbstractMethodsToBeImplemented(ArenaVector &abstractsToBeImplemented, ETSObjectType *classType, const std::vector &implementedSignatures); @@ -500,7 +501,7 @@ public: OverrideErrorCode CheckOverride(Signature *signature, Signature *other); bool IsMethodOverridesOther(Signature *base, Signature *derived); bool IsOverridableIn(Signature *signature); - [[nodiscard]] bool AreOverrideEquivalent(Signature *s1, Signature *s2); + [[nodiscard]] bool AreOverrideCompatible(Signature *s1, Signature *s2); [[nodiscard]] bool IsReturnTypeSubstitutable(Signature *s1, Signature *s2); bool NeedToVerifySignatureVisibility(Signature *signature, const lexer::SourcePosition &pos); void ValidateSignatureAccessibility(ETSObjectType *callee, const ir::CallExpression *callExpr, Signature *signature, @@ -678,6 +679,8 @@ public: varbinder::ClassScope *scope, bool isSetter, ETSChecker *checker); void GenerateGetterSetterPropertyAndMethod(ir::ClassProperty *originalProp, ETSObjectType *classType); + void SetupGetterSetterFlags(ir::ClassProperty *originalProp, ETSObjectType *classType, ir::MethodDefinition *getter, + ir::MethodDefinition *setter, const bool inExternal); Type *GetImportSpecifierObjectType(ir::ETSImportDeclaration *importDecl, ir::Identifier *ident); void ImportNamespaceObjectTypeAddReExportType(ir::ETSImportDeclaration *importDecl, checker::ETSObjectType *lastObjectType, ir::Identifier *ident); diff --git a/ets2panda/checker/ets/function.cpp b/ets2panda/checker/ets/function.cpp index 51526229ee..154e785a69 100644 --- a/ets2panda/checker/ets/function.cpp +++ b/ets2panda/checker/ets/function.cpp @@ -1511,7 +1511,9 @@ bool CheckTypeParameterConstraints(ArenaVector typeParamList1, ArenaVect bool ETSChecker::CheckOverride(Signature *signature, ETSObjectType *site) { - auto *target = site->GetProperty(signature->Function()->Id()->Name(), PropertySearchFlags::SEARCH_METHOD); + PropertySearchFlags flags = + PropertySearchFlags::SEARCH_METHOD | PropertySearchFlags::DISALLOW_SYNTHETIC_METHOD_CREATION; + auto *target = site->GetProperty(signature->Function()->Id()->Name(), flags); bool isOverridingAnySignature = false; if (target == nullptr) { @@ -1718,7 +1720,7 @@ void ETSChecker::CheckCapturedVariables() } } -bool ETSChecker::AreOverrideEquivalent(Signature *const s1, Signature *const s2) +bool ETSChecker::AreOverrideCompatible(Signature *const s1, Signature *const s2) { // Two functions, methods or constructors M and N have the same signature if // their names and type parameters (if any) are the same, and their formal parameter @@ -1734,6 +1736,9 @@ bool ETSChecker::AreOverrideEquivalent(Signature *const s1, Signature *const s2) bool ETSChecker::IsReturnTypeSubstitutable(Signature *const s1, Signature *const s2) { + if (s2->HasSignatureFlag(checker::SignatureFlags::NEED_RETURN_TYPE)) { + s2->Function()->Parent()->Parent()->Check(this); + } auto *const r1 = s1->ReturnType(); auto *const r2 = s2->ReturnType(); diff --git a/ets2panda/checker/ets/helpers.cpp b/ets2panda/checker/ets/helpers.cpp index b28811f544..33ed14bf36 100644 --- a/ets2panda/checker/ets/helpers.cpp +++ b/ets2panda/checker/ets/helpers.cpp @@ -2769,8 +2769,9 @@ ir::ClassProperty *GetImplementationClassProp(ETSChecker *checker, ir::ClassProp return classProp; } -static void SetupGetterSetterFlags(ir::ClassProperty *originalProp, ETSObjectType *classType, - ir::MethodDefinition *getter, ir::MethodDefinition *setter, const bool inExternal) +void ETSChecker::SetupGetterSetterFlags(ir::ClassProperty *originalProp, ETSObjectType *classType, + ir::MethodDefinition *getter, ir::MethodDefinition *setter, + const bool inExternal) { auto *const classDef = classType->GetDeclNode()->AsClassDefinition(); for (auto &method : {getter, setter}) { @@ -2795,7 +2796,7 @@ static void SetupGetterSetterFlags(ir::ClassProperty *originalProp, ETSObjectTyp method->AddModifier(ir::ModifierFlags::DECLARE); method->Function()->AddModifier(ir::ModifierFlags::DECLARE); } - + this->CheckOverride(method->Function()->Signature()); method->SetParent(classDef); classType->AddProperty(method->Variable()->AsLocalVariable()); } diff --git a/ets2panda/checker/ets/object.cpp b/ets2panda/checker/ets/object.cpp index 9dbe6a10d1..cde41eddb7 100644 --- a/ets2panda/checker/ets/object.cpp +++ b/ets2panda/checker/ets/object.cpp @@ -784,20 +784,25 @@ ArenaVector &ETSChecker::GetAbstractsForClass(ETSObjectType * return cachedComputedAbstracts_.insert({classType, {merged, abstractInheritanceTarget}}).first->second.first; } -static bool DoObjectImplementInterface(const ETSObjectType *interfaceType, const ETSObjectType *target) +[[maybe_unused]] static bool DoObjectImplementInterface(const ETSObjectType *interfaceType, const ETSObjectType *target, + const ETSChecker *checker) { - return std::any_of(interfaceType->Interfaces().begin(), interfaceType->Interfaces().end(), - [&target](auto *it) { return it == target || DoObjectImplementInterface(it, target); }); + auto &interfaces = interfaceType->Interfaces(); + return std::any_of(interfaces.begin(), interfaces.end(), [&target, checker](auto *it) { + return it->IsSameBasedGeneric(checker->Relation(), target) || DoObjectImplementInterface(it, target, checker); + }); } static bool CheckIfInterfaceCanBeFoundOnDifferentPaths(const ETSObjectType *classType, - const ETSObjectType *interfaceType) + const ETSObjectType *interfaceType, const ETSChecker *checker) { return std::count_if(classType->Interfaces().begin(), classType->Interfaces().end(), - [&interfaceType](auto *it) { return DoObjectImplementInterface(it, interfaceType); }) == 1; + [&interfaceType, checker](auto *it) { + return DoObjectImplementInterface(it, interfaceType, checker); + }) == 1; } -static void GetInterfacesOfClass(ETSObjectType *type, ArenaVector &interfaces) +void ETSChecker::GetInterfacesOfClass(ETSObjectType *type, ArenaVector &interfaces) { for (auto &classInterface : type->Interfaces()) { if (std::find(interfaces.begin(), interfaces.end(), classInterface) == interfaces.end()) { @@ -807,36 +812,66 @@ static void GetInterfacesOfClass(ETSObjectType *type, ArenaVectorSignature(), sig) && func->IsStatic() == sig->Function()->IsStatic()) { - if (CheckIfInterfaceCanBeFoundOnDifferentPaths(classType, func->Signature()->Owner()) && - (Relation()->IsSupertypeOf(func->Signature()->Owner(), sig->Owner()) || - Relation()->IsSupertypeOf(sig->Owner(), func->Signature()->Owner()))) { + bool throwError = false; + if (AreOverrideCompatible(sig, sigFunc) && sigFunc->Function()->IsStatic() == sig->Function()->IsStatic()) { + SavedTypeRelationFlagsContext const savedFlags(Relation(), Relation()->GetTypeRelationFlags() | + TypeRelationFlag::IGNORE_TYPE_PARAMETERS); + if (CheckIfInterfaceCanBeFoundOnDifferentPaths(classType, sigFunc->Owner(), this) && + (Relation()->IsSupertypeOf(sigFunc->Owner(), sig->Owner()) || + Relation()->IsSupertypeOf(sig->Owner(), sigFunc->Owner()))) { return; } + throwError = true; + } else if (sigFunc->Function()->IsStatic() == sig->Function()->IsStatic()) { + Relation()->Result(false); + SavedTypeRelationFlagsContext savedFlagsCtx(Relation(), TypeRelationFlag::NO_RETURN_TYPE_CHECK); + Relation()->SignatureIsIdenticalTo(sig, sigFunc); + if ((Relation()->IsTrue() && + (sig->GetSignatureInfo()->restVar == nullptr) == (sigFunc->GetSignatureInfo()->restVar == nullptr)) || + (HasSameAssemblySignature(sigFunc, sig))) { + throwError = true; + } + } + if (throwError) { LogError(diagnostic::INTERFACE_METHOD_COLLISION, - {sig->Function()->Id()->Name(), sig->Owner()->Name(), func->Signature()->Owner()->Name()}, + {sig->Function()->Id()->Name(), sig->Owner()->Name(), sigFunc->Owner()->Name()}, classType->GetDeclNode()->Start()); } } void ETSChecker::CheckFunctionRedeclarationInInterface(ETSObjectType *classType, - ArenaVector &similarSignatures, - ir::ScriptFunction *func) + ArenaVector &similarSignatures, Signature *sigFunc) { for (auto *const sig : similarSignatures) { - if (sig != func->Signature() && func->HasBody()) { - if (classType == sig->Owner()) { + if (sig == sigFunc) { + return; + } + if (sigFunc->Function()->Id()->Name() == sig->Function()->Id()->Name()) { + if (classType->IsSameBasedGeneric(Relation(), sig->Owner())) { return; } - - CheckIfOverrideIsValidInInterface(classType, sig, func); + if (Relation()->IsIdenticalTo(sig->Owner(), sigFunc->Owner())) { + continue; + } + CheckIfOverrideIsValidInInterface(classType, sig, sigFunc); } } - similarSignatures.push_back(func->Signature()); + similarSignatures.push_back(sigFunc); +} + +static void CallRedeclarationCheckForCorrectSignature(ir::MethodDefinition *method, ETSFunctionType *funcType, + ArenaVector &similarSignatures, + ETSObjectType *classType, ETSChecker *checker) +{ + ir::ScriptFunction *func = method->Function(); + if (!func->IsAbstract()) { + auto *sigFunc = funcType->FindSignature(func); + checker->CheckFunctionRedeclarationInInterface(classType, similarSignatures, sigFunc); + } } void ETSChecker::CheckInterfaceFunctions(ETSObjectType *classType) @@ -844,14 +879,18 @@ void ETSChecker::CheckInterfaceFunctions(ETSObjectType *classType) ArenaVector interfaces(Allocator()->Adapter()); ArenaVector similarSignatures(Allocator()->Adapter()); interfaces.emplace_back(classType); - checker::GetInterfacesOfClass(classType, interfaces); + GetInterfacesOfClass(classType, interfaces); for (auto *const &interface : interfaces) { for (auto *const &prop : interface->Methods()) { - ir::AstNode *node = prop->Declaration()->Node(); - ir::ScriptFunction *func = node->AsMethodDefinition()->Function(); - if (func->Body() != nullptr) { - CheckFunctionRedeclarationInInterface(classType, similarSignatures, func); + ir::MethodDefinition *node = prop->Declaration()->Node()->AsMethodDefinition(); + if (prop->TsType()->IsTypeError()) { + continue; + } + auto *funcType = prop->TsType()->AsETSFunctionType(); + CallRedeclarationCheckForCorrectSignature(node, funcType, similarSignatures, classType, this); + for (auto *const &overload : node->Overloads()) { + CallRedeclarationCheckForCorrectSignature(overload, funcType, similarSignatures, classType, this); } } } @@ -907,7 +946,7 @@ void ETSChecker::ValidateAbstractSignature(ArenaVector::itera continue; } - if (!AreOverrideEquivalent(*abstractSignature, substImplemented) || + if (!AreOverrideCompatible(*abstractSignature, substImplemented) || !IsReturnTypeSubstitutable(substImplemented, *abstractSignature)) { continue; } diff --git a/ets2panda/checker/types/ets/etsObjectType.cpp b/ets2panda/checker/types/ets/etsObjectType.cpp index 6a85627d83..f68e6e9c9e 100644 --- a/ets2panda/checker/types/ets/etsObjectType.cpp +++ b/ets2panda/checker/types/ets/etsObjectType.cpp @@ -196,27 +196,41 @@ ETSFunctionType *ETSObjectType::CreateMethodTypeForProp(const util::StringView & return GetRelation()->GetChecker()->AsETSChecker()->CreateETSMethodType(name, {{}, Allocator()->Adapter()}); } +static void AddSignature(std::vector &signatures, PropertySearchFlags flags, ETSChecker *checker, + varbinder::LocalVariable *found) +{ + for (auto *it : found->TsType()->AsETSFunctionType()->CallSignatures()) { + if (std::find(signatures.begin(), signatures.end(), it) != signatures.end()) { + continue; + } + if (((flags & PropertySearchFlags::IGNORE_ABSTRACT) != 0) && it->HasSignatureFlag(SignatureFlags::ABSTRACT)) { + continue; + } + if (std::any_of(signatures.begin(), signatures.end(), [&it, &checker](auto sig) { + return checker->AreOverrideCompatible(sig, it) && + it->Owner()->HasObjectFlag(ETSObjectFlags::INTERFACE) && + (checker->Relation()->IsSupertypeOf(it->Owner(), sig->Owner()) || + !sig->Owner()->HasObjectFlag(ETSObjectFlags::INTERFACE)); + })) { + continue; + } + // Issue: #18720 + // NOLINTNEXTLINE(clang-analyzer-core.CallAndMessage) + signatures.emplace_back(it); + } +} + varbinder::LocalVariable *ETSObjectType::CollectSignaturesForSyntheticType(std::vector &signatures, const util::StringView &name, PropertySearchFlags flags) const { - auto const addSignature = [&signatures, flags](varbinder::LocalVariable *found) -> void { - for (auto *it : found->TsType()->AsETSFunctionType()->CallSignatures()) { - if (((flags & PropertySearchFlags::IGNORE_ABSTRACT) != 0) && - it->HasSignatureFlag(SignatureFlags::ABSTRACT)) { - continue; - } - // Issue: #18720 - // NOLINTNEXTLINE(clang-analyzer-core.CallAndMessage) - signatures.push_back(&*it); - } - }; + auto *checker = GetRelation()->GetChecker()->AsETSChecker(); if ((flags & PropertySearchFlags::SEARCH_STATIC_METHOD) != 0) { if (auto *found = GetOwnProperty(name); found != nullptr && !found->TsType()->IsTypeError()) { ES2PANDA_ASSERT(found->TsType()->IsETSFunctionType()); - addSignature(found); + AddSignature(signatures, flags, checker, found); } } @@ -224,14 +238,28 @@ varbinder::LocalVariable *ETSObjectType::CollectSignaturesForSyntheticType(std:: if (auto *found = GetOwnProperty(name); found != nullptr && !found->TsType()->IsTypeError()) { ES2PANDA_ASSERT(found->TsType()->IsETSFunctionType()); - addSignature(found); + AddSignature(signatures, flags, checker, found); } } if (superType_ != nullptr && ((flags & PropertySearchFlags::SEARCH_IN_BASE) != 0)) { - return superType_->CollectSignaturesForSyntheticType(signatures, name, flags); + superType_->CollectSignaturesForSyntheticType(signatures, name, flags); } + ArenaVector interfaces(Allocator()->Adapter()); + checker->GetInterfacesOfClass(const_cast(this), interfaces); + + for (auto *const &interface : interfaces) { + if (interface != nullptr && ((flags & PropertySearchFlags::SEARCH_IN_INTERFACES) != 0) && + !this->IsPartial()) { // NOTE: issue 24548 + if (auto *found = + interface->GetProperty(name, flags | PropertySearchFlags::DISALLOW_SYNTHETIC_METHOD_CREATION); + found != nullptr && !found->TsType()->IsTypeError()) { + ES2PANDA_ASSERT(found->TsType()->IsETSFunctionType()); + AddSignature(signatures, flags, checker, found); + } + } + } return nullptr; } diff --git a/ets2panda/test/ast/compiler/ets/multiple_interface_inheritance_n_1.sts b/ets2panda/test/ast/compiler/ets/multiple_interface_inheritance_n_1.sts new file mode 100644 index 0000000000..299d99292c --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/multiple_interface_inheritance_n_1.sts @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +let res: number = 0; + +interface I { + foo(i: number) { + return 1; + } +} + +interface J { + foo(j: string) { + return 2; + } + foo(i: number) { + return 1; + } +} + +class A implements I, J /* @@ label */{} + +/* @@@ label Error TypeError: Method 'foo' is declared in I and J interfaces. */ \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/multiple_interface_inheritance_n_2.sts b/ets2panda/test/ast/compiler/ets/multiple_interface_inheritance_n_2.sts new file mode 100644 index 0000000000..ef84118c38 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/multiple_interface_inheritance_n_2.sts @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +let res: number = 0; + +interface I { + foo(i: number) { + return 1; + } +} + +interface J extends I { + foo(j: string) { + return 2; + } + foo(i: number) { + return 1; + } +} + +class A implements I, J /* @@ label */{} + +/* @@@ label Error TypeError: Method 'foo' is declared in I and J interfaces. */ \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/multiple_interface_inheritance_n_3.sts b/ets2panda/test/ast/compiler/ets/multiple_interface_inheritance_n_3.sts new file mode 100644 index 0000000000..1329c83040 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/multiple_interface_inheritance_n_3.sts @@ -0,0 +1,32 @@ +// /* +// * Copyright (c) 2025 Huawei Device Co., Ltd. +// * Licensed under the Apache License, Version 2.0 (the "License"); +// * you may not use this file except in compliance with the License. +// * You may obtain a copy of the License at +// * +// * http://www.apache.org/licenses/LICENSE-2.0 +// * +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an "AS IS" BASIS, +// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// * See the License for the specific language governing permissions and +// * limitations under the License. +// */ + +let res: number = 0; + +interface I { + foo(i: number): string { + return "str"; + } +} +interface J { + foo(i: number): int { + return 3; + } + +} + +class A implements J, I /* @@ label */{} + +/* @@@ label Error TypeError: Method 'foo' is declared in J and I interfaces. */ diff --git a/ets2panda/test/runtime/ets/multiple_interface_inheritance_1.sts b/ets2panda/test/runtime/ets/multiple_interface_inheritance_1.sts new file mode 100644 index 0000000000..90a14cbcd3 --- /dev/null +++ b/ets2panda/test/runtime/ets/multiple_interface_inheritance_1.sts @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +let res: number = 0; + +interface I { + foo(i: number) { + return 1; + } +} +interface J extends I { + foo(j: string) { + return 2; + } +} + +class A implements I, J {} + +function main(): void { + let a = new A(); + assertEQ(a.foo(1.1 as number), 1); + assertEQ(a.foo("some string"), 2); +} \ No newline at end of file diff --git a/ets2panda/test/runtime/ets/multiple_interface_inheritance_2.sts b/ets2panda/test/runtime/ets/multiple_interface_inheritance_2.sts new file mode 100644 index 0000000000..c3e5110ba0 --- /dev/null +++ b/ets2panda/test/runtime/ets/multiple_interface_inheritance_2.sts @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +let res: number = 0; + +interface I { + foo(i: number) { + return 1; + } +} +interface J extends I { + foo(j: string) { + return 2; + } +} + +class A implements J, I {} + +function main(): void { + let a = new A(); + assertEQ(a.foo(1.1 as number), 1); + assertEQ(a.foo("some string"), 2); +} \ No newline at end of file diff --git a/ets2panda/test/runtime/ets/multiple_interface_inheritance_3.sts b/ets2panda/test/runtime/ets/multiple_interface_inheritance_3.sts new file mode 100644 index 0000000000..72c606eadb --- /dev/null +++ b/ets2panda/test/runtime/ets/multiple_interface_inheritance_3.sts @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +let res: number = 0; + +interface I { + foo(i: number) { + return 1; + } +} +interface J extends I { + foo(j: string) { + return 2; + } +} + +class B { + foo(j: string) { + return 3; + } + +} +class A extends B implements J, I { + foo(i: number) { + return 4; + } +} + +function main(): void { + let a = new A(); + assertEQ(a.foo(1.1 as number), 4); + assertEQ(a.foo("some string"), 3); +} \ No newline at end of file diff --git a/ets2panda/test/runtime/ets/multiple_interface_inheritance_4.sts b/ets2panda/test/runtime/ets/multiple_interface_inheritance_4.sts new file mode 100644 index 0000000000..4c4e82e2b4 --- /dev/null +++ b/ets2panda/test/runtime/ets/multiple_interface_inheritance_4.sts @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +let res: number = 0; + +interface I { + foo(i: number) { + return 1; + } +} +interface J extends I { + foo(j: string) { + return 2; + } +} + +class B { + foo(j: string) { + return 3; + } +} + +class A extends B implements J, I {} + +function main(): void { + let a = new A(); + assertEQ(a.foo(1.1 as number), 1); + assertEQ(a.foo("some string"), 3); +} \ No newline at end of file -- Gitee From 59d283679324c7aedd0bfe8aefae315de9fac8d8 Mon Sep 17 00:00:00 2001 From: groshevmaksim Date: Thu, 17 Apr 2025 14:22:18 +0300 Subject: [PATCH 145/268] Frontend Codefix Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC20MO Tests: ninja all tests Signed-off-by: groshevmaksim --- ets2panda/linter/src/lib/TypeScriptLinter.ts | 4 ++++ ets2panda/test/depanalyzer/test.cpp | 4 ++++ ets2panda/test/unit/ast_dumper_test.cpp | 4 ++-- .../unit/public/ast_verifier_private_access_negative_test.cpp | 4 ++++ .../public/ast_verifier_protected_access_negative_test.cpp | 4 ++++ ets2panda/test/unit/public/ast_verifier_short_test.cpp | 4 ++++ ets2panda/test/unit/public/es2panda_public_test.cpp | 4 ++++ ets2panda/util/importPathManager.h | 4 ++-- ets2panda/varbinder/ETSBinder.h | 4 ++-- ets2panda/varbinder/varbinder.h | 2 +- 10 files changed, 31 insertions(+), 7 deletions(-) diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index a95af41659..d1b09c5367 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -2481,7 +2481,11 @@ export class TypeScriptLinter { private static findFinalExpression(typeNode: ts.TypeNode): ts.Node { let currentNode = typeNode; + /* CC-OFFNXT(no_explicit_any) std lib */ + // Handle comment directive '@ts-nocheck' while ((currentNode as any).expression) { + /* CC-OFFNXT(no_explicit_any) std lib */ + // Handle comment directive '@ts-nocheck' currentNode = (currentNode as any).expression; } return currentNode; diff --git a/ets2panda/test/depanalyzer/test.cpp b/ets2panda/test/depanalyzer/test.cpp index 348ace2adb..d48242182b 100644 --- a/ets2panda/test/depanalyzer/test.cpp +++ b/ets2panda/test/depanalyzer/test.cpp @@ -21,6 +21,8 @@ #include "path_getter.h" #include "os/filesystem.h" +namespace { + class DepAnalyzerTest : public testing::Test { public: DepAnalyzerTest() = default; @@ -96,3 +98,5 @@ TEST_F(DepAnalyzerTest, Subtestv4) GetExpectedAns(expected, testFolderNum, testFileCounter); ASSERT(GetTestSourcePaths() == expected); } + +} // namespace diff --git a/ets2panda/test/unit/ast_dumper_test.cpp b/ets2panda/test/unit/ast_dumper_test.cpp index 19ad7c92e8..de68acb836 100644 --- a/ets2panda/test/unit/ast_dumper_test.cpp +++ b/ets2panda/test/unit/ast_dumper_test.cpp @@ -105,8 +105,6 @@ TestParams DumpEtsSrcSimple() "--dump-ets-src-before-phases=plugins-after-parse,plugins-after-check,plugins-after-lowering"}}; } -} // namespace - class ASTDumperTest : public testing::TestWithParam { public: ASTDumperTest() @@ -156,3 +154,5 @@ TEST_F(ASTDumperTest, CheckSrcDump) ASSERT(program); ASSERT(!dumpStr.str().empty()); } + +} // namespace diff --git a/ets2panda/test/unit/public/ast_verifier_private_access_negative_test.cpp b/ets2panda/test/unit/public/ast_verifier_private_access_negative_test.cpp index 6a7cd71d0a..4fbc212dba 100644 --- a/ets2panda/test/unit/public/ast_verifier_private_access_negative_test.cpp +++ b/ets2panda/test/unit/public/ast_verifier_private_access_negative_test.cpp @@ -16,6 +16,8 @@ #include "ast_verifier_test.h" #include "checker/ETSchecker.h" +namespace { + using ark::es2panda::compiler::ast_verifier::ModifierAccessValid; TEST_F(ASTVerifierTest, PrivateAccessTestNegative1) @@ -251,3 +253,5 @@ TEST_F(ASTVerifierTest, PrivateAccessTestNegative7) EXPECT_TRUE(Verify(ExpectVerifierMessage {"PROPERTY_NOT_VISIBLE_HERE"})); } } + +} // namespace diff --git a/ets2panda/test/unit/public/ast_verifier_protected_access_negative_test.cpp b/ets2panda/test/unit/public/ast_verifier_protected_access_negative_test.cpp index d3204e733f..2573cc1244 100644 --- a/ets2panda/test/unit/public/ast_verifier_protected_access_negative_test.cpp +++ b/ets2panda/test/unit/public/ast_verifier_protected_access_negative_test.cpp @@ -16,6 +16,8 @@ #include "ast_verifier_test.h" #include "checker/ETSchecker.h" +namespace { + using ark::es2panda::compiler::ast_verifier::ModifierAccessValid; TEST_F(ASTVerifierTest, ProtectedAccessTestNegative1) @@ -225,3 +227,5 @@ TEST_F(ASTVerifierTest, ProtectedAccessTestNegative6) EXPECT_TRUE(Verify(ExpectVerifierMessage {"PROPERTY_NOT_VISIBLE_HERE"})); } } + +} // namespace diff --git a/ets2panda/test/unit/public/ast_verifier_short_test.cpp b/ets2panda/test/unit/public/ast_verifier_short_test.cpp index 214ac89d08..c5cf75fa2b 100644 --- a/ets2panda/test/unit/public/ast_verifier_short_test.cpp +++ b/ets2panda/test/unit/public/ast_verifier_short_test.cpp @@ -24,6 +24,8 @@ #include "varbinder/ETSBinder.h" #include "util/diagnosticEngine.h" +namespace { + using ark::es2panda::ScriptExtension; using ark::es2panda::checker::ETSChecker; using ark::es2panda::compiler::ast_verifier::ArithmeticOperationValid; @@ -278,3 +280,5 @@ TEST_F(ASTVerifierTest, VariableNameIdentifierNameSame) EXPECT_TRUE(Verify()); } } + +} // namespace diff --git a/ets2panda/test/unit/public/es2panda_public_test.cpp b/ets2panda/test/unit/public/es2panda_public_test.cpp index e32c4791a8..aab1f3a3f4 100644 --- a/ets2panda/test/unit/public/es2panda_public_test.cpp +++ b/ets2panda/test/unit/public/es2panda_public_test.cpp @@ -20,6 +20,8 @@ #include "test/utils/ast_verifier_test.h" #include "util/diagnostic.h" +namespace { + using Es2PandaLibTest = test::utils::AstVerifierTest; TEST_F(Es2PandaLibTest, NoError) @@ -93,3 +95,5 @@ TEST_F(Es2PandaLibTest, LogDiagnostic) ASSERT_EQ((*diagnosticStorage)[0]->Message(), "Test 1"); } } + +} // namespace diff --git a/ets2panda/util/importPathManager.h b/ets2panda/util/importPathManager.h index 11bb355d53..23530cb7e6 100644 --- a/ets2panda/util/importPathManager.h +++ b/ets2panda/util/importPathManager.h @@ -149,13 +149,13 @@ private: // NOLINTEND(misc-non-private-member-variables-in-classes) }; ResolvedPathRes ResolvePath(std::string_view curModulePath, ir::StringLiteral *importPath) const; - ResolvedPathRes ResolveAbsolutePath(const ir::StringLiteral &importPath) const; + ResolvedPathRes ResolveAbsolutePath(const ir::StringLiteral &importPathNode) const; std::string_view DirOrDirWithIndexFile(StringView dir) const; ResolvedPathRes AppendExtensionOrIndexFileIfOmitted(StringView basePath) const; std::string TryMatchDynamicPath(std::string_view fixedPath) const; StringView GetRealPath(StringView path) const; - void AddToParseList(ImportMetadata importMetadata); + void AddToParseList(const ImportMetadata importMetadata); #ifdef USE_UNIX_SYSCALL void UnixWalkThroughDirectoryAndAddToParseList(ImportMetadata importMetadata); #endif diff --git a/ets2panda/varbinder/ETSBinder.h b/ets2panda/varbinder/ETSBinder.h index 66b242933f..6463ebb852 100644 --- a/ets2panda/varbinder/ETSBinder.h +++ b/ets2panda/varbinder/ETSBinder.h @@ -171,8 +171,8 @@ public: const varbinder::Scope::VariableMap &globalBindings, Span record); Variable *FindStaticBinding(Span records, const ir::StringLiteral *importPath); - void AddSpecifiersToTopBindings(ir::AstNode *specifier, const ir::ETSImportDeclaration *import); - void AddDynamicSpecifiersToTopBindings(ir::AstNode *specifier, const ir::ETSImportDeclaration *import); + void AddSpecifiersToTopBindings(ir::AstNode *const specifier, const ir::ETSImportDeclaration *const import); + void AddDynamicSpecifiersToTopBindings(ir::AstNode *const specifier, const ir::ETSImportDeclaration *const import); void ResolveInterfaceDeclaration(ir::TSInterfaceDeclaration *decl); void ResolveMethodDefinition(ir::MethodDefinition *methodDef); diff --git a/ets2panda/varbinder/varbinder.h b/ets2panda/varbinder/varbinder.h index a7649724f5..8fe135f211 100644 --- a/ets2panda/varbinder/varbinder.h +++ b/ets2panda/varbinder/varbinder.h @@ -249,7 +249,7 @@ protected: void BuildForInOfLoop(varbinder::LoopScope *loopScope, ir::AstNode *left, ir::Expression *right, ir::Statement *body); void BuildCatchClause(ir::CatchClause *catchClauseStmt); - void BuildTypeAliasDeclaration(ir::TSTypeAliasDeclaration *typeAliasDecl); + void BuildTypeAliasDeclaration(ir::TSTypeAliasDeclaration *const typeAliasDecl); void ResolveReferences(const ir::AstNode *parent); void VisitScriptFunctionWithPotentialTypeParams(ir::ScriptFunction *func); void VisitScriptFunction(ir::ScriptFunction *func); -- Gitee From cf5aa838dffe8854857e755eea1331b94dfd4d9e Mon Sep 17 00:00:00 2001 From: zhangziye Date: Tue, 22 Apr 2025 14:39:53 +0800 Subject: [PATCH 146/268] etssdk use GN template Issue: #IC1F7V Signed-off-by: zhangziye --- ets2panda/CMakeLists.txt | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/ets2panda/CMakeLists.txt b/ets2panda/CMakeLists.txt index 57b60df30b..bd09554954 100644 --- a/ets2panda/CMakeLists.txt +++ b/ets2panda/CMakeLists.txt @@ -48,8 +48,27 @@ if(PANDA_WITH_ETS) " \"paths\": {\n" " \"std\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}stdlib${DELIM}std\"],\n" " \"escompat\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}stdlib${DELIM}escompat\"],\n" - " \"api\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api\"],\n" - " \"arkts\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}arkts\"],\n" + " \"@ohos.buffer\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.buffer.ets\"],\n" + " \"@ohos.util.ArrayList\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.util.ArrayList.ets\"],\n" + " \"@ohos.util.Deque\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.util.Deque.ets\"],\n" + " \"@ohos.util.HashMap\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.util.HashMap.ets\"],\n" + " \"@ohos.util.HashSet\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.util.HashSet.ets\"],\n" + " \"@ohos.util.json\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.util.json.ets\"],\n" + " \"@ohos.util.LightWeightMap\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.util.LightWeightMap.ets\"],\n" + " \"@ohos.util.LightWeightSet\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.util.LightWeightSet.ets\"],\n" + " \"@ohos.util.LinkedList\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.util.LinkedList.ets\"],\n" + " \"@ohos.util.List\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.util.List.ets\"],\n" + " \"@ohos.util.PlainArray\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.util.PlainArray.ets\"],\n" + " \"@ohos.util.Queue\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.util.Queue.ets\"],\n" + " \"@ohos.util.Stack\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.util.Stack.ets\"],\n" + " \"@ohos.util\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.util.ets\"],\n" + " \"@ohos.util.TreeMap\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.util.TreeMap.ets\"],\n" + " \"@ohos.util.TreeSet\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.util.TreeSet.ets\"],\n" + " \"@ohos.uri\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.uri.ets\"],\n" + " \"@ohos.url\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.url.ets\"],\n" + " \"@ohos.xml\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.xml.ets\"],\n" + " \"@ohos.base\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}api${DELIM}@ohos.base.ets\"],\n" + " \"@arkts.math.Decimal\": [\"${STATIC_CORE}${DELIM}plugins${DELIM}ets${DELIM}sdk${DELIM}arkts${DELIM}@arkts.math.Decimal.ets\"],\n" " \"import_tests\": [\"${CMAKE_CURRENT_SOURCE_DIR}/test/parser/ets/import_tests\"]\n" " },\n" " \"dynamicPaths\": {\n" -- Gitee From b50602155641310d40a5d3e8036ca29552a37059 Mon Sep 17 00:00:00 2001 From: Dmitry Pimenov Date: Wed, 9 Apr 2025 11:44:04 +0300 Subject: [PATCH 147/268] Don't test this in ValidateSignatureAccessibility Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBVDPT Change-Id: I4ba8801b8148b8cc8455cc20b74464009841880a Signed-off-by: Dmitry Pimenov --- ets2panda/checker/ETSAnalyzer.cpp | 8 ++-- ets2panda/checker/ETSchecker.h | 3 +- ets2panda/checker/ets/function.cpp | 12 +----- ets2panda/checker/ets/helpers.cpp | 2 +- ets2panda/checker/ets/object.cpp | 5 +-- ets2panda/ir/expressions/memberExpression.cpp | 39 ++++++++++++++++++- ets2panda/ir/expressions/memberExpression.h | 5 +++ ets2panda/ir/statements/forOfStatement.cpp | 3 +- .../ets/InterfacePrivateMethod.ets | 4 +- 9 files changed, 54 insertions(+), 27 deletions(-) rename ets2panda/test/{ast/parser => runtime}/ets/InterfacePrivateMethod.ets (87%) diff --git a/ets2panda/checker/ETSAnalyzer.cpp b/ets2panda/checker/ETSAnalyzer.cpp index 0a2b718926..f127204827 100644 --- a/ets2panda/checker/ETSAnalyzer.cpp +++ b/ets2panda/checker/ETSAnalyzer.cpp @@ -396,7 +396,7 @@ static bool CheckArrayElementType(ETSChecker *checker, T *newArrayInstanceExpr) // A workaround check for new Interface[...] in test cases newArrayInstanceExpr->SetSignature(checker->CollectParameterlessConstructor( calleeObj->ConstructSignatures(), newArrayInstanceExpr->Start())); - checker->ValidateSignatureAccessibility(calleeObj, nullptr, newArrayInstanceExpr->Signature(), + checker->ValidateSignatureAccessibility(calleeObj, newArrayInstanceExpr->Signature(), newArrayInstanceExpr->Start()); } else { checker->LogError(diagnostic::ABSTRACT_CLASS_AS_ARRAY_ELEMENT_TYPE, {}, newArrayInstanceExpr->Start()); @@ -492,7 +492,7 @@ checker::Type *ETSAnalyzer::Check(ir::ETSNewClassInstanceExpression *expr) const checker->CheckObjectLiteralArguments(signature, expr->GetArguments()); - checker->ValidateSignatureAccessibility(calleeObj, nullptr, signature, expr->Start()); + checker->ValidateSignatureAccessibility(calleeObj, signature, expr->Start()); if (calleeType->IsETSDynamicType()) { ES2PANDA_ASSERT(signature->Function()->IsDynamic()); @@ -1280,7 +1280,7 @@ Type *ETSAnalyzer::GetReturnType(ir::CallExpression *expr, Type *calleeType) con if (calleeType->IsETSMethodType()) { ETSObjectType *calleeObj = GetCallExpressionCalleeObject(checker, expr, calleeType); - checker->ValidateSignatureAccessibility(calleeObj, expr, signature, expr->Start()); + checker->ValidateSignatureAccessibility(calleeObj, signature, expr->Start()); } if (calleeType->IsETSMethodType() && signature->Function()->IsDynamic()) { @@ -1765,7 +1765,7 @@ checker::Type *ETSAnalyzer::Check(ir::ObjectExpression *expr) const for (checker::Signature *sig : objType->ConstructSignatures()) { if (sig->Params().empty()) { haveEmptyConstructor = true; - checker->ValidateSignatureAccessibility(objType, nullptr, sig, expr->Start()); + checker->ValidateSignatureAccessibility(objType, sig, expr->Start()); break; } } diff --git a/ets2panda/checker/ETSchecker.h b/ets2panda/checker/ETSchecker.h index 5c9c003d5a..9c760e7c80 100644 --- a/ets2panda/checker/ETSchecker.h +++ b/ets2panda/checker/ETSchecker.h @@ -503,8 +503,7 @@ public: [[nodiscard]] bool AreOverrideEquivalent(Signature *s1, Signature *s2); [[nodiscard]] bool IsReturnTypeSubstitutable(Signature *s1, Signature *s2); bool NeedToVerifySignatureVisibility(Signature *signature, const lexer::SourcePosition &pos); - void ValidateSignatureAccessibility(ETSObjectType *callee, const ir::CallExpression *callExpr, Signature *signature, - const lexer::SourcePosition &pos, + void ValidateSignatureAccessibility(ETSObjectType *callee, Signature *signature, const lexer::SourcePosition &pos, const MaybeDiagnosticInfo &maybeErrorInfo = std::nullopt); void CheckCapturedVariables(); void CheckCapturedVariableInSubnodes(ir::AstNode *node, varbinder::Variable *var); diff --git a/ets2panda/checker/ets/function.cpp b/ets2panda/checker/ets/function.cpp index 51526229ee..97b05cc97f 100644 --- a/ets2panda/checker/ets/function.cpp +++ b/ets2panda/checker/ets/function.cpp @@ -1616,8 +1616,8 @@ bool ETSChecker::NeedToVerifySignatureVisibility(Signature *signature, const lex signature->HasSignatureFlag(SignatureFlags::PROTECTED)); } -void ETSChecker::ValidateSignatureAccessibility(ETSObjectType *callee, const ir::CallExpression *callExpr, - Signature *signature, const lexer::SourcePosition &pos, +void ETSChecker::ValidateSignatureAccessibility(ETSObjectType *callee, Signature *signature, + const lexer::SourcePosition &pos, const MaybeDiagnosticInfo &maybeErrorInfo) { if (!NeedToVerifySignatureVisibility(signature, pos)) { @@ -1629,14 +1629,6 @@ void ETSChecker::ValidateSignatureAccessibility(ETSObjectType *callee, const ir: ES2PANDA_ASSERT(declNode && (declNode->IsClassDefinition() || declNode->IsTSInterfaceDeclaration())); if (declNode->IsTSInterfaceDeclaration()) { - const auto *enclosingFunc = - util::Helpers::FindAncestorGivenByType(callExpr, ir::AstNodeType::SCRIPT_FUNCTION)->AsScriptFunction(); - if (callExpr->Callee()->IsMemberExpression() && - callExpr->Callee()->AsMemberExpression()->Object()->IsThisExpression() && - signature->Function()->IsPrivate() && !enclosingFunc->IsPrivate()) { - LogError(diagnostic::THIS_OUTSIDE_METHOD_CTX, {}, enclosingFunc->Start()); - } - if (containingClass == declNode->AsTSInterfaceDeclaration()->TsType() && isContainingSignatureInherited) { return; } diff --git a/ets2panda/checker/ets/helpers.cpp b/ets2panda/checker/ets/helpers.cpp index b28811f544..a6d6640757 100644 --- a/ets2panda/checker/ets/helpers.cpp +++ b/ets2panda/checker/ets/helpers.cpp @@ -874,7 +874,7 @@ static checker::Type *ResolveGetter(checker::ETSChecker *checker, ir::MemberExpr return nullptr; } - checker->ValidateSignatureAccessibility(objType, nullptr, originalGetter, expr->Start()); + checker->ValidateSignatureAccessibility(objType, originalGetter, expr->Start()); return originalGetter->ReturnType(); } diff --git a/ets2panda/checker/ets/object.cpp b/ets2panda/checker/ets/object.cpp index 9dbe6a10d1..449d9f9204 100644 --- a/ets2panda/checker/ets/object.cpp +++ b/ets2panda/checker/ets/object.cpp @@ -1951,10 +1951,9 @@ ETSFunctionType *ETSChecker::ResolveAccessorTypeByFlag(ir::MemberExpression *con { ETSFunctionType *finalRes = nullptr; auto const &sourcePos = memberExpr->Property()->Start(); - auto callExpr = memberExpr->Parent()->IsCallExpression() ? memberExpr->Parent()->AsCallExpression() : nullptr; if ((searchFlag & PropertySearchFlags::IS_GETTER) != 0) { if (propType != nullptr && propType->HasTypeFlag(TypeFlag::GETTER)) { - ValidateSignatureAccessibility(memberExpr->ObjType(), callExpr, propType->FindGetter(), sourcePos); + ValidateSignatureAccessibility(memberExpr->ObjType(), propType->FindGetter(), sourcePos); finalRes = propType; } @@ -1975,7 +1974,7 @@ ETSFunctionType *ETSChecker::ResolveAccessorTypeByFlag(ir::MemberExpression *con if (propType != nullptr) { ValidateReadonlyProperty(memberExpr, propType, sourcePos); if (propType->FindSetter() != nullptr) { - ValidateSignatureAccessibility(memberExpr->ObjType(), callExpr, propType->FindSetter(), sourcePos); + ValidateSignatureAccessibility(memberExpr->ObjType(), propType->FindSetter(), sourcePos); finalRes = propType; } } diff --git a/ets2panda/ir/expressions/memberExpression.cpp b/ets2panda/ir/expressions/memberExpression.cpp index 14f43a1d25..0382afa775 100644 --- a/ets2panda/ir/expressions/memberExpression.cpp +++ b/ets2panda/ir/expressions/memberExpression.cpp @@ -346,6 +346,42 @@ bool MemberExpression::CheckArrayIndexValue(checker::ETSChecker *checker) const return true; } +checker::Type *MemberExpression::ResolveReturnTypeFromSignature(checker::ETSChecker *checker, bool isSetter, + ArenaVector &arguments, + ArenaVector &signatures, + std::string_view const methodName) +{ + auto flags = checker::TypeRelationFlag::NONE; + checker::Signature *signature = + checker->ValidateSignatures(signatures, nullptr, arguments, Start(), "indexing", flags); + if (signature == nullptr) { + if (isSetter) { + Parent()->AsAssignmentExpression()->Right()->SetParent(Parent()); + } + checker->LogError(diagnostic::MISSING_INDEX_ACCESSOR_WITH_SIG, {}, Property()->Start()); + return nullptr; + } + checker->ValidateSignatureAccessibility(objType_, signature, Start()); + + ES2PANDA_ASSERT(signature->Function() != nullptr); + + if (isSetter) { + if (checker->IsClassStaticMethod(objType_, signature)) { + checker->LogError(diagnostic::PROP_IS_STATIC, {methodName, objType_->Name()}, Property()->Start()); + } + // Restore the right assignment node's parent to keep AST invariant valid. + Parent()->AsAssignmentExpression()->Right()->SetParent(Parent()); + return signature->Params()[1]->TsType(); + } + + // #24301: requires enum refactoring + if (!signature->Owner()->IsETSEnumType() && checker->IsClassStaticMethod(objType_, signature)) { + checker->LogError(diagnostic::PROP_IS_STATIC, {methodName, objType_->Name()}, Property()->Start()); + return nullptr; + } + return signature->ReturnType(); +} + checker::Type *MemberExpression::CheckIndexAccessMethod(checker::ETSChecker *checker) { checker::PropertySearchFlags searchFlag = checker::PropertySearchFlags::SEARCH_METHOD; @@ -385,8 +421,7 @@ checker::Type *MemberExpression::CheckIndexAccessMethod(checker::ETSChecker *che checker->LogError(diagnostic::MISSING_INDEX_ACCESSOR_WITH_SIG, {}, Property()->Start()); return nullptr; } - checker->ValidateSignatureAccessibility(objType_, nullptr, signature, Start(), - {{diagnostic::INVISIBLE_INDEX_ACCESSOR, {}}}); + checker->ValidateSignatureAccessibility(objType_, signature, Start(), {{diagnostic::INVISIBLE_INDEX_ACCESSOR, {}}}); ES2PANDA_ASSERT(signature->Function() != nullptr); diff --git a/ets2panda/ir/expressions/memberExpression.h b/ets2panda/ir/expressions/memberExpression.h index fa2c4d5361..04acc4fbd6 100644 --- a/ets2panda/ir/expressions/memberExpression.h +++ b/ets2panda/ir/expressions/memberExpression.h @@ -253,6 +253,11 @@ private: bool CheckArrayIndexValue(checker::ETSChecker *checker) const; checker::Type *CheckIndexAccessMethod(checker::ETSChecker *checker); + checker::Type *ResolveReturnTypeFromSignature(checker::ETSChecker *checker, bool isSetter, + ArenaVector &arguments, + ArenaVector &signatures, + std::string_view const methodName); + void LoadRhs(compiler::PandaGen *pg) const; Expression *object_ = nullptr; diff --git a/ets2panda/ir/statements/forOfStatement.cpp b/ets2panda/ir/statements/forOfStatement.cpp index 5426ff6b50..31198b09a9 100644 --- a/ets2panda/ir/statements/forOfStatement.cpp +++ b/ets2panda/ir/statements/forOfStatement.cpp @@ -169,8 +169,7 @@ checker::Type *ForOfStatement::CheckIteratorMethodForObject(checker::ETSChecker checker->LogError(diagnostic::MISSING_ITERATOR_METHOD_WITH_SIG, {}, position); return nullptr; } - checker->ValidateSignatureAccessibility(sourceType, nullptr, signature, position, - {{diagnostic::INVISIBLE_ITERATOR, {}}}); + checker->ValidateSignatureAccessibility(sourceType, signature, position, {{diagnostic::INVISIBLE_ITERATOR, {}}}); ES2PANDA_ASSERT(signature->Function() != nullptr); diff --git a/ets2panda/test/ast/parser/ets/InterfacePrivateMethod.ets b/ets2panda/test/runtime/ets/InterfacePrivateMethod.ets similarity index 87% rename from ets2panda/test/ast/parser/ets/InterfacePrivateMethod.ets rename to ets2panda/test/runtime/ets/InterfacePrivateMethod.ets index ab7a71d219..775cdd1052 100644 --- a/ets2panda/test/ast/parser/ets/InterfacePrivateMethod.ets +++ b/ets2panda/test/runtime/ets/InterfacePrivateMethod.ets @@ -18,7 +18,7 @@ interface Vehicle { return (rpm * trq) / 5252; } - getPwrIndex/* @@ label */(trq: int): int{ + getPwrIndex(trq: int): int{ return this.getHorsePower3(5252, trq); } } @@ -28,5 +28,3 @@ class Car implements Vehicle{} function main(): void { assertEQ(new Car().getPwrIndex(1), 1); } - -/* @@@ label Error TypeError: Cannot reference 'this' in this context. */ -- Gitee From 95a5af837765145983d40229be1fb50488179034 Mon Sep 17 00:00:00 2001 From: Klimentieva Date: Thu, 27 Mar 2025 19:51:25 +0300 Subject: [PATCH 148/268] Add plugin to test recheck Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBY3YB Change-Id: I6aa814d338588f025df9daa9712167642954ebe4 Signed-off-by: Klimentieva --- .../test-lists/recheck/recheck-ignored.txt | 1467 +++++++++++++++++ ets2panda/test/unit/plugin/CMakeLists.txt | 1 + .../unit/plugin/e2p_test_plugin_recheck.c | 42 + 3 files changed, 1510 insertions(+) create mode 100644 ets2panda/test/test-lists/recheck/recheck-ignored.txt create mode 100644 ets2panda/test/unit/plugin/e2p_test_plugin_recheck.c diff --git a/ets2panda/test/test-lists/recheck/recheck-ignored.txt b/ets2panda/test/test-lists/recheck/recheck-ignored.txt new file mode 100644 index 0000000000..408ac1b5b3 --- /dev/null +++ b/ets2panda/test/test-lists/recheck/recheck-ignored.txt @@ -0,0 +1,1467 @@ +# New failures at #FailKind.ES2PANDA_FAIL +# Negative tests that are ignored +ast/parser/ets/import_tests/export_and_import_class.ets +ast/parser/ets/import_tests/export_and_import_top_level.ets +compiler/ets/ConditionalExpressionCallVoidNeg.ets +compiler/ets/abstractNewClassInstanceExpression.ets +compiler/ets/dynamic_instanceof_error.ets +compiler/ets/func-ref-private.ets +compiler/ets/functions_with_ambiguous_rest_parameter.ets +compiler/ets/generic_arrayaslist.ets +compiler/ets/instanceof_dyndecl_dynvalue.ets +compiler/ets/instanceof_dyndecl_jsvalue.ets +compiler/ets/instanceof_dynvalue_dynvalue.ets +compiler/ets/instanceof_dynvalue_jsvalue.ets +compiler/ets/instanceof_etsobject_dynvalue.ets +compiler/ets/instanceof_etsobject_jsvalue.ets +compiler/ets/instanceof_jsvalue_dynvalue.ets +compiler/ets/instanceof_jsvalue_jsvalue.ets +compiler/ets/instanceof_object_dynvalue.ets +compiler/ets/instanceof_object_jsvalue.ets +compiler/ets/instanceof_object_long.ets +parser/ets/dynamic_import_tests/dynamic_iface_decl_bad.ets +parser/ets/import_tests/packages/var-duplication/subpackage_module_1.ets +parser/ets/import_tests/packages/var-duplication/subpackage_module_2.ets +parser/ets/interfaces.ets +parser/ets/lambda-type-inference-overloaded.ets +parser/ets/localTypeAlias.ets +parser/ets/re_export/import_10.ets +parser/ets/re_export/re_export_4.ets +parser/ets/test_type_alias6.ets +parser/ets/type_alias_1.ets +runtime/ets/ClassNewInstance.ets +runtime/ets/GenericsTest.ets +runtime/ets/Object-type-in-binary-logical-expression.ets +runtime/ets/StringFasta.ets +runtime/ets/conditionalExpressionGenericLUB.ets +runtime/ets/funcRefWithRestArguments.ets +runtime/ets/generics_1.ets +runtime/ets/implementsClassPropertyUnionType1.ets +runtime/ets/implementsClassPropertyUnionType2.ets +runtime/ets/lambda_with_receiver/lambda_with_receiver_generics_return_this_rotate.ets +runtime/ets/lambda_with_receiver/lambda_with_receiver_return_this3.ets +runtime/ets/lambda_with_receiver/lambda_with_receiver_trailing_in_class_method_return_this_rotate.ets +runtime/ets/lambda_with_receiver/lambda_with_receiver_trailing_in_function_return_this_rotate.ets +runtime/ets/n_overrideWithNullable.ets +runtime/ets/nullCoalesc.ets +runtime/ets/nullableType.ets +runtime/ets/objectEquality.ets +runtime/ets/optional_field.ets +runtime/ets/override_for_partial_01.ets +runtime/ets/override_for_partial_02.ets +runtime/ets/struct-identifier.ets +runtime/ets/struct-init.ets +runtime/ets/struct-init2.ets +runtime/ets/struct_implements.ets +runtime/ets/top_level_03.ets +runtime/ets/type_param_in_union.ets + +# New failures at #FailKind.ABORT_FAIL +runtime/ets/lambda_with_receiver/lambda_with_receiver_generics_return_this.ets + +# Negative tests that should be ignored +ast/parser/multi_returnstatement_typeerror.ets +ast/parser/ets/spreadexpr_in_newexpr_neg02.ets +ast/parser/ets/multiple_fields.ets +ast/parser/ets/enum18.ets +ast/parser/ets/async_ctor.ets +ast/parser/ets/special_signatures.ets +ast/parser/ets/local-class-access-modifier-private.ets +ast/parser/ets/generic_error.ets +ast/parser/ets/getterOverrideGen_n.ets +ast/parser/ets/unexpected_token_3.ets +ast/parser/ets/unexpected_token_34.ets +ast/parser/ets/partialGenericInterface_n.ets +ast/parser/ets/spreadExpressionNotArrayType.ets +ast/parser/ets/method_modifier_check_6.ets +ast/parser/ets/interfaceMethodNativeModifier.ets +ast/parser/ets/interfaceMethodPrivatePrivate.ets +ast/parser/ets/ambient_indexer_4.ets +ast/parser/ets/genericDefaultParam_4.ets +ast/parser/ets/inheritance-cyclic.ets +ast/parser/ets/lambda-type-inference-bad-arrow.ets +ast/parser/ets/non_constant_expression.ets +ast/parser/ets/function_decl.ets +ast/parser/ets/undefinedNullNotObject.ets +ast/parser/ets/unexpected_token_59.ets +ast/parser/ets/switch_alive_2.ets +ast/parser/ets/recordKeyTypeCheck01.ets +ast/parser/ets/static_func_call_10.ets +ast/parser/ets/local-class-member-access-modifier-private1.ets +ast/parser/ets/unexpected_token_52.ets +ast/parser/ets/cast_expressions7.ets +ast/parser/ets/async_method_bad.ets +ast/parser/ets/recordKeyTypeCheck04.ets +ast/parser/ets/struct_with_annotations.ets +ast/parser/ets/launch_super_ctor.ets +ast/parser/ets/declare_namespace_5.ets +ast/parser/ets/class_keyword.ets +ast/parser/ets/function_implicit_return_type2.ets +ast/parser/ets/nonIntegralIndex.ets +ast/parser/ets/missing_in_for_statement_2.ets +ast/parser/ets/accessor_void.ets +ast/parser/ets/unexpected_token_20.ets +ast/parser/ets/async_lambda_bad.ets +ast/parser/ets/unexpected_token_33.ets +ast/parser/ets/method_modifier_check_7.ets +ast/parser/ets/wrong_context_function_3.ets +ast/parser/ets/getter_native.ets +ast/parser/ets/lambda-type-inference-neg2.ets +ast/parser/ets/ambient_indexer_8.ets +ast/parser/ets/async_function_bad.ets +ast/parser/ets/increment-on-nullish-type-undefined-invalid.ets +ast/parser/ets/circulary_interface_declaration.ets +ast/parser/ets/ambiguous_call_1.ets +ast/parser/ets/function_implicit_return_type7.ets +ast/parser/ets/unexpected_token_7.ets +ast/parser/ets/nonPublicInterfaceProp.ets +ast/parser/ets/struct_keywords2.ets +ast/parser/ets/unexpected_token_30.ets +ast/parser/ets/invalidEnums.ets +ast/parser/ets/InvalidExpressions1.ets +ast/parser/ets/interface_member_initialization.ets +ast/parser/ets/constant_expression_divide_zero.ets +ast/parser/ets/default_parameter1.ets +ast/parser/ets/method_modifier_check_4.ets +ast/parser/ets/typeparameter_constraint_circular-neg_0.ets +ast/parser/ets/class_interface_enum_only_top_level_5.ets +ast/parser/ets/namespace_badtoken03.ets +ast/parser/ets/enum24.ets +ast/parser/ets/for_of_02.ets +ast/parser/ets/method_modifier_check_3.ets +ast/parser/ets/unexpected_token_31.ets +ast/parser/ets/array_2.ets +ast/parser/ets/visible_signatures_1.ets +ast/parser/multierror_switchcases.ets +ast/parser/ets/method_modifier_check_9.ets +ast/parser/ets/TypeInferFunc.ets +ast/parser/ets/non_proper_iterator_method.ets +ast/parser/ets/thisInConstructor.ets +ast/parser/ets/keyof_type_parameter.ets +ast/parser/ets/local-interface-access-modifier-public.ets +ast/parser/ets/rest_parameter_03.ets +ast/parser/ets/unexpected_token_50.ets +ast/parser/ets/assignment_non-functional_variable_to_functional_type.ets +ast/parser/ets/access_modifier_4.ets +ast/parser/ets/class-static-field-redeclaration.ets +ast/parser/ets/method_modifier_check_5.ets +ast/parser/ets/enum23.ets +ast/parser/ets/arrow_1.ets +ast/parser/ets/readonlyGetterSetterReassignment2.ets +ast/parser/ets/StructTest3.ets +ast/parser/ets/trailing_comma_1.ets +ast/parser/ets/invalid_access_static.ets +ast/parser/ets/interfaces2.ets +ast/parser/ets/generics_type_param_no_typeargs_no_default_2.ets +ast/parser/ets/namespace_badtoken04.ets +ast/parser/ets/InvalidStatements1.ets +ast/parser/ets/wrong-union-array-assignment.ets +ast/parser/ets/optional_field_interfaceUnionNotCompatible.ets +ast/parser/ets/struct_invalid_nested2.ets +ast/parser/ets/distinguishable-decl-1.ets +ast/parser/ets/class_interface_enum_only_top_level_2.ets +ast/parser/ets/for_of_loop_variable.ets +ast/parser/ets/single_statement_2.ets +ast/parser/ets/switch_readonly_member_different_enum_2.ets +ast/parser/ets/unexpected_token_44.ets +ast/parser/ets/tryBlockOnly.ets +ast/parser/ets/test_type_alias2.ets +ast/parser/ets/switch_readonly_member_enum.ets +ast/parser/ets/nested_function_in_method.ets +ast/parser/ets/main_entry_point_4.ets +ast/parser/ets/enum12.ets +ast/parser/ets/n_returnNullFromMethod.ets +ast/parser/ets/enum28.ets +ast/parser/ets/unexpected_token_17.ets +ast/parser/ets/try_catch_alive_5.ets +ast/parser/ets/SmartCast_2.ets +ast/parser/ets/user_defined_20.ets +ast/parser/ets/enum13.ets +ast/parser/ets/cycle_constructor.ets +ast/parser/ets/unexpected_token_25.ets +ast/parser/ets/test_type_alias4.ets +ast/parser/ets/missing_in_for_statement_1.ets +ast/parser/ets/multi_typeerror_function_implicit_return_value.ets +ast/parser/ets/anonymous_class.ets +ast/parser/ets/ambient_indexer_7.ets +ast/parser/ets/for_of_03.ets +ast/parser/ets/rest_parameter_04.ets +ast/parser/ets/invalid_access_static2.ets +ast/parser/ets/class_property_access.ets +ast/parser/ets/tuple_type_3_neg.ets +ast/parser/ets/readonly_reference_CTE_err_elimilate.ets +ast/parser/ets/setter_native.ets +ast/parser/ets/missing_implementation_1.ets +ast/parser/ets/user_defined_14.ets +ast/parser/ets/static_func_call_9.ets +ast/parser/ets/enum2.ets +ast/parser/ets/method_modifier_check_1.ets +ast/parser/ets/dynmicImportUnimplemented.ets +ast/parser/ets/try_catch_alive_8.ets +ast/parser/ets/partialGenericInterface_2.ets +ast/parser/ets/lambda_infer_type_neg_2.ets +ast/parser/ets/local_interface_already_class.ets +ast/parser/ets/calls.ets +ast/parser/ets/this_type_lambda_declaration_return_invalid.ets +ast/parser/ets/static_field_2.ets +ast/parser/ets/invalidEnums1.ets +ast/parser/ets/static_func_call_2.ets +ast/parser/ets/record_object_value.ets +ast/parser/ets/operator_logical_nullish_equal.ets +ast/parser/ets/user_defined_24.ets +ast/parser/ets/unexpected_token_41.ets +ast/parser/ets/typeinference_function_generic.ets +ast/parser/ets/n_assignNullableFromFunctionToNonNullable.ets +ast/parser/ets/local-interface-member-access-modifier-private2.ets +ast/parser/ets/keyof_annotation.ets +ast/parser/ets/unexpected_token_37.ets +ast/parser/ets/cast_expressions8.ets +ast/parser/ets/unexpected_token_35.ets +ast/parser/ets/static_func_call_1.ets +ast/parser/ets/class_interface_enum_only_top_level_1.ets +ast/parser/ets/this_type_class_static_method_return_invalid.ets +ast/parser/ets/unexpected_token_36.ets +ast/parser/ets/struct_export1.ets +ast/parser/ets/local_interface_already_variable..ets +ast/parser/ets/enum_default_negative.ets +ast/parser/ets/struct_in_class.ets +ast/parser/ets/switch_enum.ets +ast/parser/ets/InterfaceWithDefaultFunction2.ets +ast/parser/ets/enum8.ets +ast/parser/ets/struct_invalid_abstract.ets +ast/parser/ets/partialPrimitiveConversion_n.ets +ast/parser/ets/superInConstructor3.ets +ast/parser/ets/primitive_type_method_2.ets +ast/parser/ets/method_modifier_check_11.ets +ast/parser/ets/this_type_lambda_declaration_return_in_class_invalid.ets +ast/parser/ets/interfaceAbstract.ets +ast/parser/ets/non-ambient_call_signature.ets +ast/parser/ets/await_promise_bad.ets +ast/parser/ets/class_interface_enum_only_top_level_3.ets +ast/parser/ets/forOfType.ets +ast/parser/ets/SmartCast_1.ets +ast/parser/ets/lambda-type-inference-overloaded-1.ets +ast/parser/ets/superInConstructor1.ets +ast/parser/ets/assign_bad.ets +ast/parser/ets/topLevelStaticClass.ets +ast/parser/ets/InvalidParserImpl.ets +ast/parser/ets/privateSuperConstructorCall.ets +ast/parser/ets/declare_class_neg.ets +ast/parser/ets/unexpected_token_10.ets +ast/parser/ets/method_modifier_check_16.ets +ast/parser/ets/keyof_applied_to_other.ets +ast/parser/ets/ambient_indexer_9.ets +ast/parser/ets/enum15.ets +ast/parser/ets/async_abstract_bad.ets +ast/parser/ets/typeparameter_constraint_circular-neg_1.ets +ast/parser/ets/user_defined_17.ets +ast/parser/ets/class_composite_1.ets +ast/parser/ets/unclosed_loop.ets +ast/parser/ets/static_field_3.ets +ast/parser/ets/missing_implementation_2.ets +ast/parser/ets/object_literal_withfunc.ets +ast/parser/ets/default_parameters_multi_error.ets +ast/parser/ets/unexpected_token_13.ets +ast/parser/ets/functionTypeRethrows.ets +ast/parser/ets/type_param_contraint_override.ets +ast/parser/ets/namespace_badtoken02.ets +ast/parser/ets/return_null_and_type_not_match.ets +ast/parser/ets/union_static_method.ets +ast/parser/ets/unexpected_token_28.ets +ast/parser/ets/overrideFuncWithGetter_n.ets +ast/parser/ets/operator_logical_or_equal.ets +ast/parser/ets/type_references.ets +ast/parser/ets/fields.ets +ast/parser/ets/generic_defined_before_use_neg_5.ets +ast/parser/ets/constructor_functionbody_nullptr.ets +ast/parser/ets/switch_enum_case_duplicate.ets +ast/parser/ets/lambda-arrow-after-braces.ets +ast/parser/ets/variable_throw_function_2.ets +ast/parser/ets/interfaceMethodPrivateStaticModifier.ets +ast/parser/ets/user_defined_7.ets +ast/parser/ets/optional_chaining_invalid_property.ets +ast/parser/ets/string_literal_const_cast.ets +ast/parser/ets/InvalidClasses.ets +ast/parser/ets/interfaceExtendInterfaces1.ets +ast/parser/ets/method_modifier_check_17.ets +ast/parser/ets/operator_logical_and_euqal.ets +ast/parser/ets/ambient_indexer_5.ets +ast/parser/ets/declare_class_bad_2.ets +ast/parser/ets/wrong_context_function_2.ets +ast/parser/ets/enum22.ets +ast/parser/ets/test_type_alias1.ets +ast/parser/ets/unexpected_token_21.ets +ast/parser/ets/enum17.ets +ast/parser/ets/superStaticCall.ets +ast/parser/ets/unexpected_token_8.ets +ast/parser/ets/reserved_type.ets +ast/parser/ets/SmartCast_3.ets +ast/parser/ets/types_decls.ets +ast/parser/ets/partialInterface_n1.ets +ast/parser/ets/keyof_never.ets +ast/parser/ets/empty_launch.ets +ast/parser/ets/increment-on-nullish-type-undefined.ets +ast/parser/ets/generics_type_param_no_typeargs_no_default.ets +ast/parser/ets/lambda_infer_type_neg_1.ets +ast/parser/ets/readonlyGetterSetterReassignment1.ets +ast/parser/ets/interface_instantiation.ets +ast/parser/ets/Dollar_doller_invalid2.ets +ast/parser/ets/enum3.ets +ast/parser/ets/static_field_5.ets +ast/parser/ets/unexpected_token_5.ets +ast/parser/ets/new_object_undefined.ets +ast/parser/ets/unexpected_token_40.ets +ast/parser/ets/string_literal_01.ets +ast/parser/ets/wrong_context_function_4.ets +ast/parser/ets/struct_extends_class.ets +ast/parser/ets/keyof_union.ets +ast/parser/ets/for_await_of_loop.ets +ast/parser/ets/keyof_private_and_protected.ets +ast/parser/ets/local-class-member-access-modifier-protected1.ets +ast/parser/ets/MultipleClassErrors.ets +ast/parser/ets/unexpected_token_15.ets +ast/parser/ets/arrAsArray.ets +ast/parser/ets/ambient_indexer_2.ets +ast/parser/ets/method_modifier_check_10.ets +ast/parser/ets/switch_num_compare_char_duplicate.ets +ast/parser/ets/static_func_call_8.ets +ast/parser/ets/InvalidLexer.ets +ast/parser/ets/local_class_already_class.ets +ast/parser/ets/illegal_break_statement.ets +ast/parser/ets/user_defined_13.ets +ast/parser/ets/unexpected_token_22.ets +ast/parser/ets/SmartCast_4.ets +ast/parser/ets/static_func_call_3.ets +ast/parser/ets/generics_1.ets +ast/parser/ets/unexpected_token_56.ets +ast/parser/ets/index_not_support_such_type.ets +ast/parser/ets/unexpected_token_45.ets +ast/parser/ets/unexpected_token_26.ets +ast/parser/ets/this_type_function_return_invalid.ets +ast/parser/ets/InvalidStatements2.ets +ast/parser/ets/user_defined_18.ets +ast/parser/ets/array_new_failed.ets +ast/parser/ets/trailing_comma_2.ets +ast/parser/ets/this_type_lambda_declaration_parameter_invalid.ets +ast/parser/ets/static_field_1.ets +ast/parser/ets/struct_with_component_annotation.ets +ast/parser/ets/InferTypeParamFromParam2.ets +ast/parser/ets/interface.ets +ast/parser/ets/namespace_badtoken01.ets +ast/parser/ets/recordKeyTypeCheck02.ets +ast/parser/ets/user_defined_15.ets +ast/parser/ets/ambient_iterable_declaration.ets +ast/parser/ets/lambda_omit_parentheses_parameter_neg_1.ets +ast/parser/ets/object_literal_dup_keys_0.ets +ast/parser/ets/global_const_vars1.ets +ast/parser/ets/partialType_4.ets +ast/parser/ets/function_implicit_return_type4.ets +ast/parser/ets/lambda_optional_param_3.ets +ast/parser/ets/type_variance3.ets +ast/parser/ets/partial_interface.ets +ast/parser/ets/wrong_context_class_3.ets +ast/parser/ets/try_catch_alive_2.ets +ast/parser/ets/enum14.ets +ast/parser/ets/UnexpectedToken.ets +ast/parser/ets/unexpected_token_4.ets +ast/parser/ets/setter_with_non_void.ets +ast/parser/ets/local_class_already_interface.ets +ast/parser/ets/returntype_override_object.ets +ast/parser/ets/class_optional_property.ets +ast/parser/ets/unexpected_token_60.ets +ast/parser/ets/illegal_line_after_throw.ets +ast/parser/ets/enum5.ets +ast/parser/ets/new_object_2.ets +ast/parser/ets/unexpected_token_51.ets +ast/parser/ets/constructors.ets +ast/parser/ets/static_func_call_7.ets +ast/parser/ets/constructor_with_return_3.ets +ast/parser/ets/unexpected_token_18.ets +ast/parser/ets/interfaceMethodReadonlyModifier.ets +ast/parser/ets/switch_enum2.ets +ast/parser/ets/declare_class_bad_5.ets +ast/parser/ets/async_func_return_type_bad.ets +ast/parser/ets/method_modifier_check_2.ets +ast/parser/ets/main_entry_point_2.ets +ast/parser/ets/ambiguous_call_3.ets +ast/parser/ets/method_modifier_check_13.ets +ast/parser/ets/differentTypeCompare.ets +ast/parser/ets/Interface_variable_identifier.ets +ast/parser/ets/interface_with_different_type.ets +ast/parser/ets/enum16.ets +ast/parser/ets/function_implicit_return_type3.ets +ast/parser/ets/class_as_object_1.ets +ast/parser/ets/tuple_trailing_comma.ets +ast/parser/ets/lambda_omit_parentheses_type_alias_neg_1.ets +ast/parser/ets/unexpected_token_2.ets +ast/parser/ets/getter_setter_modifier_diff.ets +ast/parser/ets/forOfCustomIterator1.ets +ast/parser/ets/property-access-method-2.ets +ast/parser/ets/switch_readonly_member_number_duplicate.ets +ast/parser/ets/declare_class_bad_3.ets +ast/parser/ets/launch_unresolved.ets +ast/parser/ets/call_expression_for_non_functional_type.ets +ast/parser/ets/keyof_array_tuple.ets +ast/parser/ets/user_defined_23.ets +ast/parser/ets/generic_defined_before_use_neg_4.ets +ast/parser/ets/this_type_lambda_declaration_parameter_in_class_invalid.ets +ast/parser/ets/double_parenthesis_invocation_supposed_to_fail.ets +ast/parser/ets/functionTypeWithDefaultParam1.ets +ast/parser/ets/cast_expressions9.ets +ast/parser/ets/assignment_non-functional_variable_to_functional_type_1.ets +ast/parser/ets/interface_private_function_1.ets +ast/parser/ets/unexpected_token_39.ets +ast/parser/ets/cast_expressions2.ets +ast/parser/ets/unexpected_token_58.ets +ast/parser/ets/unexpected_token_11.ets +ast/parser/ets/constructor_with_return_1.ets +ast/parser/ets/lambda-type-inference-neg.ets +ast/parser/ets/genericDefaultParam_2.ets +ast/parser/ets/MultipleFunctionErrors.ets +ast/parser/ets/unexpected_token_49.ets +ast/parser/ets/unexpected_token_43.ets +ast/parser/ets/static_func_call_6.ets +ast/parser/ets/iterator_override_next.ets +ast/parser/ets/user_defined_10.ets +ast/parser/ets/tuple_type_4_neg.ets +ast/parser/ets/unexpected_token_24.ets +ast/parser/ets/wrong_context_class_4.ets +ast/parser/ets/property-access-method-1.ets +ast/parser/ets/record_dup_key_02.ets +ast/parser/ets/switch_readonly_member_different_enum.ets +ast/parser/ets/user_defined_25.ets +ast/parser/ets/partialInterface_n0.ets +ast/parser/ets/unexpected_token_9.ets +ast/parser/ets/static_field_4.ets +ast/parser/ets/local-interface-member-access-modifier-private1.ets +ast/parser/ets/class-instance-field-redeclaration.ets +ast/parser/ets/enum11.ets +ast/parser/ets/user_defined_11.ets +ast/parser/ets/InvalidTyped.ets +ast/parser/ets/DeclareAsyncFunction.ets +ast/parser/ets/unexpected_token_1.ets +ast/parser/ets/InvalidStatements3.ets +ast/parser/ets/enum20.ets +ast/parser/ets/struct_in_interface.ets +ast/parser/ets/this_type_function_parameter_invalid.ets +ast/parser/ets/declare_func_bad.ets +ast/parser/ets/assignment_with_wrong_type.ets +ast/parser/ets/functionTypeWithDefaultParam2.ets +ast/parser/ets/method_modifier_check_12.ets +ast/parser/ets/generics_type_param_constraint_8.ets +ast/parser/ets/local-class-member-access-modifier-public1.ets +ast/parser/ets/enum7.ets +ast/parser/ets/InterfacePrivateMethod.ets +ast/parser/ets/switch_const_int_compare_char_duplicate.ets +ast/parser/ets/Dollar_doller_invalid3.ets +ast/parser/ets/try_catch_alive_3.ets +ast/parser/ets/local_class_already_variable.ets +ast/parser/ets/static_function_override_4.ets +ast/parser/ets/await_argument_null.ets +ast/parser/ets/native_constructor_non_empty_body.ets +ast/parser/ets/primitive_type_method_1.ets +ast/parser/ets/Multiline_string_escape_char.ets +ast/parser/ets/missing_in_if_statement_1.ets +ast/parser/ets/user_defined_9.ets +ast/parser/ets/unexpected_token_12.ets +ast/parser/ets/methods.ets +ast/parser/ets/nested_function.ets +ast/parser/ets/returntype_override_primitive.ets +ast/parser/ets/lambda_optional_param_2.ets +ast/parser/ets/ambient_indexer_3.ets +ast/parser/ets/required_multiple_fields.ets +ast/parser/ets/user_defined_5.ets +ast/parser/ets/object_literal_dup_keys_2.ets +ast/parser/ets/main_entry_point_3.ets +ast/parser/ets/local_interface_already_interface.ets +ast/parser/ets/generic_defined_before_use_neg_2.ets +ast/parser/ets/type_decution_unnecessary_boxing.ets +ast/parser/ets/ets_never_type_without_affect_other.ets +ast/parser/ets/return_type_non_match.ets +ast/parser/ets/nested_function_1.ets +ast/parser/ets/interfaces3.ets +ast/parser/ets/tuple_type_2_neg.ets +ast/parser/ets/interfaceExtendInterfaces2.ets +ast/parser/ets/this_type_lambda_definition_parameter_invalid.ets +ast/parser/ets/abstract_class_modidier.ets +ast/parser/ets/unexpected_token_47.ets +ast/parser/ets/wrongReadonlyUtilityType.ets +ast/parser/ets/assign-func-iface.ets +ast/parser/ets/labeled.ets +ast/parser/ets/array_missing_element.ets +ast/parser/ets/constFloatInSwitch.ets +ast/parser/ets/getter_setter_access_modifiers_2.ets +ast/parser/ets/global_scope_string.ets +ast/parser/ets/static_func_call_4.ets +ast/parser/ets/unexpected_token_23.ets +ast/parser/ets/null_invalid.ets +ast/parser/ets/static_func_call_5.ets +ast/parser/ets/keyof_predefined_type.ets +ast/parser/ets/loops.ets +ast/parser/ets/generic_defined_before_use_neg_3.ets +ast/parser/ets/user_defined_21.ets +ast/parser/ets/ambiguous_call_2.ets +ast/parser/ets/generic_defined_before_use_neg_1.ets +ast/parser/ets/local_class_in_classfunction.ets +ast/parser/ets/unexpected_token_42.ets +ast/parser/ets/local-class-member-access-modifier-private2.ets +ast/parser/ets/required_multiple_fields_2.ets +ast/parser/ets/accessor_call.ets +ast/parser/ets/this_type_class_method_parameter_invalid.ets +ast/parser/ets/unexpected_token_61.ets +ast/parser/ets/property-access-field-1.ets +ast/parser/ets/switch_readonly_member_enum_duplicate.ets +ast/parser/ets/superInConstructor2.ets +ast/parser/ets/unexpected_token_53.ets +ast/parser/ets/invalidTypes.ets +ast/parser/ets/swtich_not_const.ets +ast/parser/ets/keyof_smartcast.ets +ast/parser/ets/struct_extends_struct.ets +ast/parser/ets/try_catch_alive_7.ets +ast/parser/ets/declare_class_bad_4.ets +ast/parser/ets/this_type_class_static_method_parameter_invalid.ets +ast/parser/ets/array_type.ets +ast/parser/ets/global_const_vars4.ets +ast/parser/ets/AllowSequence.ets +ast/parser/ets/declare_class_bad_1.ets +ast/parser/ets/InterfaceWithDefaultFunction1.ets +ast/parser/ets/partial_not_reference_type.ets +ast/parser/ets/assert_with_not_boolean_type_1.ets +ast/parser/ets/test_type_alias10.ets +ast/parser/ets/windows_multiline_comments.ets +ast/parser/ets/override_method.ets +ast/parser/ets/wrong_context_class_1.ets +ast/parser/ets/new_object_1.ets +ast/parser/ets/unexpected_token_6.ets +ast/parser/ets/native_function_without_return_type.ets +ast/parser/ets/spreadexpr_in_newexpr_neg01.ets +ast/parser/ets/unexpected_token_38.ets +ast/parser/ets/single_statement_1.ets +ast/parser/ets/StructTest2.ets +ast/parser/ets/struct_keywords1.ets +ast/parser/ets/this_type_class_field_invalid.ets +ast/parser/ets/n_nullableTypeMissingNull.ets +ast/parser/ets/this_type_lambda_definition_parameter_in_class_invalid.ets +ast/parser/ets/non_proper_index_method.ets +ast/parser/ets/type_argument_conversion.ets +ast/parser/ets/local-interface-access-modifier-private.ets +ast/parser/ets/unexpected_token_57.ets +ast/parser/ets/staticFunctionCallOfObject.ets +ast/parser/ets/functionTypeParam_neg2.ets +ast/parser/ets/instanceof_with_not_object_type.ets +ast/parser/ets/InvalidExpressions.ets +ast/parser/ets/n_returnNullFromFunction.ets +ast/parser/ets/local-interface-access-modifier-protected.ets +ast/parser/ets/Dollar_doller_invalid1.ets +ast/parser/ets/local-class-member-access-modifier-protected2.ets +ast/parser/ets/generic_defined_before_use_neg_6.ets +ast/parser/ets/default_parameter3.ets +ast/parser/ets/try_catch_alive_9.ets +ast/parser/ets/struct_keywords3.ets +ast/parser/ets/test_type_alias3.ets +ast/parser/ets/namespace_bad_token.ets +ast/parser/ets/optional_field_variable_forof.ets +ast/parser/ets/StructTest1.ets +ast/parser/ets/n_arrayHoldingNullValue.ets +ast/parser/ets/local-class-access-modifier-protected.ets +ast/parser/ets/unexpected_token_32.ets +ast/parser/ets/assert_with_not_boolean_type_2.ets +ast/parser/ets/switch_enum_string_case_duplicate.ets +ast/parser/ets/instantied_abstract_class_with_array_creation_expression.ets +ast/parser/ets/unexpected_token_54.ets +ast/parser/ets/local-interface-member-access-modifier-protected1.ets +ast/parser/ets/array_union_type_not_contains_nullish_type.ets +ast/parser/ets/illegal_union_member_exp.ets +ast/parser/ets/struct_in_struct.ets +ast/parser/ets/this_type_lambda_definition_return_invalid.ets +ast/parser/ets/unexpected_token_19.ets +ast/parser/ets/unexpected_token_16.ets +ast/parser/ets/labeledBlockStatement.ets +ast/parser/ets/enum6.ets +ast/parser/ets/struct_extends_interface.ets +ast/parser/ets/instantied_interface_with_array_creation_expression.ets +ast/parser/ets/lexer002.ets +ast/parser/ets/function_implicit_return_type.ets +ast/parser/ets/lexer001.ets +ast/parser/ets/spreadArrayInTuple.ets +ast/parser/ets/enum27.ets +ast/parser/ets/recordKeyTypeCheck03.ets +ast/parser/ets/await_object_bad.ets +ast/parser/ets/unexpected_token_29.ets +ast/parser/ets/null-coalesc-negative.ets +ast/parser/ets/recordIndexing.ets +ast/parser/ets/record_dup_key_01.ets +ast/parser/ets/try_catch_alive_6.ets +ast/parser/ets/global_scope_boolean.ets +ast/parser/ets/interfaceMethodStaticModifier.ets +ast/parser/ets/wrong_context_class_2.ets +ast/parser/ets/unexpected_token_48.ets +ast/parser/ets/default_parameter2.ets +ast/parser/ets/lambdaWithWrongOptionalParameter.ets +ast/parser/ets/tupleIndexWithLargeInt.ets +ast/parser/ets/struct_invalid_local.ets +ast/parser/ets/enum26.ets +ast/parser/ets/forOfCustomIterator2.ets +ast/parser/ets/launch_non_callable.ets +ast/parser/ets/missing_in_if_statement_2.ets +ast/parser/ets/unexpected_token_14.ets +ast/parser/ets/lambda_omit_parentheses_parameter_neg_3.ets +ast/parser/ets/for_of_04.ets +ast/parser/ets/cast_expressions10.ets +ast/parser/ets/named_types.ets +ast/parser/ets/native_constructor_empty_body.ets +ast/parser/ets/user_defined_19.ets +ast/parser/ets/accessor_with_this_param.ets +ast/parser/ets/constructor_super_call2.ets +ast/parser/ets/constructor_default_super.ets +ast/parser/ets/global_const_vars2.ets +ast/parser/ets/user_defined_8.ets +ast/parser/ets/main_entry_point_5.ets +ast/parser/ets/record_init_check.ets +ast/parser/ets/property-access-field-2.ets +ast/parser/ets/functionTypeParam_neg.ets +ast/parser/ets/interface-override-function.ets +ast/parser/ets/FunctionalTypeAsArrayElement.ets +ast/parser/ets/this_type_lambda_definition_return_in_class_invalid.ets +ast/parser/ets/user_defined_12.ets +ast/parser/ets/unexpected_token_27.ets +ast/parser/ets/localTypeAlias_n.ets +ast/parser/ets/access_modifier_1.ets +ast/parser/ets/method_modifier_check_15.ets +ast/parser/ets/user_defined_16.ets +ast/parser/ets/enum_default_invalid_value_type.ets +ast/parser/ets/struct_implements_interface.ets +ast/parser/ets/wrong_context_function_1.ets +ast/parser/ets/illegal_continue_statement.ets +ast/compiler/ets/union_string_literals_5.ets +ast/compiler/ets/annotation_tests/annotation_for_type_parameter01.ets +ast/compiler/ets/readonlyType_4.ets +ast/compiler/ets/annotation_tests/annotationUsage_excessive_param02.ets +ast/compiler/ets/ambient_indexer_2.ets +ast/compiler/ets/annotation_tests/annotation_for_types_in_interface.ets +ast/compiler/ets/annotation_tests/annotationUsage_missing_arguements01.ets +ast/compiler/ets/method-resolution-class-and-interface-in-signatures_4.ets +ast/compiler/ets/annotation_tests/annotation_as_negative_case.ets +ast/compiler/ets/mostSpecificMethod1.ets +ast/compiler/ets/annotation_tests/annotationUsage_duplicate_on_class.ets +ast/compiler/ets/function_subtyping_3.ets +ast/compiler/ets/annotation_tests/annotationUsage_bad_param10.ets +ast/compiler/ets/readonlyType_5.ets +ast/compiler/ets/annotation_tests/annotation_for_array_type02.ets +ast/compiler/ets/annotation_tests/annotationUsage_missing_param_for_type_alias.ets +ast/compiler/ets/objectLiteralBadKey.ets +ast/compiler/ets/annotation_tests/annotation_for_types_in_annotation.ets +ast/compiler/ets/lambda_type_mismatch.ets +ast/compiler/ets/annotation_tests/annotationUsage_excessive_param_for_classproperty.ets +ast/compiler/ets/cast_UnionType_to_PrimitiveType3.ets +ast/compiler/ets/annotation_tests/annotation_for_type_parameter02.ets +ast/compiler/ets/readonlyType_3.ets +ast/compiler/ets/annotation_tests/annotationUsage_missing_param_for_classproperty.ets +ast/compiler/ets/etsObjectToString0.ets +ast/compiler/ets/annotation_tests/annotation_for_tuple_type.ets +ast/compiler/ets/void_as_value_neg_3.ets +ast/compiler/ets/annotation_tests/annotation_for_boxing_type.ets +ast/compiler/ets/nullable_type_in_stringconcat_func.ets +ast/compiler/ets/annotation_tests/annotationUsage_duplicate_on_function.ets +ast/compiler/ets/annotation_tests/annotationUsage_missing_param_for_interface.ets +ast/compiler/ets/tuple_types_1_neg.ets +ast/compiler/ets/annotation_tests/ambient_annotations_bad_type03.ets +ast/compiler/ets/invalidPrivateAccess1.ets +ast/compiler/ets/annotation_tests/annotation_for_types_in_variance.ets +ast/compiler/ets/identifierReference11.ets +ast/compiler/ets/annotation_tests/annotationUsage_duplicate_for_interfacemethod.ets +ast/compiler/ets/readonlyField_2.ets +ast/compiler/ets/annotation_tests/annotation_for_array_type01.ets +ast/compiler/ets/recursive_interface_neg_1.ets +ast/compiler/ets/annotation_tests/annotationDecl_bad_type.ets +ast/compiler/ets/ambient_namesapce07.ets +ast/compiler/ets/annotation_tests/annotation_for_types_in_class.ets +ast/compiler/ets/typeOfString.ets +ast/compiler/ets/annotation_tests/annotationUsage_as_type04.ets +ast/compiler/ets/getterNoReturn1.ets +ast/compiler/ets/annotation_tests/annotation_for_union_type.ets +ast/compiler/ets/switch_negative_5.ets +ast/compiler/ets/annotation_tests/annotationUsage_duplicate_for_classproperty.ets +ast/compiler/ets/annotation_tests/annotationUsage_conflict_for_namespace02.ets +ast/compiler/ets/invalidIndirectInheritanceFromInterface.ets +ast/compiler/ets/annotation_tests/annotationUsage_as_type14.ets +ast/compiler/ets/setter_func_no_return_type.ets +ast/compiler/ets/annotation_tests/annotationUsage_as_type10.ets +ast/compiler/ets/genericObjectLiteral_neg_3.ets +ast/compiler/ets/annotation_tests/annotation_for_readonly_type.ets +ast/compiler/ets/variable_declaretion_neg_1.ets +ast/compiler/ets/annotation_tests/annotationUsage_duplicate_from_import.ets +ast/compiler/ets/requiredType_8_neg.ets +ast/compiler/ets/annotation_tests/annotation_for_types_in_function.ets +ast/compiler/ets/objectLiteral_abstract_class_2.ets +ast/compiler/ets/annotation_tests/ambient_annotations_bad_type01.ets +ast/compiler/ets/generics_implicit_lambda2.ets +ast/compiler/ets/annotation_tests/annotationUsage_as_type12.ets +ast/compiler/ets/void_as_return_type_neg_1.ets +ast/compiler/ets/annotation_tests/annotationUsage_excessive_param_for_variable_decl.ets +ast/compiler/ets/annotation_tests/annotationUsage_excessive_param_for_function_param.ets +ast/compiler/ets/union_types_2.ets +ast/compiler/ets/annotation_tests/annotationUsage_as_type09.ets +ast/compiler/ets/annotation_tests/annotationUsage_duplicate_on_extension_lambda.ets +ast/compiler/ets/namespace_export_invalid02.ets +ast/compiler/ets/annotation_tests/annotationUsage_unordered_params.ets +ast/compiler/ets/readonlyType_1.ets +ast/compiler/ets/annotation_tests/annotationUsage_bad_param08.ets +ast/compiler/ets/export_and_export_type_class.ets +ast/compiler/ets/annotation_tests/annotationUsage_excessive_param_for_interface.ets +ast/compiler/ets/trailing_lambda.ets +ast/compiler/ets/annotation_tests/annotationUsage_missing_AT_for_variable_decl.ets +ast/compiler/ets/identifierReference9.ets +ast/compiler/ets/annotation_tests/annotation_for_other_type.ets +ast/compiler/ets/assert_bad.ets +ast/compiler/ets/annotation_tests/annotationUsage_missing_param_for_variable_decl.ets +ast/compiler/ets/null_coalescing_generic_1_neg.ets +ast/compiler/ets/annotation_tests/annotation_for_types_in_expression.ets +ast/compiler/ets/overload_equivalent_generics.ets +ast/compiler/ets/annotation_tests/annotationUsage_missing_arguements02.ets +ast/compiler/ets/variance_typeparam_class.ets +ast/compiler/ets/annotation_tests/annotation_for_function_type.ets +ast/compiler/ets/override11.ets +ast/compiler/ets/annotation_tests/annotationUsage_bad_param09.ets +ast/compiler/ets/forbidden_inherit_class_3.ets +ast/compiler/ets/annotation_tests/annotationUsage_as_type01.ets +ast/compiler/ets/ObjectLiteral_neg_2.ets +ast/compiler/ets/recursive_method_neg_2.ets +ast/compiler/ets/nullable_type_in_arithmeticmult_func_w_undefined.ets +ast/compiler/ets/union_string_literals_4.ets +ast/compiler/ets/objectLiteral_abstract_class.ets +ast/compiler/ets/etsObjectToString3.ets +ast/compiler/ets/same_assembly_overload/overload_signature_neg_2.ets +ast/compiler/ets/enum-to-int-conversion.ets +ast/compiler/ets/expression/this_expression/undefined_class_for_this_1.ets +ast/compiler/ets/generic_function_call_2.ets +ast/compiler/ets/expression/this_expression/undefined_class_for_this_2.ets +ast/compiler/ets/cast_NonNullishType_to_PrimitiveType2.ets +ast/compiler/ets/same_assembly_overload/identical_signature.ets +ast/compiler/ets/cast_TypeParameter_to_PrimitiveType3.ets +ast/compiler/ets/extension_accessor_tests/setterAsFunctionCall.ets +ast/compiler/ets/objectLiteralInterface3.ets +ast/compiler/ets/extension_accessor_tests/extensionAccessorNameDuplicatedWithInterfaceInstanceField.ets +ast/compiler/ets/variance_typeparam_super.ets +ast/compiler/ets/extension_accessor_tests/extensionGetterInWrongUsage.ets +ast/compiler/ets/recursive_method_neg_1.ets +ast/compiler/ets/same_assembly_overload/overload_signature_neg_1.ets +ast/compiler/ets/thisReferenceFromStaticContext.ets +ast/compiler/ets/extension_accessor_tests/extensionAccessorNameDuplicatedWithInstanceField.ets +ast/compiler/ets/ambient_namesapce04.ets +ast/compiler/ets/extension_accessor_tests/getterAsMethodCall.ets +ast/compiler/ets/async_with_non_generic_return_type.ets +ast/compiler/ets/extension_accessor_tests/extensionAccessorParams.ets +ast/compiler/ets/nullable_type_in_arithmeticplus_func.ets +ast/compiler/ets/extension_accessor_tests/extensionAccessorNameDuplicatedWithExtensionFunction.ets +ast/compiler/ets/void_as_return_type_neg_2.ets +ast/compiler/ets/extension_accessor_tests/setterAsMethodCall.ets +ast/compiler/ets/FunctionType8.ets +ast/compiler/ets/extension_accessor_tests/extensionAccessorNameDuplicatedWithSuperMethod2.ets +ast/compiler/ets/invalidMemberExpressionFromStaticContext4.ets +ast/compiler/ets/implicit_package_import/scopes_multi_error.ets +ast/compiler/ets/recursive_union_neg_2.ets +ast/compiler/ets/implicit_package_import/package_test_9/package_module_with_syntax_error.ets +ast/compiler/ets/generic_class_without_type_arg_1.ets +ast/compiler/ets/implicit_package_import/package_test_9/package_module.ets +ast/compiler/ets/lambdaExpressionWithoutBlockStatementDifferentTypeInfunction.ets +ast/compiler/ets/implicit_package_import/package_test_9/package_with_both_errors.ets +ast/compiler/ets/validate_signatures_throw_type_error.ets +ast/compiler/ets/implicit_package_import/package_test_9/package_module_with_semantic_error.ets +ast/compiler/ets/unionCommonMember_neg.ets +ast/compiler/ets/extension_accessor_tests/extensionAccessorMissingReceiver.ets +ast/compiler/ets/extension_accessor_tests/extensionAccessorNameDuplicatedWithSuperInstanceField.ets +ast/compiler/ets/Non-static-private-method-used-as-val-neg.ets +ast/compiler/ets/extension_accessor_tests/extensionAccessorNameDuplicatedWithMethod1.ets +ast/compiler/ets/tuple_types_11_neg.ets +ast/compiler/ets/extension_accessor_tests/extensionSetCantReturnValue.ets +ast/compiler/ets/conversion_Double-to-Int_w_try_stmt_typerror.ets +ast/compiler/ets/extension_accessor_tests/extensionAccessorNameDuplicatedWithFunction.ets +ast/compiler/ets/invalidMemberExpressionFromStaticContext3.ets +ast/compiler/ets/extension_accessor_tests/extensionAccessorNameDuplicatedWithMethod2.ets +ast/compiler/ets/partialType_1_neg.ets +ast/compiler/ets/extension_accessor_tests/extensionGetMustReturnValue.ets +ast/compiler/ets/extension_accessor_tests/extensionAccessorNameDuplicatedWithSuperMethod1.ets +ast/compiler/ets/resolve_func_name_union_type_1.ets +ast/compiler/ets/extension_accessor_tests/getterAsFunctionCall.ets +ast/compiler/ets/implicit_package_import/package_test_7/package_module_1_neg.ets +ast/compiler/ets/invalidInheritance2.ets +ast/compiler/ets/implicit_package_import/package_test_7/package_module_2_neg.ets +ast/compiler/ets/variance_typeparam_union.ets +ast/compiler/ets/implicit_package_import/package_test_5/package_module_1.ets +ast/compiler/ets/staticInitializerInInnerClass.ets +ast/compiler/ets/implicit_package_import/package_test_5/package_module_2_neg.ets +ast/compiler/ets/tuple_types_3_neg.ets +ast/compiler/ets/implicit_package_import/package_test_6/package_module_2.ets +ast/compiler/ets/same_name_field_err.ets +ast/compiler/ets/implicit_package_import/package_test_6/package_module_1.ets +ast/compiler/ets/implicit_package_import/package_test_4/package_module_1.ets +ast/compiler/ets/conversion_call-context_Int-to-Double_typeerror.ets +ast/compiler/ets/implicit_package_import/package_test_3/package_module_1_neg.ets +ast/compiler/ets/implicit_package_import/package_test_3/package_module_2_neg.ets +ast/compiler/ets/union_string_literals_2.ets +ast/compiler/ets/union_array_declaration.ets +ast/compiler/ets/FixedArray/spreadMultiArrayInTuple.ets +ast/compiler/ets/tuple_types_2_neg.ets +ast/compiler/ets/FixedArray/array_indexing_without_chaining_nullish.ets +ast/compiler/ets/generic_typealias_3_neg.ets +ast/compiler/ets/FixedArray/for_of_missing_iterator_type.ets +ast/compiler/ets/namespace_export_invalid01.ets +ast/compiler/ets/FixedArray/tuple_types_5_neg.ets +ast/compiler/ets/method-resolution-class-and-interface-in-signatures_6.ets +ast/compiler/ets/implicit_package_import/package_test_8/import_multi_error.ets +ast/compiler/ets/return_missing_argument.ets +ast/compiler/ets/type_error_processing/not_constructible_types.ets +ast/compiler/ets/export_type_variable_at_definition.ets +ast/compiler/ets/type_error_processing/var_without_def.ets +ast/compiler/ets/objectLiteralInaccessibleKey.ets +ast/compiler/ets/type_error_processing/type_handlers.ets +ast/compiler/ets/identifierReference3.ets +ast/compiler/ets/lambda_with_receiver_tests/extensionFuncTypeAsParamsNameDuplicated2.ets +ast/compiler/ets/objectLiteralNoContextType.ets +ast/compiler/ets/lambda_with_receiver_tests/MakeNormalFunctypeAsMethodCall.ets +ast/compiler/ets/import_type_without_export.ets +ast/compiler/ets/lambda_with_receiver_tests/extensionFuncTypeAsParamsNameDuplicated3.ets +ast/compiler/ets/inferTypeOfArrayNegative2.ets +ast/compiler/ets/lambda_with_receiver_tests/extensionFuncTypeAsParamsNameDuplicated.ets +ast/compiler/ets/TypeError_recursive_parameter_2.ets +ast/compiler/ets/lambda_with_receiver_tests/ExtensionFunctypeUncompatible.ets +ast/compiler/ets/genericObjectLiteral_neg_2.ets +ast/compiler/ets/FixedArray/most_specific_method_with_empty_rest_param.ets +ast/compiler/ets/FixedArray/annotation_tests/ambient_annotations_bad_type02.ets +ast/compiler/ets/method-resolution-class-and-interface-in-signatures_1.ets +ast/compiler/ets/FixedArray/union_string_literals_7.ets +ast/compiler/ets/FixedArray/setArrayLength3.ets +ast/compiler/ets/FunctionType9.ets +ast/compiler/ets/namespace_tests/namespace_as_type03.ets +ast/compiler/ets/setArrayLength3.ets +ast/compiler/ets/namespace_tests/namespace_as_type07.ets +ast/compiler/ets/variance_typeparam.ets +ast/compiler/ets/FixedArray/setArrayLength1.ets +ast/compiler/ets/recursive_union_neg_1.ets +ast/compiler/ets/FixedArray/annotation_tests/annotation_for_array_type01.ets +ast/compiler/ets/tuple_types_5_neg.ets +ast/compiler/ets/namespace_tests/namespace_bad_merged01.ets +ast/compiler/ets/objectLiteralWrongValueType.ets +ast/compiler/ets/namespace_tests/src01.ets +ast/compiler/ets/method-resolution-class-and-interface-in-signatures_2.ets +ast/compiler/ets/superReferenceFromStaticContext.ets +ast/compiler/ets/namespace_tests/namespace_bad_merged02.ets +ast/compiler/ets/string_tuple_type_neg.ets +ast/compiler/ets/FixedArray/lambda_type_mismatch.ets +ast/compiler/ets/invalidMemberExpressionFromStaticContext7.ets +ast/compiler/ets/FixedArray/tuple_types_1_neg.ets +ast/compiler/ets/variance_typeparam_tuple.ets +ast/compiler/ets/FixedArray/unionCommonMember_neg.ets +ast/compiler/ets/invalidMemberExpressionFromStaticContext8.ets +ast/compiler/ets/cast_TypeParameter_to_PrimitiveType2.ets +ast/compiler/ets/namespace_tests/namespace_as_type02.ets +ast/compiler/ets/generic_typealias_4_neg.ets +ast/compiler/ets/namespace_tests/namespace_access_violation.ets +ast/compiler/ets/invalidMemberExpressionFromStaticContext2.ets +ast/compiler/ets/FixedArray/union_array_declaration.ets +ast/compiler/ets/overloadMethodNoReturn0.ets +ast/compiler/ets/FixedArray/setArrayLength2.ets +ast/compiler/ets/recordWithLambdaFunction1.ets +ast/compiler/ets/FixedArray/annotation_tests/annotation_for_readonly_type.ets +ast/compiler/ets/invalidPrivateAccess5.ets +ast/compiler/ets/etsObjectToString5.ets +ast/compiler/ets/namespace_tests/namespace_access_violation_nested_scopes.ets +ast/compiler/ets/partialType_2_neg.ets +ast/compiler/ets/namespace_tests/namespace_access_violation_scope_resolution.ets +ast/compiler/ets/cast_NonNullishType_to_PrimitiveType3.ets +ast/compiler/ets/invalidPrivateAccess2.ets +ast/compiler/ets/FixedArray/unresolved_reference.ets +ast/compiler/ets/tuple_types_9_neg.ets +ast/compiler/ets/FixedArray/annotation_tests/ambient_annotations_bad_type01.ets +ast/compiler/ets/identifierReference16.ets +ast/compiler/ets/namespace_tests/namespace_access_violation_exports.ets +ast/compiler/ets/ambient_namesapce02.ets +ast/compiler/ets/FixedArray/iterabletypes_with_protected_iterator_neg.ets +ast/compiler/ets/lambdaFunction3.ets +ast/compiler/ets/FixedArray/newClassInstanceExpression.ets +ast/compiler/ets/export_same_type_at_decl_and_selective_binding.ets +ast/compiler/ets/namespace_tests/namespace_merge_conflicts.ets +ast/compiler/ets/invalidPrivateAccess6.ets +ast/compiler/ets/namespace_tests/namespace_as_type05.ets +ast/compiler/ets/invalidInheritanceFromClass.ets +ast/compiler/ets/FunctionType5.ets +ast/compiler/ets/FixedArray/annotation_tests/annotationUsage_bad_param09.ets +ast/compiler/ets/invalidPrivateAccess3.ets +ast/compiler/ets/namespace_tests/namespace_access_violation_circular_dependencies.ets +ast/compiler/ets/invalidProtectedAccess3.ets +ast/compiler/ets/export_and_export_type_interface.ets +ast/compiler/ets/FixedArray/tuple_types_9_neg.ets +ast/compiler/ets/FunctionType3.ets +ast/compiler/ets/namespace_tests/namespace_access_violation_undefined_scopes.ets +ast/compiler/ets/nullable_type_in_arithmeticmult_func.ets +ast/compiler/ets/namespace_tests/namespace_as_type12.ets +ast/compiler/ets/genericObjectLiteral_neg_1.ets +ast/compiler/ets/void_as_typeAnnotation_neg_1.ets +ast/compiler/ets/namespace_tests/namespace_as_type01.ets +ast/compiler/ets/tryCatchErrorIncorrectParamType.ets +ast/compiler/ets/namespace_tests/namespace_as_type09.ets +ast/compiler/ets/generic_typealias_5_neg.ets +ast/compiler/ets/namespace_tests/namespace_access_violation_conflicts.ets +ast/compiler/ets/generics_primitive_type_param_neg_2.ets +ast/compiler/ets/namespace_tests/namespace_as_type11.ets +ast/compiler/ets/cast_NonNullishType_to_PrimitiveType1.ets +ast/compiler/ets/namespace_tests/namespace_default_import.ets +ast/compiler/ets/inferTypeOfArrayNegative3.ets +ast/compiler/ets/namespace_tests/namespace_as_type06.ets +ast/compiler/ets/FixedArray/variance_typeparam_array.ets +ast/compiler/ets/etsObjectToString2.ets +ast/compiler/ets/identifierReference10.ets +ast/compiler/ets/FixedArray/implicit_package_import/scopes_multi_error.ets +ast/compiler/ets/identifierReference2.ets +ast/compiler/ets/namespace_tests/namespace_access_violation_import_conflicts.ets +ast/compiler/ets/requiredType_6.ets +ast/compiler/ets/objectLiteralNoSuchKey.ets +ast/compiler/ets/FixedArray/extension_function_tests/array_extension_func_dupicated_name_with_builtin.ets +ast/compiler/ets/invalidProtectedAccess1.ets +ast/compiler/ets/infinityNarrowing.ets +ast/compiler/ets/generic_variance_4.ets +ast/compiler/ets/FixedArray/extension_function_tests/extension_function_return_this_neg2.ets +ast/compiler/ets/union_string_literals_1.ets +ast/compiler/ets/namespace_tests/namespace_as_type10.ets +ast/compiler/ets/invalidMemberExpressionFromStaticContext1.ets +ast/compiler/ets/default_export/export_default_bad2.ets +ast/compiler/ets/ambient_namesapce06.ets +ast/compiler/ets/identifierReference13.ets +ast/compiler/ets/generics_primitive_type_param_neg_1.ets +ast/compiler/ets/selective-export-multiple/import_ambient_const_neg.ets +ast/compiler/ets/tryCatchFlow.ets +ast/compiler/ets/switchcaseDuplicate.ets +ast/compiler/ets/setArrayLength2.ets +ast/compiler/ets/import_type_with_invalid_syntax.ets +ast/compiler/ets/tryCatchMissingParam.ets +ast/compiler/ets/FixedArray/annotation_tests/annotationDecl_bad_initializer08.ets +ast/compiler/ets/forbidden_inherit_class_1.ets +ast/compiler/ets/namespace_tests/namespace_as_type08.ets +ast/compiler/ets/identifierReference1.ets +ast/compiler/ets/default_export/export_default_bad1.ets +ast/compiler/ets/readonlyType_6.ets +ast/compiler/ets/forbidden_inherit_class_2.ets +ast/compiler/ets/objectLiteralPrimitiveContextType.ets +ast/compiler/ets/lambdaFunction5.ets +ast/compiler/ets/array_with_type_parameter.ets +ast/compiler/ets/readonlyIntfObjectLiteral_neg_1.ets +ast/compiler/ets/cast_UnionType_to_PrimitiveType2.ets +ast/compiler/ets/tryCatchErrorFlow.ets +ast/compiler/ets/export_type_enum.ets +ast/compiler/ets/union_string_literals_6.ets +ast/compiler/ets/namespace_tests/namespace_as_type04.ets +ast/compiler/ets/FunctionType1.ets +ast/compiler/ets/invalidInheritance1.ets +ast/compiler/ets/absent_return_statement.ets +ast/compiler/ets/unresolved_reference.ets +ast/compiler/ets/generic_variance_5.ets +ast/compiler/ets/iterabletypes_with_protected_iterator_neg.ets +ast/compiler/ets/UnresolvedReferenceInCamparison.ets +ast/compiler/ets/invalidMemberExpressionFromStaticContext5.ets +ast/compiler/ets/override7.ets +ast/compiler/ets/invalidProtectedAccess2.ets +ast/compiler/ets/recordWithLambdaFunction2.ets +ast/compiler/ets/variance_typeparam_array.ets +ast/compiler/ets/spreadExpressionAsPropertyInObjectLiteral.ets +ast/compiler/ets/export_type_variable.ets +ast/compiler/ets/lambdaExpressionWithoutBlockStatementDifferentType.ets +ast/compiler/ets/interfaceMethodNotOverridden.ets +ast/compiler/ets/lambda_infer_type/lambda_param_type_cannot_be_determined.ets +ast/compiler/ets/extension_function_tests/extension_function_return_this_union2.ets +ast/compiler/ets/extension_function_tests/extension_function_params_neg2.ets +ast/compiler/ets/extension_function_tests/normal_function_with_extension_style_signature.ets +ast/compiler/ets/namespace_tests/namespace_access_violation_non_exported_merge.ets +ast/compiler/ets/mostSpecificMethod2.ets +ast/compiler/ets/privateMethodOverride.ets +ast/compiler/ets/import_tests/export_multi_error.ets +ast/compiler/ets/extension_function_tests/extension_function_duplicated_with_private_field.ets +ast/compiler/ets/extension_function_tests/extension_function_miss_signature.ets +ast/compiler/ets/extension_function_tests/extension_function_called_by_class.ets +ast/compiler/ets/extension_function_tests/extension_function_return_this_union3.ets +ast/compiler/ets/generic_typealias_2_neg.ets +ast/compiler/ets/tuple_types_4_neg.ets +ast/compiler/ets/annotation_tests/annotationUsage_excessive_param01.ets +ast/compiler/ets/import_tests/dynamic_import_interop_neg.ets +ast/compiler/ets/import_tests/selective_export_tests/import_function_wrong_name.ets +ast/compiler/ets/import_tests/selective_export_tests/import_interface_wrong_name.ets +ast/compiler/ets/import_tests/selective_export_tests/namespace_import_wrong_access_name.ets +ast/compiler/ets/import_tests/selective_export_tests/selective_export_clashing_exports_1.ets +ast/compiler/ets/extension_function_tests/array_extension_func_dupicated_name_with_builtin.ets +ast/compiler/ets/extension_function_tests/extension_function_not_for_class_type.ets +ast/compiler/ets/extension_function_tests/extension_function_duplication.ets +ast/compiler/ets/extension_function_tests/extension_function_access_protected_field.ets +ast/compiler/ets/extension_function_tests/extension_function_return_this_neg3.ets +ast/compiler/ets/extension_function_tests/extension_function_shadowed_by_member_function.ets +ast/compiler/ets/extension_function_tests/put_this_as_method_params.ets +ast/compiler/ets/extension_function_tests/extension_function_return_this_neg.ets +ast/compiler/ets/extension_function_tests/extension_function_access_private_field.ets +ast/compiler/ets/extension_function_tests/extension_function_shadowed_by_different_return_type_interface_function.ets +ast/compiler/ets/extension_function_tests/normal_function_duplicated_with_extension_function.ets +ast/compiler/ets/extension_function_tests/extension_function_return_this_neg2.ets +ast/compiler/ets/extension_function_tests/extension_function_params_neg1.ets +ast/compiler/ets/extension_function_tests/extension_function_return_this_union.ets +ast/compiler/ets/extension_function_tests/extension_function_for_unresolved_type.ets +ast/compiler/ets/extension_function_tests/extension_function_primitive.ets +ast/compiler/ets/annotation_tests/annotationUsage_duplicate_on_method.ets +ast/compiler/ets/this_type_invalid_return_type.ets +ast/compiler/ets/annotation_tests/annotation_for_object_type.ets +ast/compiler/ets/annotation_tests/annotationUsage_as_type08.ets +ast/compiler/ets/annotation_tests/annotationUsage_duplicate_for_namespace01.ets +ast/compiler/ets/variance_typeparam_transmit.ets +ast/compiler/ets/requiredType_2_neg.ets +ast/compiler/ets/generic_function_call_6.ets +ast/compiler/ets/enum_not_constant_var.ets +ast/compiler/ets/union_string_literals_8.ets +ast/compiler/ets/nullable_type_in_arithmeticplus_w_undefined.ets +ast/compiler/ets/override14.ets +ast/compiler/ets/tuple_types_10_neg.ets +ast/compiler/ets/validate_signatures_throw_type_error_more_param.ets +ast/compiler/ets/annotation_tests/annotationUsage_duplicate_for_interfaceproperty.ets +ast/compiler/ets/ambient_indexer_1.ets +ast/compiler/ets/namespace_tests/namespace_access_violation_merge_conflicts.ets +ast/compiler/ets/newClassInstanceExpression.ets +ast/compiler/ets/n_assignGenericWithNullableTypeParamToNonNullable.ets +ast/compiler/ets/overrideModifierNotOverriding.ets +ast/compiler/ets/tryCatchIncorrectParamType.ets +ast/compiler/ets/circular_variable_init.ets +ast/compiler/ets/type_binding_neg_02.ets +ast/compiler/ets/annotation_tests/annotationUsage_duplicate_for_namespace02.ets +ast/compiler/ets/ambient_namesapce05.ets +ast/compiler/ets/identifierReference8.ets +ast/compiler/ets/annotation_tests/annotationUsage_duplicate_for_variable_decl.ets +ast/compiler/ets/annotation_tests/annotationUsage_as_type11.ets +ast/compiler/ets/annotation_tests/Retentions_missing_arguments.ets +ast/compiler/ets/method-resolution-class-and-interface-in-signatures_3.ets +ast/compiler/ets/void_as_value_neg_2.ets +ast/compiler/ets/readonlyIntfObjectLiteral_neg_2.ets +ast/compiler/ets/annotation_tests/annotationUsage_missing_AT_for_interface.ets +ast/compiler/ets/annotation_tests/annotationUsage_excessive_param_for_type_alias.ets +ast/compiler/ets/generic_variance_2.ets +ast/compiler/ets/annotation_tests/annotationUsage_bad_param07.ets +ast/compiler/ets/annotation_tests/annotationUsage_as_type05.ets +ast/compiler/ets/requiredType_3_neg.ets +ast/compiler/ets/etsObjectToString1.ets +ast/compiler/ets/objectLiteralPrivateConstructor.ets +ast/compiler/ets/invalidMemberExpressionFromStaticContext6.ets +ast/compiler/ets/annotation_tests/annotationUsage_missing_param_for_function_param.ets +ast/compiler/ets/void_as_value_neg_4.ets +ast/compiler/ets/annotation_tests/annotationUsage_duplicate_for_interface.ets +ast/compiler/ets/annotation_tests/annotationUsage_missing_AT01.ets +ast/compiler/ets/annotation_tests/annotationUsage_missing_AT02.ets +ast/compiler/ets/annotation_tests/annotation_for_annotation.ets +ast/compiler/ets/annotation_tests/annotationUsage_as_type06.ets +ast/compiler/ets/annotation_tests/annotationUsage_missing_AT_for_type_alias.ets +ast/compiler/ets/annotation_tests/annotation_without_source_policy.ets +ast/compiler/ets/annotation_tests/annotationDecl_bad_initializer08.ets +ast/compiler/ets/annotation_tests/annotationUsage_as_type07.ets +ast/compiler/ets/annotation_tests/annotationUsage_duplicate_for_type_alias.ets +ast/compiler/ets/annotation_tests/annotation_for_string_literal.ets +ast/compiler/ets/annotation_tests/annotationUsage_as_type02.ets +ast/compiler/ets/annotation_tests/annotationDecl_bad_initializer07.ets +ast/compiler/ets/import_tests/selective_export_tests/selective_export_clashing_exports_4.ets +ast/compiler/ets/import_tests/selective_export_tests/selective_export_clashing_exports_3.ets +ast/compiler/ets/import_tests/selective_export_tests/selective_export_clashing_exports_2.ets +ast/compiler/ets/import_tests/import_chain_with_errors/master_file.ets +ast/compiler/ets/import_tests/import_chain_with_errors/import_2.ets +ast/compiler/ets/import_tests/import_chain_with_errors/import_1.ets +ast/compiler/ets/import_tests/import_distant_package/master_file.ets +ast/compiler/ets/import_tests/import_distant_package/package_with_errors/package_with_errors_2.ets +ast/compiler/ets/import_tests/import_distant_package/package_with_errors/package_with_errors_1.ets +ast/compiler/ets/identifierReference6.ets +ast/compiler/ets/conversion_Double-to-Int_typeerror.ets +ast/compiler/ets/ambient_namesapce03.ets +ast/compiler/ets/export_type_class_multiple_times.ets +ast/compiler/ets/TypeError_recursive_parameter_1.ets +ast/compiler/ets/FunctionType10.ets +ast/compiler/ets/recursive_interface_neg_2.ets +ast/compiler/ets/annotation_tests/annotationUsage_as_type03.ets +ast/compiler/ets/annotation_tests/annotationUsage_as_type13.ets +ast/compiler/ets/annotation_tests/annotation_for_named_type.ets +ast/compiler/ets/annotation_tests/annotationUsage_conflict_for_namespace01.ets +ast/compiler/ets/import_tests/import_distant_package/package_with_errors/import_in_package_with_error.ets +ast/compiler/ets/import_tests/import_distant_package/package_with_errors/inner_package_with_errors/distant_package.ets +ast/compiler/ets/annotation_tests/ambient_annotations_bad_type02.ets +ast/compiler/ets/constant_variable_import_tests/enum_import_constant.ets +ast/parser/ets/classAsFunctionParam.ets +ast/parser/ets/double_parenthesis_invocation_setter_supposed_to_fail.ets +ast/parser/ets/keyof_constraint.ets +ast/parser/ets/enum_default_negative1.ets +ast/parser/ets/predefined_non_primitive_types.ets +ast/parser/ets/dynamic_import_tests/dynamic_class_ctor_decl_import_bad.ets +ast/parser/ets/dynamic_import_tests/dynamic_class_method_decl_import_bad_2.ets +ast/parser/ets/dynamic_import_tests/dynamic_func_decl_import_bad.ets +ast/parser/ets/dynamic_import_tests/dynamic_class_field_decl_import_bad_1.ets +ast/parser/ets/dynamic_import_tests/dynamic_class_method_decl_import_bad_1.ets +ast/parser/ets/dynamic_import_tests/dynamic_class_field_decl_import_bad_2.ets +ast/parser/ets/annotations_tests/annotationUsage_bad_param01.ets +ast/parser/ets/annotations_tests/annotationUsage_parser_bad_token03.ets +ast/parser/ets/annotations_tests/annotationDecl_parser_bad_token03.ets +ast/parser/ets/annotations_tests/annotationUsage_bad_param_for_lambda.ets +ast/parser/ets/annotations_tests/annotationUsage_bad_param04.ets +ast/parser/ets/annotations_tests/annotation_rename_export.ets +ast/parser/ets/annotations_tests/annotationUsage_parser_bad_token04.ets +ast/parser/ets/annotations_tests/annotationDecl_parser_bad_token05.ets +ast/parser/ets/annotations_tests/annotationDecl_bad_initializer03.ets +ast/parser/ets/annotations_tests/annotationDecl_redefined.ets +ast/parser/ets/annotations_tests/annotation_export_type.ets +ast/parser/ets/annotations_tests/annotationUsage_bad_param_for_interfacemethod.ets +ast/parser/ets/annotations_tests/annotationDecl_field_with_modifiers01.ets +ast/parser/ets/annotations_tests/annotationDecl_parser_bad_token04.ets +ast/parser/ets/annotations_tests/annotationUsage_bad_param_for_local_variable_decl.ets +ast/parser/ets/annotations_tests/annotationDecl_with_method.ets +ast/parser/ets/annotations_tests/annotationDecl_missing_typeAnnotation03.ets +ast/parser/ets/annotations_tests/annotationUsage_on_annotationDecl.ets +ast/parser/ets/annotations_tests/annotationUsage_parser_bad_token05.ets +ast/parser/ets/annotations_tests/annotationUsage_bad_param05.ets +ast/parser/ets/annotations_tests/annotationUsage_bad_param_for_type_alias.ets +ast/parser/ets/annotations_tests/annotationDecl_with_innerclass.ets +ast/parser/ets/annotations_tests/annotation_default_export.ets +ast/parser/ets/annotations_tests/annotationDecl_parser_bad_token07.ets +ast/parser/ets/annotations_tests/annotationDecl_field_with_modifiers04.ets +ast/parser/ets/annotations_tests/annotationUsage_bad_param_for_classproperty.ets +ast/parser/ets/annotations_tests/annotationUsage_bad_param07.ets +ast/parser/ets/annotations_tests/annotationUsage_bad_param_for_global_variable_decl.ets +ast/parser/ets/annotations_tests/annotationDecl_parser_bad_token01.ets +ast/parser/ets/annotations_tests/annotationUsage_bad_param06.ets +ast/parser/ets/annotations_tests/annotationUsage_missing_AT_for_function_param.ets +ast/parser/ets/annotations_tests/annotationDecl_bad_initializer02.ets +ast/parser/ets/annotations_tests/annotationDecl_field_with_modifiers03.ets +ast/parser/ets/annotations_tests/annotationDecl_classDecl_conflict.ets +ast/parser/ets/annotations_tests/annotationUsage_bad_param_for_interface.ets +ast/parser/ets/annotations_tests/annotationUsage_parser_bad_token02.ets +ast/parser/ets/annotations_tests/annotationDecl_enum_conflict.ets +ast/parser/ets/annotations_tests/annotationUsage_tmp.ets +ast/parser/ets/annotations_tests/annotationDecl_field_with_modifiers02.ets +ast/parser/ets/annotations_tests/annotationDecl_bad_initializer06.ets +ast/parser/ets/annotations_tests/annotationUsage_on_abstract_class.ets +ast/parser/ets/annotations_tests/annotationUsage_bad_param_for_function_param.ets +ast/parser/ets/annotations_tests/annotationDecl_missing_typeAnnotation01.ets +ast/parser/ets/annotations_tests/annotationUsage_on_abstract_method.ets +ast/parser/ets/annotations_tests/annotationUsage_bad_param_for_interfaceproperty.ets +ast/parser/ets/annotations_tests/annotationUsage_bad_param02.ets +ast/parser/ets/annotations_tests/annotationUsage_missing_AT_for_classproperty.ets +ast/parser/ets/annotations_tests/annotationDecl_bad_initializer01.ets +ast/parser/ets/annotations_tests/annotationDecl_with_access_modifier01.ets +ast/parser/ets/annotations_tests/annotation_rename_import.ets +ast/parser/ets/annotations_tests/annotationDecl_bad_initializer04.ets +ast/parser/ets/annotations_tests/annotationDecl_parser_bad_token06.ets +ast/parser/ets/annotations_tests/annotationDecl_parser_bad_token02.ets +ast/parser/ets/annotations_tests/annotationUsage_parser_bad_token01.ets +ast/parser/ets/annotations_tests/annotationDecl_interface_conflict.ets +ast/parser/ets/annotations_tests/annotationUsage_bad_param03.ets +ast/parser/ets/annotations_tests/annotationUsage_for_invalid_expr.ets +ast/parser/ets/annotations_tests/annotationDecl_with_access_modifier03.ets +ast/parser/ets/annotations_tests/annotationUsage_missing_initializer01.ets +ast/parser/ets/annotations_tests/annotationDecl_with_access_modifier02.ets +ast/parser/ets/annotations_tests/annotationDecl_missing_typeAnnotation02.ets +ast/parser/ets/annotations_tests/annotationDecl_bad_initializer05.ets +ast/parser/ets/annotations_tests/annotationDecl_locally.ets +ast/parser/ets/import_tests/import_type_error_top_level.ets +ast/parser/ets/import_tests/import_name_conflict_4.ets +ast/parser/ets/import_tests/Import_error_token_1.ets +ast/parser/ets/import_tests/import_all_2.ets +ast/parser/ets/import_tests/import_all_alias_neg.ets +ast/parser/ets/import_tests/import_name_alias_2.ets +ast/parser/ets/import_tests/import_name_conflict_5.ets +ast/parser/ets/import_tests/import_name_3.ets +ast/parser/ets/import_tests/import_name_conflict_11.ets +ast/parser/ets/import_tests/import_name_conflict_8.ets +ast/parser/ets/import_tests/default_import3.ets +ast/parser/ets/import_tests/check_exported_1.ets +ast/parser/ets/import_tests/import_name_conflict_9.ets +ast/parser/ets/import_tests/import_name_conflict_1.ets +ast/parser/ets/import_tests/import_all_alias_2.ets +ast/parser/ets/import_tests/import_name_conflict_6.ets +ast/parser/ets/import_tests/export_no_comma.ets +ast/parser/ets/import_tests/default_import2.ets +ast/parser/ets/import_tests/import_folder_n.ets +ast/parser/ets/import_tests/import_name_conflict_10.ets +ast/parser/ets/import_tests/import_name_conflict_7.ets +ast/parser/ets/import_tests/export_trailing_comma.ets +ast/parser/ets/import_tests/import_name_2.ets +ast/parser/ets/import_tests/import_name_conflict_2.ets +ast/parser/ets/import_tests/import_type_error_in_class.ets +ast/parser/ets/import_tests/import_name_conflict_12.ets +ast/parser/ets/import_tests/import_no_comma.ets +ast/parser/ets/import_tests/packages/different-header/subpackage_module_1.ets +ast/parser/ets/import_tests/packages/different-header/subpackage_module_2.ets +ast/parser/ets/import_tests/invalid_default_export/default_export_invalid_syntax_3.ets +ast/parser/ets/import_tests/modules/too_many_default_exports_2.ets +ast/parser/ets/import_tests/modules/too_many_default_exports.ets +ast/parser/ets/import_tests/modules/invalid_namespace_import.ets +ast/parser/ets/import_tests/invalid_default_export/default_export_invalid_syntax_4.ets +ast/parser/ets/import_tests/import_alias/import_alias_3.ets +ast/parser/ets/import_tests/import_alias/import_alias_2.ets +ast/parser/ets/import_tests/import_alias/import_alias_4.ets +ast/parser/ets/import_tests/import_name_conflicts/main_1.ets +ast/parser/ets/import_tests/import_name_conflicts/main_6.ets +ast/parser/ets/import_tests/import_name_conflicts/main_4.ets +ast/parser/ets/import_tests/import_name_conflicts/main_7.ets +ast/parser/ets/import_tests/wrong_import_decl_placement/import_decl_in_block_n.ets +ast/parser/ets/import_tests/wrong_import_decl_placement/import_decl_after_decl_n.ets +ast/parser/ets/import_tests/import_name_conflicts/main_5.ets +ast/parser/ets/import_tests/import_name_conflicts/main_8.ets +ast/parser/ets/import_tests/import_name_conflicts/main_3.ets +ast/parser/ets/import_tests/import_name_conflicts/main_2.ets +ast/parser/ets/import_tests/type/import_type_1.ets +ast/parser/ets/import_tests/type/type_2.ets +ast/parser/ets/import_tests/type/type_3.ets +ast/parser/ets/import_tests/type/import_type_2.ets +ast/parser/ets/readonly-parameter-test/readonly-parameter-test2.ets +ast/parser/ets/readonly-parameter-test/readonly-parameter-test6.ets +ast/parser/ets/readonly-parameter-test/readonly-parameter-and-Readonly-test1.ets +ast/parser/ets/readonly-parameter-test/readonly-parameter-test5.ets +ast/parser/ets/readonly-parameter-test/readonly-parameter-and-Readonly-test2.ets +ast/parser/ets/readonly-parameter-test/readonly-parameter-test3.ets +ast/parser/ets/readonly-parameter-test/Readonly-with-ArrayType-test3.ets +ast/parser/ets/readonly-parameter-test/readonly-parameter-test1.ets +ast/parser/ets/readonly-parameter-test/Readonly-with-ArrayType-test1.ets +ast/parser/ets/trailing_lambda_tests/trailing_lambda_mismatch_lambda_signature_1.ets +ast/parser/ets/trailing_lambda_tests/trailing_lambda_not_transform_trailing_block_1.ets +ast/parser/ets/trailing_lambda_tests/trailing_lambda_not_transform_trailing_block_3.ets +ast/parser/ets/trailing_lambda_tests/trailing_lambda_not_transform_trailing_block_5.ets +ast/parser/ets/trailing_lambda_tests/trailing_lambda_not_transform_trailing_block_2.ets +ast/parser/ets/trailing_lambda_tests/trailing_lambda_not_transform_trailing_block_4.ets +ast/parser/ets/trailing_lambda_tests/trailing_lambda_omit_call_parentheses.ets +ast/parser/ets/re_export/import_5.ets +ast/parser/ets/type_variance2.ets +ast/parser/ets/type_variance4.ets +ast/parser/ets/MultipleParserErrors.ets +ast/parser/ets/local-class-member-access-modifier-public2.ets +ast/parser/ets/local-class-access-modifier-public.ets +ast/parser/ets/setter_with_more_than_one_formal_parameter.ets +ast/parser/ets/keyof_parameter.ets +ast/parser/ets/method_full.ets +ast/parser/ets/try_catch_alive_4.ets +ast/parser/ets/class_variable_empty.ets +ast/parser/ets/unexpected_token_46.ets +ast/parser/ets/StringFasta.ets +ast/parser/ets/unexpected_token_55.ets +ast/parser/ets/re_export/import_17.ets +ast/parser/ets/FixedArray/main_entry_point_3.ets +ast/parser/ets/FixedArray/for_of_02.ets +ast/parser/ets/FixedArray/unexpected_token_31.ets +ast/parser/ets/FixedArray/main_entry_point_4.ets +ast/parser/ets/FixedArray/spreadexpr_in_newexpr_neg02.ets +ast/parser/ets/extension_function_tests/extension_function_not_in_toplevel.ets +ast/parser/ets/readonly-parameter-test/Readonly-with-ArrayType-test4.ets +ast/parser/ets/readonly-parameter-test/readonly-parameter-test4.ets +ast/parser/ets/readonly-parameter-test/Readonly-with-ArrayType-test2.ets +ast/parser/ets/static_invoke_tests/static_invoke_mismatch_signature_1.ets +ast/parser/ets/static_invoke_tests/static_invoke_coexist_invoke_method.ets +ast/parser/ets/static_invoke_tests/static_invoke_mismatch_signature.ets +ast/parser/ets/static_invoke_tests/static_invoke_mismatch_signature_2.ets +ast/parser/ets/single_export/single_export_n.ets +ast/parser/ets/single_export/single_export_from_n.ets +ast/parser/ets/single_export/single_export_lambda.ets +ast/parser/ets/single_export/single_export_expression.ets +ast/parser/ets/single_export/single_export_default_lambda.ets +ast/parser/ets/single_export/single_export_as_n.ets +ast/compiler/ets/generic_variance_3.ets +ast/compiler/ets/recursive_function_neg_1.ets +ast/compiler/ets/readonlyType_2.ets +ast/compiler/ets/cast_TypeParameter_to_PrimitiveType1.ets +ast/compiler/ets/identifierReference12.ets +ast/parser/ets/enum_multi_error/enum_not_pair_brackets.ets +ast/parser/ets/enum_multi_error/enum_with_identifier.ets +ast/parser/ets/enum_multi_error/enum_empty.ets +ast/parser/ets/FixedArray/wrong-union-array-assignment.ets +ast/parser/ets/FixedArray/array_2.ets +ast/compiler/ets/type_binding_neg_01.ets +ast/compiler/ets/lambdaFunction4.ets +ast/compiler/ets/spreadMultiArrayInTuple.ets +ast/compiler/ets/union_string_literals_3.ets +ast/parser/ets/FixedArray/nonIntegralIndex.ets +ast/compiler/ets/boxingConversion1.ets +ast/compiler/ets/ObjectLiteral_neg_1.ets +ast/compiler/ets/invalidPrivateAccess4.ets +ast/compiler/ets/invalidInheritanceFromInterface.ets +ast/compiler/ets/override3.ets +ast/compiler/ets/recursive_class_neg.ets +ast/compiler/ets/ambient_namesapce01.ets +ast/compiler/ets/variance_typeparam_lambda.ets +ast/compiler/ets/union_types_4.ets +ast/compiler/ets/function_subtyping_2.ets +ast/compiler/ets/override15.ets +ast/compiler/ets/identifierReference7.ets +ast/compiler/ets/tuple_types_6_neg.ets +ast/compiler/ets/etsObjectToString4.ets +ast/compiler/ets/DeclareCheckAssign.ets +ast/compiler/ets/invalidInheritance4.ets +ast/compiler/ets/overloadMethodNoReturn1.ets +ast/compiler/ets/array_indexing_without_chaining_nullish.ets +ast/compiler/ets/async_import_3.ets +ast/compiler/ets/for_of_missing_iterator_type.ets +ast/compiler/ets/generic_class_without_type_arg_2.ets +ast/compiler/ets/most_specific_method_with_empty_rest_param.ets +ast/compiler/ets/voidTypeInBinaryOperation.ets +ast/compiler/ets/export_type_interface_multiple_times.ets +ast/compiler/ets/cast_UnionType_to_PrimitiveType1.ets +ast/parser/ets/FixedArray/rest_parameter_04.ets +ast/parser/ets/FixedArray/unclosed_loop.ets +ast/parser/ets/FixedArray/trailing_comma_1.ets +ast/parser/ets/FixedArray/record_object_value.ets +ast/parser/ets/FixedArray/for_of_03.ets +ast/parser/ets/FixedArray/superInConstructor3.ets +ast/parser/ets/FixedArray/static_field_3.ets +ast/parser/ets/FixedArray/forOfCustomIterator1.ets +ast/parser/ets/FixedArray/tuple_type_2_neg.ets +ast/parser/ets/FixedArray/array_missing_element.ets +ast/parser/ets/FixedArray/forOfCustomIterator2.ets +ast/compiler/ets/partialType_3_neg.ets +ast/compiler/ets/math_const_as_identifier.ets +ast/compiler/ets/call_for_method_never_exist.ets +ast/compiler/ets/requiredType_7_neg.ets +ast/parser/ets/FixedArray/static_func_call_8.ets +ast/parser/ets/FixedArray/unexpected_token_26.ets +ast/parser/ets/re_export/re_export_4.ets +ast/parser/ets/re_export/import_16.ets +ast/parser/ets/FixedArray/unexpected_token_42.ets +ast/parser/ets/FixedArray/invalidTypes.ets +ast/parser/ets/FixedArray/unexpected_token_38.ets +ast/parser/ets/FixedArray/type_argument_conversion.ets +ast/parser/ets/FixedArray/functionTypeParam_neg2.ets +ast/parser/ets/FixedArray/MultipleParserErrors.ets +ast/parser/ets/FixedArray/method_full.ets +ast/parser/ets/FixedArray/StringFasta.ets +ast/parser/ets/FixedArray/predefined_non_primitive_types.ets +ast/parser/ets/FixedArray/readonly-parameter-test/Readonly-with-ArrayType-test4.ets +ast/parser/ets/FixedArray/readonly-parameter-test/Readonly-with-ArrayType-test1.ets +ast/parser/ets/selective_export/selective_export_bad.ets +ast/parser/ets/static_invoke_tests/static_invoke_coexist_invoke_method_1.ets +ast/compiler/ets/variance_typeparam_overload.ets +ast/compiler/ets/identifierReference15.ets +ast/compiler/ets/identifierReference5.ets +ast/compiler/ets/requiredType_10_neg.ets +ast/compiler/ets/union_string_literals_7.ets +ast/compiler/ets/objectLiteralNoParameterlessConstructor.ets +ast/compiler/ets/export_type_function.ets +ast/compiler/ets/readonlyField.ets +ast/compiler/ets/typeVarReferenceFromStaticContext.ets +ast/compiler/ets/generic_typealias_10_neg.ets +ast/compiler/ets/invalidIndirectInheritanceFromClass.ets +ast/compiler/ets/getterNoReturn0.ets +ast/compiler/ets/void_as_value_neg_1.ets +ast/compiler/ets/setArrayLength1.ets +ast/compiler/ets/boxingConversion4.ets +ast/compiler/ets/resolve_func_name_union_type.ets +ast/parser/ets/FixedArray/InvalidStatements3.ets +ast/parser/ets/FixedArray/ets_never_type_without_affect_other.ets +ast/parser/ets/FixedArray/array_type.ets +ast/parser/ets/FixedArray/spreadexpr_in_newexpr_neg01.ets +ast/parser/ets/FixedArray/n_arrayHoldingNullValue.ets +ast/parser/ets/FixedArray/spreadArrayInTuple.ets +ast/parser/ets/FixedArray/FunctionalTypeAsArrayElement.ets +ast/parser/ets/FixedArray/illegal_union_member_exp.ets +ast/parser/ets/FixedArray/unexpected_token_36.ets +ast/parser/ets/FixedArray/enum11.ets +ast/parser/ets/FixedArray/unexpected_token_47.ets +ast/parser/ets/FixedArray/function_decl.ets +ast/parser/ets/FixedArray/main_entry_point_5.ets +ast/parser/ets/FixedArray/unexpected_token_39.ets + +# Failures with plugin recheck that should be fixed (Issue #24651) +ast/compiler/ets/ambiguous_signature01.ets +ast/compiler/ets/ambiguous_signature02.ets +ast/compiler/ets/async_import_2.ets +ast/compiler/ets/interface_ambient_call_signature_1.ets +ast/compiler/ets/interface_ambient_indexer_3.ets +ast/compiler/ets/optionalClassProperty1.ets +ast/compiler/ets/static_index_function1.ets +ast/compiler/ets/static_index_function2.ets +ast/compiler/ets/static_index_function3.ets +ast/parser/ets/enum29.ets +ast/parser/ets/enum31.ets +ast/parser/ets/enum32.ets +ast/parser/ets/interface_ambient_call_signature.ets +ast/parser/ets/interface_ambient_call_signature_1.ets +ast/parser/ets/interface_ambient_indexer_1.ets +ast/parser/ets/interface_ambient_indexer_2.ets +ast/parser/ets/interface_ambient_iterable.ets +ast/parser/ets/named_types_1.ets +ast/parser/ets/named_types_2.ets +ast/parser/ets/readonly-parameter-test/Readonly-Array-test1.ets +ast/parser/ets/readonly-parameter-test/Readonly-Array-test2.ets +ast/parser/ets/readonly-parameter-test/Readonly-Array-test3.ets +compiler/ets/dynamic-equality.ets +compiler/ets/dynamicJsImport.ets +compiler/ets/dynamicLambda.ets +compiler/ets/dynamicLambdaJSValue.ets +compiler/ets/dynamicObjectLiteral.ets +compiler/ets/dynamic_call.ets +compiler/ets/import_tests/asyncfun_lambda_lib.ets +compiler/ets/instanceof_x_dyndecl.ets +compiler/ets/instanceof_x_etstype.ets +compiler/ets/instanceof_x_object.ets +parser/ets/async_function.ets +parser/ets/async_overload.ets +parser/ets/async_with_lambda.ets +parser/ets/await_keyword.ets +parser/ets/dynamic_import_tests/dynamic_decl_import.ets +parser/ets/dynamic_import_tests/dynamic_optional_decl.ets +parser/ets/re_export/diamond/D.ets +parser/ets/re_export/diamond/D2.ets +parser/ets/re_export/import_14.ets +parser/ets/re_export/import_2.ets +runtime/ets/async-func-overload-and-type-infer.ets +runtime/ets/async_and_instance_method_with_same_name01.ets +runtime/ets/async_and_instance_method_with_same_name02.ets +runtime/ets/async_method_with_same_name01.ets +runtime/ets/async_method_with_same_name02.ets +runtime/ets/async_optional.ets +runtime/ets/async_return_void_1.ets +runtime/ets/async_return_void_2.ets +runtime/ets/async_return_void_3.ets +runtime/ets/async_scope_fix.ets +runtime/ets/extension_function_tests/extensionFunctionReturnThis2.ets +runtime/ets/getteSetterImplementation.ets +runtime/ets/getterSetterImplementationWithConstructor.ets +runtime/ets/implementsClassPropertyFunctionType.ets +runtime/ets/implementsClassPropertyFunctionType2.ets +runtime/ets/lambda_with_receiver/lambda_with_receiver_return_this2.ets +runtime/ets/readonly_simple_form_pos.ets +ast/compiler/ets/declareNameSpace.ets +ast/compiler/ets/multiple_inheritance_neg.ets +ast/compiler/ets/multiple_inheritance_neg_2.ets +ast/compiler/ets/namespaceExport_neg.ets +ast/parser/ets/invalid_object_literal.ets +ast/parser/ets/static_block.ets +runtime/ets/GenericBridges_01.ets +ast/compiler/ets/tuple_union_neg.ets +ast/compiler/ets/union_method_4.ets +ast/parser/ets/rest_parameter_05.ets +ast/parser/ets/rest_parameter_06.ets +ast/parser/ets/rest_parameter_07.ets +ast/parser/ets/rest_parameter_08.ets +ast/parser/ets/user_defined_27.ets +ast/compiler/ets/interface_ambient_iterable_1.ets +ast/parser/ets/implement_interface1.ets +compiler/ets/lowering-interaction.ets +runtime/ets/Function.ets +runtime/ets/IterableTypesWithProtectedIterator.ets +runtime/ets/ObjectIterable_1.ets +runtime/ets/ObjectIterable_2.ets +runtime/ets/extension_accessor/extensionAccessorAlone.ets +runtime/ets/extension_accessor/extensionAccessorAsClassPropertyValue.ets +runtime/ets/extension_accessor/extensionAccessorAsExprOfStatementExpr.ets +runtime/ets/extension_accessor/extensionAccessorAsMemberExprObject.ets +runtime/ets/extension_accessor/extensionAccessorAsMemberExprProperty.ets +runtime/ets/extension_accessor/extensionAccessorInCallArgs.ets +runtime/ets/extension_accessor/extensionAccessorInCallArgs2.ets +runtime/ets/extension_accessor/extensionAccessorInFunction.ets +runtime/ets/extension_accessor/extensionAccessorInOpAssignment.ets +runtime/ets/extension_accessor/extensionAccessorInOpAssignment2.ets +runtime/ets/extension_accessor/extensionAccessorInherited1.ets +runtime/ets/extension_accessor/extensionAccessorInherited2.ets +runtime/ets/extension_accessor/extensionAccessorWithNewExpr1.ets +runtime/ets/extension_accessor/extensionAccessorWithNewExpr2.ets +runtime/ets/extension_accessor/extensionGetterAndOriginalSetter.ets +runtime/ets/extension_accessor/extensionSetterAndOriginalGetter.ets +runtime/ets/forOfCustomIterator1.ets +runtime/ets/forOfCustomIterator2.ets +runtime/ets/objectLiteral-2.ets +runtime/ets/objectLiteral.ets +runtime/ets/objectLiteralInterfaceType.ets +runtime/ets/objectLiteral_abstract_class_object.ets +runtime/ets/rest_object_literal.ets \ No newline at end of file diff --git a/ets2panda/test/unit/plugin/CMakeLists.txt b/ets2panda/test/unit/plugin/CMakeLists.txt index 3456abfeb2..7b685f4f25 100644 --- a/ets2panda/test/unit/plugin/CMakeLists.txt +++ b/ets2panda/test/unit/plugin/CMakeLists.txt @@ -37,6 +37,7 @@ set(PLUGIN_TESTS "e2p_test_plugin_ets_node_types compile.ets ${RUNTIME_MODE} c ${LIBRARY_PLUGIN}" "e2p_test_plugin_ets_varibles_and_types compile.ets ${RUNTIME_MODE} c ${LIBRARY_PLUGIN}" "e2p_test_plugin_change_func runtime_change_func_call.ets ${RUNTIME_MODE} cpp ${LIBRARY_PLUGIN}" + "e2p_test_plugin_recheck compile.ets ${COMPILE_MODE} c ${LIBRARY_PLUGIN}" "e2p_test_plugin compile.ets ${EXPECTED_MODE} c ${LIBRARY_PLUGIN}" "e2p_test_plugin_is compile.ets ${EXPECTED_MODE} c ${LIBRARY_PLUGIN}" "e2p_test_plugin_after_bind compile.ets ${EXPECTED_MODE} cpp ${LIBRARY_PLUGIN}" diff --git a/ets2panda/test/unit/plugin/e2p_test_plugin_recheck.c b/ets2panda/test/unit/plugin/e2p_test_plugin_recheck.c new file mode 100644 index 0000000000..15b4775e1d --- /dev/null +++ b/ets2panda/test/unit/plugin/e2p_test_plugin_recheck.c @@ -0,0 +1,42 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// No linting for pure C file +// NOLINTBEGIN + +#include +#include + +#include "public/es2panda_lib.h" + +static struct es2panda_Impl const *impl = NULL; + +void e2p_test_plugin_recheck_Initialize() +{ + impl = es2panda_GetImpl(ES2PANDA_LIB_VERSION); +} + +void e2p_test_plugin_recheck_AfterCheck(es2panda_Context *ctx) +{ + puts("Before recheck: "); + if (impl->ContextState(ctx) == ES2PANDA_STATE_ERROR) { + return; + } + es2panda_AstNode *ast = impl->ProgramAst(ctx, impl->ContextProgram(ctx)); + impl->AstNodeRecheck(ctx, ast); + puts("After recheck: "); +} + +// NOLINTEND \ No newline at end of file -- Gitee From aaee30ff6e96c3d9f45b28f1c1b9bb306f497d82 Mon Sep 17 00:00:00 2001 From: Viktoria Shirunova Date: Tue, 25 Mar 2025 21:03:44 +0300 Subject: [PATCH 149/268] URunner2: fix review notes Issue: https://gitee.com/openharmony/arkcompiler_runtime_core/issues/IBW9X1 Testing: All required pre-merge tests passed. Results are available in the ggwatcher. Signed-off-by: Viktoria Shirunova --- .../ets/{return_type inference.ets => return_type_inference.ets} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename ets2panda/test/runtime/ets/{return_type inference.ets => return_type_inference.ets} (100%) diff --git a/ets2panda/test/runtime/ets/return_type inference.ets b/ets2panda/test/runtime/ets/return_type_inference.ets similarity index 100% rename from ets2panda/test/runtime/ets/return_type inference.ets rename to ets2panda/test/runtime/ets/return_type_inference.ets -- Gitee From 9d71c8865120b63109165d0fbaf6204c9baaebff Mon Sep 17 00:00:00 2001 From: huyunhui1 Date: Fri, 7 Feb 2025 16:48:36 +0800 Subject: [PATCH 150/268] Memory Optimization Issue: https://gitee.com/openharmony/arkcompiler_runtime_core/issues/IBO35I Signed-off-by: huyunhui1 Change-Id: Ib340bbc068a5856fb0b28ecd357f1167a626c701 --- es2panda/compiler/core/emitter/emitter.cpp | 14 +- es2panda/compiler/core/emitter/emitter.h | 2 +- .../compiler/debugger/debuginfoDumper.cpp | 24 +-- es2panda/compiler/debugger/debuginfoDumper.h | 2 +- es2panda/compiler/templates/isa.h.erb | 41 ++-- es2panda/ir/irnode.h | 4 +- .../debugInfo/test-for-loop-expected.txt | 200 ------------------ .../test-local-variable-expected.txt | 34 --- es2panda/util/commonUtil.h | 8 +- es2panda/util/patchFix.cpp | 78 +++---- es2panda/util/patchFix.h | 6 +- merge_abc/src/assemblyDebugProto.cpp | 4 - merge_abc/src/assemblyFunctionProto.cpp | 4 +- merge_abc/src/assemblyInsProto.cpp | 50 +++-- merge_abc/src/assemblyInsProto.h | 4 +- 15 files changed, 107 insertions(+), 368 deletions(-) diff --git a/es2panda/compiler/core/emitter/emitter.cpp b/es2panda/compiler/core/emitter/emitter.cpp index 5f760e5a3e..463d078169 100644 --- a/es2panda/compiler/core/emitter/emitter.cpp +++ b/es2panda/compiler/core/emitter/emitter.cpp @@ -209,11 +209,6 @@ void FunctionEmitter::GenInstructionDebugInfo(const IRNode *ins, panda::pandasm: if (pg_->IsDebug()) { size_t insLen = GetIRNodeWholeLength(ins); - if (insLen != 0) { - pandaIns->ins_debug.bound_left = offset_; - pandaIns->ins_debug.bound_right = offset_ + insLen; - } - offset_ += insLen; pandaIns->ins_debug.column_number = columnNum; } @@ -455,10 +450,9 @@ void FunctionEmitter::GenFunctionInstructions() func_->ins.reserve(pg_->Insns().size()); for (const auto *ins : pg_->Insns()) { - auto &pandaIns = func_->ins.emplace_back(); - - ins->Transform(&pandaIns); - GenInstructionDebugInfo(ins, &pandaIns); + auto *pandaIns = ins->Transform(); + func_->ins.emplace_back(pandaIns); + GenInstructionDebugInfo(ins, pandaIns); } } @@ -1256,7 +1250,7 @@ void Emitter::DumpAsm(const panda::pandasm::Program *prog) ss << ") {" << std::endl; for (const auto &ins : func.ins) { - ss << (ins.set_label ? "" : "\t") << ins.ToString("", true, func.GetTotalRegs()) << std::endl; + ss << (ins->IsLabel() ? "" : "\t") << ins->ToString("", true, func.GetTotalRegs()) << std::endl; } ss << "}" << std::endl << std::endl; diff --git a/es2panda/compiler/core/emitter/emitter.h b/es2panda/compiler/core/emitter/emitter.h index f43cf2f36d..7353567fc5 100644 --- a/es2panda/compiler/core/emitter/emitter.h +++ b/es2panda/compiler/core/emitter/emitter.h @@ -34,7 +34,7 @@ namespace panda::pandasm { struct Program; struct Function; -struct Ins; +class Ins; struct Record; } // namespace panda::pandasm diff --git a/es2panda/compiler/debugger/debuginfoDumper.cpp b/es2panda/compiler/debugger/debuginfoDumper.cpp index 37d2beb5aa..5bbbd2b5d7 100644 --- a/es2panda/compiler/debugger/debuginfoDumper.cpp +++ b/es2panda/compiler/debugger/debuginfoDumper.cpp @@ -55,7 +55,7 @@ void DebugInfoDumper::WrapArray(const char *name, const std::vector &array, b for (elem = array.begin(); elem != array.end(); ++elem) { Indent(); // NOLINTNEXTLINE - if constexpr (std::is_same_v) { + if constexpr (std::is_same_v) { WriteIns(*elem); // NOLINTNEXTLINE } else if constexpr (std::is_same_v) { @@ -86,25 +86,19 @@ void DebugInfoDumper::WrapArray(const char *name, const std::vector &array, b ss_ << "]" << PutComma(comma); } -void DebugInfoDumper::WriteIns(const pandasm::Ins &ins) +void DebugInfoDumper::WriteIns(const pandasm::InsPtr &ins) { ss_ << "{"; - { - pandasm::Ins insCopy; - insCopy.opcode = ins.opcode; - insCopy.set_label = ins.set_label; - insCopy.label = ins.label; - WriteProperty("opcode", insCopy.ToString()); - } + WriteProperty("opcode", ins->OpcodeToString()); indent_++; - WrapArray("regs", ins.regs); - WrapArray("ids", ins.ids); - WrapArray("imms", ins.imms); + WrapArray("regs", ins->Regs()); + WrapArray("ids", ins->Ids()); + WrapArray("imms", ins->Imms()); ss_ << std::endl; Indent(); ss_ << "\"label\": " - << "\"" << ins.label << "\","; - WritePosInfo(ins.ins_debug); + << "\"" << (ins->IsLabel() ? ins->Label() : "") << "\","; + WritePosInfo(ins->ins_debug); indent_--; Indent(); ss_ << "}"; @@ -129,8 +123,6 @@ void DebugInfoDumper::WritePosInfo(const pandasm::debuginfo::Ins &posInfo) ss_ << std::endl; Indent(); ss_ << "\"debug_pos_info\": {"; - WriteProperty("boundLeft", posInfo.bound_left); - WriteProperty("boundRight", posInfo.bound_right); WriteProperty("sourceLineNum", static_cast(posInfo.line_number), false); Indent(); ss_ << "}" << std::endl; diff --git a/es2panda/compiler/debugger/debuginfoDumper.h b/es2panda/compiler/debugger/debuginfoDumper.h index a9d0aecf5a..02a6dfbbbf 100644 --- a/es2panda/compiler/debugger/debuginfoDumper.h +++ b/es2panda/compiler/debugger/debuginfoDumper.h @@ -36,7 +36,7 @@ public: private: template void WrapArray(const char *name, const std::vector &array, bool comma = true); - void WriteIns(const pandasm::Ins &ins); + void WriteIns(const pandasm::InsPtr &ins); void WriteMetaData(const std::vector &metaData); void WriteProperty(const char *key, const Value &value, bool comma = true); void WritePosInfo(const pandasm::debuginfo::Ins &posInfo); diff --git a/es2panda/compiler/templates/isa.h.erb b/es2panda/compiler/templates/isa.h.erb index 9d5137be16..eeaef9e919 100644 --- a/es2panda/compiler/templates/isa.h.erb +++ b/es2panda/compiler/templates/isa.h.erb @@ -57,11 +57,9 @@ public: return 0; } - void Transform(pandasm::Ins *ins) const override + pandasm::Ins *Transform() const override { - ins->opcode = pandasm::Opcode::INVALID; - ins->set_label = true; - ins->label = id_; + return new pandasm::LabelIns(id_); } ICSlot SetIcSlot(IcSizeType currentSlot) override @@ -236,30 +234,21 @@ public: return <%= reg_cnt %>; } - void Transform(pandasm::Ins* ins) const override + pandasm::Ins *Transform() const override { - ins->opcode = pandasm::Opcode::<%= node_kind %>; -% if op_map['reg'].length != 0 - ins->regs.reserve(<%= op_map['reg'].length %>); -% end -% if op_map['imm'].length != 0 - ins->imms.reserve(<%= op_map['imm'].length %>); -% end -% if op_map['str'].length + op_map['lbl'].length != 0 - ins->ids.reserve(<%= op_map['str'].length + op_map['lbl'].length %>); -% end -% for reg in op_map['reg'] - ins->regs.emplace_back(<%= reg %>); -% end -% for imm in op_map['imm'] - ins->imms.emplace_back(<%= imm %>); -% end -% for str in op_map['str'] - ins->ids.emplace_back(<%= str %>.Mutf8()); -% end -% for lbl in op_map['lbl'] - ins->ids.emplace_back(<%= lbl %>->Id()); +% pa_ins_args_list = Array.new +% ctor_arg_list.each do |arg| +% type = arg.split(" ")[0] +% name = arg.split(" ")[1] +% if type == "util::StringView" +% pa_ins_args_list.push("#{name}_.Mutf8()") +% elsif type == "Label*" +% pa_ins_args_list.push("#{name}_->Id()") +% else +% pa_ins_args_list.push("#{name}_") +% end % end + return new pandasm::<%= class_name %>(<%= pa_ins_args_list.join(", ") %>); } ICSlot SetIcSlot(IcSizeType slot) override diff --git a/es2panda/ir/irnode.h b/es2panda/ir/irnode.h index 576c50cbf3..bde613106d 100644 --- a/es2panda/ir/irnode.h +++ b/es2panda/ir/irnode.h @@ -33,7 +33,7 @@ class AstNode; } // namespace panda::es2panda::ir namespace panda::pandasm { -struct Ins; +class Ins; } // namespace panda::pandasm namespace panda::es2panda::compiler { @@ -120,7 +120,7 @@ public: virtual Formats GetFormats() const = 0; virtual size_t Registers([[maybe_unused]] std::array *regs) = 0; virtual size_t Registers([[maybe_unused]] std::array *regs) const = 0; - virtual void Transform(panda::pandasm::Ins *ins) const = 0; + virtual panda::pandasm::Ins *Transform() const = 0; virtual ICSlot SetIcSlot(IcSizeType currentSlot) = 0; virtual bool InlineCacheEnabled() = 0; virtual ICSlot GetIcSlot() = 0; diff --git a/es2panda/test/compiler/debugInfo/test-for-loop-expected.txt b/es2panda/test/compiler/debugInfo/test-for-loop-expected.txt index c581c730f7..1de3436539 100644 --- a/es2panda/test/compiler/debugInfo/test-for-loop-expected.txt +++ b/es2panda/test/compiler/debugInfo/test-for-loop-expected.txt @@ -21,8 +21,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 0, - "boundRight": 1, "sourceLineNum": -1 } }, @@ -36,8 +34,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 1, - "boundRight": 2, "sourceLineNum": -1 } }, @@ -51,8 +47,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 2, - "boundRight": 3, "sourceLineNum": -1 } }, @@ -65,8 +59,6 @@ ], "label": "", "debug_pos_info": { - "boundLeft": 3, - "boundRight": 8, "sourceLineNum": 15 } }, @@ -79,8 +71,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 8, - "boundRight": 10, "sourceLineNum": 15 } }, @@ -91,8 +81,6 @@ "imms": [], "label": "LABEL_2", "debug_pos_info": { - "boundLeft": 0, - "boundRight": 0, "sourceLineNum": 15 } }, @@ -105,8 +93,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 10, - "boundRight": 12, "sourceLineNum": 15 } }, @@ -119,8 +105,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 12, - "boundRight": 14, "sourceLineNum": 15 } }, @@ -133,8 +117,6 @@ ], "label": "", "debug_pos_info": { - "boundLeft": 14, - "boundRight": 19, "sourceLineNum": 15 } }, @@ -149,8 +131,6 @@ ], "label": "", "debug_pos_info": { - "boundLeft": 19, - "boundRight": 22, "sourceLineNum": 15 } }, @@ -163,8 +143,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 22, - "boundRight": 24, "sourceLineNum": 15 } }, @@ -177,8 +155,6 @@ ], "label": "", "debug_pos_info": { - "boundLeft": 24, - "boundRight": 29, "sourceLineNum": 16 } }, @@ -191,8 +167,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 29, - "boundRight": 31, "sourceLineNum": 16 } }, @@ -205,8 +179,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 31, - "boundRight": 34, "sourceLineNum": 17 } }, @@ -217,8 +189,6 @@ "imms": [], "label": "LABEL_1", "debug_pos_info": { - "boundLeft": 0, - "boundRight": 0, "sourceLineNum": 15 } }, @@ -231,8 +201,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 34, - "boundRight": 36, "sourceLineNum": 15 } }, @@ -245,8 +213,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 36, - "boundRight": 38, "sourceLineNum": 15 } }, @@ -259,8 +225,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 38, - "boundRight": 40, "sourceLineNum": 15 } }, @@ -273,8 +237,6 @@ ], "label": "", "debug_pos_info": { - "boundLeft": 40, - "boundRight": 42, "sourceLineNum": 15 } }, @@ -287,8 +249,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 42, - "boundRight": 44, "sourceLineNum": 15 } }, @@ -301,8 +261,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 44, - "boundRight": 46, "sourceLineNum": 15 } }, @@ -315,8 +273,6 @@ ], "label": "", "debug_pos_info": { - "boundLeft": 46, - "boundRight": 48, "sourceLineNum": 15 } }, @@ -329,8 +285,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 48, - "boundRight": 50, "sourceLineNum": 15 } }, @@ -343,8 +297,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 50, - "boundRight": 52, "sourceLineNum": 15 } }, @@ -357,8 +309,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 52, - "boundRight": 54, "sourceLineNum": 15 } }, @@ -369,8 +319,6 @@ "imms": [], "label": "LABEL_0", "debug_pos_info": { - "boundLeft": 0, - "boundRight": 0, "sourceLineNum": 15 } }, @@ -383,8 +331,6 @@ ], "label": "", "debug_pos_info": { - "boundLeft": 54, - "boundRight": 59, "sourceLineNum": 19 } }, @@ -399,8 +345,6 @@ ], "label": "", "debug_pos_info": { - "boundLeft": 59, - "boundRight": 64, "sourceLineNum": 19 } }, @@ -413,8 +357,6 @@ ], "label": "", "debug_pos_info": { - "boundLeft": 64, - "boundRight": 69, "sourceLineNum": 20 } }, @@ -427,8 +369,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 69, - "boundRight": 71, "sourceLineNum": 20 } }, @@ -439,8 +379,6 @@ "imms": [], "label": "LABEL_5", "debug_pos_info": { - "boundLeft": 0, - "boundRight": 0, "sourceLineNum": 20 } }, @@ -453,8 +391,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 71, - "boundRight": 73, "sourceLineNum": 20 } }, @@ -467,8 +403,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 73, - "boundRight": 75, "sourceLineNum": 20 } }, @@ -481,8 +415,6 @@ ], "label": "", "debug_pos_info": { - "boundLeft": 75, - "boundRight": 80, "sourceLineNum": 20 } }, @@ -497,8 +429,6 @@ ], "label": "", "debug_pos_info": { - "boundLeft": 80, - "boundRight": 83, "sourceLineNum": 20 } }, @@ -511,8 +441,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 83, - "boundRight": 85, "sourceLineNum": 20 } }, @@ -525,8 +453,6 @@ ], "label": "", "debug_pos_info": { - "boundLeft": 85, - "boundRight": 90, "sourceLineNum": 21 } }, @@ -539,8 +465,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 90, - "boundRight": 92, "sourceLineNum": 21 } }, @@ -555,8 +479,6 @@ ], "label": "", "debug_pos_info": { - "boundLeft": 92, - "boundRight": 96, "sourceLineNum": 22 } }, @@ -569,8 +491,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 96, - "boundRight": 98, "sourceLineNum": 22 } }, @@ -583,8 +503,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 98, - "boundRight": 100, "sourceLineNum": 22 } }, @@ -597,8 +515,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 100, - "boundRight": 102, "sourceLineNum": 22 } }, @@ -611,8 +527,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 102, - "boundRight": 104, "sourceLineNum": 22 } }, @@ -627,8 +541,6 @@ ], "label": "", "debug_pos_info": { - "boundLeft": 104, - "boundRight": 107, "sourceLineNum": 22 } }, @@ -639,8 +551,6 @@ "imms": [], "label": "LABEL_4", "debug_pos_info": { - "boundLeft": 0, - "boundRight": 0, "sourceLineNum": 19 } }, @@ -653,8 +563,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 107, - "boundRight": 109, "sourceLineNum": 20 } }, @@ -667,8 +575,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 109, - "boundRight": 111, "sourceLineNum": 20 } }, @@ -681,8 +587,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 111, - "boundRight": 113, "sourceLineNum": 20 } }, @@ -695,8 +599,6 @@ ], "label": "", "debug_pos_info": { - "boundLeft": 113, - "boundRight": 115, "sourceLineNum": 20 } }, @@ -709,8 +611,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 115, - "boundRight": 117, "sourceLineNum": 20 } }, @@ -723,8 +623,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 117, - "boundRight": 119, "sourceLineNum": 20 } }, @@ -737,8 +635,6 @@ ], "label": "", "debug_pos_info": { - "boundLeft": 119, - "boundRight": 121, "sourceLineNum": 20 } }, @@ -751,8 +647,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 121, - "boundRight": 123, "sourceLineNum": 20 } }, @@ -765,8 +659,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 123, - "boundRight": 125, "sourceLineNum": 20 } }, @@ -779,8 +671,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 125, - "boundRight": 127, "sourceLineNum": 20 } }, @@ -791,8 +681,6 @@ "imms": [], "label": "LABEL_3", "debug_pos_info": { - "boundLeft": 0, - "boundRight": 0, "sourceLineNum": 19 } }, @@ -805,8 +693,6 @@ ], "label": "", "debug_pos_info": { - "boundLeft": 127, - "boundRight": 132, "sourceLineNum": 24 } }, @@ -819,8 +705,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 132, - "boundRight": 134, "sourceLineNum": 24 } }, @@ -831,8 +715,6 @@ "imms": [], "label": "LABEL_8", "debug_pos_info": { - "boundLeft": 0, - "boundRight": 0, "sourceLineNum": 24 } }, @@ -845,8 +727,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 134, - "boundRight": 136, "sourceLineNum": 24 } }, @@ -859,8 +739,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 136, - "boundRight": 138, "sourceLineNum": 24 } }, @@ -873,8 +751,6 @@ ], "label": "", "debug_pos_info": { - "boundLeft": 138, - "boundRight": 143, "sourceLineNum": 24 } }, @@ -889,8 +765,6 @@ ], "label": "", "debug_pos_info": { - "boundLeft": 143, - "boundRight": 146, "sourceLineNum": 24 } }, @@ -903,8 +777,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 146, - "boundRight": 148, "sourceLineNum": 24 } }, @@ -917,8 +789,6 @@ ], "label": "", "debug_pos_info": { - "boundLeft": 148, - "boundRight": 153, "sourceLineNum": 25 } }, @@ -931,8 +801,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 153, - "boundRight": 155, "sourceLineNum": 25 } }, @@ -943,8 +811,6 @@ "imms": [], "label": "LABEL_11", "debug_pos_info": { - "boundLeft": 0, - "boundRight": 0, "sourceLineNum": 25 } }, @@ -957,8 +823,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 155, - "boundRight": 157, "sourceLineNum": 25 } }, @@ -971,8 +835,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 157, - "boundRight": 159, "sourceLineNum": 25 } }, @@ -985,8 +847,6 @@ ], "label": "", "debug_pos_info": { - "boundLeft": 159, - "boundRight": 164, "sourceLineNum": 25 } }, @@ -1001,8 +861,6 @@ ], "label": "", "debug_pos_info": { - "boundLeft": 164, - "boundRight": 167, "sourceLineNum": 25 } }, @@ -1015,8 +873,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 167, - "boundRight": 169, "sourceLineNum": 25 } }, @@ -1029,8 +885,6 @@ ], "label": "", "debug_pos_info": { - "boundLeft": 169, - "boundRight": 174, "sourceLineNum": 26 } }, @@ -1043,8 +897,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 174, - "boundRight": 176, "sourceLineNum": 26 } }, @@ -1055,8 +907,6 @@ "imms": [], "label": "LABEL_10", "debug_pos_info": { - "boundLeft": 0, - "boundRight": 0, "sourceLineNum": 24 } }, @@ -1069,8 +919,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 176, - "boundRight": 178, "sourceLineNum": 25 } }, @@ -1083,8 +931,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 178, - "boundRight": 180, "sourceLineNum": 25 } }, @@ -1097,8 +943,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 180, - "boundRight": 182, "sourceLineNum": 25 } }, @@ -1111,8 +955,6 @@ ], "label": "", "debug_pos_info": { - "boundLeft": 182, - "boundRight": 184, "sourceLineNum": 25 } }, @@ -1125,8 +967,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 184, - "boundRight": 186, "sourceLineNum": 25 } }, @@ -1139,8 +979,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 186, - "boundRight": 188, "sourceLineNum": 25 } }, @@ -1153,8 +991,6 @@ ], "label": "", "debug_pos_info": { - "boundLeft": 188, - "boundRight": 190, "sourceLineNum": 25 } }, @@ -1167,8 +1003,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 190, - "boundRight": 192, "sourceLineNum": 25 } }, @@ -1181,8 +1015,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 192, - "boundRight": 194, "sourceLineNum": 25 } }, @@ -1195,8 +1027,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 194, - "boundRight": 196, "sourceLineNum": 25 } }, @@ -1207,8 +1037,6 @@ "imms": [], "label": "LABEL_9", "debug_pos_info": { - "boundLeft": 0, - "boundRight": 0, "sourceLineNum": 24 } }, @@ -1219,8 +1047,6 @@ "imms": [], "label": "LABEL_7", "debug_pos_info": { - "boundLeft": 0, - "boundRight": 0, "sourceLineNum": 19 } }, @@ -1233,8 +1059,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 196, - "boundRight": 198, "sourceLineNum": 24 } }, @@ -1247,8 +1071,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 198, - "boundRight": 200, "sourceLineNum": 24 } }, @@ -1261,8 +1083,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 200, - "boundRight": 202, "sourceLineNum": 24 } }, @@ -1275,8 +1095,6 @@ ], "label": "", "debug_pos_info": { - "boundLeft": 202, - "boundRight": 204, "sourceLineNum": 24 } }, @@ -1289,8 +1107,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 204, - "boundRight": 206, "sourceLineNum": 24 } }, @@ -1303,8 +1119,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 206, - "boundRight": 208, "sourceLineNum": 24 } }, @@ -1317,8 +1131,6 @@ ], "label": "", "debug_pos_info": { - "boundLeft": 208, - "boundRight": 210, "sourceLineNum": 24 } }, @@ -1331,8 +1143,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 210, - "boundRight": 212, "sourceLineNum": 24 } }, @@ -1345,8 +1155,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 212, - "boundRight": 214, "sourceLineNum": 24 } }, @@ -1359,8 +1167,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 214, - "boundRight": 216, "sourceLineNum": 24 } }, @@ -1371,8 +1177,6 @@ "imms": [], "label": "LABEL_6", "debug_pos_info": { - "boundLeft": 0, - "boundRight": 0, "sourceLineNum": 19 } }, @@ -1383,8 +1187,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 0, - "boundRight": 0, "sourceLineNum": -1 } }, @@ -1395,8 +1197,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 0, - "boundRight": 0, "sourceLineNum": -1 } } diff --git a/es2panda/test/compiler/debugInfo/test-local-variable-expected.txt b/es2panda/test/compiler/debugInfo/test-local-variable-expected.txt index 90556498d0..be4b8491f7 100644 --- a/es2panda/test/compiler/debugInfo/test-local-variable-expected.txt +++ b/es2panda/test/compiler/debugInfo/test-local-variable-expected.txt @@ -21,8 +21,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 0, - "boundRight": 1, "sourceLineNum": -1 } }, @@ -36,8 +34,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 1, - "boundRight": 2, "sourceLineNum": -1 } }, @@ -51,8 +47,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 2, - "boundRight": 3, "sourceLineNum": -1 } }, @@ -65,8 +59,6 @@ ], "label": "", "debug_pos_info": { - "boundLeft": 3, - "boundRight": 8, "sourceLineNum": 15 } }, @@ -81,8 +73,6 @@ ], "label": "", "debug_pos_info": { - "boundLeft": 8, - "boundRight": 13, "sourceLineNum": 15 } }, @@ -95,8 +85,6 @@ ], "label": "", "debug_pos_info": { - "boundLeft": 13, - "boundRight": 18, "sourceLineNum": 17 } }, @@ -109,8 +97,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 18, - "boundRight": 20, "sourceLineNum": 17 } }, @@ -123,8 +109,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 20, - "boundRight": 23, "sourceLineNum": 18 } }, @@ -137,8 +121,6 @@ ], "label": "", "debug_pos_info": { - "boundLeft": 23, - "boundRight": 28, "sourceLineNum": 22 } }, @@ -151,8 +133,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 28, - "boundRight": 30, "sourceLineNum": 22 } }, @@ -165,8 +145,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 30, - "boundRight": 33, "sourceLineNum": 23 } }, @@ -179,8 +157,6 @@ ], "label": "", "debug_pos_info": { - "boundLeft": 33, - "boundRight": 38, "sourceLineNum": 25 } }, @@ -193,8 +169,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 38, - "boundRight": 40, "sourceLineNum": 25 } }, @@ -207,8 +181,6 @@ ], "label": "", "debug_pos_info": { - "boundLeft": 40, - "boundRight": 45, "sourceLineNum": 27 } }, @@ -221,8 +193,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 45, - "boundRight": 47, "sourceLineNum": 27 } }, @@ -233,8 +203,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 0, - "boundRight": 0, "sourceLineNum": -1 } }, @@ -245,8 +213,6 @@ "imms": [], "label": "", "debug_pos_info": { - "boundLeft": 0, - "boundRight": 0, "sourceLineNum": -1 } } diff --git a/es2panda/util/commonUtil.h b/es2panda/util/commonUtil.h index f63afffa7d..6d91fdb41e 100644 --- a/es2panda/util/commonUtil.h +++ b/es2panda/util/commonUtil.h @@ -104,15 +104,15 @@ void VisitDyanmicImports(ConstReferenceIf function, // The dynamicimport bytecode should not have label, otherwise the dyanmicimport might be a jump // target and its parameter is a variable instead of a constant string expression (Check // AbcCodeProcessor::AddJumpLabels for more details). - if (iter->opcode != pandasm::Opcode::DYNAMICIMPORT || iter->set_label) { + if ((*iter)->opcode != pandasm::Opcode::DYNAMICIMPORT || (*iter)->IsLabel()) { continue; } auto prevIns = iter - 1; - if (prevIns->opcode != pandasm::Opcode::LDA_STR) { + if ((*prevIns)->opcode != pandasm::Opcode::LDA_STR) { continue; } - ASSERT(prevIns->ids.size() == 1); - cb(prevIns->ids[0]); // 0: index of the string in lda.str bytecode + ASSERT((*prevIns)->Ids().size() == 1); + cb((*prevIns)->GetId(0)); // 0: index of the string in lda.str bytecode } } } // namespace panda::es2panda::util diff --git a/es2panda/util/patchFix.cpp b/es2panda/util/patchFix.cpp index e7c0dd5646..4a05c01108 100644 --- a/es2panda/util/patchFix.cpp +++ b/es2panda/util/patchFix.cpp @@ -176,18 +176,18 @@ std::vector> PatchFix::GenerateFunctionAndCl ss << ") {" << std::endl; for (const auto &ins : func->ins) { - ss << (ins.set_label ? "" : "\t") << ins.ToString("", true, func->GetTotalRegs()) << " "; - if (ins.opcode == panda::pandasm::Opcode::CREATEARRAYWITHBUFFER || - ins.opcode == panda::pandasm::Opcode::CREATEOBJECTWITHBUFFER) { - int64_t bufferIdx = GetLiteralIdxFromStringId(ins.ids[0]); + ss << (ins->IsLabel() ? "" : "\t") << ins->ToString("", true, func->GetTotalRegs()) << " "; + if (ins->opcode == panda::pandasm::Opcode::CREATEARRAYWITHBUFFER || + ins->opcode == panda::pandasm::Opcode::CREATEOBJECTWITHBUFFER) { + int64_t bufferIdx = GetLiteralIdxFromStringId(ins->GetId(0)); ss << ExpandLiteral(bufferIdx, literalBuffers) << " "; - } else if (ins.opcode == panda::pandasm::Opcode::DEFINECLASSWITHBUFFER) { - CollectFunctionsWithDefinedClasses(func->name, ins.ids[0]); - int64_t bufferIdx = GetLiteralIdxFromStringId(ins.ids[1]); + } else if (ins->opcode == panda::pandasm::Opcode::DEFINECLASSWITHBUFFER) { + CollectFunctionsWithDefinedClasses(func->name, ins->GetId(0)); + int64_t bufferIdx = GetLiteralIdxFromStringId(ins->GetId(1)); std::string literalStr = ExpandLiteral(bufferIdx, literalBuffers); auto classHash = Helpers::GetHashString(literalStr); - hashList.push_back(std::pair(ins.ids[0], classHash)); - CollectClassMemberFunctions(ins.ids[0], bufferIdx, literalBuffers); + hashList.push_back(std::pair(ins->GetId(0), classHash)); + CollectClassMemberFunctions(ins->GetId(0), bufferIdx, literalBuffers); } ss << " "; } @@ -319,27 +319,27 @@ uint32_t PatchFix::GetPatchLexicalIdx(const std::string &variableName) return topScopeLexEnvs_[variableName]; } -bool IsFunctionOrClassDefineIns(panda::pandasm::Ins &ins) +bool IsFunctionOrClassDefineIns(panda::pandasm::Ins *ins) { - if (ins.opcode == panda::pandasm::Opcode::DEFINEMETHOD || - ins.opcode == panda::pandasm::Opcode::DEFINEFUNC || - ins.opcode == panda::pandasm::Opcode::DEFINECLASSWITHBUFFER) { + if (ins->opcode == panda::pandasm::Opcode::DEFINEMETHOD || + ins->opcode == panda::pandasm::Opcode::DEFINEFUNC || + ins->opcode == panda::pandasm::Opcode::DEFINECLASSWITHBUFFER) { return true; } return false; } -bool IsStPatchVarIns(panda::pandasm::Ins &ins) +bool IsStPatchVarIns(panda::pandasm::Ins *ins) { - return ins.opcode == panda::pandasm::Opcode::WIDE_STPATCHVAR; + return ins->opcode == panda::pandasm::Opcode::WIDE_STPATCHVAR; } void PatchFix::CollectFuncDefineIns(panda::pandasm::Function *func) { for (size_t i = 0; i < func->ins.size(); ++i) { - if (IsFunctionOrClassDefineIns(func->ins[i])) { - funcDefineIns_.push_back(func->ins[i]); // push define ins - funcDefineIns_.push_back(func->ins[i + 1]); // push store ins + if (IsFunctionOrClassDefineIns(func->ins[i].get())) { + funcDefineIns_.push_back(func->ins[i].get()); // push define ins + funcDefineIns_.push_back(func->ins[i + 1].get()); // push store ins } } } @@ -377,31 +377,23 @@ void PatchFix::HandleModifiedDefinedClassFunc(panda::pandasm::Program *prog) } } -void PatchFix::AddHeadAndTailInsForPatchFuncMain0(std::vector &ins) +void PatchFix::AddHeadAndTailInsForPatchFuncMain0(std::vector &ins) { - panda::pandasm::Ins returnUndefine; - returnUndefine.opcode = pandasm::Opcode::RETURNUNDEFINED; - + auto returnUndefined = new pandasm::Returnundefined(); if (ins.size() == 0) { - ins.push_back(returnUndefine); + ins.emplace_back(returnUndefined); return; } - panda::pandasm::Ins newLexenv; - newLexenv.opcode = pandasm::Opcode::NEWLEXENV; - newLexenv.imms.reserve(1); - auto newFuncNum = long(ins.size() / 2); // each new function has 2 ins: define and store - newLexenv.imms.emplace_back(newFuncNum); - - ins.insert(ins.begin(), newLexenv); - ins.push_back(returnUndefine); + auto newLexenv = new pandasm::Newlexenv(long(ins.size() / 2)); // each new function has 2 ins: define and stor + ins.emplace(ins.begin(), newLexenv); + ins.emplace_back(returnUndefined); } -void PatchFix::AddTailInsForPatchFuncMain1(std::vector &ins) +void PatchFix::AddTailInsForPatchFuncMain1(std::vector &ins) { - panda::pandasm::Ins returnUndefined; - returnUndefined.opcode = pandasm::Opcode::RETURNUNDEFINED; - ins.push_back(returnUndefined); + auto returnUndefined = new pandasm::Returnundefined(); + ins.emplace_back(returnUndefined); } void PatchFix::CreateFunctionPatchMain0AndMain1(panda::pandasm::Function &patchFuncMain0, @@ -415,19 +407,19 @@ void PatchFix::CreateFunctionPatchMain0AndMain1(panda::pandasm::Function &patchF patchFuncMain1.params.emplace_back(panda::pandasm::Type("any", 0), patchFuncMain1.language); } - std::vector patchMain0DefineIns; - std::vector patchMain1DefineIns; + std::vector patchMain0DefineIns; + std::vector patchMain1DefineIns; for (size_t i = 0; i < funcDefineIns_.size(); ++i) { if (IsFunctionOrClassDefineIns(funcDefineIns_[i])) { - auto &name = funcDefineIns_[i].ids[0]; + auto name = funcDefineIns_[i]->GetId(0); if (newFuncNames_.count(name) && IsStPatchVarIns(funcDefineIns_[i + 1])) { - patchMain0DefineIns.push_back(funcDefineIns_[i]); - patchMain0DefineIns.push_back(funcDefineIns_[i + 1]); + patchMain0DefineIns.emplace_back(funcDefineIns_[i]->DeepCopy()); + patchMain0DefineIns.emplace_back(funcDefineIns_[i + 1]->DeepCopy()); continue; } if (patchFuncNames_.count(name) || modifiedClassNames_.count(name)) { - patchMain1DefineIns.push_back(funcDefineIns_[i]); + patchMain1DefineIns.emplace_back(funcDefineIns_[i]->DeepCopy()); continue; } } @@ -436,8 +428,8 @@ void PatchFix::CreateFunctionPatchMain0AndMain1(panda::pandasm::Function &patchF AddHeadAndTailInsForPatchFuncMain0(patchMain0DefineIns); AddTailInsForPatchFuncMain1(patchMain1DefineIns); - patchFuncMain0.ins = patchMain0DefineIns; - patchFuncMain1.ins = patchMain1DefineIns; + patchFuncMain0.ins = std::move(patchMain0DefineIns); + patchFuncMain1.ins = std::move(patchMain1DefineIns); patchFuncMain0.return_type = panda::pandasm::Type("any", 0); patchFuncMain1.return_type = panda::pandasm::Type("any", 0); diff --git a/es2panda/util/patchFix.h b/es2panda/util/patchFix.h index 1802233e0e..db26b4a25e 100644 --- a/es2panda/util/patchFix.h +++ b/es2panda/util/patchFix.h @@ -99,8 +99,8 @@ private: std::string ExpandLiteral(int64_t bufferIdx, LiteralBuffers &literalBuffers); std::string ConvertLiteralToString(std::vector &literalBuffer); void CollectFuncDefineIns(panda::pandasm::Function *func); - void AddHeadAndTailInsForPatchFuncMain0(std::vector &ins); - void AddTailInsForPatchFuncMain1(std::vector &ins); + void AddHeadAndTailInsForPatchFuncMain0(std::vector &ins); + void AddTailInsForPatchFuncMain1(std::vector &ins); void CreateFunctionPatchMain0AndMain1(panda::pandasm::Function &patchFuncMain0, panda::pandasm::Function &patchFuncMain1); bool IsAnonymousOrSpecialOrDuplicateFunction(const std::string &funcName); @@ -135,7 +135,7 @@ private: ArenaUnorderedMap topScopeLexEnvs_; ArenaSet patchFuncNames_; ArenaSet newFuncNames_; - ArenaVector funcDefineIns_; + ArenaVector funcDefineIns_; ArenaSet modifiedClassNames_; ArenaUnorderedMap> classMemberFunctions_; ArenaUnorderedMap> funcDefinedClasses_; diff --git a/merge_abc/src/assemblyDebugProto.cpp b/merge_abc/src/assemblyDebugProto.cpp index 5fad0e562a..0be9fbf1f4 100644 --- a/merge_abc/src/assemblyDebugProto.cpp +++ b/merge_abc/src/assemblyDebugProto.cpp @@ -20,16 +20,12 @@ void DebuginfoIns::Serialize(const panda::pandasm::debuginfo::Ins &debug, protoP { protoDebug.set_linenumber(debug.line_number); protoDebug.set_columnnumber(debug.column_number); - protoDebug.set_boundleft(debug.bound_left); - protoDebug.set_boundright(debug.bound_right); } void DebuginfoIns::Deserialize(const protoPanda::DebuginfoIns &protoDebug, panda::pandasm::debuginfo::Ins &debug) { debug.line_number = protoDebug.linenumber(); debug.column_number = protoDebug.columnnumber(); - debug.bound_left = protoDebug.boundleft(); - debug.bound_right = protoDebug.boundright(); } void LocalVariable::Serialize(const panda::pandasm::debuginfo::LocalVariable &debug, diff --git a/merge_abc/src/assemblyFunctionProto.cpp b/merge_abc/src/assemblyFunctionProto.cpp index fe40351bb6..522437ad13 100644 --- a/merge_abc/src/assemblyFunctionProto.cpp +++ b/merge_abc/src/assemblyFunctionProto.cpp @@ -122,9 +122,9 @@ void Function::DeserializeProtoIns(const protoPanda::Function &protoFunction, pa { function.ins.reserve(protoFunction.ins_size()); for (const auto &protoIns : protoFunction.ins()) { - panda::pandasm::Ins ins; + panda::pandasm::Ins *ins {nullptr}; Ins::Deserialize(protoIns, ins); - function.ins.emplace_back(std::move(ins)); + function.ins.emplace_back(ins); } } diff --git a/merge_abc/src/assemblyInsProto.cpp b/merge_abc/src/assemblyInsProto.cpp index c1016ef04a..fe322bba7f 100644 --- a/merge_abc/src/assemblyInsProto.cpp +++ b/merge_abc/src/assemblyInsProto.cpp @@ -16,16 +16,16 @@ #include "assemblyInsProto.h" namespace panda::proto { -void Ins::Serialize(const panda::pandasm::Ins &insn, protoPanda::Ins &protoInsn) +void Ins::Serialize(const panda::pandasm::InsPtr &insn, protoPanda::Ins &protoInsn) { - protoInsn.set_opcode(static_cast(insn.opcode)); - for (const auto ® : insn.regs) { + protoInsn.set_opcode(static_cast(insn->opcode)); + for (const auto ® : insn->Regs()) { protoInsn.add_regs(static_cast(reg)); } - for (const auto &str : insn.ids) { + for (const auto &str : insn->Ids()) { protoInsn.add_ids(str); } - for (const auto &imm : insn.imms) { + for (const auto &imm : insn->Imms()) { auto *protoImm = protoInsn.add_imms(); switch (static_cast(imm.index() + 1)) { // 1: enum TypeCase start from 1 case protoPanda::Ins_IType::kValueInt: @@ -38,41 +38,51 @@ void Ins::Serialize(const panda::pandasm::Ins &insn, protoPanda::Ins &protoInsn) UNREACHABLE(); } } - protoInsn.set_label(insn.label); - protoInsn.set_setlabelval(insn.set_label); + protoInsn.set_label(insn->IsLabel() ? insn->Label() : ""); + protoInsn.set_setlabelval(insn->IsLabel()); auto *protoDebug = protoInsn.mutable_insdebug(); - DebuginfoIns::Serialize(insn.ins_debug, *protoDebug); + DebuginfoIns::Serialize(insn->ins_debug, *protoDebug); } -void Ins::Deserialize(const protoPanda::Ins &protoInsn, panda::pandasm::Ins &insn) +void Ins::Deserialize(const protoPanda::Ins &protoInsn, panda::pandasm::Ins *&insn) { - insn.opcode = static_cast(protoInsn.opcode()); - insn.regs.reserve(protoInsn.regs_size()); + auto opcode = static_cast(protoInsn.opcode()); + std::vector regs; + regs.reserve(protoInsn.regs_size()); for (const auto &protoReg : protoInsn.regs()) { - insn.regs.push_back(static_cast(protoReg)); + regs.push_back(static_cast(protoReg)); } - insn.ids.reserve(protoInsn.ids_size()); + std::vector ids; + ids.reserve(protoInsn.ids_size()); for (const auto &protoId : protoInsn.ids()) { - insn.ids.push_back(protoId); + ids.push_back(protoId); } - insn.imms.reserve(protoInsn.imms_size()); + std::vector imms; + imms.reserve(protoInsn.imms_size()); for (const auto &protoImm : protoInsn.imms()) { switch (protoImm.type_case()) { case protoPanda::Ins_IType::kValueInt: { - insn.imms.push_back(protoImm.valueint()); + imms.push_back(protoImm.valueint()); break; } case protoPanda::Ins_IType::kValueDouble: { - insn.imms.push_back(protoImm.valuedouble()); + imms.push_back(protoImm.valuedouble()); break; } default: UNREACHABLE(); } } - insn.label = protoInsn.label(); - insn.set_label = protoInsn.setlabelval(); + + auto set_label = protoInsn.setlabelval(); + if (set_label) { + auto label = protoInsn.label(); + insn = new pandasm::LabelIns(label); + } else { + insn = pandasm::Ins::CreateIns(opcode, regs, imms, ids); + } + const protoPanda::DebuginfoIns &protoDebugInfoIns = protoInsn.insdebug(); - DebuginfoIns::Deserialize(protoDebugInfoIns, insn.ins_debug); + DebuginfoIns::Deserialize(protoDebugInfoIns, insn->ins_debug); } } // panda::proto diff --git a/merge_abc/src/assemblyInsProto.h b/merge_abc/src/assemblyInsProto.h index 05053d5dec..3daeb45353 100644 --- a/merge_abc/src/assemblyInsProto.h +++ b/merge_abc/src/assemblyInsProto.h @@ -23,8 +23,8 @@ namespace panda::proto { class Ins { public: - static void Serialize(const panda::pandasm::Ins &insn, protoPanda::Ins &protoInsn); - static void Deserialize(const protoPanda::Ins &protoInsn, panda::pandasm::Ins &insn); + static void Serialize(const panda::pandasm::InsPtr &insn, protoPanda::Ins &protoInsn); + static void Deserialize(const protoPanda::Ins &protoInsn, panda::pandasm::Ins *&insn); }; } // panda::proto #endif -- Gitee From 79e3aadea98a74f539b4157dae5d1ce39cf579ad Mon Sep 17 00:00:00 2001 From: zhangzezhong Date: Wed, 9 Apr 2025 15:54:08 +0800 Subject: [PATCH 151/268] =?UTF-8?q?=E3=80=90=E6=B7=B7=E6=B7=86=E3=80=91?= =?UTF-8?q?=E9=80=82=E9=85=8DarkUl@Intent=E8=A3=85=E9=A5=B0=E5=99=A8=20add?= =?UTF-8?q?=20arkUIKeepInfo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBZRVO Signed-off-by: zhangzezhong --- arkguard/src/ArkObfuscator.ts | 3 +- arkguard/src/initialization/ConfigResolver.ts | 7 +++- .../rename/RenameIdentifierTransformer.ts | 3 ++ arkguard/src/utils/CommonCollections.ts | 10 ++++++ arkguard/src/utils/ProjectCollections.ts | 30 ++++++++++++++++- .../test/ut/utils/ProjectCollections.spec.ts | 24 +++++++++++++- .../fileWhiteLists_expected01.json | 22 +++++++++++-- .../fileWhiteLists_expected02.json | 26 +++++++++++++-- .../fileWhiteLists_expected03.json | 32 ++++++++++++++++--- .../projectWhiteList_expected01.json | 2 ++ .../projectWhiteList_expected02.json | 8 +++-- 11 files changed, 151 insertions(+), 16 deletions(-) diff --git a/arkguard/src/ArkObfuscator.ts b/arkguard/src/ArkObfuscator.ts index 90820b662b..087ff1dfda 100644 --- a/arkguard/src/ArkObfuscator.ts +++ b/arkguard/src/ArkObfuscator.ts @@ -35,7 +35,7 @@ import type { import path from 'path'; -import { AtKeepCollections, LocalVariableCollections, PropCollections } from './utils/CommonCollections'; +import { AtIntentCollections, AtKeepCollections, LocalVariableCollections, PropCollections } from './utils/CommonCollections'; import type { IOptions } from './configs/IOptions'; import { FileUtils } from './utils/FileUtils'; import { TransformerManager } from './transformers/TransformerManager'; @@ -169,6 +169,7 @@ export function clearGlobalCaches(): void { UnobfuscationCollections.clear(); LocalVariableCollections.clear(); AtKeepCollections.clear(); + AtIntentCollections.clear(); renameFileNameModule.clearCaches(); clearUnobfuscationNamesObj(); clearHistoryUnobfuscatedMap(); diff --git a/arkguard/src/initialization/ConfigResolver.ts b/arkguard/src/initialization/ConfigResolver.ts index 88d526312e..da447bae2b 100644 --- a/arkguard/src/initialization/ConfigResolver.ts +++ b/arkguard/src/initialization/ConfigResolver.ts @@ -37,7 +37,7 @@ import { import { isDebug, isFileExist, sortAndDeduplicateStringArr, mergeSet, convertSetToArray } from './utils'; import { nameCacheMap, yellow, unobfuscationNamesObj } from './CommonObject'; import { clearHistoryUnobfuscatedMap, historyAllUnobfuscatedNamesMap, historyUnobfuscatedPropMap } from './Initializer'; -import { AtKeepCollections, LocalVariableCollections, UnobfuscationCollections } from '../utils/CommonCollections'; +import { AtIntentCollections, AtKeepCollections, LocalVariableCollections, UnobfuscationCollections } from '../utils/CommonCollections'; import { INameObfuscationOption } from '../configs/INameObfuscationOption'; import { WhitelistType } from '../utils/TransformUtil'; import { endFilesEvent, startFilesEvent } from '../utils/PrinterUtils'; @@ -1211,6 +1211,11 @@ export function printWhitelist(obfuscationOptions: ObOptions, nameOptions: IName whitelistObj.conf.push(...atKeepSet); } + let atIndentSet: Set = new Set(); + addToSet(atIndentSet, AtIntentCollections.propertyNames); + addToSet(atIndentSet, AtIntentCollections.globalNames); + whitelistObj.conf.push(...atIndentSet); + let enumSet: Set; if (enableProperty) { enumSet = UnobfuscationCollections.reservedEnum; diff --git a/arkguard/src/transformers/rename/RenameIdentifierTransformer.ts b/arkguard/src/transformers/rename/RenameIdentifierTransformer.ts index 53c45994d4..76e8656595 100644 --- a/arkguard/src/transformers/rename/RenameIdentifierTransformer.ts +++ b/arkguard/src/transformers/rename/RenameIdentifierTransformer.ts @@ -104,6 +104,7 @@ import { endSingleFileEvent, startSingleFileEvent } from '../../utils/PrinterUti import { EventList, endSingleFileForMoreTimeEvent, startSingleFileForMoreTimeEvent } from '../../utils/PrinterTimeAndMemUtils'; import { isViewPUBasedClass } from '../../utils/OhsUtil'; import { + AtIntentCollections, AtKeepCollections, LocalVariableCollections, PropCollections, @@ -849,6 +850,7 @@ namespace secharmony { PropCollections.globalMangledNamesInCache = new Set(PropCollections.historyMangledTable?.values()); addToSet(PropCollections.reservedProperties, AtKeepCollections.keepSymbol.propertyNames); addToSet(PropCollections.reservedProperties, AtKeepCollections.keepAsConsumer.propertyNames); + addToSet(PropCollections.reservedProperties, AtIntentCollections.propertyNames); if (profile?.mUniversalReservedProperties) { PropCollections.universalReservedProperties = [...profile.mUniversalReservedProperties]; @@ -867,6 +869,7 @@ namespace secharmony { profile?.mReservedToplevelNames?.forEach(item => PropCollections.reservedProperties.add(item)); addToSet(PropCollections.reservedProperties, AtKeepCollections.keepSymbol.globalNames); addToSet(PropCollections.reservedProperties, AtKeepCollections.keepAsConsumer.globalNames); + addToSet(PropCollections.reservedProperties, AtIntentCollections.globalNames); profile?.mUniversalReservedToplevelNames?.forEach(item => PropCollections.universalReservedProperties.push(item)); isInitializedReservedList = true; } diff --git a/arkguard/src/utils/CommonCollections.ts b/arkguard/src/utils/CommonCollections.ts index 1db093f1eb..3cf9f0aace 100644 --- a/arkguard/src/utils/CommonCollections.ts +++ b/arkguard/src/utils/CommonCollections.ts @@ -104,4 +104,14 @@ export namespace AtKeepCollections { keepAsConsumer.globalNames.clear(); keepAsConsumer.propertyNames.clear(); }; +} + +export namespace AtIntentCollections{ + export let propertyNames: Set = new Set(); + export let globalNames: Set = new Set(); + + export function clear(): void{ + propertyNames.clear(); + globalNames.clear(); + } } \ No newline at end of file diff --git a/arkguard/src/utils/ProjectCollections.ts b/arkguard/src/utils/ProjectCollections.ts index 62071f3388..ec155c1e59 100644 --- a/arkguard/src/utils/ProjectCollections.ts +++ b/arkguard/src/utils/ProjectCollections.ts @@ -15,7 +15,7 @@ import { ApiExtractor } from '../common/ApiExtractor'; import { FileUtils } from './FileUtils'; -import { AtKeepCollections, UnobfuscationCollections } from './CommonCollections'; +import { AtIntentCollections, AtKeepCollections, UnobfuscationCollections } from './CommonCollections'; import * as crypto from 'crypto'; import * as ts from 'typescript'; import fs from 'fs'; @@ -111,6 +111,9 @@ export interface FileContent { * │ │ └── globalNames: Set * │ ├── enumProperties: Set * │ └── stringProperties: Set + * │ └── arkUIKeepInfo: KeepInfo + * │ ├── propertyNames: Set + * │ └── globalNames: Set * └── fileReservedInfo: FileReservedInfo * ├── enumProperties: Set * └── propertyParams: Set @@ -122,6 +125,7 @@ export interface FileKeepInfo { exported: KeepInfo; // Exported names and properties. enumProperties: Set; // Enum properties. stringProperties: Set; // String properties. + arkUIKeepInfo: KeepInfo; // Collecting classes and members } export interface FileReservedInfo { @@ -241,6 +245,10 @@ export class ProjectWhiteListManager { }, enumProperties: new Set(), stringProperties: new Set(), + arkUIKeepInfo: { + propertyNames: new Set(), + globalNames: new Set(), + }, }; } @@ -311,6 +319,10 @@ export class ProjectWhiteListManager { }, enumProperties: arrayToSet(parsed[key].fileKeepInfo.enumProperties), stringProperties: arrayToSet(parsed[key].fileKeepInfo.stringProperties), + arkUIKeepInfo: { + propertyNames: arrayToSet(parsed[key].fileKeepInfo.arkUIKeepInfo.propertyNames), + globalNames: arrayToSet(parsed[key].fileKeepInfo.arkUIKeepInfo.globalNames), + }, }; const fileReservedInfo: FileReservedInfo = { @@ -349,6 +361,10 @@ export class ProjectWhiteListManager { }, enumProperties: setToArray(value.fileKeepInfo.enumProperties), stringProperties: setToArray(value.fileKeepInfo.stringProperties), + arkUIKeepInfo: { + propertyNames: setToArray(value.fileKeepInfo.arkUIKeepInfo.propertyNames), + globalNames: setToArray(value.fileKeepInfo.arkUIKeepInfo.globalNames), + }, }, fileReservedInfo: { enumProperties: setToArray(value.fileReservedInfo.enumProperties), @@ -462,6 +478,16 @@ export class ProjectWhiteListManager { projectKeepInfo.propertyNames.add(propertyName); }); + // Collect arkUIKeepInfo + fileWhiteList.fileKeepInfo.arkUIKeepInfo.globalNames.forEach((globalName) => { + projectKeepInfo.globalNames.add(globalName); + AtIntentCollections.globalNames.add(globalName); + }); + fileWhiteList.fileKeepInfo.arkUIKeepInfo.propertyNames.forEach((propertyName) => { + projectKeepInfo.propertyNames.add(propertyName); + AtIntentCollections.propertyNames.add(propertyName); + }); + // 2. Collect fileReservedInfo // Collect enumProperties fileWhiteList.fileReservedInfo.enumProperties.forEach((enumPropertyName) => { @@ -515,6 +541,8 @@ export class ProjectWhiteListManager { addToSet(UnobfuscationCollections.reservedExportName, fileWhiteList.fileKeepInfo.exported.globalNames); addToSet(UnobfuscationCollections.reservedExportNameAndProp, fileWhiteList.fileKeepInfo.exported.propertyNames); addToSet(UnobfuscationCollections.reservedStrProp, fileWhiteList.fileKeepInfo.stringProperties); + addToSet(AtIntentCollections.propertyNames, fileWhiteList.fileKeepInfo.arkUIKeepInfo.propertyNames); + addToSet(AtIntentCollections.globalNames, fileWhiteList.fileKeepInfo.arkUIKeepInfo.globalNames); addToSet(ApiExtractor.mConstructorPropertySet, fileWhiteList.fileReservedInfo.propertyParams); addToSet(ApiExtractor.mEnumMemberSet, fileWhiteList.fileReservedInfo.enumProperties); }); diff --git a/arkguard/test/ut/utils/ProjectCollections.spec.ts b/arkguard/test/ut/utils/ProjectCollections.spec.ts index f1f6dcd6b3..fc121436aa 100644 --- a/arkguard/test/ut/utils/ProjectCollections.spec.ts +++ b/arkguard/test/ut/utils/ProjectCollections.spec.ts @@ -26,7 +26,7 @@ import { FileWhiteList, FileContent } from '../../../src/utils/ProjectCollections'; -import { AtKeepCollections, UnobfuscationCollections } from '../../../src/utils/CommonCollections'; +import { AtIntentCollections, AtKeepCollections, UnobfuscationCollections } from '../../../src/utils/CommonCollections'; import { ApiExtractor } from '../../../src/common/ApiExtractor' import { FileUtils } from '../../../src/utils/FileUtils'; import * as fs from 'fs'; @@ -113,6 +113,8 @@ describe('test for CommonCollections', function () { expect(fileWhiteLists.fileKeepInfo.exported?.globalNames.size).to.be.equal(0); expect(fileWhiteLists.fileKeepInfo.enumProperties.size).to.be.equal(0); expect(fileWhiteLists.fileKeepInfo.stringProperties.size).to.be.equal(0); + expect(fileWhiteLists.fileKeepInfo.arkUIKeepInfo?.propertyNames.size).to.be.equal(0); + expect(fileWhiteLists.fileKeepInfo.arkUIKeepInfo?.globalNames.size).to.be.equal(0); expect(fileWhiteLists.fileReservedInfo.enumProperties.size).to.be.equal(0); expect(fileWhiteLists.fileReservedInfo.propertyParams.size).to.be.equal(0); }); @@ -159,6 +161,8 @@ describe('test for CommonCollections', function () { fileWhilteListTemp.fileKeepInfo.exported.globalNames.add('test7'); fileWhilteListTemp.fileKeepInfo.exported.propertyNames.add('test8'); fileWhilteListTemp.fileKeepInfo.stringProperties.add('test9'); + fileWhilteListTemp.fileKeepInfo.arkUIKeepInfo.globalNames.add('test111'); + fileWhilteListTemp.fileKeepInfo.arkUIKeepInfo.propertyNames.add('test112'); fileWhilteListTemp.fileReservedInfo.enumProperties.add('test10'); fileWhilteListTemp.fileReservedInfo.propertyParams.add('test11'); const fileWhilteList: FileWhiteList | undefined = projectWhiteListManagerForTest.getFileWhiteListMap().get('testPath3'); @@ -171,6 +175,8 @@ describe('test for CommonCollections', function () { expect(fileWhilteList?.fileKeepInfo.exported.globalNames.has('test7')).to.be.true; expect(fileWhilteList?.fileKeepInfo.exported.propertyNames.has('test8')).to.be.true; expect(fileWhilteList?.fileKeepInfo.stringProperties.has('test9')).to.be.true; + expect(fileWhilteList?.fileKeepInfo.arkUIKeepInfo.globalNames.has('test111')).to.be.true; + expect(fileWhilteList?.fileKeepInfo.arkUIKeepInfo.propertyNames.has('test112')).to.be.true; expect(fileWhilteList?.fileReservedInfo.enumProperties.has('test10')).to.be.true; expect(fileWhilteList?.fileReservedInfo.propertyParams.has('test11')).to.be.true; expect(fileWhilteListTemp.fileKeepInfo.keepSymbol?.globalNames.size).to.be.equal(1); @@ -184,6 +190,8 @@ describe('test for CommonCollections', function () { expect(fileWhilteListTemp.fileKeepInfo.stringProperties.size).to.be.equal(1); expect(fileWhilteListTemp.fileReservedInfo.enumProperties.size).to.be.equal(1); expect(fileWhilteListTemp.fileReservedInfo.propertyParams.size).to.be.equal(1); + expect(fileWhilteListTemp.fileKeepInfo.arkUIKeepInfo.globalNames.size).to.be.equal(1); + expect(fileWhilteListTemp.fileKeepInfo.arkUIKeepInfo.propertyNames.size).to.be.equal(1); }); it('should not collect atKeep if not enabled', () => { let projectWhiteListManager = new ProjectWhiteListManager(cachePath, false, false); @@ -198,6 +206,8 @@ describe('test for CommonCollections', function () { fileWhilteListTemp.fileKeepInfo.exported.globalNames.add('test7'); fileWhilteListTemp.fileKeepInfo.exported.propertyNames.add('test8'); fileWhilteListTemp.fileKeepInfo.stringProperties.add('test9'); + fileWhilteListTemp.fileKeepInfo.arkUIKeepInfo.globalNames.add('test111'); + fileWhilteListTemp.fileKeepInfo.arkUIKeepInfo.propertyNames.add('test112'); fileWhilteListTemp.fileReservedInfo.enumProperties.add('test10'); fileWhilteListTemp.fileReservedInfo.propertyParams.add('test11'); const fileWhilteList: FileWhiteList | undefined = projectWhiteListManager.getFileWhiteListMap().get('testPath4'); @@ -210,6 +220,8 @@ describe('test for CommonCollections', function () { expect(fileWhilteList?.fileKeepInfo.exported.globalNames.has('test7')).to.be.true; expect(fileWhilteList?.fileKeepInfo.exported.propertyNames.has('test8')).to.be.true; expect(fileWhilteList?.fileKeepInfo.stringProperties.has('test9')).to.be.true; + expect(fileWhilteList?.fileKeepInfo.arkUIKeepInfo.globalNames.has('test111')).to.be.true; + expect(fileWhilteList?.fileKeepInfo.arkUIKeepInfo.propertyNames.has('test112')).to.be.true; expect(fileWhilteList?.fileReservedInfo.enumProperties.has('test10')).to.be.true; expect(fileWhilteList?.fileReservedInfo.propertyParams.has('test11')).to.be.true; }); @@ -236,6 +248,8 @@ describe('test for CommonCollections', function () { fileWhilteListTemp.fileKeepInfo.exported.globalNames.add('test7'); fileWhilteListTemp.fileKeepInfo.exported.propertyNames.add('test8'); fileWhilteListTemp.fileKeepInfo.stringProperties.add('test9'); + fileWhilteListTemp.fileKeepInfo.arkUIKeepInfo?.globalNames.add('test111'); + fileWhilteListTemp.fileKeepInfo.arkUIKeepInfo?.propertyNames.add('test112'); fileWhilteListTemp.fileReservedInfo.enumProperties.add('test10'); fileWhilteListTemp.fileReservedInfo.propertyParams.add('test11'); projectWhiteListManager.setCurrentCollector('testPath2'); @@ -262,6 +276,10 @@ describe('test for CommonCollections', function () { expect(UnobfuscationCollections.reservedStrProp.size==0).to.be.true; expect(ApiExtractor.mConstructorPropertySet.size==0).to.be.true; expect(ApiExtractor.mEnumMemberSet.size==0).to.be.true; + expect(AtIntentCollections.globalNames.size==1).to.be.true; + expect(AtIntentCollections.propertyNames.size==1).to.be.true; + expect(AtIntentCollections.globalNames.has('test111')).to.be.true; + expect(AtIntentCollections.propertyNames.has('test112')).to.be.true; }); it('should update fileWhiteLists and projectWhiteList if is incremental(project white list changed)', () => { let projectWhiteListManager = new ProjectWhiteListManager(cachePath, true, true); @@ -281,6 +299,8 @@ describe('test for CommonCollections', function () { fileWhilteListTemp.fileKeepInfo.exported.globalNames.add('test7'); fileWhilteListTemp.fileKeepInfo.exported.propertyNames.add('test8'); fileWhilteListTemp.fileKeepInfo.stringProperties.add('test9'); + fileWhilteListTemp.fileKeepInfo.arkUIKeepInfo.globalNames.add('test122'); + fileWhilteListTemp.fileKeepInfo.arkUIKeepInfo.propertyNames.add('test123'); fileWhilteListTemp.fileReservedInfo.enumProperties.add('test10'); fileWhilteListTemp.fileReservedInfo.propertyParams.add('test11'); fileWhilteListTemp.fileReservedInfo.propertyParams.add('test31'); @@ -313,6 +333,8 @@ describe('test for CommonCollections', function () { expect(ApiExtractor.mConstructorPropertySet.has('test31')).to.be.true; expect(UnobfuscationCollections.reservedExportName.has('test33')).to.be.true; expect(UnobfuscationCollections.reservedExportNameAndProp.has('test12')).to.be.false; + expect(AtIntentCollections.globalNames.has('test122')).to.be.true; + expect(AtIntentCollections.propertyNames.has('test123')).to.be.true; }); it('should update fileWhiteLists and projectWhiteList if is incremental(project white list not changed)', () => { let projectWhiteListManager = new ProjectWhiteListManager(cachePath, true, true); diff --git a/arkguard/test/ut/utils/obfuscation/fileWhiteLists_expected01.json b/arkguard/test/ut/utils/obfuscation/fileWhiteLists_expected01.json index 9112b78b8c..6bde5ff86f 100644 --- a/arkguard/test/ut/utils/obfuscation/fileWhiteLists_expected01.json +++ b/arkguard/test/ut/utils/obfuscation/fileWhiteLists_expected01.json @@ -35,7 +35,15 @@ ], "stringProperties": [ "test9" - ] + ], + "arkUIKeepInfo": { + "propertyNames": [ + "test112" + ], + "globalNames": [ + "test111" + ] + } }, "fileReservedInfo": { "enumProperties": [ @@ -64,7 +72,11 @@ "globalNames": [] }, "enumProperties": [], - "stringProperties": [] + "stringProperties": [], + "arkUIKeepInfo": { + "propertyNames": [], + "globalNames": [] + } }, "fileReservedInfo": { "enumProperties": [], @@ -89,7 +101,11 @@ ] }, "enumProperties": [], - "stringProperties": [] + "stringProperties": [], + "arkUIKeepInfo": { + "propertyNames": [], + "globalNames": [] + } }, "fileReservedInfo": { "enumProperties": [], diff --git a/arkguard/test/ut/utils/obfuscation/fileWhiteLists_expected02.json b/arkguard/test/ut/utils/obfuscation/fileWhiteLists_expected02.json index f0d382095b..419d982f19 100644 --- a/arkguard/test/ut/utils/obfuscation/fileWhiteLists_expected02.json +++ b/arkguard/test/ut/utils/obfuscation/fileWhiteLists_expected02.json @@ -35,7 +35,15 @@ ], "stringProperties": [ "test9" - ] + ], + "arkUIKeepInfo": { + "propertyNames": [ + "test112" + ], + "globalNames": [ + "test111" + ] + } }, "fileReservedInfo": { "enumProperties": [ @@ -64,7 +72,11 @@ ] }, "enumProperties": [], - "stringProperties": [] + "stringProperties": [], + "arkUIKeepInfo": { + "propertyNames": [], + "globalNames": [] + } }, "fileReservedInfo": { "enumProperties": [], @@ -108,7 +120,15 @@ ], "stringProperties": [ "test9" - ] + ], + "arkUIKeepInfo": { + "propertyNames": [ + "test123" + ], + "globalNames": [ + "test122" + ] + } }, "fileReservedInfo": { "enumProperties": [ diff --git a/arkguard/test/ut/utils/obfuscation/fileWhiteLists_expected03.json b/arkguard/test/ut/utils/obfuscation/fileWhiteLists_expected03.json index 809b11a783..af417be379 100644 --- a/arkguard/test/ut/utils/obfuscation/fileWhiteLists_expected03.json +++ b/arkguard/test/ut/utils/obfuscation/fileWhiteLists_expected03.json @@ -35,7 +35,15 @@ ], "stringProperties": [ "test9" - ] + ], + "arkUIKeepInfo": { + "propertyNames": [ + "test112" + ], + "globalNames": [ + "test111" + ] + } }, "fileReservedInfo": { "enumProperties": [ @@ -64,7 +72,11 @@ ] }, "enumProperties": [], - "stringProperties": [] + "stringProperties": [], + "arkUIKeepInfo": { + "propertyNames": [], + "globalNames": [] + } }, "fileReservedInfo": { "enumProperties": [], @@ -108,7 +120,15 @@ ], "stringProperties": [ "test9" - ] + ], + "arkUIKeepInfo": { + "propertyNames": [ + "test123" + ], + "globalNames": [ + "test122" + ] + } }, "fileReservedInfo": { "enumProperties": [ @@ -143,7 +163,11 @@ "enumProperties": [ "test02" ], - "stringProperties": [] + "stringProperties": [], + "arkUIKeepInfo": { + "propertyNames": [], + "globalNames": [] + } }, "fileReservedInfo": { "enumProperties": [], diff --git a/arkguard/test/ut/utils/obfuscation/projectWhiteList_expected01.json b/arkguard/test/ut/utils/obfuscation/projectWhiteList_expected01.json index d7ce25e326..a2a5d19ca7 100644 --- a/arkguard/test/ut/utils/obfuscation/projectWhiteList_expected01.json +++ b/arkguard/test/ut/utils/obfuscation/projectWhiteList_expected01.json @@ -9,12 +9,14 @@ "test02", "test6", "test9", + "test112", "test12" ], "globalNames": [ "test1", "test3", "test7", + "test111", "test13" ] }, diff --git a/arkguard/test/ut/utils/obfuscation/projectWhiteList_expected02.json b/arkguard/test/ut/utils/obfuscation/projectWhiteList_expected02.json index 212230f3d0..c377335249 100644 --- a/arkguard/test/ut/utils/obfuscation/projectWhiteList_expected02.json +++ b/arkguard/test/ut/utils/obfuscation/projectWhiteList_expected02.json @@ -8,14 +8,18 @@ "test8", "test02", "test6", - "test9" + "test9", + "test112", + "test123" ], "globalNames": [ "test1", "test3", "test7", + "test111", "test33", - "test32" + "test32", + "test122" ] }, "projectReservedInfo": { -- Gitee From a1a164c853ac2046628da627b37aa88e691964d7 Mon Sep 17 00:00:00 2001 From: zenghang Date: Sat, 19 Apr 2025 16:19:59 +0800 Subject: [PATCH 152/268] Bytecode obfuscation Integrate Issue: IC2EJF Signed-off-by: zenghang Change-Id: Ic216c7cccfa8e7dd87e3a642c4a13dccc12b6d3b --- arkguard/src/ArkObfuscator.ts | 9 +- arkguard/src/common/ApiExtractor.ts | 99 ++++++++++++++++++- arkguard/src/common/ApiReader.ts | 14 ++- arkguard/src/initialization/ConfigResolver.ts | 73 +++++++++++++- arkguard/src/initialization/Initializer.ts | 7 ++ .../rename/RenameIdentifierTransformer.ts | 2 + arkguard/src/utils/CommonCollections.ts | 8 ++ arkguard/src/utils/ProjectCollections.ts | 46 ++++++++- .../Configs/bytecodeObf/arkguard_enable.txt | 1 + .../bytecodeObf/bytecodeObf_enable.txt | 3 + .../bytecode_obfuscation.txt | 1 + .../ut/initialization/ConfigResolver.spec.ts | 82 +++++++++++++++ .../ut/initialization/Initializer.spec.ts | 79 ++++++++++++++- arkguard/test/ut/utils/ApiExtractor.spec.ts | 10 ++ arkguard/test/ut/utils/ApiReader.spec.ts | 80 ++++++++++++--- .../test/ut/utils/ProjectCollections.spec.ts | 18 ++++ .../collectFileWhiteList02.ets | 8 ++ 17 files changed, 509 insertions(+), 31 deletions(-) create mode 100644 arkguard/test/testData/obfuscation/Configs/bytecodeObf/arkguard_enable.txt create mode 100644 arkguard/test/testData/obfuscation/Configs/bytecodeObf/bytecodeObf_enable.txt create mode 100644 arkguard/test/testData/obfuscation/system_api_obfuscation/bytecode_obfuscation/bytecode_obfuscation.txt create mode 100644 arkguard/test/ut/utils/apiTest_collectFileWhiteList/collectFileWhiteList02.ets diff --git a/arkguard/src/ArkObfuscator.ts b/arkguard/src/ArkObfuscator.ts index 087ff1dfda..556186b280 100644 --- a/arkguard/src/ArkObfuscator.ts +++ b/arkguard/src/ArkObfuscator.ts @@ -35,7 +35,13 @@ import type { import path from 'path'; -import { AtIntentCollections, AtKeepCollections, LocalVariableCollections, PropCollections } from './utils/CommonCollections'; +import { + AtIntentCollections, + AtKeepCollections, + BytecodeObfuscationCollections, + LocalVariableCollections, + PropCollections +} from './utils/CommonCollections'; import type { IOptions } from './configs/IOptions'; import { FileUtils } from './utils/FileUtils'; import { TransformerManager } from './transformers/TransformerManager'; @@ -177,6 +183,7 @@ export function clearGlobalCaches(): void { disablePrinterTimeAndMemConfig(); ApiExtractor.mConstructorPropertySet.clear(); ApiExtractor.mEnumMemberSet.clear(); + BytecodeObfuscationCollections.clear(); } export type ObfuscationResultType = { diff --git a/arkguard/src/common/ApiExtractor.ts b/arkguard/src/common/ApiExtractor.ts index b6450ea212..558d56dfcd 100644 --- a/arkguard/src/common/ApiExtractor.ts +++ b/arkguard/src/common/ApiExtractor.ts @@ -16,13 +16,16 @@ import type { ClassDeclaration, CommentRange, + Decorator, ElementAccessExpression, EnumDeclaration, ExportDeclaration, + Expression, FunctionDeclaration, InterfaceDeclaration, ModifiersArray, ModuleDeclaration, + NamedDeclaration, Node, ParameterDeclaration, PropertyAccessExpression, @@ -76,7 +79,9 @@ import { isParameter, isTypeParameterDeclaration, isIndexedAccessTypeNode, - Extension + Extension, + isCallExpression, + isDecorator } from 'typescript'; import fs from 'fs'; @@ -99,8 +104,13 @@ import { scanProjectConfig } from './ApiReader'; import { enumPropsSet } from '../utils/OhsUtil'; import { FileUtils } from '../utils/FileUtils'; import { supportedParsingExtension } from './type'; -import { addToSet, FileWhiteList, KeepInfo, projectWhiteListManager } from '../utils/ProjectCollections'; -import { AtKeepCollections } from '../utils/CommonCollections'; +import { + addToSet, + DECORATOR_WHITE_LIST, + FileWhiteList, KeepInfo, + projectWhiteListManager +} from '../utils/ProjectCollections'; +import { AtKeepCollections, BytecodeObfuscationCollections } from '../utils/CommonCollections'; import { hasExportModifier } from '../utils/NodeUtils'; export namespace ApiExtractor { @@ -143,6 +153,8 @@ export namespace ApiExtractor { let mCurrentExportedPropertySet: Set = new Set(); let mCurrentExportNameSet: Set = new Set(); + let decoratorMap: Map> = new Map>(); + let keepSymbolTemp: KeepInfo = { propertyNames: new Set(), globalNames: new Set(), @@ -693,6 +705,11 @@ export namespace ApiExtractor { collectWhiteListByApiType(sourceFile, apiType, fileName); + // collect field decorated by UI + if (scanProjectConfig.scanDecorator) { + collectAndAddFieldDecorator(sourceFile); + } + // collect names marked with '// @KeepSymbol' or '// @KeepAsConsumer', only support .ts/.ets if (shouldCollectAtKeep(fileName)) { collectAndAddAtKeepNames(sourceFile); @@ -710,6 +727,7 @@ export namespace ApiExtractor { mCurrentExportedPropertySet.forEach(item => mPropertySet.add(item)); mCurrentExportedPropertySet.clear(); exportOriginalNameSet.clear(); + decoratorMap.clear(); }; function shouldCollectAtKeep(fileName: string): boolean { @@ -756,6 +774,59 @@ export namespace ApiExtractor { addToSet(fileWhiteLists.fileKeepInfo.keepAsConsumer.globalNames, keepAsConsumerTemp.globalNames); addToSet(fileWhiteLists.fileKeepInfo.keepAsConsumer.propertyNames, keepAsConsumerTemp.propertyNames); } + if (scanProjectConfig.scanDecorator) { + const convertedMap = new Map( + Array.from(decoratorMap.entries()).map(([key, value]) => [key, Array.from(value)])); + if (!fileWhiteLists.bytecodeObfuscateKeepInfo) { + fileWhiteLists.bytecodeObfuscateKeepInfo = {}; + } + fileWhiteLists.bytecodeObfuscateKeepInfo.decoratorMap = Object.fromEntries(convertedMap); + const allProp = Array.from(convertedMap.values()).flat(); + allProp.forEach(value => BytecodeObfuscationCollections.decoratorProp.add(value)); + } + } + + function collectAndAddFieldDecorator(sourceFile: SourceFile): void { + visitDecorator(sourceFile); + } + + function getDecorators(node: Node): Decorator[] { + const decorators: Decorator[] = []; + forEachChild(node, child => { + if (isDecorator(child)) { + decorators.push(child); + } + }); + return decorators; + } + + function visitDecorator(node: Node): void { + const decorators = getDecorators(node) || []; + const propertyName = (node as NamedDeclaration).name?.getText(); + if (!propertyName) { + forEachChild(node, visitDecorator); + return; + } + + decorators.forEach(decorator => { + const expr = decorator.expression; + const decoratorName = getDecoratorName(expr); + if (!decoratorName || !isWhiteListedDecorator(decoratorName)) { + return; + } + ensureEntry(decoratorMap, decoratorName, () => new Set()); + const decoratorSet = decoratorMap.get(decoratorName)!; + + if (isCallExpression(expr)) { + expr.arguments.forEach(arg => { + const stripped = arg.getText().replace(/^['"]|['"]$/g, '').split('.'); + stripped.forEach(item => decoratorSet.add(item)); + }); + } + decoratorSet.add(propertyName); + + }); + forEachChild(node, visitDecorator); } function collectWhiteListByApiType(sourceFile: SourceFile, apiType: ApiType, fileName: string): void { @@ -1414,4 +1485,24 @@ export namespace ApiExtractor { collector.globalNames.add(name); } } -} + + function ensureEntry(map: Map, key: K, createValue: () => V): void { + if (!map.has(key)) { + map.set(key, createValue()); + } + } + + function isWhiteListedDecorator(name: string): boolean { + return DECORATOR_WHITE_LIST.includes(name); + } + + function getDecoratorName(expr: Expression): string | undefined { + if (isCallExpression(expr)) { + return expr.expression.getText(); + } + if (isIdentifier(expr)) { + return expr.text; + } + return undefined; + } +} \ No newline at end of file diff --git a/arkguard/src/common/ApiReader.ts b/arkguard/src/common/ApiReader.ts index aecec4c600..0504003668 100644 --- a/arkguard/src/common/ApiReader.ts +++ b/arkguard/src/common/ApiReader.ts @@ -28,7 +28,8 @@ export interface ScanProjectConfig { mkeepFilesAndDependencies?: Set, isHarCompiled?: boolean, mStripSystemApiArgs?: boolean, - mEnableAtKeep: boolean + mEnableAtKeep: boolean, + scanDecorator?: boolean; } // Settings for collect white lists. @@ -71,13 +72,18 @@ export function isEnabledPropertyObfuscation(customProfiles: IOptions): boolean customProfiles.mNameObfuscation.mRenameProperties); } -function initScanProjectConfig(customProfiles: IOptions, isHarCompiled?: boolean): void { +export function initScanProjectConfig( + customProfiles: IOptions, + isHarCompiled?: boolean, + scanDecorator: boolean = false +): void { scanProjectConfig.mPropertyObfuscation = customProfiles.mNameObfuscation?.mRenameProperties; scanProjectConfig.mKeepStringProperty = customProfiles.mNameObfuscation?.mKeepStringProperty; scanProjectConfig.mExportObfuscation = customProfiles.mExportObfuscation; scanProjectConfig.mkeepFilesAndDependencies = customProfiles.mKeepFileSourceCode?.mkeepFilesAndDependencies; scanProjectConfig.isHarCompiled = isHarCompiled; scanProjectConfig.mEnableAtKeep = customProfiles.mNameObfuscation?.mEnableAtKeep; + scanProjectConfig.scanDecorator = scanDecorator; } /** @@ -109,7 +115,7 @@ export interface ReseverdSetForArkguard { * @param customProfiles */ export function readProjectPropertiesByCollectedPaths(filesForCompilation: Set, - customProfiles: IOptions, isHarCompiled: boolean): ReseverdSetForArkguard { + customProfiles: IOptions, isHarCompiled: boolean, scanDecorator: boolean = false): ReseverdSetForArkguard { const apiType = ApiExtractor.ApiType; let scanningCommonType = undefined; if (needReadApiInfo(customProfiles)) { @@ -118,7 +124,7 @@ export function readProjectPropertiesByCollectedPaths(filesForCompilation: Set 0) { resultStr += ObConfigResolver.KEEP_GLOBAL_NAME + '\n'; this.reservedGlobalNames.forEach((item) => { @@ -250,10 +271,19 @@ export class ObConfigResolver { this.handleReservedArray(mergedConfigs); endFilesEvent(EventList.RESOLVE_OBFUSCATION_CONFIGS); + /** + * Bytecode obfuscate mode: + * temporary variable or in non-top-level scope is obfuscated to be added to the obfuscate name set, + * All names that appear in the confused name collection will be obfuscated later + * So when a developer-defined name has the same name as systemApi + * Without a whitelist, all the same names would be obfuscated, leading to devastating errors + * so in order to work properly, Bytecode obfuscate enables the obfuscate function and requires whitelist + */ let needKeepSystemApi = enableObfuscation && (mergedConfigs.options.enablePropertyObfuscation || - (mergedConfigs.options.enableExportObfuscation && mergedConfigs.options.enableToplevelObfuscation)); + (mergedConfigs.options.enableExportObfuscation && mergedConfigs.options.enableToplevelObfuscation) || + mergedConfigs.options.bytecodeObf.enable); if (needKeepSystemApi && sourceObConfig.obfuscationCacheDir) { const systemApiCachePath: string = path.join(sourceObConfig.obfuscationCacheDir, 'systemApiCache.json'); @@ -364,6 +394,11 @@ export class ObConfigResolver { static readonly PRINT_NAMECACHE = '-print-namecache'; static readonly PRINT_KEPT_NAMES = '-print-kept-names'; static readonly APPLY_NAMECACHE = '-apply-namecache'; + // obfuscation options for bytecode obfuscation + static readonly ENABLE_BYTECODE_OBFUSCATION = '-enable-bytecode-obfuscation'; + static readonly ENABLE_BYTECODE_OBFUSCATION_DEBUGGING = '-enable-bytecode-obfuscation-debugging'; + static readonly ENABLE_BYTECODE_OBFUSCATION_ENHANCED = '-enable-bytecode-obfuscation-enhanced'; + static readonly ENABLE_BYTECODE_OBFUSCATION_ARKUI = '-enable-bytecode-obfuscation-arkui'; static readonly EXTRA_OPTIONS = '-extra-options'; static readonly STRIP_LANGUAGE_DEFAULT = 'strip-language-default'; static readonly STRIP_SYSTEM_API_ARGS = 'strip-system-api-args'; @@ -380,6 +415,14 @@ export class ObConfigResolver { private getTokenType(token: string): OptionType { switch (token) { + case ObConfigResolver.ENABLE_BYTECODE_OBFUSCATION: + return OptionType.ENABLE_BYTECODE_OBFUSCATION; + case ObConfigResolver.ENABLE_BYTECODE_OBFUSCATION_DEBUGGING: + return OptionType.ENABLE_BYTECODE_OBFUSCATION_DEBUGGING; + case ObConfigResolver.ENABLE_BYTECODE_OBFUSCATION_ENHANCED: + return OptionType.ENABLE_BYTECODE_OBFUSCATION_ENHANCED; + case ObConfigResolver.ENABLE_BYTECODE_OBFUSCATION_ARKUI: + return OptionType.ENABLE_BYTECODE_OBFUSCATION_ARKUI; case ObConfigResolver.KEEP_DTS: return OptionType.KEEP_DTS; case ObConfigResolver.KEEP_GLOBAL_NAME: @@ -450,6 +493,26 @@ export class ObConfigResolver { tokenType = this.getTokenType(token); // handle switches cases switch (tokenType) { + case OptionType.ENABLE_BYTECODE_OBFUSCATION: { + configs.options.bytecodeObf.enable = true; + extraOptionType = OptionType.NONE; + continue; + } + case OptionType.ENABLE_BYTECODE_OBFUSCATION_DEBUGGING: { + configs.options.bytecodeObf.debugging = true; + extraOptionType = OptionType.NONE; + continue; + } + case OptionType.ENABLE_BYTECODE_OBFUSCATION_ENHANCED: { + configs.options.bytecodeObf.enhanced = true; + extraOptionType = OptionType.NONE; + continue; + } + case OptionType.ENABLE_BYTECODE_OBFUSCATION_ARKUI: { + configs.options.bytecodeObf.obfArkUI = true; + extraOptionType = OptionType.NONE; + continue; + } case OptionType.DISABLE_OBFUSCATION: { configs.options.disableObfuscation = true; extraOptionType = OptionType.NONE; @@ -719,7 +782,7 @@ export class ObConfigResolver { } const arkUIReservedPropertyNames: string[] = this.collectUIApiWhitelist(existPreDefineFilePath, existArkUIWhitelistPath, config); let systemApiContent: SystemApiContent = {}; - if (config.options.enablePropertyObfuscation) { + if (config.options.enablePropertyObfuscation || config.options.bytecodeObf?.enable) { if (!config.options.stripSystemApiArgs) { UnobfuscationCollections.reservedSdkApiForLocal = new Set(ApiExtractor.mPropertySet); systemApiContent.ReservedLocalNames = Array.from(ApiExtractor.mPropertySet); @@ -728,7 +791,8 @@ export class ObConfigResolver { UnobfuscationCollections.reservedSdkApiForProp = savedNameAndPropertySet; systemApiContent.ReservedPropertyNames = Array.from(savedNameAndPropertySet); } - if (config.options.enableToplevelObfuscation && config.options.enableExportObfuscation) { + if ((config.options.enableToplevelObfuscation && config.options.enableExportObfuscation) || + config.options.bytecodeObf?.enable) { const savedExportNamesSet = new Set(ApiExtractor.mSystemExportSet); UnobfuscationCollections.reservedSdkApiForGlobal = savedExportNamesSet; systemApiContent.ReservedGlobalNames = Array.from(savedExportNamesSet); @@ -1321,7 +1385,8 @@ export function enableObfuscatedFilePathConfig(isPackageModules: boolean, projec } const disableObfuscation = hasObfuscationConfig.options.disableObfuscation; const enableFileNameObfuscation = hasObfuscationConfig.options.enableFileNameObfuscation; - if (disableObfuscation || !enableFileNameObfuscation) { + const enableBytecodeObfuscation = hasObfuscationConfig.options.bytecodeObf?.enable; + if (disableObfuscation || !enableFileNameObfuscation || enableBytecodeObfuscation) { return false; } return true; diff --git a/arkguard/src/initialization/Initializer.ts b/arkguard/src/initialization/Initializer.ts index 16b3fc6dd7..0bf8bcea24 100644 --- a/arkguard/src/initialization/Initializer.ts +++ b/arkguard/src/initialization/Initializer.ts @@ -62,6 +62,13 @@ export function initObfuscationConfig(projectConfig: any, arkProjectConfig: any, return; } getObfuscationCacheDir(projectConfig); + /** + * Only one of bytecode obfuscation and source code obfuscation will take effect. + * Enabling bytecode obfuscation is to obfuscate declaration files when compile bytecode har. + */ + const isBytecodeObfEnabled = mergedObConfig.options.bytecodeObf.enable; + arkProjectConfig.isBytecodeObfEnabled = isBytecodeObfEnabled; + arkProjectConfig.isArkguardEnabled = !isBytecodeObfEnabled; if (mergedObConfig.options.enableFileNameObfuscation) { const ohPackagePath = path.join(projectConfig.modulePath, 'oh-package.json5'); diff --git a/arkguard/src/transformers/rename/RenameIdentifierTransformer.ts b/arkguard/src/transformers/rename/RenameIdentifierTransformer.ts index 76e8656595..eff9d64cb4 100644 --- a/arkguard/src/transformers/rename/RenameIdentifierTransformer.ts +++ b/arkguard/src/transformers/rename/RenameIdentifierTransformer.ts @@ -106,6 +106,7 @@ import { isViewPUBasedClass } from '../../utils/OhsUtil'; import { AtIntentCollections, AtKeepCollections, + BytecodeObfuscationCollections, LocalVariableCollections, PropCollections, UnobfuscationCollections @@ -870,6 +871,7 @@ namespace secharmony { addToSet(PropCollections.reservedProperties, AtKeepCollections.keepSymbol.globalNames); addToSet(PropCollections.reservedProperties, AtKeepCollections.keepAsConsumer.globalNames); addToSet(PropCollections.reservedProperties, AtIntentCollections.globalNames); + addToSet(UnobfuscationCollections.reservedSdkApiForProp, BytecodeObfuscationCollections.decoratorProp); profile?.mUniversalReservedToplevelNames?.forEach(item => PropCollections.universalReservedProperties.push(item)); isInitializedReservedList = true; } diff --git a/arkguard/src/utils/CommonCollections.ts b/arkguard/src/utils/CommonCollections.ts index 3cf9f0aace..aa31e00fd0 100644 --- a/arkguard/src/utils/CommonCollections.ts +++ b/arkguard/src/utils/CommonCollections.ts @@ -114,4 +114,12 @@ export namespace AtIntentCollections{ propertyNames.clear(); globalNames.clear(); } +} + +export namespace BytecodeObfuscationCollections { + export let decoratorProp: Set = new Set(); + + export function clear(): void { + decoratorProp.clear(); + } } \ No newline at end of file diff --git a/arkguard/src/utils/ProjectCollections.ts b/arkguard/src/utils/ProjectCollections.ts index ec155c1e59..a8b583fe60 100644 --- a/arkguard/src/utils/ProjectCollections.ts +++ b/arkguard/src/utils/ProjectCollections.ts @@ -15,7 +15,12 @@ import { ApiExtractor } from '../common/ApiExtractor'; import { FileUtils } from './FileUtils'; -import { AtIntentCollections, AtKeepCollections, UnobfuscationCollections } from './CommonCollections'; +import { + AtIntentCollections, + AtKeepCollections, + BytecodeObfuscationCollections, + UnobfuscationCollections +} from './CommonCollections'; import * as crypto from 'crypto'; import * as ts from 'typescript'; import fs from 'fs'; @@ -51,6 +56,14 @@ export const FILE_NAMES_MAP: string = 'transformedFileNamesMap.json'; export const FILE_WHITE_LISTS: string = 'fileWhiteLists.json'; export const PROJECT_WHITE_LIST: string = 'projectWhiteList.json'; +// this while list is only used for bytecode obfuscation +export const DECORATOR_WHITE_LIST = [ + 'Monitor', + 'Track', + 'Trace', + 'AnimatableExtend' +]; + export interface KeepInfo { propertyNames: Set; globalNames: Set; @@ -114,6 +127,8 @@ export interface FileContent { * │ └── arkUIKeepInfo: KeepInfo * │ ├── propertyNames: Set * │ └── globalNames: Set + * └── bytecodeObfuscateKeepInfo: BytecodeObfuscateKeepInfo + * └── decoratorMap?: Map * └── fileReservedInfo: FileReservedInfo * ├── enumProperties: Set * └── propertyParams: Set @@ -133,9 +148,14 @@ export interface FileReservedInfo { propertyParams: Set; // Properties parameters in constructor. } +export interface BytecodeObfuscateKeepInfo { + decoratorMap?: Object; // collect DecoratorMap +} + export interface FileWhiteList { fileKeepInfo: FileKeepInfo; fileReservedInfo: FileReservedInfo; + bytecodeObfuscateKeepInfo?: BytecodeObfuscateKeepInfo } export interface ProjectKeepInfo { @@ -329,8 +349,10 @@ export class ProjectWhiteListManager { enumProperties: arrayToSet(parsed[key].fileReservedInfo.enumProperties), propertyParams: arrayToSet(parsed[key].fileReservedInfo.propertyParams), }; - - map.set(key, { fileKeepInfo, fileReservedInfo }); + const bytecodeObfuscateKeepInfo: BytecodeObfuscateKeepInfo = { + decoratorMap: parsed[key].bytecodeObfuscateKeepInfo?.decoratorMap, + }; + map.set(key, { fileKeepInfo, fileReservedInfo, bytecodeObfuscateKeepInfo }); } } @@ -371,6 +393,11 @@ export class ProjectWhiteListManager { propertyParams: setToArray(value.fileReservedInfo.propertyParams), }, }; + if (value.bytecodeObfuscateKeepInfo?.decoratorMap) { + jsonData[key].bytecodeObfuscateKeepInfo = { + decoratorMap: value.bytecodeObfuscateKeepInfo.decoratorMap, + }; + } } const jsonString = JSON.stringify(jsonData, null, 2); @@ -498,6 +525,13 @@ export class ProjectWhiteListManager { fileWhiteList.fileReservedInfo.propertyParams.forEach((propertyParam) => { projectReservedInfo.propertyParams.add(propertyParam); }); + + const decoratorMap = fileWhiteList.bytecodeObfuscateKeepInfo?.decoratorMap; + for (const key in decoratorMap) { + if (Object.prototype.hasOwnProperty.call(decoratorMap, key)) { + decoratorMap[key]?.forEach(item => projectKeepInfo.globalNames.add(item)); + } + } }); const projectWhiteList = { @@ -545,6 +579,12 @@ export class ProjectWhiteListManager { addToSet(AtIntentCollections.globalNames, fileWhiteList.fileKeepInfo.arkUIKeepInfo.globalNames); addToSet(ApiExtractor.mConstructorPropertySet, fileWhiteList.fileReservedInfo.propertyParams); addToSet(ApiExtractor.mEnumMemberSet, fileWhiteList.fileReservedInfo.enumProperties); + const decoratorMap = fileWhiteList.bytecodeObfuscateKeepInfo?.decoratorMap; + for (const key in decoratorMap) { + if (Object.prototype.hasOwnProperty.call(decoratorMap, key)) { + decoratorMap[key]?.forEach(item => BytecodeObfuscationCollections.decoratorProp.add(item)); + } + } }); } diff --git a/arkguard/test/testData/obfuscation/Configs/bytecodeObf/arkguard_enable.txt b/arkguard/test/testData/obfuscation/Configs/bytecodeObf/arkguard_enable.txt new file mode 100644 index 0000000000..3886aed9a1 --- /dev/null +++ b/arkguard/test/testData/obfuscation/Configs/bytecodeObf/arkguard_enable.txt @@ -0,0 +1 @@ +#default \ No newline at end of file diff --git a/arkguard/test/testData/obfuscation/Configs/bytecodeObf/bytecodeObf_enable.txt b/arkguard/test/testData/obfuscation/Configs/bytecodeObf/bytecodeObf_enable.txt new file mode 100644 index 0000000000..810df52a85 --- /dev/null +++ b/arkguard/test/testData/obfuscation/Configs/bytecodeObf/bytecodeObf_enable.txt @@ -0,0 +1,3 @@ +-enable-bytecode-obfuscation +-enable-bytecode-obfuscation-debugging +-enable-bytecode-obfuscation-enhanced \ No newline at end of file diff --git a/arkguard/test/testData/obfuscation/system_api_obfuscation/bytecode_obfuscation/bytecode_obfuscation.txt b/arkguard/test/testData/obfuscation/system_api_obfuscation/bytecode_obfuscation/bytecode_obfuscation.txt new file mode 100644 index 0000000000..43c1c46fc8 --- /dev/null +++ b/arkguard/test/testData/obfuscation/system_api_obfuscation/bytecode_obfuscation/bytecode_obfuscation.txt @@ -0,0 +1 @@ +-enable-bytecode-obfuscation \ No newline at end of file diff --git a/arkguard/test/ut/initialization/ConfigResolver.spec.ts b/arkguard/test/ut/initialization/ConfigResolver.spec.ts index f5b9bc480a..aba1673894 100644 --- a/arkguard/test/ut/initialization/ConfigResolver.spec.ts +++ b/arkguard/test/ut/initialization/ConfigResolver.spec.ts @@ -956,6 +956,24 @@ describe('test for ConfigResolve', function() { expect(configs.options.enableLibObfuscationOptions).to.be.true; }); + + it('should handle config correctly when enable bytecode obfuscation options', () => { + const configs: MergedConfig = new MergedConfig(); + configs.options = new ObOptionsForTest(); + + const configPath = './test/testData/obfuscation/enable_lib_obfuscation_options/obfuscation-rule.txt'; + const data = ` + -enable-bytecode-obfuscation + -enable-bytecode-obfuscation-debugging + -enable-bytecode-obfuscation-enhanced + -enable-bytecode-obfuscation-arkui + `; + newObConfigResolver.handleConfigContentForTest(data, configs, configPath); + expect(configs.options.bytecodeObf.enable).to.be.true; + expect(configs.options.bytecodeObf.debugging).to.be.true; + expect(configs.options.bytecodeObf.enhanced).to.be.true; + expect(configs.options.bytecodeObf.obfArkUI).to.be.true; + }); }); describe('1: test Api collectSystemApiWhitelist', function() { @@ -1188,6 +1206,52 @@ describe('test for ConfigResolve', function() { fs.unlinkSync(systemApiPath); }); + + it('1-5: test collectSystemApiWhitelist: -enable-bytecode-obfuscation', function () { + let obfuscationCacheDir = path.join(OBFUSCATE_TESTDATA_DIR, 'bytecode_obfuscation'); + let obfuscationOptions = { + 'selfConfig': { + 'ruleOptions': { + 'enable': true, + 'rules': [ + path.join(OBFUSCATE_TESTDATA_DIR, 'bytecode_obfuscation/bytecode_obfuscation.txt') + ] + }, + 'consumerRules': [], + }, + 'dependencies': { + 'libraries': [], + 'hars': [] + }, + 'obfuscationCacheDir': obfuscationCacheDir, + 'sdkApis': [ + path.join(OBFUSCATE_TESTDATA_DIR, 'system_api.d.ts') + ] + }; + let projectConfig = { + obfuscationOptions, + compileHar: false + }; + const obConfig: ObConfigResolver = new ObConfigResolver(projectConfig, undefined); + obConfig.resolveObfuscationConfigs(); + const reservedSdkApiForProp = UnobfuscationCollections.reservedSdkApiForProp; + const reservedSdkApiForGlobal = UnobfuscationCollections.reservedSdkApiForGlobal; + const reservedSdkApiForLocal = UnobfuscationCollections.reservedSdkApiForLocal; + + expect(reservedSdkApiForProp.size == 12).to.be.true; + expect(reservedSdkApiForGlobal.size == 3).to.be.true; + expect(reservedSdkApiForLocal.size == 8).to.be.true; + UnobfuscationCollections.clear(); + + let systemApiPath = obfuscationCacheDir + '/systemApiCache.json'; + const data = fs.readFileSync(systemApiPath, 'utf8'); + const systemApiContent = JSON.parse(data); + + expect(systemApiContent.ReservedLocalNames.length == 8).to.be.true; + expect(systemApiContent.ReservedPropertyNames.length == 12).to.be.true; + expect(systemApiContent.ReservedGlobalNames.length == 3).to.be.true; + fs.unlinkSync(systemApiPath); + }); }); }); @@ -2015,6 +2079,24 @@ describe('test for ConfigResolve', function() { const result = enableObfuscateFileName(isPackageModules, projectConfig); expect(result).to.be.false; }); + + it('should return false if obfuscation is enabled and bytecodeObf is enable', () => { + const isPackageModules = false; + const projectConfig = { + obfuscationMergedObConfig: { + options: { + disableObfuscation: false, + enableFileNameObfuscation: true, + bytecodeObf: { + enable: true + }, + }, + }, + buildMode: "not Debug" + }; + const result = enableObfuscatedFilePathConfig(isPackageModules, projectConfig); + expect(result).to.be.false; + }); }); describe('getRelativeSourcePath', () => { diff --git a/arkguard/test/ut/initialization/Initializer.spec.ts b/arkguard/test/ut/initialization/Initializer.spec.ts index 69ae8b1a74..56ab226bb3 100644 --- a/arkguard/test/ut/initialization/Initializer.spec.ts +++ b/arkguard/test/ut/initialization/Initializer.spec.ts @@ -14,11 +14,22 @@ */ import { - clearHistoryUnobfuscatedMap, - historyAllUnobfuscatedNamesMap, - historyUnobfuscatedPropMap + clearHistoryUnobfuscatedMap, + historyAllUnobfuscatedNamesMap, + historyUnobfuscatedPropMap, + initObfuscationConfig } from '../../../src/initialization/Initializer'; -import { expect } from 'chai'; +import { + expect, + assert +} from 'chai'; +import { + describe, + it +} from 'mocha'; +import { + HvigorErrorInfo, +} from '../../../src/ArkObfuscator'; describe('Tester Cases for .', function () { it('Tester Cases for .', function () { @@ -31,3 +42,63 @@ describe('Tester Cases for .', function () { expect(historyUnobfuscatedPropMap.size).to.equal(0); }); }); + +function printObfLogger(errorInfo: string, errorCodeInfo: HvigorErrorInfo | string, level: string): void { + switch (level) { + case 'warn': + console.warn(errorInfo); + break; + case 'error': + console.error(errorInfo); + break; + default: + break; + } +} +const projectConfig = { + 'obfuscationOptions': { + 'selfConfig': { + 'ruleOptions': { + 'enable': true, + 'rules': ['./test/testData/obfuscation/Configs/bytecodeObf/bytecodeObf_enable.txt'] + }, + 'consumerRules': [], + }, + 'dependencies': { + 'libraries': [], + 'hars': [] + }, + obfuscationCacheDir: "" + } +}; +interface ArkProjectConfig { + isBytecodeObfEnabled?: boolean; + isArkguardEnabled?: boolean; +} + +describe('test for set arkguard mode property correctly for arkProjectConfig', function () { + describe('test for set arkguard mode property correctly for arkProjectConfig', () => { + it('should set isBytecodeObfEnabled when enable bytecodeObf', () => { + const arkProjectConfig: ArkProjectConfig = {}; + initObfuscationConfig(projectConfig, arkProjectConfig, printObfLogger); + expect(arkProjectConfig.isBytecodeObfEnabled).to.be.true; + expect(arkProjectConfig.isArkguardEnabled).to.be.false; + }); + + it('should set isArkguardEnabled when enable arkguardObf', () => { + const arkProjectConfig: ArkProjectConfig = {}; + projectConfig.obfuscationOptions.selfConfig.ruleOptions.rules = ['./test/testData/obfuscation/Configs/bytecodeObf/arkguard_enable.txt']; + initObfuscationConfig(projectConfig, arkProjectConfig, printObfLogger); + expect(arkProjectConfig.isArkguardEnabled).to.be.true; + expect(arkProjectConfig.isBytecodeObfEnabled).to.be.false; + }); + + it('should not set isArkguardEnabled and isBytecodeObfEnabled when obf is disabled', () => { + const arkProjectConfig: ArkProjectConfig = {}; + projectConfig.obfuscationOptions.selfConfig.ruleOptions.enable = false; + initObfuscationConfig(projectConfig, arkProjectConfig, printObfLogger); + expect(arkProjectConfig.isBytecodeObfEnabled).to.be.undefined; + expect(arkProjectConfig.isArkguardEnabled).to.be.undefined; + }); + }); +}); diff --git a/arkguard/test/ut/utils/ApiExtractor.spec.ts b/arkguard/test/ut/utils/ApiExtractor.spec.ts index 0f29756774..f293d23df6 100644 --- a/arkguard/test/ut/utils/ApiExtractor.spec.ts +++ b/arkguard/test/ut/utils/ApiExtractor.spec.ts @@ -1200,5 +1200,15 @@ describe('test for ApiExtractor', function () { expect(fileWhiteList.fileKeepInfo.stringProperties.size).to.be.equal(0); expect(fileWhiteList.fileKeepInfo.structProperties.size).to.be.equal(0); }) + it('should collect decoratorMap if need scanDecorator', function () { + let filePath: string = 'test/ut/utils/apiTest_collectFileWhiteList/collectFileWhiteList02.ets'; + scanProjectConfig.scanDecorator = true; + collectApi(filePath, ApiExtractor.ApiType.PROJECT); + const fileWhiteList: FileWhiteList = projectWhiteListManager?.getFileWhiteListMap().get(filePath)!; + if (fileWhiteList?.bytecodeObfuscateKeepInfo?.decoratorMap) { + const decoratorKeys = Object.keys(fileWhiteList.bytecodeObfuscateKeepInfo.decoratorMap); + expect(decoratorKeys.length).to.be.greaterThan(0); + } + }) }) }); \ No newline at end of file diff --git a/arkguard/test/ut/utils/ApiReader.spec.ts b/arkguard/test/ut/utils/ApiReader.spec.ts index 3d0e7ed55e..32563048f2 100644 --- a/arkguard/test/ut/utils/ApiReader.spec.ts +++ b/arkguard/test/ut/utils/ApiReader.spec.ts @@ -13,7 +13,12 @@ * limitations under the License. */ -import { readProjectPropertiesByCollectedPaths, ReseverdSetForArkguard } from '../../../src/common/ApiReader'; +import { + readProjectPropertiesByCollectedPaths, + ReseverdSetForArkguard, + scanProjectConfig, + initScanProjectConfig +} from '../../../src/common/ApiReader'; import { assert, expect } from 'chai'; import { NameGeneratorType } from '../../../src/generator/NameFactory'; import { @@ -40,7 +45,7 @@ describe('test for ApiReader', function () { mRenameProperties: true, mKeepStringProperty: false, mNameGeneratorType: NameGeneratorType.ORDERED, - mReservedNames: [], + mReservedNames: [], mReservedToplevelNames: [] } }; @@ -88,7 +93,7 @@ describe('test for ApiReader', function () { mRenameProperties: true, mKeepStringProperty: false, mNameGeneratorType: NameGeneratorType.ORDERED, - mReservedNames: [], + mReservedNames: [], mReservedToplevelNames: [] } }; @@ -142,7 +147,7 @@ describe('test for ApiReader', function () { mRenameProperties: false, mKeepStringProperty: false, mNameGeneratorType: NameGeneratorType.ORDERED, - mReservedNames: [], + mReservedNames: [], mReservedToplevelNames: [] } }; @@ -181,7 +186,7 @@ describe('test for ApiReader', function () { mRenameProperties: false, mKeepStringProperty: false, mNameGeneratorType: NameGeneratorType.ORDERED, - mReservedNames: [], + mReservedNames: [], mReservedToplevelNames: [] } }; @@ -270,7 +275,7 @@ describe('test for ApiReader', function () { mRenameProperties: true, mKeepStringProperty: false, mNameGeneratorType: NameGeneratorType.ORDERED, - mReservedNames: [], + mReservedNames: [], mReservedToplevelNames: [] } }; @@ -360,7 +365,7 @@ describe('test for ApiReader', function () { mKeepStringProperty: false, mTopLevel: true, mNameGeneratorType: NameGeneratorType.ORDERED, - mReservedNames: [], + mReservedNames: [], mReservedToplevelNames: [] } }; @@ -396,7 +401,7 @@ describe('test for ApiReader', function () { mKeepStringProperty: false, mTopLevel: true, mNameGeneratorType: NameGeneratorType.ORDERED, - mReservedNames: [], + mReservedNames: [], mReservedToplevelNames: [] } }; @@ -486,7 +491,7 @@ describe('test for ApiReader', function () { mKeepStringProperty: false, mTopLevel: false, mNameGeneratorType: NameGeneratorType.ORDERED, - mReservedNames: [], + mReservedNames: [], mReservedToplevelNames: [] } }; @@ -630,7 +635,7 @@ describe('test for ApiReader', function () { mKeepStringProperty: false, mTopLevel: true, mNameGeneratorType: NameGeneratorType.ORDERED, - mReservedNames: [], + mReservedNames: [], mReservedToplevelNames: [] } }; @@ -776,7 +781,7 @@ describe('test for ApiReader', function () { mKeepStringProperty: false, mTopLevel: true, mNameGeneratorType: NameGeneratorType.ORDERED, - mReservedNames: [], + mReservedNames: [], mReservedToplevelNames: [] } }; @@ -876,5 +881,58 @@ describe('test for ApiReader', function () { expect(fileWhiteList.fileKeepInfo.exported.propertyNames.has('otherElement2')).to.be.false; expect(fileWhiteList.fileKeepInfo.exported.propertyNames.has('o2')).to.be.true; }); + it('decorate collect test', function () { + const filePath = 'test/ut/utils/apiTest_collectFileWhiteList/collectFileWhiteList02.ets' + const fileList: Set = new Set([filePath]); + let config: IOptions = { + mNameObfuscation: { + mEnable: true, + mReservedProperties: [], + mRenameProperties: true, + mKeepStringProperty: false, + mTopLevel: false, + mNameGeneratorType: NameGeneratorType.ORDERED, + mReservedNames: [], + mReservedToplevelNames: [] + } + }; + let cachePath = 'test/ut/utils/obfuscation'; + initProjectWhiteListManager(cachePath, false, false); + let projectAndLibs: ReseverdSetForArkguard = + readProjectPropertiesByCollectedPaths(fileList, + { + mNameObfuscation: config.mNameObfuscation, + mExportObfuscation: true, + mKeepFileSourceCode: { + mKeepSourceOfPaths: new Set(), + mkeepFilesAndDependencies: new Set(), + } + }, true, true); + const fileWhiteList: FileWhiteList = projectWhiteListManager!.getFileWhiteListMap().get(filePath)!; + if (fileWhiteList?.bytecodeObfuscateKeepInfo?.decoratorMap) { + const decoratorKeys = Object.keys(fileWhiteList.bytecodeObfuscateKeepInfo.decoratorMap); + expect(decoratorKeys.length).to.be.greaterThan(0); + } + }); + }); + + describe('test initScanProjectConfig', function () { + it('scanDecorator is false', function () { + let customProfiles = {} + initScanProjectConfig(customProfiles, false, false) + expect(scanProjectConfig.scanDecorator).to.be.false; + }); + + it('scanDecorator is default', function () { + let customProfiles = {} + initScanProjectConfig(customProfiles, false) + expect(scanProjectConfig.scanDecorator).to.be.false; + }); + + it('scanDecorator is true', function () { + let customProfiles = {} + initScanProjectConfig(customProfiles, false, true) + expect(scanProjectConfig.scanDecorator).to.be.true; + }); }); }); \ No newline at end of file diff --git a/arkguard/test/ut/utils/ProjectCollections.spec.ts b/arkguard/test/ut/utils/ProjectCollections.spec.ts index fc121436aa..1695ac1e82 100644 --- a/arkguard/test/ut/utils/ProjectCollections.spec.ts +++ b/arkguard/test/ut/utils/ProjectCollections.spec.ts @@ -354,6 +354,24 @@ describe('test for CommonCollections', function () { expect(projectWhiteListManager.getShouldReObfuscate()).to.be.false; }); }); + + describe('test for createProjectWhiteList when bytecodeObfuscate enable', function () { + it('should add property decorated to projectWhiteList when bytecodeObfuscate enable)', () => { + let projectWhiteListManager = new ProjectWhiteListManager(cachePath, false, false); + projectWhiteListManager.setCurrentCollector("testPath5") + const fileWhiteLists = projectWhiteListManager.createFileWhiteList(); + fileWhiteLists.bytecodeObfuscateKeepInfo = { + "decoratorMap": { + "Track": ["prop1"] + } + }; + projectWhiteListManager.getFileWhiteListMap().set("testPath5", fileWhiteLists); + projectWhiteListManager.createOrUpdateWhiteListCaches(); + const cacheContent = fs.readFileSync(projectWhiteListManager.getProjectWhiteListCachePath(), 'utf-8'); + const parsedCache = JSON.parse(cacheContent); + expect(parsedCache.projectKeepInfo.globalNames).to.include("prop1"); + }); + }) }) describe('test for FilePathManager', function () { diff --git a/arkguard/test/ut/utils/apiTest_collectFileWhiteList/collectFileWhiteList02.ets b/arkguard/test/ut/utils/apiTest_collectFileWhiteList/collectFileWhiteList02.ets new file mode 100644 index 0000000000..a6464b217c --- /dev/null +++ b/arkguard/test/ut/utils/apiTest_collectFileWhiteList/collectFileWhiteList02.ets @@ -0,0 +1,8 @@ +@ObservedV2 +class son{ + @Trace aaaa:number=100; +} + +class father{ + bbb:number=100; +} \ No newline at end of file -- Gitee From e19ad1e3e6c65172c1076caa6e0c422e124bf4b9 Mon Sep 17 00:00:00 2001 From: zhongmingwei Date: Mon, 14 Apr 2025 21:36:47 +0800 Subject: [PATCH 153/268] Annotations bugfix Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC78O9 Description: fix some annotaton bug Signed-off-by: zhongmingwei Change-Id: Ib44a4d045f1efd075f82c6d06077037cb3f16c5c --- es2panda/aot/options.cpp | 4 +- es2panda/compiler/core/emitter/emitter.cpp | 4 +- es2panda/ir/base/annotation.h | 5 +- es2panda/lexer/token/token.h | 5 + es2panda/parser/parserImpl.cpp | 77 +- es2panda/parser/parserImpl.h | 8 +- es2panda/parser/program/program.cpp | 2 + es2panda/parser/program/program.h | 2 +- es2panda/parser/statementParser.cpp | 10 +- .../test-ts-identical-annotations-exec.ts | 2 +- .../test-ts-identical-annotations.ts | 2 +- .../test-ts-export-annotations.ts | 5 +- .../test-ts-import-annotations-exec.ts | 14 +- .../test-ts-export-annotations.ts | 4 +- .../test-ts-import-annotations-exec.ts | 2 +- .../declaration-3d-array-boolean.ts | 6 +- .../declaration-3d-array-enum-number.ts | 6 +- .../declaration-3d-array-enum-string.ts | 6 +- .../declaration-3d-array-number.ts | 6 +- .../declaration-3d-array-string.ts | 6 +- .../annotations/declaration-array-boolean.ts | 6 +- .../declaration-array-enum-number.ts | 6 +- .../declaration-array-enum-string.ts | 6 +- .../annotations/declaration-array-number.ts | 6 +- .../annotations/declaration-array-string.ts | 6 +- .../annotations/declaration-boolean.ts | 4 +- .../annotations/declaration-combination.ts | 2 +- .../compiler/annotations/declaration-empty.ts | 2 +- .../annotations/declaration-enum-number.ts | 4 +- .../annotations/declaration-enum-string.ts | 4 +- .../annotations/declaration-number.ts | 6 +- .../annotations/declaration-string.ts | 4 +- .../declaration-usage-3d-array-boolean.ts | 2 +- .../declaration-usage-3d-array-enum-number.ts | 2 +- .../declaration-usage-3d-array-enum-string.ts | 2 +- .../declaration-usage-3d-array-number.ts | 2 +- .../declaration-usage-3d-array-string.ts | 2 +- .../declaration-usage-array-boolean.ts | 2 +- .../declaration-usage-array-enum-number.ts | 2 +- .../declaration-usage-array-enum-string.ts | 2 +- .../declaration-usage-array-number.ts | 2 +- .../declaration-usage-array-string.ts | 2 +- .../annotations/declaration-usage-boolean.ts | 2 +- .../declaration-usage-combination.ts | 2 +- .../annotations/declaration-usage-empty.ts | 2 +- .../declaration-usage-enum-number.ts | 2 +- .../declaration-usage-enum-string.ts | 2 +- .../annotations/declaration-usage-number.ts | 2 +- .../annotations/declaration-usage-string.ts | 2 +- es2panda/test/compiler/annotations/export.ts | 4 +- .../annotations/multiple-annotations.ts | 6 +- .../abcinputs/bytecodehar.txt | 2 + .../bytecodehar-dynamic-import.ts | 61 + .../bytecodehar-static-import.ts | 43 + .../compileContextInfo.json | 12 + .../hap-file-exec-expected.pa.txt | 1670 ++++++++++++++++ .../hap-file-exec.ts | 24 + .../importfile1.ts | 16 + .../importfile2.ts | 16 + .../importfile3.ts | 16 + .../importfile4.ts | 16 + .../recordnames.txt | 7 + .../abcinputs/bytecodehar1.txt | 2 + .../abcinputs/bytecodehar2.txt | 2 + .../bytecodehar1-file1.ts | 28 + .../bytecodehar1-file2.ts | 28 + .../bytecodehar2-file1.ts | 25 + .../bytecodehar2-file2.ts | 25 + .../compileContextInfo.json | 44 + .../hap-file-exec-expected.pa.txt | 1354 +++++++++++++ .../hap-file-exec.ts | 24 + .../recordnames.txt | 7 + .../sourcehar-file1.ts | 20 + .../sourcehar-file2.ts | 18 + .../abcinputs/bytecodehar.txt | 2 + .../bytecodehar-dynamic-import.ts | 61 + .../bytecodehar-static-import.ts | 43 + .../compileContextInfo.json | 17 + .../importfile1.ts | 16 + .../importfile2.ts | 16 + .../importfile3.ts | 16 + .../importfile4.ts | 16 + .../inter-app-hsp-file-exec-expected.pa.txt | 1508 +++++++++++++++ .../inter-app-hsp-file-exec.ts | 24 + .../recordnames.txt | 7 + .../abcinputs/bytecodehar1.txt | 2 + .../abcinputs/bytecodehar2.txt | 2 + .../bytecodehar1-file1.ts | 34 + .../bytecodehar1-file2.ts | 40 + .../bytecodehar2-file1.ts | 25 + .../bytecodehar2-file2.ts | 25 + .../compileContextInfo.json | 44 + .../hap-file-exec-expected.pa.txt | 1340 +++++++++++++ .../hap-file-exec.ts | 24 + .../recordnames.txt | 7 + .../sourcehar-file1.ts | 18 + .../sourcehar-file2.ts | 18 + .../abcinputs/bytecodehar.txt | 2 + .../bytecodehar-dynamic-import.ts | 61 + .../bytecodehar-static-import.ts | 43 + .../compileContextInfo.json | 53 + .../hap-file-exec-expected.pa.txt | 1670 ++++++++++++++++ .../hap-file-exec.ts | 24 + .../importfile1.ts | 16 + .../importfile2.ts | 16 + .../importfile3.ts | 16 + .../importfile4.ts | 16 + .../recordnames.txt | 7 + .../abcinputs/bytecodehar1.txt | 2 + .../abcinputs/bytecodehar2.txt | 2 + .../bytecodehar1-file1.ts | 28 + .../bytecodehar1-file2.ts | 28 + .../bytecodehar2-file1.ts | 25 + .../bytecodehar2-file2.ts | 25 + .../compileContextInfo.json | 13 + .../hap-file-exec-expected.pa.txt | 1354 +++++++++++++ .../hap-file-exec.ts | 24 + .../recordnames.txt | 7 + .../sourcehar-file1.ts | 20 + .../sourcehar-file2.ts | 18 + .../abcinputs/bytecodehar1.txt | 2 + .../abcinputs/bytecodehar2.txt | 2 + .../bytecodehar1-file1.ts | 28 + .../bytecodehar1-file2.ts | 28 + .../bytecodehar2-file1.ts | 25 + .../bytecodehar2-file2.ts | 25 + .../compileContextInfo.json | 13 + .../hap-file-exec-expected.pa.txt | 1718 +++++++++++++++++ .../hap-file-exec.ts | 26 + .../mod/hap-add-file.ts | 20 + .../recordnames.txt | 8 + .../sourcehar-file1.ts | 20 + .../sourcehar-file2.ts | 18 + es2panda/test/config.py | 10 + .../declaration-3d-array-boolean-expected.txt | 12 +- .../declaration-3d-array-boolean.ts | 6 +- ...laration-3d-array-enum-number-expected.txt | 12 +- .../declaration-3d-array-enum-number.ts | 6 +- ...laration-3d-array-enum-string-expected.txt | 12 +- .../declaration-3d-array-enum-string.ts | 6 +- .../declaration-3d-array-number-expected.txt | 12 +- .../declaration-3d-array-number.ts | 6 +- .../declaration-3d-array-string-expected.txt | 12 +- .../declaration-3d-array-string.ts | 6 +- .../declaration-array-boolean-expected.txt | 12 +- .../annotations/declaration-array-boolean.ts | 6 +- ...declaration-array-enum-number-expected.txt | 12 +- .../declaration-array-enum-number.ts | 6 +- ...declaration-array-enum-string-expected.txt | 12 +- .../declaration-array-enum-string.ts | 6 +- .../declaration-array-number-expected.txt | 12 +- .../annotations/declaration-array-number.ts | 6 +- .../declaration-array-string-expected.txt | 12 +- .../annotations/declaration-array-string.ts | 6 +- .../declaration-boolean-expected.txt | 8 +- .../parser/annotations/declaration-boolean.ts | 4 +- .../declaration-combination-expected.txt | 4 +- .../annotations/declaration-combination.ts | 2 +- .../declaration-empty-expected.txt | 10 +- .../parser/annotations/declaration-empty.ts | 2 +- .../declaration-enum-number-expected.txt | 8 +- .../annotations/declaration-enum-number.ts | 4 +- .../declaration-enum-string-expected.txt | 8 +- .../annotations/declaration-enum-string.ts | 4 +- .../declaration-number-expected.txt | 8 +- .../parser/annotations/declaration-number.ts | 4 +- .../declaration-string-expected.txt | 8 +- .../parser/annotations/declaration-string.ts | 4 +- ...ration-usage-3d-array-boolean-expected.txt | 8 +- .../declaration-usage-3d-array-boolean.ts | 2 +- ...on-usage-3d-array-enum-number-expected.txt | 8 +- .../declaration-usage-3d-array-enum-number.ts | 2 +- ...on-usage-3d-array-enum-string-expected.txt | 8 +- .../declaration-usage-3d-array-enum-string.ts | 2 +- ...aration-usage-3d-array-number-expected.txt | 8 +- .../declaration-usage-3d-array-number.ts | 2 +- ...aration-usage-3d-array-string-expected.txt | 8 +- .../declaration-usage-3d-array-string.ts | 2 +- ...claration-usage-array-boolean-expected.txt | 8 +- .../declaration-usage-array-boolean.ts | 2 +- ...ation-usage-array-enum-number-expected.txt | 8 +- .../declaration-usage-array-enum-number.ts | 2 +- ...ation-usage-array-enum-string-expected.txt | 8 +- .../declaration-usage-array-enum-string.ts | 2 +- ...eclaration-usage-array-number-expected.txt | 8 +- .../declaration-usage-array-number.ts | 2 +- ...eclaration-usage-array-string-expected.txt | 8 +- .../declaration-usage-array-string.ts | 2 +- .../declaration-usage-boolean-expected.txt | 8 +- .../annotations/declaration-usage-boolean.ts | 2 +- ...declaration-usage-combination-expected.txt | 8 +- .../declaration-usage-combination.ts | 2 +- .../declaration-usage-empty-expected.txt | 16 +- .../annotations/declaration-usage-empty.ts | 2 +- ...declaration-usage-enum-number-expected.txt | 8 +- .../declaration-usage-enum-number.ts | 2 +- ...declaration-usage-enum-string-expected.txt | 8 +- .../declaration-usage-enum-string.ts | 2 +- .../declaration-usage-number-expected.txt | 8 +- .../annotations/declaration-usage-number.ts | 2 +- .../declaration-usage-string-expected.txt | 8 +- .../annotations/declaration-usage-string.ts | 2 +- .../parser/annotations/export-expected.txt | 20 +- es2panda/test/parser/annotations/export.ts | 4 +- .../annotations/import-qualified-expected.txt | 72 +- .../parser/annotations/import-qualified.ts | 12 +- .../import-unqualified-expected.txt | 8 +- .../multiple-annotations-expected.txt | 24 +- .../annotations/multiple-annotations.ts | 6 +- es2panda/test/runner.py | 65 +- ...supported_compile_asm_version-expected.txt | 3 +- ...supported_compile_asm_version-expected.txt | 3 +- ...d_unsupported_compile_version-expected.txt | 3 +- ...d_unsupported_compile_version-expected.txt | 3 +- ...y_unsupported_compile_version-expected.txt | 3 +- ...supported_compile_asm_version-expected.txt | 4 +- ...supported_compile_asm_version-expected.txt | 4 +- ...t_unsupported_compile_version-expected.txt | 4 +- .../derived-class-default-constructor-opt.js | 0 ...runtime_below_abc_api_version-expected.txt | 0 ...supported_compile_asm_version-expected.txt | 0 ...opt_supported_runtime_version-expected.txt | 0 ..._below_API12beta3_asm_version-expected.txt | 0 ...ual_to_API12beta3_asm_version-expected.txt | 0 ...t_unsupported_runtime_version-expected.txt | 0 .../bytecode_feature/sendable-class-export.ts | 0 ...runtime_below_abc_api_version-expected.txt | 0 ...supported_compile_asm_version-expected.txt | 0 ...ort_supported_runtime_version-expected.txt | 0 ...supported_compile_asm_version-expected.txt | 0 ...e_for_below_API11_asm_version-expected.txt | 0 ...ual_to_API12beta3_asm_version-expected.txt | 0 ...t_unsupported_runtime_version-expected.txt | 0 .../API20/bytecode_feature/annotations.ts | 22 + ...runtime_below_abc_api_version-expected.txt | 1 + ...supported_compile_asm_version-expected.txt | 24 + ...ons_supported_runtime_version-expected.txt | 0 ...supported_compile_asm_version-expected.txt | 3 + es2panda/util/commonUtil.h | 1 + es2panda/util/helpers.cpp | 38 +- es2panda/util/helpers.h | 4 + 241 files changed, 12788 insertions(+), 433 deletions(-) create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/abcinputs/bytecodehar.txt create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/bytecodehar-dynamic-import.ts create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/bytecodehar-static-import.ts create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/compileContextInfo.json create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/hap-file-exec-expected.pa.txt create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/hap-file-exec.ts create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/importfile1.ts create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/importfile2.ts create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/importfile3.ts create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/importfile4.ts create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/recordnames.txt create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/abcinputs/bytecodehar1.txt create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/abcinputs/bytecodehar2.txt create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/bytecodehar1-file1.ts create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/bytecodehar1-file2.ts create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/bytecodehar2-file1.ts create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/bytecodehar2-file2.ts create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/compileContextInfo.json create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/hap-file-exec-expected.pa.txt create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/hap-file-exec.ts create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/recordnames.txt create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/sourcehar-file1.ts create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/sourcehar-file2.ts create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/abcinputs/bytecodehar.txt create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/bytecodehar-dynamic-import.ts create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/bytecodehar-static-import.ts create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/compileContextInfo.json create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/importfile1.ts create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/importfile2.ts create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/importfile3.ts create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/importfile4.ts create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/inter-app-hsp-file-exec-expected.pa.txt create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/inter-app-hsp-file-exec.ts create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/recordnames.txt create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/abcinputs/bytecodehar1.txt create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/abcinputs/bytecodehar2.txt create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/bytecodehar1-file1.ts create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/bytecodehar1-file2.ts create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/bytecodehar2-file1.ts create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/bytecodehar2-file2.ts create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/compileContextInfo.json create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/hap-file-exec-expected.pa.txt create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/hap-file-exec.ts create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/recordnames.txt create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/sourcehar-file1.ts create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/sourcehar-file2.ts create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/abcinputs/bytecodehar.txt create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/bytecodehar-dynamic-import.ts create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/bytecodehar-static-import.ts create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/compileContextInfo.json create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/hap-file-exec-expected.pa.txt create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/hap-file-exec.ts create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/importfile1.ts create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/importfile2.ts create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/importfile3.ts create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/importfile4.ts create mode 100644 es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/recordnames.txt create mode 100644 es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/abcinputs/bytecodehar1.txt create mode 100644 es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/abcinputs/bytecodehar2.txt create mode 100644 es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/bytecodehar1-file1.ts create mode 100644 es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/bytecodehar1-file2.ts create mode 100644 es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/bytecodehar2-file1.ts create mode 100644 es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/bytecodehar2-file2.ts create mode 100644 es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/compileContextInfo.json create mode 100644 es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/hap-file-exec-expected.pa.txt create mode 100644 es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/hap-file-exec.ts create mode 100644 es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/recordnames.txt create mode 100644 es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/sourcehar-file1.ts create mode 100644 es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/sourcehar-file2.ts create mode 100644 es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/abcinputs/bytecodehar1.txt create mode 100644 es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/abcinputs/bytecodehar2.txt create mode 100644 es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/bytecodehar1-file1.ts create mode 100644 es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/bytecodehar1-file2.ts create mode 100644 es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/bytecodehar2-file1.ts create mode 100644 es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/bytecodehar2-file2.ts create mode 100644 es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/compileContextInfo.json create mode 100644 es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/hap-file-exec-expected.pa.txt create mode 100644 es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/hap-file-exec.ts create mode 100644 es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/mod/hap-add-file.ts create mode 100644 es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/recordnames.txt create mode 100644 es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/sourcehar-file1.ts create mode 100644 es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/sourcehar-file2.ts rename es2panda/test/version_control/{API16 => API18}/bytecode_feature/derived-class-default-constructor-opt.js (100%) rename es2panda/test/version_control/{API16 => API18}/bytecode_feature/derived-class-default-constructor-opt_runtime_below_abc_api_version-expected.txt (100%) rename es2panda/test/version_control/{API16 => API18}/bytecode_feature/derived-class-default-constructor-opt_supported_compile_asm_version-expected.txt (100%) rename es2panda/test/version_control/{API16 => API18}/bytecode_feature/derived-class-default-constructor-opt_supported_runtime_version-expected.txt (100%) rename es2panda/test/version_control/{API16 => API18}/bytecode_feature/derived-class-default-constructor-opt_unsupported_compile_for_below_API12beta3_asm_version-expected.txt (100%) rename es2panda/test/version_control/{API16 => API18}/bytecode_feature/derived-class-default-constructor-opt_unsupported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt (100%) rename es2panda/test/version_control/{API16 => API18}/bytecode_feature/derived-class-default-constructor-opt_unsupported_runtime_version-expected.txt (100%) rename es2panda/test/version_control/{API16 => API18}/bytecode_feature/sendable-class-export.ts (100%) rename es2panda/test/version_control/{API16 => API18}/bytecode_feature/sendable-class-export_runtime_below_abc_api_version-expected.txt (100%) rename es2panda/test/version_control/{API16 => API18}/bytecode_feature/sendable-class-export_supported_compile_asm_version-expected.txt (100%) rename es2panda/test/version_control/{API16 => API18}/bytecode_feature/sendable-class-export_supported_runtime_version-expected.txt (100%) rename es2panda/test/version_control/{API16 => API18}/bytecode_feature/sendable-class-export_unsupported_compile_asm_version-expected.txt (100%) rename es2panda/test/version_control/{API16 => API18}/bytecode_feature/sendable-class-export_unsupported_compile_for_below_API11_asm_version-expected.txt (100%) rename es2panda/test/version_control/{API16 => API18}/bytecode_feature/sendable-class-export_unsupported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt (100%) rename es2panda/test/version_control/{API16 => API18}/bytecode_feature/sendable-class-export_unsupported_runtime_version-expected.txt (100%) create mode 100644 es2panda/test/version_control/API20/bytecode_feature/annotations.ts create mode 100644 es2panda/test/version_control/API20/bytecode_feature/annotations_runtime_below_abc_api_version-expected.txt create mode 100644 es2panda/test/version_control/API20/bytecode_feature/annotations_supported_compile_asm_version-expected.txt create mode 100644 es2panda/test/version_control/API20/bytecode_feature/annotations_supported_runtime_version-expected.txt create mode 100644 es2panda/test/version_control/API20/bytecode_feature/annotations_unsupported_compile_asm_version-expected.txt diff --git a/es2panda/aot/options.cpp b/es2panda/aot/options.cpp index ccaa1d2a9a..bf96171397 100644 --- a/es2panda/aot/options.cpp +++ b/es2panda/aot/options.cpp @@ -420,8 +420,8 @@ bool Options::Parse(int argc, const char **argv) "bc-min-version are enabled, only bc-version will take effects"); panda::PandArg bcMinVersion("bc-min-version", false, "Print ark bytecode minimum supported version"); // todo(huyunhui): change default api verion to 0 after refactoring - // Current api version is 18 - panda::PandArg targetApiVersion("target-api-version", 18, + // Current api version is 20 + panda::PandArg targetApiVersion("target-api-version", 20, "Specify the targeting api version for es2abc to generated the corresponding version of bytecode"); panda::PandArg targetBcVersion("target-bc-version", false, "Print the corresponding ark bytecode version"\ "for target api version. If both target-bc-version and bc-version are enabled, only target-bc-version"\ diff --git a/es2panda/compiler/core/emitter/emitter.cpp b/es2panda/compiler/core/emitter/emitter.cpp index 5f760e5a3e..4bcc99004b 100644 --- a/es2panda/compiler/core/emitter/emitter.cpp +++ b/es2panda/compiler/core/emitter/emitter.cpp @@ -71,7 +71,9 @@ void FunctionEmitter::Generate(util::PatchFix *patchFixHelper) GenFunctionCatchTables(); GenLiteralBuffers(); GenConcurrentFunctionModuleRequests(); - GenAnnotations(); + if (pg_->Binder()->Program()->IsEnableAnnotations()) { + GenAnnotations(); + } if (patchFixHelper != nullptr) { patchFixHelper->ProcessFunction(pg_, func_, literalBuffers_); } diff --git a/es2panda/ir/base/annotation.h b/es2panda/ir/base/annotation.h index ce9c16f172..6df31ff5a5 100644 --- a/es2panda/ir/base/annotation.h +++ b/es2panda/ir/base/annotation.h @@ -20,8 +20,7 @@ #include #include #include - -#include +#include namespace panda::es2panda::compiler { class PandaGen; @@ -48,9 +47,7 @@ public: name_.insert(0, "."); expr = expr->AsMemberExpression()->Object(); } - name_.insert(0, expr->AsIdentifier()->Name().Utf8()); - name_.erase(0, std::strlen(annotationPrefix)); nameView_ = util::StringView(name_); } diff --git a/es2panda/lexer/token/token.h b/es2panda/lexer/token/token.h index 168af8dad0..383f9a1c22 100644 --- a/es2panda/lexer/token/token.h +++ b/es2panda/lexer/token/token.h @@ -85,6 +85,11 @@ public: return src_; } + void SetIdent(const util::StringView &ident) + { + src_ = ident; + } + const util::StringView &BigInt() const { ASSERT(type_ == TokenType::LITERAL_NUMBER && (flags_ & TokenFlags::NUMBER_BIGINT)); diff --git a/es2panda/parser/parserImpl.cpp b/es2panda/parser/parserImpl.cpp index 9b79f9e567..d92e9c42d2 100644 --- a/es2panda/parser/parserImpl.cpp +++ b/es2panda/parser/parserImpl.cpp @@ -117,7 +117,9 @@ Program ParserImpl::Parse(const SourceFile &sourceFile, const CompilerOptions &o program_.SetDebug(options.isDebug); program_.SetTargetApiVersion(options.targetApiVersion); program_.SetTargetApiSubVersion(options.targetApiSubVersion); - program_.SetEnableAnnotations(options.enableAnnotations); + if (util::Helpers::IsSupportAnnotationVersion(program_.TargetApiVersion())) { + program_.SetEnableAnnotations(options.enableAnnotations); + } program_.SetShared(sourceFile.isSharedModule); program_.SetModuleRecordFieldName(options.moduleRecordFieldName); program_.SetSourceLang(sourceFile.sourceLang); @@ -2786,6 +2788,47 @@ ir::Expression *ParserImpl::ParseClassKeyAnnotation() return nullptr; } +bool ParserImpl::CheckAnnotationPrefix(const util::StringView &Ident) +{ + auto prefixLen = std::strlen(ir::Annotation::annotationPrefix); + return Ident.Length() >= prefixLen && + Ident.Substr(0, prefixLen) == ir::Annotation::annotationPrefix; +} + +void ParserImpl::ThrowAnnotationNotEnable() +{ + std::string errMessage = + "Current configuration does not support using annotations. " + "Annotations can be used in the version of API 20 or higher versions.\n" + "Solutions: > Check the compatibleSdkVersion in build-profile.json5." + "> If compatibleSdkVersion is set to API 20 or higher version." + "> If you're running es2abc in commandline without IDE, please check whether target-api-version and " + "enable-annotations options are correctly configured."; + ThrowSyntaxError(errMessage); +} + +ir::Statement *ParserImpl::ParseAnnotationUsage(ir::Expression *expr, lexer::SourcePosition start) +{ + auto *exprTemp = expr; + if (exprTemp->IsCallExpression()) { + exprTemp = expr->AsCallExpression()->Callee(); + } + if (exprTemp->IsMemberExpression() || exprTemp->IsIdentifier()) { + auto *ident = exprTemp->IsIdentifier() ? exprTemp->AsIdentifier() + : exprTemp->AsMemberExpression()->Property()->AsIdentifier(); + if (CheckAnnotationPrefix(ident->Name())) { + if (!program_.IsEnableAnnotations()) { + ThrowAnnotationNotEnable(); + } + ident->SetName(ident->Name().Substr(std::strlen(ir::Annotation::annotationPrefix), ident->Name().Length())); + ir::Statement *resultAnnotation = static_cast(AllocNode(expr)); + resultAnnotation->SetRange({start, expr->End()}); + return resultAnnotation; + } + } + return nullptr; +} + ir::Statement *ParserImpl::ParseDecoratorAndAnnotation() { ASSERT(lexer_->GetToken().Type() == lexer::TokenType::PUNCTUATOR_AT); @@ -2794,23 +2837,22 @@ ir::Statement *ParserImpl::ParseDecoratorAndAnnotation() lexer::SourcePosition start = lexer_->GetToken().Start(); lexer_->NextToken(); // eat '@' - if (lexer_->GetToken().Type() == lexer::TokenType::LITERAL_IDENT && - lexer_->GetToken().Ident().Utf8().rfind(ir::Annotation::annotationPrefix, 0) != std::string_view::npos) { - // Annotation usage case - if (!program_.IsEnableAnnotations()) { - ThrowSyntaxError("Annotations are not enabled"); - } - ir::Expression *expr = ParseLeftHandSideExpression(); - ir::Statement *resultAnnotation = static_cast(AllocNode(expr)); - resultAnnotation->SetRange({start, expr->End()}); + ir::Expression *expr = ParseLeftHandSideExpression(); + auto *resultAnnotation = ParseAnnotationUsage(expr, start); + if (resultAnnotation != nullptr) { return resultAnnotation; } - ir::Expression *expr = ParseLeftHandSideExpression(); if (expr->IsIdentifier() && expr->AsIdentifier()->Name().Utf8() == ir::Annotation::interfaceString) { // Annotation declaration case if (!program_.IsEnableAnnotations()) { - ThrowSyntaxError("Annotations are not enabled"); + ThrowAnnotationNotEnable(); + } + + if (!CheckAnnotationPrefix(lexer_->GetToken().Ident())) { + std::stringstream ss; + ss << "Annotation declaration need to be prefixed with '" << ir::Annotation::annotationPrefix << "'"; + ThrowSyntaxError(ss.str()); } lexer_->Rewind(lexPos); return nullptr; @@ -3134,13 +3176,16 @@ bool ParserImpl::IsMethodDefinitionsAreSame(const ir::MethodDefinition *property return IsPropertyKeysAreSame(property->Key(), overload->Key()); } -ir::Identifier *ParserImpl::SetIdentNodeInClassDefinition(bool isDeclare, binder::ConstDecl **decl) +ir::Identifier *ParserImpl::SetIdentNodeInClassDefinition(bool isDeclare, binder::ConstDecl **decl, bool isAnnotation) { if (!isDeclare) { CheckStrictReservedWord(); } - const util::StringView &identStr = lexer_->GetToken().Ident(); + const util::StringView &identStr = + isAnnotation ? lexer_->GetToken().Ident().Substr(std::strlen(ir::Annotation::annotationPrefix), + lexer_->GetToken().Ident().Length()) + : lexer_->GetToken().Ident(); *decl = Binder()->AddDecl(lexer_->GetToken().Start(), isDeclare, identStr); @@ -3153,7 +3198,7 @@ ir::Identifier *ParserImpl::SetIdentNodeInClassDefinition(bool isDeclare, binder } ir::ClassDefinition *ParserImpl::ParseClassDefinition(bool isDeclaration, bool idRequired, bool isDeclare, - bool isAbstract) + bool isAbstract, bool isAnnotation) { isDeclare = isDeclare | (context_.Status() & ParserStatus::IN_AMBIENT_CONTEXT); lexer::SourcePosition startLoc = lexer_->GetToken().Start(); @@ -3167,7 +3212,7 @@ ir::ClassDefinition *ParserImpl::ParseClassDefinition(bool isDeclaration, bool i if ((lexer_->GetToken().Type() == lexer::TokenType::LITERAL_IDENT || lexer_->GetToken().Type() == lexer::TokenType::KEYW_AWAIT) && (Extension() != ScriptExtension::TS || lexer_->GetToken().KeywordType() != lexer::TokenType::KEYW_IMPLEMENTS)) { - identNode = SetIdentNodeInClassDefinition(isDeclare, &decl); + identNode = SetIdentNodeInClassDefinition(isDeclare, &decl, isAnnotation); } else if (isDeclaration && idRequired) { ThrowSyntaxError("Unexpected token, expected an identifier."); } diff --git a/es2panda/parser/parserImpl.h b/es2panda/parser/parserImpl.h index cf51697667..3254760260 100644 --- a/es2panda/parser/parserImpl.h +++ b/es2panda/parser/parserImpl.h @@ -322,7 +322,11 @@ private: void CheckClassGeneratorMethod(ClassElmentDescriptor *desc); void CheckClassPrivateIdentifier(ClassElmentDescriptor *desc); void CheckFieldKey(ir::Expression *propName); + bool CheckAnnotationPrefix(const util::StringView &Ident); + void ThrowAnnotationNotEnable(); + ir::Expression *ParseClassKeyAnnotation(); + ir::Statement *ParseAnnotationUsage(ir::Expression *expr, lexer::SourcePosition start); ir::Statement *ParseDecoratorAndAnnotation(); std::pair, ArenaVector> ParseDecoratorsAndAnnotations(); ir::Statement *ParseClassElement(const ArenaVector &properties, @@ -335,9 +339,9 @@ private: ir::MethodDefinition *CheckClassMethodOverload(ir::Statement *property, ir::MethodDefinition **ctor, bool isDeclare, lexer::SourcePosition errorInfo, ir::MethodDefinition *lastOverload, bool implExists, bool isAbstract = false); - ir::Identifier *SetIdentNodeInClassDefinition(bool isDeclare, binder::ConstDecl **decl); + ir::Identifier *SetIdentNodeInClassDefinition(bool isDeclare, binder::ConstDecl **decl, bool isAnnotation = false); ir::ClassDefinition *ParseClassDefinition(bool isDeclaration, bool idRequired = true, bool isDeclare = false, - bool isAbstract = false); + bool isAbstract = false, bool isAnnotation = false); ir::Expression *ParseSuperClass(bool isDeclare, bool *hasSuperClass, bool *isExtendsFromNull); ArenaVector ParseTSClassImplements(bool isDeclare); void ValidateClassConstructor(const ir::MethodDefinition *ctor, diff --git a/es2panda/parser/program/program.cpp b/es2panda/parser/program/program.cpp index a87107bf88..ed6e6ca1be 100644 --- a/es2panda/parser/program/program.cpp +++ b/es2panda/parser/program/program.cpp @@ -48,6 +48,7 @@ Program::Program(Program &&other) targetApiVersion_(other.targetApiVersion_), useDefineSemantic_(other.useDefineSemantic_), isShared_(other.isShared_), + enableAnnotations_(other.enableAnnotations_), targetApiSubVersion_(other.targetApiSubVersion_), moduleRecordFieldName_(other.moduleRecordFieldName_), sourceLang_(other.sourceLang_) @@ -78,6 +79,7 @@ Program &Program::operator=(Program &&other) targetApiVersion_ = other.targetApiVersion_; useDefineSemantic_ = other.useDefineSemantic_; isShared_ = other.isShared_; + enableAnnotations_ = other.enableAnnotations_; targetApiSubVersion_ = other.targetApiSubVersion_; moduleRecordFieldName_ = other.moduleRecordFieldName_; sourceLang_ = other.sourceLang_; diff --git a/es2panda/parser/program/program.h b/es2panda/parser/program/program.h index 050cf23457..cba731c6c7 100644 --- a/es2panda/parser/program/program.h +++ b/es2panda/parser/program/program.h @@ -230,7 +230,7 @@ public: enableAnnotations_ = enableAnnotations; } - bool IsEnableAnnotations() + bool IsEnableAnnotations() const { return enableAnnotations_; } diff --git a/es2panda/parser/statementParser.cpp b/es2panda/parser/statementParser.cpp index a5f16176d7..b158dbae4e 100644 --- a/es2panda/parser/statementParser.cpp +++ b/es2panda/parser/statementParser.cpp @@ -690,7 +690,7 @@ ir::ClassDeclaration *ParserImpl::ParseClassDeclaration(bool idRequired, ArenaVe bool isAbstract, bool isExported, bool isAnnotation) { lexer::SourcePosition startLoc = lexer_->GetToken().Start(); - ir::ClassDefinition *classDefinition = ParseClassDefinition(true, idRequired, isDeclare, isAbstract); + ir::ClassDefinition *classDefinition = ParseClassDefinition(true, idRequired, isDeclare, isAbstract, isAnnotation); if (isExported && !idRequired) { classDefinition->SetAsExportDefault(); } @@ -2610,6 +2610,10 @@ ir::ExportNamedDeclaration *ParserImpl::ParseExportNamedSpecifiers(const lexer:: } lexer::Token localToken = lexer_->GetToken(); + if (program_.IsEnableAnnotations() && CheckAnnotationPrefix(lexer_->GetToken().Ident())) { + localToken.SetIdent(lexer_->GetToken().Ident().Substr(std::strlen(ir::Annotation::annotationPrefix), + lexer_->GetToken().Ident().Length())); + } auto *local = AllocNode(lexer_->GetToken().Ident()); local->SetRange(lexer_->GetToken().Loc()); @@ -2990,6 +2994,10 @@ void ParserImpl::ParseNamedImportSpecifiers(ArenaVector *specifie } lexer::Token importedToken = lexer_->GetToken(); + if (program_.IsEnableAnnotations() && CheckAnnotationPrefix(lexer_->GetToken().Ident())) { + importedToken.SetIdent(lexer_->GetToken().Ident().Substr(std::strlen(ir::Annotation::annotationPrefix), + lexer_->GetToken().Ident().Length())); + } auto *imported = AllocNode(importedToken.Ident()); ir::Identifier *local = nullptr; imported->SetRange(lexer_->GetToken().Loc()); diff --git a/es2panda/test/compiler/annotations-projects/ts_identical_annotations_project/test-ts-identical-annotations-exec.ts b/es2panda/test/compiler/annotations-projects/ts_identical_annotations_project/test-ts-identical-annotations-exec.ts index 84370500e3..44f43d0ae8 100644 --- a/es2panda/test/compiler/annotations-projects/ts_identical_annotations_project/test-ts-identical-annotations-exec.ts +++ b/es2panda/test/compiler/annotations-projects/ts_identical_annotations_project/test-ts-identical-annotations-exec.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { a: number = 42 } diff --git a/es2panda/test/compiler/annotations-projects/ts_identical_annotations_project/test-ts-identical-annotations.ts b/es2panda/test/compiler/annotations-projects/ts_identical_annotations_project/test-ts-identical-annotations.ts index 56903a4827..49a9b8d2d8 100644 --- a/es2panda/test/compiler/annotations-projects/ts_identical_annotations_project/test-ts-identical-annotations.ts +++ b/es2panda/test/compiler/annotations-projects/ts_identical_annotations_project/test-ts-identical-annotations.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { b: boolean = true } diff --git a/es2panda/test/compiler/annotations-projects/ts_import_annotations_project_1/test-ts-export-annotations.ts b/es2panda/test/compiler/annotations-projects/ts_import_annotations_project_1/test-ts-export-annotations.ts index 8c10cc0628..2a5d2772fd 100644 --- a/es2panda/test/compiler/annotations-projects/ts_import_annotations_project_1/test-ts-export-annotations.ts +++ b/es2panda/test/compiler/annotations-projects/ts_import_annotations_project_1/test-ts-export-annotations.ts @@ -13,9 +13,9 @@ * limitations under the License. */ -export @interface Anno1 {} +export @interface __$$ETS_ANNOTATION$$__Anno1 {} -export @interface Anno2 { +export @interface __$$ETS_ANNOTATION$$__Anno2 { a: number = 0; } @@ -24,4 +24,3 @@ export class A {} @__$$ETS_ANNOTATION$$__Anno1() export default class B {} - diff --git a/es2panda/test/compiler/annotations-projects/ts_import_annotations_project_1/test-ts-import-annotations-exec.ts b/es2panda/test/compiler/annotations-projects/ts_import_annotations_project_1/test-ts-import-annotations-exec.ts index 446556e337..13ab7bdb6b 100644 --- a/es2panda/test/compiler/annotations-projects/ts_import_annotations_project_1/test-ts-import-annotations-exec.ts +++ b/es2panda/test/compiler/annotations-projects/ts_import_annotations_project_1/test-ts-import-annotations-exec.ts @@ -15,20 +15,20 @@ import * as Namespace1 from "./test-ts-export-annotations" -@__$$ETS_ANNOTATION$$__Namespace1.Anno() +@Namespace1.__$$ETS_ANNOTATION$$__Anno() class A {} -@__$$ETS_ANNOTATION$$__Namespace1.Anno +@Namespace1.__$$ETS_ANNOTATION$$__Anno class B {} -@__$$ETS_ANNOTATION$$__Namespace1.Anno1({a: 1, b: "string"}) +@Namespace1.__$$ETS_ANNOTATION$$__Anno1({a: 1, b: "string"}) class C {} -@__$$ETS_ANNOTATION$$__Namespace1.Namespace2.Namespace3.Anno2() +@Namespace1.Namespace2.Namespace3.__$$ETS_ANNOTATION$$__Anno2() class D {} -@__$$ETS_ANNOTATION$$__Namespace1.Namespace2.Namespace3.Anno2 +@Namespace1.Namespace2.Namespace3.__$$ETS_ANNOTATION$$__Anno2 class E {} -@__$$ETS_ANNOTATION$$__Namespace1.Namespace2.Namespace3.Anno3({a: 1, b: "string"}) -class F {} \ No newline at end of file +@Namespace1.Namespace2.Namespace3.__$$ETS_ANNOTATION$$__Anno3({a: 1, b: "string"}) +class F {} diff --git a/es2panda/test/compiler/annotations-projects/ts_import_annotations_project_2/test-ts-export-annotations.ts b/es2panda/test/compiler/annotations-projects/ts_import_annotations_project_2/test-ts-export-annotations.ts index 8c10cc0628..6bea13acdc 100644 --- a/es2panda/test/compiler/annotations-projects/ts_import_annotations_project_2/test-ts-export-annotations.ts +++ b/es2panda/test/compiler/annotations-projects/ts_import_annotations_project_2/test-ts-export-annotations.ts @@ -13,9 +13,9 @@ * limitations under the License. */ -export @interface Anno1 {} +export @interface __$$ETS_ANNOTATION$$__Anno1 {} -export @interface Anno2 { +export @interface __$$ETS_ANNOTATION$$__Anno2 { a: number = 0; } diff --git a/es2panda/test/compiler/annotations-projects/ts_import_annotations_project_2/test-ts-import-annotations-exec.ts b/es2panda/test/compiler/annotations-projects/ts_import_annotations_project_2/test-ts-import-annotations-exec.ts index 734f114a32..de240324b1 100644 --- a/es2panda/test/compiler/annotations-projects/ts_import_annotations_project_2/test-ts-import-annotations-exec.ts +++ b/es2panda/test/compiler/annotations-projects/ts_import_annotations_project_2/test-ts-import-annotations-exec.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -import { Anno1, Anno2 } from "./test-ts-export-annotations" +import { __$$ETS_ANNOTATION$$__Anno1, __$$ETS_ANNOTATION$$__Anno2 } from "./test-ts-export-annotations" @__$$ETS_ANNOTATION$$__Anno1 class A {} diff --git a/es2panda/test/compiler/annotations/declaration-3d-array-boolean.ts b/es2panda/test/compiler/annotations/declaration-3d-array-boolean.ts index 8bb5148dc7..b13f16c168 100644 --- a/es2panda/test/compiler/annotations/declaration-3d-array-boolean.ts +++ b/es2panda/test/compiler/annotations/declaration-3d-array-boolean.ts @@ -13,14 +13,14 @@ * limitations under the License. */ -@interface Anno1 { +@interface __$$ETS_ANNOTATION$$__Anno1 { a: boolean[][][]; } -@interface Anno2 { +@interface __$$ETS_ANNOTATION$$__Anno2 { a: boolean[][][] = [[new Array()]]; } -@interface Anno3 { +@interface __$$ETS_ANNOTATION$$__Anno3 { a: boolean[][][] = [[[true, false], [true, false]]]; } diff --git a/es2panda/test/compiler/annotations/declaration-3d-array-enum-number.ts b/es2panda/test/compiler/annotations/declaration-3d-array-enum-number.ts index 8f50c85fbf..bf399ee5c9 100644 --- a/es2panda/test/compiler/annotations/declaration-3d-array-enum-number.ts +++ b/es2panda/test/compiler/annotations/declaration-3d-array-enum-number.ts @@ -18,16 +18,16 @@ const enum E { B = -314 } -@interface Anno1 { +@interface __$$ETS_ANNOTATION$$__Anno1 { // without initializer in .ets source code with underlying number type a: E[][][] = [[new Array(0)]]; } -@interface Anno2 { +@interface __$$ETS_ANNOTATION$$__Anno2 { // with empty array initializer in .ets source code with underlying number type a: E[][][] = [[new Array(1)]]; } -@interface Anno3 { +@interface __$$ETS_ANNOTATION$$__Anno3 { a: E[][][] = [[[42, -314, 42]]]; } diff --git a/es2panda/test/compiler/annotations/declaration-3d-array-enum-string.ts b/es2panda/test/compiler/annotations/declaration-3d-array-enum-string.ts index 8eeef595d0..a24f1a805f 100644 --- a/es2panda/test/compiler/annotations/declaration-3d-array-enum-string.ts +++ b/es2panda/test/compiler/annotations/declaration-3d-array-enum-string.ts @@ -18,16 +18,16 @@ const enum E { B = "world!" } -@interface Anno1 { +@interface __$$ETS_ANNOTATION$$__Anno1 { // without initializer in .ets source code with underlying string type a: E[][][] = [[new Array(2)]]; } -@interface Anno2 { +@interface __$$ETS_ANNOTATION$$__Anno2 { // with empty array initializer in .ets source code with underlying string type a: E[][][] = [[new Array(3)]]; } -@interface Anno3 { +@interface __$$ETS_ANNOTATION$$__Anno3 { a: E[][][] = [[["Hello", "world!", "Hello"]]]; } diff --git a/es2panda/test/compiler/annotations/declaration-3d-array-number.ts b/es2panda/test/compiler/annotations/declaration-3d-array-number.ts index e83e604801..22d5141578 100644 --- a/es2panda/test/compiler/annotations/declaration-3d-array-number.ts +++ b/es2panda/test/compiler/annotations/declaration-3d-array-number.ts @@ -13,14 +13,14 @@ * limitations under the License. */ -@interface Anno1 { +@interface __$$ETS_ANNOTATION$$__Anno1 { a: number[][][]; } -@interface Anno2 { +@interface __$$ETS_ANNOTATION$$__Anno2 { a: number[][][] = [[new Array()]]; } -@interface Anno3 { +@interface __$$ETS_ANNOTATION$$__Anno3 { a: number[][][] = [[[1, -2, 3], [4, -5, 6]]]; } diff --git a/es2panda/test/compiler/annotations/declaration-3d-array-string.ts b/es2panda/test/compiler/annotations/declaration-3d-array-string.ts index 9d2d477d78..09a27904d4 100644 --- a/es2panda/test/compiler/annotations/declaration-3d-array-string.ts +++ b/es2panda/test/compiler/annotations/declaration-3d-array-string.ts @@ -13,14 +13,14 @@ * limitations under the License. */ -@interface Anno1 { +@interface __$$ETS_ANNOTATION$$__Anno1 { a: string[][][]; } -@interface Anno2 { +@interface __$$ETS_ANNOTATION$$__Anno2 { a: string[][][] = [[new Array()]]; } -@interface Anno3 { +@interface __$$ETS_ANNOTATION$$__Anno3 { a: string[][][] = [[["hello", "world"], ["hello", "world"]]]; } diff --git a/es2panda/test/compiler/annotations/declaration-array-boolean.ts b/es2panda/test/compiler/annotations/declaration-array-boolean.ts index b5e92f592d..c575410d77 100644 --- a/es2panda/test/compiler/annotations/declaration-array-boolean.ts +++ b/es2panda/test/compiler/annotations/declaration-array-boolean.ts @@ -13,14 +13,14 @@ * limitations under the License. */ -@interface Anno1 { +@interface __$$ETS_ANNOTATION$$__Anno1 { a: boolean[]; } -@interface Anno2 { +@interface __$$ETS_ANNOTATION$$__Anno2 { a: boolean[] = new Array(); } -@interface Anno3 { +@interface __$$ETS_ANNOTATION$$__Anno3 { a: boolean[] = [true, false, true]; } diff --git a/es2panda/test/compiler/annotations/declaration-array-enum-number.ts b/es2panda/test/compiler/annotations/declaration-array-enum-number.ts index d947e16c08..139e108acb 100644 --- a/es2panda/test/compiler/annotations/declaration-array-enum-number.ts +++ b/es2panda/test/compiler/annotations/declaration-array-enum-number.ts @@ -18,16 +18,16 @@ const enum E { B = -314 } -@interface Anno1 { +@interface __$$ETS_ANNOTATION$$__Anno1 { // without initializer in .ets source code with underlying number type a: E[] = new Array(0); } -@interface Anno2 { +@interface __$$ETS_ANNOTATION$$__Anno2 { // with empty array initializer in .ets source code with underlying number type a: E[] = new Array(1); } -@interface Anno3 { +@interface __$$ETS_ANNOTATION$$__Anno3 { a: E[] = [42, -314, 42]; } diff --git a/es2panda/test/compiler/annotations/declaration-array-enum-string.ts b/es2panda/test/compiler/annotations/declaration-array-enum-string.ts index a55745424c..39e7411e1a 100644 --- a/es2panda/test/compiler/annotations/declaration-array-enum-string.ts +++ b/es2panda/test/compiler/annotations/declaration-array-enum-string.ts @@ -18,16 +18,16 @@ const enum E { B = "world!" } -@interface Anno1 { +@interface __$$ETS_ANNOTATION$$__Anno1 { // without initializer in .ets source code with underlying string type a: E[] = new Array(2); } -@interface Anno2 { +@interface __$$ETS_ANNOTATION$$__Anno2 { // with empty array initializer in .ets source code with underlying string type a: E[] = new Array(3); } -@interface Anno3 { +@interface __$$ETS_ANNOTATION$$__Anno3 { a: E[] = ["Hello", "world!", "Hello"]; } diff --git a/es2panda/test/compiler/annotations/declaration-array-number.ts b/es2panda/test/compiler/annotations/declaration-array-number.ts index d573f6ebb3..13e7ce6232 100644 --- a/es2panda/test/compiler/annotations/declaration-array-number.ts +++ b/es2panda/test/compiler/annotations/declaration-array-number.ts @@ -13,14 +13,14 @@ * limitations under the License. */ -@interface Anno1 { +@interface __$$ETS_ANNOTATION$$__Anno1 { a: number[]; } -@interface Anno2 { +@interface __$$ETS_ANNOTATION$$__Anno2 { a: number[] = new Array(); } -@interface Anno3 { +@interface __$$ETS_ANNOTATION$$__Anno3 { a: number[] = [1, -2, 3]; } diff --git a/es2panda/test/compiler/annotations/declaration-array-string.ts b/es2panda/test/compiler/annotations/declaration-array-string.ts index 69cfe97efc..2de6642e24 100644 --- a/es2panda/test/compiler/annotations/declaration-array-string.ts +++ b/es2panda/test/compiler/annotations/declaration-array-string.ts @@ -13,14 +13,14 @@ * limitations under the License. */ -@interface Anno1 { +@interface __$$ETS_ANNOTATION$$__Anno1 { a: string[]; } -@interface Anno2 { +@interface __$$ETS_ANNOTATION$$__Anno2 { a: string[] = new Array(); } -@interface Anno3 { +@interface __$$ETS_ANNOTATION$$__Anno3 { a: string[] = ["Hello", "world", "!"]; } diff --git a/es2panda/test/compiler/annotations/declaration-boolean.ts b/es2panda/test/compiler/annotations/declaration-boolean.ts index e9bf814b7e..086025dbd9 100644 --- a/es2panda/test/compiler/annotations/declaration-boolean.ts +++ b/es2panda/test/compiler/annotations/declaration-boolean.ts @@ -13,10 +13,10 @@ * limitations under the License. */ -@interface Anno1 { +@interface __$$ETS_ANNOTATION$$__Anno1 { a: boolean; } -@interface Anno2 { +@interface __$$ETS_ANNOTATION$$__Anno2 { a: boolean = true; } \ No newline at end of file diff --git a/es2panda/test/compiler/annotations/declaration-combination.ts b/es2panda/test/compiler/annotations/declaration-combination.ts index 15fa1399e4..7eaa0d8662 100644 --- a/es2panda/test/compiler/annotations/declaration-combination.ts +++ b/es2panda/test/compiler/annotations/declaration-combination.ts @@ -24,7 +24,7 @@ const enum E1 { B = "world" } -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { a: number b: number[] = [13, -10] c: string diff --git a/es2panda/test/compiler/annotations/declaration-empty.ts b/es2panda/test/compiler/annotations/declaration-empty.ts index 4d205f1d28..80ae4e05b8 100644 --- a/es2panda/test/compiler/annotations/declaration-empty.ts +++ b/es2panda/test/compiler/annotations/declaration-empty.ts @@ -13,4 +13,4 @@ * limitations under the License. */ -@interface Anno {} +@interface __$$ETS_ANNOTATION$$__Anno {} diff --git a/es2panda/test/compiler/annotations/declaration-enum-number.ts b/es2panda/test/compiler/annotations/declaration-enum-number.ts index 095d97c985..74f8289004 100644 --- a/es2panda/test/compiler/annotations/declaration-enum-number.ts +++ b/es2panda/test/compiler/annotations/declaration-enum-number.ts @@ -18,11 +18,11 @@ const enum E { B = 314 } -@interface Anno1 { +@interface __$$ETS_ANNOTATION$$__Anno1 { // No initializer with underlying type number a: E = new Number(0) as number; } -@interface Anno2 { +@interface __$$ETS_ANNOTATION$$__Anno2 { a: E = 42; } \ No newline at end of file diff --git a/es2panda/test/compiler/annotations/declaration-enum-string.ts b/es2panda/test/compiler/annotations/declaration-enum-string.ts index 668b13ba51..e8f77e41a2 100644 --- a/es2panda/test/compiler/annotations/declaration-enum-string.ts +++ b/es2panda/test/compiler/annotations/declaration-enum-string.ts @@ -18,11 +18,11 @@ const enum E { B = "world!" } -@interface Anno1 { +@interface __$$ETS_ANNOTATION$$__Anno1 { // No initializer with underlying type string a: E; } -@interface Anno2 { +@interface __$$ETS_ANNOTATION$$__Anno2 { a: E = "Hello"; } \ No newline at end of file diff --git a/es2panda/test/compiler/annotations/declaration-number.ts b/es2panda/test/compiler/annotations/declaration-number.ts index 47f96358bc..241b690977 100644 --- a/es2panda/test/compiler/annotations/declaration-number.ts +++ b/es2panda/test/compiler/annotations/declaration-number.ts @@ -13,14 +13,14 @@ * limitations under the License. */ -@interface Anno1 { +@interface __$$ETS_ANNOTATION$$__Anno1 { a: number; } -@interface Anno2 { +@interface __$$ETS_ANNOTATION$$__Anno2 { a: number = 42; } -@interface Anno3 { +@interface __$$ETS_ANNOTATION$$__Anno3 { a: number = -314; } \ No newline at end of file diff --git a/es2panda/test/compiler/annotations/declaration-string.ts b/es2panda/test/compiler/annotations/declaration-string.ts index 2f67dfdc93..52e9959461 100644 --- a/es2panda/test/compiler/annotations/declaration-string.ts +++ b/es2panda/test/compiler/annotations/declaration-string.ts @@ -13,10 +13,10 @@ * limitations under the License. */ -@interface Anno1 { +@interface __$$ETS_ANNOTATION$$__Anno1 { a: string; } -@interface Anno2 { +@interface __$$ETS_ANNOTATION$$__Anno2 { a: string = "Hello world!"; } \ No newline at end of file diff --git a/es2panda/test/compiler/annotations/declaration-usage-3d-array-boolean.ts b/es2panda/test/compiler/annotations/declaration-usage-3d-array-boolean.ts index b228a7be88..e707f942b5 100644 --- a/es2panda/test/compiler/annotations/declaration-usage-3d-array-boolean.ts +++ b/es2panda/test/compiler/annotations/declaration-usage-3d-array-boolean.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { a: boolean[][][]; } diff --git a/es2panda/test/compiler/annotations/declaration-usage-3d-array-enum-number.ts b/es2panda/test/compiler/annotations/declaration-usage-3d-array-enum-number.ts index 4439bb4464..3c503d4bdc 100644 --- a/es2panda/test/compiler/annotations/declaration-usage-3d-array-enum-number.ts +++ b/es2panda/test/compiler/annotations/declaration-usage-3d-array-enum-number.ts @@ -18,7 +18,7 @@ const enum E { B = -2 } -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { a: E[][][] = [[new Array(0)]]; } diff --git a/es2panda/test/compiler/annotations/declaration-usage-3d-array-enum-string.ts b/es2panda/test/compiler/annotations/declaration-usage-3d-array-enum-string.ts index 3ea8b4242b..175a0dcb7a 100644 --- a/es2panda/test/compiler/annotations/declaration-usage-3d-array-enum-string.ts +++ b/es2panda/test/compiler/annotations/declaration-usage-3d-array-enum-string.ts @@ -18,7 +18,7 @@ const enum E { B = "world" } -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { a: E[][][] = [[new Array(2)]]; } diff --git a/es2panda/test/compiler/annotations/declaration-usage-3d-array-number.ts b/es2panda/test/compiler/annotations/declaration-usage-3d-array-number.ts index 880fe4b3a0..9dbe6711ed 100644 --- a/es2panda/test/compiler/annotations/declaration-usage-3d-array-number.ts +++ b/es2panda/test/compiler/annotations/declaration-usage-3d-array-number.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { a: number[][][]; } diff --git a/es2panda/test/compiler/annotations/declaration-usage-3d-array-string.ts b/es2panda/test/compiler/annotations/declaration-usage-3d-array-string.ts index 8bdbb7118e..37e8437d72 100644 --- a/es2panda/test/compiler/annotations/declaration-usage-3d-array-string.ts +++ b/es2panda/test/compiler/annotations/declaration-usage-3d-array-string.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { a: string[][][]; } diff --git a/es2panda/test/compiler/annotations/declaration-usage-array-boolean.ts b/es2panda/test/compiler/annotations/declaration-usage-array-boolean.ts index 06ae0c9957..cd8fece827 100644 --- a/es2panda/test/compiler/annotations/declaration-usage-array-boolean.ts +++ b/es2panda/test/compiler/annotations/declaration-usage-array-boolean.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { a: boolean[]; } diff --git a/es2panda/test/compiler/annotations/declaration-usage-array-enum-number.ts b/es2panda/test/compiler/annotations/declaration-usage-array-enum-number.ts index 03162a2def..07c2b6bb2f 100644 --- a/es2panda/test/compiler/annotations/declaration-usage-array-enum-number.ts +++ b/es2panda/test/compiler/annotations/declaration-usage-array-enum-number.ts @@ -18,7 +18,7 @@ const enum E { B = -2, } -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { a: E[] = new Array(0); } diff --git a/es2panda/test/compiler/annotations/declaration-usage-array-enum-string.ts b/es2panda/test/compiler/annotations/declaration-usage-array-enum-string.ts index aa3bd9c9fb..52742a3241 100644 --- a/es2panda/test/compiler/annotations/declaration-usage-array-enum-string.ts +++ b/es2panda/test/compiler/annotations/declaration-usage-array-enum-string.ts @@ -18,7 +18,7 @@ const enum E { B = "world", } -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { a: E[] = new Array(2); } diff --git a/es2panda/test/compiler/annotations/declaration-usage-array-number.ts b/es2panda/test/compiler/annotations/declaration-usage-array-number.ts index e2003df66c..2fe6ab909a 100644 --- a/es2panda/test/compiler/annotations/declaration-usage-array-number.ts +++ b/es2panda/test/compiler/annotations/declaration-usage-array-number.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { a: number[]; } diff --git a/es2panda/test/compiler/annotations/declaration-usage-array-string.ts b/es2panda/test/compiler/annotations/declaration-usage-array-string.ts index c14f9d9d8f..c00fe674fc 100644 --- a/es2panda/test/compiler/annotations/declaration-usage-array-string.ts +++ b/es2panda/test/compiler/annotations/declaration-usage-array-string.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { a: string[]; } diff --git a/es2panda/test/compiler/annotations/declaration-usage-boolean.ts b/es2panda/test/compiler/annotations/declaration-usage-boolean.ts index b47a207848..3e7da49918 100644 --- a/es2panda/test/compiler/annotations/declaration-usage-boolean.ts +++ b/es2panda/test/compiler/annotations/declaration-usage-boolean.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { a: boolean; } diff --git a/es2panda/test/compiler/annotations/declaration-usage-combination.ts b/es2panda/test/compiler/annotations/declaration-usage-combination.ts index ca3633d57a..30fa5b53c6 100644 --- a/es2panda/test/compiler/annotations/declaration-usage-combination.ts +++ b/es2panda/test/compiler/annotations/declaration-usage-combination.ts @@ -24,7 +24,7 @@ const enum E1 { B = "world" } -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { a: number b: number[] = [13, -10] c: string diff --git a/es2panda/test/compiler/annotations/declaration-usage-empty.ts b/es2panda/test/compiler/annotations/declaration-usage-empty.ts index badbc9745a..b781add198 100644 --- a/es2panda/test/compiler/annotations/declaration-usage-empty.ts +++ b/es2panda/test/compiler/annotations/declaration-usage-empty.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -@interface Anno {} +@interface __$$ETS_ANNOTATION$$__Anno {} @__$$ETS_ANNOTATION$$__Anno class A { diff --git a/es2panda/test/compiler/annotations/declaration-usage-enum-number.ts b/es2panda/test/compiler/annotations/declaration-usage-enum-number.ts index 3bc341432f..ecba445cf8 100644 --- a/es2panda/test/compiler/annotations/declaration-usage-enum-number.ts +++ b/es2panda/test/compiler/annotations/declaration-usage-enum-number.ts @@ -18,7 +18,7 @@ const enum E { B = -2 } -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { a: E = new Number(0) as number; } diff --git a/es2panda/test/compiler/annotations/declaration-usage-enum-string.ts b/es2panda/test/compiler/annotations/declaration-usage-enum-string.ts index d9c8f8e047..320500abe9 100644 --- a/es2panda/test/compiler/annotations/declaration-usage-enum-string.ts +++ b/es2panda/test/compiler/annotations/declaration-usage-enum-string.ts @@ -18,7 +18,7 @@ const enum E { B = "world" } -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { a: E; } diff --git a/es2panda/test/compiler/annotations/declaration-usage-number.ts b/es2panda/test/compiler/annotations/declaration-usage-number.ts index 34e2ac30ec..637713e192 100644 --- a/es2panda/test/compiler/annotations/declaration-usage-number.ts +++ b/es2panda/test/compiler/annotations/declaration-usage-number.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { a: number; } diff --git a/es2panda/test/compiler/annotations/declaration-usage-string.ts b/es2panda/test/compiler/annotations/declaration-usage-string.ts index 0c627768fd..5ad01ef4ed 100644 --- a/es2panda/test/compiler/annotations/declaration-usage-string.ts +++ b/es2panda/test/compiler/annotations/declaration-usage-string.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { a: string; } diff --git a/es2panda/test/compiler/annotations/export.ts b/es2panda/test/compiler/annotations/export.ts index d11841f8a9..3dd42d6c74 100644 --- a/es2panda/test/compiler/annotations/export.ts +++ b/es2panda/test/compiler/annotations/export.ts @@ -15,9 +15,9 @@ // import tests are located in compiler/ts/annotations-projects -export @interface Anno1 {} +export @interface __$$ETS_ANNOTATION$$__Anno1 {} -export @interface Anno2 { +export @interface __$$ETS_ANNOTATION$$__Anno2 { a: number = 0; } diff --git a/es2panda/test/compiler/annotations/multiple-annotations.ts b/es2panda/test/compiler/annotations/multiple-annotations.ts index cf0af17c46..246af473b2 100644 --- a/es2panda/test/compiler/annotations/multiple-annotations.ts +++ b/es2panda/test/compiler/annotations/multiple-annotations.ts @@ -13,15 +13,15 @@ * limitations under the License. */ -@interface Anno1 { +@interface __$$ETS_ANNOTATION$$__Anno1 { a: number = 1; } -@interface Anno2 { +@interface __$$ETS_ANNOTATION$$__Anno2 { b: string = "string" } -@interface Anno3 { +@interface __$$ETS_ANNOTATION$$__Anno3 { c: boolean[] = [true, false]; } diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/abcinputs/bytecodehar.txt b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/abcinputs/bytecodehar.txt new file mode 100644 index 0000000000..2bed2a047f --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/abcinputs/bytecodehar.txt @@ -0,0 +1,2 @@ +bytecodehar-dynamic-import.ts +bytecodehar-static-import.ts diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/bytecodehar-dynamic-import.ts b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/bytecodehar-dynamic-import.ts new file mode 100644 index 0000000000..8a98a541e1 --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/bytecodehar-dynamic-import.ts @@ -0,0 +1,61 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export let test: string = "test"; + +function testReplacementWoAt() { + import("@normalized:N&module&bundle&lib/importfile1&1.0.0"); + import("@normalized:N&module&bundle&lib/importfile1&"); + import("@normalized:N&&bundle&lib/importfile1&1.0.0"); + import("@normalized:N&&bundle&lib/importfile1&"); + + // No-effect since no version info in compileContextInfo.json + import("@normalized:N&&&lib2/importfile3&"); +} + +function testReplacementWithAt() { + import("@normalized:N&module&&@ohos/lib/importfile2&1.0.0"); + import("@normalized:N&module&&@ohos/lib/importfile2&"); + import("@normalized:N&&&@ohos/lib/importfile2&1.0.0"); + import("@normalized:N&&&@ohos/lib/importfile2&"); + + // No-effect since no version info in compileContextInfo.json + import("@normalized:N&&&@ohos/lib2/importfile4&"); +} + +function testNonOhmurl() { + import("aaa"); +} + +function testNonConst() { + // Take effect only under release due to bcopt + let a = "@normalized:N&&bundle&lib/importfile1&" + import(a); + + a = "@normalized:N&&bundle&lib/importfile1&"; + let b = "@normalized:N&&bundle&lib/importfile1&"; + import(a); + + a = "@normalized:N&&bundle&lib/importfile1&"; + "@normalized:N&&bundle&lib/importfile1&"; + import(a); +} + +export @interface __$$ETS_ANNOTATION$$__Anno1 { + b: boolean = true +} + +@__$$ETS_ANNOTATION$$__Anno1() +class A { } \ No newline at end of file diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/bytecodehar-static-import.ts b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/bytecodehar-static-import.ts new file mode 100644 index 0000000000..9b6252c67f --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/bytecodehar-static-import.ts @@ -0,0 +1,43 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// testReplacementWoAt +import * as a from "@normalized:N&module&bundle&lib/importfile1&1.0.0"; +import * as b from "@normalized:N&module&bundle&lib/importfile1&"; +import * as c from "@normalized:N&&bundle&lib/importfile1&1.0.0"; +import * as d from "@normalized:N&&bundle&lib/importfile1&"; + +// No-effect since no version info in compileContextInfo.json +import * as e from "@normalized:N&&&lib2/importfile3&"; + +//testReplacementWithAt +import * as f from "@normalized:N&module&&@ohos/lib/importfile2&1.0.0"; +import * as g from "@normalized:N&module&&@ohos/lib/importfile2&"; +import * as h from "@normalized:N&&&@ohos/lib/importfile2&1.0.0"; +import * as i from "@normalized:N&&&@ohos/lib/importfile2&"; + +// No-effect since no version info in compileContextInfo.json +import * as j from "@normalized:N&&&@ohos/lib2/importfile4&"; + +function foo() { + print([a, b, c, d, e, f, g, h, i, j]); +} + +export @interface __$$ETS_ANNOTATION$$__Anno2 { + b: boolean = true +} + +@__$$ETS_ANNOTATION$$__Anno2() +class A { } \ No newline at end of file diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/compileContextInfo.json b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/compileContextInfo.json new file mode 100644 index 0000000000..3c35014906 --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/compileContextInfo.json @@ -0,0 +1,12 @@ +{ + "compileEntries": [ + "&myapp/hap-file-exec&" + ], + "hspPkgNames": [], + "updateVersionInfo": { + "bytecodehar": { + "lib": "2.0.0", + "@ohos/lib": "2.0.0" + } + } +} diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/hap-file-exec-expected.pa.txt b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/hap-file-exec-expected.pa.txt new file mode 100644 index 0000000000..6f146bddc0 --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/hap-file-exec-expected.pa.txt @@ -0,0 +1,1670 @@ +All Dependency Files: +program_file: bytecodehar-abcinput.abc +record_name: &bytecodehar/bytecodehar-dynamic-import& +program_file: bytecodehar-abcinput.abc +record_name: &bytecodehar/bytecodehar-static-import& +program_file: hap-file-exec.ts +record_name: &myapp/hap-file-exec& +program_file: importfile1.ts +record_name: bundle&lib/importfile1&2.0.0 +program_file: importfile2.ts +record_name: &@ohos/lib/importfile2&2.0.0 +program_file: importfile3.ts +record_name: &lib2/importfile3& +program_file: importfile4.ts +record_name: &@ohos/lib2/importfile4& + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar/bytecodehar-dynamic-import&.#*#testNonConst(any a0, any a1, any a2) { + lda.str @normalized:N&&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&&bundle&lib/importfile1&2.0.0 + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar/bytecodehar-dynamic-import&.#*#testNonOhmurl(any a0, any a1, any a2) { + lda.str aaa + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWithAt(any a0, any a1, any a2) { + lda.str @normalized:N&module&&@ohos/lib/importfile2&2.0.0 + dynamicimport + lda.str @normalized:N&module&&@ohos/lib/importfile2&2.0.0 + dynamicimport + lda.str @normalized:N&&&@ohos/lib/importfile2&2.0.0 + dynamicimport + lda.str @normalized:N&&&@ohos/lib/importfile2&2.0.0 + dynamicimport + lda.str @normalized:N&&&@ohos/lib2/importfile4& + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWoAt(any a0, any a1, any a2) { + lda.str @normalized:N&module&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&module&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&&&lib2/importfile3& + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar/bytecodehar-dynamic-import&.#~A=#A(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x7 +.language ECMAScript +.function any &bytecodehar/bytecodehar-dynamic-import&.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, &bytecodehar/bytecodehar-dynamic-import&.#*#testNonConst, 0x0 + definefunc 0x1, &bytecodehar/bytecodehar-dynamic-import&.#*#testNonOhmurl, 0x0 + definefunc 0x2, &bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWithAt, 0x0 + definefunc 0x3, &bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWoAt, 0x0 + lda.str test + stmodulevar 0x1 + ldhole + sta v0 + defineclasswithbuffer 0x4, &bytecodehar/bytecodehar-dynamic-import&.#~A=#A, &bytecodehar/bytecodehar-dynamic-import&_2514, 0x0, v0 + ldobjbyname 0x5, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &bytecodehar/bytecodehar-dynamic-import&_2466 +------------------------------------ +slot &bytecodehar/bytecodehar-dynamic-import&_2470 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 2 +}, +{ + index: 4 + tag: 5 + val: Anno1 +}, +{ + index: 5 + tag: 5 + val: Anno1 +}, +{ + index: 6 + tag: 5 + val: test +}, +{ + index: 7 + tag: 5 + val: test +}, +{ + index: 8 + tag: 2 + val: 0 +}, +{ + index: 9 + tag: 2 + val: 0 +}, +------------------------------------ +slot &bytecodehar/bytecodehar-dynamic-import&_2514 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&bytecodehar/bytecodehar-dynamic-import&.#*#testNonConst"; "&bytecodehar/bytecodehar-dynamic-import&.#*#testNonOhmurl"; "&bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWithAt"; "&bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWoAt"; "&bytecodehar/bytecodehar-dynamic-import&.#~A=#A"; "@normalized:N&&&@ohos/lib/importfile2&2.0.0"; "@normalized:N&&&@ohos/lib2/importfile4&"; "@normalized:N&&&lib2/importfile3&"; "@normalized:N&&bundle&lib/importfile1&2.0.0"; "@normalized:N&module&&@ohos/lib/importfile2&2.0.0"; "@normalized:N&module&bundle&lib/importfile1&2.0.0"; "aaa"; "prototype"; "test"; + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x18 +.language ECMAScript +.function any &bytecodehar/bytecodehar-static-import&.#*#foo(any a0, any a1, any a2) { + tryldglobalbyname 0x0, print + sta v0 + createemptyarray 0x1 + sta v1 + ldlexvar 0x0, 0x0 + sta v2 + throw.undefinedifholewithname a + lda v2 + stownbyindex 0x2, v1, 0x0 + ldlexvar 0x0, 0x1 + sta v2 + throw.undefinedifholewithname b + lda v2 + stownbyindex 0x4, v1, 0x1 + ldlexvar 0x0, 0x2 + sta v2 + throw.undefinedifholewithname c + lda v2 + stownbyindex 0x6, v1, 0x2 + ldlexvar 0x0, 0x3 + sta v2 + throw.undefinedifholewithname d + lda v2 + stownbyindex 0x8, v1, 0x3 + ldlexvar 0x0, 0x4 + sta v2 + throw.undefinedifholewithname e + lda v2 + stownbyindex 0xa, v1, 0x4 + ldlexvar 0x0, 0x5 + sta v2 + throw.undefinedifholewithname f + lda v2 + stownbyindex 0xc, v1, 0x5 + ldlexvar 0x0, 0x6 + sta v2 + throw.undefinedifholewithname g + lda v2 + stownbyindex 0xe, v1, 0x6 + ldlexvar 0x0, 0x7 + sta v2 + throw.undefinedifholewithname h + lda v2 + stownbyindex 0x10, v1, 0x7 + ldlexvar 0x0, 0x8 + sta v2 + throw.undefinedifholewithname i + lda v2 + stownbyindex 0x12, v1, 0x8 + ldlexvar 0x0, 0x9 + sta v2 + throw.undefinedifholewithname j + lda v2 + stownbyindex 0x14, v1, 0x9 + lda v0 + callarg1 0x16, v1 + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar/bytecodehar-static-import&.#~A=#A(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x4 +.language ECMAScript +.function any &bytecodehar/bytecodehar-static-import&.func_main_0(any a0, any a1, any a2) { + newlexenv 0xa + definefunc 0x0, &bytecodehar/bytecodehar-static-import&.#*#foo, 0x0 + getmodulenamespace 0x0 + stlexvar 0x0, 0x0 + getmodulenamespace 0x1 + stlexvar 0x0, 0x1 + getmodulenamespace 0x2 + stlexvar 0x0, 0x2 + getmodulenamespace 0x3 + stlexvar 0x0, 0x3 + getmodulenamespace 0x4 + stlexvar 0x0, 0x4 + getmodulenamespace 0x5 + stlexvar 0x0, 0x5 + getmodulenamespace 0x6 + stlexvar 0x0, 0x6 + getmodulenamespace 0x7 + stlexvar 0x0, 0x7 + getmodulenamespace 0x8 + stlexvar 0x0, 0x8 + getmodulenamespace 0x9 + stlexvar 0x0, 0x9 + ldhole + sta v0 + defineclasswithbuffer 0x1, &bytecodehar/bytecodehar-static-import&.#~A=#A, &bytecodehar/bytecodehar-static-import&_2663, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &bytecodehar/bytecodehar-static-import&_2523 +------------------------------------ +slot &bytecodehar/bytecodehar-static-import&_2527 +{ + index: 0 + tag: 2 + val: 10 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&module&bundle&lib/importfile1&2.0.0 +}, +{ + index: 2 + tag: 5 + val: @normalized:N&module&bundle&lib/importfile1&2.0.0 +}, +{ + index: 3 + tag: 5 + val: @normalized:N&&bundle&lib/importfile1&2.0.0 +}, +{ + index: 4 + tag: 5 + val: @normalized:N&&bundle&lib/importfile1&2.0.0 +}, +{ + index: 5 + tag: 5 + val: @normalized:N&&&lib2/importfile3& +}, +{ + index: 6 + tag: 5 + val: @normalized:N&module&&@ohos/lib/importfile2&2.0.0 +}, +{ + index: 7 + tag: 5 + val: @normalized:N&module&&@ohos/lib/importfile2&2.0.0 +}, +{ + index: 8 + tag: 5 + val: @normalized:N&&&@ohos/lib/importfile2&2.0.0 +}, +{ + index: 9 + tag: 5 + val: @normalized:N&&&@ohos/lib/importfile2&2.0.0 +}, +{ + index: 10 + tag: 5 + val: @normalized:N&&&@ohos/lib2/importfile4& +}, +{ + index: 11 + tag: 2 + val: 0 +}, +{ + index: 12 + tag: 2 + val: 10 +}, +{ + index: 13 + tag: 5 + val: a +}, +{ + index: 14 + tag: 9 + val: 0 +}, +{ + index: 15 + tag: 5 + val: b +}, +{ + index: 16 + tag: 9 + val: 1 +}, +{ + index: 17 + tag: 5 + val: c +}, +{ + index: 18 + tag: 9 + val: 2 +}, +{ + index: 19 + tag: 5 + val: d +}, +{ + index: 20 + tag: 9 + val: 3 +}, +{ + index: 21 + tag: 5 + val: e +}, +{ + index: 22 + tag: 9 + val: 4 +}, +{ + index: 23 + tag: 5 + val: f +}, +{ + index: 24 + tag: 9 + val: 5 +}, +{ + index: 25 + tag: 5 + val: g +}, +{ + index: 26 + tag: 9 + val: 6 +}, +{ + index: 27 + tag: 5 + val: h +}, +{ + index: 28 + tag: 9 + val: 7 +}, +{ + index: 29 + tag: 5 + val: i +}, +{ + index: 30 + tag: 9 + val: 8 +}, +{ + index: 31 + tag: 5 + val: j +}, +{ + index: 32 + tag: 9 + val: 9 +}, +{ + index: 33 + tag: 2 + val: 1 +}, +{ + index: 34 + tag: 5 + val: Anno2 +}, +{ + index: 35 + tag: 5 + val: Anno2 +}, +{ + index: 36 + tag: 2 + val: 0 +}, +{ + index: 37 + tag: 2 + val: 0 +}, +------------------------------------ +slot &bytecodehar/bytecodehar-static-import&_2663 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&bytecodehar/bytecodehar-static-import&.#*#foo"; "&bytecodehar/bytecodehar-static-import&.#~A=#A"; "a"; "b"; "c"; "d"; "e"; "f"; "g"; "h"; "i"; "j"; "print"; "prototype"; + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x0 +.language ECMAScript +.function any &myapp/hap-file-exec&.#~A=#A(any a0, any a1, any a2) { +label_1: +label_0: + lda a2 + return +label_2: +} + +slotNum = 0xd +.language ECMAScript +.function any &myapp/hap-file-exec&.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + getmodulenamespace 0x0 + sta v0 + getmodulenamespace 0x1 + sta v1 + tryldglobalbyname 0x0, print + sta v2 + lda v0 + ldobjbyname 0x1, test + sta v0 + lda v2 + callarg1 0x3, v0 + tryldglobalbyname 0x5, print + sta v0 + lda v1 + ldobjbyname 0x6, test + sta v1 + lda v0 + callarg1 0x8, v1 + ldhole + sta v0 + defineclasswithbuffer 0xa, &myapp/hap-file-exec&.#~A=#A, &myapp/hap-file-exec&_2, 0x0, v0 + ldobjbyname 0xb, prototype + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &myapp/hap-file-exec&_0 +------------------------------------ +slot &myapp/hap-file-exec&_1 +{ + index: 0 + tag: 2 + val: 2 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&&&bytecodehar/bytecodehar-dynamic-import& +}, +{ + index: 2 + tag: 5 + val: @normalized:N&&&bytecodehar/bytecodehar-static-import& +}, +{ + index: 3 + tag: 2 + val: 0 +}, +{ + index: 4 + tag: 2 + val: 2 +}, +{ + index: 5 + tag: 5 + val: bytecodeharDynamicImport +}, +{ + index: 6 + tag: 9 + val: 0 +}, +{ + index: 7 + tag: 5 + val: bytecodeharStaticImport +}, +{ + index: 8 + tag: 9 + val: 1 +}, +{ + index: 9 + tag: 2 + val: 0 +}, +{ + index: 10 + tag: 2 + val: 0 +}, +{ + index: 11 + tag: 2 + val: 0 +}, +------------------------------------ +slot &myapp/hap-file-exec&_2 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&myapp/hap-file-exec&.#~A=#A"; "print"; "prototype"; "test"; +slotNum = 0x0 +.language ECMAScript +.function any bundle&lib/importfile1&2.0.0.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + ldtrue + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot bundle&lib/importfile1&2.0.0_0 +------------------------------------ +slot bundle&lib/importfile1&2.0.0_1 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 1 +}, +{ + index: 4 + tag: 5 + val: test1 +}, +{ + index: 5 + tag: 5 + val: test1 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +======> strings <====== + +slotNum = 0x0 +.language ECMAScript +.function any &@ohos/lib/importfile2&2.0.0.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + ldtrue + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &@ohos/lib/importfile2&2.0.0_0 +------------------------------------ +slot &@ohos/lib/importfile2&2.0.0_1 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 1 +}, +{ + index: 4 + tag: 5 + val: test2 +}, +{ + index: 5 + tag: 5 + val: test2 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +======> strings <====== + +slotNum = 0x0 +.language ECMAScript +.function any &lib2/importfile3&.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + ldtrue + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &lib2/importfile3&_0 +------------------------------------ +slot &lib2/importfile3&_1 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 1 +}, +{ + index: 4 + tag: 5 + val: test3 +}, +{ + index: 5 + tag: 5 + val: test3 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +======> strings <====== + +slotNum = 0x0 +.language ECMAScript +.function any &@ohos/lib2/importfile4&.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + ldtrue + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &@ohos/lib2/importfile4&_0 +------------------------------------ +slot &@ohos/lib2/importfile4&_1 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 1 +}, +{ + index: 4 + tag: 5 + val: test4 +}, +{ + index: 5 + tag: 5 + val: test4 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +======> strings <====== + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar/bytecodehar-dynamic-import&.#*#testNonConst(any a0, any a1, any a2) { + lda.str @normalized:N&&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&&bundle&lib/importfile1&2.0.0 + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar/bytecodehar-dynamic-import&.#*#testNonOhmurl(any a0, any a1, any a2) { + lda.str aaa + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWithAt(any a0, any a1, any a2) { + lda.str @normalized:N&module&&@ohos/lib/importfile2&2.0.0 + dynamicimport + lda.str @normalized:N&module&&@ohos/lib/importfile2&2.0.0 + dynamicimport + lda.str @normalized:N&&&@ohos/lib/importfile2&2.0.0 + dynamicimport + lda.str @normalized:N&&&@ohos/lib/importfile2&2.0.0 + dynamicimport + lda.str @normalized:N&&&@ohos/lib2/importfile4& + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWoAt(any a0, any a1, any a2) { + lda.str @normalized:N&module&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&module&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&&&lib2/importfile3& + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar/bytecodehar-dynamic-import&.#~A=#A(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x7 +.language ECMAScript +.function any &bytecodehar/bytecodehar-dynamic-import&.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, &bytecodehar/bytecodehar-dynamic-import&.#*#testNonConst, 0x0 + definefunc 0x1, &bytecodehar/bytecodehar-dynamic-import&.#*#testNonOhmurl, 0x0 + definefunc 0x2, &bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWithAt, 0x0 + definefunc 0x3, &bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWoAt, 0x0 + lda.str test + stmodulevar 0x1 + ldhole + sta v0 + defineclasswithbuffer 0x4, &bytecodehar/bytecodehar-dynamic-import&.#~A=#A, &bytecodehar/bytecodehar-dynamic-import&_2514, 0x0, v0 + ldobjbyname 0x5, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &bytecodehar/bytecodehar-dynamic-import&_2466 +------------------------------------ +slot &bytecodehar/bytecodehar-dynamic-import&_2470 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 2 +}, +{ + index: 4 + tag: 5 + val: Anno1 +}, +{ + index: 5 + tag: 5 + val: Anno1 +}, +{ + index: 6 + tag: 5 + val: test +}, +{ + index: 7 + tag: 5 + val: test +}, +{ + index: 8 + tag: 2 + val: 0 +}, +{ + index: 9 + tag: 2 + val: 0 +}, +------------------------------------ +slot &bytecodehar/bytecodehar-dynamic-import&_2514 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&bytecodehar/bytecodehar-dynamic-import&.#*#testNonConst"; "&bytecodehar/bytecodehar-dynamic-import&.#*#testNonOhmurl"; "&bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWithAt"; "&bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWoAt"; "&bytecodehar/bytecodehar-dynamic-import&.#~A=#A"; "@normalized:N&&&@ohos/lib/importfile2&2.0.0"; "@normalized:N&&&@ohos/lib2/importfile4&"; "@normalized:N&&&lib2/importfile3&"; "@normalized:N&&bundle&lib/importfile1&2.0.0"; "@normalized:N&module&&@ohos/lib/importfile2&2.0.0"; "@normalized:N&module&bundle&lib/importfile1&2.0.0"; "aaa"; "prototype"; "test"; + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x18 +.language ECMAScript +.function any &bytecodehar/bytecodehar-static-import&.#*#foo(any a0, any a1, any a2) { + tryldglobalbyname 0x0, print + sta v0 + createemptyarray 0x1 + sta v1 + ldlexvar 0x0, 0x0 + sta v2 + throw.undefinedifholewithname a + lda v2 + stownbyindex 0x2, v1, 0x0 + ldlexvar 0x0, 0x1 + sta v2 + throw.undefinedifholewithname b + lda v2 + stownbyindex 0x4, v1, 0x1 + ldlexvar 0x0, 0x2 + sta v2 + throw.undefinedifholewithname c + lda v2 + stownbyindex 0x6, v1, 0x2 + ldlexvar 0x0, 0x3 + sta v2 + throw.undefinedifholewithname d + lda v2 + stownbyindex 0x8, v1, 0x3 + ldlexvar 0x0, 0x4 + sta v2 + throw.undefinedifholewithname e + lda v2 + stownbyindex 0xa, v1, 0x4 + ldlexvar 0x0, 0x5 + sta v2 + throw.undefinedifholewithname f + lda v2 + stownbyindex 0xc, v1, 0x5 + ldlexvar 0x0, 0x6 + sta v2 + throw.undefinedifholewithname g + lda v2 + stownbyindex 0xe, v1, 0x6 + ldlexvar 0x0, 0x7 + sta v2 + throw.undefinedifholewithname h + lda v2 + stownbyindex 0x10, v1, 0x7 + ldlexvar 0x0, 0x8 + sta v2 + throw.undefinedifholewithname i + lda v2 + stownbyindex 0x12, v1, 0x8 + ldlexvar 0x0, 0x9 + sta v2 + throw.undefinedifholewithname j + lda v2 + stownbyindex 0x14, v1, 0x9 + lda v0 + callarg1 0x16, v1 + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar/bytecodehar-static-import&.#~A=#A(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x4 +.language ECMAScript +.function any &bytecodehar/bytecodehar-static-import&.func_main_0(any a0, any a1, any a2) { + newlexenv 0xa + definefunc 0x0, &bytecodehar/bytecodehar-static-import&.#*#foo, 0x0 + getmodulenamespace 0x0 + stlexvar 0x0, 0x0 + getmodulenamespace 0x1 + stlexvar 0x0, 0x1 + getmodulenamespace 0x2 + stlexvar 0x0, 0x2 + getmodulenamespace 0x3 + stlexvar 0x0, 0x3 + getmodulenamespace 0x4 + stlexvar 0x0, 0x4 + getmodulenamespace 0x5 + stlexvar 0x0, 0x5 + getmodulenamespace 0x6 + stlexvar 0x0, 0x6 + getmodulenamespace 0x7 + stlexvar 0x0, 0x7 + getmodulenamespace 0x8 + stlexvar 0x0, 0x8 + getmodulenamespace 0x9 + stlexvar 0x0, 0x9 + ldhole + sta v0 + defineclasswithbuffer 0x1, &bytecodehar/bytecodehar-static-import&.#~A=#A, &bytecodehar/bytecodehar-static-import&_2663, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &bytecodehar/bytecodehar-static-import&_2523 +------------------------------------ +slot &bytecodehar/bytecodehar-static-import&_2527 +{ + index: 0 + tag: 2 + val: 10 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&module&bundle&lib/importfile1&2.0.0 +}, +{ + index: 2 + tag: 5 + val: @normalized:N&module&bundle&lib/importfile1&2.0.0 +}, +{ + index: 3 + tag: 5 + val: @normalized:N&&bundle&lib/importfile1&2.0.0 +}, +{ + index: 4 + tag: 5 + val: @normalized:N&&bundle&lib/importfile1&2.0.0 +}, +{ + index: 5 + tag: 5 + val: @normalized:N&&&lib2/importfile3& +}, +{ + index: 6 + tag: 5 + val: @normalized:N&module&&@ohos/lib/importfile2&2.0.0 +}, +{ + index: 7 + tag: 5 + val: @normalized:N&module&&@ohos/lib/importfile2&2.0.0 +}, +{ + index: 8 + tag: 5 + val: @normalized:N&&&@ohos/lib/importfile2&2.0.0 +}, +{ + index: 9 + tag: 5 + val: @normalized:N&&&@ohos/lib/importfile2&2.0.0 +}, +{ + index: 10 + tag: 5 + val: @normalized:N&&&@ohos/lib2/importfile4& +}, +{ + index: 11 + tag: 2 + val: 0 +}, +{ + index: 12 + tag: 2 + val: 10 +}, +{ + index: 13 + tag: 5 + val: a +}, +{ + index: 14 + tag: 9 + val: 0 +}, +{ + index: 15 + tag: 5 + val: b +}, +{ + index: 16 + tag: 9 + val: 1 +}, +{ + index: 17 + tag: 5 + val: c +}, +{ + index: 18 + tag: 9 + val: 2 +}, +{ + index: 19 + tag: 5 + val: d +}, +{ + index: 20 + tag: 9 + val: 3 +}, +{ + index: 21 + tag: 5 + val: e +}, +{ + index: 22 + tag: 9 + val: 4 +}, +{ + index: 23 + tag: 5 + val: f +}, +{ + index: 24 + tag: 9 + val: 5 +}, +{ + index: 25 + tag: 5 + val: g +}, +{ + index: 26 + tag: 9 + val: 6 +}, +{ + index: 27 + tag: 5 + val: h +}, +{ + index: 28 + tag: 9 + val: 7 +}, +{ + index: 29 + tag: 5 + val: i +}, +{ + index: 30 + tag: 9 + val: 8 +}, +{ + index: 31 + tag: 5 + val: j +}, +{ + index: 32 + tag: 9 + val: 9 +}, +{ + index: 33 + tag: 2 + val: 1 +}, +{ + index: 34 + tag: 5 + val: Anno2 +}, +{ + index: 35 + tag: 5 + val: Anno2 +}, +{ + index: 36 + tag: 2 + val: 0 +}, +{ + index: 37 + tag: 2 + val: 0 +}, +------------------------------------ +slot &bytecodehar/bytecodehar-static-import&_2663 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&bytecodehar/bytecodehar-static-import&.#*#foo"; "&bytecodehar/bytecodehar-static-import&.#~A=#A"; "a"; "b"; "c"; "d"; "e"; "f"; "g"; "h"; "i"; "j"; "print"; "prototype"; + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x0 +.language ECMAScript +.function any &myapp/hap-file-exec&.#~A=#A(any a0, any a1, any a2) { +label_1: +label_0: + lda a2 + return +label_2: +} + +slotNum = 0xd +.language ECMAScript +.function any &myapp/hap-file-exec&.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + getmodulenamespace 0x0 + sta v0 + getmodulenamespace 0x1 + sta v1 + tryldglobalbyname 0x0, print + sta v2 + lda v0 + ldobjbyname 0x1, test + sta v0 + lda v2 + callarg1 0x3, v0 + tryldglobalbyname 0x5, print + sta v0 + lda v1 + ldobjbyname 0x6, test + sta v1 + lda v0 + callarg1 0x8, v1 + ldhole + sta v0 + defineclasswithbuffer 0xa, &myapp/hap-file-exec&.#~A=#A, &myapp/hap-file-exec&_2, 0x0, v0 + ldobjbyname 0xb, prototype + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &myapp/hap-file-exec&_0 +------------------------------------ +slot &myapp/hap-file-exec&_1 +{ + index: 0 + tag: 2 + val: 2 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&&&bytecodehar/bytecodehar-dynamic-import& +}, +{ + index: 2 + tag: 5 + val: @normalized:N&&&bytecodehar/bytecodehar-static-import& +}, +{ + index: 3 + tag: 2 + val: 0 +}, +{ + index: 4 + tag: 2 + val: 2 +}, +{ + index: 5 + tag: 5 + val: bytecodeharDynamicImport +}, +{ + index: 6 + tag: 9 + val: 0 +}, +{ + index: 7 + tag: 5 + val: bytecodeharStaticImport +}, +{ + index: 8 + tag: 9 + val: 1 +}, +{ + index: 9 + tag: 2 + val: 0 +}, +{ + index: 10 + tag: 2 + val: 0 +}, +{ + index: 11 + tag: 2 + val: 0 +}, +------------------------------------ +slot &myapp/hap-file-exec&_2 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&myapp/hap-file-exec&.#~A=#A"; "print"; "prototype"; "test"; +slotNum = 0x0 +.language ECMAScript +.function any bundle&lib/importfile1&2.0.0.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + ldtrue + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot bundle&lib/importfile1&2.0.0_0 +------------------------------------ +slot bundle&lib/importfile1&2.0.0_1 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 1 +}, +{ + index: 4 + tag: 5 + val: test1 +}, +{ + index: 5 + tag: 5 + val: test1 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +======> strings <====== + +slotNum = 0x0 +.language ECMAScript +.function any &@ohos/lib/importfile2&2.0.0.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + ldtrue + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &@ohos/lib/importfile2&2.0.0_0 +------------------------------------ +slot &@ohos/lib/importfile2&2.0.0_1 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 1 +}, +{ + index: 4 + tag: 5 + val: test2 +}, +{ + index: 5 + tag: 5 + val: test2 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +======> strings <====== + +slotNum = 0x0 +.language ECMAScript +.function any &lib2/importfile3&.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + ldtrue + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &lib2/importfile3&_0 +------------------------------------ +slot &lib2/importfile3&_1 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 1 +}, +{ + index: 4 + tag: 5 + val: test3 +}, +{ + index: 5 + tag: 5 + val: test3 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +======> strings <====== + +slotNum = 0x0 +.language ECMAScript +.function any &@ohos/lib2/importfile4&.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + ldtrue + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &@ohos/lib2/importfile4&_0 +------------------------------------ +slot &@ohos/lib2/importfile4&_1 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 1 +}, +{ + index: 4 + tag: 5 + val: test4 +}, +{ + index: 5 + tag: 5 + val: test4 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +======> strings <====== + diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/hap-file-exec.ts b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/hap-file-exec.ts new file mode 100644 index 0000000000..6c9b1c36d2 --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/hap-file-exec.ts @@ -0,0 +1,24 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as bytecodeharDynamicImport from "@normalized:N&&&bytecodehar/bytecodehar-dynamic-import&"; +import * as bytecodeharStaticImport from "@normalized:N&&&bytecodehar/bytecodehar-static-import&"; + +print(bytecodeharDynamicImport.test) +print(bytecodeharStaticImport.test) + +@bytecodeharDynamicImport.__$$ETS_ANNOTATION$$__Anno1() +@bytecodeharStaticImport.__$$ETS_ANNOTATION$$__Anno2() +class A { } diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/importfile1.ts b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/importfile1.ts new file mode 100644 index 0000000000..5635f70b71 --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/importfile1.ts @@ -0,0 +1,16 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const test1: boolean = true; \ No newline at end of file diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/importfile2.ts b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/importfile2.ts new file mode 100644 index 0000000000..5267ff5e29 --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/importfile2.ts @@ -0,0 +1,16 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const test2: boolean = true; \ No newline at end of file diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/importfile3.ts b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/importfile3.ts new file mode 100644 index 0000000000..d9a8057d7b --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/importfile3.ts @@ -0,0 +1,16 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const test3: boolean = true; \ No newline at end of file diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/importfile4.ts b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/importfile4.ts new file mode 100644 index 0000000000..3fedda824b --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/importfile4.ts @@ -0,0 +1,16 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const test4: boolean = true; \ No newline at end of file diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/recordnames.txt b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/recordnames.txt new file mode 100644 index 0000000000..185dca6111 --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-accuate-version-update/recordnames.txt @@ -0,0 +1,7 @@ +bytecodehar-dynamic-import:&bytecodehar/bytecodehar-dynamic-import& +bytecodehar-static-import:&bytecodehar/bytecodehar-static-import& +importfile1:bundle&lib/importfile1&2.0.0 +importfile2:&@ohos/lib/importfile2&2.0.0 +importfile3:&lib2/importfile3& +importfile4:&@ohos/lib2/importfile4& +hap-file-exec:&myapp/hap-file-exec& diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/abcinputs/bytecodehar1.txt b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/abcinputs/bytecodehar1.txt new file mode 100644 index 0000000000..44fef6254c --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/abcinputs/bytecodehar1.txt @@ -0,0 +1,2 @@ +bytecodehar1-file1.ts +bytecodehar1-file2.ts diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/abcinputs/bytecodehar2.txt b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/abcinputs/bytecodehar2.txt new file mode 100644 index 0000000000..01249cd0af --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/abcinputs/bytecodehar2.txt @@ -0,0 +1,2 @@ +bytecodehar2-file1.ts +bytecodehar2-file2.ts diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/bytecodehar1-file1.ts b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/bytecodehar1-file1.ts new file mode 100644 index 0000000000..27094c100a --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/bytecodehar1-file1.ts @@ -0,0 +1,28 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {test as test1} from '@normalized:N&&&@ohos/bytecodehar2/bytecodehar2-file1&2.0.0' + +export function test() { + print('bytecodehar1.file1.test'); + import('@normalized:N&&&sourcehar/sourcehar-file1&2.0.0') +} + +export @interface __$$ETS_ANNOTATION$$__Anno1 { + b: boolean = true +} + +@__$$ETS_ANNOTATION$$__Anno1() +class A { } diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/bytecodehar1-file2.ts b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/bytecodehar1-file2.ts new file mode 100644 index 0000000000..5962b22672 --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/bytecodehar1-file2.ts @@ -0,0 +1,28 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {test as test1} from "@normalized:N&&&@ohos/bytecodehar2/bytecodehar2-file2&1.0.0" + +export function test() { + print('bytecodehar1.file2.test'); + import("@normalized:N&&&sourcehar/sourcehar-file2&2.0.0") +} + +export @interface __$$ETS_ANNOTATION$$__Anno2 { + b: boolean = true +} + +@__$$ETS_ANNOTATION$$__Anno2() +class A { } \ No newline at end of file diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/bytecodehar2-file1.ts b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/bytecodehar2-file1.ts new file mode 100644 index 0000000000..fc82d9af73 --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/bytecodehar2-file1.ts @@ -0,0 +1,25 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export function test() { + print('bytecodehar2.file1.test'); +} + +export @interface __$$ETS_ANNOTATION$$__Anno1 { + b: boolean = true +} + +@__$$ETS_ANNOTATION$$__Anno1() +class A { } \ No newline at end of file diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/bytecodehar2-file2.ts b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/bytecodehar2-file2.ts new file mode 100644 index 0000000000..aacfd72555 --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/bytecodehar2-file2.ts @@ -0,0 +1,25 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export function test() { + print('bytecodehar2.file2.test'); +} + +export @interface __$$ETS_ANNOTATION$$__Anno2 { + b: boolean = true +} + +@__$$ETS_ANNOTATION$$__Anno2() +class A { } diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/compileContextInfo.json b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/compileContextInfo.json new file mode 100644 index 0000000000..a8744ff6d3 --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/compileContextInfo.json @@ -0,0 +1,44 @@ +{ + "compileEntries": [ + "&myapp/hap-file-exec&" + ], + "hspPkgNames": [], + "pkgContextInfo": { + "myapp": { + "packageName": "myapp", + "bundleName": "", + "moduleName": "", + "version": "", + "entryPath": "", + "isSo": false, + "dependencyAlias": "" + }, + "bytecodehar1": { + "packageName": "bytecodehar1", + "bundleName": "", + "moduleName": "", + "version": "2.0.0", + "entryPath": "", + "isSo": false, + "dependencyAlias": "" + }, + "@ohos/bytecodehar2": { + "packageName": "@ohos/bytecodehar2", + "bundleName": "", + "moduleName": "", + "version": "2.0.0", + "entryPath": "", + "isSo": false, + "dependencyAlias": "" + }, + "sourcehar": { + "packageName": "sourcehar", + "bundleName": "", + "moduleName": "", + "version": "2.0.0", + "entryPath": "", + "isSo": false, + "dependencyAlias": "" + } + } +} diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/hap-file-exec-expected.pa.txt b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/hap-file-exec-expected.pa.txt new file mode 100644 index 0000000000..d327a5a78a --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/hap-file-exec-expected.pa.txt @@ -0,0 +1,1354 @@ +All Dependency Files: +program_file: bytecodehar1-abcinput.abc +record_name: &bytecodehar1/bytecodehar1-file1&2.0.0 +program_file: bytecodehar2-abcinput.abc +record_name: &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0 +program_file: hap-file-exec.ts +record_name: &myapp/hap-file-exec& +program_file: sourcehar-file1.ts +record_name: &sourcehar/sourcehar-file1&2.0.0 +program_file: sourcehar-file2.ts +record_name: &sourcehar/sourcehar-file2&2.0.0 + +slotNum = 0x3 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file1&2.0.0.#*#test(any a0, any a1, any a2) { + tryldglobalbyname 0x0, print + sta v0 + lda.str bytecodehar1.file1.test + sta v1 + lda v0 + callarg1 0x1, v1 + lda.str @normalized:N&&&sourcehar/sourcehar-file1&2.0.0 + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file1&2.0.0.#~A=#A(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x4 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file1&2.0.0.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, &bytecodehar1/bytecodehar1-file1&2.0.0.#*#test, 0x0 + stmodulevar 0x1 + ldhole + sta v0 + defineclasswithbuffer 0x1, &bytecodehar1/bytecodehar1-file1&2.0.0.#~A=#A, &bytecodehar1/bytecodehar1-file1&2.0.0_1844, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &bytecodehar1/bytecodehar1-file1&2.0.0_1782 +------------------------------------ +slot &bytecodehar1/bytecodehar1-file1&2.0.0_1786 +{ + index: 0 + tag: 2 + val: 1 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&&&@ohos/bytecodehar2/bytecodehar2-file1&2.0.0 +}, +{ + index: 2 + tag: 2 + val: 1 +}, +{ + index: 3 + tag: 5 + val: test1 +}, +{ + index: 4 + tag: 5 + val: test +}, +{ + index: 5 + tag: 9 + val: 0 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 2 +}, +{ + index: 8 + tag: 5 + val: Anno1 +}, +{ + index: 9 + tag: 5 + val: Anno1 +}, +{ + index: 10 + tag: 5 + val: test +}, +{ + index: 11 + tag: 5 + val: test +}, +{ + index: 12 + tag: 2 + val: 0 +}, +{ + index: 13 + tag: 2 + val: 0 +}, +------------------------------------ +slot &bytecodehar1/bytecodehar1-file1&2.0.0_1844 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&bytecodehar1/bytecodehar1-file1&2.0.0.#*#test"; "&bytecodehar1/bytecodehar1-file1&2.0.0.#~A=#A"; "@normalized:N&&&sourcehar/sourcehar-file1&2.0.0"; "bytecodehar1.file1.test"; "print"; "prototype"; + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x3 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file2&2.0.0.#*#test(any a0, any a1, any a2) { + tryldglobalbyname 0x0, print + sta v0 + lda.str bytecodehar1.file2.test + sta v1 + lda v0 + callarg1 0x1, v1 + lda.str @normalized:N&&&sourcehar/sourcehar-file2&2.0.0 + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file2&2.0.0.#~A=#A(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x4 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file2&2.0.0.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, &bytecodehar1/bytecodehar1-file2&2.0.0.#*#test, 0x0 + stmodulevar 0x1 + ldhole + sta v0 + defineclasswithbuffer 0x1, &bytecodehar1/bytecodehar1-file2&2.0.0.#~A=#A, &bytecodehar1/bytecodehar1-file2&2.0.0_1915, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &bytecodehar1/bytecodehar1-file2&2.0.0_1853 +------------------------------------ +slot &bytecodehar1/bytecodehar1-file2&2.0.0_1857 +{ + index: 0 + tag: 2 + val: 1 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&&&@ohos/bytecodehar2/bytecodehar2-file2&2.0.0 +}, +{ + index: 2 + tag: 2 + val: 1 +}, +{ + index: 3 + tag: 5 + val: test1 +}, +{ + index: 4 + tag: 5 + val: test +}, +{ + index: 5 + tag: 9 + val: 0 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 2 +}, +{ + index: 8 + tag: 5 + val: Anno2 +}, +{ + index: 9 + tag: 5 + val: Anno2 +}, +{ + index: 10 + tag: 5 + val: test +}, +{ + index: 11 + tag: 5 + val: test +}, +{ + index: 12 + tag: 2 + val: 0 +}, +{ + index: 13 + tag: 2 + val: 0 +}, +------------------------------------ +slot &bytecodehar1/bytecodehar1-file2&2.0.0_1915 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&bytecodehar1/bytecodehar1-file2&2.0.0.#*#test"; "&bytecodehar1/bytecodehar1-file2&2.0.0.#~A=#A"; "@normalized:N&&&sourcehar/sourcehar-file2&2.0.0"; "bytecodehar1.file2.test"; "print"; "prototype"; + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x3 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#*#test(any a0, any a1, any a2) { + tryldglobalbyname 0x0, print + sta v0 + lda.str bytecodehar2.file1.test + sta v1 + lda v0 + callarg1 0x1, v1 + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#~A=#A(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x4 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#*#test, 0x0 + stmodulevar 0x1 + ldhole + sta v0 + defineclasswithbuffer 0x1, &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#~A=#A, &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0_1655, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0_1607 +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0_1611 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 2 +}, +{ + index: 4 + tag: 5 + val: Anno1 +}, +{ + index: 5 + tag: 5 + val: Anno1 +}, +{ + index: 6 + tag: 5 + val: test +}, +{ + index: 7 + tag: 5 + val: test +}, +{ + index: 8 + tag: 2 + val: 0 +}, +{ + index: 9 + tag: 2 + val: 0 +}, +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0_1655 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#*#test"; "&@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#~A=#A"; "bytecodehar2.file1.test"; "print"; "prototype"; + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x3 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0.#*#test(any a0, any a1, any a2) { + tryldglobalbyname 0x0, print + sta v0 + lda.str bytecodehar2.file2.test + sta v1 + lda v0 + callarg1 0x1, v1 + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0.#~A=#A(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x4 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0.#*#test, 0x0 + stmodulevar 0x1 + ldhole + sta v0 + defineclasswithbuffer 0x1, &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0.#~A=#A, &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0_1712, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0_1664 +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0_1668 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 2 +}, +{ + index: 4 + tag: 5 + val: Anno2 +}, +{ + index: 5 + tag: 5 + val: Anno2 +}, +{ + index: 6 + tag: 5 + val: test +}, +{ + index: 7 + tag: 5 + val: test +}, +{ + index: 8 + tag: 2 + val: 0 +}, +{ + index: 9 + tag: 2 + val: 0 +}, +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0_1712 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&@ohos/bytecodehar2/bytecodehar2-file2&2.0.0.#*#test"; "&@ohos/bytecodehar2/bytecodehar2-file2&2.0.0.#~A=#A"; "bytecodehar2.file2.test"; "print"; "prototype"; + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x4 +.language ECMAScript +.function any &myapp/hap-file-exec&.#*#main(any a0, any a1, any a2) { +label_1: +label_0: + ldexternalmodulevar 0x2 + sta v0 + throw.undefinedifholewithname test + lda v0 + callarg0 0x0 + ldexternalmodulevar 0x0 + sta v0 + throw.undefinedifholewithname A + mov v1, v0 + newobjrange 0x2, 0x1, v1 + returnundefined +label_2: +} + +slotNum = 0x0 +.language ECMAScript +.function any &myapp/hap-file-exec&.#~B=#B(any a0, any a1, any a2) { +label_1: +label_0: + lda a2 + return +label_2: +} + +slotNum = 0x4 +.language ECMAScript +.function any &myapp/hap-file-exec&.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + definefunc 0x0, &myapp/hap-file-exec&.#*#main, 0x0 + ldhole + sta v0 + defineclasswithbuffer 0x1, &myapp/hap-file-exec&.#~B=#B, &myapp/hap-file-exec&_2, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &myapp/hap-file-exec&_0 +------------------------------------ +slot &myapp/hap-file-exec&_1 +{ + index: 0 + tag: 2 + val: 1 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&&&bytecodehar1/bytecodehar1-file1&2.0.0 +}, +{ + index: 2 + tag: 2 + val: 3 +}, +{ + index: 3 + tag: 5 + val: A +}, +{ + index: 4 + tag: 5 + val: A +}, +{ + index: 5 + tag: 9 + val: 0 +}, +{ + index: 6 + tag: 5 + val: Anno1 +}, +{ + index: 7 + tag: 5 + val: Anno1 +}, +{ + index: 8 + tag: 9 + val: 0 +}, +{ + index: 9 + tag: 5 + val: test +}, +{ + index: 10 + tag: 5 + val: test +}, +{ + index: 11 + tag: 9 + val: 0 +}, +{ + index: 12 + tag: 2 + val: 0 +}, +{ + index: 13 + tag: 2 + val: 0 +}, +{ + index: 14 + tag: 2 + val: 0 +}, +{ + index: 15 + tag: 2 + val: 0 +}, +------------------------------------ +slot &myapp/hap-file-exec&_2 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&myapp/hap-file-exec&.#*#main"; "&myapp/hap-file-exec&.#~B=#B"; "A"; "prototype"; "test"; +slotNum = 0x3 +.language ECMAScript +.function any &sourcehar/sourcehar-file1&2.0.0.#*#test(any a0, any a1, any a2) { +label_1: +label_0: + tryldglobalbyname 0x0, print + sta v0 + lda.str sourcehar.file1.test + sta v1 + lda v0 + callarg1 0x1, v1 + returnundefined +label_2: +} + +slotNum = 0x1 +.language ECMAScript +.function any &sourcehar/sourcehar-file1&2.0.0.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + definefunc 0x0, &sourcehar/sourcehar-file1&2.0.0.#*#test, 0x0 + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &sourcehar/sourcehar-file1&2.0.0_0 +------------------------------------ +slot &sourcehar/sourcehar-file1&2.0.0_1 +{ + index: 0 + tag: 2 + val: 1 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&&&sourcehar/sourcehar-file2&2.0.0 +}, +{ + index: 2 + tag: 2 + val: 1 +}, +{ + index: 3 + tag: 5 + val: test1 +}, +{ + index: 4 + tag: 5 + val: test +}, +{ + index: 5 + tag: 9 + val: 0 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 1 +}, +{ + index: 8 + tag: 5 + val: test +}, +{ + index: 9 + tag: 5 + val: test +}, +{ + index: 10 + tag: 2 + val: 0 +}, +{ + index: 11 + tag: 2 + val: 0 +}, +======> strings <====== +"&sourcehar/sourcehar-file1&2.0.0.#*#test"; "print"; "sourcehar.file1.test"; +slotNum = 0x3 +.language ECMAScript +.function any &sourcehar/sourcehar-file2&2.0.0.#*#test(any a0, any a1, any a2) { +label_1: +label_0: + tryldglobalbyname 0x0, print + sta v0 + lda.str sourcehar.file2.test + sta v1 + lda v0 + callarg1 0x1, v1 + returnundefined +label_2: +} + +slotNum = 0x1 +.language ECMAScript +.function any &sourcehar/sourcehar-file2&2.0.0.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + definefunc 0x0, &sourcehar/sourcehar-file2&2.0.0.#*#test, 0x0 + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &sourcehar/sourcehar-file2&2.0.0_0 +------------------------------------ +slot &sourcehar/sourcehar-file2&2.0.0_1 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 1 +}, +{ + index: 4 + tag: 5 + val: test +}, +{ + index: 5 + tag: 5 + val: test +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +======> strings <====== +"&sourcehar/sourcehar-file2&2.0.0.#*#test"; "print"; "sourcehar.file2.test"; +slotNum = 0x3 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file1&2.0.0.#*#test(any a0, any a1, any a2) { + tryldglobalbyname 0x0, print + sta v0 + lda.str bytecodehar1.file1.test + sta v1 + lda v0 + callarg1 0x1, v1 + lda.str @normalized:N&&&sourcehar/sourcehar-file1&2.0.0 + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file1&2.0.0.#~A=#A(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x4 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file1&2.0.0.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, &bytecodehar1/bytecodehar1-file1&2.0.0.#*#test, 0x0 + stmodulevar 0x1 + ldhole + sta v0 + defineclasswithbuffer 0x1, &bytecodehar1/bytecodehar1-file1&2.0.0.#~A=#A, &bytecodehar1/bytecodehar1-file1&2.0.0_1844, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &bytecodehar1/bytecodehar1-file1&2.0.0_1782 +------------------------------------ +slot &bytecodehar1/bytecodehar1-file1&2.0.0_1786 +{ + index: 0 + tag: 2 + val: 1 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&&&@ohos/bytecodehar2/bytecodehar2-file1&2.0.0 +}, +{ + index: 2 + tag: 2 + val: 1 +}, +{ + index: 3 + tag: 5 + val: test1 +}, +{ + index: 4 + tag: 5 + val: test +}, +{ + index: 5 + tag: 9 + val: 0 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 2 +}, +{ + index: 8 + tag: 5 + val: Anno1 +}, +{ + index: 9 + tag: 5 + val: Anno1 +}, +{ + index: 10 + tag: 5 + val: test +}, +{ + index: 11 + tag: 5 + val: test +}, +{ + index: 12 + tag: 2 + val: 0 +}, +{ + index: 13 + tag: 2 + val: 0 +}, +------------------------------------ +slot &bytecodehar1/bytecodehar1-file1&2.0.0_1844 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&bytecodehar1/bytecodehar1-file1&2.0.0.#*#test"; "&bytecodehar1/bytecodehar1-file1&2.0.0.#~A=#A"; "@normalized:N&&&sourcehar/sourcehar-file1&2.0.0"; "bytecodehar1.file1.test"; "print"; "prototype"; + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x3 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#*#test(any a0, any a1, any a2) { + tryldglobalbyname 0x0, print + sta v0 + lda.str bytecodehar2.file1.test + sta v1 + lda v0 + callarg1 0x1, v1 + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#~A=#A(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x4 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#*#test, 0x0 + stmodulevar 0x1 + ldhole + sta v0 + defineclasswithbuffer 0x1, &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#~A=#A, &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0_1655, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0_1607 +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0_1611 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 2 +}, +{ + index: 4 + tag: 5 + val: Anno1 +}, +{ + index: 5 + tag: 5 + val: Anno1 +}, +{ + index: 6 + tag: 5 + val: test +}, +{ + index: 7 + tag: 5 + val: test +}, +{ + index: 8 + tag: 2 + val: 0 +}, +{ + index: 9 + tag: 2 + val: 0 +}, +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0_1655 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#*#test"; "&@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#~A=#A"; "bytecodehar2.file1.test"; "print"; "prototype"; + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x4 +.language ECMAScript +.function any &myapp/hap-file-exec&.#*#main(any a0, any a1, any a2) { +label_1: +label_0: + ldexternalmodulevar 0x2 + sta v0 + throw.undefinedifholewithname test + lda v0 + callarg0 0x0 + ldexternalmodulevar 0x0 + sta v0 + throw.undefinedifholewithname A + mov v1, v0 + newobjrange 0x2, 0x1, v1 + returnundefined +label_2: +} + +slotNum = 0x0 +.language ECMAScript +.function any &myapp/hap-file-exec&.#~B=#B(any a0, any a1, any a2) { +label_1: +label_0: + lda a2 + return +label_2: +} + +slotNum = 0x4 +.language ECMAScript +.function any &myapp/hap-file-exec&.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + definefunc 0x0, &myapp/hap-file-exec&.#*#main, 0x0 + ldhole + sta v0 + defineclasswithbuffer 0x1, &myapp/hap-file-exec&.#~B=#B, &myapp/hap-file-exec&_2, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &myapp/hap-file-exec&_0 +------------------------------------ +slot &myapp/hap-file-exec&_1 +{ + index: 0 + tag: 2 + val: 1 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&&&bytecodehar1/bytecodehar1-file1&2.0.0 +}, +{ + index: 2 + tag: 2 + val: 3 +}, +{ + index: 3 + tag: 5 + val: A +}, +{ + index: 4 + tag: 5 + val: A +}, +{ + index: 5 + tag: 9 + val: 0 +}, +{ + index: 6 + tag: 5 + val: Anno1 +}, +{ + index: 7 + tag: 5 + val: Anno1 +}, +{ + index: 8 + tag: 9 + val: 0 +}, +{ + index: 9 + tag: 5 + val: test +}, +{ + index: 10 + tag: 5 + val: test +}, +{ + index: 11 + tag: 9 + val: 0 +}, +{ + index: 12 + tag: 2 + val: 0 +}, +{ + index: 13 + tag: 2 + val: 0 +}, +{ + index: 14 + tag: 2 + val: 0 +}, +{ + index: 15 + tag: 2 + val: 0 +}, +------------------------------------ +slot &myapp/hap-file-exec&_2 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&myapp/hap-file-exec&.#*#main"; "&myapp/hap-file-exec&.#~B=#B"; "A"; "prototype"; "test"; +slotNum = 0x3 +.language ECMAScript +.function any &sourcehar/sourcehar-file1&2.0.0.#*#test(any a0, any a1, any a2) { +label_1: +label_0: + tryldglobalbyname 0x0, print + sta v0 + lda.str sourcehar.file1.test + sta v1 + lda v0 + callarg1 0x1, v1 + returnundefined +label_2: +} + +slotNum = 0x1 +.language ECMAScript +.function any &sourcehar/sourcehar-file1&2.0.0.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + definefunc 0x0, &sourcehar/sourcehar-file1&2.0.0.#*#test, 0x0 + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &sourcehar/sourcehar-file1&2.0.0_0 +------------------------------------ +slot &sourcehar/sourcehar-file1&2.0.0_1 +{ + index: 0 + tag: 2 + val: 1 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&&&sourcehar/sourcehar-file2&2.0.0 +}, +{ + index: 2 + tag: 2 + val: 1 +}, +{ + index: 3 + tag: 5 + val: test1 +}, +{ + index: 4 + tag: 5 + val: test +}, +{ + index: 5 + tag: 9 + val: 0 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 1 +}, +{ + index: 8 + tag: 5 + val: test +}, +{ + index: 9 + tag: 5 + val: test +}, +{ + index: 10 + tag: 2 + val: 0 +}, +{ + index: 11 + tag: 2 + val: 0 +}, +======> strings <====== +"&sourcehar/sourcehar-file1&2.0.0.#*#test"; "print"; "sourcehar.file1.test"; +slotNum = 0x3 +.language ECMAScript +.function any &sourcehar/sourcehar-file2&2.0.0.#*#test(any a0, any a1, any a2) { +label_1: +label_0: + tryldglobalbyname 0x0, print + sta v0 + lda.str sourcehar.file2.test + sta v1 + lda v0 + callarg1 0x1, v1 + returnundefined +label_2: +} + +slotNum = 0x1 +.language ECMAScript +.function any &sourcehar/sourcehar-file2&2.0.0.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + definefunc 0x0, &sourcehar/sourcehar-file2&2.0.0.#*#test, 0x0 + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &sourcehar/sourcehar-file2&2.0.0_0 +------------------------------------ +slot &sourcehar/sourcehar-file2&2.0.0_1 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 1 +}, +{ + index: 4 + tag: 5 + val: test +}, +{ + index: 5 + tag: 5 + val: test +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +======> strings <====== +"&sourcehar/sourcehar-file2&2.0.0.#*#test"; "print"; "sourcehar.file2.test"; diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/hap-file-exec.ts b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/hap-file-exec.ts new file mode 100644 index 0000000000..8fe9e1625e --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/hap-file-exec.ts @@ -0,0 +1,24 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { test, __$$ETS_ANNOTATION$$__Anno1, A } from "@normalized:N&&&bytecodehar1/bytecodehar1-file1&2.0.0" + +function main() { + test(); + let a = new A(); +} + +@__$$ETS_ANNOTATION$$__Anno1({ b: true }) +class B { } \ No newline at end of file diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/recordnames.txt b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/recordnames.txt new file mode 100644 index 0000000000..70074eddf7 --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/recordnames.txt @@ -0,0 +1,7 @@ +bytecodehar1-file1:&bytecodehar1/bytecodehar1-file1&2.0.0 +bytecodehar1-file2:&bytecodehar1/bytecodehar1-file2&2.0.0 +bytecodehar2-file1:&@ohos/bytecodehar2/bytecodehar2-file1&2.0.0 +bytecodehar2-file2:&@ohos/bytecodehar2/bytecodehar2-file2&2.0.0 +sourcehar-file1:&sourcehar/sourcehar-file1&2.0.0 +sourcehar-file2:&sourcehar/sourcehar-file2&2.0.0 +hap-file-exec:&myapp/hap-file-exec& diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/sourcehar-file1.ts b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/sourcehar-file1.ts new file mode 100644 index 0000000000..f688431373 --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/sourcehar-file1.ts @@ -0,0 +1,20 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {test as test1} from '@normalized:N&&&sourcehar/sourcehar-file2&2.0.0' + +export function test() { + print('sourcehar.file1.test'); +} \ No newline at end of file diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/sourcehar-file2.ts b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/sourcehar-file2.ts new file mode 100644 index 0000000000..7702af0778 --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-dependency-resolve/sourcehar-file2.ts @@ -0,0 +1,18 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export function test() { + print('sourcehar.file2.test'); +} \ No newline at end of file diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/abcinputs/bytecodehar.txt b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/abcinputs/bytecodehar.txt new file mode 100644 index 0000000000..2bed2a047f --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/abcinputs/bytecodehar.txt @@ -0,0 +1,2 @@ +bytecodehar-dynamic-import.ts +bytecodehar-static-import.ts diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/bytecodehar-dynamic-import.ts b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/bytecodehar-dynamic-import.ts new file mode 100644 index 0000000000..30d55ea9ae --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/bytecodehar-dynamic-import.ts @@ -0,0 +1,61 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export let test: string = "test"; + +function testReplacementWoAt() { + import("@normalized:N&module&bundle&lib/importfile1&1.0.0"); + import("@normalized:N&module&bundle&lib/importfile1&"); + import("@normalized:N&module&bundle&lib/importfile1&1.0.0"); + import("@normalized:N&module&bundle&lib/importfile1&"); + + // No-effect since no version info in compileContextInfo.json + import("@normalized:N&&&lib2/importfile3&"); +} + +function testReplacementWithAt() { + import("@normalized:N&lib&&@ohos/lib/importfile2&1.0.0"); + import("@normalized:N&lib&&@ohos/lib/importfile2&"); + import("@normalized:N&lib&&@ohos/lib/importfile2&1.0.0"); + import("@normalized:N&lib&&@ohos/lib/importfile2&"); + + // No-effect since no version info in compileContextInfo.json + import("@normalized:N&&&@ohos/lib2/importfile4&"); +} + +function testNonOhmurl() { + import("aaa"); +} + +function testNonConst() { + // Take effect only under release due to bcopt + let a = "@normalized:N&module&bundle&lib/importfile1&" + import(a); + + a = "@normalized:N&module&bundle&lib/importfile1&"; + let b = "@normalized:N&module&bundle&lib/importfile1&"; + import(a); + + a = "@normalized:N&module&bundle&lib/importfile1&"; + "@normalized:N&module&bundle&lib/importfile1&"; + import(a); +} + +@interface __$$ETS_ANNOTATION$$__Anno1 { + b: boolean = true +} + +@__$$ETS_ANNOTATION$$__Anno1() +class A1 { } diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/bytecodehar-static-import.ts b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/bytecodehar-static-import.ts new file mode 100644 index 0000000000..e8d2d8608c --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/bytecodehar-static-import.ts @@ -0,0 +1,43 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// testReplacementWoAt +import * as a from "@normalized:N&module&bundle&lib/importfile1&1.0.0"; +import * as b from "@normalized:N&module&bundle&lib/importfile1&"; +import * as c from "@normalized:N&&bundle&lib/importfile1&1.0.0"; +import * as d from "@normalized:N&&bundle&lib/importfile1&"; + +// No-effect since no version info in compileContextInfo.json +import * as e from "@normalized:N&&&lib2/importfile3&"; + +//testReplacementWithAt +import * as f from "@normalized:N&module&&@ohos/lib/importfile2&1.0.0"; +import * as g from "@normalized:N&module&&@ohos/lib/importfile2&"; +import * as h from "@normalized:N&&&@ohos/lib/importfile2&1.0.0"; +import * as i from "@normalized:N&&&@ohos/lib/importfile2&"; + +// No-effect since no version info in compileContextInfo.json +import * as j from "@normalized:N&&&@ohos/lib2/importfile4&"; + +function foo() { + print([a, b, c, d, e, f, g, h, i, j]); +} + +@interface __$$ETS_ANNOTATION$$__Anno2 { + b: boolean = true +} + +@__$$ETS_ANNOTATION$$__Anno2() +class B { } diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/compileContextInfo.json b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/compileContextInfo.json new file mode 100644 index 0000000000..f7127bcf76 --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/compileContextInfo.json @@ -0,0 +1,17 @@ +{ + "compileEntries": [ + "com.inter_app.hsp&myapp/inter-app-hsp-file-exec&" + ], + "hspPkgNames": [ + "lib", + "@ohos/lib" + ], + "updateVersionInfo": { + "bytecodehar": { + "lib": "2.0.0", + "@ohos/lib": "2.0.0" + } + }, + "needModifyRecord": true, + "bundleName": "com.inter_app.hsp" +} diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/importfile1.ts b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/importfile1.ts new file mode 100644 index 0000000000..5635f70b71 --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/importfile1.ts @@ -0,0 +1,16 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const test1: boolean = true; \ No newline at end of file diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/importfile2.ts b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/importfile2.ts new file mode 100644 index 0000000000..5267ff5e29 --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/importfile2.ts @@ -0,0 +1,16 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const test2: boolean = true; \ No newline at end of file diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/importfile3.ts b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/importfile3.ts new file mode 100644 index 0000000000..d9a8057d7b --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/importfile3.ts @@ -0,0 +1,16 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const test3: boolean = true; \ No newline at end of file diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/importfile4.ts b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/importfile4.ts new file mode 100644 index 0000000000..3fedda824b --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/importfile4.ts @@ -0,0 +1,16 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const test4: boolean = true; \ No newline at end of file diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/inter-app-hsp-file-exec-expected.pa.txt b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/inter-app-hsp-file-exec-expected.pa.txt new file mode 100644 index 0000000000..cf4b80b652 --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/inter-app-hsp-file-exec-expected.pa.txt @@ -0,0 +1,1508 @@ +All Dependency Files: +program_file: bytecodehar-abcinput.abc +record_name: com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import& +program_file: bytecodehar-abcinput.abc +record_name: com.inter_app.hsp&bytecodehar/bytecodehar-static-import& +program_file: importfile3.ts +record_name: com.inter_app.hsp&lib2/importfile3& +program_file: importfile4.ts +record_name: com.inter_app.hsp&@ohos/lib2/importfile4& +program_file: inter-app-hsp-file-exec.ts +record_name: com.inter_app.hsp&myapp/inter-app-hsp-file-exec& + + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x0 +.language ECMAScript +.function any com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&.#*#testNonConst(any a0, any a1, any a2) { + lda.str @normalized:N&module&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&module&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&module&bundle&lib/importfile1&2.0.0 + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&.#*#testNonOhmurl(any a0, any a1, any a2) { + lda.str aaa + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWithAt(any a0, any a1, any a2) { + lda.str @normalized:N&lib&&@ohos/lib/importfile2&2.0.0 + dynamicimport + lda.str @normalized:N&lib&&@ohos/lib/importfile2&2.0.0 + dynamicimport + lda.str @normalized:N&lib&&@ohos/lib/importfile2&2.0.0 + dynamicimport + lda.str @normalized:N&lib&&@ohos/lib/importfile2&2.0.0 + dynamicimport + lda.str @normalized:N&&com.inter_app.hsp&@ohos/lib2/importfile4& + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWoAt(any a0, any a1, any a2) { + lda.str @normalized:N&module&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&module&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&module&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&module&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&&com.inter_app.hsp&lib2/importfile3& + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&.#~A1=#A1(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x7 +.language ECMAScript +.function any com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&.#*#testNonConst, 0x0 + definefunc 0x1, com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&.#*#testNonOhmurl, 0x0 + definefunc 0x2, com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWithAt, 0x0 + definefunc 0x3, com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWoAt, 0x0 + lda.str test + stmodulevar 0x0 + ldhole + sta v0 + defineclasswithbuffer 0x4, com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&.#~A1=#A1, com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&_2561, 0x0, v0 + ldobjbyname 0x5, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&_2521 +------------------------------------ +slot com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&_2525 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 1 +}, +{ + index: 4 + tag: 5 + val: test +}, +{ + index: 5 + tag: 5 + val: test +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +------------------------------------ +slot com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&_2561 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"@normalized:N&&com.inter_app.hsp&@ohos/lib2/importfile4&"; "@normalized:N&&com.inter_app.hsp&lib2/importfile3&"; "@normalized:N&lib&&@ohos/lib/importfile2&2.0.0"; "@normalized:N&module&bundle&lib/importfile1&2.0.0"; "aaa"; "com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&.#*#testNonConst"; "com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&.#*#testNonOhmurl"; "com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWithAt"; "com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWoAt"; "com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&.#~A1=#A1"; "prototype"; "test"; + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x18 +.language ECMAScript +.function any com.inter_app.hsp&bytecodehar/bytecodehar-static-import&.#*#foo(any a0, any a1, any a2) { + tryldglobalbyname 0x0, print + sta v0 + createemptyarray 0x1 + sta v1 + ldlexvar 0x0, 0x0 + sta v2 + throw.undefinedifholewithname a + lda v2 + stownbyindex 0x2, v1, 0x0 + ldlexvar 0x0, 0x1 + sta v2 + throw.undefinedifholewithname b + lda v2 + stownbyindex 0x4, v1, 0x1 + ldlexvar 0x0, 0x2 + sta v2 + throw.undefinedifholewithname c + lda v2 + stownbyindex 0x6, v1, 0x2 + ldlexvar 0x0, 0x3 + sta v2 + throw.undefinedifholewithname d + lda v2 + stownbyindex 0x8, v1, 0x3 + ldlexvar 0x0, 0x4 + sta v2 + throw.undefinedifholewithname e + lda v2 + stownbyindex 0xa, v1, 0x4 + ldlexvar 0x0, 0x5 + sta v2 + throw.undefinedifholewithname f + lda v2 + stownbyindex 0xc, v1, 0x5 + ldlexvar 0x0, 0x6 + sta v2 + throw.undefinedifholewithname g + lda v2 + stownbyindex 0xe, v1, 0x6 + ldlexvar 0x0, 0x7 + sta v2 + throw.undefinedifholewithname h + lda v2 + stownbyindex 0x10, v1, 0x7 + ldlexvar 0x0, 0x8 + sta v2 + throw.undefinedifholewithname i + lda v2 + stownbyindex 0x12, v1, 0x8 + ldlexvar 0x0, 0x9 + sta v2 + throw.undefinedifholewithname j + lda v2 + stownbyindex 0x14, v1, 0x9 + lda v0 + callarg1 0x16, v1 + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any com.inter_app.hsp&bytecodehar/bytecodehar-static-import&.#~B=#B(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x4 +.language ECMAScript +.function any com.inter_app.hsp&bytecodehar/bytecodehar-static-import&.func_main_0(any a0, any a1, any a2) { + newlexenv 0xa + definefunc 0x0, com.inter_app.hsp&bytecodehar/bytecodehar-static-import&.#*#foo, 0x0 + getmodulenamespace 0x0 + stlexvar 0x0, 0x0 + getmodulenamespace 0x1 + stlexvar 0x0, 0x1 + getmodulenamespace 0x2 + stlexvar 0x0, 0x2 + getmodulenamespace 0x3 + stlexvar 0x0, 0x3 + getmodulenamespace 0x4 + stlexvar 0x0, 0x4 + getmodulenamespace 0x5 + stlexvar 0x0, 0x5 + getmodulenamespace 0x6 + stlexvar 0x0, 0x6 + getmodulenamespace 0x7 + stlexvar 0x0, 0x7 + getmodulenamespace 0x8 + stlexvar 0x0, 0x8 + getmodulenamespace 0x9 + stlexvar 0x0, 0x9 + ldhole + sta v0 + defineclasswithbuffer 0x1, com.inter_app.hsp&bytecodehar/bytecodehar-static-import&.#~B=#B, com.inter_app.hsp&bytecodehar/bytecodehar-static-import&_2702, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot com.inter_app.hsp&bytecodehar/bytecodehar-static-import&_2570 +------------------------------------ +slot com.inter_app.hsp&bytecodehar/bytecodehar-static-import&_2574 +{ + index: 0 + tag: 2 + val: 10 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&module&bundle&lib/importfile1&2.0.0 +}, +{ + index: 2 + tag: 5 + val: @normalized:N&module&bundle&lib/importfile1&2.0.0 +}, +{ + index: 3 + tag: 5 + val: @normalized:N&&bundle&lib/importfile1&2.0.0 +}, +{ + index: 4 + tag: 5 + val: @normalized:N&&bundle&lib/importfile1&2.0.0 +}, +{ + index: 5 + tag: 5 + val: @normalized:N&&com.inter_app.hsp&lib2/importfile3& +}, +{ + index: 6 + tag: 5 + val: @normalized:N&module&&@ohos/lib/importfile2&2.0.0 +}, +{ + index: 7 + tag: 5 + val: @normalized:N&module&&@ohos/lib/importfile2&2.0.0 +}, +{ + index: 8 + tag: 5 + val: @normalized:N&&&@ohos/lib/importfile2&2.0.0 +}, +{ + index: 9 + tag: 5 + val: @normalized:N&&&@ohos/lib/importfile2&2.0.0 +}, +{ + index: 10 + tag: 5 + val: @normalized:N&&com.inter_app.hsp&@ohos/lib2/importfile4& +}, +{ + index: 11 + tag: 2 + val: 0 +}, +{ + index: 12 + tag: 2 + val: 10 +}, +{ + index: 13 + tag: 5 + val: a +}, +{ + index: 14 + tag: 9 + val: 0 +}, +{ + index: 15 + tag: 5 + val: b +}, +{ + index: 16 + tag: 9 + val: 1 +}, +{ + index: 17 + tag: 5 + val: c +}, +{ + index: 18 + tag: 9 + val: 2 +}, +{ + index: 19 + tag: 5 + val: d +}, +{ + index: 20 + tag: 9 + val: 3 +}, +{ + index: 21 + tag: 5 + val: e +}, +{ + index: 22 + tag: 9 + val: 4 +}, +{ + index: 23 + tag: 5 + val: f +}, +{ + index: 24 + tag: 9 + val: 5 +}, +{ + index: 25 + tag: 5 + val: g +}, +{ + index: 26 + tag: 9 + val: 6 +}, +{ + index: 27 + tag: 5 + val: h +}, +{ + index: 28 + tag: 9 + val: 7 +}, +{ + index: 29 + tag: 5 + val: i +}, +{ + index: 30 + tag: 9 + val: 8 +}, +{ + index: 31 + tag: 5 + val: j +}, +{ + index: 32 + tag: 9 + val: 9 +}, +{ + index: 33 + tag: 2 + val: 0 +}, +{ + index: 34 + tag: 2 + val: 0 +}, +{ + index: 35 + tag: 2 + val: 0 +}, +------------------------------------ +slot com.inter_app.hsp&bytecodehar/bytecodehar-static-import&_2702 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"a"; "b"; "c"; "com.inter_app.hsp&bytecodehar/bytecodehar-static-import&.#*#foo"; "com.inter_app.hsp&bytecodehar/bytecodehar-static-import&.#~B=#B"; "d"; "e"; "f"; "g"; "h"; "i"; "j"; "print"; "prototype"; + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x0 +.language ECMAScript +.function any bundle&lib/importfile1&2.0.0.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + ldtrue + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot bundle&lib/importfile1&2.0.0_0 +------------------------------------ +slot bundle&lib/importfile1&2.0.0_1 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 1 +}, +{ + index: 4 + tag: 5 + val: test1 +}, +{ + index: 5 + tag: 5 + val: test1 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +======> strings <====== + +slotNum = 0x0 +.language ECMAScript +.function any com.inter_app.hsp&@ohos/lib/importfile2&2.0.0.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + ldtrue + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot com.inter_app.hsp&@ohos/lib/importfile2&2.0.0_0 +------------------------------------ +slot com.inter_app.hsp&@ohos/lib/importfile2&2.0.0_1 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 1 +}, +{ + index: 4 + tag: 5 + val: test2 +}, +{ + index: 5 + tag: 5 + val: test2 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +======> strings <====== + +slotNum = 0x0 +.language ECMAScript +.function any com.inter_app.hsp&lib2/importfile3&.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + ldtrue + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot com.inter_app.hsp&lib2/importfile3&_0 +------------------------------------ +slot com.inter_app.hsp&lib2/importfile3&_1 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 1 +}, +{ + index: 4 + tag: 5 + val: test3 +}, +{ + index: 5 + tag: 5 + val: test3 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +======> strings <====== + +slotNum = 0x0 +.language ECMAScript +.function any com.inter_app.hsp&@ohos/lib2/importfile4&.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + ldtrue + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot com.inter_app.hsp&@ohos/lib2/importfile4&_0 +------------------------------------ +slot com.inter_app.hsp&@ohos/lib2/importfile4&_1 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 1 +}, +{ + index: 4 + tag: 5 + val: test4 +}, +{ + index: 5 + tag: 5 + val: test4 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +======> strings <====== + +slotNum = 0x0 +.language ECMAScript +.function any com.inter_app.hsp&myapp/inter-app-hsp-file-exec&.#~A=#A(any a0, any a1, any a2) { +label_1: +label_0: + lda a2 + return +label_2: +} + +slotNum = 0xd +.language ECMAScript +.function any com.inter_app.hsp&myapp/inter-app-hsp-file-exec&.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + getmodulenamespace 0x0 + sta v0 + getmodulenamespace 0x1 + sta v1 + tryldglobalbyname 0x0, print + sta v2 + lda v0 + ldobjbyname 0x1, test + sta v0 + lda v2 + callarg1 0x3, v0 + tryldglobalbyname 0x5, print + sta v0 + lda v1 + ldobjbyname 0x6, test + sta v1 + lda v0 + callarg1 0x8, v1 + ldhole + sta v0 + defineclasswithbuffer 0xa, com.inter_app.hsp&myapp/inter-app-hsp-file-exec&.#~A=#A, com.inter_app.hsp&myapp/inter-app-hsp-file-exec&_2, 0x0, v0 + ldobjbyname 0xb, prototype + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot com.inter_app.hsp&myapp/inter-app-hsp-file-exec&_0 +------------------------------------ +slot com.inter_app.hsp&myapp/inter-app-hsp-file-exec&_1 +{ + index: 0 + tag: 2 + val: 2 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&&com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import& +}, +{ + index: 2 + tag: 5 + val: @normalized:N&&com.inter_app.hsp&bytecodehar/bytecodehar-static-import& +}, +{ + index: 3 + tag: 2 + val: 0 +}, +{ + index: 4 + tag: 2 + val: 2 +}, +{ + index: 5 + tag: 5 + val: bytecodeharDynamicImport +}, +{ + index: 6 + tag: 9 + val: 0 +}, +{ + index: 7 + tag: 5 + val: bytecodeharStaticImport +}, +{ + index: 8 + tag: 9 + val: 1 +}, +{ + index: 9 + tag: 2 + val: 0 +}, +{ + index: 10 + tag: 2 + val: 0 +}, +{ + index: 11 + tag: 2 + val: 0 +}, +------------------------------------ +slot com.inter_app.hsp&myapp/inter-app-hsp-file-exec&_2 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"com.inter_app.hsp&myapp/inter-app-hsp-file-exec&.#~A=#A"; "print"; "prototype"; "test"; +slotNum = 0x0 +.language ECMAScript +.function any com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&.#*#testNonConst(any a0, any a1, any a2) { + lda.str @normalized:N&module&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&module&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&module&bundle&lib/importfile1&2.0.0 + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&.#*#testNonOhmurl(any a0, any a1, any a2) { + lda.str aaa + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWithAt(any a0, any a1, any a2) { + lda.str @normalized:N&lib&&@ohos/lib/importfile2&2.0.0 + dynamicimport + lda.str @normalized:N&lib&&@ohos/lib/importfile2&2.0.0 + dynamicimport + lda.str @normalized:N&lib&&@ohos/lib/importfile2&2.0.0 + dynamicimport + lda.str @normalized:N&lib&&@ohos/lib/importfile2&2.0.0 + dynamicimport + lda.str @normalized:N&&com.inter_app.hsp&@ohos/lib2/importfile4& + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWoAt(any a0, any a1, any a2) { + lda.str @normalized:N&module&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&module&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&module&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&module&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&&com.inter_app.hsp&lib2/importfile3& + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&.#~A1=#A1(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x7 +.language ECMAScript +.function any com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&.#*#testNonConst, 0x0 + definefunc 0x1, com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&.#*#testNonOhmurl, 0x0 + definefunc 0x2, com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWithAt, 0x0 + definefunc 0x3, com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWoAt, 0x0 + lda.str test + stmodulevar 0x0 + ldhole + sta v0 + defineclasswithbuffer 0x4, com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&.#~A1=#A1, com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&_2561, 0x0, v0 + ldobjbyname 0x5, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&_2521 +------------------------------------ +slot com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&_2525 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 1 +}, +{ + index: 4 + tag: 5 + val: test +}, +{ + index: 5 + tag: 5 + val: test +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +------------------------------------ +slot com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&_2561 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"@normalized:N&&com.inter_app.hsp&@ohos/lib2/importfile4&"; "@normalized:N&&com.inter_app.hsp&lib2/importfile3&"; "@normalized:N&lib&&@ohos/lib/importfile2&2.0.0"; "@normalized:N&module&bundle&lib/importfile1&2.0.0"; "aaa"; "com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&.#*#testNonConst"; "com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&.#*#testNonOhmurl"; "com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWithAt"; "com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWoAt"; "com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&.#~A1=#A1"; "prototype"; "test"; + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x18 +.language ECMAScript +.function any com.inter_app.hsp&bytecodehar/bytecodehar-static-import&.#*#foo(any a0, any a1, any a2) { + tryldglobalbyname 0x0, print + sta v0 + createemptyarray 0x1 + sta v1 + ldlexvar 0x0, 0x0 + sta v2 + throw.undefinedifholewithname a + lda v2 + stownbyindex 0x2, v1, 0x0 + ldlexvar 0x0, 0x1 + sta v2 + throw.undefinedifholewithname b + lda v2 + stownbyindex 0x4, v1, 0x1 + ldlexvar 0x0, 0x2 + sta v2 + throw.undefinedifholewithname c + lda v2 + stownbyindex 0x6, v1, 0x2 + ldlexvar 0x0, 0x3 + sta v2 + throw.undefinedifholewithname d + lda v2 + stownbyindex 0x8, v1, 0x3 + ldlexvar 0x0, 0x4 + sta v2 + throw.undefinedifholewithname e + lda v2 + stownbyindex 0xa, v1, 0x4 + ldlexvar 0x0, 0x5 + sta v2 + throw.undefinedifholewithname f + lda v2 + stownbyindex 0xc, v1, 0x5 + ldlexvar 0x0, 0x6 + sta v2 + throw.undefinedifholewithname g + lda v2 + stownbyindex 0xe, v1, 0x6 + ldlexvar 0x0, 0x7 + sta v2 + throw.undefinedifholewithname h + lda v2 + stownbyindex 0x10, v1, 0x7 + ldlexvar 0x0, 0x8 + sta v2 + throw.undefinedifholewithname i + lda v2 + stownbyindex 0x12, v1, 0x8 + ldlexvar 0x0, 0x9 + sta v2 + throw.undefinedifholewithname j + lda v2 + stownbyindex 0x14, v1, 0x9 + lda v0 + callarg1 0x16, v1 + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any com.inter_app.hsp&bytecodehar/bytecodehar-static-import&.#~B=#B(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x4 +.language ECMAScript +.function any com.inter_app.hsp&bytecodehar/bytecodehar-static-import&.func_main_0(any a0, any a1, any a2) { + newlexenv 0xa + definefunc 0x0, com.inter_app.hsp&bytecodehar/bytecodehar-static-import&.#*#foo, 0x0 + getmodulenamespace 0x0 + stlexvar 0x0, 0x0 + getmodulenamespace 0x1 + stlexvar 0x0, 0x1 + getmodulenamespace 0x2 + stlexvar 0x0, 0x2 + getmodulenamespace 0x3 + stlexvar 0x0, 0x3 + getmodulenamespace 0x4 + stlexvar 0x0, 0x4 + getmodulenamespace 0x5 + stlexvar 0x0, 0x5 + getmodulenamespace 0x6 + stlexvar 0x0, 0x6 + getmodulenamespace 0x7 + stlexvar 0x0, 0x7 + getmodulenamespace 0x8 + stlexvar 0x0, 0x8 + getmodulenamespace 0x9 + stlexvar 0x0, 0x9 + ldhole + sta v0 + defineclasswithbuffer 0x1, com.inter_app.hsp&bytecodehar/bytecodehar-static-import&.#~B=#B, com.inter_app.hsp&bytecodehar/bytecodehar-static-import&_2702, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot com.inter_app.hsp&bytecodehar/bytecodehar-static-import&_2570 +------------------------------------ +slot com.inter_app.hsp&bytecodehar/bytecodehar-static-import&_2574 +{ + index: 0 + tag: 2 + val: 10 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&module&bundle&lib/importfile1&2.0.0 +}, +{ + index: 2 + tag: 5 + val: @normalized:N&module&bundle&lib/importfile1&2.0.0 +}, +{ + index: 3 + tag: 5 + val: @normalized:N&&bundle&lib/importfile1&2.0.0 +}, +{ + index: 4 + tag: 5 + val: @normalized:N&&bundle&lib/importfile1&2.0.0 +}, +{ + index: 5 + tag: 5 + val: @normalized:N&&com.inter_app.hsp&lib2/importfile3& +}, +{ + index: 6 + tag: 5 + val: @normalized:N&module&&@ohos/lib/importfile2&2.0.0 +}, +{ + index: 7 + tag: 5 + val: @normalized:N&module&&@ohos/lib/importfile2&2.0.0 +}, +{ + index: 8 + tag: 5 + val: @normalized:N&&&@ohos/lib/importfile2&2.0.0 +}, +{ + index: 9 + tag: 5 + val: @normalized:N&&&@ohos/lib/importfile2&2.0.0 +}, +{ + index: 10 + tag: 5 + val: @normalized:N&&com.inter_app.hsp&@ohos/lib2/importfile4& +}, +{ + index: 11 + tag: 2 + val: 0 +}, +{ + index: 12 + tag: 2 + val: 10 +}, +{ + index: 13 + tag: 5 + val: a +}, +{ + index: 14 + tag: 9 + val: 0 +}, +{ + index: 15 + tag: 5 + val: b +}, +{ + index: 16 + tag: 9 + val: 1 +}, +{ + index: 17 + tag: 5 + val: c +}, +{ + index: 18 + tag: 9 + val: 2 +}, +{ + index: 19 + tag: 5 + val: d +}, +{ + index: 20 + tag: 9 + val: 3 +}, +{ + index: 21 + tag: 5 + val: e +}, +{ + index: 22 + tag: 9 + val: 4 +}, +{ + index: 23 + tag: 5 + val: f +}, +{ + index: 24 + tag: 9 + val: 5 +}, +{ + index: 25 + tag: 5 + val: g +}, +{ + index: 26 + tag: 9 + val: 6 +}, +{ + index: 27 + tag: 5 + val: h +}, +{ + index: 28 + tag: 9 + val: 7 +}, +{ + index: 29 + tag: 5 + val: i +}, +{ + index: 30 + tag: 9 + val: 8 +}, +{ + index: 31 + tag: 5 + val: j +}, +{ + index: 32 + tag: 9 + val: 9 +}, +{ + index: 33 + tag: 2 + val: 0 +}, +{ + index: 34 + tag: 2 + val: 0 +}, +{ + index: 35 + tag: 2 + val: 0 +}, +------------------------------------ +slot com.inter_app.hsp&bytecodehar/bytecodehar-static-import&_2702 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"a"; "b"; "c"; "com.inter_app.hsp&bytecodehar/bytecodehar-static-import&.#*#foo"; "com.inter_app.hsp&bytecodehar/bytecodehar-static-import&.#~B=#B"; "d"; "e"; "f"; "g"; "h"; "i"; "j"; "print"; "prototype"; + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x0 +.language ECMAScript +.function any com.inter_app.hsp&lib2/importfile3&.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + ldtrue + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot com.inter_app.hsp&lib2/importfile3&_0 +------------------------------------ +slot com.inter_app.hsp&lib2/importfile3&_1 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 1 +}, +{ + index: 4 + tag: 5 + val: test3 +}, +{ + index: 5 + tag: 5 + val: test3 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +======> strings <====== + +slotNum = 0x0 +.language ECMAScript +.function any com.inter_app.hsp&@ohos/lib2/importfile4&.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + ldtrue + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot com.inter_app.hsp&@ohos/lib2/importfile4&_0 +------------------------------------ +slot com.inter_app.hsp&@ohos/lib2/importfile4&_1 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 1 +}, +{ + index: 4 + tag: 5 + val: test4 +}, +{ + index: 5 + tag: 5 + val: test4 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +======> strings <====== + +slotNum = 0x0 +.language ECMAScript +.function any com.inter_app.hsp&myapp/inter-app-hsp-file-exec&.#~A=#A(any a0, any a1, any a2) { +label_1: +label_0: + lda a2 + return +label_2: +} + +slotNum = 0xd +.language ECMAScript +.function any com.inter_app.hsp&myapp/inter-app-hsp-file-exec&.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + getmodulenamespace 0x0 + sta v0 + getmodulenamespace 0x1 + sta v1 + tryldglobalbyname 0x0, print + sta v2 + lda v0 + ldobjbyname 0x1, test + sta v0 + lda v2 + callarg1 0x3, v0 + tryldglobalbyname 0x5, print + sta v0 + lda v1 + ldobjbyname 0x6, test + sta v1 + lda v0 + callarg1 0x8, v1 + ldhole + sta v0 + defineclasswithbuffer 0xa, com.inter_app.hsp&myapp/inter-app-hsp-file-exec&.#~A=#A, com.inter_app.hsp&myapp/inter-app-hsp-file-exec&_2, 0x0, v0 + ldobjbyname 0xb, prototype + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot com.inter_app.hsp&myapp/inter-app-hsp-file-exec&_0 +------------------------------------ +slot com.inter_app.hsp&myapp/inter-app-hsp-file-exec&_1 +{ + index: 0 + tag: 2 + val: 2 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&&com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import& +}, +{ + index: 2 + tag: 5 + val: @normalized:N&&com.inter_app.hsp&bytecodehar/bytecodehar-static-import& +}, +{ + index: 3 + tag: 2 + val: 0 +}, +{ + index: 4 + tag: 2 + val: 2 +}, +{ + index: 5 + tag: 5 + val: bytecodeharDynamicImport +}, +{ + index: 6 + tag: 9 + val: 0 +}, +{ + index: 7 + tag: 5 + val: bytecodeharStaticImport +}, +{ + index: 8 + tag: 9 + val: 1 +}, +{ + index: 9 + tag: 2 + val: 0 +}, +{ + index: 10 + tag: 2 + val: 0 +}, +{ + index: 11 + tag: 2 + val: 0 +}, +------------------------------------ +slot com.inter_app.hsp&myapp/inter-app-hsp-file-exec&_2 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"com.inter_app.hsp&myapp/inter-app-hsp-file-exec&.#~A=#A"; "print"; "prototype"; "test"; diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/inter-app-hsp-file-exec.ts b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/inter-app-hsp-file-exec.ts new file mode 100644 index 0000000000..0a849d9f96 --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/inter-app-hsp-file-exec.ts @@ -0,0 +1,24 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as bytecodeharDynamicImport from "@normalized:N&&com.inter_app.hsp&bytecodehar/bytecodehar-dynamic-import&"; +import * as bytecodeharStaticImport from "@normalized:N&&com.inter_app.hsp&bytecodehar/bytecodehar-static-import&"; + +print(bytecodeharDynamicImport.test) +print(bytecodeharStaticImport.test) + +@bytecodeharDynamicImport.__$$ETS_ANNOTATION$$__Anno1() +@bytecodeharStaticImport.__$$ETS_ANNOTATION$$__Anno2() +class A { } \ No newline at end of file diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/recordnames.txt b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/recordnames.txt new file mode 100644 index 0000000000..7fff897e3c --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-inter-app-hsp/recordnames.txt @@ -0,0 +1,7 @@ +bytecodehar-dynamic-import:&bytecodehar/bytecodehar-dynamic-import& +bytecodehar-static-import:&bytecodehar/bytecodehar-static-import& +importfile1:bundle&lib/importfile1&2.0.0 +importfile2:com.inter_app.hsp&@ohos/lib/importfile2&2.0.0 +importfile3:com.inter_app.hsp&lib2/importfile3& +importfile4:com.inter_app.hsp&@ohos/lib2/importfile4& +inter-app-hsp-file-exec:com.inter_app.hsp&myapp/inter-app-hsp-file-exec& diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/abcinputs/bytecodehar1.txt b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/abcinputs/bytecodehar1.txt new file mode 100644 index 0000000000..44fef6254c --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/abcinputs/bytecodehar1.txt @@ -0,0 +1,2 @@ +bytecodehar1-file1.ts +bytecodehar1-file2.ts diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/abcinputs/bytecodehar2.txt b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/abcinputs/bytecodehar2.txt new file mode 100644 index 0000000000..01249cd0af --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/abcinputs/bytecodehar2.txt @@ -0,0 +1,2 @@ +bytecodehar2-file1.ts +bytecodehar2-file2.ts diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/bytecodehar1-file1.ts b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/bytecodehar1-file1.ts new file mode 100644 index 0000000000..a057a3927b --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/bytecodehar1-file1.ts @@ -0,0 +1,34 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {test as test1} from '@normalized:N&&&@ohos/bytecodehar2/bytecodehar2-file1&2.0.0' + +export function test() { + print('bytecodehar1.file1.test'); + import('@normalized:N&&&sourcehar/sourcehar-file1&2.0.0') +} + +function A(a) { + this.a = a + this.b = 1 + this.c = 2 +} + +export @interface __$$ETS_ANNOTATION$$__Anno1 { + b: boolean = true +} + +@__$$ETS_ANNOTATION$$__Anno1() +class B { } diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/bytecodehar1-file2.ts b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/bytecodehar1-file2.ts new file mode 100644 index 0000000000..3946722605 --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/bytecodehar1-file2.ts @@ -0,0 +1,40 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {test as test1} from "@normalized:N&&&@ohos/bytecodehar2/bytecodehar2-file2&1.0.0" + +export function test() { + print('bytecodehar1.file2.test'); + import("@normalized:N&&&sourcehar/sourcehar-file2&2.0.0") +} + +class Example { + a: number; + + constructor() { + this.a = 0; + } + + setValue(value: number) { + this.a = value; + } +} + +export @interface __$$ETS_ANNOTATION$$__Anno2 { + b: boolean = true +} + +@__$$ETS_ANNOTATION$$__Anno2() +class A { } diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/bytecodehar2-file1.ts b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/bytecodehar2-file1.ts new file mode 100644 index 0000000000..c040f93e6c --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/bytecodehar2-file1.ts @@ -0,0 +1,25 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export function test() { + print('bytecodehar2.file1.test'); +} + +export @interface __$$ETS_ANNOTATION$$__Anno1 { + b: boolean = true +} + +@__$$ETS_ANNOTATION$$__Anno1() +class A { } diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/bytecodehar2-file2.ts b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/bytecodehar2-file2.ts new file mode 100644 index 0000000000..a2da8dcd93 --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/bytecodehar2-file2.ts @@ -0,0 +1,25 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export function test() { + print('bytecodehar2.file2.test'); +} + +export @interface __$$ETS_ANNOTATION$$__Anno2 { + b: boolean = true +} + +@__$$ETS_ANNOTATION$$__Anno2() +class B { } diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/compileContextInfo.json b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/compileContextInfo.json new file mode 100644 index 0000000000..a8744ff6d3 --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/compileContextInfo.json @@ -0,0 +1,44 @@ +{ + "compileEntries": [ + "&myapp/hap-file-exec&" + ], + "hspPkgNames": [], + "pkgContextInfo": { + "myapp": { + "packageName": "myapp", + "bundleName": "", + "moduleName": "", + "version": "", + "entryPath": "", + "isSo": false, + "dependencyAlias": "" + }, + "bytecodehar1": { + "packageName": "bytecodehar1", + "bundleName": "", + "moduleName": "", + "version": "2.0.0", + "entryPath": "", + "isSo": false, + "dependencyAlias": "" + }, + "@ohos/bytecodehar2": { + "packageName": "@ohos/bytecodehar2", + "bundleName": "", + "moduleName": "", + "version": "2.0.0", + "entryPath": "", + "isSo": false, + "dependencyAlias": "" + }, + "sourcehar": { + "packageName": "sourcehar", + "bundleName": "", + "moduleName": "", + "version": "2.0.0", + "entryPath": "", + "isSo": false, + "dependencyAlias": "" + } + } +} diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/hap-file-exec-expected.pa.txt b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/hap-file-exec-expected.pa.txt new file mode 100644 index 0000000000..d6cd6d3e45 --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/hap-file-exec-expected.pa.txt @@ -0,0 +1,1340 @@ +All Dependency Files: +program_file: bytecodehar1-abcinput.abc +record_name: &bytecodehar1/bytecodehar1-file1&2.0.0 +program_file: bytecodehar2-abcinput.abc +record_name: &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0 +program_file: hap-file-exec.ts +record_name: &myapp/hap-file-exec& +program_file: sourcehar-file1.ts +record_name: &sourcehar/sourcehar-file1&2.0.0 + +slotNum = 0x6 +expectedProperty = 0x3 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file1&2.0.0.#*#A(any a0, any a1, any a2, any a3) { + lda a3 + stobjbyname 0x0, a, a2 + ldai 0x1 + stobjbyname 0x2, b, a2 + ldai 0x2 + stobjbyname 0x4, c, a2 + returnundefined +} + +slotNum = 0x3 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file1&2.0.0.#*#test(any a0, any a1, any a2) { + tryldglobalbyname 0x0, print + sta v0 + lda.str bytecodehar1.file1.test + sta v1 + lda v0 + callarg1 0x1, v1 + lda.str @normalized:N&&&sourcehar/sourcehar-file1&2.0.0 + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file1&2.0.0.#~B=#B(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x5 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file1&2.0.0.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, &bytecodehar1/bytecodehar1-file1&2.0.0.#*#A, 0x1 + definefunc 0x1, &bytecodehar1/bytecodehar1-file1&2.0.0.#*#test, 0x0 + stmodulevar 0x1 + ldhole + sta v0 + defineclasswithbuffer 0x2, &bytecodehar1/bytecodehar1-file1&2.0.0.#~B=#B, &bytecodehar1/bytecodehar1-file1&2.0.0_2142, 0x0, v0 + ldobjbyname 0x3, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &bytecodehar1/bytecodehar1-file1&2.0.0_2080 +------------------------------------ +slot &bytecodehar1/bytecodehar1-file1&2.0.0_2084 +{ + index: 0 + tag: 2 + val: 1 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&&&@ohos/bytecodehar2/bytecodehar2-file1&2.0.0 +}, +{ + index: 2 + tag: 2 + val: 1 +}, +{ + index: 3 + tag: 5 + val: test1 +}, +{ + index: 4 + tag: 5 + val: test +}, +{ + index: 5 + tag: 9 + val: 0 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 2 +}, +{ + index: 8 + tag: 5 + val: Anno1 +}, +{ + index: 9 + tag: 5 + val: Anno1 +}, +{ + index: 10 + tag: 5 + val: test +}, +{ + index: 11 + tag: 5 + val: test +}, +{ + index: 12 + tag: 2 + val: 0 +}, +{ + index: 13 + tag: 2 + val: 0 +}, +------------------------------------ +slot &bytecodehar1/bytecodehar1-file1&2.0.0_2142 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&bytecodehar1/bytecodehar1-file1&2.0.0.#*#A"; "&bytecodehar1/bytecodehar1-file1&2.0.0.#*#test"; "&bytecodehar1/bytecodehar1-file1&2.0.0.#~B=#B"; "@normalized:N&&&sourcehar/sourcehar-file1&2.0.0"; "a"; "b"; "bytecodehar1.file1.test"; "c"; "print"; "prototype"; + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x3 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file2&2.0.0.#*#test(any a0, any a1, any a2) { + tryldglobalbyname 0x0, print + sta v0 + lda.str bytecodehar1.file2.test + sta v1 + lda v0 + callarg1 0x1, v1 + lda.str @normalized:N&&&sourcehar/sourcehar-file2&2.0.0 + dynamicimport + returnundefined +} + +slotNum = 0x2 +expectedProperty = 0x1 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file2&2.0.0.#~@0=#Example(any a0, any a1, any a2) { + ldai 0x0 + stobjbyname 0x0, a, a2 + lda a2 + return +} + +slotNum = 0x2 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file2&2.0.0.#~@0>#setValue(any a0, any a1, any a2, any a3) { + lda a3 + stobjbyname 0x0, a, a2 + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file2&2.0.0.#~A=#A(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x7 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file2&2.0.0.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, &bytecodehar1/bytecodehar1-file2&2.0.0.#*#test, 0x0 + stmodulevar 0x1 + ldhole + sta v0 + defineclasswithbuffer 0x1, &bytecodehar1/bytecodehar1-file2&2.0.0.#~@0=#Example, &bytecodehar1/bytecodehar1-file2&2.0.0_2218, 0x0, v0 + ldobjbyname 0x2, prototype + ldhole + sta v0 + defineclasswithbuffer 0x4, &bytecodehar1/bytecodehar1-file2&2.0.0.#~A=#A, &bytecodehar1/bytecodehar1-file2&2.0.0_2240, 0x0, v0 + ldobjbyname 0x5, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &bytecodehar1/bytecodehar1-file2&2.0.0_2151 +{ + index: 0 + tag: 0 + val: 5 +}, +{ + index: 1 + tag: 5 + val: Example +}, +------------------------------------ +slot &bytecodehar1/bytecodehar1-file2&2.0.0_2160 +{ + index: 0 + tag: 2 + val: 1 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&&&@ohos/bytecodehar2/bytecodehar2-file2&2.0.0 +}, +{ + index: 2 + tag: 2 + val: 1 +}, +{ + index: 3 + tag: 5 + val: test1 +}, +{ + index: 4 + tag: 5 + val: test +}, +{ + index: 5 + tag: 9 + val: 0 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 2 +}, +{ + index: 8 + tag: 5 + val: Anno2 +}, +{ + index: 9 + tag: 5 + val: Anno2 +}, +{ + index: 10 + tag: 5 + val: test +}, +{ + index: 11 + tag: 5 + val: test +}, +{ + index: 12 + tag: 2 + val: 0 +}, +{ + index: 13 + tag: 2 + val: 0 +}, +------------------------------------ +slot &bytecodehar1/bytecodehar1-file2&2.0.0_2218 +{ + index: 0 + tag: 0 + val: 5 +}, +{ + index: 1 + tag: 5 + val: setValue +}, +{ + index: 2 + tag: 0 + val: 6 +}, +{ + index: 3 + tag: 6 + val: &bytecodehar1/bytecodehar1-file2&2.0.0.#~@0>#setValue +}, +{ + index: 4 + tag: 0 + val: 9 +}, +{ + index: 5 + tag: 9 + val: 1 +}, +{ + index: 6 + tag: 0 + val: 2 +}, +{ + index: 7 + tag: 2 + val: 1 +}, +------------------------------------ +slot &bytecodehar1/bytecodehar1-file2&2.0.0_2240 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&bytecodehar1/bytecodehar1-file2&2.0.0.#*#test"; "&bytecodehar1/bytecodehar1-file2&2.0.0.#~@0=#Example"; "&bytecodehar1/bytecodehar1-file2&2.0.0.#~A=#A"; "@normalized:N&&&sourcehar/sourcehar-file2&2.0.0"; "a"; "bytecodehar1.file2.test"; "print"; "prototype"; + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x3 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#*#test(any a0, any a1, any a2) { + tryldglobalbyname 0x0, print + sta v0 + lda.str bytecodehar2.file1.test + sta v1 + lda v0 + callarg1 0x1, v1 + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#~A=#A(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x4 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#*#test, 0x0 + stmodulevar 0x1 + ldhole + sta v0 + defineclasswithbuffer 0x1, &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#~A=#A, &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0_1649, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0_1601 +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0_1605 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 2 +}, +{ + index: 4 + tag: 5 + val: Anno1 +}, +{ + index: 5 + tag: 5 + val: Anno1 +}, +{ + index: 6 + tag: 5 + val: test +}, +{ + index: 7 + tag: 5 + val: test +}, +{ + index: 8 + tag: 2 + val: 0 +}, +{ + index: 9 + tag: 2 + val: 0 +}, +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0_1649 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#*#test"; "&@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#~A=#A"; "bytecodehar2.file1.test"; "print"; "prototype"; + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x3 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0.#*#test(any a0, any a1, any a2) { + tryldglobalbyname 0x0, print + sta v0 + lda.str bytecodehar2.file2.test + sta v1 + lda v0 + callarg1 0x1, v1 + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0.#~B=#B(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x4 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0.#*#test, 0x0 + stmodulevar 0x1 + ldhole + sta v0 + defineclasswithbuffer 0x1, &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0.#~B=#B, &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0_1706, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0_1658 +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0_1662 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 2 +}, +{ + index: 4 + tag: 5 + val: Anno2 +}, +{ + index: 5 + tag: 5 + val: Anno2 +}, +{ + index: 6 + tag: 5 + val: test +}, +{ + index: 7 + tag: 5 + val: test +}, +{ + index: 8 + tag: 2 + val: 0 +}, +{ + index: 9 + tag: 2 + val: 0 +}, +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0_1706 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&@ohos/bytecodehar2/bytecodehar2-file2&2.0.0.#*#test"; "&@ohos/bytecodehar2/bytecodehar2-file2&2.0.0.#~B=#B"; "bytecodehar2.file2.test"; "print"; "prototype"; + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x4 +.language ECMAScript +.function any &myapp/hap-file-exec&.#*#main(any a0, any a1, any a2) { +label_1: +label_0: + ldexternalmodulevar 0x2 + sta v0 + throw.undefinedifholewithname test + lda v0 + callarg0 0x0 + ldexternalmodulevar 0x1 + sta v0 + throw.undefinedifholewithname B + mov v1, v0 + newobjrange 0x2, 0x1, v1 + returnundefined +label_2: +} + +slotNum = 0x0 +.language ECMAScript +.function any &myapp/hap-file-exec&.#~C=#C(any a0, any a1, any a2) { +label_1: +label_0: + lda a2 + return +label_2: +} + +slotNum = 0x4 +.language ECMAScript +.function any &myapp/hap-file-exec&.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + definefunc 0x0, &myapp/hap-file-exec&.#*#main, 0x0 + ldhole + sta v0 + defineclasswithbuffer 0x1, &myapp/hap-file-exec&.#~C=#C, &myapp/hap-file-exec&_2, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &myapp/hap-file-exec&_0 +------------------------------------ +slot &myapp/hap-file-exec&_1 +{ + index: 0 + tag: 2 + val: 1 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&&&bytecodehar1/bytecodehar1-file1&2.0.0 +}, +{ + index: 2 + tag: 2 + val: 3 +}, +{ + index: 3 + tag: 5 + val: Anno1 +}, +{ + index: 4 + tag: 5 + val: Anno1 +}, +{ + index: 5 + tag: 9 + val: 0 +}, +{ + index: 6 + tag: 5 + val: B +}, +{ + index: 7 + tag: 5 + val: B +}, +{ + index: 8 + tag: 9 + val: 0 +}, +{ + index: 9 + tag: 5 + val: test +}, +{ + index: 10 + tag: 5 + val: test +}, +{ + index: 11 + tag: 9 + val: 0 +}, +{ + index: 12 + tag: 2 + val: 0 +}, +{ + index: 13 + tag: 2 + val: 0 +}, +{ + index: 14 + tag: 2 + val: 0 +}, +{ + index: 15 + tag: 2 + val: 0 +}, +------------------------------------ +slot &myapp/hap-file-exec&_2 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&myapp/hap-file-exec&.#*#main"; "&myapp/hap-file-exec&.#~C=#C"; "B"; "prototype"; "test"; +slotNum = 0x3 +.language ECMAScript +.function any &sourcehar/sourcehar-file1&2.0.0.#*#test(any a0, any a1, any a2) { +label_1: +label_0: + tryldglobalbyname 0x0, print + sta v0 + lda.str sourcehar.file1.test + sta v1 + lda v0 + callarg1 0x1, v1 + returnundefined +label_2: +} + +slotNum = 0x1 +.language ECMAScript +.function any &sourcehar/sourcehar-file1&2.0.0.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + definefunc 0x0, &sourcehar/sourcehar-file1&2.0.0.#*#test, 0x0 + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &sourcehar/sourcehar-file1&2.0.0_0 +------------------------------------ +slot &sourcehar/sourcehar-file1&2.0.0_1 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 1 +}, +{ + index: 4 + tag: 5 + val: test +}, +{ + index: 5 + tag: 5 + val: test +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +======> strings <====== +"&sourcehar/sourcehar-file1&2.0.0.#*#test"; "print"; "sourcehar.file1.test"; +slotNum = 0x3 +.language ECMAScript +.function any &sourcehar/sourcehar-file2&2.0.0.#*#test(any a0, any a1, any a2) { +label_1: +label_0: + tryldglobalbyname 0x0, print + sta v0 + lda.str sourcehar.file2.test + sta v1 + lda v0 + callarg1 0x1, v1 + returnundefined +label_2: +} + +slotNum = 0x1 +.language ECMAScript +.function any &sourcehar/sourcehar-file2&2.0.0.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + definefunc 0x0, &sourcehar/sourcehar-file2&2.0.0.#*#test, 0x0 + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &sourcehar/sourcehar-file2&2.0.0_0 +------------------------------------ +slot &sourcehar/sourcehar-file2&2.0.0_1 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 1 +}, +{ + index: 4 + tag: 5 + val: test +}, +{ + index: 5 + tag: 5 + val: test +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +======> strings <====== +"&sourcehar/sourcehar-file2&2.0.0.#*#test"; "print"; "sourcehar.file2.test"; +slotNum = 0x6 +expectedProperty = 0x3 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file1&2.0.0.#*#A(any a0, any a1, any a2, any a3) { + lda a3 + stobjbyname 0x0, a, a2 + ldai 0x1 + stobjbyname 0x2, b, a2 + ldai 0x2 + stobjbyname 0x4, c, a2 + returnundefined +} + +slotNum = 0x3 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file1&2.0.0.#*#test(any a0, any a1, any a2) { + tryldglobalbyname 0x0, print + sta v0 + lda.str bytecodehar1.file1.test + sta v1 + lda v0 + callarg1 0x1, v1 + lda.str @normalized:N&&&sourcehar/sourcehar-file1&2.0.0 + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file1&2.0.0.#~B=#B(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x5 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file1&2.0.0.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, &bytecodehar1/bytecodehar1-file1&2.0.0.#*#A, 0x1 + definefunc 0x1, &bytecodehar1/bytecodehar1-file1&2.0.0.#*#test, 0x0 + stmodulevar 0x1 + ldhole + sta v0 + defineclasswithbuffer 0x2, &bytecodehar1/bytecodehar1-file1&2.0.0.#~B=#B, &bytecodehar1/bytecodehar1-file1&2.0.0_2142, 0x0, v0 + ldobjbyname 0x3, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &bytecodehar1/bytecodehar1-file1&2.0.0_2080 +------------------------------------ +slot &bytecodehar1/bytecodehar1-file1&2.0.0_2084 +{ + index: 0 + tag: 2 + val: 1 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&&&@ohos/bytecodehar2/bytecodehar2-file1&2.0.0 +}, +{ + index: 2 + tag: 2 + val: 1 +}, +{ + index: 3 + tag: 5 + val: test1 +}, +{ + index: 4 + tag: 5 + val: test +}, +{ + index: 5 + tag: 9 + val: 0 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 2 +}, +{ + index: 8 + tag: 5 + val: Anno1 +}, +{ + index: 9 + tag: 5 + val: Anno1 +}, +{ + index: 10 + tag: 5 + val: test +}, +{ + index: 11 + tag: 5 + val: test +}, +{ + index: 12 + tag: 2 + val: 0 +}, +{ + index: 13 + tag: 2 + val: 0 +}, +------------------------------------ +slot &bytecodehar1/bytecodehar1-file1&2.0.0_2142 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&bytecodehar1/bytecodehar1-file1&2.0.0.#*#A"; "&bytecodehar1/bytecodehar1-file1&2.0.0.#*#test"; "&bytecodehar1/bytecodehar1-file1&2.0.0.#~B=#B"; "@normalized:N&&&sourcehar/sourcehar-file1&2.0.0"; "a"; "b"; "bytecodehar1.file1.test"; "c"; "print"; "prototype"; + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x3 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#*#test(any a0, any a1, any a2) { + tryldglobalbyname 0x0, print + sta v0 + lda.str bytecodehar2.file1.test + sta v1 + lda v0 + callarg1 0x1, v1 + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#~A=#A(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x4 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#*#test, 0x0 + stmodulevar 0x1 + ldhole + sta v0 + defineclasswithbuffer 0x1, &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#~A=#A, &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0_1649, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0_1601 +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0_1605 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 2 +}, +{ + index: 4 + tag: 5 + val: Anno1 +}, +{ + index: 5 + tag: 5 + val: Anno1 +}, +{ + index: 6 + tag: 5 + val: test +}, +{ + index: 7 + tag: 5 + val: test +}, +{ + index: 8 + tag: 2 + val: 0 +}, +{ + index: 9 + tag: 2 + val: 0 +}, +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0_1649 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#*#test"; "&@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#~A=#A"; "bytecodehar2.file1.test"; "print"; "prototype"; + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x4 +.language ECMAScript +.function any &myapp/hap-file-exec&.#*#main(any a0, any a1, any a2) { +label_1: +label_0: + ldexternalmodulevar 0x2 + sta v0 + throw.undefinedifholewithname test + lda v0 + callarg0 0x0 + ldexternalmodulevar 0x1 + sta v0 + throw.undefinedifholewithname B + mov v1, v0 + newobjrange 0x2, 0x1, v1 + returnundefined +label_2: +} + +slotNum = 0x0 +.language ECMAScript +.function any &myapp/hap-file-exec&.#~C=#C(any a0, any a1, any a2) { +label_1: +label_0: + lda a2 + return +label_2: +} + +slotNum = 0x4 +.language ECMAScript +.function any &myapp/hap-file-exec&.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + definefunc 0x0, &myapp/hap-file-exec&.#*#main, 0x0 + ldhole + sta v0 + defineclasswithbuffer 0x1, &myapp/hap-file-exec&.#~C=#C, &myapp/hap-file-exec&_2, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &myapp/hap-file-exec&_0 +------------------------------------ +slot &myapp/hap-file-exec&_1 +{ + index: 0 + tag: 2 + val: 1 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&&&bytecodehar1/bytecodehar1-file1&2.0.0 +}, +{ + index: 2 + tag: 2 + val: 3 +}, +{ + index: 3 + tag: 5 + val: Anno1 +}, +{ + index: 4 + tag: 5 + val: Anno1 +}, +{ + index: 5 + tag: 9 + val: 0 +}, +{ + index: 6 + tag: 5 + val: B +}, +{ + index: 7 + tag: 5 + val: B +}, +{ + index: 8 + tag: 9 + val: 0 +}, +{ + index: 9 + tag: 5 + val: test +}, +{ + index: 10 + tag: 5 + val: test +}, +{ + index: 11 + tag: 9 + val: 0 +}, +{ + index: 12 + tag: 2 + val: 0 +}, +{ + index: 13 + tag: 2 + val: 0 +}, +{ + index: 14 + tag: 2 + val: 0 +}, +{ + index: 15 + tag: 2 + val: 0 +}, +------------------------------------ +slot &myapp/hap-file-exec&_2 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&myapp/hap-file-exec&.#*#main"; "&myapp/hap-file-exec&.#~C=#C"; "B"; "prototype"; "test"; +slotNum = 0x3 +.language ECMAScript +.function any &sourcehar/sourcehar-file1&2.0.0.#*#test(any a0, any a1, any a2) { +label_1: +label_0: + tryldglobalbyname 0x0, print + sta v0 + lda.str sourcehar.file1.test + sta v1 + lda v0 + callarg1 0x1, v1 + returnundefined +label_2: +} + +slotNum = 0x1 +.language ECMAScript +.function any &sourcehar/sourcehar-file1&2.0.0.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + definefunc 0x0, &sourcehar/sourcehar-file1&2.0.0.#*#test, 0x0 + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &sourcehar/sourcehar-file1&2.0.0_0 +------------------------------------ +slot &sourcehar/sourcehar-file1&2.0.0_1 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 1 +}, +{ + index: 4 + tag: 5 + val: test +}, +{ + index: 5 + tag: 5 + val: test +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +======> strings <====== +"&sourcehar/sourcehar-file1&2.0.0.#*#test"; "print"; "sourcehar.file1.test"; diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/hap-file-exec.ts b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/hap-file-exec.ts new file mode 100644 index 0000000000..dfb9dcabd3 --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/hap-file-exec.ts @@ -0,0 +1,24 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { test, __$$ETS_ANNOTATION$$__Anno1, B } from "@normalized:N&&&bytecodehar1/bytecodehar1-file1&2.0.0" + +function main() { + test(); + let a = new B(); +} + +@__$$ETS_ANNOTATION$$__Anno1({ b: true }) +class C { } diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/recordnames.txt b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/recordnames.txt new file mode 100644 index 0000000000..70074eddf7 --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/recordnames.txt @@ -0,0 +1,7 @@ +bytecodehar1-file1:&bytecodehar1/bytecodehar1-file1&2.0.0 +bytecodehar1-file2:&bytecodehar1/bytecodehar1-file2&2.0.0 +bytecodehar2-file1:&@ohos/bytecodehar2/bytecodehar2-file1&2.0.0 +bytecodehar2-file2:&@ohos/bytecodehar2/bytecodehar2-file2&2.0.0 +sourcehar-file1:&sourcehar/sourcehar-file1&2.0.0 +sourcehar-file2:&sourcehar/sourcehar-file2&2.0.0 +hap-file-exec:&myapp/hap-file-exec& diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/sourcehar-file1.ts b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/sourcehar-file1.ts new file mode 100644 index 0000000000..e9215bd1f3 --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/sourcehar-file1.ts @@ -0,0 +1,18 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export function test() { + print('sourcehar.file1.test'); +} \ No newline at end of file diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/sourcehar-file2.ts b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/sourcehar-file2.ts new file mode 100644 index 0000000000..7702af0778 --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-test-project/sourcehar-file2.ts @@ -0,0 +1,18 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export function test() { + print('sourcehar.file2.test'); +} \ No newline at end of file diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/abcinputs/bytecodehar.txt b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/abcinputs/bytecodehar.txt new file mode 100644 index 0000000000..2bed2a047f --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/abcinputs/bytecodehar.txt @@ -0,0 +1,2 @@ +bytecodehar-dynamic-import.ts +bytecodehar-static-import.ts diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/bytecodehar-dynamic-import.ts b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/bytecodehar-dynamic-import.ts new file mode 100644 index 0000000000..773f5fa662 --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/bytecodehar-dynamic-import.ts @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export let test: string = "test"; + +function testReplacementWoAt() { + import("@normalized:N&module&bundle&lib/importfile1&1.0.0"); + import("@normalized:N&module&bundle&lib/importfile1&"); + import("@normalized:N&&bundle&lib/importfile1&1.0.0"); + import("@normalized:N&&bundle&lib/importfile1&"); + + // No-effect since no version info in compileContextInfo.json + import("@normalized:N&&&lib2/importfile3&"); +} + +function testReplacementWithAt() { + import("@normalized:N&module&&@ohos/lib/importfile2&1.0.0"); + import("@normalized:N&module&&@ohos/lib/importfile2&"); + import("@normalized:N&&&@ohos/lib/importfile2&1.0.0"); + import("@normalized:N&&&@ohos/lib/importfile2&"); + + // No-effect since no version info in compileContextInfo.json + import("@normalized:N&&&@ohos/lib2/importfile4&"); +} + +function testNonOhmurl() { + import("aaa"); +} + +function testNonConst() { + // Take effect only under release due to bcopt + let a = "@normalized:N&&bundle&lib/importfile1&" + import(a); + + a = "@normalized:N&&bundle&lib/importfile1&"; + let b = "@normalized:N&&bundle&lib/importfile1&"; + import(a); + + a = "@normalized:N&&bundle&lib/importfile1&"; + "@normalized:N&&bundle&lib/importfile1&"; + import(a); +} + +export @interface __$$ETS_ANNOTATION$$__Anno1 { + b: boolean = true +} + +@__$$ETS_ANNOTATION$$__Anno1() +class A { } \ No newline at end of file diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/bytecodehar-static-import.ts b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/bytecodehar-static-import.ts new file mode 100644 index 0000000000..730ef99951 --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/bytecodehar-static-import.ts @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// testReplacementWoAt +import * as a from "@normalized:N&module&bundle&lib/importfile1&1.0.0"; +import * as b from "@normalized:N&module&bundle&lib/importfile1&"; +import * as c from "@normalized:N&&bundle&lib/importfile1&1.0.0"; +import * as d from "@normalized:N&&bundle&lib/importfile1&"; + +// No-effect since no version info in compileContextInfo.json +import * as e from "@normalized:N&&&lib2/importfile3&"; + +//testReplacementWithAt +import * as f from "@normalized:N&module&&@ohos/lib/importfile2&1.0.0"; +import * as g from "@normalized:N&module&&@ohos/lib/importfile2&"; +import * as h from "@normalized:N&&&@ohos/lib/importfile2&1.0.0"; +import * as i from "@normalized:N&&&@ohos/lib/importfile2&"; + +// No-effect since no version info in compileContextInfo.json +import * as j from "@normalized:N&&&@ohos/lib2/importfile4&"; + +function foo() { + print([a, b, c, d, e, f, g, h, i, j]); +} + +export @interface __$$ETS_ANNOTATION$$__Anno2 { + b: boolean = true +} + +@__$$ETS_ANNOTATION$$__Anno2() +class A { } \ No newline at end of file diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/compileContextInfo.json b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/compileContextInfo.json new file mode 100644 index 0000000000..be6b280850 --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/compileContextInfo.json @@ -0,0 +1,53 @@ +{ + "compileEntries": [ + "&myapp/hap-file-exec&" + ], + "hspPkgNames": [], + "pkgContextInfo": { + "myapp": { + "packageName": "myapp", + "bundleName": "", + "moduleName": "", + "version": "", + "entryPath": "", + "isSo": false, + "dependencyAlias": "" + }, + "lib": { + "packageName": "lib", + "bundleName": "bundle", + "moduleName": "module", + "version": "2.0.0", + "entryPath": "", + "isSo": false, + "dependencyAlias": "" + }, + "@ohos/lib": { + "packageName": "@ohos/lib", + "bundleName": "", + "moduleName": "module", + "version": "2.0.0", + "entryPath": "", + "isSo": false, + "dependencyAlias": "" + }, + "lib2": { + "packageName": "lib2", + "bundleName": "", + "moduleName": "", + "version": "", + "entryPath": "", + "isSo": false, + "dependencyAlias": "" + }, + "@ohos/lib2": { + "packageName": "@ohos/lib2", + "bundleName": "", + "moduleName": "", + "version": "", + "entryPath": "", + "isSo": false, + "dependencyAlias": "" + } + } +} diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/hap-file-exec-expected.pa.txt b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/hap-file-exec-expected.pa.txt new file mode 100644 index 0000000000..951b2a1d14 --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/hap-file-exec-expected.pa.txt @@ -0,0 +1,1670 @@ +All Dependency Files: +program_file: bytecodehar-abcinput.abc +record_name: &bytecodehar/bytecodehar-dynamic-import& +program_file: bytecodehar-abcinput.abc +record_name: &bytecodehar/bytecodehar-static-import& +program_file: hap-file-exec.ts +record_name: &myapp/hap-file-exec& +program_file: importfile1.ts +record_name: bundle&lib/importfile1&2.0.0 +program_file: importfile2.ts +record_name: &@ohos/lib/importfile2&2.0.0 +program_file: importfile3.ts +record_name: &lib2/importfile3& +program_file: importfile4.ts +record_name: &@ohos/lib2/importfile4& + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar/bytecodehar-dynamic-import&.#*#testNonConst(any a0, any a1, any a2) { + lda.str @normalized:N&&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&&bundle&lib/importfile1&2.0.0 + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar/bytecodehar-dynamic-import&.#*#testNonOhmurl(any a0, any a1, any a2) { + lda.str aaa + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWithAt(any a0, any a1, any a2) { + lda.str @normalized:N&module&&@ohos/lib/importfile2&2.0.0 + dynamicimport + lda.str @normalized:N&module&&@ohos/lib/importfile2&2.0.0 + dynamicimport + lda.str @normalized:N&&&@ohos/lib/importfile2&2.0.0 + dynamicimport + lda.str @normalized:N&&&@ohos/lib/importfile2&2.0.0 + dynamicimport + lda.str @normalized:N&&&@ohos/lib2/importfile4& + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWoAt(any a0, any a1, any a2) { + lda.str @normalized:N&module&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&module&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&&&lib2/importfile3& + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar/bytecodehar-dynamic-import&.#~A=#A(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x7 +.language ECMAScript +.function any &bytecodehar/bytecodehar-dynamic-import&.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, &bytecodehar/bytecodehar-dynamic-import&.#*#testNonConst, 0x0 + definefunc 0x1, &bytecodehar/bytecodehar-dynamic-import&.#*#testNonOhmurl, 0x0 + definefunc 0x2, &bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWithAt, 0x0 + definefunc 0x3, &bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWoAt, 0x0 + lda.str test + stmodulevar 0x1 + ldhole + sta v0 + defineclasswithbuffer 0x4, &bytecodehar/bytecodehar-dynamic-import&.#~A=#A, &bytecodehar/bytecodehar-dynamic-import&_2498, 0x0, v0 + ldobjbyname 0x5, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &bytecodehar/bytecodehar-dynamic-import&_2450 +------------------------------------ +slot &bytecodehar/bytecodehar-dynamic-import&_2454 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 2 +}, +{ + index: 4 + tag: 5 + val: Anno1 +}, +{ + index: 5 + tag: 5 + val: Anno1 +}, +{ + index: 6 + tag: 5 + val: test +}, +{ + index: 7 + tag: 5 + val: test +}, +{ + index: 8 + tag: 2 + val: 0 +}, +{ + index: 9 + tag: 2 + val: 0 +}, +------------------------------------ +slot &bytecodehar/bytecodehar-dynamic-import&_2498 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&bytecodehar/bytecodehar-dynamic-import&.#*#testNonConst"; "&bytecodehar/bytecodehar-dynamic-import&.#*#testNonOhmurl"; "&bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWithAt"; "&bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWoAt"; "&bytecodehar/bytecodehar-dynamic-import&.#~A=#A"; "@normalized:N&&&@ohos/lib/importfile2&2.0.0"; "@normalized:N&&&@ohos/lib2/importfile4&"; "@normalized:N&&&lib2/importfile3&"; "@normalized:N&&bundle&lib/importfile1&2.0.0"; "@normalized:N&module&&@ohos/lib/importfile2&2.0.0"; "@normalized:N&module&bundle&lib/importfile1&2.0.0"; "aaa"; "prototype"; "test"; + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x18 +.language ECMAScript +.function any &bytecodehar/bytecodehar-static-import&.#*#foo(any a0, any a1, any a2) { + tryldglobalbyname 0x0, print + sta v0 + createemptyarray 0x1 + sta v1 + ldlexvar 0x0, 0x0 + sta v2 + throw.undefinedifholewithname a + lda v2 + stownbyindex 0x2, v1, 0x0 + ldlexvar 0x0, 0x1 + sta v2 + throw.undefinedifholewithname b + lda v2 + stownbyindex 0x4, v1, 0x1 + ldlexvar 0x0, 0x2 + sta v2 + throw.undefinedifholewithname c + lda v2 + stownbyindex 0x6, v1, 0x2 + ldlexvar 0x0, 0x3 + sta v2 + throw.undefinedifholewithname d + lda v2 + stownbyindex 0x8, v1, 0x3 + ldlexvar 0x0, 0x4 + sta v2 + throw.undefinedifholewithname e + lda v2 + stownbyindex 0xa, v1, 0x4 + ldlexvar 0x0, 0x5 + sta v2 + throw.undefinedifholewithname f + lda v2 + stownbyindex 0xc, v1, 0x5 + ldlexvar 0x0, 0x6 + sta v2 + throw.undefinedifholewithname g + lda v2 + stownbyindex 0xe, v1, 0x6 + ldlexvar 0x0, 0x7 + sta v2 + throw.undefinedifholewithname h + lda v2 + stownbyindex 0x10, v1, 0x7 + ldlexvar 0x0, 0x8 + sta v2 + throw.undefinedifholewithname i + lda v2 + stownbyindex 0x12, v1, 0x8 + ldlexvar 0x0, 0x9 + sta v2 + throw.undefinedifholewithname j + lda v2 + stownbyindex 0x14, v1, 0x9 + lda v0 + callarg1 0x16, v1 + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar/bytecodehar-static-import&.#~A=#A(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x4 +.language ECMAScript +.function any &bytecodehar/bytecodehar-static-import&.func_main_0(any a0, any a1, any a2) { + newlexenv 0xa + definefunc 0x0, &bytecodehar/bytecodehar-static-import&.#*#foo, 0x0 + getmodulenamespace 0x0 + stlexvar 0x0, 0x0 + getmodulenamespace 0x1 + stlexvar 0x0, 0x1 + getmodulenamespace 0x2 + stlexvar 0x0, 0x2 + getmodulenamespace 0x3 + stlexvar 0x0, 0x3 + getmodulenamespace 0x4 + stlexvar 0x0, 0x4 + getmodulenamespace 0x5 + stlexvar 0x0, 0x5 + getmodulenamespace 0x6 + stlexvar 0x0, 0x6 + getmodulenamespace 0x7 + stlexvar 0x0, 0x7 + getmodulenamespace 0x8 + stlexvar 0x0, 0x8 + getmodulenamespace 0x9 + stlexvar 0x0, 0x9 + ldhole + sta v0 + defineclasswithbuffer 0x1, &bytecodehar/bytecodehar-static-import&.#~A=#A, &bytecodehar/bytecodehar-static-import&_2647, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &bytecodehar/bytecodehar-static-import&_2507 +------------------------------------ +slot &bytecodehar/bytecodehar-static-import&_2511 +{ + index: 0 + tag: 2 + val: 10 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&module&bundle&lib/importfile1&2.0.0 +}, +{ + index: 2 + tag: 5 + val: @normalized:N&module&bundle&lib/importfile1&2.0.0 +}, +{ + index: 3 + tag: 5 + val: @normalized:N&&bundle&lib/importfile1&2.0.0 +}, +{ + index: 4 + tag: 5 + val: @normalized:N&&bundle&lib/importfile1&2.0.0 +}, +{ + index: 5 + tag: 5 + val: @normalized:N&&&lib2/importfile3& +}, +{ + index: 6 + tag: 5 + val: @normalized:N&module&&@ohos/lib/importfile2&2.0.0 +}, +{ + index: 7 + tag: 5 + val: @normalized:N&module&&@ohos/lib/importfile2&2.0.0 +}, +{ + index: 8 + tag: 5 + val: @normalized:N&&&@ohos/lib/importfile2&2.0.0 +}, +{ + index: 9 + tag: 5 + val: @normalized:N&&&@ohos/lib/importfile2&2.0.0 +}, +{ + index: 10 + tag: 5 + val: @normalized:N&&&@ohos/lib2/importfile4& +}, +{ + index: 11 + tag: 2 + val: 0 +}, +{ + index: 12 + tag: 2 + val: 10 +}, +{ + index: 13 + tag: 5 + val: a +}, +{ + index: 14 + tag: 9 + val: 0 +}, +{ + index: 15 + tag: 5 + val: b +}, +{ + index: 16 + tag: 9 + val: 1 +}, +{ + index: 17 + tag: 5 + val: c +}, +{ + index: 18 + tag: 9 + val: 2 +}, +{ + index: 19 + tag: 5 + val: d +}, +{ + index: 20 + tag: 9 + val: 3 +}, +{ + index: 21 + tag: 5 + val: e +}, +{ + index: 22 + tag: 9 + val: 4 +}, +{ + index: 23 + tag: 5 + val: f +}, +{ + index: 24 + tag: 9 + val: 5 +}, +{ + index: 25 + tag: 5 + val: g +}, +{ + index: 26 + tag: 9 + val: 6 +}, +{ + index: 27 + tag: 5 + val: h +}, +{ + index: 28 + tag: 9 + val: 7 +}, +{ + index: 29 + tag: 5 + val: i +}, +{ + index: 30 + tag: 9 + val: 8 +}, +{ + index: 31 + tag: 5 + val: j +}, +{ + index: 32 + tag: 9 + val: 9 +}, +{ + index: 33 + tag: 2 + val: 1 +}, +{ + index: 34 + tag: 5 + val: Anno2 +}, +{ + index: 35 + tag: 5 + val: Anno2 +}, +{ + index: 36 + tag: 2 + val: 0 +}, +{ + index: 37 + tag: 2 + val: 0 +}, +------------------------------------ +slot &bytecodehar/bytecodehar-static-import&_2647 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&bytecodehar/bytecodehar-static-import&.#*#foo"; "&bytecodehar/bytecodehar-static-import&.#~A=#A"; "a"; "b"; "c"; "d"; "e"; "f"; "g"; "h"; "i"; "j"; "print"; "prototype"; + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x0 +.language ECMAScript +.function any &myapp/hap-file-exec&.#~A=#A(any a0, any a1, any a2) { +label_1: +label_0: + lda a2 + return +label_2: +} + +slotNum = 0xd +.language ECMAScript +.function any &myapp/hap-file-exec&.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + getmodulenamespace 0x0 + sta v0 + getmodulenamespace 0x1 + sta v1 + tryldglobalbyname 0x0, print + sta v2 + lda v0 + ldobjbyname 0x1, test + sta v0 + lda v2 + callarg1 0x3, v0 + tryldglobalbyname 0x5, print + sta v0 + lda v1 + ldobjbyname 0x6, test + sta v1 + lda v0 + callarg1 0x8, v1 + ldhole + sta v0 + defineclasswithbuffer 0xa, &myapp/hap-file-exec&.#~A=#A, &myapp/hap-file-exec&_2, 0x0, v0 + ldobjbyname 0xb, prototype + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &myapp/hap-file-exec&_0 +------------------------------------ +slot &myapp/hap-file-exec&_1 +{ + index: 0 + tag: 2 + val: 2 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&&&bytecodehar/bytecodehar-dynamic-import& +}, +{ + index: 2 + tag: 5 + val: @normalized:N&&&bytecodehar/bytecodehar-static-import& +}, +{ + index: 3 + tag: 2 + val: 0 +}, +{ + index: 4 + tag: 2 + val: 2 +}, +{ + index: 5 + tag: 5 + val: bytecodeharDynamicImport +}, +{ + index: 6 + tag: 9 + val: 0 +}, +{ + index: 7 + tag: 5 + val: bytecodeharStaticImport +}, +{ + index: 8 + tag: 9 + val: 1 +}, +{ + index: 9 + tag: 2 + val: 0 +}, +{ + index: 10 + tag: 2 + val: 0 +}, +{ + index: 11 + tag: 2 + val: 0 +}, +------------------------------------ +slot &myapp/hap-file-exec&_2 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&myapp/hap-file-exec&.#~A=#A"; "print"; "prototype"; "test"; +slotNum = 0x0 +.language ECMAScript +.function any bundle&lib/importfile1&2.0.0.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + ldtrue + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot bundle&lib/importfile1&2.0.0_0 +------------------------------------ +slot bundle&lib/importfile1&2.0.0_1 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 1 +}, +{ + index: 4 + tag: 5 + val: test1 +}, +{ + index: 5 + tag: 5 + val: test1 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +======> strings <====== + +slotNum = 0x0 +.language ECMAScript +.function any &@ohos/lib/importfile2&2.0.0.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + ldtrue + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &@ohos/lib/importfile2&2.0.0_0 +------------------------------------ +slot &@ohos/lib/importfile2&2.0.0_1 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 1 +}, +{ + index: 4 + tag: 5 + val: test2 +}, +{ + index: 5 + tag: 5 + val: test2 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +======> strings <====== + +slotNum = 0x0 +.language ECMAScript +.function any &lib2/importfile3&.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + ldtrue + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &lib2/importfile3&_0 +------------------------------------ +slot &lib2/importfile3&_1 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 1 +}, +{ + index: 4 + tag: 5 + val: test3 +}, +{ + index: 5 + tag: 5 + val: test3 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +======> strings <====== + +slotNum = 0x0 +.language ECMAScript +.function any &@ohos/lib2/importfile4&.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + ldtrue + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &@ohos/lib2/importfile4&_0 +------------------------------------ +slot &@ohos/lib2/importfile4&_1 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 1 +}, +{ + index: 4 + tag: 5 + val: test4 +}, +{ + index: 5 + tag: 5 + val: test4 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +======> strings <====== + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar/bytecodehar-dynamic-import&.#*#testNonConst(any a0, any a1, any a2) { + lda.str @normalized:N&&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&&bundle&lib/importfile1&2.0.0 + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar/bytecodehar-dynamic-import&.#*#testNonOhmurl(any a0, any a1, any a2) { + lda.str aaa + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWithAt(any a0, any a1, any a2) { + lda.str @normalized:N&module&&@ohos/lib/importfile2&2.0.0 + dynamicimport + lda.str @normalized:N&module&&@ohos/lib/importfile2&2.0.0 + dynamicimport + lda.str @normalized:N&&&@ohos/lib/importfile2&2.0.0 + dynamicimport + lda.str @normalized:N&&&@ohos/lib/importfile2&2.0.0 + dynamicimport + lda.str @normalized:N&&&@ohos/lib2/importfile4& + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWoAt(any a0, any a1, any a2) { + lda.str @normalized:N&module&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&module&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&&bundle&lib/importfile1&2.0.0 + dynamicimport + lda.str @normalized:N&&&lib2/importfile3& + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar/bytecodehar-dynamic-import&.#~A=#A(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x7 +.language ECMAScript +.function any &bytecodehar/bytecodehar-dynamic-import&.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, &bytecodehar/bytecodehar-dynamic-import&.#*#testNonConst, 0x0 + definefunc 0x1, &bytecodehar/bytecodehar-dynamic-import&.#*#testNonOhmurl, 0x0 + definefunc 0x2, &bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWithAt, 0x0 + definefunc 0x3, &bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWoAt, 0x0 + lda.str test + stmodulevar 0x1 + ldhole + sta v0 + defineclasswithbuffer 0x4, &bytecodehar/bytecodehar-dynamic-import&.#~A=#A, &bytecodehar/bytecodehar-dynamic-import&_2498, 0x0, v0 + ldobjbyname 0x5, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &bytecodehar/bytecodehar-dynamic-import&_2450 +------------------------------------ +slot &bytecodehar/bytecodehar-dynamic-import&_2454 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 2 +}, +{ + index: 4 + tag: 5 + val: Anno1 +}, +{ + index: 5 + tag: 5 + val: Anno1 +}, +{ + index: 6 + tag: 5 + val: test +}, +{ + index: 7 + tag: 5 + val: test +}, +{ + index: 8 + tag: 2 + val: 0 +}, +{ + index: 9 + tag: 2 + val: 0 +}, +------------------------------------ +slot &bytecodehar/bytecodehar-dynamic-import&_2498 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&bytecodehar/bytecodehar-dynamic-import&.#*#testNonConst"; "&bytecodehar/bytecodehar-dynamic-import&.#*#testNonOhmurl"; "&bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWithAt"; "&bytecodehar/bytecodehar-dynamic-import&.#*#testReplacementWoAt"; "&bytecodehar/bytecodehar-dynamic-import&.#~A=#A"; "@normalized:N&&&@ohos/lib/importfile2&2.0.0"; "@normalized:N&&&@ohos/lib2/importfile4&"; "@normalized:N&&&lib2/importfile3&"; "@normalized:N&&bundle&lib/importfile1&2.0.0"; "@normalized:N&module&&@ohos/lib/importfile2&2.0.0"; "@normalized:N&module&bundle&lib/importfile1&2.0.0"; "aaa"; "prototype"; "test"; + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x18 +.language ECMAScript +.function any &bytecodehar/bytecodehar-static-import&.#*#foo(any a0, any a1, any a2) { + tryldglobalbyname 0x0, print + sta v0 + createemptyarray 0x1 + sta v1 + ldlexvar 0x0, 0x0 + sta v2 + throw.undefinedifholewithname a + lda v2 + stownbyindex 0x2, v1, 0x0 + ldlexvar 0x0, 0x1 + sta v2 + throw.undefinedifholewithname b + lda v2 + stownbyindex 0x4, v1, 0x1 + ldlexvar 0x0, 0x2 + sta v2 + throw.undefinedifholewithname c + lda v2 + stownbyindex 0x6, v1, 0x2 + ldlexvar 0x0, 0x3 + sta v2 + throw.undefinedifholewithname d + lda v2 + stownbyindex 0x8, v1, 0x3 + ldlexvar 0x0, 0x4 + sta v2 + throw.undefinedifholewithname e + lda v2 + stownbyindex 0xa, v1, 0x4 + ldlexvar 0x0, 0x5 + sta v2 + throw.undefinedifholewithname f + lda v2 + stownbyindex 0xc, v1, 0x5 + ldlexvar 0x0, 0x6 + sta v2 + throw.undefinedifholewithname g + lda v2 + stownbyindex 0xe, v1, 0x6 + ldlexvar 0x0, 0x7 + sta v2 + throw.undefinedifholewithname h + lda v2 + stownbyindex 0x10, v1, 0x7 + ldlexvar 0x0, 0x8 + sta v2 + throw.undefinedifholewithname i + lda v2 + stownbyindex 0x12, v1, 0x8 + ldlexvar 0x0, 0x9 + sta v2 + throw.undefinedifholewithname j + lda v2 + stownbyindex 0x14, v1, 0x9 + lda v0 + callarg1 0x16, v1 + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar/bytecodehar-static-import&.#~A=#A(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x4 +.language ECMAScript +.function any &bytecodehar/bytecodehar-static-import&.func_main_0(any a0, any a1, any a2) { + newlexenv 0xa + definefunc 0x0, &bytecodehar/bytecodehar-static-import&.#*#foo, 0x0 + getmodulenamespace 0x0 + stlexvar 0x0, 0x0 + getmodulenamespace 0x1 + stlexvar 0x0, 0x1 + getmodulenamespace 0x2 + stlexvar 0x0, 0x2 + getmodulenamespace 0x3 + stlexvar 0x0, 0x3 + getmodulenamespace 0x4 + stlexvar 0x0, 0x4 + getmodulenamespace 0x5 + stlexvar 0x0, 0x5 + getmodulenamespace 0x6 + stlexvar 0x0, 0x6 + getmodulenamespace 0x7 + stlexvar 0x0, 0x7 + getmodulenamespace 0x8 + stlexvar 0x0, 0x8 + getmodulenamespace 0x9 + stlexvar 0x0, 0x9 + ldhole + sta v0 + defineclasswithbuffer 0x1, &bytecodehar/bytecodehar-static-import&.#~A=#A, &bytecodehar/bytecodehar-static-import&_2647, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &bytecodehar/bytecodehar-static-import&_2507 +------------------------------------ +slot &bytecodehar/bytecodehar-static-import&_2511 +{ + index: 0 + tag: 2 + val: 10 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&module&bundle&lib/importfile1&2.0.0 +}, +{ + index: 2 + tag: 5 + val: @normalized:N&module&bundle&lib/importfile1&2.0.0 +}, +{ + index: 3 + tag: 5 + val: @normalized:N&&bundle&lib/importfile1&2.0.0 +}, +{ + index: 4 + tag: 5 + val: @normalized:N&&bundle&lib/importfile1&2.0.0 +}, +{ + index: 5 + tag: 5 + val: @normalized:N&&&lib2/importfile3& +}, +{ + index: 6 + tag: 5 + val: @normalized:N&module&&@ohos/lib/importfile2&2.0.0 +}, +{ + index: 7 + tag: 5 + val: @normalized:N&module&&@ohos/lib/importfile2&2.0.0 +}, +{ + index: 8 + tag: 5 + val: @normalized:N&&&@ohos/lib/importfile2&2.0.0 +}, +{ + index: 9 + tag: 5 + val: @normalized:N&&&@ohos/lib/importfile2&2.0.0 +}, +{ + index: 10 + tag: 5 + val: @normalized:N&&&@ohos/lib2/importfile4& +}, +{ + index: 11 + tag: 2 + val: 0 +}, +{ + index: 12 + tag: 2 + val: 10 +}, +{ + index: 13 + tag: 5 + val: a +}, +{ + index: 14 + tag: 9 + val: 0 +}, +{ + index: 15 + tag: 5 + val: b +}, +{ + index: 16 + tag: 9 + val: 1 +}, +{ + index: 17 + tag: 5 + val: c +}, +{ + index: 18 + tag: 9 + val: 2 +}, +{ + index: 19 + tag: 5 + val: d +}, +{ + index: 20 + tag: 9 + val: 3 +}, +{ + index: 21 + tag: 5 + val: e +}, +{ + index: 22 + tag: 9 + val: 4 +}, +{ + index: 23 + tag: 5 + val: f +}, +{ + index: 24 + tag: 9 + val: 5 +}, +{ + index: 25 + tag: 5 + val: g +}, +{ + index: 26 + tag: 9 + val: 6 +}, +{ + index: 27 + tag: 5 + val: h +}, +{ + index: 28 + tag: 9 + val: 7 +}, +{ + index: 29 + tag: 5 + val: i +}, +{ + index: 30 + tag: 9 + val: 8 +}, +{ + index: 31 + tag: 5 + val: j +}, +{ + index: 32 + tag: 9 + val: 9 +}, +{ + index: 33 + tag: 2 + val: 1 +}, +{ + index: 34 + tag: 5 + val: Anno2 +}, +{ + index: 35 + tag: 5 + val: Anno2 +}, +{ + index: 36 + tag: 2 + val: 0 +}, +{ + index: 37 + tag: 2 + val: 0 +}, +------------------------------------ +slot &bytecodehar/bytecodehar-static-import&_2647 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&bytecodehar/bytecodehar-static-import&.#*#foo"; "&bytecodehar/bytecodehar-static-import&.#~A=#A"; "a"; "b"; "c"; "d"; "e"; "f"; "g"; "h"; "i"; "j"; "print"; "prototype"; + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x0 +.language ECMAScript +.function any &myapp/hap-file-exec&.#~A=#A(any a0, any a1, any a2) { +label_1: +label_0: + lda a2 + return +label_2: +} + +slotNum = 0xd +.language ECMAScript +.function any &myapp/hap-file-exec&.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + getmodulenamespace 0x0 + sta v0 + getmodulenamespace 0x1 + sta v1 + tryldglobalbyname 0x0, print + sta v2 + lda v0 + ldobjbyname 0x1, test + sta v0 + lda v2 + callarg1 0x3, v0 + tryldglobalbyname 0x5, print + sta v0 + lda v1 + ldobjbyname 0x6, test + sta v1 + lda v0 + callarg1 0x8, v1 + ldhole + sta v0 + defineclasswithbuffer 0xa, &myapp/hap-file-exec&.#~A=#A, &myapp/hap-file-exec&_2, 0x0, v0 + ldobjbyname 0xb, prototype + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &myapp/hap-file-exec&_0 +------------------------------------ +slot &myapp/hap-file-exec&_1 +{ + index: 0 + tag: 2 + val: 2 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&&&bytecodehar/bytecodehar-dynamic-import& +}, +{ + index: 2 + tag: 5 + val: @normalized:N&&&bytecodehar/bytecodehar-static-import& +}, +{ + index: 3 + tag: 2 + val: 0 +}, +{ + index: 4 + tag: 2 + val: 2 +}, +{ + index: 5 + tag: 5 + val: bytecodeharDynamicImport +}, +{ + index: 6 + tag: 9 + val: 0 +}, +{ + index: 7 + tag: 5 + val: bytecodeharStaticImport +}, +{ + index: 8 + tag: 9 + val: 1 +}, +{ + index: 9 + tag: 2 + val: 0 +}, +{ + index: 10 + tag: 2 + val: 0 +}, +{ + index: 11 + tag: 2 + val: 0 +}, +------------------------------------ +slot &myapp/hap-file-exec&_2 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&myapp/hap-file-exec&.#~A=#A"; "print"; "prototype"; "test"; +slotNum = 0x0 +.language ECMAScript +.function any bundle&lib/importfile1&2.0.0.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + ldtrue + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot bundle&lib/importfile1&2.0.0_0 +------------------------------------ +slot bundle&lib/importfile1&2.0.0_1 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 1 +}, +{ + index: 4 + tag: 5 + val: test1 +}, +{ + index: 5 + tag: 5 + val: test1 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +======> strings <====== + +slotNum = 0x0 +.language ECMAScript +.function any &@ohos/lib/importfile2&2.0.0.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + ldtrue + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &@ohos/lib/importfile2&2.0.0_0 +------------------------------------ +slot &@ohos/lib/importfile2&2.0.0_1 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 1 +}, +{ + index: 4 + tag: 5 + val: test2 +}, +{ + index: 5 + tag: 5 + val: test2 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +======> strings <====== + +slotNum = 0x0 +.language ECMAScript +.function any &lib2/importfile3&.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + ldtrue + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &lib2/importfile3&_0 +------------------------------------ +slot &lib2/importfile3&_1 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 1 +}, +{ + index: 4 + tag: 5 + val: test3 +}, +{ + index: 5 + tag: 5 + val: test3 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +======> strings <====== + +slotNum = 0x0 +.language ECMAScript +.function any &@ohos/lib2/importfile4&.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + ldtrue + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &@ohos/lib2/importfile4&_0 +------------------------------------ +slot &@ohos/lib2/importfile4&_1 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 1 +}, +{ + index: 4 + tag: 5 + val: test4 +}, +{ + index: 5 + tag: 5 + val: test4 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +======> strings <====== + diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/hap-file-exec.ts b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/hap-file-exec.ts new file mode 100644 index 0000000000..572bc4616e --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/hap-file-exec.ts @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as bytecodeharDynamicImport from "@normalized:N&&&bytecodehar/bytecodehar-dynamic-import&"; +import * as bytecodeharStaticImport from "@normalized:N&&&bytecodehar/bytecodehar-static-import&"; + +print(bytecodeharDynamicImport.test) +print(bytecodeharStaticImport.test) + +@bytecodeharDynamicImport.__$$ETS_ANNOTATION$$__Anno1() +@bytecodeharStaticImport.__$$ETS_ANNOTATION$$__Anno2() +class A { } \ No newline at end of file diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/importfile1.ts b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/importfile1.ts new file mode 100644 index 0000000000..afc68146cd --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/importfile1.ts @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const test1: boolean = true; \ No newline at end of file diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/importfile2.ts b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/importfile2.ts new file mode 100644 index 0000000000..f31867bafa --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/importfile2.ts @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const test2: boolean = true; \ No newline at end of file diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/importfile3.ts b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/importfile3.ts new file mode 100644 index 0000000000..314b5403fc --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/importfile3.ts @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const test3: boolean = true; \ No newline at end of file diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/importfile4.ts b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/importfile4.ts new file mode 100644 index 0000000000..fad2380a35 --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/importfile4.ts @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const test4: boolean = true; \ No newline at end of file diff --git a/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/recordnames.txt b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/recordnames.txt new file mode 100644 index 0000000000..185dca6111 --- /dev/null +++ b/es2panda/test/compiler/bytecodehar/projects/bytecodehar-annotations-version-update/recordnames.txt @@ -0,0 +1,7 @@ +bytecodehar-dynamic-import:&bytecodehar/bytecodehar-dynamic-import& +bytecodehar-static-import:&bytecodehar/bytecodehar-static-import& +importfile1:bundle&lib/importfile1&2.0.0 +importfile2:&@ohos/lib/importfile2&2.0.0 +importfile3:&lib2/importfile3& +importfile4:&@ohos/lib2/importfile4& +hap-file-exec:&myapp/hap-file-exec& diff --git a/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/abcinputs/bytecodehar1.txt b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/abcinputs/bytecodehar1.txt new file mode 100644 index 0000000000..44fef6254c --- /dev/null +++ b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/abcinputs/bytecodehar1.txt @@ -0,0 +1,2 @@ +bytecodehar1-file1.ts +bytecodehar1-file2.ts diff --git a/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/abcinputs/bytecodehar2.txt b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/abcinputs/bytecodehar2.txt new file mode 100644 index 0000000000..01249cd0af --- /dev/null +++ b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/abcinputs/bytecodehar2.txt @@ -0,0 +1,2 @@ +bytecodehar2-file1.ts +bytecodehar2-file2.ts diff --git a/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/bytecodehar1-file1.ts b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/bytecodehar1-file1.ts new file mode 100644 index 0000000000..7478e00482 --- /dev/null +++ b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/bytecodehar1-file1.ts @@ -0,0 +1,28 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {test as test1} from '@normalized:N&&&@ohos/bytecodehar2/bytecodehar2-file1&2.0.0' + +export function test() { + print('bytecodehar1.file1.test'); + import('@normalized:N&&&sourcehar/sourcehar-file1&2.0.0') +} + +export @interface __$$ETS_ANNOTATION$$__Anno1 { + b: boolean = true +} + +@__$$ETS_ANNOTATION$$__Anno1() +class A { } \ No newline at end of file diff --git a/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/bytecodehar1-file2.ts b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/bytecodehar1-file2.ts new file mode 100644 index 0000000000..5962b22672 --- /dev/null +++ b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/bytecodehar1-file2.ts @@ -0,0 +1,28 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {test as test1} from "@normalized:N&&&@ohos/bytecodehar2/bytecodehar2-file2&1.0.0" + +export function test() { + print('bytecodehar1.file2.test'); + import("@normalized:N&&&sourcehar/sourcehar-file2&2.0.0") +} + +export @interface __$$ETS_ANNOTATION$$__Anno2 { + b: boolean = true +} + +@__$$ETS_ANNOTATION$$__Anno2() +class A { } \ No newline at end of file diff --git a/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/bytecodehar2-file1.ts b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/bytecodehar2-file1.ts new file mode 100644 index 0000000000..fc82d9af73 --- /dev/null +++ b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/bytecodehar2-file1.ts @@ -0,0 +1,25 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export function test() { + print('bytecodehar2.file1.test'); +} + +export @interface __$$ETS_ANNOTATION$$__Anno1 { + b: boolean = true +} + +@__$$ETS_ANNOTATION$$__Anno1() +class A { } \ No newline at end of file diff --git a/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/bytecodehar2-file2.ts b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/bytecodehar2-file2.ts new file mode 100644 index 0000000000..3716361621 --- /dev/null +++ b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/bytecodehar2-file2.ts @@ -0,0 +1,25 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export function test() { + print('bytecodehar2.file2.test'); +} + +export @interface __$$ETS_ANNOTATION$$__Anno2 { + b: boolean = true +} + +@__$$ETS_ANNOTATION$$__Anno2() +class A { } \ No newline at end of file diff --git a/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/compileContextInfo.json b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/compileContextInfo.json new file mode 100644 index 0000000000..43eafd903d --- /dev/null +++ b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/compileContextInfo.json @@ -0,0 +1,13 @@ +{ + "compileEntries": [ + "&myapp/hap-file-exec&" + ], + "hspPkgNames": [], + "updateVersionInfo": { + "bytecodehar1": { + "@ohos/bytecodehar2": "2.0.0" + }, + "@ohos/bytecodehar2": { + } + } +} diff --git a/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/hap-file-exec-expected.pa.txt b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/hap-file-exec-expected.pa.txt new file mode 100644 index 0000000000..819272cd4a --- /dev/null +++ b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/hap-file-exec-expected.pa.txt @@ -0,0 +1,1354 @@ +All Dependency Files: +program_file: bytecodehar1-abcinput.abc +record_name: &bytecodehar1/bytecodehar1-file1&2.0.0 +program_file: bytecodehar2-abcinput.abc +record_name: &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0 +program_file: hap-file-exec.ts +record_name: &myapp/hap-file-exec& +program_file: sourcehar-file1.ts +record_name: &sourcehar/sourcehar-file1&2.0.0 +program_file: sourcehar-file2.ts +record_name: &sourcehar/sourcehar-file2&2.0.0 + +slotNum = 0x3 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file1&2.0.0.#*#test(any a0, any a1, any a2) { + tryldglobalbyname 0x0, print + sta v0 + lda.str bytecodehar1.file1.test + sta v1 + lda v0 + callarg1 0x1, v1 + lda.str @normalized:N&&&sourcehar/sourcehar-file1&2.0.0 + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file1&2.0.0.#~A=#A(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x4 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file1&2.0.0.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, &bytecodehar1/bytecodehar1-file1&2.0.0.#*#test, 0x0 + stmodulevar 0x1 + ldhole + sta v0 + defineclasswithbuffer 0x1, &bytecodehar1/bytecodehar1-file1&2.0.0.#~A=#A, &bytecodehar1/bytecodehar1-file1&2.0.0_1826, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &bytecodehar1/bytecodehar1-file1&2.0.0_1764 +------------------------------------ +slot &bytecodehar1/bytecodehar1-file1&2.0.0_1768 +{ + index: 0 + tag: 2 + val: 1 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&&&@ohos/bytecodehar2/bytecodehar2-file1&2.0.0 +}, +{ + index: 2 + tag: 2 + val: 1 +}, +{ + index: 3 + tag: 5 + val: test1 +}, +{ + index: 4 + tag: 5 + val: test +}, +{ + index: 5 + tag: 9 + val: 0 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 2 +}, +{ + index: 8 + tag: 5 + val: Anno1 +}, +{ + index: 9 + tag: 5 + val: Anno1 +}, +{ + index: 10 + tag: 5 + val: test +}, +{ + index: 11 + tag: 5 + val: test +}, +{ + index: 12 + tag: 2 + val: 0 +}, +{ + index: 13 + tag: 2 + val: 0 +}, +------------------------------------ +slot &bytecodehar1/bytecodehar1-file1&2.0.0_1826 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&bytecodehar1/bytecodehar1-file1&2.0.0.#*#test"; "&bytecodehar1/bytecodehar1-file1&2.0.0.#~A=#A"; "@normalized:N&&&sourcehar/sourcehar-file1&2.0.0"; "bytecodehar1.file1.test"; "print"; "prototype"; + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x3 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file2&2.0.0.#*#test(any a0, any a1, any a2) { + tryldglobalbyname 0x0, print + sta v0 + lda.str bytecodehar1.file2.test + sta v1 + lda v0 + callarg1 0x1, v1 + lda.str @normalized:N&&&sourcehar/sourcehar-file2&2.0.0 + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file2&2.0.0.#~A=#A(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x4 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file2&2.0.0.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, &bytecodehar1/bytecodehar1-file2&2.0.0.#*#test, 0x0 + stmodulevar 0x1 + ldhole + sta v0 + defineclasswithbuffer 0x1, &bytecodehar1/bytecodehar1-file2&2.0.0.#~A=#A, &bytecodehar1/bytecodehar1-file2&2.0.0_1897, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &bytecodehar1/bytecodehar1-file2&2.0.0_1835 +------------------------------------ +slot &bytecodehar1/bytecodehar1-file2&2.0.0_1839 +{ + index: 0 + tag: 2 + val: 1 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&&&@ohos/bytecodehar2/bytecodehar2-file2&2.0.0 +}, +{ + index: 2 + tag: 2 + val: 1 +}, +{ + index: 3 + tag: 5 + val: test1 +}, +{ + index: 4 + tag: 5 + val: test +}, +{ + index: 5 + tag: 9 + val: 0 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 2 +}, +{ + index: 8 + tag: 5 + val: Anno2 +}, +{ + index: 9 + tag: 5 + val: Anno2 +}, +{ + index: 10 + tag: 5 + val: test +}, +{ + index: 11 + tag: 5 + val: test +}, +{ + index: 12 + tag: 2 + val: 0 +}, +{ + index: 13 + tag: 2 + val: 0 +}, +------------------------------------ +slot &bytecodehar1/bytecodehar1-file2&2.0.0_1897 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&bytecodehar1/bytecodehar1-file2&2.0.0.#*#test"; "&bytecodehar1/bytecodehar1-file2&2.0.0.#~A=#A"; "@normalized:N&&&sourcehar/sourcehar-file2&2.0.0"; "bytecodehar1.file2.test"; "print"; "prototype"; + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x3 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#*#test(any a0, any a1, any a2) { + tryldglobalbyname 0x0, print + sta v0 + lda.str bytecodehar2.file1.test + sta v1 + lda v0 + callarg1 0x1, v1 + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#~A=#A(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x4 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#*#test, 0x0 + stmodulevar 0x1 + ldhole + sta v0 + defineclasswithbuffer 0x1, &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#~A=#A, &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0_1637, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0_1589 +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0_1593 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 2 +}, +{ + index: 4 + tag: 5 + val: Anno1 +}, +{ + index: 5 + tag: 5 + val: Anno1 +}, +{ + index: 6 + tag: 5 + val: test +}, +{ + index: 7 + tag: 5 + val: test +}, +{ + index: 8 + tag: 2 + val: 0 +}, +{ + index: 9 + tag: 2 + val: 0 +}, +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0_1637 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#*#test"; "&@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#~A=#A"; "bytecodehar2.file1.test"; "print"; "prototype"; + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x3 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0.#*#test(any a0, any a1, any a2) { + tryldglobalbyname 0x0, print + sta v0 + lda.str bytecodehar2.file2.test + sta v1 + lda v0 + callarg1 0x1, v1 + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0.#~A=#A(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x4 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0.#*#test, 0x0 + stmodulevar 0x1 + ldhole + sta v0 + defineclasswithbuffer 0x1, &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0.#~A=#A, &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0_1694, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0_1646 +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0_1650 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 2 +}, +{ + index: 4 + tag: 5 + val: Anno2 +}, +{ + index: 5 + tag: 5 + val: Anno2 +}, +{ + index: 6 + tag: 5 + val: test +}, +{ + index: 7 + tag: 5 + val: test +}, +{ + index: 8 + tag: 2 + val: 0 +}, +{ + index: 9 + tag: 2 + val: 0 +}, +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0_1694 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&@ohos/bytecodehar2/bytecodehar2-file2&2.0.0.#*#test"; "&@ohos/bytecodehar2/bytecodehar2-file2&2.0.0.#~A=#A"; "bytecodehar2.file2.test"; "print"; "prototype"; + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x4 +.language ECMAScript +.function any &myapp/hap-file-exec&.#*#main(any a0, any a1, any a2) { +label_1: +label_0: + ldexternalmodulevar 0x2 + sta v0 + throw.undefinedifholewithname test + lda v0 + callarg0 0x0 + ldexternalmodulevar 0x0 + sta v0 + throw.undefinedifholewithname A + mov v1, v0 + newobjrange 0x2, 0x1, v1 + returnundefined +label_2: +} + +slotNum = 0x0 +.language ECMAScript +.function any &myapp/hap-file-exec&.#~B=#B(any a0, any a1, any a2) { +label_1: +label_0: + lda a2 + return +label_2: +} + +slotNum = 0x4 +.language ECMAScript +.function any &myapp/hap-file-exec&.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + definefunc 0x0, &myapp/hap-file-exec&.#*#main, 0x0 + ldhole + sta v0 + defineclasswithbuffer 0x1, &myapp/hap-file-exec&.#~B=#B, &myapp/hap-file-exec&_2, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &myapp/hap-file-exec&_0 +------------------------------------ +slot &myapp/hap-file-exec&_1 +{ + index: 0 + tag: 2 + val: 1 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&&&bytecodehar1/bytecodehar1-file1&2.0.0 +}, +{ + index: 2 + tag: 2 + val: 3 +}, +{ + index: 3 + tag: 5 + val: A +}, +{ + index: 4 + tag: 5 + val: A +}, +{ + index: 5 + tag: 9 + val: 0 +}, +{ + index: 6 + tag: 5 + val: Anno1 +}, +{ + index: 7 + tag: 5 + val: Anno1 +}, +{ + index: 8 + tag: 9 + val: 0 +}, +{ + index: 9 + tag: 5 + val: test +}, +{ + index: 10 + tag: 5 + val: test +}, +{ + index: 11 + tag: 9 + val: 0 +}, +{ + index: 12 + tag: 2 + val: 0 +}, +{ + index: 13 + tag: 2 + val: 0 +}, +{ + index: 14 + tag: 2 + val: 0 +}, +{ + index: 15 + tag: 2 + val: 0 +}, +------------------------------------ +slot &myapp/hap-file-exec&_2 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&myapp/hap-file-exec&.#*#main"; "&myapp/hap-file-exec&.#~B=#B"; "A"; "prototype"; "test"; +slotNum = 0x3 +.language ECMAScript +.function any &sourcehar/sourcehar-file1&2.0.0.#*#test(any a0, any a1, any a2) { +label_1: +label_0: + tryldglobalbyname 0x0, print + sta v0 + lda.str sourcehar.file1.test + sta v1 + lda v0 + callarg1 0x1, v1 + returnundefined +label_2: +} + +slotNum = 0x1 +.language ECMAScript +.function any &sourcehar/sourcehar-file1&2.0.0.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + definefunc 0x0, &sourcehar/sourcehar-file1&2.0.0.#*#test, 0x0 + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &sourcehar/sourcehar-file1&2.0.0_0 +------------------------------------ +slot &sourcehar/sourcehar-file1&2.0.0_1 +{ + index: 0 + tag: 2 + val: 1 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&&&sourcehar/sourcehar-file2&2.0.0 +}, +{ + index: 2 + tag: 2 + val: 1 +}, +{ + index: 3 + tag: 5 + val: test1 +}, +{ + index: 4 + tag: 5 + val: test +}, +{ + index: 5 + tag: 9 + val: 0 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 1 +}, +{ + index: 8 + tag: 5 + val: test +}, +{ + index: 9 + tag: 5 + val: test +}, +{ + index: 10 + tag: 2 + val: 0 +}, +{ + index: 11 + tag: 2 + val: 0 +}, +======> strings <====== +"&sourcehar/sourcehar-file1&2.0.0.#*#test"; "print"; "sourcehar.file1.test"; +slotNum = 0x3 +.language ECMAScript +.function any &sourcehar/sourcehar-file2&2.0.0.#*#test(any a0, any a1, any a2) { +label_1: +label_0: + tryldglobalbyname 0x0, print + sta v0 + lda.str sourcehar.file2.test + sta v1 + lda v0 + callarg1 0x1, v1 + returnundefined +label_2: +} + +slotNum = 0x1 +.language ECMAScript +.function any &sourcehar/sourcehar-file2&2.0.0.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + definefunc 0x0, &sourcehar/sourcehar-file2&2.0.0.#*#test, 0x0 + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &sourcehar/sourcehar-file2&2.0.0_0 +------------------------------------ +slot &sourcehar/sourcehar-file2&2.0.0_1 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 1 +}, +{ + index: 4 + tag: 5 + val: test +}, +{ + index: 5 + tag: 5 + val: test +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +======> strings <====== +"&sourcehar/sourcehar-file2&2.0.0.#*#test"; "print"; "sourcehar.file2.test"; +slotNum = 0x3 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file1&2.0.0.#*#test(any a0, any a1, any a2) { + tryldglobalbyname 0x0, print + sta v0 + lda.str bytecodehar1.file1.test + sta v1 + lda v0 + callarg1 0x1, v1 + lda.str @normalized:N&&&sourcehar/sourcehar-file1&2.0.0 + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file1&2.0.0.#~A=#A(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x4 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file1&2.0.0.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, &bytecodehar1/bytecodehar1-file1&2.0.0.#*#test, 0x0 + stmodulevar 0x1 + ldhole + sta v0 + defineclasswithbuffer 0x1, &bytecodehar1/bytecodehar1-file1&2.0.0.#~A=#A, &bytecodehar1/bytecodehar1-file1&2.0.0_1826, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &bytecodehar1/bytecodehar1-file1&2.0.0_1764 +------------------------------------ +slot &bytecodehar1/bytecodehar1-file1&2.0.0_1768 +{ + index: 0 + tag: 2 + val: 1 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&&&@ohos/bytecodehar2/bytecodehar2-file1&2.0.0 +}, +{ + index: 2 + tag: 2 + val: 1 +}, +{ + index: 3 + tag: 5 + val: test1 +}, +{ + index: 4 + tag: 5 + val: test +}, +{ + index: 5 + tag: 9 + val: 0 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 2 +}, +{ + index: 8 + tag: 5 + val: Anno1 +}, +{ + index: 9 + tag: 5 + val: Anno1 +}, +{ + index: 10 + tag: 5 + val: test +}, +{ + index: 11 + tag: 5 + val: test +}, +{ + index: 12 + tag: 2 + val: 0 +}, +{ + index: 13 + tag: 2 + val: 0 +}, +------------------------------------ +slot &bytecodehar1/bytecodehar1-file1&2.0.0_1826 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&bytecodehar1/bytecodehar1-file1&2.0.0.#*#test"; "&bytecodehar1/bytecodehar1-file1&2.0.0.#~A=#A"; "@normalized:N&&&sourcehar/sourcehar-file1&2.0.0"; "bytecodehar1.file1.test"; "print"; "prototype"; + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x3 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#*#test(any a0, any a1, any a2) { + tryldglobalbyname 0x0, print + sta v0 + lda.str bytecodehar2.file1.test + sta v1 + lda v0 + callarg1 0x1, v1 + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#~A=#A(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x4 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#*#test, 0x0 + stmodulevar 0x1 + ldhole + sta v0 + defineclasswithbuffer 0x1, &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#~A=#A, &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0_1637, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0_1589 +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0_1593 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 2 +}, +{ + index: 4 + tag: 5 + val: Anno1 +}, +{ + index: 5 + tag: 5 + val: Anno1 +}, +{ + index: 6 + tag: 5 + val: test +}, +{ + index: 7 + tag: 5 + val: test +}, +{ + index: 8 + tag: 2 + val: 0 +}, +{ + index: 9 + tag: 2 + val: 0 +}, +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0_1637 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#*#test"; "&@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#~A=#A"; "bytecodehar2.file1.test"; "print"; "prototype"; + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x4 +.language ECMAScript +.function any &myapp/hap-file-exec&.#*#main(any a0, any a1, any a2) { +label_1: +label_0: + ldexternalmodulevar 0x2 + sta v0 + throw.undefinedifholewithname test + lda v0 + callarg0 0x0 + ldexternalmodulevar 0x0 + sta v0 + throw.undefinedifholewithname A + mov v1, v0 + newobjrange 0x2, 0x1, v1 + returnundefined +label_2: +} + +slotNum = 0x0 +.language ECMAScript +.function any &myapp/hap-file-exec&.#~B=#B(any a0, any a1, any a2) { +label_1: +label_0: + lda a2 + return +label_2: +} + +slotNum = 0x4 +.language ECMAScript +.function any &myapp/hap-file-exec&.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + definefunc 0x0, &myapp/hap-file-exec&.#*#main, 0x0 + ldhole + sta v0 + defineclasswithbuffer 0x1, &myapp/hap-file-exec&.#~B=#B, &myapp/hap-file-exec&_2, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &myapp/hap-file-exec&_0 +------------------------------------ +slot &myapp/hap-file-exec&_1 +{ + index: 0 + tag: 2 + val: 1 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&&&bytecodehar1/bytecodehar1-file1&2.0.0 +}, +{ + index: 2 + tag: 2 + val: 3 +}, +{ + index: 3 + tag: 5 + val: A +}, +{ + index: 4 + tag: 5 + val: A +}, +{ + index: 5 + tag: 9 + val: 0 +}, +{ + index: 6 + tag: 5 + val: Anno1 +}, +{ + index: 7 + tag: 5 + val: Anno1 +}, +{ + index: 8 + tag: 9 + val: 0 +}, +{ + index: 9 + tag: 5 + val: test +}, +{ + index: 10 + tag: 5 + val: test +}, +{ + index: 11 + tag: 9 + val: 0 +}, +{ + index: 12 + tag: 2 + val: 0 +}, +{ + index: 13 + tag: 2 + val: 0 +}, +{ + index: 14 + tag: 2 + val: 0 +}, +{ + index: 15 + tag: 2 + val: 0 +}, +------------------------------------ +slot &myapp/hap-file-exec&_2 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&myapp/hap-file-exec&.#*#main"; "&myapp/hap-file-exec&.#~B=#B"; "A"; "prototype"; "test"; +slotNum = 0x3 +.language ECMAScript +.function any &sourcehar/sourcehar-file1&2.0.0.#*#test(any a0, any a1, any a2) { +label_1: +label_0: + tryldglobalbyname 0x0, print + sta v0 + lda.str sourcehar.file1.test + sta v1 + lda v0 + callarg1 0x1, v1 + returnundefined +label_2: +} + +slotNum = 0x1 +.language ECMAScript +.function any &sourcehar/sourcehar-file1&2.0.0.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + definefunc 0x0, &sourcehar/sourcehar-file1&2.0.0.#*#test, 0x0 + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &sourcehar/sourcehar-file1&2.0.0_0 +------------------------------------ +slot &sourcehar/sourcehar-file1&2.0.0_1 +{ + index: 0 + tag: 2 + val: 1 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&&&sourcehar/sourcehar-file2&2.0.0 +}, +{ + index: 2 + tag: 2 + val: 1 +}, +{ + index: 3 + tag: 5 + val: test1 +}, +{ + index: 4 + tag: 5 + val: test +}, +{ + index: 5 + tag: 9 + val: 0 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 1 +}, +{ + index: 8 + tag: 5 + val: test +}, +{ + index: 9 + tag: 5 + val: test +}, +{ + index: 10 + tag: 2 + val: 0 +}, +{ + index: 11 + tag: 2 + val: 0 +}, +======> strings <====== +"&sourcehar/sourcehar-file1&2.0.0.#*#test"; "print"; "sourcehar.file1.test"; +slotNum = 0x3 +.language ECMAScript +.function any &sourcehar/sourcehar-file2&2.0.0.#*#test(any a0, any a1, any a2) { +label_1: +label_0: + tryldglobalbyname 0x0, print + sta v0 + lda.str sourcehar.file2.test + sta v1 + lda v0 + callarg1 0x1, v1 + returnundefined +label_2: +} + +slotNum = 0x1 +.language ECMAScript +.function any &sourcehar/sourcehar-file2&2.0.0.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + definefunc 0x0, &sourcehar/sourcehar-file2&2.0.0.#*#test, 0x0 + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &sourcehar/sourcehar-file2&2.0.0_0 +------------------------------------ +slot &sourcehar/sourcehar-file2&2.0.0_1 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 1 +}, +{ + index: 4 + tag: 5 + val: test +}, +{ + index: 5 + tag: 5 + val: test +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +======> strings <====== +"&sourcehar/sourcehar-file2&2.0.0.#*#test"; "print"; "sourcehar.file2.test"; diff --git a/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/hap-file-exec.ts b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/hap-file-exec.ts new file mode 100644 index 0000000000..8fe9e1625e --- /dev/null +++ b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/hap-file-exec.ts @@ -0,0 +1,24 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { test, __$$ETS_ANNOTATION$$__Anno1, A } from "@normalized:N&&&bytecodehar1/bytecodehar1-file1&2.0.0" + +function main() { + test(); + let a = new A(); +} + +@__$$ETS_ANNOTATION$$__Anno1({ b: true }) +class B { } \ No newline at end of file diff --git a/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/recordnames.txt b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/recordnames.txt new file mode 100644 index 0000000000..70074eddf7 --- /dev/null +++ b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/recordnames.txt @@ -0,0 +1,7 @@ +bytecodehar1-file1:&bytecodehar1/bytecodehar1-file1&2.0.0 +bytecodehar1-file2:&bytecodehar1/bytecodehar1-file2&2.0.0 +bytecodehar2-file1:&@ohos/bytecodehar2/bytecodehar2-file1&2.0.0 +bytecodehar2-file2:&@ohos/bytecodehar2/bytecodehar2-file2&2.0.0 +sourcehar-file1:&sourcehar/sourcehar-file1&2.0.0 +sourcehar-file2:&sourcehar/sourcehar-file2&2.0.0 +hap-file-exec:&myapp/hap-file-exec& diff --git a/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/sourcehar-file1.ts b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/sourcehar-file1.ts new file mode 100644 index 0000000000..f688431373 --- /dev/null +++ b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/sourcehar-file1.ts @@ -0,0 +1,20 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {test as test1} from '@normalized:N&&&sourcehar/sourcehar-file2&2.0.0' + +export function test() { + print('sourcehar.file1.test'); +} \ No newline at end of file diff --git a/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/sourcehar-file2.ts b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/sourcehar-file2.ts new file mode 100644 index 0000000000..7702af0778 --- /dev/null +++ b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-cache-file/sourcehar-file2.ts @@ -0,0 +1,18 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export function test() { + print('sourcehar.file2.test'); +} \ No newline at end of file diff --git a/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/abcinputs/bytecodehar1.txt b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/abcinputs/bytecodehar1.txt new file mode 100644 index 0000000000..44fef6254c --- /dev/null +++ b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/abcinputs/bytecodehar1.txt @@ -0,0 +1,2 @@ +bytecodehar1-file1.ts +bytecodehar1-file2.ts diff --git a/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/abcinputs/bytecodehar2.txt b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/abcinputs/bytecodehar2.txt new file mode 100644 index 0000000000..01249cd0af --- /dev/null +++ b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/abcinputs/bytecodehar2.txt @@ -0,0 +1,2 @@ +bytecodehar2-file1.ts +bytecodehar2-file2.ts diff --git a/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/bytecodehar1-file1.ts b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/bytecodehar1-file1.ts new file mode 100644 index 0000000000..7478e00482 --- /dev/null +++ b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/bytecodehar1-file1.ts @@ -0,0 +1,28 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {test as test1} from '@normalized:N&&&@ohos/bytecodehar2/bytecodehar2-file1&2.0.0' + +export function test() { + print('bytecodehar1.file1.test'); + import('@normalized:N&&&sourcehar/sourcehar-file1&2.0.0') +} + +export @interface __$$ETS_ANNOTATION$$__Anno1 { + b: boolean = true +} + +@__$$ETS_ANNOTATION$$__Anno1() +class A { } \ No newline at end of file diff --git a/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/bytecodehar1-file2.ts b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/bytecodehar1-file2.ts new file mode 100644 index 0000000000..5962b22672 --- /dev/null +++ b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/bytecodehar1-file2.ts @@ -0,0 +1,28 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {test as test1} from "@normalized:N&&&@ohos/bytecodehar2/bytecodehar2-file2&1.0.0" + +export function test() { + print('bytecodehar1.file2.test'); + import("@normalized:N&&&sourcehar/sourcehar-file2&2.0.0") +} + +export @interface __$$ETS_ANNOTATION$$__Anno2 { + b: boolean = true +} + +@__$$ETS_ANNOTATION$$__Anno2() +class A { } \ No newline at end of file diff --git a/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/bytecodehar2-file1.ts b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/bytecodehar2-file1.ts new file mode 100644 index 0000000000..fc82d9af73 --- /dev/null +++ b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/bytecodehar2-file1.ts @@ -0,0 +1,25 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export function test() { + print('bytecodehar2.file1.test'); +} + +export @interface __$$ETS_ANNOTATION$$__Anno1 { + b: boolean = true +} + +@__$$ETS_ANNOTATION$$__Anno1() +class A { } \ No newline at end of file diff --git a/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/bytecodehar2-file2.ts b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/bytecodehar2-file2.ts new file mode 100644 index 0000000000..3716361621 --- /dev/null +++ b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/bytecodehar2-file2.ts @@ -0,0 +1,25 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export function test() { + print('bytecodehar2.file2.test'); +} + +export @interface __$$ETS_ANNOTATION$$__Anno2 { + b: boolean = true +} + +@__$$ETS_ANNOTATION$$__Anno2() +class A { } \ No newline at end of file diff --git a/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/compileContextInfo.json b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/compileContextInfo.json new file mode 100644 index 0000000000..43eafd903d --- /dev/null +++ b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/compileContextInfo.json @@ -0,0 +1,13 @@ +{ + "compileEntries": [ + "&myapp/hap-file-exec&" + ], + "hspPkgNames": [], + "updateVersionInfo": { + "bytecodehar1": { + "@ohos/bytecodehar2": "2.0.0" + }, + "@ohos/bytecodehar2": { + } + } +} diff --git a/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/hap-file-exec-expected.pa.txt b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/hap-file-exec-expected.pa.txt new file mode 100644 index 0000000000..839d23a63b --- /dev/null +++ b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/hap-file-exec-expected.pa.txt @@ -0,0 +1,1718 @@ +All Dependency Files: +program_file: bytecodehar1-abcinput.abc +record_name: &bytecodehar1/bytecodehar1-file1&2.0.0 +program_file: bytecodehar1-abcinput.abc +record_name: &bytecodehar1/bytecodehar1-file2&2.0.0 +program_file: bytecodehar2-abcinput.abc +record_name: &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0 +program_file: bytecodehar2-abcinput.abc +record_name: &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0 +program_file: hap-file-exec.ts +record_name: &myapp/hap-file-exec& +program_file: hap-add-file.ts +record_name: &myapp/hap-add-file& +program_file: sourcehar-file1.ts +record_name: &sourcehar/sourcehar-file1&2.0.0 +program_file: sourcehar-file2.ts +record_name: &sourcehar/sourcehar-file2&2.0.0 + +slotNum = 0x3 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file1&2.0.0.#*#test(any a0, any a1, any a2) { + tryldglobalbyname 0x0, print + sta v0 + lda.str bytecodehar1.file1.test + sta v1 + lda v0 + callarg1 0x1, v1 + lda.str @normalized:N&&&sourcehar/sourcehar-file1&2.0.0 + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file1&2.0.0.#~A=#A(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x4 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file1&2.0.0.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, &bytecodehar1/bytecodehar1-file1&2.0.0.#*#test, 0x0 + stmodulevar 0x1 + ldhole + sta v0 + defineclasswithbuffer 0x1, &bytecodehar1/bytecodehar1-file1&2.0.0.#~A=#A, &bytecodehar1/bytecodehar1-file1&2.0.0_1844, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &bytecodehar1/bytecodehar1-file1&2.0.0_1782 +------------------------------------ +slot &bytecodehar1/bytecodehar1-file1&2.0.0_1786 +{ + index: 0 + tag: 2 + val: 1 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&&&@ohos/bytecodehar2/bytecodehar2-file1&2.0.0 +}, +{ + index: 2 + tag: 2 + val: 1 +}, +{ + index: 3 + tag: 5 + val: test1 +}, +{ + index: 4 + tag: 5 + val: test +}, +{ + index: 5 + tag: 9 + val: 0 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 2 +}, +{ + index: 8 + tag: 5 + val: Anno1 +}, +{ + index: 9 + tag: 5 + val: Anno1 +}, +{ + index: 10 + tag: 5 + val: test +}, +{ + index: 11 + tag: 5 + val: test +}, +{ + index: 12 + tag: 2 + val: 0 +}, +{ + index: 13 + tag: 2 + val: 0 +}, +------------------------------------ +slot &bytecodehar1/bytecodehar1-file1&2.0.0_1844 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&bytecodehar1/bytecodehar1-file1&2.0.0.#*#test"; "&bytecodehar1/bytecodehar1-file1&2.0.0.#~A=#A"; "@normalized:N&&&sourcehar/sourcehar-file1&2.0.0"; "bytecodehar1.file1.test"; "print"; "prototype"; + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x3 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file2&2.0.0.#*#test(any a0, any a1, any a2) { + tryldglobalbyname 0x0, print + sta v0 + lda.str bytecodehar1.file2.test + sta v1 + lda v0 + callarg1 0x1, v1 + lda.str @normalized:N&&&sourcehar/sourcehar-file2&2.0.0 + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file2&2.0.0.#~A=#A(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x4 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file2&2.0.0.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, &bytecodehar1/bytecodehar1-file2&2.0.0.#*#test, 0x0 + stmodulevar 0x1 + ldhole + sta v0 + defineclasswithbuffer 0x1, &bytecodehar1/bytecodehar1-file2&2.0.0.#~A=#A, &bytecodehar1/bytecodehar1-file2&2.0.0_1915, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &bytecodehar1/bytecodehar1-file2&2.0.0_1853 +------------------------------------ +slot &bytecodehar1/bytecodehar1-file2&2.0.0_1857 +{ + index: 0 + tag: 2 + val: 1 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&&&@ohos/bytecodehar2/bytecodehar2-file2&2.0.0 +}, +{ + index: 2 + tag: 2 + val: 1 +}, +{ + index: 3 + tag: 5 + val: test1 +}, +{ + index: 4 + tag: 5 + val: test +}, +{ + index: 5 + tag: 9 + val: 0 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 2 +}, +{ + index: 8 + tag: 5 + val: Anno2 +}, +{ + index: 9 + tag: 5 + val: Anno2 +}, +{ + index: 10 + tag: 5 + val: test +}, +{ + index: 11 + tag: 5 + val: test +}, +{ + index: 12 + tag: 2 + val: 0 +}, +{ + index: 13 + tag: 2 + val: 0 +}, +------------------------------------ +slot &bytecodehar1/bytecodehar1-file2&2.0.0_1915 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&bytecodehar1/bytecodehar1-file2&2.0.0.#*#test"; "&bytecodehar1/bytecodehar1-file2&2.0.0.#~A=#A"; "@normalized:N&&&sourcehar/sourcehar-file2&2.0.0"; "bytecodehar1.file2.test"; "print"; "prototype"; + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x3 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#*#test(any a0, any a1, any a2) { + tryldglobalbyname 0x0, print + sta v0 + lda.str bytecodehar2.file1.test + sta v1 + lda v0 + callarg1 0x1, v1 + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#~A=#A(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x4 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#*#test, 0x0 + stmodulevar 0x1 + ldhole + sta v0 + defineclasswithbuffer 0x1, &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#~A=#A, &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0_1655, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0_1607 +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0_1611 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 2 +}, +{ + index: 4 + tag: 5 + val: Anno1 +}, +{ + index: 5 + tag: 5 + val: Anno1 +}, +{ + index: 6 + tag: 5 + val: test +}, +{ + index: 7 + tag: 5 + val: test +}, +{ + index: 8 + tag: 2 + val: 0 +}, +{ + index: 9 + tag: 2 + val: 0 +}, +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0_1655 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#*#test"; "&@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#~A=#A"; "bytecodehar2.file1.test"; "print"; "prototype"; + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x3 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0.#*#test(any a0, any a1, any a2) { + tryldglobalbyname 0x0, print + sta v0 + lda.str bytecodehar2.file2.test + sta v1 + lda v0 + callarg1 0x1, v1 + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0.#~A=#A(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x4 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0.#*#test, 0x0 + stmodulevar 0x1 + ldhole + sta v0 + defineclasswithbuffer 0x1, &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0.#~A=#A, &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0_1712, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0_1664 +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0_1668 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 2 +}, +{ + index: 4 + tag: 5 + val: Anno2 +}, +{ + index: 5 + tag: 5 + val: Anno2 +}, +{ + index: 6 + tag: 5 + val: test +}, +{ + index: 7 + tag: 5 + val: test +}, +{ + index: 8 + tag: 2 + val: 0 +}, +{ + index: 9 + tag: 2 + val: 0 +}, +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0_1712 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&@ohos/bytecodehar2/bytecodehar2-file2&2.0.0.#*#test"; "&@ohos/bytecodehar2/bytecodehar2-file2&2.0.0.#~A=#A"; "bytecodehar2.file2.test"; "print"; "prototype"; + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x4 +.language ECMAScript +.function any &myapp/hap-file-exec&.#*#main(any a0, any a1, any a2) { +label_1: +label_0: + lda.str @normalized:N&&&myapp/hap-add-file& + dynamicimport + ldexternalmodulevar 0x2 + sta v0 + throw.undefinedifholewithname test + lda v0 + callarg0 0x0 + ldexternalmodulevar 0x0 + sta v0 + throw.undefinedifholewithname A + mov v1, v0 + newobjrange 0x2, 0x1, v1 + returnundefined +label_2: +} + +slotNum = 0x0 +.language ECMAScript +.function any &myapp/hap-file-exec&.#~B=#B(any a0, any a1, any a2) { +label_1: +label_0: + lda a2 + return +label_2: +} + +slotNum = 0x4 +.language ECMAScript +.function any &myapp/hap-file-exec&.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + definefunc 0x0, &myapp/hap-file-exec&.#*#main, 0x0 + ldhole + sta v0 + defineclasswithbuffer 0x1, &myapp/hap-file-exec&.#~B=#B, &myapp/hap-file-exec&_2, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &myapp/hap-file-exec&_0 +------------------------------------ +slot &myapp/hap-file-exec&_1 +{ + index: 0 + tag: 2 + val: 1 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&&&bytecodehar1/bytecodehar1-file1&2.0.0 +}, +{ + index: 2 + tag: 2 + val: 3 +}, +{ + index: 3 + tag: 5 + val: A +}, +{ + index: 4 + tag: 5 + val: A +}, +{ + index: 5 + tag: 9 + val: 0 +}, +{ + index: 6 + tag: 5 + val: Anno1 +}, +{ + index: 7 + tag: 5 + val: Anno1 +}, +{ + index: 8 + tag: 9 + val: 0 +}, +{ + index: 9 + tag: 5 + val: test +}, +{ + index: 10 + tag: 5 + val: test +}, +{ + index: 11 + tag: 9 + val: 0 +}, +{ + index: 12 + tag: 2 + val: 0 +}, +{ + index: 13 + tag: 2 + val: 0 +}, +{ + index: 14 + tag: 2 + val: 0 +}, +{ + index: 15 + tag: 2 + val: 0 +}, +------------------------------------ +slot &myapp/hap-file-exec&_2 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&myapp/hap-file-exec&.#*#main"; "&myapp/hap-file-exec&.#~B=#B"; "@normalized:N&&&myapp/hap-add-file&"; "A"; "prototype"; "test"; +slotNum = 0x3 +.language ECMAScript +.function any &myapp/hap-add-file&.#*#modTest(any a0, any a1, any a2) { +label_1: +label_0: + lda.str @normalized:N&&&bytecodehar1/bytecodehar1-file2&2.0.0 + dynamicimport + tryldglobalbyname 0x0, test + callarg0 0x1 + returnundefined +label_2: +} + +slotNum = 0x1 +.language ECMAScript +.function any &myapp/hap-add-file&.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + definefunc 0x0, &myapp/hap-add-file&.#*#modTest, 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &myapp/hap-add-file&_0 +------------------------------------ +slot &myapp/hap-add-file&_1 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 0 +}, +{ + index: 4 + tag: 2 + val: 0 +}, +{ + index: 5 + tag: 2 + val: 0 +}, +======> strings <====== +"&myapp/hap-add-file&.#*#modTest"; "@normalized:N&&&bytecodehar1/bytecodehar1-file2&2.0.0"; "test"; +slotNum = 0x3 +.language ECMAScript +.function any &sourcehar/sourcehar-file1&2.0.0.#*#test(any a0, any a1, any a2) { +label_1: +label_0: + tryldglobalbyname 0x0, print + sta v0 + lda.str sourcehar.file1.test + sta v1 + lda v0 + callarg1 0x1, v1 + returnundefined +label_2: +} + +slotNum = 0x1 +.language ECMAScript +.function any &sourcehar/sourcehar-file1&2.0.0.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + definefunc 0x0, &sourcehar/sourcehar-file1&2.0.0.#*#test, 0x0 + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &sourcehar/sourcehar-file1&2.0.0_0 +------------------------------------ +slot &sourcehar/sourcehar-file1&2.0.0_1 +{ + index: 0 + tag: 2 + val: 1 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&&&sourcehar/sourcehar-file2&2.0.0 +}, +{ + index: 2 + tag: 2 + val: 1 +}, +{ + index: 3 + tag: 5 + val: test1 +}, +{ + index: 4 + tag: 5 + val: test +}, +{ + index: 5 + tag: 9 + val: 0 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 1 +}, +{ + index: 8 + tag: 5 + val: test +}, +{ + index: 9 + tag: 5 + val: test +}, +{ + index: 10 + tag: 2 + val: 0 +}, +{ + index: 11 + tag: 2 + val: 0 +}, +======> strings <====== +"&sourcehar/sourcehar-file1&2.0.0.#*#test"; "print"; "sourcehar.file1.test"; +slotNum = 0x3 +.language ECMAScript +.function any &sourcehar/sourcehar-file2&2.0.0.#*#test(any a0, any a1, any a2) { +label_1: +label_0: + tryldglobalbyname 0x0, print + sta v0 + lda.str sourcehar.file2.test + sta v1 + lda v0 + callarg1 0x1, v1 + returnundefined +label_2: +} + +slotNum = 0x1 +.language ECMAScript +.function any &sourcehar/sourcehar-file2&2.0.0.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + definefunc 0x0, &sourcehar/sourcehar-file2&2.0.0.#*#test, 0x0 + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &sourcehar/sourcehar-file2&2.0.0_0 +------------------------------------ +slot &sourcehar/sourcehar-file2&2.0.0_1 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 1 +}, +{ + index: 4 + tag: 5 + val: test +}, +{ + index: 5 + tag: 5 + val: test +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +======> strings <====== +"&sourcehar/sourcehar-file2&2.0.0.#*#test"; "print"; "sourcehar.file2.test"; +slotNum = 0x3 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file1&2.0.0.#*#test(any a0, any a1, any a2) { + tryldglobalbyname 0x0, print + sta v0 + lda.str bytecodehar1.file1.test + sta v1 + lda v0 + callarg1 0x1, v1 + lda.str @normalized:N&&&sourcehar/sourcehar-file1&2.0.0 + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file1&2.0.0.#~A=#A(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x4 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file1&2.0.0.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, &bytecodehar1/bytecodehar1-file1&2.0.0.#*#test, 0x0 + stmodulevar 0x1 + ldhole + sta v0 + defineclasswithbuffer 0x1, &bytecodehar1/bytecodehar1-file1&2.0.0.#~A=#A, &bytecodehar1/bytecodehar1-file1&2.0.0_1844, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &bytecodehar1/bytecodehar1-file1&2.0.0_1782 +------------------------------------ +slot &bytecodehar1/bytecodehar1-file1&2.0.0_1786 +{ + index: 0 + tag: 2 + val: 1 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&&&@ohos/bytecodehar2/bytecodehar2-file1&2.0.0 +}, +{ + index: 2 + tag: 2 + val: 1 +}, +{ + index: 3 + tag: 5 + val: test1 +}, +{ + index: 4 + tag: 5 + val: test +}, +{ + index: 5 + tag: 9 + val: 0 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 2 +}, +{ + index: 8 + tag: 5 + val: Anno1 +}, +{ + index: 9 + tag: 5 + val: Anno1 +}, +{ + index: 10 + tag: 5 + val: test +}, +{ + index: 11 + tag: 5 + val: test +}, +{ + index: 12 + tag: 2 + val: 0 +}, +{ + index: 13 + tag: 2 + val: 0 +}, +------------------------------------ +slot &bytecodehar1/bytecodehar1-file1&2.0.0_1844 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&bytecodehar1/bytecodehar1-file1&2.0.0.#*#test"; "&bytecodehar1/bytecodehar1-file1&2.0.0.#~A=#A"; "@normalized:N&&&sourcehar/sourcehar-file1&2.0.0"; "bytecodehar1.file1.test"; "print"; "prototype"; + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x3 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file2&2.0.0.#*#test(any a0, any a1, any a2) { + tryldglobalbyname 0x0, print + sta v0 + lda.str bytecodehar1.file2.test + sta v1 + lda v0 + callarg1 0x1, v1 + lda.str @normalized:N&&&sourcehar/sourcehar-file2&2.0.0 + dynamicimport + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file2&2.0.0.#~A=#A(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x4 +.language ECMAScript +.function any &bytecodehar1/bytecodehar1-file2&2.0.0.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, &bytecodehar1/bytecodehar1-file2&2.0.0.#*#test, 0x0 + stmodulevar 0x1 + ldhole + sta v0 + defineclasswithbuffer 0x1, &bytecodehar1/bytecodehar1-file2&2.0.0.#~A=#A, &bytecodehar1/bytecodehar1-file2&2.0.0_1915, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &bytecodehar1/bytecodehar1-file2&2.0.0_1853 +------------------------------------ +slot &bytecodehar1/bytecodehar1-file2&2.0.0_1857 +{ + index: 0 + tag: 2 + val: 1 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&&&@ohos/bytecodehar2/bytecodehar2-file2&2.0.0 +}, +{ + index: 2 + tag: 2 + val: 1 +}, +{ + index: 3 + tag: 5 + val: test1 +}, +{ + index: 4 + tag: 5 + val: test +}, +{ + index: 5 + tag: 9 + val: 0 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 2 +}, +{ + index: 8 + tag: 5 + val: Anno2 +}, +{ + index: 9 + tag: 5 + val: Anno2 +}, +{ + index: 10 + tag: 5 + val: test +}, +{ + index: 11 + tag: 5 + val: test +}, +{ + index: 12 + tag: 2 + val: 0 +}, +{ + index: 13 + tag: 2 + val: 0 +}, +------------------------------------ +slot &bytecodehar1/bytecodehar1-file2&2.0.0_1915 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&bytecodehar1/bytecodehar1-file2&2.0.0.#*#test"; "&bytecodehar1/bytecodehar1-file2&2.0.0.#~A=#A"; "@normalized:N&&&sourcehar/sourcehar-file2&2.0.0"; "bytecodehar1.file2.test"; "print"; "prototype"; + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x3 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#*#test(any a0, any a1, any a2) { + tryldglobalbyname 0x0, print + sta v0 + lda.str bytecodehar2.file1.test + sta v1 + lda v0 + callarg1 0x1, v1 + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#~A=#A(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x4 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#*#test, 0x0 + stmodulevar 0x1 + ldhole + sta v0 + defineclasswithbuffer 0x1, &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#~A=#A, &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0_1655, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0_1607 +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0_1611 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 2 +}, +{ + index: 4 + tag: 5 + val: Anno1 +}, +{ + index: 5 + tag: 5 + val: Anno1 +}, +{ + index: 6 + tag: 5 + val: test +}, +{ + index: 7 + tag: 5 + val: test +}, +{ + index: 8 + tag: 2 + val: 0 +}, +{ + index: 9 + tag: 2 + val: 0 +}, +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file1&2.0.0_1655 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#*#test"; "&@ohos/bytecodehar2/bytecodehar2-file1&2.0.0.#~A=#A"; "bytecodehar2.file1.test"; "print"; "prototype"; + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x3 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0.#*#test(any a0, any a1, any a2) { + tryldglobalbyname 0x0, print + sta v0 + lda.str bytecodehar2.file2.test + sta v1 + lda v0 + callarg1 0x1, v1 + returnundefined +} + +slotNum = 0x0 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0.#~A=#A(any a0, any a1, any a2) { + lda a2 + return +} + +slotNum = 0x4 +.language ECMAScript +.function any &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0.func_main_0(any a0, any a1, any a2) { + definefunc 0x0, &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0.#*#test, 0x0 + stmodulevar 0x1 + ldhole + sta v0 + defineclasswithbuffer 0x1, &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0.#~A=#A, &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0_1712, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +} + + +======> literal array buffer <====== +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0_1664 +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0_1668 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 2 +}, +{ + index: 4 + tag: 5 + val: Anno2 +}, +{ + index: 5 + tag: 5 + val: Anno2 +}, +{ + index: 6 + tag: 5 + val: test +}, +{ + index: 7 + tag: 5 + val: test +}, +{ + index: 8 + tag: 2 + val: 0 +}, +{ + index: 9 + tag: 2 + val: 0 +}, +------------------------------------ +slot &@ohos/bytecodehar2/bytecodehar2-file2&2.0.0_1712 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&@ohos/bytecodehar2/bytecodehar2-file2&2.0.0.#*#test"; "&@ohos/bytecodehar2/bytecodehar2-file2&2.0.0.#~A=#A"; "bytecodehar2.file2.test"; "print"; "prototype"; + +======> literal array buffer <====== +======> strings <====== + +slotNum = 0x4 +.language ECMAScript +.function any &myapp/hap-file-exec&.#*#main(any a0, any a1, any a2) { +label_1: +label_0: + lda.str @normalized:N&&&myapp/hap-add-file& + dynamicimport + ldexternalmodulevar 0x2 + sta v0 + throw.undefinedifholewithname test + lda v0 + callarg0 0x0 + ldexternalmodulevar 0x0 + sta v0 + throw.undefinedifholewithname A + mov v1, v0 + newobjrange 0x2, 0x1, v1 + returnundefined +label_2: +} + +slotNum = 0x0 +.language ECMAScript +.function any &myapp/hap-file-exec&.#~B=#B(any a0, any a1, any a2) { +label_1: +label_0: + lda a2 + return +label_2: +} + +slotNum = 0x4 +.language ECMAScript +.function any &myapp/hap-file-exec&.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + definefunc 0x0, &myapp/hap-file-exec&.#*#main, 0x0 + ldhole + sta v0 + defineclasswithbuffer 0x1, &myapp/hap-file-exec&.#~B=#B, &myapp/hap-file-exec&_2, 0x0, v0 + ldobjbyname 0x2, prototype + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &myapp/hap-file-exec&_0 +------------------------------------ +slot &myapp/hap-file-exec&_1 +{ + index: 0 + tag: 2 + val: 1 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&&&bytecodehar1/bytecodehar1-file1&2.0.0 +}, +{ + index: 2 + tag: 2 + val: 3 +}, +{ + index: 3 + tag: 5 + val: A +}, +{ + index: 4 + tag: 5 + val: A +}, +{ + index: 5 + tag: 9 + val: 0 +}, +{ + index: 6 + tag: 5 + val: Anno1 +}, +{ + index: 7 + tag: 5 + val: Anno1 +}, +{ + index: 8 + tag: 9 + val: 0 +}, +{ + index: 9 + tag: 5 + val: test +}, +{ + index: 10 + tag: 5 + val: test +}, +{ + index: 11 + tag: 9 + val: 0 +}, +{ + index: 12 + tag: 2 + val: 0 +}, +{ + index: 13 + tag: 2 + val: 0 +}, +{ + index: 14 + tag: 2 + val: 0 +}, +{ + index: 15 + tag: 2 + val: 0 +}, +------------------------------------ +slot &myapp/hap-file-exec&_2 +{ + index: 0 + tag: 0 + val: 2 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +======> strings <====== +"&myapp/hap-file-exec&.#*#main"; "&myapp/hap-file-exec&.#~B=#B"; "@normalized:N&&&myapp/hap-add-file&"; "A"; "prototype"; "test"; +slotNum = 0x3 +.language ECMAScript +.function any &myapp/hap-add-file&.#*#modTest(any a0, any a1, any a2) { +label_1: +label_0: + lda.str @normalized:N&&&bytecodehar1/bytecodehar1-file2&2.0.0 + dynamicimport + tryldglobalbyname 0x0, test + callarg0 0x1 + returnundefined +label_2: +} + +slotNum = 0x1 +.language ECMAScript +.function any &myapp/hap-add-file&.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + definefunc 0x0, &myapp/hap-add-file&.#*#modTest, 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &myapp/hap-add-file&_0 +------------------------------------ +slot &myapp/hap-add-file&_1 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 0 +}, +{ + index: 4 + tag: 2 + val: 0 +}, +{ + index: 5 + tag: 2 + val: 0 +}, +======> strings <====== +"&myapp/hap-add-file&.#*#modTest"; "@normalized:N&&&bytecodehar1/bytecodehar1-file2&2.0.0"; "test"; +slotNum = 0x3 +.language ECMAScript +.function any &sourcehar/sourcehar-file1&2.0.0.#*#test(any a0, any a1, any a2) { +label_1: +label_0: + tryldglobalbyname 0x0, print + sta v0 + lda.str sourcehar.file1.test + sta v1 + lda v0 + callarg1 0x1, v1 + returnundefined +label_2: +} + +slotNum = 0x1 +.language ECMAScript +.function any &sourcehar/sourcehar-file1&2.0.0.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + definefunc 0x0, &sourcehar/sourcehar-file1&2.0.0.#*#test, 0x0 + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &sourcehar/sourcehar-file1&2.0.0_0 +------------------------------------ +slot &sourcehar/sourcehar-file1&2.0.0_1 +{ + index: 0 + tag: 2 + val: 1 +}, +{ + index: 1 + tag: 5 + val: @normalized:N&&&sourcehar/sourcehar-file2&2.0.0 +}, +{ + index: 2 + tag: 2 + val: 1 +}, +{ + index: 3 + tag: 5 + val: test1 +}, +{ + index: 4 + tag: 5 + val: test +}, +{ + index: 5 + tag: 9 + val: 0 +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 1 +}, +{ + index: 8 + tag: 5 + val: test +}, +{ + index: 9 + tag: 5 + val: test +}, +{ + index: 10 + tag: 2 + val: 0 +}, +{ + index: 11 + tag: 2 + val: 0 +}, +======> strings <====== +"&sourcehar/sourcehar-file1&2.0.0.#*#test"; "print"; "sourcehar.file1.test"; +slotNum = 0x3 +.language ECMAScript +.function any &sourcehar/sourcehar-file2&2.0.0.#*#test(any a0, any a1, any a2) { +label_1: +label_0: + tryldglobalbyname 0x0, print + sta v0 + lda.str sourcehar.file2.test + sta v1 + lda v0 + callarg1 0x1, v1 + returnundefined +label_2: +} + +slotNum = 0x1 +.language ECMAScript +.function any &sourcehar/sourcehar-file2&2.0.0.func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + definefunc 0x0, &sourcehar/sourcehar-file2&2.0.0.#*#test, 0x0 + stmodulevar 0x0 + returnundefined +label_2: +} + + +======> literal array buffer <====== +------------------------------------ +slot &sourcehar/sourcehar-file2&2.0.0_0 +------------------------------------ +slot &sourcehar/sourcehar-file2&2.0.0_1 +{ + index: 0 + tag: 2 + val: 0 +}, +{ + index: 1 + tag: 2 + val: 0 +}, +{ + index: 2 + tag: 2 + val: 0 +}, +{ + index: 3 + tag: 2 + val: 1 +}, +{ + index: 4 + tag: 5 + val: test +}, +{ + index: 5 + tag: 5 + val: test +}, +{ + index: 6 + tag: 2 + val: 0 +}, +{ + index: 7 + tag: 2 + val: 0 +}, +======> strings <====== +"&sourcehar/sourcehar-file2&2.0.0.#*#test"; "print"; "sourcehar.file2.test"; diff --git a/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/hap-file-exec.ts b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/hap-file-exec.ts new file mode 100644 index 0000000000..b50023d9ad --- /dev/null +++ b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/hap-file-exec.ts @@ -0,0 +1,26 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { test, __$$ETS_ANNOTATION$$__Anno1, A } from "@normalized:N&&&bytecodehar1/bytecodehar1-file1&2.0.0" + +function main() { + import('@normalized:N&&&myapp/hap-add-file&') + test(); + let a = new A(); +} + + +@__$$ETS_ANNOTATION$$__Anno1({ b: true }) +class B { } \ No newline at end of file diff --git a/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/mod/hap-add-file.ts b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/mod/hap-add-file.ts new file mode 100644 index 0000000000..d06729e3fa --- /dev/null +++ b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/mod/hap-add-file.ts @@ -0,0 +1,20 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +function modTest() { + import('@normalized:N&&&bytecodehar1/bytecodehar1-file2&2.0.0'); + test(); +} \ No newline at end of file diff --git a/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/recordnames.txt b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/recordnames.txt new file mode 100644 index 0000000000..92d7f0e7b6 --- /dev/null +++ b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/recordnames.txt @@ -0,0 +1,8 @@ +bytecodehar1-file1:&bytecodehar1/bytecodehar1-file1&2.0.0 +bytecodehar1-file2:&bytecodehar1/bytecodehar1-file2&2.0.0 +bytecodehar2-file1:&@ohos/bytecodehar2/bytecodehar2-file1&2.0.0 +bytecodehar2-file2:&@ohos/bytecodehar2/bytecodehar2-file2&2.0.0 +sourcehar-file1:&sourcehar/sourcehar-file1&2.0.0 +sourcehar-file2:&sourcehar/sourcehar-file2&2.0.0 +hap-file-exec:&myapp/hap-file-exec& +mod/hap-add-file:&myapp/hap-add-file& diff --git a/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/sourcehar-file1.ts b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/sourcehar-file1.ts new file mode 100644 index 0000000000..f688431373 --- /dev/null +++ b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/sourcehar-file1.ts @@ -0,0 +1,20 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {test as test1} from '@normalized:N&&&sourcehar/sourcehar-file2&2.0.0' + +export function test() { + print('sourcehar.file1.test'); +} \ No newline at end of file diff --git a/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/sourcehar-file2.ts b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/sourcehar-file2.ts new file mode 100644 index 0000000000..7702af0778 --- /dev/null +++ b/es2panda/test/compiler/cache_projects/bytecodehar-annotations-mod-hap-cache-file/sourcehar-file2.ts @@ -0,0 +1,18 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export function test() { + print('sourcehar.file2.test'); +} \ No newline at end of file diff --git a/es2panda/test/config.py b/es2panda/test/config.py index 6e57dedbad..813c555c18 100644 --- a/es2panda/test/config.py +++ b/es2panda/test/config.py @@ -22,7 +22,17 @@ API_VERSION_MAP = { "API12beta2": "12.0.2.0", "API12beta3": "12.0.6.0", "API13": "12.0.6.0", + "API14": "12.0.6.0", + "API15": "12.0.6.0", + "API16": "12.0.6.0", + "API17": "12.0.6.0", + "API18": "13.0.1.0", + "API19": "13.0.1.0", + "API20": "13.0.1.0", } + +ARK_JS_VM_LIST = {"API9", "API10", "API11", "API12beta1", "API12beta3", "API18"} + MIN_SUPPORT_BC_VERSION = "API12beta1" MIX_COMPILE_ENTRY_POINT = "import" diff --git a/es2panda/test/parser/annotations/declaration-3d-array-boolean-expected.txt b/es2panda/test/parser/annotations/declaration-3d-array-boolean-expected.txt index 4c93688056..8c9283391a 100644 --- a/es2panda/test/parser/annotations/declaration-3d-array-boolean-expected.txt +++ b/es2panda/test/parser/annotations/declaration-3d-array-boolean-expected.txt @@ -14,7 +14,7 @@ }, "end": { "line": 16, - "column": 17 + "column": 39 } } }, @@ -190,7 +190,7 @@ "loc": { "start": { "line": 16, - "column": 18 + "column": 40 }, "end": { "line": 18, @@ -224,7 +224,7 @@ }, "end": { "line": 20, - "column": 17 + "column": 39 } } }, @@ -486,7 +486,7 @@ "loc": { "start": { "line": 20, - "column": 18 + "column": 40 }, "end": { "line": 22, @@ -520,7 +520,7 @@ }, "end": { "line": 24, - "column": 17 + "column": 39 } } }, @@ -812,7 +812,7 @@ "loc": { "start": { "line": 24, - "column": 18 + "column": 40 }, "end": { "line": 26, diff --git a/es2panda/test/parser/annotations/declaration-3d-array-boolean.ts b/es2panda/test/parser/annotations/declaration-3d-array-boolean.ts index 8bb5148dc7..b13f16c168 100644 --- a/es2panda/test/parser/annotations/declaration-3d-array-boolean.ts +++ b/es2panda/test/parser/annotations/declaration-3d-array-boolean.ts @@ -13,14 +13,14 @@ * limitations under the License. */ -@interface Anno1 { +@interface __$$ETS_ANNOTATION$$__Anno1 { a: boolean[][][]; } -@interface Anno2 { +@interface __$$ETS_ANNOTATION$$__Anno2 { a: boolean[][][] = [[new Array()]]; } -@interface Anno3 { +@interface __$$ETS_ANNOTATION$$__Anno3 { a: boolean[][][] = [[[true, false], [true, false]]]; } diff --git a/es2panda/test/parser/annotations/declaration-3d-array-enum-number-expected.txt b/es2panda/test/parser/annotations/declaration-3d-array-enum-number-expected.txt index 0a07759fa1..8405fb734e 100644 --- a/es2panda/test/parser/annotations/declaration-3d-array-enum-number-expected.txt +++ b/es2panda/test/parser/annotations/declaration-3d-array-enum-number-expected.txt @@ -126,7 +126,7 @@ }, "end": { "line": 21, - "column": 17 + "column": 39 } } }, @@ -431,7 +431,7 @@ "loc": { "start": { "line": 21, - "column": 18 + "column": 40 }, "end": { "line": 24, @@ -465,7 +465,7 @@ }, "end": { "line": 26, - "column": 17 + "column": 39 } } }, @@ -770,7 +770,7 @@ "loc": { "start": { "line": 26, - "column": 18 + "column": 40 }, "end": { "line": 29, @@ -804,7 +804,7 @@ }, "end": { "line": 31, - "column": 17 + "column": 39 } } }, @@ -1081,7 +1081,7 @@ "loc": { "start": { "line": 31, - "column": 18 + "column": 40 }, "end": { "line": 33, diff --git a/es2panda/test/parser/annotations/declaration-3d-array-enum-number.ts b/es2panda/test/parser/annotations/declaration-3d-array-enum-number.ts index 744a142fe2..4a04e01d3b 100644 --- a/es2panda/test/parser/annotations/declaration-3d-array-enum-number.ts +++ b/es2panda/test/parser/annotations/declaration-3d-array-enum-number.ts @@ -18,16 +18,16 @@ const enum E { B = 314 } -@interface Anno1 { +@interface __$$ETS_ANNOTATION$$__Anno1 { // without initializer in .ets source code with underlying number type a: E[][][] = [[new Array(0)]]; } -@interface Anno2 { +@interface __$$ETS_ANNOTATION$$__Anno2 { // with empty array initializer in .ets source code with underlying number type a: E[][][] = [[new Array(1)]]; } -@interface Anno3 { +@interface __$$ETS_ANNOTATION$$__Anno3 { a: E[][][] = [[[42, 314, 42]]]; } diff --git a/es2panda/test/parser/annotations/declaration-3d-array-enum-string-expected.txt b/es2panda/test/parser/annotations/declaration-3d-array-enum-string-expected.txt index 953a3b9d73..bbbcb10019 100644 --- a/es2panda/test/parser/annotations/declaration-3d-array-enum-string-expected.txt +++ b/es2panda/test/parser/annotations/declaration-3d-array-enum-string-expected.txt @@ -126,7 +126,7 @@ }, "end": { "line": 21, - "column": 17 + "column": 39 } } }, @@ -431,7 +431,7 @@ "loc": { "start": { "line": 21, - "column": 18 + "column": 40 }, "end": { "line": 24, @@ -465,7 +465,7 @@ }, "end": { "line": 26, - "column": 17 + "column": 39 } } }, @@ -770,7 +770,7 @@ "loc": { "start": { "line": 26, - "column": 18 + "column": 40 }, "end": { "line": 29, @@ -804,7 +804,7 @@ }, "end": { "line": 31, - "column": 17 + "column": 39 } } }, @@ -1081,7 +1081,7 @@ "loc": { "start": { "line": 31, - "column": 18 + "column": 40 }, "end": { "line": 33, diff --git a/es2panda/test/parser/annotations/declaration-3d-array-enum-string.ts b/es2panda/test/parser/annotations/declaration-3d-array-enum-string.ts index 8eeef595d0..a24f1a805f 100644 --- a/es2panda/test/parser/annotations/declaration-3d-array-enum-string.ts +++ b/es2panda/test/parser/annotations/declaration-3d-array-enum-string.ts @@ -18,16 +18,16 @@ const enum E { B = "world!" } -@interface Anno1 { +@interface __$$ETS_ANNOTATION$$__Anno1 { // without initializer in .ets source code with underlying string type a: E[][][] = [[new Array(2)]]; } -@interface Anno2 { +@interface __$$ETS_ANNOTATION$$__Anno2 { // with empty array initializer in .ets source code with underlying string type a: E[][][] = [[new Array(3)]]; } -@interface Anno3 { +@interface __$$ETS_ANNOTATION$$__Anno3 { a: E[][][] = [[["Hello", "world!", "Hello"]]]; } diff --git a/es2panda/test/parser/annotations/declaration-3d-array-number-expected.txt b/es2panda/test/parser/annotations/declaration-3d-array-number-expected.txt index 6731c66866..6ba651775b 100644 --- a/es2panda/test/parser/annotations/declaration-3d-array-number-expected.txt +++ b/es2panda/test/parser/annotations/declaration-3d-array-number-expected.txt @@ -14,7 +14,7 @@ }, "end": { "line": 16, - "column": 17 + "column": 39 } } }, @@ -190,7 +190,7 @@ "loc": { "start": { "line": 16, - "column": 18 + "column": 40 }, "end": { "line": 18, @@ -224,7 +224,7 @@ }, "end": { "line": 20, - "column": 17 + "column": 39 } } }, @@ -486,7 +486,7 @@ "loc": { "start": { "line": 20, - "column": 18 + "column": 40 }, "end": { "line": 22, @@ -520,7 +520,7 @@ }, "end": { "line": 24, - "column": 17 + "column": 39 } } }, @@ -840,7 +840,7 @@ "loc": { "start": { "line": 24, - "column": 18 + "column": 40 }, "end": { "line": 26, diff --git a/es2panda/test/parser/annotations/declaration-3d-array-number.ts b/es2panda/test/parser/annotations/declaration-3d-array-number.ts index 9b4c19e954..63d77e8e81 100644 --- a/es2panda/test/parser/annotations/declaration-3d-array-number.ts +++ b/es2panda/test/parser/annotations/declaration-3d-array-number.ts @@ -13,14 +13,14 @@ * limitations under the License. */ -@interface Anno1 { +@interface __$$ETS_ANNOTATION$$__Anno1 { a: number[][][]; } -@interface Anno2 { +@interface __$$ETS_ANNOTATION$$__Anno2 { a: number[][][] = [[new Array()]]; } -@interface Anno3 { +@interface __$$ETS_ANNOTATION$$__Anno3 { a: number[][][] = [[[1, 2, 3], [4, 5, 6]]]; } diff --git a/es2panda/test/parser/annotations/declaration-3d-array-string-expected.txt b/es2panda/test/parser/annotations/declaration-3d-array-string-expected.txt index ab3dd1bc1d..f92907c304 100644 --- a/es2panda/test/parser/annotations/declaration-3d-array-string-expected.txt +++ b/es2panda/test/parser/annotations/declaration-3d-array-string-expected.txt @@ -14,7 +14,7 @@ }, "end": { "line": 16, - "column": 17 + "column": 39 } } }, @@ -190,7 +190,7 @@ "loc": { "start": { "line": 16, - "column": 18 + "column": 40 }, "end": { "line": 18, @@ -224,7 +224,7 @@ }, "end": { "line": 20, - "column": 17 + "column": 39 } } }, @@ -486,7 +486,7 @@ "loc": { "start": { "line": 20, - "column": 18 + "column": 40 }, "end": { "line": 22, @@ -520,7 +520,7 @@ }, "end": { "line": 24, - "column": 17 + "column": 39 } } }, @@ -812,7 +812,7 @@ "loc": { "start": { "line": 24, - "column": 18 + "column": 40 }, "end": { "line": 26, diff --git a/es2panda/test/parser/annotations/declaration-3d-array-string.ts b/es2panda/test/parser/annotations/declaration-3d-array-string.ts index 9d2d477d78..09a27904d4 100644 --- a/es2panda/test/parser/annotations/declaration-3d-array-string.ts +++ b/es2panda/test/parser/annotations/declaration-3d-array-string.ts @@ -13,14 +13,14 @@ * limitations under the License. */ -@interface Anno1 { +@interface __$$ETS_ANNOTATION$$__Anno1 { a: string[][][]; } -@interface Anno2 { +@interface __$$ETS_ANNOTATION$$__Anno2 { a: string[][][] = [[new Array()]]; } -@interface Anno3 { +@interface __$$ETS_ANNOTATION$$__Anno3 { a: string[][][] = [[["hello", "world"], ["hello", "world"]]]; } diff --git a/es2panda/test/parser/annotations/declaration-array-boolean-expected.txt b/es2panda/test/parser/annotations/declaration-array-boolean-expected.txt index 25bca148bd..4d3196200f 100644 --- a/es2panda/test/parser/annotations/declaration-array-boolean-expected.txt +++ b/es2panda/test/parser/annotations/declaration-array-boolean-expected.txt @@ -14,7 +14,7 @@ }, "end": { "line": 16, - "column": 17 + "column": 39 } } }, @@ -164,7 +164,7 @@ "loc": { "start": { "line": 16, - "column": 18 + "column": 40 }, "end": { "line": 18, @@ -198,7 +198,7 @@ }, "end": { "line": 20, - "column": 17 + "column": 39 } } }, @@ -404,7 +404,7 @@ "loc": { "start": { "line": 20, - "column": 18 + "column": 40 }, "end": { "line": 22, @@ -438,7 +438,7 @@ }, "end": { "line": 24, - "column": 17 + "column": 39 } } }, @@ -645,7 +645,7 @@ "loc": { "start": { "line": 24, - "column": 18 + "column": 40 }, "end": { "line": 26, diff --git a/es2panda/test/parser/annotations/declaration-array-boolean.ts b/es2panda/test/parser/annotations/declaration-array-boolean.ts index b5e92f592d..c575410d77 100644 --- a/es2panda/test/parser/annotations/declaration-array-boolean.ts +++ b/es2panda/test/parser/annotations/declaration-array-boolean.ts @@ -13,14 +13,14 @@ * limitations under the License. */ -@interface Anno1 { +@interface __$$ETS_ANNOTATION$$__Anno1 { a: boolean[]; } -@interface Anno2 { +@interface __$$ETS_ANNOTATION$$__Anno2 { a: boolean[] = new Array(); } -@interface Anno3 { +@interface __$$ETS_ANNOTATION$$__Anno3 { a: boolean[] = [true, false, true]; } diff --git a/es2panda/test/parser/annotations/declaration-array-enum-number-expected.txt b/es2panda/test/parser/annotations/declaration-array-enum-number-expected.txt index 2c0dff6197..c54ae5762c 100644 --- a/es2panda/test/parser/annotations/declaration-array-enum-number-expected.txt +++ b/es2panda/test/parser/annotations/declaration-array-enum-number-expected.txt @@ -126,7 +126,7 @@ }, "end": { "line": 21, - "column": 17 + "column": 39 } } }, @@ -375,7 +375,7 @@ "loc": { "start": { "line": 21, - "column": 18 + "column": 40 }, "end": { "line": 24, @@ -409,7 +409,7 @@ }, "end": { "line": 26, - "column": 17 + "column": 39 } } }, @@ -658,7 +658,7 @@ "loc": { "start": { "line": 26, - "column": 18 + "column": 40 }, "end": { "line": 29, @@ -692,7 +692,7 @@ }, "end": { "line": 31, - "column": 17 + "column": 39 } } }, @@ -913,7 +913,7 @@ "loc": { "start": { "line": 31, - "column": 18 + "column": 40 }, "end": { "line": 33, diff --git a/es2panda/test/parser/annotations/declaration-array-enum-number.ts b/es2panda/test/parser/annotations/declaration-array-enum-number.ts index 11b0554711..fe4efedad5 100644 --- a/es2panda/test/parser/annotations/declaration-array-enum-number.ts +++ b/es2panda/test/parser/annotations/declaration-array-enum-number.ts @@ -18,16 +18,16 @@ const enum E { B = 314 } -@interface Anno1 { +@interface __$$ETS_ANNOTATION$$__Anno1 { // without initializer in .ets source code with underlying number type a: E[] = new Array(0); } -@interface Anno2 { +@interface __$$ETS_ANNOTATION$$__Anno2 { // with empty array initializer in .ets source code with underlying number type a: E[] = new Array(1); } -@interface Anno3 { +@interface __$$ETS_ANNOTATION$$__Anno3 { a: E[] = [42, 314, 42]; } diff --git a/es2panda/test/parser/annotations/declaration-array-enum-string-expected.txt b/es2panda/test/parser/annotations/declaration-array-enum-string-expected.txt index ee84947486..e598eac92c 100644 --- a/es2panda/test/parser/annotations/declaration-array-enum-string-expected.txt +++ b/es2panda/test/parser/annotations/declaration-array-enum-string-expected.txt @@ -126,7 +126,7 @@ }, "end": { "line": 21, - "column": 17 + "column": 39 } } }, @@ -375,7 +375,7 @@ "loc": { "start": { "line": 21, - "column": 18 + "column": 40 }, "end": { "line": 24, @@ -409,7 +409,7 @@ }, "end": { "line": 26, - "column": 17 + "column": 39 } } }, @@ -658,7 +658,7 @@ "loc": { "start": { "line": 26, - "column": 18 + "column": 40 }, "end": { "line": 29, @@ -692,7 +692,7 @@ }, "end": { "line": 31, - "column": 17 + "column": 39 } } }, @@ -913,7 +913,7 @@ "loc": { "start": { "line": 31, - "column": 18 + "column": 40 }, "end": { "line": 33, diff --git a/es2panda/test/parser/annotations/declaration-array-enum-string.ts b/es2panda/test/parser/annotations/declaration-array-enum-string.ts index a55745424c..39e7411e1a 100644 --- a/es2panda/test/parser/annotations/declaration-array-enum-string.ts +++ b/es2panda/test/parser/annotations/declaration-array-enum-string.ts @@ -18,16 +18,16 @@ const enum E { B = "world!" } -@interface Anno1 { +@interface __$$ETS_ANNOTATION$$__Anno1 { // without initializer in .ets source code with underlying string type a: E[] = new Array(2); } -@interface Anno2 { +@interface __$$ETS_ANNOTATION$$__Anno2 { // with empty array initializer in .ets source code with underlying string type a: E[] = new Array(3); } -@interface Anno3 { +@interface __$$ETS_ANNOTATION$$__Anno3 { a: E[] = ["Hello", "world!", "Hello"]; } diff --git a/es2panda/test/parser/annotations/declaration-array-number-expected.txt b/es2panda/test/parser/annotations/declaration-array-number-expected.txt index b977d89047..b157c668a3 100644 --- a/es2panda/test/parser/annotations/declaration-array-number-expected.txt +++ b/es2panda/test/parser/annotations/declaration-array-number-expected.txt @@ -14,7 +14,7 @@ }, "end": { "line": 16, - "column": 17 + "column": 39 } } }, @@ -164,7 +164,7 @@ "loc": { "start": { "line": 16, - "column": 18 + "column": 40 }, "end": { "line": 18, @@ -198,7 +198,7 @@ }, "end": { "line": 20, - "column": 17 + "column": 39 } } }, @@ -404,7 +404,7 @@ "loc": { "start": { "line": 20, - "column": 18 + "column": 40 }, "end": { "line": 22, @@ -438,7 +438,7 @@ }, "end": { "line": 24, - "column": 17 + "column": 39 } } }, @@ -645,7 +645,7 @@ "loc": { "start": { "line": 24, - "column": 18 + "column": 40 }, "end": { "line": 26, diff --git a/es2panda/test/parser/annotations/declaration-array-number.ts b/es2panda/test/parser/annotations/declaration-array-number.ts index 20b83d1843..e2a8a55672 100644 --- a/es2panda/test/parser/annotations/declaration-array-number.ts +++ b/es2panda/test/parser/annotations/declaration-array-number.ts @@ -13,14 +13,14 @@ * limitations under the License. */ -@interface Anno1 { +@interface __$$ETS_ANNOTATION$$__Anno1 { a: number[]; } -@interface Anno2 { +@interface __$$ETS_ANNOTATION$$__Anno2 { a: number[] = new Array(); } -@interface Anno3 { +@interface __$$ETS_ANNOTATION$$__Anno3 { a: number[] = [1, 2, 3]; } diff --git a/es2panda/test/parser/annotations/declaration-array-string-expected.txt b/es2panda/test/parser/annotations/declaration-array-string-expected.txt index 280bb6e06c..80e6ca76fc 100644 --- a/es2panda/test/parser/annotations/declaration-array-string-expected.txt +++ b/es2panda/test/parser/annotations/declaration-array-string-expected.txt @@ -14,7 +14,7 @@ }, "end": { "line": 16, - "column": 17 + "column": 39 } } }, @@ -164,7 +164,7 @@ "loc": { "start": { "line": 16, - "column": 18 + "column": 40 }, "end": { "line": 18, @@ -198,7 +198,7 @@ }, "end": { "line": 20, - "column": 17 + "column": 39 } } }, @@ -404,7 +404,7 @@ "loc": { "start": { "line": 20, - "column": 18 + "column": 40 }, "end": { "line": 22, @@ -438,7 +438,7 @@ }, "end": { "line": 24, - "column": 17 + "column": 39 } } }, @@ -645,7 +645,7 @@ "loc": { "start": { "line": 24, - "column": 18 + "column": 40 }, "end": { "line": 26, diff --git a/es2panda/test/parser/annotations/declaration-array-string.ts b/es2panda/test/parser/annotations/declaration-array-string.ts index 69cfe97efc..2de6642e24 100644 --- a/es2panda/test/parser/annotations/declaration-array-string.ts +++ b/es2panda/test/parser/annotations/declaration-array-string.ts @@ -13,14 +13,14 @@ * limitations under the License. */ -@interface Anno1 { +@interface __$$ETS_ANNOTATION$$__Anno1 { a: string[]; } -@interface Anno2 { +@interface __$$ETS_ANNOTATION$$__Anno2 { a: string[] = new Array(); } -@interface Anno3 { +@interface __$$ETS_ANNOTATION$$__Anno3 { a: string[] = ["Hello", "world", "!"]; } diff --git a/es2panda/test/parser/annotations/declaration-boolean-expected.txt b/es2panda/test/parser/annotations/declaration-boolean-expected.txt index 3ad0c64497..55945c1f9b 100644 --- a/es2panda/test/parser/annotations/declaration-boolean-expected.txt +++ b/es2panda/test/parser/annotations/declaration-boolean-expected.txt @@ -14,7 +14,7 @@ }, "end": { "line": 16, - "column": 17 + "column": 39 } } }, @@ -151,7 +151,7 @@ "loc": { "start": { "line": 16, - "column": 18 + "column": 40 }, "end": { "line": 18, @@ -185,7 +185,7 @@ }, "end": { "line": 20, - "column": 17 + "column": 39 } } }, @@ -336,7 +336,7 @@ "loc": { "start": { "line": 20, - "column": 18 + "column": 40 }, "end": { "line": 22, diff --git a/es2panda/test/parser/annotations/declaration-boolean.ts b/es2panda/test/parser/annotations/declaration-boolean.ts index e9bf814b7e..086025dbd9 100644 --- a/es2panda/test/parser/annotations/declaration-boolean.ts +++ b/es2panda/test/parser/annotations/declaration-boolean.ts @@ -13,10 +13,10 @@ * limitations under the License. */ -@interface Anno1 { +@interface __$$ETS_ANNOTATION$$__Anno1 { a: boolean; } -@interface Anno2 { +@interface __$$ETS_ANNOTATION$$__Anno2 { a: boolean = true; } \ No newline at end of file diff --git a/es2panda/test/parser/annotations/declaration-combination-expected.txt b/es2panda/test/parser/annotations/declaration-combination-expected.txt index 43531af2d5..5fac4e23ca 100644 --- a/es2panda/test/parser/annotations/declaration-combination-expected.txt +++ b/es2panda/test/parser/annotations/declaration-combination-expected.txt @@ -279,7 +279,7 @@ }, "end": { "line": 27, - "column": 16 + "column": 38 } } }, @@ -1416,7 +1416,7 @@ "loc": { "start": { "line": 27, - "column": 17 + "column": 39 }, "end": { "line": 38, diff --git a/es2panda/test/parser/annotations/declaration-combination.ts b/es2panda/test/parser/annotations/declaration-combination.ts index 79cb3c6032..2c23ae9d6e 100644 --- a/es2panda/test/parser/annotations/declaration-combination.ts +++ b/es2panda/test/parser/annotations/declaration-combination.ts @@ -24,7 +24,7 @@ const enum E1 { B = "world" } -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { a: number b: number[] = [13, 10] c: string diff --git a/es2panda/test/parser/annotations/declaration-empty-expected.txt b/es2panda/test/parser/annotations/declaration-empty-expected.txt index 2d482ef3bf..eabbd5ebed 100644 --- a/es2panda/test/parser/annotations/declaration-empty-expected.txt +++ b/es2panda/test/parser/annotations/declaration-empty-expected.txt @@ -14,7 +14,7 @@ }, "end": { "line": 16, - "column": 16 + "column": 38 } } }, @@ -95,7 +95,7 @@ }, "end": { "line": 16, - "column": 19 + "column": 41 } } }, @@ -104,11 +104,11 @@ "loc": { "start": { "line": 16, - "column": 17 + "column": 39 }, "end": { "line": 16, - "column": 19 + "column": 41 } } }, @@ -121,7 +121,7 @@ }, "end": { "line": 16, - "column": 19 + "column": 41 } } } diff --git a/es2panda/test/parser/annotations/declaration-empty.ts b/es2panda/test/parser/annotations/declaration-empty.ts index 4d205f1d28..80ae4e05b8 100644 --- a/es2panda/test/parser/annotations/declaration-empty.ts +++ b/es2panda/test/parser/annotations/declaration-empty.ts @@ -13,4 +13,4 @@ * limitations under the License. */ -@interface Anno {} +@interface __$$ETS_ANNOTATION$$__Anno {} diff --git a/es2panda/test/parser/annotations/declaration-enum-number-expected.txt b/es2panda/test/parser/annotations/declaration-enum-number-expected.txt index 5b5801e6bb..2861338efa 100644 --- a/es2panda/test/parser/annotations/declaration-enum-number-expected.txt +++ b/es2panda/test/parser/annotations/declaration-enum-number-expected.txt @@ -126,7 +126,7 @@ }, "end": { "line": 21, - "column": 17 + "column": 39 } } }, @@ -346,7 +346,7 @@ "loc": { "start": { "line": 21, - "column": 18 + "column": 40 }, "end": { "line": 24, @@ -380,7 +380,7 @@ }, "end": { "line": 26, - "column": 17 + "column": 39 } } }, @@ -545,7 +545,7 @@ "loc": { "start": { "line": 26, - "column": 18 + "column": 40 }, "end": { "line": 28, diff --git a/es2panda/test/parser/annotations/declaration-enum-number.ts b/es2panda/test/parser/annotations/declaration-enum-number.ts index 095d97c985..74f8289004 100644 --- a/es2panda/test/parser/annotations/declaration-enum-number.ts +++ b/es2panda/test/parser/annotations/declaration-enum-number.ts @@ -18,11 +18,11 @@ const enum E { B = 314 } -@interface Anno1 { +@interface __$$ETS_ANNOTATION$$__Anno1 { // No initializer with underlying type number a: E = new Number(0) as number; } -@interface Anno2 { +@interface __$$ETS_ANNOTATION$$__Anno2 { a: E = 42; } \ No newline at end of file diff --git a/es2panda/test/parser/annotations/declaration-enum-string-expected.txt b/es2panda/test/parser/annotations/declaration-enum-string-expected.txt index 090667cd36..b259e706c7 100644 --- a/es2panda/test/parser/annotations/declaration-enum-string-expected.txt +++ b/es2panda/test/parser/annotations/declaration-enum-string-expected.txt @@ -126,7 +126,7 @@ }, "end": { "line": 21, - "column": 17 + "column": 39 } } }, @@ -277,7 +277,7 @@ "loc": { "start": { "line": 21, - "column": 18 + "column": 40 }, "end": { "line": 24, @@ -311,7 +311,7 @@ }, "end": { "line": 26, - "column": 17 + "column": 39 } } }, @@ -476,7 +476,7 @@ "loc": { "start": { "line": 26, - "column": 18 + "column": 40 }, "end": { "line": 28, diff --git a/es2panda/test/parser/annotations/declaration-enum-string.ts b/es2panda/test/parser/annotations/declaration-enum-string.ts index 668b13ba51..e8f77e41a2 100644 --- a/es2panda/test/parser/annotations/declaration-enum-string.ts +++ b/es2panda/test/parser/annotations/declaration-enum-string.ts @@ -18,11 +18,11 @@ const enum E { B = "world!" } -@interface Anno1 { +@interface __$$ETS_ANNOTATION$$__Anno1 { // No initializer with underlying type string a: E; } -@interface Anno2 { +@interface __$$ETS_ANNOTATION$$__Anno2 { a: E = "Hello"; } \ No newline at end of file diff --git a/es2panda/test/parser/annotations/declaration-number-expected.txt b/es2panda/test/parser/annotations/declaration-number-expected.txt index d692da4099..04bc5cdf91 100644 --- a/es2panda/test/parser/annotations/declaration-number-expected.txt +++ b/es2panda/test/parser/annotations/declaration-number-expected.txt @@ -14,7 +14,7 @@ }, "end": { "line": 16, - "column": 17 + "column": 39 } } }, @@ -151,7 +151,7 @@ "loc": { "start": { "line": 16, - "column": 18 + "column": 40 }, "end": { "line": 18, @@ -185,7 +185,7 @@ }, "end": { "line": 20, - "column": 17 + "column": 39 } } }, @@ -336,7 +336,7 @@ "loc": { "start": { "line": 20, - "column": 18 + "column": 40 }, "end": { "line": 22, diff --git a/es2panda/test/parser/annotations/declaration-number.ts b/es2panda/test/parser/annotations/declaration-number.ts index e5c48f9af6..340bf07751 100644 --- a/es2panda/test/parser/annotations/declaration-number.ts +++ b/es2panda/test/parser/annotations/declaration-number.ts @@ -13,10 +13,10 @@ * limitations under the License. */ -@interface Anno1 { +@interface __$$ETS_ANNOTATION$$__Anno1 { a: number; } -@interface Anno2 { +@interface __$$ETS_ANNOTATION$$__Anno2 { a: number = 42; } \ No newline at end of file diff --git a/es2panda/test/parser/annotations/declaration-string-expected.txt b/es2panda/test/parser/annotations/declaration-string-expected.txt index 45fdfa8882..e1d5699252 100644 --- a/es2panda/test/parser/annotations/declaration-string-expected.txt +++ b/es2panda/test/parser/annotations/declaration-string-expected.txt @@ -14,7 +14,7 @@ }, "end": { "line": 16, - "column": 17 + "column": 39 } } }, @@ -151,7 +151,7 @@ "loc": { "start": { "line": 16, - "column": 18 + "column": 40 }, "end": { "line": 18, @@ -185,7 +185,7 @@ }, "end": { "line": 20, - "column": 17 + "column": 39 } } }, @@ -336,7 +336,7 @@ "loc": { "start": { "line": 20, - "column": 18 + "column": 40 }, "end": { "line": 22, diff --git a/es2panda/test/parser/annotations/declaration-string.ts b/es2panda/test/parser/annotations/declaration-string.ts index 2f67dfdc93..52e9959461 100644 --- a/es2panda/test/parser/annotations/declaration-string.ts +++ b/es2panda/test/parser/annotations/declaration-string.ts @@ -13,10 +13,10 @@ * limitations under the License. */ -@interface Anno1 { +@interface __$$ETS_ANNOTATION$$__Anno1 { a: string; } -@interface Anno2 { +@interface __$$ETS_ANNOTATION$$__Anno2 { a: string = "Hello world!"; } \ No newline at end of file diff --git a/es2panda/test/parser/annotations/declaration-usage-3d-array-boolean-expected.txt b/es2panda/test/parser/annotations/declaration-usage-3d-array-boolean-expected.txt index a4e4f5d1e8..22b62cab12 100644 --- a/es2panda/test/parser/annotations/declaration-usage-3d-array-boolean-expected.txt +++ b/es2panda/test/parser/annotations/declaration-usage-3d-array-boolean-expected.txt @@ -14,7 +14,7 @@ }, "end": { "line": 16, - "column": 16 + "column": 38 } } }, @@ -190,7 +190,7 @@ "loc": { "start": { "line": 16, - "column": 17 + "column": 39 }, "end": { "line": 18, @@ -304,7 +304,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno", + "name": "Anno", "loc": { "start": { "line": 20, @@ -563,7 +563,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno", + "name": "Anno", "loc": { "start": { "line": 22, diff --git a/es2panda/test/parser/annotations/declaration-usage-3d-array-boolean.ts b/es2panda/test/parser/annotations/declaration-usage-3d-array-boolean.ts index b228a7be88..e707f942b5 100644 --- a/es2panda/test/parser/annotations/declaration-usage-3d-array-boolean.ts +++ b/es2panda/test/parser/annotations/declaration-usage-3d-array-boolean.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { a: boolean[][][]; } diff --git a/es2panda/test/parser/annotations/declaration-usage-3d-array-enum-number-expected.txt b/es2panda/test/parser/annotations/declaration-usage-3d-array-enum-number-expected.txt index 2dbeae8061..2d65b1e683 100644 --- a/es2panda/test/parser/annotations/declaration-usage-3d-array-enum-number-expected.txt +++ b/es2panda/test/parser/annotations/declaration-usage-3d-array-enum-number-expected.txt @@ -126,7 +126,7 @@ }, "end": { "line": 21, - "column": 16 + "column": 38 } } }, @@ -431,7 +431,7 @@ "loc": { "start": { "line": 21, - "column": 17 + "column": 39 }, "end": { "line": 23, @@ -545,7 +545,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno", + "name": "Anno", "loc": { "start": { "line": 25, @@ -804,7 +804,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno", + "name": "Anno", "loc": { "start": { "line": 27, diff --git a/es2panda/test/parser/annotations/declaration-usage-3d-array-enum-number.ts b/es2panda/test/parser/annotations/declaration-usage-3d-array-enum-number.ts index 112d363eaa..7a8eb2c549 100644 --- a/es2panda/test/parser/annotations/declaration-usage-3d-array-enum-number.ts +++ b/es2panda/test/parser/annotations/declaration-usage-3d-array-enum-number.ts @@ -18,7 +18,7 @@ const enum E { B = 2 } -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { a: E[][][] = [[new Array(0)]]; } diff --git a/es2panda/test/parser/annotations/declaration-usage-3d-array-enum-string-expected.txt b/es2panda/test/parser/annotations/declaration-usage-3d-array-enum-string-expected.txt index 8911a2388b..6835399a7b 100644 --- a/es2panda/test/parser/annotations/declaration-usage-3d-array-enum-string-expected.txt +++ b/es2panda/test/parser/annotations/declaration-usage-3d-array-enum-string-expected.txt @@ -126,7 +126,7 @@ }, "end": { "line": 21, - "column": 16 + "column": 38 } } }, @@ -431,7 +431,7 @@ "loc": { "start": { "line": 21, - "column": 17 + "column": 39 }, "end": { "line": 23, @@ -545,7 +545,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno", + "name": "Anno", "loc": { "start": { "line": 25, @@ -804,7 +804,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno", + "name": "Anno", "loc": { "start": { "line": 27, diff --git a/es2panda/test/parser/annotations/declaration-usage-3d-array-enum-string.ts b/es2panda/test/parser/annotations/declaration-usage-3d-array-enum-string.ts index 3ea8b4242b..175a0dcb7a 100644 --- a/es2panda/test/parser/annotations/declaration-usage-3d-array-enum-string.ts +++ b/es2panda/test/parser/annotations/declaration-usage-3d-array-enum-string.ts @@ -18,7 +18,7 @@ const enum E { B = "world" } -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { a: E[][][] = [[new Array(2)]]; } diff --git a/es2panda/test/parser/annotations/declaration-usage-3d-array-number-expected.txt b/es2panda/test/parser/annotations/declaration-usage-3d-array-number-expected.txt index c53855fdb4..c3b2c24a2a 100644 --- a/es2panda/test/parser/annotations/declaration-usage-3d-array-number-expected.txt +++ b/es2panda/test/parser/annotations/declaration-usage-3d-array-number-expected.txt @@ -14,7 +14,7 @@ }, "end": { "line": 16, - "column": 16 + "column": 38 } } }, @@ -190,7 +190,7 @@ "loc": { "start": { "line": 16, - "column": 17 + "column": 39 }, "end": { "line": 18, @@ -304,7 +304,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno", + "name": "Anno", "loc": { "start": { "line": 20, @@ -563,7 +563,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno", + "name": "Anno", "loc": { "start": { "line": 22, diff --git a/es2panda/test/parser/annotations/declaration-usage-3d-array-number.ts b/es2panda/test/parser/annotations/declaration-usage-3d-array-number.ts index 9b32dad4ff..94b2ec54c9 100644 --- a/es2panda/test/parser/annotations/declaration-usage-3d-array-number.ts +++ b/es2panda/test/parser/annotations/declaration-usage-3d-array-number.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { a: number[][][]; } diff --git a/es2panda/test/parser/annotations/declaration-usage-3d-array-string-expected.txt b/es2panda/test/parser/annotations/declaration-usage-3d-array-string-expected.txt index a2d1090634..7c40821076 100644 --- a/es2panda/test/parser/annotations/declaration-usage-3d-array-string-expected.txt +++ b/es2panda/test/parser/annotations/declaration-usage-3d-array-string-expected.txt @@ -14,7 +14,7 @@ }, "end": { "line": 16, - "column": 16 + "column": 38 } } }, @@ -190,7 +190,7 @@ "loc": { "start": { "line": 16, - "column": 17 + "column": 39 }, "end": { "line": 18, @@ -304,7 +304,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno", + "name": "Anno", "loc": { "start": { "line": 20, @@ -563,7 +563,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno", + "name": "Anno", "loc": { "start": { "line": 22, diff --git a/es2panda/test/parser/annotations/declaration-usage-3d-array-string.ts b/es2panda/test/parser/annotations/declaration-usage-3d-array-string.ts index 8bdbb7118e..37e8437d72 100644 --- a/es2panda/test/parser/annotations/declaration-usage-3d-array-string.ts +++ b/es2panda/test/parser/annotations/declaration-usage-3d-array-string.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { a: string[][][]; } diff --git a/es2panda/test/parser/annotations/declaration-usage-array-boolean-expected.txt b/es2panda/test/parser/annotations/declaration-usage-array-boolean-expected.txt index 7588f64ce7..0fe8d00444 100644 --- a/es2panda/test/parser/annotations/declaration-usage-array-boolean-expected.txt +++ b/es2panda/test/parser/annotations/declaration-usage-array-boolean-expected.txt @@ -14,7 +14,7 @@ }, "end": { "line": 16, - "column": 16 + "column": 38 } } }, @@ -164,7 +164,7 @@ "loc": { "start": { "line": 16, - "column": 17 + "column": 39 }, "end": { "line": 18, @@ -278,7 +278,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno", + "name": "Anno", "loc": { "start": { "line": 20, @@ -507,7 +507,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno", + "name": "Anno", "loc": { "start": { "line": 22, diff --git a/es2panda/test/parser/annotations/declaration-usage-array-boolean.ts b/es2panda/test/parser/annotations/declaration-usage-array-boolean.ts index 06ae0c9957..cd8fece827 100644 --- a/es2panda/test/parser/annotations/declaration-usage-array-boolean.ts +++ b/es2panda/test/parser/annotations/declaration-usage-array-boolean.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { a: boolean[]; } diff --git a/es2panda/test/parser/annotations/declaration-usage-array-enum-number-expected.txt b/es2panda/test/parser/annotations/declaration-usage-array-enum-number-expected.txt index ac78e91743..1cf2806754 100644 --- a/es2panda/test/parser/annotations/declaration-usage-array-enum-number-expected.txt +++ b/es2panda/test/parser/annotations/declaration-usage-array-enum-number-expected.txt @@ -126,7 +126,7 @@ }, "end": { "line": 21, - "column": 16 + "column": 38 } } }, @@ -375,7 +375,7 @@ "loc": { "start": { "line": 21, - "column": 17 + "column": 39 }, "end": { "line": 23, @@ -489,7 +489,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno", + "name": "Anno", "loc": { "start": { "line": 25, @@ -718,7 +718,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno", + "name": "Anno", "loc": { "start": { "line": 27, diff --git a/es2panda/test/parser/annotations/declaration-usage-array-enum-number.ts b/es2panda/test/parser/annotations/declaration-usage-array-enum-number.ts index 801fefe3f0..0524e6a240 100644 --- a/es2panda/test/parser/annotations/declaration-usage-array-enum-number.ts +++ b/es2panda/test/parser/annotations/declaration-usage-array-enum-number.ts @@ -18,7 +18,7 @@ const enum E { B = 2, } -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { a: E[] = new Array(0); } diff --git a/es2panda/test/parser/annotations/declaration-usage-array-enum-string-expected.txt b/es2panda/test/parser/annotations/declaration-usage-array-enum-string-expected.txt index b2cc2f5d77..99c0d05521 100644 --- a/es2panda/test/parser/annotations/declaration-usage-array-enum-string-expected.txt +++ b/es2panda/test/parser/annotations/declaration-usage-array-enum-string-expected.txt @@ -126,7 +126,7 @@ }, "end": { "line": 21, - "column": 16 + "column": 38 } } }, @@ -375,7 +375,7 @@ "loc": { "start": { "line": 21, - "column": 17 + "column": 39 }, "end": { "line": 23, @@ -489,7 +489,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno", + "name": "Anno", "loc": { "start": { "line": 25, @@ -718,7 +718,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno", + "name": "Anno", "loc": { "start": { "line": 27, diff --git a/es2panda/test/parser/annotations/declaration-usage-array-enum-string.ts b/es2panda/test/parser/annotations/declaration-usage-array-enum-string.ts index aa3bd9c9fb..52742a3241 100644 --- a/es2panda/test/parser/annotations/declaration-usage-array-enum-string.ts +++ b/es2panda/test/parser/annotations/declaration-usage-array-enum-string.ts @@ -18,7 +18,7 @@ const enum E { B = "world", } -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { a: E[] = new Array(2); } diff --git a/es2panda/test/parser/annotations/declaration-usage-array-number-expected.txt b/es2panda/test/parser/annotations/declaration-usage-array-number-expected.txt index ffb3336979..1dacb954aa 100644 --- a/es2panda/test/parser/annotations/declaration-usage-array-number-expected.txt +++ b/es2panda/test/parser/annotations/declaration-usage-array-number-expected.txt @@ -14,7 +14,7 @@ }, "end": { "line": 16, - "column": 16 + "column": 38 } } }, @@ -164,7 +164,7 @@ "loc": { "start": { "line": 16, - "column": 17 + "column": 39 }, "end": { "line": 18, @@ -278,7 +278,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno", + "name": "Anno", "loc": { "start": { "line": 20, @@ -507,7 +507,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno", + "name": "Anno", "loc": { "start": { "line": 22, diff --git a/es2panda/test/parser/annotations/declaration-usage-array-number.ts b/es2panda/test/parser/annotations/declaration-usage-array-number.ts index 47fc593175..995e9a0634 100644 --- a/es2panda/test/parser/annotations/declaration-usage-array-number.ts +++ b/es2panda/test/parser/annotations/declaration-usage-array-number.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { a: number[]; } diff --git a/es2panda/test/parser/annotations/declaration-usage-array-string-expected.txt b/es2panda/test/parser/annotations/declaration-usage-array-string-expected.txt index 78da22a43a..f9baa7b888 100644 --- a/es2panda/test/parser/annotations/declaration-usage-array-string-expected.txt +++ b/es2panda/test/parser/annotations/declaration-usage-array-string-expected.txt @@ -14,7 +14,7 @@ }, "end": { "line": 16, - "column": 16 + "column": 38 } } }, @@ -164,7 +164,7 @@ "loc": { "start": { "line": 16, - "column": 17 + "column": 39 }, "end": { "line": 18, @@ -278,7 +278,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno", + "name": "Anno", "loc": { "start": { "line": 20, @@ -507,7 +507,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno", + "name": "Anno", "loc": { "start": { "line": 22, diff --git a/es2panda/test/parser/annotations/declaration-usage-array-string.ts b/es2panda/test/parser/annotations/declaration-usage-array-string.ts index c14f9d9d8f..c00fe674fc 100644 --- a/es2panda/test/parser/annotations/declaration-usage-array-string.ts +++ b/es2panda/test/parser/annotations/declaration-usage-array-string.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { a: string[]; } diff --git a/es2panda/test/parser/annotations/declaration-usage-boolean-expected.txt b/es2panda/test/parser/annotations/declaration-usage-boolean-expected.txt index b77604f15c..3b769f56fa 100644 --- a/es2panda/test/parser/annotations/declaration-usage-boolean-expected.txt +++ b/es2panda/test/parser/annotations/declaration-usage-boolean-expected.txt @@ -14,7 +14,7 @@ }, "end": { "line": 16, - "column": 16 + "column": 38 } } }, @@ -151,7 +151,7 @@ "loc": { "start": { "line": 16, - "column": 17 + "column": 39 }, "end": { "line": 18, @@ -265,7 +265,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno", + "name": "Anno", "loc": { "start": { "line": 20, @@ -451,7 +451,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno", + "name": "Anno", "loc": { "start": { "line": 22, diff --git a/es2panda/test/parser/annotations/declaration-usage-boolean.ts b/es2panda/test/parser/annotations/declaration-usage-boolean.ts index b47a207848..3e7da49918 100644 --- a/es2panda/test/parser/annotations/declaration-usage-boolean.ts +++ b/es2panda/test/parser/annotations/declaration-usage-boolean.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { a: boolean; } diff --git a/es2panda/test/parser/annotations/declaration-usage-combination-expected.txt b/es2panda/test/parser/annotations/declaration-usage-combination-expected.txt index 22dba78913..c0ec68a50c 100644 --- a/es2panda/test/parser/annotations/declaration-usage-combination-expected.txt +++ b/es2panda/test/parser/annotations/declaration-usage-combination-expected.txt @@ -279,7 +279,7 @@ }, "end": { "line": 27, - "column": 16 + "column": 38 } } }, @@ -1416,7 +1416,7 @@ "loc": { "start": { "line": 27, - "column": 17 + "column": 39 }, "end": { "line": 38, @@ -1530,7 +1530,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno", + "name": "Anno", "loc": { "start": { "line": 40, @@ -2527,7 +2527,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno", + "name": "Anno", "loc": { "start": { "line": 42, diff --git a/es2panda/test/parser/annotations/declaration-usage-combination.ts b/es2panda/test/parser/annotations/declaration-usage-combination.ts index 16b861ff38..ffac927a75 100644 --- a/es2panda/test/parser/annotations/declaration-usage-combination.ts +++ b/es2panda/test/parser/annotations/declaration-usage-combination.ts @@ -24,7 +24,7 @@ const enum E1 { B = "world" } -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { a: number b: number[] = [13, 10] c: string diff --git a/es2panda/test/parser/annotations/declaration-usage-empty-expected.txt b/es2panda/test/parser/annotations/declaration-usage-empty-expected.txt index 4ab2bc897c..06af843949 100644 --- a/es2panda/test/parser/annotations/declaration-usage-empty-expected.txt +++ b/es2panda/test/parser/annotations/declaration-usage-empty-expected.txt @@ -14,7 +14,7 @@ }, "end": { "line": 16, - "column": 16 + "column": 38 } } }, @@ -95,7 +95,7 @@ }, "end": { "line": 16, - "column": 19 + "column": 41 } } }, @@ -104,11 +104,11 @@ "loc": { "start": { "line": 16, - "column": 17 + "column": 39 }, "end": { "line": 16, - "column": 19 + "column": 41 } } }, @@ -121,7 +121,7 @@ }, "end": { "line": 16, - "column": 19 + "column": 41 } } }, @@ -216,7 +216,7 @@ "type": "Annotation", "expression": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno", + "name": "Anno", "loc": { "start": { "line": 18, @@ -328,7 +328,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno", + "name": "Anno", "loc": { "start": { "line": 20, @@ -452,7 +452,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno", + "name": "Anno", "loc": { "start": { "line": 23, diff --git a/es2panda/test/parser/annotations/declaration-usage-empty.ts b/es2panda/test/parser/annotations/declaration-usage-empty.ts index badbc9745a..b781add198 100644 --- a/es2panda/test/parser/annotations/declaration-usage-empty.ts +++ b/es2panda/test/parser/annotations/declaration-usage-empty.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -@interface Anno {} +@interface __$$ETS_ANNOTATION$$__Anno {} @__$$ETS_ANNOTATION$$__Anno class A { diff --git a/es2panda/test/parser/annotations/declaration-usage-enum-number-expected.txt b/es2panda/test/parser/annotations/declaration-usage-enum-number-expected.txt index 0f2c03ff8e..08708ed1c4 100644 --- a/es2panda/test/parser/annotations/declaration-usage-enum-number-expected.txt +++ b/es2panda/test/parser/annotations/declaration-usage-enum-number-expected.txt @@ -126,7 +126,7 @@ }, "end": { "line": 21, - "column": 16 + "column": 38 } } }, @@ -346,7 +346,7 @@ "loc": { "start": { "line": 21, - "column": 17 + "column": 39 }, "end": { "line": 23, @@ -460,7 +460,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno", + "name": "Anno", "loc": { "start": { "line": 25, @@ -646,7 +646,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno", + "name": "Anno", "loc": { "start": { "line": 27, diff --git a/es2panda/test/parser/annotations/declaration-usage-enum-number.ts b/es2panda/test/parser/annotations/declaration-usage-enum-number.ts index 693f1476e1..c296d79b90 100644 --- a/es2panda/test/parser/annotations/declaration-usage-enum-number.ts +++ b/es2panda/test/parser/annotations/declaration-usage-enum-number.ts @@ -18,7 +18,7 @@ const enum E { B = 2 } -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { a: E = new Number(0) as number; } diff --git a/es2panda/test/parser/annotations/declaration-usage-enum-string-expected.txt b/es2panda/test/parser/annotations/declaration-usage-enum-string-expected.txt index 56ae1cc18a..1a8d1d292a 100644 --- a/es2panda/test/parser/annotations/declaration-usage-enum-string-expected.txt +++ b/es2panda/test/parser/annotations/declaration-usage-enum-string-expected.txt @@ -126,7 +126,7 @@ }, "end": { "line": 21, - "column": 16 + "column": 38 } } }, @@ -277,7 +277,7 @@ "loc": { "start": { "line": 21, - "column": 17 + "column": 39 }, "end": { "line": 23, @@ -391,7 +391,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno", + "name": "Anno", "loc": { "start": { "line": 25, @@ -577,7 +577,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno", + "name": "Anno", "loc": { "start": { "line": 27, diff --git a/es2panda/test/parser/annotations/declaration-usage-enum-string.ts b/es2panda/test/parser/annotations/declaration-usage-enum-string.ts index d9c8f8e047..320500abe9 100644 --- a/es2panda/test/parser/annotations/declaration-usage-enum-string.ts +++ b/es2panda/test/parser/annotations/declaration-usage-enum-string.ts @@ -18,7 +18,7 @@ const enum E { B = "world" } -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { a: E; } diff --git a/es2panda/test/parser/annotations/declaration-usage-number-expected.txt b/es2panda/test/parser/annotations/declaration-usage-number-expected.txt index 96d98fe81f..e43e54db0e 100644 --- a/es2panda/test/parser/annotations/declaration-usage-number-expected.txt +++ b/es2panda/test/parser/annotations/declaration-usage-number-expected.txt @@ -14,7 +14,7 @@ }, "end": { "line": 16, - "column": 16 + "column": 38 } } }, @@ -151,7 +151,7 @@ "loc": { "start": { "line": 16, - "column": 17 + "column": 39 }, "end": { "line": 18, @@ -265,7 +265,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno", + "name": "Anno", "loc": { "start": { "line": 20, @@ -451,7 +451,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno", + "name": "Anno", "loc": { "start": { "line": 22, diff --git a/es2panda/test/parser/annotations/declaration-usage-number.ts b/es2panda/test/parser/annotations/declaration-usage-number.ts index 50b8417b90..8fc55a987b 100644 --- a/es2panda/test/parser/annotations/declaration-usage-number.ts +++ b/es2panda/test/parser/annotations/declaration-usage-number.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { a: number; } diff --git a/es2panda/test/parser/annotations/declaration-usage-string-expected.txt b/es2panda/test/parser/annotations/declaration-usage-string-expected.txt index b8bec61953..613d0f63c9 100644 --- a/es2panda/test/parser/annotations/declaration-usage-string-expected.txt +++ b/es2panda/test/parser/annotations/declaration-usage-string-expected.txt @@ -14,7 +14,7 @@ }, "end": { "line": 16, - "column": 16 + "column": 38 } } }, @@ -151,7 +151,7 @@ "loc": { "start": { "line": 16, - "column": 17 + "column": 39 }, "end": { "line": 18, @@ -265,7 +265,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno", + "name": "Anno", "loc": { "start": { "line": 20, @@ -451,7 +451,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno", + "name": "Anno", "loc": { "start": { "line": 22, diff --git a/es2panda/test/parser/annotations/declaration-usage-string.ts b/es2panda/test/parser/annotations/declaration-usage-string.ts index 0c627768fd..5ad01ef4ed 100644 --- a/es2panda/test/parser/annotations/declaration-usage-string.ts +++ b/es2panda/test/parser/annotations/declaration-usage-string.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -@interface Anno { +@interface __$$ETS_ANNOTATION$$__Anno { a: string; } diff --git a/es2panda/test/parser/annotations/export-expected.txt b/es2panda/test/parser/annotations/export-expected.txt index 4ae0d3f25d..ddccdb842b 100644 --- a/es2panda/test/parser/annotations/export-expected.txt +++ b/es2panda/test/parser/annotations/export-expected.txt @@ -16,7 +16,7 @@ }, "end": { "line": 16, - "column": 24 + "column": 46 } } }, @@ -97,7 +97,7 @@ }, "end": { "line": 16, - "column": 27 + "column": 49 } } }, @@ -106,11 +106,11 @@ "loc": { "start": { "line": 16, - "column": 25 + "column": 47 }, "end": { "line": 16, - "column": 27 + "column": 49 } } }, @@ -123,7 +123,7 @@ }, "end": { "line": 16, - "column": 27 + "column": 49 } } }, @@ -136,7 +136,7 @@ }, "end": { "line": 16, - "column": 27 + "column": 49 } } }, @@ -155,7 +155,7 @@ }, "end": { "line": 18, - "column": 24 + "column": 46 } } }, @@ -306,7 +306,7 @@ "loc": { "start": { "line": 18, - "column": 25 + "column": 47 }, "end": { "line": 20, @@ -435,7 +435,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno1", + "name": "Anno1", "loc": { "start": { "line": 22, @@ -619,7 +619,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno1", + "name": "Anno1", "loc": { "start": { "line": 25, diff --git a/es2panda/test/parser/annotations/export.ts b/es2panda/test/parser/annotations/export.ts index 8c10cc0628..6bea13acdc 100644 --- a/es2panda/test/parser/annotations/export.ts +++ b/es2panda/test/parser/annotations/export.ts @@ -13,9 +13,9 @@ * limitations under the License. */ -export @interface Anno1 {} +export @interface __$$ETS_ANNOTATION$$__Anno1 {} -export @interface Anno2 { +export @interface __$$ETS_ANNOTATION$$__Anno2 { a: number = 0; } diff --git a/es2panda/test/parser/annotations/import-qualified-expected.txt b/es2panda/test/parser/annotations/import-qualified-expected.txt index 5f41d5ec6c..4706b8ceea 100644 --- a/es2panda/test/parser/annotations/import-qualified-expected.txt +++ b/es2panda/test/parser/annotations/import-qualified-expected.txt @@ -152,7 +152,7 @@ "type": "MemberExpression", "object": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Namespace1", + "name": "Namespace1", "loc": { "start": { "line": 18, @@ -160,7 +160,7 @@ }, "end": { "line": 18, - "column": 34 + "column": 12 } } }, @@ -170,7 +170,7 @@ "loc": { "start": { "line": 18, - "column": 35 + "column": 13 }, "end": { "line": 18, @@ -348,7 +348,7 @@ "type": "MemberExpression", "object": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Namespace1", + "name": "Namespace1", "loc": { "start": { "line": 21, @@ -356,7 +356,7 @@ }, "end": { "line": 21, - "column": 34 + "column": 12 } } }, @@ -366,7 +366,7 @@ "loc": { "start": { "line": 21, - "column": 35 + "column": 13 }, "end": { "line": 21, @@ -533,7 +533,7 @@ "type": "MemberExpression", "object": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Namespace1", + "name": "Namespace1", "loc": { "start": { "line": 24, @@ -541,7 +541,7 @@ }, "end": { "line": 24, - "column": 34 + "column": 12 } } }, @@ -551,7 +551,7 @@ "loc": { "start": { "line": 24, - "column": 35 + "column": 13 }, "end": { "line": 24, @@ -841,7 +841,7 @@ "type": "MemberExpression", "object": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Namespace1", + "name": "Namespace1", "loc": { "start": { "line": 27, @@ -849,7 +849,7 @@ }, "end": { "line": 27, - "column": 34 + "column": 12 } } }, @@ -859,11 +859,11 @@ "loc": { "start": { "line": 27, - "column": 35 + "column": 13 }, "end": { "line": 27, - "column": 45 + "column": 23 } } }, @@ -876,7 +876,7 @@ }, "end": { "line": 27, - "column": 45 + "column": 23 } } }, @@ -886,11 +886,11 @@ "loc": { "start": { "line": 27, - "column": 46 + "column": 24 }, "end": { "line": 27, - "column": 56 + "column": 34 } } }, @@ -903,7 +903,7 @@ }, "end": { "line": 27, - "column": 56 + "column": 34 } } }, @@ -913,7 +913,7 @@ "loc": { "start": { "line": 27, - "column": 57 + "column": 35 }, "end": { "line": 27, @@ -1095,7 +1095,7 @@ "type": "MemberExpression", "object": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Namespace1", + "name": "Namespace1", "loc": { "start": { "line": 30, @@ -1103,7 +1103,7 @@ }, "end": { "line": 30, - "column": 34 + "column": 12 } } }, @@ -1113,11 +1113,11 @@ "loc": { "start": { "line": 30, - "column": 35 + "column": 13 }, "end": { "line": 30, - "column": 45 + "column": 23 } } }, @@ -1130,7 +1130,7 @@ }, "end": { "line": 30, - "column": 45 + "column": 23 } } }, @@ -1140,11 +1140,11 @@ "loc": { "start": { "line": 30, - "column": 46 + "column": 24 }, "end": { "line": 30, - "column": 56 + "column": 34 } } }, @@ -1157,7 +1157,7 @@ }, "end": { "line": 30, - "column": 56 + "column": 34 } } }, @@ -1167,7 +1167,7 @@ "loc": { "start": { "line": 30, - "column": 57 + "column": 35 }, "end": { "line": 30, @@ -1338,7 +1338,7 @@ "type": "MemberExpression", "object": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Namespace1", + "name": "Namespace1", "loc": { "start": { "line": 33, @@ -1346,7 +1346,7 @@ }, "end": { "line": 33, - "column": 34 + "column": 12 } } }, @@ -1356,11 +1356,11 @@ "loc": { "start": { "line": 33, - "column": 35 + "column": 13 }, "end": { "line": 33, - "column": 45 + "column": 23 } } }, @@ -1373,7 +1373,7 @@ }, "end": { "line": 33, - "column": 45 + "column": 23 } } }, @@ -1383,11 +1383,11 @@ "loc": { "start": { "line": 33, - "column": 46 + "column": 24 }, "end": { "line": 33, - "column": 56 + "column": 34 } } }, @@ -1400,7 +1400,7 @@ }, "end": { "line": 33, - "column": 56 + "column": 34 } } }, @@ -1410,7 +1410,7 @@ "loc": { "start": { "line": 33, - "column": 57 + "column": 35 }, "end": { "line": 33, diff --git a/es2panda/test/parser/annotations/import-qualified.ts b/es2panda/test/parser/annotations/import-qualified.ts index 61a16cadc2..742f0f07ae 100644 --- a/es2panda/test/parser/annotations/import-qualified.ts +++ b/es2panda/test/parser/annotations/import-qualified.ts @@ -15,20 +15,20 @@ import * as Namespace1 from "./a" -@__$$ETS_ANNOTATION$$__Namespace1.Anno() +@Namespace1.__$$ETS_ANNOTATION$$__Anno() class A {} -@__$$ETS_ANNOTATION$$__Namespace1.Anno +@Namespace1.__$$ETS_ANNOTATION$$__Anno class B {} -@__$$ETS_ANNOTATION$$__Namespace1.Anno1({a: 1, b: "string"}) +@Namespace1.__$$ETS_ANNOTATION$$__Anno1({a: 1, b: "string"}) class C {} -@__$$ETS_ANNOTATION$$__Namespace1.Namespace2.Namespace3.Anno2() +@Namespace1.Namespace2.Namespace3.__$$ETS_ANNOTATION$$__Anno2() class D {} -@__$$ETS_ANNOTATION$$__Namespace1.Namespace2.Namespace3.Anno2 +@Namespace1.Namespace2.Namespace3.__$$ETS_ANNOTATION$$__Anno2 class E {} -@__$$ETS_ANNOTATION$$__Namespace1.Namespace2.Namespace3.Anno3({a: 1, b: "string"}) +@Namespace1.Namespace2.Namespace3.__$$ETS_ANNOTATION$$__Anno3({a: 1, b: "string"}) class F {} \ No newline at end of file diff --git a/es2panda/test/parser/annotations/import-unqualified-expected.txt b/es2panda/test/parser/annotations/import-unqualified-expected.txt index c4468f2f49..cf5699a103 100644 --- a/es2panda/test/parser/annotations/import-unqualified-expected.txt +++ b/es2panda/test/parser/annotations/import-unqualified-expected.txt @@ -205,7 +205,7 @@ "type": "Annotation", "expression": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno1", + "name": "Anno1", "loc": { "start": { "line": 18, @@ -361,7 +361,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno1", + "name": "Anno1", "loc": { "start": { "line": 21, @@ -530,7 +530,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno1", + "name": "Anno1", "loc": { "start": { "line": 24, @@ -714,7 +714,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno2", + "name": "Anno2", "loc": { "start": { "line": 27, diff --git a/es2panda/test/parser/annotations/multiple-annotations-expected.txt b/es2panda/test/parser/annotations/multiple-annotations-expected.txt index 2111cf0e0b..135d60a478 100644 --- a/es2panda/test/parser/annotations/multiple-annotations-expected.txt +++ b/es2panda/test/parser/annotations/multiple-annotations-expected.txt @@ -14,7 +14,7 @@ }, "end": { "line": 16, - "column": 17 + "column": 39 } } }, @@ -165,7 +165,7 @@ "loc": { "start": { "line": 16, - "column": 18 + "column": 40 }, "end": { "line": 18, @@ -199,7 +199,7 @@ }, "end": { "line": 20, - "column": 17 + "column": 39 } } }, @@ -350,7 +350,7 @@ "loc": { "start": { "line": 20, - "column": 18 + "column": 40 }, "end": { "line": 22, @@ -384,7 +384,7 @@ }, "end": { "line": 24, - "column": 17 + "column": 39 } } }, @@ -577,7 +577,7 @@ "loc": { "start": { "line": 24, - "column": 18 + "column": 40 }, "end": { "line": 26, @@ -691,7 +691,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno1", + "name": "Anno1", "loc": { "start": { "line": 28, @@ -796,7 +796,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno2", + "name": "Anno2", "loc": { "start": { "line": 29, @@ -901,7 +901,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno3", + "name": "Anno3", "loc": { "start": { "line": 30, @@ -1116,7 +1116,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno1", + "name": "Anno1", "loc": { "start": { "line": 32, @@ -1221,7 +1221,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno2", + "name": "Anno2", "loc": { "start": { "line": 33, @@ -1326,7 +1326,7 @@ "type": "CallExpression", "callee": { "type": "Identifier", - "name": "__$$ETS_ANNOTATION$$__Anno3", + "name": "Anno3", "loc": { "start": { "line": 34, diff --git a/es2panda/test/parser/annotations/multiple-annotations.ts b/es2panda/test/parser/annotations/multiple-annotations.ts index cf0af17c46..246af473b2 100644 --- a/es2panda/test/parser/annotations/multiple-annotations.ts +++ b/es2panda/test/parser/annotations/multiple-annotations.ts @@ -13,15 +13,15 @@ * limitations under the License. */ -@interface Anno1 { +@interface __$$ETS_ANNOTATION$$__Anno1 { a: number = 1; } -@interface Anno2 { +@interface __$$ETS_ANNOTATION$$__Anno2 { b: string = "string" } -@interface Anno3 { +@interface __$$ETS_ANNOTATION$$__Anno3 { c: boolean[] = [true, false]; } diff --git a/es2panda/test/runner.py b/es2panda/test/runner.py index abaaaab0ba..c4de73a4e9 100755 --- a/es2panda/test/runner.py +++ b/es2panda/test/runner.py @@ -25,7 +25,7 @@ import re import shutil import subprocess import sys -from config import API_VERSION_MAP, MIN_SUPPORT_BC_VERSION, MIX_COMPILE_ENTRY_POINT +from config import API_VERSION_MAP, ARK_JS_VM_LIST, MIN_SUPPORT_BC_VERSION, MIX_COMPILE_ENTRY_POINT def is_directory(parser, arg): @@ -1412,7 +1412,9 @@ class BcVersionTest(Test): 15: "12.0.6.0", 16: "12.0.6.0", 17: "12.0.6.0", - 18: "13.0.1.0" + 18: "13.0.1.0", + 19: "13.0.1.0", + 20: "13.0.1.0", } self.es2abc_script_expect = { 8: "0.0.0.2", @@ -1428,7 +1430,9 @@ class BcVersionTest(Test): 15: "12.0.6.0", 16: "12.0.6.0", 17: "12.0.6.0", - 18: "13.0.1.0" + 18: "13.0.1.0", + 19: "13.0.1.0", + 20: "13.0.1.0", } def run(self): @@ -2123,18 +2127,12 @@ class TestAbcVersionControl(Test): self.passed = False return stderr - def execute_abc(self, runner, vm_api_version, vm_api_sub_version="", entry_point=""): + def execute_abc(self, runner, vm_version, entry_point=""): cmd = [] - if vm_api_version != "12": - vm_api_sub_version = "" - # there is no virtual machine with version api12beta2 available. - # chosen api12beta1 as a replacement. - elif vm_api_version == "12" and vm_api_sub_version == "beta2": - vm_api_sub_version = "beta1" ark_js_vm_dir = os.path.join( runner.build_dir, "ark_js_vm_version", - "API%s%s" % (vm_api_version, vm_api_sub_version), + vm_version, ) ld_library_path = os.path.join(ark_js_vm_dir, "lib") os.environ["LD_LIBRARY_PATH"] = ld_library_path @@ -2150,11 +2148,9 @@ class TestAbcVersionControl(Test): stderr = None target_version = "API" + target_api_version + target_api_sub_version target_version_number = API_VERSION_MAP.get(target_version) - for api_version in API_VERSION_MAP: - vm_api_version, vm_api_sub_version = AbcTestCasesPrepare.split_api_version(api_version) - vm_version = "API" + vm_api_version + vm_api_sub_version + for vm_version in ARK_JS_VM_LIST: vm_version_number = API_VERSION_MAP.get(vm_version) - _, stderr = self.execute_abc(runner, vm_api_version, vm_api_sub_version, self.entry_point) + _, stderr = self.execute_abc(runner, vm_version, self.entry_point) self.is_support = ( TestAbcVersionControl.compare_version_number(vm_version_number, target_version_number) >= 0 ) @@ -2204,8 +2200,8 @@ class TestVersionControl(Test): def __init__(self, test_path, flags, test_version, feature_type, module_path_list): Test.__init__(self, test_path, flags) self.beta_version_default = 3 - self.version_with_sub_version_list = [12] - self.target_api_version_list = ["9", "10", "11", "12", "18"] + self.version_with_sub_version_list = ["12"] + self.target_api_version_list = ["9", "10", "11", "12", "18", "20"] self.target_api_sub_version_list = ["beta1", "beta2", "beta3"] self.specific_api_version_list = ["API11", "API12beta3"] self.output = None @@ -2347,7 +2343,7 @@ class TestVersionControl(Test): def run_process(self, cmd): self.process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = self.process.communicate() - self.output = stdout.decode("utf-8", errors="ignore") + stderr.decode("utf-8", errors="ignore").split("\n")[0] + self.output = stdout.decode("utf-8", errors="ignore") + stderr.decode("utf-8", errors="ignore") return stdout, stderr def run_process_compile(self, runner, target_api_version, target_api_sub_version="bata3", dump_type=""): @@ -2397,7 +2393,7 @@ class TestVersionControl(Test): self.output = stdout.decode("utf-8", errors="ignore") + stderr.decode("utf-8", errors="ignore").split("\n")[0] return stdout, stderr - def run_for_single_version(self, runner, target_api_version, target_api_sub_version="beta3"): + def run_for_single_version(self, runner, target_api_version, target_api_sub_version=""): cur_api_version = "API" + target_api_version + target_api_sub_version is_support = True if self.compare_two_versions(cur_api_version, self.test_version) >= 0 else False compile_expected_path = None @@ -2418,6 +2414,7 @@ class TestVersionControl(Test): self.passed = False if not self.passed or (stderr and self.passed): return stderr + cur_api_version_number = API_VERSION_MAP.get(cur_api_version) for api_version in self.target_api_version_list: # The interception capability of API9 version of ark_js_vm has not yet been launched. if api_version == "9": @@ -2425,9 +2422,18 @@ class TestVersionControl(Test): for api_sub_version in self.target_api_sub_version_list: if not api_version in self.version_with_sub_version_list and api_sub_version != "beta3": continue + elif not api_version in self.version_with_sub_version_list: + api_sub_version = "" cur_runtime_api_version = "API" + api_version + api_sub_version + cur_runtime_api_version_number = API_VERSION_MAP.get(cur_runtime_api_version) is_below_abc_version = ( - False if self.compare_two_versions(cur_runtime_api_version, cur_api_version) >= 0 else True + False + if TestAbcVersionControl.compare_version_number( + cur_runtime_api_version_number, + cur_api_version_number, + ) + >= 0 + else True ) self.generate_module_abc(runner, cur_runtime_api_version) _, stderr = self.runtime_for_target_version(runner, api_version, api_sub_version) @@ -2594,17 +2600,24 @@ def add_directory_for_version_control(runners, args): "version_control/API12beta3/bytecode_feature/import_target", ) runner.add_directory( - "version_control/API16/bytecode_feature", + "version_control/API18/bytecode_feature", "js", [], - "API16", + "API18", "bytecode_feature", ) runner.add_directory( - "version_control/API16/bytecode_feature", + "version_control/API18/bytecode_feature", "ts", ["--module"], - "API16", + "API18", + "bytecode_feature", + ) + runner.add_directory( + "version_control/API20/bytecode_feature", + "ts", + ["--module", "--enable-annotations"], + "API20", "bytecode_feature", ) runners.append(runner) @@ -2775,7 +2788,7 @@ def add_directory_for_compiler(runners, args): "--file-threads=8"])) compiler_test_infos.append(CompilerTestInfo("compiler/bytecodehar/projects", "ts", ["--merge-abc", "--dump-assembly", "--enable-abc-input", - "--dump-deps-info", "--remove-redundant-file", + "--dump-deps-info", "--remove-redundant-file", "--enable-annotations", "--dump-literal-buffer", "--dump-string", "--abc-class-threads=4"])) compiler_test_infos.append(CompilerTestInfo("compiler/bytecodehar/js/projects", "js", ["--merge-abc", "--dump-assembly", "--enable-abc-input", @@ -2786,7 +2799,7 @@ def add_directory_for_compiler(runners, args): "--abc-class-threads=4"])) compiler_test_infos.append(CompilerTestInfo("compiler/cache_projects", "ts", ["--merge-abc", "--dump-assembly", "--enable-abc-input", - "--dump-deps-info", "--remove-redundant-file", + "--dump-deps-info", "--remove-redundant-file", "--enable-annotations", "--dump-literal-buffer", "--dump-string", "--abc-class-threads=4", "--cache-file"])) diff --git a/es2panda/test/version_control/API11/bytecode_feature/class_private_property_unsupported_compile_asm_version-expected.txt b/es2panda/test/version_control/API11/bytecode_feature/class_private_property_unsupported_compile_asm_version-expected.txt index f7d4404293..382ae3503f 100644 --- a/es2panda/test/version_control/API11/bytecode_feature/class_private_property_unsupported_compile_asm_version-expected.txt +++ b/es2panda/test/version_control/API11/bytecode_feature/class_private_property_unsupported_compile_asm_version-expected.txt @@ -1 +1,2 @@ -SyntaxError: Unexpected token in class property [class_private_property.js:17:5] \ No newline at end of file +SyntaxError: Unexpected token in class property [class_private_property.js:17:5] +The size of programs is expected to be 1, but is 0 diff --git a/es2panda/test/version_control/API11/bytecode_feature/in_obj_syntax_unsupported_compile_asm_version-expected.txt b/es2panda/test/version_control/API11/bytecode_feature/in_obj_syntax_unsupported_compile_asm_version-expected.txt index 07c1ce9d18..6f86f64511 100644 --- a/es2panda/test/version_control/API11/bytecode_feature/in_obj_syntax_unsupported_compile_asm_version-expected.txt +++ b/es2panda/test/version_control/API11/bytecode_feature/in_obj_syntax_unsupported_compile_asm_version-expected.txt @@ -1 +1,2 @@ -SyntaxError: Unexpected token in class property [in_obj_syntax.js:17:5] \ No newline at end of file +SyntaxError: Unexpected token in class property [in_obj_syntax.js:17:5] +The size of programs is expected to be 1, but is 0 diff --git a/es2panda/test/version_control/API11/syntax_feature/class_private_field_unsupported_compile_version-expected.txt b/es2panda/test/version_control/API11/syntax_feature/class_private_field_unsupported_compile_version-expected.txt index 9ebbe0fbe7..55353e1e07 100644 --- a/es2panda/test/version_control/API11/syntax_feature/class_private_field_unsupported_compile_version-expected.txt +++ b/es2panda/test/version_control/API11/syntax_feature/class_private_field_unsupported_compile_version-expected.txt @@ -1 +1,2 @@ -SyntaxError: Unexpected token in class property [class_private_field.js:17:5] \ No newline at end of file +SyntaxError: Unexpected token in class property [class_private_field.js:17:5] +The size of programs is expected to be 1, but is 0 diff --git a/es2panda/test/version_control/API11/syntax_feature/class_private_method_unsupported_compile_version-expected.txt b/es2panda/test/version_control/API11/syntax_feature/class_private_method_unsupported_compile_version-expected.txt index 3303a190e5..7ac858525c 100644 --- a/es2panda/test/version_control/API11/syntax_feature/class_private_method_unsupported_compile_version-expected.txt +++ b/es2panda/test/version_control/API11/syntax_feature/class_private_method_unsupported_compile_version-expected.txt @@ -1 +1,2 @@ -SyntaxError: Unexpected token in class property [class_private_method.js:17:5] \ No newline at end of file +SyntaxError: Unexpected token in class property [class_private_method.js:17:5] +The size of programs is expected to be 1, but is 0 diff --git a/es2panda/test/version_control/API11/syntax_feature/in_check_private_property_unsupported_compile_version-expected.txt b/es2panda/test/version_control/API11/syntax_feature/in_check_private_property_unsupported_compile_version-expected.txt index 5d5a117bc1..d1e3d87e43 100644 --- a/es2panda/test/version_control/API11/syntax_feature/in_check_private_property_unsupported_compile_version-expected.txt +++ b/es2panda/test/version_control/API11/syntax_feature/in_check_private_property_unsupported_compile_version-expected.txt @@ -1 +1,2 @@ -SyntaxError: Unexpected token in class property [in_check_private_property.js:17:5] \ No newline at end of file +SyntaxError: Unexpected token in class property [in_check_private_property.js:17:5] +The size of programs is expected to be 1, but is 0 diff --git a/es2panda/test/version_control/API12beta3/bytecode_feature/lazy_import_bytecode_unsupported_compile_asm_version-expected.txt b/es2panda/test/version_control/API12beta3/bytecode_feature/lazy_import_bytecode_unsupported_compile_asm_version-expected.txt index ae2da4fe1e..7511f0e00c 100644 --- a/es2panda/test/version_control/API12beta3/bytecode_feature/lazy_import_bytecode_unsupported_compile_asm_version-expected.txt +++ b/es2panda/test/version_control/API12beta3/bytecode_feature/lazy_import_bytecode_unsupported_compile_asm_version-expected.txt @@ -1 +1,3 @@ -SyntaxError: Current configuration does not support using lazy import. Lazy import can be used in the beta3 version of API 12 or higher versions. \ No newline at end of file +SyntaxError: Current configuration does not support using lazy import. Lazy import can be used in the beta3 version of API 12 or higher versions. +Solutions: > Check the compatibleSdkVersion and compatibleSdkVersionStage in build-profile.json5.> If compatibleSdkVersion is set to API 12, then compatibleSdkVersionStage needs to be configured as beta3.> If you're running es2abc in commandline without IDE, please check whether target-api-version and target-api-sub-version options are correctly configured. [lazy_import_bytecode.ts:16:13] +The size of programs is expected to be 1, but is 0 diff --git a/es2panda/test/version_control/API12beta3/bytecode_feature/wide_lazy_import_bytecode_unsupported_compile_asm_version-expected.txt b/es2panda/test/version_control/API12beta3/bytecode_feature/wide_lazy_import_bytecode_unsupported_compile_asm_version-expected.txt index ae2da4fe1e..ab88cd29d0 100644 --- a/es2panda/test/version_control/API12beta3/bytecode_feature/wide_lazy_import_bytecode_unsupported_compile_asm_version-expected.txt +++ b/es2panda/test/version_control/API12beta3/bytecode_feature/wide_lazy_import_bytecode_unsupported_compile_asm_version-expected.txt @@ -1 +1,3 @@ -SyntaxError: Current configuration does not support using lazy import. Lazy import can be used in the beta3 version of API 12 or higher versions. \ No newline at end of file +SyntaxError: Current configuration does not support using lazy import. Lazy import can be used in the beta3 version of API 12 or higher versions. +Solutions: > Check the compatibleSdkVersion and compatibleSdkVersionStage in build-profile.json5.> If compatibleSdkVersion is set to API 12, then compatibleSdkVersionStage needs to be configured as beta3.> If you're running es2abc in commandline without IDE, please check whether target-api-version and target-api-sub-version options are correctly configured. [wide_lazy_import_bytecode.ts:16:13] +The size of programs is expected to be 1, but is 0 diff --git a/es2panda/test/version_control/API12beta3/syntax_feature/lazy_import_unsupported_compile_version-expected.txt b/es2panda/test/version_control/API12beta3/syntax_feature/lazy_import_unsupported_compile_version-expected.txt index ae2da4fe1e..6792ee776f 100644 --- a/es2panda/test/version_control/API12beta3/syntax_feature/lazy_import_unsupported_compile_version-expected.txt +++ b/es2panda/test/version_control/API12beta3/syntax_feature/lazy_import_unsupported_compile_version-expected.txt @@ -1 +1,3 @@ -SyntaxError: Current configuration does not support using lazy import. Lazy import can be used in the beta3 version of API 12 or higher versions. \ No newline at end of file +SyntaxError: Current configuration does not support using lazy import. Lazy import can be used in the beta3 version of API 12 or higher versions. +Solutions: > Check the compatibleSdkVersion and compatibleSdkVersionStage in build-profile.json5.> If compatibleSdkVersion is set to API 12, then compatibleSdkVersionStage needs to be configured as beta3.> If you're running es2abc in commandline without IDE, please check whether target-api-version and target-api-sub-version options are correctly configured. [lazy_import.ts:16:13] +The size of programs is expected to be 1, but is 0 diff --git a/es2panda/test/version_control/API16/bytecode_feature/derived-class-default-constructor-opt.js b/es2panda/test/version_control/API18/bytecode_feature/derived-class-default-constructor-opt.js similarity index 100% rename from es2panda/test/version_control/API16/bytecode_feature/derived-class-default-constructor-opt.js rename to es2panda/test/version_control/API18/bytecode_feature/derived-class-default-constructor-opt.js diff --git a/es2panda/test/version_control/API16/bytecode_feature/derived-class-default-constructor-opt_runtime_below_abc_api_version-expected.txt b/es2panda/test/version_control/API18/bytecode_feature/derived-class-default-constructor-opt_runtime_below_abc_api_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API16/bytecode_feature/derived-class-default-constructor-opt_runtime_below_abc_api_version-expected.txt rename to es2panda/test/version_control/API18/bytecode_feature/derived-class-default-constructor-opt_runtime_below_abc_api_version-expected.txt diff --git a/es2panda/test/version_control/API16/bytecode_feature/derived-class-default-constructor-opt_supported_compile_asm_version-expected.txt b/es2panda/test/version_control/API18/bytecode_feature/derived-class-default-constructor-opt_supported_compile_asm_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API16/bytecode_feature/derived-class-default-constructor-opt_supported_compile_asm_version-expected.txt rename to es2panda/test/version_control/API18/bytecode_feature/derived-class-default-constructor-opt_supported_compile_asm_version-expected.txt diff --git a/es2panda/test/version_control/API16/bytecode_feature/derived-class-default-constructor-opt_supported_runtime_version-expected.txt b/es2panda/test/version_control/API18/bytecode_feature/derived-class-default-constructor-opt_supported_runtime_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API16/bytecode_feature/derived-class-default-constructor-opt_supported_runtime_version-expected.txt rename to es2panda/test/version_control/API18/bytecode_feature/derived-class-default-constructor-opt_supported_runtime_version-expected.txt diff --git a/es2panda/test/version_control/API16/bytecode_feature/derived-class-default-constructor-opt_unsupported_compile_for_below_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API18/bytecode_feature/derived-class-default-constructor-opt_unsupported_compile_for_below_API12beta3_asm_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API16/bytecode_feature/derived-class-default-constructor-opt_unsupported_compile_for_below_API12beta3_asm_version-expected.txt rename to es2panda/test/version_control/API18/bytecode_feature/derived-class-default-constructor-opt_unsupported_compile_for_below_API12beta3_asm_version-expected.txt diff --git a/es2panda/test/version_control/API16/bytecode_feature/derived-class-default-constructor-opt_unsupported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API18/bytecode_feature/derived-class-default-constructor-opt_unsupported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API16/bytecode_feature/derived-class-default-constructor-opt_unsupported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt rename to es2panda/test/version_control/API18/bytecode_feature/derived-class-default-constructor-opt_unsupported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt diff --git a/es2panda/test/version_control/API16/bytecode_feature/derived-class-default-constructor-opt_unsupported_runtime_version-expected.txt b/es2panda/test/version_control/API18/bytecode_feature/derived-class-default-constructor-opt_unsupported_runtime_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API16/bytecode_feature/derived-class-default-constructor-opt_unsupported_runtime_version-expected.txt rename to es2panda/test/version_control/API18/bytecode_feature/derived-class-default-constructor-opt_unsupported_runtime_version-expected.txt diff --git a/es2panda/test/version_control/API16/bytecode_feature/sendable-class-export.ts b/es2panda/test/version_control/API18/bytecode_feature/sendable-class-export.ts similarity index 100% rename from es2panda/test/version_control/API16/bytecode_feature/sendable-class-export.ts rename to es2panda/test/version_control/API18/bytecode_feature/sendable-class-export.ts diff --git a/es2panda/test/version_control/API16/bytecode_feature/sendable-class-export_runtime_below_abc_api_version-expected.txt b/es2panda/test/version_control/API18/bytecode_feature/sendable-class-export_runtime_below_abc_api_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API16/bytecode_feature/sendable-class-export_runtime_below_abc_api_version-expected.txt rename to es2panda/test/version_control/API18/bytecode_feature/sendable-class-export_runtime_below_abc_api_version-expected.txt diff --git a/es2panda/test/version_control/API16/bytecode_feature/sendable-class-export_supported_compile_asm_version-expected.txt b/es2panda/test/version_control/API18/bytecode_feature/sendable-class-export_supported_compile_asm_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API16/bytecode_feature/sendable-class-export_supported_compile_asm_version-expected.txt rename to es2panda/test/version_control/API18/bytecode_feature/sendable-class-export_supported_compile_asm_version-expected.txt diff --git a/es2panda/test/version_control/API16/bytecode_feature/sendable-class-export_supported_runtime_version-expected.txt b/es2panda/test/version_control/API18/bytecode_feature/sendable-class-export_supported_runtime_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API16/bytecode_feature/sendable-class-export_supported_runtime_version-expected.txt rename to es2panda/test/version_control/API18/bytecode_feature/sendable-class-export_supported_runtime_version-expected.txt diff --git a/es2panda/test/version_control/API16/bytecode_feature/sendable-class-export_unsupported_compile_asm_version-expected.txt b/es2panda/test/version_control/API18/bytecode_feature/sendable-class-export_unsupported_compile_asm_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API16/bytecode_feature/sendable-class-export_unsupported_compile_asm_version-expected.txt rename to es2panda/test/version_control/API18/bytecode_feature/sendable-class-export_unsupported_compile_asm_version-expected.txt diff --git a/es2panda/test/version_control/API16/bytecode_feature/sendable-class-export_unsupported_compile_for_below_API11_asm_version-expected.txt b/es2panda/test/version_control/API18/bytecode_feature/sendable-class-export_unsupported_compile_for_below_API11_asm_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API16/bytecode_feature/sendable-class-export_unsupported_compile_for_below_API11_asm_version-expected.txt rename to es2panda/test/version_control/API18/bytecode_feature/sendable-class-export_unsupported_compile_for_below_API11_asm_version-expected.txt diff --git a/es2panda/test/version_control/API16/bytecode_feature/sendable-class-export_unsupported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API18/bytecode_feature/sendable-class-export_unsupported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API16/bytecode_feature/sendable-class-export_unsupported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt rename to es2panda/test/version_control/API18/bytecode_feature/sendable-class-export_unsupported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt diff --git a/es2panda/test/version_control/API16/bytecode_feature/sendable-class-export_unsupported_runtime_version-expected.txt b/es2panda/test/version_control/API18/bytecode_feature/sendable-class-export_unsupported_runtime_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API16/bytecode_feature/sendable-class-export_unsupported_runtime_version-expected.txt rename to es2panda/test/version_control/API18/bytecode_feature/sendable-class-export_unsupported_runtime_version-expected.txt diff --git a/es2panda/test/version_control/API20/bytecode_feature/annotations.ts b/es2panda/test/version_control/API20/bytecode_feature/annotations.ts new file mode 100644 index 0000000000..7cad18eb17 --- /dev/null +++ b/es2panda/test/version_control/API20/bytecode_feature/annotations.ts @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +@interface __$$ETS_ANNOTATION$$__Anno { + b: boolean = true +} + +@__$$ETS_ANNOTATION$$__Anno() +class A { } \ No newline at end of file diff --git a/es2panda/test/version_control/API20/bytecode_feature/annotations_runtime_below_abc_api_version-expected.txt b/es2panda/test/version_control/API20/bytecode_feature/annotations_runtime_below_abc_api_version-expected.txt new file mode 100644 index 0000000000..13510081b9 --- /dev/null +++ b/es2panda/test/version_control/API20/bytecode_feature/annotations_runtime_below_abc_api_version-expected.txt @@ -0,0 +1 @@ +pandafile \ No newline at end of file diff --git a/es2panda/test/version_control/API20/bytecode_feature/annotations_supported_compile_asm_version-expected.txt b/es2panda/test/version_control/API20/bytecode_feature/annotations_supported_compile_asm_version-expected.txt new file mode 100644 index 0000000000..11dd37ab8b --- /dev/null +++ b/es2panda/test/version_control/API20/bytecode_feature/annotations_supported_compile_asm_version-expected.txt @@ -0,0 +1,24 @@ +slotNum = 0x0 +.language ECMAScript +.function any .#~A=#A(any a0, any a1, any a2) { +label_1: +label_0: + lda a2 + return +label_2: +} + +slotNum = 0x3 +.language ECMAScript +.function any .func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + ldhole + sta v0 + defineclasswithbuffer 0x0, .#~A=#A, _2, 0x0, v0 + ldobjbyname 0x1, prototype + returnundefined +label_2: +} + + diff --git a/es2panda/test/version_control/API20/bytecode_feature/annotations_supported_runtime_version-expected.txt b/es2panda/test/version_control/API20/bytecode_feature/annotations_supported_runtime_version-expected.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/es2panda/test/version_control/API20/bytecode_feature/annotations_unsupported_compile_asm_version-expected.txt b/es2panda/test/version_control/API20/bytecode_feature/annotations_unsupported_compile_asm_version-expected.txt new file mode 100644 index 0000000000..d327c04a72 --- /dev/null +++ b/es2panda/test/version_control/API20/bytecode_feature/annotations_unsupported_compile_asm_version-expected.txt @@ -0,0 +1,3 @@ +SyntaxError: Current configuration does not support using annotations. Annotations can be used in the version of API 20 or higher versions. +Solutions: > Check the compatibleSdkVersion in build-profile.json5.> If compatibleSdkVersion is set to API 20 or higher version.> If you're running es2abc in commandline without IDE, please check whether target-api-version and enable-annotations options are correctly configured. [annotations.ts:17:12] +The size of programs is expected to be 1, but is 0 diff --git a/es2panda/util/commonUtil.h b/es2panda/util/commonUtil.h index f63afffa7d..196c56370d 100644 --- a/es2panda/util/commonUtil.h +++ b/es2panda/util/commonUtil.h @@ -48,6 +48,7 @@ constexpr char NORMALIZED_OHMURL_PREFIX = '@'; constexpr char SLASH_TAG = '/'; constexpr char CHAR_VERTICAL_LINE = '|'; constexpr char COLON_SEPARATOR = ':'; +constexpr char DOT_SEPARATOR = '.'; constexpr size_t ORIGINAL_PKG_NAME_POS = 0U; constexpr size_t TARGET_PKG_NAME_POS = 1U; diff --git a/es2panda/util/helpers.cpp b/es2panda/util/helpers.cpp index fcc643dfb3..30f0a4bc1c 100644 --- a/es2panda/util/helpers.cpp +++ b/es2panda/util/helpers.cpp @@ -15,6 +15,7 @@ #include "helpers.h" +#include #include #include #include @@ -31,6 +32,7 @@ #include #include #include +#include #include #ifdef ENABLE_BYTECODE_OPT @@ -955,13 +957,41 @@ bool Helpers::BelongingToRecords(const std::string &name, const std::unordered_s return retainRecordSet.find(recordName) != retainRecordSet.end(); } +bool Helpers::IsInnerAnnotationRecordName(const std::string &name) +{ + return name == panda::abc2program::CONCURRENT_MODULE_REQUEST_RECORD_NAME || + name == panda::abc2program::SLOT_NUMBER_RECORD_NAME || + name == panda::abc2program::EXPECTED_PROPERTY_COUNT_RECORD_NAME; +} + +std::string Helpers::RemoveRecordSuffixAnnotationName(const std::string &name) +{ + auto pos = name.rfind(util::DOT_SEPARATOR); + if (pos == std::string::npos) { + return name; + } + return name.substr(0, pos); +} + void Helpers::RemoveProgramsRedundantData(std::map &progsInfo, const std::map> &resolvedDepsRelation) { auto progInfoIter = progsInfo.begin(); while (progInfoIter != progsInfo.end()) { + auto name = progInfoIter->first; + auto &program = progInfoIter->second->program; + /** + * The record name of a user-defined annotation is the annotation name concatenated with the record name of the + * file where it is declared. In order to preserve the annotated record, it is necessary to remove the + * concatenated annotation name from the record name before perform dependency matching. + */ + if (!util::RecordNotGeneratedFromBytecode(name) && + (program.record_table.begin()->second.metadata->GetAccessFlags() & ACC_ANNOTATION) != 0 && + !IsInnerAnnotationRecordName(program.record_table.begin()->first)) { + name = RemoveRecordSuffixAnnotationName(name); + } // remove redundant sourcefiles and bytecodefile data which are not dependant in compilation - if (resolvedDepsRelation.find(progInfoIter->first) == resolvedDepsRelation.end()) { + if (resolvedDepsRelation.find(name) == resolvedDepsRelation.end()) { progInfoIter = progsInfo.erase(progInfoIter); continue; } @@ -987,4 +1017,10 @@ bool Helpers::IsEnableExpectedPropertyCountApiVersion(int apiVersion) { return !(apiVersion < ENABLE_EXPECTED_PROPERTY_COUNT_MIN_SUPPORTED_API_VERSION); } + +bool Helpers::IsSupportAnnotationVersion(int apiVersion) +{ + return !(apiVersion < ANNOTATION_SUPPORTED_API_VERSION); +} + } // namespace panda::es2panda::util diff --git a/es2panda/util/helpers.h b/es2panda/util/helpers.h index 67b31ec16d..91e738b542 100644 --- a/es2panda/util/helpers.h +++ b/es2panda/util/helpers.h @@ -176,11 +176,14 @@ public: static bool IsSpecialScopeName(const util::StringView &str); static bool BelongingToRecords(const std::string &name, const std::unordered_set &retainRecordSet, const std::string &delimiter = std::string(DOT)); + static bool IsInnerAnnotationRecordName(const std::string &name); + static std::string RemoveRecordSuffixAnnotationName(const std::string &name); static void RemoveProgramsRedundantData(std::map &progsInfo, const std::map> &resolveDepsRelation); static bool IsDefaultApiVersion(int apiVersion, std::string subApiVersion); static bool IsSupportLazyImportVersion(int apiVersion, std::string subApiVersion); static bool IsEnableExpectedPropertyCountApiVersion(int apiVersion); + static bool IsSupportAnnotationVersion(int apiVersion); static const uint32_t MAX_DOUBLE_DIGIT = 310; static const uint32_t MAX_DOUBLE_PRECISION_DIGIT = 17; @@ -220,6 +223,7 @@ public: static const int8_t SUPER_CALL_OPT_MIN_SUPPORTED_API_VERSION = 18; static const int8_t SENDABLE_CLASS_USING_LOCAL_MODULE_VAR_MIN_SUPPORTED_API_VERSION = 18; static const int8_t ENABLE_EXPECTED_PROPERTY_COUNT_MIN_SUPPORTED_API_VERSION = 18; + static const int8_t ANNOTATION_SUPPORTED_API_VERSION = 20; static constexpr std::string_view SUB_API_VERSION_1 = "beta1"; static constexpr std::string_view SUB_API_VERSION_2 = "beta2"; static constexpr std::string_view DEFAULT_SUB_API_VERSION = SUB_API_VERSION_1; -- Gitee From 932223f839ad383b7f3858e62ab520d53dc92d25 Mon Sep 17 00:00:00 2001 From: Lyupa Anastasia Date: Thu, 24 Apr 2025 18:35:15 +0300 Subject: [PATCH 154/268] Fix codecheck 20250424 Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC3SBN Change-Id: I2057e0cefa4af0372368e7e8f90fa5452ff96be5 Signed-off-by: Lyupa Anastasia --- ets2panda/parser/TypedParser.cpp | 1 + ets2panda/parser/expressionParser.cpp | 1 + 2 files changed, 2 insertions(+) diff --git a/ets2panda/parser/TypedParser.cpp b/ets2panda/parser/TypedParser.cpp index 94ba932dc9..30c4b499d6 100644 --- a/ets2panda/parser/TypedParser.cpp +++ b/ets2panda/parser/TypedParser.cpp @@ -164,6 +164,7 @@ ir::Statement *TypedParser::ParsePotentialExpressionStatement(StatementParsingFl if (((GetContext().Status() & ParserStatus::IN_AMBIENT_CONTEXT) != 0U) || IsNamespaceDecl()) { return ParseModuleDeclaration(); } + [[fallthrough]]; } default: { break; diff --git a/ets2panda/parser/expressionParser.cpp b/ets2panda/parser/expressionParser.cpp index a14402f5d8..37c03683eb 100644 --- a/ets2panda/parser/expressionParser.cpp +++ b/ets2panda/parser/expressionParser.cpp @@ -712,6 +712,7 @@ ir::Expression *ParserImpl::ParseAssignmentEqualExpression(const lexer::TokenTyp LogUnexpectedToken(tokenType); lexer_->NextToken(); // eat token ParseExpression(); // Try to parse expression, but skip the result. + [[fallthrough]]; } default: break; -- Gitee From a6b7cef75fd603d46a79f2d1cdc04b677a71af34 Mon Sep 17 00:00:00 2001 From: ozerovnikita Date: Tue, 25 Mar 2025 22:20:53 +0300 Subject: [PATCH 155/268] fix src interface dump Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBW9YQ Test: ninja es2panda-plugin-test Change-Id: I382e6c5847601d95367fdff743807a06c7a9d221 Signed-off-by: ozerovnikita --- ets2panda/checker/ets/helpers.cpp | 25 +++-- ets2panda/ir/base/methodDefinition.cpp | 3 +- ets2panda/ir/expressions/identifier.cpp | 7 +- ets2panda/parser/ETSparser.h | 3 +- ets2panda/parser/ETSparserAnnotations.cpp | 6 - ets2panda/parser/ETSparserClasses.cpp | 9 +- .../annotationUsage_on_abstract_class.ets | 4 +- .../annotationUsage_on_abstract_method.ets | 13 +-- ets2panda/test/unit/plugin/CMakeLists.txt | 1 + ..._state_test_interface_duplicate_setter.cpp | 106 ++++++++++++++++++ 10 files changed, 141 insertions(+), 36 deletions(-) create mode 100644 ets2panda/test/unit/plugin/plugin_proceed_to_state_test_interface_duplicate_setter.cpp diff --git a/ets2panda/checker/ets/helpers.cpp b/ets2panda/checker/ets/helpers.cpp index 33ed14bf36..7565aca473 100644 --- a/ets2panda/checker/ets/helpers.cpp +++ b/ets2panda/checker/ets/helpers.cpp @@ -2670,10 +2670,10 @@ static ir::BlockStatement *GenGetterSetterBodyHelper(ETSChecker *checker, ArenaV return body; } -ir::MethodDefinition *ETSChecker::GenerateDefaultGetterSetter(ir::ClassProperty *const property, - ir::ClassProperty *const field, - varbinder::ClassScope *classScope, bool isSetter, - ETSChecker *checker) +// Need to avoid codecheck +static std::tuple GenGetterSetterScriptFunc( + ir::ClassProperty *const property, ir::ClassProperty *const field, varbinder::ClassScope *classScope, bool isSetter, + ETSChecker *checker) { auto *paramScope = checker->Allocator()->New(checker->Allocator(), classScope); auto *functionScope = checker->Allocator()->New(checker->Allocator(), paramScope); @@ -2705,7 +2705,18 @@ ir::MethodDefinition *ETSChecker::GenerateDefaultGetterSetter(ir::ClassProperty ir::ScriptFunction::ScriptFunctionData {GenGetterSetterBodyHelper(checker, stmts, property, functionScope), ir::FunctionSignature(nullptr, std::move(params), returnTypeAnn), funcFlags, modifierFlag}); + paramScope->BindNode(func); + return {func, functionScope, modifierFlag}; +} +ir::MethodDefinition *ETSChecker::GenerateDefaultGetterSetter(ir::ClassProperty *const property, + ir::ClassProperty *const field, + varbinder::ClassScope *classScope, bool isSetter, + ETSChecker *checker) +{ + auto [func, functionScope, modifierFlag] = + // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) + GenGetterSetterScriptFunc(property, field, classScope, isSetter, checker); func->SetRange(field->Range()); func->SetScope(functionScope); // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) @@ -2715,8 +2726,9 @@ ir::MethodDefinition *ETSChecker::GenerateDefaultGetterSetter(ir::ClassProperty funcExpr->SetRange(func->Range()); func->AddFlag(ir::ScriptFunctionFlags::METHOD); // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) - auto *method = checker->AllocNode(ir::MethodDefinitionKind::METHOD, methodIdent, funcExpr, - modifierFlag, checker->Allocator(), false); + auto *method = checker->AllocNode( + isSetter ? ir::MethodDefinitionKind::SET : ir::MethodDefinitionKind::GET, methodIdent, funcExpr, modifierFlag, + checker->Allocator(), false); auto *decl = checker->Allocator()->New(checker->Allocator(), property->Key()->AsIdentifier()->Name(), method); auto *var = checker->Allocator()->New(decl, varbinder::VariableFlags::VAR); @@ -2732,7 +2744,6 @@ ir::MethodDefinition *ETSChecker::GenerateDefaultGetterSetter(ir::ClassProperty method->SetVariable(var); method->SetParent(field->Parent()); - paramScope->BindNode(func); functionScope->BindNode(func); auto classCtx = varbinder::LexicalScope::Enter(checker->VarBinder(), classScope); diff --git a/ets2panda/ir/base/methodDefinition.cpp b/ets2panda/ir/base/methodDefinition.cpp index f756c90372..9d9770bfd8 100644 --- a/ets2panda/ir/base/methodDefinition.cpp +++ b/ets2panda/ir/base/methodDefinition.cpp @@ -182,7 +182,8 @@ void MethodDefinition::DumpPrefix(ir::SrcDumper *dumper) const dumper->Add("static "); } - if (IsAbstract()) { + if (IsAbstract() && !(Parent()->IsTSInterfaceBody() || + (BaseOverloadMethod() != nullptr && BaseOverloadMethod()->Parent()->IsTSInterfaceBody()))) { dumper->Add("abstract "); } diff --git a/ets2panda/ir/expressions/identifier.cpp b/ets2panda/ir/expressions/identifier.cpp index 3234d31f5d..c384d5d5f0 100644 --- a/ets2panda/ir/expressions/identifier.cpp +++ b/ets2panda/ir/expressions/identifier.cpp @@ -143,7 +143,12 @@ void Identifier::Dump(ir::SrcDumper *dumper) const dumper->Add("private "); } - dumper->Add(std::string(name_)); + auto name = std::string(name_); + std::string propertyStr = compiler::Signatures::PROPERTY.data(); + if (UNLIKELY(name.find(propertyStr) != std::string::npos)) { + name.replace(name.find(propertyStr), propertyStr.length(), "_$property$_"); + } + dumper->Add(name); if (IsOptional()) { dumper->Add("?"); } diff --git a/ets2panda/parser/ETSparser.h b/ets2panda/parser/ETSparser.h index e6e1a76c00..52195e384d 100644 --- a/ets2panda/parser/ETSparser.h +++ b/ets2panda/parser/ETSparser.h @@ -441,8 +441,7 @@ private: ir::ModifierFlags modFlags = ir::ModifierFlags::NONE) override; ir::AstNode *ParseClassElement(const ArenaVector &properties, ir::ClassDefinitionModifiers modifiers, ir::ModifierFlags flags) override; - std::tuple HandleClassElementModifiers(ArenaVector &annotations, - ir::ModifierFlags &memberModifiers); + std::tuple HandleClassElementModifiers(ir::ModifierFlags &memberModifiers); void UpdateMemberModifiers(ir::ModifierFlags &memberModifiers, bool &seenStatic); ir::ModifierFlags ParseMemberAccessModifiers(); template diff --git a/ets2panda/parser/ETSparserAnnotations.cpp b/ets2panda/parser/ETSparserAnnotations.cpp index 511953a3c3..f95b1bb943 100644 --- a/ets2panda/parser/ETSparserAnnotations.cpp +++ b/ets2panda/parser/ETSparserAnnotations.cpp @@ -273,12 +273,6 @@ void ETSParser::ApplyAnnotationsToNode(ir::AstNode *node, ArenaVectorIsAnnotationDeclaration() && node->IsAbstract()) || - (node->IsClassDeclaration() && node->AsClassDeclaration()->Definition()->IsAbstract())) { - LogError(diagnostic::ANNOTATION_ABSTRACT, {}, pos); - return; - } - if (node->IsExpressionStatement()) { ApplyAnnotationsToNode(node->AsExpressionStatement()->GetExpression(), std::move(annotations), pos); return; diff --git a/ets2panda/parser/ETSparserClasses.cpp b/ets2panda/parser/ETSparserClasses.cpp index 78e588a47d..eed7dce2af 100644 --- a/ets2panda/parser/ETSparserClasses.cpp +++ b/ets2panda/parser/ETSparserClasses.cpp @@ -584,8 +584,7 @@ void ETSParser::UpdateMemberModifiers(ir::ModifierFlags &memberModifiers, bool & } } -std::tuple ETSParser::HandleClassElementModifiers(ArenaVector &annotations, - ir::ModifierFlags &memberModifiers) +std::tuple ETSParser::HandleClassElementModifiers(ir::ModifierFlags &memberModifiers) { auto [modifierFlags, isStepToken, isDefault] = ParseClassMemberAccessModifiers(); memberModifiers |= modifierFlags; @@ -593,10 +592,6 @@ std::tuple ETSParser::HandleClassElementModifiers(ArenaVector< bool seenStatic = false; UpdateMemberModifiers(memberModifiers, seenStatic); - if (!annotations.empty() && (memberModifiers & ir::ModifierFlags::ABSTRACT) != 0) { - LogError(diagnostic::ANNOTATION_ABSTRACT, {}, Lexer()->GetToken().Start()); - } - return {seenStatic, isStepToken, isDefault}; } @@ -619,7 +614,7 @@ ir::AstNode *ETSParser::ParseClassElement(const ArenaVector &prop return ParseClassStaticBlock(); } - auto [seenStatic, isStepToken, isDefault] = HandleClassElementModifiers(annotations, memberModifiers); + auto [seenStatic, isStepToken, isDefault] = HandleClassElementModifiers(memberModifiers); ir::AstNode *result = nullptr; auto delcStartLoc = Lexer()->GetToken().Start(); diff --git a/ets2panda/test/ast/parser/ets/annotations_tests/annotationUsage_on_abstract_class.ets b/ets2panda/test/ast/parser/ets/annotations_tests/annotationUsage_on_abstract_class.ets index e036c1ef95..b42c1ed5f2 100644 --- a/ets2panda/test/ast/parser/ets/annotations_tests/annotationUsage_on_abstract_class.ets +++ b/ets2panda/test/ast/parser/ets/annotations_tests/annotationUsage_on_abstract_class.ets @@ -18,6 +18,4 @@ } @MyAnno({testProperty1: "Bob", testProperty2: 1}) -/* @@ label */abstract class A {} - -/* @@@ label Error SyntaxError: Annotations are not allowed on an abstract class or methods. */ +abstract class A {} diff --git a/ets2panda/test/ast/parser/ets/annotations_tests/annotationUsage_on_abstract_method.ets b/ets2panda/test/ast/parser/ets/annotations_tests/annotationUsage_on_abstract_method.ets index b40fc2b0c6..18116592d3 100644 --- a/ets2panda/test/ast/parser/ets/annotations_tests/annotationUsage_on_abstract_method.ets +++ b/ets2panda/test/ast/parser/ets/annotations_tests/annotationUsage_on_abstract_method.ets @@ -18,14 +18,9 @@ } abstract class A { - @MyAnno() + @MyAnno({testProperty1: "123", testProperty2: 123}) foo1(){} // OK - @MyAnno() - abstract foo2() //CTE -} - -/* @@? 25:14 Error SyntaxError: Annotations are not allowed on an abstract class or methods. */ -/* @@? 25:14 Error SyntaxError: Annotations are not allowed on an abstract class or methods. */ -/* @@? 21:6 Error TypeError: The required field 'testProperty2' must be specified. Fields without default values cannot be omitted. */ -/* @@? 21:6 Error TypeError: The required field 'testProperty1' must be specified. Fields without default values cannot be omitted. */ + @MyAnno({testProperty1: "123", testProperty2: 123}) + abstract foo2() // OK +} diff --git a/ets2panda/test/unit/plugin/CMakeLists.txt b/ets2panda/test/unit/plugin/CMakeLists.txt index 3456abfeb2..b524c32c9c 100644 --- a/ets2panda/test/unit/plugin/CMakeLists.txt +++ b/ets2panda/test/unit/plugin/CMakeLists.txt @@ -98,6 +98,7 @@ set(PLUGIN_TESTS "plugin_proceed_to_state_assignment_expression_set_result compile.ets ${COMPILE_MODE} cpp ${EXECUTABLE_PLUGIN}" "use_plugin_to_test_export_table compile.ets ${COMPILE_MODE} cpp ${EXECUTABLE_PLUGIN}" "plugin_proceed_to_state_test_global_func_call_dump compile.ets ${COMPILE_MODE} cpp ${EXECUTABLE_PLUGIN}" + "plugin_proceed_to_state_test_interface_duplicate_setter compile.ets ${COMPILE_MODE} cpp ${EXECUTABLE_PLUGIN}" ) set(RUNTIME_ARGUMENTS diff --git a/ets2panda/test/unit/plugin/plugin_proceed_to_state_test_interface_duplicate_setter.cpp b/ets2panda/test/unit/plugin/plugin_proceed_to_state_test_interface_duplicate_setter.cpp new file mode 100644 index 0000000000..66cacf08fe --- /dev/null +++ b/ets2panda/test/unit/plugin/plugin_proceed_to_state_test_interface_duplicate_setter.cpp @@ -0,0 +1,106 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include "util.h" +#include "public/es2panda_lib.h" + +// NOLINTBEGIN + +static es2panda_Impl *impl = nullptr; + +static std::string source = R"( +interface I { + p: number; +} + +interface J { + p: number; +} + +class A implements I { + private prop: number = 4.0; + + get p(): number { + return this.prop; + } + + set p(value: number) { + this.prop = value; + } +} + +class B implements J { + private prop: number = 4.0; + public p: number = 5.0; +} +)"; + +int main(int argc, char **argv) +{ + if (argc < MIN_ARGC) { + return 1; + } + + if (GetImpl() == nullptr) { + return NULLPTR_IMPL_ERROR_CODE; + } + impl = GetImpl(); + std::cout << "LOAD SUCCESS" << std::endl; + const char **args = const_cast(&(argv[1])); + auto config = impl->CreateConfig(argc - 1, args); + auto context = impl->CreateContextFromString(config, source.data(), argv[argc - 1]); + if (context != nullptr) { + std::cout << "CREATE CONTEXT SUCCESS" << std::endl; + } + + impl->ProceedToState(context, ES2PANDA_STATE_CHECKED); + CheckForErrors("CHECKED", context); + + std::string dump = impl->AstNodeDumpEtsSrcConst(context, impl->ProgramAst(context, impl->ContextProgram(context))); + std::cout << dump << std::endl; + + impl->ProceedToState(context, ES2PANDA_STATE_BIN_GENERATED); + if (impl->ContextState(context) == ES2PANDA_STATE_ERROR) { + impl->DestroyContext(context); + impl->DestroyConfig(config); + return PROCEED_ERROR_CODE; + } + impl->DestroyContext(context); + impl->DestroyConfig(config); + + // Rerun es2panda on dumped source + config = impl->CreateConfig(argc - 1, args); + context = impl->CreateContextFromString(config, dump.data(), argv[argc - 1]); + if (context != nullptr) { + std::cout << "CREATE CONTEXT SUCCESS" << std::endl; + } + + impl->ProceedToState(context, ES2PANDA_STATE_BIN_GENERATED); + if (impl->ContextState(context) == ES2PANDA_STATE_ERROR) { + impl->DestroyContext(context); + impl->DestroyConfig(config); + return PROCEED_ERROR_CODE; + } + impl->DestroyContext(context); + impl->DestroyConfig(config); + + return 0; +} + +// NOLINTEND -- Gitee From bc9deda35ae047c5905764e45ad958c02c50238d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=A8=E4=BA=91=E9=A3=9E?= Date: Wed, 14 May 2025 20:34:42 +0800 Subject: [PATCH 156/268] =?UTF-8?q?contest=E9=9C=80=E6=B1=82=E6=8C=91?= =?UTF-8?q?=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Issue: https://gitee.com/openharmony/arkcompiler_ets_runtime/issues/IC7TW8?from=project-issue Signed-off-by: 杨云飞 --- .../cases/conformance/functions/test-ts-declare-function-1.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/es2panda/test/compiler/ts/cases/conformance/functions/test-ts-declare-function-1.ts b/es2panda/test/compiler/ts/cases/conformance/functions/test-ts-declare-function-1.ts index 0cb3633e5b..c2ec7c2624 100644 --- a/es2panda/test/compiler/ts/cases/conformance/functions/test-ts-declare-function-1.ts +++ b/es2panda/test/compiler/ts/cases/conformance/functions/test-ts-declare-function-1.ts @@ -24,8 +24,8 @@ class C { } let c = new C(); -let env = ArkTools.getLexicalEnv(c.method1); -if (env !== undefined) { +let res = ArkTools.currentEnvIsGlobal(c.method1); +if (res !== true) { print(1); } else { print(2); -- Gitee From 18de9e9c6718bf2192f55d677933b43171d03241 Mon Sep 17 00:00:00 2001 From: Vivien Voros Date: Mon, 24 Mar 2025 18:03:20 +0100 Subject: [PATCH 157/268] Compilation error for keywords CTE to the next keywords, used as identifier: bigint, boolean, byte, char, double, float, int, long, short, void. https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBVYBK Internal Issue: #23500 Change-Id: I886671331d6bc385e56d93bc08064b19368f686b Change-Id: Ifda8dd8a3e21ab56ed3af2a574c5b20f33322075 Signed-off-by: Vivien Voros --- ets2panda/lexer/scripts/keywords.yaml | 20 +- ets2panda/parser/ETSparser.cpp | 19 + ets2panda/parser/ETSparserExpressions.cpp | 6 +- ets2panda/parser/ETSparserTypes.cpp | 18 +- ets2panda/parser/TypedParser.h | 3 + .../ast/compiler/ets/Incorrect_arrow_func.ets | 6 +- .../ast/compiler/ets/declareType_neg_1.ets | 6 +- .../type_error_processing/var_without_def.ets | 3 +- .../test/ast/compiler/ets/union_method.ets | 8 +- .../ets/void_as_return_type_neg_1.ets | 5 +- .../ast/compiler/ets/void_as_value_neg_3.ets | 11 +- .../ets/FixedArray/MultipleParserErrors.ets | 17 +- .../parser/ets/FixedArray/invalidTypes.ets | 4 +- .../ets/FixedArray/rest_parameter_04.ets | 4 +- .../ets/FixedArray/unexpected_token_31.ets | 4 +- .../ets/FixedArray/unexpected_token_36.ets | 4 +- .../ast/parser/ets/InvalidExpressions1.ets | 9 +- .../test/ast/parser/ets/InvalidParserImpl.ets | 13 +- .../ast/parser/ets/MultipleParserErrors.ets | 15 +- ...ionUsage_missing_AT_for_function_param.ets | 12 +- ets2panda/test/ast/parser/ets/for_of_04.ets | 14 +- .../test/ast/parser/ets/invalidTypes.ets | 4 +- ...mbda_omit_parentheses_type_alias_neg_1.ets | 6 +- .../ast/parser/ets/namespace_badtoken04.ets | 2 + .../test/ast/parser/ets/rest_parameter_04.ets | 4 +- .../ast/parser/ets/unexpected_token_31.ets | 4 +- .../ast/parser/ets/unexpected_token_36.ets | 4 +- .../test/ast/parser/ets/user_defined_5.ets | 3 +- .../test/ast/parser/ets/user_defined_7.ets | 1 + .../parser/ets/user_defined_1-expected.txt | 766 ---------- ets2panda/test/parser/ets/user_defined_1.ets | 24 - .../parser/ets/user_defined_2-expected.txt | 808 ----------- ets2panda/test/parser/ets/user_defined_2.ets | 25 - .../parser/ets/user_defined_3-expected.txt | 1248 ----------------- ets2panda/test/parser/ets/user_defined_3.ets | 34 - ets2panda/test/parser/ets/user_defined_4.ets | 16 - .../parser/ets/user_defined_6-expected.txt | 385 ----- ets2panda/test/parser/ets/user_defined_6.ets | 17 - ets2panda/test/runtime/ets/user_defined_1.ets | 3 - ets2panda/test/runtime/ets/user_defined_2.ets | 21 - 40 files changed, 148 insertions(+), 3428 deletions(-) delete mode 100644 ets2panda/test/parser/ets/user_defined_1-expected.txt delete mode 100644 ets2panda/test/parser/ets/user_defined_1.ets delete mode 100644 ets2panda/test/parser/ets/user_defined_2-expected.txt delete mode 100644 ets2panda/test/parser/ets/user_defined_2.ets delete mode 100644 ets2panda/test/parser/ets/user_defined_3-expected.txt delete mode 100644 ets2panda/test/parser/ets/user_defined_3.ets delete mode 100644 ets2panda/test/parser/ets/user_defined_4.ets delete mode 100644 ets2panda/test/parser/ets/user_defined_6-expected.txt delete mode 100644 ets2panda/test/parser/ets/user_defined_6.ets delete mode 100644 ets2panda/test/runtime/ets/user_defined_2.ets diff --git a/ets2panda/lexer/scripts/keywords.yaml b/ets2panda/lexer/scripts/keywords.yaml index 5d1af91329..48f97e7700 100644 --- a/ets2panda/lexer/scripts/keywords.yaml +++ b/ets2panda/lexer/scripts/keywords.yaml @@ -72,7 +72,8 @@ keywords: - name: 'boolean' token: KEYW_BOOLEAN - keyword_like: [ets, js, ts] + keyword: [ets] + keyword_like: [js, ts] flags: [reserved_type_name, definable_type_name] - name: 'Boolean' @@ -87,7 +88,7 @@ keywords: - name: 'byte' token: KEYW_BYTE - keyword_like: [ets] + keyword: [ets] flags: [reserved_type_name, definable_type_name] - name: 'Byte' @@ -107,7 +108,7 @@ keywords: - name: 'char' token: KEYW_CHAR - keyword_like: [ets] + keyword: [ets] flags: [reserved_type_name, definable_type_name] - name: 'Char' @@ -161,7 +162,7 @@ keywords: - name: 'double' token: KEYW_DOUBLE - keyword_like: [ets] + keyword: [ets] flags: [reserved_type_name, definable_type_name] - name: 'Double' @@ -222,7 +223,7 @@ keywords: - name: 'float' token: KEYW_FLOAT - keyword_like: [ets] + keyword: [ets] flags: [reserved_type_name, definable_type_name] - name: 'Float' @@ -307,7 +308,7 @@ keywords: - name: 'int' token: KEYW_INT - keyword_like: [ets] + keyword: [ets] flags: [reserved_type_name, definable_type_name] - name: 'Int' @@ -342,7 +343,7 @@ keywords: - name: 'long' token: KEYW_LONG - keyword_like: [ets] + keyword: [ets] flags: [reserved_type_name, definable_type_name] - name: 'Long' @@ -461,7 +462,7 @@ keywords: - name: 'short' token: KEYW_SHORT - keyword_like: [ets] + keyword: [ets] flags: [reserved_type_name, definable_type_name] - name: 'Short' @@ -575,8 +576,7 @@ keywords: - name: 'void' token: KEYW_VOID - keyword: [as, js, ts] - keyword_like: [ets] + keyword: [as, ets, js, ts] flags: [unary, reserved_type_name, definable_type_name] - name: 'while' diff --git a/ets2panda/parser/ETSparser.cpp b/ets2panda/parser/ETSparser.cpp index 1734a7eec8..78d9e7037f 100644 --- a/ets2panda/parser/ETSparser.cpp +++ b/ets2panda/parser/ETSparser.cpp @@ -1145,6 +1145,25 @@ bool ETSParser::IsDefaultImport() return false; } +bool TypedParser::IsPrimitiveType(const lexer::TokenType &tokenType) +{ + switch (tokenType) { + case lexer::TokenType::KEYW_BIGINT: + case lexer::TokenType::KEYW_BOOLEAN: + case lexer::TokenType::KEYW_BYTE: + case lexer::TokenType::KEYW_CHAR: + case lexer::TokenType::KEYW_DOUBLE: + case lexer::TokenType::KEYW_FLOAT: + case lexer::TokenType::KEYW_INT: + case lexer::TokenType::KEYW_LONG: + case lexer::TokenType::KEYW_SHORT: + case lexer::TokenType::KEYW_VOID: + return true; + default: + return false; + } +} + void ETSParser::ParseNamedSpecifiesDefaultImport(ArenaVector *resultDefault, const std::string &fileName) { diff --git a/ets2panda/parser/ETSparserExpressions.cpp b/ets2panda/parser/ETSparserExpressions.cpp index 4ba354bbae..0c119f540a 100644 --- a/ets2panda/parser/ETSparserExpressions.cpp +++ b/ets2panda/parser/ETSparserExpressions.cpp @@ -370,13 +370,13 @@ bool IsPunctuartorSpecialCharacter(lexer::TokenType tokenType) } // This function was created to reduce the size of `EatArrowFunctionParams`. -static bool IsValidTokenTypeOfArrowFunctionStart(lexer::TokenType tokenType) +bool TypedParser::IsValidTokenTypeOfArrowFunctionStart(lexer::TokenType tokenType) { - return (tokenType == lexer::TokenType::LITERAL_IDENT || + return (tokenType == lexer::TokenType::LITERAL_IDENT || IsPrimitiveType(tokenType) || tokenType == lexer::TokenType::PUNCTUATOR_PERIOD_PERIOD_PERIOD || tokenType == lexer::TokenType::KEYW_THIS); } -static bool EatArrowFunctionParams(lexer::Lexer *lexer) +bool TypedParser::EatArrowFunctionParams(lexer::Lexer *lexer) { ES2PANDA_ASSERT(lexer->GetToken().Type() == lexer::TokenType::PUNCTUATOR_LEFT_PARENTHESIS); lexer->NextToken(); diff --git a/ets2panda/parser/ETSparserTypes.cpp b/ets2panda/parser/ETSparserTypes.cpp index 98a1a79cd7..76d23f6e42 100644 --- a/ets2panda/parser/ETSparserTypes.cpp +++ b/ets2panda/parser/ETSparserTypes.cpp @@ -309,15 +309,17 @@ ir::TypeNode *ETSParser::ParsePotentialFunctionalType(TypeAnnotationParsingOptio // Just to reduce the size of ParseTypeAnnotation(...) method std::pair ETSParser::GetTypeAnnotationFromToken(TypeAnnotationParsingOptions *options) { - switch (Lexer()->GetToken().Type()) { - case lexer::TokenType::LITERAL_IDENT: { - auto typeAnnotation = ParseLiteralIdent(options); - if (((*options) & TypeAnnotationParsingOptions::POTENTIAL_CLASS_LITERAL) != 0 && - (Lexer()->GetToken().Type() == lexer::TokenType::KEYW_CLASS || IsStructKeyword())) { - return std::make_pair(typeAnnotation, false); - } - return std::make_pair(typeAnnotation, true); + auto tokenType = Lexer()->GetToken().Type(); + if (IsPrimitiveType(Lexer()->GetToken().KeywordType()) || tokenType == lexer::TokenType::LITERAL_IDENT) { + auto typeAnnotation = ParseLiteralIdent(options); + if (((*options) & TypeAnnotationParsingOptions::POTENTIAL_CLASS_LITERAL) != 0 && + (Lexer()->GetToken().Type() == lexer::TokenType::KEYW_CLASS || IsStructKeyword())) { + return std::make_pair(typeAnnotation, false); } + return std::make_pair(typeAnnotation, true); + } + + switch (tokenType) { case lexer::TokenType::LITERAL_NULL: { auto typeAnnotation = AllocNode(Allocator()); typeAnnotation->SetRange(Lexer()->GetToken().Loc()); diff --git a/ets2panda/parser/TypedParser.h b/ets2panda/parser/TypedParser.h index d9caee03b6..8101ab7123 100644 --- a/ets2panda/parser/TypedParser.h +++ b/ets2panda/parser/TypedParser.h @@ -73,6 +73,9 @@ protected: bool CheckClassElement(ir::AstNode *property, ir::MethodDefinition *&ctor, ArenaVector &properties) override; bool IsNamespaceDecl(); + bool IsPrimitiveType(const lexer::TokenType &tokenType); + bool IsValidTokenTypeOfArrowFunctionStart(lexer::TokenType tokenType); + bool EatArrowFunctionParams(lexer::Lexer *lexer); ir::ModifierFlags ParseModifiers() override; ParserStatus ValidateArrowParameter(ir::Expression *expr, bool *seenOptional) override; diff --git a/ets2panda/test/ast/compiler/ets/Incorrect_arrow_func.ets b/ets2panda/test/ast/compiler/ets/Incorrect_arrow_func.ets index 0833b29c81..e4aa2cd0ce 100644 --- a/ets2panda/test/ast/compiler/ets/Incorrect_arrow_func.ets +++ b/ets2panda/test/ast/compiler/ets/Incorrect_arrow_func.ets @@ -16,6 +16,8 @@ let f = ()=>int {} f() -/* @@? 16:13 Error TypeError: Unresolved reference int */ +/* @@? 16:13 Error SyntaxError: Unexpected token 'int'. */ +/* @@? 16:13 Error SyntaxError: Unexpected token 'int'. */ +/* @@? 16:13 Error SyntaxError: Unexpected token 'int'. */ +/* @@? 16:13 Error SyntaxError: Unexpected token 'int'. */ /* @@? 16:13 Error TypeError: Unexpected return value, enclosing method return type is void. */ -/* @@? 16:17 Error SyntaxError: Unexpected token '{'. */ diff --git a/ets2panda/test/ast/compiler/ets/declareType_neg_1.ets b/ets2panda/test/ast/compiler/ets/declareType_neg_1.ets index 0d5dab8c8a..ad56d9aa62 100644 --- a/ets2panda/test/ast/compiler/ets/declareType_neg_1.ets +++ b/ets2panda/test/ast/compiler/ets/declareType_neg_1.ets @@ -19,5 +19,7 @@ declare const type typeA = int; /* @@? 16:20 Error SyntaxError: Variable must be initialized or it's type must be declared. */ /* @@? 16:20 Error SyntaxError: Unexpected token 'typeA'. */ /* @@? 16:20 Error TypeError: Unresolved reference typeA */ -/* @@? 16:28 Error TypeError: Unresolved reference int */ - +/* @@? 16:28 Error SyntaxError: Unexpected token 'int'. */ +/* @@? 16:28 Error SyntaxError: Unexpected token 'int'. */ +/* @@? 16:28 Error SyntaxError: Unexpected token 'int'. */ +/* @@? 16:28 Error SyntaxError: Unexpected token 'int'. */ diff --git a/ets2panda/test/ast/compiler/ets/type_error_processing/var_without_def.ets b/ets2panda/test/ast/compiler/ets/type_error_processing/var_without_def.ets index e183093f43..f845db8bb1 100644 --- a/ets2panda/test/ast/compiler/ets/type_error_processing/var_without_def.ets +++ b/ets2panda/test/ast/compiler/ets/type_error_processing/var_without_def.ets @@ -26,5 +26,6 @@ function foo() { /* @@? 16:1 Error TypeError: Unresolved reference a */ /* @@? 20:1 Error TypeError: Unresolved reference c */ -/* @@? 24:5 Error TypeError: Unresolved reference void */ +/* @@? 24:5 Error SyntaxError: Unexpected token 'void'. */ +/* @@? 24:10 Error SyntaxError: Unexpected token '='. */ /* @@? 24:18 Error TypeError: Unresolved reference asyncGenerator */ diff --git a/ets2panda/test/ast/compiler/ets/union_method.ets b/ets2panda/test/ast/compiler/ets/union_method.ets index 8820ee691a..9a46c72c40 100644 --- a/ets2panda/test/ast/compiler/ets/union_method.ets +++ b/ets2panda/test/ast/compiler/ets/union_method.ets @@ -14,19 +14,19 @@ */ class A { - short(v: string): void {} + shorting(v: string): void {} ordinary(a: int, b: int, c: int): void {} range(a: int, b: int, c: int, d: int, e: int, f: int): void {} } class B { - short(v: string): void {} + shorting(v: string): void {} ordinary(a: int, b: int, c: int): void {} range(a: int, b: int, c: int, d: int, e: int, f: int): void {} } -function short(x: A|B) { - x.short("123") +function shorting(x: A|B) { + x.shorting("123") } function ordinary(x: A|B) { diff --git a/ets2panda/test/ast/compiler/ets/void_as_return_type_neg_1.ets b/ets2panda/test/ast/compiler/ets/void_as_return_type_neg_1.ets index 1626420399..c54c59d67a 100644 --- a/ets2panda/test/ast/compiler/ets/void_as_return_type_neg_1.ets +++ b/ets2panda/test/ast/compiler/ets/void_as_return_type_neg_1.ets @@ -17,4 +17,7 @@ async function foo():Promise{ return void; } -/* @@? 17:12 Error TypeError: Unresolved reference void */ \ No newline at end of file +/* @@? 17:12 Error SyntaxError: Unexpected token 'void'. */ +/* @@? 17:12 Error SyntaxError: Unexpected token 'void'. */ +/* @@? 17:12 Error SyntaxError: Unexpected token 'void'. */ +/* @@? 17:12 Error SyntaxError: Unexpected token 'void'. */ diff --git a/ets2panda/test/ast/compiler/ets/void_as_value_neg_3.ets b/ets2panda/test/ast/compiler/ets/void_as_value_neg_3.ets index a292b7d176..d93580a127 100644 --- a/ets2panda/test/ast/compiler/ets/void_as_value_neg_3.ets +++ b/ets2panda/test/ast/compiler/ets/void_as_value_neg_3.ets @@ -15,7 +15,12 @@ function foo(x: T) {} -foo(/* @@ label */void) - -/* @@@ label Error TypeError: Unresolved reference void */ +foo(void) +/* @@? 18:11 Error SyntaxError: Unexpected token 'void'. */ +/* @@? 18:11 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 18:11 Error SyntaxError: Unexpected token 'void'. */ +/* @@? 18:11 Error SyntaxError: Unexpected token 'void'. */ +/* @@? 18:11 Error SyntaxError: Unexpected token 'void'. */ +/* @@? 18:15 Error SyntaxError: Unexpected token ')'. */ +/* @@? 18:15 Error SyntaxError: Unexpected token ')'. */ diff --git a/ets2panda/test/ast/parser/ets/FixedArray/MultipleParserErrors.ets b/ets2panda/test/ast/parser/ets/FixedArray/MultipleParserErrors.ets index 558fbe032a..78b272bb38 100644 --- a/ets2panda/test/ast/parser/ets/FixedArray/MultipleParserErrors.ets +++ b/ets2panda/test/ast/parser/ets/FixedArray/MultipleParserErrors.ets @@ -174,8 +174,8 @@ function main(): void { /* @@? 39:14 Error SyntaxError: Unexpected token, expected ',' or ')'. */ /* @@? 39:14 Error SyntaxError: Unexpected token, expected an identifier. */ /* @@? 39:24 Error SyntaxError: Unexpected token 'int'. */ -/* @@? 39:24 Error TypeError: Unresolved reference int */ -/* @@? 39:27 Error SyntaxError: Unexpected token ')'. */ +/* @@? 39:24 Error SyntaxError: Unexpected token 'int'. */ +/* @@? 39:24 Error SyntaxError: Unexpected token 'int'. */ /* @@? 39:27 Error SyntaxError: Unexpected token ')'. */ /* @@? 39:27 Error SyntaxError: Unexpected token ')'. */ /* @@? 39:31 Error SyntaxError: return keyword should be used in function body. */ @@ -195,12 +195,13 @@ function main(): void { /* @@? 51:43 Error SyntaxError: Label must be followed by a loop statement. */ /* @@? 51:43 Error TypeError: Unresolved reference FixedArray */ /* @@? 51:58 Error SyntaxError: Unexpected token, expected '('. */ -/* @@? 51:59 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 51:59 Error SyntaxError: Unexpected token ':'. */ /* @@? 51:59 Error SyntaxError: Unexpected token ':'. */ +/* @@? 51:59 Error SyntaxError: Unexpected token, expected ',' or ')'. */ /* @@? 51:59 Error SyntaxError: Unexpected token ':'. */ +/* @@? 51:59 Error SyntaxError: Unexpected token, expected ',' or ')'. */ /* @@? 51:59 Error SyntaxError: Unexpected token ':'. */ -/* @@? 51:65 Error SyntaxError: Unexpected token '{'. */ +/* @@? 51:61 Error SyntaxError: Unexpected token 'int'. */ +/* @@? 51:61 Error SyntaxError: Unexpected token 'int'. */ /* @@? 52:5 Error SyntaxError: return keyword should be used in function body. */ /* @@? 52:12 Error TypeError: Unresolved reference q */ /* @@? 52:12 Error TypeError: All return statements in the function should be empty or have a value. */ @@ -226,6 +227,10 @@ function main(): void { /* @@? 115:26 Error SyntaxError: Unexpected token, expected ',' or ')'. */ /* @@? 115:26 Error SyntaxError: Parameter declaration should have an explicit type annotation. */ /* @@? 115:26 Error SyntaxError: Unexpected token, expected an identifier. */ +/* @@? 115:26 Error SyntaxError: Parameter declaration should have an explicit type annotation. */ +/* @@? 115:26 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 115:26 Error SyntaxError: Unexpected token 'case'. */ +/* @@? 115:26 Error SyntaxError: Unexpected token 'case'. */ /* @@? 115:30 Error SyntaxError: Unexpected token ':'. */ /* @@? 115:30 Error SyntaxError: Unexpected token ':'. */ /* @@? 115:32 Error TypeError: Unresolved reference U */ @@ -284,4 +289,4 @@ function main(): void { /* @@? 165:5 Error TypeError: This expression is not callable. */ /* @@? 166:5 Error TypeError: Expected 1 arguments, got 0. */ /* @@? 166:5 Error TypeError: No matching call signature */ -/* @@? 288:1 Error SyntaxError: Expected '}', got 'eos'. */ +/* @@? 293:1 Error SyntaxError: Expected '}', got 'eos'. */ diff --git a/ets2panda/test/ast/parser/ets/FixedArray/invalidTypes.ets b/ets2panda/test/ast/parser/ets/FixedArray/invalidTypes.ets index e3fef3a176..9ad1e60b92 100644 --- a/ets2panda/test/ast/parser/ets/FixedArray/invalidTypes.ets +++ b/ets2panda/test/ast/parser/ets/FixedArray/invalidTypes.ets @@ -90,8 +90,8 @@ let var6: [a0: , a1: ]; /* @@? 30:18 Error SyntaxError: Unexpected token ':'. */ /* @@? 30:20 Error SyntaxError: Unexpected token '...'. */ /* @@? 30:20 Error SyntaxError: Unexpected token '...'. */ -/* @@? 30:23 Error TypeError: Unresolved reference int */ -/* @@? 30:26 Error SyntaxError: Unexpected token ']'. */ +/* @@? 30:23 Error SyntaxError: Unexpected token 'int'. */ +/* @@? 30:23 Error SyntaxError: Unexpected token 'int'. */ /* @@? 30:26 Error SyntaxError: Unexpected token ']'. */ /* @@? 30:26 Error SyntaxError: Unexpected token ']'. */ /* @@? 32:19 Error SyntaxError: Unexpected token, expected ',' or ']'. */ diff --git a/ets2panda/test/ast/parser/ets/FixedArray/rest_parameter_04.ets b/ets2panda/test/ast/parser/ets/FixedArray/rest_parameter_04.ets index 37e28e816e..a408eaf019 100644 --- a/ets2panda/test/ast/parser/ets/FixedArray/rest_parameter_04.ets +++ b/ets2panda/test/ast/parser/ets/FixedArray/rest_parameter_04.ets @@ -19,5 +19,5 @@ function hehe(...items: FixedArray/* @@ label */: void /* @@ label1 */{ /* @@? 16:10 Error TypeError: Only abstract or native methods can't have body. */ /* @@? 16:57 Error SyntaxError: Rest parameter must be the last formal parameter. */ -/* @@? 16:59 Error TypeError: Unresolved reference void */ -/* @@? 16:79 Error SyntaxError: Unexpected token '{'. */ +/* @@? 16:59 Error SyntaxError: Unexpected token 'void'. */ +/* @@? 16:59 Error SyntaxError: Unexpected token 'void'. */ diff --git a/ets2panda/test/ast/parser/ets/FixedArray/unexpected_token_31.ets b/ets2panda/test/ast/parser/ets/FixedArray/unexpected_token_31.ets index f3c1bde715..bb6c655e2b 100644 --- a/ets2panda/test/ast/parser/ets/FixedArray/unexpected_token_31.ets +++ b/ets2panda/test/ast/parser/ets/FixedArray/unexpected_token_31.ets @@ -25,8 +25,8 @@ function foo(...^number: FixedArray): int { /* @@? 16:41 Error SyntaxError: Unexpected token ')'. */ /* @@? 16:42 Error SyntaxError: Unexpected token ':'. */ /* @@? 16:42 Error SyntaxError: Unexpected token ':'. */ -/* @@? 16:44 Error TypeError: Unresolved reference int */ -/* @@? 16:48 Error SyntaxError: Unexpected token '{'. */ +/* @@? 16:44 Error SyntaxError: Unexpected token 'int'. */ +/* @@? 16:44 Error SyntaxError: Unexpected token 'int'. */ /* @@? 17:5 Error SyntaxError: return keyword should be used in function body. */ /* @@? 17:12 Error TypeError: Type name 'number' used in the wrong context */ /* @@? 17:12 Error TypeError: Indexed access is not supported for such expression type. */ diff --git a/ets2panda/test/ast/parser/ets/FixedArray/unexpected_token_36.ets b/ets2panda/test/ast/parser/ets/FixedArray/unexpected_token_36.ets index 35bf7c584f..fa85f22368 100644 --- a/ets2panda/test/ast/parser/ets/FixedArray/unexpected_token_36.ets +++ b/ets2panda/test/ast/parser/ets/FixedArray/unexpected_token_36.ets @@ -41,7 +41,9 @@ export class AccessNSieve { /* @@? 29:14 Error SyntaxError: Unexpected token ':'. */ /* @@? 29:14 Error SyntaxError: Unexpected token ':'. */ /* @@? 29:14 Error SyntaxError: Unexpected token ':'. */ -/* @@? 29:16 Error TypeError: Unresolved reference int */ +/* @@? 29:16 Error SyntaxError: Unexpected token 'int'. */ +/* @@? 29:16 Error SyntaxError: Unexpected token 'int'. */ +/* @@? 29:20 Error SyntaxError: Unexpected token '='. */ /* @@? 29:25 Error TypeError: Bad operand type, the types of the operands must be numeric, same enumeration, or boolean type. */ /* @@? 29:36 Error SyntaxError: Unexpected token ')'. */ /* @@? 29:36 Error SyntaxError: Unexpected token ')'. */ diff --git a/ets2panda/test/ast/parser/ets/InvalidExpressions1.ets b/ets2panda/test/ast/parser/ets/InvalidExpressions1.ets index 72316999b9..521660666b 100644 --- a/ets2panda/test/ast/parser/ets/InvalidExpressions1.ets +++ b/ets2panda/test/ast/parser/ets/InvalidExpressions1.ets @@ -76,7 +76,10 @@ let a = [1, 2, 3); /* @@? 24:24 Error SyntaxError: Unexpected token ')'. */ /* @@? 24:25 Error SyntaxError: Unexpected token ':'. */ /* @@? 24:25 Error SyntaxError: Unexpected token ':'. */ -/* @@? 24:27 Error TypeError: The type of parameter 'void' cannot be inferred */ +/* @@? 24:27 Error SyntaxError: Unexpected token 'void'. */ +/* @@? 24:27 Error SyntaxError: Unexpected token 'void'. */ +/* @@? 24:32 Error SyntaxError: Unexpected token '=>'. */ +/* @@? 24:32 Error SyntaxError: Unexpected token '=>'. */ /* @@? 26:7 Error SyntaxError: Unexpected token '||='. */ /* @@? 28:5 Error TypeError: Variable 'a' has already been declared. */ /* @@? 28:16 Error TypeError: Bad operand type, the types of the operands must be numeric type, enum or String. */ @@ -87,9 +90,9 @@ let a = [1, 2, 3); /* @@? 30:13 Error SyntaxError: Invalid Type. */ /* @@? 32:10 Error TypeError: Variable 'f' has already been declared. */ /* @@? 32:10 Error TypeError: Variable 'f' has already been declared. */ -/* @@? 33:5 Error TypeError: No matching call signature for std.core.Object(int) */ -/* @@? 33:5 Error TypeError: Expected 0 arguments, got 1. */ /* @@? 33:5 Error TypeError: Call to 'super' must be first statement in constructor */ +/* @@? 33:5 Error TypeError: Expected 0 arguments, got 1. */ +/* @@? 33:5 Error TypeError: No matching call signature for std.core.Object(int) */ /* @@? 33:10 Error SyntaxError: Unexpected super keyword. */ /* @@? 36:1 Error TypeError: Indexed access is not supported for such expression type. */ /* @@? 36:8 Error SyntaxError: Unexpected token, expected ']'. */ diff --git a/ets2panda/test/ast/parser/ets/InvalidParserImpl.ets b/ets2panda/test/ast/parser/ets/InvalidParserImpl.ets index 2439731f6e..f1a1bac935 100644 --- a/ets2panda/test/ast/parser/ets/InvalidParserImpl.ets +++ b/ets2panda/test/ast/parser/ets/InvalidParserImpl.ets @@ -15,14 +15,15 @@ class A { get abc(x: number) {} - /* @@ label */set abc(x: number, a: string) {} -/* @@ label1 */} + set abc(x: number, a: string) {} +} function fun(this: A) {} -class /* @@ label2 */int {} +class int {} -/* @@@ label Error SyntaxError: Getter must not have formal parameters. */ -/* @@@ label1 Error SyntaxError: Setter must have exactly one formal parameter. */ -/* @@@ label2 Error SyntaxError: Cannot be used as user-defined type. */ /* @@? 17:12 Error TypeError: Getter must return a value */ +/* @@? 18:5 Error SyntaxError: Getter must not have formal parameters. */ +/* @@? 19:1 Error SyntaxError: Setter must have exactly one formal parameter. */ +/* @@? 23:7 Error SyntaxError: Cannot be used as user-defined type. */ +/* @@? 23:7 Error SyntaxError: Identifier expected, got 'int'. */ diff --git a/ets2panda/test/ast/parser/ets/MultipleParserErrors.ets b/ets2panda/test/ast/parser/ets/MultipleParserErrors.ets index 7b052e2990..758b001e43 100644 --- a/ets2panda/test/ast/parser/ets/MultipleParserErrors.ets +++ b/ets2panda/test/ast/parser/ets/MultipleParserErrors.ets @@ -174,15 +174,15 @@ function main(): void { /* @@? 39:14 Error SyntaxError: Unexpected token, expected ',' or ')'. */ /* @@? 39:14 Error SyntaxError: Unexpected token, expected an identifier. */ /* @@? 39:24 Error SyntaxError: Unexpected token 'int'. */ -/* @@? 39:24 Error TypeError: Unresolved reference int */ -/* @@? 39:27 Error SyntaxError: Unexpected token ')'. */ +/* @@? 39:24 Error SyntaxError: Unexpected token 'int'. */ +/* @@? 39:24 Error SyntaxError: Unexpected token 'int'. */ /* @@? 39:27 Error SyntaxError: Unexpected token ')'. */ /* @@? 39:27 Error SyntaxError: Unexpected token ')'. */ /* @@? 39:31 Error SyntaxError: return keyword should be used in function body. */ /* @@? 39:38 Error TypeError: All return statements in the function should be empty or have a value. */ /* @@? 41:6 Error SyntaxError: Identifier expected, got 'number literal'. */ -/* @@? 43:6 Error SyntaxError: Type alias name cannot be 'null'. */ /* @@? 43:6 Error SyntaxError: Identifier expected, got 'null'. */ +/* @@? 43:6 Error SyntaxError: Type alias name cannot be 'null'. */ /* @@? 45:6 Error SyntaxError: Identifier expected, got 'this'. */ /* @@? 47:8 Error SyntaxError: Variable must be initialized or it's type must be declared. */ /* @@? 47:8 Error SyntaxError: Variable must be initialized or it's type must be declared. */ @@ -198,7 +198,8 @@ function main(): void { /* @@? 51:38 Error SyntaxError: Unexpected token ')'. */ /* @@? 51:39 Error SyntaxError: Unexpected token ':'. */ /* @@? 51:39 Error SyntaxError: Unexpected token ':'. */ -/* @@? 51:45 Error SyntaxError: Unexpected token '{'. */ +/* @@? 51:41 Error SyntaxError: Unexpected token 'int'. */ +/* @@? 51:41 Error SyntaxError: Unexpected token 'int'. */ /* @@? 52:5 Error SyntaxError: return keyword should be used in function body. */ /* @@? 52:12 Error TypeError: Unresolved reference q */ /* @@? 52:12 Error TypeError: All return statements in the function should be empty or have a value. */ @@ -236,11 +237,11 @@ function main(): void { /* @@? 115:38 Error SyntaxError: Unexpected token '{'. */ /* @@? 116:5 Error SyntaxError: return keyword should be used in function body. */ /* @@? 116:12 Error TypeError: All return statements in the function should be empty or have a value. */ -/* @@? 119:26 Error SyntaxError: Unexpected token, expected an identifier. */ /* @@? 119:26 Error SyntaxError: Parameter declaration should have an explicit type annotation. */ -/* @@? 119:26 Error SyntaxError: Unexpected token, expected ',' or ')'. */ /* @@? 119:26 Error SyntaxError: Unexpected token 'case'. */ /* @@? 119:26 Error SyntaxError: Unexpected token 'case'. */ +/* @@? 119:26 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 119:26 Error SyntaxError: Unexpected token, expected an identifier. */ /* @@? 119:30 Error SyntaxError: Unexpected token ':'. */ /* @@? 119:30 Error SyntaxError: Unexpected token ':'. */ /* @@? 119:33 Error SyntaxError: Unexpected token ')'. */ @@ -282,4 +283,4 @@ function main(): void { /* @@? 165:5 Error TypeError: This expression is not callable. */ /* @@? 166:5 Error TypeError: Expected 1 arguments, got 0. */ /* @@? 166:5 Error TypeError: No matching call signature */ -/* @@? 286:1 Error SyntaxError: Expected '}', got 'eos'. */ +/* @@? 287:1 Error SyntaxError: Expected '}', got 'eos'. */ diff --git a/ets2panda/test/ast/parser/ets/annotations_tests/annotationUsage_missing_AT_for_function_param.ets b/ets2panda/test/ast/parser/ets/annotations_tests/annotationUsage_missing_AT_for_function_param.ets index 4e5c7ed46c..6516d74eb9 100644 --- a/ets2panda/test/ast/parser/ets/annotations_tests/annotationUsage_missing_AT_for_function_param.ets +++ b/ets2panda/test/ast/parser/ets/annotations_tests/annotationUsage_missing_AT_for_function_param.ets @@ -31,9 +31,9 @@ function foo(MyAnno({testProperty1: ""}) x: int, MyAnno({testProperty1: ""}) y: /* @@? 19:20 Error SyntaxError: Parameter declaration should have an explicit type annotation. */ /* @@? 19:20 Error TypeError: need to specify target type for class composite */ /* @@? 19:42 Error SyntaxError: Unexpected token 'x'. */ +/* @@? 19:45 Error SyntaxError: Unexpected token 'int'. */ /* @@? 19:45 Error SyntaxError: Label must be followed by a loop statement. */ -/* @@? 19:45 Error TypeError: Unresolved reference int */ -/* @@? 19:48 Error SyntaxError: Unexpected token ')'. */ +/* @@? 19:45 Error SyntaxError: Unexpected token 'int'. */ /* @@? 19:48 Error SyntaxError: Unexpected token ')'. */ /* @@? 19:48 Error SyntaxError: Unexpected token ')'. */ /* @@? 22:1 Error TypeError: Function foo is already declared. */ @@ -43,7 +43,8 @@ function foo(MyAnno({testProperty1: ""}) x: int, MyAnno({testProperty1: ""}) y: /* @@? 22:20 Error TypeError: need to specify target type for class composite */ /* @@? 22:42 Error SyntaxError: Unexpected token 'x'. */ /* @@? 22:45 Error SyntaxError: Label must be followed by a loop statement. */ -/* @@? 22:48 Error SyntaxError: Unexpected token ','. */ +/* @@? 22:45 Error SyntaxError: Unexpected token 'int'. */ +/* @@? 22:45 Error SyntaxError: Unexpected token 'int'. */ /* @@? 22:48 Error SyntaxError: Unexpected token ','. */ /* @@? 22:48 Error SyntaxError: Unexpected token ','. */ /* @@? 22:50 Error TypeError: This expression is not callable. */ @@ -57,12 +58,13 @@ function foo(MyAnno({testProperty1: ""}) x: int, MyAnno({testProperty1: ""}) y: /* @@? 25:1 Error TypeError: Function foo is already declared. */ /* @@? 25:1 Error TypeError: Function foo is already declared. */ /* @@? 25:14 Error TypeError: The type of parameter 'MyAnno' cannot be inferred */ -/* @@? 25:20 Error SyntaxError: Parameter declaration should have an explicit type annotation. */ /* @@? 25:20 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 25:20 Error SyntaxError: Parameter declaration should have an explicit type annotation. */ /* @@? 25:20 Error TypeError: need to specify target type for class composite */ /* @@? 25:42 Error SyntaxError: Unexpected token 'x'. */ /* @@? 25:45 Error SyntaxError: Label must be followed by a loop statement. */ -/* @@? 25:48 Error SyntaxError: Unexpected token ','. */ +/* @@? 25:45 Error SyntaxError: Unexpected token 'int'. */ +/* @@? 25:45 Error SyntaxError: Unexpected token 'int'. */ /* @@? 25:48 Error SyntaxError: Unexpected token ','. */ /* @@? 25:48 Error SyntaxError: Unexpected token ','. */ /* @@? 25:50 Error TypeError: Annotation missing '@' symbol before annotation name. */ diff --git a/ets2panda/test/ast/parser/ets/for_of_04.ets b/ets2panda/test/ast/parser/ets/for_of_04.ets index 73102569be..1131b1d91f 100644 --- a/ets2panda/test/ast/parser/ets/for_of_04.ets +++ b/ets2panda/test/ast/parser/ets/for_of_04.ets @@ -26,11 +26,17 @@ for (i in 50) { a += 10 } /* @@? 20:9 Error SyntaxError: Type annotation is not allowed when existing variable is used as loop iterator in 'for' statement. */ -/* @@? 20:11 Error SyntaxError: Expected ';', got 'identification literal'. */ -/* @@? 20:11 Error TypeError: Unresolved reference double */ -/* @@? 20:18 Error SyntaxError: Expected ';', got 'identification literal'. */ +/* @@? 20:11 Error SyntaxError: Expected ';', got 'double'. */ +/* @@? 20:11 Error SyntaxError: Unexpected token 'double'. */ +/* @@? 20:11 Error SyntaxError: Unexpected token 'double'. */ +/* @@? 20:11 Error SyntaxError: Unexpected token 'double'. */ +/* @@? 20:11 Error SyntaxError: Unexpected token 'double'. */ +/* @@? 20:11 Error SyntaxError: Expected ')', got 'double'. */ +/* @@? 20:11 Error SyntaxError: Unexpected token 'double'. */ +/* @@? 20:11 Error SyntaxError: Expected ';', got 'double'. */ +/* @@? 20:11 Error SyntaxError: Unexpected token 'double'. */ /* @@? 20:18 Error TypeError: Unresolved reference of */ -/* @@? 20:21 Error SyntaxError: Expected ')', got 'identification literal'. */ +/* @@? 20:21 Error SyntaxError: Unexpected token 'a'. */ /* @@? 20:21 Error TypeError: Unresolved reference a */ /* @@? 20:22 Error SyntaxError: Unexpected token ')'. */ /* @@? 20:22 Error SyntaxError: Unexpected token ')'. */ diff --git a/ets2panda/test/ast/parser/ets/invalidTypes.ets b/ets2panda/test/ast/parser/ets/invalidTypes.ets index e67924adcb..276d27a280 100644 --- a/ets2panda/test/ast/parser/ets/invalidTypes.ets +++ b/ets2panda/test/ast/parser/ets/invalidTypes.ets @@ -75,8 +75,8 @@ let var6: [a0: , a1: ]; /* @@? 30:18 Error SyntaxError: Unexpected token ':'. */ /* @@? 30:20 Error SyntaxError: Unexpected token '...'. */ /* @@? 30:20 Error SyntaxError: Unexpected token '...'. */ -/* @@? 30:23 Error TypeError: Unresolved reference int */ -/* @@? 30:26 Error SyntaxError: Unexpected token ']'. */ +/* @@? 30:23 Error SyntaxError: Unexpected token 'int'. */ +/* @@? 30:23 Error SyntaxError: Unexpected token 'int'. */ /* @@? 30:26 Error SyntaxError: Unexpected token ']'. */ /* @@? 30:26 Error SyntaxError: Unexpected token ']'. */ /* @@? 32:19 Error SyntaxError: Unexpected token, expected ',' or ']'. */ diff --git a/ets2panda/test/ast/parser/ets/lambda_omit_parentheses_type_alias_neg_1.ets b/ets2panda/test/ast/parser/ets/lambda_omit_parentheses_type_alias_neg_1.ets index 13b37a95ce..b4952f183a 100644 --- a/ets2panda/test/ast/parser/ets/lambda_omit_parentheses_type_alias_neg_1.ets +++ b/ets2panda/test/ast/parser/ets/lambda_omit_parentheses_type_alias_neg_1.ets @@ -17,4 +17,8 @@ let a: int => void /* @@? 16:12 Error SyntaxError: Unexpected token '=>'. */ /* @@? 16:12 Error SyntaxError: Unexpected token '=>'. */ -/* @@? 16:12 Error SyntaxError: Unexpected token '=>'. */ \ No newline at end of file +/* @@? 16:12 Error SyntaxError: Unexpected token '=>'. */ +/* @@? 16:15 Error SyntaxError: Unexpected token 'void'. */ +/* @@? 16:15 Error SyntaxError: Unexpected token 'void'. */ +/* @@? 16:15 Error SyntaxError: Unexpected token 'void'. */ +/* @@? 16:15 Error SyntaxError: Unexpected token 'void'. */ \ No newline at end of file diff --git a/ets2panda/test/ast/parser/ets/namespace_badtoken04.ets b/ets2panda/test/ast/parser/ets/namespace_badtoken04.ets index 5f618161da..b7ddfb7d67 100644 --- a/ets2panda/test/ast/parser/ets/namespace_badtoken04.ets +++ b/ets2panda/test/ast/parser/ets/namespace_badtoken04.ets @@ -19,3 +19,5 @@ declare namespace MySpace{ /* @@? 17:10 Error SyntaxError: Unexpected token ':'. */ /* @@? 17:10 Error SyntaxError: Unexpected token ':'. */ /* @@? 17:10 Error SyntaxError: Unexpected token ':'. */ +/* @@? 17:11 Error SyntaxError: Unexpected token 'void'. */ +/* @@? 17:11 Error SyntaxError: Unexpected token 'void'. */ diff --git a/ets2panda/test/ast/parser/ets/rest_parameter_04.ets b/ets2panda/test/ast/parser/ets/rest_parameter_04.ets index 9b08f8851e..1e574c661d 100644 --- a/ets2panda/test/ast/parser/ets/rest_parameter_04.ets +++ b/ets2panda/test/ast/parser/ets/rest_parameter_04.ets @@ -19,5 +19,5 @@ function hehe(...items: number[]/* @@ label */: void /* @@ label1 */{ /* @@? 16:10 Error TypeError: Only abstract or native methods can't have body. */ /* @@? 16:47 Error SyntaxError: Rest parameter must be the last formal parameter. */ -/* @@? 16:49 Error TypeError: Unresolved reference void */ -/* @@? 16:69 Error SyntaxError: Unexpected token '{'. */ +/* @@? 16:49 Error SyntaxError: Unexpected token 'void'. */ +/* @@? 16:49 Error SyntaxError: Unexpected token 'void'. */ diff --git a/ets2panda/test/ast/parser/ets/unexpected_token_31.ets b/ets2panda/test/ast/parser/ets/unexpected_token_31.ets index 17af310ec1..3d6c57802d 100644 --- a/ets2panda/test/ast/parser/ets/unexpected_token_31.ets +++ b/ets2panda/test/ast/parser/ets/unexpected_token_31.ets @@ -25,8 +25,8 @@ function foo(...^number: int[]): int { /* @@? 16:31 Error SyntaxError: Unexpected token ')'. */ /* @@? 16:32 Error SyntaxError: Unexpected token ':'. */ /* @@? 16:32 Error SyntaxError: Unexpected token ':'. */ -/* @@? 16:34 Error TypeError: Unresolved reference int */ -/* @@? 16:38 Error SyntaxError: Unexpected token '{'. */ +/* @@? 16:34 Error SyntaxError: Unexpected token 'int'. */ +/* @@? 16:34 Error SyntaxError: Unexpected token 'int'. */ /* @@? 17:5 Error SyntaxError: return keyword should be used in function body. */ /* @@? 17:12 Error TypeError: Type name 'number' used in the wrong context */ /* @@? 17:12 Error TypeError: Indexed access is not supported for such expression type. */ diff --git a/ets2panda/test/ast/parser/ets/unexpected_token_36.ets b/ets2panda/test/ast/parser/ets/unexpected_token_36.ets index 453e5cd1e2..d9bc05814b 100644 --- a/ets2panda/test/ast/parser/ets/unexpected_token_36.ets +++ b/ets2panda/test/ast/parser/ets/unexpected_token_36.ets @@ -41,7 +41,9 @@ export class AccessNSieve { /* @@? 29:14 Error SyntaxError: Unexpected token ':'. */ /* @@? 29:14 Error SyntaxError: Unexpected token ':'. */ /* @@? 29:14 Error SyntaxError: Unexpected token ':'. */ -/* @@? 29:16 Error TypeError: Unresolved reference int */ +/* @@? 29:16 Error SyntaxError: Unexpected token 'int'. */ +/* @@? 29:16 Error SyntaxError: Unexpected token 'int'. */ +/* @@? 29:20 Error SyntaxError: Unexpected token '='. */ /* @@? 29:25 Error TypeError: Bad operand type, the types of the operands must be numeric, same enumeration, or boolean type. */ /* @@? 29:36 Error SyntaxError: Unexpected token ')'. */ /* @@? 29:36 Error SyntaxError: Unexpected token ')'. */ diff --git a/ets2panda/test/ast/parser/ets/user_defined_5.ets b/ets2panda/test/ast/parser/ets/user_defined_5.ets index bfd46c9f78..bdf44a3c52 100644 --- a/ets2panda/test/ast/parser/ets/user_defined_5.ets +++ b/ets2panda/test/ast/parser/ets/user_defined_5.ets @@ -17,4 +17,5 @@ enum /* @@ label */double { A, B, C } -/* @@@ label Error SyntaxError: Cannot be used as user-defined type. */ +/* @@@ label Error SyntaxError: Cannot be used as user-defined type. */ +/* @@@ label Error SyntaxError: Identifier expected, got 'double'. */ diff --git a/ets2panda/test/ast/parser/ets/user_defined_7.ets b/ets2panda/test/ast/parser/ets/user_defined_7.ets index d6f9dc12f8..67c6eec095 100644 --- a/ets2panda/test/ast/parser/ets/user_defined_7.ets +++ b/ets2panda/test/ast/parser/ets/user_defined_7.ets @@ -18,6 +18,7 @@ interface /* @@ label1 */double { /* @@ label4 */} /* @@@ label1 Error SyntaxError: Cannot be used as user-defined type. */ +/* @@@ label1 Error SyntaxError: Identifier expected, got 'double'. */ /* @@@ label2 Error SyntaxError: Interface member initialization is prohibited. */ /* @@@ label3 Error SyntaxError: Unexpected token, expected ','. */ /* @@? 17:51 Error SyntaxError: Unexpected token, expected 'private' or identifier. */ diff --git a/ets2panda/test/parser/ets/user_defined_1-expected.txt b/ets2panda/test/parser/ets/user_defined_1-expected.txt deleted file mode 100644 index f8859d89fc..0000000000 --- a/ets2panda/test/parser/ets/user_defined_1-expected.txt +++ /dev/null @@ -1,766 +0,0 @@ -{ - "type": "Program", - "statements": [ - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "ETSGLOBAL", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "user_defined_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "user_defined_1.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "user_defined_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "user_defined_1.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "user_defined_1.ets" - }, - "end": { - "line": 16, - "column": 14, - "program": "user_defined_1.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "user_defined_1.ets" - }, - "end": { - "line": 16, - "column": 14, - "program": "user_defined_1.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "VariableDeclaration", - "declarations": [ - { - "type": "VariableDeclarator", - "id": { - "type": "Identifier", - "name": "float", - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 17, - "column": 17, - "program": "user_defined_1.ets" - }, - "end": { - "line": 17, - "column": 24, - "program": "user_defined_1.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 17, - "column": 9, - "program": "user_defined_1.ets" - }, - "end": { - "line": 17, - "column": 14, - "program": "user_defined_1.ets" - } - } - }, - "init": { - "type": "BooleanLiteral", - "value": false, - "loc": { - "start": { - "line": 17, - "column": 27, - "program": "user_defined_1.ets" - }, - "end": { - "line": 17, - "column": 32, - "program": "user_defined_1.ets" - } - } - }, - "loc": { - "start": { - "line": 17, - "column": 9, - "program": "user_defined_1.ets" - }, - "end": { - "line": 17, - "column": 32, - "program": "user_defined_1.ets" - } - } - } - ], - "kind": "let", - "loc": { - "start": { - "line": 17, - "column": 5, - "program": "user_defined_1.ets" - }, - "end": { - "line": 17, - "column": 33, - "program": "user_defined_1.ets" - } - } - }, - { - "type": "VariableDeclaration", - "declarations": [ - { - "type": "VariableDeclarator", - "id": { - "type": "Identifier", - "name": "double", - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 18, - "column": 18, - "program": "user_defined_1.ets" - }, - "end": { - "line": 18, - "column": 25, - "program": "user_defined_1.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 9, - "program": "user_defined_1.ets" - }, - "end": { - "line": 18, - "column": 15, - "program": "user_defined_1.ets" - } - } - }, - "init": { - "type": "BooleanLiteral", - "value": false, - "loc": { - "start": { - "line": 18, - "column": 28, - "program": "user_defined_1.ets" - }, - "end": { - "line": 18, - "column": 33, - "program": "user_defined_1.ets" - } - } - }, - "loc": { - "start": { - "line": 18, - "column": 9, - "program": "user_defined_1.ets" - }, - "end": { - "line": 18, - "column": 33, - "program": "user_defined_1.ets" - } - } - } - ], - "kind": "let", - "loc": { - "start": { - "line": 18, - "column": 5, - "program": "user_defined_1.ets" - }, - "end": { - "line": 18, - "column": 34, - "program": "user_defined_1.ets" - } - } - }, - { - "type": "VariableDeclaration", - "declarations": [ - { - "type": "VariableDeclarator", - "id": { - "type": "Identifier", - "name": "byte", - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 19, - "column": 16, - "program": "user_defined_1.ets" - }, - "end": { - "line": 19, - "column": 23, - "program": "user_defined_1.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 19, - "column": 9, - "program": "user_defined_1.ets" - }, - "end": { - "line": 19, - "column": 13, - "program": "user_defined_1.ets" - } - } - }, - "init": { - "type": "BooleanLiteral", - "value": false, - "loc": { - "start": { - "line": 19, - "column": 26, - "program": "user_defined_1.ets" - }, - "end": { - "line": 19, - "column": 31, - "program": "user_defined_1.ets" - } - } - }, - "loc": { - "start": { - "line": 19, - "column": 9, - "program": "user_defined_1.ets" - }, - "end": { - "line": 19, - "column": 31, - "program": "user_defined_1.ets" - } - } - } - ], - "kind": "let", - "loc": { - "start": { - "line": 19, - "column": 5, - "program": "user_defined_1.ets" - }, - "end": { - "line": 19, - "column": 32, - "program": "user_defined_1.ets" - } - } - }, - { - "type": "VariableDeclaration", - "declarations": [ - { - "type": "VariableDeclarator", - "id": { - "type": "Identifier", - "name": "short", - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 20, - "column": 17, - "program": "user_defined_1.ets" - }, - "end": { - "line": 20, - "column": 24, - "program": "user_defined_1.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 9, - "program": "user_defined_1.ets" - }, - "end": { - "line": 20, - "column": 14, - "program": "user_defined_1.ets" - } - } - }, - "init": { - "type": "BooleanLiteral", - "value": false, - "loc": { - "start": { - "line": 20, - "column": 27, - "program": "user_defined_1.ets" - }, - "end": { - "line": 20, - "column": 32, - "program": "user_defined_1.ets" - } - } - }, - "loc": { - "start": { - "line": 20, - "column": 9, - "program": "user_defined_1.ets" - }, - "end": { - "line": 20, - "column": 32, - "program": "user_defined_1.ets" - } - } - } - ], - "kind": "let", - "loc": { - "start": { - "line": 20, - "column": 5, - "program": "user_defined_1.ets" - }, - "end": { - "line": 20, - "column": 33, - "program": "user_defined_1.ets" - } - } - }, - { - "type": "VariableDeclaration", - "declarations": [ - { - "type": "VariableDeclarator", - "id": { - "type": "Identifier", - "name": "int", - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 21, - "column": 15, - "program": "user_defined_1.ets" - }, - "end": { - "line": 21, - "column": 22, - "program": "user_defined_1.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 21, - "column": 9, - "program": "user_defined_1.ets" - }, - "end": { - "line": 21, - "column": 12, - "program": "user_defined_1.ets" - } - } - }, - "init": { - "type": "BooleanLiteral", - "value": false, - "loc": { - "start": { - "line": 21, - "column": 25, - "program": "user_defined_1.ets" - }, - "end": { - "line": 21, - "column": 30, - "program": "user_defined_1.ets" - } - } - }, - "loc": { - "start": { - "line": 21, - "column": 9, - "program": "user_defined_1.ets" - }, - "end": { - "line": 21, - "column": 30, - "program": "user_defined_1.ets" - } - } - } - ], - "kind": "let", - "loc": { - "start": { - "line": 21, - "column": 5, - "program": "user_defined_1.ets" - }, - "end": { - "line": 21, - "column": 31, - "program": "user_defined_1.ets" - } - } - }, - { - "type": "VariableDeclaration", - "declarations": [ - { - "type": "VariableDeclarator", - "id": { - "type": "Identifier", - "name": "char", - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 22, - "column": 16, - "program": "user_defined_1.ets" - }, - "end": { - "line": 22, - "column": 23, - "program": "user_defined_1.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 22, - "column": 9, - "program": "user_defined_1.ets" - }, - "end": { - "line": 22, - "column": 13, - "program": "user_defined_1.ets" - } - } - }, - "init": { - "type": "BooleanLiteral", - "value": false, - "loc": { - "start": { - "line": 22, - "column": 26, - "program": "user_defined_1.ets" - }, - "end": { - "line": 22, - "column": 31, - "program": "user_defined_1.ets" - } - } - }, - "loc": { - "start": { - "line": 22, - "column": 9, - "program": "user_defined_1.ets" - }, - "end": { - "line": 22, - "column": 31, - "program": "user_defined_1.ets" - } - } - } - ], - "kind": "let", - "loc": { - "start": { - "line": 22, - "column": 5, - "program": "user_defined_1.ets" - }, - "end": { - "line": 22, - "column": 32, - "program": "user_defined_1.ets" - } - } - } - ], - "loc": { - "start": { - "line": 16, - "column": 17, - "program": "user_defined_1.ets" - }, - "end": { - "line": 24, - "column": 2, - "program": "user_defined_1.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "user_defined_1.ets" - }, - "end": { - "line": 24, - "column": 2, - "program": "user_defined_1.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "user_defined_1.ets" - }, - "end": { - "line": 24, - "column": 2, - "program": "user_defined_1.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 1, - "program": "user_defined_1.ets" - }, - "end": { - "line": 24, - "column": 2, - "program": "user_defined_1.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "user_defined_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "user_defined_1.ets" - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "user_defined_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "user_defined_1.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "user_defined_1.ets" - }, - "end": { - "line": 25, - "column": 1, - "program": "user_defined_1.ets" - } - } -} diff --git a/ets2panda/test/parser/ets/user_defined_1.ets b/ets2panda/test/parser/ets/user_defined_1.ets deleted file mode 100644 index 14809fc3b1..0000000000 --- a/ets2panda/test/parser/ets/user_defined_1.ets +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2024-2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -function main() { - let float : boolean = false; - let double : boolean = false; - let byte : boolean = false; - let short : boolean = false; - let int : boolean = false; - let char : boolean = false; - -} diff --git a/ets2panda/test/parser/ets/user_defined_2-expected.txt b/ets2panda/test/parser/ets/user_defined_2-expected.txt deleted file mode 100644 index bbf7d8f479..0000000000 --- a/ets2panda/test/parser/ets/user_defined_2-expected.txt +++ /dev/null @@ -1,808 +0,0 @@ -{ - "type": "Program", - "statements": [ - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "ETSGLOBAL", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "user_defined_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "user_defined_2.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "user_defined_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "user_defined_2.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "user_defined_2.ets" - }, - "end": { - "line": 16, - "column": 14, - "program": "user_defined_2.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "user_defined_2.ets" - }, - "end": { - "line": 16, - "column": 14, - "program": "user_defined_2.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "VariableDeclaration", - "declarations": [ - { - "type": "VariableDeclarator", - "id": { - "type": "Identifier", - "name": "float", - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 17, - "column": 17, - "program": "user_defined_2.ets" - }, - "end": { - "line": 17, - "column": 22, - "program": "user_defined_2.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 17, - "column": 9, - "program": "user_defined_2.ets" - }, - "end": { - "line": 17, - "column": 14, - "program": "user_defined_2.ets" - } - } - }, - "init": null, - "loc": { - "start": { - "line": 17, - "column": 9, - "program": "user_defined_2.ets" - }, - "end": { - "line": 17, - "column": 14, - "program": "user_defined_2.ets" - } - } - } - ], - "kind": "let", - "loc": { - "start": { - "line": 17, - "column": 5, - "program": "user_defined_2.ets" - }, - "end": { - "line": 17, - "column": 23, - "program": "user_defined_2.ets" - } - } - }, - { - "type": "VariableDeclaration", - "declarations": [ - { - "type": "VariableDeclarator", - "id": { - "type": "Identifier", - "name": "boolean", - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 18, - "column": 19, - "program": "user_defined_2.ets" - }, - "end": { - "line": 18, - "column": 26, - "program": "user_defined_2.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 9, - "program": "user_defined_2.ets" - }, - "end": { - "line": 18, - "column": 16, - "program": "user_defined_2.ets" - } - } - }, - "init": null, - "loc": { - "start": { - "line": 18, - "column": 9, - "program": "user_defined_2.ets" - }, - "end": { - "line": 18, - "column": 16, - "program": "user_defined_2.ets" - } - } - } - ], - "kind": "let", - "loc": { - "start": { - "line": 18, - "column": 5, - "program": "user_defined_2.ets" - }, - "end": { - "line": 18, - "column": 27, - "program": "user_defined_2.ets" - } - } - }, - { - "type": "VariableDeclaration", - "declarations": [ - { - "type": "VariableDeclarator", - "id": { - "type": "Identifier", - "name": "double", - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 19, - "column": 18, - "program": "user_defined_2.ets" - }, - "end": { - "line": 19, - "column": 24, - "program": "user_defined_2.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 19, - "column": 9, - "program": "user_defined_2.ets" - }, - "end": { - "line": 19, - "column": 15, - "program": "user_defined_2.ets" - } - } - }, - "init": null, - "loc": { - "start": { - "line": 19, - "column": 9, - "program": "user_defined_2.ets" - }, - "end": { - "line": 19, - "column": 15, - "program": "user_defined_2.ets" - } - } - } - ], - "kind": "let", - "loc": { - "start": { - "line": 19, - "column": 5, - "program": "user_defined_2.ets" - }, - "end": { - "line": 19, - "column": 25, - "program": "user_defined_2.ets" - } - } - }, - { - "type": "VariableDeclaration", - "declarations": [ - { - "type": "VariableDeclarator", - "id": { - "type": "Identifier", - "name": "byte", - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 20, - "column": 16, - "program": "user_defined_2.ets" - }, - "end": { - "line": 20, - "column": 20, - "program": "user_defined_2.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 9, - "program": "user_defined_2.ets" - }, - "end": { - "line": 20, - "column": 13, - "program": "user_defined_2.ets" - } - } - }, - "init": null, - "loc": { - "start": { - "line": 20, - "column": 9, - "program": "user_defined_2.ets" - }, - "end": { - "line": 20, - "column": 13, - "program": "user_defined_2.ets" - } - } - } - ], - "kind": "let", - "loc": { - "start": { - "line": 20, - "column": 5, - "program": "user_defined_2.ets" - }, - "end": { - "line": 20, - "column": 21, - "program": "user_defined_2.ets" - } - } - }, - { - "type": "VariableDeclaration", - "declarations": [ - { - "type": "VariableDeclarator", - "id": { - "type": "Identifier", - "name": "short", - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 21, - "column": 17, - "program": "user_defined_2.ets" - }, - "end": { - "line": 21, - "column": 22, - "program": "user_defined_2.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 21, - "column": 9, - "program": "user_defined_2.ets" - }, - "end": { - "line": 21, - "column": 14, - "program": "user_defined_2.ets" - } - } - }, - "init": null, - "loc": { - "start": { - "line": 21, - "column": 9, - "program": "user_defined_2.ets" - }, - "end": { - "line": 21, - "column": 14, - "program": "user_defined_2.ets" - } - } - } - ], - "kind": "let", - "loc": { - "start": { - "line": 21, - "column": 5, - "program": "user_defined_2.ets" - }, - "end": { - "line": 21, - "column": 23, - "program": "user_defined_2.ets" - } - } - }, - { - "type": "VariableDeclaration", - "declarations": [ - { - "type": "VariableDeclarator", - "id": { - "type": "Identifier", - "name": "int", - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 22, - "column": 15, - "program": "user_defined_2.ets" - }, - "end": { - "line": 22, - "column": 18, - "program": "user_defined_2.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 22, - "column": 9, - "program": "user_defined_2.ets" - }, - "end": { - "line": 22, - "column": 12, - "program": "user_defined_2.ets" - } - } - }, - "init": null, - "loc": { - "start": { - "line": 22, - "column": 9, - "program": "user_defined_2.ets" - }, - "end": { - "line": 22, - "column": 12, - "program": "user_defined_2.ets" - } - } - } - ], - "kind": "let", - "loc": { - "start": { - "line": 22, - "column": 5, - "program": "user_defined_2.ets" - }, - "end": { - "line": 22, - "column": 19, - "program": "user_defined_2.ets" - } - } - }, - { - "type": "VariableDeclaration", - "declarations": [ - { - "type": "VariableDeclarator", - "id": { - "type": "Identifier", - "name": "char", - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 23, - "column": 16, - "program": "user_defined_2.ets" - }, - "end": { - "line": 23, - "column": 20, - "program": "user_defined_2.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 23, - "column": 9, - "program": "user_defined_2.ets" - }, - "end": { - "line": 23, - "column": 13, - "program": "user_defined_2.ets" - } - } - }, - "init": null, - "loc": { - "start": { - "line": 23, - "column": 9, - "program": "user_defined_2.ets" - }, - "end": { - "line": 23, - "column": 13, - "program": "user_defined_2.ets" - } - } - } - ], - "kind": "let", - "loc": { - "start": { - "line": 23, - "column": 5, - "program": "user_defined_2.ets" - }, - "end": { - "line": 23, - "column": 21, - "program": "user_defined_2.ets" - } - } - }, - { - "type": "VariableDeclaration", - "declarations": [ - { - "type": "VariableDeclarator", - "id": { - "type": "Identifier", - "name": "long", - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 24, - "column": 16, - "program": "user_defined_2.ets" - }, - "end": { - "line": 24, - "column": 20, - "program": "user_defined_2.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 24, - "column": 9, - "program": "user_defined_2.ets" - }, - "end": { - "line": 24, - "column": 13, - "program": "user_defined_2.ets" - } - } - }, - "init": null, - "loc": { - "start": { - "line": 24, - "column": 9, - "program": "user_defined_2.ets" - }, - "end": { - "line": 24, - "column": 13, - "program": "user_defined_2.ets" - } - } - } - ], - "kind": "let", - "loc": { - "start": { - "line": 24, - "column": 5, - "program": "user_defined_2.ets" - }, - "end": { - "line": 24, - "column": 21, - "program": "user_defined_2.ets" - } - } - } - ], - "loc": { - "start": { - "line": 16, - "column": 17, - "program": "user_defined_2.ets" - }, - "end": { - "line": 25, - "column": 2, - "program": "user_defined_2.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "user_defined_2.ets" - }, - "end": { - "line": 25, - "column": 2, - "program": "user_defined_2.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "user_defined_2.ets" - }, - "end": { - "line": 25, - "column": 2, - "program": "user_defined_2.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 1, - "program": "user_defined_2.ets" - }, - "end": { - "line": 25, - "column": 2, - "program": "user_defined_2.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "user_defined_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "user_defined_2.ets" - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "user_defined_2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "user_defined_2.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "user_defined_2.ets" - }, - "end": { - "line": 26, - "column": 1, - "program": "user_defined_2.ets" - } - } -} diff --git a/ets2panda/test/parser/ets/user_defined_2.ets b/ets2panda/test/parser/ets/user_defined_2.ets deleted file mode 100644 index a85d431332..0000000000 --- a/ets2panda/test/parser/ets/user_defined_2.ets +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2024-2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -function main() { - let float : float; - let boolean : boolean; - let double : double; - let byte : byte; - let short : short; - let int : int; - let char : char; - let long : long; -} diff --git a/ets2panda/test/parser/ets/user_defined_3-expected.txt b/ets2panda/test/parser/ets/user_defined_3-expected.txt deleted file mode 100644 index 858f5aa777..0000000000 --- a/ets2panda/test/parser/ets/user_defined_3-expected.txt +++ /dev/null @@ -1,1248 +0,0 @@ -{ - "type": "Program", - "statements": [ - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "ETSGLOBAL", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "user_defined_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "user_defined_3.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "user_defined_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "user_defined_3.ets" - } - } - }, - { - "type": "ClassProperty", - "key": { - "type": "Identifier", - "name": "float", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 9, - "program": "user_defined_3.ets" - }, - "end": { - "line": 16, - "column": 14, - "program": "user_defined_3.ets" - } - } - }, - "accessibility": "public", - "static": true, - "readonly": false, - "declare": false, - "optional": false, - "computed": false, - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 16, - "column": 17, - "program": "user_defined_3.ets" - }, - "end": { - "line": 16, - "column": 22, - "program": "user_defined_3.ets" - } - } - }, - "definite": false, - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 9, - "program": "user_defined_3.ets" - }, - "end": { - "line": 16, - "column": 14, - "program": "user_defined_3.ets" - } - } - }, - { - "type": "ClassProperty", - "key": { - "type": "Identifier", - "name": "boolean", - "decorators": [], - "loc": { - "start": { - "line": 17, - "column": 9, - "program": "user_defined_3.ets" - }, - "end": { - "line": 17, - "column": 16, - "program": "user_defined_3.ets" - } - } - }, - "accessibility": "public", - "static": true, - "readonly": false, - "declare": false, - "optional": false, - "computed": false, - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 17, - "column": 19, - "program": "user_defined_3.ets" - }, - "end": { - "line": 17, - "column": 26, - "program": "user_defined_3.ets" - } - } - }, - "definite": false, - "decorators": [], - "loc": { - "start": { - "line": 17, - "column": 9, - "program": "user_defined_3.ets" - }, - "end": { - "line": 17, - "column": 16, - "program": "user_defined_3.ets" - } - } - }, - { - "type": "ClassProperty", - "key": { - "type": "Identifier", - "name": "double", - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 9, - "program": "user_defined_3.ets" - }, - "end": { - "line": 18, - "column": 15, - "program": "user_defined_3.ets" - } - } - }, - "accessibility": "public", - "static": true, - "readonly": false, - "declare": false, - "optional": false, - "computed": false, - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 18, - "column": 18, - "program": "user_defined_3.ets" - }, - "end": { - "line": 18, - "column": 24, - "program": "user_defined_3.ets" - } - } - }, - "definite": false, - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 9, - "program": "user_defined_3.ets" - }, - "end": { - "line": 18, - "column": 15, - "program": "user_defined_3.ets" - } - } - }, - { - "type": "ClassProperty", - "key": { - "type": "Identifier", - "name": "byte", - "decorators": [], - "loc": { - "start": { - "line": 19, - "column": 9, - "program": "user_defined_3.ets" - }, - "end": { - "line": 19, - "column": 13, - "program": "user_defined_3.ets" - } - } - }, - "accessibility": "public", - "static": true, - "readonly": false, - "declare": false, - "optional": false, - "computed": false, - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 19, - "column": 16, - "program": "user_defined_3.ets" - }, - "end": { - "line": 19, - "column": 20, - "program": "user_defined_3.ets" - } - } - }, - "definite": false, - "decorators": [], - "loc": { - "start": { - "line": 19, - "column": 9, - "program": "user_defined_3.ets" - }, - "end": { - "line": 19, - "column": 13, - "program": "user_defined_3.ets" - } - } - }, - { - "type": "ClassProperty", - "key": { - "type": "Identifier", - "name": "short", - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 9, - "program": "user_defined_3.ets" - }, - "end": { - "line": 20, - "column": 14, - "program": "user_defined_3.ets" - } - } - }, - "accessibility": "public", - "static": true, - "readonly": false, - "declare": false, - "optional": false, - "computed": false, - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 20, - "column": 17, - "program": "user_defined_3.ets" - }, - "end": { - "line": 20, - "column": 22, - "program": "user_defined_3.ets" - } - } - }, - "definite": false, - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 9, - "program": "user_defined_3.ets" - }, - "end": { - "line": 20, - "column": 14, - "program": "user_defined_3.ets" - } - } - }, - { - "type": "ClassProperty", - "key": { - "type": "Identifier", - "name": "int", - "decorators": [], - "loc": { - "start": { - "line": 21, - "column": 9, - "program": "user_defined_3.ets" - }, - "end": { - "line": 21, - "column": 12, - "program": "user_defined_3.ets" - } - } - }, - "accessibility": "public", - "static": true, - "readonly": false, - "declare": false, - "optional": false, - "computed": false, - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 21, - "column": 15, - "program": "user_defined_3.ets" - }, - "end": { - "line": 21, - "column": 18, - "program": "user_defined_3.ets" - } - } - }, - "definite": false, - "decorators": [], - "loc": { - "start": { - "line": 21, - "column": 9, - "program": "user_defined_3.ets" - }, - "end": { - "line": 21, - "column": 12, - "program": "user_defined_3.ets" - } - } - }, - { - "type": "ClassProperty", - "key": { - "type": "Identifier", - "name": "char", - "decorators": [], - "loc": { - "start": { - "line": 22, - "column": 9, - "program": "user_defined_3.ets" - }, - "end": { - "line": 22, - "column": 13, - "program": "user_defined_3.ets" - } - } - }, - "accessibility": "public", - "static": true, - "readonly": false, - "declare": false, - "optional": false, - "computed": false, - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 22, - "column": 16, - "program": "user_defined_3.ets" - }, - "end": { - "line": 22, - "column": 20, - "program": "user_defined_3.ets" - } - } - }, - "definite": false, - "decorators": [], - "loc": { - "start": { - "line": 22, - "column": 9, - "program": "user_defined_3.ets" - }, - "end": { - "line": 22, - "column": 13, - "program": "user_defined_3.ets" - } - } - }, - { - "type": "ClassProperty", - "key": { - "type": "Identifier", - "name": "long", - "decorators": [], - "loc": { - "start": { - "line": 23, - "column": 9, - "program": "user_defined_3.ets" - }, - "end": { - "line": 23, - "column": 13, - "program": "user_defined_3.ets" - } - } - }, - "accessibility": "public", - "static": true, - "readonly": false, - "declare": false, - "optional": false, - "computed": false, - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 23, - "column": 16, - "program": "user_defined_3.ets" - }, - "end": { - "line": 23, - "column": 20, - "program": "user_defined_3.ets" - } - } - }, - "definite": false, - "decorators": [], - "loc": { - "start": { - "line": 23, - "column": 9, - "program": "user_defined_3.ets" - }, - "end": { - "line": 23, - "column": 13, - "program": "user_defined_3.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 25, - "column": 10, - "program": "user_defined_3.ets" - }, - "end": { - "line": 25, - "column": 14, - "program": "user_defined_3.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 25, - "column": 10, - "program": "user_defined_3.ets" - }, - "end": { - "line": 25, - "column": 14, - "program": "user_defined_3.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "VariableDeclaration", - "declarations": [ - { - "type": "VariableDeclarator", - "id": { - "type": "Identifier", - "name": "float", - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 26, - "column": 17, - "program": "user_defined_3.ets" - }, - "end": { - "line": 26, - "column": 22, - "program": "user_defined_3.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 26, - "column": 9, - "program": "user_defined_3.ets" - }, - "end": { - "line": 26, - "column": 14, - "program": "user_defined_3.ets" - } - } - }, - "init": null, - "loc": { - "start": { - "line": 26, - "column": 9, - "program": "user_defined_3.ets" - }, - "end": { - "line": 26, - "column": 14, - "program": "user_defined_3.ets" - } - } - } - ], - "kind": "let", - "loc": { - "start": { - "line": 26, - "column": 5, - "program": "user_defined_3.ets" - }, - "end": { - "line": 26, - "column": 23, - "program": "user_defined_3.ets" - } - } - }, - { - "type": "VariableDeclaration", - "declarations": [ - { - "type": "VariableDeclarator", - "id": { - "type": "Identifier", - "name": "boolean", - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 27, - "column": 19, - "program": "user_defined_3.ets" - }, - "end": { - "line": 27, - "column": 26, - "program": "user_defined_3.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 27, - "column": 9, - "program": "user_defined_3.ets" - }, - "end": { - "line": 27, - "column": 16, - "program": "user_defined_3.ets" - } - } - }, - "init": null, - "loc": { - "start": { - "line": 27, - "column": 9, - "program": "user_defined_3.ets" - }, - "end": { - "line": 27, - "column": 16, - "program": "user_defined_3.ets" - } - } - } - ], - "kind": "let", - "loc": { - "start": { - "line": 27, - "column": 5, - "program": "user_defined_3.ets" - }, - "end": { - "line": 27, - "column": 27, - "program": "user_defined_3.ets" - } - } - }, - { - "type": "VariableDeclaration", - "declarations": [ - { - "type": "VariableDeclarator", - "id": { - "type": "Identifier", - "name": "double", - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 28, - "column": 18, - "program": "user_defined_3.ets" - }, - "end": { - "line": 28, - "column": 24, - "program": "user_defined_3.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 28, - "column": 9, - "program": "user_defined_3.ets" - }, - "end": { - "line": 28, - "column": 15, - "program": "user_defined_3.ets" - } - } - }, - "init": null, - "loc": { - "start": { - "line": 28, - "column": 9, - "program": "user_defined_3.ets" - }, - "end": { - "line": 28, - "column": 15, - "program": "user_defined_3.ets" - } - } - } - ], - "kind": "let", - "loc": { - "start": { - "line": 28, - "column": 5, - "program": "user_defined_3.ets" - }, - "end": { - "line": 28, - "column": 25, - "program": "user_defined_3.ets" - } - } - }, - { - "type": "VariableDeclaration", - "declarations": [ - { - "type": "VariableDeclarator", - "id": { - "type": "Identifier", - "name": "byte", - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 29, - "column": 16, - "program": "user_defined_3.ets" - }, - "end": { - "line": 29, - "column": 20, - "program": "user_defined_3.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 29, - "column": 9, - "program": "user_defined_3.ets" - }, - "end": { - "line": 29, - "column": 13, - "program": "user_defined_3.ets" - } - } - }, - "init": null, - "loc": { - "start": { - "line": 29, - "column": 9, - "program": "user_defined_3.ets" - }, - "end": { - "line": 29, - "column": 13, - "program": "user_defined_3.ets" - } - } - } - ], - "kind": "let", - "loc": { - "start": { - "line": 29, - "column": 5, - "program": "user_defined_3.ets" - }, - "end": { - "line": 29, - "column": 21, - "program": "user_defined_3.ets" - } - } - }, - { - "type": "VariableDeclaration", - "declarations": [ - { - "type": "VariableDeclarator", - "id": { - "type": "Identifier", - "name": "short", - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 30, - "column": 17, - "program": "user_defined_3.ets" - }, - "end": { - "line": 30, - "column": 22, - "program": "user_defined_3.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 30, - "column": 9, - "program": "user_defined_3.ets" - }, - "end": { - "line": 30, - "column": 14, - "program": "user_defined_3.ets" - } - } - }, - "init": null, - "loc": { - "start": { - "line": 30, - "column": 9, - "program": "user_defined_3.ets" - }, - "end": { - "line": 30, - "column": 14, - "program": "user_defined_3.ets" - } - } - } - ], - "kind": "let", - "loc": { - "start": { - "line": 30, - "column": 5, - "program": "user_defined_3.ets" - }, - "end": { - "line": 30, - "column": 23, - "program": "user_defined_3.ets" - } - } - }, - { - "type": "VariableDeclaration", - "declarations": [ - { - "type": "VariableDeclarator", - "id": { - "type": "Identifier", - "name": "int", - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 31, - "column": 15, - "program": "user_defined_3.ets" - }, - "end": { - "line": 31, - "column": 18, - "program": "user_defined_3.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 31, - "column": 9, - "program": "user_defined_3.ets" - }, - "end": { - "line": 31, - "column": 12, - "program": "user_defined_3.ets" - } - } - }, - "init": null, - "loc": { - "start": { - "line": 31, - "column": 9, - "program": "user_defined_3.ets" - }, - "end": { - "line": 31, - "column": 12, - "program": "user_defined_3.ets" - } - } - } - ], - "kind": "let", - "loc": { - "start": { - "line": 31, - "column": 5, - "program": "user_defined_3.ets" - }, - "end": { - "line": 31, - "column": 19, - "program": "user_defined_3.ets" - } - } - }, - { - "type": "VariableDeclaration", - "declarations": [ - { - "type": "VariableDeclarator", - "id": { - "type": "Identifier", - "name": "char", - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 32, - "column": 16, - "program": "user_defined_3.ets" - }, - "end": { - "line": 32, - "column": 20, - "program": "user_defined_3.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 32, - "column": 9, - "program": "user_defined_3.ets" - }, - "end": { - "line": 32, - "column": 13, - "program": "user_defined_3.ets" - } - } - }, - "init": null, - "loc": { - "start": { - "line": 32, - "column": 9, - "program": "user_defined_3.ets" - }, - "end": { - "line": 32, - "column": 13, - "program": "user_defined_3.ets" - } - } - } - ], - "kind": "let", - "loc": { - "start": { - "line": 32, - "column": 5, - "program": "user_defined_3.ets" - }, - "end": { - "line": 32, - "column": 21, - "program": "user_defined_3.ets" - } - } - }, - { - "type": "VariableDeclaration", - "declarations": [ - { - "type": "VariableDeclarator", - "id": { - "type": "Identifier", - "name": "long", - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 33, - "column": 16, - "program": "user_defined_3.ets" - }, - "end": { - "line": 33, - "column": 20, - "program": "user_defined_3.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 33, - "column": 9, - "program": "user_defined_3.ets" - }, - "end": { - "line": 33, - "column": 13, - "program": "user_defined_3.ets" - } - } - }, - "init": null, - "loc": { - "start": { - "line": 33, - "column": 9, - "program": "user_defined_3.ets" - }, - "end": { - "line": 33, - "column": 13, - "program": "user_defined_3.ets" - } - } - } - ], - "kind": "let", - "loc": { - "start": { - "line": 33, - "column": 5, - "program": "user_defined_3.ets" - }, - "end": { - "line": 33, - "column": 21, - "program": "user_defined_3.ets" - } - } - } - ], - "loc": { - "start": { - "line": 25, - "column": 17, - "program": "user_defined_3.ets" - }, - "end": { - "line": 34, - "column": 2, - "program": "user_defined_3.ets" - } - } - }, - "loc": { - "start": { - "line": 25, - "column": 10, - "program": "user_defined_3.ets" - }, - "end": { - "line": 34, - "column": 2, - "program": "user_defined_3.ets" - } - } - }, - "loc": { - "start": { - "line": 25, - "column": 10, - "program": "user_defined_3.ets" - }, - "end": { - "line": 34, - "column": 2, - "program": "user_defined_3.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 25, - "column": 1, - "program": "user_defined_3.ets" - }, - "end": { - "line": 34, - "column": 2, - "program": "user_defined_3.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "user_defined_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "user_defined_3.ets" - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "user_defined_3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "user_defined_3.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "user_defined_3.ets" - }, - "end": { - "line": 35, - "column": 1, - "program": "user_defined_3.ets" - } - } -} diff --git a/ets2panda/test/parser/ets/user_defined_3.ets b/ets2panda/test/parser/ets/user_defined_3.ets deleted file mode 100644 index a058258ea3..0000000000 --- a/ets2panda/test/parser/ets/user_defined_3.ets +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2024-2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - let float : float; - let boolean : boolean; - let double : double; - let byte : byte; - let short : short; - let int : int; - let char : char; - let long : long; - -function main() { - let float : float; - let boolean : boolean; - let double : double; - let byte : byte; - let short : short; - let int : int; - let char : char; - let long : long; -} diff --git a/ets2panda/test/parser/ets/user_defined_4.ets b/ets2panda/test/parser/ets/user_defined_4.ets deleted file mode 100644 index f429e7107f..0000000000 --- a/ets2panda/test/parser/ets/user_defined_4.ets +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2024-2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -function boolean(){} diff --git a/ets2panda/test/parser/ets/user_defined_6-expected.txt b/ets2panda/test/parser/ets/user_defined_6-expected.txt deleted file mode 100644 index 8d2467b61a..0000000000 --- a/ets2panda/test/parser/ets/user_defined_6-expected.txt +++ /dev/null @@ -1,385 +0,0 @@ -{ - "type": "Program", - "statements": [ - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "ETSGLOBAL", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "user_defined_6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "user_defined_6.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "user_defined_6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "user_defined_6.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "user_defined_6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "user_defined_6.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "float", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "user_defined_6.ets" - }, - "end": { - "line": 16, - "column": 15, - "program": "user_defined_6.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "float", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "user_defined_6.ets" - }, - "end": { - "line": 16, - "column": 15, - "program": "user_defined_6.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 16, - "column": 18, - "program": "user_defined_6.ets" - }, - "end": { - "line": 17, - "column": 2, - "program": "user_defined_6.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "user_defined_6.ets" - }, - "end": { - "line": 17, - "column": 2, - "program": "user_defined_6.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "user_defined_6.ets" - }, - "end": { - "line": 17, - "column": 2, - "program": "user_defined_6.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 1, - "program": "user_defined_6.ets" - }, - "end": { - "line": 17, - "column": 2, - "program": "user_defined_6.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "user_defined_6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "user_defined_6.ets" - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "user_defined_6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "user_defined_6.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "user_defined_6.ets" - }, - "end": { - "line": 18, - "column": 1, - "program": "user_defined_6.ets" - } - } -} diff --git a/ets2panda/test/parser/ets/user_defined_6.ets b/ets2panda/test/parser/ets/user_defined_6.ets deleted file mode 100644 index 8e3f4782f0..0000000000 --- a/ets2panda/test/parser/ets/user_defined_6.ets +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright (c) 2024-2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -function float() { -} diff --git a/ets2panda/test/runtime/ets/user_defined_1.ets b/ets2panda/test/runtime/ets/user_defined_1.ets index 3052f4066b..e6371f450b 100644 --- a/ets2panda/test/runtime/ets/user_defined_1.ets +++ b/ets2panda/test/runtime/ets/user_defined_1.ets @@ -20,11 +20,8 @@ class B { a: boolean; } -let boolean: int = 3; - let x: B = new B(true); function main() { assertEQ(x.a, true) - assertEQ(boolean, 3) } diff --git a/ets2panda/test/runtime/ets/user_defined_2.ets b/ets2panda/test/runtime/ets/user_defined_2.ets deleted file mode 100644 index e967815345..0000000000 --- a/ets2panda/test/runtime/ets/user_defined_2.ets +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) 2023-2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -let boolean : boolean = true; - -function main() { - let boolean : boolean = false; - assertEQ(boolean, false) -} -- Gitee From b67c31441c6bd3bc3a8e59699aa99762c4fb49fb Mon Sep 17 00:00:00 2001 From: Amosov Alexey Date: Mon, 7 Apr 2025 13:09:18 +0300 Subject: [PATCH 158/268] Declgen fix Issue: https://gitee.com/openharmony/arkcompiler_runtime_core/issues/IC2BZZ Description: Fix functions from interfaces Fix ignorelist Signed-off-by: Amosov Alexey --- ets2panda/declgen_ets2ts/declgenEts2Ts.cpp | 18 ++++++++++++++++++ ets2panda/declgen_ets2ts/declgenEts2Ts.h | 3 +++ 2 files changed, 21 insertions(+) diff --git a/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp b/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp index 8cdf9344ac..a914a94096 100644 --- a/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp +++ b/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp @@ -1505,6 +1505,23 @@ void TSDeclGen::EmitClassGlueCode(const ir::ClassDefinition *classDef, const std } } +void TSDeclGen::ProcessMethodsFromInterfaces(const std::unordered_set &processedMethods, + const ir::ClassDefinition *classDef) +{ + const auto &interfaces = classDef->TsType()->AsETSObjectType()->Interfaces(); + for (const auto &interface : interfaces) { + auto methods = interface->Methods(); + for (const auto &method : methods) { + if ((method->Flags() & (varbinder::VariableFlags::PUBLIC)) != 0U && + (method->Flags() & (varbinder::VariableFlags::STATIC)) == 0U && + processedMethods.find(method->Name().Mutf8()) == processedMethods.end()) { + GenMethodDeclaration( + method->AsLocalVariable()->Declaration()->AsFunctionDecl()->Node()->AsMethodDefinition()); + } + } + } +} + void TSDeclGen::ProcessClassBody(const ir::ClassDefinition *classDef) { std::unordered_set processedMethods; @@ -1544,6 +1561,7 @@ void TSDeclGen::ProcessClassBody(const ir::ClassDefinition *classDef) GenClassDeclaration(prop->AsClassDeclaration()); } } + ProcessMethodsFromInterfaces(processedMethods, classDef); } void TSDeclGen::CloseClassBlock(const bool isDts) diff --git a/ets2panda/declgen_ets2ts/declgenEts2Ts.h b/ets2panda/declgen_ets2ts/declgenEts2Ts.h index 005c75ce3e..b56b8a933c 100644 --- a/ets2panda/declgen_ets2ts/declgenEts2Ts.h +++ b/ets2panda/declgen_ets2ts/declgenEts2Ts.h @@ -201,6 +201,9 @@ private: void ProcessMethodDefinition(const ir::MethodDefinition *methodDef, std::unordered_set &processedMethods); + void ProcessMethodsFromInterfaces(const std::unordered_set &processedMethods, + const ir::ClassDefinition *classDef); + void OutDts() {} template -- Gitee From bdbd7e753cff1e632d00c170c0c682b818ce2d91 Mon Sep 17 00:00:00 2001 From: Dmitry Pimenov Date: Wed, 23 Apr 2025 18:32:42 +0300 Subject: [PATCH 159/268] Fix crush on 'WE: readonly true' Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC3HF5 Signed-off-by: Dmitry Pimenov Change-Id: I8ed3a3845f6481e25887ca30656ad36c08c7ffca --- ets2panda/parser/ETSparserTypes.cpp | 15 +++++---- .../ets/readonly/label_readonly_true.ets | 28 ++++++++++++++++ .../compiler/ets/readonly/readonly_array.ets | 24 ++++++++++++++ .../ets/readonly/readonly_as_args_type.ets | 22 +++++++++++++ .../ets/readonly/readonly_as_fields_type.ets | 31 ++++++++++++++++++ .../ets/readonly/readonly_static_var.ets | 23 +++++++++++++ .../ets/readonlyFunctionTypeAnnotation.ets | 32 +++++++++++++++++++ 7 files changed, 169 insertions(+), 6 deletions(-) create mode 100644 ets2panda/test/ast/compiler/ets/readonly/label_readonly_true.ets create mode 100644 ets2panda/test/ast/compiler/ets/readonly/readonly_array.ets create mode 100644 ets2panda/test/ast/compiler/ets/readonly/readonly_as_args_type.ets create mode 100644 ets2panda/test/ast/compiler/ets/readonly/readonly_as_fields_type.ets create mode 100644 ets2panda/test/ast/compiler/ets/readonly/readonly_static_var.ets create mode 100644 ets2panda/test/ast/parser/ets/readonlyFunctionTypeAnnotation.ets diff --git a/ets2panda/parser/ETSparserTypes.cpp b/ets2panda/parser/ETSparserTypes.cpp index 98a1a79cd7..e754fad657 100644 --- a/ets2panda/parser/ETSparserTypes.cpp +++ b/ets2panda/parser/ETSparserTypes.cpp @@ -506,11 +506,15 @@ bool ETSParser::ParseReadonlyInTypeAnnotation() ir::TypeNode *ETSParser::ParseTypeAnnotation(TypeAnnotationParsingOptions *options) { - ir::TypeNode *typeAnnotation = nullptr; - auto startPos = Lexer()->GetToken().Start(); + const auto startPos = Lexer()->GetToken().Start(); // if there is prefix readonly parameter type, change the return result to ETSTypeReference, like Readonly<> if (Lexer()->TryEatTokenFromKeywordType(lexer::TokenType::KEYW_READONLY)) { - typeAnnotation = ParseTypeAnnotationNoPreferParam(options); + const auto beforeTypeAnnotation = Lexer()->GetToken().Loc(); + auto typeAnnotation = ParseTypeAnnotationNoPreferParam(options); + if (typeAnnotation == nullptr) { + LogError(diagnostic::INVALID_TYPE); + return AllocBrokenType(beforeTypeAnnotation); + } if (!typeAnnotation->IsTSArrayType() && !typeAnnotation->IsETSTuple() && !(typeAnnotation->IsETSTypeReference() && typeAnnotation->AsETSTypeReference()->BaseName()->Name() == compiler::Signatures::ARRAY)) { @@ -522,10 +526,9 @@ ir::TypeNode *ETSParser::ParseTypeAnnotation(TypeAnnotationParsingOptions *optio } typeAnnotation->SetStart(startPos); typeAnnotation->AddModifier(ir::ModifierFlags::READONLY_PARAMETER); - } else { - typeAnnotation = ParseTypeAnnotationNoPreferParam(options); + return typeAnnotation; } - return typeAnnotation; + return ParseTypeAnnotationNoPreferParam(options); } ir::TypeNode *ETSParser::ParseMultilineString() diff --git a/ets2panda/test/ast/compiler/ets/readonly/label_readonly_true.ets b/ets2panda/test/ast/compiler/ets/readonly/label_readonly_true.ets new file mode 100644 index 0000000000..f0f192c0a9 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/readonly/label_readonly_true.ets @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +WE: /* @@ readonly1 */readonly /* @@ true */true; +let/* @@ colon */: /* @@ readonly2 */readonly/* @@ end */; + +/* @@@ readonly1 Error SyntaxError: Label must be followed by a loop statement. */ +/* @@@ readonly1 Error TypeError: Unresolved reference readonly */ +/* @@@ true Error SyntaxError: Invalid Type. */ +/* @@@ true Error SyntaxError: Unexpected token 'true'. */ + +/* @@@ colon Error SyntaxError: Identifier expected, got ':'. */ +/* @@@ readonly2 Error SyntaxError: Variable must be initialized or it's type must be declared. */ +/* @@@ readonly2 Error SyntaxError: Variable must be initialized or it's type must be declared. */ +/* @@@ readonly2 Error SyntaxError: Unexpected token 'readonly'. */ +/* @@@ end Error SyntaxError: Invalid Type. */ diff --git a/ets2panda/test/ast/compiler/ets/readonly/readonly_array.ets b/ets2panda/test/ast/compiler/ets/readonly/readonly_array.ets new file mode 100644 index 0000000000..4b6b812ce6 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/readonly/readonly_array.ets @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +let a: readonly int [/* @@ E1 */""/* @@ E2 */]; + +/* @@@ E1 Error SyntaxError: Unexpected token, expected ']'. */ +/* @@@ E1 Error SyntaxError: Invalid Type. */ +/* @@@ E1 Error SyntaxError: Unexpected token ']'. */ +/* @@@ E1 Error SyntaxError: Unexpected token ']'. */ +/* @@@ E1 Error SyntaxError: Unexpected token ']'. */ +/* @@@ E2 Error SyntaxError: Unexpected token ']'. */ +/* @@@ E2 Error SyntaxError: Unexpected token ']'. */ diff --git a/ets2panda/test/ast/compiler/ets/readonly/readonly_as_args_type.ets b/ets2panda/test/ast/compiler/ets/readonly/readonly_as_args_type.ets new file mode 100644 index 0000000000..fe4d6158f7 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/readonly/readonly_as_args_type.ets @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +function foo(param1: readonly/* @@ foo_param1 */, param2: readonly /* @@ foo_param2 */true) {} + +/* @@@ foo_param1 Error SyntaxError: Invalid Type. */ +/* @@@ foo_param1 Error SyntaxError: 'readonly' type modifier is only permitted on resizable array and tuple types. */ + +/* @@@ foo_param2 Error SyntaxError: Invalid Type. */ +/* @@@ foo_param2 Error SyntaxError: 'readonly' type modifier is only permitted on resizable array and tuple types. */ diff --git a/ets2panda/test/ast/compiler/ets/readonly/readonly_as_fields_type.ets b/ets2panda/test/ast/compiler/ets/readonly/readonly_as_fields_type.ets new file mode 100644 index 0000000000..3830a00052 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/readonly/readonly_as_fields_type.ets @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class A { + a: readonly/* @@ A_a */; + b: readonly /* @@ A_b */false; + c: readonly /* @@ A_c */1; +} + +/* @@@ A_a Error SyntaxError: Invalid Type. */ +/* @@@ A_a Error SyntaxError: 'readonly' type modifier is only permitted on resizable array and tuple types. */ + +/* @@@ A_b Error SyntaxError: Invalid Type. */ +/* @@@ A_b Error SyntaxError: 'readonly' type modifier is only permitted on resizable array and tuple types. */ +/* @@@ A_b Error SyntaxError: Unexpected token 'false'. */ + +/* @@@ A_c Error SyntaxError: Invalid Type. */ +/* @@@ A_c Error SyntaxError: 'readonly' type modifier is only permitted on resizable array and tuple types. */ +/* @@@ A_c Error SyntaxError: Unexpected token '1'. */ diff --git a/ets2panda/test/ast/compiler/ets/readonly/readonly_static_var.ets b/ets2panda/test/ast/compiler/ets/readonly/readonly_static_var.ets new file mode 100644 index 0000000000..816f9ea537 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/readonly/readonly_static_var.ets @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* @@ readonly */readonly /* @@ static */static /* @@ S */S = c' '; + +/* @@@ readonly Error TypeError: Unresolved reference readonly */ +/* @@@ static Error SyntaxError: Invalid Type. */ +/* @@@ static Error SyntaxError: Unexpected token 'static'. */ +/* @@@ static Error SyntaxError: Unexpected token 'static'. */ +/* @@@ S Error SyntaxError: Unexpected token 'S'. */ +/* @@@ S Error TypeError: Unresolved reference S */ diff --git a/ets2panda/test/ast/parser/ets/readonlyFunctionTypeAnnotation.ets b/ets2panda/test/ast/parser/ets/readonlyFunctionTypeAnnotation.ets new file mode 100644 index 0000000000..b36e68e76e --- /dev/null +++ b/ets2panda/test/ast/parser/ets/readonlyFunctionTypeAnnotation.ets @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +func: readonly (Y : object | long [] ) => [ ] + +/* @@? 17:7 Error SyntaxError: Label must be followed by a loop statement. */ +/* @@? 17:7 Error TypeError: Unresolved reference readonly */ +/* @@? 17:17 Error SyntaxError: Invalid Type. */ +/* @@? 17:20 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 17:20 Error SyntaxError: Unexpected token ':'. */ +/* @@? 17:20 Error SyntaxError: Unexpected token ':'. */ +/* @@? 17:20 Error SyntaxError: Unexpected token ':'. */ +/* @@? 17:22 Error TypeError: Type name 'object' used in the wrong context */ +/* @@? 17:22 Error TypeError: Bad operand type, the types of the operands must be numeric type. */ +/* @@? 17:39 Error SyntaxError: Unexpected token ')'. */ +/* @@? 17:39 Error SyntaxError: Unexpected token ')'. */ +/* @@? 17:39 Error SyntaxError: Unexpected token ')'. */ +/* @@? 17:42 Error SyntaxError: Unexpected token '=>'. */ +/* @@? 17:42 Error SyntaxError: Unexpected token '=>'. */ \ No newline at end of file -- Gitee From b0a6a78857705299564a9a42f2aab5df91d25225 Mon Sep 17 00:00:00 2001 From: liyue Date: Tue, 29 Apr 2025 23:24:41 +0800 Subject: [PATCH 160/268] Add tests between different versions of es2abc Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC51G0 Signed-off-by: liyue Change-Id: Ibff3f4837b0c8f70198dc788034f9286ec1392ba --- es2panda/test/config.py | 9 + es2panda/test/runner.py | 318 +- ...r_equal_to_API11_asm_version-expected.txt} | 0 ...r_equal_to_API11_asm_version-expected.txt} | 0 ...r_equal_to_API11_asm_version-expected.txt} | 0 ...r_equal_to_API11_asm_version-expected.txt} | 0 ...r_equal_to_API11_asm_version-expected.txt} | 0 ...r_equal_to_API11_asm_version-expected.txt} | 0 ...r_equal_to_API11_asm_version-expected.txt} | 0 ...upported_compile_asm_version-expected.txt} | 0 ...r_equal_to_API11_asm_version-expected.txt} | 0 ...ual_to_API12beta3_asm_version-expected.txt | 44 + ...er_or_equal_to_API11_version-expected.txt} | 0 ..._equal_to_API12beta3_version-expected.txt} | 0 ...s_unsupported_runtime_version-expected.txt | 1 + ...r_equal_to_API11_asm_version-expected.txt} | 0 ...supported_compile_asm_version-expected.txt | 21 +- ...r_equal_to_API11_asm_version-expected.txt} | 0 ...al_to_API12beta3_asm_version-expected.txt} | 12 +- ...er_or_equal_to_API11_version-expected.txt} | 0 ..._equal_to_API12beta3_version-expected.txt} | 0 ..._unsupported_runtime_version-expected.txt} | 0 ...r_equal_to_API11_asm_version-expected.txt} | 0 ...upported_compile_asm_version-expected.txt} | 0 ...r_equal_to_API11_asm_version-expected.txt} | 0 ...ual_to_API12beta3_asm_version-expected.txt | 5651 +++++++++++++++++ ...er_or_equal_to_API11_version-expected.txt} | 0 ...r_equal_to_API12beta3_version-expected.txt | 1 + ..._unsupported_runtime_version-expected.txt} | 0 ...her_or_equal_to_API11_version-expected.txt | 1 + ...r_equal_to_API12beta3_version-expected.txt | 1 + ...e_unsupported_runtime_version-expected.txt | 1 + ...upported_compile_asm_version-expected.txt} | 0 ...r_equal_to_API11_asm_version-expected.txt} | 0 ...ual_to_API12beta3_asm_version-expected.txt | 50 + ...er_or_equal_to_API11_version-expected.txt} | 0 ...n_unsupported_runtime_version-expected.txt | 1 + ...upported_compile_asm_version-expected.txt} | 0 ...supported_compile_asm_version-expected.txt | 5 +- ...r_equal_to_API11_asm_version-expected.txt} | 5 +- 40 files changed, 6048 insertions(+), 73 deletions(-) rename es2panda/test/version_control/API11/bytecode_feature/{class_init_callinit_supported_compile_for_below_API12beta3_asm_version-expected.txt => class_init_callinit_supported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt} (100%) rename es2panda/test/version_control/API11/bytecode_feature/{class_private_property_supported_compile_for_below_API12beta3_asm_version-expected.txt => class_private_property_supported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt} (100%) rename es2panda/test/version_control/API11/bytecode_feature/{computed_property_name_as_class_key_supported_compile_for_below_API12beta3_asm_version-expected.txt => computed_property_name_as_class_key_supported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt} (100%) rename es2panda/test/version_control/API11/bytecode_feature/{define_ld_sendable_class_supported_compile_for_below_API12beta3_asm_version-expected.txt => define_ld_sendable_class_supported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt} (100%) rename es2panda/test/version_control/API11/bytecode_feature/{in_obj_syntax_supported_compile_for_below_API12beta3_asm_version-expected.txt => in_obj_syntax_supported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt} (100%) rename es2panda/test/version_control/API11/bytecode_feature/{public_field_replace_set_semantics_as_define_supported_compile_for_below_API12beta3_asm_version-expected.txt => public_field_replace_set_semantics_as_define_supported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt} (100%) rename es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/{lazy_loading_mudule_variables_in_sendable_class_supported_compile_for_below_API12beta3_asm_version-expected.txt => lazy_loading_mudule_variables_in_sendable_class_supported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt} (100%) rename es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/{lazy_loading_mudule_variables_in_sendable_class_unsupported_compile_for_below_API11_asm_version-expected.txt => lazy_loading_mudule_variables_in_sendable_class_unsupported_compile_asm_version-expected.txt} (100%) rename es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/{lazy_loading_mudule_variables_in_sendable_class_unsupported_compile_for_below_API12beta3_asm_version-expected.txt => lazy_loading_mudule_variables_in_sendable_class_unsupported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt} (100%) create mode 100644 es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_unsupported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt rename es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/{lazy_loading_mudule_variables_in_sendable_class_unsupported_runtime_for_below_API11_version-expected.txt => lazy_loading_mudule_variables_in_sendable_class_unsupported_runtime_for_higher_or_equal_to_API11_version-expected.txt} (100%) rename es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/{lazy_loading_mudule_variables_in_sendable_class_unsupported_runtime_for_below_API12beta3_version-expected.txt => lazy_loading_mudule_variables_in_sendable_class_unsupported_runtime_for_higher_or_equal_to_API12beta3_version-expected.txt} (100%) create mode 100644 es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_unsupported_runtime_version-expected.txt rename es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/{sendable_lexical_env_supported_compile_for_below_API12beta3_asm_version-expected.txt => sendable_lexical_env_supported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt} (100%) rename es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/{sendable_lexical_env_unsupported_compile_for_below_API12beta3_asm_version-expected.txt => sendable_lexical_env_unsupported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt} (100%) rename es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/{sendable_lexical_env_unsupported_compile_for_below_API11_asm_version-expected.txt => sendable_lexical_env_unsupported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt} (76%) rename es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/{sendable_lexical_env_unsupported_runtime_for_below_API12beta3_version-expected.txt => sendable_lexical_env_unsupported_runtime_for_higher_or_equal_to_API11_version-expected.txt} (100%) rename es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/{wide_sendable_lexical_env_unsupported_runtime_for_below_API12beta3_version-expected.txt => sendable_lexical_env_unsupported_runtime_for_higher_or_equal_to_API12beta3_version-expected.txt} (100%) rename es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/{sendable_lexical_env_unsupported_runtime_for_below_API11_version-expected.txt => sendable_lexical_env_unsupported_runtime_version-expected.txt} (100%) rename es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/{wide_sendable_lexical_env_supported_compile_for_below_API12beta3_asm_version-expected.txt => wide_sendable_lexical_env_supported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt} (100%) rename es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/{wide_sendable_lexical_env_unsupported_compile_for_below_API11_asm_version-expected.txt => wide_sendable_lexical_env_unsupported_compile_asm_version-expected.txt} (100%) rename es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/{wide_sendable_lexical_env_unsupported_compile_for_below_API12beta3_asm_version-expected.txt => wide_sendable_lexical_env_unsupported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt} (100%) create mode 100644 es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_unsupported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt rename es2panda/test/version_control/API12beta1_and_beta2/{syntax_feature/top_level_sendable_class_as_closure_unsupported_runtime_for_below_API12beta3_version-expected.txt => bytecode_feature/wide_sendable_lexical_env_unsupported_runtime_for_higher_or_equal_to_API11_version-expected.txt} (100%) create mode 100644 es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_unsupported_runtime_for_higher_or_equal_to_API12beta3_version-expected.txt rename es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/{wide_sendable_lexical_env_unsupported_runtime_for_below_API11_version-expected.txt => wide_sendable_lexical_env_unsupported_runtime_version-expected.txt} (100%) create mode 100644 es2panda/test/version_control/API12beta1_and_beta2/syntax_feature/top_level_sendable_class_as_closure_unsupported_runtime_for_higher_or_equal_to_API11_version-expected.txt create mode 100644 es2panda/test/version_control/API12beta1_and_beta2/syntax_feature/top_level_sendable_class_as_closure_unsupported_runtime_for_higher_or_equal_to_API12beta3_version-expected.txt create mode 100644 es2panda/test/version_control/API12beta1_and_beta2/syntax_feature/top_level_sendable_class_as_closure_unsupported_runtime_version-expected.txt rename es2panda/test/version_control/API12beta3/bytecode_feature/{define_property_by_name_unsupported_compile_for_below_API11_asm_version-expected.txt => define_property_by_name_unsupported_compile_asm_version-expected.txt} (100%) rename es2panda/test/version_control/API12beta3/bytecode_feature/{define_property_by_name_unsupported_compile_for_below_API12beta3_asm_version-expected.txt => define_property_by_name_unsupported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt} (100%) create mode 100644 es2panda/test/version_control/API12beta3/bytecode_feature/define_property_by_name_unsupported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt rename es2panda/test/version_control/API12beta3/syntax_feature/{sendable_function_unsupported_runtime_for_below_API12beta3_version-expected.txt => sendable_function_unsupported_runtime_for_higher_or_equal_to_API11_version-expected.txt} (100%) create mode 100644 es2panda/test/version_control/API12beta3/syntax_feature/sendable_function_unsupported_runtime_version-expected.txt rename es2panda/test/version_control/API18/bytecode_feature/{derived-class-default-constructor-opt_unsupported_compile_for_below_API12beta3_asm_version-expected.txt => derived-class-default-constructor-opt_unsupported_compile_asm_version-expected.txt} (100%) rename es2panda/test/version_control/API18/bytecode_feature/{sendable-class-export_unsupported_compile_for_below_API11_asm_version-expected.txt => sendable-class-export_unsupported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt} (89%) diff --git a/es2panda/test/config.py b/es2panda/test/config.py index 813c555c18..6cf0d5ede3 100644 --- a/es2panda/test/config.py +++ b/es2panda/test/config.py @@ -33,6 +33,15 @@ API_VERSION_MAP = { ARK_JS_VM_LIST = {"API9", "API10", "API11", "API12beta1", "API12beta3", "API18"} +ES2ABC_API_SUPPORT = { + "default": ["API9", "API10", "API11", "API12beta1", "API12beta2", "API12beta3", + "API13", "API14", "API15", "API16", "API17", "API18"], + "5.0": ["API9", "API10", "API11", "API12beta1", "API12beta2", "API12beta3", + "API13", "API14", "API15", "API16", "API17"], + "5.1": ["API9", "API10", "API11", "API12beta1", "API12beta2", "API12beta3", + "API13", "API14", "API15", "API16", "API17", "API18"], +} + MIN_SUPPORT_BC_VERSION = "API12beta1" MIX_COMPILE_ENTRY_POINT = "import" diff --git a/es2panda/test/runner.py b/es2panda/test/runner.py index c4de73a4e9..04870f230a 100755 --- a/es2panda/test/runner.py +++ b/es2panda/test/runner.py @@ -25,7 +25,7 @@ import re import shutil import subprocess import sys -from config import API_VERSION_MAP, ARK_JS_VM_LIST, MIN_SUPPORT_BC_VERSION, MIX_COMPILE_ENTRY_POINT +from config import API_VERSION_MAP, ARK_JS_VM_LIST, MIN_SUPPORT_BC_VERSION, MIX_COMPILE_ENTRY_POINT, ES2ABC_API_SUPPORT def is_directory(parser, arg): @@ -1888,6 +1888,40 @@ class ArkJsVmDownload: # Obtain different versions of ark_js_vm and their depen self.git_clone(self.url, self.local_path) print("\ndownload finish.\n") +class CodeDownloader: + def __init__(self, args, url, components_name, max_retries=3): + self.build_dir = args.build_dir + self.url = url + self.local_path = path.join(self.build_dir, components_name) + self.max_retries = max_retries + + def run_cmd_cwd(self, cmd): + try: + proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + _, _ = proc.communicate() + return proc.wait() + except Exception as e: + print(f"Error executing command: {e}") + return -1 + + def git_clone(self, git_url, code_dir): + cmd = ["git", "clone", git_url, code_dir, "--depth=1"] + retries = 1 + while retries <= self.max_retries: + ret = self.run_cmd_cwd(cmd) + if ret == 0: + break + else: + print(f"\nWarning: Attempt #{retries} to clone '{git_url}' failed. Retrying...") + retries += 1 + assert ret == 0, f"\nError: Cloning '{git_url}' failed." + + def run(self): + if not os.path.exists(self.local_path): + print(f"\nStart downloading {self.url}...\n") + self.git_clone(self.url, self.local_path) + print("\nDownload finished.\n") + print(self.local_path) class AbcTestCasesPrepare: def __init__(self, args): @@ -1911,34 +1945,42 @@ class AbcTestCasesPrepare: files = fnmatch.filter(files, self.test_root + "**" + self.args.filter) return files - def gen_abc_versions(self, flags, source_path): - for api_version in API_VERSION_MAP: + def get_output_path(self, source_path, main_version, beta_version, es2abc_version): + base = path.splitext(source_path)[0] + suffix = f"version_API{main_version}{beta_version}" + return f"{base}_{es2abc_version}_{suffix}.abc" if es2abc_version != "default" else f"{base}_{suffix}.abc" + + def gen_abc_versions(self, flags, source_path, es2abc_version): + supported_apis = ES2ABC_API_SUPPORT.get(es2abc_version) + for api_version in supported_apis: main_version, beta_version = AbcTestCasesPrepare.split_api_version(api_version) - output_path = "%s_version_API%s%s.abc" % ( - path.splitext(source_path)[0], - main_version, - beta_version, - ) + output_path = self.get_output_path(source_path, main_version, beta_version, es2abc_version) self.test_abc_path_list.add(output_path) - _, stderr = self.compile_for_target_version(flags, source_path, output_path, main_version, beta_version) + _, stderr = self.compile_for_target_version(flags, source_path, output_path, main_version, beta_version, es2abc_version) if stderr: - raise RuntimeError(f"abc generate error: " % (stderr.decode("utf-8", errors="ignore"))) + raise RuntimeError(f"abc generate error: {stderr}") - def gen_abc_tests(self, directory, extension, flags, abc_mode): + def gen_abc_tests(self, directory, extension, flags, abc_mode, es2abc_versions=["default"]): if abc_mode not in self.valid_mode_list: raise ValueError(f"Invalid abc_mode value: {abc_mode}") test_source_list = self.add_abc_directory(directory, extension) - for input_path in test_source_list: - self.gen_abc_versions(flags, input_path) - def compile_for_target_version(self, flags, input_path, output_path, target_api_version, target_api_sub_version=""): + for es2abc_version in es2abc_versions: + for input_path in test_source_list: + self.gen_abc_versions(flags, input_path, es2abc_version) + + def compile_for_target_version(self, flags, input_path, output_path, target_api_version, target_api_sub_version="", es2abc_version="default"): + es2panda_path = ( + self.es2panda if es2abc_version == "default" + else os.path.join(self.args.build_dir, "es2abc_version", es2abc_version, "es2abc") + ) cmd = [] - cmd.append(self.es2panda) + cmd.append(es2panda_path) cmd.append(input_path) cmd.extend(flags) cmd.append("--target-api-version=%s" % (target_api_version)) cmd.extend(["--output=%s" % (output_path)]) - if target_api_version != "": + if target_api_sub_version != "": cmd.append("--target-api-sub-version=%s" % (target_api_sub_version)) process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = process.communicate(timeout=10) @@ -1973,7 +2015,6 @@ class AbcVersionControlRunner(Runner): def run(self): for test in self.tests: test.run(self) - self.args.abc_tests_prepare.remove_abc_tests() class VersionControlRunner(Runner): @@ -2050,6 +2091,7 @@ class TestAbcVersionControl(Test): if self.abc_mode == "mix_compile_mode" and test_stage != "runtime": support_name = "" expected_name = path.splitext(self.path)[0].split("_version_API")[0] + expected_name = re.sub(r"_(\d+\.\d+)(?=(_|$))", "", expected_name) expected_path = "%s_%s%s-expected.txt" % (expected_name, support_name, test_stage) return expected_path @@ -2072,51 +2114,74 @@ class TestAbcVersionControl(Test): cmd.extend(self.flags) cmd.append("--target-api-version=%s" % (target_api_version)) cmd.extend(["--output=%s" % (output_path)]) - if target_api_version != "": + if target_api_sub_version != "": cmd.append("--target-api-sub-version=%s" % (target_api_sub_version)) + self.log_cmd(cmd) stdout, stderr = self.run_process(cmd) return stdout, stderr - def generate_abc(self, runner, target_api_version, target_api_sub_version=""): - compile_expected_path = None - target_abc_name = ( - "%s_target_%s%s.abc" % (path.splitext(self.path)[0], target_api_version, target_api_sub_version) - ).replace("/", "_") - self.target_abc_path = path.join(runner.build_dir, target_abc_name) - _, stderr = self.compile_for_target_version( - runner, self.path, self.target_abc_path, target_api_version, target_api_sub_version - ) - format_content = "" - self.is_support = False + def build_abc_filename(self, target_api_version, target_api_sub_version): + prefix = f"{path.splitext(self.path)[0]}" + abc_name = f"{prefix}_target_{target_api_version}{target_api_sub_version}.abc" + return abc_name.replace("/", "_") - # Extract the API versions of the input abc files from the file name of the test case. + def extract_input_versions(self): input_api_versions = self.extract_api_versions(path.split(self.path)[1]) input_version_numbers = [API_VERSION_MAP.get(api) for api in input_api_versions] - sorted(input_version_numbers, key=TestAbcVersionControl.version_number_to_tuple) - min_input_version_number = input_version_numbers[0] - max_input_version_number = input_version_numbers[-1] + return sorted(input_version_numbers, key=TestAbcVersionControl.version_number_to_tuple) + + def determine_expected_behavior(self, target_api_version, target_api_sub_version, input_version_numbers): target_version = "API" + target_api_version + target_api_sub_version target_version_number = API_VERSION_MAP.get(target_version) + min_input_version_number = input_version_numbers[0] + max_input_version_number = input_version_numbers[-1] + if TestAbcVersionControl.compare_version_number(target_version_number, self.min_support_version_number) < 0: compile_expected_path = self.get_path_to_expected( - self.is_support, "compile_target_version_below_min_support" + False, "compile_target_version_below_min_support" ) - format_content = target_api_version + return False, compile_expected_path, target_api_version + elif ( TestAbcVersionControl.compare_version_number(min_input_version_number, self.min_support_version_number) < 0 ): - compile_expected_path = self.get_path_to_expected(self.is_support, "compile_cur_version_below_min_support") - format_content = self.path + compile_expected_path = self.get_path_to_expected(False, "compile_cur_version_below_min_support") + return False, compile_expected_path, self.path + elif TestAbcVersionControl.compare_version_number(target_version_number, max_input_version_number) < 0: - compile_expected_path = self.get_path_to_expected(self.is_support, "compile_target_version_below_cur") - format_content = self.path + compile_expected_path = self.get_path_to_expected(False, "compile_target_version_below_cur") + return False, compile_expected_path, self.path + elif self.is_discard: - compile_expected_path = self.get_path_to_expected(self.is_support, "compile_discard") - else: - self.is_support = True + compile_expected_path = self.get_path_to_expected(False, "compile_discard") + return False, compile_expected_path, "" + + return True, None, None + + def generate_abc(self, runner, target_api_version, target_api_sub_version=""): + compile_expected_path = None + target_abc_name = self.build_abc_filename(target_api_version, target_api_sub_version) + self.target_abc_path = path.join(runner.build_dir, target_abc_name) + + _, stderr = self.compile_for_target_version( + runner, self.path, self.target_abc_path, target_api_version, target_api_sub_version + ) + format_content = "" + self.is_support = False + + # Extract the API versions of the input abc files from the file name of the test case. + input_version_numbers = self.extract_input_versions() + + is_support, compile_expected_path, format_content = self.determine_expected_behavior( + target_api_version, target_api_sub_version, input_version_numbers + ) + self.is_support = is_support + if self.is_support: if stderr: self.passed = False + else: + self.passed = True return stderr try: @@ -2141,6 +2206,7 @@ class TestAbcVersionControl(Test): if entry_point != "": cmd.append("--entry-point=%s" % entry_point) cmd.append(self.target_abc_path) + self.log_cmd(cmd) stdout, stderr = self.run_process(cmd) return stdout, stderr @@ -2184,17 +2250,132 @@ class TestAbcVersionControl(Test): target_api_version, target_api_sub_version = AbcTestCasesPrepare.split_api_version(api_version) stderr = self.generate_abc(runner, target_api_version, target_api_sub_version) if not self.passed: - self.error = stderr.decode("utf-8", errors="ignore") + self.error = stderr return self if stderr: continue stderr = self.test_abc_execution(runner, target_api_version, target_api_sub_version) self.remove_abc(self.target_abc_path) if not self.passed: - self.error = stderr.decode("utf-8", errors="ignore") + self.error = stderr return self return self +class Es2abcVersionControlRunner(Runner): + def __init__(self, args): + super().__init__(args, "Es2abcVersionControl") + self.valid_mode_list = ["non_merge_mode", "merge_mode"] + + def add_directory(self, directory, extension, flags, abc_mode, is_discard=False): + if abc_mode not in self.valid_mode_list: + raise ValueError(f"Invalid abc_mode value: {abc_mode}") + glob_expression = path.join(self.test_root, directory, "*.%s" % (extension)) + files = glob(glob_expression) + files = fnmatch.filter(files, self.test_root + "**" + self.args.filter) + self.tests += list(map(lambda f: TestEs2abcVersionControl(f, flags, abc_mode, is_discard), files)) + + def test_path(self, src): + return src + + def run(self): + for test in self.tests: + test.run(self) + self.args.abc_tests_prepare.remove_abc_tests() + +class TestEs2abcVersionControl(TestAbcVersionControl): + def __init__(self, test_path, flags, abc_mode, is_discard, es2abc_versions=None): + super().__init__(test_path, flags, abc_mode, is_discard) + self.es2abc_versions = es2abc_versions or list(ES2ABC_API_SUPPORT.keys()) + + @staticmethod + def version_str_to_tuple(version: str): + if isinstance(version, list): + version = ".".join(version) + return tuple(int(x) for x in version.split(".")) + + @classmethod + def get_max_supported_version(cls, es2abc_version: str) -> str: + supported_apis = ES2ABC_API_SUPPORT.get(es2abc_version, ES2ABC_API_SUPPORT["default"]) + max_api = max(supported_apis, key=lambda api: cls.version_str_to_tuple(API_VERSION_MAP[api])) + return API_VERSION_MAP[max_api] + + @classmethod + def should_skip_abc_file(cls, file_version: str, es2abc_version: str) -> bool: + max_supported_version = cls.get_max_supported_version(es2abc_version) + return cls.version_str_to_tuple(file_version) > cls.version_str_to_tuple(max_supported_version) + + def build_abc_filename(self, target_api_version, target_api_sub_version, es2abc_version): + prefix = f"{path.splitext(self.path)[0]}" + if es2abc_version == "default" or es2abc_version is None: + abc_name = f"{prefix}_target_{target_api_version}{target_api_sub_version}.abc" + else: + abc_name = f"{prefix}_{es2abc_version}_target_{target_api_version}{target_api_sub_version}.abc" + return abc_name.replace("/", "_") + + def compile_for_target_version( + self, runner, input_path, output_path, target_api_version, target_api_sub_version="", es2abc_version="default" + ): + cmd = [] + if es2abc_version != "default": + runner.es2panda = os.path.join(runner.build_dir, "es2abc_version", es2abc_version, "es2abc") + cmd.append(runner.es2panda) + cmd.append(input_path) + cmd.extend(self.flags) + cmd.append("--target-api-version=%s" % target_api_version) + cmd.extend(["--output=%s" % output_path]) + if target_api_sub_version: + cmd.append("--target-api-sub-version=%s" % target_api_sub_version) + self.es2abc_cmd = ' '.join(cmd) + stdout, stderr = self.run_process(cmd) + return stdout, stderr + + def generate_abc(self, runner, target_api_version, target_api_sub_version=""): + compile_expected_path = None + input_version_numbers = self.extract_input_versions() + + for es2abc_version in self.es2abc_versions: + target_abc_name = self.build_abc_filename(target_api_version, target_api_sub_version, es2abc_version) + self.target_abc_path = path.join(runner.build_dir, target_abc_name) + + _, stderr = self.compile_for_target_version( + runner, self.path, self.target_abc_path, target_api_version, target_api_sub_version, es2abc_version + ) + + format_content = "" + self.is_support = False + + # The version of the abc file exceeds the maximum supported range of es2abc + if self.should_skip_abc_file(input_version_numbers, es2abc_version): + continue + + is_support, compile_expected_path, format_content = self.determine_expected_behavior( + target_api_version, target_api_sub_version, input_version_numbers + ) + self.is_support = is_support + if self.is_support: + if stderr: + self.passed = False + else: + self.passed = True + return stderr + + try: + with open(compile_expected_path, "r") as fp: + expected = fp.read() + self.passed = expected.format(format_content) in self.output and self.process.returncode in [0, 1] + except Exception: + self.passed = False + return stderr + return None + + def run(self, runner): + for api_version in API_VERSION_MAP: + target_api_version, target_api_sub_version = AbcTestCasesPrepare.split_api_version(api_version) + stderr = self.generate_abc(runner, target_api_version, target_api_sub_version) + if not self.passed: + self.error = stderr + return self + return self class TestVersionControl(Test): def __init__(self, test_path, flags, test_version, feature_type, module_path_list): @@ -2203,7 +2384,7 @@ class TestVersionControl(Test): self.version_with_sub_version_list = ["12"] self.target_api_version_list = ["9", "10", "11", "12", "18", "20"] self.target_api_sub_version_list = ["beta1", "beta2", "beta3"] - self.specific_api_version_list = ["API11", "API12beta3"] + self.specific_api_version_list = ["API18", "API12beta3", "API11"] self.output = None self.process = None self.test_version = test_version @@ -2289,13 +2470,10 @@ class TestVersionControl(Test): api_name = "" # Higher than the specific API version, expected results may differ if target_api_version != "" and specific_api_version != "": - if self.compare_two_versions(target_api_version, "API18") >= 0: - api_name = "for_higher_or_equal_to_%s_" % "API18" + if self.compare_two_versions(target_api_version, specific_api_version) >= 0: + api_name = "for_higher_or_equal_to_%s_" % (specific_api_version) else: - if self.compare_two_versions(target_api_version, specific_api_version) >= 0: - api_name = "for_higher_or_equal_to_%s_" % (specific_api_version) - else: - api_name = "for_below_%s_" % (specific_api_version) + api_name = "for_below_%s_" % (specific_api_version) if dump_type == "ast": dump_type = "" elif dump_type == "asm": @@ -2361,6 +2539,7 @@ class TestVersionControl(Test): cmd.append("--dump-ast") elif dump_type == "assembly": cmd.append("--dump-assembly") + self.log_cmd(cmd) stdout, stderr = self.run_process(cmd) return stdout, stderr @@ -2388,6 +2567,7 @@ class TestVersionControl(Test): ark_js_vm_path = os.path.join(ark_js_vm_dir, "ark_js_vm") cmd.append(ark_js_vm_path) cmd.append(self.test_abc_path) + self.log_cmd(cmd) self.process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = self.process.communicate() self.output = stdout.decode("utf-8", errors="ignore") + stderr.decode("utf-8", errors="ignore").split("\n")[0] @@ -2507,8 +2687,21 @@ def prepare_for_obfuscation(compiler_test_infos, test_root): def add_directory_for_version_control(runners, args): - ark_js_vm_prepared = ArkJsVmDownload(args) - ark_js_vm_prepared.run() + tools = [ + { + "url": "https://gitee.com/zhongmingwei123123/ark_js_vm_version.git", + "components_name": "ark_js_vm_version" + }, + { + "url": "https://gitee.com/li_yue1999/es2abc_version.git", + "components_name": "es2abc_version" + } + ] + + for tool in tools: + downloader = CodeDownloader(args, tool['url'], tool['components_name']) + downloader.run() + runner = VersionControlRunner(args) runner.add_directory( "version_control/API11/syntax_feature", @@ -2623,17 +2816,21 @@ def add_directory_for_version_control(runners, args): runners.append(runner) abc_tests_prepare = AbcTestCasesPrepare(args) + es2abc_versions = list(ES2ABC_API_SUPPORT.keys()) + abc_tests_prepare.gen_abc_tests( "version_control/bytecode_version_control/non_merge_mode", "js", ["--module"], "non_merge_mode", + es2abc_versions ) abc_tests_prepare.gen_abc_tests( "version_control/bytecode_version_control/merge_mode", "js", ["--module", "--merge-abc"], "merge_mode", + es2abc_versions ) abc_tests_prepare.gen_abc_tests( "version_control/bytecode_version_control/mixed_compile", @@ -2664,6 +2861,21 @@ def add_directory_for_version_control(runners, args): ) runners.append(abc_version_control_runner) + es2abc_version_control_runner = Es2abcVersionControlRunner(args) + es2abc_version_control_runner.add_directory( + "version_control/bytecode_version_control/non_merge_mode", + "abc", + ["--module", "--enable-abc-input"], + "non_merge_mode", + ) + es2abc_version_control_runner.add_directory( + "version_control/bytecode_version_control/merge_mode", + "abc", + ["--module", "--enable-abc-input", "--merge-abc"], + "merge_mode", + ) + runners.append(es2abc_version_control_runner) + def add_directory_for_regression(runners, args): runner = RegressionRunner(args) runner.add_directory("parser/concurrent", "js", ["--module", "--dump-ast"]) diff --git a/es2panda/test/version_control/API11/bytecode_feature/class_init_callinit_supported_compile_for_below_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API11/bytecode_feature/class_init_callinit_supported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API11/bytecode_feature/class_init_callinit_supported_compile_for_below_API12beta3_asm_version-expected.txt rename to es2panda/test/version_control/API11/bytecode_feature/class_init_callinit_supported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt diff --git a/es2panda/test/version_control/API11/bytecode_feature/class_private_property_supported_compile_for_below_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API11/bytecode_feature/class_private_property_supported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API11/bytecode_feature/class_private_property_supported_compile_for_below_API12beta3_asm_version-expected.txt rename to es2panda/test/version_control/API11/bytecode_feature/class_private_property_supported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt diff --git a/es2panda/test/version_control/API11/bytecode_feature/computed_property_name_as_class_key_supported_compile_for_below_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API11/bytecode_feature/computed_property_name_as_class_key_supported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API11/bytecode_feature/computed_property_name_as_class_key_supported_compile_for_below_API12beta3_asm_version-expected.txt rename to es2panda/test/version_control/API11/bytecode_feature/computed_property_name_as_class_key_supported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt diff --git a/es2panda/test/version_control/API11/bytecode_feature/define_ld_sendable_class_supported_compile_for_below_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API11/bytecode_feature/define_ld_sendable_class_supported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API11/bytecode_feature/define_ld_sendable_class_supported_compile_for_below_API12beta3_asm_version-expected.txt rename to es2panda/test/version_control/API11/bytecode_feature/define_ld_sendable_class_supported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt diff --git a/es2panda/test/version_control/API11/bytecode_feature/in_obj_syntax_supported_compile_for_below_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API11/bytecode_feature/in_obj_syntax_supported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API11/bytecode_feature/in_obj_syntax_supported_compile_for_below_API12beta3_asm_version-expected.txt rename to es2panda/test/version_control/API11/bytecode_feature/in_obj_syntax_supported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt diff --git a/es2panda/test/version_control/API11/bytecode_feature/public_field_replace_set_semantics_as_define_supported_compile_for_below_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API11/bytecode_feature/public_field_replace_set_semantics_as_define_supported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API11/bytecode_feature/public_field_replace_set_semantics_as_define_supported_compile_for_below_API12beta3_asm_version-expected.txt rename to es2panda/test/version_control/API11/bytecode_feature/public_field_replace_set_semantics_as_define_supported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt diff --git a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_supported_compile_for_below_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_supported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_supported_compile_for_below_API12beta3_asm_version-expected.txt rename to es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_supported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt diff --git a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_unsupported_compile_for_below_API11_asm_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_unsupported_compile_asm_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_unsupported_compile_for_below_API11_asm_version-expected.txt rename to es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_unsupported_compile_asm_version-expected.txt diff --git a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_unsupported_compile_for_below_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_unsupported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_unsupported_compile_for_below_API12beta3_asm_version-expected.txt rename to es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_unsupported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt diff --git a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_unsupported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_unsupported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt new file mode 100644 index 0000000000..6e71af8b31 --- /dev/null +++ b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_unsupported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt @@ -0,0 +1,44 @@ +slotNum = 0x4 +.language ECMAScript +.function any .SendableLazyLoading(any a0, any a1, any a2) { +label_1: +label_0: + ldexternalmodulevar 0x0 + sta v0 + throw.undefinedifholewithname a1 + lda v0 + stobjbyname 0x0, name, a2 + wide.ldexternalmodulevar 0xad + sta v0 + throw.undefinedifholewithname a255 + lda v0 + stobjbyname 0x2, name1, a2 + lda a2 + return +label_2: +} + +slotNum = 0x8 +.language ECMAScript +.function any .func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + ldhole + sta v0 + callruntime.definesendableclass 0x0, .SendableLazyLoading, _2, 0x0, v0 + sta v0 + mov v2, v0 + newobjrange 0x1, 0x1, v2 + sta v0 + tryldglobalbyname 0x3, print + sta v1 + lda v0 + ldobjbyname 0x4, name + sta v0 + lda v1 + callarg1 0x6, v0 + returnundefined +label_2: +} + + diff --git a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_unsupported_runtime_for_below_API11_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_unsupported_runtime_for_higher_or_equal_to_API11_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_unsupported_runtime_for_below_API11_version-expected.txt rename to es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_unsupported_runtime_for_higher_or_equal_to_API11_version-expected.txt diff --git a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_unsupported_runtime_for_below_API12beta3_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_unsupported_runtime_for_higher_or_equal_to_API12beta3_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_unsupported_runtime_for_below_API12beta3_version-expected.txt rename to es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_unsupported_runtime_for_higher_or_equal_to_API12beta3_version-expected.txt diff --git a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_unsupported_runtime_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_unsupported_runtime_version-expected.txt new file mode 100644 index 0000000000..da0f8ed91a --- /dev/null +++ b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/lazy_loading_mudule_variables_in_sendable_class_unsupported_runtime_version-expected.txt @@ -0,0 +1 @@ +a1 diff --git a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_supported_compile_for_below_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_supported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_supported_compile_for_below_API12beta3_asm_version-expected.txt rename to es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_supported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt diff --git a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_unsupported_compile_asm_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_unsupported_compile_asm_version-expected.txt index cde3ccc641..fdad4e6d3a 100644 --- a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_unsupported_compile_asm_version-expected.txt +++ b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_unsupported_compile_asm_version-expected.txt @@ -1,5 +1,5 @@ +slotNum = 0xa .language ECMAScript - .function any .SendableTestClass1(any a0, any a1, any a2) { label_1: label_0: @@ -8,9 +8,9 @@ label_0: throw.undefinedifholewithname TopLevelSendableClass1 mov v1, v0 newobjrange 0x0, 0x1, v1 - stobjbyname 0x2, I1, a2 + stobjbyname 0x2, a1, a2 lda a2 - ldobjbyname 0x4, I1 + ldobjbyname 0x4, a1 ldobjbyname 0x6, o stobjbyname 0x8, u, a2 lda a2 @@ -18,6 +18,8 @@ label_0: label_2: } +slotNum = 0x2 +.language ECMAScript .function any .TopLevelSendableClass1(any a0, any a1, any a2) { label_1: label_0: @@ -28,21 +30,26 @@ label_0: label_2: } +slotNum = 0x8 +.language ECMAScript .function any .func_main_0(any a0, any a1, any a2) { label_1: label_0: newlexenv 0x1 ldhole sta v0 - callruntime.definesendableclass 0x0, .TopLevelSendableClass1, _2, 0x0, v0 + defineclasswithbuffer 0x0, .TopLevelSendableClass1, _1, 0x0, v0 + sta v0 + ldobjbyname 0x1, prototype + lda v0 stlexvar 0x0, 0x0 ldhole sta v0 - callruntime.definesendableclass 0x1, .SendableTestClass1, _4, 0x0, v0 + defineclasswithbuffer 0x3, .SendableTestClass1, _2, 0x0, v0 sta v0 + ldobjbyname 0x4, prototype mov v1, v0 - newobjrange 0x2, 0x1, v1 - ldundefined + newobjrange 0x6, 0x1, v1 returnundefined label_2: } diff --git a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_unsupported_compile_for_below_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_unsupported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_unsupported_compile_for_below_API12beta3_asm_version-expected.txt rename to es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_unsupported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt diff --git a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_unsupported_compile_for_below_API11_asm_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_unsupported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt similarity index 76% rename from es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_unsupported_compile_for_below_API11_asm_version-expected.txt rename to es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_unsupported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt index fdad4e6d3a..9648548b63 100644 --- a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_unsupported_compile_for_below_API11_asm_version-expected.txt +++ b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_unsupported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt @@ -30,7 +30,7 @@ label_0: label_2: } -slotNum = 0x8 +slotNum = 0x4 .language ECMAScript .function any .func_main_0(any a0, any a1, any a2) { label_1: @@ -38,18 +38,14 @@ label_0: newlexenv 0x1 ldhole sta v0 - defineclasswithbuffer 0x0, .TopLevelSendableClass1, _1, 0x0, v0 - sta v0 - ldobjbyname 0x1, prototype - lda v0 + callruntime.definesendableclass 0x0, .TopLevelSendableClass1, _2, 0x0, v0 stlexvar 0x0, 0x0 ldhole sta v0 - defineclasswithbuffer 0x3, .SendableTestClass1, _2, 0x0, v0 + callruntime.definesendableclass 0x1, .SendableTestClass1, _4, 0x0, v0 sta v0 - ldobjbyname 0x4, prototype mov v1, v0 - newobjrange 0x6, 0x1, v1 + newobjrange 0x2, 0x1, v1 returnundefined label_2: } diff --git a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_unsupported_runtime_for_below_API12beta3_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_unsupported_runtime_for_higher_or_equal_to_API11_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_unsupported_runtime_for_below_API12beta3_version-expected.txt rename to es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_unsupported_runtime_for_higher_or_equal_to_API11_version-expected.txt diff --git a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_unsupported_runtime_for_below_API12beta3_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_unsupported_runtime_for_higher_or_equal_to_API12beta3_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_unsupported_runtime_for_below_API12beta3_version-expected.txt rename to es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_unsupported_runtime_for_higher_or_equal_to_API12beta3_version-expected.txt diff --git a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_unsupported_runtime_for_below_API11_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_unsupported_runtime_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_unsupported_runtime_for_below_API11_version-expected.txt rename to es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/sendable_lexical_env_unsupported_runtime_version-expected.txt diff --git a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_supported_compile_for_below_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_supported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_supported_compile_for_below_API12beta3_asm_version-expected.txt rename to es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_supported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt diff --git a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_unsupported_compile_for_below_API11_asm_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_unsupported_compile_asm_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_unsupported_compile_for_below_API11_asm_version-expected.txt rename to es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_unsupported_compile_asm_version-expected.txt diff --git a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_unsupported_compile_for_below_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_unsupported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_unsupported_compile_for_below_API12beta3_asm_version-expected.txt rename to es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_unsupported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt diff --git a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_unsupported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_unsupported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt new file mode 100644 index 0000000000..33c3a51f3e --- /dev/null +++ b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_unsupported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt @@ -0,0 +1,5651 @@ +slotNum = 0x406 +.language ECMAScript +.function any .SendableTestClass1(any a0, any a1, any a2) { +label_1: +label_0: + ldlexvar 0x0, 0x0 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass1 + mov v1, v0 + newobjrange 0x0, 0x1, v1 + stobjbyname 0x2, a1, a2 + ldlexvar 0x0, 0x1 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass2 + mov v1, v0 + newobjrange 0x4, 0x1, v1 + stobjbyname 0x6, a2, a2 + ldlexvar 0x0, 0x2 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass3 + mov v1, v0 + newobjrange 0x8, 0x1, v1 + stobjbyname 0xa, a3, a2 + ldlexvar 0x0, 0x3 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass4 + mov v1, v0 + newobjrange 0xc, 0x1, v1 + stobjbyname 0xe, a4, a2 + ldlexvar 0x0, 0x4 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass5 + mov v1, v0 + newobjrange 0x10, 0x1, v1 + stobjbyname 0x12, a5, a2 + ldlexvar 0x0, 0x5 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass6 + mov v1, v0 + newobjrange 0x14, 0x1, v1 + stobjbyname 0x16, a6, a2 + ldlexvar 0x0, 0x6 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass7 + mov v1, v0 + newobjrange 0x18, 0x1, v1 + stobjbyname 0x1a, a7, a2 + ldlexvar 0x0, 0x7 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass8 + mov v1, v0 + newobjrange 0x1c, 0x1, v1 + stobjbyname 0x1e, a8, a2 + ldlexvar 0x0, 0x8 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass9 + mov v1, v0 + newobjrange 0x20, 0x1, v1 + stobjbyname 0x22, a9, a2 + ldlexvar 0x0, 0x9 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass10 + mov v1, v0 + newobjrange 0x24, 0x1, v1 + stobjbyname 0x26, a10, a2 + ldlexvar 0x0, 0xa + sta v0 + throw.undefinedifholewithname TopLevelSendableClass11 + mov v1, v0 + newobjrange 0x28, 0x1, v1 + stobjbyname 0x2a, a11, a2 + ldlexvar 0x0, 0xb + sta v0 + throw.undefinedifholewithname TopLevelSendableClass12 + mov v1, v0 + newobjrange 0x2c, 0x1, v1 + stobjbyname 0x2e, a12, a2 + ldlexvar 0x0, 0xc + sta v0 + throw.undefinedifholewithname TopLevelSendableClass13 + mov v1, v0 + newobjrange 0x30, 0x1, v1 + stobjbyname 0x32, a13, a2 + ldlexvar 0x0, 0xd + sta v0 + throw.undefinedifholewithname TopLevelSendableClass14 + mov v1, v0 + newobjrange 0x34, 0x1, v1 + stobjbyname 0x36, a14, a2 + ldlexvar 0x0, 0xe + sta v0 + throw.undefinedifholewithname TopLevelSendableClass15 + mov v1, v0 + newobjrange 0x38, 0x1, v1 + stobjbyname 0x3a, a15, a2 + ldlexvar 0x0, 0xf + sta v0 + throw.undefinedifholewithname TopLevelSendableClass16 + mov v1, v0 + newobjrange 0x3c, 0x1, v1 + stobjbyname 0x3e, a16, a2 + ldlexvar 0x0, 0x10 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass17 + mov v1, v0 + newobjrange 0x40, 0x1, v1 + stobjbyname 0x42, a17, a2 + ldlexvar 0x0, 0x11 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass18 + mov v1, v0 + newobjrange 0x44, 0x1, v1 + stobjbyname 0x46, a18, a2 + ldlexvar 0x0, 0x12 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass19 + mov v1, v0 + newobjrange 0x48, 0x1, v1 + stobjbyname 0x4a, a19, a2 + ldlexvar 0x0, 0x13 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass20 + mov v1, v0 + newobjrange 0x4c, 0x1, v1 + stobjbyname 0x4e, a20, a2 + ldlexvar 0x0, 0x14 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass21 + mov v1, v0 + newobjrange 0x50, 0x1, v1 + stobjbyname 0x52, a21, a2 + ldlexvar 0x0, 0x15 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass22 + mov v1, v0 + newobjrange 0x54, 0x1, v1 + stobjbyname 0x56, a22, a2 + ldlexvar 0x0, 0x16 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass23 + mov v1, v0 + newobjrange 0x58, 0x1, v1 + stobjbyname 0x5a, a23, a2 + ldlexvar 0x0, 0x17 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass24 + mov v1, v0 + newobjrange 0x5c, 0x1, v1 + stobjbyname 0x5e, a24, a2 + ldlexvar 0x0, 0x18 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass25 + mov v1, v0 + newobjrange 0x60, 0x1, v1 + stobjbyname 0x62, a25, a2 + ldlexvar 0x0, 0x19 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass26 + mov v1, v0 + newobjrange 0x64, 0x1, v1 + stobjbyname 0x66, a26, a2 + ldlexvar 0x0, 0x1a + sta v0 + throw.undefinedifholewithname TopLevelSendableClass27 + mov v1, v0 + newobjrange 0x68, 0x1, v1 + stobjbyname 0x6a, a27, a2 + ldlexvar 0x0, 0x1b + sta v0 + throw.undefinedifholewithname TopLevelSendableClass28 + mov v1, v0 + newobjrange 0x6c, 0x1, v1 + stobjbyname 0x6e, a28, a2 + ldlexvar 0x0, 0x1c + sta v0 + throw.undefinedifholewithname TopLevelSendableClass29 + mov v1, v0 + newobjrange 0x70, 0x1, v1 + stobjbyname 0x72, a29, a2 + ldlexvar 0x0, 0x1d + sta v0 + throw.undefinedifholewithname TopLevelSendableClass30 + mov v1, v0 + newobjrange 0x74, 0x1, v1 + stobjbyname 0x76, a30, a2 + ldlexvar 0x0, 0x1e + sta v0 + throw.undefinedifholewithname TopLevelSendableClass31 + mov v1, v0 + newobjrange 0x78, 0x1, v1 + stobjbyname 0x7a, a31, a2 + ldlexvar 0x0, 0x1f + sta v0 + throw.undefinedifholewithname TopLevelSendableClass32 + mov v1, v0 + newobjrange 0x7c, 0x1, v1 + stobjbyname 0x7e, a32, a2 + ldlexvar 0x0, 0x20 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass33 + mov v1, v0 + newobjrange 0x80, 0x1, v1 + stobjbyname 0x82, a33, a2 + ldlexvar 0x0, 0x21 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass34 + mov v1, v0 + newobjrange 0x84, 0x1, v1 + stobjbyname 0x86, a34, a2 + ldlexvar 0x0, 0x22 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass35 + mov v1, v0 + newobjrange 0x88, 0x1, v1 + stobjbyname 0x8a, a35, a2 + ldlexvar 0x0, 0x23 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass36 + mov v1, v0 + newobjrange 0x8c, 0x1, v1 + stobjbyname 0x8e, a36, a2 + ldlexvar 0x0, 0x24 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass37 + mov v1, v0 + newobjrange 0x90, 0x1, v1 + stobjbyname 0x92, a37, a2 + ldlexvar 0x0, 0x25 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass38 + mov v1, v0 + newobjrange 0x94, 0x1, v1 + stobjbyname 0x96, a38, a2 + ldlexvar 0x0, 0x26 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass39 + mov v1, v0 + newobjrange 0x98, 0x1, v1 + stobjbyname 0x9a, a39, a2 + ldlexvar 0x0, 0x27 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass40 + mov v1, v0 + newobjrange 0x9c, 0x1, v1 + stobjbyname 0x9e, a40, a2 + ldlexvar 0x0, 0x28 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass41 + mov v1, v0 + newobjrange 0xa0, 0x1, v1 + stobjbyname 0xa2, a41, a2 + ldlexvar 0x0, 0x29 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass42 + mov v1, v0 + newobjrange 0xa4, 0x1, v1 + stobjbyname 0xa6, a42, a2 + ldlexvar 0x0, 0x2a + sta v0 + throw.undefinedifholewithname TopLevelSendableClass43 + mov v1, v0 + newobjrange 0xa8, 0x1, v1 + stobjbyname 0xaa, a43, a2 + ldlexvar 0x0, 0x2b + sta v0 + throw.undefinedifholewithname TopLevelSendableClass44 + mov v1, v0 + newobjrange 0xac, 0x1, v1 + stobjbyname 0xae, a44, a2 + ldlexvar 0x0, 0x2c + sta v0 + throw.undefinedifholewithname TopLevelSendableClass45 + mov v1, v0 + newobjrange 0xb0, 0x1, v1 + stobjbyname 0xb2, a45, a2 + ldlexvar 0x0, 0x2d + sta v0 + throw.undefinedifholewithname TopLevelSendableClass46 + mov v1, v0 + newobjrange 0xb4, 0x1, v1 + stobjbyname 0xb6, a46, a2 + ldlexvar 0x0, 0x2e + sta v0 + throw.undefinedifholewithname TopLevelSendableClass47 + mov v1, v0 + newobjrange 0xb8, 0x1, v1 + stobjbyname 0xba, a47, a2 + ldlexvar 0x0, 0x2f + sta v0 + throw.undefinedifholewithname TopLevelSendableClass48 + mov v1, v0 + newobjrange 0xbc, 0x1, v1 + stobjbyname 0xbe, a48, a2 + ldlexvar 0x0, 0x30 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass49 + mov v1, v0 + newobjrange 0xc0, 0x1, v1 + stobjbyname 0xc2, a49, a2 + ldlexvar 0x0, 0x31 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass50 + mov v1, v0 + newobjrange 0xc4, 0x1, v1 + stobjbyname 0xc6, a50, a2 + ldlexvar 0x0, 0x32 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass51 + mov v1, v0 + newobjrange 0xc8, 0x1, v1 + stobjbyname 0xca, a51, a2 + ldlexvar 0x0, 0x33 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass52 + mov v1, v0 + newobjrange 0xcc, 0x1, v1 + stobjbyname 0xce, a52, a2 + ldlexvar 0x0, 0x34 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass53 + mov v1, v0 + newobjrange 0xd0, 0x1, v1 + stobjbyname 0xd2, a53, a2 + ldlexvar 0x0, 0x35 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass54 + mov v1, v0 + newobjrange 0xd4, 0x1, v1 + stobjbyname 0xd6, a54, a2 + ldlexvar 0x0, 0x36 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass55 + mov v1, v0 + newobjrange 0xd8, 0x1, v1 + stobjbyname 0xda, a55, a2 + ldlexvar 0x0, 0x37 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass56 + mov v1, v0 + newobjrange 0xdc, 0x1, v1 + stobjbyname 0xde, a56, a2 + ldlexvar 0x0, 0x38 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass57 + mov v1, v0 + newobjrange 0xe0, 0x1, v1 + stobjbyname 0xe2, a57, a2 + ldlexvar 0x0, 0x39 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass58 + mov v1, v0 + newobjrange 0xe4, 0x1, v1 + stobjbyname 0xe6, a58, a2 + ldlexvar 0x0, 0x3a + sta v0 + throw.undefinedifholewithname TopLevelSendableClass59 + mov v1, v0 + newobjrange 0xe8, 0x1, v1 + stobjbyname 0xea, a59, a2 + ldlexvar 0x0, 0x3b + sta v0 + throw.undefinedifholewithname TopLevelSendableClass60 + mov v1, v0 + newobjrange 0xec, 0x1, v1 + stobjbyname 0xee, a60, a2 + ldlexvar 0x0, 0x3c + sta v0 + throw.undefinedifholewithname TopLevelSendableClass61 + mov v1, v0 + newobjrange 0xf0, 0x1, v1 + stobjbyname 0xf2, a61, a2 + ldlexvar 0x0, 0x3d + sta v0 + throw.undefinedifholewithname TopLevelSendableClass62 + mov v1, v0 + newobjrange 0xf4, 0x1, v1 + stobjbyname 0xf6, a62, a2 + ldlexvar 0x0, 0x3e + sta v0 + throw.undefinedifholewithname TopLevelSendableClass63 + mov v1, v0 + newobjrange 0xf8, 0x1, v1 + stobjbyname 0xfa, a63, a2 + ldlexvar 0x0, 0x3f + sta v0 + throw.undefinedifholewithname TopLevelSendableClass64 + mov v1, v0 + newobjrange 0xfc, 0x1, v1 + stobjbyname 0x100, a64, a2 + ldlexvar 0x0, 0x40 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass65 + mov v1, v0 + newobjrange 0x102, 0x1, v1 + stobjbyname 0x104, a65, a2 + ldlexvar 0x0, 0x41 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass66 + mov v1, v0 + newobjrange 0x106, 0x1, v1 + stobjbyname 0x108, a66, a2 + ldlexvar 0x0, 0x42 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass67 + mov v1, v0 + newobjrange 0x10a, 0x1, v1 + stobjbyname 0x10c, a67, a2 + ldlexvar 0x0, 0x43 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass68 + mov v1, v0 + newobjrange 0x10e, 0x1, v1 + stobjbyname 0x110, a68, a2 + ldlexvar 0x0, 0x44 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass69 + mov v1, v0 + newobjrange 0x112, 0x1, v1 + stobjbyname 0x114, a69, a2 + ldlexvar 0x0, 0x45 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass70 + mov v1, v0 + newobjrange 0x116, 0x1, v1 + stobjbyname 0x118, a70, a2 + ldlexvar 0x0, 0x46 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass71 + mov v1, v0 + newobjrange 0x11a, 0x1, v1 + stobjbyname 0x11c, a71, a2 + ldlexvar 0x0, 0x47 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass72 + mov v1, v0 + newobjrange 0x11e, 0x1, v1 + stobjbyname 0x120, a72, a2 + ldlexvar 0x0, 0x48 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass73 + mov v1, v0 + newobjrange 0x122, 0x1, v1 + stobjbyname 0x124, a73, a2 + ldlexvar 0x0, 0x49 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass74 + mov v1, v0 + newobjrange 0x126, 0x1, v1 + stobjbyname 0x128, a74, a2 + ldlexvar 0x0, 0x4a + sta v0 + throw.undefinedifholewithname TopLevelSendableClass75 + mov v1, v0 + newobjrange 0x12a, 0x1, v1 + stobjbyname 0x12c, a75, a2 + ldlexvar 0x0, 0x4b + sta v0 + throw.undefinedifholewithname TopLevelSendableClass76 + mov v1, v0 + newobjrange 0x12e, 0x1, v1 + stobjbyname 0x130, a76, a2 + ldlexvar 0x0, 0x4c + sta v0 + throw.undefinedifholewithname TopLevelSendableClass77 + mov v1, v0 + newobjrange 0x132, 0x1, v1 + stobjbyname 0x134, a77, a2 + ldlexvar 0x0, 0x4d + sta v0 + throw.undefinedifholewithname TopLevelSendableClass78 + mov v1, v0 + newobjrange 0x136, 0x1, v1 + stobjbyname 0x138, a78, a2 + ldlexvar 0x0, 0x4e + sta v0 + throw.undefinedifholewithname TopLevelSendableClass79 + mov v1, v0 + newobjrange 0x13a, 0x1, v1 + stobjbyname 0x13c, a79, a2 + ldlexvar 0x0, 0x4f + sta v0 + throw.undefinedifholewithname TopLevelSendableClass80 + mov v1, v0 + newobjrange 0x13e, 0x1, v1 + stobjbyname 0x140, a80, a2 + ldlexvar 0x0, 0x50 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass81 + mov v1, v0 + newobjrange 0x142, 0x1, v1 + stobjbyname 0x144, a81, a2 + ldlexvar 0x0, 0x51 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass82 + mov v1, v0 + newobjrange 0x146, 0x1, v1 + stobjbyname 0x148, a82, a2 + ldlexvar 0x0, 0x52 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass83 + mov v1, v0 + newobjrange 0x14a, 0x1, v1 + stobjbyname 0x14c, a83, a2 + ldlexvar 0x0, 0x53 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass84 + mov v1, v0 + newobjrange 0x14e, 0x1, v1 + stobjbyname 0x150, a84, a2 + ldlexvar 0x0, 0x54 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass85 + mov v1, v0 + newobjrange 0x152, 0x1, v1 + stobjbyname 0x154, a85, a2 + ldlexvar 0x0, 0x55 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass86 + mov v1, v0 + newobjrange 0x156, 0x1, v1 + stobjbyname 0x158, a86, a2 + ldlexvar 0x0, 0x56 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass87 + mov v1, v0 + newobjrange 0x15a, 0x1, v1 + stobjbyname 0x15c, a87, a2 + ldlexvar 0x0, 0x57 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass88 + mov v1, v0 + newobjrange 0x15e, 0x1, v1 + stobjbyname 0x160, a88, a2 + ldlexvar 0x0, 0x58 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass89 + mov v1, v0 + newobjrange 0x162, 0x1, v1 + stobjbyname 0x164, a89, a2 + ldlexvar 0x0, 0x59 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass90 + mov v1, v0 + newobjrange 0x166, 0x1, v1 + stobjbyname 0x168, a90, a2 + ldlexvar 0x0, 0x5a + sta v0 + throw.undefinedifholewithname TopLevelSendableClass91 + mov v1, v0 + newobjrange 0x16a, 0x1, v1 + stobjbyname 0x16c, a91, a2 + ldlexvar 0x0, 0x5b + sta v0 + throw.undefinedifholewithname TopLevelSendableClass92 + mov v1, v0 + newobjrange 0x16e, 0x1, v1 + stobjbyname 0x170, a92, a2 + ldlexvar 0x0, 0x5c + sta v0 + throw.undefinedifholewithname TopLevelSendableClass93 + mov v1, v0 + newobjrange 0x172, 0x1, v1 + stobjbyname 0x174, a93, a2 + ldlexvar 0x0, 0x5d + sta v0 + throw.undefinedifholewithname TopLevelSendableClass94 + mov v1, v0 + newobjrange 0x176, 0x1, v1 + stobjbyname 0x178, a94, a2 + ldlexvar 0x0, 0x5e + sta v0 + throw.undefinedifholewithname TopLevelSendableClass95 + mov v1, v0 + newobjrange 0x17a, 0x1, v1 + stobjbyname 0x17c, a95, a2 + ldlexvar 0x0, 0x5f + sta v0 + throw.undefinedifholewithname TopLevelSendableClass96 + mov v1, v0 + newobjrange 0x17e, 0x1, v1 + stobjbyname 0x180, a96, a2 + ldlexvar 0x0, 0x60 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass97 + mov v1, v0 + newobjrange 0x182, 0x1, v1 + stobjbyname 0x184, a97, a2 + ldlexvar 0x0, 0x61 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass98 + mov v1, v0 + newobjrange 0x186, 0x1, v1 + stobjbyname 0x188, a98, a2 + ldlexvar 0x0, 0x62 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass99 + mov v1, v0 + newobjrange 0x18a, 0x1, v1 + stobjbyname 0x18c, a99, a2 + ldlexvar 0x0, 0x63 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass100 + mov v1, v0 + newobjrange 0x18e, 0x1, v1 + stobjbyname 0x190, a100, a2 + ldlexvar 0x0, 0x64 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass101 + mov v1, v0 + newobjrange 0x192, 0x1, v1 + stobjbyname 0x194, a101, a2 + ldlexvar 0x0, 0x65 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass102 + mov v1, v0 + newobjrange 0x196, 0x1, v1 + stobjbyname 0x198, a102, a2 + ldlexvar 0x0, 0x66 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass103 + mov v1, v0 + newobjrange 0x19a, 0x1, v1 + stobjbyname 0x19c, a103, a2 + ldlexvar 0x0, 0x67 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass104 + mov v1, v0 + newobjrange 0x19e, 0x1, v1 + stobjbyname 0x1a0, a104, a2 + ldlexvar 0x0, 0x68 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass105 + mov v1, v0 + newobjrange 0x1a2, 0x1, v1 + stobjbyname 0x1a4, a105, a2 + ldlexvar 0x0, 0x69 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass106 + mov v1, v0 + newobjrange 0x1a6, 0x1, v1 + stobjbyname 0x1a8, a106, a2 + ldlexvar 0x0, 0x6a + sta v0 + throw.undefinedifholewithname TopLevelSendableClass107 + mov v1, v0 + newobjrange 0x1aa, 0x1, v1 + stobjbyname 0x1ac, a107, a2 + ldlexvar 0x0, 0x6b + sta v0 + throw.undefinedifholewithname TopLevelSendableClass108 + mov v1, v0 + newobjrange 0x1ae, 0x1, v1 + stobjbyname 0x1b0, a108, a2 + ldlexvar 0x0, 0x6c + sta v0 + throw.undefinedifholewithname TopLevelSendableClass109 + mov v1, v0 + newobjrange 0x1b2, 0x1, v1 + stobjbyname 0x1b4, a109, a2 + ldlexvar 0x0, 0x6d + sta v0 + throw.undefinedifholewithname TopLevelSendableClass110 + mov v1, v0 + newobjrange 0x1b6, 0x1, v1 + stobjbyname 0x1b8, a110, a2 + ldlexvar 0x0, 0x6e + sta v0 + throw.undefinedifholewithname TopLevelSendableClass111 + mov v1, v0 + newobjrange 0x1ba, 0x1, v1 + stobjbyname 0x1bc, a111, a2 + ldlexvar 0x0, 0x6f + sta v0 + throw.undefinedifholewithname TopLevelSendableClass112 + mov v1, v0 + newobjrange 0x1be, 0x1, v1 + stobjbyname 0x1c0, a112, a2 + ldlexvar 0x0, 0x70 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass113 + mov v1, v0 + newobjrange 0x1c2, 0x1, v1 + stobjbyname 0x1c4, a113, a2 + ldlexvar 0x0, 0x71 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass114 + mov v1, v0 + newobjrange 0x1c6, 0x1, v1 + stobjbyname 0x1c8, a114, a2 + ldlexvar 0x0, 0x72 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass115 + mov v1, v0 + newobjrange 0x1ca, 0x1, v1 + stobjbyname 0x1cc, a115, a2 + ldlexvar 0x0, 0x73 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass116 + mov v1, v0 + newobjrange 0x1ce, 0x1, v1 + stobjbyname 0x1d0, a116, a2 + ldlexvar 0x0, 0x74 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass117 + mov v1, v0 + newobjrange 0x1d2, 0x1, v1 + stobjbyname 0x1d4, a117, a2 + ldlexvar 0x0, 0x75 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass118 + mov v1, v0 + newobjrange 0x1d6, 0x1, v1 + stobjbyname 0x1d8, a118, a2 + ldlexvar 0x0, 0x76 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass119 + mov v1, v0 + newobjrange 0x1da, 0x1, v1 + stobjbyname 0x1dc, a119, a2 + ldlexvar 0x0, 0x77 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass120 + mov v1, v0 + newobjrange 0x1de, 0x1, v1 + stobjbyname 0x1e0, a120, a2 + ldlexvar 0x0, 0x78 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass121 + mov v1, v0 + newobjrange 0x1e2, 0x1, v1 + stobjbyname 0x1e4, a121, a2 + ldlexvar 0x0, 0x79 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass122 + mov v1, v0 + newobjrange 0x1e6, 0x1, v1 + stobjbyname 0x1e8, a122, a2 + ldlexvar 0x0, 0x7a + sta v0 + throw.undefinedifholewithname TopLevelSendableClass123 + mov v1, v0 + newobjrange 0x1ea, 0x1, v1 + stobjbyname 0x1ec, a123, a2 + ldlexvar 0x0, 0x7b + sta v0 + throw.undefinedifholewithname TopLevelSendableClass124 + mov v1, v0 + newobjrange 0x1ee, 0x1, v1 + stobjbyname 0x1f0, a124, a2 + ldlexvar 0x0, 0x7c + sta v0 + throw.undefinedifholewithname TopLevelSendableClass125 + mov v1, v0 + newobjrange 0x1f2, 0x1, v1 + stobjbyname 0x1f4, a125, a2 + ldlexvar 0x0, 0x7d + sta v0 + throw.undefinedifholewithname TopLevelSendableClass126 + mov v1, v0 + newobjrange 0x1f6, 0x1, v1 + stobjbyname 0x1f8, a126, a2 + ldlexvar 0x0, 0x7e + sta v0 + throw.undefinedifholewithname TopLevelSendableClass127 + mov v1, v0 + newobjrange 0x1fa, 0x1, v1 + stobjbyname 0x1fc, a127, a2 + ldlexvar 0x0, 0x7f + sta v0 + throw.undefinedifholewithname TopLevelSendableClass128 + mov v1, v0 + newobjrange 0x1fe, 0x1, v1 + stobjbyname 0x200, a128, a2 + wide.ldlexvar 0x0, 0x80 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass129 + mov v1, v0 + newobjrange 0x202, 0x1, v1 + stobjbyname 0x204, a129, a2 + wide.ldlexvar 0x0, 0x81 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass130 + mov v1, v0 + newobjrange 0x206, 0x1, v1 + stobjbyname 0x208, a130, a2 + wide.ldlexvar 0x0, 0x82 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass131 + mov v1, v0 + newobjrange 0x20a, 0x1, v1 + stobjbyname 0x20c, a131, a2 + wide.ldlexvar 0x0, 0x83 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass132 + mov v1, v0 + newobjrange 0x20e, 0x1, v1 + stobjbyname 0x210, a132, a2 + wide.ldlexvar 0x0, 0x84 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass133 + mov v1, v0 + newobjrange 0x212, 0x1, v1 + stobjbyname 0x214, a133, a2 + wide.ldlexvar 0x0, 0x85 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass134 + mov v1, v0 + newobjrange 0x216, 0x1, v1 + stobjbyname 0x218, a134, a2 + wide.ldlexvar 0x0, 0x86 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass135 + mov v1, v0 + newobjrange 0x21a, 0x1, v1 + stobjbyname 0x21c, a135, a2 + wide.ldlexvar 0x0, 0x87 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass136 + mov v1, v0 + newobjrange 0x21e, 0x1, v1 + stobjbyname 0x220, a136, a2 + wide.ldlexvar 0x0, 0x88 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass137 + mov v1, v0 + newobjrange 0x222, 0x1, v1 + stobjbyname 0x224, a137, a2 + wide.ldlexvar 0x0, 0x89 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass138 + mov v1, v0 + newobjrange 0x226, 0x1, v1 + stobjbyname 0x228, a138, a2 + wide.ldlexvar 0x0, 0x8a + sta v0 + throw.undefinedifholewithname TopLevelSendableClass139 + mov v1, v0 + newobjrange 0x22a, 0x1, v1 + stobjbyname 0x22c, a139, a2 + wide.ldlexvar 0x0, 0x8b + sta v0 + throw.undefinedifholewithname TopLevelSendableClass140 + mov v1, v0 + newobjrange 0x22e, 0x1, v1 + stobjbyname 0x230, a140, a2 + wide.ldlexvar 0x0, 0x8c + sta v0 + throw.undefinedifholewithname TopLevelSendableClass141 + mov v1, v0 + newobjrange 0x232, 0x1, v1 + stobjbyname 0x234, a141, a2 + wide.ldlexvar 0x0, 0x8d + sta v0 + throw.undefinedifholewithname TopLevelSendableClass142 + mov v1, v0 + newobjrange 0x236, 0x1, v1 + stobjbyname 0x238, a142, a2 + wide.ldlexvar 0x0, 0x8e + sta v0 + throw.undefinedifholewithname TopLevelSendableClass143 + mov v1, v0 + newobjrange 0x23a, 0x1, v1 + stobjbyname 0x23c, a143, a2 + wide.ldlexvar 0x0, 0x8f + sta v0 + throw.undefinedifholewithname TopLevelSendableClass144 + mov v1, v0 + newobjrange 0x23e, 0x1, v1 + stobjbyname 0x240, a144, a2 + wide.ldlexvar 0x0, 0x90 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass145 + mov v1, v0 + newobjrange 0x242, 0x1, v1 + stobjbyname 0x244, a145, a2 + wide.ldlexvar 0x0, 0x91 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass146 + mov v1, v0 + newobjrange 0x246, 0x1, v1 + stobjbyname 0x248, a146, a2 + wide.ldlexvar 0x0, 0x92 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass147 + mov v1, v0 + newobjrange 0x24a, 0x1, v1 + stobjbyname 0x24c, a147, a2 + wide.ldlexvar 0x0, 0x93 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass148 + mov v1, v0 + newobjrange 0x24e, 0x1, v1 + stobjbyname 0x250, a148, a2 + wide.ldlexvar 0x0, 0x94 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass149 + mov v1, v0 + newobjrange 0x252, 0x1, v1 + stobjbyname 0x254, a149, a2 + wide.ldlexvar 0x0, 0x95 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass150 + mov v1, v0 + newobjrange 0x256, 0x1, v1 + stobjbyname 0x258, a150, a2 + wide.ldlexvar 0x0, 0x96 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass151 + mov v1, v0 + newobjrange 0x25a, 0x1, v1 + stobjbyname 0x25c, a151, a2 + wide.ldlexvar 0x0, 0x97 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass152 + mov v1, v0 + newobjrange 0x25e, 0x1, v1 + stobjbyname 0x260, a152, a2 + wide.ldlexvar 0x0, 0x98 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass153 + mov v1, v0 + newobjrange 0x262, 0x1, v1 + stobjbyname 0x264, a153, a2 + wide.ldlexvar 0x0, 0x99 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass154 + mov v1, v0 + newobjrange 0x266, 0x1, v1 + stobjbyname 0x268, a154, a2 + wide.ldlexvar 0x0, 0x9a + sta v0 + throw.undefinedifholewithname TopLevelSendableClass155 + mov v1, v0 + newobjrange 0x26a, 0x1, v1 + stobjbyname 0x26c, a155, a2 + wide.ldlexvar 0x0, 0x9b + sta v0 + throw.undefinedifholewithname TopLevelSendableClass156 + mov v1, v0 + newobjrange 0x26e, 0x1, v1 + stobjbyname 0x270, a156, a2 + wide.ldlexvar 0x0, 0x9c + sta v0 + throw.undefinedifholewithname TopLevelSendableClass157 + mov v1, v0 + newobjrange 0x272, 0x1, v1 + stobjbyname 0x274, a157, a2 + wide.ldlexvar 0x0, 0x9d + sta v0 + throw.undefinedifholewithname TopLevelSendableClass158 + mov v1, v0 + newobjrange 0x276, 0x1, v1 + stobjbyname 0x278, a158, a2 + wide.ldlexvar 0x0, 0x9e + sta v0 + throw.undefinedifholewithname TopLevelSendableClass159 + mov v1, v0 + newobjrange 0x27a, 0x1, v1 + stobjbyname 0x27c, a159, a2 + wide.ldlexvar 0x0, 0x9f + sta v0 + throw.undefinedifholewithname TopLevelSendableClass160 + mov v1, v0 + newobjrange 0x27e, 0x1, v1 + stobjbyname 0x280, a160, a2 + wide.ldlexvar 0x0, 0xa0 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass161 + mov v1, v0 + newobjrange 0x282, 0x1, v1 + stobjbyname 0x284, a161, a2 + wide.ldlexvar 0x0, 0xa1 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass162 + mov v1, v0 + newobjrange 0x286, 0x1, v1 + stobjbyname 0x288, a162, a2 + wide.ldlexvar 0x0, 0xa2 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass163 + mov v1, v0 + newobjrange 0x28a, 0x1, v1 + stobjbyname 0x28c, a163, a2 + wide.ldlexvar 0x0, 0xa3 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass164 + mov v1, v0 + newobjrange 0x28e, 0x1, v1 + stobjbyname 0x290, a164, a2 + wide.ldlexvar 0x0, 0xa4 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass165 + mov v1, v0 + newobjrange 0x292, 0x1, v1 + stobjbyname 0x294, a165, a2 + wide.ldlexvar 0x0, 0xa5 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass166 + mov v1, v0 + newobjrange 0x296, 0x1, v1 + stobjbyname 0x298, a166, a2 + wide.ldlexvar 0x0, 0xa6 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass167 + mov v1, v0 + newobjrange 0x29a, 0x1, v1 + stobjbyname 0x29c, a167, a2 + wide.ldlexvar 0x0, 0xa7 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass168 + mov v1, v0 + newobjrange 0x29e, 0x1, v1 + stobjbyname 0x2a0, a168, a2 + wide.ldlexvar 0x0, 0xa8 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass169 + mov v1, v0 + newobjrange 0x2a2, 0x1, v1 + stobjbyname 0x2a4, a169, a2 + wide.ldlexvar 0x0, 0xa9 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass170 + mov v1, v0 + newobjrange 0x2a6, 0x1, v1 + stobjbyname 0x2a8, a170, a2 + wide.ldlexvar 0x0, 0xaa + sta v0 + throw.undefinedifholewithname TopLevelSendableClass171 + mov v1, v0 + newobjrange 0x2aa, 0x1, v1 + stobjbyname 0x2ac, a171, a2 + wide.ldlexvar 0x0, 0xab + sta v0 + throw.undefinedifholewithname TopLevelSendableClass172 + mov v1, v0 + newobjrange 0x2ae, 0x1, v1 + stobjbyname 0x2b0, a172, a2 + wide.ldlexvar 0x0, 0xac + sta v0 + throw.undefinedifholewithname TopLevelSendableClass173 + mov v1, v0 + newobjrange 0x2b2, 0x1, v1 + stobjbyname 0x2b4, a173, a2 + wide.ldlexvar 0x0, 0xad + sta v0 + throw.undefinedifholewithname TopLevelSendableClass174 + mov v1, v0 + newobjrange 0x2b6, 0x1, v1 + stobjbyname 0x2b8, a174, a2 + wide.ldlexvar 0x0, 0xae + sta v0 + throw.undefinedifholewithname TopLevelSendableClass175 + mov v1, v0 + newobjrange 0x2ba, 0x1, v1 + stobjbyname 0x2bc, a175, a2 + wide.ldlexvar 0x0, 0xaf + sta v0 + throw.undefinedifholewithname TopLevelSendableClass176 + mov v1, v0 + newobjrange 0x2be, 0x1, v1 + stobjbyname 0x2c0, a176, a2 + wide.ldlexvar 0x0, 0xb0 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass177 + mov v1, v0 + newobjrange 0x2c2, 0x1, v1 + stobjbyname 0x2c4, a177, a2 + wide.ldlexvar 0x0, 0xb1 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass178 + mov v1, v0 + newobjrange 0x2c6, 0x1, v1 + stobjbyname 0x2c8, a178, a2 + wide.ldlexvar 0x0, 0xb2 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass179 + mov v1, v0 + newobjrange 0x2ca, 0x1, v1 + stobjbyname 0x2cc, a179, a2 + wide.ldlexvar 0x0, 0xb3 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass180 + mov v1, v0 + newobjrange 0x2ce, 0x1, v1 + stobjbyname 0x2d0, a180, a2 + wide.ldlexvar 0x0, 0xb4 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass181 + mov v1, v0 + newobjrange 0x2d2, 0x1, v1 + stobjbyname 0x2d4, a181, a2 + wide.ldlexvar 0x0, 0xb5 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass182 + mov v1, v0 + newobjrange 0x2d6, 0x1, v1 + stobjbyname 0x2d8, a182, a2 + wide.ldlexvar 0x0, 0xb6 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass183 + mov v1, v0 + newobjrange 0x2da, 0x1, v1 + stobjbyname 0x2dc, a183, a2 + wide.ldlexvar 0x0, 0xb7 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass184 + mov v1, v0 + newobjrange 0x2de, 0x1, v1 + stobjbyname 0x2e0, a184, a2 + wide.ldlexvar 0x0, 0xb8 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass185 + mov v1, v0 + newobjrange 0x2e2, 0x1, v1 + stobjbyname 0x2e4, a185, a2 + wide.ldlexvar 0x0, 0xb9 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass186 + mov v1, v0 + newobjrange 0x2e6, 0x1, v1 + stobjbyname 0x2e8, a186, a2 + wide.ldlexvar 0x0, 0xba + sta v0 + throw.undefinedifholewithname TopLevelSendableClass187 + mov v1, v0 + newobjrange 0x2ea, 0x1, v1 + stobjbyname 0x2ec, a187, a2 + wide.ldlexvar 0x0, 0xbb + sta v0 + throw.undefinedifholewithname TopLevelSendableClass188 + mov v1, v0 + newobjrange 0x2ee, 0x1, v1 + stobjbyname 0x2f0, a188, a2 + wide.ldlexvar 0x0, 0xbc + sta v0 + throw.undefinedifholewithname TopLevelSendableClass189 + mov v1, v0 + newobjrange 0x2f2, 0x1, v1 + stobjbyname 0x2f4, a189, a2 + wide.ldlexvar 0x0, 0xbd + sta v0 + throw.undefinedifholewithname TopLevelSendableClass190 + mov v1, v0 + newobjrange 0x2f6, 0x1, v1 + stobjbyname 0x2f8, a190, a2 + wide.ldlexvar 0x0, 0xbe + sta v0 + throw.undefinedifholewithname TopLevelSendableClass191 + mov v1, v0 + newobjrange 0x2fa, 0x1, v1 + stobjbyname 0x2fc, a191, a2 + wide.ldlexvar 0x0, 0xbf + sta v0 + throw.undefinedifholewithname TopLevelSendableClass192 + mov v1, v0 + newobjrange 0x2fe, 0x1, v1 + stobjbyname 0x300, a192, a2 + wide.ldlexvar 0x0, 0xc0 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass193 + mov v1, v0 + newobjrange 0x302, 0x1, v1 + stobjbyname 0x304, a193, a2 + wide.ldlexvar 0x0, 0xc1 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass194 + mov v1, v0 + newobjrange 0x306, 0x1, v1 + stobjbyname 0x308, a194, a2 + wide.ldlexvar 0x0, 0xc2 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass195 + mov v1, v0 + newobjrange 0x30a, 0x1, v1 + stobjbyname 0x30c, a195, a2 + wide.ldlexvar 0x0, 0xc3 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass196 + mov v1, v0 + newobjrange 0x30e, 0x1, v1 + stobjbyname 0x310, a196, a2 + wide.ldlexvar 0x0, 0xc4 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass197 + mov v1, v0 + newobjrange 0x312, 0x1, v1 + stobjbyname 0x314, a197, a2 + wide.ldlexvar 0x0, 0xc5 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass198 + mov v1, v0 + newobjrange 0x316, 0x1, v1 + stobjbyname 0x318, a198, a2 + wide.ldlexvar 0x0, 0xc6 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass199 + mov v1, v0 + newobjrange 0x31a, 0x1, v1 + stobjbyname 0x31c, a199, a2 + wide.ldlexvar 0x0, 0xc7 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass200 + mov v1, v0 + newobjrange 0x31e, 0x1, v1 + stobjbyname 0x320, a200, a2 + wide.ldlexvar 0x0, 0xc8 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass201 + mov v1, v0 + newobjrange 0x322, 0x1, v1 + stobjbyname 0x324, a201, a2 + wide.ldlexvar 0x0, 0xc9 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass202 + mov v1, v0 + newobjrange 0x326, 0x1, v1 + stobjbyname 0x328, a202, a2 + wide.ldlexvar 0x0, 0xca + sta v0 + throw.undefinedifholewithname TopLevelSendableClass203 + mov v1, v0 + newobjrange 0x32a, 0x1, v1 + stobjbyname 0x32c, a203, a2 + wide.ldlexvar 0x0, 0xcb + sta v0 + throw.undefinedifholewithname TopLevelSendableClass204 + mov v1, v0 + newobjrange 0x32e, 0x1, v1 + stobjbyname 0x330, a204, a2 + wide.ldlexvar 0x0, 0xcc + sta v0 + throw.undefinedifholewithname TopLevelSendableClass205 + mov v1, v0 + newobjrange 0x332, 0x1, v1 + stobjbyname 0x334, a205, a2 + wide.ldlexvar 0x0, 0xcd + sta v0 + throw.undefinedifholewithname TopLevelSendableClass206 + mov v1, v0 + newobjrange 0x336, 0x1, v1 + stobjbyname 0x338, a206, a2 + wide.ldlexvar 0x0, 0xce + sta v0 + throw.undefinedifholewithname TopLevelSendableClass207 + mov v1, v0 + newobjrange 0x33a, 0x1, v1 + stobjbyname 0x33c, a207, a2 + wide.ldlexvar 0x0, 0xcf + sta v0 + throw.undefinedifholewithname TopLevelSendableClass208 + mov v1, v0 + newobjrange 0x33e, 0x1, v1 + stobjbyname 0x340, a208, a2 + wide.ldlexvar 0x0, 0xd0 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass209 + mov v1, v0 + newobjrange 0x342, 0x1, v1 + stobjbyname 0x344, a209, a2 + wide.ldlexvar 0x0, 0xd1 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass210 + mov v1, v0 + newobjrange 0x346, 0x1, v1 + stobjbyname 0x348, a210, a2 + wide.ldlexvar 0x0, 0xd2 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass211 + mov v1, v0 + newobjrange 0x34a, 0x1, v1 + stobjbyname 0x34c, a211, a2 + wide.ldlexvar 0x0, 0xd3 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass212 + mov v1, v0 + newobjrange 0x34e, 0x1, v1 + stobjbyname 0x350, a212, a2 + wide.ldlexvar 0x0, 0xd4 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass213 + mov v1, v0 + newobjrange 0x352, 0x1, v1 + stobjbyname 0x354, a213, a2 + wide.ldlexvar 0x0, 0xd5 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass214 + mov v1, v0 + newobjrange 0x356, 0x1, v1 + stobjbyname 0x358, a214, a2 + wide.ldlexvar 0x0, 0xd6 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass215 + mov v1, v0 + newobjrange 0x35a, 0x1, v1 + stobjbyname 0x35c, a215, a2 + wide.ldlexvar 0x0, 0xd7 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass216 + mov v1, v0 + newobjrange 0x35e, 0x1, v1 + stobjbyname 0x360, a216, a2 + wide.ldlexvar 0x0, 0xd8 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass217 + mov v1, v0 + newobjrange 0x362, 0x1, v1 + stobjbyname 0x364, a217, a2 + wide.ldlexvar 0x0, 0xd9 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass218 + mov v1, v0 + newobjrange 0x366, 0x1, v1 + stobjbyname 0x368, a218, a2 + wide.ldlexvar 0x0, 0xda + sta v0 + throw.undefinedifholewithname TopLevelSendableClass219 + mov v1, v0 + newobjrange 0x36a, 0x1, v1 + stobjbyname 0x36c, a219, a2 + wide.ldlexvar 0x0, 0xdb + sta v0 + throw.undefinedifholewithname TopLevelSendableClass220 + mov v1, v0 + newobjrange 0x36e, 0x1, v1 + stobjbyname 0x370, a220, a2 + wide.ldlexvar 0x0, 0xdc + sta v0 + throw.undefinedifholewithname TopLevelSendableClass221 + mov v1, v0 + newobjrange 0x372, 0x1, v1 + stobjbyname 0x374, a221, a2 + wide.ldlexvar 0x0, 0xdd + sta v0 + throw.undefinedifholewithname TopLevelSendableClass222 + mov v1, v0 + newobjrange 0x376, 0x1, v1 + stobjbyname 0x378, a222, a2 + wide.ldlexvar 0x0, 0xde + sta v0 + throw.undefinedifholewithname TopLevelSendableClass223 + mov v1, v0 + newobjrange 0x37a, 0x1, v1 + stobjbyname 0x37c, a223, a2 + wide.ldlexvar 0x0, 0xdf + sta v0 + throw.undefinedifholewithname TopLevelSendableClass224 + mov v1, v0 + newobjrange 0x37e, 0x1, v1 + stobjbyname 0x380, a224, a2 + wide.ldlexvar 0x0, 0xe0 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass225 + mov v1, v0 + newobjrange 0x382, 0x1, v1 + stobjbyname 0x384, a225, a2 + wide.ldlexvar 0x0, 0xe1 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass226 + mov v1, v0 + newobjrange 0x386, 0x1, v1 + stobjbyname 0x388, a226, a2 + wide.ldlexvar 0x0, 0xe2 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass227 + mov v1, v0 + newobjrange 0x38a, 0x1, v1 + stobjbyname 0x38c, a227, a2 + wide.ldlexvar 0x0, 0xe3 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass228 + mov v1, v0 + newobjrange 0x38e, 0x1, v1 + stobjbyname 0x390, a228, a2 + wide.ldlexvar 0x0, 0xe4 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass229 + mov v1, v0 + newobjrange 0x392, 0x1, v1 + stobjbyname 0x394, a229, a2 + wide.ldlexvar 0x0, 0xe5 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass230 + mov v1, v0 + newobjrange 0x396, 0x1, v1 + stobjbyname 0x398, a230, a2 + wide.ldlexvar 0x0, 0xe6 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass231 + mov v1, v0 + newobjrange 0x39a, 0x1, v1 + stobjbyname 0x39c, a231, a2 + wide.ldlexvar 0x0, 0xe7 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass232 + mov v1, v0 + newobjrange 0x39e, 0x1, v1 + stobjbyname 0x3a0, a232, a2 + wide.ldlexvar 0x0, 0xe8 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass233 + mov v1, v0 + newobjrange 0x3a2, 0x1, v1 + stobjbyname 0x3a4, a233, a2 + wide.ldlexvar 0x0, 0xe9 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass234 + mov v1, v0 + newobjrange 0x3a6, 0x1, v1 + stobjbyname 0x3a8, a234, a2 + wide.ldlexvar 0x0, 0xea + sta v0 + throw.undefinedifholewithname TopLevelSendableClass235 + mov v1, v0 + newobjrange 0x3aa, 0x1, v1 + stobjbyname 0x3ac, a235, a2 + wide.ldlexvar 0x0, 0xeb + sta v0 + throw.undefinedifholewithname TopLevelSendableClass236 + mov v1, v0 + newobjrange 0x3ae, 0x1, v1 + stobjbyname 0x3b0, a236, a2 + wide.ldlexvar 0x0, 0xec + sta v0 + throw.undefinedifholewithname TopLevelSendableClass237 + mov v1, v0 + newobjrange 0x3b2, 0x1, v1 + stobjbyname 0x3b4, a237, a2 + wide.ldlexvar 0x0, 0xed + sta v0 + throw.undefinedifholewithname TopLevelSendableClass238 + mov v1, v0 + newobjrange 0x3b6, 0x1, v1 + stobjbyname 0x3b8, a238, a2 + wide.ldlexvar 0x0, 0xee + sta v0 + throw.undefinedifholewithname TopLevelSendableClass239 + mov v1, v0 + newobjrange 0x3ba, 0x1, v1 + stobjbyname 0x3bc, a239, a2 + wide.ldlexvar 0x0, 0xef + sta v0 + throw.undefinedifholewithname TopLevelSendableClass240 + mov v1, v0 + newobjrange 0x3be, 0x1, v1 + stobjbyname 0x3c0, a240, a2 + wide.ldlexvar 0x0, 0xf0 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass241 + mov v1, v0 + newobjrange 0x3c2, 0x1, v1 + stobjbyname 0x3c4, a241, a2 + wide.ldlexvar 0x0, 0xf1 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass242 + mov v1, v0 + newobjrange 0x3c6, 0x1, v1 + stobjbyname 0x3c8, a242, a2 + wide.ldlexvar 0x0, 0xf2 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass243 + mov v1, v0 + newobjrange 0x3ca, 0x1, v1 + stobjbyname 0x3cc, a243, a2 + wide.ldlexvar 0x0, 0xf3 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass244 + mov v1, v0 + newobjrange 0x3ce, 0x1, v1 + stobjbyname 0x3d0, a244, a2 + wide.ldlexvar 0x0, 0xf4 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass245 + mov v1, v0 + newobjrange 0x3d2, 0x1, v1 + stobjbyname 0x3d4, a245, a2 + wide.ldlexvar 0x0, 0xf5 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass246 + mov v1, v0 + newobjrange 0x3d6, 0x1, v1 + stobjbyname 0x3d8, a246, a2 + wide.ldlexvar 0x0, 0xf6 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass247 + mov v1, v0 + newobjrange 0x3da, 0x1, v1 + stobjbyname 0x3dc, a247, a2 + wide.ldlexvar 0x0, 0xf7 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass248 + mov v1, v0 + newobjrange 0x3de, 0x1, v1 + stobjbyname 0x3e0, a248, a2 + wide.ldlexvar 0x0, 0xf8 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass249 + mov v1, v0 + newobjrange 0x3e2, 0x1, v1 + stobjbyname 0x3e4, a249, a2 + wide.ldlexvar 0x0, 0xf9 + sta v0 + throw.undefinedifholewithname TopLevelSendableClass250 + mov v1, v0 + newobjrange 0x3e6, 0x1, v1 + stobjbyname 0x3e8, a250, a2 + wide.ldlexvar 0x0, 0xfa + sta v0 + throw.undefinedifholewithname TopLevelSendableClass251 + mov v1, v0 + newobjrange 0x3ea, 0x1, v1 + stobjbyname 0x3ec, a251, a2 + wide.ldlexvar 0x0, 0xfb + sta v0 + throw.undefinedifholewithname TopLevelSendableClass252 + mov v1, v0 + newobjrange 0x3ee, 0x1, v1 + stobjbyname 0x3f0, a252, a2 + wide.ldlexvar 0x0, 0xfc + sta v0 + throw.undefinedifholewithname TopLevelSendableClass253 + mov v1, v0 + newobjrange 0x3f2, 0x1, v1 + stobjbyname 0x3f4, a253, a2 + wide.ldlexvar 0x0, 0xfd + sta v0 + throw.undefinedifholewithname TopLevelSendableClass254 + mov v1, v0 + newobjrange 0x3f6, 0x1, v1 + stobjbyname 0x3f8, a254, a2 + wide.ldlexvar 0x0, 0xfe + sta v0 + throw.undefinedifholewithname TopLevelSendableClass255 + mov v1, v0 + newobjrange 0x3fa, 0x1, v1 + stobjbyname 0x3fc, a255, a2 + lda a2 + ldobjbyname 0x3fe, a1 + ldobjbyname 0x400, o + stobjbyname 0x402, u, a2 + lda.str wide_sendable_test + stobjbyname 0x404, v, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass1(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass10(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass100(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass101(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass102(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass103(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass104(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass105(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass106(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass107(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass108(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass109(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass11(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass110(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass111(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass112(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass113(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass114(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass115(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass116(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass117(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass118(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass119(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass12(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass120(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass121(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass122(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass123(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass124(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass125(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass126(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass127(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass128(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass129(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass13(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass130(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass131(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass132(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass133(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass134(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass135(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass136(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass137(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass138(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass139(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass14(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass140(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass141(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass142(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass143(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass144(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass145(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass146(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass147(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass148(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass149(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass15(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass150(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass151(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass152(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass153(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass154(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass155(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass156(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass157(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass158(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass159(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass16(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass160(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass161(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass162(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass163(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass164(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass165(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass166(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass167(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass168(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass169(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass17(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass170(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass171(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass172(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass173(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass174(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass175(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass176(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass177(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass178(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass179(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass18(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass180(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass181(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass182(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass183(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass184(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass185(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass186(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass187(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass188(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass189(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass19(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass190(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass191(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass192(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass193(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass194(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass195(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass196(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass197(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass198(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass199(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass2(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass20(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass200(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass201(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass202(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass203(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass204(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass205(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass206(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass207(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass208(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass209(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass21(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass210(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass211(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass212(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass213(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass214(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass215(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass216(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass217(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass218(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass219(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass22(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass220(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass221(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass222(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass223(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass224(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass225(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass226(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass227(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass228(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass229(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass23(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass230(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass231(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass232(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass233(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass234(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass235(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass236(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass237(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass238(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass239(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass24(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass240(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass241(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass242(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass243(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass244(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass245(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass246(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass247(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass248(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass249(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass25(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass250(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass251(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass252(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass253(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass254(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass255(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass26(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass27(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass28(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass29(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass3(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass30(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass31(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass32(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass33(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass34(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass35(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass36(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass37(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass38(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass39(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass4(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass40(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass41(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass42(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass43(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass44(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass45(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass46(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass47(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass48(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass49(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass5(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass50(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass51(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass52(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass53(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass54(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass55(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass56(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass57(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass58(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass59(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass6(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass60(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass61(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass62(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass63(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass64(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass65(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass66(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass67(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass68(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass69(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass7(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass70(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass71(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass72(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass73(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass74(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass75(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass76(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass77(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass78(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass79(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass8(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass80(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass81(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass82(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass83(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass84(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass85(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass86(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass87(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass88(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass89(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass9(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass90(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass91(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass92(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass93(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass94(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass95(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass96(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass97(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass98(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x2 +.language ECMAScript +.function any .TopLevelSendableClass99(any a0, any a1, any a2) { +label_1: +label_0: + ldai 0x1 + stobjbyname 0x0, o, a2 + lda a2 + return +label_2: +} + +slotNum = 0x108 +.language ECMAScript +.function any .func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + wide.newlexenv 0xff + ldhole + sta v0 + callruntime.definesendableclass 0x2, .TopLevelSendableClass1, _2, 0x0, v0 + stlexvar 0x0, 0x0 + ldhole + sta v0 + callruntime.definesendableclass 0x3, .TopLevelSendableClass2, _4, 0x0, v0 + stlexvar 0x0, 0x1 + ldhole + sta v0 + callruntime.definesendableclass 0x4, .TopLevelSendableClass3, _6, 0x0, v0 + stlexvar 0x0, 0x2 + ldhole + sta v0 + callruntime.definesendableclass 0x5, .TopLevelSendableClass4, _8, 0x0, v0 + stlexvar 0x0, 0x3 + ldhole + sta v0 + callruntime.definesendableclass 0x6, .TopLevelSendableClass5, _10, 0x0, v0 + stlexvar 0x0, 0x4 + ldhole + sta v0 + callruntime.definesendableclass 0x7, .TopLevelSendableClass6, _12, 0x0, v0 + stlexvar 0x0, 0x5 + ldhole + sta v0 + callruntime.definesendableclass 0x8, .TopLevelSendableClass7, _14, 0x0, v0 + stlexvar 0x0, 0x6 + ldhole + sta v0 + callruntime.definesendableclass 0x9, .TopLevelSendableClass8, _16, 0x0, v0 + stlexvar 0x0, 0x7 + ldhole + sta v0 + callruntime.definesendableclass 0xa, .TopLevelSendableClass9, _18, 0x0, v0 + stlexvar 0x0, 0x8 + ldhole + sta v0 + callruntime.definesendableclass 0xb, .TopLevelSendableClass10, _20, 0x0, v0 + stlexvar 0x0, 0x9 + ldhole + sta v0 + callruntime.definesendableclass 0xc, .TopLevelSendableClass11, _22, 0x0, v0 + stlexvar 0x0, 0xa + ldhole + sta v0 + callruntime.definesendableclass 0xd, .TopLevelSendableClass12, _24, 0x0, v0 + stlexvar 0x0, 0xb + ldhole + sta v0 + callruntime.definesendableclass 0xe, .TopLevelSendableClass13, _26, 0x0, v0 + stlexvar 0x0, 0xc + ldhole + sta v0 + callruntime.definesendableclass 0xf, .TopLevelSendableClass14, _28, 0x0, v0 + stlexvar 0x0, 0xd + ldhole + sta v0 + callruntime.definesendableclass 0x10, .TopLevelSendableClass15, _30, 0x0, v0 + stlexvar 0x0, 0xe + ldhole + sta v0 + callruntime.definesendableclass 0x11, .TopLevelSendableClass16, _32, 0x0, v0 + stlexvar 0x0, 0xf + ldhole + sta v0 + callruntime.definesendableclass 0x12, .TopLevelSendableClass17, _34, 0x0, v0 + stlexvar 0x0, 0x10 + ldhole + sta v0 + callruntime.definesendableclass 0x13, .TopLevelSendableClass18, _36, 0x0, v0 + stlexvar 0x0, 0x11 + ldhole + sta v0 + callruntime.definesendableclass 0x14, .TopLevelSendableClass19, _38, 0x0, v0 + stlexvar 0x0, 0x12 + ldhole + sta v0 + callruntime.definesendableclass 0x15, .TopLevelSendableClass20, _40, 0x0, v0 + stlexvar 0x0, 0x13 + ldhole + sta v0 + callruntime.definesendableclass 0x16, .TopLevelSendableClass21, _42, 0x0, v0 + stlexvar 0x0, 0x14 + ldhole + sta v0 + callruntime.definesendableclass 0x17, .TopLevelSendableClass22, _44, 0x0, v0 + stlexvar 0x0, 0x15 + ldhole + sta v0 + callruntime.definesendableclass 0x18, .TopLevelSendableClass23, _46, 0x0, v0 + stlexvar 0x0, 0x16 + ldhole + sta v0 + callruntime.definesendableclass 0x19, .TopLevelSendableClass24, _48, 0x0, v0 + stlexvar 0x0, 0x17 + ldhole + sta v0 + callruntime.definesendableclass 0x1a, .TopLevelSendableClass25, _50, 0x0, v0 + stlexvar 0x0, 0x18 + ldhole + sta v0 + callruntime.definesendableclass 0x1b, .TopLevelSendableClass26, _52, 0x0, v0 + stlexvar 0x0, 0x19 + ldhole + sta v0 + callruntime.definesendableclass 0x1c, .TopLevelSendableClass27, _54, 0x0, v0 + stlexvar 0x0, 0x1a + ldhole + sta v0 + callruntime.definesendableclass 0x1d, .TopLevelSendableClass28, _56, 0x0, v0 + stlexvar 0x0, 0x1b + ldhole + sta v0 + callruntime.definesendableclass 0x1e, .TopLevelSendableClass29, _58, 0x0, v0 + stlexvar 0x0, 0x1c + ldhole + sta v0 + callruntime.definesendableclass 0x1f, .TopLevelSendableClass30, _60, 0x0, v0 + stlexvar 0x0, 0x1d + ldhole + sta v0 + callruntime.definesendableclass 0x20, .TopLevelSendableClass31, _62, 0x0, v0 + stlexvar 0x0, 0x1e + ldhole + sta v0 + callruntime.definesendableclass 0x21, .TopLevelSendableClass32, _64, 0x0, v0 + stlexvar 0x0, 0x1f + ldhole + sta v0 + callruntime.definesendableclass 0x22, .TopLevelSendableClass33, _66, 0x0, v0 + stlexvar 0x0, 0x20 + ldhole + sta v0 + callruntime.definesendableclass 0x23, .TopLevelSendableClass34, _68, 0x0, v0 + stlexvar 0x0, 0x21 + ldhole + sta v0 + callruntime.definesendableclass 0x24, .TopLevelSendableClass35, _70, 0x0, v0 + stlexvar 0x0, 0x22 + ldhole + sta v0 + callruntime.definesendableclass 0x25, .TopLevelSendableClass36, _72, 0x0, v0 + stlexvar 0x0, 0x23 + ldhole + sta v0 + callruntime.definesendableclass 0x26, .TopLevelSendableClass37, _74, 0x0, v0 + stlexvar 0x0, 0x24 + ldhole + sta v0 + callruntime.definesendableclass 0x27, .TopLevelSendableClass38, _76, 0x0, v0 + stlexvar 0x0, 0x25 + ldhole + sta v0 + callruntime.definesendableclass 0x28, .TopLevelSendableClass39, _78, 0x0, v0 + stlexvar 0x0, 0x26 + ldhole + sta v0 + callruntime.definesendableclass 0x29, .TopLevelSendableClass40, _80, 0x0, v0 + stlexvar 0x0, 0x27 + ldhole + sta v0 + callruntime.definesendableclass 0x2a, .TopLevelSendableClass41, _82, 0x0, v0 + stlexvar 0x0, 0x28 + ldhole + sta v0 + callruntime.definesendableclass 0x2b, .TopLevelSendableClass42, _84, 0x0, v0 + stlexvar 0x0, 0x29 + ldhole + sta v0 + callruntime.definesendableclass 0x2c, .TopLevelSendableClass43, _86, 0x0, v0 + stlexvar 0x0, 0x2a + ldhole + sta v0 + callruntime.definesendableclass 0x2d, .TopLevelSendableClass44, _88, 0x0, v0 + stlexvar 0x0, 0x2b + ldhole + sta v0 + callruntime.definesendableclass 0x2e, .TopLevelSendableClass45, _90, 0x0, v0 + stlexvar 0x0, 0x2c + ldhole + sta v0 + callruntime.definesendableclass 0x2f, .TopLevelSendableClass46, _92, 0x0, v0 + stlexvar 0x0, 0x2d + ldhole + sta v0 + callruntime.definesendableclass 0x30, .TopLevelSendableClass47, _94, 0x0, v0 + stlexvar 0x0, 0x2e + ldhole + sta v0 + callruntime.definesendableclass 0x31, .TopLevelSendableClass48, _96, 0x0, v0 + stlexvar 0x0, 0x2f + ldhole + sta v0 + callruntime.definesendableclass 0x32, .TopLevelSendableClass49, _98, 0x0, v0 + stlexvar 0x0, 0x30 + ldhole + sta v0 + callruntime.definesendableclass 0x33, .TopLevelSendableClass50, _100, 0x0, v0 + stlexvar 0x0, 0x31 + ldhole + sta v0 + callruntime.definesendableclass 0x34, .TopLevelSendableClass51, _102, 0x0, v0 + stlexvar 0x0, 0x32 + ldhole + sta v0 + callruntime.definesendableclass 0x35, .TopLevelSendableClass52, _104, 0x0, v0 + stlexvar 0x0, 0x33 + ldhole + sta v0 + callruntime.definesendableclass 0x36, .TopLevelSendableClass53, _106, 0x0, v0 + stlexvar 0x0, 0x34 + ldhole + sta v0 + callruntime.definesendableclass 0x37, .TopLevelSendableClass54, _108, 0x0, v0 + stlexvar 0x0, 0x35 + ldhole + sta v0 + callruntime.definesendableclass 0x38, .TopLevelSendableClass55, _110, 0x0, v0 + stlexvar 0x0, 0x36 + ldhole + sta v0 + callruntime.definesendableclass 0x39, .TopLevelSendableClass56, _112, 0x0, v0 + stlexvar 0x0, 0x37 + ldhole + sta v0 + callruntime.definesendableclass 0x3a, .TopLevelSendableClass57, _114, 0x0, v0 + stlexvar 0x0, 0x38 + ldhole + sta v0 + callruntime.definesendableclass 0x3b, .TopLevelSendableClass58, _116, 0x0, v0 + stlexvar 0x0, 0x39 + ldhole + sta v0 + callruntime.definesendableclass 0x3c, .TopLevelSendableClass59, _118, 0x0, v0 + stlexvar 0x0, 0x3a + ldhole + sta v0 + callruntime.definesendableclass 0x3d, .TopLevelSendableClass60, _120, 0x0, v0 + stlexvar 0x0, 0x3b + ldhole + sta v0 + callruntime.definesendableclass 0x3e, .TopLevelSendableClass61, _122, 0x0, v0 + stlexvar 0x0, 0x3c + ldhole + sta v0 + callruntime.definesendableclass 0x3f, .TopLevelSendableClass62, _124, 0x0, v0 + stlexvar 0x0, 0x3d + ldhole + sta v0 + callruntime.definesendableclass 0x40, .TopLevelSendableClass63, _126, 0x0, v0 + stlexvar 0x0, 0x3e + ldhole + sta v0 + callruntime.definesendableclass 0x41, .TopLevelSendableClass64, _128, 0x0, v0 + stlexvar 0x0, 0x3f + ldhole + sta v0 + callruntime.definesendableclass 0x42, .TopLevelSendableClass65, _130, 0x0, v0 + stlexvar 0x0, 0x40 + ldhole + sta v0 + callruntime.definesendableclass 0x43, .TopLevelSendableClass66, _132, 0x0, v0 + stlexvar 0x0, 0x41 + ldhole + sta v0 + callruntime.definesendableclass 0x44, .TopLevelSendableClass67, _134, 0x0, v0 + stlexvar 0x0, 0x42 + ldhole + sta v0 + callruntime.definesendableclass 0x45, .TopLevelSendableClass68, _136, 0x0, v0 + stlexvar 0x0, 0x43 + ldhole + sta v0 + callruntime.definesendableclass 0x46, .TopLevelSendableClass69, _138, 0x0, v0 + stlexvar 0x0, 0x44 + ldhole + sta v0 + callruntime.definesendableclass 0x47, .TopLevelSendableClass70, _140, 0x0, v0 + stlexvar 0x0, 0x45 + ldhole + sta v0 + callruntime.definesendableclass 0x48, .TopLevelSendableClass71, _142, 0x0, v0 + stlexvar 0x0, 0x46 + ldhole + sta v0 + callruntime.definesendableclass 0x49, .TopLevelSendableClass72, _144, 0x0, v0 + stlexvar 0x0, 0x47 + ldhole + sta v0 + callruntime.definesendableclass 0x4a, .TopLevelSendableClass73, _146, 0x0, v0 + stlexvar 0x0, 0x48 + ldhole + sta v0 + callruntime.definesendableclass 0x4b, .TopLevelSendableClass74, _148, 0x0, v0 + stlexvar 0x0, 0x49 + ldhole + sta v0 + callruntime.definesendableclass 0x4c, .TopLevelSendableClass75, _150, 0x0, v0 + stlexvar 0x0, 0x4a + ldhole + sta v0 + callruntime.definesendableclass 0x4d, .TopLevelSendableClass76, _152, 0x0, v0 + stlexvar 0x0, 0x4b + ldhole + sta v0 + callruntime.definesendableclass 0x4e, .TopLevelSendableClass77, _154, 0x0, v0 + stlexvar 0x0, 0x4c + ldhole + sta v0 + callruntime.definesendableclass 0x4f, .TopLevelSendableClass78, _156, 0x0, v0 + stlexvar 0x0, 0x4d + ldhole + sta v0 + callruntime.definesendableclass 0x50, .TopLevelSendableClass79, _158, 0x0, v0 + stlexvar 0x0, 0x4e + ldhole + sta v0 + callruntime.definesendableclass 0x51, .TopLevelSendableClass80, _160, 0x0, v0 + stlexvar 0x0, 0x4f + ldhole + sta v0 + callruntime.definesendableclass 0x52, .TopLevelSendableClass81, _162, 0x0, v0 + stlexvar 0x0, 0x50 + ldhole + sta v0 + callruntime.definesendableclass 0x53, .TopLevelSendableClass82, _164, 0x0, v0 + stlexvar 0x0, 0x51 + ldhole + sta v0 + callruntime.definesendableclass 0x54, .TopLevelSendableClass83, _166, 0x0, v0 + stlexvar 0x0, 0x52 + ldhole + sta v0 + callruntime.definesendableclass 0x55, .TopLevelSendableClass84, _168, 0x0, v0 + stlexvar 0x0, 0x53 + ldhole + sta v0 + callruntime.definesendableclass 0x56, .TopLevelSendableClass85, _170, 0x0, v0 + stlexvar 0x0, 0x54 + ldhole + sta v0 + callruntime.definesendableclass 0x57, .TopLevelSendableClass86, _172, 0x0, v0 + stlexvar 0x0, 0x55 + ldhole + sta v0 + callruntime.definesendableclass 0x58, .TopLevelSendableClass87, _174, 0x0, v0 + stlexvar 0x0, 0x56 + ldhole + sta v0 + callruntime.definesendableclass 0x59, .TopLevelSendableClass88, _176, 0x0, v0 + stlexvar 0x0, 0x57 + ldhole + sta v0 + callruntime.definesendableclass 0x5a, .TopLevelSendableClass89, _178, 0x0, v0 + stlexvar 0x0, 0x58 + ldhole + sta v0 + callruntime.definesendableclass 0x5b, .TopLevelSendableClass90, _180, 0x0, v0 + stlexvar 0x0, 0x59 + ldhole + sta v0 + callruntime.definesendableclass 0x5c, .TopLevelSendableClass91, _182, 0x0, v0 + stlexvar 0x0, 0x5a + ldhole + sta v0 + callruntime.definesendableclass 0x5d, .TopLevelSendableClass92, _184, 0x0, v0 + stlexvar 0x0, 0x5b + ldhole + sta v0 + callruntime.definesendableclass 0x5e, .TopLevelSendableClass93, _186, 0x0, v0 + stlexvar 0x0, 0x5c + ldhole + sta v0 + callruntime.definesendableclass 0x5f, .TopLevelSendableClass94, _188, 0x0, v0 + stlexvar 0x0, 0x5d + ldhole + sta v0 + callruntime.definesendableclass 0x60, .TopLevelSendableClass95, _190, 0x0, v0 + stlexvar 0x0, 0x5e + ldhole + sta v0 + callruntime.definesendableclass 0x61, .TopLevelSendableClass96, _192, 0x0, v0 + stlexvar 0x0, 0x5f + ldhole + sta v0 + callruntime.definesendableclass 0x62, .TopLevelSendableClass97, _194, 0x0, v0 + stlexvar 0x0, 0x60 + ldhole + sta v0 + callruntime.definesendableclass 0x63, .TopLevelSendableClass98, _196, 0x0, v0 + stlexvar 0x0, 0x61 + ldhole + sta v0 + callruntime.definesendableclass 0x64, .TopLevelSendableClass99, _198, 0x0, v0 + stlexvar 0x0, 0x62 + ldhole + sta v0 + callruntime.definesendableclass 0x65, .TopLevelSendableClass100, _200, 0x0, v0 + stlexvar 0x0, 0x63 + ldhole + sta v0 + callruntime.definesendableclass 0x66, .TopLevelSendableClass101, _202, 0x0, v0 + stlexvar 0x0, 0x64 + ldhole + sta v0 + callruntime.definesendableclass 0x67, .TopLevelSendableClass102, _204, 0x0, v0 + stlexvar 0x0, 0x65 + ldhole + sta v0 + callruntime.definesendableclass 0x68, .TopLevelSendableClass103, _206, 0x0, v0 + stlexvar 0x0, 0x66 + ldhole + sta v0 + callruntime.definesendableclass 0x69, .TopLevelSendableClass104, _208, 0x0, v0 + stlexvar 0x0, 0x67 + ldhole + sta v0 + callruntime.definesendableclass 0x6a, .TopLevelSendableClass105, _210, 0x0, v0 + stlexvar 0x0, 0x68 + ldhole + sta v0 + callruntime.definesendableclass 0x6b, .TopLevelSendableClass106, _212, 0x0, v0 + stlexvar 0x0, 0x69 + ldhole + sta v0 + callruntime.definesendableclass 0x6c, .TopLevelSendableClass107, _214, 0x0, v0 + stlexvar 0x0, 0x6a + ldhole + sta v0 + callruntime.definesendableclass 0x6d, .TopLevelSendableClass108, _216, 0x0, v0 + stlexvar 0x0, 0x6b + ldhole + sta v0 + callruntime.definesendableclass 0x6e, .TopLevelSendableClass109, _218, 0x0, v0 + stlexvar 0x0, 0x6c + ldhole + sta v0 + callruntime.definesendableclass 0x6f, .TopLevelSendableClass110, _220, 0x0, v0 + stlexvar 0x0, 0x6d + ldhole + sta v0 + callruntime.definesendableclass 0x70, .TopLevelSendableClass111, _222, 0x0, v0 + stlexvar 0x0, 0x6e + ldhole + sta v0 + callruntime.definesendableclass 0x71, .TopLevelSendableClass112, _224, 0x0, v0 + stlexvar 0x0, 0x6f + ldhole + sta v0 + callruntime.definesendableclass 0x72, .TopLevelSendableClass113, _226, 0x0, v0 + stlexvar 0x0, 0x70 + ldhole + sta v0 + callruntime.definesendableclass 0x73, .TopLevelSendableClass114, _228, 0x0, v0 + stlexvar 0x0, 0x71 + ldhole + sta v0 + callruntime.definesendableclass 0x74, .TopLevelSendableClass115, _230, 0x0, v0 + stlexvar 0x0, 0x72 + ldhole + sta v0 + callruntime.definesendableclass 0x75, .TopLevelSendableClass116, _232, 0x0, v0 + stlexvar 0x0, 0x73 + ldhole + sta v0 + callruntime.definesendableclass 0x76, .TopLevelSendableClass117, _234, 0x0, v0 + stlexvar 0x0, 0x74 + ldhole + sta v0 + callruntime.definesendableclass 0x77, .TopLevelSendableClass118, _236, 0x0, v0 + stlexvar 0x0, 0x75 + ldhole + sta v0 + callruntime.definesendableclass 0x78, .TopLevelSendableClass119, _238, 0x0, v0 + stlexvar 0x0, 0x76 + ldhole + sta v0 + callruntime.definesendableclass 0x79, .TopLevelSendableClass120, _240, 0x0, v0 + stlexvar 0x0, 0x77 + ldhole + sta v0 + callruntime.definesendableclass 0x7a, .TopLevelSendableClass121, _242, 0x0, v0 + stlexvar 0x0, 0x78 + ldhole + sta v0 + callruntime.definesendableclass 0x7b, .TopLevelSendableClass122, _244, 0x0, v0 + stlexvar 0x0, 0x79 + ldhole + sta v0 + callruntime.definesendableclass 0x7c, .TopLevelSendableClass123, _246, 0x0, v0 + stlexvar 0x0, 0x7a + ldhole + sta v0 + callruntime.definesendableclass 0x7d, .TopLevelSendableClass124, _248, 0x0, v0 + stlexvar 0x0, 0x7b + ldhole + sta v0 + callruntime.definesendableclass 0x7e, .TopLevelSendableClass125, _250, 0x0, v0 + stlexvar 0x0, 0x7c + ldhole + sta v0 + callruntime.definesendableclass 0x7f, .TopLevelSendableClass126, _252, 0x0, v0 + stlexvar 0x0, 0x7d + ldhole + sta v0 + callruntime.definesendableclass 0x80, .TopLevelSendableClass127, _254, 0x0, v0 + stlexvar 0x0, 0x7e + ldhole + sta v0 + callruntime.definesendableclass 0x81, .TopLevelSendableClass128, _256, 0x0, v0 + stlexvar 0x0, 0x7f + ldhole + sta v0 + callruntime.definesendableclass 0x82, .TopLevelSendableClass129, _258, 0x0, v0 + wide.stlexvar 0x0, 0x80 + ldhole + sta v0 + callruntime.definesendableclass 0x83, .TopLevelSendableClass130, _260, 0x0, v0 + wide.stlexvar 0x0, 0x81 + ldhole + sta v0 + callruntime.definesendableclass 0x84, .TopLevelSendableClass131, _262, 0x0, v0 + wide.stlexvar 0x0, 0x82 + ldhole + sta v0 + callruntime.definesendableclass 0x85, .TopLevelSendableClass132, _264, 0x0, v0 + wide.stlexvar 0x0, 0x83 + ldhole + sta v0 + callruntime.definesendableclass 0x86, .TopLevelSendableClass133, _266, 0x0, v0 + wide.stlexvar 0x0, 0x84 + ldhole + sta v0 + callruntime.definesendableclass 0x87, .TopLevelSendableClass134, _268, 0x0, v0 + wide.stlexvar 0x0, 0x85 + ldhole + sta v0 + callruntime.definesendableclass 0x88, .TopLevelSendableClass135, _270, 0x0, v0 + wide.stlexvar 0x0, 0x86 + ldhole + sta v0 + callruntime.definesendableclass 0x89, .TopLevelSendableClass136, _272, 0x0, v0 + wide.stlexvar 0x0, 0x87 + ldhole + sta v0 + callruntime.definesendableclass 0x8a, .TopLevelSendableClass137, _274, 0x0, v0 + wide.stlexvar 0x0, 0x88 + ldhole + sta v0 + callruntime.definesendableclass 0x8b, .TopLevelSendableClass138, _276, 0x0, v0 + wide.stlexvar 0x0, 0x89 + ldhole + sta v0 + callruntime.definesendableclass 0x8c, .TopLevelSendableClass139, _278, 0x0, v0 + wide.stlexvar 0x0, 0x8a + ldhole + sta v0 + callruntime.definesendableclass 0x8d, .TopLevelSendableClass140, _280, 0x0, v0 + wide.stlexvar 0x0, 0x8b + ldhole + sta v0 + callruntime.definesendableclass 0x8e, .TopLevelSendableClass141, _282, 0x0, v0 + wide.stlexvar 0x0, 0x8c + ldhole + sta v0 + callruntime.definesendableclass 0x8f, .TopLevelSendableClass142, _284, 0x0, v0 + wide.stlexvar 0x0, 0x8d + ldhole + sta v0 + callruntime.definesendableclass 0x90, .TopLevelSendableClass143, _286, 0x0, v0 + wide.stlexvar 0x0, 0x8e + ldhole + sta v0 + callruntime.definesendableclass 0x91, .TopLevelSendableClass144, _288, 0x0, v0 + wide.stlexvar 0x0, 0x8f + ldhole + sta v0 + callruntime.definesendableclass 0x92, .TopLevelSendableClass145, _290, 0x0, v0 + wide.stlexvar 0x0, 0x90 + ldhole + sta v0 + callruntime.definesendableclass 0x93, .TopLevelSendableClass146, _292, 0x0, v0 + wide.stlexvar 0x0, 0x91 + ldhole + sta v0 + callruntime.definesendableclass 0x94, .TopLevelSendableClass147, _294, 0x0, v0 + wide.stlexvar 0x0, 0x92 + ldhole + sta v0 + callruntime.definesendableclass 0x95, .TopLevelSendableClass148, _296, 0x0, v0 + wide.stlexvar 0x0, 0x93 + ldhole + sta v0 + callruntime.definesendableclass 0x96, .TopLevelSendableClass149, _298, 0x0, v0 + wide.stlexvar 0x0, 0x94 + ldhole + sta v0 + callruntime.definesendableclass 0x97, .TopLevelSendableClass150, _300, 0x0, v0 + wide.stlexvar 0x0, 0x95 + ldhole + sta v0 + callruntime.definesendableclass 0x98, .TopLevelSendableClass151, _302, 0x0, v0 + wide.stlexvar 0x0, 0x96 + ldhole + sta v0 + callruntime.definesendableclass 0x99, .TopLevelSendableClass152, _304, 0x0, v0 + wide.stlexvar 0x0, 0x97 + ldhole + sta v0 + callruntime.definesendableclass 0x9a, .TopLevelSendableClass153, _306, 0x0, v0 + wide.stlexvar 0x0, 0x98 + ldhole + sta v0 + callruntime.definesendableclass 0x9b, .TopLevelSendableClass154, _308, 0x0, v0 + wide.stlexvar 0x0, 0x99 + ldhole + sta v0 + callruntime.definesendableclass 0x9c, .TopLevelSendableClass155, _310, 0x0, v0 + wide.stlexvar 0x0, 0x9a + ldhole + sta v0 + callruntime.definesendableclass 0x9d, .TopLevelSendableClass156, _312, 0x0, v0 + wide.stlexvar 0x0, 0x9b + ldhole + sta v0 + callruntime.definesendableclass 0x9e, .TopLevelSendableClass157, _314, 0x0, v0 + wide.stlexvar 0x0, 0x9c + ldhole + sta v0 + callruntime.definesendableclass 0x9f, .TopLevelSendableClass158, _316, 0x0, v0 + wide.stlexvar 0x0, 0x9d + ldhole + sta v0 + callruntime.definesendableclass 0xa0, .TopLevelSendableClass159, _318, 0x0, v0 + wide.stlexvar 0x0, 0x9e + ldhole + sta v0 + callruntime.definesendableclass 0xa1, .TopLevelSendableClass160, _320, 0x0, v0 + wide.stlexvar 0x0, 0x9f + ldhole + sta v0 + callruntime.definesendableclass 0xa2, .TopLevelSendableClass161, _322, 0x0, v0 + wide.stlexvar 0x0, 0xa0 + ldhole + sta v0 + callruntime.definesendableclass 0xa3, .TopLevelSendableClass162, _324, 0x0, v0 + wide.stlexvar 0x0, 0xa1 + ldhole + sta v0 + callruntime.definesendableclass 0xa4, .TopLevelSendableClass163, _326, 0x0, v0 + wide.stlexvar 0x0, 0xa2 + ldhole + sta v0 + callruntime.definesendableclass 0xa5, .TopLevelSendableClass164, _328, 0x0, v0 + wide.stlexvar 0x0, 0xa3 + ldhole + sta v0 + callruntime.definesendableclass 0xa6, .TopLevelSendableClass165, _330, 0x0, v0 + wide.stlexvar 0x0, 0xa4 + ldhole + sta v0 + callruntime.definesendableclass 0xa7, .TopLevelSendableClass166, _332, 0x0, v0 + wide.stlexvar 0x0, 0xa5 + ldhole + sta v0 + callruntime.definesendableclass 0xa8, .TopLevelSendableClass167, _334, 0x0, v0 + wide.stlexvar 0x0, 0xa6 + ldhole + sta v0 + callruntime.definesendableclass 0xa9, .TopLevelSendableClass168, _336, 0x0, v0 + wide.stlexvar 0x0, 0xa7 + ldhole + sta v0 + callruntime.definesendableclass 0xaa, .TopLevelSendableClass169, _338, 0x0, v0 + wide.stlexvar 0x0, 0xa8 + ldhole + sta v0 + callruntime.definesendableclass 0xab, .TopLevelSendableClass170, _340, 0x0, v0 + wide.stlexvar 0x0, 0xa9 + ldhole + sta v0 + callruntime.definesendableclass 0xac, .TopLevelSendableClass171, _342, 0x0, v0 + wide.stlexvar 0x0, 0xaa + ldhole + sta v0 + callruntime.definesendableclass 0xad, .TopLevelSendableClass172, _344, 0x0, v0 + wide.stlexvar 0x0, 0xab + ldhole + sta v0 + callruntime.definesendableclass 0xae, .TopLevelSendableClass173, _346, 0x0, v0 + wide.stlexvar 0x0, 0xac + ldhole + sta v0 + callruntime.definesendableclass 0xaf, .TopLevelSendableClass174, _348, 0x0, v0 + wide.stlexvar 0x0, 0xad + ldhole + sta v0 + callruntime.definesendableclass 0xb0, .TopLevelSendableClass175, _350, 0x0, v0 + wide.stlexvar 0x0, 0xae + ldhole + sta v0 + callruntime.definesendableclass 0xb1, .TopLevelSendableClass176, _352, 0x0, v0 + wide.stlexvar 0x0, 0xaf + ldhole + sta v0 + callruntime.definesendableclass 0xb2, .TopLevelSendableClass177, _354, 0x0, v0 + wide.stlexvar 0x0, 0xb0 + ldhole + sta v0 + callruntime.definesendableclass 0xb3, .TopLevelSendableClass178, _356, 0x0, v0 + wide.stlexvar 0x0, 0xb1 + ldhole + sta v0 + callruntime.definesendableclass 0xb4, .TopLevelSendableClass179, _358, 0x0, v0 + wide.stlexvar 0x0, 0xb2 + ldhole + sta v0 + callruntime.definesendableclass 0xb5, .TopLevelSendableClass180, _360, 0x0, v0 + wide.stlexvar 0x0, 0xb3 + ldhole + sta v0 + callruntime.definesendableclass 0xb6, .TopLevelSendableClass181, _362, 0x0, v0 + wide.stlexvar 0x0, 0xb4 + ldhole + sta v0 + callruntime.definesendableclass 0xb7, .TopLevelSendableClass182, _364, 0x0, v0 + wide.stlexvar 0x0, 0xb5 + ldhole + sta v0 + callruntime.definesendableclass 0xb8, .TopLevelSendableClass183, _366, 0x0, v0 + wide.stlexvar 0x0, 0xb6 + ldhole + sta v0 + callruntime.definesendableclass 0xb9, .TopLevelSendableClass184, _368, 0x0, v0 + wide.stlexvar 0x0, 0xb7 + ldhole + sta v0 + callruntime.definesendableclass 0xba, .TopLevelSendableClass185, _370, 0x0, v0 + wide.stlexvar 0x0, 0xb8 + ldhole + sta v0 + callruntime.definesendableclass 0xbb, .TopLevelSendableClass186, _372, 0x0, v0 + wide.stlexvar 0x0, 0xb9 + ldhole + sta v0 + callruntime.definesendableclass 0xbc, .TopLevelSendableClass187, _374, 0x0, v0 + wide.stlexvar 0x0, 0xba + ldhole + sta v0 + callruntime.definesendableclass 0xbd, .TopLevelSendableClass188, _376, 0x0, v0 + wide.stlexvar 0x0, 0xbb + ldhole + sta v0 + callruntime.definesendableclass 0xbe, .TopLevelSendableClass189, _378, 0x0, v0 + wide.stlexvar 0x0, 0xbc + ldhole + sta v0 + callruntime.definesendableclass 0xbf, .TopLevelSendableClass190, _380, 0x0, v0 + wide.stlexvar 0x0, 0xbd + ldhole + sta v0 + callruntime.definesendableclass 0xc0, .TopLevelSendableClass191, _382, 0x0, v0 + wide.stlexvar 0x0, 0xbe + ldhole + sta v0 + callruntime.definesendableclass 0xc1, .TopLevelSendableClass192, _384, 0x0, v0 + wide.stlexvar 0x0, 0xbf + ldhole + sta v0 + callruntime.definesendableclass 0xc2, .TopLevelSendableClass193, _386, 0x0, v0 + wide.stlexvar 0x0, 0xc0 + ldhole + sta v0 + callruntime.definesendableclass 0xc3, .TopLevelSendableClass194, _388, 0x0, v0 + wide.stlexvar 0x0, 0xc1 + ldhole + sta v0 + callruntime.definesendableclass 0xc4, .TopLevelSendableClass195, _390, 0x0, v0 + wide.stlexvar 0x0, 0xc2 + ldhole + sta v0 + callruntime.definesendableclass 0xc5, .TopLevelSendableClass196, _392, 0x0, v0 + wide.stlexvar 0x0, 0xc3 + ldhole + sta v0 + callruntime.definesendableclass 0xc6, .TopLevelSendableClass197, _394, 0x0, v0 + wide.stlexvar 0x0, 0xc4 + ldhole + sta v0 + callruntime.definesendableclass 0xc7, .TopLevelSendableClass198, _396, 0x0, v0 + wide.stlexvar 0x0, 0xc5 + ldhole + sta v0 + callruntime.definesendableclass 0xc8, .TopLevelSendableClass199, _398, 0x0, v0 + wide.stlexvar 0x0, 0xc6 + ldhole + sta v0 + callruntime.definesendableclass 0xc9, .TopLevelSendableClass200, _400, 0x0, v0 + wide.stlexvar 0x0, 0xc7 + ldhole + sta v0 + callruntime.definesendableclass 0xca, .TopLevelSendableClass201, _402, 0x0, v0 + wide.stlexvar 0x0, 0xc8 + ldhole + sta v0 + callruntime.definesendableclass 0xcb, .TopLevelSendableClass202, _404, 0x0, v0 + wide.stlexvar 0x0, 0xc9 + ldhole + sta v0 + callruntime.definesendableclass 0xcc, .TopLevelSendableClass203, _406, 0x0, v0 + wide.stlexvar 0x0, 0xca + ldhole + sta v0 + callruntime.definesendableclass 0xcd, .TopLevelSendableClass204, _408, 0x0, v0 + wide.stlexvar 0x0, 0xcb + ldhole + sta v0 + callruntime.definesendableclass 0xce, .TopLevelSendableClass205, _410, 0x0, v0 + wide.stlexvar 0x0, 0xcc + ldhole + sta v0 + callruntime.definesendableclass 0xcf, .TopLevelSendableClass206, _412, 0x0, v0 + wide.stlexvar 0x0, 0xcd + ldhole + sta v0 + callruntime.definesendableclass 0xd0, .TopLevelSendableClass207, _414, 0x0, v0 + wide.stlexvar 0x0, 0xce + ldhole + sta v0 + callruntime.definesendableclass 0xd1, .TopLevelSendableClass208, _416, 0x0, v0 + wide.stlexvar 0x0, 0xcf + ldhole + sta v0 + callruntime.definesendableclass 0xd2, .TopLevelSendableClass209, _418, 0x0, v0 + wide.stlexvar 0x0, 0xd0 + ldhole + sta v0 + callruntime.definesendableclass 0xd3, .TopLevelSendableClass210, _420, 0x0, v0 + wide.stlexvar 0x0, 0xd1 + ldhole + sta v0 + callruntime.definesendableclass 0xd4, .TopLevelSendableClass211, _422, 0x0, v0 + wide.stlexvar 0x0, 0xd2 + ldhole + sta v0 + callruntime.definesendableclass 0xd5, .TopLevelSendableClass212, _424, 0x0, v0 + wide.stlexvar 0x0, 0xd3 + ldhole + sta v0 + callruntime.definesendableclass 0xd6, .TopLevelSendableClass213, _426, 0x0, v0 + wide.stlexvar 0x0, 0xd4 + ldhole + sta v0 + callruntime.definesendableclass 0xd7, .TopLevelSendableClass214, _428, 0x0, v0 + wide.stlexvar 0x0, 0xd5 + ldhole + sta v0 + callruntime.definesendableclass 0xd8, .TopLevelSendableClass215, _430, 0x0, v0 + wide.stlexvar 0x0, 0xd6 + ldhole + sta v0 + callruntime.definesendableclass 0xd9, .TopLevelSendableClass216, _432, 0x0, v0 + wide.stlexvar 0x0, 0xd7 + ldhole + sta v0 + callruntime.definesendableclass 0xda, .TopLevelSendableClass217, _434, 0x0, v0 + wide.stlexvar 0x0, 0xd8 + ldhole + sta v0 + callruntime.definesendableclass 0xdb, .TopLevelSendableClass218, _436, 0x0, v0 + wide.stlexvar 0x0, 0xd9 + ldhole + sta v0 + callruntime.definesendableclass 0xdc, .TopLevelSendableClass219, _438, 0x0, v0 + wide.stlexvar 0x0, 0xda + ldhole + sta v0 + callruntime.definesendableclass 0xdd, .TopLevelSendableClass220, _440, 0x0, v0 + wide.stlexvar 0x0, 0xdb + ldhole + sta v0 + callruntime.definesendableclass 0xde, .TopLevelSendableClass221, _442, 0x0, v0 + wide.stlexvar 0x0, 0xdc + ldhole + sta v0 + callruntime.definesendableclass 0xdf, .TopLevelSendableClass222, _444, 0x0, v0 + wide.stlexvar 0x0, 0xdd + ldhole + sta v0 + callruntime.definesendableclass 0xe0, .TopLevelSendableClass223, _446, 0x0, v0 + wide.stlexvar 0x0, 0xde + ldhole + sta v0 + callruntime.definesendableclass 0xe1, .TopLevelSendableClass224, _448, 0x0, v0 + wide.stlexvar 0x0, 0xdf + ldhole + sta v0 + callruntime.definesendableclass 0xe2, .TopLevelSendableClass225, _450, 0x0, v0 + wide.stlexvar 0x0, 0xe0 + ldhole + sta v0 + callruntime.definesendableclass 0xe3, .TopLevelSendableClass226, _452, 0x0, v0 + wide.stlexvar 0x0, 0xe1 + ldhole + sta v0 + callruntime.definesendableclass 0xe4, .TopLevelSendableClass227, _454, 0x0, v0 + wide.stlexvar 0x0, 0xe2 + ldhole + sta v0 + callruntime.definesendableclass 0xe5, .TopLevelSendableClass228, _456, 0x0, v0 + wide.stlexvar 0x0, 0xe3 + ldhole + sta v0 + callruntime.definesendableclass 0xe6, .TopLevelSendableClass229, _458, 0x0, v0 + wide.stlexvar 0x0, 0xe4 + ldhole + sta v0 + callruntime.definesendableclass 0xe7, .TopLevelSendableClass230, _460, 0x0, v0 + wide.stlexvar 0x0, 0xe5 + ldhole + sta v0 + callruntime.definesendableclass 0xe8, .TopLevelSendableClass231, _462, 0x0, v0 + wide.stlexvar 0x0, 0xe6 + ldhole + sta v0 + callruntime.definesendableclass 0xe9, .TopLevelSendableClass232, _464, 0x0, v0 + wide.stlexvar 0x0, 0xe7 + ldhole + sta v0 + callruntime.definesendableclass 0xea, .TopLevelSendableClass233, _466, 0x0, v0 + wide.stlexvar 0x0, 0xe8 + ldhole + sta v0 + callruntime.definesendableclass 0xeb, .TopLevelSendableClass234, _468, 0x0, v0 + wide.stlexvar 0x0, 0xe9 + ldhole + sta v0 + callruntime.definesendableclass 0xec, .TopLevelSendableClass235, _470, 0x0, v0 + wide.stlexvar 0x0, 0xea + ldhole + sta v0 + callruntime.definesendableclass 0xed, .TopLevelSendableClass236, _472, 0x0, v0 + wide.stlexvar 0x0, 0xeb + ldhole + sta v0 + callruntime.definesendableclass 0xee, .TopLevelSendableClass237, _474, 0x0, v0 + wide.stlexvar 0x0, 0xec + ldhole + sta v0 + callruntime.definesendableclass 0xef, .TopLevelSendableClass238, _476, 0x0, v0 + wide.stlexvar 0x0, 0xed + ldhole + sta v0 + callruntime.definesendableclass 0xf0, .TopLevelSendableClass239, _478, 0x0, v0 + wide.stlexvar 0x0, 0xee + ldhole + sta v0 + callruntime.definesendableclass 0xf1, .TopLevelSendableClass240, _480, 0x0, v0 + wide.stlexvar 0x0, 0xef + ldhole + sta v0 + callruntime.definesendableclass 0xf2, .TopLevelSendableClass241, _482, 0x0, v0 + wide.stlexvar 0x0, 0xf0 + ldhole + sta v0 + callruntime.definesendableclass 0xf3, .TopLevelSendableClass242, _484, 0x0, v0 + wide.stlexvar 0x0, 0xf1 + ldhole + sta v0 + callruntime.definesendableclass 0xf4, .TopLevelSendableClass243, _486, 0x0, v0 + wide.stlexvar 0x0, 0xf2 + ldhole + sta v0 + callruntime.definesendableclass 0xf5, .TopLevelSendableClass244, _488, 0x0, v0 + wide.stlexvar 0x0, 0xf3 + ldhole + sta v0 + callruntime.definesendableclass 0xf6, .TopLevelSendableClass245, _490, 0x0, v0 + wide.stlexvar 0x0, 0xf4 + ldhole + sta v0 + callruntime.definesendableclass 0xf7, .TopLevelSendableClass246, _492, 0x0, v0 + wide.stlexvar 0x0, 0xf5 + ldhole + sta v0 + callruntime.definesendableclass 0xf8, .TopLevelSendableClass247, _494, 0x0, v0 + wide.stlexvar 0x0, 0xf6 + ldhole + sta v0 + callruntime.definesendableclass 0xf9, .TopLevelSendableClass248, _496, 0x0, v0 + wide.stlexvar 0x0, 0xf7 + ldhole + sta v0 + callruntime.definesendableclass 0xfa, .TopLevelSendableClass249, _498, 0x0, v0 + wide.stlexvar 0x0, 0xf8 + ldhole + sta v0 + callruntime.definesendableclass 0xfb, .TopLevelSendableClass250, _500, 0x0, v0 + wide.stlexvar 0x0, 0xf9 + ldhole + sta v0 + callruntime.definesendableclass 0xfc, .TopLevelSendableClass251, _502, 0x0, v0 + wide.stlexvar 0x0, 0xfa + ldhole + sta v0 + callruntime.definesendableclass 0xfd, .TopLevelSendableClass252, _504, 0x0, v0 + wide.stlexvar 0x0, 0xfb + ldhole + sta v0 + callruntime.definesendableclass 0xfe, .TopLevelSendableClass253, _506, 0x0, v0 + wide.stlexvar 0x0, 0xfc + ldhole + sta v0 + callruntime.definesendableclass 0x100, .TopLevelSendableClass254, _508, 0x0, v0 + wide.stlexvar 0x0, 0xfd + ldhole + sta v0 + callruntime.definesendableclass 0x101, .TopLevelSendableClass255, _510, 0x0, v0 + wide.stlexvar 0x0, 0xfe + ldhole + sta v0 + callruntime.definesendableclass 0x102, .SendableTestClass1, _512, 0x0, v0 + sta v0 + mov v2, v0 + newobjrange 0x103, 0x1, v2 + sta v0 + tryldglobalbyname 0x105, print + sta v1 + lda v0 + ldobjbyname 0x106, v + sta v0 + lda v1 + callarg1 0x0, v0 + returnundefined +label_2: +} + + diff --git a/es2panda/test/version_control/API12beta1_and_beta2/syntax_feature/top_level_sendable_class_as_closure_unsupported_runtime_for_below_API12beta3_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_unsupported_runtime_for_higher_or_equal_to_API11_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API12beta1_and_beta2/syntax_feature/top_level_sendable_class_as_closure_unsupported_runtime_for_below_API12beta3_version-expected.txt rename to es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_unsupported_runtime_for_higher_or_equal_to_API11_version-expected.txt diff --git a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_unsupported_runtime_for_higher_or_equal_to_API12beta3_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_unsupported_runtime_for_higher_or_equal_to_API12beta3_version-expected.txt new file mode 100644 index 0000000000..8e9b9b9398 --- /dev/null +++ b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_unsupported_runtime_for_higher_or_equal_to_API12beta3_version-expected.txt @@ -0,0 +1 @@ +TypeError: Constructor is false \ No newline at end of file diff --git a/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_unsupported_runtime_for_below_API11_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_unsupported_runtime_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_unsupported_runtime_for_below_API11_version-expected.txt rename to es2panda/test/version_control/API12beta1_and_beta2/bytecode_feature/wide_sendable_lexical_env_unsupported_runtime_version-expected.txt diff --git a/es2panda/test/version_control/API12beta1_and_beta2/syntax_feature/top_level_sendable_class_as_closure_unsupported_runtime_for_higher_or_equal_to_API11_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/syntax_feature/top_level_sendable_class_as_closure_unsupported_runtime_for_higher_or_equal_to_API11_version-expected.txt new file mode 100644 index 0000000000..8e9b9b9398 --- /dev/null +++ b/es2panda/test/version_control/API12beta1_and_beta2/syntax_feature/top_level_sendable_class_as_closure_unsupported_runtime_for_higher_or_equal_to_API11_version-expected.txt @@ -0,0 +1 @@ +TypeError: Constructor is false \ No newline at end of file diff --git a/es2panda/test/version_control/API12beta1_and_beta2/syntax_feature/top_level_sendable_class_as_closure_unsupported_runtime_for_higher_or_equal_to_API12beta3_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/syntax_feature/top_level_sendable_class_as_closure_unsupported_runtime_for_higher_or_equal_to_API12beta3_version-expected.txt new file mode 100644 index 0000000000..8e9b9b9398 --- /dev/null +++ b/es2panda/test/version_control/API12beta1_and_beta2/syntax_feature/top_level_sendable_class_as_closure_unsupported_runtime_for_higher_or_equal_to_API12beta3_version-expected.txt @@ -0,0 +1 @@ +TypeError: Constructor is false \ No newline at end of file diff --git a/es2panda/test/version_control/API12beta1_and_beta2/syntax_feature/top_level_sendable_class_as_closure_unsupported_runtime_version-expected.txt b/es2panda/test/version_control/API12beta1_and_beta2/syntax_feature/top_level_sendable_class_as_closure_unsupported_runtime_version-expected.txt new file mode 100644 index 0000000000..8e9b9b9398 --- /dev/null +++ b/es2panda/test/version_control/API12beta1_and_beta2/syntax_feature/top_level_sendable_class_as_closure_unsupported_runtime_version-expected.txt @@ -0,0 +1 @@ +TypeError: Constructor is false \ No newline at end of file diff --git a/es2panda/test/version_control/API12beta3/bytecode_feature/define_property_by_name_unsupported_compile_for_below_API11_asm_version-expected.txt b/es2panda/test/version_control/API12beta3/bytecode_feature/define_property_by_name_unsupported_compile_asm_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API12beta3/bytecode_feature/define_property_by_name_unsupported_compile_for_below_API11_asm_version-expected.txt rename to es2panda/test/version_control/API12beta3/bytecode_feature/define_property_by_name_unsupported_compile_asm_version-expected.txt diff --git a/es2panda/test/version_control/API12beta3/bytecode_feature/define_property_by_name_unsupported_compile_for_below_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API12beta3/bytecode_feature/define_property_by_name_unsupported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API12beta3/bytecode_feature/define_property_by_name_unsupported_compile_for_below_API12beta3_asm_version-expected.txt rename to es2panda/test/version_control/API12beta3/bytecode_feature/define_property_by_name_unsupported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt diff --git a/es2panda/test/version_control/API12beta3/bytecode_feature/define_property_by_name_unsupported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API12beta3/bytecode_feature/define_property_by_name_unsupported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt new file mode 100644 index 0000000000..601217c7f8 --- /dev/null +++ b/es2panda/test/version_control/API12beta3/bytecode_feature/define_property_by_name_unsupported_compile_for_higher_or_equal_to_API12beta3_asm_version-expected.txt @@ -0,0 +1,50 @@ +slotNum = 0x4 +.language ECMAScript +.function any .PropertyByName(any a0, any a1, any a2, any a3, any a4) { +label_1: +label_0: + lda a3 + stobjbyname 0x0, name, a2 + lda a4 + stobjbyname 0x2, age, a2 + lda a2 + return +label_2: +} + +slotNum = 0x3 +.language ECMAScript +.function any .func_main_0(any a0, any a1, any a2) { +label_1: +label_0: + ldhole + sta v0 + defineclasswithbuffer 0x0, .PropertyByName, _2, 0x2, v0 + ldobjbyname 0x1, prototype + returnundefined +label_2: +} + +slotNum = 0xa +.language ECMAScript +.function any .init(any a0, any a1, any a2) { +label_1: +label_0: + tryldglobalbyname 0x0, Object + sta v0 + ldobjbyname 0x1, defineProperty + sta v1 + lda.str name + sta v2 + createobjectwithbuffer 0x3, _1 + sta v3 + lda a2 + ldobjbyname 0x4, name + definefieldbyname 0x6, value, v3 + lda v1 + callthis3 0x8, v0, a2, v2, v3 + returnundefined +label_2: +} + + diff --git a/es2panda/test/version_control/API12beta3/syntax_feature/sendable_function_unsupported_runtime_for_below_API12beta3_version-expected.txt b/es2panda/test/version_control/API12beta3/syntax_feature/sendable_function_unsupported_runtime_for_higher_or_equal_to_API11_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API12beta3/syntax_feature/sendable_function_unsupported_runtime_for_below_API12beta3_version-expected.txt rename to es2panda/test/version_control/API12beta3/syntax_feature/sendable_function_unsupported_runtime_for_higher_or_equal_to_API11_version-expected.txt diff --git a/es2panda/test/version_control/API12beta3/syntax_feature/sendable_function_unsupported_runtime_version-expected.txt b/es2panda/test/version_control/API12beta3/syntax_feature/sendable_function_unsupported_runtime_version-expected.txt new file mode 100644 index 0000000000..71d2c9ab90 --- /dev/null +++ b/es2panda/test/version_control/API12beta3/syntax_feature/sendable_function_unsupported_runtime_version-expected.txt @@ -0,0 +1 @@ +TypeError: is not callable \ No newline at end of file diff --git a/es2panda/test/version_control/API18/bytecode_feature/derived-class-default-constructor-opt_unsupported_compile_for_below_API12beta3_asm_version-expected.txt b/es2panda/test/version_control/API18/bytecode_feature/derived-class-default-constructor-opt_unsupported_compile_asm_version-expected.txt similarity index 100% rename from es2panda/test/version_control/API18/bytecode_feature/derived-class-default-constructor-opt_unsupported_compile_for_below_API12beta3_asm_version-expected.txt rename to es2panda/test/version_control/API18/bytecode_feature/derived-class-default-constructor-opt_unsupported_compile_asm_version-expected.txt diff --git a/es2panda/test/version_control/API18/bytecode_feature/sendable-class-export_unsupported_compile_asm_version-expected.txt b/es2panda/test/version_control/API18/bytecode_feature/sendable-class-export_unsupported_compile_asm_version-expected.txt index b1695beb87..d8063d7e9e 100644 --- a/es2panda/test/version_control/API18/bytecode_feature/sendable-class-export_unsupported_compile_asm_version-expected.txt +++ b/es2panda/test/version_control/API18/bytecode_feature/sendable-class-export_unsupported_compile_asm_version-expected.txt @@ -32,7 +32,7 @@ label_0: label_2: } -slotNum = 0x4 +slotNum = 0x6 .language ECMAScript .function any .func_main_0(any a0, any a1, any a2) { label_1: @@ -46,7 +46,8 @@ label_0: stmodulevar 0x0 ldhole sta v0 - callruntime.definesendableclass 0x3, .B, _3, 0x0, v0 + defineclasswithbuffer 0x3, .B, _2, 0x0, v0 + ldobjbyname 0x4, prototype returnundefined label_2: } diff --git a/es2panda/test/version_control/API18/bytecode_feature/sendable-class-export_unsupported_compile_for_below_API11_asm_version-expected.txt b/es2panda/test/version_control/API18/bytecode_feature/sendable-class-export_unsupported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt similarity index 89% rename from es2panda/test/version_control/API18/bytecode_feature/sendable-class-export_unsupported_compile_for_below_API11_asm_version-expected.txt rename to es2panda/test/version_control/API18/bytecode_feature/sendable-class-export_unsupported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt index d8063d7e9e..b1695beb87 100644 --- a/es2panda/test/version_control/API18/bytecode_feature/sendable-class-export_unsupported_compile_for_below_API11_asm_version-expected.txt +++ b/es2panda/test/version_control/API18/bytecode_feature/sendable-class-export_unsupported_compile_for_higher_or_equal_to_API11_asm_version-expected.txt @@ -32,7 +32,7 @@ label_0: label_2: } -slotNum = 0x6 +slotNum = 0x4 .language ECMAScript .function any .func_main_0(any a0, any a1, any a2) { label_1: @@ -46,8 +46,7 @@ label_0: stmodulevar 0x0 ldhole sta v0 - defineclasswithbuffer 0x3, .B, _2, 0x0, v0 - ldobjbyname 0x4, prototype + callruntime.definesendableclass 0x3, .B, _3, 0x0, v0 returnundefined label_2: } -- Gitee From 13198f90b5f33b60ea0b57871f4f4104ea09144f Mon Sep 17 00:00:00 2001 From: wangyuxin Date: Wed, 12 Mar 2025 17:18:46 +0800 Subject: [PATCH 161/268] Fix bug of union tuple MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC060V Reason: There are two problems in this test. let v: [string]|null = ["A"] 1. In CheckAssignmentExprOperatorType, we set preffered type of array expression only when left type is array or tuple type. 2. Because the left type is union type, the type of array expression is generated without preferred type which is array type. 3. Array type can not be assigned to tuple type. function main() { let res: boolean = false let v: [string]|null v = null v![0] = "A" } 1. The smartType of V in line 5 is definitely null type 2. Null type can not be accessed by index. Description: 1. When left type is union type and containing array or tuple type, set the union type as preferred type 2. For TSNonNullExpression, don't use possible smart cast to null-like types. Signed-off-by: wangyuxin --- ets2panda/checker/ETSAnalyzer.cpp | 13 ++++++++++++- .../test/ast/compiler/ets/tuple_union_neg.ets | 18 ++++++++++++++++++ .../increment-on-nullish-type-undefined.ets | 4 +++- ets2panda/test/runtime/ets/tuple_union.ets | 18 ++++++++++++++++++ 4 files changed, 51 insertions(+), 2 deletions(-) create mode 100644 ets2panda/test/ast/compiler/ets/tuple_union_neg.ets create mode 100644 ets2panda/test/runtime/ets/tuple_union.ets diff --git a/ets2panda/checker/ETSAnalyzer.cpp b/ets2panda/checker/ETSAnalyzer.cpp index f127204827..f6498ed62c 100644 --- a/ets2panda/checker/ETSAnalyzer.cpp +++ b/ets2panda/checker/ETSAnalyzer.cpp @@ -3014,8 +3014,19 @@ checker::Type *ETSAnalyzer::Check(ir::TSNonNullExpression *expr) const checker->ReportWarning( {"Bad operand type, the operand of the non-nullish expression is 'null' or 'undefined'."}, expr->Expr()->Start()); + + if (expr->expr_->IsIdentifier()) { + ES2PANDA_ASSERT(expr->expr_->AsIdentifier()->Variable() != nullptr); + auto originalType = expr->expr_->AsIdentifier()->Variable()->TsType(); + if (originalType != nullptr) { + expr->SetTsType(checker->GetNonNullishType(originalType)); + } + } + } + + if (expr->TsType() == nullptr) { + expr->SetTsType(checker->GetNonNullishType(exprType)); } - expr->SetTsType(checker->GetNonNullishType(exprType)); expr->SetOriginalType(expr->TsType()); return expr->TsType(); } diff --git a/ets2panda/test/ast/compiler/ets/tuple_union_neg.ets b/ets2panda/test/ast/compiler/ets/tuple_union_neg.ets new file mode 100644 index 0000000000..34a2d31c5a --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/tuple_union_neg.ets @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let v: [number]|null = ["A"] + +/* @@? 15:25 Error TypeError: Array initializer's type is not assignable to tuple type at index: 0 */ + diff --git a/ets2panda/test/ast/parser/ets/increment-on-nullish-type-undefined.ets b/ets2panda/test/ast/parser/ets/increment-on-nullish-type-undefined.ets index 16985cfec4..975a0fe946 100644 --- a/ets2panda/test/ast/parser/ets/increment-on-nullish-type-undefined.ets +++ b/ets2panda/test/ast/parser/ets/increment-on-nullish-type-undefined.ets @@ -18,4 +18,6 @@ } /* @@? 17:3 Warning Warning: Bad operand type, the operand of the non-nullish expression is 'null' or 'undefined'. */ - /* @@? 17:3 Error TypeError: Bad operand type, the type of the operand must be numeric type. */ \ No newline at end of file + /* @@? 17:3 Error TypeError: Cannot cast 'null' or 'undefined' to non-nullish type. */ + /* @@? 17:3 Error TypeError: Type 'Double' cannot be assigned to type 'undefined' */ + diff --git a/ets2panda/test/runtime/ets/tuple_union.ets b/ets2panda/test/runtime/ets/tuple_union.ets new file mode 100644 index 0000000000..5864a61635 --- /dev/null +++ b/ets2panda/test/runtime/ets/tuple_union.ets @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +let v: [string]|null = ["A"] + -- Gitee From 9f8c028af000807fa9d1c2d6ef61500a12fcc8ca Mon Sep 17 00:00:00 2001 From: zju_wyx Date: Fri, 9 May 2025 15:54:10 +0800 Subject: [PATCH 162/268] enable annotation in arkguard MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Issue: [新需求]: 混淆适配注解 https: //gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC6MWM Signed-off-by: zju_wyx Change-Id: Ibb01be3ddb18992fc7cda4b168eafbf79eff93cd --- arkguard/src/ArkObfuscator.ts | 8 +- arkguard/src/common/ApiExtractor.ts | 7 +- arkguard/src/common/type.ts | 5 +- arkguard/src/configs/IOptions.ts | 3 + arkguard/src/initialization/ConfigResolver.ts | 1 + arkguard/src/initialization/Initializer.ts | 8 +- .../rename/RenameIdentifierTransformer.ts | 53 +++++-- .../rename/RenamePropertiesTransformer.ts | 30 +++- arkguard/src/utils/NodeUtils.ts | 40 +++++- arkguard/src/utils/ScopeAnalyzer.ts | 38 +++++- arkguard/src/utils/TypeUtils.ts | 6 +- .../ut/arkobfuscator/ArkObfuscator.spec.ts | 9 ++ .../ut/arkobfuscator/iniTestObfConfig.json | 3 +- .../ut/initialization/Initializer.spec.ts | 14 ++ .../RenameIdentifierTransformer.spec.ts | 129 +++++++++++++++++- .../RenamePropertiesTransformer.spec.ts | 85 ++++++++++++ .../test/ut/utils/KeepParameterUtils.spec.ts | 4 +- arkguard/test/ut/utils/NodeUtils.spec.ts | 43 ++++++ arkguard/test/ut/utils/ScopeAnalyzer.spec.ts | 18 +-- .../compiler/js/array-literal-1-expected.txt | 1 - es2panda/test/compiler/js/array-literal-1.js | 24 ---- 21 files changed, 458 insertions(+), 71 deletions(-) delete mode 100644 es2panda/test/compiler/js/array-literal-1-expected.txt delete mode 100644 es2panda/test/compiler/js/array-literal-1.js diff --git a/arkguard/src/ArkObfuscator.ts b/arkguard/src/ArkObfuscator.ts index 556186b280..2e4795e2ca 100644 --- a/arkguard/src/ArkObfuscator.ts +++ b/arkguard/src/ArkObfuscator.ts @@ -207,7 +207,7 @@ export class ArkObfuscator { // A text writer of Printer private mTextWriter: EmitTextWriter; - // Compiler Options for typescript,use to parse ast + // Compiler Options for typescript, use to parse ast private readonly mCompilerOptions: CompilerOptions; // User custom obfuscation profiles. @@ -360,6 +360,10 @@ export class ArkObfuscator { this.mCompilerOptions.sourceMap = true; } + if (this.mCustomProfiles.mAllowEtsAnnotations) { + this.mCompilerOptions.etsAnnotationsEnable = true; + } + const enableTopLevel: boolean = this.mCustomProfiles.mNameObfuscation?.mTopLevel; const exportObfuscation: boolean = this.mCustomProfiles.mExportObfuscation; const propertyObfuscation: boolean = this.mCustomProfiles.mNameObfuscation?.mRenameProperties; @@ -569,7 +573,7 @@ export class ArkObfuscator { startSingleFileEvent(EventList.CREATE_AST, performancePrinter.timeSumPrinter); let ast: SourceFile; if (typeof content === 'string') { - ast = TypeUtils.createObfSourceFile(sourceFilePath, content); + ast = TypeUtils.createObfSourceFile(sourceFilePath, content, this.mCompilerOptions); } else { ast = content; } diff --git a/arkguard/src/common/ApiExtractor.ts b/arkguard/src/common/ApiExtractor.ts index 558d56dfcd..12e46774cd 100644 --- a/arkguard/src/common/ApiExtractor.ts +++ b/arkguard/src/common/ApiExtractor.ts @@ -40,6 +40,7 @@ import { ClassElement, forEachChild, getLeadingCommentRangesOfNode, + isAnnotationDeclaration, isBinaryExpression, isClassDeclaration, isClassExpression, @@ -110,7 +111,7 @@ import { FileWhiteList, KeepInfo, projectWhiteListManager } from '../utils/ProjectCollections'; -import { AtKeepCollections, BytecodeObfuscationCollections } from '../utils/CommonCollections'; +import { AtKeepCollections, BytecodeObfuscationCollections, PropCollections } from '../utils/CommonCollections'; import { hasExportModifier } from '../utils/NodeUtils'; export namespace ApiExtractor { @@ -700,7 +701,9 @@ export namespace ApiExtractor { projectWhiteListManager?.setCurrentCollector(fileName); - const sourceFile: SourceFile = createSourceFile(fileName, fs.readFileSync(fileName).toString(), ScriptTarget.ES2015, true); + let sourceFile: SourceFile = createSourceFile(fileName, fs.readFileSync(fileName).toString(), ScriptTarget.ES2015, true, undefined, { + etsAnnotationsEnable: true + }, true); mCurrentExportedPropertySet.clear(); collectWhiteListByApiType(sourceFile, apiType, fileName); diff --git a/arkguard/src/common/type.ts b/arkguard/src/common/type.ts index 2d988379e1..2e613c51be 100644 --- a/arkguard/src/common/type.ts +++ b/arkguard/src/common/type.ts @@ -73,4 +73,7 @@ export interface HvigorErrorInfo { position: string; solutions: string[]; moreInfo?: Object; -} \ No newline at end of file +} + +// Prefix of annotation declaration in intermediate files +export const annotationPrefix: string = '__$$ETS_ANNOTATION$$__'; \ No newline at end of file diff --git a/arkguard/src/configs/IOptions.ts b/arkguard/src/configs/IOptions.ts index ba4c9f2207..01eaeb9190 100644 --- a/arkguard/src/configs/IOptions.ts +++ b/arkguard/src/configs/IOptions.ts @@ -69,4 +69,7 @@ export interface IOptions { // Use optimized system whitelist readonly mStripLanguageDefaultWhitelist?: boolean; + + // Is Annotation allowed + readonly mAllowEtsAnnotations?: boolean; } diff --git a/arkguard/src/initialization/ConfigResolver.ts b/arkguard/src/initialization/ConfigResolver.ts index 7d3ac07c5d..d0019caca2 100644 --- a/arkguard/src/initialization/ConfigResolver.ts +++ b/arkguard/src/initialization/ConfigResolver.ts @@ -107,6 +107,7 @@ class ObOptions { enableExportObfuscation: boolean = false; enableLibObfuscationOptions: boolean = false; enableAtKeep: boolean = false; + enableEtsAnnotation: boolean = false; printKeptNames: boolean = false; removeComments: boolean = false; compact: boolean = false; diff --git a/arkguard/src/initialization/Initializer.ts b/arkguard/src/initialization/Initializer.ts index 0bf8bcea24..c0262eb890 100644 --- a/arkguard/src/initialization/Initializer.ts +++ b/arkguard/src/initialization/Initializer.ts @@ -54,7 +54,10 @@ export const printerTimeAndMemDataConfig = { export function initObfuscationConfig(projectConfig: any, arkProjectConfig: any, printObfLogger: Function): void { const obConfig: ObConfigResolver = new ObConfigResolver(projectConfig, printObfLogger, true); - const mergedObConfig: MergedConfig = obConfig.resolveObfuscationConfigs(); + let mergedObConfig: MergedConfig = obConfig.resolveObfuscationConfigs(); + if (arkProjectConfig.allowEtsAnnotations) { + mergedObConfig.options.enableEtsAnnotation = arkProjectConfig.allowEtsAnnotations; + } const isHarCompiled: boolean = projectConfig.compileHar; if (mergedObConfig.options.disableObfuscation) { blockPrinter(); @@ -138,7 +141,8 @@ function initArkGuardConfig( mKeepSourceOfPaths: new Set(), mkeepFilesAndDependencies: new Set(), }, - mStripLanguageDefaultWhitelist: mergedObConfig.options.stripLanguageDefault + mStripLanguageDefaultWhitelist: mergedObConfig.options.stripLanguageDefault, + mAllowEtsAnnotations: mergedObConfig.options.enableEtsAnnotation, }; const arkObfuscator: ArkObfuscator = new ArkObfuscator(); diff --git a/arkguard/src/transformers/rename/RenameIdentifierTransformer.ts b/arkguard/src/transformers/rename/RenameIdentifierTransformer.ts index eff9d64cb4..a0df5ff66a 100644 --- a/arkguard/src/transformers/rename/RenameIdentifierTransformer.ts +++ b/arkguard/src/transformers/rename/RenameIdentifierTransformer.ts @@ -39,7 +39,8 @@ import { isPropertyAssignment, isPrivateIdentifier, isParameter, - isPropertyAccessExpression + isPropertyAccessExpression, + isAnnotationDeclaration } from 'typescript'; import type { @@ -84,7 +85,7 @@ import type {INameGenerator, NameGeneratorOptions} from '../../generator/INameGe import type {IOptions} from '../../configs/IOptions'; import type { INameObfuscationOption, IUnobfuscationOption } from '../../configs/INameObfuscationOption'; import type {TransformPlugin} from '../TransformPlugin'; -import type { MangledSymbolInfo } from '../../common/type'; +import { annotationPrefix, type MangledSymbolInfo } from '../../common/type'; import {TransformerOrder} from '../TransformPlugin'; import {getNameGenerator, NameGeneratorType} from '../../generator/NameFactory'; import {TypeUtils} from '../../utils/TypeUtils'; @@ -99,7 +100,7 @@ import { } from '../../utils/TransformUtil'; import {NodeUtils} from '../../utils/NodeUtils'; import {ApiExtractor} from '../../common/ApiExtractor'; -import {performancePrinter, ArkObfuscator, cleanFileMangledNames} from '../../ArkObfuscator'; +import {performancePrinter, ArkObfuscator, cleanFileMangledNames, FileUtils} from '../../ArkObfuscator'; import { endSingleFileEvent, startSingleFileEvent } from '../../utils/PrinterUtils'; import { EventList, endSingleFileForMoreTimeEvent, startSingleFileForMoreTimeEvent } from '../../utils/PrinterTimeAndMemUtils'; import { isViewPUBasedClass } from '../../utils/OhsUtil'; @@ -155,6 +156,7 @@ namespace secharmony { let mangledLabelNames: Map = new Map(); let fileExportNames: Set = undefined; let fileImportNames: Set = undefined; + let currentFileType: string | undefined = undefined; exportElementsWithoutSymbol.clear(); exportSymbolAliasMap.clear(); nodeSymbolMap.clear(); @@ -183,6 +185,7 @@ namespace secharmony { if (!isSourceFile(node) || ArkObfuscator.isKeptCurrentFile) { return node; } + currentFileType = FileUtils.getFileSuffix(node.fileName).ext; isCurFileParamertersKept = shouldKeepCurFileParamerters(node, profile); const checkRecordInfo = ArkObfuscator.recordStage(MemoryDottingDefine.CREATE_CHECKER); @@ -193,7 +196,7 @@ namespace secharmony { const scopeRecordInfo = ArkObfuscator.recordStage(MemoryDottingDefine.SCOPE_ANALYZE); startSingleFileEvent(EventList.SCOPE_ANALYZE, performancePrinter.timeSumPrinter); - manager.analyze(node, checker, exportObfuscation); + manager.analyze(node, checker, exportObfuscation, currentFileType); endSingleFileEvent(EventList.SCOPE_ANALYZE, performancePrinter.timeSumPrinter); ArkObfuscator.stopRecordStage(scopeRecordInfo); @@ -314,11 +317,10 @@ namespace secharmony { recordHistoryUnobfuscatedNames(path); // For incremental build mangled = historyName; } else if (Reflect.has(def, 'obfuscateAsProperty')) { - // obfuscate toplevel, export - mangled = getPropertyMangledName(original, path); + mangled = getPropertyOrAnnotationMangledName(original, path); } else { // obfuscate local variable - mangled = getMangled(scope, generator); + mangled = getMangledLocalName(scope, generator); } // add new names to name cache let identifierCache = nameCache?.get(IDENTIFIER_CACHE); @@ -383,11 +385,7 @@ namespace secharmony { return mangledName; } - function getPropertyMangledName(original: string, nameWithScope: string): string { - if (isInTopLevelWhitelist(original, UnobfuscationCollections.unobfuscatedNamesMap, nameWithScope, enablePropertyObf, shouldPrintKeptNames)) { - return original; - } - + function getMangledName(original: string): string { const historyName: string = PropCollections.historyMangledTable?.get(original); let mangledName: string = historyName ? historyName : PropCollections.globalMangledTable.get(original); while (!mangledName) { @@ -444,6 +442,35 @@ namespace secharmony { return mangledName; } + function getPropertyMangledName(originalName: string, nameWithScope: string): string { + if (isInTopLevelWhitelist(originalName, UnobfuscationCollections.unobfuscatedNamesMap, nameWithScope, enablePropertyObf, shouldPrintKeptNames)) { + return originalName; + } + + let mangledName = getMangledName(originalName); + return mangledName; + } + + // mangle annotation name in intermediate files + function getAnnotationMangledNameWithPrefix(originalName: string, nameWithScope: string): string { + if (isInTopLevelWhitelist(originalName, UnobfuscationCollections.unobfuscatedNamesMap, nameWithScope, enablePropertyObf, shouldPrintKeptNames)) { + return `${annotationPrefix}${originalName}`; + } + let mangledName: string = `${annotationPrefix}${getMangledName(originalName)}`; + return mangledName; + } + + function getPropertyOrAnnotationMangledName(originalName: string, nameWithScope: string): string { + let name: string | undefined = originalName.startsWith(annotationPrefix) ? originalName.substring(annotationPrefix.length) : undefined; + if (name) { + // obfuscate annotation name with prefix, e.g. in intermediate files + return getAnnotationMangledNameWithPrefix(name, nameWithScope); + } else { + // obfuscate toplevel, export + return getPropertyMangledName(originalName, nameWithScope); + } + } + function isExcludeScope(scope: Scope): boolean { if (isClassScope(scope)) { return true; @@ -475,7 +502,7 @@ namespace secharmony { return found; } - function getMangled(scope: Scope, localGenerator: INameGenerator): string { + function getMangledLocalName(scope: Scope, localGenerator: INameGenerator): string { let mangled: string = ''; do { mangled = localGenerator.getName()!; diff --git a/arkguard/src/transformers/rename/RenamePropertiesTransformer.ts b/arkguard/src/transformers/rename/RenamePropertiesTransformer.ts index d181c6f0ea..89fa6abb42 100644 --- a/arkguard/src/transformers/rename/RenamePropertiesTransformer.ts +++ b/arkguard/src/transformers/rename/RenamePropertiesTransformer.ts @@ -47,6 +47,7 @@ import type { TypeNode } from 'typescript'; +import { annotationPrefix } from '../../common/type'; import type {IOptions} from '../../configs/IOptions'; import type { INameObfuscationOption } from '../../configs/INameObfuscationOption'; import type {TransformPlugin} from '../TransformPlugin'; @@ -65,6 +66,7 @@ import { globalGenerator, nameCache } from './RenameIdentifierTransformer'; +import { FileUtils } from '../../ArkObfuscator'; import { UpdateMemberMethodName } from '../../utils/NameCacheUtil'; import { PropCollections, UnobfuscationCollections } from '../../utils/CommonCollections'; import { MemoryDottingDefine } from '../../utils/MemoryDottingDefine'; @@ -86,14 +88,14 @@ namespace secharmony { return renamePropertiesFactory; function renamePropertiesFactory(context: TransformationContext): Transformer { - + let currentFileType: string | undefined = undefined; return renamePropertiesTransformer; function renamePropertiesTransformer(node: Node): Node { if (isSourceFile(node) && ArkObfuscator.isKeptCurrentFile) { return node; } - + currentFileType = isSourceFile(node) ? FileUtils.getFileSuffix(node.fileName).ext : undefined; const recordInfo = ArkObfuscator.recordStage(MemoryDottingDefine.PROPERTY_OBFUSCATION); startSingleFileEvent(EventList.PROPERTY_OBFUSCATION, performancePrinter.timeSumPrinter); @@ -115,6 +117,10 @@ namespace secharmony { } function renameProperties(node: Node): Node { + if (NodeUtils.isObjectLiteralInAnnotation(node, currentFileType)) { + return node; + } + if (!NodeUtils.isPropertyNode(node)) { return visitEachChild(node, renameProperties, context); } @@ -204,7 +210,13 @@ namespace secharmony { return node; } - let mangledName: string = getPropertyName(original); + let mangledName: string = original; + let name: string | undefined = original.startsWith(annotationPrefix) ? original.substring(annotationPrefix.length) : undefined; + if (name) { + mangledName = getAnnotationMangledNameWithPrefix(name); + } else { + mangledName = getPropertyMangledName(original); + } if (isStringLiteralLike(node)) { return factory.createStringLiteral(mangledName); @@ -233,7 +245,17 @@ namespace secharmony { return factory.createPrivateIdentifier('#' + mangledName); } - function getPropertyName(original: string): string { + function getPropertyMangledName(original: string): string { + let mangledName: string = getMangledName(original); + return mangledName; + } + + function getAnnotationMangledNameWithPrefix(original: string): string { + let mangledName: string = `${annotationPrefix}${getMangledName(original)}`; + return mangledName; + } + + function getMangledName(original: string): string { const historyName: string = PropCollections.historyMangledTable?.get(original); let mangledName: string = historyName ? historyName : PropCollections.globalMangledTable.get(original); while (!mangledName) { diff --git a/arkguard/src/utils/NodeUtils.ts b/arkguard/src/utils/NodeUtils.ts index 08acca4072..c4701cc0af 100644 --- a/arkguard/src/utils/NodeUtils.ts +++ b/arkguard/src/utils/NodeUtils.ts @@ -13,6 +13,7 @@ * limitations under the License. */ +import { FileUtils } from './FileUtils'; import type { Expression, Identifier, @@ -24,7 +25,8 @@ import type { TransformerFactory, StringLiteralLike, NumericLiteral, - PrivateIdentifier + PrivateIdentifier, + PropertyAccessExpression, } from 'typescript'; import { canHaveModifiers, @@ -38,6 +40,7 @@ import { isClassExpression, isComputedPropertyName, isConstructorDeclaration, + isDecoratorOrAnnotation, isElementAccessExpression, isEnumMember, isGetAccessor, @@ -59,7 +62,8 @@ import { isVariableDeclaration, visitEachChild, isLiteralTypeNode, - isStringLiteralLike + isStringLiteralLike, + isObjectLiteralExpression } from 'typescript'; import { getViewPUClassProperties, @@ -67,7 +71,7 @@ import { isViewPUBasedClass, visitEnumInitializer } from './OhsUtil'; -import { Extension } from '../common/type'; +import { annotationPrefix, Extension } from '../common/type'; import { MergedConfig } from '../initialization/ConfigResolver'; export class NodeUtils { @@ -253,6 +257,36 @@ export class NodeUtils { return initializer && isCallExpression(initializer); } + public static isObjectLiteralInAnnotation(node: Node, currentFileType: string): boolean { + if (!node || !node.parent || !isObjectLiteralExpression(node) || !isCallExpression(node.parent) || !isDecoratorOrAnnotation(node.parent.parent)) { + return false; + } + if (currentFileType === Extension.DETS) { + return true; + } + const expr = node.parent.expression; + let name: string | undefined = undefined; + switch (expr.kind) { + case SyntaxKind.Identifier: + // @Anno({a: 0}), get 'Anno' + name = (expr as Identifier).text; + break; + case SyntaxKind.PropertyAccessExpression: + // @ns.Anno({a: 0}), get 'Anno' + name = (expr as PropertyAccessExpression).name.text; + break; + default: + name = undefined; + } + if (!name) { + return false; + } + if (currentFileType === Extension.TS && name.startsWith(annotationPrefix)) { + return true; + } + return false; + } + public static isDeclarationFile(node: SourceFile): boolean { return node.isDeclarationFile; } diff --git a/arkguard/src/utils/ScopeAnalyzer.ts b/arkguard/src/utils/ScopeAnalyzer.ts index a2f2466039..620758608f 100644 --- a/arkguard/src/utils/ScopeAnalyzer.ts +++ b/arkguard/src/utils/ScopeAnalyzer.ts @@ -17,6 +17,7 @@ import { forEachChild, getModifiers, getOriginalNode, + isAnnotationPropertyDeclaration, isCatchClause, isClassDeclaration, isConstructorDeclaration, @@ -40,6 +41,7 @@ import { } from 'typescript'; import type { + AnnotationDeclaration, BreakOrContinueStatement, CaseBlock, CatchClause, @@ -70,7 +72,7 @@ import type { TypeElement } from 'typescript'; -import { NodeUtils } from './NodeUtils'; +import { hasExportModifier, NodeUtils } from './NodeUtils'; import { isParameterPropertyModifier, isViewPUBasedClass } from './OhsUtil'; import { TypeUtils } from './TypeUtils'; import { endSingleFileEvent, startSingleFileEvent } from '../utils/PrinterUtils'; @@ -284,7 +286,7 @@ namespace secharmony { * @param ast ast tree of a source file * @param checker */ - analyze(ast: SourceFile, checker: TypeChecker, isEnabledExportObfuscation: boolean): void; + analyze(ast: SourceFile, checker: TypeChecker, isEnabledExportObfuscation: boolean, currentFileType: string): void; /** * get root scope of a file @@ -307,6 +309,7 @@ namespace secharmony { let checker: TypeChecker = null; let upperLabel: Label | undefined = undefined; let exportObfuscation: boolean = false; + let fileType: string | undefined = undefined; return { getReservedNames, @@ -315,9 +318,10 @@ namespace secharmony { getScopeOfNode, }; - function analyze(ast: SourceFile, typeChecker: TypeChecker, isEnabledExportObfuscation = false): void { + function analyze(ast: SourceFile, typeChecker: TypeChecker, isEnabledExportObfuscation = false, currentFileType: string): void { checker = typeChecker; exportObfuscation = isEnabledExportObfuscation; + fileType = currentFileType; analyzeScope(ast); } @@ -445,7 +449,10 @@ namespace secharmony { break; case SyntaxKind.Identifier: - analyzeSymbol(node as Identifier); + // skip property in annotationDeclaration + if (!isAnnotationPropertyDeclaration(node.parent)) { + analyzeSymbol(node as Identifier); + } break; case SyntaxKind.TypeAliasDeclaration: @@ -469,7 +476,11 @@ namespace secharmony { break; case SyntaxKind.ObjectLiteralExpression: - analyzeObjectLiteralExpression(node as ObjectLiteralExpression); + // skip prop in annotation, e.g. @Anno({a: 0}) + // here, `a` will not be collected + if (!NodeUtils.isObjectLiteralInAnnotation(node as ObjectLiteralExpression, fileType)) { + analyzeObjectLiteralExpression(node as ObjectLiteralExpression); + } break; case SyntaxKind.ExportSpecifier: @@ -488,6 +499,11 @@ namespace secharmony { analyzeImportEqualsDeclaration(node as ImportEqualsDeclaration); break; + // add symbol of annotationDeclaration into global scope + case SyntaxKind.AnnotationDeclaration: + analyzeAnnotationDeclaration(node as AnnotationDeclaration); + break; + default: forEachChild(node, analyzeScope); break; @@ -1060,6 +1076,18 @@ namespace secharmony { forEachChild(node, analyzeScope); } + function analyzeAnnotationDeclaration(node: AnnotationDeclaration): void { + if (hasExportModifier(node)) { + current.exportNames.add(node.name.text); + root.fileExportNames.add(node.name.text); + } + let sym: Symbol | undefined = getAndRecordSymbolOfIdentifier(checker, node.name); + if (sym) { + current.addDefinition(sym, true); + } + forEachChild(node, analyzeScope); + } + function tryAddNoSymbolIdentifiers(node: Identifier): void { if (!isIdentifier(node)) { return; diff --git a/arkguard/src/utils/TypeUtils.ts b/arkguard/src/utils/TypeUtils.ts index cd143376b6..1c80ffea53 100644 --- a/arkguard/src/utils/TypeUtils.ts +++ b/arkguard/src/utils/TypeUtils.ts @@ -42,7 +42,7 @@ export class TypeUtils { * @param {string} sourceFilePath * @param {string} content - The content in sourceFilePath */ - public static createObfSourceFile(sourceFilePath: string, content: string): SourceFile { + public static createObfSourceFile(sourceFilePath: string, content: string, compilerOptions?: CompilerOptions): SourceFile { const pathOrExtension: PathAndExtension = FileUtils.getFileSuffix(sourceFilePath); const fileSuffix = pathOrExtension.ext; @@ -50,6 +50,10 @@ export class TypeUtils { sourceFilePath = pathOrExtension.path + Extension.TS; } + if (compilerOptions && compilerOptions.etsAnnotationsEnable === true) { + return createSourceFile(sourceFilePath, content, ScriptTarget.ES2015, true, undefined, compilerOptions, true); + } + return createSourceFile(sourceFilePath, content, ScriptTarget.ES2015, true); } diff --git a/arkguard/test/ut/arkobfuscator/ArkObfuscator.spec.ts b/arkguard/test/ut/arkobfuscator/ArkObfuscator.spec.ts index 1d4c9b1bb9..89cba19459 100644 --- a/arkguard/test/ut/arkobfuscator/ArkObfuscator.spec.ts +++ b/arkguard/test/ut/arkobfuscator/ArkObfuscator.spec.ts @@ -260,6 +260,15 @@ class Demo{ } expect(languageSet).to.deep.equal(UnobfuscationCollections.reservedLangForProperty); }); + + it('Tester: test case for enable annotation', function (){ + let configPath = "test/ut/arkobfuscator/iniTestObfConfig.json" + let obfuscator: ArkObfuscator = new ArkObfuscator(); + let config = FileUtils.readFileAsJson(configPath) as IOptions; + obfuscator.init(config); + + expect(config.mAllowEtsAnnotations).to.be.true; + }); }); }); diff --git a/arkguard/test/ut/arkobfuscator/iniTestObfConfig.json b/arkguard/test/ut/arkobfuscator/iniTestObfConfig.json index c4ce5a7e3f..c3373c14e7 100644 --- a/arkguard/test/ut/arkobfuscator/iniTestObfConfig.json +++ b/arkguard/test/ut/arkobfuscator/iniTestObfConfig.json @@ -16,5 +16,6 @@ "mReservedToplevelNames": ["a*", "*shoul?keep*", "func2"] }, "mEnableSourceMap": false, - "mEnableNameCache": false + "mEnableNameCache": false, + "mAllowEtsAnnotations": true } \ No newline at end of file diff --git a/arkguard/test/ut/initialization/Initializer.spec.ts b/arkguard/test/ut/initialization/Initializer.spec.ts index 56ab226bb3..7657a550fe 100644 --- a/arkguard/test/ut/initialization/Initializer.spec.ts +++ b/arkguard/test/ut/initialization/Initializer.spec.ts @@ -29,6 +29,7 @@ import { } from 'mocha'; import { HvigorErrorInfo, + MergedConfig, } from '../../../src/ArkObfuscator'; describe('Tester Cases for .', function () { @@ -74,6 +75,8 @@ const projectConfig = { interface ArkProjectConfig { isBytecodeObfEnabled?: boolean; isArkguardEnabled?: boolean; + allowEtsAnnotations?: boolean; + obfuscationMergedObConfig?: MergedConfig; } describe('test for set arkguard mode property correctly for arkProjectConfig', function () { @@ -100,5 +103,16 @@ describe('test for set arkguard mode property correctly for arkProjectConfig', f expect(arkProjectConfig.isBytecodeObfEnabled).to.be.undefined; expect(arkProjectConfig.isArkguardEnabled).to.be.undefined; }); + + it('should not set enableEtsAnnotation if allowEtsAnnotations is enabled in arkProjectConfig', () => { + const arkProjectConfig: ArkProjectConfig = { + allowEtsAnnotations: true, + obfuscationMergedObConfig: new MergedConfig(), + }; + projectConfig.obfuscationOptions.selfConfig.ruleOptions.enable = true; + projectConfig.obfuscationOptions.selfConfig.ruleOptions.rules = ['./test/testData/obfuscation/Configs/bytecodeObf/arkguard_enable.txt']; + initObfuscationConfig(projectConfig, arkProjectConfig, printObfLogger); + expect(arkProjectConfig.obfuscationMergedObConfig?.options.enableEtsAnnotation).to.be.true; + }); }); }); diff --git a/arkguard/test/ut/transformer/RenameIdentifierTransformer.spec.ts b/arkguard/test/ut/transformer/RenameIdentifierTransformer.spec.ts index 6082c194a3..41856bcf8d 100644 --- a/arkguard/test/ut/transformer/RenameIdentifierTransformer.spec.ts +++ b/arkguard/test/ut/transformer/RenameIdentifierTransformer.spec.ts @@ -617,11 +617,138 @@ describe('Teste Cases for .', function () { const expectContent = `export declare function foo(para: number): void;`; assert.strictEqual(compareStringsIgnoreNewlines(actualContent, expectContent), true); }) + + it('should obfuscate annotationDeclaration when top-level obfuscation is enable', () => { + let options: IOptions = { + 'mNameObfuscation': { + 'mEnable': true, + 'mRenameProperties': false, + 'mReservedProperties': [], + 'mTopLevel': true, + 'mKeepParameterNames': false + }, + 'mAllowEtsAnnotations': true + }; + assert.strictEqual(options !== undefined, true); + const renameIdentifierFactory = secharmony.transformerPlugin.createTransformerFactory(options); + const fileContent = `@interface __$$ETS_ANNOTATION$$__Anno1 {prop1: number = 1}`; + const textWriter = ts.createTextWriter('\n'); + let arkobfuscator = new ArkObfuscatorForTest(); + arkobfuscator.init(options); + const sourceFile: ts.SourceFile = ts.createSourceFile('demo.ts', fileContent, ts.ScriptTarget.ES2015, true, undefined, { + 'etsAnnotationsEnable': true + }, true); + let transformedResult: ts.TransformationResult = ts.transform(sourceFile, [renameIdentifierFactory], {}); + let ast: ts.SourceFile = transformedResult.transformed[0] as ts.SourceFile; + arkobfuscator.createObfsPrinter(ast.isDeclarationFile).writeFile(ast, textWriter, undefined); + const actualContent = textWriter.getText(); + const expectContent = `@interface __$$ETS_ANNOTATION$$__a { + prop1: number = 1; + }`; + assert.strictEqual(compareStringsIgnoreNewlines(actualContent, expectContent), true); + PropCollections.clearPropsCollections(); + }) + + it('should not obfuscate when annotationName is in top-level whitelist', function () { + let options: IOptions = { + 'mNameObfuscation': { + 'mEnable': true, + 'mRenameProperties': false, + 'mReservedProperties': [], + 'mTopLevel': true, + 'mKeepParameterNames': false + }, + 'mAllowEtsAnnotations': true + }; + assert.strictEqual(options !== undefined, true); + PropCollections.reservedProperties.add('Anno1'); + const renameIdentifierFactory = secharmony.transformerPlugin.createTransformerFactory(options); + const fileContent = `@interface __$$ETS_ANNOTATION$$__Anno1 {prop1: number = 1}`; + const textWriter = ts.createTextWriter('\n'); + let arkobfuscator = new ArkObfuscatorForTest(); + arkobfuscator.init(options); + const sourceFile: ts.SourceFile = ts.createSourceFile('demo.ts', fileContent, ts.ScriptTarget.ES2015, true, undefined, { + 'etsAnnotationsEnable': true + }, true); + let transformedResult: ts.TransformationResult = ts.transform(sourceFile, [renameIdentifierFactory], {}); + let ast: ts.SourceFile = transformedResult.transformed[0] as ts.SourceFile; + arkobfuscator.createObfsPrinter(ast.isDeclarationFile).writeFile(ast, textWriter, undefined); + const actualContent = textWriter.getText(); + const expectContent = `@interface __$$ETS_ANNOTATION$$__Anno1 { + prop1: number = 1; + }`; + assert.strictEqual(compareStringsIgnoreNewlines(actualContent, expectContent), true); + PropCollections.clearPropsCollections(); + }) + + it('should not obfuscate when annotationName is exported and not enable export-obfuscation', function () { + let options: IOptions = { + 'mNameObfuscation': { + 'mEnable': true, + 'mRenameProperties': false, + 'mReservedProperties': [], + 'mTopLevel': true, + 'mKeepParameterNames': false + }, + 'mAllowEtsAnnotations': true, + 'mExportObfuscation': false, + }; + assert.strictEqual(options !== undefined, true); + const renameIdentifierFactory = secharmony.transformerPlugin.createTransformerFactory(options); + const fileContent = `export @interface __$$ETS_ANNOTATION$$__Anno1 {prop1: number = 1}`; + const textWriter = ts.createTextWriter('\n'); + let arkobfuscator = new ArkObfuscatorForTest(); + arkobfuscator.init(options); + const sourceFile: ts.SourceFile = ts.createSourceFile('demo.ts', fileContent, ts.ScriptTarget.ES2015, true, undefined, { + 'etsAnnotationsEnable': true + }, true); + let transformedResult: ts.TransformationResult = ts.transform(sourceFile, [renameIdentifierFactory], {}); + let ast: ts.SourceFile = transformedResult.transformed[0] as ts.SourceFile; + arkobfuscator.createObfsPrinter(ast.isDeclarationFile).writeFile(ast, textWriter, undefined); + const actualContent = textWriter.getText(); + const expectContent = `export @interface __$$ETS_ANNOTATION$$__Anno1 { + prop1: number = 1; + }`; + assert.strictEqual(compareStringsIgnoreNewlines(actualContent, expectContent), true); + PropCollections.clearPropsCollections(); + }) + + it('should obfuscate when annotationName is exported and enable export-obfuscation', function () { + let options: IOptions = { + 'mNameObfuscation': { + 'mEnable': true, + 'mRenameProperties': false, + 'mReservedProperties': [], + 'mTopLevel': true, + 'mKeepParameterNames': false + }, + 'mAllowEtsAnnotations': true, + 'mExportObfuscation': true, + }; + assert.strictEqual(options !== undefined, true); + const renameIdentifierFactory = secharmony.transformerPlugin.createTransformerFactory(options); + const fileContent = `export @interface __$$ETS_ANNOTATION$$__Anno1 {prop1: number = 1}`; + const textWriter = ts.createTextWriter('\n'); + let arkobfuscator = new ArkObfuscatorForTest(); + arkobfuscator.init(options); + const sourceFile: ts.SourceFile = ts.createSourceFile('demo.ts', fileContent, ts.ScriptTarget.ES2015, true, undefined, { + 'etsAnnotationsEnable': true + }, true); + let transformedResult: ts.TransformationResult = ts.transform(sourceFile, [renameIdentifierFactory], {}); + let ast: ts.SourceFile = transformedResult.transformed[0] as ts.SourceFile; + arkobfuscator.createObfsPrinter(ast.isDeclarationFile).writeFile(ast, textWriter, undefined); + const actualContent = textWriter.getText(); + const expectContent = `export @interface __$$ETS_ANNOTATION$$__a { + prop1: number = 1; + }`; + assert.strictEqual(compareStringsIgnoreNewlines(actualContent, expectContent), true); + PropCollections.clearPropsCollections(); + }) }) }) }) -function compareStringsIgnoreNewlines(str1: string, str2: string): boolean { +export function compareStringsIgnoreNewlines(str1: string, str2: string): boolean { const normalize = (str: string) => str.replace(/[\n\r\s]+/g, ''); return normalize(str1) === normalize(str2); } \ No newline at end of file diff --git a/arkguard/test/ut/transformer/RenamePropertiesTransformer.spec.ts b/arkguard/test/ut/transformer/RenamePropertiesTransformer.spec.ts index 24f8a3f516..213e75d667 100644 --- a/arkguard/test/ut/transformer/RenamePropertiesTransformer.spec.ts +++ b/arkguard/test/ut/transformer/RenamePropertiesTransformer.spec.ts @@ -33,6 +33,9 @@ import ts, { } from 'typescript'; import secharmony from '../../../src/transformers/rename/RenamePropertiesTransformer'; import { ArkObfuscator } from '../../../src/ArkObfuscator'; +import { compareStringsIgnoreNewlines } from './RenameIdentifierTransformer.spec'; +import { ArkObfuscatorForTest } from '../../../src/ArkObfuscatorForTest' +import { PropCollections } from '../../../src/utils/CommonCollections'; describe('Tester Cases for .', function () { @@ -202,5 +205,87 @@ describe('Tester Cases for .', function () { expect(((node.indexType as UnionTypeNode).types[0] as LiteralTypeNode).literal).to.be.equal(((parentNodes.indexType as UnionTypeNode).types[0] as LiteralTypeNode).literal); expect(((node.indexType as UnionTypeNode).types[1] as LiteralTypeNode).literal).to.be.equal(((parentNodes.indexType as UnionTypeNode).types[1] as LiteralTypeNode).literal); }); + + it('should not rename property in annotation decl and callsite when using prop', function () { + ArkObfuscator.isKeptCurrentFile = false; + options = { + mNameObfuscation: { + mEnable: true, + mNameGeneratorType: 1, + mRenameProperties: true, + mKeepStringProperty: false, + mReservedProperties: [] + }, + }; + const renameIdentifierFactory = secharmony.transformerPlugin.createTransformerFactory(options as IOptions); + const fileContent = ` + @interface __$$ETS_ANNOTATION$$__Anno1 { + prop1: number = 1; + } + @__$$ETS_ANNOTATION$$__Anno1({prop: 1}) + class myClass1 { + prop1: number = 1; + } + let var1: myClass1 = new myClass1(); + let var2 = var1.prop1; + `; + const textWriter = ts.createTextWriter('\n'); + let arkobfuscator = new ArkObfuscatorForTest(); + arkobfuscator.init(options); + const sourceFile: ts.SourceFile = ts.createSourceFile('demo.ts', fileContent, ts.ScriptTarget.ES2015, true, undefined, { + 'etsAnnotationsEnable': true + }, true); + let transformedResult: ts.TransformationResult = ts.transform(sourceFile, [renameIdentifierFactory], {}); + let ast: ts.SourceFile = transformedResult.transformed[0] as ts.SourceFile; + arkobfuscator.createObfsPrinter(ast.isDeclarationFile).writeFile(ast, textWriter, undefined); + const actualContent = textWriter.getText(); + const expectContent = ` + @interface __$$ETS_ANNOTATION$$__Anno1 { + prop1: number = 1; + } + @__$$ETS_ANNOTATION$$__Anno1({ prop: 1 }) + class myClass1 { + g: number = 1; + } + let var1: myClass1 = new myClass1(); + let var2 = var1.g; + `; + assert.strictEqual(compareStringsIgnoreNewlines(actualContent, expectContent), true); + PropCollections.clearPropsCollections(); + }); + + it('should rename annotation called as prop when using prop obfuscation', function () { + ArkObfuscator.isKeptCurrentFile = false; + options = { + mNameObfuscation: { + mEnable: true, + mNameGeneratorType: 1, + mRenameProperties: true, + mKeepStringProperty: false, + mReservedProperties: [] + }, + }; + const renameIdentifierFactory = secharmony.transformerPlugin.createTransformerFactory(options as IOptions); + const fileContent = ` + @ns.__$$ETS_ANNOTATION$$__Anno1({prop: 1}) + class myClass1 {} + `; + const textWriter = ts.createTextWriter('\n'); + let arkobfuscator = new ArkObfuscatorForTest(); + arkobfuscator.init(options); + const sourceFile: ts.SourceFile = ts.createSourceFile('demo.ts', fileContent, ts.ScriptTarget.ES2015, true, undefined, { + 'etsAnnotationsEnable': true + }, true); + let transformedResult: ts.TransformationResult = ts.transform(sourceFile, [renameIdentifierFactory], {}); + let ast: ts.SourceFile = transformedResult.transformed[0] as ts.SourceFile; + arkobfuscator.createObfsPrinter(ast.isDeclarationFile).writeFile(ast, textWriter, undefined); + const actualContent = textWriter.getText(); + const expectContent = ` + @ns.__$$ETS_ANNOTATION$$__g({ prop: 1 }) + class myClass1 {} + `; + assert.strictEqual(compareStringsIgnoreNewlines(actualContent, expectContent), true); + PropCollections.clearPropsCollections(); + }); }); }); diff --git a/arkguard/test/ut/utils/KeepParameterUtils.spec.ts b/arkguard/test/ut/utils/KeepParameterUtils.spec.ts index 9c1e22f976..5942689068 100644 --- a/arkguard/test/ut/utils/KeepParameterUtils.spec.ts +++ b/arkguard/test/ut/utils/KeepParameterUtils.spec.ts @@ -212,8 +212,8 @@ describe('Tester Cases for shouldKeepParameter.', function () { it('Tester 2-10: When node is method and method name is not kept, shouldKeepParameter returns false', function () { let content = `declare class A { - constructor(para1: number); - method(para2: number): void; + constructor(para11: number); + method1(para12: number): void; }`; const ast = ts.createSourceFile(path, content, ts.ScriptTarget.ES2015, true); let method: ts.MethodDeclaration = (ast.statements[0] as ts.ClassDeclaration).members[1] as ts.MethodDeclaration; diff --git a/arkguard/test/ut/utils/NodeUtils.spec.ts b/arkguard/test/ut/utils/NodeUtils.spec.ts index ff2672b37e..5411595ce4 100644 --- a/arkguard/test/ut/utils/NodeUtils.spec.ts +++ b/arkguard/test/ut/utils/NodeUtils.spec.ts @@ -581,4 +581,47 @@ describe('test for NodeUtils', function () { expect(hasExportModifier(sourceFile.statements[0])).to.be.true; }) }) + + describe('test for isObjectLiteralInAnnotation', function () { + it('should return false when node is not ObjectLiteral', function () { + const node = ts.factory.createObjectBindingPattern([]); + expect(NodeUtils.isObjectLiteralInAnnotation(node, '.d.ets')).to.be.false; + }) + it('should return true if annotation is in .d.ets files', function () { + const node = ts.factory.createObjectLiteralExpression( + [ts.factory.createPropertyAssignment( + ts.factory.createIdentifier("a"), + ts.factory.createNumericLiteral("1") + )], + false + ); + const expr = ts.factory.createCallExpression( + ts.factory.createIdentifier("Anno1"), + undefined, + [node] + ); + (node as Mutable).parent = expr; + const decorator = ts.factory.createDecorator(expr); + (expr as Mutable).parent = decorator; + expect(NodeUtils.isObjectLiteralInAnnotation(node, '.d.ets')).to.be.true; + }) + it('should return true if annotation is in .ts files and with annotationPrefix', function () { + const node = ts.factory.createObjectLiteralExpression( + [ts.factory.createPropertyAssignment( + ts.factory.createIdentifier("a"), + ts.factory.createNumericLiteral("1") + )], + false + ); + const expr = ts.factory.createCallExpression( + ts.factory.createIdentifier("__$$ETS_ANNOTATION$$__Anno1"), + undefined, + [node] + ); + (node as Mutable).parent = expr; + const decorator = ts.factory.createDecorator(expr); + (expr as Mutable).parent = decorator; + expect(NodeUtils.isObjectLiteralInAnnotation(node, '.ts')).to.be.true; + }) +}) }) \ No newline at end of file diff --git a/arkguard/test/ut/utils/ScopeAnalyzer.spec.ts b/arkguard/test/ut/utils/ScopeAnalyzer.spec.ts index ed10c4ec26..a9be991b62 100644 --- a/arkguard/test/ut/utils/ScopeAnalyzer.spec.ts +++ b/arkguard/test/ut/utils/ScopeAnalyzer.spec.ts @@ -317,7 +317,7 @@ describe('ScopeAnalyzer ut', function () { sourceFile = createSourceFile(newFilePath, fileContent, ScriptTarget.ES2015, true); checker = TypeUtils.createChecker(sourceFile); scopeManager = createScopeManager(); - scopeManager.analyze(sourceFile, checker, false); + scopeManager.analyze(sourceFile, checker, false, newFilePath); } describe('analyze', function () { @@ -456,7 +456,7 @@ describe('ScopeAnalyzer ut', function () { let sourceFile = createSourceFile(filePath, fileContent, ScriptTarget.ES2015, true); let checker = TypeUtils.createChecker(sourceFile); let scopeManager = createScopeManager(); - scopeManager.analyze(sourceFile, checker, false); + scopeManager.analyze(sourceFile, checker, false, filePath); const functionDeclaration = sourceFile.statements[0] as FunctionDeclaration; const parameter = functionDeclaration.parameters[0] as ParameterDeclaration; @@ -472,7 +472,7 @@ describe('ScopeAnalyzer ut', function () { let sourceFile = createSourceFile(filePath, fileContent, ScriptTarget.ES2015, true); let checker = TypeUtils.createChecker(sourceFile); let scopeManager = createScopeManager(); - scopeManager.analyze(sourceFile, checker, false); + scopeManager.analyze(sourceFile, checker, false, filePath); it('getReservedNames', function () { const reservedNames = scopeManager.getReservedNames(); assert.strictEqual(reservedNames.size === 0, true); @@ -542,7 +542,7 @@ describe('ScopeAnalyzer ut', function () { let sourceFile = createSourceFile(filePath, fileContent, ScriptTarget.ES2015, true); let checker = TypeUtils.createChecker(sourceFile); let scopeManager = createScopeManager(); - scopeManager.analyze(sourceFile, checker, false); + scopeManager.analyze(sourceFile, checker, false, filePath); it('getReservedNames', function () { const reservedNames = scopeManager.getReservedNames(); @@ -581,13 +581,13 @@ describe('ScopeAnalyzer ut', function () { let scopeManager = createScopeManager(); it('exportObfuscation is false', function () { - scopeManager.analyze(sourceFile, checker, false); + scopeManager.analyze(sourceFile, checker, false, filePath); const rootScope = scopeManager.getRootScope(); assert.deepEqual(rootScope.defs.size, 0); }); it('exportObfuscation is true', function () { - scopeManager.analyze(sourceFile, checker, true); + scopeManager.analyze(sourceFile, checker, true, filePath); const rootScope = scopeManager.getRootScope(); assert.strictEqual(rootScope.defs.size, 1); }); @@ -623,7 +623,7 @@ describe('ScopeAnalyzer ut', function () { let sourceFile = createSourceFile(filePath, fileContent, ScriptTarget.ES2015, true); let checker = TypeUtils.createChecker(sourceFile); let scopeManager = createScopeManager(); - scopeManager.analyze(sourceFile, checker, false); + scopeManager.analyze(sourceFile, checker, false, filePath); it('getReservedNames', function () { const reservedNames = scopeManager.getReservedNames(); @@ -666,7 +666,7 @@ describe('ScopeAnalyzer ut', function () { let sourceFile = createSourceFile(filePath, fileContent, ScriptTarget.ES2015, true); let checker = TypeUtils.createChecker(sourceFile); let scopeManager = createScopeManager(); - scopeManager.analyze(sourceFile, checker, false); + scopeManager.analyze(sourceFile, checker, false, filePath); it('getReservedNames', function () { const reservedNames = scopeManager.getReservedNames(); @@ -701,7 +701,7 @@ describe('ScopeAnalyzer ut', function () { let sourceFile = createSourceFile(filePath, fileContent, ScriptTarget.ES2015, true); let checker = TypeUtils.createChecker(sourceFile); let scopeManager = createScopeManager(); - scopeManager.analyze(sourceFile, checker, false); + scopeManager.analyze(sourceFile, checker, false, filePath); it('getReservedNames', function () { const reservedNames = scopeManager.getReservedNames(); diff --git a/es2panda/test/compiler/js/array-literal-1-expected.txt b/es2panda/test/compiler/js/array-literal-1-expected.txt deleted file mode 100644 index 1a9c6f0aeb..0000000000 --- a/es2panda/test/compiler/js/array-literal-1-expected.txt +++ /dev/null @@ -1 +0,0 @@ -TypeError: is not callable diff --git a/es2panda/test/compiler/js/array-literal-1.js b/es2panda/test/compiler/js/array-literal-1.js deleted file mode 100644 index 419aba9f26..0000000000 --- a/es2panda/test/compiler/js/array-literal-1.js +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2024 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -try { - Object.defineProperty(Array.prototype, "0", { - get:() => {print("get 0")}, - set: v19 => {print("set 0")} - }); - let arr =[,,,] - arr`` -} catch (e) { - print(e) -} -- Gitee From 28faf84ec87c6825d6df08da9c457a5a7328747b Mon Sep 17 00:00:00 2001 From: zhongmingwei Date: Sun, 18 May 2025 15:42:33 +0800 Subject: [PATCH 163/268] Recover array-literal-1 testcase Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC8JB9 Description: Recover array-literal-1.js testcase and fix expected. Signed-off-by: zhongmingwei Change-Id: Ie8d0799ddf6b95edc3fbf8b72254ab448a858f69 --- .../compiler/js/array-literal-1-expected.txt | 2 ++ es2panda/test/compiler/js/array-literal-1.js | 24 +++++++++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 es2panda/test/compiler/js/array-literal-1-expected.txt create mode 100644 es2panda/test/compiler/js/array-literal-1.js diff --git a/es2panda/test/compiler/js/array-literal-1-expected.txt b/es2panda/test/compiler/js/array-literal-1-expected.txt new file mode 100644 index 0000000000..4b5e7278e7 --- /dev/null +++ b/es2panda/test/compiler/js/array-literal-1-expected.txt @@ -0,0 +1,2 @@ +get 0 +TypeError: ,, is not callable diff --git a/es2panda/test/compiler/js/array-literal-1.js b/es2panda/test/compiler/js/array-literal-1.js new file mode 100644 index 0000000000..419aba9f26 --- /dev/null +++ b/es2panda/test/compiler/js/array-literal-1.js @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +try { + Object.defineProperty(Array.prototype, "0", { + get:() => {print("get 0")}, + set: v19 => {print("set 0")} + }); + let arr =[,,,] + arr`` +} catch (e) { + print(e) +} -- Gitee From 8094416437e2f179987c9c8e89994aad210fc891 Mon Sep 17 00:00:00 2001 From: Denis Slynko Date: Thu, 17 Apr 2025 09:31:04 +0300 Subject: [PATCH 164/268] [PT] Reenable debugger tests Issue: https://gitee.com/openharmony/arkcompiler_runtime_core/issues/IC8NMZ Signed-off-by: jiachong --- ets2panda/compiler/core/ETSemitter.cpp | 17 +++++++++++++++++ ets2panda/compiler/core/ETSemitter.h | 1 + ets2panda/compiler/core/JSemitter.cpp | 13 +++++++++++++ ets2panda/compiler/core/JSemitter.h | 3 ++- ets2panda/compiler/core/emitter.cpp | 13 ------------- ets2panda/compiler/core/emitter.h | 2 +- 6 files changed, 34 insertions(+), 15 deletions(-) diff --git a/ets2panda/compiler/core/ETSemitter.cpp b/ets2panda/compiler/core/ETSemitter.cpp index 64ae2b8a6a..0237060a42 100644 --- a/ets2panda/compiler/core/ETSemitter.cpp +++ b/ets2panda/compiler/core/ETSemitter.cpp @@ -176,6 +176,23 @@ void ETSFunctionEmitter::GenVariableSignature(pandasm::debuginfo::LocalVariable variableDebug.signatureType = Signatures::ANY; } +void ETSFunctionEmitter::GenSourceFileDebugInfo(pandasm::Function *func) +{ + func->sourceFile = std::string {Cg()->VarBinder()->Program()->RelativeFilePath()}; + + if (!Cg()->IsDebug()) { + return; + } + + ES2PANDA_ASSERT(Cg()->RootNode()->IsScriptFunction()); + auto *fn = Cg()->RootNode()->AsScriptFunction(); + bool isInitMethod = fn->Id()->Name().Is(compiler::Signatures::INIT_METHOD); + // Write source code of whole file into debug-info of init method + if (isInitMethod) { + func->sourceCode = SourceCode().Utf8(); + } +} + void ETSFunctionEmitter::GenFunctionAnnotations([[maybe_unused]] pandasm::Function *func) {} static pandasm::Function GenExternalFunction(checker::Signature *signature, bool isCtor) diff --git a/ets2panda/compiler/core/ETSemitter.h b/ets2panda/compiler/core/ETSemitter.h index 937d81276a..f47d2af046 100644 --- a/ets2panda/compiler/core/ETSemitter.h +++ b/ets2panda/compiler/core/ETSemitter.h @@ -68,6 +68,7 @@ protected: void GenFunctionAnnotations(pandasm::Function *func) override; void GenVariableSignature(pandasm::debuginfo::LocalVariable &variableDebug, varbinder::LocalVariable *variable) const override; + void GenSourceFileDebugInfo(pandasm::Function *func) override; }; class ETSEmitter : public Emitter { diff --git a/ets2panda/compiler/core/JSemitter.cpp b/ets2panda/compiler/core/JSemitter.cpp index 8c4925497d..9be5a0b5c4 100644 --- a/ets2panda/compiler/core/JSemitter.cpp +++ b/ets2panda/compiler/core/JSemitter.cpp @@ -51,6 +51,19 @@ void JSFunctionEmitter::GenVariableSignature(pandasm::debuginfo::LocalVariable & variableDebug.signatureType = "any"; } +void JSFunctionEmitter::GenSourceFileDebugInfo(pandasm::Function *func) +{ + func->sourceFile = std::string {Cg()->VarBinder()->Program()->RelativeFilePath()}; + + if (!Cg()->IsDebug()) { + return; + } + + if (Cg()->RootNode()->IsProgram()) { + func->sourceCode = SourceCode().EscapeSymbol(); + } +} + void JSFunctionEmitter::GenFunctionAnnotations(pandasm::Function *func) { pandasm::AnnotationData funcAnnotationData("_ESAnnotation"); diff --git a/ets2panda/compiler/core/JSemitter.h b/ets2panda/compiler/core/JSemitter.h index c49827b99c..72b8577c06 100644 --- a/ets2panda/compiler/core/JSemitter.h +++ b/ets2panda/compiler/core/JSemitter.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 - 2024 Huawei Device Co., Ltd. + * Copyright (c) 2021 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -38,6 +38,7 @@ protected: void GenFunctionAnnotations(pandasm::Function *func) override; void GenVariableSignature(pandasm::debuginfo::LocalVariable &variableDebug, varbinder::LocalVariable *variable) const override; + void GenSourceFileDebugInfo(pandasm::Function *func) override; }; class JSEmitter : public Emitter { diff --git a/ets2panda/compiler/core/emitter.cpp b/ets2panda/compiler/core/emitter.cpp index 040837e9bd..95b7d45aee 100644 --- a/ets2panda/compiler/core/emitter.cpp +++ b/ets2panda/compiler/core/emitter.cpp @@ -280,19 +280,6 @@ void FunctionEmitter::GenFunctionCatchTables(pandasm::Function *func) } } -void FunctionEmitter::GenSourceFileDebugInfo(pandasm::Function *func) -{ - func->sourceFile = std::string {cg_->VarBinder()->Program()->RelativeFilePath()}; - - if (!cg_->IsDebug()) { - return; - } - - if (cg_->RootNode()->IsProgram()) { - func->sourceCode = SourceCode().EscapeSymbol(); - } -} - static void GenLocalVariableInfo(pandasm::debuginfo::LocalVariable &variableDebug, varbinder::Variable *var, std::tuple info, ScriptExtension extension) { diff --git a/ets2panda/compiler/core/emitter.h b/ets2panda/compiler/core/emitter.h index aa196db845..84049be833 100644 --- a/ets2panda/compiler/core/emitter.h +++ b/ets2panda/compiler/core/emitter.h @@ -74,13 +74,13 @@ protected: virtual void GenFunctionAnnotations(pandasm::Function *func) = 0; virtual void GenVariableSignature(pandasm::debuginfo::LocalVariable &variableDebug, varbinder::LocalVariable *variable) const = 0; + virtual void GenSourceFileDebugInfo(pandasm::Function *func) = 0; void GenInstructionDebugInfo(const IRNode *ins, ark::pandasm::Ins *pandaIns); void GenFunctionInstructions(pandasm::Function *func); void GenScopeVariableInfo(pandasm::Function *func, const varbinder::Scope *scope) const; void GenScopeVariableInfoEnd(pandasm::Function *func, const varbinder::Scope *scope, uint32_t count, uint32_t scopeStart, const VariablesStartsMap &starts) const; - void GenSourceFileDebugInfo(pandasm::Function *func); void GenFunctionCatchTables(ark::pandasm::Function *func); void GenVariablesDebugInfo(pandasm::Function *func); util::StringView SourceCode() const; -- Gitee From 83a7e9519ca3a68fd3a091075b8cf10d3fa267e6 Mon Sep 17 00:00:00 2001 From: xiaopeiyang Date: Tue, 6 May 2025 20:21:20 +0800 Subject: [PATCH 165/268] Enable atKeep for annotation Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC5TGV Signed-off-by: xiaopeiyang Change-Id: I8d436eac403e11844387fe475f1dfad9e38dc9ae --- arkguard/src/common/ApiExtractor.ts | 15 ++++++- arkguard/test/ut/utils/ApiExtractor.spec.ts | 16 +++++++ .../atKeepAnnotation.ets | 44 +++++++++++++++++++ 3 files changed, 74 insertions(+), 1 deletion(-) create mode 100644 arkguard/test/ut/utils/apiTest_visitAtKeepNames/atKeepAnnotation.ets diff --git a/arkguard/src/common/ApiExtractor.ts b/arkguard/src/common/ApiExtractor.ts index 12e46774cd..e286f7d418 100644 --- a/arkguard/src/common/ApiExtractor.ts +++ b/arkguard/src/common/ApiExtractor.ts @@ -14,8 +14,10 @@ */ import type { + AnnotationDeclaration, ClassDeclaration, CommentRange, + CompilerOptions, Decorator, ElementAccessExpression, EnumDeclaration, @@ -146,7 +148,8 @@ export namespace ApiExtractor { | FunctionDeclaration | ModuleDeclaration | VariableDeclaration - | TypeAliasDeclaration; + | TypeAliasDeclaration + | AnnotationDeclaration; const KEEP_SYMBOL = '//@KeepSymbol'; const KEEP_AS_CONSUMER = '//@KeepAsConsumer'; @@ -1199,6 +1202,9 @@ export namespace ApiExtractor { case SyntaxKind.ModuleDeclaration: collectModuleDeclaration(node as ModuleDeclaration, sourceFile); break; + case SyntaxKind.AnnotationDeclaration: + collectAnnotationDeclaration(node as AnnotationDeclaration, sourceFile); + break; } forEachChild(node, child => collectNamesWithAtKeep(child, sourceFile)); } @@ -1435,6 +1441,13 @@ export namespace ApiExtractor { } } + function collectAnnotationDeclaration(node: AnnotationDeclaration, sourceFile: SourceFile): void { + const atKeepType: AtKeepType = getAtKeepType(node, sourceFile); + const isToplevel: boolean = isSourceFile(node.parent); + const isExported: boolean = hasExportModifier(node); + collectToplevelOrExportedNames(node, isToplevel, isExported, atKeepType); + } + function getAtKeepType(node: Node, sourceFile: SourceFile): AtKeepType { const ranges: CommentRange[] | undefined = getLeadingCommentRangesOfNode(node, sourceFile); let atKeepType: AtKeepType = AtKeepType.None; diff --git a/arkguard/test/ut/utils/ApiExtractor.spec.ts b/arkguard/test/ut/utils/ApiExtractor.spec.ts index f293d23df6..628598b86b 100644 --- a/arkguard/test/ut/utils/ApiExtractor.spec.ts +++ b/arkguard/test/ut/utils/ApiExtractor.spec.ts @@ -1091,6 +1091,22 @@ describe('test for ApiExtractor', function () { expect(AtKeepCollections.keepAsConsumer.propertyNames.has('globalFunc04')).to.be.true; expect(AtKeepCollections.keepAsConsumer.propertyNames.has('globalMyClass04')).to.be.true; }) + it('should collect atKeep names from annotation declarations if enabled', function () { + let filePath: string = 'test/ut/utils/apiTest_visitAtKeepNames/atKeepAnnotation.ets'; + AtKeepCollections.clear(); + scanProjectConfig.mEnableAtKeep = true; + collectApi(filePath, ApiExtractor.ApiType.PROJECT); + expect(AtKeepCollections.keepSymbol.globalNames.size).to.be.equal(2); + expect(AtKeepCollections.keepSymbol.globalNames.has('MyAnnotation01')).to.be.true; + expect(AtKeepCollections.keepSymbol.globalNames.has('MyAnnotation02')).to.be.true; + expect(AtKeepCollections.keepSymbol.propertyNames.size).to.be.equal(1); + expect(AtKeepCollections.keepSymbol.propertyNames.has('MyAnnotation02')).to.be.true; + expect(AtKeepCollections.keepAsConsumer.globalNames.size).to.be.equal(2); + expect(AtKeepCollections.keepAsConsumer.globalNames.has('MyAnnotation04')).to.be.true; + expect(AtKeepCollections.keepAsConsumer.globalNames.has('MyAnnotation05')).to.be.true; + expect(AtKeepCollections.keepAsConsumer.propertyNames.size).to.be.equal(1); + expect(AtKeepCollections.keepAsConsumer.globalNames.has('MyAnnotation05')).to.be.true; + }) it('should collect atKeep names from .ets', function () { let filePath: string = 'test/ut/utils/apiTest_visitAtKeepNames/atKeepTest01.ets'; AtKeepCollections.clear(); diff --git a/arkguard/test/ut/utils/apiTest_visitAtKeepNames/atKeepAnnotation.ets b/arkguard/test/ut/utils/apiTest_visitAtKeepNames/atKeepAnnotation.ets new file mode 100644 index 0000000000..c78baa7d21 --- /dev/null +++ b/arkguard/test/ut/utils/apiTest_visitAtKeepNames/atKeepAnnotation.ets @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// @KeepSymbol +@interface MyAnnotation01 { + authorName: string; +} + +// @KeepSymbol +export @interface MyAnnotation02 { + authorName: string; +} + +@interface MyAnnotation03 { + // @KeepSymbol + authorName: string; +} + +// @KeepAsConsumer +@interface MyAnnotation04 { + authorName: string; +} + +// @KeepAsConsumer +export @interface MyAnnotation05 { + authorName: string; +} + +@interface MyAnnotation06 { + // @KeepAsConsumer + authorName: string; +} \ No newline at end of file -- Gitee From 71524f4c1cb0be52930c750cceb423131cc0c6f6 Mon Sep 17 00:00:00 2001 From: liyue Date: Fri, 9 May 2025 10:30:14 +0800 Subject: [PATCH 166/268] Fix line numbers of class property inits Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC6HT0 Signed-off-by: liyue Change-Id: If224b09b092f141f22337a04e7212070b71ce2d5 --- es2panda/parser/transformer/transformer.cpp | 36 ++++++++++---- ...s-auto-accessor-1-transformed-expected.txt | 24 +++++----- ...s-auto-accessor-2-transformed-expected.txt | 24 +++++----- ...lass-constructor1-transformed-expected.txt | 24 +++++----- ...lass-constructor2-transformed-expected.txt | 24 +++++----- ...lass-constructor3-transformed-expected.txt | 24 +++++----- ...lass-constructor4-transformed-expected.txt | 24 +++++----- ...class-decorator-1-transformed-expected.txt | 8 ++-- ...lass-constructor1-transformed-expected.txt | 48 +++++++++---------- .../test-decorator-1-transformed-expected.txt | 8 ++-- ...hCase-statement-1-transformed-expected.txt | 8 ++-- ...-export-classes-1-transformed-expected.txt | 8 ++-- ...-export-classes-2-transformed-expected.txt | 8 ++-- 13 files changed, 144 insertions(+), 124 deletions(-) diff --git a/es2panda/parser/transformer/transformer.cpp b/es2panda/parser/transformer/transformer.cpp index f41498a83f..ff06eafee3 100644 --- a/es2panda/parser/transformer/transformer.cpp +++ b/es2panda/parser/transformer/transformer.cpp @@ -697,15 +697,22 @@ std::vector Transformer::VisitInstanceProperty(ir::Cl ir::MemberExpression *left = nullptr; auto *member = GetClassMemberName(it->Key(), it->IsComputed(), it, false); + auto thisExpression = AllocNode(); + // Set the range of the 'this' expression to the property key's range + // for accurate debug to the original field. (e.g., the "prop" in '"prop" = 1'). + thisExpression->SetRange(member->Range()); if (member->IsIdentifier() && !it->IsComputed()) { - left = AllocNode(AllocNode(), member, + left = AllocNode(thisExpression, member, ir::MemberExpression::MemberExpressionKind::PROPERTY_ACCESS, false, false); } else { - left = AllocNode(AllocNode(), member, + left = AllocNode(thisExpression, member, ir::MemberExpression::MemberExpressionKind::ELEMENT_ACCESS, true, false); } + // Set the range of the property access expression (e.g., this["prop"] or this.prop) + // to the property key's range for accurate debug. + left->SetRange(member->Range()); auto assignment = AllocNode(left, it->Value(), lexer::TokenType::PUNCTUATOR_SUBSTITUTION); @@ -1558,20 +1565,33 @@ ir::Expression *Transformer::GetClassMemberName(ir::Expression *key, bool isComp { if (isComputed) { auto name = GetComputedPropertyBinding(node); - return AllocNode(name); + auto *ident = AllocNode(name); + ident->SetRange(key->Range()); + return ident; } if (key->IsIdentifier()) { if (inDecorator) { - return AllocNode(key->AsIdentifier()->Name()); + auto *strLiteral = AllocNode(key->AsIdentifier()->Name()); + strLiteral->SetRange(key->AsIdentifier()->Range()); + return strLiteral; } else { - return AllocNode(key->AsIdentifier()->Name()); + auto *ident = AllocNode(key->AsIdentifier()->Name()); + ident->SetRange(key->AsIdentifier()->Range()); + return ident; } } else if (key->IsStringLiteral()) { - return AllocNode(key->AsStringLiteral()->Str()); + auto *strLiteral = AllocNode(key->AsStringLiteral()->Str()); + strLiteral->SetRange(key->AsStringLiteral()->Range()); + return strLiteral; } else if (key->IsNumberLiteral()) { - return AllocNode(key->AsNumberLiteral()->Number(), key->AsNumberLiteral()->Str()); + auto *numLiteral = AllocNode(key->AsNumberLiteral()->Number(), + key->AsNumberLiteral()->Str()); + numLiteral->SetRange(key->AsNumberLiteral()->Range()); + return numLiteral; } else if (key->IsBigIntLiteral()) { - return AllocNode(key->AsBigIntLiteral()->Str()); + auto *bigIntLiteral = AllocNode(key->AsBigIntLiteral()->Str()); + bigIntLiteral->SetRange(key->AsBigIntLiteral()->Range()); + return bigIntLiteral; } UNREACHABLE(); return nullptr; diff --git a/es2panda/test/parser/ts/transformed_cases/test-class-auto-accessor-1-transformed-expected.txt b/es2panda/test/parser/ts/transformed_cases/test-class-auto-accessor-1-transformed-expected.txt index 5b64b2d042..58587ab764 100644 --- a/es2panda/test/parser/ts/transformed_cases/test-class-auto-accessor-1-transformed-expected.txt +++ b/es2panda/test/parser/ts/transformed_cases/test-class-auto-accessor-1-transformed-expected.txt @@ -63,12 +63,12 @@ "type": "ThisExpression", "loc": { "start": { - "line": 1, - "column": 1 + "line": 18, + "column": 14 }, "end": { - "line": 1, - "column": 1 + "line": 18, + "column": 20 } } }, @@ -77,12 +77,12 @@ "name": "###A#auto_accessor_storage#1", "loc": { "start": { - "line": 1, - "column": 1 + "line": 18, + "column": 14 }, "end": { - "line": 1, - "column": 1 + "line": 18, + "column": 20 } } }, @@ -90,12 +90,12 @@ "optional": false, "loc": { "start": { - "line": 1, - "column": 1 + "line": 18, + "column": 14 }, "end": { - "line": 1, - "column": 1 + "line": 18, + "column": 20 } } }, diff --git a/es2panda/test/parser/ts/transformed_cases/test-class-auto-accessor-2-transformed-expected.txt b/es2panda/test/parser/ts/transformed_cases/test-class-auto-accessor-2-transformed-expected.txt index dc2bdf7811..027f8933cd 100644 --- a/es2panda/test/parser/ts/transformed_cases/test-class-auto-accessor-2-transformed-expected.txt +++ b/es2panda/test/parser/ts/transformed_cases/test-class-auto-accessor-2-transformed-expected.txt @@ -164,12 +164,12 @@ "type": "ThisExpression", "loc": { "start": { - "line": 1, - "column": 1 + "line": 19, + "column": 15 }, "end": { - "line": 1, - "column": 1 + "line": 19, + "column": 27 } } }, @@ -178,12 +178,12 @@ "name": "###Test#auto_accessor_storage#1", "loc": { "start": { - "line": 1, - "column": 1 + "line": 19, + "column": 15 }, "end": { - "line": 1, - "column": 1 + "line": 19, + "column": 27 } } }, @@ -191,12 +191,12 @@ "optional": false, "loc": { "start": { - "line": 1, - "column": 1 + "line": 19, + "column": 15 }, "end": { - "line": 1, - "column": 1 + "line": 19, + "column": 27 } } }, diff --git a/es2panda/test/parser/ts/transformed_cases/test-class-constructor1-transformed-expected.txt b/es2panda/test/parser/ts/transformed_cases/test-class-constructor1-transformed-expected.txt index 822c6e99a9..46330a78db 100644 --- a/es2panda/test/parser/ts/transformed_cases/test-class-constructor1-transformed-expected.txt +++ b/es2panda/test/parser/ts/transformed_cases/test-class-constructor1-transformed-expected.txt @@ -76,12 +76,12 @@ "type": "ThisExpression", "loc": { "start": { - "line": 1, - "column": 1 + "line": 18, + "column": 5 }, "end": { - "line": 1, - "column": 1 + "line": 18, + "column": 10 } } }, @@ -90,12 +90,12 @@ "name": "prop1", "loc": { "start": { - "line": 1, - "column": 1 + "line": 18, + "column": 5 }, "end": { - "line": 1, - "column": 1 + "line": 18, + "column": 10 } } }, @@ -103,12 +103,12 @@ "optional": false, "loc": { "start": { - "line": 1, - "column": 1 + "line": 18, + "column": 5 }, "end": { - "line": 1, - "column": 1 + "line": 18, + "column": 10 } } }, diff --git a/es2panda/test/parser/ts/transformed_cases/test-class-constructor2-transformed-expected.txt b/es2panda/test/parser/ts/transformed_cases/test-class-constructor2-transformed-expected.txt index 40bb140f3b..b22c158c23 100644 --- a/es2panda/test/parser/ts/transformed_cases/test-class-constructor2-transformed-expected.txt +++ b/es2panda/test/parser/ts/transformed_cases/test-class-constructor2-transformed-expected.txt @@ -103,12 +103,12 @@ "type": "ThisExpression", "loc": { "start": { - "line": 1, - "column": 1 + "line": 18, + "column": 5 }, "end": { - "line": 1, - "column": 1 + "line": 18, + "column": 9 } } }, @@ -117,12 +117,12 @@ "name": "prop", "loc": { "start": { - "line": 1, - "column": 1 + "line": 18, + "column": 5 }, "end": { - "line": 1, - "column": 1 + "line": 18, + "column": 9 } } }, @@ -130,12 +130,12 @@ "optional": false, "loc": { "start": { - "line": 1, - "column": 1 + "line": 18, + "column": 5 }, "end": { - "line": 1, - "column": 1 + "line": 18, + "column": 9 } } }, diff --git a/es2panda/test/parser/ts/transformed_cases/test-class-constructor3-transformed-expected.txt b/es2panda/test/parser/ts/transformed_cases/test-class-constructor3-transformed-expected.txt index 7936bfad6d..57e42ec3ec 100644 --- a/es2panda/test/parser/ts/transformed_cases/test-class-constructor3-transformed-expected.txt +++ b/es2panda/test/parser/ts/transformed_cases/test-class-constructor3-transformed-expected.txt @@ -268,12 +268,12 @@ "type": "ThisExpression", "loc": { "start": { - "line": 1, - "column": 1 + "line": 20, + "column": 5 }, "end": { - "line": 1, - "column": 1 + "line": 20, + "column": 9 } } }, @@ -282,12 +282,12 @@ "name": "prop", "loc": { "start": { - "line": 1, - "column": 1 + "line": 20, + "column": 5 }, "end": { - "line": 1, - "column": 1 + "line": 20, + "column": 9 } } }, @@ -295,12 +295,12 @@ "optional": false, "loc": { "start": { - "line": 1, - "column": 1 + "line": 20, + "column": 5 }, "end": { - "line": 1, - "column": 1 + "line": 20, + "column": 9 } } }, diff --git a/es2panda/test/parser/ts/transformed_cases/test-class-constructor4-transformed-expected.txt b/es2panda/test/parser/ts/transformed_cases/test-class-constructor4-transformed-expected.txt index 1548646ed4..3e56df7b4f 100644 --- a/es2panda/test/parser/ts/transformed_cases/test-class-constructor4-transformed-expected.txt +++ b/es2panda/test/parser/ts/transformed_cases/test-class-constructor4-transformed-expected.txt @@ -424,12 +424,12 @@ "type": "ThisExpression", "loc": { "start": { - "line": 1, - "column": 1 + "line": 20, + "column": 5 }, "end": { - "line": 1, - "column": 1 + "line": 20, + "column": 10 } } }, @@ -438,12 +438,12 @@ "name": "prop1", "loc": { "start": { - "line": 1, - "column": 1 + "line": 20, + "column": 5 }, "end": { - "line": 1, - "column": 1 + "line": 20, + "column": 10 } } }, @@ -451,12 +451,12 @@ "optional": false, "loc": { "start": { - "line": 1, - "column": 1 + "line": 20, + "column": 5 }, "end": { - "line": 1, - "column": 1 + "line": 20, + "column": 10 } } }, diff --git a/es2panda/test/parser/ts/transformed_cases/test-class-decorator-1-transformed-expected.txt b/es2panda/test/parser/ts/transformed_cases/test-class-decorator-1-transformed-expected.txt index edaef8740c..3c0ec91edb 100644 --- a/es2panda/test/parser/ts/transformed_cases/test-class-decorator-1-transformed-expected.txt +++ b/es2panda/test/parser/ts/transformed_cases/test-class-decorator-1-transformed-expected.txt @@ -890,12 +890,12 @@ "name": "a", "loc": { "start": { - "line": 1, - "column": 1 + "line": 23, + "column": 12 }, "end": { - "line": 1, - "column": 1 + "line": 23, + "column": 13 } } }, diff --git a/es2panda/test/parser/ts/transformed_cases_api_version_10/test-class-constructor1-transformed-expected.txt b/es2panda/test/parser/ts/transformed_cases_api_version_10/test-class-constructor1-transformed-expected.txt index 1dad3f2b1e..8a02b47f7b 100644 --- a/es2panda/test/parser/ts/transformed_cases_api_version_10/test-class-constructor1-transformed-expected.txt +++ b/es2panda/test/parser/ts/transformed_cases_api_version_10/test-class-constructor1-transformed-expected.txt @@ -424,12 +424,12 @@ "type": "ThisExpression", "loc": { "start": { - "line": 1, - "column": 1 + "line": 20, + "column": 5 }, "end": { - "line": 1, - "column": 1 + "line": 20, + "column": 10 } } }, @@ -438,12 +438,12 @@ "name": "prop1", "loc": { "start": { - "line": 1, - "column": 1 + "line": 20, + "column": 5 }, "end": { - "line": 1, - "column": 1 + "line": 20, + "column": 10 } } }, @@ -451,12 +451,12 @@ "optional": false, "loc": { "start": { - "line": 1, - "column": 1 + "line": 20, + "column": 5 }, "end": { - "line": 1, - "column": 1 + "line": 20, + "column": 10 } } }, @@ -507,12 +507,12 @@ "type": "ThisExpression", "loc": { "start": { - "line": 1, - "column": 1 + "line": 21, + "column": 5 }, "end": { - "line": 1, - "column": 1 + "line": 21, + "column": 11 } } }, @@ -521,12 +521,12 @@ "name": "###B#prop2#1", "loc": { "start": { - "line": 1, - "column": 1 + "line": 21, + "column": 5 }, "end": { - "line": 1, - "column": 1 + "line": 21, + "column": 11 } } }, @@ -534,12 +534,12 @@ "optional": false, "loc": { "start": { - "line": 1, - "column": 1 + "line": 21, + "column": 5 }, "end": { - "line": 1, - "column": 1 + "line": 21, + "column": 11 } } }, diff --git a/es2panda/test/parser/ts/transformed_cases_api_version_10/test-decorator-1-transformed-expected.txt b/es2panda/test/parser/ts/transformed_cases_api_version_10/test-decorator-1-transformed-expected.txt index 4632b52a56..f826e0a0dc 100644 --- a/es2panda/test/parser/ts/transformed_cases_api_version_10/test-decorator-1-transformed-expected.txt +++ b/es2panda/test/parser/ts/transformed_cases_api_version_10/test-decorator-1-transformed-expected.txt @@ -948,12 +948,12 @@ "name": "a", "loc": { "start": { - "line": 1, - "column": 1 + "line": 23, + "column": 12 }, "end": { - "line": 1, - "column": 1 + "line": 23, + "column": 13 } } }, diff --git a/es2panda/test/parser/ts/transformed_cases_api_version_10/test-switchCase-statement-1-transformed-expected.txt b/es2panda/test/parser/ts/transformed_cases_api_version_10/test-switchCase-statement-1-transformed-expected.txt index e4097e9570..b4d0eec5fb 100644 --- a/es2panda/test/parser/ts/transformed_cases_api_version_10/test-switchCase-statement-1-transformed-expected.txt +++ b/es2panda/test/parser/ts/transformed_cases_api_version_10/test-switchCase-statement-1-transformed-expected.txt @@ -303,12 +303,12 @@ "name": "p", "loc": { "start": { - "line": 1, - "column": 1 + "line": 20, + "column": 26 }, "end": { - "line": 1, - "column": 1 + "line": 20, + "column": 27 } } }, diff --git a/es2panda/test/parser/ts/transformed_cases_api_version_10/test-ts-export-classes-1-transformed-expected.txt b/es2panda/test/parser/ts/transformed_cases_api_version_10/test-ts-export-classes-1-transformed-expected.txt index 226a8ad0d5..173727186b 100644 --- a/es2panda/test/parser/ts/transformed_cases_api_version_10/test-ts-export-classes-1-transformed-expected.txt +++ b/es2panda/test/parser/ts/transformed_cases_api_version_10/test-ts-export-classes-1-transformed-expected.txt @@ -199,12 +199,12 @@ "name": "a", "loc": { "start": { - "line": 1, - "column": 1 + "line": 17, + "column": 30 }, "end": { - "line": 1, - "column": 1 + "line": 17, + "column": 31 } } }, diff --git a/es2panda/test/parser/ts/transformed_cases_api_version_10/test-ts-export-classes-2-transformed-expected.txt b/es2panda/test/parser/ts/transformed_cases_api_version_10/test-ts-export-classes-2-transformed-expected.txt index b56614dff4..8294b94320 100644 --- a/es2panda/test/parser/ts/transformed_cases_api_version_10/test-ts-export-classes-2-transformed-expected.txt +++ b/es2panda/test/parser/ts/transformed_cases_api_version_10/test-ts-export-classes-2-transformed-expected.txt @@ -214,12 +214,12 @@ "name": "a", "loc": { "start": { - "line": 1, - "column": 1 + "line": 17, + "column": 24 }, "end": { - "line": 1, - "column": 1 + "line": 17, + "column": 25 } } }, -- Gitee From e2098d19a2da7876db919e8f4fb0ce2b1cec802f Mon Sep 17 00:00:00 2001 From: rentangyu Date: Tue, 20 May 2025 10:17:54 +0800 Subject: [PATCH 167/268] Recover array-literal-1 testcase Issue:https://gitee.com/openharmony/arkcompiler_ets_runtime/issues/IC8X2D Signed-off-by: rentangyu --- es2panda/test/compiler/js/array-literal-1-expected.txt | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/es2panda/test/compiler/js/array-literal-1-expected.txt b/es2panda/test/compiler/js/array-literal-1-expected.txt index 4b5e7278e7..877137e32a 100644 --- a/es2panda/test/compiler/js/array-literal-1-expected.txt +++ b/es2panda/test/compiler/js/array-literal-1-expected.txt @@ -1,2 +1 @@ -get 0 -TypeError: ,, is not callable +TypeError: Object is not callable -- Gitee From 718101d4ac73d76a174b4e469d23918224007779 Mon Sep 17 00:00:00 2001 From: gizembusraturan Date: Tue, 20 May 2025 08:55:05 +0300 Subject: [PATCH 168/268] Title: support declare struct Issue: IC5TXN Testing: Build Signed-off-by: gizembusraturan --- es2panda/lexer/token/tokenType.h | 3 ++- ets2panda/parser/ETSparser.cpp | 3 ++- .../ets/ambient_struct/declare_struct.d.ets | 21 +++++++++++++++++++ 3 files changed, 25 insertions(+), 2 deletions(-) create mode 100644 ets2panda/test/ast/compiler/ets/ambient_struct/declare_struct.d.ets diff --git a/es2panda/lexer/token/tokenType.h b/es2panda/lexer/token/tokenType.h index 6fe7fb0f0e..45a23d0ed2 100644 --- a/es2panda/lexer/token/tokenType.h +++ b/es2panda/lexer/token/tokenType.h @@ -1,5 +1,5 @@ /** - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -142,6 +142,7 @@ enum class TokenType { KEYW_RETURN, KEYW_STRING, KEYW_SUPER, + KEYW_STRUCT, KEYW_SWITCH, KEYW_SYMBOL, KEYW_THIS, diff --git a/ets2panda/parser/ETSparser.cpp b/ets2panda/parser/ETSparser.cpp index 1734a7eec8..e721f5c1b4 100644 --- a/ets2panda/parser/ETSparser.cpp +++ b/ets2panda/parser/ETSparser.cpp @@ -1847,7 +1847,8 @@ void ETSParser::CheckDeclare() case lexer::TokenType::KEYW_FINAL: case lexer::TokenType::KEYW_INTERFACE: case lexer::TokenType::KEYW_TYPE: - case lexer::TokenType::KEYW_ASYNC: { + case lexer::TokenType::KEYW_ASYNC: + case lexer::TokenType::KEYW_STRUCT: { return; } default: { diff --git a/ets2panda/test/ast/compiler/ets/ambient_struct/declare_struct.d.ets b/ets2panda/test/ast/compiler/ets/ambient_struct/declare_struct.d.ets new file mode 100644 index 0000000000..820aa91867 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/ambient_struct/declare_struct.d.ets @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export declare struct Point2D { + x: number; + y: number; +} + +/* @@? 16:16 Error TypeError: Structs are only used to define UI components, it should be translated at 'plugin after parser' phase. */ -- Gitee From acf0c8f293d1ac3db01aaca7cda57c6d57bb4fc5 Mon Sep 17 00:00:00 2001 From: liyue Date: Mon, 19 May 2025 23:09:56 +0800 Subject: [PATCH 169/268] Fix line number in chained MemberExpressions Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC8XV5 Signed-off-by: liyue Change-Id: Iaaac7829104b74edb452cbf9b2eec833f7e9fad6 --- es2panda/ir/expressions/memberExpression.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/es2panda/ir/expressions/memberExpression.cpp b/es2panda/ir/expressions/memberExpression.cpp index c86f519c0a..c36674e160 100644 --- a/es2panda/ir/expressions/memberExpression.cpp +++ b/es2panda/ir/expressions/memberExpression.cpp @@ -93,9 +93,9 @@ void MemberExpression::Compile(compiler::PandaGen *pg, compiler::VReg objReg) co compiler::Operand prop = CompileKey(pg); if (object_->IsSuperExpression()) { - pg->LoadSuperProperty(this, objReg, prop); + pg->LoadSuperProperty(property_, objReg, prop); } else { - pg->LoadObjProperty(this, objReg, prop); + pg->LoadObjProperty(property_, objReg, prop); } } -- Gitee From 195d3b8db4c43b42993d2de8adec8f1a1e7dd49b Mon Sep 17 00:00:00 2001 From: cllvly Date: Tue, 20 May 2025 15:36:42 +0800 Subject: [PATCH 170/268] Update Kfl 0520 Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC94WY Signed-off-by: chenlong --- test262/ignored-test262-fastverify-x64-aot-pgo.txt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/test262/ignored-test262-fastverify-x64-aot-pgo.txt b/test262/ignored-test262-fastverify-x64-aot-pgo.txt index 3850582fdc..616d78ec15 100644 --- a/test262/ignored-test262-fastverify-x64-aot-pgo.txt +++ b/test262/ignored-test262-fastverify-x64-aot-pgo.txt @@ -1 +1,4 @@ # Known failure list for test262 - fastverify-x64-aot-pgo + +#19208 +test262/data/test_es2021/language/module-code/instn-iee-err-circular-as.js -- Gitee From ac73f310b142765341346c8c6bc311c530adc67b Mon Sep 17 00:00:00 2001 From: zhangkai366 Date: Tue, 20 May 2025 16:17:13 +0800 Subject: [PATCH 171/268] Fix the bug that performance is not defined Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC95K4 Test: grammar&ut Signed-off-by: zhangkai366 Change-Id: If68af78cbe75f57515db335401cec0522ec5a115 --- arkguard/src/utils/PrinterTimeAndMemUtils.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/arkguard/src/utils/PrinterTimeAndMemUtils.ts b/arkguard/src/utils/PrinterTimeAndMemUtils.ts index 334f542d89..24c03c900b 100644 --- a/arkguard/src/utils/PrinterTimeAndMemUtils.ts +++ b/arkguard/src/utils/PrinterTimeAndMemUtils.ts @@ -17,6 +17,7 @@ import * as fs from 'fs'; import path from 'path'; import type { IOptions } from '../configs/IOptions'; import type { IPrinterOption } from '../configs/INameObfuscationOption'; +import { performance } from 'perf_hooks'; import { performanceTimeAndMemPrinter } from '../ArkObfuscator'; import { printerTimeAndMemDataConfig } from '../initialization/Initializer'; -- Gitee From af66ad6af4a97a46ecc6e96fe75ec3d706e701e5 Mon Sep 17 00:00:00 2001 From: xingshunxiang Date: Thu, 8 May 2025 11:35:40 +0800 Subject: [PATCH 172/268] Fix Unexpected Crash When Define Var Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC8Z2N?from=project-issue Description: NaN and Infinity are not keywords now, the can be used as identifier Reason: NaN and Infinity are not keywords now, the can be used as identifier Tests: ninja tests passed tests/tests-u-runner/runner.sh --ets-cts --show-progress --build-dir x64.release --processes=all passed tests/tests-u-runner/runner.sh --ets-func-tests --show-progress --build-dir x64.release --processes=all passed tests/tests-u-runner/runner.sh --astchecker --show-progress --build-dir x64.release --processes=all passed tests/tests-u-runner/runner.sh --ets-runtime --show-progress --build-dir x64.release --processes=all passed tests/tests-u-runner/runner.sh --parser --no-js --show-progress --build-dir x64.release --processes=all passed Signed-off-by: xingshunxiang --- ets2panda/checker/ets/helpers.cpp | 2 +- ets2panda/checker/ets/utilityTypeHandlers.cpp | 2 +- .../ets/interfacePropertyDeclarations.cpp | 2 +- .../lowering/scopesInit/scopesInitPhase.cpp | 2 +- .../compiler/ets/math_const_as_identifier.ets | 2 ++ .../test/runtime/ets/define_var_test.ets | 21 +++++++++++++++++++ ets2panda/util/helpers.cpp | 18 ++++++++-------- ets2panda/util/helpers.h | 2 +- ets2panda/varbinder/ETSBinder.cpp | 5 +++++ ets2panda/varbinder/ETSBinder.h | 1 + ets2panda/varbinder/scope.cpp | 5 +++-- ets2panda/varbinder/scope.h | 3 ++- ets2panda/varbinder/varbinder.cpp | 9 ++++++-- ets2panda/varbinder/varbinder.h | 1 + 14 files changed, 56 insertions(+), 19 deletions(-) create mode 100644 ets2panda/test/runtime/ets/define_var_test.ets diff --git a/ets2panda/checker/ets/helpers.cpp b/ets2panda/checker/ets/helpers.cpp index b28811f544..ad0fa2e9e6 100644 --- a/ets2panda/checker/ets/helpers.cpp +++ b/ets2panda/checker/ets/helpers.cpp @@ -2633,7 +2633,7 @@ void ETSChecker::GenerateGetterSetterBody(ArenaVector &stmts, A auto *paramExpression = AllocNode(paramIdent, false, Allocator()); paramExpression->SetRange(paramIdent->Range()); - auto [paramVar, node] = paramScope->AddParamDecl(Allocator(), paramExpression); + auto [paramVar, node] = paramScope->AddParamDecl(Allocator(), VarBinder(), paramExpression); if (node != nullptr) { VarBinder()->ThrowRedeclaration(node->Start(), paramVar->Name()); } diff --git a/ets2panda/checker/ets/utilityTypeHandlers.cpp b/ets2panda/checker/ets/utilityTypeHandlers.cpp index 69ed5cb22c..138fe7d21e 100644 --- a/ets2panda/checker/ets/utilityTypeHandlers.cpp +++ b/ets2panda/checker/ets/utilityTypeHandlers.cpp @@ -542,7 +542,7 @@ ir::MethodDefinition *ETSChecker::CreateNullishAccessor(ir::MethodDefinition *co paramExpr->Ident()->SetTsTypeAnnotation(unionType); unionType->SetParent(paramExpr->Ident()); - auto [paramVar, node] = paramScope->AddParamDecl(Allocator(), paramExpr); + auto [paramVar, node] = paramScope->AddParamDecl(Allocator(), VarBinder(), paramExpr); if (node != nullptr) { VarBinder()->ThrowRedeclaration(node->Start(), paramVar->Name()); } diff --git a/ets2panda/compiler/lowering/ets/interfacePropertyDeclarations.cpp b/ets2panda/compiler/lowering/ets/interfacePropertyDeclarations.cpp index 01327be62a..f9b848d9a1 100644 --- a/ets2panda/compiler/lowering/ets/interfacePropertyDeclarations.cpp +++ b/ets2panda/compiler/lowering/ets/interfacePropertyDeclarations.cpp @@ -87,7 +87,7 @@ ir::FunctionSignature InterfacePropertyDeclarationsPhase::GenerateGetterOrSetter auto *const paramExpression = checker->AllocNode(paramIdent, false, checker->Allocator()); paramExpression->SetRange(paramIdent->Range()); - auto [paramVar, node] = paramScope->AddParamDecl(checker->Allocator(), paramExpression); + auto [paramVar, node] = paramScope->AddParamDecl(checker->Allocator(), varbinder, paramExpression); if (node != nullptr) { varbinder->ThrowRedeclaration(node->Start(), paramVar->Name()); } diff --git a/ets2panda/compiler/lowering/scopesInit/scopesInitPhase.cpp b/ets2panda/compiler/lowering/scopesInit/scopesInitPhase.cpp index a177e3b779..4d386ae30b 100644 --- a/ets2panda/compiler/lowering/scopesInit/scopesInitPhase.cpp +++ b/ets2panda/compiler/lowering/scopesInit/scopesInitPhase.cpp @@ -233,7 +233,7 @@ void ScopesInitPhase::VisitCatchClause(ir::CatchClause *catchClause) void ScopesInitPhase::VisitVariableDeclarator(ir::VariableDeclarator *varDecl) { auto init = varDecl->Id(); - std::vector bindings = util::Helpers::CollectBindingNames(init); + std::vector bindings = util::Helpers::CollectBindingNames(VarBinder(), init); for (auto *binding : bindings) { auto [decl, var] = AddOrGetVarDecl(varDecl->Flag(), binding); BindVarDecl(binding, init, decl, var); diff --git a/ets2panda/test/ast/compiler/ets/math_const_as_identifier.ets b/ets2panda/test/ast/compiler/ets/math_const_as_identifier.ets index cd1e04e086..9c7a8b2ce2 100644 --- a/ets2panda/test/ast/compiler/ets/math_const_as_identifier.ets +++ b/ets2panda/test/ast/compiler/ets/math_const_as_identifier.ets @@ -23,6 +23,8 @@ function foo1() { let undefined }; +/* @@? 21:9 Error TypeError: Variable 'NaN' has already been declared. */ +/* @@? 22:9 Error TypeError: Variable 'Infinity' has already been declared. */ /* @@? 22:20 Error TypeError: Unresolved reference test */ /* @@? 23:9 Error SyntaxError: Identifier expected, got 'undefined'. */ /* @@? 24:1 Error SyntaxError: Variable must be initialized or it's type must be declared. */ diff --git a/ets2panda/test/runtime/ets/define_var_test.ets b/ets2panda/test/runtime/ets/define_var_test.ets new file mode 100644 index 0000000000..4de85c7aa4 --- /dev/null +++ b/ets2panda/test/runtime/ets/define_var_test.ets @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +function main() { + let Infinity: number = Double.POSITIVE_INFINITY; + let NaN: number; + assertEQ(Infinity, Double.POSITIVE_INFINITY); + assertEQ(NaN, 0); +} diff --git a/ets2panda/util/helpers.cpp b/ets2panda/util/helpers.cpp index e7204d2d33..2b9494e966 100644 --- a/ets2panda/util/helpers.cpp +++ b/ets2panda/util/helpers.cpp @@ -402,11 +402,11 @@ bool Helpers::IsPattern(const ir::AstNode *node) return node->IsArrayPattern() || node->IsObjectPattern() || node->IsAssignmentPattern(); } -static void CollectBindingName(ir::AstNode *node, std::vector *bindings) +static void CollectBindingName(varbinder::VarBinder *vb, ir::AstNode *node, std::vector *bindings) { switch (node->Type()) { case ir::AstNodeType::IDENTIFIER: { - if (!Helpers::IsGlobalIdentifier(node->AsIdentifier()->Name())) { + if (!vb->IsGlobalIdentifier(node->AsIdentifier()->Name())) { bindings->push_back(node->AsIdentifier()); } @@ -414,26 +414,26 @@ static void CollectBindingName(ir::AstNode *node, std::vector } case ir::AstNodeType::OBJECT_PATTERN: { for (auto *prop : node->AsObjectPattern()->Properties()) { - CollectBindingName(prop, bindings); + CollectBindingName(vb, prop, bindings); } break; } case ir::AstNodeType::ARRAY_PATTERN: { for (auto *element : node->AsArrayPattern()->Elements()) { - CollectBindingName(element, bindings); + CollectBindingName(vb, element, bindings); } break; } case ir::AstNodeType::ASSIGNMENT_PATTERN: { - CollectBindingName(node->AsAssignmentPattern()->Left(), bindings); + CollectBindingName(vb, node->AsAssignmentPattern()->Left(), bindings); break; } case ir::AstNodeType::PROPERTY: { - CollectBindingName(node->AsProperty()->Value(), bindings); + CollectBindingName(vb, node->AsProperty()->Value(), bindings); break; } case ir::AstNodeType::REST_ELEMENT: { - CollectBindingName(node->AsRestElement()->Argument(), bindings); + CollectBindingName(vb, node->AsRestElement()->Argument(), bindings); break; } default: @@ -441,10 +441,10 @@ static void CollectBindingName(ir::AstNode *node, std::vector } } -std::vector Helpers::CollectBindingNames(ir::Expression *node) +std::vector Helpers::CollectBindingNames(varbinder::VarBinder *vb, ir::Expression *node) { std::vector bindings; - CollectBindingName(node, &bindings); + CollectBindingName(vb, node, &bindings); return bindings; } diff --git a/ets2panda/util/helpers.h b/ets2panda/util/helpers.h index 3ac2779161..75b9eed903 100644 --- a/ets2panda/util/helpers.h +++ b/ets2panda/util/helpers.h @@ -149,7 +149,7 @@ public: static compiler::Literal ToConstantLiteral(const ir::Expression *expr); static bool IsBindingPattern(const ir::AstNode *node); static bool IsPattern(const ir::AstNode *node); - static std::vector CollectBindingNames(ir::Expression *node); + static std::vector CollectBindingNames(varbinder::VarBinder *vb, ir::Expression *node); static util::StringView FunctionName(ArenaAllocator *allocator, const ir::ScriptFunction *func); static void CheckImportedName(const ArenaVector &specifiers, const ir::ImportSpecifier *specifier, const std::string &fileName); diff --git a/ets2panda/varbinder/ETSBinder.cpp b/ets2panda/varbinder/ETSBinder.cpp index 216018b1b4..e8a663f170 100644 --- a/ets2panda/varbinder/ETSBinder.cpp +++ b/ets2panda/varbinder/ETSBinder.cpp @@ -1473,4 +1473,9 @@ void ETSBinder::ThrowError(const lexer::SourcePosition &pos, const std::string_v GetContext()->diagnosticEngine->LogSemanticError(msg, pos); } +bool ETSBinder::IsGlobalIdentifier([[maybe_unused]] const util::StringView &str) const +{ + return false; +} + } // namespace ark::es2panda::varbinder diff --git a/ets2panda/varbinder/ETSBinder.h b/ets2panda/varbinder/ETSBinder.h index 6463ebb852..dd96529259 100644 --- a/ets2panda/varbinder/ETSBinder.h +++ b/ets2panda/varbinder/ETSBinder.h @@ -188,6 +188,7 @@ public: void AddFunctionThisParam(ir::ScriptFunction *func); void ThrowError(const lexer::SourcePosition &pos, const std::string_view msg) const override; + bool IsGlobalIdentifier(const util::StringView &str) const override; void SetDefaultImports(ArenaVector defaultImports) noexcept { diff --git a/ets2panda/varbinder/scope.cpp b/ets2panda/varbinder/scope.cpp index 7e0673b210..292801e3f3 100644 --- a/ets2panda/varbinder/scope.cpp +++ b/ets2panda/varbinder/scope.cpp @@ -437,7 +437,8 @@ Variable *ParamScope::AddParameter(ArenaAllocator *allocator, Decl *newDecl, Var return param; } -std::tuple ParamScope::AddParamDecl(ArenaAllocator *allocator, ir::Expression *parameter) +std::tuple ParamScope::AddParamDecl(ArenaAllocator *allocator, varbinder::VarBinder *vb, + ir::Expression *parameter) { auto [name, pattern] = util::Helpers::ParamName(allocator, parameter, params_.size()); if (name.Is(ERROR_LITERAL)) { @@ -450,7 +451,7 @@ std::tuple ParamScope::AddParamDecl(ArenaAllocator } if (pattern) { - std::vector bindings = util::Helpers::CollectBindingNames(parameter); + std::vector bindings = util::Helpers::CollectBindingNames(vb, parameter); for (auto *binding : bindings) { auto *varDecl = NewDecl(allocator, binding->Name()); diff --git a/ets2panda/varbinder/scope.h b/ets2panda/varbinder/scope.h index 5ef35b88d0..8cff3b9d7d 100644 --- a/ets2panda/varbinder/scope.h +++ b/ets2panda/varbinder/scope.h @@ -441,7 +441,8 @@ public: return params_; } - std::tuple AddParamDecl(ArenaAllocator *allocator, ir::Expression *parameter); + std::tuple AddParamDecl(ArenaAllocator *allocator, varbinder::VarBinder *vb, + ir::Expression *parameter); protected: explicit ParamScope(ArenaAllocator *allocator, Scope *parent) diff --git a/ets2panda/varbinder/varbinder.cpp b/ets2panda/varbinder/varbinder.cpp index 7d668b5de2..0dcc26f31e 100644 --- a/ets2panda/varbinder/varbinder.cpp +++ b/ets2panda/varbinder/varbinder.cpp @@ -33,7 +33,7 @@ Variable *VarBinder::AddParamDecl(ir::Expression *param) { ES2PANDA_ASSERT(scope_->IsFunctionParamScope() || scope_->IsCatchParamScope()); - auto [var, node] = static_cast(scope_)->AddParamDecl(Allocator(), param); + auto [var, node] = static_cast(scope_)->AddParamDecl(Allocator(), this, param); ES2PANDA_ASSERT(var != nullptr); if (node != nullptr) { @@ -82,6 +82,11 @@ void VarBinder::ThrowError(const lexer::SourcePosition &pos, const std::string_v context_->diagnosticEngine->ThrowSyntaxError(msg, program_->SourceFilePath().Utf8(), loc.line, loc.col); } +bool VarBinder::IsGlobalIdentifier(const util::StringView &str) const +{ + return util::Helpers::IsGlobalIdentifier(str); +} + void VarBinder::IdentifierAnalysis() { ES2PANDA_ASSERT(program_->Ast()); @@ -249,7 +254,7 @@ void VarBinder::BuildVarDeclaratorId(ir::AstNode *childNode) auto *ident = childNode->AsIdentifier(); const auto &name = ident->Name(); - if (util::Helpers::IsGlobalIdentifier(name) || name.Is(ERROR_LITERAL)) { + if (IsGlobalIdentifier(name) || name.Is(ERROR_LITERAL)) { break; } diff --git a/ets2panda/varbinder/varbinder.h b/ets2panda/varbinder/varbinder.h index 8fe135f211..fe029aad6f 100644 --- a/ets2panda/varbinder/varbinder.h +++ b/ets2panda/varbinder/varbinder.h @@ -165,6 +165,7 @@ public: void ThrowTDZ(const lexer::SourcePosition &pos, const util::StringView &name) const; void ThrowInvalidCapture(const lexer::SourcePosition &pos, const util::StringView &name) const; virtual void ThrowError(const lexer::SourcePosition &pos, const std::string_view msg) const; + virtual bool IsGlobalIdentifier(const util::StringView &str) const; void PropagateDirectEval() const; -- Gitee From a108b65192c8eb5ddcb295ce93b222444be083fc Mon Sep 17 00:00:00 2001 From: xingshunxiang Date: Sun, 27 Apr 2025 09:24:27 +0800 Subject: [PATCH 173/268] Fix OpAssignment Lowering Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC4G5H?from=project-issue Description: when handle OpAssignmentExpr With UpdateExpression, we met some bad ast tree; Reason: We need correct the behavior of opAssignment lowering. Tests: ninja tests passed tests/tests-u-runner/runner.sh --ets-cts --show-progress --build-dir x64.release --processes=all passed tests/tests-u-runner/runner.sh --ets-func-tests --show-progress --build-dir x64.release --processes=all passed tests/tests-u-runner/runner.sh --astchecker --show-progress --build-dir x64.release --processes=all passed tests/tests-u-runner/runner.sh --ets-runtime --show-progress --build-dir x64.release --processes=all passed tests/tests-u-runner/runner.sh --parser --no-js --show-progress --build-dir x64.release --processes=all passed Signed-off-by: xingshunxiang --- .../compiler/lowering/ets/opAssignment.cpp | 53 +++++++++++++++---- .../ets/opAssignmentWithUpdateExpression.ets | 23 ++++++++ 2 files changed, 65 insertions(+), 11 deletions(-) create mode 100644 ets2panda/test/runtime/ets/opAssignmentWithUpdateExpression.ets diff --git a/ets2panda/compiler/lowering/ets/opAssignment.cpp b/ets2panda/compiler/lowering/ets/opAssignment.cpp index c56811b387..38a9d0b4c1 100644 --- a/ets2panda/compiler/lowering/ets/opAssignment.cpp +++ b/ets2panda/compiler/lowering/ets/opAssignment.cpp @@ -196,7 +196,23 @@ static std::tuple> GenerateNestedMemb return {newAssignmentStatements, newAssignmentExpressions}; } -static ir::Expression *GenerateStringForLoweredAssignment( +static std::tuple> GenerateStringForAssignment( + const lexer::TokenType opEqual, ir::MemberExpression *expr, ArenaAllocator *const allocator, size_t counter) +{ + // Note: Handle "A `opAssign` B" to "A = (A `operation` B) as T" + // opAssign is the operation like: "+=", "-=", "*=", "/=", etc., + // operation is the operation like: "+", "-", "*", "/", etc. + auto [retStr, retVec] = GenerateNestedMemberAccess(expr, allocator, counter); + counter += retVec.size(); + auto result = GenerateNestedMemberAccess(expr, allocator, counter); + counter += std::get<1>(result).size(); + retStr += " = ( " + std::get<0>(result) + ' ' + std::string {lexer::TokenToString(CombinedOpToOp(opEqual))} + + " (@@E" + std::to_string(counter) + ")) as @@T" + std::to_string(counter + 1); + retVec.insert(retVec.end(), std::get<1>(result).begin(), std::get<1>(result).end()); + return {retStr, retVec}; +} + +static ir::Expression *GenerateLoweredResultForLoweredAssignment( const lexer::TokenType opEqual, ir::MemberExpression *expr, ArenaAllocator *const allocator, parser::ETSParser *parser, const std::array additionalAssignmentExpressions) { @@ -206,14 +222,29 @@ static ir::Expression *GenerateStringForLoweredAssignment( // `operation` is the operation of the assignment like: "+", "-", "*", "/", etc., // B is the right hand side of the assignment // T is the type of the left hand side of the assignment - size_t counter = 1; - auto [retStr, retVec] = GenerateNestedMemberAccess(expr, allocator, counter); - counter += retVec.size(); - auto result = GenerateNestedMemberAccess(expr, allocator, counter); - counter += std::get<1>(result).size(); - retStr += " = ( " + std::get<0>(result) + ' ' + std::string {lexer::TokenToString(CombinedOpToOp(opEqual))} + - " (@@E" + std::to_string(counter) + ")) as @@T" + std::to_string(counter + 1); - retVec.insert(retVec.end(), std::get<1>(result).begin(), std::get<1>(result).end()); + if (expr->Kind() == ir::MemberExpressionKind::ELEMENT_ACCESS && !expr->Property()->IsLiteral()) { + // Note: support such a situation could be okay: `a[idx++] += someExpr`. + // It should be lowered as: `let dummyIdx = (lower result of `idx++`); a[dummyIdx] = a[dummyIdx] + someExpr`; + ArenaVector dummyIndexDeclExpression(allocator->Adapter()); + std::string dummyIndexDeclStr = "let @@I1 = @@E2;\n"; + auto dummyIndex = Gensym(allocator); + dummyIndexDeclExpression.emplace_back(dummyIndex); + dummyIndexDeclExpression.emplace_back(expr->Property()->Clone(allocator, nullptr)->AsExpression()); + ClearTypesVariablesAndScopes(dummyIndexDeclExpression[1]); + + // Note: Drop the old property, substitute it with dummyIdx. + expr->Property()->SetParent(nullptr); + expr->SetProperty(dummyIndex->Clone(allocator, expr)); + auto [retStr, retVec] = + GenerateStringForAssignment(opEqual, expr, allocator, dummyIndexDeclExpression.size() + 1); + retVec.push_back(additionalAssignmentExpressions[0]); + retVec.push_back(additionalAssignmentExpressions[1]); + retVec.insert(retVec.begin(), dummyIndexDeclExpression.begin(), dummyIndexDeclExpression.end()); + retStr = dummyIndexDeclStr + retStr; + return parser->CreateFormattedExpression(retStr, retVec); + } + + auto [retStr, retVec] = GenerateStringForAssignment(opEqual, expr, allocator, 1); retVec.push_back(additionalAssignmentExpressions[0]); retVec.push_back(additionalAssignmentExpressions[1]); return parser->CreateFormattedExpression(retStr, retVec); @@ -242,8 +273,8 @@ static ir::Expression *ConstructOpAssignmentResult(public_lib::Context *ctx, ir: GetClone(allocator, left->AsIdentifier()), right, exprType); } else if (left->IsMemberExpression()) { // Generate ArkTS code string for new lowered assignment expression: - retVal = GenerateStringForLoweredAssignment(opEqual, left->AsMemberExpression(), allocator, parser, - {right, exprType}); + retVal = GenerateLoweredResultForLoweredAssignment(opEqual, left->AsMemberExpression(), allocator, parser, + {right, exprType}); } else { ES2PANDA_UNREACHABLE(); } diff --git a/ets2panda/test/runtime/ets/opAssignmentWithUpdateExpression.ets b/ets2panda/test/runtime/ets/opAssignmentWithUpdateExpression.ets new file mode 100644 index 0000000000..4ee3133e77 --- /dev/null +++ b/ets2panda/test/runtime/ets/opAssignmentWithUpdateExpression.ets @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +let line = 0; +let pixelOffset = 0; +let weight = 1; +let output = new Array(1, 2, 3, 4); +let buffer = new Array(5, 6, 7, 8); +output[line++] += buffer[pixelOffset]; +assertEQ(line, 1); +assertEQ(output[0], 6); -- Gitee From daa50e1de88ba6c88c8816fdad6303f6e7207ab9 Mon Sep 17 00:00:00 2001 From: menjiaheng Date: Thu, 24 Apr 2025 10:53:55 +0800 Subject: [PATCH 174/268] Fix the enum cannot be used as Record key Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC3KJT Description: Enum types need to be handled when comparing with the ConstraintType of Record key Tests: all test passed Signed-off-by: menjiaheng --- ets2panda/checker/types/ets/etsEnumType.cpp | 7 +++-- ets2panda/compiler/scripts/signatures.yaml | 30 +++++++++++++++++++ .../runtime/ets/enum_as_key_of_record.ets | 28 +++++++++++++++++ 3 files changed, 63 insertions(+), 2 deletions(-) create mode 100644 ets2panda/test/runtime/ets/enum_as_key_of_record.ets diff --git a/ets2panda/checker/types/ets/etsEnumType.cpp b/ets2panda/checker/types/ets/etsEnumType.cpp index 6f9d01f6b4..61d23b7cbf 100644 --- a/ets2panda/checker/types/ets/etsEnumType.cpp +++ b/ets2panda/checker/types/ets/etsEnumType.cpp @@ -27,7 +27,9 @@ bool ETSStringEnumType::AssignmentSource(TypeRelation *relation, Type *target) result = true; } else if (target->IsETSStringType()) { result = true; - relation->GetNode()->AddAstNodeFlags(ir::AstNodeFlags::GENERATE_VALUE_OF); + if (relation->GetNode() != nullptr) { + relation->GetNode()->AddAstNodeFlags(ir::AstNodeFlags::GENERATE_VALUE_OF); + } } else if (target->IsETSUnionType()) { auto &unionConstituentTypes = target->AsETSUnionType()->ConstituentTypes(); for (auto *constituentType : unionConstituentTypes) { @@ -72,7 +74,8 @@ bool ETSIntEnumType::AssignmentSource(TypeRelation *relation, Type *target) { bool result = false; if (target->IsETSObjectType()) { - if (target->AsETSObjectType()->IsGlobalETSObjectType()) { + if (target->AsETSObjectType()->IsGlobalETSObjectType() || + target->AsETSObjectType()->Name() == compiler::Signatures::NUMERIC) { result = true; } else if (target->AsETSObjectType()->HasObjectFlag(ETSObjectFlags::BUILTIN_NUMERIC)) { result = true; diff --git a/ets2panda/compiler/scripts/signatures.yaml b/ets2panda/compiler/scripts/signatures.yaml index ffc327cc47..df42c1787c 100644 --- a/ets2panda/compiler/scripts/signatures.yaml +++ b/ets2panda/compiler/scripts/signatures.yaml @@ -170,6 +170,36 @@ defines: ref: BUILTIN_RETENTION - name: 'Symbol' ref: SYMBOL + - name: 'escompat.Array' + ref: ESCOMPAT_ARRAY + - name: 'ByteType.VAL' + ref: BYTETYPE_VAL + - name: 'IntType.VAL' + ref: INTTYPE_VAL + - name: 'LongType.VAL' + ref: LONGTYPE_VAL + - name: 'ShortType.VAL' + ref: SHORTTYPE_VAL + - name: 'FloatType.VAL' + ref: FLOATTYPE_VAL + - name: 'DoubleType.VAL' + ref: DOUBLETYPE_VAL + - name: 'BooleanType.VAL' + ref: BOOLEANTYPE_VAL + - name: 'CharType.VAL' + ref: CHARTYPE_VAL + - name: 'VoidType.VAL' + ref: VOIDTYPE_VAL + - name: 'UndefinedType.REF' + ref: UNDEFINEDTYPE_REF + - name: 'NullType.REF' + ref: NULLTYPE_REF + - name: 'Type' + ref: TYPE + - name: 'from' + ref: FROM + - name: 'Numeric' + ref: NUMERIC packages: - name: 'std.core' diff --git a/ets2panda/test/runtime/ets/enum_as_key_of_record.ets b/ets2panda/test/runtime/ets/enum_as_key_of_record.ets new file mode 100644 index 0000000000..93d19bb9f6 --- /dev/null +++ b/ets2panda/test/runtime/ets/enum_as_key_of_record.ets @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + enum StringEnum { + up = "1" + } + + enum IntEnum { + up = 1 + } + + +function foo(val1:Record, val2:Record){ + +} \ No newline at end of file -- Gitee From 38d84928a4862cf00b9f2f76c2bfee27f233902b Mon Sep 17 00:00:00 2001 From: menjiaheng Date: Fri, 25 Apr 2025 14:57:59 +0800 Subject: [PATCH 175/268] Fix await works with promise union types Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC3Y6I Description: await when used with a union type composed of Promises does not pass the check Tests:passed Signed-off-by:menjiaheng --- ets2panda/checker/ETSAnalyzer.cpp | 31 +++++++++++++---- .../runtime/ets/await_promise_union_type.ets | 33 +++++++++++++++++++ 2 files changed, 58 insertions(+), 6 deletions(-) create mode 100644 ets2panda/test/runtime/ets/await_promise_union_type.ets diff --git a/ets2panda/checker/ETSAnalyzer.cpp b/ets2panda/checker/ETSAnalyzer.cpp index f6498ed62c..068f306de8 100644 --- a/ets2panda/checker/ETSAnalyzer.cpp +++ b/ets2panda/checker/ETSAnalyzer.cpp @@ -1123,6 +1123,12 @@ std::tuple ETSAnalyzer::CheckAssignmentExprOperatorTyp return {sourceType, relationNode}; } +static bool IsPromiseType(checker::Type *type, ETSChecker *checker) +{ + return type->IsETSObjectType() && + type->AsETSObjectType()->GetOriginalBaseType() == checker->GlobalBuiltinPromiseType(); +} + checker::Type *ETSAnalyzer::Check(ir::AwaitExpression *expr) const { ETSChecker *checker = GetETSChecker(); @@ -1131,14 +1137,27 @@ checker::Type *ETSAnalyzer::Check(ir::AwaitExpression *expr) const } checker::Type *argType = checker->GetApparentType(expr->argument_->Check(checker)); - // Check the argument type of await expression - if (!argType->IsETSObjectType() || - (argType->AsETSObjectType()->GetOriginalBaseType() != checker->GlobalBuiltinPromiseType())) { - return checker->TypeError(expr, diagnostic::AWAITED_NOT_PROMISE, expr->Argument()->Start()); + ArenaVector awaitedTypes(checker->Allocator()->Adapter()); + + if (argType->IsETSUnionType()) { + for (Type *type : argType->AsETSUnionType()->ConstituentTypes()) { + if (!IsPromiseType(type, checker)) { + return checker->TypeError(expr, diagnostic::AWAITED_NOT_PROMISE, expr->Argument()->Start()); + } + + Type *typeArg = type->AsETSObjectType()->TypeArguments().at(0); + awaitedTypes.push_back(UnwrapPromiseType(typeArg)); + } + } else { + if (!IsPromiseType(argType, checker)) { + return checker->TypeError(expr, diagnostic::AWAITED_NOT_PROMISE, expr->Argument()->Start()); + } + + Type *typeArg = argType->AsETSObjectType()->TypeArguments().at(0); + awaitedTypes.push_back(UnwrapPromiseType(typeArg)); } - Type *type = argType->AsETSObjectType()->TypeArguments().at(0); - expr->SetTsType(UnwrapPromiseType(type)); + expr->SetTsType(argType->IsETSUnionType() ? checker->CreateETSUnionType(std::move(awaitedTypes)) : awaitedTypes[0]); return expr->TsType(); } diff --git a/ets2panda/test/runtime/ets/await_promise_union_type.ets b/ets2panda/test/runtime/ets/await_promise_union_type.ets new file mode 100644 index 0000000000..f4529432ca --- /dev/null +++ b/ets2panda/test/runtime/ets/await_promise_union_type.ets @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class Person{ + name:string; + fetchData?:()=>Promise; + constructor(name:string){ + this.name = name; + } +} + +async function foo():Promise{ +const bob = new Person("Bob"); +const resultPromise = bob.fetchData?.()??Promise.resolve(undefined); +const result = await resultPromise; +assertEQ(result,undefined); +} + +function main():void{ + foo(); +} \ No newline at end of file -- Gitee From 68a9bbce47e4f6639b899003c35c7ff5dd83acc9 Mon Sep 17 00:00:00 2001 From: xingshunxiang Date: Tue, 1 Apr 2025 16:38:45 +0800 Subject: [PATCH 176/268] Fix the type infer of str literal type Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBY18G?from=project-issue Description: a bug about enum initialize Reason: enum can be initialized by the constant expression which is consist of the member of itself. Tests: ninja tests passed tests/tests-u-runner/runner.sh --ets-cts --show-progress --build-dir x64.release --processes=all passed tests/tests-u-runner/runner.sh --ets-func-tests --show-progress --build-dir x64.release --processes=all passed tests/tests-u-runner/runner.sh --astchecker --show-progress --build-dir x64.release --processes=all passed tests/tests-u-runner/runner.sh --ets-runtime --show-progress --build-dir x64.release --processes=all passed tests/tests-u-runner/runner.sh --parser --no-js --show-progress --build-dir x64.release --processes=all passed Signed-off-by: xingshunxiang --- .../ets/constantExpressionLowering.cpp | 38 +++++++++++++------ .../lowering/ets/constantExpressionLowering.h | 2 +- .../ets/enum-initialize-with-enum3.ets | 28 ++++++++++++++ .../ets/enum-initialize-with-itself.ets | 31 +++++++++++++++ .../ets-runtime/ets-runtime-ignored.txt | 3 ++ 5 files changed, 89 insertions(+), 13 deletions(-) create mode 100644 ets2panda/test/runtime/ets/enum-initialize-with-enum3.ets create mode 100644 ets2panda/test/runtime/ets/enum-initialize-with-itself.ets diff --git a/ets2panda/compiler/lowering/ets/constantExpressionLowering.cpp b/ets2panda/compiler/lowering/ets/constantExpressionLowering.cpp index c9a93ad8c7..24118c12ed 100644 --- a/ets2panda/compiler/lowering/ets/constantExpressionLowering.cpp +++ b/ets2panda/compiler/lowering/ets/constantExpressionLowering.cpp @@ -765,12 +765,28 @@ ir::AstNode *ConstantExpressionLowering::FoldMultilineString(ir::TemplateLiteral return result; } +static bool IsEnumMemberInit(ir::AstNode *node) +{ + auto parent = node->Parent(); + if (node->IsMemberExpression()) { + return node->AsMemberExpression()->Object()->IsIdentifier(); + } + + if (node->IsIdentifier()) { + if (parent->IsTSEnumMember()) { + return parent->AsTSEnumMember()->Init() == node; + } + return !parent->IsMemberExpression() && !parent->IsTSEnumDeclaration() && !parent->IsETSTypeReferencePart(); + } + + return false; +} + ir::AstNode *ConstantExpressionLowering::UnFoldEnumMemberExpression(ir::AstNode *constantNode) { ir::NodeTransformer handleUnfoldEnumMember = [this, constantNode](ir::AstNode *const node) { - if (node->IsMemberExpression() && !node->Parent()->IsMemberExpression()) { - auto memExp = node->AsMemberExpression(); - return FindAndReplaceEnumMember(memExp, constantNode); + if (IsEnumMemberInit(node) && constantNode->IsTSEnumDeclaration()) { + return FindAndReplaceEnumMember(node, constantNode); } return node; @@ -788,15 +804,13 @@ ir::AstNode *ConstantExpressionLowering::FindNameInEnumMember(ArenaVectorend()) ? *it : nullptr; } -ir::AstNode *ConstantExpressionLowering::FindAndReplaceEnumMember(ir::MemberExpression *expr, ir::AstNode *node) +ir::AstNode *ConstantExpressionLowering::FindAndReplaceEnumMember(ir::AstNode *const expr, ir::AstNode *constantNode) { - if (!expr->Object()->IsIdentifier()) { - return expr; - } - - auto objectName = expr->Object()->AsIdentifier()->Name(); - auto propertyName = expr->Property()->AsIdentifier()->Name(); - for (auto curScope = node->Scope(); curScope != nullptr; curScope = curScope->Parent()) { + auto objectName = expr->IsMemberExpression() ? expr->AsMemberExpression()->Object()->AsIdentifier()->Name() + : constantNode->AsTSEnumDeclaration()->Key()->AsIdentifier()->Name(); + auto propertyName = expr->IsMemberExpression() ? expr->AsMemberExpression()->Property()->AsIdentifier()->Name() + : expr->AsIdentifier()->Name(); + for (auto curScope = constantNode->Scope(); curScope != nullptr; curScope = curScope->Parent()) { auto *foundDecl = curScope->FindDecl(objectName); if (foundDecl == nullptr || !foundDecl->Node()->IsTSEnumDeclaration()) { continue; @@ -810,7 +824,7 @@ ir::AstNode *ConstantExpressionLowering::FindAndReplaceEnumMember(ir::MemberExpr return expr; } - auto clonedInit = transformedInit->Clone(context_->allocator, transformedInit->Parent()); + auto clonedInit = transformedInit->Clone(context_->allocator, expr->Parent()); clonedInit->SetRange(expr->Range()); return UnFoldEnumMemberExpression(clonedInit); } diff --git a/ets2panda/compiler/lowering/ets/constantExpressionLowering.h b/ets2panda/compiler/lowering/ets/constantExpressionLowering.h index ded999e2f8..0656790207 100644 --- a/ets2panda/compiler/lowering/ets/constantExpressionLowering.h +++ b/ets2panda/compiler/lowering/ets/constantExpressionLowering.h @@ -106,7 +106,7 @@ private: ir::AstNode *FindNameInEnumMember(ArenaVector *members, util::StringView targetName); - ir::AstNode *FindAndReplaceEnumMember(ir::MemberExpression *expr, ir::AstNode *node); + ir::AstNode *FindAndReplaceEnumMember(ir::AstNode *expr, ir::AstNode *constantNode); ir::AstNode *UnfoldConstIdentifiers(ir::AstNode *constantNode); diff --git a/ets2panda/test/runtime/ets/enum-initialize-with-enum3.ets b/ets2panda/test/runtime/ets/enum-initialize-with-enum3.ets new file mode 100644 index 0000000000..5d263d01eb --- /dev/null +++ b/ets2panda/test/runtime/ets/enum-initialize-with-enum3.ets @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +namespace NS { + export enum E { + B = 4, + C = B + 1 + } +} +enum F { + R = 1 << 1, + W = 1 << 2, + O = NS.E.C +} + +assertEQ(F.O.valueOf(), 5) diff --git a/ets2panda/test/runtime/ets/enum-initialize-with-itself.ets b/ets2panda/test/runtime/ets/enum-initialize-with-itself.ets new file mode 100644 index 0000000000..4c116a0eb2 --- /dev/null +++ b/ets2panda/test/runtime/ets/enum-initialize-with-itself.ets @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +enum FileAccess { + None, + Read = 1 << 1, + Write = 1 << 2, + ReadWrite = Read | Write +} + +enum FileAccess2 { + None, + Read = 1 << 1, + Write = 1 << 2, + ReadWrite = Read +} + +assertEQ(FileAccess.ReadWrite.valueOf(), 6) +assertEQ(FileAccess2.ReadWrite.valueOf(), 2) \ No newline at end of file diff --git a/ets2panda/test/test-lists/ets-runtime/ets-runtime-ignored.txt b/ets2panda/test/test-lists/ets-runtime/ets-runtime-ignored.txt index ed76e9c73b..66c523e646 100644 --- a/ets2panda/test/test-lists/ets-runtime/ets-runtime-ignored.txt +++ b/ets2panda/test/test-lists/ets-runtime/ets-runtime-ignored.txt @@ -95,3 +95,6 @@ override_for_partial_01.ets #HEAD FILE NO NEED TO RUN import_self_head_tests/B/test.d.ets + +#Issue 25550 +enum-initialize-with-enum3.ets -- Gitee From 62b239e31c7af3a709bceb25c8160e1a98642946 Mon Sep 17 00:00:00 2001 From: muhammethalilsolmaz Date: Fri, 25 Apr 2025 11:39:00 +0300 Subject: [PATCH 177/268] fix: Null check added for TypeAliasDeclaration Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC3Z8W Reason: No null check Description: Need null check for typealiasdec Tests: The relevant fuzzy test should no longer crash. Signed-off-by: muhammethalilsolmaz --- ets2panda/parser/ETSparser.cpp | 3 ++ .../parser/ets/invalid_type_assignment.ets | 34 +++++++++++++++++++ .../test-lists/recheck/recheck-ignored.txt | 1 + 3 files changed, 38 insertions(+) create mode 100644 ets2panda/test/ast/parser/ets/invalid_type_assignment.ets diff --git a/ets2panda/parser/ETSparser.cpp b/ets2panda/parser/ETSparser.cpp index 78d9e7037f..0490f6c912 100644 --- a/ets2panda/parser/ETSparser.cpp +++ b/ets2panda/parser/ETSparser.cpp @@ -654,6 +654,9 @@ ir::TSTypeAliasDeclaration *ETSParser::ParseTypeAliasDeclaration() TypeAnnotationParsingOptions options = TypeAnnotationParsingOptions::REPORT_ERROR; ir::TypeNode *typeAnnotation = ParseTypeAnnotation(&options); + if (typeAnnotation == nullptr) { + return nullptr; + } typeAliasDecl->SetTsTypeAnnotation(typeAnnotation); typeAnnotation->SetParent(typeAliasDecl); typeAliasDecl->SetRange({typeStart, Lexer()->GetToken().End()}); diff --git a/ets2panda/test/ast/parser/ets/invalid_type_assignment.ets b/ets2panda/test/ast/parser/ets/invalid_type_assignment.ets new file mode 100644 index 0000000000..d270acffb0 --- /dev/null +++ b/ets2panda/test/ast/parser/ets/invalid_type_assignment.ets @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/*--- +flags: [dynamic-ast] +---*/ + + type Point = { x: number; y: number }; + type AxeX = Point['x']; + +/* @@? 20:18 Error SyntaxError: Invalid Type. */ +/* @@? 20:23 Error SyntaxError: Label must be followed by a loop statement. */ +/* @@? 20:23 Error TypeError: Type name 'number' used in the wrong context */ +/* @@? 20:34 Error SyntaxError: Label must be followed by a loop statement. */ +/* @@? 20:34 Error TypeError: Type name 'number' used in the wrong context */ +/* @@? 21:23 Error SyntaxError: Unexpected token, expected ']'. */ +/* @@? 21:23 Error SyntaxError: Unexpected token ']'. */ +/* @@? 21:23 Error SyntaxError: Unexpected token ']'. */ +/* @@? 21:23 Error SyntaxError: Unexpected token ']'. */ +/* @@? 21:23 Error SyntaxError: Unexpected token ']'. */ +/* @@? 21:26 Error SyntaxError: Unexpected token ']'. */ +/* @@? 21:26 Error SyntaxError: Unexpected token ']'. */ diff --git a/ets2panda/test/test-lists/recheck/recheck-ignored.txt b/ets2panda/test/test-lists/recheck/recheck-ignored.txt index 408ac1b5b3..07ac4c0ca7 100644 --- a/ets2panda/test/test-lists/recheck/recheck-ignored.txt +++ b/ets2panda/test/test-lists/recheck/recheck-ignored.txt @@ -438,6 +438,7 @@ ast/parser/ets/class-instance-field-redeclaration.ets ast/parser/ets/enum11.ets ast/parser/ets/user_defined_11.ets ast/parser/ets/InvalidTyped.ets +ast/parser/ets/invalid_type_assignment.ets ast/parser/ets/DeclareAsyncFunction.ets ast/parser/ets/unexpected_token_1.ets ast/parser/ets/InvalidStatements3.ets -- Gitee From 930ddf6540875f0e127aacaa72cbf8948891524f Mon Sep 17 00:00:00 2001 From: abdulsamethaymana Date: Thu, 24 Apr 2025 14:09:58 +0300 Subject: [PATCH 178/268] Fix: Null check at type annotation parser Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC3QYM?from=project-issue Signed-off-by: abdulsamethaymana --- ets2panda/test/ast/parser/ets/readonlyFunctionTypeAnnotation.ets | 1 - ets2panda/test/test-lists/recheck/recheck-ignored.txt | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/ets2panda/test/ast/parser/ets/readonlyFunctionTypeAnnotation.ets b/ets2panda/test/ast/parser/ets/readonlyFunctionTypeAnnotation.ets index b36e68e76e..b413b11d6f 100644 --- a/ets2panda/test/ast/parser/ets/readonlyFunctionTypeAnnotation.ets +++ b/ets2panda/test/ast/parser/ets/readonlyFunctionTypeAnnotation.ets @@ -18,7 +18,6 @@ func: readonly (Y : object | long [] ) => [ ] /* @@? 17:7 Error SyntaxError: Label must be followed by a loop statement. */ /* @@? 17:7 Error TypeError: Unresolved reference readonly */ -/* @@? 17:17 Error SyntaxError: Invalid Type. */ /* @@? 17:20 Error SyntaxError: Unexpected token, expected ',' or ')'. */ /* @@? 17:20 Error SyntaxError: Unexpected token ':'. */ /* @@? 17:20 Error SyntaxError: Unexpected token ':'. */ diff --git a/ets2panda/test/test-lists/recheck/recheck-ignored.txt b/ets2panda/test/test-lists/recheck/recheck-ignored.txt index 07ac4c0ca7..3b20da4546 100644 --- a/ets2panda/test/test-lists/recheck/recheck-ignored.txt +++ b/ets2panda/test/test-lists/recheck/recheck-ignored.txt @@ -303,6 +303,7 @@ ast/parser/ets/empty_launch.ets ast/parser/ets/increment-on-nullish-type-undefined.ets ast/parser/ets/generics_type_param_no_typeargs_no_default.ets ast/parser/ets/lambda_infer_type_neg_1.ets +ast/parser/ets/readonlyFunctionTypeAnnotation.ets ast/parser/ets/readonlyGetterSetterReassignment1.ets ast/parser/ets/interface_instantiation.ets ast/parser/ets/Dollar_doller_invalid2.ets -- Gitee From e8c31979b152740f863bb568f4f242ec4a3218c8 Mon Sep 17 00:00:00 2001 From: mustafadinc Date: Wed, 30 Apr 2025 00:54:43 +0300 Subject: [PATCH 179/268] Handle nullptr in cacheLookup Issue : https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC3XT6 Signed-off-by: mustafadinc --- ets2panda/checker/types/typeRelation.cpp | 7 ++++++ .../test/ast/parser/ets/invalid_type.ets | 22 +++++++++++++++++++ .../test-lists/recheck/recheck-ignored.txt | 1 + 3 files changed, 30 insertions(+) create mode 100644 ets2panda/test/ast/parser/ets/invalid_type.ets diff --git a/ets2panda/checker/types/typeRelation.cpp b/ets2panda/checker/types/typeRelation.cpp index 5f59255974..2a7bf8a2f9 100644 --- a/ets2panda/checker/types/typeRelation.cpp +++ b/ets2panda/checker/types/typeRelation.cpp @@ -33,6 +33,9 @@ RelationResult TypeRelation::CacheLookup(const Type *source, const Type *target, return result_; } + ES2PANDA_ASSERT(source != nullptr); + ES2PANDA_ASSERT(target != nullptr); + RelationKey relationKey {source->Id(), target->Id()}; auto res = holder.cached.find(relationKey); if (res == holder.cached.end()) { @@ -237,6 +240,10 @@ bool TypeRelation::IsSupertypeOf(Type *super, Type *sub) return Result(true); } + if (sub == nullptr) { + return false; + } + result_ = CacheLookup(super, sub, checker_->SupertypeResults(), RelationType::SUPERTYPE); if (result_ == RelationResult::CACHE_MISS) { if (IsIdenticalTo(super, sub)) { diff --git a/ets2panda/test/ast/parser/ets/invalid_type.ets b/ets2panda/test/ast/parser/ets/invalid_type.ets new file mode 100644 index 0000000000..36b08c0491 --- /dev/null +++ b/ets2panda/test/ast/parser/ets/invalid_type.ets @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class Function extends Intl.DateTimeFormat{ +let RegExp = Intl.PluralRules +} + +/* @@? 1:3 Error TypeError: Variable 'Function' is already defined with different type. */ +/* @@? 17:1 Error SyntaxError: Unexpected token 'let'. */ +/* @@? 17:19 Error TypeError: Property 'PluralRules' does not exist on type 'Intl' */ diff --git a/ets2panda/test/test-lists/recheck/recheck-ignored.txt b/ets2panda/test/test-lists/recheck/recheck-ignored.txt index 3b20da4546..2d803a9717 100644 --- a/ets2panda/test/test-lists/recheck/recheck-ignored.txt +++ b/ets2panda/test/test-lists/recheck/recheck-ignored.txt @@ -131,6 +131,7 @@ ast/parser/ets/for_of_02.ets ast/parser/ets/method_modifier_check_3.ets ast/parser/ets/unexpected_token_31.ets ast/parser/ets/array_2.ets +ast/parser/ets/invalid_type.ets ast/parser/ets/visible_signatures_1.ets ast/parser/multierror_switchcases.ets ast/parser/ets/method_modifier_check_9.ets -- Gitee From 430b7b41d41cab29a7c25f63c08b721d37a451ab Mon Sep 17 00:00:00 2001 From: beratagaca_9a91 Date: Fri, 25 Apr 2025 16:35:33 +0300 Subject: [PATCH 180/268] Title:[FUZZING][AUTOREPORT][es2panda] Crash Issue: IC42EG Test: Build Signed-off-by: beratagaca_9a91 --- ets2panda/parser/ETSparserClasses.cpp | 5 ++++ .../ast/parser/ets/minus_sign_as_index_1.ets | 25 +++++++++++++++++++ .../test-lists/recheck/recheck-ignored.txt | 1 + 3 files changed, 31 insertions(+) create mode 100644 ets2panda/test/ast/parser/ets/minus_sign_as_index_1.ets diff --git a/ets2panda/parser/ETSparserClasses.cpp b/ets2panda/parser/ETSparserClasses.cpp index eed7dce2af..2a76826e63 100644 --- a/ets2panda/parser/ETSparserClasses.cpp +++ b/ets2panda/parser/ETSparserClasses.cpp @@ -470,6 +470,11 @@ void ETSParser::ParseClassFieldDefinition(ir::Identifier *fieldName, ir::Modifie } if (Lexer()->TryEatTokenType(lexer::TokenType::PUNCTUATOR_COLON)) { typeAnnotation = ParseTypeAnnotation(&options); + if (typeAnnotation == nullptr) { + LogError(diagnostic::ID_EXPECTED); + return; + } + endLoc = typeAnnotation->End(); } diff --git a/ets2panda/test/ast/parser/ets/minus_sign_as_index_1.ets b/ets2panda/test/ast/parser/ets/minus_sign_as_index_1.ets new file mode 100644 index 0000000000..3f2ffefd8c --- /dev/null +++ b/ets2panda/test/ast/parser/ets/minus_sign_as_index_1.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class URIError extends WebAssembly {WebAssembly : WeakMap [-6]} + +/* @@? 1:3 Error TypeError: Class 'URIError' is already defined. */ +/* @@? 16:24 Error TypeError: Cannot find type 'WebAssembly'. */ +/* @@? 16:24 Error TypeError: The super type of 'URIError' class is not extensible. */ +/* @@? 16:60 Error SyntaxError: Unexpected token, expected ']'. */ +/* @@? 16:60 Error SyntaxError: Identifier expected. */ +/* @@? 16:60 Error SyntaxError: Unexpected token ']'. */ +/* @@? 16:61 Error SyntaxError: Unexpected token '6'. */ +/* @@? 16:62 Error SyntaxError: Unexpected token ']'. */ \ No newline at end of file diff --git a/ets2panda/test/test-lists/recheck/recheck-ignored.txt b/ets2panda/test/test-lists/recheck/recheck-ignored.txt index 2d803a9717..d80436cff8 100644 --- a/ets2panda/test/test-lists/recheck/recheck-ignored.txt +++ b/ets2panda/test/test-lists/recheck/recheck-ignored.txt @@ -636,6 +636,7 @@ ast/parser/ets/enum_default_invalid_value_type.ets ast/parser/ets/struct_implements_interface.ets ast/parser/ets/wrong_context_function_1.ets ast/parser/ets/illegal_continue_statement.ets +ast/parser/ets/minus_sign_as_index_1.ets ast/compiler/ets/union_string_literals_5.ets ast/compiler/ets/annotation_tests/annotation_for_type_parameter01.ets ast/compiler/ets/readonlyType_4.ets -- Gitee From 7ca33611a6e35cf3fdec6ed92145993e2d5c5a06 Mon Sep 17 00:00:00 2001 From: tolgayakar Date: Tue, 29 Apr 2025 10:30:04 +0300 Subject: [PATCH 181/268] Handle nullptr and IsETSParameterExpression Description: Handle nullptr in ETSAnalyzer.cpp and added params[0]->IsETSParameterExpression for ETSparserTypes.cpp Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC3XSK Signed-off-by: tolgayakar --- ets2panda/checker/ETSAnalyzer.cpp | 3 +- ets2panda/parser/ETSparserTypes.cpp | 3 +- .../parser/ets/invalid_decorator_usage.ets | 35 +++++++++++++++++++ .../test-lists/recheck/recheck-ignored.txt | 1 + 4 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 ets2panda/test/ast/parser/ets/invalid_decorator_usage.ets diff --git a/ets2panda/checker/ETSAnalyzer.cpp b/ets2panda/checker/ETSAnalyzer.cpp index 068f306de8..0941663949 100644 --- a/ets2panda/checker/ETSAnalyzer.cpp +++ b/ets2panda/checker/ETSAnalyzer.cpp @@ -2347,7 +2347,8 @@ checker::Type *ETSAnalyzer::Check(ir::AnnotationUsage *st) const ETSChecker *checker = GetETSChecker(); st->Expr()->Check(checker); - if (!st->GetBaseName()->Variable()->Declaration()->Node()->IsAnnotationDeclaration()) { + if (st->GetBaseName()->Variable() == nullptr || + !st->GetBaseName()->Variable()->Declaration()->Node()->IsAnnotationDeclaration()) { checker->LogError(diagnostic::NOT_AN_ANNOTATION, {st->GetBaseName()->Name()}, st->GetBaseName()->Start()); return ReturnTypeForStatement(st); } diff --git a/ets2panda/parser/ETSparserTypes.cpp b/ets2panda/parser/ETSparserTypes.cpp index c172d751d0..7c247dcb73 100644 --- a/ets2panda/parser/ETSparserTypes.cpp +++ b/ets2panda/parser/ETSparserTypes.cpp @@ -190,7 +190,8 @@ ir::TypeNode *ETSParser::ParseFunctionType(TypeAnnotationParsingOptions *options { auto startLoc = Lexer()->GetToken().Start(); auto params = ParseFunctionParams(); - bool hasReceiver = !params.empty() && params[0]->AsETSParameterExpression()->Ident()->IsReceiver(); + bool hasReceiver = !params.empty() && params[0]->IsETSParameterExpression() && + params[0]->AsETSParameterExpression()->Ident()->IsReceiver(); if (!Lexer()->TryEatTokenType(lexer::TokenType::PUNCTUATOR_ARROW)) { if (((*options) & TypeAnnotationParsingOptions::REPORT_ERROR) != 0) { LogExpectedToken(lexer::TokenType::PUNCTUATOR_ARROW); diff --git a/ets2panda/test/ast/parser/ets/invalid_decorator_usage.ets b/ets2panda/test/ast/parser/ets/invalid_decorator_usage.ets new file mode 100644 index 0000000000..3299f88853 --- /dev/null +++ b/ets2panda/test/ast/parser/ets/invalid_decorator_usage.ets @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@ q.M function i ( this : ( this : @ e ( ) [ ] ) => ( @ V ( ) "" ) ) { } + +/* @@? 16:3 Error TypeError: Cannot find type 'q'. */ +/* @@? 16:5 Error TypeError: 'M' is not an annotation. */ +/* @@? 16:5 Error TypeError: 'M' type does not exist. */ +/* @@? 16:16 Error TypeError: Only abstract or native methods can't have body. */ +/* @@? 16:29 Error SyntaxError: Unexpected 'this' keyword in non-receiver context. */ +/* @@? 16:44 Error SyntaxError: Unexpected token, expected '('. */ +/* @@? 16:44 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:44 Error SyntaxError: Unexpected token, expected '=>'. */ +/* @@? 16:44 Error SyntaxError: Invalid Type. */ +/* @@? 16:46 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 16:46 Error SyntaxError: Unexpected token ']'. */ +/* @@? 16:48 Error SyntaxError: Unexpected token ')'. */ +/* @@? 16:50 Error SyntaxError: Unexpected token '=>'. */ +/* @@? 16:59 Error SyntaxError: Annotations are not allowed on this type of declaration. */ +/* @@? 16:61 Error SyntaxError: Unexpected token ')'. */ +/* @@? 16:63 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 16:66 Error SyntaxError: Unexpected token ')'. */ +/* @@? 16:68 Error SyntaxError: Unexpected token ')'. */ diff --git a/ets2panda/test/test-lists/recheck/recheck-ignored.txt b/ets2panda/test/test-lists/recheck/recheck-ignored.txt index d80436cff8..291dc7bb67 100644 --- a/ets2panda/test/test-lists/recheck/recheck-ignored.txt +++ b/ets2panda/test/test-lists/recheck/recheck-ignored.txt @@ -285,6 +285,7 @@ ast/parser/ets/string_literal_const_cast.ets ast/parser/ets/InvalidClasses.ets ast/parser/ets/interfaceExtendInterfaces1.ets ast/parser/ets/method_modifier_check_17.ets +ast/parser/ets/invalid_decorator_usage.ets ast/parser/ets/operator_logical_and_euqal.ets ast/parser/ets/ambient_indexer_5.ets ast/parser/ets/declare_class_bad_2.ets -- Gitee From d59894b63a71b6de1065c1798fafdaf7b6b2bd34 Mon Sep 17 00:00:00 2001 From: Mikhail Kaskov Date: Mon, 5 May 2025 14:18:11 +0300 Subject: [PATCH 182/268] Fixed compilation of packages with relative path * Fixed compilation of packages if used relative path to file * Tests with error with import in duplicated package is changed because previous package and import resolved different pathes (with soft link and without), so generated additional error. Now the behavior is consistent, there aren't extra errors. Issue: https://gitee.com/openharmony/arkcompiler_runtime_core/issues/IC5IPB Signed-off-by: Kaskov Mikhail --- .../lowering/ets/packageImplicitImport.cpp | 3 +- ets2panda/parser/ETSparser.cpp | 4 +- .../package_test_4/package_module_1.ets | 1 - .../package_test_8/import_multi_error.ets | 2 - ets2panda/test/unit/CMakeLists.txt | 3 +- .../test/unit/relative_path/CMakeLists.txt | 43 +++++++++++++++++++ .../unit/relative_path/package_a_file_1.ets | 18 ++++++++ ets2panda/util/path.cpp | 2 +- 8 files changed, 68 insertions(+), 8 deletions(-) create mode 100644 ets2panda/test/unit/relative_path/CMakeLists.txt create mode 100644 ets2panda/test/unit/relative_path/package_a_file_1.ets diff --git a/ets2panda/compiler/lowering/ets/packageImplicitImport.cpp b/ets2panda/compiler/lowering/ets/packageImplicitImport.cpp index 0f1f935337..104d9083ac 100644 --- a/ets2panda/compiler/lowering/ets/packageImplicitImport.cpp +++ b/ets2panda/compiler/lowering/ets/packageImplicitImport.cpp @@ -46,7 +46,8 @@ static void ValidateFolderContainOnlySamePackageFiles(const public_lib::Context return; } - if ((prog1->ModuleName() != prog2->ModuleName()) && (prog1->SourceFileFolder() == prog2->SourceFileFolder())) { + if ((prog1->ModuleName() != prog2->ModuleName()) && + (prog1->SourceFile().GetAbsoluteParentFolder() == prog2->SourceFile().GetAbsoluteParentFolder())) { // There exist 2 files in the same folder, with different package names // // Showing the full path would be more informative, but it also leaks it to the stdout, which is diff --git a/ets2panda/parser/ETSparser.cpp b/ets2panda/parser/ETSparser.cpp index 0490f6c912..84932db2c3 100644 --- a/ets2panda/parser/ETSparser.cpp +++ b/ets2panda/parser/ETSparser.cpp @@ -1974,11 +1974,11 @@ ir::FunctionDeclaration *ETSParser::ParseAccessorWithReceiver(ir::ModifierFlags void ETSParser::AddPackageSourcesToParseList() { - importPathManager_->AddImplicitPackageImportToParseList(GetProgram()->SourceFileFolder(), + importPathManager_->AddImplicitPackageImportToParseList(GetProgram()->SourceFile().GetAbsoluteParentFolder(), Lexer()->GetToken().Start()); // Global program file is always in the same folder that we scanned, but we don't need to parse it twice - importPathManager_->MarkAsParsed(globalProgram_->SourceFilePath()); + importPathManager_->MarkAsParsed(globalProgram_->SourceFile().GetAbsolutePath()); } //================================================================================================// diff --git a/ets2panda/test/ast/compiler/ets/implicit_package_import/package_test_4/package_module_1.ets b/ets2panda/test/ast/compiler/ets/implicit_package_import/package_test_4/package_module_1.ets index 025f586615..60a86f221b 100644 --- a/ets2panda/test/ast/compiler/ets/implicit_package_import/package_test_4/package_module_1.ets +++ b/ets2panda/test/ast/compiler/ets/implicit_package_import/package_test_4/package_module_1.ets @@ -19,5 +19,4 @@ import {myvar} from "./package_module_2" // compiling this file will fail with import from it's own package /* @@? 17:1 Error SyntaxError: Package module cannot import from a file in it's own package. */ -/* @@? package_module_2.ets:18:12 Error TypeError: Variable 'myvar' has already been declared. */ /* @@? 17:21 Error TypeError: Cannot find import: ./package_module_2 */ diff --git a/ets2panda/test/ast/compiler/ets/implicit_package_import/package_test_8/import_multi_error.ets b/ets2panda/test/ast/compiler/ets/implicit_package_import/package_test_8/import_multi_error.ets index 1d9762690a..a0e59061b5 100644 --- a/ets2panda/test/ast/compiler/ets/implicit_package_import/package_test_8/import_multi_error.ets +++ b/ets2panda/test/ast/compiler/ets/implicit_package_import/package_test_8/import_multi_error.ets @@ -22,7 +22,5 @@ export let a: String = "SubpackageA"; /* @@? 18:1 Error SyntaxError: Package module cannot import from a file in it's own package. */ /* @@? 19:1 Error SyntaxError: Package module cannot import from a file in it's own package. */ -/* @@? package_module.ets:20:12 Error TypeError: Variable 'myvar' has already been declared. */ -/* @@? package_module.ets:21:12 Error TypeError: Variable 'myvar2' has already been declared. */ /* @@? 18:21 Error TypeError: Cannot find import: ./package_module */ /* @@? 19:22 Error TypeError: Cannot find import: ./package_module */ diff --git a/ets2panda/test/unit/CMakeLists.txt b/ets2panda/test/unit/CMakeLists.txt index a0b496400e..d1e6f78536 100644 --- a/ets2panda/test/unit/CMakeLists.txt +++ b/ets2panda/test/unit/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (c) 2024 Huawei Device Co., Ltd. +# Copyright (c) 2024-2025 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -25,6 +25,7 @@ add_subdirectory(plugin_conversion_rule) add_subdirectory(arktsconfig-parser) add_subdirectory(annotations) add_subdirectory(lsp) +add_subdirectory(relative_path) ets2panda_add_gtest(es2panda_astdumper_tests CPP_SOURCES ast_dumper_test.cpp diff --git a/ets2panda/test/unit/relative_path/CMakeLists.txt b/ets2panda/test/unit/relative_path/CMakeLists.txt new file mode 100644 index 0000000000..928c34b3f6 --- /dev/null +++ b/ets2panda/test/unit/relative_path/CMakeLists.txt @@ -0,0 +1,43 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +add_custom_target(es2panda_relative_path_to_file) + +function(copy_to_workdir filename) + get_filename_component(filename_without_ext ${filename} NAME_WLE) + add_custom_target("copy_test_${filename_without_ext}" + COMMAND ${CMAKE_COMMAND} -E copy + ${CMAKE_CURRENT_SOURCE_DIR}/${filename} + ${CMAKE_CURRENT_BINARY_DIR}/${filename_without_ext}/${filename}) +endfunction() + +function(launch_with_reletaive_path_single_file filename) + copy_to_workdir(${filename}) + get_filename_component(filename_without_ext ${filename} NAME_WLE) + set(filename_abc "${filename_without_ext}.abc") + add_custom_command( + OUTPUT "${filename_abc}" + DEPENDS es2panda copy_test_${filename_without_ext} + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/${filename_without_ext} + COMMAND ${CMAKE_COMMAND} -E env + LD_LIBRARY_PATH=${CMAKE_LIBRARY_OUTPUT_DIRECTORY} ${PANDA_RUN_PREFIX} + $ --extension=ets --ets-unnamed --output=${filename_abc} + ${filename} + ) + add_custom_target(es2panda_relative_path_to_file_${filename_without_ext} DEPENDS ${filename_abc}) + add_dependencies(es2panda_relative_path_to_file es2panda_relative_path_to_file_${filename_without_ext}) +endfunction() + +add_dependencies(es2panda_tests es2panda_relative_path_to_file) + +launch_with_reletaive_path_single_file(package_a_file_1.ets) diff --git a/ets2panda/test/unit/relative_path/package_a_file_1.ets b/ets2panda/test/unit/relative_path/package_a_file_1.ets new file mode 100644 index 0000000000..db6181aaca --- /dev/null +++ b/ets2panda/test/unit/relative_path/package_a_file_1.ets @@ -0,0 +1,18 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package A; + +export const num = 1; diff --git a/ets2panda/util/path.cpp b/ets2panda/util/path.cpp index 5c5e54c443..23bc2175c3 100644 --- a/ets2panda/util/path.cpp +++ b/ets2panda/util/path.cpp @@ -116,7 +116,7 @@ void Path::InitializeAbsoluteParentFolder() int position = absolutePath_.Mutf8().find_last_of(PATH_DELIMITER); - if (!absolutePath_.Empty() && isRelative_) { + if (!absolutePath_.Empty()) { absoluteParentFolder_ = absolutePath_.Substr(0, position); } } -- Gitee From 3d7bfc5bc14fa0c401a10c082e9e11f10705e73c Mon Sep 17 00:00:00 2001 From: xuxinjie4 Date: Tue, 13 May 2025 19:19:45 +0800 Subject: [PATCH 183/268] Fix a bug of neverType Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC6S2Z?from=project-issue Signed-off-by: xuxinjie4 --- ets2panda/checker/types/ets/etsNeverType.cpp | 2 +- .../ets/comparability_of_never_type01.ets | 18 ++++++++++++++++++ .../ets/comparability_of_never_type02.ets | 19 +++++++++++++++++++ .../ets/comparability_of_never_type03.ets | 19 +++++++++++++++++++ 4 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 ets2panda/test/ast/compiler/ets/comparability_of_never_type01.ets create mode 100644 ets2panda/test/ast/compiler/ets/comparability_of_never_type02.ets create mode 100644 ets2panda/test/ast/compiler/ets/comparability_of_never_type03.ets diff --git a/ets2panda/checker/types/ets/etsNeverType.cpp b/ets2panda/checker/types/ets/etsNeverType.cpp index e6fa4f3806..0b5401c3ba 100644 --- a/ets2panda/checker/types/ets/etsNeverType.cpp +++ b/ets2panda/checker/types/ets/etsNeverType.cpp @@ -22,7 +22,7 @@ namespace ark::es2panda::checker { void ETSNeverType::Identical(TypeRelation *relation, Type *other) { - relation->Result(other->IsNeverType()); + relation->Result(other->IsETSNeverType()); } void ETSNeverType::AssignmentTarget(TypeRelation *relation, Type *source) diff --git a/ets2panda/test/ast/compiler/ets/comparability_of_never_type01.ets b/ets2panda/test/ast/compiler/ets/comparability_of_never_type01.ets new file mode 100644 index 0000000000..02cf672e62 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/comparability_of_never_type01.ets @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +const a: readonly Array> = new Array>() +const b: readonly Array> = new Array>() +const c: readonly Array> = new Array>() diff --git a/ets2panda/test/ast/compiler/ets/comparability_of_never_type02.ets b/ets2panda/test/ast/compiler/ets/comparability_of_never_type02.ets new file mode 100644 index 0000000000..04e270a8c1 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/comparability_of_never_type02.ets @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +function foo(a:readonly Array){} +function bar(a:Array){ + foo(a) +} \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/comparability_of_never_type03.ets b/ets2panda/test/ast/compiler/ets/comparability_of_never_type03.ets new file mode 100644 index 0000000000..582677c3d4 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/comparability_of_never_type03.ets @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +function foo(a:readonly Array){} +function bar(a:readonly Array){ + foo(a) +} \ No newline at end of file -- Gitee From ad92de4b358e6ca062515f0df83237dd0eb8d735 Mon Sep 17 00:00:00 2001 From: xuxinjie4 Date: Fri, 9 May 2025 19:26:50 +0800 Subject: [PATCH 184/268] Fix out-of-bounds read in UTF-8 decoding Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC6O5J?from=project-issue Signed-off-by: xuxinjie4 --- .../ast/parser/ets/unexpected_token_62.ets | 71 +++++++++++++++++++ ets2panda/util/ustring.h | 13 +++- 2 files changed, 81 insertions(+), 3 deletions(-) create mode 100644 ets2panda/test/ast/parser/ets/unexpected_token_62.ets diff --git a/ets2panda/test/ast/parser/ets/unexpected_token_62.ets b/ets2panda/test/ast/parser/ets/unexpected_token_62.ets new file mode 100644 index 0000000000..1932877b96 --- /dev/null +++ b/ets2panda/test/ast/parser/ets/unexpected_token_62.ets @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class A {} +class B extendsA {} + +functioew Nu +nt = 10 A {} + +functioew Nu +nt = 10 +)void {nt = 20, g: s A {} +int = 10 +) => B = (p:+): A6=> { reƒurn _ew B(ô } +|ó + +/* @@? 17:9 Error SyntaxError: Expected '{', got 'identification literal'. */ +/* @@? 17:18 Error SyntaxError: Unexpected token '{'. */ +/* @@? 19:1 Error TypeError: Unresolved reference functioew */ +/* @@? 19:11 Error SyntaxError: Unexpected token 'Nu'. */ +/* @@? 19:11 Error TypeError: Unresolved reference Nu */ +/* @@? 20:1 Error SyntaxError: Unexpected token, expected an identifier. */ +/* @@? 20:1 Error TypeError: Unresolved reference nt */ +/* @@? 20:10 Error SyntaxError: Unexpected token 'A'. */ +/* @@? 20:10 Error TypeError: Class name 'A' used in the wrong context */ +/* @@? 20:12 Error SyntaxError: Unexpected token '{'. */ +/* @@? 22:11 Error SyntaxError: Unexpected token 'Nu'. */ +/* @@? 23:1 Error SyntaxError: Unexpected token, expected an identifier. */ +/* @@? 24:1 Error SyntaxError: Unexpected token ')'. */ +/* @@? 24:2 Error SyntaxError: Unexpected token 'void'. */ +/* @@? 24:8 Error SyntaxError: Unexpected token, expected an identifier. */ +/* @@? 24:8 Error TypeError: Unresolved reference nt */ +/* @@? 24:16 Error SyntaxError: Unexpected token ','. */ +/* @@? 24:21 Error SyntaxError: Label must be followed by a loop statement. */ +/* @@? 24:21 Error TypeError: Unresolved reference s */ +/* @@? 24:23 Error SyntaxError: Unexpected token 'A'. */ +/* @@? 24:23 Error TypeError: Class name 'A' used in the wrong context */ +/* @@? 24:25 Error SyntaxError: Unexpected token '{'. */ +/* @@? 25:1 Error SyntaxError: Unexpected token 'int'. */ +/* @@? 25:5 Error SyntaxError: Unexpected token '='. */ +/* @@? 26:1 Error SyntaxError: Unexpected token ')'. */ +/* @@? 26:3 Error SyntaxError: Unexpected token '=>'. */ +/* @@? 26:13 Error SyntaxError: Unexpected token, expected an identifier. */ +/* @@? 26:13 Error TypeError: Cannot find type ''. */ +/* @@? 26:14 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 26:14 Error SyntaxError: Expected '=>', got '+'. */ +/* @@? 26:15 Error SyntaxError: Unexpected token ')'. */ +/* @@? 26:16 Error SyntaxError: Unexpected token ':'. */ +/* @@? 26:18 Error TypeError: The type of parameter 'A6' cannot be inferred */ +/* @@? 26:18 Error TypeError: Bad operand type, the types of the operands must be numeric type. */ +/* @@? 26:25 Error TypeError: Unresolved reference reƒurn */ +/* @@? 26:32 Error SyntaxError: Unexpected token '_ew'. */ +/* @@? 26:32 Error TypeError: Unresolved reference _ew */ +/* @@? 26:36 Error SyntaxError: Unexpected token 'B'. */ +/* @@? 26:36 Error TypeError: No static $_invoke method and static $_instantiate method in B. B() is not allowed. */ +/* @@? 26:36 Error TypeError: Type 'B' has no call signatures. */ +/* @@? 26:40 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 27:2 Error TypeError: Unresolved reference ó */ +/* @@? 71:60 Error SyntaxError: Expected '}', got 'eos'. */ \ No newline at end of file diff --git a/ets2panda/util/ustring.h b/ets2panda/util/ustring.h index a1fc97e97d..4437014055 100644 --- a/ets2panda/util/ustring.h +++ b/ets2panda/util/ustring.h @@ -234,6 +234,10 @@ public: class Constants { public: + static constexpr uint16_t UTF8_2BYTE_REQUIRED = 2; + static constexpr uint16_t UTF8_3BYTE_REQUIRED = 3; + static constexpr uint16_t UTF8_4BYTE_REQUIRED = 4; + static constexpr uint16_t UTF8_1BYTE_LIMIT = 0x80; static constexpr uint16_t UTF8_2BYTE_LIMIT = 0x800; static constexpr uint32_t UTF8_3BYTE_LIMIT = 0x10000; @@ -375,22 +379,25 @@ char32_t StringView::Iterator::DecodeCP([[maybe_unused]] size_t *cpSize) const } const auto *iterNext = iter_; + const auto remain = static_cast(sv_.end() - iterNext); char32_t cu0 = static_cast(*iterNext++); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) char32_t res {}; if (cu0 < Constants::UTF8_1BYTE_LIMIT) { res = cu0; - } else if ((cu0 & Constants::UTF8_3BYTE_HEADER) == Constants::UTF8_2BYTE_HEADER) { + } else if ((cu0 & Constants::UTF8_3BYTE_HEADER) == Constants::UTF8_2BYTE_HEADER && + remain >= Constants::UTF8_2BYTE_REQUIRED) { char32_t cu1 = static_cast(*iterNext++); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) res = ((cu0 & Constants::UTF8_2BYTE_MASK) << Constants::UTF8_2BYTE_SHIFT) | (cu1 & Constants::UTF8_CONT_MASK); - } else if ((cu0 & Constants::UTF8_4BYTE_HEADER) == Constants::UTF8_3BYTE_HEADER) { + } else if ((cu0 & Constants::UTF8_4BYTE_HEADER) == Constants::UTF8_3BYTE_HEADER && + remain >= Constants::UTF8_3BYTE_REQUIRED) { char32_t cu1 = static_cast(*iterNext++); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) char32_t cu2 = static_cast(*iterNext++); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) res = ((cu0 & Constants::UTF8_3BYTE_MASK) << Constants::UTF8_3BYTE_SHIFT) | ((cu1 & Constants::UTF8_CONT_MASK) << Constants::UTF8_2BYTE_SHIFT) | (cu2 & Constants::UTF8_CONT_MASK); } else if (((cu0 & Constants::UTF8_DECODE_4BYTE_MASK) == Constants::UTF8_4BYTE_HEADER) && - (cu0 <= Constants::UTF8_DECODE_4BYTE_LIMIT)) { + cu0 <= Constants::UTF8_DECODE_4BYTE_LIMIT && remain >= Constants::UTF8_4BYTE_REQUIRED) { char32_t cu1 = static_cast(*iterNext++); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) char32_t cu2 = static_cast(*iterNext++); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) char32_t cu3 = static_cast(*iterNext++); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) -- Gitee From 1e2f6d99e8d0af69f487d9aa1b65a24414ed7f00 Mon Sep 17 00:00:00 2001 From: xuxinjie4 Date: Tue, 13 May 2025 11:56:06 +0800 Subject: [PATCH 185/268] Fix union infer bug Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC7BAF?from=project-issue Signed-off-by: xuxinjie4 --- ets2panda/checker/ETSchecker.h | 2 ++ ets2panda/checker/ets/function.cpp | 24 +++++++++----- .../ets/type_param_infer_in_union_1.ets | 28 +++++++++++++++++ .../ets/type_param_infer_in_union_2.ets | 29 +++++++++++++++++ .../ets/type_param_infer_in_union_3.ets | 31 +++++++++++++++++++ 5 files changed, 106 insertions(+), 8 deletions(-) create mode 100644 ets2panda/test/runtime/ets/type_param_infer_in_union_1.ets create mode 100644 ets2panda/test/runtime/ets/type_param_infer_in_union_2.ets create mode 100644 ets2panda/test/runtime/ets/type_param_infer_in_union_3.ets diff --git a/ets2panda/checker/ETSchecker.h b/ets2panda/checker/ETSchecker.h index dfc8762e5a..a7bbaa288a 100644 --- a/ets2panda/checker/ETSchecker.h +++ b/ets2panda/checker/ETSchecker.h @@ -411,6 +411,8 @@ public: { return Allocator()->New(*src); } + bool ValidateTypeSubstitution(const ArenaVector &typeParams, Type *ctype, Type *argumentType, + Substitution *substitution); void EmplaceSubstituted(Substitution *substitution, ETSTypeParameter *tparam, Type *typeArg); [[nodiscard]] bool EnhanceSubstitutionForType(const ArenaVector &typeParams, Type *paramType, Type *argumentType, Substitution *substitution); diff --git a/ets2panda/checker/ets/function.cpp b/ets2panda/checker/ets/function.cpp index 94db51adb5..f48e7a8ece 100644 --- a/ets2panda/checker/ets/function.cpp +++ b/ets2panda/checker/ets/function.cpp @@ -126,18 +126,26 @@ bool ETSChecker::EnhanceSubstitutionForType(const ArenaVector &typeParam return true; } +bool ETSChecker::ValidateTypeSubstitution(const ArenaVector &typeParams, Type *ctype, Type *argumentType, + Substitution *substitution) +{ + if (!EnhanceSubstitutionForType(typeParams, ctype, argumentType, substitution)) { + return false; + } + return !ctype->IsETSTypeParameter() || + (substitution->count(ctype->AsETSTypeParameter()) > 0 && + Relation()->IsAssignableTo(argumentType, substitution->at(ctype->AsETSTypeParameter()))); +} + bool ETSChecker::EnhanceSubstitutionForUnion(const ArenaVector &typeParams, ETSUnionType *paramUn, Type *argumentType, Substitution *substitution) { if (!argumentType->IsETSUnionType()) { - return std::any_of( - paramUn->ConstituentTypes().begin(), paramUn->ConstituentTypes().end(), - [this, typeParams, argumentType, substitution](Type *ctype) { - return EnhanceSubstitutionForType(typeParams, ctype, argumentType, substitution) && - (!ctype->IsETSTypeParameter() || - (substitution->find(ctype->AsETSTypeParameter()) != substitution->end() && - Relation()->IsAssignableTo(argumentType, substitution->at(ctype->AsETSTypeParameter())))); - }); + bool foundValid = false; + for (Type *ctype : paramUn->ConstituentTypes()) { + foundValid |= ValidateTypeSubstitution(typeParams, ctype, argumentType, substitution); + } + return foundValid; } auto *const argUn = argumentType->AsETSUnionType(); diff --git a/ets2panda/test/runtime/ets/type_param_infer_in_union_1.ets b/ets2panda/test/runtime/ets/type_param_infer_in_union_1.ets new file mode 100644 index 0000000000..4f9604f115 --- /dev/null +++ b/ets2panda/test/runtime/ets/type_param_infer_in_union_1.ets @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class A{} +function foo1(array:Iterable|U>){ + return "foo1 should be ok" +} +function foo2(array:Iterable>){ + return "foo2 should be ok too" +} + +function main(){ + let a = [1,2,3] + assertEQ(foo1(a), "foo1 should be ok") + assertEQ(foo2(a), "foo2 should be ok too") +} \ No newline at end of file diff --git a/ets2panda/test/runtime/ets/type_param_infer_in_union_2.ets b/ets2panda/test/runtime/ets/type_param_infer_in_union_2.ets new file mode 100644 index 0000000000..487dfda9d3 --- /dev/null +++ b/ets2panda/test/runtime/ets/type_param_infer_in_union_2.ets @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class A { } +class B { } + +function testNested(data: A> | U): string { + return "nested passed"; +} + +function main() { + const validInput: A> = new A>(); + assertEQ(testNested(validInput), "nested passed"); + + const validValue = 42; + assertEQ(testNested(validValue), "nested passed"); +} \ No newline at end of file diff --git a/ets2panda/test/runtime/ets/type_param_infer_in_union_3.ets b/ets2panda/test/runtime/ets/type_param_infer_in_union_3.ets new file mode 100644 index 0000000000..ced320a63b --- /dev/null +++ b/ets2panda/test/runtime/ets/type_param_infer_in_union_3.ets @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class A { } + +function testConstraints(arg: A | U[] | U): string { + return "constraints passed"; +} + +function main() { + const valid1: A = new A(); + assertEQ(testConstraints(valid1), "constraints passed"); + + const valid2 = ["text"]; + assertEQ(testConstraints(valid2), "constraints passed"); + + const valid3 = "text"; + assertEQ(testConstraints(valid3), "constraints passed"); +} \ No newline at end of file -- Gitee From 0a2660bdc127ffa9a8f94cf5497bc5353056942d Mon Sep 17 00:00:00 2001 From: xuxinjie4 Date: Fri, 25 Apr 2025 16:14:54 +0800 Subject: [PATCH 186/268] Fix arrow type infer bug Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC3RWG?from=project-issue Signed-off-by: xuxinjie4 --- ets2panda/checker/ETSAnalyzer.cpp | 3 +- ets2panda/checker/ETSchecker.h | 2 + ets2panda/checker/ets/function.cpp | 112 ++++++++++++++---- ets2panda/checker/ets/function_helpers.h | 3 + .../ast/compiler/ets/inferTypeLambda_0.ets | 28 +++++ .../test/runtime/ets/inferTypeLambda_11.ets | 25 ++++ .../test/runtime/ets/inferTypeLambda_12.ets | 25 ++++ .../test/runtime/ets/inferTypeLambda_13.ets | 25 ++++ .../test/runtime/ets/inferTypeLambda_14.ets | 25 ++++ .../test/runtime/ets/inferTypeLambda_15.ets | 25 ++++ 10 files changed, 249 insertions(+), 24 deletions(-) create mode 100644 ets2panda/test/ast/compiler/ets/inferTypeLambda_0.ets create mode 100644 ets2panda/test/runtime/ets/inferTypeLambda_11.ets create mode 100644 ets2panda/test/runtime/ets/inferTypeLambda_12.ets create mode 100644 ets2panda/test/runtime/ets/inferTypeLambda_13.ets create mode 100644 ets2panda/test/runtime/ets/inferTypeLambda_14.ets create mode 100644 ets2panda/test/runtime/ets/inferTypeLambda_15.ets diff --git a/ets2panda/checker/ETSAnalyzer.cpp b/ets2panda/checker/ETSAnalyzer.cpp index 0941663949..80e75bf318 100644 --- a/ets2panda/checker/ETSAnalyzer.cpp +++ b/ets2panda/checker/ETSAnalyzer.cpp @@ -2849,12 +2849,11 @@ checker::Type *ETSAnalyzer::Check(ir::VariableDeclarator *st) const flags |= ir::ModifierFlags::OPTIONAL; } - auto *const variableType = checker->CheckVariableDeclaration(ident, ident->TypeAnnotation(), st->Init(), flags); - // Processing possible parser errors if (ident->Variable() == nullptr) { ident->Check(checker); } + auto *const variableType = checker->CheckVariableDeclaration(ident, ident->TypeAnnotation(), st->Init(), flags); // Now try to define the actual type of Identifier so that smart cast can be used in further checker processing // NOTE: T_S and K_o_t_l_i_n don't act in such way, but we can try - why not? :) diff --git a/ets2panda/checker/ETSchecker.h b/ets2panda/checker/ETSchecker.h index a7bbaa288a..b5c091e603 100644 --- a/ets2panda/checker/ETSchecker.h +++ b/ets2panda/checker/ETSchecker.h @@ -413,6 +413,8 @@ public: } bool ValidateTypeSubstitution(const ArenaVector &typeParams, Type *ctype, Type *argumentType, Substitution *substitution); + bool ProcessUntypedParameter(ir::AstNode *declNode, size_t paramIndex, Signature *paramSig, Signature *argSig, + Substitution *substitution); void EmplaceSubstituted(Substitution *substitution, ETSTypeParameter *tparam, Type *typeArg); [[nodiscard]] bool EnhanceSubstitutionForType(const ArenaVector &typeParams, Type *paramType, Type *argumentType, Substitution *substitution); diff --git a/ets2panda/checker/ets/function.cpp b/ets2panda/checker/ets/function.cpp index f48e7a8ece..c080bcd9af 100644 --- a/ets2panda/checker/ets/function.cpp +++ b/ets2panda/checker/ets/function.cpp @@ -174,6 +174,70 @@ bool ETSChecker::EnhanceSubstitutionForUnion(const ArenaVector &typePara return true; } +bool ETSChecker::ProcessUntypedParameter(ir::AstNode *declNode, size_t paramIndex, Signature *paramSig, + Signature *argSig, Substitution *substitution) +{ + if (!declNode->IsETSParameterExpression() || !HasStatus(CheckerStatus::IN_TYPE_INFER)) { + return false; + } + + auto *paramExpr = declNode->AsETSParameterExpression(); + if (paramExpr->Ident()->TypeAnnotation() != nullptr) { + return false; + } + + Type *paramType = paramSig->Params()[paramIndex]->TsType(); + Type *inferredType = paramType->Substitute(Relation(), substitution); + + varbinder::Variable *argParam = argSig->Params()[paramIndex]; + argParam->SetTsType(inferredType); + paramExpr->Ident()->SetTsType(inferredType); + + return true; +} + +static void RemoveInvalidTypeMarkers(ir::AstNode *node) noexcept +{ + std::function doNode = [&](ir::AstNode *nn) { + if (nn->IsTyped() && !(nn->IsExpression() && nn->AsExpression()->IsTypeNode()) && + nn->AsTyped()->TsType() != nullptr && nn->AsTyped()->TsType()->IsTypeError()) { + nn->AsTyped()->SetTsType(nullptr); + } + if (nn->IsIdentifier() && nn->AsIdentifier()->TsType() != nullptr && + nn->AsIdentifier()->TsType()->IsTypeError()) { + nn->AsIdentifier()->SetVariable(nullptr); + } + if (!nn->IsETSTypeReference()) { + nn->Iterate([&](ir::AstNode *child) { doNode(child); }); + } + }; + + doNode(node); +} + +static void ResetInferredNode(ETSChecker *checker) +{ + auto relation = checker->Relation(); + auto resetFuncState = [](ir::ArrowFunctionExpression *expr) { + auto *func = expr->Function(); + func->SetSignature(nullptr); + func->ReturnStatements().clear(); + expr->SetTsType(nullptr); + }; + + const bool hasValidNode = relation->GetNode() != nullptr && relation->GetNode()->IsArrowFunctionExpression(); + if (!checker->HasStatus(CheckerStatus::IN_TYPE_INFER) || !hasValidNode) { + return; + } + + auto *arrowFunc = relation->GetNode()->AsArrowFunctionExpression(); + relation->SetNode(nullptr); + + RemoveInvalidTypeMarkers(arrowFunc); + resetFuncState(arrowFunc); + arrowFunc->Check(checker); +} + bool ETSChecker::EnhanceSubstitutionForFunction(const ArenaVector &typeParams, ETSFunctionType *paramType, Type *argumentType, Substitution *substitution) { @@ -181,32 +245,36 @@ bool ETSChecker::EnhanceSubstitutionForFunction(const ArenaVector &typeP return EnhanceSubstitutionForType(typeParams, ptype, atype, substitution); }; - if (argumentType->IsETSFunctionType()) { - auto parameterSignature = paramType->ArrowSignature(); - auto argumentSignature = argumentType->AsETSFunctionType()->ArrowSignature(); - // NOTE(gogabr): handle rest parameter for argumentSignature - if (parameterSignature->MinArgCount() < argumentSignature->MinArgCount()) { - return false; - } - bool res = true; - size_t const commonArity = std::min(argumentSignature->ArgCount(), parameterSignature->ArgCount()); - for (size_t idx = 0; idx < commonArity; idx++) { - auto *declNode = argumentSignature->Params()[idx]->Declaration()->Node(); - if (declNode->IsETSParameterExpression() && - declNode->AsETSParameterExpression()->Ident()->TypeAnnotation() == nullptr) { - continue; - } - res &= enhance(parameterSignature->Params()[idx]->TsType(), argumentSignature->Params()[idx]->TsType()); - } + if (!argumentType->IsETSFunctionType()) { + return true; + } - if (argumentSignature->HasRestParameter() && parameterSignature->HasRestParameter()) { - res &= enhance(parameterSignature->RestVar()->TsType(), argumentSignature->RestVar()->TsType()); + auto *paramSig = paramType->ArrowSignature(); + auto *argSig = argumentType->AsETSFunctionType()->ArrowSignature(); + + if (paramSig->MinArgCount() < argSig->MinArgCount()) { + return false; + } + + bool res = true; + const size_t commonArity = std::min(argSig->ArgCount(), paramSig->ArgCount()); + + for (size_t idx = 0; idx < commonArity; idx++) { + auto *declNode = argSig->Params()[idx]->Declaration()->Node(); + if (ProcessUntypedParameter(declNode, idx, paramSig, argSig, substitution)) { + continue; } - res &= enhance(parameterSignature->ReturnType(), argumentSignature->ReturnType()); - return res; + res &= enhance(paramSig->Params()[idx]->TsType(), argSig->Params()[idx]->TsType()); } - return true; + ResetInferredNode(this); + + if (argSig->HasRestParameter() && paramSig->HasRestParameter()) { + res &= enhance(paramSig->RestVar()->TsType(), argSig->RestVar()->TsType()); + } + res &= enhance(paramSig->ReturnType(), argSig->ReturnType()); + + return res; } // Try to find the base type somewhere in object subtypes. Incomplete, yet safe diff --git a/ets2panda/checker/ets/function_helpers.h b/ets2panda/checker/ets/function_helpers.h index e44d54ffc0..1051bb4987 100644 --- a/ets2panda/checker/ets/function_helpers.h +++ b/ets2panda/checker/ets/function_helpers.h @@ -100,6 +100,9 @@ static void InferUntilFail(Signature const *const signature, const ArenaVectorIsArrowFunctionExpression()) { + checker->Relation()->SetNode(arg); + } if (checker->EnhanceSubstitutionForType(sigInfo->typeParams, paramType, argType, substitution)) { inferStatus[ix] = true; diff --git a/ets2panda/test/ast/compiler/ets/inferTypeLambda_0.ets b/ets2panda/test/ast/compiler/ets/inferTypeLambda_0.ets new file mode 100644 index 0000000000..c4664c65f9 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/inferTypeLambda_0.ets @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +function foo(arr:T[], f:(a:T[])=>string){ + return f(arr[0]) // CTE +} + +function bar(arr:number[]){ + return foo(arr, (a):string=>{ + let res = a.toString(); + return res + }) +} + +/* @@? 17:12 Error TypeError: No matching call signature for (T) */ +/* @@? 17:14 Error TypeError: Type 'T' is not compatible with type 'Array' at index 1 */ diff --git a/ets2panda/test/runtime/ets/inferTypeLambda_11.ets b/ets2panda/test/runtime/ets/inferTypeLambda_11.ets new file mode 100644 index 0000000000..c3222907b0 --- /dev/null +++ b/ets2panda/test/runtime/ets/inferTypeLambda_11.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function foo(arr:T[], f:(a:T)=>string){ + return f(arr[0]) +} + +function bar(arr:number[]){ + return foo(arr, a=>a.toString()) +} + +function main(){ + assertTrue(bar([1,2,3,4]) == "1") +} \ No newline at end of file diff --git a/ets2panda/test/runtime/ets/inferTypeLambda_12.ets b/ets2panda/test/runtime/ets/inferTypeLambda_12.ets new file mode 100644 index 0000000000..3599d278ce --- /dev/null +++ b/ets2panda/test/runtime/ets/inferTypeLambda_12.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function foo(arr:T[], f:(a:T|Object)=>string){ + return f(arr[1]) +} + +function bar(arr:number[]){ + return foo(arr, a=>a.toString()) +} + +function main(){ + assertTrue(bar([1,2,3,4]) == "2") +} \ No newline at end of file diff --git a/ets2panda/test/runtime/ets/inferTypeLambda_13.ets b/ets2panda/test/runtime/ets/inferTypeLambda_13.ets new file mode 100644 index 0000000000..5c41a4301c --- /dev/null +++ b/ets2panda/test/runtime/ets/inferTypeLambda_13.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function foo(arr:T[], f:(a:T[])=>string){ + return f(arr) +} + +function bar(arr:number[]){ + return foo(arr, a=>a.toString()) +} + +function main(){ + assertTrue(bar([1,2,3,4]) == "1,2,3,4") +} \ No newline at end of file diff --git a/ets2panda/test/runtime/ets/inferTypeLambda_14.ets b/ets2panda/test/runtime/ets/inferTypeLambda_14.ets new file mode 100644 index 0000000000..0dfd8932a1 --- /dev/null +++ b/ets2panda/test/runtime/ets/inferTypeLambda_14.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function foo(arr:FixedArray, f:(a:FixedArray)=>string){ + return f(arr) +} + +function bar(arr:FixedArray){ + return foo(arr, a=>a.toString()) +} + +function main(){ + assertTrue(bar([1,2,3,4]) == "1,2,3,4") +} \ No newline at end of file diff --git a/ets2panda/test/runtime/ets/inferTypeLambda_15.ets b/ets2panda/test/runtime/ets/inferTypeLambda_15.ets new file mode 100644 index 0000000000..4c7191af26 --- /dev/null +++ b/ets2panda/test/runtime/ets/inferTypeLambda_15.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function foo(arr:T[], f:(a:[T, string])=>string){ + return f([arr[0], "1"]) +} + +function bar(arr:number[]){ + return foo(arr, a=>a.toString()) +} + +function main(){ + assertTrue(bar([1,2,3,4]) == "1,1") +} \ No newline at end of file -- Gitee From 51a14f70b0d43cf36c70ec5606603aecf5656c54 Mon Sep 17 00:00:00 2001 From: xuxinjie4 Date: Thu, 8 May 2025 15:58:18 +0800 Subject: [PATCH 187/268] Fix readonly bug Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC362Y?from=project-issue Signed-off-by: xuxinjie4 --- ets2panda/checker/types/ets/etsTupleType.cpp | 52 +++++++-------- ets2panda/checker/types/ets/etsTupleType.h | 2 + ets2panda/checker/types/ets/etsUnionType.cpp | 66 +++++++++++++------ ets2panda/checker/types/ets/etsUnionType.h | 3 + .../ast/compiler/ets/readonly_array01.ets | 23 +++++++ .../ast/compiler/ets/readonly_array02.ets | 25 +++++++ 6 files changed, 124 insertions(+), 47 deletions(-) create mode 100644 ets2panda/test/ast/compiler/ets/readonly_array01.ets create mode 100644 ets2panda/test/ast/compiler/ets/readonly_array02.ets diff --git a/ets2panda/checker/types/ets/etsTupleType.cpp b/ets2panda/checker/types/ets/etsTupleType.cpp index fc5c9a9aec..7a18c2ab03 100644 --- a/ets2panda/checker/types/ets/etsTupleType.cpp +++ b/ets2panda/checker/types/ets/etsTupleType.cpp @@ -69,6 +69,20 @@ Type *ETSTupleType::GetTypeAtIndex(const TupleSizeType index) const return GetTupleTypesList().at(index); } +bool ETSTupleType::CheckElementsIdentical(TypeRelation *relation, const ETSTupleType *other) const +{ + if (GetTupleSize() != other->GetTupleSize()) { + return false; + } + + for (TupleSizeType idx = 0; idx < GetTupleSize(); ++idx) { + if (!relation->IsIdenticalTo(GetTypeAtIndex(idx), other->GetTypeAtIndex(idx))) { + return false; + } + } + return true; +} + void ETSTupleType::Identical([[maybe_unused]] TypeRelation *const relation, Type *const other) { if (!other->IsETSTupleType()) { @@ -77,15 +91,14 @@ void ETSTupleType::Identical([[maybe_unused]] TypeRelation *const relation, Type const auto *const otherTuple = other->AsETSTupleType(); - if (GetTupleSize() != otherTuple->GetTupleSize()) { + if (HasTypeFlag(TypeFlag::READONLY) != other->HasTypeFlag(TypeFlag::READONLY)) { + relation->Result(false); return; } - for (TupleSizeType idx = 0; idx < GetTupleSize(); ++idx) { - if (!relation->IsIdenticalTo(GetTypeAtIndex(idx), otherTuple->GetTypeAtIndex(idx))) { - relation->Result(false); - return; - } + if (!CheckElementsIdentical(relation, otherTuple)) { + relation->Result(false); + return; } relation->Result(true); @@ -102,27 +115,9 @@ bool ETSTupleType::AssignmentSource(TypeRelation *const relation, Type *const ta void ETSTupleType::AssignmentTarget(TypeRelation *const relation, Type *const source) { - if (source->HasTypeFlag(TypeFlag::READONLY)) { - relation->Result(false); - return; - } - - if (!source->IsETSTupleType()) { - return; - } - - const auto *const sourceTuple = source->AsETSTupleType(); - if (sourceTuple->GetTupleSize() != GetTupleSize()) { - return; - } - - for (TupleSizeType idx = 0; idx < GetTupleSize(); ++idx) { - if (!relation->IsIdenticalTo(GetTypeAtIndex(idx), sourceTuple->GetTypeAtIndex(idx))) { - return; - } + if (!source->HasTypeFlag(TypeFlag::READONLY) && source->IsETSTupleType()) { + source->AsETSTupleType()->IsSubtypeOf(relation, this); } - - relation->Result(true); } Type *ETSTupleType::Substitute(TypeRelation *relation, const Substitution *substitution) @@ -143,6 +138,11 @@ void ETSTupleType::IsSubtypeOf(TypeRelation *const relation, Type *target) relation->Result(true); return; } + if (target->IsETSTupleType()) { + if (!HasTypeFlag(TypeFlag::READONLY) && CheckElementsIdentical(relation, target->AsETSTupleType())) { + relation->Result(true); + } + } } void ETSTupleType::Cast(TypeRelation *const relation, Type *const target) diff --git a/ets2panda/checker/types/ets/etsTupleType.h b/ets2panda/checker/types/ets/etsTupleType.h index 31aca83175..53418a226c 100644 --- a/ets2panda/checker/types/ets/etsTupleType.h +++ b/ets2panda/checker/types/ets/etsTupleType.h @@ -70,6 +70,8 @@ public: void ToDebugInfoType(std::stringstream &ss) const override; private: + bool CheckElementsIdentical(TypeRelation *relation, const ETSTupleType *other) const; + const ArenaVector typeList_; ETSObjectType *wrapperType_; }; diff --git a/ets2panda/checker/types/ets/etsUnionType.cpp b/ets2panda/checker/types/ets/etsUnionType.cpp index fc29b8b98b..2bbdf54442 100644 --- a/ets2panda/checker/types/ets/etsUnionType.cpp +++ b/ets2panda/checker/types/ets/etsUnionType.cpp @@ -14,9 +14,10 @@ */ #include +#include "etsObjectType.h" #include "etsUnionType.h" - #include "checker/ets/conversion.h" +#include "checker/types/ets/etsTupleType.h" #include "checker/types/globalTypesHolder.h" #include "checker/ETSchecker.h" @@ -377,6 +378,25 @@ bool ETSUnionType::IsAssignableType(checker::Type *sourceType) const noexcept return false; } +checker::Type *ETSUnionType::HandleNumericPrecedence( + checker::ETSChecker *checker, checker::ETSObjectType *objectType, checker::Type *sourceType, + std::map &numericTypes) const noexcept +{ + auto const sourceId = + (objectType != nullptr) ? ETSObjectType::GetPrecedence(checker, objectType) : Type::GetPrecedence(sourceType); + if (sourceId > 0U) { + for (auto const [id, type] : numericTypes) { + if (id >= sourceId) { + return type; + } + } + if (sourceType->IsConstantType() && !numericTypes.empty()) { + return numericTypes.begin()->second; + } + } + return nullptr; +} + // NOTE! When calling this method we assume that 'AssignmentTarget(...)' check was passes successfully, // thus the required assignable type always exists. checker::Type *ETSUnionType::GetAssignableType(checker::ETSChecker *checker, checker::Type *sourceType) const noexcept @@ -385,34 +405,37 @@ checker::Type *ETSUnionType::GetAssignableType(checker::ETSChecker *checker, che return sourceType; } - auto *objectType = sourceType->IsETSObjectType() ? sourceType->AsETSObjectType() : nullptr; - if (objectType != nullptr && (!objectType->HasObjectFlag(ETSObjectFlags::BUILTIN_TYPE) || - objectType->HasObjectFlag(ETSObjectFlags::BUILTIN_STRING))) { - // NOTE: here wo don't cast the actual type to possible base type using in the union, but use it as is! - return sourceType; - } - + auto *objectType = sourceType->IsETSObjectType() ? sourceType->AsETSObjectType() + : sourceType->IsETSTupleType() ? sourceType->AsETSTupleType()->GetWrapperType() + : nullptr; std::map numericTypes {}; bool const isBool = objectType != nullptr ? objectType->HasObjectFlag(ETSObjectFlags::BUILTIN_BOOLEAN) : sourceType->HasTypeFlag(TypeFlag::ETS_BOOLEAN); bool const isChar = objectType != nullptr ? objectType->HasObjectFlag(ETSObjectFlags::BUILTIN_CHAR) : sourceType->HasTypeFlag(TypeFlag::CHAR); + + if (objectType != nullptr) { + if (objectType->IsETSResizableArrayType() || sourceType->IsETSTupleType()) { + checker::Type *assignableType = GetAssignableBuiltinType(checker, objectType, isBool, isChar, numericTypes); + // NOTE: For array and tuple types, they may be readonly, so we cannot simply use the it + if (assignableType != nullptr && assignableType->HasTypeFlag(TypeFlag::READONLY)) { + return assignableType; + } + } + if ((!objectType->HasObjectFlag(ETSObjectFlags::BUILTIN_TYPE) || + objectType->HasObjectFlag(ETSObjectFlags::BUILTIN_STRING))) { + // NOTE: here wo don't cast the actual type to possible base type using in the union, but use it as is! + return sourceType; + } + } + if (checker::Type *assignableType = GetAssignableBuiltinType(checker, objectType, isBool, isChar, numericTypes); assignableType != nullptr) { return assignableType; } - if (auto const sourceId = - objectType != nullptr ? ETSObjectType::GetPrecedence(checker, objectType) : Type::GetPrecedence(sourceType); - sourceId > 0U) { - for (auto const [id, type] : numericTypes) { - if (id >= sourceId) { - return type; - } - } - if (sourceType->IsConstantType() && !numericTypes.empty()) { - return numericTypes.begin()->second; - } + if (auto *assignableType = HandleNumericPrecedence(checker, objectType, sourceType, numericTypes)) { + return assignableType; } for (auto *constituentType : constituentTypes_) { @@ -431,11 +454,12 @@ checker::Type *ETSUnionType::GetAssignableBuiltinType( checker::Type *assignableType = nullptr; for (auto *constituentType : constituentTypes_) { - if (!constituentType->IsETSObjectType()) { + if (!constituentType->IsETSObjectType() && !constituentType->IsETSTupleType()) { continue; } - auto *const type = constituentType->AsETSObjectType(); + auto *const type = constituentType->IsETSTupleType() ? constituentType->AsETSTupleType()->GetWrapperType() + : constituentType->AsETSObjectType(); if (type->HasObjectFlag(ETSObjectFlags::BUILTIN_BOOLEAN)) { if (isBool) { assignableType = constituentType; diff --git a/ets2panda/checker/types/ets/etsUnionType.h b/ets2panda/checker/types/ets/etsUnionType.h index d38376a8f8..12ae980aec 100644 --- a/ets2panda/checker/types/ets/etsUnionType.h +++ b/ets2panda/checker/types/ets/etsUnionType.h @@ -74,6 +74,9 @@ public: return std::all_of(constituentTypes_.cbegin(), constituentTypes_.cend(), p); } + checker::Type *HandleNumericPrecedence(checker::ETSChecker *checker, checker::ETSObjectType *objectType, + checker::Type *sourceType, + std::map &numericTypes) const noexcept; [[nodiscard]] checker::Type *GetAssignableType(ETSChecker *checker, checker::Type *sourceType) const noexcept; [[nodiscard]] std::pair GetComplimentaryType(ETSChecker *checker, checker::Type *sourceType); diff --git a/ets2panda/test/ast/compiler/ets/readonly_array01.ets b/ets2panda/test/ast/compiler/ets/readonly_array01.ets new file mode 100644 index 0000000000..d377fa27f9 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/readonly_array01.ets @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +function main() { + let v: readonly number[][] = [[1.0,2.0]] + v[0][0] = 3.0 // ok + v[0] = [] // CTE +} + +/* @@? 19:5 Error TypeError: Cannot modify an array or tuple content that has the readonly parameter */ + diff --git a/ets2panda/test/ast/compiler/ets/readonly_array02.ets b/ets2panda/test/ast/compiler/ets/readonly_array02.ets new file mode 100644 index 0000000000..282f2fcfba --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/readonly_array02.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +type U1 = number[][] | string[] +type U2 = (readonly number[][]) | (readonly string[]) + +function main() { + let v: U1 | U2 = [[1.0,2.0]] + v[0] = [1.0,3.0] // CTE, readonly array +} + +/* @@? 21:5 Error TypeError: Cannot modify an array or tuple content that has the readonly parameter */ + -- Gitee From 1c909f3a0a11d3ab1d02dcc34361f30ff6dd40d7 Mon Sep 17 00:00:00 2001 From: daizihan Date: Sun, 27 Apr 2025 10:23:06 +0800 Subject: [PATCH 188/268] Fix interface object literal in complex case Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC48K5?from=project-issue Signed-off-by: daizihan --- .../ets/interfaceObjectLiteralLowering.cpp | 10 +++--- .../test/runtime/ets/interface_objliteral.ets | 34 +++++++++++++++++++ 2 files changed, 40 insertions(+), 4 deletions(-) create mode 100644 ets2panda/test/runtime/ets/interface_objliteral.ets diff --git a/ets2panda/compiler/lowering/ets/interfaceObjectLiteralLowering.cpp b/ets2panda/compiler/lowering/ets/interfaceObjectLiteralLowering.cpp index 4b5ff91757..b430e9b49f 100644 --- a/ets2panda/compiler/lowering/ets/interfaceObjectLiteralLowering.cpp +++ b/ets2panda/compiler/lowering/ets/interfaceObjectLiteralLowering.cpp @@ -179,16 +179,18 @@ static void FillClassBody(public_lib::Context *ctx, ArenaVector * } } +// CC-OFFNXT(G.FUN.01-CPP) solid logic static void FillAnonClassBody(public_lib::Context *ctx, ArenaVector *classBody, ir::TSInterfaceDeclaration *ifaceNode, ir::ObjectExpression *objExpr, - ArenaVector &readonlyFields) + ArenaVector &readonlyFields, + checker::ETSObjectType *interfaceType = nullptr) { for (auto *extendedIface : ifaceNode->TsType()->AsETSObjectType()->Interfaces()) { - auto extendedIfaceBody = extendedIface->GetDeclNode()->AsTSInterfaceDeclaration()->Body()->Body(); - FillClassBody(ctx, classBody, extendedIfaceBody, objExpr, readonlyFields, extendedIface); + FillAnonClassBody(ctx, classBody, extendedIface->GetDeclNode()->AsTSInterfaceDeclaration(), objExpr, + readonlyFields, extendedIface); } - FillClassBody(ctx, classBody, ifaceNode->Body()->Body(), objExpr, readonlyFields); + FillClassBody(ctx, classBody, ifaceNode->Body()->Body(), objExpr, readonlyFields, interfaceType); } static checker::Type *GenerateAnonClassTypeFromInterface(public_lib::Context *ctx, diff --git a/ets2panda/test/runtime/ets/interface_objliteral.ets b/ets2panda/test/runtime/ets/interface_objliteral.ets new file mode 100644 index 0000000000..821f013ac7 --- /dev/null +++ b/ets2panda/test/runtime/ets/interface_objliteral.ets @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +interface InterfaceA { + propA: string +} +interface InterfaceAA extends InterfaceA {} + +interface InterfaceB { + propB: number; +} +interface ParentInterface extends InterfaceA, InterfaceB {} +interface ChildInterface extends ParentInterface {} + +function main() { + const obj: ChildInterface = { + propA: "Hello", + propB: 42 + } + assertEQ(obj.propA, "Hello") + assertEQ(obj.propB, 42) +} \ No newline at end of file -- Gitee From a2a8dd0dfe6d3177b649bd75aca9a139475e1a9e Mon Sep 17 00:00:00 2001 From: daizihan Date: Tue, 29 Apr 2025 16:48:08 +0800 Subject: [PATCH 189/268] Fix unexpected crash when logerror Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC4YQ3?from=project-issue Signed-off-by: daizihan --- ets2panda/checker/ets/object.cpp | 4 ++-- .../test/ast/compiler/ets/tolocalString.ets | 20 +++++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) create mode 100644 ets2panda/test/ast/compiler/ets/tolocalString.ets diff --git a/ets2panda/checker/ets/object.cpp b/ets2panda/checker/ets/object.cpp index eceaf9209b..05faafa378 100644 --- a/ets2panda/checker/ets/object.cpp +++ b/ets2panda/checker/ets/object.cpp @@ -2291,8 +2291,8 @@ void ETSChecker::CheckProperties(ETSObjectType *classType, ir::ClassDefinition * interfaceFound->GetDeclNode()->Start()); return; } - LogError(diagnostic::INHERITED_CLASS_TYPE_MISMATCH, {classType->SuperType()->Name(), targetType, it->Name()}, - classDef->Super()->Start()); + auto pos = classDef->Super() == nullptr ? classDef->Ident()->Start() : classDef->Super()->Start(); + LogError(diagnostic::INHERITED_CLASS_TYPE_MISMATCH, {classType->SuperType()->Name(), targetType, it->Name()}, pos); } void ETSChecker::CheckReadonlyClassPropertyInImplementedInterface(ETSObjectType *classType, diff --git a/ets2panda/test/ast/compiler/ets/tolocalString.ets b/ets2panda/test/ast/compiler/ets/tolocalString.ets new file mode 100644 index 0000000000..e2576c4fd4 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/tolocalString.ets @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class A { + toLocaleString = () => {} +} + +/* @@? 16:7 Error TypeError: Cannot inherit from class Object, because field toLocaleString is inherited with a different declaration type */ -- Gitee From e1346f6a6c0a491c8851a3624385c728d519026f Mon Sep 17 00:00:00 2001 From: daizihan Date: Tue, 22 Apr 2025 19:04:36 +0800 Subject: [PATCH 190/268] Fix union call in generic and overload scenario Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC35UH?from=project-issue Signed-off-by: daizihan --- ets2panda/checker/ets/helpers.cpp | 3 +- ets2panda/compiler/core/ETSCompiler.cpp | 2 +- .../compiler/lowering/ets/lambdaLowering.cpp | 7 ++-- .../compiler/lowering/ets/unionLowering.cpp | 22 +++++------- .../test/ast/compiler/ets/union_method_3.ets | 4 +-- ets2panda/test/runtime/ets/generic_union.ets | 36 +++++++++++++++++++ ets2panda/test/runtime/ets/union_call.ets | 34 ++++++++++++++++++ ets2panda/util/diagnostic/semantic.yaml | 8 ++--- 8 files changed, 88 insertions(+), 28 deletions(-) create mode 100644 ets2panda/test/runtime/ets/generic_union.ets create mode 100644 ets2panda/test/runtime/ets/union_call.ets diff --git a/ets2panda/checker/ets/helpers.cpp b/ets2panda/checker/ets/helpers.cpp index d2e28eaec7..e321d18ba4 100644 --- a/ets2panda/checker/ets/helpers.cpp +++ b/ets2panda/checker/ets/helpers.cpp @@ -3084,7 +3084,8 @@ checker::ETSFunctionType *ETSChecker::IntersectSignatureSets(const checker::ETSF { auto sameSig = [this](checker::Signature *leftSig, checker::Signature *rightSig) { auto relation = Relation(); - if (leftSig->Flags() != rightSig->Flags()) { + if ((leftSig->Flags() & ~checker::SignatureFlags::FINAL) != + (rightSig->Flags() & ~checker::SignatureFlags::FINAL)) { return false; } return relation->SignatureIsIdenticalTo(rightSig, leftSig); diff --git a/ets2panda/compiler/core/ETSCompiler.cpp b/ets2panda/compiler/core/ETSCompiler.cpp index efe0fbb8cb..0ecd925cb5 100644 --- a/ets2panda/compiler/core/ETSCompiler.cpp +++ b/ets2panda/compiler/core/ETSCompiler.cpp @@ -776,7 +776,7 @@ void ETSCompiler::EmitCall(const ir::CallExpression *expr, compiler::VReg &calle // NOTE: need to refactor: type of member expression object can be obtained via // me->ObjType() or me->Object()->TsType() and they may differ!!!! } else if (me->ObjType() == etsg->Checker()->GlobalETSObjectType() && - me->Object()->TsType()->IsETSUnionType()) { + (etsg->Checker()->GetApparentType(me->Object()->TsType())->IsETSUnionType())) { etsg->CallByName(expr, signature, calleeReg, expr->Arguments()); } else { etsg->CallVirtual(expr, signature, calleeReg, expr->Arguments()); diff --git a/ets2panda/compiler/lowering/ets/lambdaLowering.cpp b/ets2panda/compiler/lowering/ets/lambdaLowering.cpp index 1f4fc3dedb..5937da285f 100644 --- a/ets2panda/compiler/lowering/ets/lambdaLowering.cpp +++ b/ets2panda/compiler/lowering/ets/lambdaLowering.cpp @@ -1037,7 +1037,7 @@ static bool IsVariableOriginalAccessor(const varbinder::Variable *var) return checker::ETSChecker::IsVariableGetterSetter(var) && !(checker::ETSChecker::IsVariableExtensionAccessor(var)); } -static bool IsFunctionOrMethodCall(ir::CallExpression const *node) +static bool IsFunctionOrMethodCall(checker::ETSChecker *checker, ir::CallExpression const *node) { auto const *callee = node->Callee(); if (callee->TsType() != nullptr && callee->TsType()->IsETSExtensionFuncHelperType()) { @@ -1048,7 +1048,7 @@ static bool IsFunctionOrMethodCall(ir::CallExpression const *node) // Not skip if invoke pattern Union.() where field is of ETSArrowType if (callee->IsMemberExpression()) { auto me = callee->AsMemberExpression(); - if (me->Object()->TsType() != nullptr && me->Object()->TsType()->IsETSUnionType() && + if (me->Object()->TsType() != nullptr && checker->GetApparentType(me->Object()->TsType())->IsETSUnionType() && me->TsType()->IsETSMethodType()) { return true; } @@ -1214,7 +1214,8 @@ bool LambdaConversionPhase::PerformForModule(public_lib::Context *ctx, parser::P [ctx](ir::AstNode *node) { return LowerTypeNodeIfNeeded(ctx, node); }, Name()); auto insertInvokeIfNeeded = [ctx](ir::AstNode *node) { - if (node->IsCallExpression() && !IsFunctionOrMethodCall(node->AsCallExpression()) && + if (node->IsCallExpression() && + !IsFunctionOrMethodCall(ctx->checker->AsETSChecker(), node->AsCallExpression()) && !IsRedirectingConstructorCall(node->AsCallExpression())) { return InsertInvokeCall(ctx, node->AsCallExpression()); } diff --git a/ets2panda/compiler/lowering/ets/unionLowering.cpp b/ets2panda/compiler/lowering/ets/unionLowering.cpp index 8b94066abc..537de9bed0 100644 --- a/ets2panda/compiler/lowering/ets/unionLowering.cpp +++ b/ets2panda/compiler/lowering/ets/unionLowering.cpp @@ -77,7 +77,8 @@ static ir::ClassDefinition *GetUnionAccessClass(checker::ETSChecker *checker, va } static std::tuple CreateNamedAccessMethod( - checker::ETSChecker *checker, varbinder::VarBinder *varbinder, ir::MemberExpression *expr) + checker::ETSChecker *checker, varbinder::VarBinder *varbinder, ir::MemberExpression *expr, + checker::Signature *signature) { auto allocator = checker->Allocator(); auto unionType = checker->GetApparentType(checker->GetNonNullishType(expr->Object()->TsType()))->AsETSUnionType(); @@ -87,14 +88,11 @@ static std::tuple CreateNamedA // Create method name for synthetic class auto *methodIdent = checker->AllocNode(methodName, allocator); - // Create the synthetic function node - auto *sig = expr->Parent()->AsCallExpression()->Signature(); - ArenaVector params {allocator->Adapter()}; - for (auto param : sig->Function()->Params()) { + for (auto param : signature->Function()->Params()) { params.emplace_back(param->Clone(allocator, nullptr)->AsETSParameterExpression()); } - auto returnTypeAnno = checker->AllocNode(sig->ReturnType(), allocator); + auto returnTypeAnno = checker->AllocNode(signature->ReturnType(), allocator); auto *func = checker->AllocNode( allocator, ir::ScriptFunction::ScriptFunctionData { @@ -174,14 +172,10 @@ static varbinder::LocalVariable *CreateNamedAccess(checker::ETSChecker *checker, // arrow type fields should be processed as property access not method invocation if (type->IsETSMethodType() && !type->IsETSArrowType()) { - if (type->AsETSFunctionType()->CallSignatures().size() != 1) { - checker->LogError(diagnostic::UNION_METHOD_SIGNATURE, {}, expr->Start()); - } - auto parent = expr->Parent(); - ES2PANDA_ASSERT(parent->IsCallExpression() && parent->AsCallExpression()->Callee() == expr && - parent->AsCallExpression()->Signature()->HasFunction()); - auto [var, sig] = CreateNamedAccessMethod(checker, varbinder, expr); - ES2PANDA_ASSERT(parent->IsCallExpression()); + auto parent = expr->Parent()->AsCallExpression(); + ES2PANDA_ASSERT(parent->Callee() == expr && parent->Signature()->HasFunction()); + + auto [var, sig] = CreateNamedAccessMethod(checker, varbinder, expr, parent->Signature()); parent->AsCallExpression()->SetSignature(sig); return var; } diff --git a/ets2panda/test/ast/compiler/ets/union_method_3.ets b/ets2panda/test/ast/compiler/ets/union_method_3.ets index a6c0a9191e..80b3ba46de 100644 --- a/ets2panda/test/ast/compiler/ets/union_method_3.ets +++ b/ets2panda/test/ast/compiler/ets/union_method_3.ets @@ -24,7 +24,5 @@ class B { } function foo(x: A|B) { - /* @@ label */x.foo("123") + x.foo("123") } - -/* @@@ label Error TypeError: Union constituent types should have only one common method signature. */ diff --git a/ets2panda/test/runtime/ets/generic_union.ets b/ets2panda/test/runtime/ets/generic_union.ets new file mode 100644 index 0000000000..08d2e64448 --- /dev/null +++ b/ets2panda/test/runtime/ets/generic_union.ets @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class A { + foo(a : int){} + foo() { + return 1 + } +} + +class B { + foo(a : int){} + foo() { + return 2 + } +} +type AAA = A | B +function foo(a : T) { + return a.foo() +} +function main() { + assertEQ(foo(new A()), 1) + assertEQ(foo(new B()), 2) +} diff --git a/ets2panda/test/runtime/ets/union_call.ets b/ets2panda/test/runtime/ets/union_call.ets new file mode 100644 index 0000000000..bb39f1e813 --- /dev/null +++ b/ets2panda/test/runtime/ets/union_call.ets @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class A { + foo() { + return 1 + } +} + +final class B { + foo() { + return 2 + } +} +type AAA = A | B +function foo(a : AAA) { + return a.foo() +} +function main() { + assertEQ(foo(new A()), 1) + assertEQ(foo(new B()), 2) +} diff --git a/ets2panda/util/diagnostic/semantic.yaml b/ets2panda/util/diagnostic/semantic.yaml index 1d2b8db7e1..1132d7d595 100644 --- a/ets2panda/util/diagnostic/semantic.yaml +++ b/ets2panda/util/diagnostic/semantic.yaml @@ -1111,9 +1111,9 @@ semantic: id: 279 message: "Tuple types with arity >16 are not yet implemented" -- name: UNION_METHOD_SIGNATURE +- name: PROPERTY_MAYBE_MISSING_INIT id: 280 - message: "Union constituent types should have only one common method signature." + message: "Property '{}' might not have been initialized." - name: NOT_ALLOWED_THIS_IN_UNION_TYPE id: 281 @@ -1346,7 +1346,3 @@ semantic: - name: READONLY_PROPERTY_REASSIGN id: 338 message: "The 'Readonly' property cannot be reassigned." - -- name: PROPERTY_MAYBE_MISSING_INIT - id: 339 - message: "Property '{}' might not have been initialized." -- Gitee From 7f9e0191f7245e1afc4503ef4136a82160a5c2c4 Mon Sep 17 00:00:00 2001 From: daizihan Date: Fri, 18 Apr 2025 11:35:49 +0800 Subject: [PATCH 191/268] Fix missing lambda call generation for super Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC25EY?from=project-issue Signed-off-by: daizihan --- .../compiler/lowering/ets/lambdaLowering.cpp | 3 +- .../test/runtime/ets/lambda_call_base.ets | 31 +++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 ets2panda/test/runtime/ets/lambda_call_base.ets diff --git a/ets2panda/compiler/lowering/ets/lambdaLowering.cpp b/ets2panda/compiler/lowering/ets/lambdaLowering.cpp index 5937da285f..4ea83a9a6e 100644 --- a/ets2panda/compiler/lowering/ets/lambdaLowering.cpp +++ b/ets2panda/compiler/lowering/ets/lambdaLowering.cpp @@ -996,6 +996,7 @@ static ir::AstNode *ConvertFunctionReference(public_lib::Context *ctx, ir::Expre var = mexpr->Object()->TsType()->AsETSObjectType()->GetProperty( mexpr->Property()->AsIdentifier()->Name(), checker::PropertySearchFlags::SEARCH_INSTANCE_METHOD | checker::PropertySearchFlags::SEARCH_STATIC_METHOD | + checker::PropertySearchFlags::SEARCH_IN_BASE | checker::PropertySearchFlags::DISALLOW_SYNTHETIC_METHOD_CREATION); ES2PANDA_ASSERT(var != nullptr); } @@ -1165,7 +1166,7 @@ static ir::AstNode *BuildLambdaClassWhenNeeded(public_lib::Context *ctx, ir::Ast auto *var = mexpr->Object()->TsType()->AsETSObjectType()->GetProperty( mexpr->Property()->AsIdentifier()->Name(), checker::PropertySearchFlags::SEARCH_INSTANCE_METHOD | - checker::PropertySearchFlags::SEARCH_STATIC_METHOD | + checker::PropertySearchFlags::SEARCH_STATIC_METHOD | checker::PropertySearchFlags::SEARCH_IN_BASE | checker::PropertySearchFlags::DISALLOW_SYNTHETIC_METHOD_CREATION); if (IsValidFunctionDeclVar(var) && !IsInCalleePosition(mexpr)) { return ConvertFunctionReference(ctx, mexpr); diff --git a/ets2panda/test/runtime/ets/lambda_call_base.ets b/ets2panda/test/runtime/ets/lambda_call_base.ets new file mode 100644 index 0000000000..0a34d3f244 --- /dev/null +++ b/ets2panda/test/runtime/ets/lambda_call_base.ets @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class MyDate { + public getFullYear(): int { + return 20; + } +} + +class DateC extends MyDate { + bigY() { + let x = this.getFullYear + return x(); + } +} + +function main() { + assertEQ(new DateC().bigY(), 20) +} -- Gitee From 89a86d6ccffb62aecd5026c07dc37c836affac6c Mon Sep 17 00:00:00 2001 From: daizihan Date: Fri, 18 Apr 2025 18:04:33 +0800 Subject: [PATCH 192/268] Fix oom in baseanalyzer with big switch Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC2AVH?from=project-issue Signed-off-by: daizihan -- Gitee From 6de8975b19fc481b5fee7ddf5061df5d2ae220d0 Mon Sep 17 00:00:00 2001 From: fcc Date: Mon, 31 Mar 2025 10:57:37 +0800 Subject: [PATCH 193/268] Fix segfault on qualified type name there is a infinite recursion Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IBXMVE Signed-off-by: fcc -- Gitee From 8101bbbeee1f86cc19f296e32901566cff36d7ef Mon Sep 17 00:00:00 2001 From: fcc Date: Fri, 25 Apr 2025 11:00:44 +0800 Subject: [PATCH 194/268] Fix name conflict on static and instance members According to spec, static members and instance members belongs to different name scope. They can use the same name separately. Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC3V6D Signed-off-by: fcc --- ets2panda/checker/types/ets/etsObjectType.cpp | 34 +++++++++++++++---- .../runtime/ets/class-fields-same-name.ets | 20 +++++++++++ 2 files changed, 47 insertions(+), 7 deletions(-) diff --git a/ets2panda/checker/types/ets/etsObjectType.cpp b/ets2panda/checker/types/ets/etsObjectType.cpp index f68e6e9c9e..c28e5d494d 100644 --- a/ets2panda/checker/types/ets/etsObjectType.cpp +++ b/ets2panda/checker/types/ets/etsObjectType.cpp @@ -334,20 +334,40 @@ std::vector ETSObjectType::Fields() const std::vector ETSObjectType::ForeignProperties() const { std::vector foreignProps; - std::unordered_set ownProps; + + // spec 9.3: all names in static and, separately, non-static class declaration scopes must be unique. + std::unordered_set ownInstanceProps; + std::unordered_set ownStaticProps; EnsurePropertiesInstantiated(); - ownProps.reserve(properties_.size()); + ownInstanceProps.reserve(properties_.size()); + ownStaticProps.reserve(properties_.size()); for (const auto *prop : GetAllProperties()) { - ownProps.insert(prop->Name()); + if (prop->HasFlag(varbinder::VariableFlags::STATIC)) { + ownStaticProps.insert(prop->Name()); + } else { + ownInstanceProps.insert(prop->Name()); + } } - std::map allProps {}; - Iterate([&allProps](const varbinder::LocalVariable *var) { allProps.emplace(var->Name(), var); }); + std::map allInstanceProps {}; + std::map allStaticProps {}; + Iterate([&allInstanceProps, &allStaticProps](const varbinder::LocalVariable *var) { + if (var->HasFlag(varbinder::VariableFlags::STATIC)) { + allStaticProps.emplace(var->Name(), var); + } else { + allInstanceProps.emplace(var->Name(), var); + } + }); - for (const auto &[name, var] : allProps) { - if (ownProps.find(name) == ownProps.end()) { + for (const auto &[name, var] : allInstanceProps) { + if (ownInstanceProps.find(name) == ownInstanceProps.end()) { + foreignProps.push_back(var); + } + } + for (const auto &[name, var] : allStaticProps) { + if (ownStaticProps.find(name) == ownStaticProps.end()) { foreignProps.push_back(var); } } diff --git a/ets2panda/test/runtime/ets/class-fields-same-name.ets b/ets2panda/test/runtime/ets/class-fields-same-name.ets index 82ae8aa38c..c556135949 100644 --- a/ets2panda/test/runtime/ets/class-fields-same-name.ets +++ b/ets2panda/test/runtime/ets/class-fields-same-name.ets @@ -23,9 +23,29 @@ class D extends C { public foo: int = 40 } +class E { + public static foo: int = 50 +} + +class F extends E { + public foo: int = 60 +} + +class G { + public foo: int = 70 +} + +class H extends G { + public static foo: int = 80 +} + function main(): void { assertEQ(C.foo, 10) assertEQ(new C().foo, 20) assertEQ(D.foo, 30) assertEQ(new D().foo, 40) + assertEQ(F.foo, 50) + assertEQ(new F().foo, 60) + assertEQ(H.foo, 80) + assertEQ(new H().foo, 70) } -- Gitee From 554a6e5551b85a73c0dec0fc6bd566c3f3c71a5b Mon Sep 17 00:00:00 2001 From: fcc Date: Mon, 28 Apr 2025 14:10:48 +0800 Subject: [PATCH 195/268] Fix verify failure for arrow function The generated ir are different when an arrow function body is inside a block or not. Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC4LQM Signed-off-by: fcc --- ets2panda/compiler/core/ETSCompiler.cpp | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/ets2panda/compiler/core/ETSCompiler.cpp b/ets2panda/compiler/core/ETSCompiler.cpp index 0ecd925cb5..2a24c1055f 100644 --- a/ets2panda/compiler/core/ETSCompiler.cpp +++ b/ets2panda/compiler/core/ETSCompiler.cpp @@ -1426,13 +1426,17 @@ void ETSCompiler::Compile(const ir::ReturnStatement *st) const if (argument->IsCallExpression() && argument->AsCallExpression()->Signature()->ReturnType()->IsETSVoidType()) { argument->Compile(etsg); - if (isAsyncImpl) { - etsg->LoadAccumulatorUndefined(st); + if (etsg->ReturnType()->IsETSVoidType()) { + if (isAsyncImpl) { + etsg->LoadAccumulatorUndefined(st); + etsg->ReturnAcc(st); + } else { + etsg->EmitReturnVoid(st); + } + } else { + etsg->LoadDefaultValue(st, etsg->ReturnType()); etsg->ReturnAcc(st); - return; } - - etsg->EmitReturnVoid(st); return; } -- Gitee From 0b36d33a72987513306507191ccada70b735fe5a Mon Sep 17 00:00:00 2001 From: zengzengran Date: Thu, 17 Apr 2025 23:21:18 +0800 Subject: [PATCH 196/268] Set variable Decl for identifier Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC1QG4 Description: UI feedback: When the type of property a_ in the class is a lambda, and this.a() is used to call this lambda, the Decl is not set for the variable without an identifier. On the UI side, the corresponding declaration cannot be obtained through getDeclarationFromIdentifier. Tested-by: ninja tests (passed) ets_testrunner (passed) Signed-off-by: zengzengran # --- ets2panda/checker/types/ets/etsObjectType.cpp | 11 +++++-- .../ets/accessor_functional_declaration.ets | 32 +++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) create mode 100644 ets2panda/test/runtime/ets/accessor_functional_declaration.ets diff --git a/ets2panda/checker/types/ets/etsObjectType.cpp b/ets2panda/checker/types/ets/etsObjectType.cpp index c28e5d494d..5d54c7235b 100644 --- a/ets2panda/checker/types/ets/etsObjectType.cpp +++ b/ets2panda/checker/types/ets/etsObjectType.cpp @@ -146,11 +146,18 @@ bool ETSObjectType::IsDescendantOf(const ETSObjectType *ascendant) const return this->SuperType()->IsDescendantOf(ascendant); } +static bool HasAccessor(const PropertySearchFlags &flags, const ETSFunctionType *funcType) +{ + if ((flags & (PropertySearchFlags::IS_GETTER | PropertySearchFlags::IS_SETTER)) != 0) { + return true; + } + return funcType->HasTypeFlag(TypeFlag::GETTER) || funcType->HasTypeFlag(TypeFlag::SETTER); +} + static void UpdateDeclarationForGetterSetter(varbinder::LocalVariable *res, const ETSFunctionType *funcType, const PropertySearchFlags &flags) { - if ((flags & (PropertySearchFlags::IS_GETTER | PropertySearchFlags::IS_SETTER)) == 0 || - res->Declaration() != nullptr) { + if (!HasAccessor(flags, funcType) || res->Declaration() != nullptr) { return; } auto var = funcType->CallSignatures().front()->OwnerVar(); diff --git a/ets2panda/test/runtime/ets/accessor_functional_declaration.ets b/ets2panda/test/runtime/ets/accessor_functional_declaration.ets new file mode 100644 index 0000000000..acee909100 --- /dev/null +++ b/ets2panda/test/runtime/ets/accessor_functional_declaration.ets @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class A{ + a_:()=>void = ()=>{}; + get a(){ + return this.a_; + } + set a(a:()=>void){ + this.a_ = a + } + method(){ + this.a + this.a() + } +} +function main(){ + let a = new A(); + a.method() +} -- Gitee From f02bea5e2186adba95a18f8604102f0a42e53f16 Mon Sep 17 00:00:00 2001 From: zengzengran Date: Thu, 24 Apr 2025 18:56:55 +0800 Subject: [PATCH 197/268] Match signature for lambda parameter Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC2YJK Description: For assignable signatures, when matching lambda parameters, the best matching should first be performed based on the number of lambda parameters Tested-by: ninja tests (passed) ets_testrunner (passed) Signed-off-by: zengzengran # --- ets2panda/checker/ETSchecker.h | 6 +- ets2panda/checker/ets/function.cpp | 56 ++++++++++++++++--- ...bda-type-inference-overloaded-expected.txt | 1 - .../runtime/ets/signature_match_lambda.ets | 42 ++++++++++++++ 4 files changed, 96 insertions(+), 9 deletions(-) create mode 100644 ets2panda/test/runtime/ets/signature_match_lambda.ets diff --git a/ets2panda/checker/ETSchecker.h b/ets2panda/checker/ETSchecker.h index b5c091e603..a610a3902d 100644 --- a/ets2panda/checker/ETSchecker.h +++ b/ets2panda/checker/ETSchecker.h @@ -463,11 +463,15 @@ public: void SearchAmongMostSpecificTypes(Type *&mostSpecificType, Signature *&prevSig, std::tuple info, bool lookForClassType); + void CollectSuitableSignaturesForTypeInference(size_t paramIdx, ArenaVector &signatures, + ArenaMultiMap &bestSignaturesForParameter, + const ArenaVector &arguments); ArenaMultiMap GetSuitableSignaturesForParameter( const std::vector &argTypeInferenceRequired, size_t paramCount, ArenaVector &signatures, - const lexer::SourcePosition &pos); + const ArenaVector &arguments, const lexer::SourcePosition &pos); Signature *ChooseMostSpecificSignature(ArenaVector &signatures, const std::vector &argTypeInferenceRequired, + const ArenaVector &arguments, const lexer::SourcePosition &pos, size_t argumentsSize = ULONG_MAX); Signature *ResolvePotentialTrailingLambdaWithReceiver(ir::CallExpression *callExpr, ArenaVector const &signatures, diff --git a/ets2panda/checker/ets/function.cpp b/ets2panda/checker/ets/function.cpp index c080bcd9af..adeea4b940 100644 --- a/ets2panda/checker/ets/function.cpp +++ b/ets2panda/checker/ets/function.cpp @@ -683,7 +683,8 @@ Signature *ETSChecker::GetMostSpecificSignature(ArenaVector &compat const lexer::SourcePosition &pos, TypeRelationFlag resolveFlags) { std::vector argTypeInferenceRequired = FindTypeInferenceArguments(arguments); - Signature *mostSpecificSignature = ChooseMostSpecificSignature(compatibleSignatures, argTypeInferenceRequired, pos); + Signature *mostSpecificSignature = + ChooseMostSpecificSignature(compatibleSignatures, argTypeInferenceRequired, arguments, pos); if (mostSpecificSignature == nullptr) { LogError(diagnostic::AMBIGUOUS_FUNC_REF, {compatibleSignatures.front()->Function()->Id()->Name()}, pos); @@ -849,9 +850,43 @@ void ETSChecker::SearchAmongMostSpecificTypes(Type *&mostSpecificType, Signature } } -static void CollectSuitableSignaturesForTypeInference(size_t paramIdx, ArenaVector &signatures, - ArenaMultiMap &bestSignaturesForParameter) +void ETSChecker::CollectSuitableSignaturesForTypeInference( + size_t paramIdx, ArenaVector &signatures, + ArenaMultiMap &bestSignaturesForParameter, const ArenaVector &arguments) { + // For lambda parameters, attempt to obtain the most matching signature through the number of lambda parameters + ES2PANDA_ASSERT(arguments.at(paramIdx)->IsArrowFunctionExpression()); + [[maybe_unused]] size_t paramCount = + arguments.at(paramIdx)->AsArrowFunctionExpression()->Function()->Params().size(); + size_t minMatchArgCount = SIZE_MAX; + + for (auto *sig : signatures) { + auto *sigParamType = GetNonNullishType(sig->Params().at(paramIdx)->TsType()); + if (!sigParamType->IsETSFunctionType()) { + continue; + } + + auto sigParamArgCount = sigParamType->AsETSFunctionType()->ArrowSignature()->ArgCount(); + ES2PANDA_ASSERT(sigParamArgCount >= paramCount); + + minMatchArgCount = std::min(minMatchArgCount, sigParamArgCount); + } + + for (auto *sig : signatures) { + auto *sigParamType = GetNonNullishType(sig->Params().at(paramIdx)->TsType()); + if (!sigParamType->IsETSFunctionType()) { + continue; + } + + if (sigParamType->AsETSFunctionType()->ArrowSignature()->ArgCount() == minMatchArgCount) { + bestSignaturesForParameter.insert({paramIdx, sig}); + } + } + + if (bestSignaturesForParameter.find(paramIdx) != bestSignaturesForParameter.end()) { + return; + } + for (auto *sig : signatures) { if (paramIdx >= sig->Params().size() || !sig->Params().at(paramIdx)->TsType()->IsETSObjectType() || !sig->Params().at(paramIdx)->TsType()->AsETSObjectType()->IsGlobalETSObjectType()) { @@ -862,7 +897,7 @@ static void CollectSuitableSignaturesForTypeInference(size_t paramIdx, ArenaVect ArenaMultiMap ETSChecker::GetSuitableSignaturesForParameter( const std::vector &argTypeInferenceRequired, size_t paramCount, ArenaVector &signatures, - const lexer::SourcePosition &pos) + const ArenaVector &arguments, const lexer::SourcePosition &pos) { // Collect which signatures are most specific for each parameter. ArenaMultiMap bestSignaturesForParameter(Allocator()->Adapter()); @@ -871,8 +906,14 @@ ArenaMultiMap ETSChecker::GetSuitableSignaturesForParameter TypeRelationFlag::ONLY_CHECK_WIDENING); for (size_t i = 0; i < paramCount; ++i) { - if (i >= argTypeInferenceRequired.size() || argTypeInferenceRequired[i]) { - CollectSuitableSignaturesForTypeInference(i, signatures, bestSignaturesForParameter); + if (i >= argTypeInferenceRequired.size()) { + for (auto *sig : signatures) { + bestSignaturesForParameter.insert({i, sig}); + } + continue; + } + if (argTypeInferenceRequired[i]) { + CollectSuitableSignaturesForTypeInference(i, signatures, bestSignaturesForParameter, arguments); continue; } // 1st step: check which is the most specific parameter type for i. parameter. @@ -899,6 +940,7 @@ ArenaMultiMap ETSChecker::GetSuitableSignaturesForParameter Signature *ETSChecker::ChooseMostSpecificSignature(ArenaVector &signatures, const std::vector &argTypeInferenceRequired, + const ArenaVector &arguments, const lexer::SourcePosition &pos, size_t argumentsSize) { ES2PANDA_ASSERT(signatures.empty() == false); @@ -937,7 +979,7 @@ Signature *ETSChecker::ChooseMostSpecificSignature(ArenaVector &sig } ArenaMultiMap bestSignaturesForParameter = - GetSuitableSignaturesForParameter(argTypeInferenceRequired, paramCount, signatures, pos); + GetSuitableSignaturesForParameter(argTypeInferenceRequired, paramCount, signatures, arguments, pos); // Find the signature that are most specific for all parameters. Signature *mostSpecificSignature = FindMostSpecificSignature(signatures, bestSignaturesForParameter, paramCount); diff --git a/ets2panda/test/parser/ets/lambda-type-inference-overloaded-expected.txt b/ets2panda/test/parser/ets/lambda-type-inference-overloaded-expected.txt index e8ff142dfa..2203a5146a 100644 --- a/ets2panda/test/parser/ets/lambda-type-inference-overloaded-expected.txt +++ b/ets2panda/test/parser/ets/lambda-type-inference-overloaded-expected.txt @@ -1643,4 +1643,3 @@ } } } -TypeError: Reference to foo is ambiguous [lambda-type-inference-overloaded.ets:28:5] diff --git a/ets2panda/test/runtime/ets/signature_match_lambda.ets b/ets2panda/test/runtime/ets/signature_match_lambda.ets new file mode 100644 index 0000000000..54f38746a3 --- /dev/null +++ b/ets2panda/test/runtime/ets/signature_match_lambda.ets @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class A { + catch(onRejected: () => U | PromiseLike): string { + onRejected() + return "first catch is matched" + } + catch(onRejected: (error: Error) => U | PromiseLike): string { + onRejected(new Error()) + return "second catch is matched" + } + catch(onRejected: (a: Error, b: Error) => U | PromiseLike): string { + onRejected(new Error(), new Error()) + return "third catch is matched" + } + catch(onRejected: (a: Error, b: Error, c: Error) => U | PromiseLike): string { + onRejected(new Error(), new Error(), new Error()) + return "fourth catch is matched" + } +} + +function main(){ + let a = new A() + assertEQ(a.catch(()=>{}),"first catch is matched") + assertEQ(a.catch((e:Error|undefined|null)=>{}),"second catch is matched") + assertEQ(a.catch((e:Error)=>{}),"second catch is matched") + assertEQ(a.catch((e:Error,e2:Error)=>{}),"third catch is matched") + assertEQ(a.catch((e:Error,e2:Error,e3:Error)=>{}),"fourth catch is matched") +} -- Gitee From 565606804483c599c3abd2b5874d9e5e68f6cc09 Mon Sep 17 00:00:00 2001 From: zengzengran Date: Wed, 14 May 2025 09:31:05 +0800 Subject: [PATCH 198/268] Fix crash Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC6I7X Description: Incorrect code leads to error in AST tree structure. When class identifier is not pointing to ETSObjectType, no longer BuildBasicClassProperties, return TypeError Tested-by: ninja tests (passed) ets_testrunner (passed) Signed-off-by: zengzengran # --- ets2panda/checker/ets/object.cpp | 5 +- .../ast/parser/ets/unexpected_token_63.ets | 58 +++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 ets2panda/test/ast/parser/ets/unexpected_token_63.ets diff --git a/ets2panda/checker/ets/object.cpp b/ets2panda/checker/ets/object.cpp index 05faafa378..4f57901d9f 100644 --- a/ets2panda/checker/ets/object.cpp +++ b/ets2panda/checker/ets/object.cpp @@ -475,8 +475,11 @@ Type *ETSChecker::BuildBasicClassProperties(ir::ClassDefinition *classDef) if (classDef->IsAbstract()) { classType->AddObjectFlag(checker::ETSObjectFlags::ABSTRACT); } - } else { + } else if (var->TsType()->IsETSObjectType()) { classType = var->TsType()->AsETSObjectType(); + } else { + ES2PANDA_ASSERT(IsAnyError()); + return GlobalTypeError(); } classDef->SetTsType(classType); diff --git a/ets2panda/test/ast/parser/ets/unexpected_token_63.ets b/ets2panda/test/ast/parser/ets/unexpected_token_63.ets new file mode 100644 index 0000000000..833cf39392 --- /dev/null +++ b/ets2panda/test/ast/parser/ets/unexpected_token_63.ets @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class A { + func1(list : number, final : number) { + while(true) { + if(false) { + break; + } else { + let endSequence = false + this.func(list, final, endSequence) + } + } + } +} + +/* @@? 17:7 Error TypeError: Only abstract or native methods can't have body. */ +/* @@? 17:23 Error SyntaxError: Parameter declaration should have an explicit type annotation. */ +/* @@? 17:23 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 17:23 Error SyntaxError: Unexpected token, expected an identifier. */ +/* @@? 17:29 Error SyntaxError: Unexpected token ':'. */ +/* @@? 17:31 Error SyntaxError: number is a predefined type, cannot be used as an identifier */ +/* @@? 17:37 Error SyntaxError: Unexpected token ')'. */ +/* @@? 17:37 Error SyntaxError: Field type annotation expected. */ +/* @@? 17:39 Error SyntaxError: Unexpected token '{'. */ +/* @@? 18:3 Error SyntaxError: Unexpected token 'while'. */ +/* @@? 18:8 Error SyntaxError: Unexpected token '('. */ +/* @@? 18:9 Error SyntaxError: Unexpected token 'true'. */ +/* @@? 18:13 Error SyntaxError: Unexpected token ')'. */ +/* @@? 18:15 Error SyntaxError: Unexpected token '{'. */ +/* @@? 19:4 Error SyntaxError: Unexpected token 'if'. */ +/* @@? 19:6 Error SyntaxError: Unexpected token '('. */ +/* @@? 19:7 Error SyntaxError: Unexpected token 'false'. */ +/* @@? 19:12 Error SyntaxError: Unexpected token ')'. */ +/* @@? 19:14 Error SyntaxError: Unexpected token '{'. */ +/* @@? 20:5 Error SyntaxError: Unexpected token 'break'. */ +/* @@? 21:6 Error SyntaxError: Unexpected token 'else'. */ +/* @@? 21:6 Error SyntaxError: Unexpected token 'else'. */ +/* @@? 23:5 Error TypeError: Cannot reference 'this' in this context. */ +/* @@? 23:10 Error TypeError: Property 'func' does not exist on type 'Error' */ +/* @@? 23:21 Error SyntaxError: Unexpected token 'final'. */ +/* @@? 23:21 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 23:21 Error SyntaxError: Unexpected token 'final'. */ +/* @@? 23:39 Error SyntaxError: Expected '{', got ')'. */ +/* @@? 26:2 Error SyntaxError: Unexpected token '}'. */ +/* @@? 27:1 Error SyntaxError: Unexpected token '}'. */ -- Gitee From 12e39ae4c29ed4bbfe42e800232b7d3d3d3b9add Mon Sep 17 00:00:00 2001 From: "584648456@qq.com" Date: Sat, 19 Apr 2025 15:46:12 +0800 Subject: [PATCH 199/268] Fix unreachable stmt Description(optional):Unreachable statement. Error registration changed to Warning Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC2EIL Signed-off-by: semon <584648456@qq.com> --- ets2panda/checker/ets/aliveAnalyzer.cpp | 2 +- .../ast/compiler/ets/inferTypeLambda_0.ets | 4 +- .../ast/compiler/ets/readonly_array02.ets | 25 ------- .../parser/ets/return_while_warning.ets} | 13 ++-- .../test/ast/parser/ets/try_catch_alive_5.ets | 2 +- .../test/ast/parser/ets/try_catch_alive_6.ets | 2 +- .../test/ast/parser/ets/try_catch_alive_8.ets | 2 +- .../test/ast/parser/ets/try_catch_alive_9.ets | 2 +- .../ast/parser/ets/unexpected_token_62.ets | 24 +++++-- .../test/runtime/ets/inferTypeLambda_12.ets | 25 ------- .../test/runtime/ets/inferTypeLambda_13.ets | 25 ------- .../ets/type_param_infer_in_union_1.ets | 2 +- ...inferTypeLambda_15.ets => unreachable.ets} | 29 +++++--- ets2panda/util/diagnostic/semantic.yaml | 8 ++- ets2panda/util/diagnostic/warning.yaml | 68 +++++++++++++++++++ 15 files changed, 125 insertions(+), 108 deletions(-) delete mode 100644 ets2panda/test/ast/compiler/ets/readonly_array02.ets rename ets2panda/test/{runtime/ets/inferTypeLambda_11.ets => ast/parser/ets/return_while_warning.ets} (76%) delete mode 100644 ets2panda/test/runtime/ets/inferTypeLambda_12.ets delete mode 100644 ets2panda/test/runtime/ets/inferTypeLambda_13.ets rename ets2panda/test/runtime/ets/{inferTypeLambda_15.ets => unreachable.ets} (56%) diff --git a/ets2panda/checker/ets/aliveAnalyzer.cpp b/ets2panda/checker/ets/aliveAnalyzer.cpp index 7c9a9142ba..a6a2282f07 100644 --- a/ets2panda/checker/ets/aliveAnalyzer.cpp +++ b/ets2panda/checker/ets/aliveAnalyzer.cpp @@ -189,7 +189,7 @@ void AliveAnalyzer::AnalyzeStat(const ir::AstNode *node) } if (status_ == LivenessStatus::DEAD) { - checker_->LogError(diagnostic::UNREACHABLE_STMT, {}, node->Start()); + checker_->LogError(diagnostic::UNREACHABLE_STMT, node->Start()); return; } diff --git a/ets2panda/test/ast/compiler/ets/inferTypeLambda_0.ets b/ets2panda/test/ast/compiler/ets/inferTypeLambda_0.ets index c4664c65f9..6abcf73491 100644 --- a/ets2panda/test/ast/compiler/ets/inferTypeLambda_0.ets +++ b/ets2panda/test/ast/compiler/ets/inferTypeLambda_0.ets @@ -13,11 +13,11 @@ * limitations under the License. */ -function foo(arr:T[], f:(a:T[])=>string){ +function foo(arr:Array, f:(a:Array)=>string){ return f(arr[0]) // CTE } -function bar(arr:number[]){ +function bar(arr:Array){ return foo(arr, (a):string=>{ let res = a.toString(); return res diff --git a/ets2panda/test/ast/compiler/ets/readonly_array02.ets b/ets2panda/test/ast/compiler/ets/readonly_array02.ets deleted file mode 100644 index 282f2fcfba..0000000000 --- a/ets2panda/test/ast/compiler/ets/readonly_array02.ets +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -type U1 = number[][] | string[] -type U2 = (readonly number[][]) | (readonly string[]) - -function main() { - let v: U1 | U2 = [[1.0,2.0]] - v[0] = [1.0,3.0] // CTE, readonly array -} - -/* @@? 21:5 Error TypeError: Cannot modify an array or tuple content that has the readonly parameter */ - diff --git a/ets2panda/test/runtime/ets/inferTypeLambda_11.ets b/ets2panda/test/ast/parser/ets/return_while_warning.ets similarity index 76% rename from ets2panda/test/runtime/ets/inferTypeLambda_11.ets rename to ets2panda/test/ast/parser/ets/return_while_warning.ets index c3222907b0..5c9a15296e 100644 --- a/ets2panda/test/runtime/ets/inferTypeLambda_11.ets +++ b/ets2panda/test/ast/parser/ets/return_while_warning.ets @@ -12,14 +12,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -function foo(arr:T[], f:(a:T)=>string){ - return f(arr[0]) -} -function bar(arr:number[]){ - return foo(arr, a=>a.toString()) +function main(): void { + while (false) { + assertTrue( false ); + } } -function main(){ - assertTrue(bar([1,2,3,4]) == "1") -} \ No newline at end of file +/* @@? 17:19 Warning Warning: Unreachable statement. */ \ No newline at end of file diff --git a/ets2panda/test/ast/parser/ets/try_catch_alive_5.ets b/ets2panda/test/ast/parser/ets/try_catch_alive_5.ets index 3ab56c1963..efd161568c 100644 --- a/ets2panda/test/ast/parser/ets/try_catch_alive_5.ets +++ b/ets2panda/test/ast/parser/ets/try_catch_alive_5.ets @@ -24,4 +24,4 @@ function foo(): int { } } -/* @@@ label Error TypeError: Unreachable statement. */ +/* @@@ label Warning Warning: Unreachable statement. */ diff --git a/ets2panda/test/ast/parser/ets/try_catch_alive_6.ets b/ets2panda/test/ast/parser/ets/try_catch_alive_6.ets index 307bae6833..40fe55f8cc 100644 --- a/ets2panda/test/ast/parser/ets/try_catch_alive_6.ets +++ b/ets2panda/test/ast/parser/ets/try_catch_alive_6.ets @@ -25,5 +25,5 @@ function foo(): int { } -/* @@@ label1 Error TypeError: Unreachable statement. */ +/* @@@ label1 Warning Warning: Unreachable statement. */ /* @@@ label Warning Warning: Finally clause cannot complete normally */ diff --git a/ets2panda/test/ast/parser/ets/try_catch_alive_8.ets b/ets2panda/test/ast/parser/ets/try_catch_alive_8.ets index 33824549a9..356e8c5c6d 100644 --- a/ets2panda/test/ast/parser/ets/try_catch_alive_8.ets +++ b/ets2panda/test/ast/parser/ets/try_catch_alive_8.ets @@ -25,4 +25,4 @@ function foo(): int { } /* @@@ label Warning Warning: Finally clause cannot complete normally */ -/* @@@ label1 Error TypeError: Unreachable statement. */ +/* @@@ label1 Warning Warning: Unreachable statement. */ diff --git a/ets2panda/test/ast/parser/ets/try_catch_alive_9.ets b/ets2panda/test/ast/parser/ets/try_catch_alive_9.ets index 8c4d938a5a..2b31a764f1 100644 --- a/ets2panda/test/ast/parser/ets/try_catch_alive_9.ets +++ b/ets2panda/test/ast/parser/ets/try_catch_alive_9.ets @@ -24,5 +24,5 @@ function foo(): int { } } -/* @@@ label Error TypeError: Unreachable statement. */ +/* @@@ label Warning Warning: Unreachable statement. */ /* @@@ label1 Warning Warning: Finally clause cannot complete normally */ diff --git a/ets2panda/test/ast/parser/ets/unexpected_token_62.ets b/ets2panda/test/ast/parser/ets/unexpected_token_62.ets index 1932877b96..b5e6b422a8 100644 --- a/ets2panda/test/ast/parser/ets/unexpected_token_62.ets +++ b/ets2panda/test/ast/parser/ets/unexpected_token_62.ets @@ -32,34 +32,46 @@ int = 10 /* @@? 19:11 Error SyntaxError: Unexpected token 'Nu'. */ /* @@? 19:11 Error TypeError: Unresolved reference Nu */ /* @@? 20:1 Error SyntaxError: Unexpected token, expected an identifier. */ +/* @@? 20:1 Error SyntaxError: Unexpected token, expected an identifier. */ +/* @@? 20:1 Error SyntaxError: Unexpected token, expected an identifier. */ /* @@? 20:1 Error TypeError: Unresolved reference nt */ /* @@? 20:10 Error SyntaxError: Unexpected token 'A'. */ /* @@? 20:10 Error TypeError: Class name 'A' used in the wrong context */ /* @@? 20:12 Error SyntaxError: Unexpected token '{'. */ /* @@? 22:11 Error SyntaxError: Unexpected token 'Nu'. */ /* @@? 23:1 Error SyntaxError: Unexpected token, expected an identifier. */ +/* @@? 23:1 Error SyntaxError: Unexpected token, expected an identifier. */ +/* @@? 23:1 Error SyntaxError: Unexpected token, expected an identifier. */ /* @@? 24:1 Error SyntaxError: Unexpected token ')'. */ -/* @@? 24:2 Error SyntaxError: Unexpected token 'void'. */ +/* @@? 24:2 Error TypeError: Unresolved reference void */ +/* @@? 24:7 Error SyntaxError: Unexpected token '{'. */ /* @@? 24:8 Error SyntaxError: Unexpected token, expected an identifier. */ /* @@? 24:8 Error TypeError: Unresolved reference nt */ /* @@? 24:16 Error SyntaxError: Unexpected token ','. */ +/* @@? 24:16 Error SyntaxError: Unexpected token ','. */ +/* @@? 24:16 Error SyntaxError: Unexpected token ','. */ /* @@? 24:21 Error SyntaxError: Label must be followed by a loop statement. */ /* @@? 24:21 Error TypeError: Unresolved reference s */ /* @@? 24:23 Error SyntaxError: Unexpected token 'A'. */ /* @@? 24:23 Error TypeError: Class name 'A' used in the wrong context */ /* @@? 24:25 Error SyntaxError: Unexpected token '{'. */ -/* @@? 25:1 Error SyntaxError: Unexpected token 'int'. */ -/* @@? 25:5 Error SyntaxError: Unexpected token '='. */ +/* @@? 25:1 Error TypeError: Unresolved reference int */ /* @@? 26:1 Error SyntaxError: Unexpected token ')'. */ /* @@? 26:3 Error SyntaxError: Unexpected token '=>'. */ +/* @@? 26:3 Error SyntaxError: Unexpected token '=>'. */ +/* @@? 26:13 Error SyntaxError: Unexpected token, expected an identifier. */ /* @@? 26:13 Error SyntaxError: Unexpected token, expected an identifier. */ /* @@? 26:13 Error TypeError: Cannot find type ''. */ -/* @@? 26:14 Error SyntaxError: Unexpected token, expected ',' or ')'. */ /* @@? 26:14 Error SyntaxError: Expected '=>', got '+'. */ +/* @@? 26:14 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 26:15 Error SyntaxError: Unexpected token ')'. */ +/* @@? 26:15 Error SyntaxError: Unexpected token ')'. */ +/* @@? 26:15 Error SyntaxError: Unexpected token ')'. */ /* @@? 26:15 Error SyntaxError: Unexpected token ')'. */ /* @@? 26:16 Error SyntaxError: Unexpected token ':'. */ -/* @@? 26:18 Error TypeError: The type of parameter 'A6' cannot be inferred */ +/* @@? 26:16 Error SyntaxError: Unexpected token ':'. */ /* @@? 26:18 Error TypeError: Bad operand type, the types of the operands must be numeric type. */ +/* @@? 26:18 Error TypeError: The type of parameter 'A6' cannot be inferred */ /* @@? 26:25 Error TypeError: Unresolved reference reƒurn */ /* @@? 26:32 Error SyntaxError: Unexpected token '_ew'. */ /* @@? 26:32 Error TypeError: Unresolved reference _ew */ @@ -68,4 +80,4 @@ int = 10 /* @@? 26:36 Error TypeError: Type 'B' has no call signatures. */ /* @@? 26:40 Error SyntaxError: Unexpected token, expected ',' or ')'. */ /* @@? 27:2 Error TypeError: Unresolved reference ó */ -/* @@? 71:60 Error SyntaxError: Expected '}', got 'eos'. */ \ No newline at end of file +/* @@? 84:1 Error SyntaxError: Expected '}', got 'eos'. */ diff --git a/ets2panda/test/runtime/ets/inferTypeLambda_12.ets b/ets2panda/test/runtime/ets/inferTypeLambda_12.ets deleted file mode 100644 index 3599d278ce..0000000000 --- a/ets2panda/test/runtime/ets/inferTypeLambda_12.ets +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -function foo(arr:T[], f:(a:T|Object)=>string){ - return f(arr[1]) -} - -function bar(arr:number[]){ - return foo(arr, a=>a.toString()) -} - -function main(){ - assertTrue(bar([1,2,3,4]) == "2") -} \ No newline at end of file diff --git a/ets2panda/test/runtime/ets/inferTypeLambda_13.ets b/ets2panda/test/runtime/ets/inferTypeLambda_13.ets deleted file mode 100644 index 5c41a4301c..0000000000 --- a/ets2panda/test/runtime/ets/inferTypeLambda_13.ets +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -function foo(arr:T[], f:(a:T[])=>string){ - return f(arr) -} - -function bar(arr:number[]){ - return foo(arr, a=>a.toString()) -} - -function main(){ - assertTrue(bar([1,2,3,4]) == "1,2,3,4") -} \ No newline at end of file diff --git a/ets2panda/test/runtime/ets/type_param_infer_in_union_1.ets b/ets2panda/test/runtime/ets/type_param_infer_in_union_1.ets index 4f9604f115..95a6a06e50 100644 --- a/ets2panda/test/runtime/ets/type_param_infer_in_union_1.ets +++ b/ets2panda/test/runtime/ets/type_param_infer_in_union_1.ets @@ -22,7 +22,7 @@ function foo2(array:Iterable>){ } function main(){ - let a = [1,2,3] + let a = new Array(1,2,3) assertEQ(foo1(a), "foo1 should be ok") assertEQ(foo2(a), "foo2 should be ok too") } \ No newline at end of file diff --git a/ets2panda/test/runtime/ets/inferTypeLambda_15.ets b/ets2panda/test/runtime/ets/unreachable.ets similarity index 56% rename from ets2panda/test/runtime/ets/inferTypeLambda_15.ets rename to ets2panda/test/runtime/ets/unreachable.ets index 4c7191af26..3415a066c5 100644 --- a/ets2panda/test/runtime/ets/inferTypeLambda_15.ets +++ b/ets2panda/test/runtime/ets/unreachable.ets @@ -12,14 +12,25 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -function foo(arr:T[], f:(a:[T, string])=>string){ - return f([arr[0], "1"]) -} -function bar(arr:number[]){ - return foo(arr, a=>a.toString()) -} - -function main(){ - assertTrue(bar([1,2,3,4]) == "1,1") +function SwitchTest(value:int){ + let result = 0; + switch(value) { + case 0: + switch(value) { + case 0: + result += 3; + break; + default: + result += 32; + break; + } + result *= 2; + break; + result=3; + default: + result += 32; + break; + } + return result; } \ No newline at end of file diff --git a/ets2panda/util/diagnostic/semantic.yaml b/ets2panda/util/diagnostic/semantic.yaml index 1132d7d595..f374ad7d6c 100644 --- a/ets2panda/util/diagnostic/semantic.yaml +++ b/ets2panda/util/diagnostic/semantic.yaml @@ -415,9 +415,9 @@ semantic: id: 101 message: "Initializer must be able to complete normally." -- name: UNREACHABLE_STMT +- name: EXTEND_DYNAMIC id: 102 - message: "Unreachable statement." + message: "Class {} shouldn't extend dynamic class." - name: MISSING_RETURN_STMT id: 103 @@ -1346,3 +1346,7 @@ semantic: - name: READONLY_PROPERTY_REASSIGN id: 338 message: "The 'Readonly' property cannot be reassigned." + +- name: PROPERTY_MAYBE_MISSING_INIT + id: 339 + message: "Property '{}' might not have been initialized." \ No newline at end of file diff --git a/ets2panda/util/diagnostic/warning.yaml b/ets2panda/util/diagnostic/warning.yaml index 7c5314fafb..e00451b71a 100644 --- a/ets2panda/util/diagnostic/warning.yaml +++ b/ets2panda/util/diagnostic/warning.yaml @@ -47,3 +47,71 @@ warning: - name : ANNOTATION_UNUSED_GENERIC_ALIAS_WARN id: 9 message: "Type alias generic parameter '{}' is not used in type annotation" + +- name: DYNAMIC_PATHS_ABSOLUTE + id: 10 + message: "Don't use absolute path '{}' as key in 'dynamicPaths'" + +- name: NO_OHMURL + id: 11 + message: "'ohmUrl' for module '{}' wasn't specified" + +- name: DUPLICATE_SIGS + id: 12 + message: "Detect duplicate signatures, use '{}{}' to replace" + +- name: EXTENSION_NONPUBLIC_COLLISION + id: 13 + message: "The extension function '{}' has the same name with non-public method in class {}" + +- name: NULLISH_OPERAND + id: 14 + message: "Bad operand type, the operand of the non-nullish expression is 'null' or 'undefined'." + +- name: INSTANCEOF_ERASED + id: 15 + message: "Type parameter is erased from type '{}' when used in instanceof expression." + +- name: ASSIGN_TO_READONLY + id: 16 + message: "Cannot assign to '{}' because it is a read-only property." + +- name: MAYBE_REASSIGNED + id: 17 + message: "{} '{}' might already have been assigned." + +- name: PROP_MAYBE_UNINITIALIZED + id: 18 + message: "Property '{}' might not have been initialized." + +- name: USE_BEFORE_INIT + id: 19 + message: "{} '{}' is used before being assigned." + +- name: MAYBE_FALLTHROUGH + id: 20 + message: "Possible fall-through into case" + +- name: FINALLY_CANT_COMPLETE + id: 21 + message: "Finally clause cannot complete normally" + +- name: FUNCTION_ASM_SIG_COLLISION + id: 22 + message: "Function {} with this assembly signature already declared." + +- name: GETTER_LOOP + id: 23 + message: "Reading the value of the property inside its getter may lead to an endless loop." + +- name: SETTER_LOOP + id: 24 + message: "Assigning new value to the property inside its setter may lead to an endless loop." + +- name: EXTENSION_MISMATCH + id: 25 + message: "Not matching extensions! Sourcefile: {}, Manual(used): {}" + +- name: UNREACHABLE_STMT + id: 26 + message: "Unreachable statement." \ No newline at end of file -- Gitee From d5c474bcaa6f5629612a78c2c1e7460ec18dd671 Mon Sep 17 00:00:00 2001 From: hasansemihkahveci Date: Tue, 29 Apr 2025 09:36:32 +0300 Subject: [PATCH 200/268] Handle inference error in empty array map Issue : https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC3R1T Signed-off-by: hasansemihkahveci --- ets2panda/checker/ets/typeCheckingHelpers.cpp | 3 ++ .../ets/empty_array_map_inference_fail.ets | 38 +++++++++++++++++++ .../test-lists/recheck/recheck-ignored.txt | 1 + 3 files changed, 42 insertions(+) create mode 100644 ets2panda/test/ast/parser/ets/empty_array_map_inference_fail.ets diff --git a/ets2panda/checker/ets/typeCheckingHelpers.cpp b/ets2panda/checker/ets/typeCheckingHelpers.cpp index 9506cb451d..a077b6024f 100644 --- a/ets2panda/checker/ets/typeCheckingHelpers.cpp +++ b/ets2panda/checker/ets/typeCheckingHelpers.cpp @@ -1392,6 +1392,9 @@ bool ETSChecker::CheckLambdaAssignable(ir::Expression *param, ir::ScriptFunction { ES2PANDA_ASSERT(param->IsETSParameterExpression()); ir::AstNode *typeAnn = param->AsETSParameterExpression()->Ident()->TypeAnnotation(); + if (typeAnn == nullptr) { + return false; + } if (typeAnn->IsETSTypeReference()) { typeAnn = DerefETSTypeReference(typeAnn); } diff --git a/ets2panda/test/ast/parser/ets/empty_array_map_inference_fail.ets b/ets2panda/test/ast/parser/ets/empty_array_map_inference_fail.ets new file mode 100644 index 0000000000..9552cc43a9 --- /dev/null +++ b/ets2panda/test/ast/parser/ets/empty_array_map_inference_fail.ets @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +(function() { + return 37; +})(); + +[].map(function(x) { + return x+1; +}); + +/* @@? 16:1 Error TypeError: No matching call signature */ +/* @@? 16:1 Error TypeError: Expected 1 arguments, got 0. */ +/* @@? 16:2 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 16:2 Error SyntaxError: Unexpected token 'function'. */ +/* @@? 18:2 Error SyntaxError: Unexpected token ')'. */ +/* @@? 18:4 Error SyntaxError: Unexpected token ')'. */ +/* @@? 20:1 Error TypeError: Can't resolve array type */ +/* @@? 20:8 Error SyntaxError: Unexpected token 'function'. */ +/* @@? 20:8 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 20:16 Error SyntaxError: Unexpected token, expected an identifier. */ +/* @@? 20:17 Error TypeError: The type of parameter 'x' cannot be inferred */ +/* @@? 20:18 Error SyntaxError: Parameter declaration should have an explicit type annotation. */ +/* @@? 22:2 Error SyntaxError: Unexpected token ')'. */ + + diff --git a/ets2panda/test/test-lists/recheck/recheck-ignored.txt b/ets2panda/test/test-lists/recheck/recheck-ignored.txt index 291dc7bb67..eb292bd540 100644 --- a/ets2panda/test/test-lists/recheck/recheck-ignored.txt +++ b/ets2panda/test/test-lists/recheck/recheck-ignored.txt @@ -636,6 +636,7 @@ ast/parser/ets/user_defined_16.ets ast/parser/ets/enum_default_invalid_value_type.ets ast/parser/ets/struct_implements_interface.ets ast/parser/ets/wrong_context_function_1.ets +ast/parser/ets/empty_array_map_inference_fail.ets ast/parser/ets/illegal_continue_statement.ets ast/parser/ets/minus_sign_as_index_1.ets ast/compiler/ets/union_string_literals_5.ets -- Gitee From 326550a5a336b817fc474ec69ff83053bf61ff6d Mon Sep 17 00:00:00 2001 From: furkanocalan Date: Fri, 25 Apr 2025 11:07:58 +0300 Subject: [PATCH 201/268] [FUZZING][AUTOREPORT][es2panda] Crash in Parser Issue: #IC3YXV Description: Fix on crash because of not handling interface in the ETSparserClasses Signed-off-by: furkanocalan --- ets2panda/parser/ETSparser.h | 1 + ets2panda/parser/ETSparserClasses.cpp | 49 +++++++------- .../ets/interfaceMethodReadonlyModifier.ets | 8 ++- .../parser/ets/interface_parser_error_1.ets | 67 +++++++++++++++++++ .../parser/ets/interface_parser_error_2.ets | 24 +++++++ .../test/parser/ets/interfaces-expected.txt | 6 +- ets2panda/test/parser/ets/interfaces.ets | 2 + .../parser/ets/test_interface-expected.txt | 2 +- .../test-lists/recheck/recheck-ignored.txt | 4 ++ 9 files changed, 132 insertions(+), 31 deletions(-) create mode 100644 ets2panda/test/ast/parser/ets/interface_parser_error_1.ets create mode 100644 ets2panda/test/ast/parser/ets/interface_parser_error_2.ets diff --git a/ets2panda/parser/ETSparser.h b/ets2panda/parser/ETSparser.h index 52195e384d..0c5a04636b 100644 --- a/ets2panda/parser/ETSparser.h +++ b/ets2panda/parser/ETSparser.h @@ -400,6 +400,7 @@ private: VariableParsingFlags flags) override; ir::VariableDeclarator *ParseVariableDeclaratorInitializer(ir::Expression *init, VariableParsingFlags flags, const lexer::SourcePosition &startLoc) override; + bool IsFieldStartToken(lexer::TokenType t); ir::AstNode *ParseTypeLiteralOrInterfaceMember() override; ir::AstNode *ParseAnnotationsInInterfaceBody(); void ParseNameSpaceSpecifier(ArenaVector *specifiers, bool isReExport = false); diff --git a/ets2panda/parser/ETSparserClasses.cpp b/ets2panda/parser/ETSparserClasses.cpp index 2a76826e63..cc020083e0 100644 --- a/ets2panda/parser/ETSparserClasses.cpp +++ b/ets2panda/parser/ETSparserClasses.cpp @@ -1036,53 +1036,52 @@ ir::AstNode *ETSParser::ParseAnnotationsInInterfaceBody() return result; } +bool ETSParser::IsFieldStartToken(lexer::TokenType tokenType) +{ + return tokenType == lexer::TokenType::LITERAL_IDENT || + tokenType == lexer::TokenType::PUNCTUATOR_LEFT_SQUARE_BRACKET || + tokenType == lexer::TokenType::PUNCTUATOR_LEFT_PARENTHESIS; +} + ir::AstNode *ETSParser::ParseTypeLiteralOrInterfaceMember() { if (Lexer()->GetToken().Type() == lexer::TokenType::PUNCTUATOR_AT) { return ParseAnnotationsInInterfaceBody(); } - auto startLoc = Lexer()->GetToken().Start(); - if (Lexer()->Lookahead() != lexer::LEX_CHAR_LEFT_PAREN && Lexer()->Lookahead() != lexer::LEX_CHAR_LESS_THAN && (Lexer()->GetToken().KeywordType() == lexer::TokenType::KEYW_GET || Lexer()->GetToken().KeywordType() == lexer::TokenType::KEYW_SET)) { return ParseInterfaceGetterSetterMethod(ir::ModifierFlags::PUBLIC); } - if (Lexer()->TryEatTokenKeyword(lexer::TokenType::KEYW_READONLY)) { - char32_t nextCp = Lexer()->Lookahead(); - if (nextCp == lexer::LEX_CHAR_LEFT_PAREN || nextCp == lexer::LEX_CHAR_LESS_THAN) { + ir::ModifierFlags modifiers = ParseInterfaceMethodModifiers(); + char32_t nextCp = Lexer()->Lookahead(); + auto startLoc = Lexer()->GetToken().Start(); + auto readonlyTok = Lexer()->TryEatTokenKeyword(lexer::TokenType::KEYW_READONLY); + bool isReadonly = readonlyTok.has_value(); + + if (nextCp == lexer::LEX_CHAR_LEFT_PAREN || nextCp == lexer::LEX_CHAR_LESS_THAN) { + if (isReadonly) { LogError(diagnostic::READONLY_INTERFACE_METHOD, {}, startLoc); - ir::ModifierFlags modfiers = ParseInterfaceMethodModifiers(); - auto *method = ParseInterfaceMethod(modfiers, ir::MethodDefinitionKind::METHOD); - method->SetStart(startLoc); - return method; } - auto *field = ParseInterfaceField(); - field->SetStart(startLoc); - field->AddModifier(ir::ModifierFlags::READONLY); - return field; + auto *method = ParseInterfaceMethod(modifiers, ir::MethodDefinitionKind::METHOD); + method->SetStart(startLoc); + return method; } - ir::ModifierFlags modfiers = ParseInterfaceMethodModifiers(); - if (Lexer()->GetToken().Type() != lexer::TokenType::LITERAL_IDENT && - Lexer()->GetToken().Type() != lexer::TokenType::PUNCTUATOR_LEFT_SQUARE_BRACKET && - Lexer()->GetToken().Type() != lexer::TokenType::PUNCTUATOR_LEFT_PARENTHESIS) { - LogError(diagnostic::ID_EXPECTED); + auto tok = Lexer()->GetToken().Type(); + if (!IsFieldStartToken(tok)) { + LogError(diagnostic::ID_EXPECTED, {}, startLoc); return AllocBrokenExpression(Lexer()->GetToken().Loc()); } - char32_t nextCp = Lexer()->Lookahead(); - if (nextCp == lexer::LEX_CHAR_LEFT_PAREN || nextCp == lexer::LEX_CHAR_LESS_THAN) { - auto *method = ParseInterfaceMethod(modfiers, ir::MethodDefinitionKind::METHOD); - method->SetStart(startLoc); - return method; - } - auto *field = ParseInterfaceField(); if (field != nullptr) { field->SetStart(startLoc); + if (isReadonly) { + field->AddModifier(ir::ModifierFlags::READONLY); + } return field; } diff --git a/ets2panda/test/ast/parser/ets/interfaceMethodReadonlyModifier.ets b/ets2panda/test/ast/parser/ets/interfaceMethodReadonlyModifier.ets index 0bcf0c313b..39dcced0fd 100644 --- a/ets2panda/test/ast/parser/ets/interfaceMethodReadonlyModifier.ets +++ b/ets2panda/test/ast/parser/ets/interfaceMethodReadonlyModifier.ets @@ -14,7 +14,11 @@ */ interface I { - /* @@ label */readonly foo() + readonly foo() } -/* @@@ label Error SyntaxError: Modifier 'readonly' cannot be applied to an interface method. */ +/* @@? 17:17 Error SyntaxError: Interface fields must have type annotation. */ +/* @@? 17:18 Error SyntaxError: Invalid Type. */ +/* @@? 17:18 Error SyntaxError: Unexpected token, expected ','. */ +/* @@? 17:18 Error SyntaxError: Unexpected token, expected 'private' or identifier. */ +/* @@? 18:1 Error SyntaxError: Identifier expected. */ \ No newline at end of file diff --git a/ets2panda/test/ast/parser/ets/interface_parser_error_1.ets b/ets2panda/test/ast/parser/ets/interface_parser_error_1.ets new file mode 100644 index 0000000000..0b3fc3728f --- /dev/null +++ b/ets2panda/test/ast/parser/ets/interface_parser_error_1.ets @@ -0,0 +1,67 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +b: Geit { + t {name(): + +interface I { + readonly : boolean +} +inter + +class A implements I { + reanstructor() { + this.a = f�ls + s A { + @ constructor() { + this.a = ruO; + } +}* +function mdin() { let a = new A(); + ass + +/* @@? 16:4 Error SyntaxError: Label must be followed by a loop statement. */ +/* @@? 16:4 Error TypeError: Unresolved reference Geit */ +/* @@? 16:9 Error SyntaxError: Unexpected token '{'. */ +/* @@? 17:2 Error TypeError: Unresolved reference t */ +/* @@? 17:4 Error SyntaxError: Unexpected token '{'. */ +/* @@? 17:5 Error TypeError: Unresolved reference name */ +/* @@? 17:11 Error SyntaxError: Unexpected token ':'. */ +/* @@? 20:5 Error SyntaxError: Identifier expected. */ +/* @@? 20:14 Error SyntaxError: Unexpected token, expected ','. */ +/* @@? 20:14 Error SyntaxError: Unexpected token, expected 'private' or identifier. */ +/* @@? 20:16 Error SyntaxError: Identifier expected. */ +/* @@? 20:16 Error SyntaxError: Unexpected token, expected ','. */ +/* @@? 20:16 Error SyntaxError: Unexpected token, expected 'private' or identifier. */ +/* @@? 21:1 Error SyntaxError: Identifier expected. */ +/* @@? 22:1 Error TypeError: Class literal is not yet supported. */ +/* @@? 22:1 Error TypeError: Cannot find type 'inter'. */ +/* @@? 24:7 Error SyntaxError: Unexpected token 'A'. */ +/* @@? 24:7 Error TypeError: Unresolved reference A */ +/* @@? 24:9 Error SyntaxError: Unexpected token 'implements'. */ +/* @@? 24:20 Error TypeError: Interface name 'I' used in the wrong context */ +/* @@? 24:22 Error SyntaxError: Unexpected token '{'. */ +/* @@? 25:4 Error TypeError: Unresolved reference reanstructor */ +/* @@? 26:19 Error SyntaxError: Unexpected token, expected an identifier. */ +/* @@? 26:19 Error SyntaxError: Unexpected token '�ls'. */ +/* @@? 27:5 Error SyntaxError: Unexpected token 'A'. */ +/* @@? 27:7 Error SyntaxError: Unexpected token '{'. */ +/* @@? 28:5 Error SyntaxError: Identifier expected, got 'constructor'. */ +/* @@? 28:19 Error SyntaxError: Annotations are not allowed on this type of declaration. */ +/* @@? 29:18 Error SyntaxError: Unexpected token, expected an identifier. */ +/* @@? 31:2 Error SyntaxError: Unexpected token '*'. */ +/* @@? 32:1 Error SyntaxError: Nested functions are not allowed. */ +/* @@? 32:1 Error SyntaxError: Unexpected token 'function'. */ +/* @@? 68:1 Error SyntaxError: Expected '}', got 'eos'. */ diff --git a/ets2panda/test/ast/parser/ets/interface_parser_error_2.ets b/ets2panda/test/ast/parser/ets/interface_parser_error_2.ets new file mode 100644 index 0000000000..b2f0dcd090 --- /dev/null +++ b/ets2panda/test/ast/parser/ets/interface_parser_error_2.ets @@ -0,0 +1,24 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +interface I { + : boolean +} + +/* @@? 17:5 Error SyntaxError: Unexpected token, expected 'private' or identifier. */ +/* @@? 17:7 Error SyntaxError: Identifier expected. */ +/* @@? 17:7 Error SyntaxError: Unexpected token, expected ','. */ +/* @@? 17:7 Error SyntaxError: Unexpected token, expected 'private' or identifier. */ +/* @@? 18:1 Error SyntaxError: Identifier expected. */ diff --git a/ets2panda/test/parser/ets/interfaces-expected.txt b/ets2panda/test/parser/ets/interfaces-expected.txt index 2a1b0fcc27..020f98c54c 100644 --- a/ets2panda/test/parser/ets/interfaces-expected.txt +++ b/ets2panda/test/parser/ets/interfaces-expected.txt @@ -739,7 +739,7 @@ "loc": { "start": { "line": 22, - "column": 3, + "column": 11, "program": "interfaces.ets" }, "end": { @@ -1204,7 +1204,7 @@ "program": "interfaces.ets" }, "end": { - "line": 29, + "line": 31, "column": 1, "program": "interfaces.ets" } @@ -1480,7 +1480,7 @@ "program": "interfaces.ets" }, "end": { - "line": 29, + "line": 31, "column": 1, "program": "interfaces.ets" } diff --git a/ets2panda/test/parser/ets/interfaces.ets b/ets2panda/test/parser/ets/interfaces.ets index 4d9b87c7a0..e6ff2c2e03 100644 --- a/ets2panda/test/parser/ets/interfaces.ets +++ b/ets2panda/test/parser/ets/interfaces.ets @@ -26,3 +26,5 @@ interface I0 { interface I1 extends I, I0 { } + +/* @@? 22:28 Error TypeError: 'nopnop' is an instance property of 'I0' */ diff --git a/ets2panda/test/parser/ets/test_interface-expected.txt b/ets2panda/test/parser/ets/test_interface-expected.txt index 468b940760..2661e891fd 100644 --- a/ets2panda/test/parser/ets/test_interface-expected.txt +++ b/ets2panda/test/parser/ets/test_interface-expected.txt @@ -913,7 +913,7 @@ "loc": { "start": { "line": 24, - "column": 5, + "column": 13, "program": "test_interface.ets" }, "end": { diff --git a/ets2panda/test/test-lists/recheck/recheck-ignored.txt b/ets2panda/test/test-lists/recheck/recheck-ignored.txt index eb292bd540..514e054bf5 100644 --- a/ets2panda/test/test-lists/recheck/recheck-ignored.txt +++ b/ets2panda/test/test-lists/recheck/recheck-ignored.txt @@ -639,6 +639,10 @@ ast/parser/ets/wrong_context_function_1.ets ast/parser/ets/empty_array_map_inference_fail.ets ast/parser/ets/illegal_continue_statement.ets ast/parser/ets/minus_sign_as_index_1.ets +ast/parser/ets/export_after_statement.ets +ast/parser/ets/unreachable_fuzz_error.ets +ast/parser/ets/interface_parser_error_1.ets +ast/parser/ets/interface_parser_error_2.ets ast/compiler/ets/union_string_literals_5.ets ast/compiler/ets/annotation_tests/annotation_for_type_parameter01.ets ast/compiler/ets/readonlyType_4.ets -- Gitee From a618afb650fa8fcd123b9d2d4d667d13e97c1541 Mon Sep 17 00:00:00 2001 From: hasansemihkahveci Date: Fri, 25 Apr 2025 11:17:20 +0300 Subject: [PATCH 202/268] Fix issue related to #24682 Issue : https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC3SHI Signed-off-by: hasansemihkahveci --- ets2panda/checker/ets/object.cpp | 2 +- .../ets/constructor_type_inference_crash.ets | 27 +++++++++++++++++++ .../test-lists/recheck/recheck-ignored.txt | 1 + 3 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 ets2panda/test/ast/parser/ets/constructor_type_inference_crash.ets diff --git a/ets2panda/checker/ets/object.cpp b/ets2panda/checker/ets/object.cpp index 4f57901d9f..9b36448b0b 100644 --- a/ets2panda/checker/ets/object.cpp +++ b/ets2panda/checker/ets/object.cpp @@ -1704,7 +1704,7 @@ void ETSChecker::CheckCyclicConstructorCall(Signature *signature) ->Callee() ->IsThisExpression()) { auto *constructorCall = funcBody->Statements()[0]->AsExpressionStatement()->GetExpression()->AsCallExpression(); - if (constructorCall->TsType()->HasTypeFlag(TypeFlag::TYPE_ERROR)) { + if (constructorCall->TsType() == nullptr || constructorCall->TsType()->HasTypeFlag(TypeFlag::TYPE_ERROR)) { LogError(diagnostic::NO_SUCH_CTOR_SIG, {}, constructorCall->Start()); return; } diff --git a/ets2panda/test/ast/parser/ets/constructor_type_inference_crash.ets b/ets2panda/test/ast/parser/ets/constructor_type_inference_crash.ets new file mode 100644 index 0000000000..d31d7c3e7a --- /dev/null +++ b/ets2panda/test/ast/parser/ets/constructor_type_inference_crash.ets @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class C { + constructor(x: number, y: string); + constructor(s: string); + constructor(xs: any, y?: any) {} +} +let c = new C(10, 'foo'); + +/* @@? 17:14 Error TypeError: Only abstract or native methods can't have body. */ +/* @@? 19:3 Error TypeError: No matching call signature for constructor */ +/* @@? 19:19 Error TypeError: Cannot find type 'any'. */ +/* @@? 19:28 Error TypeError: Cannot find type 'any'. */ + diff --git a/ets2panda/test/test-lists/recheck/recheck-ignored.txt b/ets2panda/test/test-lists/recheck/recheck-ignored.txt index 514e054bf5..0c7bc94ce1 100644 --- a/ets2panda/test/test-lists/recheck/recheck-ignored.txt +++ b/ets2panda/test/test-lists/recheck/recheck-ignored.txt @@ -635,6 +635,7 @@ ast/parser/ets/method_modifier_check_15.ets ast/parser/ets/user_defined_16.ets ast/parser/ets/enum_default_invalid_value_type.ets ast/parser/ets/struct_implements_interface.ets +ast/parser/ets/constructor_type_inference_crash.ets ast/parser/ets/wrong_context_function_1.ets ast/parser/ets/empty_array_map_inference_fail.ets ast/parser/ets/illegal_continue_statement.ets -- Gitee From c1e71965f5f3f269791ed84160aa8fcf07497124 Mon Sep 17 00:00:00 2001 From: e84401138 Date: Mon, 5 May 2025 11:36:47 +0300 Subject: [PATCH 203/268] Fuzzing: es2panda crash astNode.cpp Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC424X Reason: Missing override for child class clone method Description: EmptyStatement class doesn't provide an override for Clone method Tests: ninja all tests Signed-off-by: e84401138 --- ets2panda/ir/statements/emptyStatement.cpp | 13 +++++++- ets2panda/ir/statements/emptyStatement.h | 3 +- .../ast/parser/ets/unreachable_fuzz_error.ets | 30 +++++++++++++++++++ .../test-lists/recheck/recheck-ignored.txt | 1 + 4 files changed, 45 insertions(+), 2 deletions(-) create mode 100644 ets2panda/test/ast/parser/ets/unreachable_fuzz_error.ets diff --git a/ets2panda/ir/statements/emptyStatement.cpp b/ets2panda/ir/statements/emptyStatement.cpp index 5159ef56e3..f3f541464b 100644 --- a/ets2panda/ir/statements/emptyStatement.cpp +++ b/ets2panda/ir/statements/emptyStatement.cpp @@ -1,5 +1,5 @@ /** - * Copyright (c) 2021-2024 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -58,4 +58,15 @@ checker::VerifiedType EmptyStatement::Check(checker::ETSChecker *checker) { return {this, checker->GetAnalyzer()->Check(this)}; } + +[[nodiscard]] EmptyStatement *EmptyStatement::Clone(ArenaAllocator *allocator, AstNode *parent) +{ + EmptyStatement *stmt = allocator->New(); + if (stmt != nullptr) { + stmt->SetParent(parent); + stmt->SetRange(Range()); + } + + return stmt; +} } // namespace ark::es2panda::ir diff --git a/ets2panda/ir/statements/emptyStatement.h b/ets2panda/ir/statements/emptyStatement.h index bba6f5958a..22c56bfb40 100644 --- a/ets2panda/ir/statements/emptyStatement.h +++ b/ets2panda/ir/statements/emptyStatement.h @@ -1,5 +1,5 @@ /** - * Copyright (c) 2021-2024 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -31,6 +31,7 @@ public: void Compile(compiler::ETSGen *etsg) const override; checker::Type *Check(checker::TSChecker *checker) override; checker::VerifiedType Check(checker::ETSChecker *checker) override; + [[nodiscard]] EmptyStatement *Clone(ArenaAllocator *allocator, AstNode *parent) override; void Accept(ASTVisitorT *v) override { diff --git a/ets2panda/test/ast/parser/ets/unreachable_fuzz_error.ets b/ets2panda/test/ast/parser/ets/unreachable_fuzz_error.ets new file mode 100644 index 0000000000..94b7879b28 --- /dev/null +++ b/ets2panda/test/ast/parser/ets/unreachable_fuzz_error.ets @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + let x = z.meth(foo) + +{ + assert(y[0] == 1) + assert(y[1] == 2) + +classtext: string, reviver: ((key: string, value: NullishType) => NullishType) | undefined, type: Type + +/* @@? 16:13 Error TypeError: Unresolved reference z */ +/* @@? 22:12 Error SyntaxError: Label must be followed by a loop statement. */ +/* @@? 22:18 Error SyntaxError: Unexpected token ','. */ +/* @@? 22:29 Error SyntaxError: Label must be followed by a loop statement. */ +/* @@? 22:91 Error SyntaxError: Unexpected token ','. */ +/* @@? 22:99 Error SyntaxError: Label must be followed by a loop statement. */ +/* @@? 30:60 Error SyntaxError: Expected '}', got 'eos'. */ \ No newline at end of file diff --git a/ets2panda/test/test-lists/recheck/recheck-ignored.txt b/ets2panda/test/test-lists/recheck/recheck-ignored.txt index 0c7bc94ce1..754a174c46 100644 --- a/ets2panda/test/test-lists/recheck/recheck-ignored.txt +++ b/ets2panda/test/test-lists/recheck/recheck-ignored.txt @@ -642,6 +642,7 @@ ast/parser/ets/illegal_continue_statement.ets ast/parser/ets/minus_sign_as_index_1.ets ast/parser/ets/export_after_statement.ets ast/parser/ets/unreachable_fuzz_error.ets +ast/parser/ets/unreachable_fuzz_error.ets ast/parser/ets/interface_parser_error_1.ets ast/parser/ets/interface_parser_error_2.ets ast/compiler/ets/union_string_literals_5.ets -- Gitee From 6e1348fed04c45b91a29da95e39a39281300ba52 Mon Sep 17 00:00:00 2001 From: tolgayakar Date: Tue, 29 Apr 2025 10:30:04 +0300 Subject: [PATCH 204/268] Handle nullptr and IsETSParameterExpression Description: Handle nullptr in ETSAnalyzer.cpp and added params[0]->IsETSParameterExpression for ETSparserTypes.cpp Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC3XSK Signed-off-by: tolgayakar -- Gitee From 31dfa922af9051baf931145173b8cd3a9a3d8f17 Mon Sep 17 00:00:00 2001 From: Utku Enes GURSEL Date: Sun, 27 Apr 2025 00:39:15 +0300 Subject: [PATCH 205/268] handle nullptr for loop body Issue: IC427V Description: Handled the nullptr for loop body, which was reported by the fuzzing platform tests. Signed-off-by: Utku Enes GURSEL --- ets2panda/parser/statementParser.cpp | 4 +++ .../ast/parser/ets/for_with_empty_body.ets | 26 +++++++++++++++++++ .../test-lists/recheck/recheck-ignored.txt | 3 ++- 3 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 ets2panda/test/ast/parser/ets/for_with_empty_body.ets diff --git a/ets2panda/parser/statementParser.cpp b/ets2panda/parser/statementParser.cpp index dc9ad8cce5..d3fcb64454 100644 --- a/ets2panda/parser/statementParser.cpp +++ b/ets2panda/parser/statementParser.cpp @@ -1021,6 +1021,10 @@ ir::Statement *ParserImpl::ParseForStatement() ExpectToken(lexer::TokenType::PUNCTUATOR_RIGHT_PARENTHESIS); ir::Statement *bodyNode = ParseStatement(); + if (bodyNode == nullptr) { + return AllocBrokenStatement(Lexer()->GetToken().Loc()); + } + return CreateForStatement({initNode, rightNode, updateNode, bodyNode}, forKind, startLoc, isAwait); } diff --git a/ets2panda/test/ast/parser/ets/for_with_empty_body.ets b/ets2panda/test/ast/parser/ets/for_with_empty_body.ets new file mode 100644 index 0000000000..a1e35845ea --- /dev/null +++ b/ets2panda/test/ast/parser/ets/for_with_empty_body.ets @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/*--- +flags: [dynamic-ast] +---*/ + +for ( ; ; ) + +try { + +} + +/* @@? 22:1 Error SyntaxError: A try statement should contain either finally clause or at least one catch clause. */ diff --git a/ets2panda/test/test-lists/recheck/recheck-ignored.txt b/ets2panda/test/test-lists/recheck/recheck-ignored.txt index 754a174c46..2af8ec9339 100644 --- a/ets2panda/test/test-lists/recheck/recheck-ignored.txt +++ b/ets2panda/test/test-lists/recheck/recheck-ignored.txt @@ -153,6 +153,7 @@ ast/parser/ets/StructTest3.ets ast/parser/ets/trailing_comma_1.ets ast/parser/ets/invalid_access_static.ets ast/parser/ets/interfaces2.ets +ast/parser/ets/for_with_empty_body.ets ast/parser/ets/generics_type_param_no_typeargs_no_default_2.ets ast/parser/ets/namespace_badtoken04.ets ast/parser/ets/InvalidStatements1.ets @@ -1476,4 +1477,4 @@ runtime/ets/objectLiteral-2.ets runtime/ets/objectLiteral.ets runtime/ets/objectLiteralInterfaceType.ets runtime/ets/objectLiteral_abstract_class_object.ets -runtime/ets/rest_object_literal.ets \ No newline at end of file +runtime/ets/rest_object_literal.ets -- Gitee From 5295ef796e1e16d65f697d906ad43969358ce214 Mon Sep 17 00:00:00 2001 From: Dmitry Pimenov Date: Wed, 23 Apr 2025 18:32:42 +0300 Subject: [PATCH 206/268] Fix crush on 'WE: readonly true' Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC3HF5 Signed-off-by: Dmitry Pimenov --- ets2panda/test/ast/parser/ets/readonlyFunctionTypeAnnotation.ets | 1 + 1 file changed, 1 insertion(+) diff --git a/ets2panda/test/ast/parser/ets/readonlyFunctionTypeAnnotation.ets b/ets2panda/test/ast/parser/ets/readonlyFunctionTypeAnnotation.ets index b413b11d6f..b36e68e76e 100644 --- a/ets2panda/test/ast/parser/ets/readonlyFunctionTypeAnnotation.ets +++ b/ets2panda/test/ast/parser/ets/readonlyFunctionTypeAnnotation.ets @@ -18,6 +18,7 @@ func: readonly (Y : object | long [] ) => [ ] /* @@? 17:7 Error SyntaxError: Label must be followed by a loop statement. */ /* @@? 17:7 Error TypeError: Unresolved reference readonly */ +/* @@? 17:17 Error SyntaxError: Invalid Type. */ /* @@? 17:20 Error SyntaxError: Unexpected token, expected ',' or ')'. */ /* @@? 17:20 Error SyntaxError: Unexpected token ':'. */ /* @@? 17:20 Error SyntaxError: Unexpected token ':'. */ -- Gitee From c5c184b0e77cedbe6d9fb5d868ba2e3c9f61a77f Mon Sep 17 00:00:00 2001 From: xuxinjie4 Date: Sat, 17 May 2025 18:07:27 +0800 Subject: [PATCH 207/268] Fix merge conflict Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC8V3A?from=project-issue Signed-off-by: xuxinjie4 --- ets2panda/parser/ETSparser.cpp | 2 +- .../parser/ets/interface_parser_error_1.ets | 111 ++++++++++++------ .../parser/ets/interface_parser_error_2.ets | 7 +- ets2panda/util/diagnostic/semantic.yaml | 6 +- 4 files changed, 80 insertions(+), 46 deletions(-) diff --git a/ets2panda/parser/ETSparser.cpp b/ets2panda/parser/ETSparser.cpp index 84932db2c3..5ded0f1749 100644 --- a/ets2panda/parser/ETSparser.cpp +++ b/ets2panda/parser/ETSparser.cpp @@ -1612,7 +1612,7 @@ ir::Statement *ETSParser::ParseImportDeclaration([[maybe_unused]] StatementParsi ir::Statement *ETSParser::ParseExportDeclaration([[maybe_unused]] StatementParsingFlags flags) { LogUnexpectedToken(lexer::TokenType::KEYW_EXPORT); - return nullptr; + return AllocBrokenStatement(Lexer()->GetToken().Start()); } ir::Expression *ETSParser::ParseExpressionOrTypeAnnotation(lexer::TokenType type, diff --git a/ets2panda/test/ast/parser/ets/interface_parser_error_1.ets b/ets2panda/test/ast/parser/ets/interface_parser_error_1.ets index 0b3fc3728f..a26a0ccd89 100644 --- a/ets2panda/test/ast/parser/ets/interface_parser_error_1.ets +++ b/ets2panda/test/ast/parser/ets/interface_parser_error_1.ets @@ -14,16 +14,17 @@ */ b: Geit { - t {name(): + t { + name(): -interface I { - readonly : boolean -} -inter + interface I { + readonly: boolean + } + inter -class A implements I { - reanstructor() { - this.a = f�ls + class A implements I { + reanstructor() { + this.a = f�ls s A { @ constructor() { this.a = ruO; @@ -37,31 +38,69 @@ function mdin() { let a = new A(); /* @@? 16:9 Error SyntaxError: Unexpected token '{'. */ /* @@? 17:2 Error TypeError: Unresolved reference t */ /* @@? 17:4 Error SyntaxError: Unexpected token '{'. */ -/* @@? 17:5 Error TypeError: Unresolved reference name */ -/* @@? 17:11 Error SyntaxError: Unexpected token ':'. */ -/* @@? 20:5 Error SyntaxError: Identifier expected. */ -/* @@? 20:14 Error SyntaxError: Unexpected token, expected ','. */ -/* @@? 20:14 Error SyntaxError: Unexpected token, expected 'private' or identifier. */ -/* @@? 20:16 Error SyntaxError: Identifier expected. */ -/* @@? 20:16 Error SyntaxError: Unexpected token, expected ','. */ -/* @@? 20:16 Error SyntaxError: Unexpected token, expected 'private' or identifier. */ -/* @@? 21:1 Error SyntaxError: Identifier expected. */ -/* @@? 22:1 Error TypeError: Class literal is not yet supported. */ -/* @@? 22:1 Error TypeError: Cannot find type 'inter'. */ -/* @@? 24:7 Error SyntaxError: Unexpected token 'A'. */ -/* @@? 24:7 Error TypeError: Unresolved reference A */ -/* @@? 24:9 Error SyntaxError: Unexpected token 'implements'. */ -/* @@? 24:20 Error TypeError: Interface name 'I' used in the wrong context */ -/* @@? 24:22 Error SyntaxError: Unexpected token '{'. */ -/* @@? 25:4 Error TypeError: Unresolved reference reanstructor */ -/* @@? 26:19 Error SyntaxError: Unexpected token, expected an identifier. */ -/* @@? 26:19 Error SyntaxError: Unexpected token '�ls'. */ -/* @@? 27:5 Error SyntaxError: Unexpected token 'A'. */ -/* @@? 27:7 Error SyntaxError: Unexpected token '{'. */ -/* @@? 28:5 Error SyntaxError: Identifier expected, got 'constructor'. */ -/* @@? 28:19 Error SyntaxError: Annotations are not allowed on this type of declaration. */ -/* @@? 29:18 Error SyntaxError: Unexpected token, expected an identifier. */ -/* @@? 31:2 Error SyntaxError: Unexpected token '*'. */ -/* @@? 32:1 Error SyntaxError: Nested functions are not allowed. */ -/* @@? 32:1 Error SyntaxError: Unexpected token 'function'. */ -/* @@? 68:1 Error SyntaxError: Expected '}', got 'eos'. */ +/* @@? 18:9 Error TypeError: Unresolved reference name */ +/* @@? 18:15 Error SyntaxError: Unexpected token ':'. */ +/* @@? 18:15 Error SyntaxError: Unexpected token ':'. */ +/* @@? 18:15 Error SyntaxError: Unexpected token ':'. */ +/* @@? 21:13 Error SyntaxError: Identifier expected. */ +/* @@? 21:21 Error SyntaxError: Unexpected token, expected ','. */ +/* @@? 21:21 Error SyntaxError: Unexpected token, expected 'private' or identifier. */ +/* @@? 21:21 Error TypeError: Property '*ERROR_LITERAL*' must be accessed through 'this' */ +/* @@? 22:9 Error SyntaxError: Interface fields must have type annotation. */ +/* @@? 23:9 Error TypeError: Cannot find type 'inter'. */ +/* @@? 23:9 Error TypeError: Cannot find type 'inter'. */ +/* @@? 25:15 Error TypeError: Cannot find type 'A'. */ +/* @@? 25:15 Error TypeError: Cannot find type 'A'. */ +/* @@? 25:17 Error SyntaxError: Unexpected token, expected 'private' or identifier. */ +/* @@? 25:17 Error SyntaxError: Unexpected token, expected ','. */ +/* @@? 25:30 Error SyntaxError: Interface fields must have type annotation. */ +/* @@? 26:13 Error TypeError: Cannot find type 'reanstructor'. */ +/* @@? 26:13 Error TypeError: Cannot find type 'reanstructor'. */ +/* @@? 26:25 Error SyntaxError: Unexpected token, expected ','. */ +/* @@? 26:25 Error SyntaxError: Unexpected token, expected 'private' or identifier. */ +/* @@? 26:26 Error SyntaxError: Identifier expected. */ +/* @@? 26:26 Error SyntaxError: Unexpected token, expected ','. */ +/* @@? 26:26 Error SyntaxError: Unexpected token, expected 'private' or identifier. */ +/* @@? 26:26 Error TypeError: Property '*ERROR_LITERAL*' must be accessed through 'this' */ +/* @@? 26:28 Error SyntaxError: Identifier expected. */ +/* @@? 26:28 Error SyntaxError: Unexpected token, expected ','. */ +/* @@? 26:28 Error SyntaxError: Unexpected token, expected 'private' or identifier. */ +/* @@? 26:28 Error TypeError: Property '*ERROR_LITERAL*' must be accessed through 'this' */ +/* @@? 27:17 Error SyntaxError: Identifier expected. */ +/* @@? 27:17 Error TypeError: Property '*ERROR_LITERAL*' must be accessed through 'this' */ +/* @@? 27:21 Error SyntaxError: Interface fields must have type annotation. */ +/* @@? 27:22 Error TypeError: Cannot find type 'a'. */ +/* @@? 27:22 Error TypeError: Cannot find type 'a'. */ +/* @@? 27:24 Error SyntaxError: Interface member initialization is prohibited. */ +/* @@? 27:26 Error SyntaxError: Unexpected token, expected ','. */ +/* @@? 27:26 Error SyntaxError: Unexpected token, expected 'private' or identifier. */ +/* @@? 27:27 Error SyntaxError: Unexpected token, expected an identifier. */ +/* @@? 28:3 Error TypeError: Cannot find type 's'. */ +/* @@? 28:3 Error TypeError: Cannot find type 's'. */ +/* @@? 28:5 Error SyntaxError: Unexpected token, expected 'private' or identifier. */ +/* @@? 28:5 Error SyntaxError: Unexpected token, expected ','. */ +/* @@? 28:7 Error SyntaxError: Unexpected token, expected 'private' or identifier. */ +/* @@? 28:7 Error SyntaxError: Unexpected token, expected ','. */ +/* @@? 28:7 Error SyntaxError: Identifier expected. */ +/* @@? 28:7 Error TypeError: Property '*ERROR_LITERAL*' must be accessed through 'this' */ +/* @@? 29:3 Error SyntaxError: Identifier expected. */ +/* @@? 29:3 Error TypeError: Property '*ERROR_LITERAL*' must be accessed through 'this' */ +/* @@? 29:5 Error SyntaxError: Identifier expected, got 'constructor'. */ +/* @@? 29:19 Error SyntaxError: Annotations are not allowed on this type of declaration. */ +/* @@? 29:19 Error SyntaxError: Unexpected token, expected 'private' or identifier. */ +/* @@? 30:9 Error SyntaxError: Identifier expected. */ +/* @@? 30:9 Error TypeError: Property '*ERROR_LITERAL*' must be accessed through 'this' */ +/* @@? 30:13 Error SyntaxError: Interface fields must have type annotation. */ +/* @@? 30:14 Error TypeError: Cannot find type 'a'. */ +/* @@? 30:14 Error TypeError: Cannot find type 'a'. */ +/* @@? 30:16 Error SyntaxError: Interface member initialization is prohibited. */ +/* @@? 30:18 Error SyntaxError: Unexpected token, expected 'private' or identifier. */ +/* @@? 30:18 Error SyntaxError: Unexpected token, expected ','. */ +/* @@? 30:18 Error SyntaxError: Unexpected token, expected an identifier. */ +/* @@? 30:22 Error SyntaxError: Identifier expected. */ +/* @@? 30:22 Error TypeError: Property '*ERROR_LITERAL*' must be accessed through 'this' */ +/* @@? 32:2 Error SyntaxError: Unexpected token '*'. */ +/* @@? 33:1 Error SyntaxError: Nested functions are not allowed. */ +/* @@? 33:1 Error SyntaxError: Unexpected token 'function'. */ +/* @@? 106:61 Error SyntaxError: Expected '}', got 'eos'. */ +/* @@? 106:61 Error SyntaxError: Expected '}', got 'eos'. */ \ No newline at end of file diff --git a/ets2panda/test/ast/parser/ets/interface_parser_error_2.ets b/ets2panda/test/ast/parser/ets/interface_parser_error_2.ets index b2f0dcd090..3c2f299b32 100644 --- a/ets2panda/test/ast/parser/ets/interface_parser_error_2.ets +++ b/ets2panda/test/ast/parser/ets/interface_parser_error_2.ets @@ -18,7 +18,6 @@ interface I { } /* @@? 17:5 Error SyntaxError: Unexpected token, expected 'private' or identifier. */ -/* @@? 17:7 Error SyntaxError: Identifier expected. */ -/* @@? 17:7 Error SyntaxError: Unexpected token, expected ','. */ -/* @@? 17:7 Error SyntaxError: Unexpected token, expected 'private' or identifier. */ -/* @@? 18:1 Error SyntaxError: Identifier expected. */ +/* @@? 18:1 Error SyntaxError: Interface fields must have type annotation. */ +/* @@? 23:67 Error SyntaxError: Invalid Type. */ +/* @@? 23:67 Error SyntaxError: Unexpected token, expected '}'. */ \ No newline at end of file diff --git a/ets2panda/util/diagnostic/semantic.yaml b/ets2panda/util/diagnostic/semantic.yaml index f374ad7d6c..11e8dc17f5 100644 --- a/ets2panda/util/diagnostic/semantic.yaml +++ b/ets2panda/util/diagnostic/semantic.yaml @@ -1345,8 +1345,4 @@ semantic: - name: READONLY_PROPERTY_REASSIGN id: 338 - message: "The 'Readonly' property cannot be reassigned." - -- name: PROPERTY_MAYBE_MISSING_INIT - id: 339 - message: "Property '{}' might not have been initialized." \ No newline at end of file + message: "The 'Readonly' property cannot be reassigned." \ No newline at end of file -- Gitee From bc8de40ea03e4f4f61b0692a239979ceaf94766a Mon Sep 17 00:00:00 2001 From: eraycinar Date: Tue, 13 May 2025 14:45:32 +0300 Subject: [PATCH 208/268] [FUZZING]fix segfault by adding recursive guard Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC8J2B?from=project-issue Signed-off-by: eraycinar --- ets2panda/parser/ETSparser.h | 3 + ets2panda/parser/ETSparserExpressions.cpp | 21 +- .../parser/ets/interface_parser_error_1.ets | 74 +-- .../parser/ets/interface_parser_error_2.ets | 7 +- .../ast/parser/ets/too_many_expression.ets | 478 ++++++++++++++++++ .../ast/parser/ets/unexpected_token_62.ets | 13 +- .../test-lists/recheck/recheck-ignored.txt | 1 + ets2panda/util/diagnostic/fatal.yaml | 4 + ets2panda/util/recursiveGuard.h | 57 +++ 9 files changed, 597 insertions(+), 61 deletions(-) create mode 100644 ets2panda/test/ast/parser/ets/too_many_expression.ets create mode 100644 ets2panda/util/recursiveGuard.h diff --git a/ets2panda/parser/ETSparser.h b/ets2panda/parser/ETSparser.h index 0c5a04636b..7721a8ffa6 100644 --- a/ets2panda/parser/ETSparser.h +++ b/ets2panda/parser/ETSparser.h @@ -18,6 +18,7 @@ #include "util/arktsconfig.h" #include "util/importPathManager.h" +#include "util/recursiveGuard.h" #include "innerSourceParser.h" #include "TypedParser.h" #include "ir/base/classDefinition.h" @@ -551,6 +552,7 @@ private: friend class ExternalSourceParser; friend class InnerSourceParser; + friend ir::Expression *HandleLeftParanthesis(ETSParser *parser, ExpressionParseFlags flags); private: uint32_t namespaceNestedRank_; @@ -560,6 +562,7 @@ private: parser::Program *globalProgram_; std::vector insertingNodes_ {}; std::unique_ptr importPathManager_ {nullptr}; + RecursiveContext recursiveCtx_; }; class ExternalSourceParser { diff --git a/ets2panda/parser/ETSparserExpressions.cpp b/ets2panda/parser/ETSparserExpressions.cpp index 0c119f540a..aec40b4e82 100644 --- a/ets2panda/parser/ETSparserExpressions.cpp +++ b/ets2panda/parser/ETSparserExpressions.cpp @@ -15,11 +15,16 @@ #include "ETSparser.h" +#include "generated/tokenType.h" #include "lexer/lexer.h" #include "ir/expressions/literals/undefinedLiteral.h" #include "ir/ets/etsTuple.h" +#include "macros.h" +#include "parserFlags.h" #include "util/errorRecovery.h" #include "generated/diagnostic.h" +#include "parserImpl.h" +#include "util/recursiveGuard.h" namespace ark::es2panda::parser { class FunctionContext; @@ -302,12 +307,26 @@ ir::Expression *ETSParser::ParsePrimaryExpressionWithLiterals(ExpressionParseFla } } +// This function is used to handle the left parenthesis in the expression parsing. +ir::Expression *HandleLeftParanthesis(ETSParser *parser, ExpressionParseFlags flags) +{ + TrackRecursive trackRecursive(parser->recursiveCtx_); + if (!trackRecursive) { + parser->LogError(diagnostic::DEEP_NESTING); + while (parser->Lexer()->GetToken().Type() != lexer::TokenType::EOS) { + parser->Lexer()->NextToken(); + } + return parser->AllocBrokenExpression(parser->Lexer()->GetToken().Loc()); + } + return parser->ParseCoverParenthesizedExpressionAndArrowParameterList(flags); +} + // NOLINTNEXTLINE(google-default-arguments) ir::Expression *ETSParser::ParsePrimaryExpression(ExpressionParseFlags flags) { switch (Lexer()->GetToken().Type()) { case lexer::TokenType::PUNCTUATOR_LEFT_PARENTHESIS: { - return ParseCoverParenthesizedExpressionAndArrowParameterList(flags); + return HandleLeftParanthesis(this, flags); } case lexer::TokenType::KEYW_THIS: { return ParseThisExpression(); diff --git a/ets2panda/test/ast/parser/ets/interface_parser_error_1.ets b/ets2panda/test/ast/parser/ets/interface_parser_error_1.ets index a26a0ccd89..d18aff4108 100644 --- a/ets2panda/test/ast/parser/ets/interface_parser_error_1.ets +++ b/ets2panda/test/ast/parser/ets/interface_parser_error_1.ets @@ -45,62 +45,34 @@ function mdin() { let a = new A(); /* @@? 21:13 Error SyntaxError: Identifier expected. */ /* @@? 21:21 Error SyntaxError: Unexpected token, expected ','. */ /* @@? 21:21 Error SyntaxError: Unexpected token, expected 'private' or identifier. */ -/* @@? 21:21 Error TypeError: Property '*ERROR_LITERAL*' must be accessed through 'this' */ -/* @@? 22:9 Error SyntaxError: Interface fields must have type annotation. */ +/* @@? 21:23 Error SyntaxError: Identifier expected. */ +/* @@? 21:23 Error SyntaxError: Unexpected token, expected ','. */ +/* @@? 21:23 Error SyntaxError: Unexpected token, expected 'private' or identifier. */ +/* @@? 22:9 Error SyntaxError: Identifier expected. */ +/* @@? 23:9 Error TypeError: Class literal is not yet supported. */ /* @@? 23:9 Error TypeError: Cannot find type 'inter'. */ -/* @@? 23:9 Error TypeError: Cannot find type 'inter'. */ -/* @@? 25:15 Error TypeError: Cannot find type 'A'. */ -/* @@? 25:15 Error TypeError: Cannot find type 'A'. */ -/* @@? 25:17 Error SyntaxError: Unexpected token, expected 'private' or identifier. */ -/* @@? 25:17 Error SyntaxError: Unexpected token, expected ','. */ -/* @@? 25:30 Error SyntaxError: Interface fields must have type annotation. */ -/* @@? 26:13 Error TypeError: Cannot find type 'reanstructor'. */ -/* @@? 26:13 Error TypeError: Cannot find type 'reanstructor'. */ -/* @@? 26:25 Error SyntaxError: Unexpected token, expected ','. */ -/* @@? 26:25 Error SyntaxError: Unexpected token, expected 'private' or identifier. */ -/* @@? 26:26 Error SyntaxError: Identifier expected. */ -/* @@? 26:26 Error SyntaxError: Unexpected token, expected ','. */ -/* @@? 26:26 Error SyntaxError: Unexpected token, expected 'private' or identifier. */ -/* @@? 26:26 Error TypeError: Property '*ERROR_LITERAL*' must be accessed through 'this' */ -/* @@? 26:28 Error SyntaxError: Identifier expected. */ -/* @@? 26:28 Error SyntaxError: Unexpected token, expected ','. */ -/* @@? 26:28 Error SyntaxError: Unexpected token, expected 'private' or identifier. */ -/* @@? 26:28 Error TypeError: Property '*ERROR_LITERAL*' must be accessed through 'this' */ -/* @@? 27:17 Error SyntaxError: Identifier expected. */ -/* @@? 27:17 Error TypeError: Property '*ERROR_LITERAL*' must be accessed through 'this' */ -/* @@? 27:21 Error SyntaxError: Interface fields must have type annotation. */ -/* @@? 27:22 Error TypeError: Cannot find type 'a'. */ -/* @@? 27:22 Error TypeError: Cannot find type 'a'. */ -/* @@? 27:24 Error SyntaxError: Interface member initialization is prohibited. */ -/* @@? 27:26 Error SyntaxError: Unexpected token, expected ','. */ -/* @@? 27:26 Error SyntaxError: Unexpected token, expected 'private' or identifier. */ +/* @@? 25:15 Error SyntaxError: Unexpected token 'A'. */ +/* @@? 25:15 Error TypeError: Unresolved reference A */ +/* @@? 25:17 Error SyntaxError: Unexpected token 'implements'. */ +/* @@? 25:17 Error SyntaxError: Unexpected token 'implements'. */ +/* @@? 25:17 Error SyntaxError: Unexpected token 'implements'. */ +/* @@? 25:28 Error TypeError: Interface name 'I' used in the wrong context */ +/* @@? 25:30 Error SyntaxError: Unexpected token '{'. */ +/* @@? 26:13 Error TypeError: Unresolved reference reanstructor */ +/* @@? 27:27 Error SyntaxError: Unexpected token, expected an identifier. */ +/* @@? 27:27 Error SyntaxError: Unexpected token, expected an identifier. */ /* @@? 27:27 Error SyntaxError: Unexpected token, expected an identifier. */ -/* @@? 28:3 Error TypeError: Cannot find type 's'. */ -/* @@? 28:3 Error TypeError: Cannot find type 's'. */ -/* @@? 28:5 Error SyntaxError: Unexpected token, expected 'private' or identifier. */ -/* @@? 28:5 Error SyntaxError: Unexpected token, expected ','. */ -/* @@? 28:7 Error SyntaxError: Unexpected token, expected 'private' or identifier. */ -/* @@? 28:7 Error SyntaxError: Unexpected token, expected ','. */ -/* @@? 28:7 Error SyntaxError: Identifier expected. */ -/* @@? 28:7 Error TypeError: Property '*ERROR_LITERAL*' must be accessed through 'this' */ -/* @@? 29:3 Error SyntaxError: Identifier expected. */ -/* @@? 29:3 Error TypeError: Property '*ERROR_LITERAL*' must be accessed through 'this' */ +/* @@? 27:27 Error SyntaxError: Unexpected token '�ls'. */ +/* @@? 28:5 Error SyntaxError: Unexpected token 'A'. */ +/* @@? 28:7 Error SyntaxError: Unexpected token '{'. */ /* @@? 29:5 Error SyntaxError: Identifier expected, got 'constructor'. */ /* @@? 29:19 Error SyntaxError: Annotations are not allowed on this type of declaration. */ -/* @@? 29:19 Error SyntaxError: Unexpected token, expected 'private' or identifier. */ -/* @@? 30:9 Error SyntaxError: Identifier expected. */ -/* @@? 30:9 Error TypeError: Property '*ERROR_LITERAL*' must be accessed through 'this' */ -/* @@? 30:13 Error SyntaxError: Interface fields must have type annotation. */ -/* @@? 30:14 Error TypeError: Cannot find type 'a'. */ -/* @@? 30:14 Error TypeError: Cannot find type 'a'. */ -/* @@? 30:16 Error SyntaxError: Interface member initialization is prohibited. */ -/* @@? 30:18 Error SyntaxError: Unexpected token, expected 'private' or identifier. */ -/* @@? 30:18 Error SyntaxError: Unexpected token, expected ','. */ /* @@? 30:18 Error SyntaxError: Unexpected token, expected an identifier. */ -/* @@? 30:22 Error SyntaxError: Identifier expected. */ -/* @@? 30:22 Error TypeError: Property '*ERROR_LITERAL*' must be accessed through 'this' */ /* @@? 32:2 Error SyntaxError: Unexpected token '*'. */ /* @@? 33:1 Error SyntaxError: Nested functions are not allowed. */ /* @@? 33:1 Error SyntaxError: Unexpected token 'function'. */ -/* @@? 106:61 Error SyntaxError: Expected '}', got 'eos'. */ -/* @@? 106:61 Error SyntaxError: Expected '}', got 'eos'. */ \ No newline at end of file +/* @@? 78:60 Error SyntaxError: Expected '}', got 'eos'. */ +/* @@? 78:60 Error SyntaxError: Expected '}', got 'eos'. */ +/* @@? 78:60 Error SyntaxError: Expected '}', got 'eos'. */ +/* @@? 78:60 Error SyntaxError: Expected '}', got 'eos'. */ +/* @@? 78:60 Error SyntaxError: Expected '}', got 'eos'. */ \ No newline at end of file diff --git a/ets2panda/test/ast/parser/ets/interface_parser_error_2.ets b/ets2panda/test/ast/parser/ets/interface_parser_error_2.ets index 3c2f299b32..bc6fdafb25 100644 --- a/ets2panda/test/ast/parser/ets/interface_parser_error_2.ets +++ b/ets2panda/test/ast/parser/ets/interface_parser_error_2.ets @@ -18,6 +18,7 @@ interface I { } /* @@? 17:5 Error SyntaxError: Unexpected token, expected 'private' or identifier. */ -/* @@? 18:1 Error SyntaxError: Interface fields must have type annotation. */ -/* @@? 23:67 Error SyntaxError: Invalid Type. */ -/* @@? 23:67 Error SyntaxError: Unexpected token, expected '}'. */ \ No newline at end of file +/* @@? 17:7 Error SyntaxError: Identifier expected. */ +/* @@? 17:7 Error SyntaxError: Unexpected token, expected ','. */ +/* @@? 17:7 Error SyntaxError: Unexpected token, expected 'private' or identifier. */ +/* @@? 18:1 Error SyntaxError: Identifier expected. */ \ No newline at end of file diff --git a/ets2panda/test/ast/parser/ets/too_many_expression.ets b/ets2panda/test/ast/parser/ets/too_many_expression.ets new file mode 100644 index 0000000000..e46f538c79 --- /dev/null +++ b/ets2panda/test/ast/parser/ets/too_many_expression.ets @@ -0,0 +1,478 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/new Uint8Array[let [-9] = ([((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= . 7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .$7 = + >>> 0O5.25657e9)]((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= . + +/* @@? 16:1 Error SyntaxError: Unexpected token '/'. */ +/* @@? 16:1 Error TypeError: Bad operand type, the types of the operands must be numeric type. */ +/* @@? 16:17 Error SyntaxError: Unexpected token 'let'. */ +/* @@? 16:17 Error SyntaxError: Expected ']', got 'let'. */ +/* @@? 16:17 Error SyntaxError: Unexpected token 'let'. */ +/* @@? 16:22 Error SyntaxError: Identifier expected, got '['. */ +/* @@? 16:23 Error SyntaxError: Variable must be initialized or it's type must be declared. */ +/* @@? 16:23 Error SyntaxError: Unexpected token '9'. */ +/* @@? 16:24 Error SyntaxError: Unexpected token ']'. */ +/* @@? 16:26 Error SyntaxError: Unexpected token '='. */ +/* @@? 16:28 Error SyntaxError: Unexpected token '<'. */ +/* @@? 16:29 Error TypeError: Unresolved reference missing */ +/* @@? 16:37 Error SyntaxError: Unexpected token ']'. */ +/* @@? 16:37 Error TypeError: Bad operand type, the types of the operands must be numeric, same enumeration, or boolean type. */ +/* @@? 16:42 Error SyntaxError: Unexpected token '<'. */ +/* @@? 16:51 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 16:56 Error TypeError: need to specify target type for class composite */ +/* @@? 16:189 Error SyntaxError: Unexpected token. */ +/* @@? 16:189 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:189 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 16:191 Error SyntaxError: Invalid shorthand property initializer. */ +/* @@? 16:194 Error SyntaxError: Unexpected token '.'. */ +/* @@? 16:196 Error SyntaxError: Identifier expected, got 'number literal'. */ +/* @@? 16:202 Error SyntaxError: Unexpected token '>>>'. */ +/* @@? 16:209 Error SyntaxError: Unexpected token. */ +/* @@? 16:217 Error SyntaxError: Unexpected token. */ +/* @@? 16:218 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 16:353 Error SyntaxError: Unexpected token. */ +/* @@? 16:353 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 16:353 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:355 Error SyntaxError: Invalid shorthand property initializer. */ +/* @@? 16:361 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 16:365 Error SyntaxError: Unexpected token '>>>'. */ +/* @@? 16:372 Error SyntaxError: Unexpected token. */ +/* @@? 16:380 Error SyntaxError: Unexpected token. */ +/* @@? 16:381 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 16:516 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 16:516 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:516 Error SyntaxError: Unexpected token. */ +/* @@? 16:518 Error SyntaxError: Invalid shorthand property initializer. */ +/* @@? 16:524 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 16:528 Error SyntaxError: Unexpected token '>>>'. */ +/* @@? 16:535 Error SyntaxError: Unexpected token. */ +/* @@? 16:543 Error SyntaxError: Unexpected token. */ +/* @@? 16:544 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 16:679 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:679 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 16:679 Error SyntaxError: Unexpected token. */ +/* @@? 16:681 Error SyntaxError: Invalid shorthand property initializer. */ +/* @@? 16:687 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 16:691 Error SyntaxError: Unexpected token '>>>'. */ +/* @@? 16:698 Error SyntaxError: Unexpected token. */ +/* @@? 16:706 Error SyntaxError: Unexpected token. */ +/* @@? 16:707 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 16:842 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:842 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 16:842 Error SyntaxError: Unexpected token. */ +/* @@? 16:844 Error SyntaxError: Invalid shorthand property initializer. */ +/* @@? 16:850 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 16:854 Error SyntaxError: Unexpected token '>>>'. */ +/* @@? 16:861 Error SyntaxError: Unexpected token. */ +/* @@? 16:869 Error SyntaxError: Unexpected token. */ +/* @@? 16:870 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 16:1005 Error SyntaxError: Unexpected token. */ +/* @@? 16:1005 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 16:1005 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:1007 Error SyntaxError: Invalid shorthand property initializer. */ +/* @@? 16:1013 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 16:1017 Error SyntaxError: Unexpected token '>>>'. */ +/* @@? 16:1024 Error SyntaxError: Unexpected token. */ +/* @@? 16:1032 Error SyntaxError: Unexpected token. */ +/* @@? 16:1033 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 16:1168 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 16:1168 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:1168 Error SyntaxError: Unexpected token. */ +/* @@? 16:1170 Error SyntaxError: Invalid shorthand property initializer. */ +/* @@? 16:1176 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 16:1180 Error SyntaxError: Unexpected token '>>>'. */ +/* @@? 16:1187 Error SyntaxError: Unexpected token. */ +/* @@? 16:1195 Error SyntaxError: Unexpected token. */ +/* @@? 16:1196 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 16:1331 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 16:1331 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:1331 Error SyntaxError: Unexpected token. */ +/* @@? 16:1333 Error SyntaxError: Invalid shorthand property initializer. */ +/* @@? 16:1339 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 16:1343 Error SyntaxError: Unexpected token '>>>'. */ +/* @@? 16:1350 Error SyntaxError: Unexpected token. */ +/* @@? 16:1358 Error SyntaxError: Unexpected token. */ +/* @@? 16:1359 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 16:1494 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 16:1494 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:1494 Error SyntaxError: Unexpected token. */ +/* @@? 16:1496 Error SyntaxError: Invalid shorthand property initializer. */ +/* @@? 16:1502 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 16:1506 Error SyntaxError: Unexpected token '>>>'. */ +/* @@? 16:1513 Error SyntaxError: Unexpected token. */ +/* @@? 16:1521 Error SyntaxError: Unexpected token. */ +/* @@? 16:1522 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 16:1657 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:1657 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 16:1657 Error SyntaxError: Unexpected token. */ +/* @@? 16:1659 Error SyntaxError: Invalid shorthand property initializer. */ +/* @@? 16:1665 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 16:1669 Error SyntaxError: Unexpected token '>>>'. */ +/* @@? 16:1676 Error SyntaxError: Unexpected token. */ +/* @@? 16:1684 Error SyntaxError: Unexpected token. */ +/* @@? 16:1685 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 16:1820 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:1820 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 16:1820 Error SyntaxError: Unexpected token. */ +/* @@? 16:1822 Error SyntaxError: Invalid shorthand property initializer. */ +/* @@? 16:1828 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 16:1832 Error SyntaxError: Unexpected token '>>>'. */ +/* @@? 16:1839 Error SyntaxError: Unexpected token. */ +/* @@? 16:1847 Error SyntaxError: Unexpected token. */ +/* @@? 16:1848 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 16:1983 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:1983 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 16:1983 Error SyntaxError: Unexpected token. */ +/* @@? 16:1985 Error SyntaxError: Invalid shorthand property initializer. */ +/* @@? 16:1991 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 16:1995 Error SyntaxError: Unexpected token '>>>'. */ +/* @@? 16:2002 Error SyntaxError: Unexpected token. */ +/* @@? 16:2010 Error SyntaxError: Unexpected token. */ +/* @@? 16:2011 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 16:2146 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:2146 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 16:2146 Error SyntaxError: Unexpected token. */ +/* @@? 16:2148 Error SyntaxError: Invalid shorthand property initializer. */ +/* @@? 16:2154 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 16:2158 Error SyntaxError: Unexpected token '>>>'. */ +/* @@? 16:2165 Error SyntaxError: Unexpected token. */ +/* @@? 16:2173 Error SyntaxError: Unexpected token. */ +/* @@? 16:2174 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 16:2309 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:2309 Error SyntaxError: Unexpected token. */ +/* @@? 16:2309 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 16:2311 Error SyntaxError: Invalid shorthand property initializer. */ +/* @@? 16:2317 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 16:2321 Error SyntaxError: Unexpected token '>>>'. */ +/* @@? 16:2328 Error SyntaxError: Unexpected token. */ +/* @@? 16:2336 Error SyntaxError: Unexpected token. */ +/* @@? 16:2337 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 16:2472 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:2472 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 16:2472 Error SyntaxError: Unexpected token. */ +/* @@? 16:2474 Error SyntaxError: Invalid shorthand property initializer. */ +/* @@? 16:2480 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 16:2484 Error SyntaxError: Unexpected token '>>>'. */ +/* @@? 16:2491 Error SyntaxError: Unexpected token. */ +/* @@? 16:2499 Error SyntaxError: Unexpected token. */ +/* @@? 16:2500 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 16:2635 Error SyntaxError: Unexpected token. */ +/* @@? 16:2635 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 16:2635 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:2637 Error SyntaxError: Invalid shorthand property initializer. */ +/* @@? 16:2643 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 16:2647 Error SyntaxError: Unexpected token '>>>'. */ +/* @@? 16:2654 Error SyntaxError: Unexpected token. */ +/* @@? 16:2662 Error SyntaxError: Unexpected token. */ +/* @@? 16:2663 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 16:2798 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:2798 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 16:2798 Error SyntaxError: Unexpected token. */ +/* @@? 16:2800 Error SyntaxError: Invalid shorthand property initializer. */ +/* @@? 16:2806 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 16:2810 Error SyntaxError: Unexpected token '>>>'. */ +/* @@? 16:2817 Error SyntaxError: Unexpected token. */ +/* @@? 16:2825 Error SyntaxError: Unexpected token. */ +/* @@? 16:2826 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 16:2961 Error SyntaxError: Unexpected token. */ +/* @@? 16:2961 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 16:2961 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:2963 Error SyntaxError: Invalid shorthand property initializer. */ +/* @@? 16:2969 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 16:2973 Error SyntaxError: Unexpected token '>>>'. */ +/* @@? 16:2980 Error SyntaxError: Unexpected token. */ +/* @@? 16:2988 Error SyntaxError: Unexpected token. */ +/* @@? 16:2989 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 16:3124 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:3124 Error SyntaxError: Unexpected token. */ +/* @@? 16:3124 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 16:3126 Error SyntaxError: Invalid shorthand property initializer. */ +/* @@? 16:3132 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 16:3136 Error SyntaxError: Unexpected token '>>>'. */ +/* @@? 16:3143 Error SyntaxError: Unexpected token. */ +/* @@? 16:3151 Error SyntaxError: Unexpected token. */ +/* @@? 16:3152 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 16:3287 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:3287 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 16:3287 Error SyntaxError: Unexpected token. */ +/* @@? 16:3289 Error SyntaxError: Invalid shorthand property initializer. */ +/* @@? 16:3295 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 16:3299 Error SyntaxError: Unexpected token '>>>'. */ +/* @@? 16:3306 Error SyntaxError: Unexpected token. */ +/* @@? 16:3314 Error SyntaxError: Unexpected token. */ +/* @@? 16:3315 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 16:3450 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:3450 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 16:3450 Error SyntaxError: Unexpected token. */ +/* @@? 16:3452 Error SyntaxError: Invalid shorthand property initializer. */ +/* @@? 16:3458 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 16:3462 Error SyntaxError: Unexpected token '>>>'. */ +/* @@? 16:3469 Error SyntaxError: Unexpected token. */ +/* @@? 16:3477 Error SyntaxError: Unexpected token. */ +/* @@? 16:3478 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 16:3613 Error SyntaxError: Unexpected token. */ +/* @@? 16:3613 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 16:3613 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:3615 Error SyntaxError: Invalid shorthand property initializer. */ +/* @@? 16:3621 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 16:3625 Error SyntaxError: Unexpected token '>>>'. */ +/* @@? 16:3632 Error SyntaxError: Unexpected token. */ +/* @@? 16:3640 Error SyntaxError: Unexpected token. */ +/* @@? 16:3641 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 16:3776 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:3776 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 16:3776 Error SyntaxError: Unexpected token. */ +/* @@? 16:3778 Error SyntaxError: Invalid shorthand property initializer. */ +/* @@? 16:3784 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 16:3788 Error SyntaxError: Unexpected token '>>>'. */ +/* @@? 16:3795 Error SyntaxError: Unexpected token. */ +/* @@? 16:3803 Error SyntaxError: Unexpected token. */ +/* @@? 16:3804 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 16:3939 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:3939 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 16:3939 Error SyntaxError: Unexpected token. */ +/* @@? 16:3941 Error SyntaxError: Invalid shorthand property initializer. */ +/* @@? 16:3947 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 16:3951 Error SyntaxError: Unexpected token '>>>'. */ +/* @@? 16:3958 Error SyntaxError: Unexpected token. */ +/* @@? 16:3966 Error SyntaxError: Unexpected token. */ +/* @@? 16:3967 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 16:4102 Error SyntaxError: Unexpected token. */ +/* @@? 16:4102 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 16:4102 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:4104 Error SyntaxError: Invalid shorthand property initializer. */ +/* @@? 16:4110 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 16:4114 Error SyntaxError: Unexpected token '>>>'. */ +/* @@? 16:4121 Error SyntaxError: Unexpected token. */ +/* @@? 16:4129 Error SyntaxError: Unexpected token. */ +/* @@? 16:4130 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 16:4265 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:4265 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 16:4265 Error SyntaxError: Unexpected token. */ +/* @@? 16:4267 Error SyntaxError: Invalid shorthand property initializer. */ +/* @@? 16:4273 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 16:4277 Error SyntaxError: Unexpected token '>>>'. */ +/* @@? 16:4284 Error SyntaxError: Unexpected token. */ +/* @@? 16:4292 Error SyntaxError: Unexpected token. */ +/* @@? 16:4293 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 16:4428 Error SyntaxError: Unexpected token. */ +/* @@? 16:4428 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 16:4428 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:4430 Error SyntaxError: Invalid shorthand property initializer. */ +/* @@? 16:4436 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 16:4440 Error SyntaxError: Unexpected token '>>>'. */ +/* @@? 16:4447 Error SyntaxError: Unexpected token. */ +/* @@? 16:4455 Error SyntaxError: Unexpected token. */ +/* @@? 16:4456 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 16:4591 Error SyntaxError: Unexpected token. */ +/* @@? 16:4591 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 16:4591 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:4593 Error SyntaxError: Invalid shorthand property initializer. */ +/* @@? 16:4599 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 16:4603 Error SyntaxError: Unexpected token '>>>'. */ +/* @@? 16:4610 Error SyntaxError: Unexpected token. */ +/* @@? 16:4618 Error SyntaxError: Unexpected token. */ +/* @@? 16:4619 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 16:4754 Error SyntaxError: Unexpected token. */ +/* @@? 16:4754 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 16:4754 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:4756 Error SyntaxError: Invalid shorthand property initializer. */ +/* @@? 16:4762 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 16:4766 Error SyntaxError: Unexpected token '>>>'. */ +/* @@? 16:4773 Error SyntaxError: Unexpected token. */ +/* @@? 16:4781 Error SyntaxError: Unexpected token. */ +/* @@? 16:4782 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 16:4917 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:4917 Error SyntaxError: Unexpected token. */ +/* @@? 16:4917 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 16:4919 Error SyntaxError: Invalid shorthand property initializer. */ +/* @@? 16:4925 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 16:4929 Error SyntaxError: Unexpected token '>>>'. */ +/* @@? 16:4936 Error SyntaxError: Unexpected token. */ +/* @@? 16:4944 Error SyntaxError: Unexpected token. */ +/* @@? 16:4945 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 16:5080 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:5080 Error SyntaxError: Unexpected token. */ +/* @@? 16:5080 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 16:5082 Error SyntaxError: Invalid shorthand property initializer. */ +/* @@? 16:5088 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 16:5092 Error SyntaxError: Unexpected token '>>>'. */ +/* @@? 16:5099 Error SyntaxError: Unexpected token. */ +/* @@? 16:5107 Error SyntaxError: Unexpected token. */ +/* @@? 16:5108 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 16:5243 Error SyntaxError: Unexpected token. */ +/* @@? 16:5243 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:5243 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 16:5245 Error SyntaxError: Invalid shorthand property initializer. */ +/* @@? 16:5251 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 16:5255 Error SyntaxError: Unexpected token '>>>'. */ +/* @@? 16:5262 Error SyntaxError: Unexpected token. */ +/* @@? 16:5270 Error SyntaxError: Unexpected token. */ +/* @@? 16:5271 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 16:5406 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 16:5406 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:5406 Error SyntaxError: Unexpected token. */ +/* @@? 16:5408 Error SyntaxError: Invalid shorthand property initializer. */ +/* @@? 16:5414 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 16:5418 Error SyntaxError: Unexpected token '>>>'. */ +/* @@? 16:5425 Error SyntaxError: Unexpected token. */ +/* @@? 16:5433 Error SyntaxError: Unexpected token. */ +/* @@? 16:5434 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 16:5569 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 16:5569 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:5569 Error SyntaxError: Unexpected token. */ +/* @@? 16:5571 Error SyntaxError: Invalid shorthand property initializer. */ +/* @@? 16:5577 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 16:5581 Error SyntaxError: Unexpected token '>>>'. */ +/* @@? 16:5588 Error SyntaxError: Unexpected token. */ +/* @@? 16:5596 Error SyntaxError: Unexpected token. */ +/* @@? 16:5597 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 16:5732 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 16:5732 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 16:5732 Error SyntaxError: Unexpected token. */ +/* @@? 16:5734 Error SyntaxError: Invalid shorthand property initializer. */ +/* @@? 16:5740 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 16:5744 Error SyntaxError: Unexpected token '>>>'. */ +/* @@? 16:5751 Error SyntaxError: Unexpected token. */ +/* @@? 16:5759 Error SyntaxError: Unexpected token. */ +/* @@? 16:5760 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 479:1 Error SyntaxError: Unexpected token. */ +/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ diff --git a/ets2panda/test/ast/parser/ets/unexpected_token_62.ets b/ets2panda/test/ast/parser/ets/unexpected_token_62.ets index b5e6b422a8..e4a3e105d1 100644 --- a/ets2panda/test/ast/parser/ets/unexpected_token_62.ets +++ b/ets2panda/test/ast/parser/ets/unexpected_token_62.ets @@ -43,8 +43,8 @@ int = 10 /* @@? 23:1 Error SyntaxError: Unexpected token, expected an identifier. */ /* @@? 23:1 Error SyntaxError: Unexpected token, expected an identifier. */ /* @@? 24:1 Error SyntaxError: Unexpected token ')'. */ -/* @@? 24:2 Error TypeError: Unresolved reference void */ -/* @@? 24:7 Error SyntaxError: Unexpected token '{'. */ +/* @@? 24:2 Error SyntaxError: Unexpected token 'void'. */ +/* @@? 24:2 Error SyntaxError: Unexpected token 'void'. */ /* @@? 24:8 Error SyntaxError: Unexpected token, expected an identifier. */ /* @@? 24:8 Error TypeError: Unresolved reference nt */ /* @@? 24:16 Error SyntaxError: Unexpected token ','. */ @@ -55,23 +55,24 @@ int = 10 /* @@? 24:23 Error SyntaxError: Unexpected token 'A'. */ /* @@? 24:23 Error TypeError: Class name 'A' used in the wrong context */ /* @@? 24:25 Error SyntaxError: Unexpected token '{'. */ -/* @@? 25:1 Error TypeError: Unresolved reference int */ +/* @@? 25:1 Error SyntaxError: Unexpected token 'int'. */ +/* @@? 25:5 Error SyntaxError: Unexpected token '='. */ /* @@? 26:1 Error SyntaxError: Unexpected token ')'. */ /* @@? 26:3 Error SyntaxError: Unexpected token '=>'. */ /* @@? 26:3 Error SyntaxError: Unexpected token '=>'. */ /* @@? 26:13 Error SyntaxError: Unexpected token, expected an identifier. */ /* @@? 26:13 Error SyntaxError: Unexpected token, expected an identifier. */ /* @@? 26:13 Error TypeError: Cannot find type ''. */ -/* @@? 26:14 Error SyntaxError: Expected '=>', got '+'. */ /* @@? 26:14 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 26:14 Error SyntaxError: Expected '=>', got '+'. */ /* @@? 26:15 Error SyntaxError: Unexpected token ')'. */ /* @@? 26:15 Error SyntaxError: Unexpected token ')'. */ /* @@? 26:15 Error SyntaxError: Unexpected token ')'. */ /* @@? 26:15 Error SyntaxError: Unexpected token ')'. */ /* @@? 26:16 Error SyntaxError: Unexpected token ':'. */ /* @@? 26:16 Error SyntaxError: Unexpected token ':'. */ -/* @@? 26:18 Error TypeError: Bad operand type, the types of the operands must be numeric type. */ /* @@? 26:18 Error TypeError: The type of parameter 'A6' cannot be inferred */ +/* @@? 26:18 Error TypeError: Bad operand type, the types of the operands must be numeric type. */ /* @@? 26:25 Error TypeError: Unresolved reference reƒurn */ /* @@? 26:32 Error SyntaxError: Unexpected token '_ew'. */ /* @@? 26:32 Error TypeError: Unresolved reference _ew */ @@ -80,4 +81,4 @@ int = 10 /* @@? 26:36 Error TypeError: Type 'B' has no call signatures. */ /* @@? 26:40 Error SyntaxError: Unexpected token, expected ',' or ')'. */ /* @@? 27:2 Error TypeError: Unresolved reference ó */ -/* @@? 84:1 Error SyntaxError: Expected '}', got 'eos'. */ +/* @@? 85:1 Error SyntaxError: Expected '}', got 'eos'. */ diff --git a/ets2panda/test/test-lists/recheck/recheck-ignored.txt b/ets2panda/test/test-lists/recheck/recheck-ignored.txt index 2af8ec9339..b860b7bb00 100644 --- a/ets2panda/test/test-lists/recheck/recheck-ignored.txt +++ b/ets2panda/test/test-lists/recheck/recheck-ignored.txt @@ -2,6 +2,7 @@ # Negative tests that are ignored ast/parser/ets/import_tests/export_and_import_class.ets ast/parser/ets/import_tests/export_and_import_top_level.ets +ast/parser/ets/too_many_expression.ets compiler/ets/ConditionalExpressionCallVoidNeg.ets compiler/ets/abstractNewClassInstanceExpression.ets compiler/ets/dynamic_instanceof_error.ets diff --git a/ets2panda/util/diagnostic/fatal.yaml b/ets2panda/util/diagnostic/fatal.yaml index 0bc08c8af6..c8e64913cc 100644 --- a/ets2panda/util/diagnostic/fatal.yaml +++ b/ets2panda/util/diagnostic/fatal.yaml @@ -111,3 +111,7 @@ fatal: - name: MISSING_OUTPUT_FILE id: 25 message: "Output file path must be specified." + +- name: DEEP_NESTING + id: 26 + message: "Maximum allowed nesting level exceeded." diff --git a/ets2panda/util/recursiveGuard.h b/ets2panda/util/recursiveGuard.h new file mode 100644 index 0000000000..ad89f5a8e5 --- /dev/null +++ b/ets2panda/util/recursiveGuard.h @@ -0,0 +1,57 @@ +/** + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef RECURSIVE_GUARD_H +#define RECURSIVE_GUARD_H + +namespace ark::es2panda::parser { + +constexpr unsigned int MAX_RECURSION_DEPTH = 4096; + +struct RecursiveContext { + unsigned depth = 0; +}; + +class TrackRecursive { +public: + explicit TrackRecursive(RecursiveContext &recursivecontext) : recursivecontext_(recursivecontext) + { + ++recursivecontext_.depth; + valid_ = recursivecontext_.depth <= MAX_RECURSION_DEPTH; + }; + + ~TrackRecursive() + { + --recursivecontext_.depth; + } + + TrackRecursive(const TrackRecursive &) = delete; + TrackRecursive(TrackRecursive &&) = delete; + TrackRecursive &operator=(const TrackRecursive &) = delete; + TrackRecursive &operator=(TrackRecursive &&) = delete; + + explicit operator bool() const + { + return valid_; + } + +private: + RecursiveContext &recursivecontext_; + bool valid_ = true; +}; + +} // namespace ark::es2panda::parser + +#endif // UTIL_GUARD_H -- Gitee From 1481910b2426d4406f47566d441f320a26e19f82 Mon Sep 17 00:00:00 2001 From: dongchao Date: Sun, 27 Apr 2025 14:40:20 +0800 Subject: [PATCH 209/268] Fix some declgen scenes Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC9IYZ Signed-off-by: kanghonglin Signed-off-by: dongchao Change-Id: I101d37e08ae802cd8c4a89bda735fe84cb337094 --- ets2panda/declgen_ets2ts/declgenEts2Ts.cpp | 289 +++++++++++------- ets2panda/declgen_ets2ts/declgenEts2Ts.h | 9 +- .../declgen-ets2ts-runtime-ignored.txt | 24 +- 3 files changed, 195 insertions(+), 127 deletions(-) diff --git a/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp b/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp index a914a94096..6255e84e5c 100644 --- a/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp +++ b/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp @@ -106,32 +106,37 @@ void TSDeclGen::ProcessTypeAliasDependencies(const ir::TSTypeAliasDeclaration *t void TSDeclGen::ProcessTypeAnnotationDependencies(const ir::TypeNode *typeAnnotation) { - if (!typeAnnotation->IsETSTypeReference() || - !typeAnnotation->AsETSTypeReference()->Part()->Name()->IsIdentifier()) { - return; - } - - const auto part = typeAnnotation->AsETSTypeReference()->Part(); - const auto partParams = part->TypeParams(); - if (partParams == nullptr) { + if (typeAnnotation->IsETSTypeReference()) { + ProcessETSTypeReferenceDependencies(typeAnnotation->AsETSTypeReference()); return; + } else if (typeAnnotation->IsETSUnionType()) { + GenSeparated( + typeAnnotation->AsETSUnionType()->Types(), + [this](ir::TypeNode *arg) { ProcessTypeAnnotationDependencies(arg); }, ""); } +} - const auto typeParams = partParams->AsTSTypeParameterInstantiation(); - if (typeParams == nullptr) { +void TSDeclGen::ProcessETSTypeReferenceDependencies(const ir::ETSTypeReference *typeReference) +{ + const auto part = typeReference->Part(); + auto partName = part->GetIdent()->Name().Mutf8(); + if (part->TypeParams() != nullptr && part->TypeParams()->IsTSTypeParameterInstantiation()) { + indirectDependencyObjects_.insert(partName); + GenSeparated( + part->TypeParams()->Params(), [this](ir::TypeNode *param) { ProcessTypeAnnotationDependencies(param); }, + ""); return; + } else if (part->Name()->IsTSQualifiedName() && part->Name()->AsTSQualifiedName()->Name() != nullptr) { + const auto qualifiedName = part->Name()->AsTSQualifiedName()->Name().Mutf8(); + std::istringstream stream(qualifiedName.data()); + std::string firstSegment; + if (std::getline(stream, firstSegment, '.')) { + importSet_.insert(firstSegment); + indirectDependencyObjects_.insert(firstSegment); + } + } else { + indirectDependencyObjects_.insert(partName); } - - GenSeparated( - typeParams->Params(), - [this](ir::TypeNode *param) { - if (param->IsETSTypeReference() && param->AsETSTypeReference()->Part()->Name()->IsIdentifier()) { - const auto paramName = param->AsETSTypeReference()->Part()->Name()->AsIdentifier()->Name().Mutf8(); - importSet_.insert(paramName); - indirectDependencyObjects_.insert(paramName); - } - }, - ""); } void TSDeclGen::ProcessClassDependencies(const ir::ClassDeclaration *classDecl) @@ -163,21 +168,38 @@ void TSDeclGen::ProcessClassDependencies(const ir::ClassDeclaration *classDecl) ""); } - GenSeparated( - classDef->Body(), [this](ir::AstNode *prop) { ProcessClassPropDependencies(prop); }, ""); + ProcessClassPropDependencies(classDef); } -void TSDeclGen::ProcessClassPropDependencies(const ir::AstNode *prop) +void TSDeclGen::ProcessClassPropDependencies(const ir::ClassDefinition *classDef) { - if (prop->IsClassProperty() && prop->AsClassProperty()->Value() != nullptr) { - AddSuperType(prop->AsClassProperty()->Value()); - } else if (prop->IsMethodDefinition()) { - ProcessClassMethodDependencies(prop->AsMethodDefinition()); + for (const auto *prop : classDef->Body()) { + if (prop->IsClassProperty()) { + auto value = prop->AsClassProperty()->Value(); + if (value != nullptr && value->IsETSNewClassInstanceExpression() && + value->AsETSNewClassInstanceExpression()->GetTypeRef() != nullptr && + value->AsETSNewClassInstanceExpression()->GetTypeRef()->IsETSTypeReference()) { + auto typeReference = value->AsETSNewClassInstanceExpression()->GetTypeRef()->AsETSTypeReference(); + ProcessETSTypeReferenceDependencies(typeReference); + continue; + } + if (prop->AsClassProperty()->TypeAnnotation() != nullptr) { + ProcessTypeAnnotationDependencies(prop->AsClassProperty()->TypeAnnotation()); + continue; + } + } else if (prop->IsMethodDefinition()) { + ProcessClassMethodDependencies(prop->AsMethodDefinition()); + } else if (prop->IsClassDeclaration() && classDef->IsNamespaceTransformed()) { + ProcessClassDependencies(prop->AsClassDeclaration()); + } } } void TSDeclGen::ProcessClassMethodDependencies(const ir::MethodDefinition *methodDef) { + if (!methodDef->IsExported() && !methodDef->IsExportedType() && !methodDef->IsDefaultExported()) { + return; + } auto sig = methodDef->Function()->Signature(); GenSeparated( sig->Params(), [this](varbinder::LocalVariable *param) { AddSuperType(param->TsType()); }, ""); @@ -508,17 +530,32 @@ const checker::Signature *TSDeclGen::GetFuncSignature(const checker::ETSFunction return etsFunctionType->CallSignatures()[0]; } -void TSDeclGen::ProcessFuncParameter(varbinder::LocalVariable *param) +void TSDeclGen::ProcessParameterName(varbinder::LocalVariable *param) { - if (std::string(param->Name()).find("") != std::string::npos) { - return; - } + const auto *paramDeclNode = param->Declaration()->Node(); + const std::string prefix = "gensym%%_"; + if (!paramDefaultMap_.empty() && paramDefaultMap_.find(param->Name()) != paramDefaultMap_.end()) { OutDts(paramDefaultMap_[param->Name()]); paramDefaultMap_.erase(param->Name()); + } else if (param->Name().Is("=t")) { + OutDts("this"); + } else if (paramDeclNode->IsETSParameterExpression() && paramDeclNode->AsETSParameterExpression()->IsOptional() && + paramDeclNode->AsETSParameterExpression()->Name().StartsWith(prefix)) { + OutDts("arg", param->Name().Mutf8().substr(prefix.size())); } else { - OutDts(param->Name().Is("=t") ? "this" : param->Name()); + OutDts(param->Name()); + } +} + +void TSDeclGen::ProcessFuncParameter(varbinder::LocalVariable *param) +{ + if (std::string(param->Name()).find("") != std::string::npos) { + return; } + + ProcessParameterName(param); + const auto *paramType = param->TsType(); const auto *paramDeclNode = param->Declaration()->Node(); @@ -536,15 +573,15 @@ void TSDeclGen::ProcessFuncParameter(varbinder::LocalVariable *param) OutDts(": "); const auto *typeAnnotation = expr->TypeAnnotation(); - if (typeAnnotation == nullptr) { - GenType(paramType); - return; - } - if (expr->IsOptional()) { - GenType(typeAnnotation->TsType()); + if (typeAnnotation != nullptr) { + if (expr->IsOptional()) { + ProcessTypeAnnotationType(typeAnnotation); + return; + } + ProcessTypeAnnotationType(typeAnnotation, paramType); return; } - ProcessTypeAnnotationType(typeAnnotation, paramType); + OutDts("any"); } void TSDeclGen::ProcessFuncParameters(const checker::Signature *sig) @@ -609,13 +646,18 @@ void TSDeclGen::ProcessFunctionReturnType(const checker::Signature *sig) return; } - const auto param = sig->Function()->Params(); - if (!param.empty() && param.size() == 1 && param.at(0)->IsETSParameterExpression() && - param.at(0)->AsETSParameterExpression()->Ident()->TypeAnnotation() != nullptr && - sig->HasSignatureFlag(checker::SignatureFlags::SETTER)) { - ProcessTypeAnnotationType(param.at(0)->AsETSParameterExpression()->Ident()->TypeAnnotation(), - sig->Params()[0]->TsType()); - return; + if (sig->HasSignatureFlag(checker::SignatureFlags::SETTER)) { + const auto param = sig->Function()->Params(); + if (!param.empty() && param.size() == 1 && param.at(0)->IsETSParameterExpression() && + param.at(0)->AsETSParameterExpression()->Ident()->TypeAnnotation() != nullptr) { + ProcessTypeAnnotationType(param.at(0)->AsETSParameterExpression()->Ident()->TypeAnnotation(), + sig->Params()[0]->TsType()); + return; + } + if (!sig->Params().empty() && sig->Params().size() == 1) { + GenType(sig->Params()[0]->TsType()); + return; + } } GenType(sig->ReturnType()); } @@ -812,6 +854,9 @@ bool TSDeclGen::ShouldEmitDeclarationSymbol(const ir::Identifier *symbol) if (symbol->Parent()->IsExported() || symbol->Parent()->IsExportedType() || symbol->Parent()->IsDefaultExported()) { return true; } + if (state_.isDeclareNamespace) { + return true; + } if (indirectDependencyObjects_.find(symbol->Name().Mutf8()) != indirectDependencyObjects_.end()) { classNode_.isIndirect = true; return true; @@ -870,6 +915,9 @@ void TSDeclGen::GenAnnotations(const T *node) if (annotationList_.count(anno->GetBaseName()->Name().Mutf8()) == 0U) { return; } + if (!state_.inGlobalClass && (state_.inClass || state_.inInterface)) { + ProcessIndent(); + } OutDts("@", anno->GetBaseName()->Name()); GenAnnotationProperties(anno); OutEndlDts(); @@ -1084,12 +1132,30 @@ std::string TSDeclGen::ReplaceETSGLOBAL(const std::string &typeName) return globalDesc_; } +bool TSDeclGen::ProcessTSQualifiedName(const ir::ETSTypeReference *typeReference) +{ + if (typeReference->Part()->Name()->IsTSQualifiedName() && + typeReference->Part()->Name()->AsTSQualifiedName()->Name() != nullptr) { + const auto qualifiedName = typeReference->Part()->Name()->AsTSQualifiedName()->Name().Mutf8(); + std::istringstream stream(qualifiedName.data()); + std::string segment; + while (std::getline(stream, segment, '.')) { + importSet_.insert(segment); + indirectDependencyObjects_.insert(segment); + } + OutDts(qualifiedName); + return true; + } + return false; +} + void TSDeclGen::ProcessETSTypeReferenceType(const ir::ETSTypeReference *typeReference, const checker::Type *checkerType) { auto typePart = typeReference->Part(); auto partName = typePart->GetIdent()->Name().Mutf8(); importSet_.insert(partName); if (typePart->TypeParams() != nullptr && typePart->TypeParams()->IsTSTypeParameterInstantiation()) { + indirectDependencyObjects_.insert(partName); if (partName == "FixedArray") { GenSeparated(typePart->TypeParams()->Params(), [this](ir::TypeNode *param) { ProcessTypeAnnotationType(param, param->GetType(checker_)); }); @@ -1101,15 +1167,8 @@ void TSDeclGen::ProcessETSTypeReferenceType(const ir::ETSTypeReference *typeRefe GenSeparated(typePart->TypeParams()->Params(), [this](ir::TypeNode *param) { ProcessTypeAnnotationType(param, param->GetType(checker_)); }); OutDts(">"); - } else if (typePart->Name()->IsTSQualifiedName() && typePart->Name()->AsTSQualifiedName()->Name() != nullptr) { - const auto qualifiedName = typePart->Name()->AsTSQualifiedName()->Name().Mutf8(); - std::istringstream stream(qualifiedName.data()); - std::string segment; - while (std::getline(stream, segment, '.')) { - importSet_.insert(segment); - indirectDependencyObjects_.insert(segment); - } - OutDts(qualifiedName); + } else if (ProcessTSQualifiedName(typeReference)) { + return; } else if (checkerType != nullptr && checkerType->IsETSFunctionType()) { indirectDependencyObjects_.insert(partName); OutDts(partName); @@ -1127,6 +1186,7 @@ bool TSDeclGen::ProcessTypeAnnotationSpecificTypes(const checker::Type *checkerT } importSet_.insert(checkerType->ToString()); + indirectDependencyObjects_.insert(checkerType->ToString()); if (HandleBasicTypes(checkerType)) { return true; } @@ -1187,6 +1247,9 @@ void TSDeclGen::ProcessTypeAnnotationType(const ir::TypeNode *typeAnnotation, co void TSDeclGen::ProcessETSTypeReference(const ir::TypeNode *typeAnnotation, const checker::Type *checkerType) { + if (ProcessTSQualifiedName(typeAnnotation->AsETSTypeReference())) { + return; + } if (ProcessTypeAnnotationSpecificTypes(checkerType)) { return; } @@ -1237,6 +1300,11 @@ void TSDeclGen::GenTypeAliasDeclaration(const ir::TSTypeAliasDeclaration *typeAl if (!ShouldEmitDeclarationSymbol(typeAlias->Id())) { return; } + if (state_.inClass) { + auto indent = GetIndent(); + OutDts(indent); + OutTs(indent); + } GenAnnotations(typeAlias); if (classNode_.isIndirect || state_.inNamespace || typeAlias->IsDefaultExported()) { OutDts("type ", name); @@ -1295,7 +1363,6 @@ void TSDeclGen::GenEnumDeclaration(const ir::ClassProperty *enumMember) void TSDeclGen::GenInterfaceDeclaration(const ir::TSInterfaceDeclaration *interfaceDecl) { - state_.inInterface = true; const auto interfaceName = interfaceDecl->Id()->Name().Mutf8(); DebugPrint("GenInterfaceDeclaration: " + interfaceName); if (interfaceName.find("$partial") != std::string::npos) { @@ -1305,6 +1372,7 @@ void TSDeclGen::GenInterfaceDeclaration(const ir::TSInterfaceDeclaration *interf return; } GenAnnotations(interfaceDecl); + state_.inInterface = true; if (classNode_.isIndirect) { OutDts(state_.isInterfaceInNamespace ? "interface " : "declare interface ", interfaceName); } else if (!interfaceDecl->IsDefaultExported()) { @@ -1314,10 +1382,22 @@ void TSDeclGen::GenInterfaceDeclaration(const ir::TSInterfaceDeclaration *interf } GenTypeParameters(interfaceDecl->TypeParams()); + if (!interfaceDecl->Extends().empty()) { + OutDts(" extends "); + GenSeparated(interfaceDecl->Extends(), [this](ir::TSInterfaceHeritage *param) { + if (param->Expr()->IsETSTypeReference()) { + ProcessETSTypeReferenceType(param->Expr()->AsETSTypeReference()); + } + }); + } OutDts(" {"); OutEndlDts(); ProcessInterfaceBody(interfaceDecl->Body()); + if (state_.isInterfaceInNamespace) { + classNode_.indentLevel--; + OutDts(GetIndent()); + } OutDts("}"); OutEndlDts(); } @@ -1343,8 +1423,8 @@ void TSDeclGen::ProcessMethodDefinition(const ir::MethodDefinition *methodDef, } if (methodDef->IsGetter() || methodDef->IsSetter()) { GenMethodDeclaration(methodDef); + processedMethods.insert(methodName); } - processedMethods.insert(methodName); if (!methodDef->Overloads().empty()) { for (const auto *overloadMethd : methodDef->Overloads()) { if (overloadMethd->IsGetter() || overloadMethd->IsSetter()) { @@ -1355,6 +1435,7 @@ void TSDeclGen::ProcessMethodDefinition(const ir::MethodDefinition *methodDef, } if (!methodDef->IsGetter() && !methodDef->IsSetter()) { GenMethodDeclaration(methodDef); + processedMethods.insert(methodName); } } @@ -1367,6 +1448,7 @@ void TSDeclGen::PrepareClassDeclaration(const ir::ClassDefinition *classDef) if (classDef->IsNamespaceTransformed()) { state_.inNamespace = true; state_.isClassInNamespace = false; + state_.isDeclareNamespace = classDef->IsDeclare(); } else { state_.isClassInNamespace = true; } @@ -1380,40 +1462,32 @@ bool TSDeclGen::ShouldSkipClassDeclaration(const std::string_view &className) co className == compiler::Signatures::JSCALL_CLASS || (className.find("$partial") != std::string::npos); } +void TSDeclGen::EmitDeclarationPrefix(const ir::ClassDefinition *classDef, const std::string &typeName, + const std::string_view &className) +{ + if (classDef->IsDefaultExported()) { + OutDts(classNode_.indentLevel > 1 ? typeName : "declare " + typeName, className); + } else if (classDef->IsExported() || declgenOptions_.exportAll) { + OutDts(classNode_.indentLevel > 1 ? typeName : "export declare " + typeName, className); + } else { + OutDts(classNode_.indentLevel > 1 ? typeName : "declare " + typeName, className); + } +} + void TSDeclGen::EmitClassDeclaration(const ir::ClassDefinition *classDef, const std::string_view &className) { if (classDef->IsNamespaceTransformed()) { - if (classDef->IsDefaultExported()) { - OutDts("declare namespace ", className); - } else { - OutDts(classNode_.indentLevel > 1 ? "namespace " : "export declare namespace ", className); - } + EmitDeclarationPrefix(classDef, "namespace ", className); OutTs("export namespace ", className, " {"); } else if (classDef->IsEnumTransformed()) { - if (classDef->IsDefaultExported()) { - OutDts("declare enum ", className); - } else { - OutDts(classNode_.indentLevel > 1 ? "enum " : "export declare enum ", className); - } + EmitDeclarationPrefix(classDef, "enum ", className); OutTs("export const enum ", className, " {"); } else if (classDef->IsFromStruct()) { - if (classDef->IsDefaultExported()) { - OutDts("declare struct ", className); - } else { - OutDts(classNode_.indentLevel > 1 ? "struct " : "export declare struct ", className); - } - } else if (classNode_.isIndirect) { - OutDts("declare class ", className); + EmitDeclarationPrefix(classDef, "struct ", className); } else if (classDef->IsAbstract()) { - if (classDef->IsDefaultExported()) { - OutDts("export default abstract class ", className); - } else { - OutDts("export declare abstract class ", className); - } - } else if (classDef->IsDefaultExported()) { - OutDts("export default class ", className); + EmitDeclarationPrefix(classDef, "abstract class ", className); } else { - OutDts(classNode_.indentLevel > 1 ? "class " : "export declare class ", className); + EmitDeclarationPrefix(classDef, "class ", className); } OutEndlTs(); } @@ -1442,7 +1516,9 @@ void TSDeclGen::GenPartName(std::string &partName) void TSDeclGen::ProcessIndent() { - if (classNode_.hasNestedClass || state_.inNamespace || state_.inEnum) { + if (state_.isInterfaceInNamespace) { + OutDts(GetIndent()); + } else if (classNode_.hasNestedClass || state_.inNamespace || state_.inEnum) { auto indent = GetIndent(); OutDts(indent); OutTs(indent); @@ -1453,10 +1529,15 @@ void TSDeclGen::ProcessIndent() void TSDeclGen::HandleClassDeclarationTypeInfo(const ir::ClassDefinition *classDef, const std::string_view &className) { - if (!ShouldEmitDeclarationSymbol(classDef->Ident())) { - return; + if (classNode_.hasNestedClass) { + classNode_.indentLevel--; + ES2PANDA_ASSERT(classNode_.indentLevel != static_cast(-1)); } GenAnnotations(classDef); + if (classNode_.hasNestedClass) { + OutDts(GetIndent()); + classNode_.indentLevel++; + } EmitClassDeclaration(classDef, className); GenTypeParameters(classDef->TypeParams()); @@ -1524,6 +1605,7 @@ void TSDeclGen::ProcessMethodsFromInterfaces(const std::unordered_set processedMethods; for (const auto *prop : classDef->Body()) { if (classDef->IsEnumTransformed()) { @@ -1534,11 +1616,11 @@ void TSDeclGen::ProcessClassBody(const ir::ClassDefinition *classDef) } else if (prop->IsTSInterfaceDeclaration()) { state_.isInterfaceInNamespace = true; OutDts(GetIndent()); + classNode_.indentLevel++; GenInterfaceDeclaration(prop->AsTSInterfaceDeclaration()); + state_.inInterface = false; state_.isInterfaceInNamespace = false; } else if (prop->IsTSTypeAliasDeclaration()) { - OutDts(GetIndent()); - OutTs(GetIndent()); GenTypeAliasDeclaration(prop->AsTSTypeAliasDeclaration()); } else if (prop->IsMethodDefinition()) { ProcessMethodDefinition(prop->AsMethodDefinition(), processedMethods); @@ -1551,9 +1633,7 @@ void TSDeclGen::ProcessClassBody(const ir::ClassDefinition *classDef) GenPropDeclaration(classProp); } else if (prop->IsClassDeclaration() && classDef->IsNamespaceTransformed()) { classNode_.hasNestedClass = true; - auto indent = GetIndent(); - OutDts(indent); - OutTs(indent); + OutTs(GetIndent()); classNode_.indentLevel++; GenClassDeclaration(prop->AsClassDeclaration()); state_.isClassInNamespace = false; @@ -1611,8 +1691,7 @@ void TSDeclGen::GenClassDeclaration(const ir::ClassDeclaration *classDecl) CloseClassBlock(false); } } - if ((classDef->IsNamespaceTransformed() || classDef->IsEnumTransformed() || classDef->IsFromStruct()) && - classDef->IsDefaultExported()) { + if (classDef->IsDefaultExported()) { OutDts("export default ", className, ";"); OutEndlDts(); } @@ -1677,6 +1756,11 @@ void TSDeclGen::GenMethodDeclaration(const ir::MethodDefinition *methodDef) OutDts(";"); OutEndlDts(); + + if (methodDef->IsDefaultExported()) { + OutDts("export default ", methodName, ";"); + OutEndlDts(); + } } bool TSDeclGen::GenMethodDeclarationPrefix(const ir::MethodDefinition *methodDef, const ir::Identifier *methodIdent, @@ -1687,13 +1771,16 @@ bool TSDeclGen::GenMethodDeclarationPrefix(const ir::MethodDefinition *methodDef return true; } if (methodDef->IsDefaultExported()) { - OutDts("export default function "); + OutDts("declare function "); } else { OutDts("export declare function "); } } else { + if (state_.inNamespace && !state_.isClassInNamespace && !state_.isInterfaceInNamespace && + !ShouldEmitDeclarationSymbol(methodIdent) && !methodDef->IsConstructor()) { + return true; + } if (!methodDef->Function()->Annotations().empty()) { - ProcessIndent(); GenAnnotations(methodDef->Function()); } ProcessIndent(); @@ -1727,11 +1814,7 @@ void TSDeclGen::GenMethodSignature(const ir::MethodDefinition *methodDef, const OutDts(")"); } else { DebugPrint(" GenMethodDeclaration: " + methodName); - if (methodName.find("$_iterator") != std::string::npos) { - OutDts("[Symbol.iterator]"); - } else { - OutDts(methodName); - } + OutDts(methodName); if (methodDef->TsType() == nullptr) { LogWarning(diagnostic::UNTYPED_METHOD, {methodName}, methodIdent->Start()); @@ -1812,18 +1895,16 @@ void TSDeclGen::GenPropDeclaration(const ir::ClassProperty *classProp) void TSDeclGen::ProcessClassPropDeclaration(const ir::ClassProperty *classProp) { - ProcessIndent(); if (!state_.inInterface && (!state_.inNamespace || state_.isClassInNamespace) && !classNode_.isStruct) { GenPropAccessor(classProp, "get "); if (!classProp->IsReadonly()) { - ProcessIndent(); GenPropAccessor(classProp, "set "); } } else { if (!classProp->Annotations().empty()) { GenAnnotations(classProp); - ProcessIndent(); } + ProcessIndent(); if (!classNode_.isStruct) { GenModifier(classProp, true); } @@ -1847,8 +1928,8 @@ void TSDeclGen::GenPropAccessor(const ir::ClassProperty *classProp, const std::s } if (!classProp->Annotations().empty()) { GenAnnotations(classProp); - ProcessIndent(); } + ProcessIndent(); GenModifier(classProp); const auto propName = GetKeyIdent(classProp->Key())->Name().Mutf8(); diff --git a/ets2panda/declgen_ets2ts/declgenEts2Ts.h b/ets2panda/declgen_ets2ts/declgenEts2Ts.h index b56b8a933c..72ea50e805 100644 --- a/ets2panda/declgen_ets2ts/declgenEts2Ts.h +++ b/ets2panda/declgen_ets2ts/declgenEts2Ts.h @@ -97,6 +97,7 @@ private: void GenType(const checker::Type *checkerType); void GenFunctionType(const checker::ETSFunctionType *functionType, const ir::MethodDefinition *methodDef = nullptr); void ProcessFunctionReturnType(const checker::Signature *sig); + bool ProcessTSQualifiedName(const ir::ETSTypeReference *typeReference); void ProcessETSTypeReferenceType(const ir::ETSTypeReference *typeReference, const checker::Type *checkerType = nullptr); bool ProcessTypeAnnotationSpecificTypes(const checker::Type *checkerType); @@ -160,6 +161,7 @@ private: void HandleClassInherit(const ir::Expression *expr); void ProcessClassBody(const ir::ClassDefinition *classDef); void ProcessParamDefaultToMap(const ir::Statement *stmt); + void ProcessParameterName(varbinder::LocalVariable *param); void ProcessFuncParameter(varbinder::LocalVariable *param); void ProcessFuncParameters(const checker::Signature *sig); void ProcessClassPropertyType(const ir::ClassProperty *classProp); @@ -175,8 +177,9 @@ private: void ProcessTypeAliasDependencies(const ir::TSTypeAliasDeclaration *typeAliasDecl); void ProcessTypeAnnotationDependencies(const ir::TypeNode *typeAnnotation); void ProcessClassDependencies(const ir::ClassDeclaration *classDecl); - void ProcessClassPropDependencies(const ir::AstNode *prop); + void ProcessClassPropDependencies(const ir::ClassDefinition *classDef); void ProcessClassMethodDependencies(const ir::MethodDefinition *methodDef); + void ProcessETSTypeReferenceDependencies(const ir::ETSTypeReference *typeReference); void AddSuperType(const ir::Expression *super); void AddSuperType(const checker::Type *tsType); void ProcessInterfacesDependencies(const ArenaVector &interfaces); @@ -184,6 +187,8 @@ private: void GenDeclarations(); void CloseClassBlock(const bool isDts); + void EmitDeclarationPrefix(const ir::ClassDefinition *classDef, const std::string &typeName, + const std::string_view &className); void EmitClassDeclaration(const ir::ClassDefinition *classDef, const std::string_view &className); void EmitClassGlueCode(const ir::ClassDefinition *classDef, const std::string &className); void EmitMethodGlueCode(const std::string &methodName, const ir::Identifier *methodIdentifier); @@ -247,10 +252,12 @@ private: const ir::Expression *super {nullptr}; bool inInterface {false}; bool inGlobalClass {false}; + bool inClass {false}; bool inNamespace {false}; bool inEnum {false}; bool isClassInNamespace {false}; bool isInterfaceInNamespace {false}; + bool isDeclareNamespace {false}; std::string currentClassDescriptor {}; std::stack inUnionBodyStack {}; std::string currentTypeAliasName; diff --git a/ets2panda/test/test-lists/declgenets2ts/ets-runtime/declgen-ets2ts-runtime-ignored.txt b/ets2panda/test/test-lists/declgenets2ts/ets-runtime/declgen-ets2ts-runtime-ignored.txt index c2369f6c00..ada93aefcf 100644 --- a/ets2panda/test/test-lists/declgenets2ts/ets-runtime/declgen-ets2ts-runtime-ignored.txt +++ b/ets2panda/test/test-lists/declgenets2ts/ets-runtime/declgen-ets2ts-runtime-ignored.txt @@ -7,38 +7,18 @@ funcRefWithRestArguments.ets struct-identifier.ets struct-init2.ets type_param_in_union.ets -#FailKind.TSC_FAIL - 34 tests: +#FailKind.TSC_FAIL - 14 tests: ClassNewInstance.ets Enum7.ets GenericBridges_01.ets GenericBridges_02.ets -InterfacePrivateMethod.ets +InterfaceWithDefaultFunction1.ets RecordKeyTypeCheck.ets -classGetterSetter.ets -class_implements_interface.ets function_type_with_receiver/validReturnThisOfExtensionFunction.ets generic_constraint_implicit.ets generics_1.ets -getteSetterImplementation.ets -getterSetterImplementationWithConstructor.ets -implementClassPropertyFunctionOptionCall.ets -implementsClassPropertyFunctionType.ets -implementsClassPropertyFunctionType2.ets -implementsClassPropertyUnionType1.ets -implementsClassPropertyUnionType2.ets -import_self_head_tests/A/test.ets -inherited_getter_setter_implementation_1.ets -inherited_getter_setter_implementation_2.ets -interfacePropertyTypeAnnotationWithParameter.ets -interface_prop.ets -interface_with_optional_property_cycle_import/class_file.ets lambda_with_receiver/lambda_with_receiver_generics_return_this_rotate.ets lambda_with_receiver/lambda_with_receiver_return_this3.ets lambda_with_receiver/lambda_with_receiver_trailing_in_function_return_this_rotate.ets -multiple_inheritance.ets -multiple_inheritance_2.ets -override_for_partial_02.ets -readonly_simple_form_pos.ets -simple_form_pos.ets static-invoke.ets top_level_03.ets -- Gitee From 2b76c5f1313924b6ce372df62b8da88ab0afd1ad Mon Sep 17 00:00:00 2001 From: fanglou Date: Fri, 23 May 2025 09:59:46 +0800 Subject: [PATCH 210/268] fix pandasdk Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICA065 Signed-off-by: fanglou Change-Id: I755aba76d03b6703e53ac75c504f1d9e2fa9e790 --- .../linter/scripts/install-ohos-typescript-and-homecheck.mjs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ets2panda/linter/scripts/install-ohos-typescript-and-homecheck.mjs b/ets2panda/linter/scripts/install-ohos-typescript-and-homecheck.mjs index 0852d74006..912c5c599a 100644 --- a/ets2panda/linter/scripts/install-ohos-typescript-and-homecheck.mjs +++ b/ets2panda/linter/scripts/install-ohos-typescript-and-homecheck.mjs @@ -86,14 +86,14 @@ function getTypescript(detectedOS) { fs.mkdirSync(third_party); } - let branch = process.env.TYPESCRIPT_BRANCH ?? 'master' + let branch = process.env.TYPESCRIPT_BRANCH ?? 'OpenHarmony_feature_20250328' if (detectedOS === 'Linux') { let timeToWait = 5000 const iterations = 4 if (!fs.existsSync(typescript_dir)) { for (let i = 0; i <= iterations; i++) { - shell.exec(`git clone --depth=1 https://gitee.com/openharmony/third_party_typescript.git ${typescript_dir}`, { stdio: 'ignore', fatal: true } ) + shell.exec(`git clone --depth=1 https://gitee.com/openharmony/third_party_typescript.git -b ${branch} ${typescript_dir}`, { stdio: 'ignore', fatal: true } ) if (fs.existsSync(typescript_dir) || i === iterations) { break; } -- Gitee From 65e8c3a98bac62b6937d39326c3dc34cb440e81e Mon Sep 17 00:00:00 2001 From: ElevenDuan Date: Wed, 21 May 2025 23:05:42 +0800 Subject: [PATCH 211/268] Fix ldlexvar from lexical env failed Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC9IXX?from=project-issue Change-Id: I04bb6569ad78978fc23cb37d5ab5be74414dfd97 Signed-off-by: ElevenDuan --- es2panda/compiler/core/dynamicContext.cpp | 14 +- es2panda/compiler/core/dynamicContext.h | 6 + es2panda/compiler/core/pandagen.cpp | 9 + .../constructor-try-catch-expected.txt | 162 ++++++++++++++++++ .../js/lexicalEnv/constructor-try-catch.js | 38 ++++ ...r-try-catch-nosuper-exception-expected.txt | 10 ++ ...constructor-try-catch-nosuper-exception.js | 36 ++++ .../constructor-try-catch-super-expected.txt | 0 .../classEnv/constructor-try-catch-super.js | 36 ++++ 9 files changed, 310 insertions(+), 1 deletion(-) create mode 100644 es2panda/test/bytecode/js/lexicalEnv/constructor-try-catch-expected.txt create mode 100644 es2panda/test/bytecode/js/lexicalEnv/constructor-try-catch.js create mode 100644 es2panda/test/compiler/js/lexicalEnv/classEnv/constructor-try-catch-nosuper-exception-expected.txt create mode 100644 es2panda/test/compiler/js/lexicalEnv/classEnv/constructor-try-catch-nosuper-exception.js create mode 100644 es2panda/test/compiler/js/lexicalEnv/classEnv/constructor-try-catch-super-expected.txt create mode 100644 es2panda/test/compiler/js/lexicalEnv/classEnv/constructor-try-catch-super.js diff --git a/es2panda/compiler/core/dynamicContext.cpp b/es2panda/compiler/core/dynamicContext.cpp index a6e2c3d60f..5949319bc4 100644 --- a/es2panda/compiler/core/dynamicContext.cpp +++ b/es2panda/compiler/core/dynamicContext.cpp @@ -95,6 +95,17 @@ bool LexEnvContext::HasTryCatch() const return envScope_->HasEnv(); } +void LexEnvContext::HandleForUpdateDirectReturnContext() +{ + if (!envScope_->HasEnv()) { + return; + } + const auto *node = envScope_->Scope()->Node(); + if (node->IsForUpdateStatement()) { + pg_->PopLexEnv(node); + } +} + void LexEnvContext::AbortContext([[maybe_unused]] ControlFlowChange cfc, const util::StringView &targetLabel) { @@ -105,7 +116,8 @@ void LexEnvContext::AbortContext([[maybe_unused]] ControlFlowChange cfc, const auto *node = envScope_->Scope()->Node(); // Process the continue label in the ForUpdate Statement. if (node->IsForUpdateStatement()) { - if (targetLabel == LabelTarget::CONTINUE_LABEL || targetLabel == LabelTarget::BREAK_LABEL) { + if (targetLabel == LabelTarget::CONTINUE_LABEL || targetLabel == LabelTarget::BREAK_LABEL || + targetLabel == LabelTarget::RETURN_LABEL) { return; } diff --git a/es2panda/compiler/core/dynamicContext.h b/es2panda/compiler/core/dynamicContext.h index 3fa63347fd..3ab8647bc2 100644 --- a/es2panda/compiler/core/dynamicContext.h +++ b/es2panda/compiler/core/dynamicContext.h @@ -125,6 +125,12 @@ public: { return tryEndFlag; } + /** + * Handle for update direct return context + * If the lexical environment context is in for update statement, pop the lexical environment + */ + void HandleForUpdateDirectReturnContext(); + private: VariableEnvScope *envScope_; CatchTable *catchTable_ {}; diff --git a/es2panda/compiler/core/pandagen.cpp b/es2panda/compiler/core/pandagen.cpp index 72071c9af2..f2bb23e699 100644 --- a/es2panda/compiler/core/pandagen.cpp +++ b/es2panda/compiler/core/pandagen.cpp @@ -1268,6 +1268,15 @@ void PandaGen::ValidateClassDirectReturn(const ir::AstNode *node) BranchIfStrictNotUndefined(node, notUndefined); GetThis(func); ThrowIfSuperNotCorrectCall(func, 0); + + auto *iter = dynamicContext_; + while (iter) { + if (iter->Type() == DynamicContextType::LEX_ENV) { + auto *envContext = static_cast(iter); + envContext->HandleForUpdateDirectReturnContext(); + } + iter = iter->Prev(); + } Branch(node, condEnd); SetLabel(node, notUndefined); diff --git a/es2panda/test/bytecode/js/lexicalEnv/constructor-try-catch-expected.txt b/es2panda/test/bytecode/js/lexicalEnv/constructor-try-catch-expected.txt new file mode 100644 index 0000000000..dfa8103e1b --- /dev/null +++ b/es2panda/test/bytecode/js/lexicalEnv/constructor-try-catch-expected.txt @@ -0,0 +1,162 @@ +slotNum = 0x0 +.language ECMAScript +.function any .#~@0=#C34(any a0, any a1, any a2) { +label_1: +label_0: + lda a2 + return +label_2: +} + +slotNum = 0xb +.language ECMAScript +.function any .#~@1=#C35(any a0, any a1, any a2, any a3, any a4, any a5) { + nop +label_17: +label_0: + newlexenv 0x1 +label_11: +label_13: + ldai 0x19 + sta v1 + ldai 0x7 + sta v2 +label_7: + lda v1 + less 0x0, v2 + jeqz label_8 +label_9: +label_2: + definefunc 0x1, .#~@1=@1*#f43, 0x0 + stlexvar 0x0, 0x0 + definefunc 0x2, .#~@1=@1*#f46, 0x2 + ldundefined + sta v3 + ldundefined + stricteq 0x3, v3 + jeqz label_5 +label_4: + lda a2 + throw.ifsupernotcorrectcall 0x0 + poplexenv + mov v3, a2 +label_5: + lda v3 + return +label_10: +end_label_10: +label_19: +label_15: + lda.str 123 + sta v3 + tryldglobalbyname 0x4, print + callarg1 0x5, v3 + ldlexvar 0x0, 0x0 + sta v3 + poplexenv + newlexenv 0x1 + lda v3 + stlexvar 0x0, 0x0 + lda v2 + tonumeric 0x7 + inc 0x8 + sta v2 +label_12: +end_label_12: + jmp label_7 +label_20: + sta v0 +label_16: + poplexenv + lda v0 + throw +label_8: + poplexenv + ldundefined + sta v0 + mov v4, v0 + supercallthisrange 0x9, 0x0, v4 + sta v0 + lda a2 + throw.ifsupernotcorrectcall 0x1 + lda v0 + throw.ifsupernotcorrectcall 0x0 + lda v0 + return +label_18: +} + +.catchall label_9, end_label_10, label_19 + +.catchall label_11, end_label_12, label_20 + +slotNum = 0x0 +.language ECMAScript +.function any .#~@1=@1*#f43(any a0, any a1, any a2) { +label_1: +label_0: + ldlexvar 0x0, 0x0 + return +label_2: +} + +slotNum = 0x0 +.language ECMAScript +.function any .#~@1=@1*#f46(any a0, any a1, any a2, any a3, any a4) { +label_1: +label_0: + ldlexvar 0x1, 0x0 + sta v0 + throw.undefinedifholewithname C35 + lda v0 + return +label_2: +} + +slotNum = 0xc +.language ECMAScript +.function any .func_main_0(any a0, any a1, any a2) { + nop +label_7: +label_0: + ldhole + sta v0 + defineclasswithbuffer 0x0, .#~@0=#C34, _1, 0x0, v0 + sta v0 + ldobjbyname 0x1, prototype + lda v0 + sttoglobalrecord 0x3, C34 + newlexenv 0x1 +label_2: +label_4: + tryldglobalbyname 0x4, C34 + sta v1 + defineclasswithbuffer 0x5, .#~@1=#C35, _2, 0x3, v1 + sta v1 + stlexvar 0x0, 0x0 + lda v1 + ldobjbyname 0x6, prototype +label_3: +end_label_3: + jmp label_1 +label_9: + sta v0 +label_6: + poplexenv + lda v0 + throw +label_1: + poplexenv + lda v1 + sttoglobalrecord 0x8, C35 + tryldglobalbyname 0x9, C35 + sta v0 + mov v2, v0 + newobjrange 0xa, 0x1, v2 + returnundefined +label_8: +} + +.catchall label_2, end_label_3, label_9 + + diff --git a/es2panda/test/bytecode/js/lexicalEnv/constructor-try-catch.js b/es2panda/test/bytecode/js/lexicalEnv/constructor-try-catch.js new file mode 100644 index 0000000000..f3a1fc3929 --- /dev/null +++ b/es2panda/test/bytecode/js/lexicalEnv/constructor-try-catch.js @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class C34 {} +class C35 extends C34 { + constructor(a37, a38 , a39) { + for (let v40 = 7; v40 < 25; v40++) { + try { + let v42; + return v42; + function f43() { + return f43; + } + function f46(a47, a48) { + return C35; + } + } catch (e52) { + let x = '123'; + print(x); + } + } + super(); + } +} + +new C35(); diff --git a/es2panda/test/compiler/js/lexicalEnv/classEnv/constructor-try-catch-nosuper-exception-expected.txt b/es2panda/test/compiler/js/lexicalEnv/classEnv/constructor-try-catch-nosuper-exception-expected.txt new file mode 100644 index 0000000000..5ab2536e66 --- /dev/null +++ b/es2panda/test/compiler/js/lexicalEnv/classEnv/constructor-try-catch-nosuper-exception-expected.txt @@ -0,0 +1,10 @@ +ReferenceError: undefinedsub-class must call super before use 'this' +ReferenceError: undefinedsub-class must call super before use 'this' +ReferenceError: undefinedsub-class must call super before use 'this' +ReferenceError: undefinedsub-class must call super before use 'this' +ReferenceError: undefinedsub-class must call super before use 'this' +ReferenceError: undefinedsub-class must call super before use 'this' +ReferenceError: undefinedsub-class must call super before use 'this' +ReferenceError: undefinedsub-class must call super before use 'this' +ReferenceError: undefinedsub-class must call super before use 'this' +ReferenceError: undefinedsub-class must call super before use 'this' diff --git a/es2panda/test/compiler/js/lexicalEnv/classEnv/constructor-try-catch-nosuper-exception.js b/es2panda/test/compiler/js/lexicalEnv/classEnv/constructor-try-catch-nosuper-exception.js new file mode 100644 index 0000000000..75672f2a6b --- /dev/null +++ b/es2panda/test/compiler/js/lexicalEnv/classEnv/constructor-try-catch-nosuper-exception.js @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class C34 {} +class C35 extends C34 { + constructor(a37, a38 , a39) { + for (let v40 = 0; v40 < 10; v40++) { + try { + let v42; + return v42; + function f43() { + return f43; + } + function f46(a47, a48) { + return C35; + } + } catch (e52) { + print(e52); + } + } + super(); + } +} +new C35(); \ No newline at end of file diff --git a/es2panda/test/compiler/js/lexicalEnv/classEnv/constructor-try-catch-super-expected.txt b/es2panda/test/compiler/js/lexicalEnv/classEnv/constructor-try-catch-super-expected.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/es2panda/test/compiler/js/lexicalEnv/classEnv/constructor-try-catch-super.js b/es2panda/test/compiler/js/lexicalEnv/classEnv/constructor-try-catch-super.js new file mode 100644 index 0000000000..d9f1492444 --- /dev/null +++ b/es2panda/test/compiler/js/lexicalEnv/classEnv/constructor-try-catch-super.js @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class C34 {} +class C35 extends C34 { + constructor(a37, a38 , a39) { + super(); + for (let v40 = 0; v40 < 10; v40++) { + try { + let v42; + return v42; + function f43() { + return f43; + } + function f46(a47, a48) { + return C35; + } + } catch (e52) { + print(e52); + } + } + } +} +new C35(); -- Gitee From c6a358078625841ba98799f06b7a8daab4a8dda3 Mon Sep 17 00:00:00 2001 From: fanglou Date: Sun, 25 May 2025 17:12:28 +0800 Subject: [PATCH 212/268] 0328 to 0411 Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICACDY Signed-off-by: fanglou Change-Id: I0a75936badc7602e31fb56dd50eac05162258a0b --- ets2panda/linter/.prettierignore | 4 +- ets2panda/linter/BUILD.gn | 12 +- ets2panda/linter/arkanalyzer/.prettierrc | 5 +- ets2panda/linter/arkanalyzer/README.en.md | 96 + ets2panda/linter/arkanalyzer/README.md | 107 + .../arkanalyzer/config/arkanalyzer.json | 7 +- ets2panda/linter/arkanalyzer/package.json | 14 +- .../typescriptCollectionDefinitionCopy.ts | 2 +- ets2panda/linter/arkanalyzer/src/Config.ts | 60 +- ets2panda/linter/arkanalyzer/src/Scene.ts | 203 +- ets2panda/linter/arkanalyzer/src/VFG/DVFG.ts | 17 +- .../src/VFG/builder/DVFGBuilder.ts | 52 +- .../callgraph/algorithm/AbstractAnalysis.ts | 74 +- .../algorithm/ClassHierarchyAnalysis.ts | 27 +- .../callgraph/algorithm/RapidTypeAnalysis.ts | 42 +- .../src/callgraph/common/Statistics.ts | 95 +- .../src/callgraph/model/CallGraph.ts | 54 +- .../model/builder/CallGraphBuilder.ts | 24 +- .../src/callgraph/pointerAnalysis/Context.ts | 26 +- .../pointerAnalysis/DummyCallCreator.ts | 11 +- .../src/callgraph/pointerAnalysis/PTAUtils.ts | 52 +- .../src/callgraph/pointerAnalysis/Pag.ts | 312 +- .../callgraph/pointerAnalysis/PagBuilder.ts | 1083 ++- .../pointerAnalysis/PointerAnalysis.ts | 61 +- .../pointerAnalysis/PointerAnalysisConfig.ts | 39 +- .../src/callgraph/pointerAnalysis/PtsDS.ts | 29 +- .../arkanalyzer/src/core/base/Constant.ts | 4 +- .../arkanalyzer/src/core/base/Decorator.ts | 2 +- .../arkanalyzer/src/core/base/DefUseChain.ts | 20 +- .../linter/arkanalyzer/src/core/base/Expr.ts | 26 +- .../linter/arkanalyzer/src/core/base/Local.ts | 28 +- .../arkanalyzer/src/core/base/Position.ts | 9 +- .../linter/arkanalyzer/src/core/base/Ref.ts | 13 +- .../linter/arkanalyzer/src/core/base/Stmt.ts | 26 +- .../linter/arkanalyzer/src/core/base/Trap.ts | 4 +- .../linter/arkanalyzer/src/core/base/Type.ts | 46 +- .../arkanalyzer/src/core/base/TypeExpr.ts | 2 +- .../linter/arkanalyzer/src/core/base/Value.ts | 12 +- .../arkanalyzer/src/core/common/ArkError.ts | 2 +- .../src/core/common/ArkIRTransformer.ts | 225 +- .../src/core/common/ArkValueTransformer.ts | 846 +- .../arkanalyzer/src/core/common/Builtin.ts | 6 +- .../arkanalyzer/src/core/common/Const.ts | 2 +- .../src/core/common/DummyMainCreater.ts | 58 +- .../arkanalyzer/src/core/common/EtsConst.ts | 18 +- .../src/core/common/ExprUseReplacer.ts | 8 +- .../src/core/common/IRInference.ts | 127 +- .../arkanalyzer/src/core/common/IRUtils.ts | 36 +- .../arkanalyzer/src/core/common/ModelUtils.ts | 126 +- .../src/core/common/RefUseReplacer.ts | 6 +- .../arkanalyzer/src/core/common/SdkUtils.ts | 65 +- .../src/core/common/StmtDefReplacer.ts | 5 +- .../src/core/common/StmtUseReplacer.ts | 8 +- .../arkanalyzer/src/core/common/TSConst.ts | 3 +- .../src/core/common/TypeInference.ts | 123 +- .../arkanalyzer/src/core/common/ValueUtil.ts | 14 +- .../src/core/common/VisibleValue.ts | 18 +- .../src/core/dataflow/DataflowProblem.ts | 25 +- .../src/core/dataflow/DataflowResult.ts | 4 +- .../src/core/dataflow/DataflowSolver.ts | 44 +- .../arkanalyzer/src/core/dataflow/Edge.ts | 18 +- .../arkanalyzer/src/core/dataflow/Fact.ts | 6 +- .../src/core/dataflow/GenericDataFlow.ts | 18 +- .../src/core/dataflow/ReachingDef.ts | 26 +- .../src/core/dataflow/UndefinedVariable.ts | 62 +- .../arkanalyzer/src/core/dataflow/Util.ts | 24 +- .../src/core/graph/BaseExplicitGraph.ts | 4 +- .../src/core/graph/BaseImplicitGraph.ts | 3 +- .../arkanalyzer/src/core/graph/BasicBlock.ts | 24 +- .../linter/arkanalyzer/src/core/graph/Cfg.ts | 22 +- .../src/core/graph/DependsGraph.ts | 8 +- .../src/core/graph/DominanceFinder.ts | 11 +- .../src/core/graph/DominanceTree.ts | 2 +- .../arkanalyzer/src/core/graph/GraphTraits.ts | 4 +- .../linter/arkanalyzer/src/core/graph/Scc.ts | 6 +- .../arkanalyzer/src/core/graph/ViewTree.ts | 34 +- .../src/core/graph/builder/CfgBuilder.ts | 147 +- .../core/graph/builder/ConditionBuilder.ts | 125 +- .../src/core/graph/builder/LoopBuilder.ts | 166 +- .../src/core/graph/builder/SwitchBuilder.ts | 67 +- .../src/core/graph/builder/TrapBuilder.ts | 122 +- .../src/core/graph/builder/ViewTreeBuilder.ts | 131 +- .../src/core/model/ArkBaseModel.ts | 13 +- .../arkanalyzer/src/core/model/ArkBody.ts | 17 +- .../arkanalyzer/src/core/model/ArkClass.ts | 52 +- .../arkanalyzer/src/core/model/ArkExport.ts | 19 +- .../arkanalyzer/src/core/model/ArkField.ts | 39 +- .../arkanalyzer/src/core/model/ArkFile.ts | 85 +- .../arkanalyzer/src/core/model/ArkImport.ts | 20 +- .../arkanalyzer/src/core/model/ArkMetadata.ts | 13 +- .../arkanalyzer/src/core/model/ArkMethod.ts | 138 +- .../src/core/model/ArkNamespace.ts | 54 +- .../src/core/model/ArkSignature.ts | 102 +- .../src/core/model/builder/ArkClassBuilder.ts | 177 +- .../core/model/builder/ArkExportBuilder.ts | 38 +- .../src/core/model/builder/ArkFieldBuilder.ts | 33 +- .../src/core/model/builder/ArkFileBuilder.ts | 61 +- .../core/model/builder/ArkImportBuilder.ts | 24 +- .../core/model/builder/ArkMethodBuilder.ts | 125 +- .../core/model/builder/ArkNamespaceBuilder.ts | 53 +- .../core/model/builder/ArkSignatureBuilder.ts | 10 +- .../src/core/model/builder/BodyBuilder.ts | 67 +- .../src/core/model/builder/builderUtils.ts | 87 +- ets2panda/linter/arkanalyzer/src/index.ts | 3 +- .../linter/arkanalyzer/src/save/ArkStream.ts | 4 +- .../linter/arkanalyzer/src/save/DotPrinter.ts | 6 +- .../arkanalyzer/src/save/GraphPrinter.ts | 20 +- .../arkanalyzer/src/save/JsonPrinter.ts | 80 +- .../linter/arkanalyzer/src/save/Printer.ts | 2 +- .../arkanalyzer/src/save/PrinterBuilder.ts | 31 +- .../arkanalyzer/src/save/ViewTreePrinter.ts | 24 +- .../src/save/arkir/ArkIRClassPrinter.ts | 2 +- .../src/save/arkir/ArkIRMethodPrinter.ts | 10 +- .../src/save/arkir/ArkIRNamespacePrinter.ts | 11 +- .../arkanalyzer/src/save/base/BasePrinter.ts | 4 +- .../src/save/base/ExportPrinter.ts | 13 +- .../src/save/base/ImportPrinter.ts | 10 +- .../arkanalyzer/src/save/base/PrinterUtils.ts | 22 +- .../arkanalyzer/src/save/serializeArkIR.ts | 23 +- .../arkanalyzer/src/save/source/SourceBase.ts | 12 +- .../arkanalyzer/src/save/source/SourceBody.ts | 6 +- .../src/save/source/SourceClass.ts | 7 +- .../src/save/source/SourceField.ts | 4 +- .../src/save/source/SourceFilePrinter.ts | 4 +- .../src/save/source/SourceMethod.ts | 16 +- .../src/save/source/SourceNamespace.ts | 9 +- .../arkanalyzer/src/save/source/SourceStmt.ts | 76 +- .../src/save/source/SourceTransformer.ts | 32 +- .../src/transformer/FunctionTransformer.ts | 7 +- .../src/transformer/SceneTransformer.ts | 7 +- .../StaticSingleAssignmentFormer.ts | 56 +- .../src/transformer/Transformer.ts | 11 +- .../arkanalyzer/src/utils/AstTreeUtils.ts | 58 +- .../src/utils/CfgStructualAnalysis.ts | 85 +- .../linter/arkanalyzer/src/utils/FileUtils.ts | 25 +- .../arkanalyzer/src/utils/SparseBitVector.ts | 18 +- .../arkanalyzer/src/utils/callGraphUtils.ts | 66 +- .../arkanalyzer/src/utils/crypto_utils.ts | 5 +- .../arkanalyzer/src/utils/entryMethodUtils.ts | 50 +- .../arkanalyzer/src/utils/getAllFiles.ts | 72 +- .../arkanalyzer/src/utils/json5parser.ts | 15 +- .../linter/arkanalyzer/src/utils/logger.ts | 12 +- .../arkanalyzer/src/utils/pathTransfer.ts | 12 +- ets2panda/linter/arkanalyzer/vitest.config.ts | 18 +- ets2panda/linter/build_linter.py | 82 +- ets2panda/linter/eslint.config.mjs | 2 +- ets2panda/linter/homecheck/.prettierrc | 10 + ets2panda/linter/homecheck/README.en.md | 36 + ets2panda/linter/homecheck/README.md | 201 + .../homecheck/config/projectConfig.json | 4 +- .../linter/homecheck/config/ruleConfig.json | 3 +- ets2panda/linter/homecheck/package.json | 14 +- .../resources/internalSdk/@internal/es5.d.ts | 56 - .../@hview/moment/index.d.ts | 2 +- ets2panda/linter/homecheck/ruleSet.json | 16 +- ets2panda/linter/homecheck/src/Index.ts | 6 +- ets2panda/linter/homecheck/src/Main.ts | 18 +- .../homecheck/src/checker/BaseChecker.ts | 10 +- .../checker/migration/AppStorageGetCheck.ts | 91 +- .../checker/migration/CustomBuilderCheck.ts | 183 +- .../checker/migration/InteropAssignCheck.ts | 293 + .../migration/InteropBackwardDFACheck.ts | 458 + .../migration/InteropBoxedTypeCheck.ts | 450 + .../InteropDynamicObjectLiteralsCheck.ts | 277 + .../migration/InteropJSModifyPropertyCheck.ts | 309 + .../src/checker/migration/InteropRuleInfo.ts | 141 + .../checker/migration/ModifyStateVarCheck.ts | 98 +- .../migration/NoMethodOverridingFieldCheck.ts | 46 +- .../migration/NoOptionalMethodCheck.ts | 56 +- .../src/checker/migration/NoTSLikeAsCheck.ts | 584 ++ .../checker/migration/ObjectLiteralCheck.ts | 317 +- .../migration/ObservedDecoratorCheck.ts | 290 +- .../src/checker/migration/ThisBindCheck.ts | 253 +- .../homecheck/src/checker/migration/Utils.ts | 152 + .../linter/homecheck/src/codeFix/FixEngine.ts | 10 +- .../src/codeFix/engines/AIFixEngine.ts | 8 +- .../src/codeFix/engines/EsLintFixEngine.ts | 28 +- .../src/codeFix/engines/HomeCheckFixEngine.ts | 21 +- .../linter/homecheck/src/matcher/Matchers.ts | 6 +- .../src/matcher/matcherAdapter/matchClass.ts | 6 +- .../src/matcher/matcherAdapter/matchFields.ts | 6 +- .../src/matcher/matcherAdapter/matchFiles.ts | 4 +- .../matcher/matcherAdapter/matchMethods.ts | 6 +- .../matcher/matcherAdapter/matchNameSpaces.ts | 4 +- .../linter/homecheck/src/model/Defects.ts | 18 +- .../linter/homecheck/src/model/Engine.ts | 6 +- .../linter/homecheck/src/model/File2Check.ts | 77 +- ets2panda/linter/homecheck/src/model/Fix.ts | 2 +- .../linter/homecheck/src/model/Interfaces.ts | 6 +- .../linter/homecheck/src/model/Message.ts | 4 +- .../linter/homecheck/src/model/NumberValue.ts | 2 +- .../homecheck/src/model/Project2Check.ts | 62 +- .../homecheck/src/model/ProjectConfig.ts | 8 +- ets2panda/linter/homecheck/src/model/Rule.ts | 8 +- .../linter/homecheck/src/model/RuleConfig.ts | 4 +- ets2panda/linter/homecheck/src/model/Scope.ts | 6 +- .../homecheck/src/model/SparseArrayValue.ts | 8 +- .../linter/homecheck/src/model/StmtExt.ts | 6 +- .../linter/homecheck/src/model/VarInfo.ts | 6 +- .../linter/homecheck/src/model/Variable.ts | 8 +- ets2panda/linter/homecheck/src/run.ts | 4 +- ets2panda/linter/homecheck/src/runTool.ts | 6 +- .../homecheck/src/tools/BuildModuleChains.ts | 50 +- .../homecheck/src/tools/depGraph/builder.ts | 2 +- .../src/tools/depGraph/fileComponent.ts | 2 +- .../homecheck/src/tools/depGraph/fileDeps.ts | 2 +- .../src/tools/depGraph/moduleComponent.ts | 2 +- .../src/tools/depGraph/moduleDeps.ts | 2 +- .../homecheck/src/tools/depGraph/utils.ts | 2 +- .../src/tools/migrationTool/ExportIssue.ts | 62 - .../src/tools/migrationTool/MigrationTool.ts | 16 +- .../linter/homecheck/src/tools/toolEntry.ts | 2 +- .../linter/homecheck/src/tools/toolRun.ts | 8 +- .../src/utils/checker/AbilityInterface.ts | 2 +- .../homecheck/src/utils/checker/BytesUtils.ts | 24 +- .../src/utils/checker/CheckerUtils.ts | 2 +- .../homecheck/src/utils/checker/ImageUtils.ts | 6 +- .../src/utils/checker/NumberUtils.ts | 62 +- .../src/utils/checker/StringUtils.ts | 14 +- .../homecheck/src/utils/checker/TypeUtils.ts | 2 +- .../src/utils/checker/ViewTreeTool.ts | 8 +- .../src/utils/checker/imageFormat/bmp.ts | 2 +- .../src/utils/checker/imageFormat/jpg.ts | 24 +- .../src/utils/checker/imageFormat/png.ts | 6 +- .../src/utils/checker/imageFormat/svg.ts | 16 +- .../src/utils/checker/imageFormat/webp.ts | 10 +- .../homecheck/src/utils/common/AfterCheck.ts | 6 +- .../src/utils/common/CheckBuilder.ts | 18 +- .../homecheck/src/utils/common/CheckEntry.ts | 56 +- .../src/utils/common/CheckerFactory.ts | 8 +- .../src/utils/common/CheckerIndex.ts | 32 +- .../src/utils/common/CheckerStorage.ts | 6 +- .../homecheck/src/utils/common/ConfigUtils.ts | 36 +- .../homecheck/src/utils/common/DefectsList.ts | 18 +- .../homecheck/src/utils/common/Disable.ts | 25 +- .../src/utils/common/FileRuleMapping.ts | 22 +- .../homecheck/src/utils/common/FileUtils.ts | 62 +- .../homecheck/src/utils/common/FixUtils.ts | 150 +- .../src/utils/common/GeneratingJsonFile.ts | 14 +- .../homecheck/src/utils/common/GlobMatch.ts | 8 +- .../homecheck/src/utils/common/Json5parser.ts | 6 +- .../homecheck/src/utils/common/ScopeHelper.ts | 16 +- .../homecheck/src/utils/common/Utils.ts | 24 +- ets2panda/linter/homecheck/vitest.config.ts | 6 +- ets2panda/linter/package.json | 13 +- .../install-ohos-typescript-and-homecheck.mjs | 36 +- .../linter/scripts/update-test-results.mjs | 216 +- ets2panda/linter/src/cli/CommandLineParser.ts | 61 +- ets2panda/linter/src/cli/LinterCLI.ts | 76 +- .../linter/src/lib/BaseTypeScriptLinter.ts | 112 + .../linter/src/lib/CommandLineOptions.ts | 5 +- ets2panda/linter/src/lib/CookBookMsg.ts | 127 +- ets2panda/linter/src/lib/FaultAttrs.ts | 57 +- ets2panda/linter/src/lib/FaultDesc.ts | 61 +- ets2panda/linter/src/lib/HomeCheck.ts | 49 +- .../linter/src/lib/InteropTypescriptLinter.ts | 138 +- ets2panda/linter/src/lib/LintRunResult.ts | 6 +- ets2panda/linter/src/lib/LinterOptions.ts | 10 +- ets2panda/linter/src/lib/LinterRunner.ts | 309 +- ets2panda/linter/src/lib/ProblemInfo.ts | 4 +- ets2panda/linter/src/lib/Problems.ts | 55 +- ets2panda/linter/src/lib/TypeScriptLinter.ts | 3891 ++++++-- .../linter/src/lib/TypeScriptLinterConfig.ts | 8 +- .../lib/autofixes/AutofixReportHtmlHelper.ts | 47 + .../linter/src/lib/autofixes/AutofixTitles.ts | 9 +- .../linter/src/lib/autofixes/Autofixer.ts | 1185 ++- .../linter/src/lib/autofixes/QuasiEditor.ts | 119 +- .../linter/src/lib/autofixes/SymbolCache.ts | 6 +- .../linter/src/lib/data/BuiltinList.json | 4631 +++++++++ .../linter/src/lib/data/SdkWhitelist.json | 8613 ++++++++++++++++- .../lib/statistics/FileProblemStatistics.ts | 23 + .../src/lib/statistics/FileStatistics.ts | 36 + .../src/lib/statistics/ProjectStatistics.ts | 31 + .../src/lib/statistics/StatisticsLogger.ts | 180 + .../src/{cli => lib/ts-compiler}/Compiler.ts | 60 +- .../ts-compiler/FormTscOptions.ts | 26 +- .../{cli => lib}/ts-compiler/ResolveSdks.ts | 41 +- .../lib/ts-diagnostics/TSCCompiledProgram.ts | 3 +- ets2panda/linter/src/lib/utils/TsUtils.ts | 329 +- .../src/lib/utils/consts/ArkTS2Rules.ts | 32 - .../src/lib/utils/consts/ArkTSUtilsAPI.ts | 18 + .../src/lib/utils/consts/ArkuiConstants.ts | 25 +- .../utils/consts/BuiltinGenericConstructor.ts | 11 +- .../src/lib/utils/consts/BuiltinWhiteList.ts | 47 + .../src/lib/utils/consts/CollectionsAPI.ts | 17 + .../src/lib/utils/consts/ConcurrentAPI.ts | 20 + .../linter/src/lib/utils/consts/InteropAPI.ts | 7 + .../src/lib/utils/consts/LimitedStdAPI.ts | 5 +- .../lib/utils/consts/Literals.ts} | 2 +- .../lib/utils/consts/MethodDeclaration.ts} | 2 +- .../lib/utils/consts/MethodSignature.ts} | 33 +- .../src/lib/utils/consts/OptionalMethod.ts | 16 + .../src/lib/utils/consts/RuntimeCheckAPI.ts | 38 + .../src/lib/utils/consts/SdkWhitelist.ts | 69 +- .../src/lib/utils/consts/SendableAPI.ts | 2 + .../src/lib/utils/consts/StringLiteral.ts | 4 + .../src/lib/utils/consts/TaskpoolAPI.ts | 20 + .../src/lib/utils/functions/ArrayUtils.ts | 2 +- .../src/lib/utils/functions/IsStruct.ts | 6 +- .../LibraryTypeCallDiagnosticChecker.ts | 2 +- .../src/sdk/linter_1_1/LintParameter.ts | 9 +- .../src/sdk/linter_1_1/RunArkTSLinter.ts | 68 +- ets2panda/linter/src/testRunner/Consts.ts | 23 + ets2panda/linter/src/testRunner/FileUtil.ts | 21 + ets2panda/linter/src/testRunner/LintTest.ts | 199 + .../linter/src/testRunner/MigrateTest.ts | 140 + .../src/testRunner/RunTestFileOptions.ts | 22 + ets2panda/linter/src/testRunner/TestArgs.ts | 20 +- .../linter/src/testRunner/TestFactory.ts | 134 + ets2panda/linter/src/testRunner/TestMode.ts | 64 + ets2panda/linter/src/testRunner/TestResult.ts | 6 +- ets2panda/linter/src/testRunner/TestRunner.ts | 405 +- .../src/testRunner/TestRunnerOptions.ts | 22 + .../TestUtil.ts} | 34 +- .../test/builtin/builtin_callsignature.ets | 37 + .../builtin_callsignature.ets.args.json} | 0 .../builtin_callsignature.ets.arkts2.json | 118 + .../builtin_callsignature.ets.json} | 0 ...uiltin_not_support_property_descriptor.ets | 61 + ..._support_property_descriptor.ets.args.json | 19 + ...pport_property_descriptor.ets.arkts2.json} | 378 +- ...n_not_support_property_descriptor.ets.json | 38 + .../builtin_object_getownpropertynames.ets | 18 + ...n_object_getownpropertynames.ets.args.json | 21 + ...object_getownpropertynames.ets.arkts2.json | 28 + ...bject_getownpropertynames.ets.autofix.json | 35 + ...iltin_object_getownpropertynames.ets.json} | 0 ...object_getownpropertynames.ets.migrate.ets | 18 + ...ject_getownpropertynames.ets.migrate.json} | 0 .../test/builtin/builtin_symbol_iterator.ets | 20 + .../builtin_symbol_iterator.ets.args.json} | 0 .../builtin_symbol_iterator.ets.arkts2.json | 58 + .../builtin/builtin_symbol_iterator.ets.json | 17 + .../linter/test/builtin/builtin_thisArgs.ets | 31 + .../builtin_thisArgs.ets.args.json} | 0 .../builtin/builtin_thisArgs.ets.arkts2.json | 118 + .../test/builtin/builtin_thisArgs.ets.json | 48 + .../concurrent_decorator_arkts2.ets | 5 +- .../concurrent_decorator_arkts2.ets.args.json | 3 +- ...oncurrent_decorator_arkts2.ets.arkts2.json | 38 +- ...ncurrent_decorator_arkts2.ets.autofix.json | 54 +- .../concurrent_decorator_arkts2.ets.json} | 0 ...oncurrent_decorator_arkts2.ets.migrate.ets | 28 + ...ncurrent_decorator_arkts2.ets.migrate.json | 28 + .../concurrent_sharedarraybuffer_arkts2.ets | 24 + ...ent_sharedarraybuffer_arkts2.ets.args.json | 21 + ...t_sharedarraybuffer_arkts2.ets.arkts2.json | 68 + ..._sharedarraybuffer_arkts2.ets.autofix.json | 103 + ...current_sharedarraybuffer_arkts2.ets.json} | 0 ...t_sharedarraybuffer_arkts2.ets.migrate.ets | 24 + ..._sharedarraybuffer_arkts2.ets.migrate.json | 3 + .../concurrent/no_support_isconcurrent.ets | 37 + .../no_support_isconcurrent.ets.args.json | 19 + .../no_support_isconcurrent.ets.arkts2.json | 38 + .../no_support_isconcurrent.ets.json | 17 + .../concurrent/use_limited_and_concurrent.ets | 41 + .../use_limited_and_concurrent.ets.args.json | 21 + ...use_limited_and_concurrent.ets.arkts2.json | 48 + ...se_limited_and_concurrent.ets.autofix.json | 62 + .../use_limited_and_concurrent.ets.json | 28 + ...use_limited_and_concurrent.ets.migrate.ets | 41 + ...e_limited_and_concurrent.ets.migrate.json} | 0 .../binary_operation_js_obj.ets.args.json | 4 +- .../binary_operation_js_obj.ets.arkts2.json | 10 +- .../binary_operation_js_obj.ets.autofix.json | 137 + .../binary_operation_js_obj.ets.migrate.ets} | 58 +- .../binary_operation_js_obj.ets.migrate.json | 68 + .../interop/call_function.ets.arkts2.json | 34 +- .../test/interop/call_object_methods.ets | 38 +- .../interop/call_object_methods.ets.args.json | 3 +- .../call_object_methods.ets.arkts2.json | 18 +- .../call_object_methods.ets.autofix.json | 29 +- .../call_object_methods.ets.migrate.ets | 21 + .../call_object_methods.ets.migrate.json | 38 + .../test/interop/ignore_files/unique_types.ts | 4 +- .../increases_decreases_js_obj.ets.args.json | 4 +- ...increases_decreases_js_obj.ets.arkts2.json | 26 +- ...ncreases_decreases_js_obj.ets.autofix.json | 248 + ...increases_decreases_js_obj.ets.migrate.ets | 23 + ...ncreases_decreases_js_obj.ets.migrate.json | 38 + .../interop/instantiated_js_obj.ets.args.json | 3 +- .../instantiated_js_obj.ets.arkts2.json | 16 +- .../instantiated_js_obj.ets.autofix.json | 18 +- .../instantiated_js_obj.ets.migrate.ets | 36 + .../instantiated_js_obj.ets.migrate.json | 48 + .../test/interop/interop_convert_import.ets | 7 +- .../interop_convert_import.ets.arkts2.json | 130 +- .../interop/interop_convert_import.ets.json | 2 +- .../test/interop/interop_convert_import_js.js | 5 +- .../interop_equality_judgment.ets.args.json | 3 +- .../interop_equality_judgment.ets.arkts2.json | 10 +- ...interop_equality_judgment.ets.autofix.json | 12 +- .../interop_equality_judgment.ets.migrate.ets | 24 + ...interop_equality_judgment.ets.migrate.json | 48 + .../test/interop/interop_export_js_rules.ets | 25 + .../interop_export_js_rules.ets.args.json | 21 + .../interop_export_js_rules.ets.arkts2.json | 68 + .../interop_export_js_rules.ets.autofix.json | 88 + .../interop/interop_export_js_rules.ets.json | 28 + .../interop_export_js_rules.ets.migrate.ets | 27 + .../interop_export_js_rules.ets.migrate.json | 58 + .../interop/interop_import_js.ets.args.json | 3 +- .../interop/interop_import_js.ets.arkts2.json | 14 +- .../interop_import_js.ets.autofix.json | 28 +- .../interop/interop_import_js.ets.migrate.ets | 40 + .../interop_import_js.ets.migrate.json | 198 + .../interop/interop_import_js_compare.ets | 4 +- .../interop_import_js_compare.ets.arkts2.json | 130 +- .../interop_import_js_index.ets.args.json | 3 +- .../interop_import_js_index.ets.arkts2.json | 18 +- .../interop_import_js_index.ets.autofix.json | 20 +- .../interop_import_js_index.ets.migrate.ets | 22 + .../interop_import_js_index.ets.migrate.json | 48 + .../test/interop/interop_import_js_rules.ets | 20 +- .../interop_import_js_rules.ets.arkts2.json | 664 +- .../interop_import_js_rules.ets.autofix.json | 986 +- .../interop/interop_import_js_rules.ets.json | 83 +- ...rules.js => interop_import_js_rules_js.js} | 5 + .../interop_import_typeof_js.ets.args.json | 3 +- .../interop_import_typeof_js.ets.arkts2.json | 212 +- .../interop_import_typeof_js.ets.autofix.json | 218 +- .../interop_import_typeof_js.ets.migrate.ets | 83 + .../interop_import_typeof_js.ets.migrate.json | 168 + ...rop_not_have_property_arkts2.ets.args.json | 3 +- ...p_not_have_property_arkts2.ets.arkts2.json | 20 +- ..._not_have_property_arkts2.ets.autofix.json | 20 +- ...p_not_have_property_arkts2.ets.migrate.ets | 25 + ..._not_have_property_arkts2.ets.migrate.json | 48 + .../interop_not_have_property_num_arkts2.ets | 6 +- ...not_have_property_num_arkts2.ets.args.json | 3 +- ...t_have_property_num_arkts2.ets.arkts2.json | 186 +- ..._have_property_num_arkts2.ets.autofix.json | 272 +- ...t_have_property_num_arkts2.ets.migrate.ets | 28 + ..._have_property_num_arkts2.ets.migrate.json | 98 + ...o_js_await.ets => no_await_js_promise.ets} | 134 +- .../interop/no_await_js_promise.ets.args.json | 19 + .../no_await_js_promise.ets.arkts2.json | 258 + ....ets.json => no_await_js_promise.ets.json} | 10 +- ..._awai.js => no_await_js_promise_export.js} | 0 .../interop/no_js_instanceof.ets.arkts2.json | 62 +- .../linter/test/interop/object_built_in.ets | 11 +- .../interop/object_built_in.ets.args.json | 1 + .../interop/object_built_in.ets.arkts2.json | 69 + .../test/interop/object_built_in.ets.json | 40 +- .../interop/object_literal_constructor.ets | 25 + ... object_literal_constructor.ets.args.json} | 0 ...object_literal_constructor.ets.arkts2.json | 58 + .../object_literal_constructor.ets.json | 28 + .../interop/object_literal_union_type.ets | 29 + .../object_literal_union_type.ets.args.json} | 0 .../object_literal_union_type.ets.arkts2.json | 68 + .../object_literal_union_type.ets.json | 38 + .../interop/oh_modules/object_built_in.ets | 11 +- .../oh_modules/object_literal_constructor.ets | 42 + .../oh_modules/object_literal_union_type.ets | 26 + .../object_literal_union_type_arkts2.ets | 18 + .../interop/oh_modules/reflect_export.ets | 4 + .../static_object_literals_export.ets | 28 + .../linter/test/interop/reflect_built_in.ets | 32 +- .../interop/reflect_built_in.ets.args.json | 6 +- .../interop/reflect_built_in.ets.arkts2.json | 68 + .../test/interop/reflect_built_in.ets.json | 60 +- .../test/interop/static_dynamic_import.ets | 25 + .../static_dynamic_import.ets.args.json | 19 + .../static_dynamic_import.ets.arkts2.json | 98 + .../static_dynamic_import.ets.json} | 0 .../test/interop/static_object_literals.ets | 44 + .../static_object_literals.ets.args.json} | 4 +- .../interop/static_object_literals.ets.json | 78 + .../interop/test_files/dummy_arkts1_file.ets | 16 + .../test/interop/test_files/dummy_js_file.js | 16 + .../test/interop/test_files/dummy_ts_file.ts | 16 + .../linter/test/interop/unique_types.ets | 4 + .../test/interop/unique_types.ets.args.json | 1 + .../test/interop/unique_types.ets.arkts2.json | 52 +- .../interop/unique_types.ets.autofix.json | 72 +- .../linter/test/interop/unique_types.ets.json | 29 +- .../test/interop/unique_types.ets.migrate.ets | 36 + .../interop/unique_types.ets.migrate.json | 58 + ...nimatable_extend_decorator_1.ets.args.json | 3 +- ...matable_extend_decorator_1.ets.migrate.ets | 41 + ...atable_extend_decorator_1.ets.migrate.json | 58 + ...nimatable_extend_decorator_2.ets.args.json | 3 +- ...matable_extend_decorator_2.ets.migrate.ets | 41 + ...atable_extend_decorator_2.ets.migrate.json | 58 + .../test/main/arkts-array-type-immutable.ets | 37 + .../arkts-array-type-immutable.ets.args.json | 19 + ...arkts-array-type-immutable.ets.arkts2.json | 68 + ...on => arkts-array-type-immutable.ets.json} | 0 .../arkts-primitive-type-normalization.ets | 22 + ...primitive-type-normalization.ets.args.json | 19 + ...imitive-type-normalization.ets.arkts2.json | 98 + ...kts-primitive-type-normalization.ets.json} | 0 .../linter/test/main/arktsutils_module.ets | 35 + .../test/main/arktsutils_module.ets.args.json | 21 + .../main/arktsutils_module.ets.arkts2.json | 58 + .../main/arktsutils_module.ets.autofix.json | 86 + .../arktsutils_module.ets.json} | 0 .../main/arktsutils_module.ets.migrate.ets | 35 + .../main/arktsutils_module.ets.migrate.json | 17 + .../test/main/array_index_expr_type.ets | 4 +- .../main/array_index_expr_type.ets.args.json | 4 +- .../array_index_expr_type.ets.arkts2.json | 52 +- .../array_index_expr_type.ets.autofix.json | 631 ++ .../array_index_expr_type.ets.migrate.ets | 85 + .../array_index_expr_type.ets.migrate.json | 138 + .../test/main/case_expr.ets.arkts2.json | 2 +- .../test/main/catch_clause.ets.args.json | 5 +- .../test/main/catch_clause.ets.migrate.ets | 32 + .../test/main/catch_clause.ets.migrate.json | 48 + .../test/main/class_as_object.ets.arkts2.json | 32 +- .../linter/test/main/class_no_constructor.ets | 19 + .../main/class_no_constructor.ets.args.json | 20 + .../main/class_no_constructor.ets.arkts2.json | 28 + .../test/main/class_no_constructor.ets.json | 17 + .../main/class_no_constructor.ets.migrate.ets | 19 + .../class_no_constructor.ets.migrate.json | 28 + .../main/class_static_block.ets.args.json | 5 +- .../class_static_block.ets.migrate.ets} | 9 +- .../class_static_block.ets.migrate.json} | 0 .../linter/test/main/class_static_init.ets | 126 +- .../test/main/class_static_init.ets.args.json | 3 +- .../main/class_static_init.ets.arkts2.json | 450 + .../main/class_static_init.ets.autofix.json | 876 ++ .../test/main/class_static_init.ets.json | 143 +- .../collections_module.ets} | 56 +- .../main/collections_module.ets.args.json | 21 + .../main/collections_module.ets.arkts2.json | 138 + .../main/collections_module.ets.autofix.json | 222 + .../collections_module.ets.json} | 0 .../main/collections_module.ets.migrate.ets | 38 + .../main/collections_module.ets.migrate.json | 18 + ets2panda/linter/test/main/custom_layout.ets | 100 + .../test/main/custom_layout.ets.args.json | 21 + ...ts2.json => custom_layout.ets.arkts2.json} | 286 +- ...ix.json => custom_layout.ets.autofix.json} | 399 +- .../linter/test/main/custom_layout.ets.json | 38 + .../test/main/custom_layout.ets.migrate.ets | 104 + .../test/main/custom_layout.ets.migrate.json | 48 + .../main/debugger_statememt.ets.args.json | 3 +- .../main/debugger_statememt.ets.autofix.json | 4 +- .../debugger_statememt.ets.migrate.ets} | 42 +- .../debugger_statememt.ets.migrate.json} | 0 .../test/main/default_required_args.ets | 60 + .../main/default_required_args.ets.args.json | 19 + .../default_required_args.ets.arkts2.json | 88 + .../test/main/default_required_args.ets.json | 17 + .../destructuring_assignments.ets.args.json | 5 +- ...destructuring_assignments.ets.autofix.json | 20 +- ...destructuring_assignments.ets.migrate.ets} | 114 +- ...estructuring_assignments.ets.migrate.json} | 360 +- .../destructuring_declarations.ets.args.json | 5 +- ...estructuring_declarations.ets.autofix.json | 20 +- ...estructuring_declarations.ets.migrate.ets} | 119 +- ...structuring_declarations.ets.migrate.json} | 300 +- .../destructuring_parameters.ets.args.json | 3 +- .../destructuring_parameters.ets.migrate.ets | 99 + .../destructuring_parameters.ets.migrate.json | 228 + .../linter/test/main/dollar_binding_1.ets | 4 + .../test/main/dollar_binding_1.ets.args.json | 3 +- .../main/dollar_binding_1.ets.arkts2.json | 44 +- .../main/dollar_binding_1.ets.autofix.json | 86 +- .../main/dollar_binding_1.ets.migrate.ets | 44 + .../dollar_binding_1.ets.migrate.json} | 0 .../linter/test/main/dollar_binding_2.ets | 4 + .../test/main/dollar_binding_2.ets.args.json | 3 +- .../main/dollar_binding_2.ets.migrate.ets | 44 + .../dollar_binding_2.ets.migrate.json} | 0 .../double_dollar_binding_1.ets.args.json | 3 +- .../double_dollar_binding_1.ets.migrate.ets | 42 + .../double_dollar_binding_1.ets.migrate.json} | 0 .../double_dollar_binding_2.ets.args.json | 3 +- .../double_dollar_binding_2.ets.migrate.ets | 42 + .../double_dollar_binding_2.ets.migrate.json} | 4 +- .../main/double_excla_binding_1.ets.args.json | 3 +- .../double_excla_binding_1.ets.migrate.ets | 124 + .../double_excla_binding_1.ets.migrate.json | 28 + .../main/double_excla_binding_2.ets.args.json | 3 +- .../double_excla_binding_2.ets.migrate.ets | 123 + .../double_excla_binding_2.ets.migrate.json | 28 + .../test/main/entry_annotation_test10_1.ets | 48 +- .../entry_annotation_test10_1.ets.args.json | 3 +- ...entry_annotation_test10_1.ets.autofix.json | 68 +- .../entry_annotation_test10_1.ets.migrate.ets | 26 + ...ntry_annotation_test10_1.ets.migrate.json} | 4 +- .../test/main/entry_annotation_test10_2.ets | 50 +- .../entry_annotation_test10_2.ets.args.json | 3 +- .../entry_annotation_test10_2.ets.migrate.ets | 26 + ...ntry_annotation_test10_2.ets.migrate.json} | 4 +- .../test/main/entry_annotation_test1_1.ets | 46 +- .../entry_annotation_test1_1.ets.args.json | 3 +- .../entry_annotation_test1_1.ets.migrate.ets} | 9 +- .../entry_annotation_test1_1.ets.migrate.json | 17 + .../test/main/entry_annotation_test1_2.ets | 46 +- .../entry_annotation_test1_2.ets.args.json | 3 +- .../entry_annotation_test1_2.ets.migrate.ets | 24 + .../entry_annotation_test1_2.ets.migrate.json | 17 + .../test/main/entry_annotation_test2_1.ets | 48 +- .../entry_annotation_test2_1.ets.args.json | 3 +- .../entry_annotation_test2_1.ets.autofix.json | 108 +- .../entry_annotation_test2_1.ets.migrate.ets | 26 + .../entry_annotation_test2_1.ets.migrate.json | 38 + .../test/main/entry_annotation_test2_2.ets | 48 +- .../entry_annotation_test2_2.ets.args.json | 3 +- .../entry_annotation_test2_2.ets.migrate.ets | 25 + .../entry_annotation_test2_2.ets.migrate.json | 38 + .../test/main/entry_annotation_test3_1.ets | 46 +- .../entry_annotation_test3_1.ets.args.json | 3 +- .../entry_annotation_test3_1.ets.autofix.json | 88 +- .../entry_annotation_test3_1.ets.migrate.ets | 25 + .../entry_annotation_test3_1.ets.migrate.json | 28 + .../test/main/entry_annotation_test3_2.ets | 48 +- .../entry_annotation_test3_2.ets.args.json | 3 +- .../entry_annotation_test3_2.ets.migrate.ets | 25 + .../entry_annotation_test3_2.ets.migrate.json | 28 + .../test/main/entry_annotation_test4_1.ets | 46 +- .../entry_annotation_test4_1.ets.args.json | 3 +- .../entry_annotation_test4_1.ets.autofix.json | 68 +- .../entry_annotation_test4_1.ets.migrate.ets | 25 + .../entry_annotation_test4_1.ets.migrate.json | 17 + .../test/main/entry_annotation_test4_2.ets | 48 +- .../entry_annotation_test4_2.ets.args.json | 3 +- .../entry_annotation_test4_2.ets.migrate.ets | 25 + .../entry_annotation_test4_2.ets.migrate.json | 17 + .../test/main/entry_annotation_test5_1.ets | 48 +- .../entry_annotation_test5_1.ets.args.json | 3 +- .../entry_annotation_test5_1.ets.autofix.json | 108 +- .../entry_annotation_test5_1.ets.migrate.ets | 26 + .../entry_annotation_test5_1.ets.migrate.json | 38 + .../test/main/entry_annotation_test5_2.ets | 48 +- .../entry_annotation_test5_2.ets.args.json | 3 +- .../entry_annotation_test5_2.ets.migrate.ets | 25 + .../entry_annotation_test5_2.ets.migrate.json | 38 + .../test/main/entry_annotation_test6_1.ets | 46 +- .../entry_annotation_test6_1.ets.args.json | 3 +- .../entry_annotation_test6_1.ets.autofix.json | 88 +- .../entry_annotation_test6_1.ets.migrate.ets | 25 + .../entry_annotation_test6_1.ets.migrate.json | 28 + .../test/main/entry_annotation_test6_2.ets | 48 +- .../entry_annotation_test6_2.ets.args.json | 3 +- .../entry_annotation_test6_2.ets.migrate.ets | 25 + .../entry_annotation_test6_2.ets.migrate.json | 28 + .../test/main/entry_annotation_test7_1.ets | 46 +- .../entry_annotation_test7_1.ets.args.json | 3 +- .../entry_annotation_test7_1.ets.autofix.json | 68 +- .../entry_annotation_test7_1.ets.migrate.ets | 25 + .../entry_annotation_test7_1.ets.migrate.json | 17 + .../test/main/entry_annotation_test7_2.ets | 48 +- .../entry_annotation_test7_2.ets.args.json | 3 +- .../entry_annotation_test7_2.ets.migrate.ets | 25 + .../entry_annotation_test7_2.ets.migrate.json | 17 + .../test/main/entry_annotation_test8_1.ets | 48 +- .../entry_annotation_test8_1.ets.args.json | 3 +- .../entry_annotation_test8_1.ets.autofix.json | 102 +- .../entry_annotation_test8_1.ets.migrate.ets | 26 + .../entry_annotation_test8_1.ets.migrate.json | 28 + .../test/main/entry_annotation_test8_2.ets | 50 +- .../entry_annotation_test8_2.ets.args.json | 3 +- .../entry_annotation_test8_2.ets.autofix.json | 68 +- .../entry_annotation_test8_2.ets.migrate.ets | 26 + .../entry_annotation_test8_2.ets.migrate.json | 28 + .../test/main/entry_annotation_test9_1.ets | 46 +- .../entry_annotation_test9_1.ets.args.json | 3 +- .../entry_annotation_test9_1.ets.autofix.json | 102 +- .../entry_annotation_test9_1.ets.migrate.ets | 25 + .../entry_annotation_test9_1.ets.migrate.json | 17 + .../test/main/entry_annotation_test9_2.ets | 48 +- .../entry_annotation_test9_2.ets.args.json | 3 +- .../entry_annotation_test9_2.ets.autofix.json | 68 +- .../entry_annotation_test9_2.ets.migrate.ets | 25 + .../entry_annotation_test9_2.ets.migrate.json | 17 + .../linter/test/main/equals_token_option.ets | 55 + .../equals_token_option.ets.args.json} | 0 .../main/equals_token_option.ets.arkts2.json | 198 + .../test/main/equals_token_option.ets.json | 28 + .../test/main/explicit_function_type.ets | 13 +- .../main/explicit_function_type.ets.args.json | 4 +- .../explicit_function_type.ets.arkts2.json | 754 +- .../explicit_function_type.ets.autofix.json} | 365 +- .../explicit_function_type.ets.migrate.ets | 175 + .../explicit_function_type.ets.migrate.json | 148 + .../linter/test/main/exponent.ets.args.json | 3 +- .../linter/test/main/exponent.ets.migrate.ets | 26 + .../test/main/exponent.ets.migrate.json | 58 + .../main/extend_decorator_1.ets.args.json | 3 +- .../main/extend_decorator_1.ets.migrate.ets | 49 + .../main/extend_decorator_1.ets.migrate.json | 178 + .../main/extend_decorator_2.ets.args.json | 3 +- .../main/extend_decorator_2.ets.migrate.ets | 48 + .../main/extend_decorator_2.ets.migrate.json | 148 + .../linter/test/main/extends_expression.ets | 2 + .../main/extends_expression.ets.arkts2.json | 224 +- .../test/main/extends_expression.ets.json | 146 +- .../test/main/func_inferred_type_args.ets | 45 +- .../func_inferred_type_args.ets.arkts2.json | 460 +- .../main/func_inferred_type_args.ets.json | 554 +- .../test/main/func_inferred_type_args_2.ets | 74 + .../func_inferred_type_args_2.ets.args.json | 21 + .../func_inferred_type_args_2.ets.arkts2.json | 378 + ...func_inferred_type_args_2.ets.autofix.json | 483 + .../main/func_inferred_type_args_2.ets.json | 128 + .../func_inferred_type_args_2.ets.migrate.ets | 74 + ...func_inferred_type_args_2.ets.migrate.json | 228 + .../test/main/func_return_type.ets.args.json | 5 +- .../func_return_type.ets.migrate.ets} | 54 +- .../func_return_type.ets.migrate.json} | 122 +- .../main/function_expression.ets.args.json | 5 +- .../function_expression.ets.migrate.ets} | 94 +- .../function_expression.ets.migrate.json} | 122 +- .../function_object_methods.ets.arkts2.json | 80 +- .../test/main/global_this.ets.args.json | 3 +- .../test/main/global_this.ets.migrate.ets | 41 + .../test/main/global_this.ets.migrate.json | 58 + .../test/main/index_negative.ets.arkts2.json | 352 +- .../main/interface_import_1.ets.args.json | 3 +- .../main/interface_import_1.ets.arkts2.json | 10 - .../main/interface_import_1.ets.autofix.json | 47 +- ...ets => interface_import_1.ets.migrate.ets} | 99 +- .../main/interface_import_1.ets.migrate.json | 98 + .../linter/test/main/interface_import_2.ets | 3 +- .../main/interface_import_2.ets.args.json | 3 +- .../main/interface_import_2.ets.migrate.ets | 93 + .../main/interface_import_2.ets.migrate.json | 98 + .../main/invalid_identifier.ets.arkts2.json | 2 +- ets2panda/linter/test/main/lazy_import.ets | 3 + .../test/main/lazy_import.ets.args.json | 3 +- .../test/main/lazy_import.ets.arkts2.json | 10 + .../test/main/lazy_import.ets.autofix.json | 52 + .../linter/test/main/limit_void_type.ets | 14 + .../test/main/limit_void_type.ets.arkts2.json | 62 +- .../linter/test/main/limit_void_type.ets.json | 10 + .../linter/test/main/limited_literal_type.ets | 15 + .../main/limited_literal_type.ets.arkts2.json | 160 + .../test/main/limited_literal_type.ets.json | 23 +- .../main/limited_stdlib_api.ets.arkts2.json | 26 +- .../main/literals_as_prop_names.ets.args.json | 5 +- .../literals_as_prop_names.ets.arkts2.json | 52 +- .../literals_as_prop_names.ets.autofix.json | 121 +- .../literals_as_prop_names.ets.migrate.ets} | 75 +- .../literals_as_prop_names.ets.migrate.json} | 138 +- ets2panda/linter/test/main/localBuilder_1.ets | 33 + ...args.json => localBuilder_1.ets.args.json} | 3 +- .../localBuilder_1.ets.arkts2.json} | 80 +- .../test/main/localBuilder_1.ets.autofix.json | 137 + .../linter/test/main/localBuilder_1.ets.json | 17 + .../test/main/localBuilder_1.ets.migrate.ets | 37 + .../test/main/localBuilder_1.ets.migrate.json | 17 + ets2panda/linter/test/main/localBuilder_2.ets | 37 + .../test/main/localBuilder_2.ets.args.json | 21 + .../test/main/localBuilder_2.ets.arkts2.json | 17 + .../test/main/localBuilder_2.ets.autofix.json | 17 + .../linter/test/main/localBuilder_2.ets.json | 17 + .../test/main/localBuilder_2.ets.migrate.ets | 37 + .../test/main/localBuilder_2.ets.migrate.json | 17 + .../linter/test/main/make_observed_1.ets | 42 + .../test/main/make_observed_1.ets.args.json | 19 + .../make_observed_1.ets.arkts2.json} | 92 +- .../linter/test/main/make_observed_1.ets.json | 17 + .../linter/test/main/make_observed_2.ets | 42 + .../test/main/make_observed_2.ets.args.json | 19 + .../test/main/make_observed_2.ets.arkts2.json | 108 + .../linter/test/main/make_observed_2.ets.json | 17 + .../linter/test/main/make_observed_3.ets | 49 + .../test/main/make_observed_3.ets.args.json | 19 + .../test/main/make_observed_3.ets.arkts2.json | 98 + .../linter/test/main/make_observed_3.ets.json | 17 + .../linter/test/main/method_inheritance.ets | 99 + .../main/method_inheritance.ets.args.json | 19 + .../main/method_inheritance.ets.arkts2.json | 98 + .../test/main/method_inheritance.ets.json | 17 + .../linter/test/main/method_overriding.ets | 8 + .../main/method_overriding.ets.arkts2.json | 24 +- .../linter/test/main/no_enum_prop_as_type.ets | 20 + .../main/no_enum_prop_as_type.ets.args.json | 19 + .../main/no_enum_prop_as_type.ets.arkts2.json | 38 + .../test/main/no_enum_prop_as_type.ets.json | 17 + .../test/main/no_import_concurrency.ets | 12 +- .../main/no_import_concurrency.ets.args.json | 4 +- .../no_import_concurrency.ets.arkts2.json | 74 +- .../no_import_concurrency.ets.autofix.json | 171 + .../no_import_concurrency.ets.migrate.ets | 25 + .../no_import_concurrency.ets.migrate.json | 17 + .../linter/test/main/no_sparse_array.ets | 17 + .../test/main/no_sparse_array.ets.args.json | 20 + .../test/main/no_sparse_array.ets.arkts2.json | 38 + .../linter/test/main/no_sparse_array.ets.json | 17 + .../test/main/no_ts_like_smart_type.ets | 34 + .../main/no_ts_like_smart_type.ets.args.json | 19 + .../no_ts_like_smart_type.ets.arkts2.json | 58 + .../test/main/no_ts_like_smart_type.ets.json | 28 + .../linter/test/main/no_tuples_arrays.ets | 17 +- .../main/no_tuples_arrays.ets.arkts2.json | 180 + .../test/main/no_tuples_arrays.ets.json | 23 +- .../linter/test/main/nondecimal-bigint.ets | 19 + .../test/main/nondecimal-bigint.ets.args.json | 19 + .../main/nondecimal-bigint.ets.arkts2.json | 48 + .../test/main/nondecimal-bigint.ets.json | 17 + .../numeric_bigint_compare.ets} | 28 +- ...n => numeric_bigint_compare.ets.args.json} | 37 +- .../numeric_bigint_compare.ets.arkts2.json | 98 + .../test/main/numeric_bigint_compare.ets.json | 17 + .../linter/test/main/numeric_semantics.ets | 64 +- .../test/main/numeric_semantics.ets.args.json | 3 +- .../main/numeric_semantics.ets.arkts2.json | 330 +- .../main/numeric_semantics.ets.autofix.json | 741 +- .../test/main/numeric_semantics.ets.json | 124 +- .../main/numeric_semantics.ets.migrate.ets | 211 + .../main/numeric_semantics.ets.migrate.json | 118 + .../test/main/object_literals.ets.args.json | 5 +- .../test/main/object_literals.ets.migrate.ets | 293 + .../main/object_literals.ets.migrate.json | 198 + .../test/main/object_literals_2.ets.args.json | 5 +- .../main/object_literals_2.ets.migrate.ets | 289 + .../main/object_literals_2.ets.migrate.json | 178 + .../test/main/object_literals_3.ets.args.json | 5 +- .../main/object_literals_3.ets.migrate.ets | 277 + .../main/object_literals_3.ets.migrate.json | 78 + .../test/main/object_literals_4.ets.args.json | 5 +- .../main/object_literals_4.ets.migrate.ets | 73 + .../main/object_literals_4.ets.migrate.json | 17 + .../test/main/object_literals_autofixes.ets | 6 +- .../object_literals_autofixes.ets.args.json | 5 +- ...object_literals_autofixes.ets.autofix.json | 60 +- ...object_literals_autofixes.ets.migrate.ets} | 236 +- ...bject_literals_autofixes.ets.migrate.json} | 512 +- ...ject_literals_prop_func_type.ets.args.json | 5 +- ...ct_literals_prop_func_type.ets.migrate.ets | 54 + ...t_literals_prop_func_type.ets.migrate.json | 78 + .../test/main/object_literals_properties.ets | 241 +- .../object_literals_properties.ets.args.json | 6 +- ...object_literals_properties.ets.arkts2.json | 784 +- ...ject_literals_properties.ets.autofix.json} | 1218 ++- .../main/object_literals_properties.ets.json | 276 +- ...object_literals_properties.ets.migrate.ets | 307 + ...bject_literals_properties.ets.migrate.json | 318 + .../test/main/object_spread.ets.args.json | 5 +- .../test/main/object_spread.ets.migrate.ets | 26 + .../test/main/object_spread.ets.migrate.json | 38 + .../main/oh_modules/@arkts.collections.d.ets | 28 + .../test/main/oh_modules/@arkts.utils.d.ets | 22 + .../test/main/oh_modules/@kit.ArkTS.d.ets | 19 + .../oh_modules/@ohos.taskpool.d.ets} | 6 +- .../test/main/oh_modules/@ohos.worker.d.ets | 28 + .../main/parameter_properties.ets.args.json | 3 +- .../main/parameter_properties.ets.migrate.ets | 147 + .../parameter_properties.ets.migrate.json | 38 + .../main/private_identifiers.ets.args.json | 5 +- .../main/private_identifiers.ets.migrate.ets | 78 + .../main/private_identifiers.ets.migrate.json | 318 + .../main/prop_decorator_and_interfaces_1.ets | 39 + ...p_decorator_and_interfaces_1.ets.args.json | 19 + ...decorator_and_interfaces_1.ets.arkts2.json | 128 + .../prop_decorator_and_interfaces_1.ets.json | 17 + .../main/prop_decorator_and_interfaces_2.ets | 49 + ...p_decorator_and_interfaces_2.ets.args.json | 19 + ...decorator_and_interfaces_2.ets.arkts2.json | 448 + .../prop_decorator_and_interfaces_2.ets.json | 98 + .../main/prop_decorator_and_interfaces_3.ets | 59 + ...p_decorator_and_interfaces_3.ets.args.json | 19 + ...decorator_and_interfaces_3.ets.arkts2.json | 248 + .../prop_decorator_and_interfaces_3.ets.json | 108 + .../linter/test/main/prop_name_from_value.ets | 25 + .../main/prop_name_from_value.ets.args.json | 19 + .../prop_name_from_value.ets.arkts2.json} | 12 +- .../test/main/prop_name_from_value.ets.json | 17 + .../property_access_by_index.ets.args.json | 5 +- .../property_access_by_index.ets.arkts2.json | 54 +- .../property_access_by_index.ets.migrate.ets | 184 + ...property_access_by_index.ets.migrate.json} | 42 +- .../property_decl_on_function.ets.arkts2.json | 10 - .../linter/test/main/provide_annotation_1.ets | 86 +- .../main/provide_annotation_1.ets.args.json | 3 +- .../provide_annotation_1.ets.autofix.json | 44 +- .../main/provide_annotation_1.ets.migrate.ets | 46 + .../provide_annotation_1.ets.migrate.json | 48 + .../linter/test/main/provide_annotation_2.ets | 86 +- .../main/provide_annotation_2.ets.args.json | 3 +- .../provide_annotation_2.ets.autofix.json | 36 +- .../main/provide_annotation_2.ets.migrate.ets | 46 + .../provide_annotation_2.ets.migrate.json | 48 + .../linter/test/main/runtime_array_bound.ets | 90 + .../main/runtime_array_bound.ets.args.json | 20 + .../main/runtime_array_bound.ets.arkts2.json | 168 + .../test/main/runtime_array_bound.ets.json | 17 + .../main/runtime_array_bound.ets.migrate.ets | 90 + .../main/runtime_array_bound.ets.migrate.json | 98 + .../sendable_class_inheritance.ets.args.json | 3 +- ...sendable_class_inheritance.ets.migrate.ets | 190 + ...ndable_class_inheritance.ets.migrate.json} | 122 +- ...sendable_class_inheritance_2.ets.args.json | 3 +- ...ndable_class_inheritance_2.ets.migrate.ets | 49 + ...dable_class_inheritance_2.ets.migrate.json | 28 + .../test/main/sendable_decorator_arkts2.ets | 1 + .../sendable_decorator_arkts2.ets.args.json | 3 +- .../sendable_decorator_arkts2.ets.arkts2.json | 24 +- ...sendable_decorator_arkts2.ets.autofix.json | 12 +- .../sendable_decorator_arkts2.ets.migrate.ets | 19 + ...sendable_decorator_arkts2.ets.migrate.json | 17 + .../sendable_decorator_limited.ets.args.json | 5 +- ...sendable_decorator_limited.ets.migrate.ets | 53 + ...endable_decorator_limited.ets.migrate.json | 17 + ...sendable_explicit_field_type.ets.args.json | 3 +- ...dable_explicit_field_type.ets.autofix.json | 792 +- ...ndable_explicit_field_type.ets.migrate.ets | 659 ++ ...dable_explicit_field_type.ets.migrate.json | 2498 +++++ ...ndable_explicit_field_type_2.ets.args.json | 3 +- ...ble_explicit_field_type_2.ets.autofix.json | 36 +- ...ble_explicit_field_type_2.ets.migrate.ets} | 55 +- ...ble_explicit_field_type_2.ets.migrate.json | 58 + .../test/main/sendable_function.ets.args.json | 3 +- .../main/sendable_function.ets.migrate.ets | 230 + .../main/sendable_function.ets.migrate.json | 388 + .../main/sendable_function_2.ets.args.json | 3 +- .../main/sendable_function_2.ets.migrate.ets | 28 + .../main/sendable_function_2.ets.migrate.json | 17 + ets2panda/linter/test/main/static_class.ets | 21 + .../test/main/static_class.ets.args.json | 20 + .../test/main/static_class.ets.arkts2.json | 28 + .../linter/test/main/static_class.ets.json | 17 + .../test/main/static_class.ets.migrate.ets | 21 + .../test/main/static_class.ets.migrate.json | 28 + .../main/structural_identity.ets.arkts2.json | 32 +- .../styles_decorator_anon_1.ets.args.json | 37 +- .../styles_decorator_anon_1.ets.arkts2.json | 4 +- .../styles_decorator_anon_1.ets.autofix.json | 4 +- .../styles_decorator_anon_1.ets.migrate.ets | 44 + .../styles_decorator_anon_1.ets.migrate.json | 17 + .../styles_decorator_anon_2.ets.args.json | 3 +- .../styles_decorator_anon_2.ets.migrate.ets | 44 + .../styles_decorator_anon_2.ets.migrate.json | 17 + .../test/main/styles_decorator_global_1.ets | 3 +- .../styles_decorator_global_1.ets.args.json | 3 +- .../styles_decorator_global_1.ets.arkts2.json | 44 +- ...styles_decorator_global_1.ets.autofix.json | 89 +- .../styles_decorator_global_1.ets.migrate.ets | 65 + ...styles_decorator_global_1.ets.migrate.json | 17 + .../test/main/styles_decorator_global_2.ets | 7 +- .../styles_decorator_global_2.ets.args.json | 3 +- .../styles_decorator_global_2.ets.migrate.ets | 65 + ...styles_decorator_global_2.ets.migrate.json | 17 + .../test/main/styles_decorator_mix_1.ets | 92 + .../main/styles_decorator_mix_1.ets.args.json | 21 + .../styles_decorator_mix_1.ets.arkts2.json} | 310 +- .../styles_decorator_mix_1.ets.autofix.json | 443 + .../test/main/styles_decorator_mix_1.ets.json | 17 + ...=> styles_decorator_mix_1.ets.migrate.ets} | 118 +- .../styles_decorator_mix_1.ets.migrate.json | 17 + .../test/main/styles_decorator_mix_2.ets | 92 + .../main/styles_decorator_mix_2.ets.args.json | 21 + .../styles_decorator_mix_2.ets.arkts2.json | 17 + .../styles_decorator_mix_2.ets.autofix.json | 17 + .../test/main/styles_decorator_mix_2.ets.json | 17 + .../styles_decorator_mix_2.ets.migrate.ets | 92 + .../styles_decorator_mix_2.ets.migrate.json | 17 + .../test/main/styles_decorator_struct_1.ets | 10 +- .../styles_decorator_struct_1.ets.args.json | 3 +- .../styles_decorator_struct_1.ets.arkts2.json | 112 +- ...styles_decorator_struct_1.ets.autofix.json | 160 +- .../main/styles_decorator_struct_1.ets.json | 4 +- .../styles_decorator_struct_1.ets.migrate.ets | 146 + ...styles_decorator_struct_1.ets.migrate.json | 28 + .../test/main/styles_decorator_struct_2.ets | 37 +- .../styles_decorator_struct_2.ets.args.json | 3 +- .../styles_decorator_struct_2.ets.arkts2.json | 24 +- ...styles_decorator_struct_2.ets.autofix.json | 24 +- .../main/styles_decorator_struct_2.ets.json | 4 +- .../styles_decorator_struct_2.ets.migrate.ets | 146 + ...styles_decorator_struct_2.ets.migrate.json | 28 + .../subclass_super_call.ets} | 33 +- .../subclass_super_call.ets.args.json} | 0 .../main/subclass_super_call.ets.arkts2.json | 38 + .../test/main/subclass_super_call.ets.json | 17 + ets2panda/linter/test/main/swicth_expr.ets | 160 +- .../test/main/swicth_expr.ets.arkts2.json | 634 +- .../linter/test/main/swicth_expr.ets.json | 36 +- .../test/main/taskpool_deprecated_usages.ets | 22 + .../taskpool_deprecated_usages.ets.args.json} | 4 +- ...taskpool_deprecated_usages.ets.arkts2.json | 68 + .../main/taskpool_deprecated_usages.ets.json | 28 + .../linter/test/main/ts-like-catch-type.ets | 30 + .../main/ts-like-catch-type.ets.args.json | 19 + .../main/ts-like-catch-type.ets.arkts2.json | 58 + .../test/main/ts-like-catch-type.ets.json | 38 + .../test/main/type_literals.ets.args.json | 5 +- .../type_literals.ets.migrate.ets} | 216 +- .../type_literals.ets.migrate.json} | 468 +- .../linter/test/main/types.ets.args.json | 5 +- .../types.sts => main/types.ets.migrate.ets} | 80 +- .../types.ets.migrate.json} | 338 +- .../test/main/void_operator.ets.args.json | 3 +- .../test/main/void_operator.ets.migrate.ets | 149 + .../test/main/void_operator.ets.migrate.json | 58 + ets2panda/linter/test/main/worker_module.ets | 26 +- .../test/main/worker_module.ets.arkts2.json | 126 +- .../class_static_block.ts.migrate.json | 14 - .../destructuring_assignments.ts.migrate.json | 624 -- ...destructuring_declarations.ts.migrate.json | 494 - .../migrate/function_expression.ts.args.json | 19 - .../function_expression.ts.migrate.json | 334 - .../literals_as_prop_names.ts.args.json | 19 - .../object_literals_autofixes.ts.args.json | 19 - .../migrate/parameter_properties.ts.args.json | 19 - .../parameter_properties.ts.migrate.json | 104 - .../test/migrate/type_literals.ts.args.json | 19 - .../migrate/type_literals.ts.migrate.json | 644 -- .../linter/test/migrate/types.ts.args.json | 19 - .../migrate/void_operator.ts.migrate.json | 104 - .../linter/test/migration/mixed_problems.ets | 54 + .../migration/mixed_problems.ets.args.json | 20 + .../migration/mixed_problems.ets.autofix.json | 303 + .../test/migration/mixed_problems.ets.json | 208 + .../migration/mixed_problems.ets.migrate.ets | 77 + .../migration/mixed_problems.ets.migrate.json | 78 + .../test/ohmurl/ohmurl_import.ets.args.json | 3 +- .../test/ohmurl/ohmurl_import.ets.migrate.ets | 23 + .../ohmurl/ohmurl_import.ets.migrate.json | 17 + .../linter/test/rules/rule1.ets.args.json | 5 +- .../linter/test/rules/rule1.ets.autofix.json | 16 +- .../linter/test/rules/rule1.ets.migrate.ets | 58 + .../linter/test/rules/rule1.ets.migrate.json | 88 + .../linter/test/rules/rule113.ets.args.json | 5 +- .../linter/test/rules/rule113.ets.migrate.ets | 69 + .../test/rules/rule113.ets.migrate.json | 78 + .../linter/test/rules/rule140.ets.args.json | 5 +- .../linter/test/rules/rule140.ets.migrate.ets | 30 + .../test/rules/rule140.ets.migrate.json | 68 + .../linter/test/rules/rule16.ets.args.json | 5 +- .../linter/test/rules/rule16.ets.migrate.ets | 33 + .../linter/test/rules/rule16.ets.migrate.json | 17 + .../linter/test/rules/rule25.ets.args.json | 5 +- .../linter/test/rules/rule25.ets.migrate.ets | 59 + .../linter/test/rules/rule25.ets.migrate.json | 17 + .../linter/test/rules/rule29.ets.args.json | 5 +- .../linter/test/rules/rule29.ets.migrate.ets | 22 + .../linter/test/rules/rule29.ets.migrate.json | 17 + .../linter/test/rules/rule3.ets.args.json | 5 +- .../linter/test/rules/rule3.ets.migrate.ets | 36 + .../linter/test/rules/rule3.ets.migrate.json | 17 + ets2panda/linter/test/rules/rule37.ets | 10 +- .../linter/test/rules/rule37.ets.args.json | 3 +- .../linter/test/rules/rule37.ets.arkts2.json | 40 + .../linter/test/rules/rule37.ets.autofix.json | 68 + .../linter/test/rules/rule37.ets.migrate.ets | 75 + .../linter/test/rules/rule37.ets.migrate.json | 17 + .../linter/test/rules/rule38.ets.args.json | 5 +- .../linter/test/rules/rule38.ets.migrate.ets | 69 + .../rule38.ets.migrate.json} | 104 +- .../linter/test/rules/rule40.ets.args.json | 5 +- .../linter/test/rules/rule40.ets.migrate.ets | 38 + .../linter/test/rules/rule40.ets.migrate.json | 17 + .../linter/test/rules/rule46.ets.args.json | 5 +- .../linter/test/rules/rule46.ets.migrate.ets | 22 + .../linter/test/rules/rule46.ets.migrate.json | 17 + .../linter/test/rules/rule5.ets.args.json | 5 +- .../linter/test/rules/rule5.ets.migrate.ets | 124 + .../rule5.ets.migrate.json} | 776 +- .../linter/test/rules/rule53.ets.args.json | 5 +- .../linter/test/rules/rule53.ets.migrate.ets | 39 + .../linter/test/rules/rule53.ets.migrate.json | 28 + .../linter/test/rules/rule71.ets.args.json | 5 +- .../linter/test/rules/rule71.ets.migrate.ets | 112 + .../linter/test/rules/rule71.ets.migrate.json | 148 + .../linter/test/rules/rule79.ets.args.json | 5 +- .../linter/test/rules/rule79.ets.migrate.ets | 29 + .../linter/test/rules/rule79.ets.migrate.json | 17 + .../linter/test/rules/rule90.ets.args.json | 5 +- .../linter/test/rules/rule90.ets.migrate.ets | 52 + .../linter/test/rules/rule90.ets.migrate.json | 38 + .../linter/test/rules/rule90_1.ets.args.json | 5 +- .../test/rules/rule90_1.ets.migrate.ets | 23 + .../test/rules/rule90_1.ets.migrate.json | 17 + .../linter/test/rules/rule90_2.ets.args.json | 5 +- .../test/rules/rule90_2.ets.migrate.ets | 26 + .../test/rules/rule90_2.ets.migrate.json | 17 + .../linter/test/rules/rule90_3.ets.args.json | 5 +- .../test/rules/rule90_3.ets.migrate.ets | 46 + .../test/rules/rule90_3.ets.migrate.json | 17 + .../linter/test/rules/rule90_4.ets.args.json | 5 +- .../test/rules/rule90_4.ets.migrate.ets | 39 + .../test/rules/rule90_4.ets.migrate.json | 17 + .../linter/test/rules/rule90_5.ets.args.json | 5 +- .../test/rules/rule90_5.ets.migrate.ets | 32 + .../test/rules/rule90_5.ets.migrate.json | 17 + .../linter/test/rules/rule92.ets.args.json | 5 +- .../linter/test/rules/rule92.ets.migrate.ets | 90 + .../linter/test/rules/rule92.ets.migrate.json | 88 + .../linter/test/sdkwhite/ConstructorFuncs.ets | 109 - .../InterfaceExtendsClass.ets.arkts2.json | 19 - ...gs.json => LimitedVoidType3.ets.args.json} | 0 .../sdkwhite/LimitedVoidType3.ets.arkts2.json | 101 +- .../LiteralAsPropertyName2.ets.arkts2.json | 19 - .../sdkwhite/SendablePropType.ets.arkts2.json | 19 - .../sdkwhite/decl_with_duplicate_name_sdk.ets | 60 + ...ecl_with_duplicate_name_sdk.ets.args.json} | 4 +- ...cl_with_duplicate_name_sdk.ets.arkts2.json | 278 + .../decl_with_duplicate_name_sdk.ets.json | 48 + .../test/sdkwhite/limit_void_type_sdk.ets | 60 +- .../limit_void_type_sdk.ets.arkts2.json | 94 +- .../sdkwhite/limit_void_type_sdk.ets.json | 11 +- .../test/sdkwhite/limit_void_type_sdk2.ets | 40 +- .../limit_void_type_sdk2.ets.arkts2.json | 124 +- ...VoidType3.ets => limit_void_type_sdk3.ets} | 19 +- .../limit_void_type_sdk3.ets.args.json} | 2 +- .../limit_void_type_sdk3.ets.arkts2.json} | 118 +- ...ets.json => limit_void_type_sdk3.ets.json} | 0 ...2.ets => literal_as_property_name_sdk.ets} | 3 +- ...literal_as_property_name_sdk.ets.args.json | 19 + ...eral_as_property_name_sdk.ets.arkts2.json} | 190 +- .../literal_as_property_name_sdk.ets.json | 17 + .../quoted_hyphen_props_deprecated_sdk.ets | 231 +- ..._hyphen_props_deprecated_sdk.ets.args.json | 36 +- ...yphen_props_deprecated_sdk.ets.arkts2.json | 610 +- ...uoted_hyphen_props_deprecated_sdk.ets.json | 153 +- .../quoted_hyphen_props_deprecated_sdk2.ets | 117 + ...yphen_props_deprecated_sdk2.ets.args.json} | 4 +- ...phen_props_deprecated_sdk2.ets.arkts2.json | 328 + ...oted_hyphen_props_deprecated_sdk2.ets.json | 28 + .../test/sdkwhite/return_new_interface.ets | 31 + .../return_new_interface.ets.args.json | 19 + .../return_new_interface.ets.arkts2.json | 98 + .../sdkwhite/return_new_interface.ets.json | 58 + .../sdk/declarations/alert_dialog.d.ts | 18 + .../sdkwhite/sdk/declarations/hyperlink.d.ts | 19 + .../sdk/declarations/styled_string.d.ts | 23 + ...ated_sdk.ets => sdk_constructor_funcs.ets} | 0 .../sdk_constructor_funcs.ets.args.json | 19 + ... => sdk_constructor_funcs.ets.arkts2.json} | 0 .../sdkwhite/sdk_constructor_funcs.ets.json | 17 + ...ace4.ets => sdk_ctor_signatures_iface.ets} | 0 .../sdk_ctor_signatures_iface.ets.args.json} | 4 +- ...sdk_ctor_signatures_iface.ets.arkts2.json} | 0 .../sdk_ctor_signatures_iface.ets.json | 17 + ...alMethod1.ets => sdk_optional_methods.ets} | 44 + .../sdk_optional_methods.ets.args.json | 19 + ...n => sdk_optional_methods.ets.arkts2.json} | 56 +- .../sdkwhite/sdk_optional_methods.ets.json | 17 + ...dAccessType.ets => sdk_props_by_index.ets} | 0 .../sdkwhite/sdk_props_by_index.ets.args.json | 19 + ...son => sdk_props_by_index.ets.arkts2.json} | 0 ...e.ets.json => sdk_props_by_index.ets.json} | 0 .../linter/test/sdkwhite/sdk_type_query.ets | 37 +- .../sdkwhite/sdk_type_query.ets.arkts2.json | 274 +- .../test/sdkwhite/sdk_type_query.ets.json | 168 +- .../sendable_class_interface_property_sdk.ets | 1 + ...class_interface_property_sdk.ets.args.json | 19 + ...ass_interface_property_sdk.ets.arkts2.json | 10 +- ...able_class_interface_property_sdk.ets.json | 28 + ets2panda/linter/webpack.config.js | 7 +- 1148 files changed, 75796 insertions(+), 19176 deletions(-) create mode 100644 ets2panda/linter/arkanalyzer/README.en.md create mode 100644 ets2panda/linter/arkanalyzer/README.md create mode 100644 ets2panda/linter/homecheck/.prettierrc create mode 100644 ets2panda/linter/homecheck/README.en.md create mode 100644 ets2panda/linter/homecheck/README.md delete mode 100644 ets2panda/linter/homecheck/resources/internalSdk/@internal/es5.d.ts create mode 100644 ets2panda/linter/homecheck/src/checker/migration/InteropAssignCheck.ts create mode 100644 ets2panda/linter/homecheck/src/checker/migration/InteropBackwardDFACheck.ts create mode 100644 ets2panda/linter/homecheck/src/checker/migration/InteropBoxedTypeCheck.ts create mode 100644 ets2panda/linter/homecheck/src/checker/migration/InteropDynamicObjectLiteralsCheck.ts create mode 100644 ets2panda/linter/homecheck/src/checker/migration/InteropJSModifyPropertyCheck.ts create mode 100644 ets2panda/linter/homecheck/src/checker/migration/InteropRuleInfo.ts create mode 100644 ets2panda/linter/homecheck/src/checker/migration/NoTSLikeAsCheck.ts create mode 100644 ets2panda/linter/homecheck/src/checker/migration/Utils.ts delete mode 100644 ets2panda/linter/homecheck/src/tools/migrationTool/ExportIssue.ts create mode 100644 ets2panda/linter/src/lib/BaseTypeScriptLinter.ts create mode 100644 ets2panda/linter/src/lib/autofixes/AutofixReportHtmlHelper.ts create mode 100644 ets2panda/linter/src/lib/data/BuiltinList.json create mode 100644 ets2panda/linter/src/lib/statistics/FileProblemStatistics.ts create mode 100644 ets2panda/linter/src/lib/statistics/FileStatistics.ts create mode 100644 ets2panda/linter/src/lib/statistics/ProjectStatistics.ts create mode 100644 ets2panda/linter/src/lib/statistics/StatisticsLogger.ts rename ets2panda/linter/src/{cli => lib/ts-compiler}/Compiler.ts (44%) rename ets2panda/linter/src/{cli => lib}/ts-compiler/FormTscOptions.ts (66%) rename ets2panda/linter/src/{cli => lib}/ts-compiler/ResolveSdks.ts (92%) create mode 100644 ets2panda/linter/src/lib/utils/consts/ArkTSUtilsAPI.ts create mode 100644 ets2panda/linter/src/lib/utils/consts/BuiltinWhiteList.ts create mode 100644 ets2panda/linter/src/lib/utils/consts/CollectionsAPI.ts create mode 100644 ets2panda/linter/src/lib/utils/consts/ConcurrentAPI.ts rename ets2panda/linter/{test/sdkwhite/GlobalThisError&TypeQuery.ets => src/lib/utils/consts/Literals.ts} (93%) rename ets2panda/linter/{test/sdkwhite/SendablePropType.ets => src/lib/utils/consts/MethodDeclaration.ts} (85%) rename ets2panda/linter/{test/interop/oh_modules/ts_decorator.ts => src/lib/utils/consts/MethodSignature.ts} (84%) create mode 100644 ets2panda/linter/src/lib/utils/consts/OptionalMethod.ts create mode 100644 ets2panda/linter/src/lib/utils/consts/RuntimeCheckAPI.ts create mode 100644 ets2panda/linter/src/lib/utils/consts/TaskpoolAPI.ts create mode 100644 ets2panda/linter/src/testRunner/Consts.ts create mode 100644 ets2panda/linter/src/testRunner/FileUtil.ts create mode 100644 ets2panda/linter/src/testRunner/LintTest.ts create mode 100644 ets2panda/linter/src/testRunner/MigrateTest.ts create mode 100644 ets2panda/linter/src/testRunner/RunTestFileOptions.ts create mode 100644 ets2panda/linter/src/testRunner/TestFactory.ts create mode 100644 ets2panda/linter/src/testRunner/TestMode.ts create mode 100644 ets2panda/linter/src/testRunner/TestRunnerOptions.ts rename ets2panda/linter/src/{lib/utils/consts/WhiteListProblemType.ts => testRunner/TestUtil.ts} (47%) create mode 100644 ets2panda/linter/test/builtin/builtin_callsignature.ets rename ets2panda/linter/test/{sdkwhite/ConstructorIface4.ets.args.json => builtin/builtin_callsignature.ets.args.json} (100%) create mode 100644 ets2panda/linter/test/builtin/builtin_callsignature.ets.arkts2.json rename ets2panda/linter/test/{main/concurrent_decorator_arkts2.ets.json => builtin/builtin_callsignature.ets.json} (100%) create mode 100644 ets2panda/linter/test/builtin/builtin_not_support_property_descriptor.ets create mode 100644 ets2panda/linter/test/builtin/builtin_not_support_property_descriptor.ets.args.json rename ets2panda/linter/test/{migrate/function_expression.ts.json => builtin/builtin_not_support_property_descriptor.ets.arkts2.json} (31%) create mode 100644 ets2panda/linter/test/builtin/builtin_not_support_property_descriptor.ets.json create mode 100755 ets2panda/linter/test/builtin/builtin_object_getownpropertynames.ets create mode 100755 ets2panda/linter/test/builtin/builtin_object_getownpropertynames.ets.args.json create mode 100755 ets2panda/linter/test/builtin/builtin_object_getownpropertynames.ets.arkts2.json create mode 100644 ets2panda/linter/test/builtin/builtin_object_getownpropertynames.ets.autofix.json rename ets2panda/linter/test/{sdkwhite/api_path_changed.ets.json => builtin/builtin_object_getownpropertynames.ets.json} (100%) create mode 100644 ets2panda/linter/test/builtin/builtin_object_getownpropertynames.ets.migrate.ets rename ets2panda/linter/test/{interop/ts_decorator.ets.json => builtin/builtin_object_getownpropertynames.ets.migrate.json} (100%) create mode 100755 ets2panda/linter/test/builtin/builtin_symbol_iterator.ets rename ets2panda/linter/test/{interop/no_js_await.ets.args.json => builtin/builtin_symbol_iterator.ets.args.json} (100%) create mode 100755 ets2panda/linter/test/builtin/builtin_symbol_iterator.ets.arkts2.json create mode 100755 ets2panda/linter/test/builtin/builtin_symbol_iterator.ets.json create mode 100755 ets2panda/linter/test/builtin/builtin_thisArgs.ets rename ets2panda/linter/test/{sdkwhite/api_path_changed.ets.args.json => builtin/builtin_thisArgs.ets.args.json} (100%) create mode 100755 ets2panda/linter/test/builtin/builtin_thisArgs.ets.arkts2.json create mode 100755 ets2panda/linter/test/builtin/builtin_thisArgs.ets.json rename ets2panda/linter/test/{main => concurrent}/concurrent_decorator_arkts2.ets (87%) rename ets2panda/linter/test/{main => concurrent}/concurrent_decorator_arkts2.ets.args.json (92%) rename ets2panda/linter/test/{main => concurrent}/concurrent_decorator_arkts2.ets.arkts2.json (64%) rename ets2panda/linter/test/{main => concurrent}/concurrent_decorator_arkts2.ets.autofix.json (64%) rename ets2panda/linter/test/{main/sendable_class_interface_property_sdk.ets.json => concurrent/concurrent_decorator_arkts2.ets.json} (100%) create mode 100644 ets2panda/linter/test/concurrent/concurrent_decorator_arkts2.ets.migrate.ets create mode 100644 ets2panda/linter/test/concurrent/concurrent_decorator_arkts2.ets.migrate.json create mode 100644 ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets create mode 100644 ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets.args.json create mode 100644 ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets.arkts2.json create mode 100644 ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets.autofix.json rename ets2panda/linter/test/{sdkwhite/constructor_types_deprecated_sdk.ets.json => concurrent/concurrent_sharedarraybuffer_arkts2.ets.json} (100%) mode change 100755 => 100644 create mode 100644 ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets.migrate.ets create mode 100644 ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets.migrate.json create mode 100644 ets2panda/linter/test/concurrent/no_support_isconcurrent.ets create mode 100644 ets2panda/linter/test/concurrent/no_support_isconcurrent.ets.args.json create mode 100644 ets2panda/linter/test/concurrent/no_support_isconcurrent.ets.arkts2.json create mode 100644 ets2panda/linter/test/concurrent/no_support_isconcurrent.ets.json create mode 100644 ets2panda/linter/test/concurrent/use_limited_and_concurrent.ets create mode 100644 ets2panda/linter/test/concurrent/use_limited_and_concurrent.ets.args.json create mode 100644 ets2panda/linter/test/concurrent/use_limited_and_concurrent.ets.arkts2.json create mode 100644 ets2panda/linter/test/concurrent/use_limited_and_concurrent.ets.autofix.json create mode 100644 ets2panda/linter/test/concurrent/use_limited_and_concurrent.ets.json create mode 100644 ets2panda/linter/test/concurrent/use_limited_and_concurrent.ets.migrate.ets rename ets2panda/linter/test/{main/data_observation_1.ets.json => concurrent/use_limited_and_concurrent.ets.migrate.json} (100%) rename ets2panda/linter/test/{sdkwhite/ComputedPropertyName.ets => interop/binary_operation_js_obj.ets.migrate.ets} (70%) create mode 100644 ets2panda/linter/test/interop/binary_operation_js_obj.ets.migrate.json create mode 100644 ets2panda/linter/test/interop/call_object_methods.ets.migrate.ets create mode 100644 ets2panda/linter/test/interop/call_object_methods.ets.migrate.json create mode 100644 ets2panda/linter/test/interop/increases_decreases_js_obj.ets.migrate.ets create mode 100644 ets2panda/linter/test/interop/increases_decreases_js_obj.ets.migrate.json create mode 100644 ets2panda/linter/test/interop/instantiated_js_obj.ets.migrate.ets create mode 100644 ets2panda/linter/test/interop/instantiated_js_obj.ets.migrate.json create mode 100644 ets2panda/linter/test/interop/interop_equality_judgment.ets.migrate.ets create mode 100644 ets2panda/linter/test/interop/interop_equality_judgment.ets.migrate.json create mode 100644 ets2panda/linter/test/interop/interop_export_js_rules.ets create mode 100644 ets2panda/linter/test/interop/interop_export_js_rules.ets.args.json create mode 100644 ets2panda/linter/test/interop/interop_export_js_rules.ets.arkts2.json create mode 100644 ets2panda/linter/test/interop/interop_export_js_rules.ets.autofix.json create mode 100644 ets2panda/linter/test/interop/interop_export_js_rules.ets.json create mode 100644 ets2panda/linter/test/interop/interop_export_js_rules.ets.migrate.ets create mode 100644 ets2panda/linter/test/interop/interop_export_js_rules.ets.migrate.json create mode 100644 ets2panda/linter/test/interop/interop_import_js.ets.migrate.ets create mode 100644 ets2panda/linter/test/interop/interop_import_js.ets.migrate.json create mode 100644 ets2panda/linter/test/interop/interop_import_js_index.ets.migrate.ets create mode 100644 ets2panda/linter/test/interop/interop_import_js_index.ets.migrate.json rename ets2panda/linter/test/interop/{oh_modules/interop_import_js_rules.js => interop_import_js_rules_js.js} (92%) create mode 100644 ets2panda/linter/test/interop/interop_import_typeof_js.ets.migrate.ets create mode 100644 ets2panda/linter/test/interop/interop_import_typeof_js.ets.migrate.json create mode 100644 ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.migrate.ets create mode 100644 ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.migrate.json create mode 100644 ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.migrate.ets create mode 100644 ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.migrate.json rename ets2panda/linter/test/interop/{no_js_await.ets => no_await_js_promise.ets} (86%) create mode 100755 ets2panda/linter/test/interop/no_await_js_promise.ets.args.json create mode 100755 ets2panda/linter/test/interop/no_await_js_promise.ets.arkts2.json rename ets2panda/linter/test/interop/{no_js_await.ets.json => no_await_js_promise.ets.json} (92%) rename ets2panda/linter/test/interop/{no_js_awai.js => no_await_js_promise_export.js} (100%) create mode 100644 ets2panda/linter/test/interop/object_built_in.ets.arkts2.json create mode 100644 ets2panda/linter/test/interop/object_literal_constructor.ets rename ets2panda/linter/test/interop/{ts_decorator.ets.args.json => object_literal_constructor.ets.args.json} (100%) create mode 100644 ets2panda/linter/test/interop/object_literal_constructor.ets.arkts2.json create mode 100644 ets2panda/linter/test/interop/object_literal_constructor.ets.json create mode 100644 ets2panda/linter/test/interop/object_literal_union_type.ets rename ets2panda/linter/test/{main/sendable_class_interface_property_sdk.ets.args.json => interop/object_literal_union_type.ets.args.json} (100%) create mode 100644 ets2panda/linter/test/interop/object_literal_union_type.ets.arkts2.json create mode 100644 ets2panda/linter/test/interop/object_literal_union_type.ets.json create mode 100644 ets2panda/linter/test/interop/oh_modules/object_literal_constructor.ets create mode 100644 ets2panda/linter/test/interop/oh_modules/object_literal_union_type.ets create mode 100644 ets2panda/linter/test/interop/oh_modules/object_literal_union_type_arkts2.ets create mode 100644 ets2panda/linter/test/interop/oh_modules/static_object_literals_export.ets create mode 100644 ets2panda/linter/test/interop/reflect_built_in.ets.arkts2.json create mode 100644 ets2panda/linter/test/interop/static_dynamic_import.ets create mode 100644 ets2panda/linter/test/interop/static_dynamic_import.ets.args.json create mode 100644 ets2panda/linter/test/interop/static_dynamic_import.ets.arkts2.json rename ets2panda/linter/test/{main/data_observation_2.ets.arkts2.json => interop/static_dynamic_import.ets.json} (100%) create mode 100644 ets2panda/linter/test/interop/static_object_literals.ets rename ets2panda/linter/test/{sdkwhite/GlobalThisError&TypeQuery.ets.arkts2.json => interop/static_object_literals.ets.args.json} (95%) create mode 100644 ets2panda/linter/test/interop/static_object_literals.ets.json create mode 100644 ets2panda/linter/test/interop/test_files/dummy_arkts1_file.ets create mode 100644 ets2panda/linter/test/interop/test_files/dummy_js_file.js create mode 100644 ets2panda/linter/test/interop/test_files/dummy_ts_file.ts create mode 100644 ets2panda/linter/test/interop/unique_types.ets.migrate.ets create mode 100644 ets2panda/linter/test/interop/unique_types.ets.migrate.json create mode 100644 ets2panda/linter/test/main/animatable_extend_decorator_1.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/animatable_extend_decorator_1.ets.migrate.json create mode 100644 ets2panda/linter/test/main/animatable_extend_decorator_2.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/animatable_extend_decorator_2.ets.migrate.json create mode 100644 ets2panda/linter/test/main/arkts-array-type-immutable.ets create mode 100644 ets2panda/linter/test/main/arkts-array-type-immutable.ets.args.json create mode 100644 ets2panda/linter/test/main/arkts-array-type-immutable.ets.arkts2.json rename ets2panda/linter/test/main/{data_observation_2.ets.autofix.json => arkts-array-type-immutable.ets.json} (100%) create mode 100644 ets2panda/linter/test/main/arkts-primitive-type-normalization.ets create mode 100644 ets2panda/linter/test/main/arkts-primitive-type-normalization.ets.args.json create mode 100644 ets2panda/linter/test/main/arkts-primitive-type-normalization.ets.arkts2.json rename ets2panda/linter/test/main/{data_observation_2.ets.json => arkts-primitive-type-normalization.ets.json} (100%) create mode 100644 ets2panda/linter/test/main/arktsutils_module.ets create mode 100644 ets2panda/linter/test/main/arktsutils_module.ets.args.json create mode 100644 ets2panda/linter/test/main/arktsutils_module.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/arktsutils_module.ets.autofix.json rename ets2panda/linter/test/{sdkwhite/ConstructorIface4.ets.json => main/arktsutils_module.ets.json} (100%) create mode 100644 ets2panda/linter/test/main/arktsutils_module.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/arktsutils_module.ets.migrate.json create mode 100644 ets2panda/linter/test/main/array_index_expr_type.ets.autofix.json create mode 100644 ets2panda/linter/test/main/array_index_expr_type.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/array_index_expr_type.ets.migrate.json create mode 100644 ets2panda/linter/test/main/catch_clause.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/catch_clause.ets.migrate.json create mode 100644 ets2panda/linter/test/main/class_no_constructor.ets create mode 100644 ets2panda/linter/test/main/class_no_constructor.ets.args.json create mode 100644 ets2panda/linter/test/main/class_no_constructor.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/class_no_constructor.ets.json create mode 100644 ets2panda/linter/test/main/class_no_constructor.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/class_no_constructor.ets.migrate.json rename ets2panda/linter/test/{migrate/class_static_block.sts => main/class_static_block.ets.migrate.ets} (93%) rename ets2panda/linter/test/{sdkwhite/DeclWithDuplicateName5.ets.json => main/class_static_block.ets.migrate.json} (100%) create mode 100644 ets2panda/linter/test/main/class_static_init.ets.autofix.json rename ets2panda/linter/test/{migrate/void_operator.sts => main/collections_module.ets} (45%) create mode 100644 ets2panda/linter/test/main/collections_module.ets.args.json create mode 100644 ets2panda/linter/test/main/collections_module.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/collections_module.ets.autofix.json rename ets2panda/linter/test/{sdkwhite/GlobalThisError&TypeQuery.ets.json => main/collections_module.ets.json} (100%) create mode 100644 ets2panda/linter/test/main/collections_module.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/collections_module.ets.migrate.json create mode 100644 ets2panda/linter/test/main/custom_layout.ets create mode 100644 ets2panda/linter/test/main/custom_layout.ets.args.json rename ets2panda/linter/test/main/{data_observation_1.ets.arkts2.json => custom_layout.ets.arkts2.json} (61%) rename ets2panda/linter/test/main/{data_observation_1.ets.autofix.json => custom_layout.ets.autofix.json} (51%) create mode 100644 ets2panda/linter/test/main/custom_layout.ets.json create mode 100644 ets2panda/linter/test/main/custom_layout.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/custom_layout.ets.migrate.json rename ets2panda/linter/test/{sdkwhite/InterfaceExtendsClass.ets => main/debugger_statememt.ets.migrate.ets} (84%) rename ets2panda/linter/test/{sdkwhite/InterfaceExtendsClass.ets.json => main/debugger_statememt.ets.migrate.json} (100%) create mode 100644 ets2panda/linter/test/main/default_required_args.ets create mode 100644 ets2panda/linter/test/main/default_required_args.ets.args.json create mode 100644 ets2panda/linter/test/main/default_required_args.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/default_required_args.ets.json rename ets2panda/linter/test/{migrate/destructuring_assignments.sts => main/destructuring_assignments.ets.migrate.ets} (41%) rename ets2panda/linter/test/{migrate/destructuring_assignments.ts.json => main/destructuring_assignments.ets.migrate.json} (60%) rename ets2panda/linter/test/{migrate/destructuring_declarations.sts => main/destructuring_declarations.ets.migrate.ets} (39%) rename ets2panda/linter/test/{migrate/destructuring_declarations.ts.json => main/destructuring_declarations.ets.migrate.json} (58%) create mode 100644 ets2panda/linter/test/main/destructuring_parameters.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/destructuring_parameters.ets.migrate.json create mode 100644 ets2panda/linter/test/main/dollar_binding_1.ets.migrate.ets rename ets2panda/linter/test/{sdkwhite/LiteralAsPropertyName2.ets.json => main/dollar_binding_1.ets.migrate.json} (100%) create mode 100644 ets2panda/linter/test/main/dollar_binding_2.ets.migrate.ets rename ets2panda/linter/test/{sdkwhite/OptionalMethod1.ets.json => main/dollar_binding_2.ets.migrate.json} (100%) create mode 100644 ets2panda/linter/test/main/double_dollar_binding_1.ets.migrate.ets rename ets2panda/linter/test/{sdkwhite/SendablePropType.ets.json => main/double_dollar_binding_1.ets.migrate.json} (100%) create mode 100644 ets2panda/linter/test/main/double_dollar_binding_2.ets.migrate.ets rename ets2panda/linter/test/{sdkwhite/ConstructorFuncs.ets.arkts2.json => main/double_dollar_binding_2.ets.migrate.json} (95%) create mode 100644 ets2panda/linter/test/main/double_excla_binding_1.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/double_excla_binding_1.ets.migrate.json create mode 100644 ets2panda/linter/test/main/double_excla_binding_2.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/double_excla_binding_2.ets.migrate.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test10_1.ets.migrate.ets rename ets2panda/linter/test/{sdkwhite/DeclWithDuplicateName5.ets.arkts2.json => main/entry_annotation_test10_1.ets.migrate.json} (95%) create mode 100644 ets2panda/linter/test/main/entry_annotation_test10_2.ets.migrate.ets rename ets2panda/linter/test/{sdkwhite/ComputedPropertyName.ets.arkts2.json => main/entry_annotation_test10_2.ets.migrate.json} (95%) rename ets2panda/linter/test/{sdkwhite/DeclWithDuplicateName5.ets => main/entry_annotation_test1_1.ets.migrate.ets} (82%) create mode 100644 ets2panda/linter/test/main/entry_annotation_test1_1.ets.migrate.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test1_2.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test1_2.ets.migrate.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test2_1.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test2_1.ets.migrate.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test2_2.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test2_2.ets.migrate.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test3_1.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test3_1.ets.migrate.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test3_2.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test3_2.ets.migrate.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test4_1.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test4_1.ets.migrate.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test4_2.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test4_2.ets.migrate.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test5_1.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test5_1.ets.migrate.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test5_2.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test5_2.ets.migrate.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test6_1.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test6_1.ets.migrate.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test6_2.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test6_2.ets.migrate.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test7_1.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test7_1.ets.migrate.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test7_2.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test7_2.ets.migrate.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test8_1.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test8_1.ets.migrate.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test8_2.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test8_2.ets.migrate.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test9_1.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test9_1.ets.migrate.json create mode 100644 ets2panda/linter/test/main/entry_annotation_test9_2.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/entry_annotation_test9_2.ets.migrate.json create mode 100755 ets2panda/linter/test/main/equals_token_option.ets rename ets2panda/linter/test/{sdkwhite/IndexedAccessType.ets.args.json => main/equals_token_option.ets.args.json} (100%) mode change 100644 => 100755 create mode 100755 ets2panda/linter/test/main/equals_token_option.ets.arkts2.json create mode 100755 ets2panda/linter/test/main/equals_token_option.ets.json rename ets2panda/linter/test/{migrate/func_return_type.ts.migrate.json => main/explicit_function_type.ets.autofix.json} (30%) create mode 100644 ets2panda/linter/test/main/explicit_function_type.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/explicit_function_type.ets.migrate.json create mode 100644 ets2panda/linter/test/main/exponent.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/exponent.ets.migrate.json create mode 100644 ets2panda/linter/test/main/extend_decorator_1.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/extend_decorator_1.ets.migrate.json create mode 100644 ets2panda/linter/test/main/extend_decorator_2.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/extend_decorator_2.ets.migrate.json create mode 100644 ets2panda/linter/test/main/func_inferred_type_args_2.ets create mode 100644 ets2panda/linter/test/main/func_inferred_type_args_2.ets.args.json create mode 100644 ets2panda/linter/test/main/func_inferred_type_args_2.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/func_inferred_type_args_2.ets.autofix.json create mode 100644 ets2panda/linter/test/main/func_inferred_type_args_2.ets.json create mode 100644 ets2panda/linter/test/main/func_inferred_type_args_2.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/func_inferred_type_args_2.ets.migrate.json rename ets2panda/linter/test/{migrate/func_return_type.sts => main/func_return_type.ets.migrate.ets} (77%) rename ets2panda/linter/test/{interop/no_js_await.ets.arkts2.json => main/func_return_type.ets.migrate.json} (66%) mode change 100755 => 100644 rename ets2panda/linter/test/{migrate/function_expression.sts => main/function_expression.ets.migrate.ets} (42%) rename ets2panda/linter/test/{migrate/void_operator.ts.json => main/function_expression.ets.migrate.json} (46%) create mode 100644 ets2panda/linter/test/main/global_this.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/global_this.ets.migrate.json rename ets2panda/linter/test/main/{data_observation_1.ets => interface_import_1.ets.migrate.ets} (37%) create mode 100644 ets2panda/linter/test/main/interface_import_1.ets.migrate.json create mode 100644 ets2panda/linter/test/main/interface_import_2.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/interface_import_2.ets.migrate.json create mode 100644 ets2panda/linter/test/main/lazy_import.ets.autofix.json rename ets2panda/linter/test/{migrate/literals_as_prop_names.sts => main/literals_as_prop_names.ets.migrate.ets} (58%) rename ets2panda/linter/test/{migrate/literals_as_prop_names.ts.json => main/literals_as_prop_names.ets.migrate.json} (60%) create mode 100644 ets2panda/linter/test/main/localBuilder_1.ets rename ets2panda/linter/test/main/{data_observation_2.ets.args.json => localBuilder_1.ets.args.json} (92%) rename ets2panda/linter/test/{interop/ts_decorator.ets.arkts2.json => main/localBuilder_1.ets.arkts2.json} (51%) create mode 100644 ets2panda/linter/test/main/localBuilder_1.ets.autofix.json create mode 100644 ets2panda/linter/test/main/localBuilder_1.ets.json create mode 100644 ets2panda/linter/test/main/localBuilder_1.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/localBuilder_1.ets.migrate.json create mode 100644 ets2panda/linter/test/main/localBuilder_2.ets create mode 100644 ets2panda/linter/test/main/localBuilder_2.ets.args.json create mode 100644 ets2panda/linter/test/main/localBuilder_2.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/localBuilder_2.ets.autofix.json create mode 100644 ets2panda/linter/test/main/localBuilder_2.ets.json create mode 100644 ets2panda/linter/test/main/localBuilder_2.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/localBuilder_2.ets.migrate.json create mode 100644 ets2panda/linter/test/main/make_observed_1.ets create mode 100644 ets2panda/linter/test/main/make_observed_1.ets.args.json rename ets2panda/linter/test/{sdkwhite/api_path_changed.ets.arkts2.json => main/make_observed_1.ets.arkts2.json} (59%) create mode 100644 ets2panda/linter/test/main/make_observed_1.ets.json create mode 100644 ets2panda/linter/test/main/make_observed_2.ets create mode 100644 ets2panda/linter/test/main/make_observed_2.ets.args.json create mode 100644 ets2panda/linter/test/main/make_observed_2.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/make_observed_2.ets.json create mode 100644 ets2panda/linter/test/main/make_observed_3.ets create mode 100644 ets2panda/linter/test/main/make_observed_3.ets.args.json create mode 100644 ets2panda/linter/test/main/make_observed_3.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/make_observed_3.ets.json create mode 100644 ets2panda/linter/test/main/method_inheritance.ets create mode 100644 ets2panda/linter/test/main/method_inheritance.ets.args.json create mode 100644 ets2panda/linter/test/main/method_inheritance.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/method_inheritance.ets.json create mode 100644 ets2panda/linter/test/main/no_enum_prop_as_type.ets create mode 100644 ets2panda/linter/test/main/no_enum_prop_as_type.ets.args.json create mode 100644 ets2panda/linter/test/main/no_enum_prop_as_type.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/no_enum_prop_as_type.ets.json create mode 100644 ets2panda/linter/test/main/no_import_concurrency.ets.autofix.json create mode 100644 ets2panda/linter/test/main/no_import_concurrency.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/no_import_concurrency.ets.migrate.json create mode 100644 ets2panda/linter/test/main/no_sparse_array.ets create mode 100644 ets2panda/linter/test/main/no_sparse_array.ets.args.json create mode 100644 ets2panda/linter/test/main/no_sparse_array.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/no_sparse_array.ets.json create mode 100755 ets2panda/linter/test/main/no_ts_like_smart_type.ets create mode 100755 ets2panda/linter/test/main/no_ts_like_smart_type.ets.args.json create mode 100755 ets2panda/linter/test/main/no_ts_like_smart_type.ets.arkts2.json create mode 100755 ets2panda/linter/test/main/no_ts_like_smart_type.ets.json create mode 100755 ets2panda/linter/test/main/nondecimal-bigint.ets create mode 100755 ets2panda/linter/test/main/nondecimal-bigint.ets.args.json create mode 100755 ets2panda/linter/test/main/nondecimal-bigint.ets.arkts2.json create mode 100755 ets2panda/linter/test/main/nondecimal-bigint.ets.json rename ets2panda/linter/test/{sdkwhite/api_path_changed.ets => main/numeric_bigint_compare.ets} (78%) rename ets2panda/linter/test/main/{data_observation_1.ets.args.json => numeric_bigint_compare.ets.args.json} (93%) mode change 100644 => 100755 create mode 100755 ets2panda/linter/test/main/numeric_bigint_compare.ets.arkts2.json create mode 100755 ets2panda/linter/test/main/numeric_bigint_compare.ets.json create mode 100644 ets2panda/linter/test/main/numeric_semantics.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/numeric_semantics.ets.migrate.json create mode 100644 ets2panda/linter/test/main/object_literals.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/object_literals.ets.migrate.json create mode 100644 ets2panda/linter/test/main/object_literals_2.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/object_literals_2.ets.migrate.json create mode 100644 ets2panda/linter/test/main/object_literals_3.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/object_literals_3.ets.migrate.json create mode 100644 ets2panda/linter/test/main/object_literals_4.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/object_literals_4.ets.migrate.json rename ets2panda/linter/test/{migrate/object_literals_autofixes.sts => main/object_literals_autofixes.ets.migrate.ets} (40%) rename ets2panda/linter/test/{migrate/object_literals_autofixes.ts.json => main/object_literals_autofixes.ets.migrate.json} (37%) create mode 100644 ets2panda/linter/test/main/object_literals_prop_func_type.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/object_literals_prop_func_type.ets.migrate.json rename ets2panda/linter/test/{migrate/object_literals_autofixes.ts.migrate.json => main/object_literals_properties.ets.autofix.json} (30%) create mode 100644 ets2panda/linter/test/main/object_literals_properties.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/object_literals_properties.ets.migrate.json create mode 100644 ets2panda/linter/test/main/object_spread.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/object_spread.ets.migrate.json create mode 100644 ets2panda/linter/test/main/oh_modules/@arkts.collections.d.ets create mode 100644 ets2panda/linter/test/main/oh_modules/@arkts.utils.d.ets create mode 100644 ets2panda/linter/test/main/oh_modules/@kit.ArkTS.d.ets rename ets2panda/linter/test/{interop/oh_modules/reflect_export_safe.ets => main/oh_modules/@ohos.taskpool.d.ets} (80%) create mode 100644 ets2panda/linter/test/main/oh_modules/@ohos.worker.d.ets create mode 100644 ets2panda/linter/test/main/parameter_properties.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/parameter_properties.ets.migrate.json create mode 100644 ets2panda/linter/test/main/private_identifiers.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/private_identifiers.ets.migrate.json create mode 100644 ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets create mode 100644 ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets.args.json create mode 100644 ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets.json create mode 100644 ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets create mode 100644 ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets.args.json create mode 100644 ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets.json create mode 100644 ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets create mode 100644 ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets.args.json create mode 100644 ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets.json create mode 100644 ets2panda/linter/test/main/prop_name_from_value.ets create mode 100644 ets2panda/linter/test/main/prop_name_from_value.ets.args.json rename ets2panda/linter/test/{migrate/class_static_block.ts.json => main/prop_name_from_value.ets.arkts2.json} (73%) create mode 100644 ets2panda/linter/test/main/prop_name_from_value.ets.json create mode 100644 ets2panda/linter/test/main/property_access_by_index.ets.migrate.ets rename ets2panda/linter/test/main/{property_access_by_index.ts.arkts2.json => property_access_by_index.ets.migrate.json} (68%) create mode 100644 ets2panda/linter/test/main/provide_annotation_1.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/provide_annotation_1.ets.migrate.json create mode 100644 ets2panda/linter/test/main/provide_annotation_2.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/provide_annotation_2.ets.migrate.json create mode 100644 ets2panda/linter/test/main/runtime_array_bound.ets create mode 100644 ets2panda/linter/test/main/runtime_array_bound.ets.args.json create mode 100644 ets2panda/linter/test/main/runtime_array_bound.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/runtime_array_bound.ets.json create mode 100644 ets2panda/linter/test/main/runtime_array_bound.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/runtime_array_bound.ets.migrate.json create mode 100644 ets2panda/linter/test/main/sendable_class_inheritance.ets.migrate.ets rename ets2panda/linter/test/{sdkwhite/ConstructorFuncs.ets.json => main/sendable_class_inheritance.ets.migrate.json} (43%) create mode 100644 ets2panda/linter/test/main/sendable_class_inheritance_2.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/sendable_class_inheritance_2.ets.migrate.json create mode 100644 ets2panda/linter/test/main/sendable_decorator_arkts2.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/sendable_decorator_arkts2.ets.migrate.json create mode 100644 ets2panda/linter/test/main/sendable_decorator_limited.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/sendable_decorator_limited.ets.migrate.json create mode 100644 ets2panda/linter/test/main/sendable_explicit_field_type.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/sendable_explicit_field_type.ets.migrate.json rename ets2panda/linter/test/{migrate/parameter_properties.sts => main/sendable_explicit_field_type_2.ets.migrate.ets} (52%) create mode 100644 ets2panda/linter/test/main/sendable_explicit_field_type_2.ets.migrate.json create mode 100644 ets2panda/linter/test/main/sendable_function.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/sendable_function.ets.migrate.json create mode 100644 ets2panda/linter/test/main/sendable_function_2.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/sendable_function_2.ets.migrate.json create mode 100644 ets2panda/linter/test/main/static_class.ets create mode 100644 ets2panda/linter/test/main/static_class.ets.args.json create mode 100644 ets2panda/linter/test/main/static_class.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/static_class.ets.json create mode 100644 ets2panda/linter/test/main/static_class.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/static_class.ets.migrate.json create mode 100644 ets2panda/linter/test/main/styles_decorator_anon_1.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/styles_decorator_anon_1.ets.migrate.json create mode 100644 ets2panda/linter/test/main/styles_decorator_anon_2.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/styles_decorator_anon_2.ets.migrate.json create mode 100644 ets2panda/linter/test/main/styles_decorator_global_1.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/styles_decorator_global_1.ets.migrate.json create mode 100644 ets2panda/linter/test/main/styles_decorator_global_2.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/styles_decorator_global_2.ets.migrate.json create mode 100644 ets2panda/linter/test/main/styles_decorator_mix_1.ets create mode 100644 ets2panda/linter/test/main/styles_decorator_mix_1.ets.args.json rename ets2panda/linter/test/{migrate/func_return_type.ts.json => main/styles_decorator_mix_1.ets.arkts2.json} (33%) create mode 100644 ets2panda/linter/test/main/styles_decorator_mix_1.ets.autofix.json create mode 100644 ets2panda/linter/test/main/styles_decorator_mix_1.ets.json rename ets2panda/linter/test/main/{data_observation_2.ets => styles_decorator_mix_1.ets.migrate.ets} (31%) create mode 100644 ets2panda/linter/test/main/styles_decorator_mix_1.ets.migrate.json create mode 100644 ets2panda/linter/test/main/styles_decorator_mix_2.ets create mode 100644 ets2panda/linter/test/main/styles_decorator_mix_2.ets.args.json create mode 100644 ets2panda/linter/test/main/styles_decorator_mix_2.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/styles_decorator_mix_2.ets.autofix.json create mode 100644 ets2panda/linter/test/main/styles_decorator_mix_2.ets.json create mode 100644 ets2panda/linter/test/main/styles_decorator_mix_2.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/styles_decorator_mix_2.ets.migrate.json create mode 100644 ets2panda/linter/test/main/styles_decorator_struct_1.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/styles_decorator_struct_1.ets.migrate.json create mode 100644 ets2panda/linter/test/main/styles_decorator_struct_2.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/styles_decorator_struct_2.ets.migrate.json rename ets2panda/linter/test/{interop/ts_decorator.ets => main/subclass_super_call.ets} (64%) rename ets2panda/linter/test/{sdkwhite/OptionalMethod1.ets.args.json => main/subclass_super_call.ets.args.json} (100%) create mode 100644 ets2panda/linter/test/main/subclass_super_call.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/subclass_super_call.ets.json create mode 100644 ets2panda/linter/test/main/taskpool_deprecated_usages.ets rename ets2panda/linter/test/{migrate/class_static_block.ts.args.json => main/taskpool_deprecated_usages.ets.args.json} (90%) create mode 100644 ets2panda/linter/test/main/taskpool_deprecated_usages.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/taskpool_deprecated_usages.ets.json create mode 100644 ets2panda/linter/test/main/ts-like-catch-type.ets create mode 100644 ets2panda/linter/test/main/ts-like-catch-type.ets.args.json create mode 100644 ets2panda/linter/test/main/ts-like-catch-type.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/ts-like-catch-type.ets.json rename ets2panda/linter/test/{migrate/type_literals.sts => main/type_literals.ets.migrate.ets} (34%) rename ets2panda/linter/test/{migrate/types.ts.migrate.json => main/type_literals.ets.migrate.json} (31%) rename ets2panda/linter/test/{migrate/types.sts => main/types.ets.migrate.ets} (67%) rename ets2panda/linter/test/{migrate/types.ts.json => main/types.ets.migrate.json} (51%) create mode 100644 ets2panda/linter/test/main/void_operator.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/void_operator.ets.migrate.json delete mode 100644 ets2panda/linter/test/migrate/class_static_block.ts.migrate.json delete mode 100644 ets2panda/linter/test/migrate/destructuring_assignments.ts.migrate.json delete mode 100644 ets2panda/linter/test/migrate/destructuring_declarations.ts.migrate.json delete mode 100644 ets2panda/linter/test/migrate/function_expression.ts.args.json delete mode 100644 ets2panda/linter/test/migrate/function_expression.ts.migrate.json delete mode 100644 ets2panda/linter/test/migrate/literals_as_prop_names.ts.args.json delete mode 100644 ets2panda/linter/test/migrate/object_literals_autofixes.ts.args.json delete mode 100644 ets2panda/linter/test/migrate/parameter_properties.ts.args.json delete mode 100644 ets2panda/linter/test/migrate/parameter_properties.ts.migrate.json delete mode 100644 ets2panda/linter/test/migrate/type_literals.ts.args.json delete mode 100644 ets2panda/linter/test/migrate/type_literals.ts.migrate.json delete mode 100644 ets2panda/linter/test/migrate/types.ts.args.json delete mode 100644 ets2panda/linter/test/migrate/void_operator.ts.migrate.json create mode 100644 ets2panda/linter/test/migration/mixed_problems.ets create mode 100644 ets2panda/linter/test/migration/mixed_problems.ets.args.json create mode 100644 ets2panda/linter/test/migration/mixed_problems.ets.autofix.json create mode 100644 ets2panda/linter/test/migration/mixed_problems.ets.json create mode 100644 ets2panda/linter/test/migration/mixed_problems.ets.migrate.ets create mode 100644 ets2panda/linter/test/migration/mixed_problems.ets.migrate.json create mode 100644 ets2panda/linter/test/ohmurl/ohmurl_import.ets.migrate.ets create mode 100644 ets2panda/linter/test/ohmurl/ohmurl_import.ets.migrate.json create mode 100644 ets2panda/linter/test/rules/rule1.ets.migrate.ets create mode 100644 ets2panda/linter/test/rules/rule1.ets.migrate.json create mode 100644 ets2panda/linter/test/rules/rule113.ets.migrate.ets create mode 100644 ets2panda/linter/test/rules/rule113.ets.migrate.json create mode 100644 ets2panda/linter/test/rules/rule140.ets.migrate.ets create mode 100644 ets2panda/linter/test/rules/rule140.ets.migrate.json create mode 100644 ets2panda/linter/test/rules/rule16.ets.migrate.ets create mode 100644 ets2panda/linter/test/rules/rule16.ets.migrate.json create mode 100644 ets2panda/linter/test/rules/rule25.ets.migrate.ets create mode 100644 ets2panda/linter/test/rules/rule25.ets.migrate.json create mode 100644 ets2panda/linter/test/rules/rule29.ets.migrate.ets create mode 100644 ets2panda/linter/test/rules/rule29.ets.migrate.json create mode 100644 ets2panda/linter/test/rules/rule3.ets.migrate.ets create mode 100644 ets2panda/linter/test/rules/rule3.ets.migrate.json create mode 100644 ets2panda/linter/test/rules/rule37.ets.migrate.ets create mode 100644 ets2panda/linter/test/rules/rule37.ets.migrate.json create mode 100644 ets2panda/linter/test/rules/rule38.ets.migrate.ets rename ets2panda/linter/test/{sdkwhite/ComputedPropertyName.ets.json => rules/rule38.ets.migrate.json} (56%) create mode 100644 ets2panda/linter/test/rules/rule40.ets.migrate.ets create mode 100644 ets2panda/linter/test/rules/rule40.ets.migrate.json create mode 100644 ets2panda/linter/test/rules/rule46.ets.migrate.ets create mode 100644 ets2panda/linter/test/rules/rule46.ets.migrate.json create mode 100644 ets2panda/linter/test/rules/rule5.ets.migrate.ets rename ets2panda/linter/test/{migrate/type_literals.ts.json => rules/rule5.ets.migrate.json} (38%) create mode 100644 ets2panda/linter/test/rules/rule53.ets.migrate.ets create mode 100644 ets2panda/linter/test/rules/rule53.ets.migrate.json create mode 100644 ets2panda/linter/test/rules/rule71.ets.migrate.ets create mode 100644 ets2panda/linter/test/rules/rule71.ets.migrate.json create mode 100644 ets2panda/linter/test/rules/rule79.ets.migrate.ets create mode 100644 ets2panda/linter/test/rules/rule79.ets.migrate.json create mode 100644 ets2panda/linter/test/rules/rule90.ets.migrate.ets create mode 100644 ets2panda/linter/test/rules/rule90.ets.migrate.json create mode 100644 ets2panda/linter/test/rules/rule90_1.ets.migrate.ets create mode 100644 ets2panda/linter/test/rules/rule90_1.ets.migrate.json create mode 100644 ets2panda/linter/test/rules/rule90_2.ets.migrate.ets create mode 100644 ets2panda/linter/test/rules/rule90_2.ets.migrate.json create mode 100644 ets2panda/linter/test/rules/rule90_3.ets.migrate.ets create mode 100644 ets2panda/linter/test/rules/rule90_3.ets.migrate.json create mode 100644 ets2panda/linter/test/rules/rule90_4.ets.migrate.ets create mode 100644 ets2panda/linter/test/rules/rule90_4.ets.migrate.json create mode 100644 ets2panda/linter/test/rules/rule90_5.ets.migrate.ets create mode 100644 ets2panda/linter/test/rules/rule90_5.ets.migrate.json create mode 100644 ets2panda/linter/test/rules/rule92.ets.migrate.ets create mode 100644 ets2panda/linter/test/rules/rule92.ets.migrate.json delete mode 100644 ets2panda/linter/test/sdkwhite/ConstructorFuncs.ets delete mode 100644 ets2panda/linter/test/sdkwhite/InterfaceExtendsClass.ets.arkts2.json rename ets2panda/linter/test/sdkwhite/{constructor_types_deprecated_sdk.ets.args.json => LimitedVoidType3.ets.args.json} (100%) mode change 100755 => 100644 delete mode 100644 ets2panda/linter/test/sdkwhite/LiteralAsPropertyName2.ets.arkts2.json delete mode 100644 ets2panda/linter/test/sdkwhite/SendablePropType.ets.arkts2.json create mode 100755 ets2panda/linter/test/sdkwhite/decl_with_duplicate_name_sdk.ets rename ets2panda/linter/test/{migrate/destructuring_declarations.ts.args.json => sdkwhite/decl_with_duplicate_name_sdk.ets.args.json} (90%) mode change 100644 => 100755 create mode 100644 ets2panda/linter/test/sdkwhite/decl_with_duplicate_name_sdk.ets.arkts2.json create mode 100755 ets2panda/linter/test/sdkwhite/decl_with_duplicate_name_sdk.ets.json rename ets2panda/linter/test/sdkwhite/{LimitedVoidType3.ets => limit_void_type_sdk3.ets} (65%) rename ets2panda/linter/test/{migrate/void_operator.ts.args.json => sdkwhite/limit_void_type_sdk3.ets.args.json} (97%) rename ets2panda/linter/test/{migrate/parameter_properties.ts.json => sdkwhite/limit_void_type_sdk3.ets.arkts2.json} (43%) rename ets2panda/linter/test/sdkwhite/{LimitedVoidType3.ets.json => limit_void_type_sdk3.ets.json} (100%) rename ets2panda/linter/test/sdkwhite/{LiteralAsPropertyName2.ets => literal_as_property_name_sdk.ets} (97%) create mode 100644 ets2panda/linter/test/sdkwhite/literal_as_property_name_sdk.ets.args.json rename ets2panda/linter/test/{migrate/literals_as_prop_names.ts.migrate.json => sdkwhite/literal_as_property_name_sdk.ets.arkts2.json} (36%) create mode 100644 ets2panda/linter/test/sdkwhite/literal_as_property_name_sdk.ets.json mode change 100755 => 100644 ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk.ets mode change 100755 => 100644 ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk.ets.args.json mode change 100755 => 100644 ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk.ets.arkts2.json create mode 100755 ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk2.ets rename ets2panda/linter/test/{migrate/func_return_type.ts.args.json => sdkwhite/quoted_hyphen_props_deprecated_sdk2.ets.args.json} (90%) mode change 100644 => 100755 create mode 100755 ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk2.ets.arkts2.json create mode 100755 ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk2.ets.json create mode 100644 ets2panda/linter/test/sdkwhite/return_new_interface.ets create mode 100644 ets2panda/linter/test/sdkwhite/return_new_interface.ets.args.json create mode 100644 ets2panda/linter/test/sdkwhite/return_new_interface.ets.arkts2.json create mode 100644 ets2panda/linter/test/sdkwhite/return_new_interface.ets.json create mode 100644 ets2panda/linter/test/sdkwhite/sdk/declarations/alert_dialog.d.ts create mode 100644 ets2panda/linter/test/sdkwhite/sdk/declarations/hyperlink.d.ts create mode 100644 ets2panda/linter/test/sdkwhite/sdk/declarations/styled_string.d.ts rename ets2panda/linter/test/sdkwhite/{constructor_types_deprecated_sdk.ets => sdk_constructor_funcs.ets} (100%) create mode 100755 ets2panda/linter/test/sdkwhite/sdk_constructor_funcs.ets.args.json rename ets2panda/linter/test/sdkwhite/{constructor_types_deprecated_sdk.ets.arkts2.json => sdk_constructor_funcs.ets.arkts2.json} (100%) create mode 100755 ets2panda/linter/test/sdkwhite/sdk_constructor_funcs.ets.json rename ets2panda/linter/test/sdkwhite/{ConstructorIface4.ets => sdk_ctor_signatures_iface.ets} (100%) rename ets2panda/linter/test/{migrate/destructuring_assignments.ts.args.json => sdkwhite/sdk_ctor_signatures_iface.ets.args.json} (90%) rename ets2panda/linter/test/sdkwhite/{ConstructorIface4.ets.arkts2.json => sdk_ctor_signatures_iface.ets.arkts2.json} (100%) create mode 100644 ets2panda/linter/test/sdkwhite/sdk_ctor_signatures_iface.ets.json rename ets2panda/linter/test/sdkwhite/{OptionalMethod1.ets => sdk_optional_methods.ets} (50%) create mode 100644 ets2panda/linter/test/sdkwhite/sdk_optional_methods.ets.args.json rename ets2panda/linter/test/sdkwhite/{OptionalMethod1.ets.arkts2.json => sdk_optional_methods.ets.arkts2.json} (54%) create mode 100644 ets2panda/linter/test/sdkwhite/sdk_optional_methods.ets.json rename ets2panda/linter/test/sdkwhite/{IndexedAccessType.ets => sdk_props_by_index.ets} (100%) create mode 100644 ets2panda/linter/test/sdkwhite/sdk_props_by_index.ets.args.json rename ets2panda/linter/test/sdkwhite/{IndexedAccessType.ets.arkts2.json => sdk_props_by_index.ets.arkts2.json} (100%) rename ets2panda/linter/test/sdkwhite/{IndexedAccessType.ets.json => sdk_props_by_index.ets.json} (100%) rename ets2panda/linter/test/{main => sdkwhite}/sendable_class_interface_property_sdk.ets (92%) create mode 100644 ets2panda/linter/test/sdkwhite/sendable_class_interface_property_sdk.ets.args.json rename ets2panda/linter/test/{main => sdkwhite}/sendable_class_interface_property_sdk.ets.arkts2.json (74%) create mode 100644 ets2panda/linter/test/sdkwhite/sendable_class_interface_property_sdk.ets.json diff --git a/ets2panda/linter/.prettierignore b/ets2panda/linter/.prettierignore index fd9022d71a..3bde64241c 100644 --- a/ets2panda/linter/.prettierignore +++ b/ets2panda/linter/.prettierignore @@ -1,5 +1,5 @@ # -# Copyright (c) 2023-2024 Huawei Device Co., Ltd. +# Copyright (c) 2023-2025 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -22,5 +22,7 @@ /scripts/** /test/** /third_party/** +/arkanalyzer/** +/homecheck/** **.json **.js diff --git a/ets2panda/linter/BUILD.gn b/ets2panda/linter/BUILD.gn index 724e7ced23..e2071e83da 100644 --- a/ets2panda/linter/BUILD.gn +++ b/ets2panda/linter/BUILD.gn @@ -22,13 +22,11 @@ action("build_linter") { sources = [ "./package.json", "./src/cli/CommandLineParser.ts", - "./src/cli/Compiler.ts", "./src/cli/ConsoleLogger.ts", "./src/cli/LinterCLI.ts", "./src/cli/LoggerImpl.ts", "./src/cli/main.ts", - "./src/cli/ts-compiler/FormTscOptions.ts", - "./src/cli/ts-compiler/ResolveSdks.ts", + "./src/lib/BaseTypeScriptLinter.ts", "./src/lib/CommandLineOptions.ts", "./src/lib/CookBookMsg.ts", "./src/lib/FaultAttrs.ts", @@ -49,8 +47,16 @@ action("build_linter") { "./src/lib/TypeScriptLinterConfig.ts", "./src/lib/autofixes/AutofixTitles.ts", "./src/lib/autofixes/Autofixer.ts", + "./src/lib/autofixes/QuasiEditor.ts", "./src/lib/autofixes/ReportAutofixCallback.ts", "./src/lib/autofixes/SymbolCache.ts", + "./src/lib/statistics/FileProblemStatistics.ts", + "./src/lib/statistics/FileStatistics.ts", + "./src/lib/statistics/ProjectStatistics.ts", + "./src/lib/statistics/StatisticsLogger.ts", + "./src/lib/ts-compiler/Compiler.ts", + "./src/lib/ts-compiler/FormTscOptions.ts", + "./src/lib/ts-compiler/ResolveSdks.ts", "./src/lib/ts-diagnostics/GetTscDiagnostics.ts", "./src/lib/ts-diagnostics/TSCCompiledProgram.ts", "./src/lib/ts-diagnostics/TransformTscDiagnostics.ts", diff --git a/ets2panda/linter/arkanalyzer/.prettierrc b/ets2panda/linter/arkanalyzer/.prettierrc index 2e3d95a2a6..4d939fa56d 100644 --- a/ets2panda/linter/arkanalyzer/.prettierrc +++ b/ets2panda/linter/arkanalyzer/.prettierrc @@ -4,7 +4,8 @@ "useTabs": false, "semi": true, "singleQuote": true, - "printWidth": 120, + "printWidth": 160, "quoteProps": "as-needed", - "arrowParens": "always" + "arrowParens": "avoid", + "bracketSpacing": true } \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/README.en.md b/ets2panda/linter/arkanalyzer/README.en.md new file mode 100644 index 0000000000..2c336a4d1b --- /dev/null +++ b/ets2panda/linter/arkanalyzer/README.en.md @@ -0,0 +1,96 @@ +# sig_programanalysis + +English | [简体中文](./README.md) + +## SIG Group Work Objectives and Scope + +### Work Objectives + +* Sig_programanalysis aims to carry out program analysis technology exploration, key technology identification, and competitiveness building for OpenHarmony systems and apps, striving to become the gathering place for OpenHarmony system and app analysis capabilities and an incubation place for related engineering tools. + +* Sig_programanalysis will build a basic program analysis framework for OpenHarmony apps, and subsequently based on it to provide application developers with out-of-the-box defect scanning and analysis tools, making it possible to automatically vet code for scenarios such as IDE, CI/CD pipelines, etc. + +### Work Scope + +* Responsible for building and maintaining the key technology map of program analysis, as well as the decomposition of functional modules in the field, interface definition, and maintenance management. + +* Responsible for the architecture design, open source development, and project maintenance of projects related to program analysis. + + +### Projects + +Sig_programanalysis currently incubates the following projects. Everyone is welcome to participate (you can apply to participate in the co-construction of existing projects, or you can apply to create a new program analysis project). + + +* ArkAnalyzer: +The Static Analysis Framework for ArkTS-based OpenHarmony Apps. + +* ArkCheck: +Checking OpenHarmony Apps for Potential Code-level Defects + + +## SIG Members + + +### Leader + +- [lilicoding](https://gitee.com/lilicoding) + + +### Committers +- [kubigao](https://gitee.com/kubigao) +- [yifei-xue](https://gitee.com/yifei_xue) +- [kubrick-hjh](https://gitee.com/kubrick-hjh) +- [speed9](https://gitee.com/speeds) +- [bbsun](https://gitee.com/bbsun) +- [chn](https://gitee.com/chn) +- [Elouan](https://gitee.com/Elouan) +- [Rnine](https://gitee.com/Rnine) +- [workspace_cb](https://gitee.com/workspace_cb) +- [longyuC](https://gitee.com/longyuC) +- [xyji95](https://gitee.com/xyji95) +- [xulingyun-red](https://gitee.com/xulingyun-red) + + +### Meetings + - Meeting Time: Bi-weekly meeting, Thursday 19:30 Beijing time + - Meeting Application:[Link](https://shimo.im/forms/B1Awd60W7bU51g3m/fill) + - Meeting Link: Welink or Others + - Meeting Notification: [Subscribe to](https://lists.openatom.io/postorius/lists/dev.openharmony.io) mailing list dev@openharmony.io for the meeting link + - Meeting Summary: [Archive link address](https://gitee.com/openharmony-sig/sig-content) + +### Contact + +- Mailing list: [dev@openharmony.io](https://lists.openatom.io/postorius/lists/dev@openharmony.io/) + +*** +# ArkAnalyzer: Static Program Analysis Framework for the ArkTS Language +## Develope environment setup +1. [Download Visual Studio Code](https://code.visualstudio.com/download) or other IDEA; +2. +3. Install Typescript via npm: +```shell +npm install -g typescript +``` +4. Install dependency libraries +```shell +cd arkanalyzer +npm install +``` +5. [Optional] Generate the latest API documentation, which will be created at docs/api_docs. +```shell +npm run gendoc +``` + +## Docmentations + +1. ArkAnalyzer API docmentations,refer to the [link](https://gitcode.com/openharmony-sig/arkanalyzer/wiki/globals.md). + +## Commit codes +Follow the code repository standards of Openharmony-Sig, refer to the [link](docs/HowToCreatePR.md#english) + +## Debug +Modify the `args` parameter array in the debug configuration file `.vscode/launch.json` to the path of the test file you want to debug, and then start the debugging process. + +## Add test cases +Place all new test codes in the `tests` directory. Corresponding sample code and other resource files should be placed in the ``tests\resources` directory, and create different folders for each testing scenario. \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/README.md b/ets2panda/linter/arkanalyzer/README.md new file mode 100644 index 0000000000..068993e9ab --- /dev/null +++ b/ets2panda/linter/arkanalyzer/README.md @@ -0,0 +1,107 @@ +# sig_programanalysis + +简体中文 | [English](./README.en.md) + +说明:本SIG的内容遵循OpenHarmony的PMC管理章程 [README](../../zh/pmc.md)中描述的约定。 + + +## SIG组工作目标和范围 + + + +### 工作目标 + +* 程序分析-SIG(Sig_programanalysis) 旨在面向OpenHarmony系统和原生应用开展程序分析技术洞察、关键技术识别和竞争力构建,同时成为OpenHarmony系统和应用程序分析能力的聚集地和相关工程工具的孵化地。 + +* 程序分析-SIG(Sig_programanalysis)将面向OpenHarmony应用构建基础程序分析框架并基于此为应用开发者提供开箱即用的缺陷扫描分析工具,面向IDE、流水线门禁、应用市场上架审核等场景,打造自动化工具看护能力。 + +### 工作范围 + +* 负责程序分析子领域关键根技术梳理,以及领域内功能模块分解、接口定义与维护管理等工作。 + +* 负责程序分析子领域相关项目的架构设计、开源开发和项目维护等工作。 + + +### 项目孵化 + +程序分析-SIG(Sig_programanalysis)正积极孵化如下项目,欢迎大家参与共享共建(可申请参与已有项目的共建,也可申请创建新的程序分析项目并联合社区启动开源共建)。 + + +* 方舟分析器(ArkAnalyzer): + 面向ArkTS的OpenHarmony应用程序分析框架。 + +* 方舟检测器(ArkCheck): + 面向OpenHarmony应用开发提供代码级缺陷自动检测(I期聚焦高性能编码规则的自动化检测) + + + +## SIG组成员 + + +### Leader + +- [lilicoding](https://gitcode.com/lilicoding) + + +### Committers列表 +- [kubigao](https://gitcode.com/kubigao) +- [yifei-xue](https://gitcode.com/yifei-xue) +- [kubrick-hjh](https://gitcode.com/kubrick-hjh) +- [speed9](https://gitee.com/speeds) +- [bbsun](https://gitcode.com/bbsun) +- [chn](https://gitcode.com/chn) +- [Elouan](https://gitcode.com/Elouan) +- [Rnine](https://gitcode.com/Rnine1) +- [workspace_cb](https://gitee.com/workspace_cb) +- [longyuC](https://gitee.com/longyuC) +- [xyji95](https://gitcode.com/xyji95) +- [xulingyun](https://gitcode.com/muya318) + + +### 会议 + - 会议时间:双周例会,周四晚上19:00, UTC+8 + - 会议申报:[申报链接](https://shimo.im/forms/B1Awd60W7bU51g3m/fill) + - 会议链接: + - 会议通知:请[订阅](https://lists.openatom.io/postorius/lists/dev.openharmony.io)邮件列表 dev@openharmony.io 获取会议链接 + - 会议纪要:[归档链接地址](https://gitee.com/openharmony-sig/sig-content) + + +### Contact (optional) + +- 邮件列表:[dev@openharmony.io](https://lists.openatom.io/postorius/lists/dev@openharmony.io/) + +*** + +# 方舟分析器:面向ArkTS语言的静态程序分析框架 +## ArkAnalyzer 环境配置 +1. 从[Download Visual Studio Code](https://code.visualstudio.com/download)下载vscode并安装,或安装其他IDE。 +2. +3. 通过npm安装TypeScript编译器,命令行输入 +```shell +npm install -g typescript +``` +4. 安装依赖库 +```shell +npm install +``` +5. 【可选】生成新API文档,文档生成在 docs/api_docs。 +```shell +npm run gendoc +``` + +## ArkAnalyzer 文档 + +1. ArkAnalyzer 快速入门文档,请参考:[链接](https://gitcode.com/openharmony-sig/arkanalyzer/wiki/ArkAnalyzer%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8%E6%8C%87%E5%8D%97.md)。 +2. ArkAnalyzer API文档,请参考:[链接](https://gitcode.com/openharmony-sig/arkanalyzer/wiki/globals.md)。 + +## ArkAnalyzer 代码上库 +遵守openharmony-sig代码上库规范, 操作方法请参考:[链接](docs/HowToCreatePR.md#中文) + +## ArkAnalyzer 调试 +将调试配置文件`.vscode/launch.json`中`args`参数数组修改为想要调试的文件路径,然后启动调试。 + +## 添加自验证测试用例 +新增测试代码统一放至`tests`目录下,对应的样例代码和资源文件统一放至`tests\resources`,按测试场景创建不同文件夹。 + +## ArkAnalyzer Issues +请参考[连接](docs/HowToHandleIssues.md)提交Issues。 diff --git a/ets2panda/linter/arkanalyzer/config/arkanalyzer.json b/ets2panda/linter/arkanalyzer/config/arkanalyzer.json index 26c5953b47..fe0c60bdc4 100644 --- a/ets2panda/linter/arkanalyzer/config/arkanalyzer.json +++ b/ets2panda/linter/arkanalyzer/config/arkanalyzer.json @@ -2,6 +2,7 @@ "supportFileExts": [ ".ets", ".ts", + ".js", ".d.ets", ".d.ts" ], @@ -9,12 +10,12 @@ "ignoreFileNames": [ "oh_modules", "node_modules", - "hvigorfile.ts", - "build-tools" + "build-tools", + "hvigorfile.ts" ], "sdkGlobalFolders": [ "component", "@internal" ], "tsconfig": "tsconfig.json" -} +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/package.json b/ets2panda/linter/arkanalyzer/package.json index 902be5d33d..a9d42adc13 100644 --- a/ets2panda/linter/arkanalyzer/package.json +++ b/ets2panda/linter/arkanalyzer/package.json @@ -18,16 +18,8 @@ "copyCollectionDefintion": "ts-node script/typescriptCollectionDefinitionCopy.ts" }, "dependencies": { - "commander": "11.0.0", - "log4js": "6.7.1" - }, - "bundleDependencies": [ - "ohos-typescript" - ], - "devDependencies": { - "@vitest/coverage-v8": "^1.5.0", - "ts-node": "^10.9.1", - "typedoc": "^0.25.13", - "vitest": "^1.5.0" + "commander": "^9.4.0", + "log4js": "^6.4.0", + "json5": "2.2.3" } } diff --git a/ets2panda/linter/arkanalyzer/script/typescriptCollectionDefinitionCopy.ts b/ets2panda/linter/arkanalyzer/script/typescriptCollectionDefinitionCopy.ts index eb4d3476e3..f44aa17f8a 100644 --- a/ets2panda/linter/arkanalyzer/script/typescriptCollectionDefinitionCopy.ts +++ b/ets2panda/linter/arkanalyzer/script/typescriptCollectionDefinitionCopy.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/ets2panda/linter/arkanalyzer/src/Config.ts b/ets2panda/linter/arkanalyzer/src/Config.ts index 24178d2b5b..bff8ddf474 100644 --- a/ets2panda/linter/arkanalyzer/src/Config.ts +++ b/ets2panda/linter/arkanalyzer/src/Config.ts @@ -35,7 +35,6 @@ export interface TsConfig { [key: string]: string[]; }; }; - } export type SceneOptionsValue = string | number | boolean | (string | number)[] | string[] | null | undefined; @@ -43,7 +42,7 @@ export interface SceneOptions { supportFileExts?: string[]; ignoreFileNames?: string[]; enableLeadingComments?: boolean; - enableTrailingComments?:boolean + enableTrailingComments?: boolean; tsconfig?: string; isScanAbc?: boolean; sdkGlobalFolders?: string[]; @@ -84,12 +83,7 @@ export class SceneConfig { * @param sdks - sdks used in this scene. * @param fullFilePath - the full file path. */ - public buildConfig( - targetProjectName: string, - targetProjectDirectory: string, - sdks: Sdk[], - fullFilePath?: string[] - ) { + public buildConfig(targetProjectName: string, targetProjectDirectory: string, sdks: Sdk[], fullFilePath?: string[]): void { this.targetProjectName = targetProjectName; this.targetProjectDirectory = targetProjectDirectory; this.sdksObj = sdks; @@ -111,18 +105,19 @@ export class SceneConfig { sceneConfig.buildFromProjectDir(projectDir); ``` */ - public buildFromProjectDir(targetProjectDirectory: string) { + public buildFromProjectDir(targetProjectDirectory: string): void { this.targetProjectDirectory = targetProjectDirectory; this.targetProjectName = path.basename(targetProjectDirectory); - this.projectFiles = getAllFiles( - targetProjectDirectory, - this.options.supportFileExts!, - this.options.ignoreFileNames - ); + this.projectFiles = getAllFiles(targetProjectDirectory, this.options.supportFileExts!, this.options.ignoreFileNames); } - public buildFromProjectFiles(projectName: string, projectDir: string, filesAndDirectorys: string[], sdks?: Sdk[], - languageTags?: Map): void { + public buildFromProjectFiles( + projectName: string, + projectDir: string, + filesAndDirectorys: string[], + sdks?: Sdk[], + languageTags?: Map + ): void { if (sdks) { this.sdksObj = sdks; } @@ -140,13 +135,13 @@ export class SceneConfig { private processFilePaths(fileOrDirectory: string, projectDir: string): void { let absoluteFilePath = ''; - if (fileOrDirectory.includes(projectDir)) { + if (path.isAbsolute(fileOrDirectory)) { absoluteFilePath = fileOrDirectory; } else { absoluteFilePath = path.join(projectDir, fileOrDirectory); } if (fs.statSync(absoluteFilePath).isDirectory()) { - getAllFiles(absoluteFilePath, this.getOptions().supportFileExts!, this.options.ignoreFileNames).forEach((filePath) => { + getAllFiles(absoluteFilePath, this.getOptions().supportFileExts!, this.options.ignoreFileNames).forEach(filePath => { if (!this.projectFiles.includes(filePath)) { this.projectFiles.push(filePath); } @@ -158,22 +153,21 @@ export class SceneConfig { private setLanguageTagForFiles(fileOrDirectory: string, projectDir: string, languageTag: Language): void { let absoluteFilePath = ''; - if (fileOrDirectory.includes(projectDir)) { + if (path.isAbsolute(fileOrDirectory)) { absoluteFilePath = fileOrDirectory; } else { absoluteFilePath = path.join(projectDir, fileOrDirectory); } if (fs.statSync(absoluteFilePath).isDirectory()) { - getAllFiles(absoluteFilePath, this.getOptions().supportFileExts!, this.options.ignoreFileNames) - .forEach((filePath) => { - this.fileLanguages.set(filePath, languageTag); - }); + getAllFiles(absoluteFilePath, this.getOptions().supportFileExts!, this.options.ignoreFileNames).forEach(filePath => { + this.fileLanguages.set(filePath, languageTag); + }); } else { this.fileLanguages.set(absoluteFilePath, languageTag); } } - public buildFromJson(configJsonPath: string) { + public buildFromJson(configJsonPath: string): void { if (fs.existsSync(configJsonPath)) { let configurationsText: string; try { @@ -193,9 +187,7 @@ export class SceneConfig { } const targetProjectName: string = configurations.targetProjectName ? configurations.targetProjectName : ''; - const targetProjectDirectory: string = configurations.targetProjectDirectory - ? configurations.targetProjectDirectory - : ''; + const targetProjectDirectory: string = configurations.targetProjectDirectory ? configurations.targetProjectDirectory : ''; const sdks: Sdk[] = configurations.sdks ? configurations.sdks : []; if (configurations.options) { @@ -208,15 +200,15 @@ export class SceneConfig { } } - public getTargetProjectName() { + public getTargetProjectName(): string { return this.targetProjectName; } - public getTargetProjectDirectory() { + public getTargetProjectDirectory(): string { return this.targetProjectDirectory; } - public getProjectFiles() { + public getProjectFiles(): string[] { return this.projectFiles; } @@ -224,19 +216,19 @@ export class SceneConfig { return this.fileLanguages; } - public getSdkFiles() { + public getSdkFiles(): string[] { return this.sdkFiles; } - public getSdkFilesMap() { + public getSdkFilesMap(): Map { return this.sdkFilesMap; } - public getEtsSdkPath() { + public getEtsSdkPath(): string { return this.etsSdkPath; } - public getSdksObj() { + public getSdksObj(): Sdk[] { return this.sdksObj; } diff --git a/ets2panda/linter/arkanalyzer/src/Scene.ts b/ets2panda/linter/arkanalyzer/src/Scene.ts index 02e26abc46..72c7828226 100644 --- a/ets2panda/linter/arkanalyzer/src/Scene.ts +++ b/ets2panda/linter/arkanalyzer/src/Scene.ts @@ -51,8 +51,8 @@ enum SceneBuildStage { CLASS_COLLECTED, METHOD_COLLECTED, SDK_INFERRED, - TYPE_INFERRED -}; + TYPE_INFERRED, +} /** * The Scene class includes everything in the analyzed project. @@ -85,7 +85,7 @@ export class Scene { private ohPkgContent: { [k: string]: unknown } = {}; private overRides: Map = new Map(); private overRideDependencyMap: Map = new Map(); - private globalModule2PathMapping?: { [k: string]: string[]; } | undefined; + private globalModule2PathMapping?: { [k: string]: string[] } | undefined; private baseUrl?: string | undefined; private buildStage: SceneBuildStage = SceneBuildStage.BUILD_INIT; @@ -97,8 +97,7 @@ export class Scene { private unhandledFilePaths: string[] = []; private unhandledSdkFilePaths: string[] = []; - constructor() { - } + constructor() {} public getOptions(): SceneOptions { return this.options; @@ -155,7 +154,7 @@ export class Scene { scene.buildSceneFromProjectDir(sceneConfig); ``` */ - public buildSceneFromProjectDir(sceneConfig: SceneConfig) { + public buildSceneFromProjectDir(sceneConfig: SceneConfig): void { this.buildBasicInfo(sceneConfig); this.genArkFiles(); } @@ -195,7 +194,7 @@ export class Scene { } // handle sdks - sceneConfig.getSdksObj()?.forEach((sdk) => { + sceneConfig.getSdksObj()?.forEach(sdk => { if (!sdk.moduleName) { this.buildSdk(sdk.name, sdk.path); this.projectSdkMap.set(sdk.name, sdk); @@ -225,7 +224,7 @@ export class Scene { const buildProfileJson = parseJsonText(configurationsText); const modules = buildProfileJson.modules; if (modules instanceof Array) { - modules.forEach((module) => { + modules.forEach(module => { this.modulePath2NameMap.set(path.resolve(this.realProjectDir, path.join(module.srcPath)), module.name); }); } @@ -253,7 +252,6 @@ export class Scene { this.overRideDependencyMap.set(key, globalDependency); } } - } else { logger.warn('This project has no oh-package.json5!'); } @@ -298,28 +296,37 @@ export class Scene { private buildAllMethodBody(): void { this.buildStage = SceneBuildStage.CLASS_DONE; + const methods: ArkMethod[] = []; for (const file of this.getFiles()) { for (const cls of file.getClasses()) { for (const method of cls.getMethods(true)) { - method.buildBody(); - method.freeBodyBuilder(); + methods.push(method); } } } for (const namespace of this.getNamespacesMap().values()) { for (const cls of namespace.getClasses()) { for (const method of cls.getMethods(true)) { - method.buildBody(); - method.freeBodyBuilder(); + methods.push(method); } } } + for (const method of methods) { + try { + method.buildBody(); + } catch (error) { + logger.error('Error building body:', method.getSignature(), error); + } finally { + method.freeBodyBuilder(); + } + } + this.buildStage = SceneBuildStage.METHOD_DONE; } - private genArkFiles() { - this.projectFiles.forEach((file) => { + private genArkFiles(): void { + this.projectFiles.forEach(file => { logger.info('=== parse file:', file); try { const arkFile: ArkFile = new ArkFile(FileUtils.getFileLanguage(file, this.fileLanguages)); @@ -426,7 +433,7 @@ export class Scene { private findDependenciesByTsConfig(from: string, arkFile: ArkFile): void { if (this.globalModule2PathMapping) { const paths: { [k: string]: string[] } = this.globalModule2PathMapping; - Object.keys(paths).forEach((key) => this.parseTsConfigParms(paths, key, from, arkFile)); + Object.keys(paths).forEach(key => this.parseTsConfigParms(paths, key, from, arkFile)); } } @@ -436,7 +443,7 @@ export class Scene { this.processFuzzyMapping(key, from, module2pathMapping, arkFile); } else if (from.startsWith(key)) { let tail = from.substring(key.length, from.length); - module2pathMapping.forEach((pathMapping) => { + module2pathMapping.forEach(pathMapping => { let originPath = path.join(this.getRealProjectDir(), pathMapping, tail); if (this.baseUrl) { originPath = path.resolve(this.baseUrl, originPath); @@ -450,7 +457,7 @@ export class Scene { key = key.substring(0, key.indexOf(ALL) - 1); if (from.substring(0, key.indexOf(ALL) - 1) === key) { let tail = from.substring(key.indexOf(ALL) - 1, from.length); - module2pathMapping.forEach((pathMapping) => { + module2pathMapping.forEach(pathMapping => { pathMapping = pathMapping.substring(0, pathMapping.indexOf(ALL) - 1); let originPath = path.join(this.getRealProjectDir(), pathMapping, tail); if (this.baseUrl) { @@ -462,7 +469,7 @@ export class Scene { } private findDependenciesByRule(originPath: string, arkFile: ArkFile): void { - const extNameArray = ['.ets', '.ts', '.d.ets', '.d.ts']; + const extNameArray = ['.ets', '.ts', '.d.ets', '.d.ts', '.js']; if (!this.findFilesByPathArray(originPath, this.indexPathArray, arkFile) && !this.findFilesByExtNameArray(originPath, extNameArray, arkFile)) { logger.info(originPath + 'module mapperInfo is not found!'); } @@ -490,11 +497,10 @@ export class Scene { return false; } - private findRelativeDependenciesByOhPkg(from: string, arkFile: ArkFile): void { //relative path ../from ./from //order - //1. ../from/oh-package.json5 -> [[name]] -> overRides/overRideDependencyMap? -> + //1. ../from/oh-package.json5 -> [[name]] -> overRides/overRideDependencyMap? -> //[[main]] -> file path ->dependencies(priority)+devDependencies? dynamicDependencies(not support) -> //key overRides/overRideDependencyMap? //2. ../from/index.ets(ts) @@ -511,9 +517,14 @@ export class Scene { this.findDependenciesByRule(originPath, arkFile); } - private findDependenciesByOhPkg(ohPkgContentPath: string, ohPkgContentInfo: { - [k: string]: unknown - }, from: string, arkFile: ArkFile): void { + private findDependenciesByOhPkg( + ohPkgContentPath: string, + ohPkgContentInfo: { + [k: string]: unknown; + }, + from: string, + arkFile: ArkFile + ): void { //module name @ohos/from const ohPkgContent: { [k: string]: unknown } | undefined = ohPkgContentInfo; //module main name is must be @@ -560,9 +571,9 @@ export class Scene { this.filesMap.set(arkFile.getFileSignature().toMapKey(), arkFile); } - private buildSdk(sdkName: string, sdkPath: string) { + private buildSdk(sdkName: string, sdkPath: string): void { const allFiles = getAllFiles(sdkPath, this.options.supportFileExts!, this.options.ignoreFileNames); - allFiles.forEach((file) => { + allFiles.forEach(file => { logger.info('=== parse sdk file:', file); try { const arkFile: ArkFile = new ArkFile(FileUtils.getFileLanguage(file, this.fileLanguages)); @@ -574,6 +585,7 @@ export class Scene { }); const fileSig = arkFile.getFileSignature().toMapKey(); this.sdkArkFilesMap.set(fileSig, arkFile); + SdkUtils.buildSdkImportMap(arkFile); SdkUtils.buildGlobalMap(arkFile, this.sdkGlobalMap); } catch (error) { logger.error('Error parsing file:', file, error); @@ -588,7 +600,7 @@ export class Scene { * dependencies from this file. Next, build a `ModuleScene` for this project to generate {@link ArkFile}. Finally, * it build bodies of all methods, generate extended classes, and add DefaultConstructors. */ - public buildScene4HarmonyProject() { + public buildScene4HarmonyProject(): void { this.buildOhPkgContentMap(); this.modulePath2NameMap.forEach((value, key) => { let moduleScene = new ModuleScene(this); @@ -610,7 +622,7 @@ export class Scene { }); } - public buildModuleScene(moduleName: string, modulePath: string, supportFileExts: string[]) { + public buildModuleScene(moduleName: string, modulePath: string, supportFileExts: string[]): void { if (this.moduleScenesMap.get(moduleName)) { return; } @@ -642,7 +654,7 @@ export class Scene { private processModuleOhPkgContent(dependencies: Object, moduleOhPkgFilePath: string, supportFileExts: string[]): void { Object.entries(dependencies).forEach(([k, v]) => { const pattern = new RegExp('^(\\.\\.\\/\|\\.\\/)'); - if (typeof (v) === 'string') { + if (typeof v === 'string') { let dependencyModulePath: string = ''; if (pattern.test(v)) { dependencyModulePath = path.join(moduleOhPkgFilePath, v); @@ -680,7 +692,7 @@ export class Scene { return this.projectName; } - public getProjectFiles() { + public getProjectFiles(): string[] { return this.projectFiles; } @@ -744,7 +756,7 @@ export class Scene { * @example * 1. In inferSimpleTypes() to check arkClass and arkMethod. * ```typescript - * public inferSimpleTypes() { + * public inferSimpleTypes(): void { * for (let arkFile of this.getFiles()) { * for (let arkClass of arkFile.getClasses()) { * for (let arkMethod of arkClass.getMethods()) { @@ -777,11 +789,11 @@ export class Scene { return Array.from(this.sdkArkFilesMap.values()); } - public getModuleSdkMap() { + public getModuleSdkMap(): Map { return this.moduleSdkMap; } - public getProjectSdkMap() { + public getProjectSdkMap(): Map { return this.projectSdkMap; } @@ -815,7 +827,7 @@ export class Scene { private getNamespacesMap(): Map { if (this.buildStage === SceneBuildStage.CLASS_DONE) { for (const file of this.getFiles()) { - ModelUtils.getAllNamespacesInFile(file).forEach((namespace) => { + ModelUtils.getAllNamespacesInFile(file).forEach(namespace => { this.namespacesMap.set(namespace.getNamespaceSignature().toMapKey(), namespace); }); } @@ -963,7 +975,7 @@ export class Scene { } //Get the set of entry points that are used to build the call graph. - public getEntryPoints() { + public getEntryPoints(): MethodSignature[] { return []; } @@ -972,15 +984,15 @@ export class Scene { return this.visibleValue; } - public getOhPkgContent() { + public getOhPkgContent(): { [p: string]: unknown } { return this.ohPkgContent; } - public getOhPkgContentMap() { + public getOhPkgContentMap(): Map { return this.ohPkgContentMap; } - public getOhPkgFilePath() { + public getOhPkgFilePath(): string { return this.ohPkgFilePath; } @@ -1010,12 +1022,24 @@ export class Scene { scene.inferTypes(); ``` */ - public inferTypes() { + public inferTypes(): void { if (this.buildStage < SceneBuildStage.SDK_INFERRED) { - this.sdkArkFilesMap.forEach(file => IRInference.inferFile(file)); + this.sdkArkFilesMap.forEach(file => { + try { + IRInference.inferFile(file); + } catch (error) { + logger.error('Error inferring types of sdk file:', file.getFileSignature(), error); + } + }); this.buildStage = SceneBuildStage.SDK_INFERRED; } - this.filesMap.forEach(file => IRInference.inferFile(file)); + this.filesMap.forEach(file => { + try { + IRInference.inferFile(file); + } catch (error) { + logger.error('Error inferring types of project file:', file.getFileSignature(), error); + } + }); if (this.buildStage < SceneBuildStage.TYPE_INFERRED) { this.getMethodsMap(true); this.buildStage = SceneBuildStage.TYPE_INFERRED; @@ -1036,8 +1060,7 @@ export class Scene { scene.inferSimpleTypes(); ``` */ - public inferSimpleTypes() { - + public inferSimpleTypes(): void { for (let arkFile of this.getFiles()) { for (let arkClass of arkFile.getClasses()) { for (let arkMethod of arkClass.getMethods()) { @@ -1047,9 +1070,12 @@ export class Scene { } } - private addNSClasses(namespaceStack: ArkNamespace[], finalNamespaces: ArkNamespace[], - classMap: Map, - parentMap: Map): void { + private addNSClasses( + namespaceStack: ArkNamespace[], + finalNamespaces: ArkNamespace[], + classMap: Map, + parentMap: Map + ): void { while (namespaceStack.length > 0) { const ns = namespaceStack.shift()!; const nsClass: ArkClass[] = []; @@ -1068,9 +1094,11 @@ export class Scene { } } - private addNSExportedClasses(finalNamespaces: ArkNamespace[], - classMap: Map, - parentMap: Map): void { + private addNSExportedClasses( + finalNamespaces: ArkNamespace[], + classMap: Map, + parentMap: Map + ): void { while (finalNamespaces.length > 0) { const finalNS = finalNamespaces.shift()!; const exportClass = []; @@ -1117,9 +1145,7 @@ export class Scene { // 遗留问题:只统计了项目文件的namespace,没统计sdk文件内部的引入 const importNameSpaceClasses = classMap.get(importNameSpace.getNamespaceSignature())!; importClasses.push(...importNameSpaceClasses.filter(c => !importClasses.includes(c) && c.getName() !== DEFAULT_ARK_CLASS_NAME)); - } catch { - } - + } catch {} } } const fileClasses = classMap.get(file.getFileSignature())!; @@ -1171,17 +1197,25 @@ export class Scene { return classMap; } - private addNSLocals(namespaceStack: ArkNamespace[], finalNamespaces: ArkNamespace[], - parentMap: Map, - globalVariableMap: Map): void { + private addNSLocals( + namespaceStack: ArkNamespace[], + finalNamespaces: ArkNamespace[], + parentMap: Map, + globalVariableMap: Map + ): void { while (namespaceStack.length > 0) { const ns = namespaceStack.shift()!; const nsGlobalLocals: Local[] = []; - ns.getDefaultClass().getDefaultArkMethod()!.getBody()?.getLocals().forEach(local => { - if (local.getDeclaringStmt() && local.getName() !== 'this' && local.getName()[0] !== '$') { - nsGlobalLocals.push(local); - } - }); + ns + .getDefaultClass() + .getDefaultArkMethod()! + .getBody() + ?.getLocals() + .forEach(local => { + if (local.getDeclaringStmt() && local.getName() !== 'this' && local.getName()[0] !== '$') { + nsGlobalLocals.push(local); + } + }); globalVariableMap.set(ns.getNamespaceSignature(), nsGlobalLocals); if (ns.getNamespaces().length === 0) { finalNamespaces.push(ns); @@ -1194,9 +1228,11 @@ export class Scene { } } - private addNSExportedLocals(finalNamespaces: ArkNamespace[], - globalVariableMap: Map, - parentMap: Map): void { + private addNSExportedLocals( + finalNamespaces: ArkNamespace[], + globalVariableMap: Map, + parentMap: Map + ): void { while (finalNamespaces.length > 0) { const finalNS = finalNamespaces.shift()!; const exportLocal = []; @@ -1242,9 +1278,7 @@ export class Scene { // 遗留问题:只统计了项目文件,没统计sdk文件内部的引入 const importNameSpaceClasses = globalVariableMap.get(importNameSpace.getNamespaceSignature())!; importLocals.push(...importNameSpaceClasses.filter(c => !importLocals.includes(c) && c.getName() !== DEFAULT_ARK_CLASS_NAME)); - } catch { - } - + } catch {} } } const fileLocals = globalVariableMap.get(file.getFileSignature())!; @@ -1270,8 +1304,7 @@ export class Scene { } } - private handleNestedNSLocals(nsns: ArkNamespace, nsLocals: Local[], - globalVariableMap: Map): void { + private handleNestedNSLocals(nsns: ArkNamespace, nsLocals: Local[], globalVariableMap: Map): void { const nsnsLocals = globalVariableMap.get(nsns.getNamespaceSignature())!; const nsnsLocalNameSet = new Set(nsnsLocals.map(item => item.getName())); for (const local of nsLocals) { @@ -1288,11 +1321,16 @@ export class Scene { const parentMap: Map = new Map(); const finalNamespaces: ArkNamespace[] = []; const globalLocals: Local[] = []; - file.getDefaultClass()?.getDefaultArkMethod()!.getBody()?.getLocals().forEach(local => { - if (local.getDeclaringStmt() && local.getName() !== 'this' && local.getName()[0] !== '$') { - globalLocals.push(local); - } - }); + file + .getDefaultClass() + ?.getDefaultArkMethod()! + .getBody() + ?.getLocals() + .forEach(local => { + if (local.getDeclaringStmt() && local.getName() !== 'this' && local.getName()[0] !== '$') { + globalLocals.push(local); + } + }); globalVariableMap.set(file.getFileSignature(), globalLocals); for (const ns of file.getNamespaces()) { namespaceStack.push(ns); @@ -1326,7 +1364,7 @@ export class Scene { return this.buildStage >= SceneBuildStage.CLASS_DONE; } - public getModuleScene(moduleName: string) { + public getModuleScene(moduleName: string): ModuleScene | undefined { return this.moduleScenesMap.get(moduleName); } @@ -1334,7 +1372,7 @@ export class Scene { return this.moduleScenesMap; } - public getGlobalModule2PathMapping(): { [k: string]: string[]; } | undefined { + public getGlobalModule2PathMapping(): { [k: string]: string[] } | undefined { return this.globalModule2PathMapping; } @@ -1383,7 +1421,7 @@ export class ModuleScene { /** * get oh-package.json5 */ - private getModuleOhPkgFilePath() { + private getModuleOhPkgFilePath(): void { const moduleOhPkgFilePath = path.resolve(this.projectScene.getRealProjectDir(), path.join(this.modulePath, OH_PACKAGE_JSON5)); if (fs.existsSync(moduleOhPkgFilePath)) { this.moduleOhPkgFilePath = moduleOhPkgFilePath; @@ -1402,11 +1440,11 @@ export class ModuleScene { return this.modulePath; } - public getOhPkgFilePath() { + public getOhPkgFilePath(): string { return this.moduleOhPkgFilePath; } - public getOhPkgContent() { + public getOhPkgContent(): { [p: string]: unknown } { return this.ohPkgContent; } @@ -1418,15 +1456,14 @@ export class ModuleScene { this.moduleFileMap.set(arkFile.getFileSignature().toMapKey(), arkFile); } - private genArkFiles(supportFileExts: string[]) { - getAllFiles(this.modulePath, supportFileExts, this.projectScene.getOptions().ignoreFileNames).forEach((file) => { + private genArkFiles(supportFileExts: string[]): void { + getAllFiles(this.modulePath, supportFileExts, this.projectScene.getOptions().ignoreFileNames).forEach(file => { logger.info('=== parse file:', file); try { const arkFile: ArkFile = new ArkFile(FileUtils.getFileLanguage(file, this.projectScene.getFileLanguages())); arkFile.setScene(this.projectScene); arkFile.setModuleScene(this); - buildArkFileFromFile(file, this.projectScene.getRealProjectDir(), arkFile, - this.projectScene.getProjectName()); + buildArkFileFromFile(file, this.projectScene.getRealProjectDir(), arkFile, this.projectScene.getProjectName()); this.projectScene.setFile(arkFile); } catch (error) { logger.error('Error parsing file:', file, error); @@ -1435,4 +1472,4 @@ export class ModuleScene { } }); } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/VFG/DVFG.ts b/ets2panda/linter/arkanalyzer/src/VFG/DVFG.ts index cdf1b3ee10..feca7e2286 100644 --- a/ets2panda/linter/arkanalyzer/src/VFG/DVFG.ts +++ b/ets2panda/linter/arkanalyzer/src/VFG/DVFG.ts @@ -85,8 +85,19 @@ export class DVFG extends BaseExplicitGraph { } export enum DVFGNodeKind { - assign, copy, write, load, addr, if, actualParm, formalParm, actualRet, - formalRet, unary, binary, normal + assign, + copy, + write, + load, + addr, + if, + actualParm, + formalParm, + actualRet, + formalRet, + unary, + binary, + normal, } export class DVFGNode extends BaseNode { @@ -108,4 +119,4 @@ export class DVFGNode extends BaseNode { } } -export class DVFGEdge extends BaseEdge {} \ No newline at end of file +export class DVFGEdge extends BaseEdge {} diff --git a/ets2panda/linter/arkanalyzer/src/VFG/builder/DVFGBuilder.ts b/ets2panda/linter/arkanalyzer/src/VFG/builder/DVFGBuilder.ts index 51bb4fb007..f6169f1cf4 100644 --- a/ets2panda/linter/arkanalyzer/src/VFG/builder/DVFGBuilder.ts +++ b/ets2panda/linter/arkanalyzer/src/VFG/builder/DVFGBuilder.ts @@ -24,7 +24,7 @@ import { NodeID } from '../../core/graph/BaseExplicitGraph'; import { ArkMethod } from '../../core/model/ArkMethod'; import { FieldSignature } from '../../core/model/ArkSignature'; import { Scene } from '../../Scene'; -import { DVFG } from '../DVFG'; +import { DVFG, DVFGNode } from '../DVFG'; export class DVFGBuilder { private dvfg: DVFG; @@ -35,27 +35,33 @@ export class DVFGBuilder { this.scene = s; } - public build() { - this.scene.getMethods().forEach(m => { if (m.getCfg()) { this.buildForSingleMethod(m) } }); + public build(): void { + this.scene.getMethods().forEach(m => { + if (m.getCfg()) { + this.buildForSingleMethod(m); + } + }); } - public buildForSingleMethod(m: ArkMethod) { + public buildForSingleMethod(m: ArkMethod): void { let problem = new ReachingDefProblem(m); let solver = new MFPDataFlowSolver(); let solution = solver.calculateMopSolutionForwards(problem); let defMap = new Map>(); - m.getCfg()!.getStmts().forEach((s) => { - let def: Value | FieldSignature | null = s.getDef(); - if (def != null) { - if (def instanceof AbstractFieldRef) { - def = def.getFieldSignature(); + m.getCfg()! + .getStmts() + .forEach(s => { + let def: Value | FieldSignature | null = s.getDef(); + if (def != null) { + if (def instanceof AbstractFieldRef) { + def = def.getFieldSignature(); + } + let defStmts = defMap.get(def) ?? new Set(); + defStmts.add(s); + defMap.set(def, defStmts); } - let defStmts = defMap.get(def) ?? new Set(); - defStmts.add(s); - defMap.set(def, defStmts); - } - }); + }); solution.in.forEach((defs, reach) => { let addNewNodes = (defId: NodeID, def: Stmt, reach: Stmt): void => { @@ -72,7 +78,7 @@ export class DVFGBuilder { if (target instanceof AbstractFieldRef) { target = target.getFieldSignature(); } - defMap.get(target)?.forEach((defStmt) => { + defMap.get(target)?.forEach(defStmt => { let defId = problem.flowGraph.getNodeID(defStmt); addNewNodes(defId, defStmt, reachStmt); }); @@ -101,9 +107,13 @@ export class DVFGBuilder { private getUsedValues(val: Value): Value[] { if (val instanceof AbstractExpr) { if (val instanceof AbstractInvokeExpr) { - return val.getArgs().flatMap((current) => { return this.getUsedValues(current) }, []); + return val.getArgs().flatMap(current => { + return this.getUsedValues(current); + }, []); } else { - return val.getUses().flatMap((current) => { return this.getUsedValues(current) }, []); + return val.getUses().flatMap(current => { + return this.getUsedValues(current); + }, []); } } if (val instanceof Constant) { @@ -112,11 +122,11 @@ export class DVFGBuilder { return [val]; } - public getOrNewDVFGNode(stmt: Stmt) { + public getOrNewDVFGNode(stmt: Stmt): DVFGNode { return this.dvfg.getOrNewDVFGNode(stmt); } - public addDVFGNodes(): void { } + public addDVFGNodes(): void {} - public addDVFGEdges(): void { } -} \ No newline at end of file + public addDVFGEdges(): void {} +} diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/algorithm/AbstractAnalysis.ts b/ets2panda/linter/arkanalyzer/src/callgraph/algorithm/AbstractAnalysis.ts index 5c543b1c49..4fb8a6f7b7 100644 --- a/ets2panda/linter/arkanalyzer/src/callgraph/algorithm/AbstractAnalysis.ts +++ b/ets2panda/linter/arkanalyzer/src/callgraph/algorithm/AbstractAnalysis.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -24,6 +24,7 @@ import Logger, { LOG_MODULE_TYPE } from '../../utils/logger'; import { NodeID } from '../../core/graph/BaseExplicitGraph'; import { CallGraph, FuncID, CallSite, CallGraphNode } from '../model/CallGraph'; import { CallGraphBuilder } from '../model/builder/CallGraphBuilder'; +import { createPtsCollectionCtor, IPtsCollection, PtsCollectionType } from '../pointerAnalysis/PtsDS'; const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'CG'); @@ -32,7 +33,7 @@ export abstract class AbstractAnalysis { protected cg!: CallGraph; protected cgBuilder!: CallGraphBuilder; protected workList: FuncID[] = []; - protected processedMethod!: Set; + protected processedMethod!: IPtsCollection; constructor(s: Scene) { this.scene = s; @@ -54,6 +55,7 @@ export abstract class AbstractAnalysis { if (method != null) { return method; } + return undefined; } public getClassHierarchy(arkClass: ArkClass): ArkClass[] { @@ -78,35 +80,63 @@ export abstract class AbstractAnalysis { const method = this.workList.shift() as FuncID; const cgNode = this.cg.getNode(method) as CallGraphNode; - if (this.processedMethod.has(method) || cgNode.isSdkMethod()) { + if (this.processedMethod.contains(method) || cgNode.isSdkMethod()) { continue; } // pre process for RTA only this.preProcessMethod(method).forEach((cs: CallSite) => { this.workList.push(cs.calleeFuncID); - }) + }); this.processMethod(method).forEach((cs: CallSite) => { - let me = this.cg.getArkMethodByFuncID(cs.calleeFuncID); + this.processCallSite(method, cs, displayGeneratedMethod); + }); + } + } + + public projectStart(displayGeneratedMethod: boolean): void { + this.scene.getMethods().forEach((method) => { + let cgNode = this.cg.getCallGraphNodeByMethod(method.getSignature()) as CallGraphNode; + + if (cgNode.isSdkMethod()) { + return; + } + + this.preProcessMethod(cgNode.getID()); - this.addCallGraphEdge(method, me, cs, displayGeneratedMethod); + this.processMethod(cgNode.getID()).forEach((cs: CallSite) => { + this.processCallSite(cgNode.getID(), cs, displayGeneratedMethod, true); + }); + }); + } - if (!this.processedMethod.has(cs.calleeFuncID)) { - this.workList.push(cs.calleeFuncID); - logger.info(`New workList item ${cs.calleeFuncID}: ${this.cg.getArkMethodByFuncID(cs.calleeFuncID)?.getSignature().toString()}`); + private processCallSite(method: FuncID, cs: CallSite, displayGeneratedMethod: boolean, isProject: boolean = false): void { + let me = this.cg.getArkMethodByFuncID(cs.calleeFuncID); + let meNode = this.cg.getNode(cs.calleeFuncID) as CallGraphNode; + this.addCallGraphEdge(method, me, cs, displayGeneratedMethod); - this.processedMethod.add(cs.callerFuncID); - } - }) + if (isProject) { + return; + } + + this.processedMethod.insert(cs.callerFuncID); + + if (this.processedMethod.contains(cs.calleeFuncID) || meNode.isSdkMethod()) { + return; + } + + if (displayGeneratedMethod || !me?.isGenerated()) { + this.workList.push(cs.calleeFuncID); + logger.info(`New workList item ${cs.calleeFuncID}: ${this.cg.getArkMethodByFuncID(cs.calleeFuncID)?.getSignature().toString()}`); } } protected init(): void { - this.processedMethod = new Set(); - this.cg.getEntries().forEach((entryFunc) => { + this.processedMethod = new (createPtsCollectionCtor(PtsCollectionType.BitVector))(); + this.cg.getEntries().forEach(entryFunc => { this.workList.push(entryFunc); - }) + }); } protected processMethod(methodID: FuncID): CallSite[] { @@ -115,22 +145,22 @@ export abstract class AbstractAnalysis { let calleeMethods: CallSite[] = []; if (!arkMethod) { - throw new Error("can not find method"); + throw new Error('can not find method'); } const cfg = arkMethod.getCfg(); if (!cfg) { return []; } - cfg.getStmts().forEach((stmt) => { + cfg.getStmts().forEach(stmt => { if (stmt.containsInvokeExpr()) { - this.resolveCall(cgNode.getID(), stmt).forEach((callSite) => { + this.resolveCall(cgNode.getID(), stmt).forEach(callSite => { calleeMethods.push(callSite); this.cg.addStmtToCallSiteMap(stmt, callSite); this.cg.addMethodToCallSiteMap(callSite.calleeFuncID, callSite); }); } - }) + }); return calleeMethods; } @@ -138,7 +168,7 @@ export abstract class AbstractAnalysis { protected getParamAnonymousMethod(invokeExpr: AbstractInvokeExpr): MethodSignature[] { let paramMethod: MethodSignature[] = []; - invokeExpr.getArgs().forEach((args) => { + invokeExpr.getArgs().forEach(args => { let argsType = args.getType(); if (argsType instanceof FunctionType) { paramMethod.push(argsType.getMethodSignature()); @@ -153,9 +183,9 @@ export abstract class AbstractAnalysis { if (!callee) { logger.error(`FuncID has no method ${cs.calleeFuncID}`); } else { - if (displayGeneratedMethod || !(callee?.isGenerated())) { + if (displayGeneratedMethod || !callee?.isGenerated()) { this.cg.addDynamicCallEdge(caller, cs.calleeFuncID, cs.callStmt); } } } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/algorithm/ClassHierarchyAnalysis.ts b/ets2panda/linter/arkanalyzer/src/callgraph/algorithm/ClassHierarchyAnalysis.ts index f086c8267d..029d85541e 100644 --- a/ets2panda/linter/arkanalyzer/src/callgraph/algorithm/ClassHierarchyAnalysis.ts +++ b/ets2panda/linter/arkanalyzer/src/callgraph/algorithm/ClassHierarchyAnalysis.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -22,7 +22,6 @@ import { CallGraph, CallSite } from '../model/CallGraph'; import { AbstractAnalysis } from './AbstractAnalysis'; export class ClassHierarchyAnalysis extends AbstractAnalysis { - constructor(scene: Scene, cg: CallGraph) { super(scene); this.cg = cg; @@ -38,11 +37,7 @@ export class ClassHierarchyAnalysis extends AbstractAnalysis { // process anonymous method call this.getParamAnonymousMethod(invokeExpr).forEach(method => { - resolveResult.push( - new CallSite(invokeStmt, undefined, - this.cg.getCallGraphNodeByMethod(method).getID(), callerMethod - ) - ); + resolveResult.push(new CallSite(invokeStmt, undefined, this.cg.getCallGraphNodeByMethod(method).getID(), callerMethod)); }); let calleeMethod = this.resolveInvokeExpr(invokeExpr); @@ -51,9 +46,7 @@ export class ClassHierarchyAnalysis extends AbstractAnalysis { } if (invokeExpr instanceof ArkStaticInvokeExpr) { // get specific method - resolveResult.push(new CallSite(invokeStmt, undefined, - this.cg.getCallGraphNodeByMethod(calleeMethod!.getSignature()).getID(), - callerMethod!)); + resolveResult.push(new CallSite(invokeStmt, undefined, this.cg.getCallGraphNodeByMethod(calleeMethod!.getSignature()).getID(), callerMethod!)); } else { let declareClass = calleeMethod.getDeclaringArkClass(); // TODO: super class method should be placed at the end @@ -64,18 +57,18 @@ export class ClassHierarchyAnalysis extends AbstractAnalysis { let possibleCalleeMethod = arkClass.getMethodWithName(calleeMethod!.getName()); - if (possibleCalleeMethod && possibleCalleeMethod.isGenerated() && - arkClass.getSignature().toString() !== declareClass.getSignature().toString()) { + if ( + possibleCalleeMethod && + possibleCalleeMethod.isGenerated() && + arkClass.getSignature().toString() !== declareClass.getSignature().toString() + ) { // remove the generated method in extended classes return; } if (possibleCalleeMethod && !possibleCalleeMethod.isAbstract()) { resolveResult.push( - new CallSite(invokeStmt, undefined, - this.cg.getCallGraphNodeByMethod(possibleCalleeMethod.getSignature()).getID(), - callerMethod - ) + new CallSite(invokeStmt, undefined, this.cg.getCallGraphNodeByMethod(possibleCalleeMethod.getSignature()).getID(), callerMethod) ); } }); @@ -88,4 +81,4 @@ export class ClassHierarchyAnalysis extends AbstractAnalysis { // do nothing return []; } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/algorithm/RapidTypeAnalysis.ts b/ets2panda/linter/arkanalyzer/src/callgraph/algorithm/RapidTypeAnalysis.ts index 1e447e6dcc..b4ecc267ac 100644 --- a/ets2panda/linter/arkanalyzer/src/callgraph/algorithm/RapidTypeAnalysis.ts +++ b/ets2panda/linter/arkanalyzer/src/callgraph/algorithm/RapidTypeAnalysis.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -30,7 +30,7 @@ export class RapidTypeAnalysis extends AbstractAnalysis { // TODO: signature duplicated check private instancedClasses: Set = new Set(); // TODO: Set duplicated check - private ignoredCalls: Map> = new Map(); + private ignoredCalls: Map> = new Map(); constructor(scene: Scene, cg: CallGraph) { super(scene); @@ -47,9 +47,7 @@ export class RapidTypeAnalysis extends AbstractAnalysis { // process anonymous method call this.getParamAnonymousMethod(invokeExpr).forEach(method => { - resolveResult.push(new CallSite(invokeStmt, undefined, - this.cg.getCallGraphNodeByMethod(method).getID(), callerMethod) - ); + resolveResult.push(new CallSite(invokeStmt, undefined, this.cg.getCallGraphNodeByMethod(method).getID(), callerMethod)); }); let calleeMethod = this.resolveInvokeExpr(invokeExpr); @@ -59,9 +57,7 @@ export class RapidTypeAnalysis extends AbstractAnalysis { if (invokeExpr instanceof ArkStaticInvokeExpr) { // get specific method - resolveResult.push(new CallSite(invokeStmt, undefined, - this.cg.getCallGraphNodeByMethod(calleeMethod.getSignature()).getID(), callerMethod) - ); + resolveResult.push(new CallSite(invokeStmt, undefined, this.cg.getCallGraphNodeByMethod(calleeMethod.getSignature()).getID(), callerMethod)); } else { let declareClass = calleeMethod!.getDeclaringArkClass(); // TODO: super class method should be placed at the end @@ -72,8 +68,11 @@ export class RapidTypeAnalysis extends AbstractAnalysis { let possibleCalleeMethod = arkClass.getMethodWithName(calleeMethod!.getName()); - if (possibleCalleeMethod && possibleCalleeMethod.isGenerated() && - arkClass.getSignature().toString() !== declareClass.getSignature().toString()) { + if ( + possibleCalleeMethod && + possibleCalleeMethod.isGenerated() && + arkClass.getSignature().toString() !== declareClass.getSignature().toString() + ) { // remove the generated method in extended classes return; } @@ -83,14 +82,15 @@ export class RapidTypeAnalysis extends AbstractAnalysis { } if (!this.instancedClasses.has(arkClass.getSignature())) { - this.addIgnoredCalls(arkClass.getSignature(), callerMethod, + this.addIgnoredCalls( + arkClass.getSignature(), + callerMethod, this.cg.getCallGraphNodeByMethod(possibleCalleeMethod.getSignature()).getID(), invokeStmt ); } else { - resolveResult.push(new CallSite(invokeStmt, undefined, - this.cg.getCallGraphNodeByMethod(possibleCalleeMethod.getSignature()).getID(), - callerMethod) + resolveResult.push( + new CallSite(invokeStmt, undefined, this.cg.getCallGraphNodeByMethod(possibleCalleeMethod.getSignature()).getID(), callerMethod) ); } }); @@ -102,14 +102,12 @@ export class RapidTypeAnalysis extends AbstractAnalysis { protected preProcessMethod(funcID: FuncID): CallSite[] { let newCallSites: CallSite[] = []; let instancedClasses: Set = this.collectInstancedClassesInMethod(funcID); - let newlyInstancedClasses = new Set( - Array.from(instancedClasses).filter(item => !this.instancedClasses.has(item)) - ); + let newlyInstancedClasses = new Set(Array.from(instancedClasses).filter(item => !this.instancedClasses.has(item))); newlyInstancedClasses.forEach(sig => { - let ignoredCalls = this.ignoredCalls.get(sig) + let ignoredCalls = this.ignoredCalls.get(sig); if (ignoredCalls) { - ignoredCalls.forEach((call) => { + ignoredCalls.forEach(call => { this.cg.addDynamicCallEdge(call.caller, call.callee, call.callStmt); newCallSites.push(new CallSite(call.callStmt, undefined, call.callee, call.caller)); }); @@ -120,7 +118,7 @@ export class RapidTypeAnalysis extends AbstractAnalysis { return newCallSites; } - private collectInstancedClassesInMethod(funcID: FuncID) { + private collectInstancedClassesInMethod(funcID: FuncID): Set { let instancedClasses: Set = new Set(); let arkMethod = this.cg.getArkMethodByFuncID(funcID); @@ -148,9 +146,9 @@ export class RapidTypeAnalysis extends AbstractAnalysis { return instancedClasses; } - public addIgnoredCalls(arkClass: ClassSignature, callerID: FuncID, calleeID: FuncID, invokeStmt: Stmt) { + public addIgnoredCalls(arkClass: ClassSignature, callerID: FuncID, calleeID: FuncID, invokeStmt: Stmt): void { let classMap = this.ignoredCalls.get(arkClass) ?? new Set(); classMap.add({ caller: callerID, callee: calleeID, callStmt: invokeStmt }); this.ignoredCalls.set(arkClass, classMap); } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/common/Statistics.ts b/ets2panda/linter/arkanalyzer/src/callgraph/common/Statistics.ts index e3b41aeaa9..61246908ad 100644 --- a/ets2panda/linter/arkanalyzer/src/callgraph/common/Statistics.ts +++ b/ets2panda/linter/arkanalyzer/src/callgraph/common/Statistics.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,15 +13,19 @@ * limitations under the License. */ -import { ArkAssignStmt, Stmt } from "../../core/base/Stmt"; -import { UnknownType } from "../../core/base/Type"; -import { CallGraphNode, CallGraphNodeKind } from "../model/CallGraph"; -import { PointerAnalysis } from "../pointerAnalysis/PointerAnalysis"; -import Logger, { LOG_MODULE_TYPE } from "../../utils/logger"; +import { ArkAssignStmt, Stmt } from '../../core/base/Stmt'; +import { UnknownType } from '../../core/base/Type'; +import { CallGraphNode, CallGraphNodeKind } from '../model/CallGraph'; +import { PointerAnalysis } from '../pointerAnalysis/PointerAnalysis'; +import Logger, { LOG_MODULE_TYPE } from '../../utils/logger'; const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'PTA'); abstract class StatTraits { + TotalTime: number = 0; + startTime: number = 0; + endTime: number = 0; + public getStat(): string { return ''; } @@ -31,7 +35,7 @@ abstract class StatTraits { } } -export class PTAStat implements StatTraits { +export class PTAStat extends StatTraits { pta: PointerAnalysis; numProcessedAddr: number = 0; numProcessedCopy: number = 0; @@ -56,10 +60,6 @@ export class PTAStat implements StatTraits { numUnhandledFunc: number = 0; iterTimes: number = 0; - TotalTime: number = 0; - - startTime: number = 0; - endTime: number = 0; startMemUsage: any; endMemUsage: any; @@ -67,6 +67,7 @@ export class PTAStat implements StatTraits { heapUsed: number = 0; constructor(pta: PointerAnalysis) { + super(); this.pta = pta; } @@ -121,7 +122,10 @@ export class PTAStat implements StatTraits { let cg = this.pta.getCallGraph(); this.pta.getHandledFuncs().forEach(funcID => { let f = cg.getArkMethodByFuncID(funcID); - f?.getCfg()?.getStmts().forEach(s => stmtStat(s)); + f + ?.getCfg() + ?.getStmts() + .forEach(s => stmtStat(s)); }); } @@ -143,23 +147,22 @@ export class PTAStat implements StatTraits { public getStat(): string { // TODO: get PAG stat and CG stat let output: string; - output = '==== Pointer analysis Statictics: ====\n' - output = output + `Processed address\t${this.numProcessedAddr}\n` - output = output + `Processed copy\t\t${this.numProcessedCopy}\n` - output = output + `Processed load\t\t${this.numProcessedLoad}\n` - output = output + `Processed write\t\t${this.numProcessedWrite}\n` - output = output + `Real write\t\t${this.numRealWrite}\n` - output = output + `Real load\t\t${this.numRealLoad}\n` - output = output + `Processed This\t\t${this.numProcessedThis}\n\n` - output = output + `Unhandled function\t${this.numUnhandledFun}\n` - output = output + `Total values in visited function\t${this.totalValuesInVisitedFunc}\n` - output = output + `Infered Value unknown+different type\t${this.numInferedUnknownValue}+${this.numInferedDiffTypeValue}\n\n` - output = output + `Total Time\t\t${this.TotalTime} S\n` - output = output + `Total iterator Times\t${this.iterTimes}\n` - output = output + `RSS used\t\t${this.rssUsed.toFixed(3)} Mb\n` - output = output + `Heap used\t\t${this.heapUsed.toFixed(3)} Mb\n` + output = '==== Pointer analysis Statictics: ====\n'; + output = output + `Processed address\t${this.numProcessedAddr}\n`; + output = output + `Processed copy\t\t${this.numProcessedCopy}\n`; + output = output + `Processed load\t\t${this.numProcessedLoad}\n`; + output = output + `Processed write\t\t${this.numProcessedWrite}\n`; + output = output + `Real write\t\t${this.numRealWrite}\n`; + output = output + `Real load\t\t${this.numRealLoad}\n`; + output = output + `Processed This\t\t${this.numProcessedThis}\n\n`; + output = output + `Unhandled function\t${this.numUnhandledFun}\n`; + output = output + `Total values in visited function\t${this.totalValuesInVisitedFunc}\n`; + output = output + `Infered Value unknown+different type\t${this.numInferedUnknownValue}+${this.numInferedDiffTypeValue}\n\n`; + output = output + `Total Time\t\t${this.TotalTime} S\n`; + output = output + `Total iterator Times\t${this.iterTimes}\n`; + output = output + `RSS used\t\t${this.rssUsed.toFixed(3)} Mb\n`; + output = output + `Heap used\t\t${this.heapUsed.toFixed(3)} Mb\n`; return output; - } public printStat(): void { @@ -167,17 +170,17 @@ export class PTAStat implements StatTraits { } } -export class PAGStat implements StatTraits { +export class PAGStat extends StatTraits { numDynamicCall: number = 0; numTotalFunction: number = 0; numTotalNode: number = 0; public getStat(): string { let output: string; - output = '==== PAG Statictics: ====\n' - output = output + `Dynamic call\t\t${this.numDynamicCall}\n` - output = output + `Total function handled\t${this.numTotalFunction}\n` - output = output + `Total PAG Nodes\t\t${this.numTotalNode}\n` + output = '==== PAG Statictics: ====\n'; + output = output + `Dynamic call\t\t${this.numDynamicCall}\n`; + output = output + `Total function handled\t${this.numTotalFunction}\n`; + output = output + `Total PAG Nodes\t\t${this.numTotalNode}\n`; return output; } @@ -194,8 +197,17 @@ export class CGStat extends StatTraits { numIntrinsic: number = 0; numConstructor: number = 0; + public startStat(): void { + this.startTime = new Date().getTime(); + } + + public endStat(): void { + this.endTime = new Date().getTime(); + this.TotalTime = (this.endTime - this.startTime) / 1000; + } + public addNodeStat(kind: CallGraphNodeKind): void { - switch(kind) { + switch (kind) { case CallGraphNodeKind.real: this.numReal++; break; @@ -215,12 +227,13 @@ export class CGStat extends StatTraits { public getStat(): string { let output: string; - output = '==== CG Statictics: ====\n' - output = output + `Real function\t\t${this.numReal}\n` - output = output + `Intrinsic function\t${this.numIntrinsic}\n` - output = output + `Constructor function\t${this.numConstructor}\n` - output = output + `Blank function\t\t${this.numVirtual}\n` - output = output + `Total\t\t\t${this.numTotalNode}\n` + output = '==== CG Statictics: ====\n'; + output = output + `CG construction Total Time\t\t${this.TotalTime} S\n`; + output = output + `Real function\t\t${this.numReal}\n`; + output = output + `Intrinsic function\t${this.numIntrinsic}\n`; + output = output + `Constructor function\t${this.numConstructor}\n`; + output = output + `Blank function\t\t${this.numVirtual}\n`; + output = output + `Total\t\t\t${this.numTotalNode}\n`; return output; } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/model/CallGraph.ts b/ets2panda/linter/arkanalyzer/src/callgraph/model/CallGraph.ts index 78b2892088..954f47804a 100644 --- a/ets2panda/linter/arkanalyzer/src/callgraph/model/CallGraph.ts +++ b/ets2panda/linter/arkanalyzer/src/callgraph/model/CallGraph.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,9 +13,9 @@ * limitations under the License. */ -import { MethodSignature } from '../../core/model/ArkSignature' -import { Stmt } from '../../core/base/Stmt' -import { Value } from '../../core/base/Value' +import { MethodSignature } from '../../core/model/ArkSignature'; +import { Stmt } from '../../core/base/Stmt'; +import { Value } from '../../core/base/Value'; import { Scene } from '../../Scene'; import { ArkMethod } from '../../core/model/ArkMethod'; import { GraphPrinter } from '../../save/GraphPrinter'; @@ -31,7 +31,10 @@ export type FuncID = number; type StmtSet = Set; export enum CallGraphNodeKind { - real, vitual, intrinsic, constructor + real, + vitual, + intrinsic, + constructor, } export class CallSite { @@ -81,15 +84,15 @@ export class CallGraphEdge extends BaseEdge { super(src, dst, 0); } - public addDirectCallSite(stmt: Stmt) { + public addDirectCallSite(stmt: Stmt): void { this.directCalls.add(stmt); } - public addSpecialCallSite(stmt: Stmt) { + public addSpecialCallSite(stmt: Stmt): void { this.specialCalls.add(stmt); } - public addInDirectCallSite(stmt: Stmt) { + public addInDirectCallSite(stmt: Stmt): void { this.indirectCalls.add(stmt); } @@ -98,17 +101,17 @@ export class CallGraphEdge extends BaseEdge { const directCallNums: number = this.directCalls.size; const specialCallNums: number = this.specialCalls.size; if ([CallGraphNodeKind.intrinsic, CallGraphNodeKind.constructor].includes(this.getDstNode().getKind())) { - return '' + return ''; } if (indirectCallNums !== 0 && directCallNums === 0) { - return "color=red"; + return 'color=red'; } else if (specialCallNums !== 0) { - return "color=yellow"; + return 'color=yellow'; } else if (indirectCallNums === 0 && directCallNums !== 0) { - return "color=black"; + return 'color=black'; } else { - return "color=black"; + return 'color=black'; } } } @@ -132,7 +135,7 @@ export class CallGraphNode extends BaseNode { } public isSdkMethod(): boolean { - return this.ifSdkMethod + return this.ifSdkMethod; } public get isBlankMethod(): boolean { @@ -190,9 +193,7 @@ export class CallGraph extends BaseExplicitGraph { let id: NodeID = this.nodeNum; let cgNode = new CallGraphNode(id, method, kind); // check if sdk method - cgNode.setSdkMethod(this.scene.hasSdkFile( - method.getDeclaringClassSignature().getDeclaringFileSignature() - )); + cgNode.setSdkMethod(this.scene.hasSdkFile(method.getDeclaringClassSignature().getDeclaringFileSignature())); let arkMethod = this.scene.getMethod(method); if (!arkMethod || !arkMethod.getCfg()) { @@ -205,7 +206,7 @@ export class CallGraph extends BaseExplicitGraph { return cgNode; } - public removeCallGraphNode(nodeID: NodeID) { + public removeCallGraphNode(nodeID: NodeID): void { // remove edge relate to node first this.removeCallGraphEdge(nodeID); let node = this.getNode(nodeID) as CallGraphNode; @@ -264,7 +265,7 @@ export class CallGraph extends BaseExplicitGraph { } } - public removeCallGraphEdge(nodeID: NodeID) { + public removeCallGraphEdge(nodeID: NodeID): void { let node = this.getNode(nodeID) as CallGraphNode; for (const inEdge of node.getIncomingEdge()) { @@ -284,11 +285,11 @@ export class CallGraph extends BaseExplicitGraph { } let args = callStmt.getInvokeExpr()?.getArgs(); - let cs = new DynCallSite(callerNode.getID(), callStmt, args, calleeNode?.getID()) + let cs = new DynCallSite(callerNode.getID(), callStmt, args, calleeNode?.getID()); this.stmtToDynCallSitemap.set(callStmt, cs); } - public addDynamicCallEdge(callerID: NodeID, calleeID: NodeID, callStmt: Stmt) { + public addDynamicCallEdge(callerID: NodeID, calleeID: NodeID, callStmt: Stmt): void { let callerNode = this.getNode(callerID) as CallGraphNode; let calleeNode = this.getNode(calleeID) as CallGraphNode; @@ -342,7 +343,7 @@ export class CallGraph extends BaseExplicitGraph { public getInvokeStmtByMethod(func: FuncID | MethodSignature): Stmt[] { let callSites = this.getCallSitesByMethod(func); let invokeStmts: Stmt[] = []; - callSites.forEach((cs) => { + callSites.forEach(cs => { invokeStmts.push(cs.callStmt); }); @@ -372,7 +373,6 @@ export class CallGraph extends BaseExplicitGraph { if (node !== undefined) { return (node as CallGraphNode).getMethod(); } - //return undefined; return null; } @@ -428,6 +428,14 @@ export class CallGraph extends BaseExplicitGraph { return false; } + public startStat(): void { + this.cgStat.startStat(); + } + + public endStat(): void { + this.cgStat.endStat(); + } + public printStat(): void { this.cgStat.printStat(); } diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/model/builder/CallGraphBuilder.ts b/ets2panda/linter/arkanalyzer/src/callgraph/model/builder/CallGraphBuilder.ts index 88076a8eaf..c631c4333f 100644 --- a/ets2panda/linter/arkanalyzer/src/callgraph/model/builder/CallGraphBuilder.ts +++ b/ets2panda/linter/arkanalyzer/src/callgraph/model/builder/CallGraphBuilder.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -15,7 +15,7 @@ import { CallGraph, CallGraphNode, CallGraphNodeKind, Method } from '../CallGraph'; import { Scene } from '../../../Scene'; -import { AbstractInvokeExpr, ArkInstanceInvokeExpr, ArkStaticInvokeExpr } from "../../../core/base/Expr"; +import { AbstractInvokeExpr, ArkInstanceInvokeExpr, ArkStaticInvokeExpr } from '../../../core/base/Expr'; import { NodeID } from '../../../core/graph/BaseExplicitGraph'; import { ClassHierarchyAnalysis } from '../../algorithm/ClassHierarchyAnalysis'; import { RapidTypeAnalysis } from '../../algorithm/RapidTypeAnalysis'; @@ -30,7 +30,6 @@ export class CallGraphBuilder { this.scene = s; } - public buildDirectCallGraphForScene(): void { const methods = this.scene.getMethods(); this.buildDirectCallGraph(methods); @@ -70,8 +69,11 @@ export class CallGraphBuilder { // abstract method will also be added into direct cg if (callee && invokeExpr instanceof ArkStaticInvokeExpr) { this.cg.addDirectOrSpecialCallEdge(method.getSignature(), callee, stmt); - } else if (callee && (invokeExpr instanceof ArkInstanceInvokeExpr && ( - this.isConstructor(callee) || this.scene.getMethod(callee)?.isGenerated()))) { + } else if ( + callee && + invokeExpr instanceof ArkInstanceInvokeExpr && + (this.isConstructor(callee) || this.scene.getMethod(callee)?.isGenerated()) + ) { this.cg.addDirectOrSpecialCallEdge(method.getSignature(), callee, stmt, false); } else { this.cg.addDynamicCallInfo(stmt, method.getSignature(), callee); @@ -84,18 +86,23 @@ export class CallGraphBuilder { let cgEntries: NodeID[] = []; entries.forEach((entry: Method) => { cgEntries.push(this.cg.getCallGraphNodeByMethod(entry).getID()); - }) + }); this.cg.setEntries(cgEntries); let classHierarchyAnalysis: ClassHierarchyAnalysis = new ClassHierarchyAnalysis(this.scene, this.cg); classHierarchyAnalysis.start(displayGeneratedMethod); } + public buildCHA4WholeProject(displayGeneratedMethod: boolean = false): void { + let classHierarchyAnalysis: ClassHierarchyAnalysis = new ClassHierarchyAnalysis(this.scene, this.cg); + classHierarchyAnalysis.projectStart(displayGeneratedMethod); + } + public buildRapidTypeCallGraph(entries: Method[], displayGeneratedMethod: boolean = false): void { let cgEntries: NodeID[] = []; entries.forEach((entry: Method) => { cgEntries.push(this.cg.getCallGraphNodeByMethod(entry).getID()); - }) + }); this.cg.setEntries(cgEntries); let rapidTypeAnalysis: RapidTypeAnalysis = new RapidTypeAnalysis(this.scene, this.cg); @@ -114,8 +121,7 @@ export class CallGraphBuilder { public setEntries(): void { let nodesIter = this.cg.getNodesIter(); let entries = Array.from(nodesIter) - .filter(node => !node.hasIncomingEdges() && node.getKind() === CallGraphNodeKind.real - && !(node as CallGraphNode).isBlankMethod) + .filter(node => !node.hasIncomingEdges() && node.getKind() === CallGraphNodeKind.real && !(node as CallGraphNode).isBlankMethod) .map(node => node.getID()); this.cg.setEntries(entries); } diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/Context.ts b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/Context.ts index e8affe8adb..71b00b5b9b 100644 --- a/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/Context.ts +++ b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/Context.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,10 +13,10 @@ * limitations under the License. */ -import {FuncID} from '../model/CallGraph' +import { FuncID } from '../model/CallGraph'; -export type ContextID = number -export const DUMMY_CID = 0 +export type ContextID = number; +export const DUMMY_CID = 0; class Context { private contextElems: number[]; @@ -34,7 +34,7 @@ class Context { return new Context(contextElems); } - // use old context and a new element to create a new k-limited Context + // use old context and a new element to create a new k-limited Context static newKLimitedContext(oldCtx: Context, elem: number, k: number): Context { let elems: number[] = []; if (k > 0) { @@ -48,7 +48,7 @@ class Context { return new Context(elems); } - static kLimitedContext(ctx: Context, k:number): Context { + static kLimitedContext(ctx: Context, k: number): Context { if (ctx.length() <= k) { return new Context(ctx.contextElems); } else { @@ -69,7 +69,7 @@ class Context { } public toString(): String { - return this.contextElems.join('-') + return this.contextElems.join('-'); } } @@ -96,7 +96,7 @@ class ContextCache { } public updateContext(id: ContextID, newContext: Context, oldContext: Context): boolean { - if(this.contextList.length < id) { + if (this.contextList.length < id) { return false; } this.contextList[id] = newContext; @@ -143,11 +143,11 @@ export class KLimitedContextSensitive { return new Context([]); } - public getEmptyContextID(): ContextID{ + public getEmptyContextID(): ContextID { return this.getContextID(Context.newEmpty()); } - public getContextID(context: Context): ContextID{ + public getContextID(context: Context): ContextID { return this.ctxCache.getOrNewContextID(context); } @@ -156,7 +156,7 @@ export class KLimitedContextSensitive { } public getNewContextID(callerFuncId: FuncID): ContextID { - return this.ctxCache.getOrNewContextID(Context.new([callerFuncId])); + return this.ctxCache.getOrNewContextID(Context.new([callerFuncId])); } public getOrNewContext(callerCid: ContextID, calleeFuncId: FuncID, findCalleeAsTop: boolean = false): ContextID { @@ -166,7 +166,7 @@ export class KLimitedContextSensitive { } const calleeNewCtx = Context.newKLimitedContext(callerCtx, calleeFuncId, this.k); - if (findCalleeAsTop){ + if (findCalleeAsTop) { const calleeAsTopCtx = Context.newKLimitedContext(Context.sEmptyCtx, calleeFuncId, this.k); let topID = this.ctxCache.getContextID(calleeAsTopCtx); if (topID) { @@ -178,4 +178,4 @@ export class KLimitedContextSensitive { const calleeCid = this.ctxCache.getOrNewContextID(calleeNewCtx); return calleeCid; } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/DummyCallCreator.ts b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/DummyCallCreator.ts index 3708605bdf..0595926cc4 100644 --- a/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/DummyCallCreator.ts +++ b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/DummyCallCreator.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,7 +13,6 @@ * limitations under the License. */ - import { ArkInstanceInvokeExpr } from '../../core/base/Expr'; import { Local } from '../../core/base/Local'; import { Stmt, ArkInvokeStmt } from '../../core/base/Stmt'; @@ -31,7 +30,7 @@ const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'Dummy Call'); export class DummyCallCreator { private scene: Scene; private pageMap; - // TODO: classSig -> str ? + // TODO: classSig -> str ? private componentMap: Map>; constructor(scene: Scene) { @@ -86,7 +85,9 @@ export class DummyCallCreator { let callStmts: Stmt[] = []; // filter callback method - componentClass.getMethods().filter(method => COMPONENT_LIFECYCLE_METHOD_NAME.includes(method.getName())) + componentClass + .getMethods() + .filter(method => COMPONENT_LIFECYCLE_METHOD_NAME.includes(method.getName())) .forEach((method: ArkMethod) => { // TODO: args pointer ? if (method.getParameters().length === 0) { @@ -98,4 +99,4 @@ export class DummyCallCreator { return callStmts; } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PTAUtils.ts b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PTAUtils.ts index 04b07551c9..a8940d5d3c 100644 --- a/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PTAUtils.ts +++ b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PTAUtils.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,30 +16,44 @@ import { ClassSignature, MethodSignature } from '../../core/model/ArkSignature'; export function IsCollectionClass(classSignature: ClassSignature): boolean { - if (classSignature.toString().endsWith('lib.es2015.collection.d.ts: Set') || - classSignature.toString().endsWith('lib.es2015.collection.d.ts: Map')) { + if (classSignature.toString().endsWith('lib.es2015.collection.d.ts: Set') || classSignature.toString().endsWith('lib.es2015.collection.d.ts: Map')) { return true; } return false; } -export function IsCollectionAPI(method: MethodSignature): boolean { - if (IsCollectionSetAdd(method) || IsCollectionMapSet(method)) { - return true; - } - return false; +export enum BuiltApiType { + SetAdd, + MapSet, + FunctionCall, + FunctionApply, + FunctionBind, + NotBuiltIn, } -export function IsCollectionSetAdd(method: MethodSignature): boolean { - if (method.toString().endsWith('lib.es2015.collection.d.ts: Set.add(T)')) { - return true; - } - return false; -} +export function getBuiltInApiType(method: MethodSignature): BuiltApiType { + let methodSigStr = method.toString(); -export function IsCollectionMapSet(method: MethodSignature): boolean { - if (method.toString().endsWith('lib.es2015.collection.d.ts: Map.set(K, V)')) { - return true; + const regex = /lib\.es5\.d\.ts: Function\.(call|apply|bind)\(/; + + if (methodSigStr.endsWith('lib.es2015.collection.d.ts: Set.add(T)')) { + return BuiltApiType.SetAdd; + } else if (methodSigStr.endsWith('lib.es2015.collection.d.ts: Map.set(K, V)')) { + return BuiltApiType.MapSet; + } else { + const match = methodSigStr.match(regex); + if (match) { + const functionName = match[1]; + switch (functionName) { + case 'call': + return BuiltApiType.FunctionCall; + case 'apply': + return BuiltApiType.FunctionApply; + case 'bind': + return BuiltApiType.FunctionBind; + } + } } - return false; -} \ No newline at end of file + + return BuiltApiType.NotBuiltIn; +} diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/Pag.ts b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/Pag.ts index 6da4c6c9ac..b04e4cc1ec 100644 --- a/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/Pag.ts +++ b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/Pag.ts @@ -29,7 +29,7 @@ import { ContextID } from './Context'; import Logger, { LOG_MODULE_TYPE } from '../../utils/logger'; import { GLOBAL_THIS_NAME } from '../../core/common/TSConst'; import { ExportInfo } from '../../core/model/ArkExport'; -import { IsCollectionClass } from './PTAUtils'; +import { BuiltApiType, getBuiltInApiType, IsCollectionClass } from './PTAUtils'; import { IPtsCollection } from './PtsDS'; import { PointerAnalysisConfig } from './PointerAnalysisConfig'; @@ -40,20 +40,28 @@ export type PagNodeType = Value; * Implementation of pointer-to assignment graph for pointer analysis */ -const DUMMY_PAG_NODE_ID = -1 +const DUMMY_PAG_NODE_ID = -1; export enum PagEdgeKind { - Address, Copy, Load, Write, This, Unknown, InterProceduralCopy -}; + Address, + Copy, + Load, + Write, + This, + Unknown, + InterProceduralCopy, +} export enum StorageType { - APP_STORAGE, LOCAL_STORAGE, Undefined -}; + APP_STORAGE, + LOCAL_STORAGE, + Undefined, +} export enum StorageLinkEdgeType { Property2Local, Local2Property, - TwoWay + TwoWay, } export class PagEdge extends BaseEdge { @@ -62,27 +70,27 @@ export class PagEdge extends BaseEdge { constructor(n: PagNode, d: PagNode, k: PagEdgeKind, s?: Stmt) { super(n, d, k); this.stmt = s; - }; + } public getDotAttr(): string { switch (this.getKind()) { case PagEdgeKind.Address: - return "color=green"; + return 'color=green'; case PagEdgeKind.Copy: if (this.stmt?.getInvokeExpr() !== undefined || this.stmt instanceof ArkReturnStmt) { - return "color=black,style=dotted"; + return 'color=black,style=dotted'; } - return "color=black"; + return 'color=black'; case PagEdgeKind.Load: - return "color=red"; + return 'color=red'; case PagEdgeKind.Write: - return "color=blue" + return 'color=blue'; case PagEdgeKind.This: - return "color=orange" + return 'color=orange'; case PagEdgeKind.InterProceduralCopy: - return "color=purple,style=dashed"; + return 'color=purple,style=dashed'; default: - return "color=black"; + return 'color=black'; } } } @@ -90,36 +98,46 @@ export class PagEdge extends BaseEdge { export class AddrPagEdge extends PagEdge { constructor(n: PagNode, d: PagNode, s: Stmt) { super(n, d, PagEdgeKind.Address, s); - }; + } } export class CopyPagEdge extends PagEdge { constructor(n: PagNode, d: PagNode, s: Stmt) { super(n, d, PagEdgeKind.Copy, s); - }; + } } export class LoadPagEdge extends PagEdge { constructor(n: PagNode, d: PagNode, s: Stmt) { super(n, d, PagEdgeKind.Copy, s); - }; + } } export class WritePagEdge extends PagEdge { constructor(n: PagNode, d: PagNode, s: Stmt) { super(n, d, PagEdgeKind.Write, s); - }; + } } export class ThisPagEdge extends PagEdge { constructor(n: PagNode, d: PagNode, s: Stmt) { super(n, d, PagEdgeKind.This, s); - }; + } } type PagEdgeSet = Set; -export enum PagNodeKind { HeapObj, LocalVar, RefVar, Param, ThisRef, Function, GlobalThis, ExportInfo } +export enum PagNodeKind { + HeapObj, + LocalVar, + RefVar, + Param, + ThisRef, + Function, + GlobalThis, + ExportInfo, +} + export class PagNode extends BaseNode { private cid: ContextID | undefined; private value: Value; @@ -156,22 +174,22 @@ export class PagNode extends BaseNode { return this.basePt; } - public setBasePt(pt: NodeID) { + public setBasePt(pt: NodeID): void { this.basePt = pt; } public getCid(): ContextID { if (this.cid === undefined) { - throw new Error('cid is undefine') + throw new Error('cid is undefine'); } return this.cid; } - public setCid(cid: ContextID) { + public setCid(cid: ContextID): void { this.cid = cid; } - public setStmt(s: Stmt) { + public setStmt(s: Stmt): void { this.stmt = s; } @@ -180,7 +198,7 @@ export class PagNode extends BaseNode { } public hasOutgoingCopyEdge(): boolean { - return (this.copyOutEdges.size !== 0); + return this.copyOutEdges.size !== 0; } public getOutgoingCopyEdges(): PagEdgeSet { @@ -212,38 +230,38 @@ export class PagNode extends BaseNode { } public addAddressInEdge(e: AddrPagEdge): void { - this.addressInEdges === undefined ? this.addressInEdges = new Set() : undefined; + this.addressInEdges === undefined ? (this.addressInEdges = new Set()) : undefined; this.addressInEdges.add(e); this.addIncomingEdge(e); } public addAddressOutEdge(e: AddrPagEdge): void { - this.addressOutEdges === undefined ? this.addressOutEdges = new Set() : undefined; + this.addressOutEdges === undefined ? (this.addressOutEdges = new Set()) : undefined; this.addressOutEdges.add(e); this.addOutgoingEdge(e); } public addCopyInEdge(e: CopyPagEdge): void { - this.copyInEdges === undefined ? this.copyInEdges = new Set() : undefined; + this.copyInEdges === undefined ? (this.copyInEdges = new Set()) : undefined; this.copyInEdges.add(e); this.addIncomingEdge(e); } public addCopyOutEdge(e: CopyPagEdge): void { - this.copyOutEdges === undefined ? this.copyOutEdges = new Set() : undefined; + this.copyOutEdges === undefined ? (this.copyOutEdges = new Set()) : undefined; this.copyOutEdges.add(e); this.addOutgoingEdge(e); } public addLoadInEdge(e: LoadPagEdge): void { - this.loadInEdges === undefined ? this.loadInEdges = new Set() : undefined; + this.loadInEdges === undefined ? (this.loadInEdges = new Set()) : undefined; this.loadInEdges.add(e); this.addIncomingEdge(e); } public addLoadOutEdge(e: LoadPagEdge): void { - this.loadOutEdges === undefined ? this.loadOutEdges = new Set() : undefined; + this.loadOutEdges === undefined ? (this.loadOutEdges = new Set()) : undefined; this.loadOutEdges.add(e); this.addOutgoingEdge(e); } @@ -280,7 +298,7 @@ export class PagNode extends BaseNode { return this.pointTo; } - public addPointToElement(node: NodeID) { + public addPointToElement(node: NodeID): void { this.pointTo.insert(node); } @@ -288,13 +306,18 @@ export class PagNode extends BaseNode { this.pointTo = pts; } - public getOutEdges() { + public getOutEdges(): { + AddressEdge: PagEdgeSet; + CopyEdge: PagEdgeSet; + LoadEdge: PagEdgeSet; + WriteEdge: PagEdgeSet; + } { return { AddressEdge: this.addressOutEdges, CopyEdge: this.copyOutEdges, LoadEdge: this.loadOutEdges, - WriteEdge: this.writeOutEdges - } + WriteEdge: this.writeOutEdges, + }; } public getClonedFrom(): NodeID { @@ -320,7 +343,7 @@ export class PagNode extends BaseNode { case PagNodeKind.ExportInfo: return 'shape=tab,color=purple'; case PagNodeKind.ThisRef: - return 'shape=box,color=orange' + return 'shape=box,color=orange'; default: return 'shape=box'; } @@ -335,7 +358,7 @@ export class PagNode extends BaseNode { if (this.basePt) { label = label + ` base:{${this.basePt}}`; } - label = label + ` pts:{${Array.from(this.pointTo).join(',')}}` + label = label + ` pts:{${Array.from(this.pointTo).join(',')}}`; if (this.getKind() === PagNodeKind.Param) { param = this.value as ArkParameterRef; @@ -346,6 +369,10 @@ export class PagNode extends BaseNode { label = label + `\n${(this.value as ArkThisRef).toString()}`; } + if (this.getKind() === PagNodeKind.Function) { + label = label + ` thisPt:{${(this as unknown as PagFuncNode).getThisPt()}}`; + } + if (this.stmt) { label = label + `\n${this.stmt.toString()}`; let method = this.stmt.getCfg()?.getDeclaringMethod().getSubSignature().toString(); @@ -371,20 +398,20 @@ export class PagLocalNode extends PagNode { private sdkParam: boolean = false; constructor(id: NodeID, cid: ContextID | undefined = undefined, value: Local, stmt?: Stmt) { - super(id, cid, value, PagNodeKind.LocalVar, stmt) + super(id, cid, value, PagNodeKind.LocalVar, stmt); } - public addRelatedDynCallSite(cs: DynCallSite) { - this.relatedDynamicCallSite = this.relatedDynamicCallSite ?? new Set() + public addRelatedDynCallSite(cs: DynCallSite): void { + this.relatedDynamicCallSite = this.relatedDynamicCallSite ?? new Set(); - this.relatedDynamicCallSite.add(cs) + this.relatedDynamicCallSite.add(cs); } public getRelatedDynCallSites(): Set { return this.relatedDynamicCallSite ?? new Set(); } - public addRelatedUnknownCallSite(cs: CallSite) { + public addRelatedUnknownCallSite(cs: CallSite): void { this.relatedUnknownCallSite = this.relatedUnknownCallSite ?? new Set(); this.relatedUnknownCallSite.add(cs); @@ -400,10 +427,10 @@ export class PagLocalNode extends PagNode { this.propertyName = propertyName; } - public getStorage(): { StorageType: StorageType, PropertyName: string } { + public getStorage(): { StorageType: StorageType; PropertyName: string } { return { StorageType: this.storageType!, - PropertyName: this.propertyName! + PropertyName: this.propertyName!, }; } @@ -422,14 +449,13 @@ export class PagLocalNode extends PagNode { export class PagInstanceFieldNode extends PagNode { constructor(id: NodeID, cid: ContextID | undefined = undefined, instanceFieldRef: ArkInstanceFieldRef, stmt?: Stmt) { - super(id, cid, instanceFieldRef, PagNodeKind.RefVar, stmt) + super(id, cid, instanceFieldRef, PagNodeKind.RefVar, stmt); } - } export class PagStaticFieldNode extends PagNode { constructor(id: NodeID, cid: ContextID | undefined = undefined, staticFieldRef: ArkStaticFieldRef, stmt?: Stmt) { - super(id, cid, staticFieldRef, PagNodeKind.RefVar, stmt) + super(id, cid, staticFieldRef, PagNodeKind.RefVar, stmt); } } @@ -444,8 +470,8 @@ export class PagThisRefNode extends PagNode { return this.pointToNode; } - public addPTNode(ptNode: NodeID) { - this.pointToNode.push(ptNode) + public addPTNode(ptNode: NodeID): void { + this.pointToNode.push(ptNode); } } @@ -458,41 +484,40 @@ export class PagArrayNode extends PagNode { } } - /** * below is heapObj like Node */ export class PagNewExprNode extends PagNode { // store the cloned field node - fieldNodes!: Map + fieldNodes!: Map; constructor(id: NodeID, cid: ContextID | undefined = undefined, expr: AbstractExpr, stmt?: Stmt) { - super(id, cid, expr, PagNodeKind.HeapObj, stmt) + super(id, cid, expr, PagNodeKind.HeapObj, stmt); } public addFieldNode(fieldSignature: AbstractFieldRef, nodeID: NodeID): boolean { if (!this.fieldNodes) { - this.fieldNodes = new Map() + this.fieldNodes = new Map(); } if (this.fieldNodes.has(fieldSignature.getFieldSignature().toString())) { - return false + return false; } this.fieldNodes.set(fieldSignature.getFieldSignature().toString(), nodeID); - return true + return true; } public getFieldNode(fieldSignature: AbstractFieldRef): NodeID | undefined { if (!this.fieldNodes) { - return undefined + return undefined; } - return this.fieldNodes.get(fieldSignature.getFieldSignature().toString()) + return this.fieldNodes.get(fieldSignature.getFieldSignature().toString()); } public getFieldNodes(): Map | undefined { if (!this.fieldNodes) { - return undefined + return undefined; } - return this.fieldNodes + return this.fieldNodes; } } @@ -522,27 +547,75 @@ export class PagNewContainerExprNode extends PagNode { export class PagParamNode extends PagNode { constructor(id: NodeID, cid: ContextID | undefined = undefined, r: ArkParameterRef, stmt?: Stmt) { - super(id, cid, r, PagNodeKind.Param, stmt) + super(id, cid, r, PagNodeKind.Param, stmt); } } export class PagFuncNode extends PagNode { - private methodSignature!: MethodSignature + private methodSignature!: MethodSignature; + private thisPt!: NodeID; + private methodType!: BuiltApiType; + // for Function.bind, store the original call message and caller cid + private originCallSite!: CallSite; + private argsOffset: number = 0; + private originCid!: ContextID; // TODO: may add obj interface - constructor(id: NodeID, cid: ContextID | undefined = undefined, r: Value, stmt?: Stmt, method?: MethodSignature) { - super(id, cid, r, PagNodeKind.Function, stmt) + constructor(id: NodeID, cid: ContextID | undefined = undefined, r: Value, stmt?: Stmt, method?: MethodSignature, thisInstanceID?: NodeID) { + super(id, cid, r, PagNodeKind.Function, stmt); if (method) { this.methodSignature = method; + this.methodType = getBuiltInApiType(method); + } + + if (thisInstanceID) { + this.thisPt = thisInstanceID; } } - public setMethod(method: MethodSignature) { - this.methodSignature = method + public setMethod(method: MethodSignature): void { + this.methodSignature = method; + this.methodType = getBuiltInApiType(method); } public getMethod(): MethodSignature { - return this.methodSignature + return this.methodSignature; + } + + public setThisPt(thisPt: NodeID): void { + this.thisPt = thisPt; + } + + public getThisPt(): NodeID { + return this.thisPt; + } + + public setCS(callsite: CallSite): void { + this.originCallSite = callsite; + } + + public getCS(): CallSite { + return this.originCallSite; + } + + public setArgsOffset(offset: number): void { + this.argsOffset = offset; + } + + public getArgsOffset(): number { + return this.argsOffset; + } + + public getMethodType(): BuiltApiType { + return this.methodType; + } + + public setOriginCid(cid: ContextID): void { + this.originCid = cid; + } + + public getOriginCid(): ContextID { + return this.originCid; } } @@ -550,32 +623,31 @@ export class PagFuncNode extends PagNode { * almost same as PagNewExprNode, used only for globalThis and its field reference */ export class PagGlobalThisNode extends PagNode { - fieldNodes: Map + fieldNodes: Map; constructor(id: NodeID, cid: ContextID | undefined = undefined, r: Value, stmt?: Stmt) { - super(id, cid, r, PagNodeKind.GlobalThis, stmt) - this.fieldNodes = new Map() + super(id, cid, r, PagNodeKind.GlobalThis, stmt); + this.fieldNodes = new Map(); } public addFieldNode(fieldSignature: AbstractFieldRef, nodeID: NodeID): boolean { if (this.fieldNodes.has(fieldSignature.getFieldSignature().toString())) { - return false + return false; } this.fieldNodes.set(fieldSignature.getFieldSignature().toString(), nodeID); - return true + return true; } public getFieldNode(fieldSignature: AbstractFieldRef): NodeID | undefined { - return this.fieldNodes.get(fieldSignature.getFieldSignature().toString()) + return this.fieldNodes.get(fieldSignature.getFieldSignature().toString()); } public getFieldNodes(): Map | undefined { - return this.fieldNodes + return this.fieldNodes; } } export class Pag extends BaseExplicitGraph { - private cg!: CallGraph; private contextValueToIdMap: Map> = new Map(); private ExportInfoToIdMap?: Map; @@ -612,27 +684,27 @@ export class Pag extends BaseExplicitGraph { } // Not found - let cloneNode = this.addPagNode(src.getCid(), src.getValue(), src.getStmt(), false) + let cloneNode = this.addPagNode(src.getCid(), src.getValue(), src.getStmt(), false); cloneNode.setClonedFrom(src.getID()); cloneSet.set(basePt, cloneNode.getID()); return cloneNode; } public getOrClonePagFieldNode(src: PagInstanceFieldNode, basePt: NodeID): PagInstanceFieldNode | undefined { - let baseNode = this.getNode(basePt) + let baseNode = this.getNode(basePt); if (baseNode instanceof PagNewExprNode || baseNode instanceof PagGlobalThisNode) { // check if real field node has been created with basePT, using FieldSignature as key - let existedNode = baseNode.getFieldNode(src.getValue() as ArkInstanceFieldRef) + let existedNode = baseNode.getFieldNode(src.getValue() as ArkInstanceFieldRef); if (existedNode) { - return this.getNode(existedNode) as PagInstanceFieldNode + return this.getNode(existedNode) as PagInstanceFieldNode; } - let fieldNode = this.getOrClonePagNode(src, basePt) - baseNode.addFieldNode(src.getValue() as ArkInstanceFieldRef, fieldNode.getID()) - fieldNode.setBasePt(basePt) - return fieldNode + let fieldNode = this.getOrClonePagNode(src, basePt); + baseNode.addFieldNode(src.getValue() as ArkInstanceFieldRef, fieldNode.getID()); + fieldNode.setBasePt(basePt); + return fieldNode; } else { - logger.error(`Error clone field node ${src.getValue()}`) + logger.error(`Error clone field node ${src.getValue()}`); return undefined; } } @@ -650,12 +722,15 @@ export class Pag extends BaseExplicitGraph { if (src) { fieldNode = this.getOrClonePagNode(src, basePt); } else if (base) { - const containerFieldSignature = new FieldSignature('field', + const containerFieldSignature = new FieldSignature( + 'field', new ClassSignature('container', new FileSignature('container', 'lib.es2015.collection.d.ts')), - new UnclearReferenceType('')); + new UnclearReferenceType('') + ); fieldNode = this.getOrClonePagNode( // TODO: cid check - this.addPagNode(0, new ArkInstanceFieldRef(base, containerFieldSignature)), basePt + this.addPagNode(0, new ArkInstanceFieldRef(base, containerFieldSignature)), + basePt ); } @@ -675,6 +750,17 @@ export class Pag extends BaseExplicitGraph { return undefined; } + public getOrClonePagFuncNode(basePt: NodeID): PagFuncNode | undefined { + let baseNode = this.getNode(basePt) as PagNode; + if (baseNode instanceof PagFuncNode) { + let clonedFuncNode = this.getOrClonePagNode(baseNode, basePt) as PagFuncNode; + return clonedFuncNode; + } else { + logger.error(`Error clone func node ${baseNode.getValue()}`); + return undefined; + } + } + public addPagNode(cid: ContextID, value: PagNodeType, stmt?: Stmt, refresh: boolean = true): PagNode { let id: NodeID = this.nodeNum + 1; let pagNode: PagNode; @@ -741,8 +827,7 @@ export class Pag extends BaseExplicitGraph { } } - private addContextOrExportInfoMap(refresh: boolean, cid: ContextID, id: NodeID, - value: PagNodeType, pagNode: PagNode, stmt?: Stmt): void { + private addContextOrExportInfoMap(refresh: boolean, cid: ContextID, id: NodeID, value: PagNodeType, pagNode: PagNode, stmt?: Stmt): void { if (!(value instanceof ExportInfo)) { this.addContextMap(refresh, cid, id, value, stmt!, pagNode!); } else { @@ -774,9 +859,11 @@ export class Pag extends BaseExplicitGraph { let base = value.getBase(); //TODO: remove below once this Local is not uniq in %instInit is fix if (base instanceof Local && base.getName() === 'this') { - stmt?.getCfg() ?.getStmts() .forEach((s) => { - if (s instanceof ArkAssignStmt && s.getLeftOp() instanceof Local && - (s.getLeftOp() as Local).getName() === 'this') { + stmt + ?.getCfg() + ?.getStmts() + .forEach(s => { + if (s instanceof ArkAssignStmt && s.getLeftOp() instanceof Local && (s.getLeftOp() as Local).getName() === 'this') { base = s.getLeftOp() as Local; return; } @@ -820,11 +907,11 @@ export class Pag extends BaseExplicitGraph { public getOrNewThisRefNode(thisRefNodeID: NodeID, value: ArkThisRef): PagNode { if (thisRefNodeID !== -1) { - return this.getNode(thisRefNodeID) as PagNode + return this.getNode(thisRefNodeID) as PagNode; } - let thisRefNode = this.addPagThisRefNode(value) - return thisRefNode + let thisRefNode = this.addPagThisRefNode(value); + return thisRefNode; } public getOrNewThisLocalNode(cid: ContextID, ptNode: NodeID, value: Local, s?: Stmt): PagNode { @@ -904,11 +991,7 @@ export class Pag extends BaseExplicitGraph { case PagEdgeKind.InterProceduralCopy: src.addCopyOutEdge(edge); dst.addCopyInEdge(edge); - if (src instanceof PagFuncNode || - src instanceof PagGlobalThisNode || - src instanceof PagNewExprNode || - src instanceof PagNewContainerExprNode - ) { + if (src instanceof PagFuncNode || src instanceof PagGlobalThisNode || src instanceof PagNewExprNode || src instanceof PagNewContainerExprNode) { this.addrEdge.add(edge); this.stashAddrEdge.add(edge); } @@ -932,7 +1015,6 @@ export class Pag extends BaseExplicitGraph { dst.addThisInEdge(edge); break; default: - ; } return true; } @@ -941,7 +1023,7 @@ export class Pag extends BaseExplicitGraph { return this.stashAddrEdge; } - public resetAddrEdges() { + public resetAddrEdges(): void { this.stashAddrEdge.clear(); } @@ -956,8 +1038,17 @@ export class Pag extends BaseExplicitGraph { } export type InterProceduralSrcType = Local; -export type IntraProceduralEdge = { src: Value, dst: Value, kind: PagEdgeKind, stmt: Stmt } -export type InterProceduralEdge = { src: InterProceduralSrcType, dst: Value, kind: PagEdgeKind } +export type IntraProceduralEdge = { + src: Value; + dst: Value; + kind: PagEdgeKind; + stmt: Stmt; +}; +export type InterProceduralEdge = { + src: InterProceduralSrcType; + dst: Value; + kind: PagEdgeKind; +}; export class FuncPag { private internalEdges!: Set; @@ -1000,7 +1091,7 @@ export class FuncPag { } public addInternalEdge(stmt: ArkAssignStmt, k: PagEdgeKind): boolean { - this.internalEdges === undefined ? this.internalEdges = new Set() : undefined; + this.internalEdges === undefined ? (this.internalEdges = new Set()) : undefined; let lhOp = stmt.getLeftOp(); let rhOp = stmt.getRightOp(); @@ -1008,7 +1099,12 @@ export class FuncPag { return false; } - let iEdge: IntraProceduralEdge = { src: rhOp, dst: lhOp, kind: k, stmt: stmt }; + let iEdge: IntraProceduralEdge = { + src: rhOp, + dst: lhOp, + kind: k, + stmt: stmt, + }; this.internalEdges.add(iEdge); return true; @@ -1029,4 +1125,4 @@ export class InterFuncPag { public addToInterProceduralEdgeSet(e: InterProceduralEdge): void { this.interFuncEdges.add(e); } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PagBuilder.ts b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PagBuilder.ts index 98abe7e584..bd3917b090 100644 --- a/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PagBuilder.ts +++ b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PagBuilder.ts @@ -14,8 +14,8 @@ */ import { CallGraph, CallGraphNode, CallGraphNodeKind, CallSite, DynCallSite, FuncID } from '../model/CallGraph'; -import { Scene } from '../../Scene' -import { ArkAssignStmt, ArkInvokeStmt, ArkReturnStmt, Stmt } from '../../core/base/Stmt' +import { Scene } from '../../Scene'; +import { ArkAssignStmt, ArkInvokeStmt, ArkReturnStmt, Stmt } from '../../core/base/Stmt'; import { AbstractExpr, AbstractInvokeExpr, @@ -23,25 +23,18 @@ import { ArkNewArrayExpr, ArkNewExpr, ArkPtrInvokeExpr, - ArkStaticInvokeExpr + ArkStaticInvokeExpr, } from '../../core/base/Expr'; -import { - AbstractFieldRef, - ArkArrayRef, - ArkInstanceFieldRef, - ArkParameterRef, - ArkStaticFieldRef, - ArkThisRef -} from '../../core/base/Ref'; +import { AbstractFieldRef, ArkArrayRef, ArkInstanceFieldRef, ArkParameterRef, ArkStaticFieldRef, ArkThisRef } from '../../core/base/Ref'; import { Value } from '../../core/base/Value'; import { ArkMethod } from '../../core/model/ArkMethod'; -import Logger, { LOG_MODULE_TYPE } from "../../utils/logger"; +import Logger, { LOG_MODULE_TYPE } from '../../utils/logger'; import { Local } from '../../core/base/Local'; import { NodeID } from '../../core/graph/BaseExplicitGraph'; import { ClassSignature } from '../../core/model/ArkSignature'; import { ArkClass } from '../../core/model/ArkClass'; -import { ClassType, FunctionType, StringType } from '../../core/base/Type'; -import { Constant } from '../../core/base/Constant'; +import { ArrayType, ClassType, FunctionType, StringType } from '../../core/base/Type'; +import { Constant, NullConstant } from '../../core/base/Constant'; import { PAGStat } from '../common/Statistics'; import { ContextID, DUMMY_CID, KLimitedContextSensitive } from './Context'; import { @@ -59,12 +52,12 @@ import { PagNodeType, PagThisRefNode, StorageLinkEdgeType, - StorageType + StorageType, } from './Pag'; import { GLOBAL_THIS_NAME } from '../../core/common/TSConst'; import { IPtsCollection } from './PtsDS'; import { UNKNOWN_FILE_NAME } from '../../core/common/Const'; -import { IsCollectionAPI, IsCollectionMapSet, IsCollectionSetAdd } from './PTAUtils'; +import { BuiltApiType, getBuiltInApiType } from './PTAUtils'; import { PointerAnalysisConfig, PtaAnalysisScale } from './PointerAnalysisConfig'; const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'PTA'); @@ -85,7 +78,7 @@ export class PagBuilder { private scale: PtaAnalysisScale; private funcPags: Map; private interFuncPags?: Map; - private handledFunc: Set = new Set() + private handledFunc: Set = new Set(); private ctx: KLimitedContextSensitive; private scene: Scene; private worklist: CSFuncID[] = []; @@ -99,20 +92,21 @@ export class PagBuilder { private sdkMethodReturnValueMap: Map> = new Map(); // record the SDK API param, and create fake Values private methodParamValueMap: Map> = new Map(); - private fakeSdkMethodParamDeclaringStmt: Stmt = new ArkAssignStmt(new Local(""), new Local("")); + private fakeSdkMethodParamDeclaringStmt: Stmt = new ArkAssignStmt(new Local(''), new Local('')); private funcHandledThisRound: Set = new Set(); - private updatedNodesThisRound: Map> = new Map() + private updatedNodesThisRound: Map> = new Map(); private singletonFuncMap: Map = new Map(); private globalThisValue: Local = new Local(GLOBAL_THIS_NAME); private globalThisPagNode?: PagGlobalThisNode; private storagePropertyMap: Map> = new Map(); private externalScopeVariableMap: Map = new Map(); + private retriggerNodesList: Set = new Set(); constructor(p: Pag, cg: CallGraph, s: Scene, kLimit: number, scale: PtaAnalysisScale) { this.pag = p; this.cg = cg; this.scale = scale; - this.funcPags = new Map; + this.funcPags = new Map(); this.ctx = new KLimitedContextSensitive(kLimit); this.scene = s; this.pagStat = new PAGStat(); @@ -129,15 +123,15 @@ export class PagBuilder { } this.worklist.push(cs); - return cs + return cs; } - private addToFuncHandledListThisRound(id: FuncID) { + private addToFuncHandledListThisRound(id: FuncID): void { if (this.funcHandledThisRound.has(id)) { return; } - this.funcHandledThisRound.add(id) + this.funcHandledThisRound.add(id); } public buildForEntries(funcIDs: FuncID[]): void { @@ -188,20 +182,18 @@ export class PagBuilder { return false; } - let cfg = arkMethod.getCfg() + let cfg = arkMethod.getCfg(); if (!cfg) { this.buildSDKFuncPag(funcID); - return false + return false; } - logger.trace(`[build FuncPag] ${arkMethod.getSignature().toString()}`) + logger.trace(`[build FuncPag] ${arkMethod.getSignature().toString()}`); let fpag = new FuncPag(); for (let stmt of cfg.getStmts()) { if (stmt instanceof ArkAssignStmt) { - stmt.getRightOp().getUses().forEach((v) => { - this.handleValueFromExternalScope(v, funcID); - }); + this.processExternalScopeValue(stmt.getRightOp(), funcID); // Add non-call edges let kind = this.getEdgeKindForAssignStmt(stmt); if (kind !== PagEdgeKind.Unknown) { @@ -212,6 +204,7 @@ export class PagBuilder { // handle call this.buildInvokeExprInAssignStmt(stmt, fpag); } else if (stmt instanceof ArkInvokeStmt && this.scale === PtaAnalysisScale.WholeProgram) { + this.processExternalScopeValue(stmt.getInvokeExpr(), funcID); this.buildInvokeExprInInvokeStmt(stmt, fpag); } else { // TODO: need handle other type of stmt? @@ -230,7 +223,7 @@ export class PagBuilder { if (callSites.length !== 0) { // direct call is already existing in CG // TODO: API Invoke stmt has anonymous method param, how to add these param into callee - callSites.forEach((cs) => { + callSites.forEach(cs => { this.addFuncPagCallSite(fpag, cs, ivkExpr); }); } else { @@ -246,8 +239,7 @@ export class PagBuilder { private addFuncPagCallSite(fpag: FuncPag, cs: CallSite, ivkExpr: AbstractInvokeExpr): void { if (ivkExpr instanceof ArkStaticInvokeExpr) { - if (ivkExpr.getMethodSignature().getDeclaringClassSignature() - .getDeclaringFileSignature().getFileName() === UNKNOWN_FILE_NAME) { + if (ivkExpr.getMethodSignature().getDeclaringClassSignature().getDeclaringFileSignature().getFileName() === UNKNOWN_FILE_NAME) { fpag.addUnknownCallSite(cs); } else { fpag.addNormalCallSite(cs); @@ -263,7 +255,7 @@ export class PagBuilder { // direct call or constructor call is already existing in CG // TODO: some ptr invoke stmt is recognized as Static invoke in tests/resources/callgraph/funPtrTest1/fnPtrTest4.ts // TODO: instance invoke(ptr invoke) - callSites.forEach((cs) => { + callSites.forEach(cs => { if (this.cg.isUnknownMethod(cs.calleeFuncID)) { fpag.addUnknownCallSite(cs); } else { @@ -282,6 +274,21 @@ export class PagBuilder { } } + private processExternalScopeValue(value: Value, funcID: FuncID): void { + let dummyMainFuncID = this.cg.getDummyMainFuncID(); + if (dummyMainFuncID && funcID === dummyMainFuncID) { + return; + } + + if (value instanceof Local) { + this.handleValueFromExternalScope(value, funcID); + } else if (value instanceof ArkInstanceInvokeExpr) { + value.getUses().forEach(v => { + this.handleValueFromExternalScope(v, funcID); + }); + } + } + /** * will not create real funcPag, only create param values */ @@ -348,7 +355,7 @@ export class PagBuilder { return paramPagNodes; } - public buildPagFromFuncPag(funcID: FuncID, cid: ContextID) { + public buildPagFromFuncPag(funcID: FuncID, cid: ContextID): void { let funcPag = this.funcPags.get(funcID); if (funcPag === undefined) { return; @@ -364,7 +371,7 @@ export class PagBuilder { } this.addCallsEdgesFromFuncPag(funcPag, cid); - this.addDynamicCallSite(funcPag, funcID); + this.addDynamicCallSite(funcPag, funcID, cid); this.addUnknownCallSite(funcPag, funcID); this.handledFunc.add(`${cid}-${funcID}`); } @@ -394,7 +401,7 @@ export class PagBuilder { // for demand-driven analysis, add fake parameter heapObj nodes if (e.src instanceof ArkParameterRef && this.scale === PtaAnalysisScale.MethodLevel) { - let paramObjNodeID = paramNodes?.get(paramRefIndex ++); + let paramObjNodeID = paramNodes?.get(paramRefIndex++); if (!paramObjNodeID) { continue; } @@ -425,14 +432,13 @@ export class PagBuilder { } // Add edge to thisRef for special calls - if (calleeCGNode.getKind() === CallGraphNodeKind.constructor || - calleeCGNode.getKind() === CallGraphNodeKind.intrinsic) { - let callee = this.scene.getMethod(this.cg.getMethodByFuncID(cs.calleeFuncID)!)! + if (calleeCGNode.getKind() === CallGraphNodeKind.constructor || calleeCGNode.getKind() === CallGraphNodeKind.intrinsic) { + let callee = this.scene.getMethod(this.cg.getMethodByFuncID(cs.calleeFuncID)!)!; if (ivkExpr instanceof ArkInstanceInvokeExpr) { - let baseNode = this.getOrNewPagNode(cid, ivkExpr.getBase()) + let baseNode = this.getOrNewPagNode(cid, ivkExpr.getBase()); let baseNodeID = baseNode.getID(); - this.addThisRefCallEdge(baseNodeID, cid, ivkExpr, callee, calleeCid, cs.callerFuncID); + this.addThisRefCallEdge(baseNodeID, cid, ivkExpr.getBase(), callee, calleeCid, cs.callerFuncID); } else { logger.error(`constructor or intrinsic func is static ${ivkExpr!.toString()}`); } @@ -442,146 +448,7 @@ export class PagBuilder { return true; } - /** - * process Storage API - * @returns boolean: check if the cs represent a Storage API, no matter the API will success or fail - */ - private processStorage(cs: CallSite | DynCallSite, calleeCGNode: CallGraphNode, cid: ContextID): boolean { - let storageName = calleeCGNode.getMethod().getDeclaringClassSignature().getClassName(); - let storageType: StorageType = this.getStorageType(storageName, cs, cid); - - // TODO: add other storages - if (storageType === StorageType.APP_STORAGE) { - let calleeName = calleeCGNode.getMethod().getMethodSubSignature().getMethodName(); - - // TODO: complete AppStorage API - if (calleeName === 'setOrCreate') { - this.processStorageSetOrCreate(cs, cid); - } else if (calleeName === 'link') { - this.processStorageLink(cs, cid); - } else if (calleeName === 'prop') { - this.processStorageProp(cs, cid); - } else if (calleeName === 'set') { - this.processStorageSet(cs, cid); - } else if (calleeName === 'get') { - this.processStorageGet(cs, cid); - } - return true; - } else if (storageType === StorageType.LOCAL_STORAGE) { - // TODO: LocalStorage is not Static - } - - return false; - } - - private processStorageSetOrCreate(cs: CallSite | DynCallSite, cid: ContextID): void { - let propertyStr = this.getPropertyName(cs.args![0]); - if (!propertyStr) { - return; - } - - let propertyName = propertyStr; - let propertyNode = this.getOrNewPropertyNode(StorageType.APP_STORAGE, propertyName, cs.callStmt); - let storageObj = cs.args![1]; - - this.addPropertyLinkEdge(propertyNode, storageObj, cid, cs.callStmt, StorageLinkEdgeType.Local2Property); - } - - private processStorageLink(cs: CallSite | DynCallSite, cid: ContextID): void { - let propertyStr = this.getPropertyName(cs.args![0]); - if (!propertyStr) { - return; - } - - let propertyName = propertyStr; - let propertyNode = this.getOrNewPropertyNode(StorageType.APP_STORAGE, propertyName, cs.callStmt); - let leftOp = (cs.callStmt as ArkAssignStmt).getLeftOp() as Local; - let linkedOpNode = this.pag.getOrNewNode(cid, leftOp) as PagNode; - if (linkedOpNode instanceof PagLocalNode) { - linkedOpNode.setStorageLink(StorageType.APP_STORAGE, propertyName); - } - - this.pag.addPagEdge(propertyNode, linkedOpNode, PagEdgeKind.Copy); - this.pag.addPagEdge(linkedOpNode, propertyNode, PagEdgeKind.Copy); - } - - private processStorageProp(cs: CallSite | DynCallSite, cid: ContextID): void { - let propertyStr = this.getPropertyName(cs.args![0]); - if (!propertyStr) { - return; - } - - let propertyName = propertyStr; - let propertyNode = this.getOrNewPropertyNode(StorageType.APP_STORAGE, propertyName, cs.callStmt); - let leftOp = (cs.callStmt as ArkAssignStmt).getLeftOp() as Local; - let linkedOpNode = this.pag.getOrNewNode(cid, leftOp) as PagNode; - if (linkedOpNode instanceof PagLocalNode) { - linkedOpNode.setStorageLink(StorageType.APP_STORAGE, propertyName); - } - - this.pag.addPagEdge(propertyNode, linkedOpNode, PagEdgeKind.Copy); - } - - private processStorageSet(cs: CallSite | DynCallSite, cid: ContextID): void { - let ivkExpr: AbstractInvokeExpr = cs.callStmt.getInvokeExpr()!; - if (ivkExpr instanceof ArkInstanceInvokeExpr) { - let base = ivkExpr.getBase(); - let baseNode = this.pag.getOrNewNode(cid, base) as PagLocalNode; - - if (baseNode.isStorageLinked()) { - let argsNode = this.pag.getOrNewNode(cid, cs.args![0]) as PagNode; - - this.pag.addPagEdge(argsNode, baseNode, PagEdgeKind.Copy); - } - } else if (ivkExpr instanceof ArkStaticInvokeExpr) { - // TODO: process AppStorage.set() - } - } - - private processStorageGet(cs: CallSite | DynCallSite, cid: ContextID): void { - if (!(cs.callStmt instanceof ArkAssignStmt)) { - return; - } - let leftOp = (cs.callStmt as ArkAssignStmt).getLeftOp() as Local; - let ivkExpr = cs.callStmt.getInvokeExpr(); - let propertyName!: string; - if (ivkExpr instanceof ArkStaticInvokeExpr) { - let propertyStr = this.getPropertyName(cs.args![0]); - if (propertyStr) { - propertyName = propertyStr; - } - } else if (ivkExpr instanceof ArkInstanceInvokeExpr) { - let baseNode = this.pag.getOrNewNode(cid, ivkExpr.getBase()) as PagLocalNode; - if (baseNode.isStorageLinked()) { - propertyName = baseNode.getStorage().PropertyName!; - } - } - - let propertyNode = this.getPropertyNode(StorageType.APP_STORAGE, propertyName, cs.callStmt); - if (!propertyNode) { - return; - } - - this.pag.addPagEdge( - propertyNode, this.pag.getOrNewNode(cid, leftOp, cs.callStmt), - PagEdgeKind.Copy, cs.callStmt - ); - } - - private getPropertyName(value: Value): string | undefined { - if (value instanceof Local) { - let type = value.getType(); - if (type instanceof StringType) { - return type.getName(); - } - } else if (value instanceof Constant) { - return value.getValue(); - } - - return undefined; - } - - public addDynamicCallSite(funcPag: FuncPag, funcID: FuncID) { + public addDynamicCallSite(funcPag: FuncPag, funcID: FuncID, cid: ContextID): void { // add dyn callsite in funcpag to base node for (let cs of funcPag.getDynamicCallSites()) { let invokeExpr: AbstractInvokeExpr = cs.callStmt.getInvokeExpr()!; @@ -590,6 +457,13 @@ export class PagBuilder { base = invokeExpr.getBase(); } else if (invokeExpr instanceof ArkPtrInvokeExpr && invokeExpr.getFuncPtrLocal() instanceof Local) { base = invokeExpr.getFuncPtrLocal() as Local; + } else if (invokeExpr instanceof ArkPtrInvokeExpr && invokeExpr.getFuncPtrLocal() instanceof AbstractFieldRef) { + /** + * TODO: wait for IR change + * throw error in ptrInvoke with field ref + * this.field() // field is lambda expression + */ + continue; } // TODO: check base under different cid let baseNodeIDs = this.pag.getNodesByValue(base); @@ -614,6 +488,10 @@ export class PagBuilder { node.addRelatedDynCallSite(cs); } + + if (cs.callStmt instanceof ArkAssignStmt) { + this.getOrNewPagNode(cid, cs.callStmt.getLeftOp(), cs.callStmt); + } } } @@ -626,9 +504,8 @@ export class PagBuilder { let locals = method.getBody()?.getLocals()!; - funcPag.getUnknownCallSites().forEach((unknownCallSite) => { - let calleeName = unknownCallSite.callStmt.getInvokeExpr()?.getMethodSignature() - .getMethodSubSignature().getMethodName()!; + funcPag.getUnknownCallSites().forEach(unknownCallSite => { + let calleeName = unknownCallSite.callStmt.getInvokeExpr()?.getMethodSignature().getMethodSubSignature().getMethodName()!; let base = locals.get(calleeName); if (!base) { @@ -647,7 +524,7 @@ export class PagBuilder { node.addRelatedUnknownCallSite(unknownCallSite); } - }) + }); } public addDynamicCallEdge(cs: DynCallSite | CallSite, baseClassPTNode: NodeID, cid: ContextID): NodeID[] { @@ -666,33 +543,40 @@ export class PagBuilder { let dstCGNode = this.cg.getCallGraphNodeByMethod(callee.getSignature()); let callerNode = this.cg.getNode(cs.callerFuncID) as CallGraphNode; if (!callerNode) { - throw new Error("Can not get caller method node"); + throw new Error('Can not get caller method node'); } // update call graph // TODO: movo to cgbuilder + this.cg.addDynamicCallEdge(callerNode.getID(), dstCGNode.getID(), cs.callStmt); - if (!this.cg.detectReachable(dstCGNode.getID(), callerNode.getID())) { - let calleeCid = this.ctx.getOrNewContext(cid, dstCGNode.getID(), true); - let staticCS = new CallSite(cs.callStmt, cs.args, dstCGNode.getID(), cs.callerFuncID); - if (this.scale === PtaAnalysisScale.MethodLevel) { - srcNodes.push(...this.addStaticPagCallReturnEdge(staticCS, baseClassPTNode, calleeCid)); - continue; - } - srcNodes.push(...this.processContainerPagCallEdge(staticCS, cid, baseClassPTNode)); - srcNodes.push(...this.addStaticPagCallEdge(staticCS, cid, calleeCid)); + if (this.cg.detectReachable(dstCGNode.getID(), callerNode.getID())) { + return srcNodes; + } - // Pass base's pts to callee's this pointer - if (!dstCGNode.isSdkMethod() && ivkExpr instanceof ArkInstanceInvokeExpr) { - let srcBaseNode = this.addThisRefCallEdge(baseClassPTNode, cid, ivkExpr, callee!, calleeCid, cs.callerFuncID); - srcNodes.push(srcBaseNode); - } + let calleeCid = this.ctx.getOrNewContext(cid, dstCGNode.getID(), true); + let staticCS = new CallSite(cs.callStmt, cs.args, dstCGNode.getID(), cs.callerFuncID); + + if (this.scale === PtaAnalysisScale.MethodLevel) { + srcNodes.push(...this.addStaticPagCallReturnEdge(staticCS, baseClassPTNode, calleeCid)); + continue; + } + + if (getBuiltInApiType(ivkExpr?.getMethodSignature()!) === BuiltApiType.NotBuiltIn) { + srcNodes.push(...this.processNormalMethodPagCallEdge(staticCS, cid, calleeCid, baseClassPTNode)); + } else { + // special SDK call: Container API, Function API + srcNodes.push(...this.processBuiltInMethodPagCallEdge(staticCS, cid, calleeCid, baseClassPTNode)); } } return srcNodes; } + /** + * all possible callee methods of a dynamic call site + * handle both PtrInvokeExpr and InstanceInvokeExpr + */ private getDynamicCallee(ptNode: PagNode, value: Value, ivkExpr: AbstractInvokeExpr, cs: DynCallSite | CallSite): ArkMethod[] { let callee: ArkMethod[] = []; @@ -750,29 +634,196 @@ export class PagBuilder { return callee; } - public addUpdatedNode(nodeID: NodeID, diffPT: IPtsCollection) { - let ptaConfig = PointerAnalysisConfig.getInstance(); - let updatedNode = this.updatedNodesThisRound.get(nodeID) ?? new ptaConfig.ptsCollectionCtor(); - updatedNode.union(diffPT); - this.updatedNodesThisRound.set(nodeID, updatedNode); + public processNormalMethodPagCallEdge(staticCS: CallSite, cid: ContextID, calleeCid: ContextID, baseClassPTNode: NodeID): NodeID[] { + let srcNodes: NodeID[] = []; + let ivkExpr = staticCS.callStmt.getInvokeExpr()!; + let ptNode = this.pag.getNode(baseClassPTNode) as PagNode; + let dstCGNode = this.cg.getNode(staticCS.calleeFuncID) as CallGraphNode; + let callee = this.cg.getArkMethodByFuncID(staticCS.calleeFuncID); + // Dynamic call, Ptr call, normal SDK call + srcNodes.push(...this.addStaticPagCallEdge(staticCS, cid, calleeCid, ptNode)); + + // Pass base's pts to callee's this pointer + if (!dstCGNode.isSdkMethod() && ivkExpr instanceof ArkInstanceInvokeExpr) { + let srcBaseNode = this.addThisRefCallEdge(baseClassPTNode, cid, ivkExpr.getBase(), callee!, calleeCid, staticCS.callerFuncID); + srcNodes.push(srcBaseNode); + } else if (!dstCGNode.isSdkMethod() && ivkExpr instanceof ArkPtrInvokeExpr) { + let originCS = (ptNode as PagFuncNode).getCS(); + if (!originCS) { + return srcNodes; + } + + let thisValue = originCS.args![0]; + + if (!(thisValue instanceof Local)) { + return srcNodes; + } + this.addThisRefCallEdge(baseClassPTNode, (ptNode as PagFuncNode).getOriginCid(), thisValue, callee!, calleeCid, staticCS.callerFuncID); + } + + return srcNodes; } - public getUpdatedNodes() { - return this.updatedNodesThisRound; + /** + * include container API, Function API + */ + public processBuiltInMethodPagCallEdge(staticCS: CallSite, cid: ContextID, calleeCid: ContextID, baseClassPTNode: NodeID): NodeID[] { + let srcNodes: NodeID[] = []; + let ivkExpr = staticCS.callStmt.getInvokeExpr()!; + let callee = this.scene.getMethod(ivkExpr.getMethodSignature()); + let realCallee = this.cg.getArkMethodByFuncID(staticCS.calleeFuncID); + if (!callee) { + return srcNodes; + } + + let builtInType = getBuiltInApiType(callee.getSignature()); + + if (builtInType === BuiltApiType.NotBuiltIn || !realCallee) { + return srcNodes; + } + + switch (builtInType) { + case BuiltApiType.SetAdd: + case BuiltApiType.MapSet: + this.processContainerPagCallEdge(staticCS, cid, baseClassPTNode, builtInType); + break; + + case BuiltApiType.FunctionCall: + /** + * set this and param + * function.call(thisArg, arg1, arg2, ...) + */ + this.handleFunctionCall(staticCS, cid, calleeCid, realCallee, srcNodes, baseClassPTNode); + break; + + case BuiltApiType.FunctionApply: + /** + * set this, resolve array param + * function.apply(thisArg, [argsArray]) + */ + this.handleFunctionApply(staticCS, cid, calleeCid, realCallee, srcNodes, baseClassPTNode); + break; + + case BuiltApiType.FunctionBind: + /** + * clone the function node and add the this pointer, origin callsite, args offset to it + * let f = function.bind(thisArg, arg1, arg2, ...) + * f(); + */ + this.handleFunctionBind(staticCS, cid, baseClassPTNode, srcNodes); + break; + } + + return srcNodes; } - public resetUpdatedNodes() { - this.updatedNodesThisRound.clear(); + private processContainerPagCallEdge(cs: CallSite, cid: ContextID, baseClassPTNode: NodeID, type: BuiltApiType): NodeID[] { + let srcNodes: NodeID[] = []; + let calleeNode = this.cg.getNode(cs.calleeFuncID) as CallGraphNode; + let calleeMethod: ArkMethod | null = this.scene.getMethod(calleeNode.getMethod()); + let ptNode = this.pag.getNode(baseClassPTNode) as PagNode; + + if (!calleeMethod || !(ptNode instanceof PagNewContainerExprNode)) { + return srcNodes; + } + + let containerValue = (cs.callStmt.getInvokeExpr() as ArkInstanceInvokeExpr).getBase(); + + const containerValueProcess = (argIndex: number): void => { + let srcNode = this.pag.getOrNewNode(cid, cs.args![argIndex], cs.callStmt); + let realContainerFieldPagNode = this.pag.getOrClonePagContainerFieldNode(baseClassPTNode, undefined, containerValue); + + if (realContainerFieldPagNode) { + // In some cases, the value of a variable of array type may not be an explicit array object, + // and the value of `realContainerFieldPagNode` will be undefined. + this.pag.addPagEdge(srcNode, realContainerFieldPagNode, PagEdgeKind.Copy, cs.callStmt); + srcNodes.push(srcNode.getID()); + } + }; + + if (type === BuiltApiType.SetAdd) { + containerValueProcess(0); + } else if (type === BuiltApiType.MapSet) { + containerValueProcess(1); + } + + return srcNodes; + } + + private handleFunctionCall( + staticCS: CallSite, + cid: ContextID, + calleeCid: ContextID, + realCallee: ArkMethod, + srcNodes: NodeID[], + baseClassPTNode: NodeID + ): void { + this.buildFuncPagAndAddToWorklist(new CSFuncID(calleeCid, staticCS.calleeFuncID)); + srcNodes.push(...this.addCallParamPagEdge(realCallee, staticCS.args!, staticCS.callStmt, cid, calleeCid, 1)); + this.addThisEdge(staticCS, cid, realCallee, srcNodes, baseClassPTNode, calleeCid); + } + + private handleFunctionApply( + staticCS: CallSite, + cid: ContextID, + calleeCid: ContextID, + realCallee: ArkMethod, + srcNodes: NodeID[], + baseClassPTNode: NodeID + ): void { + this.buildFuncPagAndAddToWorklist(new CSFuncID(calleeCid, staticCS.calleeFuncID)); + let callerMethod = this.cg.getArkMethodByFuncID(staticCS.callerFuncID); + if (!callerMethod) { + throw new Error('Cannot get caller method'); + } + let argsRealValues = this.transferArrayValues(callerMethod, staticCS.args![1]); + srcNodes.push(...this.addCallParamPagEdge(realCallee, argsRealValues, staticCS.callStmt, cid, calleeCid, 0)); + this.addThisEdge(staticCS, cid, realCallee, srcNodes, baseClassPTNode, calleeCid); + } + + private handleFunctionBind(staticCS: CallSite, cid: ContextID, baseClassPTNode: NodeID, srcNodes: NodeID[]): void { + let srcNode = this.pag.getOrClonePagFuncNode(baseClassPTNode); + if (!srcNode) { + return; + } + this.setFunctionThisPt(staticCS, srcNode, cid); + + let dstNode = this.getOrNewPagNode(cid, (staticCS.callStmt as ArkAssignStmt).getLeftOp() as Local); + this.pag.addPagEdge(srcNode, dstNode, PagEdgeKind.Copy, staticCS.callStmt); + srcNodes.push(srcNode.getID()); + + srcNode.setCS(staticCS); + srcNode.setArgsOffset(1); + srcNode.setOriginCid(cid); + } + + private addThisEdge(staticCS: CallSite, cid: ContextID, realCallee: ArkMethod, srcNodes: NodeID[], baseClassPTNode: NodeID, calleeCid: ContextID): void { + if (!(staticCS.args![0] instanceof NullConstant) && !realCallee.isStatic()) { + srcNodes.push(this.addThisRefCallEdge(baseClassPTNode, cid, staticCS.args![0] as Local, realCallee, calleeCid, staticCS.callerFuncID)); + } + } + + private setFunctionThisPt(staticCS: CallSite, srcNode: PagFuncNode, cid: ContextID): void { + let thisLocal = staticCS.args![0]; + if (!(thisLocal instanceof Local)) { + return; + } + + let thisInstanceLocal = this.getRealThisLocal(thisLocal, staticCS.callerFuncID); + let baseThisNode = this.pag.getOrNewNode(cid, thisInstanceLocal); + + for (let pt of baseThisNode.getPointTo()) { + srcNode.setThisPt(pt); + } } public handleUnkownDynamicCall(cs: DynCallSite, cid: ContextID): NodeID[] { let srcNodes: NodeID[] = []; let callerNode = this.cg.getNode(cs.callerFuncID) as CallGraphNode; let ivkExpr = cs.callStmt.getInvokeExpr() as AbstractInvokeExpr; - logger.warn("Handling unknown dyn call site : \n " + callerNode.getMethod().toString() - + '\n --> ' + ivkExpr.toString() + '\n CID: ' + cid); + logger.warn('Handling unknown dyn call site : \n ' + callerNode.getMethod().toString() + '\n --> ' + ivkExpr.toString() + '\n CID: ' + cid); - let callees: ArkMethod[] = [] + let callees: ArkMethod[] = []; let callee: ArkMethod | null = null; callee = this.scene.getMethod(ivkExpr.getMethodSignature()); if (!callee) { @@ -785,7 +836,7 @@ export class PagBuilder { if (callee) { callees.push(callee); } - }) + }); } else { callees.push(callee); } @@ -797,7 +848,7 @@ export class PagBuilder { callees.forEach(callee => { let dstCGNode = this.cg.getCallGraphNodeByMethod(callee.getSignature()); if (!callerNode) { - throw new Error("Can not get caller method node"); + throw new Error('Can not get caller method node'); } if (this.processStorage(cs, dstCGNode, cid)) { @@ -808,7 +859,7 @@ export class PagBuilder { } } - logger.warn(`\tAdd call edge of unknown call ${callee.getSignature().toString()}`) + logger.warn(`\tAdd call edge of unknown call ${callee.getSignature().toString()}`); this.cg.addDynamicCallEdge(callerNode.getID(), dstCGNode.getID(), cs.callStmt); if (!this.cg.detectReachable(dstCGNode.getID(), callerNode.getID())) { let calleeCid = this.ctx.getOrNewContext(cid, dstCGNode.getID(), true); @@ -816,22 +867,22 @@ export class PagBuilder { let staticSrcNodes = this.addStaticPagCallEdge(staticCS, cid, calleeCid); srcNodes.push(...staticSrcNodes); } - }) + }); return srcNodes; } public handleUnprocessedCallSites(processedCallSites: Set): NodeID[] { let reAnalyzeNodes: NodeID[] = []; for (let funcID of this.funcHandledThisRound) { - let funcPag = this.funcPags.get(funcID) + let funcPag = this.funcPags.get(funcID); if (!funcPag) { - logger.error(`can not find funcPag of handled func ${funcID}`) - continue + logger.error(`can not find funcPag of handled func ${funcID}`); + continue; } - let callSites = funcPag.getDynamicCallSites() + let callSites = funcPag.getDynamicCallSites(); - const diffCallSites = new Set(Array.from(callSites).filter(item => !processedCallSites.has(item))) - diffCallSites.forEach((cs) => { + const diffCallSites = new Set(Array.from(callSites).filter(item => !processedCallSites.has(item))); + diffCallSites.forEach(cs => { let ivkExpr = cs.callStmt.getInvokeExpr(); if (!(ivkExpr instanceof ArkInstanceInvokeExpr)) { return; @@ -839,7 +890,7 @@ export class PagBuilder { // Get local of base class let base = ivkExpr.getBase(); // TODO: remove this after multiple this local fixed - base = this.getRealThisLocal(base, cs.callerFuncID) + base = this.getRealThisLocal(base, cs.callerFuncID); // Get PAG nodes for this base's local let ctx2NdMap = this.pag.getNodesByValue(base); if (!ctx2NdMap) { @@ -849,31 +900,23 @@ export class PagBuilder { for (let [cid] of ctx2NdMap.entries()) { reAnalyzeNodes.push(...this.handleUnkownDynamicCall(cs, cid)); } - }) + }); } return reAnalyzeNodes; } - private addThisRefCallEdge(baseClassPTNode: NodeID, cid: ContextID, - ivkExpr: ArkInstanceInvokeExpr, callee: ArkMethod, calleeCid: ContextID, callerFunID: FuncID): NodeID { - - if (!callee || !callee.getCfg()) { - logger.error(`callee is null`); - return -1; - } - let thisAssignStmt = callee.getCfg()?.getStmts().filter(s => - s instanceof ArkAssignStmt && s.getRightOp() instanceof ArkThisRef); - let thisPtr = (thisAssignStmt?.at(0) as ArkAssignStmt).getRightOp() as ArkThisRef; - if (!thisPtr) { - throw new Error('Can not get this ptr'); - } - - // IMPORTANT: set cid 2 base Pt info firstly - this.cid2ThisRefPtMap.set(calleeCid, baseClassPTNode); - let thisRefNode = this.getOrNewThisRefNode(calleeCid, thisPtr) as PagThisRefNode; - thisRefNode.addPTNode(baseClassPTNode); - let srcBaseLocal = ivkExpr.getBase(); + private addThisRefCallEdge( + baseClassPTNode: NodeID, + cid: ContextID, + baseLocal: Local, + callee: ArkMethod, + calleeCid: ContextID, + callerFunID: FuncID + ): NodeID { + let thisRefNodeID = this.recordThisRefNode(baseClassPTNode, callee, calleeCid); + let thisRefNode = this.pag.getNode(thisRefNodeID) as PagThisRefNode; + let srcBaseLocal = baseLocal; srcBaseLocal = this.getRealThisLocal(srcBaseLocal, callerFunID); let srcNodeId = this.pag.hasCtxNode(cid, srcBaseLocal); if (!srcNodeId) { @@ -893,17 +936,39 @@ export class PagBuilder { return srcNodeId; } + private recordThisRefNode(baseClassPTNode: NodeID, callee: ArkMethod, calleeCid: ContextID): NodeID { + if (!callee || !callee.getCfg()) { + logger.error(`callee is null`); + return -1; + } + let thisAssignStmt = callee + .getCfg() + ?.getStmts() + .filter(s => s instanceof ArkAssignStmt && s.getRightOp() instanceof ArkThisRef); + let thisPtr = (thisAssignStmt?.at(0) as ArkAssignStmt).getRightOp() as ArkThisRef; + if (!thisPtr) { + throw new Error('Can not get this ptr'); + } + + // IMPORTANT: set cid 2 base Pt info firstly + this.cid2ThisRefPtMap.set(calleeCid, baseClassPTNode); + let thisRefNode = this.getOrNewThisRefNode(calleeCid, thisPtr) as PagThisRefNode; + thisRefNode.addPTNode(baseClassPTNode); + + return thisRefNode.getID(); + } + /* * Add copy edges from arguments to parameters * ret edges from return values to callsite * Return src node */ - public addStaticPagCallEdge(cs: CallSite, callerCid: ContextID, calleeCid?: ContextID): NodeID[] { + public addStaticPagCallEdge(cs: CallSite, callerCid: ContextID, calleeCid?: ContextID, ptNode?: PagNode): NodeID[] { if (!calleeCid) { calleeCid = this.ctx.getOrNewContext(callerCid, cs.calleeFuncID, true); } - let srcNodes: NodeID[] = [] + let srcNodes: NodeID[] = []; // Add reachable let calleeNode = this.cg.getNode(cs.calleeFuncID) as CallGraphNode; @@ -917,32 +982,127 @@ export class PagBuilder { return srcNodes; } - if (!calleeMethod.getCfg()) { - // method have no cfg body + if (!calleeMethod.getCfg()) { + // method have no cfg body + return srcNodes; + } + + let calleeCS = this.buildFuncPagAndAddToWorklist(new CSFuncID(calleeCid, cs.calleeFuncID)); + // callee cid will updated if callee is singleton + calleeCid = calleeCS.cid; + + let realArgs: Value[] = cs.args ?? []; + let argsOffset: number = 0; + if (ptNode && ptNode instanceof PagFuncNode && ptNode.getCS()) { + // for ptr invoke cloned by Function.bind() + realArgs = ptNode.getCS().args ?? []; + argsOffset = ptNode.getArgsOffset() ?? 0; + callerCid = ptNode.getOriginCid() ?? callerCid; + } + + srcNodes.push(...this.addCallParamPagEdge(calleeMethod, realArgs, cs.callStmt, callerCid, calleeCid, argsOffset)); + srcNodes.push(...this.addCallReturnPagEdge(calleeMethod, cs.callStmt, callerCid, calleeCid)); + + return srcNodes; + } + + /** + * only process the param PAG edge for invoke stmt + */ + private addCallParamPagEdge(calleeMethod: ArkMethod, args: Value[], callStmt: Stmt, callerCid: ContextID, calleeCid: ContextID, offset: number): NodeID[] { + let params = calleeMethod + .getCfg()! + .getStmts() + .filter(stmt => stmt instanceof ArkAssignStmt && stmt.getRightOp() instanceof ArkParameterRef) + .map(stmt => (stmt as ArkAssignStmt).getRightOp()); + + let srcNodes: NodeID[] = []; + + /** + * process foreach situation + * e.g. arr.forEach((item) => { ... }) + * cs.args is anonymous method local, will have only 1 parameter + * but inside foreach will have >= 1 parameters + */ + if (callStmt.getInvokeExpr()?.getMethodSignature().getMethodSubSignature().getMethodName() === 'forEach') { + srcNodes.push(...this.addForeachParamPagEdge(callerCid, calleeCid, callStmt, params)); + return srcNodes; + } + + // add args to parameters edges + for (let i = offset; i <= args.length; i++) { + let arg = args.at(i); + let param = params.at(i - offset); + if (!arg || !param) { + return srcNodes; + } + + if (arg instanceof Constant || arg instanceof AbstractExpr) { + // TODO: handle AbstractExpr + continue; + } + + // Get or create new PAG node for argument and parameter + let srcPagNode = this.getOrNewPagNode(callerCid, arg, callStmt); + let dstPagNode = this.getOrNewPagNode(calleeCid, param, callStmt); + + this.pag.addPagEdge(srcPagNode, dstPagNode, PagEdgeKind.Copy, callStmt); + srcNodes.push(srcPagNode.getID()); + // TODO: handle other types of parmeters + } + + return srcNodes; + } + + /** + * temporary solution for foreach + * deprecate when foreach is handled by built-in method + * connect the element node with the value inside foreach + */ + private addForeachParamPagEdge(callerCid: ContextID, calleeCid: ContextID, callStmt: Stmt, params: Value[]): NodeID[] { + // container value is the base value of callstmt, its points-to is PagNewContainerExprNode + let srcNodes: NodeID[] = []; + let containerValue = (callStmt.getInvokeExpr() as ArkInstanceInvokeExpr).getBase(); + let param = params.at(0); + if (!containerValue || !param) { return srcNodes; } - let calleeCS = this.buildFuncPagAndAddToWorklist(new CSFuncID(calleeCid, cs.calleeFuncID)); - // callee cid will updated if callee is singleton - calleeCid = calleeCS.cid + let basePagNode = this.getOrNewPagNode(callerCid, containerValue, callStmt); + let dstPagNode = this.getOrNewPagNode(calleeCid, param, callStmt); - // TODO: getParameterInstances's performance is not good. Need to refactor - let params = calleeMethod.getCfg()!.getStmts() - .filter(stmt => stmt instanceof ArkAssignStmt && stmt.getRightOp() instanceof ArkParameterRef) - .map(stmt => (stmt as ArkAssignStmt).getRightOp()); + for (let pt of basePagNode.getPointTo()) { + let newContainerExprPagNode = this.pag.getNode(pt) as PagNewContainerExprNode; + + // PagNewContainerExprNode's points-to is the element node + if (!newContainerExprPagNode || !newContainerExprPagNode.getElementNode()) { + continue; + } + let srcPagNode = this.pag.getNode(newContainerExprPagNode.getElementNode()!) as PagNode; + + // connect the element node with the value inside foreach + this.pag.addPagEdge(srcPagNode, dstPagNode, PagEdgeKind.Copy, callStmt); + srcNodes.push(srcPagNode.getID()); + } - srcNodes.push(...this.addCallParamPagEdge(params, cs, callerCid, calleeCid)); + return srcNodes; + } + /** + * process the return value PAG edge for invoke stmt + */ + public addCallReturnPagEdge(calleeMethod: ArkMethod, callStmt: Stmt, callerCid: ContextID, calleeCid: ContextID): NodeID[] { + let srcNodes: NodeID[] = []; // add ret to caller edges let retStmts = calleeMethod.getReturnStmt(); // TODO: call statement must be a assignment state - if (cs.callStmt instanceof ArkAssignStmt) { - let retDst = cs.callStmt.getLeftOp(); + if (callStmt instanceof ArkAssignStmt) { + let retDst = callStmt.getLeftOp(); for (let retStmt of retStmts) { let retValue = (retStmt as ArkReturnStmt).getOp(); if (retValue instanceof Local) { let srcPagNode = this.getOrNewPagNode(calleeCid, retValue, retStmt); - let dstPagNode = this.getOrNewPagNode(callerCid, retDst, cs.callStmt); + let dstPagNode = this.getOrNewPagNode(callerCid, retDst, callStmt); this.pag.addPagEdge(srcPagNode, dstPagNode, PagEdgeKind.Copy, retStmt); } else if (retValue instanceof Constant) { @@ -951,7 +1111,7 @@ export class PagBuilder { logger.debug(retValue); continue; } else { - throw new Error('return dst not a local or constant, but: ' + retValue.getType().toString()) + throw new Error('return dst not a local or constant, but: ' + retValue.getType().toString()); } } } @@ -977,68 +1137,6 @@ export class PagBuilder { return srcNodes; } - public addCallParamPagEdge(params: Value[], cs: CallSite, callerCid: ContextID, calleeCid: ContextID): NodeID[] { - let srcNodes: NodeID[] = []; - let argNum = cs.args?.length; - if (argNum === params.length) { - // add args to parameters edges - for (let i = 0; i < argNum; i++) { - let arg = cs.args?.at(i); - let param = params.at(i); - if (!arg || !param) { - return srcNodes; - } - - if (arg instanceof Constant || arg instanceof AbstractExpr) { - // TODO: handle AbstractExpr - continue; - } - - // Get or create new PAG node for argument and parameter - let srcPagNode = this.getOrNewPagNode(callerCid, arg, cs.callStmt); - let dstPagNode = this.getOrNewPagNode(calleeCid, param, cs.callStmt); - - this.pag.addPagEdge(srcPagNode, dstPagNode, PagEdgeKind.Copy, cs.callStmt); - srcNodes.push(srcPagNode.getID()); - // TODO: handle other types of parmeters - } - } else { - /** - * process foreach situation - * e.g. arr.forEach((item) => { ... }) - * cs.args is anonymous method local, will have only 1 parameter - * but inside foreach will have >= 1 parameters - */ - if (!(cs.callStmt.getInvokeExpr()?.getMethodSignature().getMethodSubSignature().getMethodName() === 'forEach')) { - return srcNodes; - } - // container value is the base value of callstmt, its points-to is PagNewContainerExprNode - let containerValue = (cs.callStmt.getInvokeExpr() as ArkInstanceInvokeExpr).getBase(); - let param = params.at(0); - if (!containerValue || !param) { - return srcNodes; - } - - let basePagNode = this.getOrNewPagNode(callerCid, containerValue, cs.callStmt); - let dstPagNode = this.getOrNewPagNode(calleeCid, param, cs.callStmt); - - for (let pt of basePagNode.getPointTo()) { - let newContainerExprPagNode = this.pag.getNode(pt) as PagNewContainerExprNode; - - // PagNewContainerExprNode's points-to is the element node - if (!newContainerExprPagNode || !newContainerExprPagNode.getElementNode()) { - continue; - } - let srcPagNode = this.pag.getNode(newContainerExprPagNode.getElementNode()!) as PagNode; - - // connect the element node with the value inside foreach - this.pag.addPagEdge(srcPagNode, dstPagNode, PagEdgeKind.Copy, cs.callStmt); - srcNodes.push(srcPagNode.getID()); - } - } - return srcNodes; - } - private addSDKMethodPagCallEdge(cs: CallSite, callerCid: ContextID, calleeCid: ContextID): NodeID[] { let srcNodes: NodeID[] = []; let calleeNode = this.cg.getNode(cs.calleeFuncID) as CallGraphNode; @@ -1047,9 +1145,10 @@ export class PagBuilder { if (!calleeMethod) { return srcNodes; } + let methodType = getBuiltInApiType(calleeMethod.getSignature()); // block the container SDK - if (IsCollectionAPI(calleeMethod.getSignature())) { + if (methodType === BuiltApiType.SetAdd || BuiltApiType.MapSet) { return srcNodes; } @@ -1059,7 +1158,7 @@ export class PagBuilder { srcNodes.push(...this.addSDKMethodReturnPagEdge(cs, callerCid, calleeCid, calleeMethod)); srcNodes.push(...this.addSDKMethodParamPagEdge(cs, callerCid, calleeCid, calleeNode.getID())); - return srcNodes + return srcNodes; } private addSDKMethodReturnPagEdge(cs: CallSite, callerCid: ContextID, calleeCid: ContextID, calleeMethod: ArkMethod): NodeID[] { @@ -1070,20 +1169,20 @@ export class PagBuilder { } // check fake heap object exists or not - let cidMap = this.sdkMethodReturnValueMap.get(calleeMethod) + let cidMap = this.sdkMethodReturnValueMap.get(calleeMethod); if (!cidMap) { - cidMap = new Map() + cidMap = new Map(); } - let newExpr = cidMap.get(calleeCid) + let newExpr = cidMap.get(calleeCid); if (!newExpr) { if (returnType instanceof ClassType) { - newExpr = new ArkNewExpr(returnType) + newExpr = new ArkNewExpr(returnType); } } - cidMap.set(calleeCid, newExpr!) - this.sdkMethodReturnValueMap.set(calleeMethod, cidMap) + cidMap.set(calleeCid, newExpr!); + this.sdkMethodReturnValueMap.set(calleeMethod, cidMap); - let srcPagNode = this.getOrNewPagNode(calleeCid, newExpr!) + let srcPagNode = this.getOrNewPagNode(calleeCid, newExpr!); let dstPagNode = this.getOrNewPagNode(callerCid, cs.callStmt.getLeftOp(), cs.callStmt); this.pag.addPagEdge(srcPagNode, dstPagNode, PagEdgeKind.Address, cs.callStmt); @@ -1131,9 +1230,7 @@ export class PagBuilder { * when this API is called, the anonymous method pointer will not be able to pass into the fake Value PagNode */ dstPagNode.setSdkParam(); - let sdkParamInvokeStmt = new ArkInvokeStmt( - new ArkPtrInvokeExpr((arg.getType() as FunctionType).getMethodSignature(), paramValue as Local, []) - ); + let sdkParamInvokeStmt = new ArkInvokeStmt(new ArkPtrInvokeExpr((arg.getType() as FunctionType).getMethodSignature(), paramValue as Local, [])); // create new DynCallSite let sdkParamCallSite = new DynCallSite(funcID, sdkParamInvokeStmt, undefined, undefined); @@ -1147,39 +1244,6 @@ export class PagBuilder { return srcNodes; } - private processContainerPagCallEdge(cs: CallSite, cid: ContextID, baseClassPTNode: NodeID): NodeID[] { - let srcNodes: NodeID[] = []; - let calleeNode = this.cg.getNode(cs.calleeFuncID) as CallGraphNode; - let calleeMethod: ArkMethod | null = this.scene.getMethod(calleeNode.getMethod()); - let ptNode = this.pag.getNode(baseClassPTNode) as PagNode; - - if (!calleeMethod || !(ptNode instanceof PagNewContainerExprNode)) { - return srcNodes; - } - - let containerValue = (cs.callStmt.getInvokeExpr() as ArkInstanceInvokeExpr).getBase(); - - const containerValueProcess = (argIndex: number): void => { - let srcNode = this.pag.getOrNewNode(cid, cs.args![argIndex], cs.callStmt); - let realContainerFieldPagNode = this.pag.getOrClonePagContainerFieldNode(baseClassPTNode, undefined, containerValue); - - if (realContainerFieldPagNode) { - // In some cases, the value of a variable of array type may not be an explicit array object, - // and the value of `realContainerFieldPagNode` will be undefined. - this.pag.addPagEdge(srcNode, realContainerFieldPagNode, PagEdgeKind.Copy, cs.callStmt); - srcNodes.push(srcNode.getID()); - } - }; - - if (IsCollectionSetAdd(calleeMethod.getSignature())) { - containerValueProcess(0); - } else if (IsCollectionMapSet(calleeMethod.getSignature())) { - containerValueProcess(1); - } - - return srcNodes; - } - public getOrNewPagNode(cid: ContextID, v: PagNodeType, s?: Stmt): PagNode { if (v instanceof ArkThisRef) { return this.getOrNewThisRefNode(cid, v as ArkThisRef); @@ -1190,11 +1254,11 @@ export class PagBuilder { // globalThis process can not be removed while all `globalThis` ref is the same Value if (v instanceof Local) { - if (v.getName() === "this") { + if (v.getName() === 'this') { return this.getOrNewThisLoalNode(cid, v as Local, s); } else if (v.getName() === GLOBAL_THIS_NAME && v.getDeclaringStmt() == null) { // globalThis node has no cid - return this.getOrNewGlobalThisNode(-1) + return this.getOrNewGlobalThisNode(-1); } } @@ -1210,19 +1274,19 @@ export class PagBuilder { * @param cid: current contextID */ public getOrNewThisRefNode(cid: ContextID, v: ArkThisRef): PagNode { - let thisRefNodeID = this.cid2ThisRefMap.get(cid) + let thisRefNodeID = this.cid2ThisRefMap.get(cid); if (!thisRefNodeID) { thisRefNodeID = -1; } - let thisRefNode = this.pag.getOrNewThisRefNode(thisRefNodeID, v) - this.cid2ThisRefMap.set(cid, thisRefNode.getID()) - return thisRefNode + let thisRefNode = this.pag.getOrNewThisRefNode(thisRefNodeID, v); + this.cid2ThisRefMap.set(cid, thisRefNode.getID()); + return thisRefNode; } // TODO: remove it once this local not uniq issue is fixed public getOrNewThisLoalNode(cid: ContextID, v: Local, s?: Stmt): PagNode { - let thisLocalNodeID = this.cid2ThisLocalMap.get(cid) + let thisLocalNodeID = this.cid2ThisLocalMap.get(cid); if (thisLocalNodeID) { return this.pag.getNode(thisLocalNodeID) as PagNode; } @@ -1274,7 +1338,6 @@ export class PagBuilder { propertyLocal = storageMap.get(propertyName)!; } - if (propertyLocal) { return this.getOrNewPagNode(-1, propertyLocal, stmt); } @@ -1309,9 +1372,9 @@ export class PagBuilder { /* * In ArkIR, ArkField has multiple instances for each stmt which use it * But the unique one is needed for pointer analysis - * This is a temp solution to use a ArkField->(first instance) + * This is a temp solution to use a ArkField->(first instance) * as the unique instance - * + * * node merge condition: * instance field: value and ArkField * static field: ArkField @@ -1322,18 +1385,18 @@ export class PagBuilder { } let sig = v.getFieldSignature(); - let sigStr = sig.toString() + let sigStr = sig.toString(); let base: Local; let real: Value | undefined; if (v instanceof ArkInstanceFieldRef) { - base = (v as ArkInstanceFieldRef).getBase() + base = (v as ArkInstanceFieldRef).getBase(); if (base instanceof Local && base.getName() === GLOBAL_THIS_NAME && base.getDeclaringStmt() == null) { // replace the base in fieldRef base = this.getGlobalThisValue(); - (v as ArkInstanceFieldRef).setBase(base as Local) + (v as ArkInstanceFieldRef).setBase(base as Local); } - let key = `${base.getSignature()}-${sigStr}` + let key = `${base.getSignature()}-${sigStr}`; real = this.instanceField2UniqInstanceMap.get(key); if (!real) { @@ -1371,9 +1434,7 @@ export class PagBuilder { } let funcPag = this.funcPags.get(funcID)!; - let heapObjects = [...funcPag.getInternalEdges()!] - .filter(edge => edge.kind === PagEdgeKind.Address) - .map(edge => edge.dst); + let heapObjects = [...funcPag.getInternalEdges()!].filter(edge => edge.kind === PagEdgeKind.Address).map(edge => edge.dst); let returnValues = arkMethod.getReturnValues(); @@ -1428,8 +1489,7 @@ export class PagBuilder { return false; } - private funcPagDfs(graph: Map, visited: Set, currentNode: Value, targetNode: Value, - staticFieldFound: boolean): boolean { + private funcPagDfs(graph: Map, visited: Set, currentNode: Value, targetNode: Value, staticFieldFound: boolean): boolean { if (currentNode === targetNode) { return staticFieldFound; } @@ -1478,6 +1538,142 @@ export class PagBuilder { return PagEdgeKind.Unknown; } + /** + * process Storage API + * @returns boolean: check if the cs represent a Storage API, no matter the API will success or fail + */ + private processStorage(cs: CallSite | DynCallSite, calleeCGNode: CallGraphNode, cid: ContextID): boolean { + let storageName = calleeCGNode.getMethod().getDeclaringClassSignature().getClassName(); + let storageType: StorageType = this.getStorageType(storageName, cs, cid); + + // TODO: add other storages + if (storageType === StorageType.APP_STORAGE) { + let calleeName = calleeCGNode.getMethod().getMethodSubSignature().getMethodName(); + + // TODO: complete AppStorage API + if (calleeName === 'setOrCreate') { + this.processStorageSetOrCreate(cs, cid); + } else if (calleeName === 'link') { + this.processStorageLink(cs, cid); + } else if (calleeName === 'prop') { + this.processStorageProp(cs, cid); + } else if (calleeName === 'set') { + this.processStorageSet(cs, cid); + } else if (calleeName === 'get') { + this.processStorageGet(cs, cid); + } + return true; + } else if (storageType === StorageType.LOCAL_STORAGE) { + // TODO: LocalStorage is not Static + } + + return false; + } + + private processStorageSetOrCreate(cs: CallSite | DynCallSite, cid: ContextID): void { + let propertyStr = this.getPropertyName(cs.args![0]); + if (!propertyStr) { + return; + } + + let propertyName = propertyStr; + let propertyNode = this.getOrNewPropertyNode(StorageType.APP_STORAGE, propertyName, cs.callStmt); + let storageObj = cs.args![1]; + + this.addPropertyLinkEdge(propertyNode, storageObj, cid, cs.callStmt, StorageLinkEdgeType.Local2Property); + } + + private processStorageLink(cs: CallSite | DynCallSite, cid: ContextID): void { + let propertyStr = this.getPropertyName(cs.args![0]); + if (!propertyStr) { + return; + } + + let propertyName = propertyStr; + let propertyNode = this.getOrNewPropertyNode(StorageType.APP_STORAGE, propertyName, cs.callStmt); + let leftOp = (cs.callStmt as ArkAssignStmt).getLeftOp() as Local; + let linkedOpNode = this.pag.getOrNewNode(cid, leftOp) as PagNode; + if (linkedOpNode instanceof PagLocalNode) { + linkedOpNode.setStorageLink(StorageType.APP_STORAGE, propertyName); + } + + this.pag.addPagEdge(propertyNode, linkedOpNode, PagEdgeKind.Copy); + this.pag.addPagEdge(linkedOpNode, propertyNode, PagEdgeKind.Copy); + } + + private processStorageProp(cs: CallSite | DynCallSite, cid: ContextID): void { + let propertyStr = this.getPropertyName(cs.args![0]); + if (!propertyStr) { + return; + } + + let propertyName = propertyStr; + let propertyNode = this.getOrNewPropertyNode(StorageType.APP_STORAGE, propertyName, cs.callStmt); + let leftOp = (cs.callStmt as ArkAssignStmt).getLeftOp() as Local; + let linkedOpNode = this.pag.getOrNewNode(cid, leftOp) as PagNode; + if (linkedOpNode instanceof PagLocalNode) { + linkedOpNode.setStorageLink(StorageType.APP_STORAGE, propertyName); + } + + this.pag.addPagEdge(propertyNode, linkedOpNode, PagEdgeKind.Copy); + } + + private processStorageSet(cs: CallSite | DynCallSite, cid: ContextID): void { + let ivkExpr: AbstractInvokeExpr = cs.callStmt.getInvokeExpr()!; + if (ivkExpr instanceof ArkInstanceInvokeExpr) { + let base = ivkExpr.getBase(); + let baseNode = this.pag.getOrNewNode(cid, base) as PagLocalNode; + + if (baseNode.isStorageLinked()) { + let argsNode = this.pag.getOrNewNode(cid, cs.args![0]) as PagNode; + + this.pag.addPagEdge(argsNode, baseNode, PagEdgeKind.Copy); + } + } else if (ivkExpr instanceof ArkStaticInvokeExpr) { + // TODO: process AppStorage.set() + } + } + + private processStorageGet(cs: CallSite | DynCallSite, cid: ContextID): void { + if (!(cs.callStmt instanceof ArkAssignStmt)) { + return; + } + let leftOp = (cs.callStmt as ArkAssignStmt).getLeftOp() as Local; + let ivkExpr = cs.callStmt.getInvokeExpr(); + let propertyName!: string; + if (ivkExpr instanceof ArkStaticInvokeExpr) { + let propertyStr = this.getPropertyName(cs.args![0]); + if (propertyStr) { + propertyName = propertyStr; + } + } else if (ivkExpr instanceof ArkInstanceInvokeExpr) { + let baseNode = this.pag.getOrNewNode(cid, ivkExpr.getBase()) as PagLocalNode; + if (baseNode.isStorageLinked()) { + propertyName = baseNode.getStorage().PropertyName!; + } + } + + let propertyNode = this.getPropertyNode(StorageType.APP_STORAGE, propertyName, cs.callStmt); + if (!propertyNode) { + return; + } + + this.pag.addPagEdge(propertyNode, this.pag.getOrNewNode(cid, leftOp, cs.callStmt), PagEdgeKind.Copy, cs.callStmt); + } + + private getPropertyName(value: Value): string | undefined { + if (value instanceof Local) { + let type = value.getType(); + if (type instanceof StringType) { + return type.getName(); + } + } else if (value instanceof Constant) { + return value.getValue(); + } + + return undefined; + } + /** * get storageType enum with method's Declaring ClassName * @@ -1515,11 +1711,12 @@ export class PagBuilder { private stmtIsCreateAddressObj(stmt: ArkAssignStmt): boolean { let lhOp = stmt.getLeftOp(); let rhOp = stmt.getRightOp(); - if ((rhOp instanceof ArkNewExpr || rhOp instanceof ArkNewArrayExpr) || - (lhOp instanceof Local && ( - (rhOp instanceof Local && rhOp.getType() instanceof FunctionType && - rhOp.getDeclaringStmt() === null) || - (rhOp instanceof AbstractFieldRef && rhOp.getType() instanceof FunctionType))) || + if ( + rhOp instanceof ArkNewExpr || + rhOp instanceof ArkNewArrayExpr || + (lhOp instanceof Local && + ((rhOp instanceof Local && rhOp.getType() instanceof FunctionType && rhOp.getDeclaringStmt() === null) || + (rhOp instanceof AbstractFieldRef && rhOp.getType() instanceof FunctionType))) || (rhOp instanceof Local && rhOp.getName() === GLOBAL_THIS_NAME && rhOp.getDeclaringStmt() == null) ) { return true; @@ -1535,10 +1732,9 @@ export class PagBuilder { let rhOp = stmt.getRightOp(); let condition: boolean = - (lhOp instanceof Local && ( - rhOp instanceof Local || rhOp instanceof ArkParameterRef || - rhOp instanceof ArkThisRef || rhOp instanceof ArkStaticFieldRef)) || - (lhOp instanceof ArkStaticFieldRef && rhOp instanceof Local) + (lhOp instanceof Local && + (rhOp instanceof Local || rhOp instanceof ArkParameterRef || rhOp instanceof ArkThisRef || rhOp instanceof ArkStaticFieldRef)) || + (lhOp instanceof ArkStaticFieldRef && rhOp instanceof Local); if (condition) { return true; @@ -1550,8 +1746,7 @@ export class PagBuilder { let lhOp = stmt.getLeftOp(); let rhOp = stmt.getRightOp(); - if (rhOp instanceof Local && - (lhOp instanceof ArkInstanceFieldRef || lhOp instanceof ArkArrayRef)) { + if (rhOp instanceof Local && (lhOp instanceof ArkInstanceFieldRef || lhOp instanceof ArkArrayRef)) { return true; } return false; @@ -1561,8 +1756,7 @@ export class PagBuilder { let lhOp = stmt.getLeftOp(); let rhOp = stmt.getRightOp(); - if (lhOp instanceof Local && - (rhOp instanceof ArkInstanceFieldRef || rhOp instanceof ArkArrayRef)) { + if (lhOp instanceof Local && (rhOp instanceof ArkInstanceFieldRef || rhOp instanceof ArkArrayRef)) { return true; } return false; @@ -1572,7 +1766,7 @@ export class PagBuilder { funcPag.addDynamicCallSite(cs); this.pagStat.numDynamicCall++; - logger.trace("[add dynamic callsite] " + cs.callStmt.toString() + ": " + cs.callStmt.getCfg()?.getDeclaringMethod().getSignature().toString()); + logger.trace('[add dynamic callsite] ' + cs.callStmt.toString() + ': ' + cs.callStmt.getCfg()?.getDeclaringMethod().getSignature().toString()); } public setPtForNode(node: NodeID, pts: IPtsCollection | undefined): void { @@ -1584,19 +1778,23 @@ export class PagBuilder { } public getRealThisLocal(input: Local, funcId: FuncID): Local { - if (input.getName() !== 'this') + if (input.getName() !== 'this') { return input; + } let real = input; let f = this.cg.getArkMethodByFuncID(funcId); - f?.getCfg()?.getStmts().forEach(s => { - if (s instanceof ArkAssignStmt && s.getLeftOp() instanceof Local) { - if ((s.getLeftOp() as Local).getName() === 'this') { - real = s.getLeftOp() as Local; - return; + f + ?.getCfg() + ?.getStmts() + .forEach(s => { + if (s instanceof ArkAssignStmt && s.getLeftOp() instanceof Local) { + if ((s.getLeftOp() as Local).getName() === 'this') { + real = s.getLeftOp() as Local; + return; + } } - } - }) + }); return real; } @@ -1632,7 +1830,7 @@ export class PagBuilder { */ private handleValueFromExternalScope(value: Value, funcID: FuncID, originValue?: Value): void { if (value instanceof Local) { - if (value.getDeclaringStmt()) { + if (value.getDeclaringStmt() || value.getName() === 'this') { // not from external scope return; } @@ -1661,7 +1859,11 @@ export class PagBuilder { // Export a local // Add a InterProcedural edge if (dst instanceof Local) { - let e: InterProceduralEdge = { src: src, dst: dst, kind: PagEdgeKind.InterProceduralCopy }; + let e: InterProceduralEdge = { + src: src, + dst: dst, + kind: PagEdgeKind.InterProceduralCopy, + }; interFuncPag.addToInterProceduralEdgeSet(e); this.addExportVariableMap(src, dst as Local); } else if (dst instanceof ArkInstanceFieldRef) { @@ -1683,7 +1885,7 @@ export class PagBuilder { private getSourceValueFromExternalScope(value: Local, funcID: FuncID): Local | undefined { let sourceValue; - // TODO: first from default method + sourceValue = this.getDefaultMethodSourceValue(value, funcID); if (!sourceValue) { sourceValue = this.getExportSourceValue(value, funcID); @@ -1696,13 +1898,12 @@ export class PagBuilder { // namespace check let arkMethod = this.cg.getArkMethodByFuncID(funcID); if (!arkMethod) { - return; + return undefined; } let declaringNameSpace = arkMethod.getDeclaringArkClass().getDeclaringArkNamespace(); while (declaringNameSpace) { - let nameSpaceLocals = declaringNameSpace.getDefaultClass() - .getDefaultArkMethod()?.getBody()?.getLocals() ?? new Map(); + let nameSpaceLocals = declaringNameSpace.getDefaultClass().getDefaultArkMethod()?.getBody()?.getLocals() ?? new Map(); if (nameSpaceLocals.has(value.getName())) { return nameSpaceLocals.get(value.getName()); } @@ -1712,10 +1913,9 @@ export class PagBuilder { // file check let declaringFile = arkMethod.getDeclaringArkFile(); - let fileLocals = declaringFile.getDefaultClass() - .getDefaultArkMethod()?.getBody()?.getLocals() ?? new Map(); + let fileLocals = declaringFile.getDefaultClass().getDefaultArkMethod()?.getBody()?.getLocals() ?? new Map(); if (!fileLocals.has(value.getName())) { - return; + return undefined; } return fileLocals.get(value.getName()); @@ -1724,24 +1924,25 @@ export class PagBuilder { private getExportSourceValue(value: Local, funcID: FuncID): Local | undefined { let curMethod = this.cg.getArkMethodByFuncID(funcID); if (!curMethod) { - return; + return undefined; } let curFile = curMethod.getDeclaringArkFile(); let impInfo = curFile.getImportInfoBy(value.getName()); if (!impInfo) { - return; + return undefined; } let exportSource = impInfo.getLazyExportInfo(); if (!exportSource) { - return; + return undefined; } let exportSouceValue = exportSource.getArkExport(); if (exportSouceValue instanceof Local) { return exportSouceValue; } + return undefined; } private addExportVariableMap(src: Local, dst: Local): void { @@ -1772,9 +1973,53 @@ export class PagBuilder { let existingNodes = this.pag.getNodesByValue(exportLocal); existingNodes?.forEach(n => { this.pag.addPagEdge(this.pag.getNode(n)! as PagNode, dstPagNode, e.kind); + this.retriggerNodesList.add(n); }); } return true; } + + public getRetriggerNodes(): NodeID[] { + let retriggerNodes = Array.from(this.retriggerNodesList); + this.retriggerNodesList.clear(); + return retriggerNodes; + } + + public addUpdatedNode(nodeID: NodeID, diffPT: IPtsCollection): void { + let ptaConfig = PointerAnalysisConfig.getInstance(); + let updatedNode = this.updatedNodesThisRound.get(nodeID) ?? new ptaConfig.ptsCollectionCtor(); + updatedNode.union(diffPT); + this.updatedNodesThisRound.set(nodeID, updatedNode); + } + + public getUpdatedNodes(): Map> { + return this.updatedNodesThisRound; + } + + public resetUpdatedNodes(): void { + this.updatedNodesThisRound.clear(); + } + + private transferArrayValues(method: ArkMethod, arrayLocal: Value): Local[] { + if (!(arrayLocal instanceof Local) || !(arrayLocal.getType() instanceof ArrayType)) { + return []; + } + + /** + * TODO: get array element values + * need to resolve multi dimension array + */ + const usedValuesInArray = arrayLocal.getUsedStmts().flatMap(stmt => { + if (stmt instanceof ArkAssignStmt) { + const rightOp = stmt.getRightOp(); + if (rightOp instanceof Local) { + return rightOp; + } + } + return []; + }); + + return usedValuesInArray; + } } diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PointerAnalysis.ts b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PointerAnalysis.ts index 9dca84f638..902a05b902 100644 --- a/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PointerAnalysis.ts +++ b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PointerAnalysis.ts @@ -47,7 +47,7 @@ export class PointerAnalysis extends AbstractAnalysis { private config: PointerAnalysisConfig; constructor(p: Pag, cg: CallGraph, s: Scene, config: PointerAnalysisConfig) { - super(s) + super(s); this.pag = p; this.cg = cg; this.ptd = new DiffPTData>(config.ptsCollectionCtor); @@ -96,7 +96,7 @@ export class PointerAnalysis extends AbstractAnalysis { return pta; } - protected init() { + protected init(): void { logger.warn(`========== Init Pointer Analysis ==========`); // start statistics this.ptaStat.startStat(); @@ -108,13 +108,13 @@ export class PointerAnalysis extends AbstractAnalysis { } } - public start() { + public start(): void { this.init(); this.solveConstraint(); this.postProcess(); } - private postProcess() { + private postProcess(): void { this.ptaStat.endStat(); this.pagBuilder.doStat(); this.cg.printStat(); @@ -147,11 +147,11 @@ export class PointerAnalysis extends AbstractAnalysis { return []; } - public setEntries(fIds: FuncID[]) { + public setEntries(fIds: FuncID[]): void { this.entries = fIds; } - private solveConstraint() { + private solveConstraint(): void { this.worklist = []; logger.warn(`========== Pointer Analysis Start ==========`); this.initWorklist(); @@ -164,7 +164,7 @@ export class PointerAnalysis extends AbstractAnalysis { // do pointer transfer this.solveWorklist(); // process dynamic call - if (this.config.analysisScale === PtaAnalysisScale.WholeProgram || this.ptaStat.iterTimes === 1 ) { + if (this.config.analysisScale === PtaAnalysisScale.WholeProgram || this.ptaStat.iterTimes === 1) { reanalyzer = this.onTheFlyDynamicCallSolve(); } else { reanalyzer = false; @@ -180,6 +180,7 @@ export class PointerAnalysis extends AbstractAnalysis { */ private initWorklist(): boolean { let changed: boolean = false; + this.addToReanalyze(this.pagBuilder.getRetriggerNodes()); for (let e of this.pag.getAddrEdges()) { this.ptaStat.numProcessedAddr++; @@ -241,10 +242,10 @@ export class PointerAnalysis extends AbstractAnalysis { let intraProceduralFieldNodeMap = new Map(); if (nodeValue instanceof Local) { - this.pagBuilder.getExportVariableMap(nodeValue).forEach((dst) => { + this.pagBuilder.getExportVariableMap(nodeValue).forEach(dst => { let temp = this.pag.getNodesByBaseValue(dst) ?? new Map(); intraProceduralFieldNodeMap = this.mergeInstanceFieldMap(instanceFieldNodeMap, temp); - }) + }); } instanceFieldNodeMap!.forEach((nodeIDs, cid) => { @@ -260,25 +261,25 @@ export class PointerAnalysis extends AbstractAnalysis { this.handleFieldInEdges(fieldNode, diffPts!); this.handleFieldOutEdges(fieldNode, diffPts!); - }) - }) + }); + }); // without cid check, because closure and export is under different cid - intraProceduralFieldNodeMap!.forEach((nodeIDs) => { + intraProceduralFieldNodeMap!.forEach(nodeIDs => { nodeIDs.forEach((nodeID: number) => { // get abstract field node let fieldNode = this.pag.getNode(nodeID) as PagNode; this.handleFieldInEdges(fieldNode, diffPts!); this.handleFieldOutEdges(fieldNode, diffPts!); - }) - }) + }); + }); return true; } private handleFieldInEdges(fieldNode: PagNode, diffPts: IPtsCollection): void { - fieldNode.getIncomingEdge().forEach((edge) => { + fieldNode.getIncomingEdge().forEach(edge => { if (edge.getKind() !== PagEdgeKind.Write) { return; } @@ -307,7 +308,7 @@ export class PointerAnalysis extends AbstractAnalysis { } private handleFieldOutEdges(fieldNode: PagNode, diffPts: IPtsCollection): void { - fieldNode.getOutgoingEdges().forEach((edge) => { + fieldNode.getOutgoingEdges().forEach(edge => { if (edge.getKind() !== PagEdgeKind.Load) { return; } @@ -347,7 +348,7 @@ export class PointerAnalysis extends AbstractAnalysis { return true; } - private handlePt(nodeID: NodeID) { + private handlePt(nodeID: NodeID): void { let realDiff = this.ptd.calculateDiff(nodeID, nodeID); if (realDiff.count() !== 0) { @@ -396,7 +397,7 @@ export class PointerAnalysis extends AbstractAnalysis { changed = this.processDynCallSite(node, pts, processedCallSites) || changed; changed = this.processUnknownCallSite(node, pts) || changed; - }) + }); this.pagBuilder.resetUpdatedNodes(); let srcNodes = this.pagBuilder.handleUnprocessedCallSites(processedCallSites); changed = this.addToReanalyze(srcNodes) || changed; @@ -416,13 +417,13 @@ export class PointerAnalysis extends AbstractAnalysis { } logger.info(`[process dynamic callsite] node ${node.getID()}`); - dynCallSites.forEach((dynCallsite) => { + dynCallSites.forEach(dynCallsite => { for (let pt of pts) { let srcNodes = this.pagBuilder.addDynamicCallEdge(dynCallsite, pt, node.getCid()); changed = this.addToReanalyze(srcNodes) || changed; } processedCallSites.add(dynCallsite); - }) + }); return changed; } @@ -437,12 +438,12 @@ export class PointerAnalysis extends AbstractAnalysis { } logger.info(`[process unknown callsite] node ${node.getID()}`); - unknownCallSites.forEach((unknownCallSite) => { + unknownCallSites.forEach(unknownCallSite => { for (let pt of pts) { let srcNodes = this.pagBuilder.addDynamicCallEdge(unknownCallSite, pt, node.getCid()); changed = this.addToReanalyze(srcNodes) || changed; } - }) + }); return changed; } @@ -524,7 +525,7 @@ export class PointerAnalysis extends AbstractAnalysis { processedNodes.forEach(nodeID => { let valueNode = this.pag.getNode(nodeID) as PagNode; relatedAllNodes.add(valueNode.getValue()); - }) + }); return relatedAllNodes; } @@ -541,7 +542,7 @@ export class PointerAnalysis extends AbstractAnalysis { private addIncomingEdgesToWorkList(valueNode: PagNode, workListNodes: NodeID[], processedNodes: Set): void { let inCopyEdges = valueNode.getIncomingCopyEdges(); let inThisEdges = valueNode.getIncomingThisEdges(); - let combinedEdges = new Set([...inCopyEdges ?? [], ...inThisEdges ?? []]); + let combinedEdges = new Set([...(inCopyEdges ?? []), ...(inThisEdges ?? [])]); if (combinedEdges) { combinedEdges.forEach(edge => { let srcID = edge.getSrcID(); @@ -555,7 +556,7 @@ export class PointerAnalysis extends AbstractAnalysis { private addOutgoingEdgesToWorkList(valueNode: PagNode, workListNodes: NodeID[], processedNodes: Set): void { let outCopyEdges = valueNode.getOutgoingCopyEdges(); let outThisEdges = valueNode.getOutgoingThisEdges(); - let combinedEdges = new Set([...outCopyEdges ?? [], ...outThisEdges ?? []]); + let combinedEdges = new Set([...(outCopyEdges ?? []), ...(outThisEdges ?? [])]); if (combinedEdges) { combinedEdges.forEach(edge => { let dstID = edge.getDstID(); @@ -601,7 +602,7 @@ export class PointerAnalysis extends AbstractAnalysis { } } - // If find pts to original type, + // If find pts to original type, // need add original type back since it is a correct type let diffSet = this.typeDiffMap.get(value); if (diffSet && findSameType) { @@ -631,9 +632,9 @@ export class PointerAnalysis extends AbstractAnalysis { private dumpUnhandledFunctions(): void { const filePath = path.join(this.config.outputDirectory, 'PtaUnhandledFunctionList.txt'); - fs.access(filePath, fs.constants.F_OK, (err) => { + fs.access(filePath, fs.constants.F_OK, err => { if (!err) { - fs.truncate(filePath, 0, (err) => { + fs.truncate(filePath, 0, err => { err && logger.error('Error to truncate file ', err); }); } @@ -651,7 +652,7 @@ export class PointerAnalysis extends AbstractAnalysis { } }); - fs.writeFile(filePath, updatedContent, 'utf8', (err) => { + fs.writeFile(filePath, updatedContent, 'utf8', err => { if (err) { logger.error('Error to write file', err); } @@ -669,4 +670,4 @@ export class PointerAnalysis extends AbstractAnalysis { }); return src; } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PointerAnalysisConfig.ts b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PointerAnalysisConfig.ts index 9dcde376dd..1e68c981db 100644 --- a/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PointerAnalysisConfig.ts +++ b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PointerAnalysisConfig.ts @@ -19,7 +19,7 @@ import { NodeID } from '../../core/graph/BaseExplicitGraph'; export enum PtaAnalysisScale { WholeProgram = 0, - MethodLevel = 1 + MethodLevel = 1, } export class PointerAnalysisConfig { @@ -36,11 +36,17 @@ export class PointerAnalysisConfig { /* * Note: DO NOT use `new PointerAnalysisConfig` to initialize ptaconfig - * Use PointerAnalysisConfig.create() for singleton pattern + * Use PointerAnalysisConfig.create() for singleton pattern */ - constructor(kLimit: number, outputDirectory: string, detectTypeDiff: boolean = false, - dotDump: boolean = false, unhandledFuncDump: boolean = false, - analysisScale: PtaAnalysisScale = PtaAnalysisScale.WholeProgram, ptsCoType = PtsCollectionType.Set) { + constructor( + kLimit: number, + outputDirectory: string, + detectTypeDiff: boolean = false, + dotDump: boolean = false, + unhandledFuncDump: boolean = false, + analysisScale: PtaAnalysisScale = PtaAnalysisScale.WholeProgram, + ptsCoType = PtsCollectionType.Set + ) { if (kLimit > 5) { throw new Error('K Limit too large'); } @@ -58,16 +64,27 @@ export class PointerAnalysisConfig { } } - /* * Create Singleton instance * The instance can be created multi-times and be overwrited */ - public static create(kLimit: number, outputDirectory: string, detectTypeDiff: boolean = false, - dotDump: boolean = false, unhandledFuncDump: boolean = false, - analysisScale: PtaAnalysisScale = PtaAnalysisScale.WholeProgram, ptsCoType = PtsCollectionType.Set): PointerAnalysisConfig { + public static create( + kLimit: number, + outputDirectory: string, + detectTypeDiff: boolean = false, + dotDump: boolean = false, + unhandledFuncDump: boolean = false, + analysisScale: PtaAnalysisScale = PtaAnalysisScale.WholeProgram, + ptsCoType = PtsCollectionType.Set + ): PointerAnalysisConfig { PointerAnalysisConfig.instance = new PointerAnalysisConfig( - kLimit, outputDirectory, detectTypeDiff, dotDump, unhandledFuncDump, analysisScale, ptsCoType + kLimit, + outputDirectory, + detectTypeDiff, + dotDump, + unhandledFuncDump, + analysisScale, + ptsCoType ); return PointerAnalysisConfig.instance; } @@ -81,4 +98,4 @@ export class PointerAnalysisConfig { } return PointerAnalysisConfig.instance; } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PtsDS.ts b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PtsDS.ts index 3b7c3baf81..492d6c99ec 100644 --- a/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PtsDS.ts +++ b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PtsDS.ts @@ -215,12 +215,15 @@ export class PtsBV implements IPtsCollection { } } -export enum PtsCollectionType { Set, BitVector }; +export enum PtsCollectionType { + Set, + BitVector, +} export class DiffPTData> { private diffPtsMap: Map; private propaPtsMap: Map; - constructor(private DSCreator: (new () => DS)) { + constructor(private DSCreator: new () => DS) { this.diffPtsMap = new Map(); this.propaPtsMap = new Map(); } @@ -323,7 +326,9 @@ export class DiffPTData> { } flush(v: K): void { - if (!this.diffPtsMap.has(v)) return; + if (!this.diffPtsMap.has(v)) { + return; + } let diff = this.diffPtsMap.get(v)!; let propa = this.getPropaPtsMut(v); // do not clear origin propa, only copy the pt and add it to diff @@ -333,19 +338,27 @@ export class DiffPTData> { clearPts(v: K): void { let diff = this.diffPtsMap.get(v); - if (diff) diff.clear(); + if (diff) { + diff.clear(); + } let propa = this.propaPtsMap.get(v); - if (propa) propa.clear(); + if (propa) { + propa.clear(); + } } clearDiffPts(v: K): void { let diff = this.diffPtsMap.get(v); - if (diff) diff.clear(); + if (diff) { + diff.clear(); + } } clearPropaPts(v: K): void { let propa = this.propaPtsMap.get(v); - if (propa) propa.clear(); + if (propa) { + propa.clear(); + } } calculateDiff(src: K, dst: K): DS { @@ -360,4 +373,4 @@ export class DiffPTData> { result.subtract(dstPropa); return result; } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/base/Constant.ts b/ets2panda/linter/arkanalyzer/src/core/base/Constant.ts index d6541f1cb1..cc7da1df70 100644 --- a/ets2panda/linter/arkanalyzer/src/core/base/Constant.ts +++ b/ets2panda/linter/arkanalyzer/src/core/base/Constant.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -56,7 +56,7 @@ export class Constant implements Value { public toString(): string { let str = ''; if (this.type instanceof StringType) { - str = '\'' + this.value + '\''; + str = "'" + this.value + "'"; } else { str = this.value; } diff --git a/ets2panda/linter/arkanalyzer/src/core/base/Decorator.ts b/ets2panda/linter/arkanalyzer/src/core/base/Decorator.ts index 8c98790ff9..f53d1f78bd 100644 --- a/ets2panda/linter/arkanalyzer/src/core/base/Decorator.ts +++ b/ets2panda/linter/arkanalyzer/src/core/base/Decorator.ts @@ -41,4 +41,4 @@ export class Decorator { public toString(): string { return `@${this.content}`; } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/base/DefUseChain.ts b/ets2panda/linter/arkanalyzer/src/core/base/DefUseChain.ts index 669bc74f27..8c4bd3ce97 100644 --- a/ets2panda/linter/arkanalyzer/src/core/base/DefUseChain.ts +++ b/ets2panda/linter/arkanalyzer/src/core/base/DefUseChain.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,13 +16,13 @@ import { Value } from './Value'; import { Stmt } from './Stmt'; -export class DefUseChain{ - value:Value; - def:Stmt; - use:Stmt; - constructor(value:Value,def:Stmt,use:Stmt){ - this.value=value; - this.def=def; - this.use=use; +export class DefUseChain { + value: Value; + def: Stmt; + use: Stmt; + constructor(value: Value, def: Stmt, use: Stmt) { + this.value = value; + this.def = def; + this.use = use; } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/base/Expr.ts b/ets2panda/linter/arkanalyzer/src/core/base/Expr.ts index 96a499d5a5..dcf4695331 100644 --- a/ets2panda/linter/arkanalyzer/src/core/base/Expr.ts +++ b/ets2panda/linter/arkanalyzer/src/core/base/Expr.ts @@ -19,7 +19,8 @@ import { MethodSignature } from '../model/ArkSignature'; import { Local } from './Local'; import { AliasType, - ArrayType, BigIntType, + ArrayType, + BigIntType, BooleanType, ClassType, FunctionType, @@ -60,7 +61,7 @@ export abstract class AbstractExpr implements Value { export abstract class AbstractInvokeExpr extends AbstractExpr { private methodSignature: MethodSignature; private args: Value[]; - private realGenericTypes?: Type[];//新增 + private realGenericTypes?: Type[]; //新增 constructor(methodSignature: MethodSignature, args: Value[], realGenericTypes?: Type[]) { super(); @@ -216,7 +217,6 @@ export class ArkInstanceInvokeExpr extends AbstractInvokeExpr { public inferType(arkMethod: ArkMethod): AbstractInvokeExpr { return IRInference.inferInstanceInvokeExpr(this, arkMethod); } - } export class ArkStaticInvokeExpr extends AbstractInvokeExpr { @@ -243,7 +243,6 @@ export class ArkStaticInvokeExpr extends AbstractInvokeExpr { public inferType(arkMethod: ArkMethod): AbstractInvokeExpr { return IRInference.inferStaticInvokeExpr(this, arkMethod); } - } /** @@ -439,7 +438,6 @@ export class ArkDeleteExpr extends AbstractExpr { public toString(): string { return 'delete ' + this.field; } - } export class ArkAwaitExpr extends AbstractExpr { @@ -640,13 +638,13 @@ export abstract class AbstractBinopExpr extends AbstractExpr { return this.op1 + ' ' + this.operator + ' ' + this.op2; } - protected inferOpType(op: Value, arkMethod: ArkMethod) { + protected inferOpType(op: Value, arkMethod: ArkMethod): void { if (op instanceof AbstractExpr || op instanceof AbstractRef) { TypeInference.inferValueType(op, arkMethod); } } - protected setType() { + protected setType(): void { let op1Type = this.op1.getType(); let op2Type = this.op2.getType(); if (op1Type instanceof UnionType) { @@ -706,15 +704,13 @@ export abstract class AbstractBinopExpr extends AbstractExpr { } break; case '??': - if (op1Type === UnknownType.getInstance() || op1Type === UndefinedType.getInstance() - || op1Type === NullType.getInstance()) { + if (op1Type === UnknownType.getInstance() || op1Type === UndefinedType.getInstance() || op1Type === NullType.getInstance()) { type = op2Type; } else { type = op1Type; } break; default: - ; } this.type = type; } @@ -945,7 +941,7 @@ export class ArkPhiExpr extends AbstractExpr { export enum UnaryOperator { Neg = '-', BitwiseNot = '~', - LogicalNot = '!' + LogicalNot = '!', } // unary operation expression @@ -1124,17 +1120,19 @@ export class AliasTypeExpr extends AbstractExpr { const genericTypes = this.getRealGenericTypes()!.join(','); res = res.replace('(', `<${genericTypes}>(`).replace(/\([^)]*\)/g, `(${genericTypes})`); } - return res + return res; } return `${typeOf}${typeObject.getName()}`; } public static isAliasTypeOriginalModel(object: any): object is AliasTypeOriginalModel { - return object instanceof Type || + return ( + object instanceof Type || object instanceof ImportInfo || object instanceof Local || object instanceof ArkClass || object instanceof ArkMethod || - object instanceof ArkField; + object instanceof ArkField + ); } } diff --git a/ets2panda/linter/arkanalyzer/src/core/base/Local.ts b/ets2panda/linter/arkanalyzer/src/core/base/Local.ts index b018725ccb..aa4fbebdf0 100644 --- a/ets2panda/linter/arkanalyzer/src/core/base/Local.ts +++ b/ets2panda/linter/arkanalyzer/src/core/base/Local.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -14,7 +14,7 @@ */ import { Stmt } from './Stmt'; -import { Type, UnknownType } from './Type'; +import { ClassType, Type, UnknownType } from './Type'; import { Value } from './Value'; import { TypeInference } from '../common/TypeInference'; import { ArkExport, ExportType } from '../model/ArkExport'; @@ -24,6 +24,7 @@ import { UNKNOWN_METHOD_NAME } from '../common/Const'; import { ModifierType } from '../model/ArkBaseModel'; import { ArkMethod } from '../model/ArkMethod'; import { ModelUtils } from '../common/ModelUtils'; +import { THIS_NAME } from '../common/TSConst'; /** * @category core/base @@ -49,9 +50,11 @@ export class Local implements Value, ArkExport { } public inferType(arkMethod: ArkMethod): Local { - if (TypeInference.isUnclearType(this.type)) { - const type = TypeInference.inferUnclearRefName(this.name, arkMethod.getDeclaringArkClass()) ?? - ModelUtils.findDeclaredLocal(this, arkMethod)?.getType(); + if (this.name === THIS_NAME && this.type instanceof UnknownType) { + const declaringArkClass = arkMethod.getDeclaringArkClass(); + this.type = new ClassType(declaringArkClass.getSignature(), declaringArkClass.getRealTypes()); + } else if (TypeInference.isUnclearType(this.type)) { + const type = TypeInference.inferBaseType(this.name, arkMethod.getDeclaringArkClass()) ?? ModelUtils.findDeclaredLocal(this, arkMethod)?.getType(); if (type) { this.type = type; } @@ -127,7 +130,7 @@ export class Local implements Value, ArkExport { return this.declaringStmt; } - public setDeclaringStmt(declaringStmt: Stmt) { + public setDeclaringStmt(declaringStmt: Stmt): void { this.declaringStmt = declaringStmt; } @@ -139,7 +142,7 @@ export class Local implements Value, ArkExport { return []; } - public addUsedStmt(usedStmt: Stmt) { + public addUsedStmt(usedStmt: Stmt): void { this.usedStmts.push(usedStmt); } @@ -187,8 +190,13 @@ export class Local implements Value, ArkExport { } public getSignature(): LocalSignature { - return this.signature ?? new LocalSignature(this.name, new MethodSignature(ClassSignature.DEFAULT, - ArkSignatureBuilder.buildMethodSubSignatureFromMethodName(UNKNOWN_METHOD_NAME))); + return ( + this.signature ?? + new LocalSignature( + this.name, + new MethodSignature(ClassSignature.DEFAULT, ArkSignatureBuilder.buildMethodSubSignatureFromMethodName(UNKNOWN_METHOD_NAME)) + ) + ); } public setSignature(signature: LocalSignature): void { @@ -205,4 +213,4 @@ export class Local implements Value, ArkExport { public setConstFlag(newConstFlag: boolean): void { this.constFlag = newConstFlag; } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/base/Position.ts b/ets2panda/linter/arkanalyzer/src/core/base/Position.ts index 9ae747dac9..2e1087b4cd 100644 --- a/ets2panda/linter/arkanalyzer/src/core/base/Position.ts +++ b/ets2panda/linter/arkanalyzer/src/core/base/Position.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -94,7 +94,7 @@ export class LineColPosition { return getColNo(this.lineCol); } - public static buildFromNode(node: ts.Node, sourceFile: ts.SourceFile) { + public static buildFromNode(node: ts.Node, sourceFile: ts.SourceFile): LineColPosition { let { line, character } = ts.getLineAndCharacterOfPosition(sourceFile, node.getStart(sourceFile)); // line start from 1. return new LineColPosition(line + 1, character + 1); @@ -129,10 +129,7 @@ export class FullPosition { } public static buildFromNode(node: ts.Node, sourceFile: ts.SourceFile): FullPosition { - const { line: startLine, character: startCharacter } = ts.getLineAndCharacterOfPosition( - sourceFile, - node.getStart(sourceFile) - ); + const { line: startLine, character: startCharacter } = ts.getLineAndCharacterOfPosition(sourceFile, node.getStart(sourceFile)); const { line: endLine, character: endCharacter } = ts.getLineAndCharacterOfPosition(sourceFile, node.getEnd()); // line start from 1 diff --git a/ets2panda/linter/arkanalyzer/src/core/base/Ref.ts b/ets2panda/linter/arkanalyzer/src/core/base/Ref.ts index 612b0e3371..66e13f6d90 100644 --- a/ets2panda/linter/arkanalyzer/src/core/base/Ref.ts +++ b/ets2panda/linter/arkanalyzer/src/core/base/Ref.ts @@ -39,7 +39,7 @@ export abstract class AbstractRef implements Value { } export class ArkArrayRef extends AbstractRef { - private base: Local; // 数组变量 + private base: Local; // 数组变量 private index: Value; // 索引 constructor(base: Local, index: Value) { @@ -167,7 +167,7 @@ export abstract class AbstractFieldRef extends AbstractRef { } export class ArkInstanceFieldRef extends AbstractFieldRef { - private base: Local; // which obj this field belong to + private base: Local; // which obj this field belong to constructor(base: Local, fieldSignature: FieldSignature) { super(fieldSignature); @@ -216,7 +216,6 @@ export class ArkInstanceFieldRef extends AbstractFieldRef { public inferType(arkMethod: ArkMethod): AbstractRef { return IRInference.inferFieldRef(this, arkMethod); } - } export class ArkStaticFieldRef extends AbstractFieldRef { @@ -272,7 +271,6 @@ export class ArkParameterRef extends AbstractRef { } } - export class ArkThisRef extends AbstractRef { private type: ClassType; @@ -400,7 +398,10 @@ export class ClosureFieldRef extends AbstractRef { if (TypeInference.isUnclearType(this.type)) { let type: Type | undefined = this.base.getType(); if (type instanceof LexicalEnvType) { - type = type.getClosures().find(c => c.getName() === this.fieldName)?.getType(); + type = type + .getClosures() + .find(c => c.getName() === this.fieldName) + ?.getType(); } if (type && !TypeInference.isUnclearType(type)) { this.type = type; @@ -408,4 +409,4 @@ export class ClosureFieldRef extends AbstractRef { } return this; } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/base/Stmt.ts b/ets2panda/linter/arkanalyzer/src/core/base/Stmt.ts index 914bf73043..6d792a826e 100644 --- a/ets2panda/linter/arkanalyzer/src/core/base/Stmt.ts +++ b/ets2panda/linter/arkanalyzer/src/core/base/Stmt.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -30,12 +30,12 @@ import { AbstractTypeExpr } from './TypeExpr'; * @category core/base/stmt */ export abstract class Stmt { - protected text?: string; // just for debug + protected text?: string; // just for debug protected originalText?: string; protected originalPosition: LineColPosition = LineColPosition.DEFAULT; protected cfg!: Cfg; protected operandOriginalPositions?: FullPosition[]; // operandOriginalPositions correspond with - // def and uses one by one + // def and uses one by one metadata?: ArkMetadata; public getMetadata(kind: ArkMetadataKind): ArkMetadataType | undefined { @@ -48,7 +48,7 @@ export abstract class Stmt { } return this.metadata?.setMetadata(kind, value); } - + /** Return a list of values which are uesd in this statement */ public getUses(): Value[] { return []; @@ -274,7 +274,7 @@ export abstract class Stmt { return this.originalPosition; } - abstract toString(): string ; + abstract toString(): string; public setText(text: string): void { this.text = text; @@ -290,14 +290,14 @@ export abstract class Stmt { public setOperandOriginalPositions(operandOriginalPositions: FullPosition[]): void { this.operandOriginalPositions = operandOriginalPositions; - }; + } public getOperandOriginalPositions(): FullPosition[] | undefined { return this.operandOriginalPositions; - }; + } public getOperandOriginalPosition(indexOrOperand: number | Value): FullPosition | null { - let index:number = -1; + let index: number = -1; if (typeof indexOrOperand !== 'number') { index = IRUtils.findOperandIdx(this, indexOrOperand); } else { @@ -308,7 +308,7 @@ export abstract class Stmt { return null; } return this.operandOriginalPositions[index]; - }; + } } export class ArkAssignStmt extends Stmt { @@ -322,7 +322,7 @@ export class ArkAssignStmt extends Stmt { } /** - * Returns the left operand of the assigning statement. + * Returns the left operand of the assigning statement. * @returns The left operand of the assigning statement. * @example * 1. If the statement is `a=b;`, the right operand is `a`; if the statement is `dd = cc + 5;`, the right operand @@ -381,11 +381,11 @@ export class ArkInvokeStmt extends Stmt { this.invokeExpr = invokeExpr; } - public replaceInvokeExpr(newExpr: AbstractInvokeExpr) { + public replaceInvokeExpr(newExpr: AbstractInvokeExpr): void { this.invokeExpr = newExpr; } - public getInvokeExpr() { + public getInvokeExpr(): AbstractInvokeExpr { return this.invokeExpr; } @@ -600,4 +600,4 @@ export class ArkAliasTypeDefineStmt extends Stmt { } return []; } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/base/Trap.ts b/ets2panda/linter/arkanalyzer/src/core/base/Trap.ts index b5e22d7594..62237fe0e9 100644 --- a/ets2panda/linter/arkanalyzer/src/core/base/Trap.ts +++ b/ets2panda/linter/arkanalyzer/src/core/base/Trap.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -31,4 +31,4 @@ export class Trap { public getCatchBlocks(): BasicBlock[] { return this.catchBlocks; } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/base/Type.ts b/ets2panda/linter/arkanalyzer/src/core/base/Type.ts index 18a85c32fc..1698746774 100644 --- a/ets2panda/linter/arkanalyzer/src/core/base/Type.ts +++ b/ets2panda/linter/arkanalyzer/src/core/base/Type.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -import { AliasTypeSignature, ClassSignature, MethodSignature, NamespaceSignature, } from '../model/ArkSignature'; +import { AliasTypeSignature, ClassSignature, FieldSignature, MethodSignature, NamespaceSignature } from '../model/ArkSignature'; import { ArkExport, ExportType } from '../model/ArkExport'; import { MODIFIER_TYPE_MASK, ModifierType } from '../model/ArkBaseModel'; import { @@ -29,6 +29,7 @@ import { VOID_KEYWORD, } from '../common/TSConst'; import { Local } from './Local'; +import { Constant } from './Constant'; /** * @category core/base/type @@ -95,7 +96,7 @@ export class UnclearReferenceType extends Type { this.genericTypes = genericTypes; } - public getName() { + public getName(): string { return this.name; } @@ -124,7 +125,7 @@ export abstract class PrimitiveType extends Type { this.name = name; } - public getName() { + public getName(): string { return this.name; } @@ -140,7 +141,7 @@ export class BooleanType extends PrimitiveType { super(BOOLEAN_KEYWORD); } - public static getInstance() { + public static getInstance(): BooleanType { return this.INSTANCE; } } @@ -152,7 +153,7 @@ export class NumberType extends PrimitiveType { super(NUMBER_KEYWORD); } - public static getInstance() { + public static getInstance(): NumberType { return this.INSTANCE; } } @@ -168,7 +169,7 @@ export class BigIntType extends PrimitiveType { super(BIGINT_KEYWORD); } - public static getInstance() { + public static getInstance(): BigIntType { return this.INSTANCE; } } @@ -180,7 +181,7 @@ export class StringType extends PrimitiveType { super(STRING_KEYWORD); } - public static getInstance() { + public static getInstance(): StringType { return this.INSTANCE; } } @@ -247,7 +248,7 @@ export class LiteralType extends PrimitiveType { */ export class UnionType extends Type { private types: Type[]; - private currType: Type; // The true type of the value at this time + private currType: Type; // The true type of the value at this time constructor(types: Type[], currType: Type = UnknownType.getInstance()) { super(); this.types = [...types]; @@ -268,7 +269,7 @@ export class UnionType extends Type { public getTypeString(): string { let typesString: string[] = []; - this.getTypes().forEach((t) => { + this.getTypes().forEach(t => { if (t instanceof UnionType || t instanceof IntersectionType) { typesString.push(`(${t.toString()})`); } else { @@ -310,7 +311,7 @@ export class IntersectionType extends Type { public getTypeString(): string { let typesString: string[] = []; - this.getTypes().forEach((t) => { + this.getTypes().forEach(t => { if (t instanceof UnionType || t instanceof IntersectionType) { typesString.push(`(${t.toString()})`); } else { @@ -697,7 +698,7 @@ export class GenericType extends Type { this.constraint = type; } - public setIndex(index: number) { + public setIndex(index: number): void { this.index = index; } @@ -792,3 +793,26 @@ export class LexicalEnvType extends Type { return `[${this.getClosures().join(', ')}]`; } } + +export class EnumValueType extends Type { + private signature: FieldSignature; + private constant?: Constant; + + constructor(signature: FieldSignature, constant?: Constant) { + super(); + this.signature = signature; + this.constant = constant; + } + + public getFieldSignature(): FieldSignature { + return this.signature; + } + + public getConstant(): Constant | undefined { + return this.constant; + } + + public getTypeString(): string { + return this.signature.toString(); + } +} diff --git a/ets2panda/linter/arkanalyzer/src/core/base/TypeExpr.ts b/ets2panda/linter/arkanalyzer/src/core/base/TypeExpr.ts index c390f3ce5b..8995083feb 100644 --- a/ets2panda/linter/arkanalyzer/src/core/base/TypeExpr.ts +++ b/ets2panda/linter/arkanalyzer/src/core/base/TypeExpr.ts @@ -175,4 +175,4 @@ export class KeyofTypeExpr extends AbstractTypeExpr { public inferType(arkMethod: ArkMethod): void { IRInference.inferKeyofTypeExpr(this, arkMethod); } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/base/Value.ts b/ets2panda/linter/arkanalyzer/src/core/base/Value.ts index 89ed31ee51..abeb8acba8 100644 --- a/ets2panda/linter/arkanalyzer/src/core/base/Value.ts +++ b/ets2panda/linter/arkanalyzer/src/core/base/Value.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -19,11 +19,11 @@ import { Type } from './Type'; * @category core/base */ export interface Value { - /** + /** * Return a list of values which are contained in this {@link Value}. - * Value is a core interface in ArkAnalyzer, which may represent any value or expression. + * Value is a core interface in ArkAnalyzer, which may represent any value or expression. * @returns An **array** of values used by this value. - */ + */ getUses(): Value[]; /** @@ -45,5 +45,5 @@ export interface Value { } ``` */ - getType():Type; -} \ No newline at end of file + getType(): Type; +} diff --git a/ets2panda/linter/arkanalyzer/src/core/common/ArkError.ts b/ets2panda/linter/arkanalyzer/src/core/common/ArkError.ts index be9fa839a1..effb281a6e 100644 --- a/ets2panda/linter/arkanalyzer/src/core/common/ArkError.ts +++ b/ets2panda/linter/arkanalyzer/src/core/common/ArkError.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/ets2panda/linter/arkanalyzer/src/core/common/ArkIRTransformer.ts b/ets2panda/linter/arkanalyzer/src/core/common/ArkIRTransformer.ts index ab15671794..31f9ecf635 100644 --- a/ets2panda/linter/arkanalyzer/src/core/common/ArkIRTransformer.ts +++ b/ets2panda/linter/arkanalyzer/src/core/common/ArkIRTransformer.ts @@ -29,37 +29,16 @@ import { ArkCaughtExceptionRef, ArkInstanceFieldRef, ArkParameterRef, ArkThisRef import { Value } from '../base/Value'; import * as ts from 'ohos-typescript'; import { Local } from '../base/Local'; -import { - ArkAliasTypeDefineStmt, - ArkAssignStmt, - ArkIfStmt, - ArkInvokeStmt, - ArkReturnStmt, - ArkReturnVoidStmt, - ArkThrowStmt, - Stmt, -} from '../base/Stmt'; +import { ArkAliasTypeDefineStmt, ArkAssignStmt, ArkIfStmt, ArkInvokeStmt, ArkReturnStmt, ArkReturnVoidStmt, ArkThrowStmt, Stmt } from '../base/Stmt'; import { AliasType, BooleanType, ClassType, Type, UnclearReferenceType, UnknownType, VoidType } from '../base/Type'; import { ValueUtil } from './ValueUtil'; -import { - AliasTypeSignature, - ClassSignature, - FieldSignature, - MethodSignature, - MethodSubSignature, -} from '../model/ArkSignature'; +import { AliasTypeSignature, ClassSignature, FieldSignature, MethodSignature, MethodSubSignature } from '../model/ArkSignature'; import { IRUtils } from './IRUtils'; import { ArkMethod } from '../model/ArkMethod'; import { buildArkMethodFromArkClass } from '../model/builder/ArkMethodBuilder'; import { ArkSignatureBuilder } from '../model/builder/ArkSignatureBuilder'; -import { - COMPONENT_BRANCH_FUNCTION, - COMPONENT_CREATE_FUNCTION, - COMPONENT_IF, - COMPONENT_POP_FUNCTION, - COMPONENT_REPEAT, -} from './EtsConst'; +import { COMPONENT_BRANCH_FUNCTION, COMPONENT_CREATE_FUNCTION, COMPONENT_IF, COMPONENT_POP_FUNCTION, COMPONENT_REPEAT } from './EtsConst'; import { FullPosition, LineColPosition } from '../base/Position'; import { ModelUtils } from './ModelUtils'; import { Builtin } from './Builtin'; @@ -74,9 +53,9 @@ import { ArkClass } from '../model/ArkClass'; import { ModifierType } from '../model/ArkBaseModel'; export type ValueAndStmts = { - value: Value, - valueOriginalPositions: FullPosition[], // original positions of value and its uses - stmts: Stmt[] + value: Value; + valueOriginalPositions: FullPosition[]; // original positions of value and its uses + stmts: Stmt[]; }; export class DummyStmt extends Stmt { @@ -132,9 +111,7 @@ export class ArkIRTransformer { let index = 0; for (const methodParameter of this.declaringMethod.getParameters()) { const parameterRef = new ArkParameterRef(index, methodParameter.getType()); - stmts.push(new ArkAssignStmt( - this.arkValueTransformer.addNewLocal(methodParameter.getName(), parameterRef.getType()), - parameterRef)); + stmts.push(new ArkAssignStmt(this.arkValueTransformer.addNewLocal(methodParameter.getName(), parameterRef.getType()), parameterRef)); index++; } @@ -216,18 +193,10 @@ export class ArkIRTransformer { private returnStatementToStmts(returnStatement: ts.ReturnStatement): Stmt[] { const stmts: Stmt[] = []; if (returnStatement.expression) { - let { - value: exprValue, - valueOriginalPositions: exprPositions, - stmts: exprStmts, - } = this.tsNodeToValueAndStmts(returnStatement.expression); + let { value: exprValue, valueOriginalPositions: exprPositions, stmts: exprStmts } = this.tsNodeToValueAndStmts(returnStatement.expression); exprStmts.forEach(stmt => stmts.push(stmt)); if (IRUtils.moreThanOneAddress(exprValue)) { - ({ - value: exprValue, - valueOriginalPositions: exprPositions, - stmts: exprStmts, - } = this.generateAssignStmtForValue(exprValue, exprPositions)); + ({ value: exprValue, valueOriginalPositions: exprPositions, stmts: exprStmts } = this.generateAssignStmtForValue(exprValue, exprPositions)); exprStmts.forEach(stmt => stmts.push(stmt)); } const returnStmt = new ArkReturnStmt(exprValue); @@ -264,11 +233,7 @@ export class ArkIRTransformer { private expressionStatementToStmts(expressionStatement: ts.ExpressionStatement): Stmt[] { const exprNode = expressionStatement.expression; - const { - value: exprValue, - valueOriginalPositions: exprPositions, - stmts: stmts, - } = this.tsNodeToValueAndStmts(exprNode); + const { value: exprValue, valueOriginalPositions: exprPositions, stmts: stmts } = this.tsNodeToValueAndStmts(exprNode); if (exprValue instanceof AbstractInvokeExpr) { this.addInvokeStmts(exprValue, exprPositions, stmts); } else if (this.shouldGenerateExtraAssignStmt(exprNode)) { @@ -285,11 +250,13 @@ export class ArkIRTransformer { let hasRepeat: boolean = false; for (const stmt of stmts) { - if ((stmt instanceof ArkAssignStmt) && (stmt.getRightOp() instanceof ArkStaticInvokeExpr)) { + if (stmt instanceof ArkAssignStmt && stmt.getRightOp() instanceof ArkStaticInvokeExpr) { const rightOp = stmt.getRightOp() as ArkStaticInvokeExpr; if (rightOp.getMethodSignature().getMethodSubSignature().getMethodName() === COMPONENT_REPEAT) { - const createMethodSignature = - ArkSignatureBuilder.buildMethodSignatureFromClassNameAndMethodName(COMPONENT_REPEAT, COMPONENT_CREATE_FUNCTION); + const createMethodSignature = ArkSignatureBuilder.buildMethodSignatureFromClassNameAndMethodName( + COMPONENT_REPEAT, + COMPONENT_CREATE_FUNCTION + ); const createInvokeExpr = new ArkStaticInvokeExpr(createMethodSignature, rightOp.getArgs()); stmt.setRightOp(createInvokeExpr); hasRepeat = true; @@ -308,16 +275,19 @@ export class ArkIRTransformer { if (ts.isParenthesizedExpression(expression)) { return this.shouldGenerateExtraAssignStmt(expression.expression); } - if ((ts.isBinaryExpression(expression) && (expression.operatorToken.kind === ts.SyntaxKind.FirstAssignment || - ArkValueTransformer.isCompoundAssignmentOperator(expression.operatorToken.kind))) || - ts.isEtsComponentExpression(expression) || ts.isVoidExpression(expression) || - ts.isNewExpression(expression) || ts.isCallExpression(expression) || + if ( + (ts.isBinaryExpression(expression) && + (expression.operatorToken.kind === ts.SyntaxKind.FirstAssignment || + ArkValueTransformer.isCompoundAssignmentOperator(expression.operatorToken.kind))) || + ts.isEtsComponentExpression(expression) || + ts.isVoidExpression(expression) || + ts.isNewExpression(expression) || + ts.isCallExpression(expression) || (ts.isPrefixUnaryExpression(expression) && - (expression.operator === ts.SyntaxKind.PlusPlusToken || - expression.operator === ts.SyntaxKind.MinusMinusToken)) || + (expression.operator === ts.SyntaxKind.PlusPlusToken || expression.operator === ts.SyntaxKind.MinusMinusToken)) || (ts.isPostfixUnaryExpression(expression) && - (expression.operator === ts.SyntaxKind.PlusPlusToken || - expression.operator === ts.SyntaxKind.MinusMinusToken))) { + (expression.operator === ts.SyntaxKind.PlusPlusToken || expression.operator === ts.SyntaxKind.MinusMinusToken)) + ) { return false; } @@ -377,8 +347,7 @@ export class ArkIRTransformer { } } else if (ts.isTypeQueryNode(rightOp)) { const localName = rightOp.exprName.getText(this.sourceFile); - const originalLocal = Array.from(this.arkValueTransformer.getLocals()).find(local => - local.getName() === localName); + const originalLocal = Array.from(this.arkValueTransformer.getLocals()).find(local => local.getName() === localName); if (originalLocal === undefined || rightType instanceof UnclearReferenceType) { expr = new AliasTypeExpr(new Local(localName, rightType), true); } else { @@ -441,28 +410,22 @@ export class ArkIRTransformer { public switchStatementToValueAndStmts(switchStatement: ts.SwitchStatement): ValueAndStmts[] { const valueAndStmtsOfSwitchAndCases: ValueAndStmts[] = []; const exprStmts: Stmt[] = []; - let { - value: exprValue, - valueOriginalPositions: exprPositions, - stmts: exprTempStmts, - } = this.tsNodeToValueAndStmts(switchStatement.expression); + let { value: exprValue, valueOriginalPositions: exprPositions, stmts: exprTempStmts } = this.tsNodeToValueAndStmts(switchStatement.expression); exprTempStmts.forEach(stmt => exprStmts.push(stmt)); if (IRUtils.moreThanOneAddress(exprValue)) { - ({ value: exprValue, valueOriginalPositions: exprPositions, stmts: exprTempStmts } = - this.generateAssignStmtForValue(exprValue, exprPositions)); + ({ value: exprValue, valueOriginalPositions: exprPositions, stmts: exprTempStmts } = this.generateAssignStmtForValue(exprValue, exprPositions)); exprTempStmts.forEach(stmt => exprStmts.push(stmt)); } - valueAndStmtsOfSwitchAndCases.push( - { value: exprValue, valueOriginalPositions: exprPositions, stmts: exprStmts }); + valueAndStmtsOfSwitchAndCases.push({ + value: exprValue, + valueOriginalPositions: exprPositions, + stmts: exprStmts, + }); for (const clause of switchStatement.caseBlock.clauses) { if (ts.isCaseClause(clause)) { const clauseStmts: Stmt[] = []; - let { - value: clauseValue, - valueOriginalPositions: clausePositions, - stmts: clauseTempStmts, - } = this.tsNodeToValueAndStmts(clause.expression); + let { value: clauseValue, valueOriginalPositions: clausePositions, stmts: clauseTempStmts } = this.tsNodeToValueAndStmts(clause.expression); clauseTempStmts.forEach(stmt => clauseStmts.push(stmt)); if (IRUtils.moreThanOneAddress(clauseValue)) { ({ @@ -472,8 +435,11 @@ export class ArkIRTransformer { } = this.generateAssignStmtForValue(clauseValue, clausePositions)); clauseTempStmts.forEach(stmt => clauseStmts.push(stmt)); } - valueAndStmtsOfSwitchAndCases.push( - { value: clauseValue, valueOriginalPositions: clausePositions, stmts: clauseStmts }); + valueAndStmtsOfSwitchAndCases.push({ + value: clauseValue, + valueOriginalPositions: clausePositions, + stmts: clauseStmts, + }); } } return valueAndStmtsOfSwitchAndCases; @@ -488,10 +454,7 @@ export class ArkIRTransformer { stmts.push(dummyInitializerStmt); if (forStatement.condition) { - const { - value: conditionValue, - stmts: conditionStmts, - } = this.arkValueTransformer.conditionToValueAndStmts(forStatement.condition); + const { value: conditionValue, stmts: conditionStmts } = this.arkValueTransformer.conditionToValueAndStmts(forStatement.condition); conditionStmts.forEach(stmt => stmts.push(stmt)); stmts.push(new ArkIfStmt(conditionValue as ArkConditionExpr)); } else { @@ -508,19 +471,17 @@ export class ArkIRTransformer { private rangeForStatementToStmts(forOfStatement: ts.ForOfStatement | ts.ForInStatement): Stmt[] { const stmts: Stmt[] = []; - let { - value: iterableValue, - valueOriginalPositions: iterablePositions, - stmts: iterableStmts, - } = this.tsNodeToValueAndStmts(forOfStatement.expression); + let { value: iterableValue, valueOriginalPositions: iterablePositions, stmts: iterableStmts } = this.tsNodeToValueAndStmts(forOfStatement.expression); iterableStmts.forEach(stmt => stmts.push(stmt)); if (!(iterableValue instanceof Local)) { - ({ value: iterableValue, valueOriginalPositions: iterablePositions, stmts: iterableStmts } = - this.generateAssignStmtForValue(iterableValue, iterablePositions)); + ({ + value: iterableValue, + valueOriginalPositions: iterablePositions, + stmts: iterableStmts, + } = this.generateAssignStmtForValue(iterableValue, iterablePositions)); iterableStmts.forEach(stmt => stmts.push(stmt)); } - const iteratorMethodSubSignature = new MethodSubSignature(Builtin.ITERATOR_FUNCTION, [], - Builtin.ITERATOR_CLASS_TYPE); + const iteratorMethodSubSignature = new MethodSubSignature(Builtin.ITERATOR_FUNCTION, [], Builtin.ITERATOR_CLASS_TYPE); const iteratorMethodSignature = new MethodSignature(ClassSignature.DEFAULT, iteratorMethodSubSignature); const iteratorInvokeExpr = new ArkInstanceInvokeExpr(iterableValue as Local, iteratorMethodSignature, []); const iteratorInvokeExprPositions = [iterablePositions[0], ...iterablePositions]; @@ -532,8 +493,7 @@ export class ArkIRTransformer { iteratorStmts.forEach(stmt => stmts.push(stmt)); (iterator as Local).setType(Builtin.ITERATOR_CLASS_TYPE); - const nextMethodSubSignature = new MethodSubSignature(Builtin.ITERATOR_NEXT, [], - Builtin.ITERATOR_RESULT_CLASS_TYPE); + const nextMethodSubSignature = new MethodSubSignature(Builtin.ITERATOR_NEXT, [], Builtin.ITERATOR_RESULT_CLASS_TYPE); const nextMethodSignature = new MethodSignature(ClassSignature.DEFAULT, nextMethodSubSignature); const iteratorNextInvokeExpr = new ArkInstanceInvokeExpr(iterator as Local, nextMethodSignature, []); const iteratorNextInvokeExprPositions = [iteratorPositions[0], ...iteratorPositions]; @@ -541,12 +501,10 @@ export class ArkIRTransformer { value: iteratorResult, valueOriginalPositions: iteratorResultPositions, stmts: iteratorResultStmts, - } = this.generateAssignStmtForValue(iteratorNextInvokeExpr, - iteratorNextInvokeExprPositions); + } = this.generateAssignStmtForValue(iteratorNextInvokeExpr, iteratorNextInvokeExprPositions); iteratorResultStmts.forEach(stmt => stmts.push(stmt)); (iteratorResult as Local).setType(Builtin.ITERATOR_RESULT_CLASS_TYPE); - const doneFieldSignature = new FieldSignature(Builtin.ITERATOR_RESULT_DONE, - Builtin.ITERATOR_RESULT_CLASS_SIGNATURE, BooleanType.getInstance(), false); + const doneFieldSignature = new FieldSignature(Builtin.ITERATOR_RESULT_DONE, Builtin.ITERATOR_RESULT_CLASS_SIGNATURE, BooleanType.getInstance(), false); const doneFieldRef = new ArkInstanceFieldRef(iteratorResult as Local, doneFieldSignature); const doneFieldRefPositions = [iteratorResultPositions[0], ...iteratorResultPositions]; const { @@ -562,8 +520,12 @@ export class ArkIRTransformer { ifStmt.setOperandOriginalPositions(conditionExprPositions); stmts.push(ifStmt); - const valueFieldSignature = new FieldSignature(Builtin.ITERATOR_RESULT_VALUE, - Builtin.ITERATOR_RESULT_CLASS_SIGNATURE, UnknownType.getInstance(), false); + const valueFieldSignature = new FieldSignature( + Builtin.ITERATOR_RESULT_VALUE, + Builtin.ITERATOR_RESULT_CLASS_SIGNATURE, + UnknownType.getInstance(), + false + ); const valueFieldRef = new ArkInstanceFieldRef(iteratorResult as Local, valueFieldSignature); const valueFieldRefPositions = [iteratorResultPositions[0], ...iteratorResultPositions]; const { @@ -579,17 +541,17 @@ export class ArkIRTransformer { if (ts.isVariableDeclarationList(initializerNode)) { const isConst = (initializerNode.flags & ts.NodeFlags.Const) !== 0; const { - value: initValue, valueOriginalPositions: initOriPos, stmts: initStmts, - } = this.arkValueTransformer.variableDeclarationToValueAndStmts(initializerNode.declarations[0], isConst, - false); + value: initValue, + valueOriginalPositions: initOriPos, + stmts: initStmts, + } = this.arkValueTransformer.variableDeclarationToValueAndStmts(initializerNode.declarations[0], isConst, false); const assignStmt = new ArkAssignStmt(initValue, castExpr); assignStmt.setOperandOriginalPositions([...initOriPos, ...castExprPositions]); stmts.push(assignStmt); initStmts.forEach(stmt => stmts.push(stmt)); - } else { // initializer maybe an expression - const { - value: initValue, valueOriginalPositions: initOriPos, stmts: initStmts, - } = this.tsNodeToValueAndStmts(initializerNode); + } else { + // initializer maybe an expression + const { value: initValue, valueOriginalPositions: initOriPos, stmts: initStmts } = this.tsNodeToValueAndStmts(initializerNode); const assignStmt = new ArkAssignStmt(initValue, castExpr); assignStmt.setOperandOriginalPositions([...initOriPos, ...castExprPositions]); initStmts.forEach(stmt => stmts.push(stmt)); @@ -603,10 +565,7 @@ export class ArkIRTransformer { const dummyInitializerStmt = new DummyStmt(ArkIRTransformer.DUMMY_LOOP_INITIALIZER_STMT); stmts.push(dummyInitializerStmt); - const { - value: conditionExpr, - stmts: conditionStmts, - } = this.arkValueTransformer.conditionToValueAndStmts(whileStatement.expression); + const { value: conditionExpr, stmts: conditionStmts } = this.arkValueTransformer.conditionToValueAndStmts(whileStatement.expression); conditionStmts.forEach(stmt => stmts.push(stmt)); stmts.push(new ArkIfStmt(conditionExpr as ArkConditionExpr)); return stmts; @@ -614,10 +573,7 @@ export class ArkIRTransformer { private doStatementToStmts(doStatement: ts.DoStatement): Stmt[] { const stmts: Stmt[] = []; - const { - value: conditionExpr, - stmts: conditionStmts, - } = this.arkValueTransformer.conditionToValueAndStmts(doStatement.expression); + const { value: conditionExpr, stmts: conditionStmts } = this.arkValueTransformer.conditionToValueAndStmts(doStatement.expression); conditionStmts.forEach(stmt => stmts.push(stmt)); stmts.push(new ArkIfStmt(conditionExpr as ArkConditionExpr)); return stmts; @@ -644,13 +600,12 @@ export class ArkIRTransformer { const { value: conditionLocal, valueOriginalPositions: conditionLocalPositions, - stmts: assignConditionStmts + stmts: assignConditionStmts, } = this.generateAssignStmtForValue(conditionExpr, conditionExprPositions); assignConditionStmts.forEach(stmt => stmts.push(stmt)); const createInvokeExpr = new ArkStaticInvokeExpr(createMethodSignature, [conditionLocal]); const createInvokeExprPositions = [conditionLocalPositions[0], ...conditionLocalPositions]; - const { stmts: createStmts } = this.generateAssignStmtForValue(createInvokeExpr, - createInvokeExprPositions); + const { stmts: createStmts } = this.generateAssignStmtForValue(createInvokeExpr, createInvokeExprPositions); createStmts.forEach(stmt => stmts.push(stmt)); const branchMethodSignature = ArkSignatureBuilder.buildMethodSignatureFromClassNameAndMethodName(COMPONENT_IF, COMPONENT_BRANCH_FUNCTION); const branchInvokeExpr = new ArkStaticInvokeExpr(branchMethodSignature, [ValueUtil.getOrCreateNumberConst(0)]); @@ -662,8 +617,7 @@ export class ArkIRTransformer { if (ifStatement.elseStatement) { const branchElseMethodSignature = ArkSignatureBuilder.buildMethodSignatureFromClassNameAndMethodName(COMPONENT_IF, COMPONENT_BRANCH_FUNCTION); const branchElseInvokeExpr = new ArkStaticInvokeExpr(branchElseMethodSignature, [ValueUtil.getOrCreateNumberConst(1)]); - const branchElseInvokeExprPositions = [FullPosition.buildFromNode(ifStatement.elseStatement, - this.sourceFile), FullPosition.DEFAULT]; + const branchElseInvokeExprPositions = [FullPosition.buildFromNode(ifStatement.elseStatement, this.sourceFile), FullPosition.DEFAULT]; const branchElseInvokeStmt = new ArkInvokeStmt(branchElseInvokeExpr); branchElseInvokeStmt.setOperandOriginalPositions(branchElseInvokeExprPositions); stmts.push(branchElseInvokeStmt); @@ -694,11 +648,7 @@ export class ArkIRTransformer { private throwStatementToStmts(throwStatement: ts.ThrowStatement): Stmt[] { const stmts: Stmt[] = []; - const { - value: throwValue, - valueOriginalPositions: throwValuePositions, - stmts: throwStmts, - } = this.tsNodeToValueAndStmts(throwStatement.expression); + const { value: throwValue, valueOriginalPositions: throwValuePositions, stmts: throwStmts } = this.tsNodeToValueAndStmts(throwStatement.expression); throwStmts.forEach(stmt => stmts.push(stmt)); const throwStmt = new ArkThrowStmt(throwValue); throwStmt.setOperandOriginalPositions(throwValuePositions); @@ -710,9 +660,10 @@ export class ArkIRTransformer { const stmts: Stmt[] = []; if (catchClause.variableDeclaration) { const { - value: catchValue, valueOriginalPositions: catchOriPos, stmts: catchStmts, - } = this.arkValueTransformer.variableDeclarationToValueAndStmts(catchClause.variableDeclaration, false, - false); + value: catchValue, + valueOriginalPositions: catchOriPos, + stmts: catchStmts, + } = this.arkValueTransformer.variableDeclarationToValueAndStmts(catchClause.variableDeclaration, false, false); const caughtExceptionRef = new ArkCaughtExceptionRef(UnknownType.getInstance()); const assignStmt = new ArkAssignStmt(catchValue, caughtExceptionRef); assignStmt.setOperandOriginalPositions(catchOriPos); @@ -731,11 +682,7 @@ export class ArkIRTransformer { private newClassInExportToStmts(expression: ts.NewExpression | ts.ObjectLiteralExpression): Stmt[] { let stmts: Stmt[] = []; - let { - value: rightValue, - valueOriginalPositions: rightPositions, - stmts: rightStmts, - } = this.tsNodeToValueAndStmts(expression); + let { value: rightValue, valueOriginalPositions: rightPositions, stmts: rightStmts } = this.tsNodeToValueAndStmts(expression); rightStmts.forEach(stmt => stmts.push(stmt)); let leftValue = this.arkValueTransformer.addNewLocal(DEFAULT); let leftPositions = rightPositions; @@ -764,7 +711,6 @@ export class ArkIRTransformer { case ts.SyntaxKind.ExclamationToken: return UnaryOperator.LogicalNot; default: - ; } return null; } @@ -818,7 +764,6 @@ export class ArkIRTransformer { case ts.SyntaxKind.ExclamationEqualsEqualsToken: return RelationalBinaryOperator.StrictInequality; default: - ; } return null; } @@ -828,11 +773,19 @@ export class ArkIRTransformer { const leftOpPosition = valueOriginalPositions[0]; const assignStmt = new ArkAssignStmt(leftOp, value); assignStmt.setOperandOriginalPositions([leftOpPosition, ...valueOriginalPositions]); - return { value: leftOp, valueOriginalPositions: [leftOpPosition], stmts: [assignStmt] }; - } - - public generateIfStmtForValues(leftValue: Value, leftOpOriginalPositions: FullPosition[], rightValue: Value, - rightOpOriginalPositions: FullPosition[]): Stmt[] { + return { + value: leftOp, + valueOriginalPositions: [leftOpPosition], + stmts: [assignStmt], + }; + } + + public generateIfStmtForValues( + leftValue: Value, + leftOpOriginalPositions: FullPosition[], + rightValue: Value, + rightOpOriginalPositions: FullPosition[] + ): Stmt[] { const stmts: Stmt[] = []; if (IRUtils.moreThanOneAddress(leftValue)) { const { @@ -866,4 +819,4 @@ export class ArkIRTransformer { public setBuilderMethodContextFlag(builderMethodContextFlag: boolean): void { this.builderMethodContextFlag = builderMethodContextFlag; } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/common/ArkValueTransformer.ts b/ets2panda/linter/arkanalyzer/src/core/common/ArkValueTransformer.ts index 1e22c774d4..75d8689428 100644 --- a/ets2panda/linter/arkanalyzer/src/core/common/ArkValueTransformer.ts +++ b/ets2panda/linter/arkanalyzer/src/core/common/ArkValueTransformer.ts @@ -209,8 +209,7 @@ export class ArkValueTransformer { let { value, valueOriginalPositions, stmts } = this.tsNodeToValueAndStmts(node); stmts.forEach(stmt => allStmts.push(stmt)); if (IRUtils.moreThanOneAddress(value)) { - ({ value, valueOriginalPositions, stmts } = - this.arkIRTransformer.generateAssignStmtForValue(value, valueOriginalPositions)); + ({ value, valueOriginalPositions, stmts } = this.arkIRTransformer.generateAssignStmtForValue(value, valueOriginalPositions)); stmts.forEach(stmt => allStmts.push(stmt)); } return { value, valueOriginalPositions, stmts: allStmts }; @@ -237,8 +236,7 @@ export class ArkValueTransformer { ifStmt.setOperandOriginalPositions(conditionPositions); stmts.push(ifStmt); - stmts.push( - new DummyStmt(ArkIRTransformer.DUMMY_CONDITIONAL_OPERATOR_IF_TRUE_STMT + currConditionalOperatorIndex)); + stmts.push(new DummyStmt(ArkIRTransformer.DUMMY_CONDITIONAL_OPERATOR_IF_TRUE_STMT + currConditionalOperatorIndex)); const { value: whenTrueValue, valueOriginalPositions: whenTruePositions, @@ -251,8 +249,7 @@ export class ArkValueTransformer { assignStmtWhenTrue.setOperandOriginalPositions([...resultLocalPosition, ...whenTruePositions]); stmts.push(assignStmtWhenTrue); - stmts.push( - new DummyStmt(ArkIRTransformer.DUMMY_CONDITIONAL_OPERATOR_IF_FALSE_STMT + currConditionalOperatorIndex)); + stmts.push(new DummyStmt(ArkIRTransformer.DUMMY_CONDITIONAL_OPERATOR_IF_FALSE_STMT + currConditionalOperatorIndex)); const { value: whenFalseValue, valueOriginalPositions: whenFalsePositions, @@ -262,9 +259,12 @@ export class ArkValueTransformer { const assignStmt = new ArkAssignStmt(resultLocal, whenFalseValue); assignStmt.setOperandOriginalPositions([...resultLocalPosition, ...whenFalsePositions]); stmts.push(assignStmt); - stmts.push( - new DummyStmt(ArkIRTransformer.DUMMY_CONDITIONAL_OPERATOR_END_STMT + currConditionalOperatorIndex)); - return { value: resultLocal, valueOriginalPositions: resultLocalPosition, stmts: stmts }; + stmts.push(new DummyStmt(ArkIRTransformer.DUMMY_CONDITIONAL_OPERATOR_END_STMT + currConditionalOperatorIndex)); + return { + value: resultLocal, + valueOriginalPositions: resultLocalPosition, + stmts: stmts, + }; } private objectLiteralExpresionToValueAndStmts(objectLiteralExpression: ts.ObjectLiteralExpression): ValueAndStmts { @@ -272,13 +272,11 @@ export class ArkValueTransformer { const declaringArkNamespace = declaringArkClass.getDeclaringArkNamespace(); const anonymousClass = new ArkClass(); if (declaringArkNamespace) { - buildNormalArkClassFromArkNamespace(objectLiteralExpression, declaringArkNamespace, anonymousClass, - this.sourceFile, this.declaringMethod); + buildNormalArkClassFromArkNamespace(objectLiteralExpression, declaringArkNamespace, anonymousClass, this.sourceFile, this.declaringMethod); declaringArkNamespace.addArkClass(anonymousClass); } else { const declaringArkFile = declaringArkClass.getDeclaringArkFile(); - buildNormalArkClassFromArkFile(objectLiteralExpression, declaringArkFile, anonymousClass, this.sourceFile, - this.declaringMethod); + buildNormalArkClassFromArkFile(objectLiteralExpression, declaringArkFile, anonymousClass, this.sourceFile, this.declaringMethod); declaringArkFile.addArkClass(anonymousClass); } @@ -294,24 +292,33 @@ export class ArkValueTransformer { } = this.arkIRTransformer.generateAssignStmtForValue(newExpr, [objectLiteralExpressionPosition]); newExprStmts.forEach(stmt => stmts.push(stmt)); - const constructorMethodSubSignature = ArkSignatureBuilder.buildMethodSubSignatureFromMethodName( - CONSTRUCTOR_NAME); + const constructorMethodSubSignature = ArkSignatureBuilder.buildMethodSubSignatureFromMethodName(CONSTRUCTOR_NAME); const constructorMethodSignature = new MethodSignature(anonymousClassSignature, constructorMethodSubSignature); const constructorInvokeExpr = new ArkInstanceInvokeExpr(newExprLocal as Local, constructorMethodSignature, []); const constructorInvokeExprPositions = [objectLiteralExpressionPosition, ...newExprLocalPositions]; const constructorInvokeStmt = new ArkInvokeStmt(constructorInvokeExpr); constructorInvokeStmt.setOperandOriginalPositions(constructorInvokeExprPositions); stmts.push(constructorInvokeStmt); - return { value: newExprLocal, valueOriginalPositions: newExprLocalPositions, stmts: stmts }; + return { + value: newExprLocal, + valueOriginalPositions: newExprLocalPositions, + stmts: stmts, + }; } - private generateSystemComponentStmt(componentName: string, args: Value[], argPositionsAllFlat: FullPosition[], - componentExpression: ts.EtsComponentExpression | ts.CallExpression, - currStmts: Stmt[]): ValueAndStmts { + private generateSystemComponentStmt( + componentName: string, + args: Value[], + argPositionsAllFlat: FullPosition[], + componentExpression: ts.EtsComponentExpression | ts.CallExpression, + currStmts: Stmt[] + ): ValueAndStmts { const stmts: Stmt[] = [...currStmts]; const componentExpressionPosition = FullPosition.buildFromNode(componentExpression, this.sourceFile); const { - value: componentValue, valueOriginalPositions: componentPositions, stmts: componentStmts, + value: componentValue, + valueOriginalPositions: componentPositions, + stmts: componentStmts, } = this.generateComponentCreationStmts(componentName, args, componentExpressionPosition, argPositionsAllFlat); componentStmts.forEach(stmt => stmts.push(stmt)); @@ -321,12 +328,20 @@ export class ArkValueTransformer { } } stmts.push(this.generateComponentPopStmts(componentName, componentExpressionPosition)); - return { value: componentValue, valueOriginalPositions: componentPositions, stmts: stmts }; + return { + value: componentValue, + valueOriginalPositions: componentPositions, + stmts: stmts, + }; } - private generateCustomViewStmt(componentName: string, args: Value[], argPositionsAllFlat: FullPosition[], - componentExpression: ts.EtsComponentExpression | ts.CallExpression, - currStmts: Stmt[]): ValueAndStmts { + private generateCustomViewStmt( + componentName: string, + args: Value[], + argPositionsAllFlat: FullPosition[], + componentExpression: ts.EtsComponentExpression | ts.CallExpression, + currStmts: Stmt[] + ): ValueAndStmts { const stmts: Stmt[] = [...currStmts]; const componentExpressionPosition = FullPosition.buildFromNode(componentExpression, this.sourceFile); const classSignature = ArkSignatureBuilder.buildClassSignatureFromClassName(componentName); @@ -338,8 +353,7 @@ export class ArkValueTransformer { stmts: newExprStmts, } = this.arkIRTransformer.generateAssignStmtForValue(newExpr, [componentExpressionPosition]); newExprStmts.forEach(stmt => stmts.push(stmt)); - const constructorMethodSubSignature = ArkSignatureBuilder.buildMethodSubSignatureFromMethodName( - CONSTRUCTOR_NAME); + const constructorMethodSubSignature = ArkSignatureBuilder.buildMethodSubSignatureFromMethodName(CONSTRUCTOR_NAME); const constructorMethodSignature = new MethodSignature(classSignature, constructorMethodSubSignature); const instanceInvokeExpr = new ArkInstanceInvokeExpr(newExprLocal as Local, constructorMethodSignature, args); const instanceInvokeExprPositions = [componentExpressionPosition, ...newExprPositions, ...argPositionsAllFlat]; @@ -349,44 +363,52 @@ export class ArkValueTransformer { const createViewArgs = [newExprLocal]; const createViewArgPositionsAll = [newExprPositions]; if (ts.isEtsComponentExpression(componentExpression) && componentExpression.body) { - const anonymous = ts.factory.createArrowFunction([], [], [], undefined, undefined, - componentExpression.body); + const anonymous = ts.factory.createArrowFunction([], [], [], undefined, undefined, componentExpression.body); // @ts-expect-error: add pos info for the created ArrowFunction anonymous.pos = componentExpression.body.pos; // @ts-expect-error: add end info for the created ArrowFunction anonymous.end = componentExpression.body.end; - const { - value: builderMethod, - valueOriginalPositions: builderMethodPositions, - } = this.callableNodeToValueAndStmts(anonymous); + const { value: builderMethod, valueOriginalPositions: builderMethodPositions } = this.callableNodeToValueAndStmts(anonymous); createViewArgs.push(builderMethod); createViewArgPositionsAll.push(builderMethodPositions); } const { - value: componentValue, valueOriginalPositions: componentPositions, stmts: componentStmts, - } = this.generateComponentCreationStmts(COMPONENT_CUSTOMVIEW, createViewArgs, componentExpressionPosition, - createViewArgPositionsAll.flat()); + value: componentValue, + valueOriginalPositions: componentPositions, + stmts: componentStmts, + } = this.generateComponentCreationStmts(COMPONENT_CUSTOMVIEW, createViewArgs, componentExpressionPosition, createViewArgPositionsAll.flat()); componentStmts.forEach(stmt => stmts.push(stmt)); stmts.push(this.generateComponentPopStmts(COMPONENT_CUSTOMVIEW, componentExpressionPosition)); - return { value: componentValue, valueOriginalPositions: componentPositions, stmts: stmts }; + return { + value: componentValue, + valueOriginalPositions: componentPositions, + stmts: stmts, + }; } - private generateComponentCreationStmts(componentName: string, createArgs: Value[], - componentExpressionPosition: FullPosition, - createArgsPositionsAllFlat: FullPosition[]): ValueAndStmts { - const createMethodSignature = ArkSignatureBuilder.buildMethodSignatureFromClassNameAndMethodName( - componentName, COMPONENT_CREATE_FUNCTION); + private generateComponentCreationStmts( + componentName: string, + createArgs: Value[], + componentExpressionPosition: FullPosition, + createArgsPositionsAllFlat: FullPosition[] + ): ValueAndStmts { + const createMethodSignature = ArkSignatureBuilder.buildMethodSignatureFromClassNameAndMethodName(componentName, COMPONENT_CREATE_FUNCTION); const createInvokeExpr = new ArkStaticInvokeExpr(createMethodSignature, createArgs); const createInvokeExprPositions = [componentExpressionPosition, ...createArgsPositionsAllFlat]; const { - value: componentValue, valueOriginalPositions: componentPositions, stmts: componentStmts, + value: componentValue, + valueOriginalPositions: componentPositions, + stmts: componentStmts, } = this.arkIRTransformer.generateAssignStmtForValue(createInvokeExpr, createInvokeExprPositions); - return { value: componentValue, valueOriginalPositions: componentPositions, stmts: componentStmts }; + return { + value: componentValue, + valueOriginalPositions: componentPositions, + stmts: componentStmts, + }; } private generateComponentPopStmts(componentName: string, componentExpressionPosition: FullPosition): Stmt { - const popMethodSignature = ArkSignatureBuilder.buildMethodSignatureFromClassNameAndMethodName( - componentName, COMPONENT_POP_FUNCTION); + const popMethodSignature = ArkSignatureBuilder.buildMethodSignatureFromClassNameAndMethodName(componentName, COMPONENT_POP_FUNCTION); const popInvokeExpr = new ArkStaticInvokeExpr(popMethodSignature, []); const popInvokeExprPositions = [componentExpressionPosition]; const popInvokeStmt = new ArkInvokeStmt(popInvokeExpr); @@ -397,11 +419,9 @@ export class ArkValueTransformer { private etsComponentExpressionToValueAndStmts(etsComponentExpression: ts.EtsComponentExpression): ValueAndStmts { const stmts: Stmt[] = []; const componentName = (etsComponentExpression.expression as ts.Identifier).text; - const { args: args, argPositions: argPositions } = this.parseArguments(stmts, - etsComponentExpression.arguments); + const { args: args, argPositions: argPositions } = this.parseArguments(stmts, etsComponentExpression.arguments); if (isEtsSystemComponent(componentName)) { - return this.generateSystemComponentStmt(componentName, args, argPositions, etsComponentExpression, - stmts); + return this.generateSystemComponentStmt(componentName, args, argPositions, etsComponentExpression, stmts); } return this.generateCustomViewStmt(componentName, args, argPositions, etsComponentExpression, stmts); } @@ -411,13 +431,11 @@ export class ArkValueTransformer { const declaringArkNamespace = declaringArkClass.getDeclaringArkNamespace(); const newClass = new ArkClass(); if (declaringArkNamespace) { - buildNormalArkClassFromArkNamespace(classExpression, declaringArkNamespace, newClass, this.sourceFile, - this.declaringMethod); + buildNormalArkClassFromArkNamespace(classExpression, declaringArkNamespace, newClass, this.sourceFile, this.declaringMethod); declaringArkNamespace.addArkClass(newClass); } else { const declaringArkFile = declaringArkClass.getDeclaringArkFile(); - buildNormalArkClassFromArkFile(classExpression, declaringArkFile, newClass, this.sourceFile, - this.declaringMethod); + buildNormalArkClassFromArkFile(classExpression, declaringArkFile, newClass, this.sourceFile, this.declaringMethod); declaringArkFile.addArkClass(newClass); } const classValue = this.addNewLocal(newClass.getName(), new ClassType(newClass.getSignature())); @@ -429,17 +447,25 @@ export class ArkValueTransformer { } private templateExpressionToValueAndStmts(templateExpression: ts.TemplateExpression): ValueAndStmts { - const { stmts, stringTextValues, placeholderValues, stringTextPositions, placeholderPositions } = - this.collectTemplateValues(templateExpression); + const { stmts, stringTextValues, placeholderValues, stringTextPositions, placeholderPositions } = this.collectTemplateValues(templateExpression); - const { placeholderStringLocals, placeholderStringLocalPositions, newStmts } = - this.processTemplatePlaceholders(placeholderValues, placeholderPositions, stmts); + const { placeholderStringLocals, placeholderStringLocalPositions, newStmts } = this.processTemplatePlaceholders( + placeholderValues, + placeholderPositions, + stmts + ); return this.combineTemplateParts(stringTextValues, stringTextPositions, placeholderStringLocals, placeholderStringLocalPositions, newStmts); } - private processTemplatePlaceholders(placeholderValues: Value[], placeholderPositions: FullPosition[], currStmts: Stmt[]): { - placeholderStringLocals: Local[], placeholderStringLocalPositions: FullPosition[], newStmts: Stmt[] + private processTemplatePlaceholders( + placeholderValues: Value[], + placeholderPositions: FullPosition[], + currStmts: Stmt[] + ): { + placeholderStringLocals: Local[]; + placeholderStringLocalPositions: FullPosition[]; + newStmts: Stmt[]; } { const placeholderStringLocals: Local[] = []; const placeholderStringLocalPositions: FullPosition[] = []; @@ -451,27 +477,40 @@ export class ArkValueTransformer { let placeholderStmts: Stmt[] = []; if (!(placeholderValue instanceof Local)) { - ({ value: placeholderValue, valueOriginalPositions: placeholderPosition, stmts: placeholderStmts } = - this.arkIRTransformer.generateAssignStmtForValue(placeholderValue, placeholderPosition)); + ({ + value: placeholderValue, + valueOriginalPositions: placeholderPosition, + stmts: placeholderStmts, + } = this.arkIRTransformer.generateAssignStmtForValue(placeholderValue, placeholderPosition)); } placeholderStmts.forEach(stmt => newStmts.push(stmt)); const toStringExpr = new ArkInstanceInvokeExpr(placeholderValue as Local, Builtin.TO_STRING_METHOD_SIGNATURE, []); const toStringExprPosition: FullPosition[] = [placeholderPosition[0], placeholderPosition[0]]; const { - value: placeholderStringLocal, valueOriginalPositions: placeholderStringPositions, stmts: toStringStmts, + value: placeholderStringLocal, + valueOriginalPositions: placeholderStringPositions, + stmts: toStringStmts, } = this.arkIRTransformer.generateAssignStmtForValue(toStringExpr, toStringExprPosition); placeholderStringLocals.push(placeholderStringLocal as Local); placeholderStringLocalPositions.push(placeholderStringPositions[0]); toStringStmts.forEach(stmt => newStmts.push(stmt)); } - return { placeholderStringLocals, placeholderStringLocalPositions, newStmts }; + return { + placeholderStringLocals, + placeholderStringLocalPositions, + newStmts, + }; } - private combineTemplateParts(stringTextValues: Value[], stringTextPositions: FullPosition[], - placeholderStringLocals: Local[], placeholderStringLocalPositions: FullPosition[], - currStmts: Stmt[]): ValueAndStmts { + private combineTemplateParts( + stringTextValues: Value[], + stringTextPositions: FullPosition[], + placeholderStringLocals: Local[], + placeholderStringLocalPositions: FullPosition[], + currStmts: Stmt[] + ): ValueAndStmts { const templateParts: Value[] = []; const templatePartPositions: FullPosition[] = []; @@ -496,60 +535,93 @@ export class ArkValueTransformer { for (let i = 1; i < templateParts.length; i++) { const nextTemplatePartPosition = templatePartPositions[i]; const normalBinopExpr = new ArkNormalBinopExpr(currTemplateResult, templateParts[i], NormalBinaryOperator.Addition); - const normalBinopExprPositions = [FullPosition.merge(currTemplateResultPosition, nextTemplatePartPosition), - currTemplateResultPosition, nextTemplatePartPosition]; + const normalBinopExprPositions = [ + FullPosition.merge(currTemplateResultPosition, nextTemplatePartPosition), + currTemplateResultPosition, + nextTemplatePartPosition, + ]; const { - value: combinationValue, valueOriginalPositions: combinationValuePositions, stmts: combinationStmts, + value: combinationValue, + valueOriginalPositions: combinationValuePositions, + stmts: combinationStmts, } = this.arkIRTransformer.generateAssignStmtForValue(normalBinopExpr, normalBinopExprPositions); combinationStmts.forEach(stmt => finalStmts.push(stmt)); currTemplateResult = combinationValue; currTemplateResultPosition = combinationValuePositions[0]; } - return { value: currTemplateResult, valueOriginalPositions: [currTemplateResultPosition], stmts: finalStmts }; + return { + value: currTemplateResult, + valueOriginalPositions: [currTemplateResultPosition], + stmts: finalStmts, + }; } private taggedTemplateExpressionToValueAndStmts(taggedTemplateExpression: ts.TaggedTemplateExpression): ValueAndStmts { - const { - stmts, stringTextValues, placeholderValues, stringTextPositions, placeholderPositions, - } = this.collectTemplateValues(taggedTemplateExpression.template); + const { stmts, stringTextValues, placeholderValues, stringTextPositions, placeholderPositions } = this.collectTemplateValues( + taggedTemplateExpression.template + ); const stringTextBaseType = StringType.getInstance(); const stringTextArrayLen = stringTextValues.length; const stringTextArrayLenValue = ValueUtil.getOrCreateNumberConst(stringTextArrayLen); const stringTextArrayLenPosition = FullPosition.DEFAULT; const { - value: templateObjectLocal, valueOriginalPositions: templateObjectLocalPositions, + value: templateObjectLocal, + valueOriginalPositions: templateObjectLocalPositions, stmts: templateObjectStmts, - } = this.generateArrayExprAndStmts(stringTextBaseType, stringTextArrayLenValue, stringTextArrayLenPosition, - stringTextArrayLen, stringTextValues, stringTextPositions, stmts, FullPosition.DEFAULT, true); + } = this.generateArrayExprAndStmts( + stringTextBaseType, + stringTextArrayLenValue, + stringTextArrayLenPosition, + stringTextArrayLen, + stringTextValues, + stringTextPositions, + stmts, + FullPosition.DEFAULT, + true + ); const placeholderBaseType = AnyType.getInstance(); const placeholdersArrayLen = placeholderValues.length; const placeholdersArrayLenValue = ValueUtil.getOrCreateNumberConst(placeholdersArrayLen); const placeholdersArrayLenPosition = FullPosition.DEFAULT; const { - value: placeholdersLocal, valueOriginalPositions: placeholdersLocalPositions, + value: placeholdersLocal, + valueOriginalPositions: placeholdersLocalPositions, stmts: placeholdersStmts, - } = this.generateArrayExprAndStmts(placeholderBaseType, placeholdersArrayLenValue, placeholdersArrayLenPosition, - placeholdersArrayLen, placeholderValues, placeholderPositions, templateObjectStmts, FullPosition.DEFAULT, true); + } = this.generateArrayExprAndStmts( + placeholderBaseType, + placeholdersArrayLenValue, + placeholdersArrayLenPosition, + placeholdersArrayLen, + placeholderValues, + placeholderPositions, + templateObjectStmts, + FullPosition.DEFAULT, + true + ); const taggedFuncArgus = { - realGenericTypes: undefined, args: [templateObjectLocal, placeholdersLocal], + realGenericTypes: undefined, + args: [templateObjectLocal, placeholdersLocal], argPositions: [templateObjectLocalPositions[0], placeholdersLocalPositions[0]], }; return this.generateInvokeValueAndStmts(taggedTemplateExpression.tag, taggedFuncArgus, placeholdersStmts, taggedTemplateExpression); } - private collectTemplateValues(templateLiteral: ts.TemplateLiteral): - { - stmts: Stmt[], stringTextValues: Value[], placeholderValues: Value[], stringTextPositions: FullPosition[], - placeholderPositions: FullPosition[] - } { + private collectTemplateValues(templateLiteral: ts.TemplateLiteral): { + stmts: Stmt[]; + stringTextValues: Value[]; + placeholderValues: Value[]; + stringTextPositions: FullPosition[]; + placeholderPositions: FullPosition[]; + } { const stmts: Stmt[] = []; if (ts.isNoSubstitutionTemplateLiteral(templateLiteral)) { const templateLiteralString = templateLiteral.getText(this.sourceFile); return { - stmts: [], stringTextValues: [ValueUtil.createStringConst(templateLiteralString)], + stmts: [], + stringTextValues: [ValueUtil.createStringConst(templateLiteralString)], placeholderValues: [], stringTextPositions: [FullPosition.buildFromNode(templateLiteral, this.sourceFile)], placeholderPositions: [], @@ -561,13 +633,14 @@ export class ArkValueTransformer { const stringTextPositions: FullPosition[] = [FullPosition.buildFromNode(head, this.sourceFile)]; const placeholderPositions: FullPosition[] = []; for (const templateSpan of templateLiteral.templateSpans) { - let { - value: exprValue, valueOriginalPositions: exprPositions, stmts: exprStmts, - } = this.tsNodeToValueAndStmts(templateSpan.expression); + let { value: exprValue, valueOriginalPositions: exprPositions, stmts: exprStmts } = this.tsNodeToValueAndStmts(templateSpan.expression); exprStmts.forEach(stmt => stmts.push(stmt)); if (IRUtils.moreThanOneAddress(exprValue)) { - ({ value: exprValue, valueOriginalPositions: exprPositions, stmts: exprStmts } = - this.arkIRTransformer.generateAssignStmtForValue(exprValue, exprPositions)); + ({ + value: exprValue, + valueOriginalPositions: exprPositions, + stmts: exprStmts, + } = this.arkIRTransformer.generateAssignStmtForValue(exprValue, exprPositions)); exprStmts.forEach(stmt => stmts.push(stmt)); } placeholderValues.push(exprValue); @@ -575,7 +648,13 @@ export class ArkValueTransformer { stringTextPositions.push(FullPosition.buildFromNode(templateSpan.literal, this.sourceFile)); stringTextValues.push(ValueUtil.createStringConst(templateSpan.literal.rawText || '')); } - return { stmts, stringTextValues, placeholderValues, stringTextPositions, placeholderPositions }; + return { + stmts, + stringTextValues, + placeholderValues, + stringTextPositions, + placeholderPositions, + }; } private identifierToValueAndStmts(identifier: ts.Identifier, variableDefFlag: boolean = false): ValueAndStmts { @@ -590,25 +669,31 @@ export class ArkValueTransformer { identifierValue = this.getOrCreateLocal(identifier.text); } } - return { value: identifierValue, valueOriginalPositions: identifierPositions, stmts: [] }; + return { + value: identifierValue, + valueOriginalPositions: identifierPositions, + stmts: [], + }; } private propertyAccessExpressionToValue(propertyAccessExpression: ts.PropertyAccessExpression): ValueAndStmts { const stmts: Stmt[] = []; - let { - value: baseValue, - valueOriginalPositions: basePositions, - stmts: baseStmts, - } = this.tsNodeToValueAndStmts(propertyAccessExpression.expression); + let { value: baseValue, valueOriginalPositions: basePositions, stmts: baseStmts } = this.tsNodeToValueAndStmts(propertyAccessExpression.expression); baseStmts.forEach(stmt => stmts.push(stmt)); if (IRUtils.moreThanOneAddress(baseValue)) { - ({ value: baseValue, valueOriginalPositions: basePositions, stmts: baseStmts } = - this.arkIRTransformer.generateAssignStmtForValue(baseValue, basePositions)); + ({ + value: baseValue, + valueOriginalPositions: basePositions, + stmts: baseStmts, + } = this.arkIRTransformer.generateAssignStmtForValue(baseValue, basePositions)); baseStmts.forEach(stmt => stmts.push(stmt)); } if (!(baseValue instanceof Local)) { - ({ value: baseValue, valueOriginalPositions: basePositions, stmts: baseStmts } = - this.arkIRTransformer.generateAssignStmtForValue(baseValue, basePositions)); + ({ + value: baseValue, + valueOriginalPositions: basePositions, + stmts: baseStmts, + } = this.arkIRTransformer.generateAssignStmtForValue(baseValue, basePositions)); baseStmts.forEach(stmt => stmts.push(stmt)); } @@ -617,32 +702,49 @@ export class ArkValueTransformer { // this if for the case: const obj: Object = Object.create(Object.prototype); if (baseValue instanceof Local && baseValue.getName() === Builtin.OBJECT) { this.locals.delete(baseValue.getName()); - const fieldSignature = new FieldSignature(propertyAccessExpression.name.getText(this.sourceFile), - Builtin.OBJECT_CLASS_SIGNATURE, UnknownType.getInstance(), true); + const fieldSignature = new FieldSignature( + propertyAccessExpression.name.getText(this.sourceFile), + Builtin.OBJECT_CLASS_SIGNATURE, + UnknownType.getInstance(), + true + ); const fieldRef = new ArkStaticFieldRef(fieldSignature); - return { value: fieldRef, valueOriginalPositions: fieldRefPositions, stmts: stmts }; + return { + value: fieldRef, + valueOriginalPositions: fieldRefPositions, + stmts: stmts, + }; } let fieldSignature: FieldSignature; if (baseValue instanceof Local && baseValue.getType() instanceof ClassType) { - fieldSignature = new FieldSignature(propertyAccessExpression.name.getText(this.sourceFile), - (baseValue.getType() as ClassType).getClassSignature(), UnknownType.getInstance()); + fieldSignature = new FieldSignature( + propertyAccessExpression.name.getText(this.sourceFile), + (baseValue.getType() as ClassType).getClassSignature(), + UnknownType.getInstance() + ); } else { fieldSignature = ArkSignatureBuilder.buildFieldSignatureFromFieldName(propertyAccessExpression.name.getText(this.sourceFile)); } const fieldRef = new ArkInstanceFieldRef(baseValue as Local, fieldSignature); - return { value: fieldRef, valueOriginalPositions: fieldRefPositions, stmts: stmts }; + return { + value: fieldRef, + valueOriginalPositions: fieldRefPositions, + stmts: stmts, + }; } private elementAccessExpressionToValueAndStmts(elementAccessExpression: ts.ElementAccessExpression): ValueAndStmts { const stmts: Stmt[] = []; - let { value: baseValue, valueOriginalPositions: basePositions, stmts: baseStmts } = this.tsNodeToValueAndStmts( - elementAccessExpression.expression); + let { value: baseValue, valueOriginalPositions: basePositions, stmts: baseStmts } = this.tsNodeToValueAndStmts(elementAccessExpression.expression); baseStmts.forEach(stmt => stmts.push(stmt)); if (!(baseValue instanceof Local)) { - ({ value: baseValue, valueOriginalPositions: basePositions, stmts: baseStmts } = - this.arkIRTransformer.generateAssignStmtForValue(baseValue, basePositions)); + ({ + value: baseValue, + valueOriginalPositions: basePositions, + stmts: baseStmts, + } = this.arkIRTransformer.generateAssignStmtForValue(baseValue, basePositions)); baseStmts.forEach(stmt => stmts.push(stmt)); } let { @@ -652,8 +754,11 @@ export class ArkValueTransformer { } = this.tsNodeToValueAndStmts(elementAccessExpression.argumentExpression); argumentStmts.forEach(stmt => stmts.push(stmt)); if (IRUtils.moreThanOneAddress(argumentValue)) { - ({ value: argumentValue, valueOriginalPositions: arguPositions, stmts: argumentStmts } = - this.arkIRTransformer.generateAssignStmtForValue(argumentValue, arguPositions)); + ({ + value: argumentValue, + valueOriginalPositions: arguPositions, + stmts: argumentStmts, + } = this.arkIRTransformer.generateAssignStmtForValue(argumentValue, arguPositions)); argumentStmts.forEach(stmt => stmts.push(stmt)); } @@ -666,9 +771,12 @@ export class ArkValueTransformer { elementAccessExpr = new ArkInstanceFieldRef(baseValue as Local, fieldSignature); } // reserve positions for field name - const exprPositions = [FullPosition.buildFromNode(elementAccessExpression, this.sourceFile), ...basePositions, - ...arguPositions]; - return { value: elementAccessExpr, valueOriginalPositions: exprPositions, stmts: stmts }; + const exprPositions = [FullPosition.buildFromNode(elementAccessExpression, this.sourceFile), ...basePositions, ...arguPositions]; + return { + value: elementAccessExpr, + valueOriginalPositions: exprPositions, + stmts: stmts, + }; } private callExpressionToValueAndStmts(callExpression: ts.CallExpression): ValueAndStmts { @@ -677,17 +785,18 @@ export class ArkValueTransformer { return this.generateInvokeValueAndStmts(callExpression.expression, argus, stmts, callExpression); } - private generateInvokeValueAndStmts(functionNameNode: ts.LeftHandSideExpression, argus: { - realGenericTypes: Type[] | undefined, - args: Value[], - argPositions: FullPosition[] - }, currStmts: Stmt[], callExpression: ts.CallExpression | ts.TaggedTemplateExpression): ValueAndStmts { + private generateInvokeValueAndStmts( + functionNameNode: ts.LeftHandSideExpression, + argus: { + realGenericTypes: Type[] | undefined; + args: Value[]; + argPositions: FullPosition[]; + }, + currStmts: Stmt[], + callExpression: ts.CallExpression | ts.TaggedTemplateExpression + ): ValueAndStmts { const stmts: Stmt[] = [...currStmts]; - let { - value: callerValue, - valueOriginalPositions: callerPositions, - stmts: callerStmts, - } = this.tsNodeToValueAndStmts(functionNameNode); + let { value: callerValue, valueOriginalPositions: callerPositions, stmts: callerStmts } = this.tsNodeToValueAndStmts(functionNameNode); callerStmts.forEach(stmt => stmts.push(stmt)); let invokeValue: Value; @@ -724,20 +833,30 @@ export class ArkValueTransformer { invokeValue = new ArkStaticInvokeExpr(methodSignature, args, realGenericTypes); } } else { - ({ value: callerValue, valueOriginalPositions: callerPositions, stmts: callerStmts } = - this.arkIRTransformer.generateAssignStmtForValue(callerValue, callerPositions)); + ({ + value: callerValue, + valueOriginalPositions: callerPositions, + stmts: callerStmts, + } = this.arkIRTransformer.generateAssignStmtForValue(callerValue, callerPositions)); callerStmts.forEach(stmt => stmts.push(stmt)); const methodSignature = ArkSignatureBuilder.buildMethodSignatureFromMethodName((callerValue as Local).getName()); invokeValue = new ArkStaticInvokeExpr(methodSignature, args, realGenericTypes); } invokeValuePositions.push(...argPositions); - return { value: invokeValue, valueOriginalPositions: invokeValuePositions, stmts: stmts }; + return { + value: invokeValue, + valueOriginalPositions: invokeValuePositions, + stmts: stmts, + }; } - private parseArgumentsOfCallExpression(currStmts: Stmt[], callExpression: ts.CallExpression): { - realGenericTypes: Type[] | undefined, - args: Value[], - argPositions: FullPosition[] + private parseArgumentsOfCallExpression( + currStmts: Stmt[], + callExpression: ts.CallExpression + ): { + realGenericTypes: Type[] | undefined; + args: Value[]; + argPositions: FullPosition[]; } { let realGenericTypes: Type[] | undefined; if (callExpression.typeArguments) { @@ -754,15 +873,21 @@ export class ArkValueTransformer { builderMethodIndexes = new Set([1]); } } - const { args: args, argPositions: argPositions } = this.parseArguments(currStmts, - callExpression.arguments, builderMethodIndexes); - return { realGenericTypes: realGenericTypes, args: args, argPositions: argPositions }; + const { args: args, argPositions: argPositions } = this.parseArguments(currStmts, callExpression.arguments, builderMethodIndexes); + return { + realGenericTypes: realGenericTypes, + args: args, + argPositions: argPositions, + }; } - private parseArguments(currStmts: Stmt[], argumentNodes?: ts.NodeArray, - builderMethodIndexes?: Set): { - args: Value[], - argPositions: FullPosition[] + private parseArguments( + currStmts: Stmt[], + argumentNodes?: ts.NodeArray, + builderMethodIndexes?: Set + ): { + args: Value[]; + argPositions: FullPosition[]; } { const args: Value[] = []; const argPositions: FullPosition[] = []; @@ -774,17 +899,16 @@ export class ArkValueTransformer { this.builderMethodContextFlag = true; this.arkIRTransformer.setBuilderMethodContextFlag(true); } - let { - value: argValue, - valueOriginalPositions: argPositionsSingle, - stmts: argStmts, - } = this.tsNodeToValueAndStmts(argument); + let { value: argValue, valueOriginalPositions: argPositionsSingle, stmts: argStmts } = this.tsNodeToValueAndStmts(argument); this.builderMethodContextFlag = prevBuilderMethodContextFlag; this.arkIRTransformer.setBuilderMethodContextFlag(prevBuilderMethodContextFlag); argStmts.forEach(s => currStmts.push(s)); if (IRUtils.moreThanOneAddress(argValue)) { - ({ value: argValue, valueOriginalPositions: argPositionsSingle, stmts: argStmts } = - this.arkIRTransformer.generateAssignStmtForValue(argValue, argPositionsSingle)); + ({ + value: argValue, + valueOriginalPositions: argPositionsSingle, + stmts: argStmts, + } = this.arkIRTransformer.generateAssignStmtForValue(argValue, argPositionsSingle)); argStmts.forEach(s => currStmts.push(s)); } args.push(argValue); @@ -843,23 +967,23 @@ export class ArkValueTransformer { value: newLocal, valueOriginalPositions: newLocalPositions, stmts: newExprStmts, - } = this.arkIRTransformer.generateAssignStmtForValue(newExpr, - [FullPosition.buildFromNode(newExpression, this.sourceFile)]); + } = this.arkIRTransformer.generateAssignStmtForValue(newExpr, [FullPosition.buildFromNode(newExpression, this.sourceFile)]); newExprStmts.forEach(stmt => stmts.push(stmt)); - const constructorMethodSubSignature = ArkSignatureBuilder.buildMethodSubSignatureFromMethodName( - CONSTRUCTOR_NAME); + const constructorMethodSubSignature = ArkSignatureBuilder.buildMethodSubSignatureFromMethodName(CONSTRUCTOR_NAME); const constructorMethodSignature = new MethodSignature(classSignature, constructorMethodSubSignature); - const { args: argValues, argPositions: argPositions } = this.parseArguments(stmts, - newExpression.arguments); - const instanceInvokeExpr = new ArkInstanceInvokeExpr(newLocal as Local, constructorMethodSignature, - argValues); + const { args: argValues, argPositions: argPositions } = this.parseArguments(stmts, newExpression.arguments); + const instanceInvokeExpr = new ArkInstanceInvokeExpr(newLocal as Local, constructorMethodSignature, argValues); const instanceInvokeExprPositions = [newLocalPositions[0], ...newLocalPositions, ...argPositions]; const invokeStmt = new ArkInvokeStmt(instanceInvokeExpr); invokeStmt.setOperandOriginalPositions(instanceInvokeExprPositions); stmts.push(invokeStmt); - return { value: newLocal, valueOriginalPositions: newLocalPositions, stmts: stmts }; + return { + value: newLocal, + valueOriginalPositions: newLocalPositions, + stmts: stmts, + }; } private newArrayExpressionToValueAndStmts(newArrayExpression: ts.NewExpression): ValueAndStmts { @@ -871,15 +995,12 @@ export class ArkValueTransformer { } } const stmts: Stmt[] = []; - const { args: argumentValues, argPositions: argPositions } = this.parseArguments(stmts, - newArrayExpression.arguments); + const { args: argumentValues, argPositions: argPositions } = this.parseArguments(stmts, newArrayExpression.arguments); let argumentsLength = newArrayExpression.arguments ? newArrayExpression.arguments.length : 0; let arrayLengthValue: Value; let arrayLength = -1; let arrayLengthPosition = FullPosition.DEFAULT; - if ((argumentsLength === 1) && - ((argumentValues[0].getType() instanceof NumberType) || argumentValues[0].getType() instanceof - UnknownType)) { + if (argumentsLength === 1 && (argumentValues[0].getType() instanceof NumberType || argumentValues[0].getType() instanceof UnknownType)) { arrayLengthValue = argumentValues[0]; arrayLengthPosition = argPositions[0]; } else { @@ -887,15 +1008,24 @@ export class ArkValueTransformer { arrayLength = argumentsLength; } if (baseType instanceof UnknownType) { - if ((argumentsLength > 1) && !(argumentValues[0].getType() instanceof UnknownType)) { + if (argumentsLength > 1 && !(argumentValues[0].getType() instanceof UnknownType)) { baseType = argumentValues[0].getType(); } else { baseType = AnyType.getInstance(); } } const newArrayExprPosition = FullPosition.buildFromNode(newArrayExpression, this.sourceFile); - return this.generateArrayExprAndStmts(baseType, arrayLengthValue, arrayLengthPosition, arrayLength, - argumentValues, argPositions, stmts, newArrayExprPosition, false); + return this.generateArrayExprAndStmts( + baseType, + arrayLengthValue, + arrayLengthPosition, + arrayLength, + argumentValues, + argPositions, + stmts, + newArrayExprPosition, + false + ); } private arrayLiteralExpressionToValueAndStmts(arrayLiteralExpression: ts.ArrayLiteralExpression): ValueAndStmts { @@ -905,15 +1035,14 @@ export class ArkValueTransformer { const elementPositions: FullPosition[] = []; const arrayLength = arrayLiteralExpression.elements.length; for (const element of arrayLiteralExpression.elements) { - let { - value: elementValue, - valueOriginalPositions: elementPosition, - stmts: elementStmts, - } = this.tsNodeToValueAndStmts(element); + let { value: elementValue, valueOriginalPositions: elementPosition, stmts: elementStmts } = this.tsNodeToValueAndStmts(element); elementStmts.forEach(stmt => stmts.push(stmt)); if (IRUtils.moreThanOneAddress(elementValue)) { - ({ value: elementValue, valueOriginalPositions: elementPosition, stmts: elementStmts } = - this.arkIRTransformer.generateAssignStmtForValue(elementValue, elementPosition)); + ({ + value: elementValue, + valueOriginalPositions: elementPosition, + stmts: elementStmts, + } = this.arkIRTransformer.generateAssignStmtForValue(elementValue, elementPosition)); elementStmts.forEach(stmt => stmts.push(stmt)); } elementValues.push(elementValue); @@ -928,15 +1057,30 @@ export class ArkValueTransformer { baseType = new UnionType(Array.from(elementTypes)); } const newArrayExprPosition = FullPosition.buildFromNode(arrayLiteralExpression, this.sourceFile); - return this.generateArrayExprAndStmts(baseType, ValueUtil.getOrCreateNumberConst(arrayLength), FullPosition.DEFAULT, - arrayLength, elementValues, elementPositions, stmts, newArrayExprPosition, true); - } - - private generateArrayExprAndStmts(baseType: Type, arrayLengthValue: Value, arrayLengthPosition: FullPosition, - arrayLength: number, initializerValues: Value[], - initializerPositions: FullPosition[], - currStmts: Stmt[], - newArrayExprPosition: FullPosition, fromLiteral: boolean): ValueAndStmts { + return this.generateArrayExprAndStmts( + baseType, + ValueUtil.getOrCreateNumberConst(arrayLength), + FullPosition.DEFAULT, + arrayLength, + elementValues, + elementPositions, + stmts, + newArrayExprPosition, + true + ); + } + + private generateArrayExprAndStmts( + baseType: Type, + arrayLengthValue: Value, + arrayLengthPosition: FullPosition, + arrayLength: number, + initializerValues: Value[], + initializerPositions: FullPosition[], + currStmts: Stmt[], + newArrayExprPosition: FullPosition, + fromLiteral: boolean + ): ValueAndStmts { const stmts: Stmt[] = [...currStmts]; const newArrayExpr = new ArkNewArrayExpr(baseType, arrayLengthValue, fromLiteral); const newArrayExprPositions = [newArrayExprPosition, arrayLengthPosition]; @@ -954,21 +1098,23 @@ export class ArkValueTransformer { assignStmt.setOperandOriginalPositions([...arrayRefPositions, initializerPositions[i]]); stmts.push(assignStmt); } - return { value: arrayLocal, valueOriginalPositions: arrayLocalPositions, stmts: stmts }; + return { + value: arrayLocal, + valueOriginalPositions: arrayLocalPositions, + stmts: stmts, + }; } - private prefixUnaryExpressionToValueAndStmts(prefixUnaryExpression: ts.PrefixUnaryExpression): ValueAndStmts { const stmts: Stmt[] = []; - let { - value: operandValue, - valueOriginalPositions: operandPositions, - stmts: operandStmts, - } = this.tsNodeToValueAndStmts(prefixUnaryExpression.operand); + let { value: operandValue, valueOriginalPositions: operandPositions, stmts: operandStmts } = this.tsNodeToValueAndStmts(prefixUnaryExpression.operand); operandStmts.forEach(stmt => stmts.push(stmt)); if (IRUtils.moreThanOneAddress(operandValue)) { - ({ value: operandValue, valueOriginalPositions: operandPositions, stmts: operandStmts } = - this.arkIRTransformer.generateAssignStmtForValue(operandValue, operandPositions)); + ({ + value: operandValue, + valueOriginalPositions: operandPositions, + stmts: operandStmts, + } = this.arkIRTransformer.generateAssignStmtForValue(operandValue, operandPositions)); operandStmts.forEach(stmt => stmts.push(stmt)); } @@ -981,9 +1127,17 @@ export class ArkValueTransformer { const assignStmt = new ArkAssignStmt(operandValue, binopExpr); assignStmt.setOperandOriginalPositions([...operandPositions, ...exprPositions]); stmts.push(assignStmt); - return { value: operandValue, valueOriginalPositions: operandPositions, stmts: stmts }; + return { + value: operandValue, + valueOriginalPositions: operandPositions, + stmts: stmts, + }; } else if (operatorToken === ts.SyntaxKind.PlusToken) { - return { value: operandValue, valueOriginalPositions: operandPositions, stmts: stmts }; + return { + value: operandValue, + valueOriginalPositions: operandPositions, + stmts: stmts, + }; } else { let unopExpr: Value; const operator = ArkIRTransformer.tokenToUnaryOperator(operatorToken); @@ -994,21 +1148,24 @@ export class ArkValueTransformer { unopExpr = ValueUtil.getUndefinedConst(); exprPositions = [FullPosition.DEFAULT]; } - return { value: unopExpr, valueOriginalPositions: exprPositions, stmts: stmts }; + return { + value: unopExpr, + valueOriginalPositions: exprPositions, + stmts: stmts, + }; } } private postfixUnaryExpressionToValueAndStmts(postfixUnaryExpression: ts.PostfixUnaryExpression): ValueAndStmts { const stmts: Stmt[] = []; - let { - value: operandValue, - valueOriginalPositions: operandPositions, - stmts: exprStmts, - } = this.tsNodeToValueAndStmts(postfixUnaryExpression.operand); + let { value: operandValue, valueOriginalPositions: operandPositions, stmts: exprStmts } = this.tsNodeToValueAndStmts(postfixUnaryExpression.operand); exprStmts.forEach(stmt => stmts.push(stmt)); if (IRUtils.moreThanOneAddress(operandValue)) { - ({ value: operandValue, valueOriginalPositions: operandPositions, stmts: exprStmts } = - this.arkIRTransformer.generateAssignStmtForValue(operandValue, operandPositions)); + ({ + value: operandValue, + valueOriginalPositions: operandPositions, + stmts: exprStmts, + } = this.arkIRTransformer.generateAssignStmtForValue(operandValue, operandPositions)); exprStmts.forEach(stmt => stmts.push(stmt)); } @@ -1028,25 +1185,32 @@ export class ArkValueTransformer { exprPositions = [FullPosition.DEFAULT]; } - return { value: value, valueOriginalPositions: exprPositions, stmts: stmts }; + return { + value: value, + valueOriginalPositions: exprPositions, + stmts: stmts, + }; } private awaitExpressionToValueAndStmts(awaitExpression: ts.AwaitExpression): ValueAndStmts { const stmts: Stmt[] = []; - let { - value: promiseValue, - valueOriginalPositions: promisePositions, - stmts: promiseStmts, - } = this.tsNodeToValueAndStmts(awaitExpression.expression); + let { value: promiseValue, valueOriginalPositions: promisePositions, stmts: promiseStmts } = this.tsNodeToValueAndStmts(awaitExpression.expression); promiseStmts.forEach(stmt => stmts.push(stmt)); if (IRUtils.moreThanOneAddress(promiseValue)) { - ({ value: promiseValue, valueOriginalPositions: promisePositions, stmts: promiseStmts } = - this.arkIRTransformer.generateAssignStmtForValue(promiseValue, promisePositions)); + ({ + value: promiseValue, + valueOriginalPositions: promisePositions, + stmts: promiseStmts, + } = this.arkIRTransformer.generateAssignStmtForValue(promiseValue, promisePositions)); promiseStmts.forEach(stmt => stmts.push(stmt)); } const awaitExpr = new ArkAwaitExpr(promiseValue); const awaitExprPositions = [FullPosition.buildFromNode(awaitExpression, this.sourceFile), ...promisePositions]; - return { value: awaitExpr, valueOriginalPositions: awaitExprPositions, stmts: stmts }; + return { + value: awaitExpr, + valueOriginalPositions: awaitExprPositions, + stmts: stmts, + }; } private yieldExpressionToValueAndStmts(yieldExpression: ts.YieldExpression): ValueAndStmts { @@ -1054,30 +1218,38 @@ export class ArkValueTransformer { let yieldPositions = [FullPosition.DEFAULT]; let stmts: Stmt[] = []; if (yieldExpression.expression) { - ({ value: yieldValue, valueOriginalPositions: yieldPositions, stmts: stmts } = - this.tsNodeToValueAndStmts(yieldExpression.expression)); + ({ value: yieldValue, valueOriginalPositions: yieldPositions, stmts: stmts } = this.tsNodeToValueAndStmts(yieldExpression.expression)); } const yieldExpr = new ArkYieldExpr(yieldValue); const yieldExprPositions = [FullPosition.buildFromNode(yieldExpression, this.sourceFile), ...yieldPositions]; - return { value: yieldExpr, valueOriginalPositions: yieldExprPositions, stmts: stmts }; + return { + value: yieldExpr, + valueOriginalPositions: yieldExprPositions, + stmts: stmts, + }; } private deleteExpressionToValueAndStmts(deleteExpression: ts.DeleteExpression): ValueAndStmts { - const { value: exprValue, valueOriginalPositions: exprPositions, stmts: stmts } = this.tsNodeToValueAndStmts( - deleteExpression.expression); + const { value: exprValue, valueOriginalPositions: exprPositions, stmts: stmts } = this.tsNodeToValueAndStmts(deleteExpression.expression); const deleteExpr = new ArkDeleteExpr(exprValue as AbstractFieldRef); - const deleteExprPositions = [FullPosition.buildFromNode(deleteExpression, this.sourceFile), - ...exprPositions]; - return { value: deleteExpr, valueOriginalPositions: deleteExprPositions, stmts: stmts }; + const deleteExprPositions = [FullPosition.buildFromNode(deleteExpression, this.sourceFile), ...exprPositions]; + return { + value: deleteExpr, + valueOriginalPositions: deleteExprPositions, + stmts: stmts, + }; } private voidExpressionToValueAndStmts(voidExpression: ts.VoidExpression): ValueAndStmts { - const { value: exprValue, valueOriginalPositions: exprPositions, stmts: stmts } = this.tsNodeToValueAndStmts( - voidExpression.expression); + const { value: exprValue, valueOriginalPositions: exprPositions, stmts: stmts } = this.tsNodeToValueAndStmts(voidExpression.expression); const { stmts: exprStmts } = this.arkIRTransformer.generateAssignStmtForValue(exprValue, exprPositions); exprStmts.forEach(stmt => stmts.push(stmt)); - return { value: ValueUtil.getUndefinedConst(), valueOriginalPositions: [FullPosition.DEFAULT], stmts: stmts }; + return { + value: ValueUtil.getUndefinedConst(), + valueOriginalPositions: [FullPosition.DEFAULT], + stmts: stmts, + }; } private nonNullExpressionToValueAndStmts(nonNullExpression: ts.NonNullExpression): ValueAndStmts { @@ -1089,40 +1261,46 @@ export class ArkValueTransformer { } private typeOfExpressionToValueAndStmts(typeOfExpression: ts.TypeOfExpression): ValueAndStmts { - const { - value: exprValue, - valueOriginalPositions: exprPositions, - stmts: exprStmts, - } = this.tsNodeToValueAndStmts(typeOfExpression.expression); + const { value: exprValue, valueOriginalPositions: exprPositions, stmts: exprStmts } = this.tsNodeToValueAndStmts(typeOfExpression.expression); const typeOfExpr = new ArkTypeOfExpr(exprValue); const typeOfExprPositions = [FullPosition.buildFromNode(typeOfExpression, this.sourceFile), ...exprPositions]; - return { value: typeOfExpr, valueOriginalPositions: typeOfExprPositions, stmts: exprStmts }; + return { + value: typeOfExpr, + valueOriginalPositions: typeOfExprPositions, + stmts: exprStmts, + }; } private asExpressionToValueAndStmts(asExpression: ts.AsExpression): ValueAndStmts { const stmts: Stmt[] = []; - let { value: exprValue, valueOriginalPositions: exprPositions, stmts: exprStmts } = this.tsNodeToValueAndStmts( - asExpression.expression); + let { value: exprValue, valueOriginalPositions: exprPositions, stmts: exprStmts } = this.tsNodeToValueAndStmts(asExpression.expression); exprStmts.forEach(stmt => stmts.push(stmt)); if (IRUtils.moreThanOneAddress(exprValue)) { - ({ value: exprValue, valueOriginalPositions: exprPositions, stmts: exprStmts } = - this.arkIRTransformer.generateAssignStmtForValue(exprValue, exprPositions)); + ({ + value: exprValue, + valueOriginalPositions: exprPositions, + stmts: exprStmts, + } = this.arkIRTransformer.generateAssignStmtForValue(exprValue, exprPositions)); exprStmts.forEach(stmt => stmts.push(stmt)); } const castExpr = new ArkCastExpr(exprValue, this.resolveTypeNode(asExpression.type)); const castExprPositions = [FullPosition.buildFromNode(asExpression, this.sourceFile), ...exprPositions]; - return { value: castExpr, valueOriginalPositions: castExprPositions, stmts: stmts }; + return { + value: castExpr, + valueOriginalPositions: castExprPositions, + stmts: stmts, + }; } private typeAssertionToValueAndStmts(typeAssertion: ts.TypeAssertion): ValueAndStmts { - const { - value: exprValue, - valueOriginalPositions: exprPositions, - stmts: exprStmts, - } = this.tsNodeToValueAndStmts(typeAssertion.expression); + const { value: exprValue, valueOriginalPositions: exprPositions, stmts: exprStmts } = this.tsNodeToValueAndStmts(typeAssertion.expression); const castExpr = new ArkCastExpr(exprValue, this.resolveTypeNode(typeAssertion.type)); const castExprPositions = [FullPosition.buildFromNode(typeAssertion, this.sourceFile), ...exprPositions]; - return { value: castExpr, valueOriginalPositions: castExprPositions, stmts: exprStmts }; + return { + value: castExpr, + valueOriginalPositions: castExprPositions, + stmts: exprStmts, + }; } public variableDeclarationListToValueAndStmts(variableDeclarationList: ts.VariableDeclarationList): ValueAndStmts { @@ -1132,21 +1310,28 @@ export class ArkValueTransformer { const { stmts: declaredStmts } = this.variableDeclarationToValueAndStmts(declaration, isConst); declaredStmts.forEach(s => stmts.push(s)); } - return { value: ValueUtil.getUndefinedConst(), valueOriginalPositions: [FullPosition.DEFAULT], stmts: stmts }; + return { + value: ValueUtil.getUndefinedConst(), + valueOriginalPositions: [FullPosition.DEFAULT], + stmts: stmts, + }; } - public variableDeclarationToValueAndStmts(variableDeclaration: ts.VariableDeclaration, - isConst: boolean, needRightOp: boolean = true): ValueAndStmts { + public variableDeclarationToValueAndStmts(variableDeclaration: ts.VariableDeclaration, isConst: boolean, needRightOp: boolean = true): ValueAndStmts { const leftOpNode = variableDeclaration.name; const rightOpNode = variableDeclaration.initializer; - const declarationType = variableDeclaration.type ? this.resolveTypeNode( - variableDeclaration.type) : UnknownType.getInstance(); + const declarationType = variableDeclaration.type ? this.resolveTypeNode(variableDeclaration.type) : UnknownType.getInstance(); return this.assignmentToValueAndStmts(leftOpNode, rightOpNode, true, isConst, declarationType, needRightOp); } - private assignmentToValueAndStmts(leftOpNode: ts.Node, rightOpNode: ts.Node | undefined, variableDefFlag: boolean, - isConst: boolean, declarationType: Type, - needRightOp: boolean = true): ValueAndStmts { + private assignmentToValueAndStmts( + leftOpNode: ts.Node, + rightOpNode: ts.Node | undefined, + variableDefFlag: boolean, + isConst: boolean, + declarationType: Type, + needRightOp: boolean = true + ): ValueAndStmts { let leftValueAndStmts: ValueAndStmts; if (ts.isIdentifier(leftOpNode)) { leftValueAndStmts = this.identifierToValueAndStmts(leftOpNode, variableDefFlag); @@ -1162,22 +1347,31 @@ export class ArkValueTransformer { let stmts: Stmt[] = []; if (needRightOp) { const { - value: rightValue, valueOriginalPositions: rightPositions, stmts: rightStmts, + value: rightValue, + valueOriginalPositions: rightPositions, + stmts: rightStmts, } = this.assignmentRightOpToValueAndStmts(rightOpNode, leftValue); if (leftValue instanceof Local) { if (variableDefFlag) { leftValue.setConstFlag(isConst); leftValue.setType(declarationType); } - if (leftValue.getType() instanceof UnknownType && !(rightValue.getType() instanceof UnknownType) && - !(rightValue.getType() instanceof UndefinedType)) { + if ( + leftValue.getType() instanceof UnknownType && + !(rightValue.getType() instanceof UnknownType) && + !(rightValue.getType() instanceof UndefinedType) + ) { leftValue.setType(rightValue.getType()); } } const assignStmt = new ArkAssignStmt(leftValue, rightValue); assignStmt.setOperandOriginalPositions([...leftPositions, ...rightPositions]); - if (ts.isArrayBindingPattern(leftOpNode) || ts.isArrayLiteralExpression(leftOpNode) || - ts.isObjectBindingPattern(leftOpNode) || ts.isObjectLiteralExpression(leftOpNode)) { + if ( + ts.isArrayBindingPattern(leftOpNode) || + ts.isArrayLiteralExpression(leftOpNode) || + ts.isObjectBindingPattern(leftOpNode) || + ts.isObjectLiteralExpression(leftOpNode) + ) { rightStmts.forEach(stmt => stmts.push(stmt)); stmts.push(assignStmt); leftStmts.forEach(stmt => stmts.push(stmt)); @@ -1189,7 +1383,11 @@ export class ArkValueTransformer { } else { stmts = leftStmts; } - return { value: leftValue, valueOriginalPositions: leftPositions, stmts: stmts }; + return { + value: leftValue, + valueOriginalPositions: leftPositions, + stmts: stmts, + }; } private assignmentRightOpToValueAndStmts(rightOpNode: ts.Node | undefined, leftValue: Value): ValueAndStmts { @@ -1198,24 +1396,29 @@ export class ArkValueTransformer { let tempRightStmts: Stmt[] = []; const rightStmts: Stmt[] = []; if (rightOpNode) { - ({ value: rightValue, valueOriginalPositions: rightPositions, stmts: tempRightStmts } = - this.tsNodeToValueAndStmts(rightOpNode)); + ({ value: rightValue, valueOriginalPositions: rightPositions, stmts: tempRightStmts } = this.tsNodeToValueAndStmts(rightOpNode)); tempRightStmts.forEach(stmt => rightStmts.push(stmt)); } else { rightValue = ValueUtil.getUndefinedConst(); rightPositions = [FullPosition.DEFAULT]; } if (IRUtils.moreThanOneAddress(leftValue) && IRUtils.moreThanOneAddress(rightValue)) { - ({ value: rightValue, valueOriginalPositions: rightPositions, stmts: tempRightStmts } = - this.arkIRTransformer.generateAssignStmtForValue(rightValue, rightPositions)); + ({ + value: rightValue, + valueOriginalPositions: rightPositions, + stmts: tempRightStmts, + } = this.arkIRTransformer.generateAssignStmtForValue(rightValue, rightPositions)); tempRightStmts.forEach(stmt => rightStmts.push(stmt)); } - return { value: rightValue, valueOriginalPositions: rightPositions, stmts: rightStmts }; + return { + value: rightValue, + valueOriginalPositions: rightPositions, + stmts: rightStmts, + }; } // In assignment patterns, the left operand will be an array literal expression - private arrayDestructuringToValueAndStmts(arrayDestructuring: ts.ArrayBindingPattern | ts.ArrayLiteralExpression, - isConst: boolean = false): ValueAndStmts { + private arrayDestructuringToValueAndStmts(arrayDestructuring: ts.ArrayBindingPattern | ts.ArrayLiteralExpression, isConst: boolean = false): ValueAndStmts { const stmts: Stmt[] = []; const arrayTempLocal = this.generateTempLocal(); const leftOriginalPosition = FullPosition.buildFromNode(arrayDestructuring, this.sourceFile); @@ -1234,12 +1437,18 @@ export class ArkValueTransformer { stmts.push(assignStmt); index++; } - return { value: arrayTempLocal, valueOriginalPositions: [leftOriginalPosition], stmts: stmts }; + return { + value: arrayTempLocal, + valueOriginalPositions: [leftOriginalPosition], + stmts: stmts, + }; } // In assignment patterns, the left operand will be an object literal expression - private objectDestructuringToValueAndStmts(objectDestructuring: ts.ObjectBindingPattern | ts.ObjectLiteralExpression, - isConst: boolean = false): ValueAndStmts { + private objectDestructuringToValueAndStmts( + objectDestructuring: ts.ObjectBindingPattern | ts.ObjectLiteralExpression, + isConst: boolean = false + ): ValueAndStmts { const stmts: Stmt[] = []; const objectTempLocal = this.generateTempLocal(); const leftOriginalPosition = FullPosition.buildFromNode(objectDestructuring, this.sourceFile); @@ -1249,8 +1458,7 @@ export class ArkValueTransformer { let fieldName = ''; let targetName = ''; if (ts.isBindingElement(element)) { - fieldName = element.propertyName ? element.propertyName.getText(this.sourceFile) : element.name.getText( - this.sourceFile); + fieldName = element.propertyName ? element.propertyName.getText(this.sourceFile) : element.name.getText(this.sourceFile); targetName = element.name.getText(this.sourceFile); } else if (ts.isPropertyAssignment(element)) { fieldName = element.name.getText(this.sourceFile); @@ -1265,15 +1473,18 @@ export class ArkValueTransformer { const fieldSignature = ArkSignatureBuilder.buildFieldSignatureFromFieldName(fieldName); const fieldRef = new ArkInstanceFieldRef(objectTempLocal, fieldSignature); const fieldRefPositions = [leftOriginalPosition, leftOriginalPosition]; - const targetLocal = isObjectBindingPattern ? this.addNewLocal(targetName) : this.getOrCreateLocal( - targetName); + const targetLocal = isObjectBindingPattern ? this.addNewLocal(targetName) : this.getOrCreateLocal(targetName); isObjectBindingPattern && targetLocal.setConstFlag(isConst); const targetLocalPosition = FullPosition.buildFromNode(element, this.sourceFile); const assignStmt = new ArkAssignStmt(targetLocal, fieldRef); assignStmt.setOperandOriginalPositions([targetLocalPosition, ...fieldRefPositions]); stmts.push(assignStmt); } - return { value: objectTempLocal, valueOriginalPositions: [leftOriginalPosition], stmts: stmts }; + return { + value: objectTempLocal, + valueOriginalPositions: [leftOriginalPosition], + stmts: stmts, + }; } private binaryExpressionToValueAndStmts(binaryExpression: ts.BinaryExpression): ValueAndStmts { @@ -1288,16 +1499,11 @@ export class ArkValueTransformer { } const stmts: Stmt[] = []; const binaryExpressionPosition = FullPosition.buildFromNode(binaryExpression, this.sourceFile); - const { - value: opValue1, - valueOriginalPositions: opPositions1, - stmts: opStmts1, - } = this.tsNodeToSingleAddressValueAndStmts(binaryExpression.left); + const { value: opValue1, valueOriginalPositions: opPositions1, stmts: opStmts1 } = this.tsNodeToSingleAddressValueAndStmts(binaryExpression.left); opStmts1.forEach(stmt => stmts.push(stmt)); if (operatorToken.kind === ts.SyntaxKind.InstanceOfKeyword) { - const instanceOfExpr = new ArkInstanceOfExpr(opValue1, - new UnclearReferenceType(binaryExpression.right.getText(this.sourceFile))); + const instanceOfExpr = new ArkInstanceOfExpr(opValue1, new UnclearReferenceType(binaryExpression.right.getText(this.sourceFile))); const instanceOfExprPositions = [binaryExpressionPosition, ...opPositions1]; const { value: instanceofRes, @@ -1305,14 +1511,14 @@ export class ArkValueTransformer { stmts: instanceofStmt, } = this.arkIRTransformer.generateAssignStmtForValue(instanceOfExpr, instanceOfExprPositions); instanceofStmt.forEach(stmt => stmts.push(stmt)); - return { value: instanceofRes, valueOriginalPositions: instanceofPos, stmts: stmts }; + return { + value: instanceofRes, + valueOriginalPositions: instanceofPos, + stmts: stmts, + }; } - const { - value: opValue2, - valueOriginalPositions: opPositions2, - stmts: opStmts2, - } = this.tsNodeToSingleAddressValueAndStmts(binaryExpression.right); + const { value: opValue2, valueOriginalPositions: opPositions2, stmts: opStmts2 } = this.tsNodeToSingleAddressValueAndStmts(binaryExpression.right); opStmts2.forEach(stmt => stmts.push(stmt)); let exprValue: Value; let exprValuePositions = [binaryExpressionPosition]; @@ -1332,22 +1538,18 @@ export class ArkValueTransformer { exprValuePositions.push(binaryExpressionPosition); } } - return { value: exprValue, valueOriginalPositions: exprValuePositions, stmts: stmts }; + return { + value: exprValue, + valueOriginalPositions: exprValuePositions, + stmts: stmts, + }; } private compoundAssignmentToValueAndStmts(binaryExpression: ts.BinaryExpression): ValueAndStmts { const stmts: Stmt[] = []; - let { - value: leftValue, - valueOriginalPositions: leftPositions, - stmts: leftStmts, - } = this.tsNodeToValueAndStmts(binaryExpression.left); + let { value: leftValue, valueOriginalPositions: leftPositions, stmts: leftStmts } = this.tsNodeToValueAndStmts(binaryExpression.left); leftStmts.forEach(stmt => stmts.push(stmt)); - let { - value: rightValue, - valueOriginalPositions: rightPositions, - stmts: rightStmts, - } = this.tsNodeToValueAndStmts(binaryExpression.right); + let { value: rightValue, valueOriginalPositions: rightPositions, stmts: rightStmts } = this.tsNodeToValueAndStmts(binaryExpression.right); rightStmts.forEach(stmt => stmts.push(stmt)); if (IRUtils.moreThanOneAddress(leftValue) && IRUtils.moreThanOneAddress(rightValue)) { const { @@ -1367,8 +1569,7 @@ export class ArkValueTransformer { const exprValue = new ArkNormalBinopExpr(leftValue, rightValue, operator); const exprValuePosition = FullPosition.buildFromNode(binaryExpression, this.sourceFile); const assignStmt = new ArkAssignStmt(leftValue, exprValue); - assignStmt.setOperandOriginalPositions( - [...leftPositions, exprValuePosition, ...leftPositions, ...rightPositions]); + assignStmt.setOperandOriginalPositions([...leftPositions, exprValuePosition, ...leftPositions, ...rightPositions]); stmts.push(assignStmt); leftOpValue = leftValue; leftOpPositions = leftPositions; @@ -1376,7 +1577,11 @@ export class ArkValueTransformer { leftOpValue = ValueUtil.getUndefinedConst(); leftOpPositions = [leftPositions[0]]; } - return { value: leftOpValue, valueOriginalPositions: leftOpPositions, stmts: stmts }; + return { + value: leftOpValue, + valueOriginalPositions: leftOpPositions, + stmts: stmts, + }; } private compoundAssignmentTokenToBinaryOperator(token: ts.SyntaxKind): NormalBinaryOperator | null { @@ -1412,21 +1617,16 @@ export class ArkValueTransformer { case ts.SyntaxKind.BarBarEqualsToken: return NormalBinaryOperator.LogicalOr; default: - ; } return null; } public conditionToValueAndStmts(condition: ts.Expression): ValueAndStmts { const stmts: Stmt[] = []; - let { - value: conditionValue, - valueOriginalPositions: conditionPositions, - stmts: conditionStmts, - } = this.tsNodeToValueAndStmts(condition); + let { value: conditionValue, valueOriginalPositions: conditionPositions, stmts: conditionStmts } = this.tsNodeToValueAndStmts(condition); conditionStmts.forEach(stmt => stmts.push(stmt)); let conditionExpr: ArkConditionExpr; - if ((conditionValue instanceof AbstractBinopExpr) && this.isRelationalOperator(conditionValue.getOperator())) { + if (conditionValue instanceof AbstractBinopExpr && this.isRelationalOperator(conditionValue.getOperator())) { const operator = conditionValue.getOperator() as RelationalBinaryOperator; conditionExpr = new ArkConditionExpr(conditionValue.getOp1(), conditionValue.getOp2(), operator); } else { @@ -1438,11 +1638,14 @@ export class ArkValueTransformer { } = this.arkIRTransformer.generateAssignStmtForValue(conditionValue, conditionPositions)); conditionStmts.forEach(stmt => stmts.push(stmt)); } - conditionExpr = new ArkConditionExpr(conditionValue, ValueUtil.getOrCreateNumberConst(0), - RelationalBinaryOperator.InEquality); + conditionExpr = new ArkConditionExpr(conditionValue, ValueUtil.getOrCreateNumberConst(0), RelationalBinaryOperator.InEquality); conditionPositions = [conditionPositions[0], ...conditionPositions, FullPosition.DEFAULT]; } - return { value: conditionExpr, valueOriginalPositions: conditionPositions, stmts: stmts }; + return { + value: conditionExpr, + valueOriginalPositions: conditionPositions, + stmts: stmts, + }; } private literalNodeToValueAndStmts(literalNode: ts.Node): ValueAndStmts | null { @@ -1509,18 +1712,21 @@ export class ArkValueTransformer { } private isRelationalOperator(operator: BinaryOperator): boolean { - return operator === RelationalBinaryOperator.LessThan || + return ( + operator === RelationalBinaryOperator.LessThan || operator === RelationalBinaryOperator.LessThanOrEqual || operator === RelationalBinaryOperator.GreaterThan || operator === RelationalBinaryOperator.GreaterThanOrEqual || operator === RelationalBinaryOperator.Equality || operator === RelationalBinaryOperator.InEquality || operator === RelationalBinaryOperator.StrictEquality || - operator === RelationalBinaryOperator.StrictInequality; + operator === RelationalBinaryOperator.StrictInequality + ); } private isLiteralNode(node: ts.Node): boolean { - if (ts.isStringLiteral(node) || + if ( + ts.isStringLiteral(node) || ts.isNumericLiteral(node) || ts.isBigIntLiteral(node) || ts.isRegularExpressionLiteral(node) || @@ -1528,7 +1734,8 @@ export class ArkValueTransformer { node.kind === ts.SyntaxKind.NullKeyword || node.kind === ts.SyntaxKind.TrueKeyword || node.kind === ts.SyntaxKind.FalseKeyword || - node.kind === ts.SyntaxKind.UndefinedKeyword) { + node.kind === ts.SyntaxKind.UndefinedKeyword + ) { return true; } return false; @@ -1610,10 +1817,11 @@ export class ArkValueTransformer { if (ts.isQualifiedName(exprNameNode)) { if (exprNameNode.left.getText(this.sourceFile) === THIS_NAME) { const fieldName = exprNameNode.right.getText(this.sourceFile); - const fieldSignature = this.declaringMethod.getDeclaringArkClass().getFieldWithName(fieldName)?.getSignature() ?? + const fieldSignature = + this.declaringMethod.getDeclaringArkClass().getFieldWithName(fieldName)?.getSignature() ?? ArkSignatureBuilder.buildFieldSignatureFromFieldName(fieldName); - const baseLocal = this.locals.get(THIS_NAME) ?? - new Local(THIS_NAME, new ClassType(this.declaringMethod.getDeclaringArkClass().getSignature(), genericTypes)); + const baseLocal = + this.locals.get(THIS_NAME) ?? new Local(THIS_NAME, new ClassType(this.declaringMethod.getDeclaringArkClass().getSignature(), genericTypes)); opValue = new ArkInstanceFieldRef(baseLocal, fieldSignature); } else { const exprName = exprNameNode.getText(this.sourceFile); @@ -1663,7 +1871,6 @@ export class ArkValueTransformer { case ts.SyntaxKind.PrefixUnaryExpression: return new LiteralType(parseFloat(literal.getText(sourceFile))); default: - ; } return new LiteralType(literal.getText(sourceFile)); } @@ -1689,8 +1896,8 @@ export class ArkValueTransformer { const unfoldTemplateTypeStrs: string[] = []; for (const unfoldTemplateType of unfoldTemplateTypes) { unfoldTemplateTypeStrs.push( - unfoldTemplateType instanceof AliasType ? unfoldTemplateType.getOriginalType() - .toString() : unfoldTemplateType.toString()); + unfoldTemplateType instanceof AliasType ? unfoldTemplateType.getOriginalType().toString() : unfoldTemplateType.toString() + ); } const templateSpanString = templateSpan.literal.rawText || ''; @@ -1737,8 +1944,12 @@ export class ArkValueTransformer { } else { if (genericTypes.length > 0) { const oldAlias = aliasTypeAndStmt[0]; - let alias = new AliasType(oldAlias.getName(), TypeInference.replaceTypeWithReal(oldAlias.getOriginalType(), genericTypes), - oldAlias.getSignature(), oldAlias.getGenericTypes()); + let alias = new AliasType( + oldAlias.getName(), + TypeInference.replaceTypeWithReal(oldAlias.getOriginalType(), genericTypes), + oldAlias.getSignature(), + oldAlias.getGenericTypes() + ); alias.setRealGenericTypes(genericTypes); return alias; } @@ -1753,8 +1964,7 @@ export class ArkValueTransformer { if (declaringNamespace) { buildNormalArkClassFromArkNamespace(typeLiteralNode, declaringNamespace, anonymousClass, this.sourceFile); } else { - buildNormalArkClassFromArkFile(typeLiteralNode, declaringClass.getDeclaringArkFile(), anonymousClass, - this.sourceFile); + buildNormalArkClassFromArkFile(typeLiteralNode, declaringClass.getDeclaringArkFile(), anonymousClass, this.sourceFile); } return new ClassType(anonymousClass.getSignature()); } @@ -1786,4 +1996,4 @@ export class ArkValueTransformer { ]; return compoundAssignmentOperators.includes(operator); } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/common/Builtin.ts b/ets2panda/linter/arkanalyzer/src/core/common/Builtin.ts index 87cd5981a2..5c74ecf4d2 100644 --- a/ets2panda/linter/arkanalyzer/src/core/common/Builtin.ts +++ b/ets2panda/linter/arkanalyzer/src/core/common/Builtin.ts @@ -56,8 +56,10 @@ export class Builtin { // constants for string public static TO_STRING = 'toString'; - public static TO_STRING_METHOD_SIGNATURE = new MethodSignature(ClassSignature.DEFAULT, - new MethodSubSignature(this.TO_STRING, [], StringType.getInstance(), false)); + public static TO_STRING_METHOD_SIGNATURE = new MethodSignature( + ClassSignature.DEFAULT, + new MethodSubSignature(this.TO_STRING, [], StringType.getInstance(), false) + ); private static buildBuiltInClasses(): Set { const builtInClasses = new Set(); diff --git a/ets2panda/linter/arkanalyzer/src/core/common/Const.ts b/ets2panda/linter/arkanalyzer/src/core/common/Const.ts index 3edd6f6cc0..1fb1a81e79 100644 --- a/ets2panda/linter/arkanalyzer/src/core/common/Const.ts +++ b/ets2panda/linter/arkanalyzer/src/core/common/Const.ts @@ -45,4 +45,4 @@ export const TEMP_LOCAL_PREFIX = NAME_PREFIX; export const LEXICAL_ENV_NAME_PREFIX = TEMP_LOCAL_PREFIX + 'closures'; // ArkTS version -export const ARKTS_STATIC_MARK = 'use static'; \ No newline at end of file +export const ARKTS_STATIC_MARK = 'use static'; diff --git a/ets2panda/linter/arkanalyzer/src/core/common/DummyMainCreater.ts b/ets2panda/linter/arkanalyzer/src/core/common/DummyMainCreater.ts index 479cb2f76c..3818ac8051 100644 --- a/ets2panda/linter/arkanalyzer/src/core/common/DummyMainCreater.ts +++ b/ets2panda/linter/arkanalyzer/src/core/common/DummyMainCreater.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,14 +16,7 @@ import { Scene } from '../../Scene'; import { COMPONENT_LIFECYCLE_METHOD_NAME, getCallbackMethodFromStmt, LIFECYCLE_METHOD_NAME } from '../../utils/entryMethodUtils'; import { Constant } from '../base/Constant'; -import { - AbstractInvokeExpr, - ArkConditionExpr, - ArkInstanceInvokeExpr, - ArkNewExpr, - ArkStaticInvokeExpr, - RelationalBinaryOperator, -} from '../base/Expr'; +import { AbstractInvokeExpr, ArkConditionExpr, ArkInstanceInvokeExpr, ArkNewExpr, ArkStaticInvokeExpr, RelationalBinaryOperator } from '../base/Expr'; import { Local } from '../base/Local'; import { ArkAssignStmt, ArkIfStmt, ArkInvokeStmt, ArkReturnVoidStmt } from '../base/Stmt'; import { ClassType, NumberType, Type } from '../base/Type'; @@ -39,7 +32,6 @@ import { CONSTRUCTOR_NAME } from './TSConst'; import { checkAndUpdateMethod } from '../model/builder/ArkMethodBuilder'; import { ValueUtil } from './ValueUtil'; - /** 收集所有的onCreate,onStart等函数,构造一个虚拟函数,具体为: %statInit() @@ -65,7 +57,6 @@ return */ export class DummyMainCreater { - private entryMethods: ArkMethod[] = []; private classLocalMap: Map = new Map(); private dummyMain: ArkMethod = new ArkMethod(); @@ -81,7 +72,6 @@ export class DummyMainCreater { this.entryMethods.push(...this.getCallbackMethods()); } - public setEntryMethods(methods: ArkMethod[]): void { this.entryMethods = methods; } @@ -89,21 +79,23 @@ export class DummyMainCreater { public createDummyMain(): void { const dummyMainFile = new ArkFile(Language.UNKNOWN); dummyMainFile.setScene(this.scene); - const dummyMainFileSignature = new FileSignature(this.scene.getProjectName(), '@dummyFile') - dummyMainFile.setFileSignature(dummyMainFileSignature) + const dummyMainFileSignature = new FileSignature(this.scene.getProjectName(), '@dummyFile'); + dummyMainFile.setFileSignature(dummyMainFileSignature); this.scene.setFile(dummyMainFile); const dummyMainClass = new ArkClass(); dummyMainClass.setDeclaringArkFile(dummyMainFile); - const dummyMainClassSignature = new ClassSignature('@dummyClass', - dummyMainClass.getDeclaringArkFile().getFileSignature(), dummyMainClass.getDeclaringArkNamespace()?.getSignature() || null); + const dummyMainClassSignature = new ClassSignature( + '@dummyClass', + dummyMainClass.getDeclaringArkFile().getFileSignature(), + dummyMainClass.getDeclaringArkNamespace()?.getSignature() || null + ); dummyMainClass.setSignature(dummyMainClassSignature); dummyMainFile.addArkClass(dummyMainClass); this.dummyMain = new ArkMethod(); this.dummyMain.setDeclaringArkClass(dummyMainClass); const methodSubSignature = ArkSignatureBuilder.buildMethodSubSignatureFromMethodName('@dummyMain'); - const methodSignature = new MethodSignature(this.dummyMain.getDeclaringArkClass().getSignature(), - methodSubSignature); + const methodSignature = new MethodSignature(this.dummyMain.getDeclaringArkClass().getSignature(), methodSubSignature); this.dummyMain.setImplementationSignature(methodSignature); this.dummyMain.setLineCol(0); checkAndUpdateMethod(this.dummyMain, dummyMainClass); @@ -134,8 +126,8 @@ export class DummyMainCreater { } const localSet = new Set(Array.from(this.classLocalMap.values()).filter((value): value is Local => value !== null)); const dummyBody = new ArkBody(localSet, this.createDummyMainCfg()); - this.dummyMain.setBody(dummyBody) - this.addCfg2Stmt() + this.dummyMain.setBody(dummyBody); + this.addCfg2Stmt(); this.scene.addToMethodsMap(this.dummyMain); } @@ -191,6 +183,7 @@ export class DummyMainCreater { paramLocals.push(paramLocal); if (paramType instanceof ClassType) { const assStmt = new ArkAssignStmt(paramLocal, new ArkNewExpr(paramType)); + paramLocal.setDeclaringStmt(assStmt); invokeBlock.addStmt(assStmt); } paramIdx++; @@ -264,7 +257,7 @@ export class DummyMainCreater { return dummyCfg; } - private addCfg2Stmt() { + private addCfg2Stmt(): void { const cfg = this.dummyMain.getCfg(); if (!cfg) { return; @@ -283,7 +276,8 @@ export class DummyMainCreater { private getEntryMethodsFromComponents(): ArkMethod[] { const COMPONENT_BASE_CLASSES = ['CustomComponent', 'ViewPU']; let methods: ArkMethod[] = []; - this.scene.getClasses() + this.scene + .getClasses() .filter(cls => { if (COMPONENT_BASE_CLASSES.includes(cls.getSuperClassName())) { return true; @@ -316,26 +310,30 @@ export class DummyMainCreater { public getMethodsFromAllAbilities(): ArkMethod[] { let methods: ArkMethod[] = []; - this.scene.getClasses() + this.scene + .getClasses() .filter(cls => this.classInheritsAbility(cls)) .forEach(cls => { methods.push(...cls.getMethods().filter(mtd => LIFECYCLE_METHOD_NAME.includes(mtd.getName()))); }); return methods; } - + public getCallbackMethods(): ArkMethod[] { const callbackMethods: ArkMethod[] = []; this.scene.getMethods().forEach(method => { if (!method.getCfg()) { return; } - method.getCfg()!.getStmts().forEach(stmt => { - const cbMethod = getCallbackMethodFromStmt(stmt, this.scene); - if (cbMethod && !callbackMethods.includes(cbMethod)) { - callbackMethods.push(cbMethod); - } - }); + method + .getCfg()! + .getStmts() + .forEach(stmt => { + const cbMethod = getCallbackMethodFromStmt(stmt, this.scene); + if (cbMethod && !callbackMethods.includes(cbMethod)) { + callbackMethods.push(cbMethod); + } + }); }); return callbackMethods; } diff --git a/ets2panda/linter/arkanalyzer/src/core/common/EtsConst.ts b/ets2panda/linter/arkanalyzer/src/core/common/EtsConst.ts index 3d4c1a5161..f01f9396e9 100644 --- a/ets2panda/linter/arkanalyzer/src/core/common/EtsConst.ts +++ b/ets2panda/linter/arkanalyzer/src/core/common/EtsConst.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -923,11 +923,7 @@ export const ETS_COMPILER_OPTIONS = { export const COMPONENT_FOR_EACH: string = 'ForEach'; export const COMPONENT_LAZY_FOR_EACH: string = 'LazyForEach'; -export const BUILDIN_SYSTEM_COMPONENT: Set = new Set([ - ...ETS_COMPILER_OPTIONS.ets.components, - COMPONENT_FOR_EACH, - COMPONENT_LAZY_FOR_EACH, -]); +export const BUILDIN_SYSTEM_COMPONENT: Set = new Set([...ETS_COMPILER_OPTIONS.ets.components, COMPONENT_FOR_EACH, COMPONENT_LAZY_FOR_EACH]); export const BUILDIN_ATOMIC_COMPONENT: Set = new Set([ 'AbilityComponent', @@ -1011,13 +1007,7 @@ export const COMPONENT_IF_BRANCH: string = 'IfBranch'; export const COMPONENT_BRANCH_FUNCTION: string = 'branch'; export const COMPONENT_BUILD_FUNCTION: string = 'build'; -export const SPECIAL_CONTAINER_COMPONENT: Set = new Set([ - COMPONENT_IF, - COMPONENT_IF_BRANCH, - COMPONENT_CUSTOMVIEW, - COMPONENT_REPEAT, -]); - +export const SPECIAL_CONTAINER_COMPONENT: Set = new Set([COMPONENT_IF, COMPONENT_IF_BRANCH, COMPONENT_CUSTOMVIEW, COMPONENT_REPEAT]); export const COMPONENT_COMMON: string = 'Common'; export const COMPONENT_INSTANCE: string = 'Instance'; @@ -1027,4 +1017,4 @@ export const CALL_BACK: string = 'Callback'; export const ON_OFF: Set = new Set(['on', 'off']); export const OH_PACKAGE_JSON5 = 'oh-package.json5'; -export const BUILD_PROFILE_JSON5 = 'build-profile.json5'; \ No newline at end of file +export const BUILD_PROFILE_JSON5 = 'build-profile.json5'; diff --git a/ets2panda/linter/arkanalyzer/src/core/common/ExprUseReplacer.ts b/ets2panda/linter/arkanalyzer/src/core/common/ExprUseReplacer.ts index 3603b3bc51..9bc96442df 100644 --- a/ets2panda/linter/arkanalyzer/src/core/common/ExprUseReplacer.ts +++ b/ets2panda/linter/arkanalyzer/src/core/common/ExprUseReplacer.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -40,7 +40,7 @@ export class ExprUseReplacer { private newUse: Value; constructor(oldUse: Value, newUse: Value) { - this.oldUse = oldUse + this.oldUse = oldUse; this.newUse = newUse; } @@ -86,7 +86,7 @@ export class ExprUseReplacer { } if (expr instanceof ArkInstanceInvokeExpr && expr.getBase() === this.oldUse) { - expr.setBase(this.newUse); + expr.setBase( this.newUse); } else if (expr instanceof ArkPtrInvokeExpr && expr.getFuncPtrLocal() === this.oldUse && this.newUse instanceof Local) { expr.setFunPtrLocal(this.newUse); } @@ -139,4 +139,4 @@ export class ExprUseReplacer { expr.setOp(this.newUse); } } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/common/IRInference.ts b/ets2panda/linter/arkanalyzer/src/core/common/IRInference.ts index 44f222faa0..0808347490 100644 --- a/ets2panda/linter/arkanalyzer/src/core/common/IRInference.ts +++ b/ets2panda/linter/arkanalyzer/src/core/common/IRInference.ts @@ -43,7 +43,7 @@ import Logger, { LOG_MODULE_TYPE } from '../../utils/logger'; import { Scene } from '../../Scene'; import { ArkClass } from '../model/ArkClass'; import { findArkExport, ModelUtils } from './ModelUtils'; -import { ArkField } from '../model/ArkField'; +import { ArkField, FieldCategory } from '../model/ArkField'; import { CALL_BACK } from './EtsConst'; import { AliasClassSignature, @@ -63,7 +63,8 @@ import { ArkArrayRef, ArkInstanceFieldRef, ArkParameterRef, - ArkStaticFieldRef + ArkStaticFieldRef, + GlobalRef } from '../base/Ref'; import { Value } from '../base/Value'; import { Constant } from '../base/Constant'; @@ -83,7 +84,6 @@ import { ArkBaseModel } from '../model/ArkBaseModel'; const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'IRInference'); export class IRInference { - private static inferExportInfos(file: ArkFile): void { file.getExportInfos().forEach(exportInfo => { if (exportInfo.getArkExport() === undefined) { @@ -94,6 +94,15 @@ export class IRInference { } } }); + file.getNamespaces().forEach(namespace => { + namespace.getExportInfos().forEach(exportInfo => { + if (exportInfo.getArkExport() === undefined) { + let arkExport = findArkExport(exportInfo); + exportInfo.setArkExport(arkExport); + arkExport !== null ? exportInfo.setExportClauseType(arkExport.getExportType()) : true; + } + }); + }); } private static inferImportInfos(file: ArkFile): void { @@ -129,6 +138,7 @@ export class IRInference { public static inferStaticInvokeExpr(expr: ArkStaticInvokeExpr, arkMethod: ArkMethod): AbstractInvokeExpr { const arkClass = arkMethod.getDeclaringArkClass(); const methodName = expr.getMethodSignature().getMethodSubSignature().getMethodName(); + expr.getArgs().forEach(arg => TypeInference.inferValueType(arg, arkMethod)); if (methodName === IMPORT) { const arg = expr.getArg(0); let type; @@ -139,9 +149,7 @@ export class IRInference { expr.getMethodSignature().getMethodSubSignature().setReturnType(type); } return expr; - } - expr.getArgs().forEach(arg => TypeInference.inferValueType(arg, arkMethod)); - if (methodName === SUPER_NAME) { + } else if (methodName === SUPER_NAME) { const superClass = arkClass.getSuperClass(); if (superClass !== null) { const newMethodSignature = new MethodSignature(superClass.getSignature(), expr.getMethodSignature().getMethodSubSignature()); @@ -151,7 +159,7 @@ export class IRInference { } const className = expr.getMethodSignature().getDeclaringClassSignature().getClassName(); if (className && className !== UNKNOWN_CLASS_NAME) { - const baseType = TypeInference.inferUnclearRefName(className, arkClass); + const baseType = TypeInference.inferBaseType(className, arkClass); if (baseType) { let result = this.inferInvokeExpr(expr, baseType, methodName, arkClass.getDeclaringArkFile().getScene()); if (result) { @@ -166,7 +174,8 @@ export class IRInference { private static inferStaticInvokeExprByMethodName(methodName: string, arkMethod: ArkMethod, expr: AbstractInvokeExpr): AbstractInvokeExpr { const arkClass = arkMethod.getDeclaringArkClass(); - const arkExport = ModelUtils.getStaticMethodWithName(methodName, arkClass) ?? + const arkExport = + ModelUtils.getStaticMethodWithName(methodName, arkClass) ?? arkMethod.getFunctionLocal(methodName) ?? ModelUtils.findDeclaredLocal(new Local(methodName), arkMethod) ?? ModelUtils.getArkExportInImportInfoWithName(methodName, arkClass.getDeclaringArkFile()) ?? @@ -178,7 +187,7 @@ export class IRInference { } else if (arkExport instanceof ArkClass) { method = arkExport.getMethodWithName(CONSTRUCTOR_NAME); } else if (arkExport instanceof Local) { - const type = arkExport.getType(); + const type = TypeInference.replaceAliasType(arkExport.getType()); if (type instanceof ClassType) { const cls = arkClass.getDeclaringArkFile().getScene().getClass(type.getClassSignature()); method = cls?.getMethodWithName(CONSTRUCTOR_NAME) ?? cls?.getMethodWithName(CALL_SIGNATURE_NAME); @@ -218,13 +227,12 @@ export class IRInference { } } const scene = arkClass.getDeclaringArkFile().getScene(); - if ((methodName === 'forEach') && (baseType instanceof ArrayType)) { + if (methodName === 'forEach' && baseType instanceof ArrayType) { this.processForEach(expr.getArg(0), baseType, scene); return expr; } expr.getArgs().forEach(arg => TypeInference.inferValueType(arg, arkMethod)); - let result = this.inferInvokeExpr(expr, baseType, methodName, scene) ?? - this.processExtendFunc(expr, arkMethod, methodName); + let result = this.inferInvokeExpr(expr, baseType, methodName, scene) ?? this.processExtendFunc(expr, arkMethod, methodName); if (result) { this.inferArgs(result, arkMethod); return result; @@ -275,11 +283,24 @@ export class IRInference { private static inferBase(instance: ArkInstanceFieldRef | ArkInstanceInvokeExpr, arkMethod: ArkMethod): void { const base = instance.getBase(); if (base.getName() === THIS_NAME) { - let newBase = this.inferThisLocal(arkMethod); - if (newBase) { - instance.setBase(newBase); + const declaringArkClass = arkMethod.getDeclaringArkClass(); + if (declaringArkClass.isAnonymousClass()) { + let newBase = this.inferThisLocal(arkMethod); + if (newBase) { + instance.setBase(newBase); + } + } else if (base.getType() instanceof UnknownType) { + base.setType(new ClassType(declaringArkClass.getSignature(), declaringArkClass.getRealTypes())); } } else { + const value = arkMethod.getBody()?.getUsedGlobals()?.get(base.getName()); + if (value instanceof GlobalRef && !value.getRef()) { + const arkExport = ModelUtils.findGlobalRef(base.getName(), arkMethod); + if (arkExport instanceof Local) { + arkExport.getUsedStmts().push(...base.getUsedStmts()); + value.setRef(arkExport); + } + } this.inferLocal(instance.getBase(), arkMethod); } } @@ -341,15 +362,17 @@ export class IRInference { } } - if (paramType instanceof ClassType && scene.getProjectSdkMap().has(paramType.getClassSignature() - .getDeclaringFileSignature().getProjectName())) { + if (paramType instanceof ClassType && scene.getProjectSdkMap().has(paramType.getClassSignature().getDeclaringFileSignature().getProjectName())) { this.inferArgTypeWithSdk(paramType, scene, argType); } else if (paramType instanceof GenericType || paramType instanceof AnyType) { realTypes.push(argType); } else if (paramType instanceof FunctionType && argType instanceof FunctionType) { - const method = scene.getMethod(argType.getMethodSignature()); - if (method) { - TypeInference.inferTypeInMethod(method); + if (paramType.getMethodSignature().getParamLength() > 0 && paramType.getMethodSignature().getType() instanceof GenericType) { + const paramMethod = scene.getMethod(expr.getMethodSignature()); + const argMethod = scene.getMethod(argType.getMethodSignature()); + if (paramMethod && paramMethod.getGenericTypes() && argMethod) { + TypeInference.inferTypeInMethod(argMethod); + } } const realTypes = expr.getRealGenericTypes(); TypeInference.inferFunctionType(argType, paramType.getMethodSignature().getMethodSubSignature(), realTypes); @@ -380,14 +403,12 @@ export class IRInference { } else if (argType instanceof ClassType && argType.getClassSignature().getClassName().startsWith(ANONYMOUS_CLASS_PREFIX)) { this.inferAnonymousClass(scene.getClass(argType.getClassSignature()), sdkType.getClassSignature()); } else if (argType instanceof FunctionType) { - const param = scene.getClass(sdkType.getClassSignature()) - ?.getMethodWithName(CALL_SIGNATURE_NAME)?.getSignature().getMethodSubSignature(); + const param = scene.getClass(sdkType.getClassSignature())?.getMethodWithName(CALL_SIGNATURE_NAME)?.getSignature().getMethodSubSignature(); const realTypes = sdkType.getRealGenericTypes(); TypeInference.inferFunctionType(argType, param, realTypes); } } - private static inferInvokeExpr(expr: AbstractInvokeExpr, baseType: Type, methodName: string, scene: Scene): AbstractInvokeExpr | null { if (baseType instanceof AliasType) { return this.inferInvokeExpr(expr, baseType.getOriginalType(), methodName, scene); @@ -412,8 +433,7 @@ export class IRInference { let signature = foundMethod.matchMethodSignature(expr.getArgs()); TypeInference.inferSignatureReturnType(signature, foundMethod); expr.setMethodSignature(signature); - return expr instanceof ArkInstanceInvokeExpr ? - new ArkStaticInvokeExpr(signature, expr.getArgs(), expr.getRealGenericTypes()) : expr; + return expr instanceof ArkInstanceInvokeExpr ? new ArkStaticInvokeExpr(signature, expr.getArgs(), expr.getRealGenericTypes()) : expr; } } } else if (baseType instanceof FunctionType) { @@ -427,8 +447,7 @@ export class IRInference { private static inferInvokeExprWithArray(methodName: string, expr: AbstractInvokeExpr, baseType: ArrayType, scene: Scene): AbstractInvokeExpr | null { if (methodName === Builtin.ITERATOR_FUNCTION) { const returnType = expr.getMethodSignature().getMethodSubSignature().getReturnType(); - if (returnType instanceof ClassType && returnType.getClassSignature().getDeclaringFileSignature() - .getProjectName() === Builtin.DUMMY_PROJECT_NAME) { + if (returnType instanceof ClassType && returnType.getClassSignature().getDeclaringFileSignature().getProjectName() === Builtin.DUMMY_PROJECT_NAME) { expr.setRealGenericTypes([baseType.getBaseType()]); return expr; } @@ -458,8 +477,12 @@ export class IRInference { return null; } - private static inferInvokeExprWithDeclaredClass(expr: AbstractInvokeExpr, baseType: ClassType, methodName: string, - scene: Scene): AbstractInvokeExpr | null { + private static inferInvokeExprWithDeclaredClass( + expr: AbstractInvokeExpr, + baseType: ClassType, + methodName: string, + scene: Scene + ): AbstractInvokeExpr | null { if (Builtin.isBuiltinClass(baseType.getClassSignature().getClassName())) { expr.setMethodSignature(new MethodSignature(baseType.getClassSignature(), expr.getMethodSignature().getMethodSubSignature())); } @@ -492,16 +515,20 @@ export class IRInference { } } if (methodSignature) { - const ptr = expr instanceof ArkInstanceInvokeExpr ? - new ArkInstanceFieldRef(expr.getBase(), method.getSignature()) : new ArkStaticFieldRef(method.getSignature()); + const ptr = + expr instanceof ArkInstanceInvokeExpr + ? new ArkInstanceFieldRef(expr.getBase(), method.getSignature()) + : new ArkStaticFieldRef(method.getSignature()); expr = new ArkPtrInvokeExpr(methodSignature, ptr, expr.getArgs(), expr.getRealGenericTypes()); } return expr; - } else if (methodName === CONSTRUCTOR_NAME) { //sdk隐式构造 + } else if (methodName === CONSTRUCTOR_NAME) { + //sdk隐式构造 const subSignature = new MethodSubSignature(methodName, [], new ClassType(baseType.getClassSignature())); expr.setMethodSignature(new MethodSignature(baseType.getClassSignature(), subSignature)); return expr; - } else if (methodName === Builtin.ITERATOR_NEXT) { //sdk隐式构造 + } else if (methodName === Builtin.ITERATOR_NEXT) { + //sdk隐式构造 const returnType = expr.getMethodSignature().getMethodSubSignature().getReturnType(); if (returnType instanceof ClassType && returnType.getClassSignature().getDeclaringFileSignature().getProjectName() === Builtin.DUMMY_PROJECT_NAME) { returnType.setRealGenericTypes(baseType.getRealGenericTypes()); @@ -531,8 +558,7 @@ export class IRInference { } let newSubSignature; if (classSignature || newSubSignature) { - return new MethodSignature(classSignature ?? declared.getDeclaringClassSignature(), - newSubSignature ?? declared.getMethodSubSignature()); + return new MethodSignature(classSignature ?? declared.getDeclaringClassSignature(), newSubSignature ?? declared.getMethodSubSignature()); } return declared; } @@ -545,7 +571,7 @@ export class IRInference { if (argMethod != null && argMethod.getBody()) { const body = argMethod.getBody() as ArkBody; const firstStmt = body.getCfg().getStartingStmt(); - if ((firstStmt instanceof ArkAssignStmt) && (firstStmt.getRightOp() instanceof ArkParameterRef)) { + if (firstStmt instanceof ArkAssignStmt && firstStmt.getRightOp() instanceof ArkParameterRef) { const parameterRef = firstStmt.getRightOp() as ArkParameterRef; parameterRef.setType(baseType.getBaseType()); const argMethodParams = argMethod.getSignature().getMethodSubSignature().getParameters(); @@ -593,8 +619,8 @@ export class IRInference { const fieldName = ref.getFieldName().replace(/[\"|\']/g, ''); const propertyAndType = TypeInference.inferFieldType(baseType, fieldName, arkClass); let propertyType = propertyAndType?.[1]; - if (!propertyType) { - const newType = TypeInference.inferUnclearRefName(fieldName, arkClass); + if (!propertyType || propertyType instanceof UnknownType) { + const newType = TypeInference.inferBaseType(fieldName, arkClass); if (newType) { propertyType = newType; } @@ -608,11 +634,12 @@ export class IRInference { let signature: BaseSignature; if (baseType instanceof ClassType) { const property = propertyAndType?.[0]; - if (property instanceof ArkField) { + if (property instanceof ArkField && property.getCategory() !== FieldCategory.ENUM_MEMBER) { return property.getSignature(); } - staticFlag = baseType.getClassSignature().getClassName() === DEFAULT_ARK_CLASS_NAME || - (property instanceof ArkMethod && property.isStatic()); + staticFlag = + baseType.getClassSignature().getClassName() === DEFAULT_ARK_CLASS_NAME || + ((property instanceof ArkField || property instanceof ArkMethod) && property.isStatic()); signature = property instanceof ArkMethod ? property.getSignature().getDeclaringClassSignature() : baseType.getClassSignature(); } else if (baseType instanceof AnnotationNamespaceType) { staticFlag = true; @@ -623,7 +650,6 @@ export class IRInference { return new FieldSignature(fieldName, signature, propertyType ?? ref.getType(), staticFlag); } - public static inferAnonymousClass(anon: ArkClass | null, declaredSignature: ClassSignature, set: Set = new Set()): void { if (!anon) { return; @@ -648,8 +674,9 @@ export class IRInference { if (type instanceof FunctionType) { this.assignAnonMethod(scene.getMethod(type.getMethodSignature()), property); } - anonField.setSignature(new FieldSignature(anonField.getName(), - property.getDeclaringArkClass().getSignature(), new FunctionType(property.getSignature()))); + anonField.setSignature( + new FieldSignature(anonField.getName(), property.getDeclaringArkClass().getSignature(), new FunctionType(property.getSignature())) + ); } } for (const anonMethod of anon.getMethods()) { @@ -657,7 +684,6 @@ export class IRInference { } } - private static assignAnonMethod(anonMethod: ArkMethod | null, declaredMethod: ArkMethod | null): void { if (declaredMethod && anonMethod) { anonMethod.setImplementationSignature(declaredMethod.matchMethodSignature(anonMethod.getSubSignature().getParameters())); @@ -677,8 +703,7 @@ export class IRInference { const rightType = lastStmt.getRightOp().getType(); if (type instanceof ClassType) { deepInfer(rightType, type.getClassSignature()); - } else if (type instanceof ArrayType && type.getBaseType() instanceof ClassType && - rightType instanceof ArrayType) { + } else if (type instanceof ArrayType && type.getBaseType() instanceof ClassType && rightType instanceof ArrayType) { const baseType = rightType.getBaseType(); const classSignature = (type.getBaseType() as ClassType).getClassSignature(); if (baseType instanceof UnionType) { @@ -753,7 +778,7 @@ export class IRInference { return; } if (opValue instanceof Local) { - const newOpValueType = TypeInference.inferUnclearRefName(opValue.getName(), arkMethod.getDeclaringArkClass()); + const newOpValueType = TypeInference.inferBaseType(opValue.getName(), arkMethod.getDeclaringArkClass()); const scene = arkMethod.getDeclaringArkFile().getScene(); if (newOpValueType instanceof ClassType) { const newOpValue = ModelUtils.findArkModelBySignature(newOpValueType.getClassSignature(), scene); @@ -796,7 +821,9 @@ export class IRInference { return ref; } } else if (paramType instanceof LexicalEnvType) { - paramType.getClosures().filter(c => TypeInference.isUnclearType(c.getType())) + paramType + .getClosures() + .filter(c => TypeInference.isUnclearType(c.getType())) .forEach(e => this.inferLocal(e, arkMethod)); return ref; } @@ -806,4 +833,4 @@ export class IRInference { } return ref; } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/common/IRUtils.ts b/ets2panda/linter/arkanalyzer/src/core/common/IRUtils.ts index 9af148f93b..c6b5ea378e 100644 --- a/ets2panda/linter/arkanalyzer/src/core/common/IRUtils.ts +++ b/ets2panda/linter/arkanalyzer/src/core/common/IRUtils.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -52,10 +52,7 @@ export class IRUtils { } } - public static setComments(metadata: Stmt | ArkBaseModel, - node: ts.Node, - sourceFile: ts.SourceFile, - options: SceneOptions): void { + public static setComments(metadata: Stmt | ArkBaseModel, node: ts.Node, sourceFile: ts.SourceFile, options: SceneOptions): void { const leadingCommentsMetadata = this.getCommentsMetadata(node, sourceFile, options, true); if (leadingCommentsMetadata.getComments().length > 0) { metadata.setMetadata(ArkMetadataKind.LEADING_COMMENTS, leadingCommentsMetadata); @@ -67,17 +64,17 @@ export class IRUtils { } } - public static getCommentsMetadata(node: ts.Node, sourceFile: ts.SourceFile, options: SceneOptions, - isLeading: boolean): CommentsMetadata { + public static getCommentsMetadata(node: ts.Node, sourceFile: ts.SourceFile, options: SceneOptions, isLeading: boolean): CommentsMetadata { const comments: CommentItem[] = []; if ((isLeading && !options.enableLeadingComments) || (!isLeading && !options.enableTrailingComments)) { return new CommentsMetadata(comments); } - const commentRanges = (isLeading ? ts.getLeadingCommentRanges(sourceFile.text, node.pos) - : ts.getTrailingCommentRanges(sourceFile.text, node.end)) || []; // node.pos is the start position of - // leading comment, while node.end is the - // end position of the statement + // node.pos is the start position of + const commentRanges = + (isLeading ? ts.getLeadingCommentRanges(sourceFile.text, node.pos) : ts.getTrailingCommentRanges(sourceFile.text, node.end)) || []; + // leading comment, while node.end is the + // end position of the statement const getPosition = (pos: number, end: number): FullPosition => { const start = ts.getLineAndCharacterOfPosition(sourceFile, pos); const endPos = ts.getLineAndCharacterOfPosition(sourceFile, end); @@ -125,23 +122,18 @@ export class IRUtils { if (oldValue instanceof AbstractRef && newValue instanceof AbstractRef) { if (newValue instanceof ArkStaticFieldRef) { - operandOriginalPositions.splice(oldValueIdx + baseValueOffset, - oldValueUseSize - newValueUseSize); + operandOriginalPositions.splice(oldValueIdx + baseValueOffset, oldValueUseSize - newValueUseSize); } else if (oldValue instanceof ArkStaticFieldRef) { - operandOriginalPositions.splice(oldValueIdx + baseValueOffset, 0, - ...IRUtils.generateDefaultPositions( - newValueUseSize - oldValueUseSize)); + operandOriginalPositions.splice(oldValueIdx + baseValueOffset, 0, ...IRUtils.generateDefaultPositions(newValueUseSize - oldValueUseSize)); } if (oldValue instanceof ArkInstanceFieldRef && newValue instanceof ArkArrayRef) { - if (operandOriginalPositionSize === defUseSize) { // may not reserve positions for field name - operandOriginalPositions.splice(oldValueIdx + fieldValueOffset, 0, - ...IRUtils.generateDefaultPositions( - newValueUseSize - oldValueUseSize)); + if (operandOriginalPositionSize === defUseSize) { + // may not reserve positions for field name + operandOriginalPositions.splice(oldValueIdx + fieldValueOffset, 0, ...IRUtils.generateDefaultPositions(newValueUseSize - oldValueUseSize)); } } else if (oldValue instanceof ArkArrayRef && newValue instanceof ArkInstanceFieldRef) { - operandOriginalPositions.splice(oldValueIdx + fieldValueOffset, - oldValueUseSize - newValueUseSize); + operandOriginalPositions.splice(oldValueIdx + fieldValueOffset, oldValueUseSize - newValueUseSize); } } else if (oldValue instanceof AbstractInvokeExpr && newValue instanceof AbstractInvokeExpr) { if (oldValueUseSize === newValueUseSize + 1) { diff --git a/ets2panda/linter/arkanalyzer/src/core/common/ModelUtils.ts b/ets2panda/linter/arkanalyzer/src/core/common/ModelUtils.ts index 9e3f335317..7b90129608 100644 --- a/ets2panda/linter/arkanalyzer/src/core/common/ModelUtils.ts +++ b/ets2panda/linter/arkanalyzer/src/core/common/ModelUtils.ts @@ -27,7 +27,7 @@ import { LocalSignature, MethodSignature, NamespaceSignature, - Signature + Signature, } from '../model/ArkSignature'; import { ArkExport, ExportInfo, ExportType, FromInfo } from '../model/ArkExport'; import { ArkField } from '../model/ArkField'; @@ -51,6 +51,7 @@ import { EMPTY_STRING } from './ValueUtil'; import { ArkBaseModel } from '../model/ArkBaseModel'; import { ArkAssignStmt } from '../base/Stmt'; import { ClosureFieldRef } from '../base/Ref'; +import { SdkUtils } from './SdkUtils'; export class ModelUtils { public static implicitArkUIBuilderMethods: Set = new Set(); @@ -95,8 +96,9 @@ export class ModelUtils { const names = className.split('.'); let nameSpace = this.getNamespaceWithNameFromClass(names[0], startFrom); for (let i = 1; i < names.length - 1; i++) { - if (nameSpace) + if (nameSpace) { nameSpace = nameSpace.getNamespaceWithName(names[i]); + } } if (nameSpace) { return nameSpace.getClassWithName(names[names.length - 1]); @@ -214,7 +216,6 @@ export class ModelUtils { } public static getStaticMethodWithName(methodName: string, thisClass: ArkClass): ArkMethod | null { - const thisNamespace = thisClass.getDeclaringArkNamespace(); if (thisNamespace) { const defaultClass = thisNamespace.getClassWithName(DEFAULT_ARK_CLASS_NAME); @@ -274,7 +275,7 @@ export class ModelUtils { public static getAllClassesInFile(arkFile: ArkFile): ArkClass[] { const allClasses = arkFile.getClasses(); - this.getAllNamespacesInFile(arkFile).forEach((namespace) => { + this.getAllNamespacesInFile(arkFile).forEach(namespace => { allClasses.push(...namespace.getClasses()); }); return allClasses; @@ -282,7 +283,7 @@ export class ModelUtils { public static getAllMethodsInFile(arkFile: ArkFile): ArkMethod[] { const allMethods: ArkMethod[] = []; - this.getAllClassesInFile(arkFile).forEach((cls) => { + this.getAllClassesInFile(arkFile).forEach(cls => { allMethods.push(...cls.getMethods()); }); return allMethods; @@ -291,12 +292,7 @@ export class ModelUtils { public static isArkUIBuilderMethod(arkMethod: ArkMethod): boolean { let isArkUIBuilderMethod = arkMethod.hasBuilderDecorator() || this.implicitArkUIBuilderMethods.has(arkMethod); - if ( - !isArkUIBuilderMethod && - arkMethod.getName() === 'build' && - arkMethod.getDeclaringArkClass().hasComponentDecorator() && - !arkMethod.isStatic() - ) { + if (!isArkUIBuilderMethod && arkMethod.getName() === 'build' && arkMethod.getDeclaringArkClass().hasComponentDecorator() && !arkMethod.isStatic()) { const fileName = arkMethod.getDeclaringArkClass().getDeclaringArkFile().getName(); if (fileName.endsWith('.ets')) { isArkUIBuilderMethod = true; @@ -347,18 +343,22 @@ export class ModelUtils { } public static findPropertyInNamespace(name: string, namespace: ArkNamespace): ArkExport | undefined { - return namespace.getDefaultClass()?.getMethodWithName(name) - ?? findArkExport(namespace.getExportInfoBy(name)) - ?? namespace.getClassWithName(name) - ?? namespace.getNamespaceWithName(name) - ?? namespace.getDefaultClass()?.getDefaultArkMethod()?.getBody()?.getAliasTypeByName(name) - ?? namespace.getDefaultClass()?.getDefaultArkMethod()?.getBody()?.getLocals()?.get(name); + return ( + namespace.getDefaultClass()?.getMethodWithName(name) ?? + findArkExport(namespace.getExportInfoBy(name)) ?? + namespace.getClassWithName(name) ?? + namespace.getNamespaceWithName(name) ?? + namespace.getDefaultClass()?.getDefaultArkMethod()?.getBody()?.getAliasTypeByName(name) ?? + namespace.getDefaultClass()?.getDefaultArkMethod()?.getBody()?.getLocals()?.get(name) + ); } public static findPropertyInClass(name: string, arkClass: ArkClass): ArkExport | ArkField | null { - let property: ArkExport | ArkField | null = arkClass.getMethodWithName(name) - ?? arkClass.getStaticMethodWithName(name) ?? arkClass.getFieldWithName(name) - ?? arkClass.getStaticFieldWithName(name); + let property: ArkExport | ArkField | null = + arkClass.getMethodWithName(name) ?? + arkClass.getStaticMethodWithName(name) ?? + arkClass.getFieldWithName(name) ?? + arkClass.getStaticFieldWithName(name); if (property) { return property; } @@ -388,8 +388,11 @@ export class ModelUtils { } if (times > 0) { const declaredLocal = arkMethod.getBody()?.getLocals().get(name); - if (declaredLocal && declaredLocal.getDeclaringStmt() instanceof ArkAssignStmt && - !((declaredLocal.getDeclaringStmt() as ArkAssignStmt).getRightOp() instanceof ClosureFieldRef)) { + if ( + declaredLocal && + declaredLocal.getDeclaringStmt() instanceof ArkAssignStmt && + !((declaredLocal.getDeclaringStmt() as ArkAssignStmt).getRightOp() instanceof ClosureFieldRef) + ) { return declaredLocal; } } @@ -403,7 +406,9 @@ export class ModelUtils { const outerStart = className.indexOf(NAME_DELIMITER); const outerEnd = className.lastIndexOf('.'); if (outerStart > -1 && outerEnd > -1) { - invokeMethod = arkMethod.getDeclaringArkFile().getClassWithName(className.substring(outerStart + 1, outerEnd)) + invokeMethod = arkMethod + .getDeclaringArkFile() + .getClassWithName(className.substring(outerStart + 1, outerEnd)) ?.getMethodWithName(className.substring(outerEnd + 1)); } else { const cls = arkMethod.getDeclaringArkClass(); @@ -417,13 +422,16 @@ export class ModelUtils { } public static findArkModel(baseName: string, arkClass: ArkClass): ArkExport | ArkField | null { - let arkModel: ArkExport | ArkField | null = arkClass.getMethodWithName(baseName) ?? - arkClass.getStaticMethodWithName(baseName) ?? arkClass.getFieldWithName(baseName) ?? + let arkModel: ArkExport | ArkField | null = + arkClass.getMethodWithName(baseName) ?? + arkClass.getStaticMethodWithName(baseName) ?? + arkClass.getFieldWithName(baseName) ?? arkClass.getStaticFieldWithName(baseName); if (arkModel) { return arkModel; } - arkModel = ModelUtils.getDefaultClass(arkClass)?.getDefaultArkMethod()?.getBody()?.getLocals()?.get(baseName) ?? + arkModel = + ModelUtils.getDefaultClass(arkClass)?.getDefaultArkMethod()?.getBody()?.getLocals()?.get(baseName) ?? ModelUtils.getClassWithName(baseName, arkClass) ?? ModelUtils.getNamespaceWithName(baseName, arkClass) ?? ModelUtils.getDefaultClass(arkClass)?.getMethodWithName(baseName) ?? @@ -435,6 +443,14 @@ export class ModelUtils { return arkModel; } + public static findGlobalRef(refName: string, method: ArkMethod): ArkExport | null { + return ( + this.findDeclaredLocal(new Local(refName), method, 1) ?? + this.getArkExportInImportInfoWithName(refName, method.getDeclaringArkFile()) ?? + method.getDeclaringArkFile().getScene().getSdkGlobal(refName) + ); + } + public static findArkModelByRefName(refName: string, arkClass: ArkClass): ArkExport | ArkField | null { const singleNames = refName.split('.'); let model = null; @@ -458,7 +474,6 @@ export class ModelUtils { if (!model) { return null; } - } return model; } @@ -505,10 +520,8 @@ export class ModelUtils { } } - const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'ModelUtils'); let moduleMap: Map | undefined; -export const sdkImportMap: Map = new Map(); /** * find arkFile by from info @@ -522,12 +535,13 @@ export function getArkFile(im: FromInfo): ArkFile | null | undefined { if (!from) { return null; } - if (/^([^@]*\/)([^\/]*)$/.test(from)) { //relative path - const parentPath = /^\.{1,2}\//.test(from) ? path.dirname(im.getDeclaringArkFile().getFilePath()) - : im.getDeclaringArkFile().getProjectDir(); + if (/^([^@]*\/)([^\/]*)$/.test(from)) { + //relative path + const parentPath = /^\.{1,2}\//.test(from) ? path.dirname(im.getDeclaringArkFile().getFilePath()) : im.getDeclaringArkFile().getProjectDir(); const originPath = path.resolve(parentPath, from); return getArkFileFromScene(im, originPath); - } else if (/^@[a-z|\-]+?\//.test(from)) { //module path + } else if (/^@[a-z|\-]+?\//.test(from)) { + //module path const arkFile = getArkFileFromOtherModule(im); if (arkFile) { return arkFile; @@ -535,7 +549,7 @@ export function getArkFile(im: FromInfo): ArkFile | null | undefined { } //sdk path - const file = sdkImportMap.get(from); + const file = SdkUtils.getImportSdkFile(from); if (file) { return file; } @@ -546,6 +560,7 @@ export function getArkFile(im: FromInfo): ArkFile | null | undefined { return arkFile; } } + return null; } /** @@ -570,8 +585,7 @@ export function findExportInfo(fromInfo: FromInfo): ExportInfo | null { } let exportInfo = findExportInfoInfile(fromInfo, file) || null; if (exportInfo === null) { - logger.warn('export info not found, ' + fromInfo.getFrom() + ' in file: ' - + fromInfo.getDeclaringArkFile().getFileSignature().toString()); + logger.warn('export info not found, ' + fromInfo.getFrom() + ' in file: ' + fromInfo.getDeclaringArkFile().getFileSignature().toString()); return null; } const arkExport = findArkExport(exportInfo); @@ -592,10 +606,11 @@ export function findArkExport(exportInfo: ExportInfo | undefined): ArkExport | n } if (!exportInfo.getFrom()) { const name = exportInfo.getOriginName(); + const defaultClass = exportInfo.getDeclaringArkNamespace()?.getDefaultClass() ?? exportInfo.getDeclaringArkFile().getDefaultClass(); if (exportInfo.getExportClauseType() === ExportType.LOCAL) { - arkExport = exportInfo.getDeclaringArkFile().getDefaultClass().getDefaultArkMethod()?.getBody()?.getLocals().get(name) || null; + arkExport = defaultClass.getDefaultArkMethod()?.getBody()?.getExportLocalByName(name); } else if (exportInfo.getExportClauseType() === ExportType.TYPE) { - arkExport = exportInfo.getDeclaringArkFile().getDefaultClass().getDefaultArkMethod()?.getBody()?.getAliasTypeByName(name) || null; + arkExport = defaultClass.getDefaultArkMethod()?.getBody()?.getAliasTypeByName(name); } else { arkExport = findArkExportInFile(name, exportInfo.getDeclaringArkFile()); } @@ -605,7 +620,9 @@ export function findArkExport(exportInfo: ExportInfo | undefined): ArkExport | n arkExport = result.getArkExport() || null; } } - if (!arkExport) { + if (arkExport) { + exportInfo.setArkExport(arkExport); + } else { logger.warn(`${exportInfo.getExportClauseName()} get arkExport fail from ${exportInfo.getFrom()} at ${exportInfo.getDeclaringArkFile().getFileSignature().toString()}`); } @@ -613,11 +630,12 @@ export function findArkExport(exportInfo: ExportInfo | undefined): ArkExport | n } export function findArkExportInFile(name: string, declaringArkFile: ArkFile): ArkExport | null { - let arkExport: ArkExport | undefined | null = declaringArkFile.getNamespaceWithName(name) - ?? declaringArkFile.getDefaultClass().getDefaultArkMethod()?.getBody()?.getAliasTypeByName(name) - ?? declaringArkFile.getClassWithName(name) - ?? declaringArkFile.getDefaultClass().getMethodWithName(name) - ?? declaringArkFile.getDefaultClass().getDefaultArkMethod()?.getBody()?.getLocals().get(name); + let arkExport: ArkExport | undefined | null = + declaringArkFile.getNamespaceWithName(name) ?? + declaringArkFile.getDefaultClass().getDefaultArkMethod()?.getBody()?.getAliasTypeByName(name) ?? + declaringArkFile.getClassWithName(name) ?? + declaringArkFile.getDefaultClass().getMethodWithName(name) ?? + declaringArkFile.getDefaultClass().getDefaultArkMethod()?.getBody()?.getExportLocalByName(name); if (!arkExport) { const importInfo = declaringArkFile.getImportInfoBy(name); @@ -639,7 +657,7 @@ function processSdkPath(sdk: Sdk, formPath: string): string { return `${formPath}`; } -function getArkFileFromScene(im: FromInfo, originPath: string) { +function getArkFileFromScene(im: FromInfo, originPath: string): ArkFile | null { if (FileUtils.isDirectory(originPath)) { originPath = path.join(originPath, FileUtils.getIndexFileName(originPath)); } @@ -670,8 +688,7 @@ function getArkFileFormMap(projectName: string, filePath: string, scene: Scene): return null; } - -function findExportInfoInfile(fromInfo: FromInfo, file: ArkFile) { +function findExportInfoInfile(fromInfo: FromInfo, file: ArkFile): ExportInfo | undefined { const exportName = fromInfo.isDefault() ? DEFAULT : fromInfo.getOriginName(); let exportInfo = file.getExportInfoBy(exportName); if (exportInfo) { @@ -690,8 +707,7 @@ function findExportInfoInfile(fromInfo: FromInfo, file: ArkFile) { exportInfo = buildDefaultExportInfo(fromInfo, file); file.addExportInfo(exportInfo, ALL); } else if (/\.d\.e?ts$/.test(file.getName())) { - let declare = exportName === DEFAULT ? undefined - : findArkExportInFile(fromInfo.getOriginName(), file) || undefined; + let declare = exportName === DEFAULT ? undefined : findArkExportInFile(fromInfo.getOriginName(), file) || undefined; exportInfo = buildDefaultExportInfo(fromInfo, file, declare); } @@ -705,10 +721,9 @@ export function initModulePathMap(ohPkgContentMap: Map): void { + private static sdkImportMap: Map = new Map(); + + public static buildSdkImportMap(file: ArkFile): void { const fileName = path.basename(file.getName()); if (fileName.startsWith('@')) { - sdkImportMap.set(fileName.replace(/\.d\.e?ts$/, ''), file); + this.sdkImportMap.set(fileName.replace(/\.d\.e?ts$/, ''), file); } + } + + public static getImportSdkFile(from: string): ArkFile | undefined { + return this.sdkImportMap.get(from); + } - const isGlobalPath = file.getScene().getOptions().sdkGlobalFolders - ?.find(x => file.getFilePath().includes(path.sep + x + path.sep)); + public static buildGlobalMap(file: ArkFile, globalMap: Map): void { + const isGlobalPath = file + .getScene() + .getOptions() + .sdkGlobalFolders?.find(x => file.getFilePath().includes(path.sep + x + path.sep)); if (!isGlobalPath) { return; } - IRInference.inferFile(file); ModelUtils.getAllClassesInFile(file).forEach(cls => { if (!cls.isAnonymousClass() && !cls.isDefaultArkClass()) { SdkUtils.loadClass(globalMap, cls); @@ -54,13 +63,22 @@ export class SdkUtils { } }); const defaultArkMethod = file.getDefaultClass().getDefaultArkMethod(); - defaultArkMethod?.getBody()?.getLocals().forEach(local => { - const name = local.getName(); - if (name !== THIS_NAME && !name.startsWith(TEMP_LOCAL_PREFIX)) { - this.loadGlobalLocal(local, defaultArkMethod, globalMap); - } - }); - defaultArkMethod?.getBody()?.getAliasTypeMap()?.forEach(a => globalMap.set(a[0].getName(), a[0])); + if (defaultArkMethod) { + TypeInference.inferTypeInMethod(defaultArkMethod); + } + defaultArkMethod + ?.getBody() + ?.getLocals() + .forEach(local => { + const name = local.getName(); + if (name !== THIS_NAME && !name.startsWith(TEMP_LOCAL_PREFIX)) { + this.loadGlobalLocal(local, defaultArkMethod, globalMap); + } + }); + defaultArkMethod + ?.getBody() + ?.getAliasTypeMap() + ?.forEach(a => globalMap.set(a[0].getName(), a[0])); ModelUtils.getAllNamespacesInFile(file).forEach(ns => globalMap.set(ns.getName(), ns)); } @@ -87,11 +105,13 @@ export class SdkUtils { const instance = globalMap.get(name + 'Interface'); const attr = globalMap.get(name + COMPONENT_ATTRIBUTE); if (attr instanceof ArkClass && instance instanceof ArkClass) { - instance.getMethods().filter(m => !attr.getMethodWithName(m.getName())).forEach(m => attr.addMethod(m)); + instance + .getMethods() + .filter(m => !attr.getMethodWithName(m.getName())) + .forEach(m => attr.addMethod(m)); globalMap.set(name, attr); return; } - } const old = globalMap.get(name); if (!old) { @@ -99,7 +119,10 @@ export class SdkUtils { } else if (old instanceof ArkClass && local.getType() instanceof ClassType) { const localConstructor = scene.getClass((local.getType() as ClassType).getClassSignature()); if (localConstructor) { - localConstructor.getMethods().filter(m => !old.getMethodWithName(m.getName())).forEach(m => old.addMethod(m)); + localConstructor + .getMethods() + .filter(m => !old.getMethodWithName(m.getName())) + .forEach(m => old.addMethod(m)); } } } @@ -119,9 +142,11 @@ export class SdkUtils { public static computeGlobalThis(leftOp: AbstractFieldRef, arkMethod: ArkMethod): void { const globalThis = arkMethod.getDeclaringArkFile().getScene().getSdkGlobal(GLOBAL_THIS_NAME); if (globalThis instanceof ArkNamespace) { - const exportInfo = new ExportInfo.Builder().exportClauseName(leftOp.getFieldName()) - .arkExport(new Local(leftOp.getFieldName(), leftOp.getType())).build(); + const exportInfo = new ExportInfo.Builder() + .exportClauseName(leftOp.getFieldName()) + .arkExport(new Local(leftOp.getFieldName(), leftOp.getType())) + .build(); globalThis.addExportInfo(exportInfo); } } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/common/StmtDefReplacer.ts b/ets2panda/linter/arkanalyzer/src/core/common/StmtDefReplacer.ts index e746072a67..134cebf5fa 100644 --- a/ets2panda/linter/arkanalyzer/src/core/common/StmtDefReplacer.ts +++ b/ets2panda/linter/arkanalyzer/src/core/common/StmtDefReplacer.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -42,5 +42,4 @@ export class StmtDefReplacer { stmt.setLeftOp(this.newDef); } } - -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/common/StmtUseReplacer.ts b/ets2panda/linter/arkanalyzer/src/core/common/StmtUseReplacer.ts index 051192098e..82e743935c 100644 --- a/ets2panda/linter/arkanalyzer/src/core/common/StmtUseReplacer.ts +++ b/ets2panda/linter/arkanalyzer/src/core/common/StmtUseReplacer.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -29,7 +29,7 @@ export class StmtUseReplacer { private newUse: Value; constructor(oldUse: Value, newUse: Value) { - this.oldUse = oldUse + this.oldUse = oldUse; this.newUse = newUse; } @@ -106,6 +106,4 @@ export class StmtUseReplacer { stmt.setOp(this.newUse); } } - - -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/common/TSConst.ts b/ets2panda/linter/arkanalyzer/src/core/common/TSConst.ts index 269c4107da..929711063d 100644 --- a/ets2panda/linter/arkanalyzer/src/core/common/TSConst.ts +++ b/ets2panda/linter/arkanalyzer/src/core/common/TSConst.ts @@ -16,7 +16,7 @@ export const CONSTRUCTOR_NAME = 'constructor'; export const SUPER_NAME = 'super'; export const THIS_NAME = 'this'; -export const GLOBAL_THIS_NAME: string = 'globalThis' +export const GLOBAL_THIS_NAME: string = 'globalThis'; export const DEFAULT = 'default'; @@ -39,4 +39,3 @@ export const VOID_KEYWORD = 'void'; export const NEVER_KEYWORD = 'never'; export const BIGINT_KEYWORD = 'bigint'; export const TSCONFIG_JSON = 'tsconfig.json'; - diff --git a/ets2panda/linter/arkanalyzer/src/core/common/TypeInference.ts b/ets2panda/linter/arkanalyzer/src/core/common/TypeInference.ts index 44a3d0136f..e754272cbf 100644 --- a/ets2panda/linter/arkanalyzer/src/core/common/TypeInference.ts +++ b/ets2panda/linter/arkanalyzer/src/core/common/TypeInference.ts @@ -16,14 +16,7 @@ import Logger, { LOG_MODULE_TYPE } from '../../utils/logger'; import { AbstractExpr, ArkInstanceInvokeExpr, ArkPtrInvokeExpr, ArkStaticInvokeExpr } from '../base/Expr'; import { Local } from '../base/Local'; -import { - AbstractFieldRef, - AbstractRef, - ArkArrayRef, - ArkInstanceFieldRef, - ArkParameterRef, - ArkStaticFieldRef, -} from '../base/Ref'; +import { AbstractFieldRef, AbstractRef, ArkArrayRef, ArkInstanceFieldRef, ArkParameterRef, ArkStaticFieldRef } from '../base/Ref'; import { ArkAliasTypeDefineStmt, ArkAssignStmt, ArkReturnStmt, Stmt } from '../base/Stmt'; import { AliasType, @@ -33,6 +26,7 @@ import { BigIntType, BooleanType, ClassType, + EnumValueType, FunctionType, GenericType, IntersectionType, @@ -50,7 +44,7 @@ import { } from '../base/Type'; import { ArkMethod } from '../model/ArkMethod'; import { ArkExport } from '../model/ArkExport'; -import { ArkClass } from '../model/ArkClass'; +import { ArkClass, ClassCategory } from '../model/ArkClass'; import { ArkField } from '../model/ArkField'; import { Value } from '../base/Value'; import { Constant } from '../base/Constant'; @@ -86,14 +80,11 @@ import { ModifierType } from '../model/ArkBaseModel'; const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'TypeInference'); - export class TypeInference { - public static inferTypeInArkField(arkField: ArkField): void { const arkClass = arkField.getDeclaringArkClass(); const stmts = arkField.getInitializer(); - const method = arkClass.getMethodWithName(INSTANCE_INIT_METHOD_NAME) ?? - arkClass.getMethodWithName(CONSTRUCTOR_NAME); + const method = arkClass.getMethodWithName(INSTANCE_INIT_METHOD_NAME) ?? arkClass.getMethodWithName(CONSTRUCTOR_NAME); for (const stmt of stmts) { if (method) { this.resolveStmt(stmt, method); @@ -142,8 +133,7 @@ export class TypeInference { visited.add(leftOpType); } let type; - if (leftOpType instanceof ClassType && - leftOpType.getClassSignature().getDeclaringFileSignature().getFileName() === UNKNOWN_FILE_NAME) { + if (leftOpType instanceof ClassType && leftOpType.getClassSignature().getDeclaringFileSignature().getFileName() === UNKNOWN_FILE_NAME) { type = TypeInference.inferUnclearRefName(leftOpType.getClassSignature().getClassName(), declaringArkClass); } else if (leftOpType instanceof UnionType || leftOpType instanceof IntersectionType || leftOpType instanceof TupleType) { let types = leftOpType.getTypes(); @@ -184,9 +174,11 @@ export class TypeInference { signatures.push(impl); } signatures.forEach(s => { - s.getMethodSubSignature().getParameters().forEach(p => { - this.inferParameterType(p, arkMethod); - }); + s.getMethodSubSignature() + .getParameters() + .forEach(p => { + this.inferParameterType(p, arkMethod); + }); }); const body = arkMethod.getBody(); if (!body) { @@ -239,8 +231,10 @@ export class TypeInference { private static resolveExprsInStmt(stmt: Stmt, arkMethod: ArkMethod): void { for (const expr of stmt.getExprs()) { const newExpr = expr.inferType(arkMethod); - if (stmt.containsInvokeExpr() && ((expr instanceof ArkInstanceInvokeExpr && newExpr instanceof ArkStaticInvokeExpr) || - newExpr instanceof ArkPtrInvokeExpr)) { + if ( + stmt.containsInvokeExpr() && + ((expr instanceof ArkInstanceInvokeExpr && newExpr instanceof ArkStaticInvokeExpr) || newExpr instanceof ArkPtrInvokeExpr) + ) { stmt.replaceUse(expr, newExpr); } } @@ -269,8 +263,13 @@ export class TypeInference { } const stmtDef = stmt.getDef(); if (stmtDef && stmtDef instanceof AbstractRef) { - if (arkMethod.getName() === INSTANCE_INIT_METHOD_NAME && stmtDef instanceof ArkInstanceFieldRef && - stmtDef.getBase().getName() === THIS_NAME && arkMethod.getDeclaringArkClass().isAnonymousClass()) { + if ( + arkMethod.getName() === INSTANCE_INIT_METHOD_NAME && + stmtDef instanceof ArkInstanceFieldRef && + stmtDef.getBase().getName() === THIS_NAME && + arkMethod.getDeclaringArkClass().isAnonymousClass() && + stmtDef.getFieldName().indexOf('.') === -1 + ) { return; } const fieldRef = stmtDef.inferType(arkMethod); @@ -388,12 +387,15 @@ export class TypeInference { public static isUnclearType(type: Type | null | undefined): boolean { // TODO: For UnionType, IntersectionType and TupleType, it should recurse check every item of them. - if (!type || type instanceof UnknownType || type instanceof UnclearReferenceType - || type instanceof NullType || type instanceof UndefinedType) { + if (!type || type instanceof UnknownType || type instanceof UnclearReferenceType || type instanceof NullType || type instanceof UndefinedType) { return true; - } else if (type instanceof ClassType && (type.getClassSignature().getDeclaringFileSignature().getFileName() === UNKNOWN_FILE_NAME || - (type.getClassSignature().getDeclaringFileSignature().getFileName() === Builtin.DUMMY_FILE_NAME && - type.getRealGenericTypes()?.find(t => t instanceof GenericType)))) { + } else if ( + type instanceof ClassType && + (type.getClassSignature().getDeclaringFileSignature().getFileName() === UNKNOWN_FILE_NAME || + (type.getClassSignature().getClassName() === PROMISE && !type.getRealGenericTypes()) || + (type.getClassSignature().getDeclaringFileSignature().getFileName() === Builtin.DUMMY_FILE_NAME && + type.getRealGenericTypes()?.find(t => t instanceof GenericType))) + ) { return true; } else if (type instanceof UnionType || type instanceof IntersectionType || type instanceof TupleType) { return !!type.getTypes().find(t => this.hasUnclearReferenceType(t)); @@ -539,7 +541,9 @@ export class TypeInference { for (let returnValue of arkMethod.getReturnValues()) { const type = returnValue.getType(); if (type instanceof UnionType) { - type.flatType().filter(t => !TypeInference.isUnclearType(t)).forEach(t => typeMap.set(t.toString(), t)); + type.flatType() + .filter(t => !TypeInference.isUnclearType(t)) + .forEach(t => typeMap.set(t.toString(), t)); } else if (!TypeInference.isUnclearType(type)) { typeMap.set(type.toString(), type); } @@ -558,7 +562,7 @@ export class TypeInference { return null; } - public static inferGenericType(types: GenericType[] | undefined, arkClass: ArkClass) { + public static inferGenericType(types: GenericType[] | undefined, arkClass: ArkClass): void { types?.forEach(type => { const defaultType = type.getDefaultType(); if (defaultType instanceof UnclearReferenceType) { @@ -617,7 +621,7 @@ export class TypeInference { return EMPTY_STRING; }); if (i === 0) { - type = this.inferBaseType(name, arkClass); + type = singleNames.length > 1 ? this.inferBaseType(name, arkClass) : this.inferTypeByName(name, arkClass); } else if (type) { type = this.inferFieldType(type, name, arkClass)?.[1]; } @@ -626,7 +630,7 @@ export class TypeInference { } if (genericName) { const realTypes = genericName.split(',').map(generic => { - const realType = this.inferBaseType(generic, arkClass); + const realType = this.inferUnclearRefName(generic, arkClass); return realType ?? new UnclearReferenceType(generic); }); if (type instanceof ClassType) { @@ -657,8 +661,10 @@ export class TypeInference { } let propertyAndType: [any, Type] | null = null; if (baseType instanceof ClassType) { - if (fieldName === Builtin.ITERATOR_RESULT_VALUE && baseType.getClassSignature() - .getDeclaringFileSignature().getProjectName() === Builtin.DUMMY_PROJECT_NAME) { + if ( + fieldName === Builtin.ITERATOR_RESULT_VALUE && + baseType.getClassSignature().getDeclaringFileSignature().getProjectName() === Builtin.DUMMY_PROJECT_NAME + ) { const types = baseType.getRealGenericTypes(); if (types && types.length > 0) { return [null, types[0]]; @@ -689,7 +695,16 @@ export class TypeInference { const property = ModelUtils.findPropertyInClass(fieldName, arkClass); let propertyType: Type | null = null; if (property instanceof ArkField) { - propertyType = property.getType(); + if (arkClass.getCategory() === ClassCategory.ENUM) { + let constant; + const lastStmt = property.getInitializer().at(-1); + if (lastStmt instanceof ArkAssignStmt && lastStmt.getRightOp() instanceof Constant) { + constant = lastStmt.getRightOp() as Constant; + } + propertyType = new EnumValueType(property.getSignature(), constant); + } else { + propertyType = property.getType(); + } } else if (property) { propertyType = this.parseArkExport2Type(property); } @@ -714,22 +729,39 @@ export class TypeInference { if (SUPER_NAME === baseName) { return this.parseArkExport2Type(arkClass.getSuperClass()); } - const field = ModelUtils.getDefaultClass(arkClass)?.getDefaultArkMethod() - ?.getBody()?.getLocals()?.get(baseName); + const field = ModelUtils.getDefaultClass(arkClass)?.getDefaultArkMethod()?.getBody()?.getLocals()?.get(baseName); if (field && !this.isUnclearType(field.getType())) { return field.getType(); } - let arkExport: ArkExport | null = ModelUtils.getClassWithName(baseName, arkClass) - ?? ModelUtils.getDefaultClass(arkClass)?.getDefaultArkMethod()?.getBody()?.getAliasTypeByName(baseName) - ?? ModelUtils.getNamespaceWithName(baseName, arkClass) - ?? ModelUtils.getDefaultClass(arkClass)?.getMethodWithName(baseName) - ?? ModelUtils.getArkExportInImportInfoWithName(baseName, arkClass.getDeclaringArkFile()); + let arkExport: ArkExport | null = + ModelUtils.getClassWithName(baseName, arkClass) ?? + ModelUtils.getDefaultClass(arkClass)?.getDefaultArkMethod()?.getBody()?.getAliasTypeByName(baseName) ?? + ModelUtils.getNamespaceWithName(baseName, arkClass) ?? + ModelUtils.getDefaultClass(arkClass)?.getMethodWithName(baseName) ?? + ModelUtils.getArkExportInImportInfoWithName(baseName, arkClass.getDeclaringArkFile()); if (!arkExport && !arkClass.getDeclaringArkFile().getImportInfoBy(baseName)) { arkExport = arkClass.getDeclaringArkFile().getScene().getSdkGlobal(baseName); } return this.parseArkExport2Type(arkExport); } + public static inferTypeByName(typeName: string, arkClass: ArkClass): Type | null { + let arkExport: ArkExport | null = + ModelUtils.getClassWithName(typeName, arkClass) ?? + ModelUtils.getDefaultClass(arkClass)?.getDefaultArkMethod()?.getBody()?.getAliasTypeByName(typeName) ?? + ModelUtils.getArkExportInImportInfoWithName(typeName, arkClass.getDeclaringArkFile()); + if (arkExport instanceof ArkClass || arkExport instanceof AliasType) { + return this.parseArkExport2Type(arkExport); + } + if (!arkClass.getDeclaringArkFile().getImportInfoBy(typeName)) { + arkExport = arkClass.getDeclaringArkFile().getScene().getSdkGlobal(typeName); + } + if (arkExport instanceof ArkClass || arkExport instanceof AliasType) { + return this.parseArkExport2Type(arkExport); + } + return null; + } + public static inferRealGenericTypes(realTypes: Type[] | undefined, arkClass: ArkClass): void { if (!realTypes) { return; @@ -745,7 +777,6 @@ export class TypeInference { } } - public static inferDynamicImportType(from: string, arkClass: ArkClass): Type | null { const importInfo = new ImportInfo(); importInfo.setNameBeforeAs(ALL); @@ -755,7 +786,6 @@ export class TypeInference { return TypeInference.parseArkExport2Type(importInfo.getLazyExportInfo()?.getArkExport()); } - public static replaceTypeWithReal(type: Type, realTypes?: Type[], visited: Set = new Set()): Type { if (visited.has(type)) { return type; @@ -814,7 +844,6 @@ export class TypeInference { return aliasType; } - public static inferFunctionType(argType: FunctionType, paramSubSignature: MethodSubSignature | undefined, realTypes: Type[] | undefined): void { const returnType = argType.getMethodSignature().getMethodSubSignature().getReturnType(); const declareType = paramSubSignature?.getReturnType(); @@ -825,7 +854,10 @@ export class TypeInference { if (!params) { return; } - argType.getMethodSignature().getMethodSubSignature().getParameters() + argType + .getMethodSignature() + .getMethodSubSignature() + .getParameters() .filter(p => !p.getName().startsWith(LEXICAL_ENV_NAME_PREFIX)) .forEach((p, i) => { let type = params?.[i]?.getType(); @@ -850,5 +882,4 @@ export class TypeInference { IRInference.inferRightWithSdkType(returnType, stmt.getOp().getType(), arkMethod.getDeclaringArkClass()); } } - } diff --git a/ets2panda/linter/arkanalyzer/src/core/common/ValueUtil.ts b/ets2panda/linter/arkanalyzer/src/core/common/ValueUtil.ts index 9247f8f4db..1731b701b0 100644 --- a/ets2panda/linter/arkanalyzer/src/core/common/ValueUtil.ts +++ b/ets2panda/linter/arkanalyzer/src/core/common/ValueUtil.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,15 +13,7 @@ * limitations under the License. */ -import { - BigIntConstant, - BooleanConstant, - Constant, - NullConstant, - NumberConstant, - StringConstant, - UndefinedConstant, -} from '../base/Constant'; +import { BigIntConstant, BooleanConstant, Constant, NullConstant, NumberConstant, StringConstant, UndefinedConstant } from '../base/Constant'; export const EMPTY_STRING = ''; @@ -68,4 +60,4 @@ export class ValueUtil { public static getBooleanConstant(value: boolean): Constant { return BooleanConstant.getInstance(value); } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/common/VisibleValue.ts b/ets2panda/linter/arkanalyzer/src/core/common/VisibleValue.ts index 6580426810..762f02592e 100644 --- a/ets2panda/linter/arkanalyzer/src/core/common/VisibleValue.ts +++ b/ets2panda/linter/arkanalyzer/src/core/common/VisibleValue.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -58,7 +58,6 @@ export class VisibleValue { } logger.info('---- into scope:{', name, '}'); - // get values in this scope let values: Value[] = []; if (model instanceof ArkFile || model instanceof ArkNamespace) { @@ -99,7 +98,6 @@ export class VisibleValue { this.deleteScope(targetDepth); } - /** clear up previous scope */ private deleteScope(targetDepth: number): void { const prevDepth = this.currScope.depth; @@ -118,7 +116,7 @@ export class VisibleValue { } this.scopeChain.splice(this.scopeChain.length - popScopeCnt, popScopeCnt)[0]; // popScopeCnt >= 1 - this.currScope = this.scopeChain[this.scopeChain.length - 1] + this.currScope = this.scopeChain[this.scopeChain.length - 1]; const totalValuesCnt = this.currVisibleValues.length; this.currVisibleValues.splice(totalValuesCnt - popScopeValuesCnt, popScopeValuesCnt); } @@ -143,13 +141,13 @@ export class VisibleValue { } else { targetDepth = prevDepth; } - } else if ((model instanceof ArkFile) && (prevModel instanceof ArkFile)) { + } else if (model instanceof ArkFile && prevModel instanceof ArkFile) { targetDepth = prevDepth; - } else if ((model instanceof ArkNamespace) && (prevModel instanceof ArkNamespace)) { + } else if (model instanceof ArkNamespace && prevModel instanceof ArkNamespace) { targetDepth = prevDepth; - } else if ((model instanceof ArkClass) && (prevModel instanceof ArkClass)) { + } else if (model instanceof ArkClass && prevModel instanceof ArkClass) { targetDepth = prevDepth; - } else if ((model instanceof ArkMethod) && (prevModel instanceof ArkMethod)) { + } else if (model instanceof ArkMethod && prevModel instanceof ArkMethod) { targetDepth = prevDepth; } return targetDepth; @@ -160,7 +158,6 @@ export class VisibleValue { return values; } - private getVisibleValuesIntoClass(cls: ArkClass): Value[] { const values: Value[] = []; const fields = cls.getFields(); @@ -193,7 +190,6 @@ export class VisibleValue { } } - type ArkModel = ArkFile | ArkNamespace | ArkClass | ArkMethod | BasicBlock; export class Scope { @@ -205,4 +201,4 @@ export class Scope { this.depth = depth; this.arkModel = arkModel; } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/dataflow/DataflowProblem.ts b/ets2panda/linter/arkanalyzer/src/core/dataflow/DataflowProblem.ts index b18d1efe48..f877a1be0e 100644 --- a/ets2panda/linter/arkanalyzer/src/core/dataflow/DataflowProblem.ts +++ b/ets2panda/linter/arkanalyzer/src/core/dataflow/DataflowProblem.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -17,10 +17,9 @@ import { Stmt } from '../base/Stmt'; import { ArkMethod } from '../model/ArkMethod'; export abstract class DataflowProblem { - /** * Transfer the outFact of srcStmt to the inFact of tgtStmt - * + * * Return true if keeping progagation (i.e., tgtStmt will be added to the WorkList for further analysis) */ /* @@ -33,23 +32,23 @@ export abstract class DataflowProblem { abstract transferReturnEdge(srcStmt: Stmt, tgtStmt: Stmt, result: DataflowResult): boolean; */ - abstract getNormalFlowFunction(srcStmt:Stmt, tgtStmt:Stmt) : FlowFunction; + abstract getNormalFlowFunction(srcStmt: Stmt, tgtStmt: Stmt): FlowFunction; - abstract getCallFlowFunction(srcStmt:Stmt, method:ArkMethod) : FlowFunction; + abstract getCallFlowFunction(srcStmt: Stmt, method: ArkMethod): FlowFunction; - abstract getExitToReturnFlowFunction(srcStmt:Stmt, tgtStmt:Stmt, callStmt:Stmt) : FlowFunction; + abstract getExitToReturnFlowFunction(srcStmt: Stmt, tgtStmt: Stmt, callStmt: Stmt): FlowFunction; - abstract getCallToReturnFlowFunction(srcStmt:Stmt, tgtStmt:Stmt) : FlowFunction; + abstract getCallToReturnFlowFunction(srcStmt: Stmt, tgtStmt: Stmt): FlowFunction; - abstract createZeroValue() : D; + abstract createZeroValue(): D; - abstract getEntryPoint() : Stmt; + abstract getEntryPoint(): Stmt; - abstract getEntryMethod() : ArkMethod; + abstract getEntryMethod(): ArkMethod; abstract factEqual(d1: D, d2: D): boolean; } -export interface FlowFunction { - getDataFacts(d:D) : Set; -} \ No newline at end of file +export interface FlowFunction { + getDataFacts(d: D): Set; +} diff --git a/ets2panda/linter/arkanalyzer/src/core/dataflow/DataflowResult.ts b/ets2panda/linter/arkanalyzer/src/core/dataflow/DataflowResult.ts index 6a26568ddf..d01d56d46a 100644 --- a/ets2panda/linter/arkanalyzer/src/core/dataflow/DataflowResult.ts +++ b/ets2panda/linter/arkanalyzer/src/core/dataflow/DataflowResult.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -22,4 +22,4 @@ export class DataflowResult { //should we specifically keep global facts or just embedding them into the two maps above globalFacts: Set = new Set(); -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/dataflow/DataflowSolver.ts b/ets2panda/linter/arkanalyzer/src/core/dataflow/DataflowSolver.ts index ef55d3354c..523dd9a41b 100644 --- a/ets2panda/linter/arkanalyzer/src/core/dataflow/DataflowSolver.ts +++ b/ets2panda/linter/arkanalyzer/src/core/dataflow/DataflowSolver.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -37,7 +37,6 @@ it have several improvments: type CallToReturnCacheEdge = PathEdge; export abstract class DataflowSolver { - protected problem: DataflowProblem; protected workList: Array>; protected pathEdgeSet: Set>; @@ -63,7 +62,7 @@ export abstract class DataflowSolver { this.stmtNexts = new Map(); } - public solve() { + public solve(): void { this.init(); this.doSolve(); } @@ -81,21 +80,21 @@ export abstract class DataflowSolver { return Array.from(this.stmtNexts.get(stmt) || []); } - protected init() { + protected init(): void { let edgePoint: PathEdgePoint = new PathEdgePoint(this.problem.getEntryPoint(), this.zeroFact); let edge: PathEdge = new PathEdge(edgePoint, edgePoint); this.workList.push(edge); this.pathEdgeSet.add(edge); // build CHA - let cg = new CallGraph(this.scene) - this.CHA = new ClassHierarchyAnalysis(this.scene, cg) + let cg = new CallGraph(this.scene); + this.CHA = new ClassHierarchyAnalysis(this.scene, cg); this.buildStmtMapInClass(); this.setCfg4AllStmt(); return; } - protected buildStmtMapInClass() { + protected buildStmtMapInClass(): void { const methods = this.scene.getMethods(); methods.push(this.problem.getEntryMethod()); for (const method of methods) { @@ -126,7 +125,7 @@ export abstract class DataflowSolver { } } - protected setCfg4AllStmt() { + protected setCfg4AllStmt(): void { for (const cls of this.scene.getClasses()) { for (const mtd of cls.getMethods(true)) { addCfg2Stmt(mtd); @@ -136,7 +135,9 @@ export abstract class DataflowSolver { protected getAllCalleeMethods(callNode: ArkInvokeStmt): Set { const callSites = this.CHA.resolveCall( - this.CHA.getCallGraph().getCallGraphNodeByMethod(this.problem.getEntryMethod().getSignature()).getID(), callNode); + this.CHA.getCallGraph().getCallGraphNodeByMethod(this.problem.getEntryMethod().getSignature()).getID(), + callNode + ); const methods: Set = new Set(); for (const callSite of callSites) { const method = this.scene.getMethod(this.CHA.getCallGraph().getMethodByFuncID(callSite.calleeFuncID)!); @@ -157,18 +158,22 @@ export abstract class DataflowSolver { return [...cfg.getBlocks()][0].getStmts()[paraNum]; } - protected pathEdgeSetHasEdge(edge: PathEdge) { + protected pathEdgeSetHasEdge(edge: PathEdge): boolean { for (const path of this.pathEdgeSet) { this.problem.factEqual(path.edgeEnd.fact, edge.edgeEnd.fact); - if (path.edgeEnd.node === edge.edgeEnd.node && this.problem.factEqual(path.edgeEnd.fact, edge.edgeEnd.fact) && - path.edgeStart.node === edge.edgeStart.node && this.problem.factEqual(path.edgeStart.fact, edge.edgeStart.fact)) { + if ( + path.edgeEnd.node === edge.edgeEnd.node && + this.problem.factEqual(path.edgeEnd.fact, edge.edgeEnd.fact) && + path.edgeStart.node === edge.edgeStart.node && + this.problem.factEqual(path.edgeStart.fact, edge.edgeStart.fact) + ) { return true; } } return false; } - protected propagate(edge: PathEdge) { + protected propagate(edge: PathEdge): void { if (!this.pathEdgeSetHasEdge(edge)) { let index = this.workList.length; for (let i = 0; i < this.workList.length; i++) { @@ -182,7 +187,7 @@ export abstract class DataflowSolver { } } - protected processExitNode(edge: PathEdge) { + protected processExitNode(edge: PathEdge): void { let startEdgePoint: PathEdgePoint = edge.edgeStart; let exitEdgePoint: PathEdgePoint = edge.edgeEnd; const summary = this.endSummary.get(startEdgePoint); @@ -205,8 +210,7 @@ export abstract class DataflowSolver { } } - private handleFacts(returnFlowFunc: FlowFunction, returnSite: Stmt, - exitEdgePoint: PathEdgePoint, callEdgePoint: PathEdgePoint): void { + private handleFacts(returnFlowFunc: FlowFunction, returnSite: Stmt, exitEdgePoint: PathEdgePoint, callEdgePoint: PathEdgePoint): void { for (let fact of returnFlowFunc.getDataFacts(exitEdgePoint.fact)) { let returnSitePoint: PathEdgePoint = new PathEdgePoint(returnSite, fact); let cacheEdge: CallToReturnCacheEdge = new PathEdge(callEdgePoint, returnSitePoint); @@ -230,7 +234,7 @@ export abstract class DataflowSolver { } } - protected processNormalNode(edge: PathEdge) { + protected processNormalNode(edge: PathEdge): void { let start: PathEdgePoint = edge.edgeStart; let end: PathEdgePoint = edge.edgeEnd; let stmts: Stmt[] = [...this.getChildren(end.node)].reverse(); @@ -239,14 +243,14 @@ export abstract class DataflowSolver { let set: Set = flowFunction.getDataFacts(end.fact); for (let fact of set) { let edgePoint: PathEdgePoint = new PathEdgePoint(stmt, fact); - const edge = new PathEdge(start, edgePoint) + const edge = new PathEdge(start, edgePoint); this.propagate(edge); this.laterEdges.add(edge); } } } - protected processCallNode(edge: PathEdge) { + protected processCallNode(edge: PathEdge): void { let start: PathEdgePoint = edge.edgeStart; let callEdgePoint: PathEdgePoint = edge.edgeEnd; const invokeStmt = callEdgePoint.node as ArkInvokeStmt; @@ -312,7 +316,7 @@ export abstract class DataflowSolver { } } - protected doSolve() { + protected doSolve(): void { while (this.workList.length !== 0) { let pathEdge: PathEdge = this.workList.shift()!; if (this.laterEdges.has(pathEdge)) { diff --git a/ets2panda/linter/arkanalyzer/src/core/dataflow/Edge.ts b/ets2panda/linter/arkanalyzer/src/core/dataflow/Edge.ts index c758713bcb..8f37f08ab0 100644 --- a/ets2panda/linter/arkanalyzer/src/core/dataflow/Edge.ts +++ b/ets2panda/linter/arkanalyzer/src/core/dataflow/Edge.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,21 +16,21 @@ import { Stmt } from '../base/Stmt'; export class PathEdgePoint { - public node:Stmt; - public fact:D; + public node: Stmt; + public fact: D; - constructor(node:Stmt, fact:D){ + constructor(node: Stmt, fact: D) { this.node = node; this.fact = fact; } } export class PathEdge { - public edgeStart:PathEdgePoint; - public edgeEnd:PathEdgePoint; + public edgeStart: PathEdgePoint; + public edgeEnd: PathEdgePoint; - constructor(start:PathEdgePoint, end:PathEdgePoint) { - this.edgeStart=start; - this.edgeEnd=end; + constructor(start: PathEdgePoint, end: PathEdgePoint) { + this.edgeStart = start; + this.edgeEnd = end; } } diff --git a/ets2panda/linter/arkanalyzer/src/core/dataflow/Fact.ts b/ets2panda/linter/arkanalyzer/src/core/dataflow/Fact.ts index 0e8eea6ca0..accc0b13e0 100644 --- a/ets2panda/linter/arkanalyzer/src/core/dataflow/Fact.ts +++ b/ets2panda/linter/arkanalyzer/src/core/dataflow/Fact.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -18,5 +18,5 @@ import { Stmt } from '../base/Stmt'; export class Fact { values: Set = new Set(); - valueMap: Map = new Map(); // 用最近的def代表value的值 -} \ No newline at end of file + valueMap: Map = new Map(); // 用最近的def代表value的值 +} diff --git a/ets2panda/linter/arkanalyzer/src/core/dataflow/GenericDataFlow.ts b/ets2panda/linter/arkanalyzer/src/core/dataflow/GenericDataFlow.ts index 1c92187866..a6b4e50d73 100644 --- a/ets2panda/linter/arkanalyzer/src/core/dataflow/GenericDataFlow.ts +++ b/ets2panda/linter/arkanalyzer/src/core/dataflow/GenericDataFlow.ts @@ -15,12 +15,12 @@ /** * Generic Data Flow Analysis Framework - * + * * This module provides a generic framework for implementing data flow analyses, * such as Reaching Definitions, Live Variables, and Available Expressions. * The framework is designed to be flexible and extensible, allowing users to * define custom flow graphs, transfer functions, and meet operations. - * + * * Design Notes: * - The framework is designed to be generic and reusable, allowing users to * implement custom data flow analyses by defining appropriate transfer functions @@ -28,7 +28,7 @@ * - The solver uses a worklist algorithm to efficiently compute the MFP solution. * - The analysis can be configured as either forward or backward, depending on * the problem requirements. - * + * */ /** @@ -168,11 +168,11 @@ export class MFPDataFlowSolver { while (workList.length > 0) { newEntries.clear(); - workList.forEach((n) => { + workList.forEach(n => { let inSet: V | undefined; const predecessors = problem.flowGraph.pred(n); if (predecessors && predecessors.length > 0) { - const predecessorOuts = predecessors.map((pred) => _out.get(pred)); + const predecessorOuts = predecessors.map(pred => _out.get(pred)); inSet = predecessorOuts.reduce((acc, cur) => problem.meet(acc!, cur!), problem.empty); } else { inSet = problem.empty; @@ -184,7 +184,7 @@ export class MFPDataFlowSolver { if (!old || old.count() === 0 || !old.equals(newSet)) { _out.set(n, newSet); - problem.flowGraph.succ(n).forEach((succ) => newEntries.add(succ)); + problem.flowGraph.succ(n).forEach(succ => newEntries.add(succ)); } }); @@ -210,7 +210,7 @@ export class MFPDataFlowSolver { while (workList.length > 0) { newEntries.clear(); - workList.forEach((n) => { + workList.forEach(n => { let outSet: T = problem.flowGraph.succ(n).reduce((acc, curr) => { return problem.meet(acc, _in.get(curr)!); }, problem.empty); @@ -220,7 +220,7 @@ export class MFPDataFlowSolver { let newSet: T = problem.transferFunction.apply(n, outSet); if (!old || !old.equals(newSet)) { _in.set(n, newSet); - problem.flowGraph.pred(n).forEach((pred) => newEntries.add(pred)); + problem.flowGraph.pred(n).forEach(pred => newEntries.add(pred)); } }); @@ -229,4 +229,4 @@ export class MFPDataFlowSolver { return new Solution(_in, _out, problem); } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/dataflow/ReachingDef.ts b/ets2panda/linter/arkanalyzer/src/core/dataflow/ReachingDef.ts index da681fd845..b9b491e697 100644 --- a/ets2panda/linter/arkanalyzer/src/core/dataflow/ReachingDef.ts +++ b/ets2panda/linter/arkanalyzer/src/core/dataflow/ReachingDef.ts @@ -15,25 +15,25 @@ /** * Reaching Definitions Data Flow Analysis - * + * * This module implements the Reaching Definitions data flow analysis algorithm. * Reaching Definitions is a forward data flow analysis that determines, for each * program point, the set of variable definitions (assignments) that may reach * that point without being overwritten. - * + * * Key Components: * 1. **Transfer Function**: * - Computes the out set for each node based on its in set. * - Uses gen and kill sets to model the effects of assignments: * - **gen**: The set of definitions generated by the current node. * - **kill**: The set of definitions killed (overwritten) by the current node. - * + * * 2. **Meet Operation**: * - Combines data flow values from multiple paths (e.g., union for reaching definitions). * - Ensures that the analysis is conservative (safe) by over-approximating the result. - * + * * The analysis is forward, meaning it propagates information from predecessors to successors. - * + * */ import { ArkAssignStmt, Stmt } from '../base/Stmt'; @@ -66,8 +66,8 @@ export class ReachingDefProblem implements DataFlowProblem [i, new coCtor(BV_SIZE)])); - this.initOut = new Map(this.flowGraph.nodesInPostOrder.map((i) => [i, new coCtor(BV_SIZE)])); + this.initIn = new Map(this.flowGraph.nodesInPostOrder.map(i => [i, new coCtor(BV_SIZE)])); + this.initOut = new Map(this.flowGraph.nodesInPostOrder.map(i => [i, new coCtor(BV_SIZE)])); this.forward = forward; } } @@ -107,7 +107,7 @@ class ReachingDefFlowGraph extends BaseImplicitGraph implements FlowGrap this.succMap = new Map(); this.predMap = new Map(); - cfg.getBlocks().forEach((bb) => { + cfg.getBlocks().forEach(bb => { let stmts = bb.getStmts(); if (stmts.length === 0) { return; @@ -128,7 +128,13 @@ class ReachingDefFlowGraph extends BaseImplicitGraph implements FlowGrap throw new Error('cfg has no terminal'); } - bb.getSuccessors().forEach((succBB) => { + let successors = bb.getSuccessors(); + // try...catch语句,catch所在的block在CFG表示里是没有前驱block的,需要在这里额外查找并将exceptionalSuccessorBlocks作为try块的后继块之一 + const exceptionalSuccessorBlocks = bb.getExceptionalSuccessorBlocks(); + if (exceptionalSuccessorBlocks !== undefined) { + successors.push(...exceptionalSuccessorBlocks); + } + successors.forEach(succBB => { let head = succBB.getHead(); if (!head) { return; @@ -202,4 +208,4 @@ export class ReachingDefTransferFunction implements TransferFunction { classMap: Map; globalVariableMap: Map; outcomes: Outcome[] = []; - constructor(stmt: Stmt, method: ArkMethod){ + constructor(stmt: Stmt, method: ArkMethod) { super(); this.entryPoint = stmt; this.entryMethod = method; @@ -68,21 +68,21 @@ export class UndefinedVariableChecker extends DataflowProblem { return false; } - getNormalFlowFunction(srcStmt:Stmt, tgtStmt:Stmt): FlowFunction { + getNormalFlowFunction(srcStmt: Stmt, tgtStmt: Stmt): FlowFunction { let checkerInstance: UndefinedVariableChecker = this; - return new class implements FlowFunction { + return new (class implements FlowFunction { getDataFacts(dataFact: Value): Set { let ret: Set = new Set(); if (checkerInstance.getEntryPoint() === srcStmt && checkerInstance.getZeroValue() === dataFact) { ret.add(checkerInstance.getZeroValue()); return ret; } - if (srcStmt instanceof ArkAssignStmt ) { + if (srcStmt instanceof ArkAssignStmt) { checkerInstance.insideNormalFlowFunction(ret, srcStmt, dataFact); } return ret; } - } + })(); } insideNormalFlowFunction(ret: Set, srcStmt: ArkAssignStmt, dataFact: Value): void { @@ -91,7 +91,7 @@ export class UndefinedVariableChecker extends DataflowProblem { ret.add(dataFact); } } - let ass: ArkAssignStmt = (srcStmt as ArkAssignStmt); + let ass: ArkAssignStmt = srcStmt as ArkAssignStmt; let assigned: Value = ass.getLeftOp(); let rightOp: Value = ass.getRightOp(); if (this.getZeroValue() === dataFact) { @@ -102,7 +102,7 @@ export class UndefinedVariableChecker extends DataflowProblem { ret.add(assigned); } else if (rightOp instanceof ArkInstanceFieldRef) { const base = rightOp.getBase(); - if (base === dataFact || !base.getDeclaringStmt() && base.getName() === dataFact.toString()) { + if (base === dataFact || (!base.getDeclaringStmt() && base.getName() === dataFact.toString())) { this.outcomes.push(new Outcome(rightOp, ass)); logger.info('undefined base'); logger.info(srcStmt.toString()); @@ -114,27 +114,38 @@ export class UndefinedVariableChecker extends DataflowProblem { } } - getCallFlowFunction(srcStmt:Stmt, method:ArkMethod): FlowFunction { + getCallFlowFunction(srcStmt: Stmt, method: ArkMethod): FlowFunction { let checkerInstance: UndefinedVariableChecker = this; - return new class implements FlowFunction { + return new (class implements FlowFunction { getDataFacts(dataFact: Value): Set { const ret: Set = new Set(); if (checkerInstance.getZeroValue() === dataFact) { checkerInstance.insideCallFlowFunction(ret, method); } else { const callExpr = srcStmt.getExprs()[0]; - if (callExpr instanceof ArkInstanceInvokeExpr && dataFact instanceof ArkInstanceFieldRef && callExpr.getBase().getName() === dataFact.getBase().getName()) { + if ( + callExpr instanceof ArkInstanceInvokeExpr && + dataFact instanceof ArkInstanceFieldRef && + callExpr.getBase().getName() === dataFact.getBase().getName() + ) { // todo:base转this - const thisRef = new ArkInstanceFieldRef(new Local('this', new ClassType(method.getDeclaringArkClass().getSignature())), dataFact.getFieldSignature()); + const thisRef = new ArkInstanceFieldRef( + new Local('this', new ClassType(method.getDeclaringArkClass().getSignature())), + dataFact.getFieldSignature() + ); ret.add(thisRef); - } else if (callExpr instanceof ArkStaticInvokeExpr && dataFact instanceof ArkStaticFieldRef && callExpr.getMethodSignature().getDeclaringClassSignature() === dataFact.getFieldSignature().getDeclaringSignature()) { + } else if ( + callExpr instanceof ArkStaticInvokeExpr && + dataFact instanceof ArkStaticFieldRef && + callExpr.getMethodSignature().getDeclaringClassSignature() === dataFact.getFieldSignature().getDeclaringSignature() + ) { ret.add(dataFact); } } checkerInstance.addParameters(srcStmt, dataFact, method, ret); return ret; } - } + })(); } insideCallFlowFunction(ret: Set, method: ArkMethod): void { @@ -175,7 +186,7 @@ export class UndefinedVariableChecker extends DataflowProblem { const callStmt = srcStmt as ArkInvokeStmt; const args = callStmt.getInvokeExpr().getArgs(); for (let i = 0; i < args.length; i++) { - if (args[i] === dataFact || this.isUndefined(args[i]) && this.getZeroValue() === dataFact) { + if (args[i] === dataFact || (this.isUndefined(args[i]) && this.getZeroValue() === dataFact)) { const realParameter = [...method.getCfg()!.getBlocks()][0].getStmts()[i].getDef(); if (realParameter) { ret.add(realParameter); @@ -190,9 +201,9 @@ export class UndefinedVariableChecker extends DataflowProblem { } } - getExitToReturnFlowFunction(srcStmt:Stmt, tgtStmt:Stmt, callStmt:Stmt): FlowFunction { + getExitToReturnFlowFunction(srcStmt: Stmt, tgtStmt: Stmt, callStmt: Stmt): FlowFunction { let checkerInstance: UndefinedVariableChecker = this; - return new class implements FlowFunction { + return new (class implements FlowFunction { getDataFacts(dataFact: Value): Set { let ret: Set = new Set(); if (dataFact === checkerInstance.getZeroValue()) { @@ -200,15 +211,14 @@ export class UndefinedVariableChecker extends DataflowProblem { } return ret; } - - } + })(); } - getCallToReturnFlowFunction(srcStmt:Stmt, tgtStmt:Stmt): FlowFunction { + getCallToReturnFlowFunction(srcStmt: Stmt, tgtStmt: Stmt): FlowFunction { let checkerInstance: UndefinedVariableChecker = this; - return new class implements FlowFunction { + return new (class implements FlowFunction { getDataFacts(dataFact: Value): Set { - const ret:Set = new Set(); + const ret: Set = new Set(); if (checkerInstance.getZeroValue() === dataFact) { ret.add(checkerInstance.getZeroValue()); } @@ -218,8 +228,7 @@ export class UndefinedVariableChecker extends DataflowProblem { } return ret; } - - } + })(); } createZeroValue(): Value { @@ -247,12 +256,11 @@ export class UndefinedVariableChecker extends DataflowProblem { } export class UndefinedVariableSolver extends DataflowSolver { - constructor(problem: UndefinedVariableChecker, scene: Scene){ + constructor(problem: UndefinedVariableChecker, scene: Scene) { super(problem, scene); } } - class Outcome { value: Value; stmt: Stmt; @@ -260,4 +268,4 @@ class Outcome { this.value = v; this.stmt = s; } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/dataflow/Util.ts b/ets2panda/linter/arkanalyzer/src/core/dataflow/Util.ts index 8bb2346eb6..34ca4323df 100644 --- a/ets2panda/linter/arkanalyzer/src/core/dataflow/Util.ts +++ b/ets2panda/linter/arkanalyzer/src/core/dataflow/Util.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,24 +13,21 @@ * limitations under the License. */ -import { ArkInvokeStmt } from "../base/Stmt"; -import { FunctionType } from "../base/Type"; -import { ArkMethod } from "../model/ArkMethod"; -import { Local } from "../base/Local"; -import { AbstractRef, ArkStaticFieldRef, ArkInstanceFieldRef } from "../base/Ref"; +import { ArkInvokeStmt } from '../base/Stmt'; +import { FunctionType } from '../base/Type'; +import { ArkMethod } from '../model/ArkMethod'; +import { Local } from '../base/Local'; +import { AbstractRef, ArkStaticFieldRef, ArkInstanceFieldRef } from '../base/Ref'; - -export const INTERNAL_PARAMETER_SOURCE: string[] = [ - '@ohos.app.ability.Want.d.ts: Want' -] +export const INTERNAL_PARAMETER_SOURCE: string[] = ['@ohos.app.ability.Want.d.ts: Want']; export const INTERNAL_SINK_METHOD: string[] = [ 'console.<@%unk/%unk: .log()>', 'console.<@%unk/%unk: .error()>', 'console.<@%unk/%unk: .info()>', 'console.<@%unk/%unk: .warn()>', - 'console.<@%unk/%unk: .assert()>' -] + 'console.<@%unk/%unk: .assert()>', +]; export function getRecallMethodInParam(stmt: ArkInvokeStmt): ArkMethod | null { for (const param of stmt.getInvokeExpr().getArgs()) { @@ -45,7 +42,6 @@ export function getRecallMethodInParam(stmt: ArkInvokeStmt): ArkMethod | null { return null; } - export function LocalEqual(local1: Local, local2: Local): boolean { if (local1.getName() === 'this' && local2.getName() === 'this') { return true; @@ -63,4 +59,4 @@ export function RefEqual(ref1: AbstractRef, ref2: AbstractRef): boolean { return LocalEqual(ref1.getBase(), ref2.getBase()) && ref1.getFieldSignature().toString() === ref2.getFieldSignature().toString(); } return false; -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/graph/BaseExplicitGraph.ts b/ets2panda/linter/arkanalyzer/src/core/graph/BaseExplicitGraph.ts index 5823fec536..fc55eb7e98 100644 --- a/ets2panda/linter/arkanalyzer/src/core/graph/BaseExplicitGraph.ts +++ b/ets2panda/linter/arkanalyzer/src/core/graph/BaseExplicitGraph.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -15,7 +15,7 @@ import { Kind, NodeID, GraphTraits } from './GraphTraits'; -export {Kind, NodeID}; +export { Kind, NodeID }; export abstract class BaseEdge { private src: BaseNode; private dst: BaseNode; diff --git a/ets2panda/linter/arkanalyzer/src/core/graph/BaseImplicitGraph.ts b/ets2panda/linter/arkanalyzer/src/core/graph/BaseImplicitGraph.ts index 671b642c4c..8eb3556425 100644 --- a/ets2panda/linter/arkanalyzer/src/core/graph/BaseImplicitGraph.ts +++ b/ets2panda/linter/arkanalyzer/src/core/graph/BaseImplicitGraph.ts @@ -88,7 +88,6 @@ export abstract class BaseImplicitGraph implements GraphTraits { } return this.nodeToIdMap.get(s)!; - } /** @@ -137,4 +136,4 @@ export abstract class BaseImplicitGraph implements GraphTraits { * @returns The name of the graph. */ public abstract getGraphName(): string; -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/graph/BasicBlock.ts b/ets2panda/linter/arkanalyzer/src/core/graph/BasicBlock.ts index dd9ee3b6d8..f8487e4e12 100644 --- a/ets2panda/linter/arkanalyzer/src/core/graph/BasicBlock.ts +++ b/ets2panda/linter/arkanalyzer/src/core/graph/BasicBlock.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -202,7 +202,7 @@ export class BasicBlock { } // Temp just for SSA - public addStmtToFirst(stmt: Stmt) { + public addStmtToFirst(stmt: Stmt): void { this.addHead(stmt); } @@ -240,28 +240,30 @@ export class BasicBlock { public validate(): ArkError { let branchStmts: Stmt[] = []; for (const stmt of this.stmts) { - if ( - stmt instanceof ArkIfStmt || - stmt instanceof ArkReturnStmt || - stmt instanceof ArkReturnVoidStmt - ) { + if (stmt instanceof ArkIfStmt || stmt instanceof ArkReturnStmt || stmt instanceof ArkReturnVoidStmt) { branchStmts.push(stmt); } } if (branchStmts.length > 1) { - let errMsg = `More than one branch or return stmts in the block: ${branchStmts.map((value) => value.toString()).join('\n')}`; + let errMsg = `More than one branch or return stmts in the block: ${branchStmts.map(value => value.toString()).join('\n')}`; logger.error(errMsg); - return {errCode: ArkErrorCode.BB_MORE_THAN_ONE_BRANCH_RET_STMT, errMsg: errMsg }; + return { + errCode: ArkErrorCode.BB_MORE_THAN_ONE_BRANCH_RET_STMT, + errMsg: errMsg, + }; } if (branchStmts.length === 1 && branchStmts[0] !== this.stmts[this.stmts.length - 1]) { let errMsg = `${branchStmts[0].toString()} not at the end of block.`; logger.error(errMsg); - return {errCode: ArkErrorCode.BB_BRANCH_RET_STMT_NOT_AT_END, errMsg: errMsg}; + return { + errCode: ArkErrorCode.BB_BRANCH_RET_STMT_NOT_AT_END, + errMsg: errMsg, + }; } - return {errCode: ArkErrorCode.OK}; + return { errCode: ArkErrorCode.OK }; } private insertPos(index: number, toInsert: Stmt | Stmt[]): number { diff --git a/ets2panda/linter/arkanalyzer/src/core/graph/Cfg.ts b/ets2panda/linter/arkanalyzer/src/core/graph/Cfg.ts index 3470793463..4ef2fadcaf 100644 --- a/ets2panda/linter/arkanalyzer/src/core/graph/Cfg.ts +++ b/ets2panda/linter/arkanalyzer/src/core/graph/Cfg.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -139,7 +139,7 @@ export class Cfg { return this.declaringMethod; } - public setDeclaringMethod(method: ArkMethod) { + public setDeclaringMethod(method: ArkMethod): void { this.declaringMethod = method; } @@ -258,26 +258,28 @@ export class Cfg { if (!startBB) { let errMsg = `Not found starting block}`; logger.error(errMsg); - return { errCode: ArkErrorCode.CFG_NOT_FOUND_START_BLOCK, errMsg: errMsg }; + return { + errCode: ArkErrorCode.CFG_NOT_FOUND_START_BLOCK, + errMsg: errMsg, + }; } let unreachable = this.getUnreachableBlocks(); if (unreachable.size !== 0) { let errMsg = `Unreachable blocks: ${Array.from(unreachable) - .map((value) => value.toString()) + .map(value => value.toString()) .join('\n')}`; logger.error(errMsg); - return { errCode: ArkErrorCode.CFG_HAS_UNREACHABLE_BLOCK, errMsg: errMsg }; + return { + errCode: ArkErrorCode.CFG_HAS_UNREACHABLE_BLOCK, + errMsg: errMsg, + }; } return { errCode: ArkErrorCode.OK }; } - private dfsPostOrder( - node: BasicBlock, - visitor: Set = new Set(), - postOrder: Set = new Set() - ): Set { + private dfsPostOrder(node: BasicBlock, visitor: Set = new Set(), postOrder: Set = new Set()): Set { visitor.add(node); for (const succ of node.getSuccessors()) { if (visitor.has(succ)) { diff --git a/ets2panda/linter/arkanalyzer/src/core/graph/DependsGraph.ts b/ets2panda/linter/arkanalyzer/src/core/graph/DependsGraph.ts index e4cab5ac97..dc3f40e69d 100644 --- a/ets2panda/linter/arkanalyzer/src/core/graph/DependsGraph.ts +++ b/ets2panda/linter/arkanalyzer/src/core/graph/DependsGraph.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -97,11 +97,7 @@ export class DependsGraph, - dst: DependsNode, - attr: EdgeAttr - ): DependsEdge { + public addEdge(src: DependsNode, dst: DependsNode, attr: EdgeAttr): DependsEdge { let edge = new DependsEdge(src, dst, attr); let key = edge.getKey(); if (this.edgesMap.has(key)) { diff --git a/ets2panda/linter/arkanalyzer/src/core/graph/DominanceFinder.ts b/ets2panda/linter/arkanalyzer/src/core/graph/DominanceFinder.ts index a3cd26a236..08afcef3be 100644 --- a/ets2panda/linter/arkanalyzer/src/core/graph/DominanceFinder.ts +++ b/ets2panda/linter/arkanalyzer/src/core/graph/DominanceFinder.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -18,7 +18,7 @@ import { Cfg } from './Cfg'; export class DominanceFinder { private blocks: BasicBlock[] = []; - private blockToIdx = new Map; + private blockToIdx = new Map(); private idoms: number[] = []; private domFrontiers: number[][] = []; @@ -51,7 +51,7 @@ export class DominanceFinder { } for (const pred of preds) { let predIdx = this.blockToIdx.get(pred) as number; - this.idoms[predIdx] !== -1 ? newIdom = this.intersect(newIdom, predIdx) : null; + this.idoms[predIdx] !== -1 ? (newIdom = this.intersect(newIdom, predIdx)) : null; } if (this.idoms[blockIdx] !== newIdom) { this.idoms[blockIdx] = newIdom; @@ -83,7 +83,7 @@ export class DominanceFinder { public getDominanceFrontiers(block: BasicBlock): Set { if (!this.blockToIdx.has(block)) { - throw new Error("The given block: " + block + " is not in Cfg!") + throw new Error('The given block: ' + block + ' is not in Cfg!'); } let idx = this.blockToIdx.get(block) as number; let dfs = new Set(); @@ -106,7 +106,6 @@ export class DominanceFinder { return this.idoms; } - private getFirstDefinedBlockPredIdx(preds: BasicBlock[]): number { for (const block of preds) { let idx = this.blockToIdx.get(block) as number; @@ -127,4 +126,4 @@ export class DominanceFinder { } return a; } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/graph/DominanceTree.ts b/ets2panda/linter/arkanalyzer/src/core/graph/DominanceTree.ts index b0cf79915c..5b595c8418 100644 --- a/ets2panda/linter/arkanalyzer/src/core/graph/DominanceTree.ts +++ b/ets2panda/linter/arkanalyzer/src/core/graph/DominanceTree.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/ets2panda/linter/arkanalyzer/src/core/graph/GraphTraits.ts b/ets2panda/linter/arkanalyzer/src/core/graph/GraphTraits.ts index cf2b89a3db..b9a8a1f71f 100644 --- a/ets2panda/linter/arkanalyzer/src/core/graph/GraphTraits.ts +++ b/ets2panda/linter/arkanalyzer/src/core/graph/GraphTraits.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -20,4 +20,4 @@ export interface GraphTraits { nodesItor(): IterableIterator; getGraphName(): string; getNode(id: NodeID): Node | undefined; -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/graph/Scc.ts b/ets2panda/linter/arkanalyzer/src/core/graph/Scc.ts index 3370659347..aeb568012d 100644 --- a/ets2panda/linter/arkanalyzer/src/core/graph/Scc.ts +++ b/ets2panda/linter/arkanalyzer/src/core/graph/Scc.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -153,7 +153,7 @@ export class SCCDetection> { this.setVisited(v); let node = this.getNode(v); - node.getOutgoingEdges().forEach((e) => { + node.getOutgoingEdges().forEach(e => { let w: NodeID = e.getDstID(); if (!this.isVisited(w)) { this.visit(w); @@ -275,4 +275,4 @@ export class SCCDetection> { public getRepNodes(): NodeSet { return this.repNodes; } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/graph/ViewTree.ts b/ets2panda/linter/arkanalyzer/src/core/graph/ViewTree.ts index 5324873ac4..b37c770748 100644 --- a/ets2panda/linter/arkanalyzer/src/core/graph/ViewTree.ts +++ b/ets2panda/linter/arkanalyzer/src/core/graph/ViewTree.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -46,8 +46,8 @@ export interface ViewTreeNode { /** * Custom component value transfer * - key: ArkField, child custom component class stateValue field. - * - value: ArkField | ArkMethod, parent component transfer value. - * key is BuilderParam, the value is Builder ArkMethod. + * - value: ArkField | ArkMethod, parent component transfer value. + * key is BuilderParam, the value is Builder ArkMethod. * Others, the value is parent class stateValue field. */ stateValuesTransfer?: Map; @@ -59,10 +59,10 @@ export interface ViewTreeNode { builder?: MethodSignature; /** - * walk node and node's children + * walk node and node's children * @param selector Node selector function, return true skipping the follow-up nodes. - * @returns - * - true: There are nodes that meet the selector. + * @returns + * - true: There are nodes that meet the selector. * - false: does not exist. */ walk(selector: (item: ViewTreeNode) => boolean): boolean; @@ -86,49 +86,49 @@ export interface ViewTreeNode { * // Component Class get ViewTree * let arkClas: ArkClass = ...; * let viewtree = arkClas.getViewTree(); - * + * * // get viewtree root node * let root: ViewTreeNode = viewtree.getRoot(); - * + * * // get viewtree stateValues Map * let stateValues: Map> = viewtree.getStateValues(); - * + * * // walk all nodes * root.walk((node) => { * // check node is builder * if (node.isBuilder()) { * xx - * } - * + * } + * * // check node is sub CustomComponent * if (node.isCustomComponent()) { * xx * } - * + * * if (xxx) { * // Skip the remaining nodes and end the traversal * return true; * } - * + * * return false; * }) - * + * * @category core/graph */ export interface ViewTree { /** - * @deprecated Use {@link getStateValues} instead. + * @deprecated Use {@link getStateValues} instead. */ isClassField(name: string): boolean; /** - * @deprecated Use {@link getStateValues} instead. + * @deprecated Use {@link getStateValues} instead. */ getClassFieldType(name: string): Decorator | Type | undefined; /** * Map of the component controlled by the state variable - * @returns + * @returns */ getStateValues(): Map>; diff --git a/ets2panda/linter/arkanalyzer/src/core/graph/builder/CfgBuilder.ts b/ets2panda/linter/arkanalyzer/src/core/graph/builder/CfgBuilder.ts index 61742e133c..5cd44402ec 100644 --- a/ets2panda/linter/arkanalyzer/src/core/graph/builder/CfgBuilder.ts +++ b/ets2panda/linter/arkanalyzer/src/core/graph/builder/CfgBuilder.ts @@ -35,16 +35,16 @@ import { ModifierType } from '../../model/ArkBaseModel'; class StatementBuilder { type: string; - //节点对应源代码 + //节点对应源代码 code: string; next: StatementBuilder | null; lasts: Set; walked: boolean; index: number; - // TODO:以下两个属性需要获取 - line: number;//行号//ast节点存了一个start值为这段代码的起始地址,可以从start开始往回查原文有几个换行符确定行号 - column: number; // 列 - astNode: ts.Node | null;//ast节点对象 + // TODO:以下两个属性需要获取 + line: number; //行号//ast节点存了一个start值为这段代码的起始地址,可以从start开始往回查原文有几个换行符确定行号 + column: number; // 列 + astNode: ts.Node | null; //ast节点对象 scopeID: number; addressCode3: string[] = []; block: BlockBuilder | null; @@ -268,7 +268,6 @@ export class CfgBuilder { lastStatement.next = s; s.lasts.add(lastStatement); } - } ASTNodeBreakStatement(c: ts.Node, lastStatement: StatementBuilder): void { @@ -359,7 +358,8 @@ export class CfgBuilder { loopExit.lasts.add(loopstm); loopstm.code = 'for ('; if (ts.isForStatement(c)) { - loopstm.code += c.initializer?.getText(this.sourceFile) + '; ' + c.condition?.getText(this.sourceFile) + '; ' + c.incrementor?.getText(this.sourceFile); + loopstm.code += + c.initializer?.getText(this.sourceFile) + '; ' + c.condition?.getText(this.sourceFile) + '; ' + c.incrementor?.getText(this.sourceFile); } else if (ts.isForOfStatement(c)) { loopstm.code += c.initializer?.getText(this.sourceFile) + ' of ' + c.expression.getText(this.sourceFile); } else { @@ -497,7 +497,6 @@ export class CfgBuilder { } else { trystm.catchError = 'Error'; } - } let final = new StatementBuilder('statement', 'finally', c, scopeID); let finalExit = new StatementBuilder('finallyExit', '', c, scopeID); @@ -505,7 +504,7 @@ export class CfgBuilder { if (c.finallyBlock && c.finallyBlock.statements.length > 0) { this.walkAST(final, finalExit, [...c.finallyBlock.statements]); } else { - let dummyFinally = new StatementBuilder('statement', 'dummyFinally', c, (new Scope(this.scopes.length)).id); + let dummyFinally = new StatementBuilder('statement', 'dummyFinally', c, new Scope(this.scopes.length).id); final.next = dummyFinally; dummyFinally.lasts.add(final); dummyFinally.next = finalExit; @@ -648,13 +647,16 @@ export class CfgBuilder { addStmt2BlockStmtQueueInSpecialCase(stmt: StatementBuilder, stmtQueue: StatementBuilder[]): StatementBuilder | null { if (stmt.next) { - if ((stmt.type === 'continueStatement' || stmt.next.type === 'loopStatement') && stmt.next.block || stmt.next.type.includes('exit')) { + if (((stmt.type === 'continueStatement' || stmt.next.type === 'loopStatement') && stmt.next.block) || stmt.next.type.includes('exit')) { return null; } stmt.next.passTmies++; if (stmt.next.passTmies === stmt.next.lasts.size || stmt.next.type === 'loopStatement' || stmt.next.isDoWhile) { - if (stmt.next.scopeID !== stmt.scopeID && !(stmt.next instanceof ConditionStatementBuilder && stmt.next.doStatement) && - !(ts.isCaseClause(stmt.astNode!) || ts.isDefaultClause(stmt.astNode!))) { + if ( + stmt.next.scopeID !== stmt.scopeID && + !(stmt.next instanceof ConditionStatementBuilder && stmt.next.doStatement) && + !(ts.isCaseClause(stmt.astNode!) || ts.isDefaultClause(stmt.astNode!)) + ) { stmtQueue.push(stmt.next); return null; } @@ -725,8 +727,7 @@ export class CfgBuilder { } } - buildConditionNextBlocks(originStatement: ConditionStatementBuilder, block: BlockBuilder, - isLastStatement: boolean): void { + buildConditionNextBlocks(originStatement: ConditionStatementBuilder, block: BlockBuilder, isLastStatement: boolean): void { let nextT = originStatement.nextT?.block; if (nextT && (isLastStatement || nextT !== block) && !originStatement.nextT?.type.includes(' exit')) { block.nexts.push(nextT); @@ -739,8 +740,7 @@ export class CfgBuilder { } } - buildSwitchNextBlocks(originStatement: SwitchStatementBuilder, block: BlockBuilder, - isLastStatement: boolean): void { + buildSwitchNextBlocks(originStatement: SwitchStatementBuilder, block: BlockBuilder, isLastStatement: boolean): void { if (originStatement.nexts.length === 0) { const nextBlock = originStatement.afterSwitch!.block; if (nextBlock && (isLastStatement || nextBlock !== block)) { @@ -768,7 +768,7 @@ export class CfgBuilder { buildBlocksNextLast(): void { for (let block of this.blocks) { for (let originStatement of block.stmts) { - let isLastStatement = (block.stmts.indexOf(originStatement) === block.stmts.length - 1); + let isLastStatement = block.stmts.indexOf(originStatement) === block.stmts.length - 1; if (originStatement instanceof ConditionStatementBuilder) { this.buildConditionNextBlocks(originStatement, block, isLastStatement); } else if (originStatement instanceof SwitchStatementBuilder) { @@ -853,10 +853,7 @@ export class CfgBuilder { addStmtBuilderPosition(): void { for (const stmt of this.statementArray) { if (stmt.astNode) { - const { line, character } = ts.getLineAndCharacterOfPosition( - this.sourceFile, - stmt.astNode.getStart(this.sourceFile), - ); + const { line, character } = ts.getLineAndCharacterOfPosition(this.sourceFile, stmt.astNode.getStart(this.sourceFile)); stmt.line = line + 1; stmt.column = character + 1; } @@ -864,7 +861,6 @@ export class CfgBuilder { } CfgBuilder2Array(stmt: StatementBuilder): void { - if (stmt.walked) { return; } @@ -964,10 +960,15 @@ export class CfgBuilder { let stmts: ts.Node[] = []; if (ts.isSourceFile(this.astRoot)) { stmts = [...this.astRoot.statements]; - } else if (ts.isFunctionDeclaration(this.astRoot) || ts.isMethodDeclaration(this.astRoot) || - ts.isConstructorDeclaration(this.astRoot) || ts.isGetAccessorDeclaration(this.astRoot) || - ts.isSetAccessorDeclaration(this.astRoot) || ts.isFunctionExpression(this.astRoot) || - ts.isClassStaticBlockDeclaration(this.astRoot)) { + } else if ( + ts.isFunctionDeclaration(this.astRoot) || + ts.isMethodDeclaration(this.astRoot) || + ts.isConstructorDeclaration(this.astRoot) || + ts.isGetAccessorDeclaration(this.astRoot) || + ts.isSetAccessorDeclaration(this.astRoot) || + ts.isFunctionExpression(this.astRoot) || + ts.isClassStaticBlockDeclaration(this.astRoot) + ) { if (this.astRoot.body) { stmts = [...this.astRoot.body.statements]; } else { @@ -977,8 +978,12 @@ export class CfgBuilder { if (ts.isBlock(this.astRoot.body)) { stmts = [...this.astRoot.body.statements]; } - } else if (ts.isMethodSignature(this.astRoot) || ts.isConstructSignatureDeclaration(this.astRoot) || - ts.isCallSignatureDeclaration(this.astRoot) || ts.isFunctionTypeNode(this.astRoot)) { + } else if ( + ts.isMethodSignature(this.astRoot) || + ts.isConstructSignatureDeclaration(this.astRoot) || + ts.isCallSignatureDeclaration(this.astRoot) || + ts.isFunctionTypeNode(this.astRoot) + ) { this.emptyBody = true; } else if (ts.isModuleDeclaration(this.astRoot) && ts.isModuleBlock(this.astRoot.body!)) { stmts = [...this.astRoot.body.statements]; @@ -996,7 +1001,7 @@ export class CfgBuilder { this.CfgBuilder2Array(this.entry); this.addStmtBuilderPosition(); this.buildBlocks(); - this.blocks = this.blocks.filter((b) => b.stmts.length !== 0); + this.blocks = this.blocks.filter(b => b.stmts.length !== 0); this.buildBlocksNextLast(); this.addReturnStmt(); } @@ -1018,11 +1023,11 @@ export class CfgBuilder { } public buildCfg(): { - cfg: Cfg, - locals: Set, - globals: Map | null, - aliasTypeMap: Map, - traps: Trap[], + cfg: Cfg; + locals: Set; + globals: Map | null; + aliasTypeMap: Map; + traps: Trap[]; } { if (ts.isArrowFunction(this.astRoot) && !ts.isBlock(this.astRoot.body)) { return this.buildCfgForSimpleArrowFunction(); @@ -1032,11 +1037,11 @@ export class CfgBuilder { } public buildCfgForSimpleArrowFunction(): { - cfg: Cfg, - locals: Set, - globals: Map | null, - aliasTypeMap: Map, - traps: Trap[], + cfg: Cfg; + locals: Set; + globals: Map | null; + aliasTypeMap: Map; + traps: Trap[]; } { const stmts: Stmt[] = []; const arkIRTransformer = new ArkIRTransformer(this.sourceFile, this.declaringMethod); @@ -1081,22 +1086,29 @@ export class CfgBuilder { } public buildNormalCfg(): { - cfg: Cfg, - locals: Set, - globals: Map | null, - aliasTypeMap: Map, - traps: Trap[], + cfg: Cfg; + locals: Set; + globals: Map | null; + aliasTypeMap: Map; + traps: Trap[]; } { const { blockBuilderToCfgBlock, basicBlockSet, arkIRTransformer } = this.initializeBuild(); - const { - blocksContainLoopCondition, blockBuildersBeforeTry, blockBuildersContainSwitch, - valueAndStmtsOfSwitchAndCasesAll, - } = this.processBlocks(blockBuilderToCfgBlock, basicBlockSet, arkIRTransformer); + const { blocksContainLoopCondition, blockBuildersBeforeTry, blockBuildersContainSwitch, valueAndStmtsOfSwitchAndCasesAll } = this.processBlocks( + blockBuilderToCfgBlock, + basicBlockSet, + arkIRTransformer + ); const currBlockId = this.blocks.length; this.linkBasicBlocks(blockBuilderToCfgBlock); - this.adjustBlocks(blockBuilderToCfgBlock, blocksContainLoopCondition, basicBlockSet, blockBuildersContainSwitch, - valueAndStmtsOfSwitchAndCasesAll, arkIRTransformer); + this.adjustBlocks( + blockBuilderToCfgBlock, + blocksContainLoopCondition, + basicBlockSet, + blockBuildersContainSwitch, + valueAndStmtsOfSwitchAndCasesAll, + arkIRTransformer + ); const trapBuilder = new TrapBuilder(); const traps = trapBuilder.buildTraps(blockBuilderToCfgBlock, blockBuildersBeforeTry, arkIRTransformer, basicBlockSet); @@ -1112,9 +1124,9 @@ export class CfgBuilder { } private initializeBuild(): { - blockBuilderToCfgBlock: Map, - basicBlockSet: Set, - arkIRTransformer: ArkIRTransformer, + blockBuilderToCfgBlock: Map; + basicBlockSet: Set; + arkIRTransformer: ArkIRTransformer; } { const blockBuilderToCfgBlock = new Map(); const basicBlockSet = new Set(); @@ -1125,12 +1137,12 @@ export class CfgBuilder { private processBlocks( blockBuilderToCfgBlock: Map, basicBlockSet: Set, - arkIRTransformer: ArkIRTransformer, + arkIRTransformer: ArkIRTransformer ): { - blocksContainLoopCondition: Set, - blockBuildersBeforeTry: Set, - blockBuildersContainSwitch: BlockBuilder[], - valueAndStmtsOfSwitchAndCasesAll: ValueAndStmts[][], + blocksContainLoopCondition: Set; + blockBuildersBeforeTry: Set; + blockBuildersContainSwitch: BlockBuilder[]; + valueAndStmtsOfSwitchAndCasesAll: ValueAndStmts[][]; } { const blocksContainLoopCondition = new Set(); const blockBuildersBeforeTry = new Set(); @@ -1150,8 +1162,7 @@ export class CfgBuilder { blocksContainLoopCondition.add(this.blocks[i]); } else if (statementBuilder instanceof SwitchStatementBuilder) { blockBuildersContainSwitch.push(this.blocks[i]); - const valueAndStmtsOfSwitchAndCases = arkIRTransformer.switchStatementToValueAndStmts( - statementBuilder.astNode as ts.SwitchStatement); + const valueAndStmtsOfSwitchAndCases = arkIRTransformer.switchStatementToValueAndStmts(statementBuilder.astNode as ts.SwitchStatement); valueAndStmtsOfSwitchAndCasesAll.push(valueAndStmtsOfSwitchAndCases); continue; } @@ -1170,7 +1181,9 @@ export class CfgBuilder { blockBuilderToCfgBlock.set(this.blocks[i], blockInCfg); } return { - blocksContainLoopCondition, blockBuildersBeforeTry, blockBuildersContainSwitch, + blocksContainLoopCondition, + blockBuildersBeforeTry, + blockBuildersContainSwitch, valueAndStmtsOfSwitchAndCasesAll, }; } @@ -1201,21 +1214,17 @@ export class CfgBuilder { basicBlockSet: Set, blockBuildersContainSwitch: BlockBuilder[], valueAndStmtsOfSwitchAndCasesAll: ValueAndStmts[][], - arkIRTransformer: ArkIRTransformer, + arkIRTransformer: ArkIRTransformer ): void { const loopBuilder = new LoopBuilder(); loopBuilder.rebuildBlocksInLoop(blockBuilderToCfgBlock, blocksContainLoopCondition, basicBlockSet, this.blocks); const switchBuilder = new SwitchBuilder(); - switchBuilder.buildSwitch(blockBuilderToCfgBlock, blockBuildersContainSwitch, - valueAndStmtsOfSwitchAndCasesAll, arkIRTransformer, basicBlockSet); + switchBuilder.buildSwitch(blockBuilderToCfgBlock, blockBuildersContainSwitch, valueAndStmtsOfSwitchAndCasesAll, arkIRTransformer, basicBlockSet); const conditionalBuilder = new ConditionBuilder(); conditionalBuilder.rebuildBlocksContainConditionalOperator(basicBlockSet, ModelUtils.isArkUIBuilderMethod(this.declaringMethod)); } - private createCfg( - blockBuilderToCfgBlock: Map, - basicBlockSet: Set, prevBlockId: number, - ): Cfg { + private createCfg(blockBuilderToCfgBlock: Map, basicBlockSet: Set, prevBlockId: number): Cfg { let currBlockId = prevBlockId; for (const blockBuilder of this.blocks) { if (blockBuilder.id === -1) { @@ -1257,4 +1266,4 @@ export class CfgBuilder { } } } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/graph/builder/ConditionBuilder.ts b/ets2panda/linter/arkanalyzer/src/core/graph/builder/ConditionBuilder.ts index 8faaad123c..2cb3c91201 100644 --- a/ets2panda/linter/arkanalyzer/src/core/graph/builder/ConditionBuilder.ts +++ b/ets2panda/linter/arkanalyzer/src/core/graph/builder/ConditionBuilder.ts @@ -36,8 +36,7 @@ export class ConditionBuilder { let conditionalOperatorEndPos = -1; for (let i = stmtsCnt - 1; i >= 0; i--) { const stmt = stmtsInCurrBasicBlock[i]; - if (stmt instanceof DummyStmt && stmt.toString() - ?.startsWith(ArkIRTransformer.DUMMY_CONDITIONAL_OPERATOR_END_STMT)) { + if (stmt instanceof DummyStmt && stmt.toString()?.startsWith(ArkIRTransformer.DUMMY_CONDITIONAL_OPERATOR_END_STMT)) { conditionalOperatorEndPos = i; break; } @@ -46,17 +45,16 @@ export class ConditionBuilder { continue; } - let { - generatedTopBlock: generatedTopBlock, - generatedBottomBlocks: generatedBottomBlocks, - } = this.generateBlocksContainConditionalOperatorGroup( - stmtsInCurrBasicBlock.slice(0, conditionalOperatorEndPos + 1), basicBlockSet); + let { generatedTopBlock: generatedTopBlock, generatedBottomBlocks: generatedBottomBlocks } = this.generateBlocksContainConditionalOperatorGroup( + stmtsInCurrBasicBlock.slice(0, conditionalOperatorEndPos + 1), + basicBlockSet + ); - if (conditionalOperatorEndPos !== stmtsCnt - 1) { // need create a new basic block for rest statements - const { - generatedTopBlock: extraBlock, - } = this.generateBlockWithoutConditionalOperator( - stmtsInCurrBasicBlock.slice(conditionalOperatorEndPos + 1)); + if (conditionalOperatorEndPos !== stmtsCnt - 1) { + // need create a new basic block for rest statements + const { generatedTopBlock: extraBlock } = this.generateBlockWithoutConditionalOperator( + stmtsInCurrBasicBlock.slice(conditionalOperatorEndPos + 1) + ); generatedBottomBlocks.forEach(generatedBottomBlock => { generatedBottomBlock.addSuccessorBlock(extraBlock); extraBlock.addPredecessorBlock(generatedBottomBlock); @@ -69,9 +67,11 @@ export class ConditionBuilder { } } - private relinkPrevAndSuccOfBlockContainConditionalOperator(currBasicBlock: BasicBlock, - generatedTopBlock: BasicBlock, - generatedBottomBlocks: BasicBlock[]): void { + private relinkPrevAndSuccOfBlockContainConditionalOperator( + currBasicBlock: BasicBlock, + generatedTopBlock: BasicBlock, + generatedBottomBlocks: BasicBlock[] + ): void { const predecessorsOfCurrBasicBlock = Array.from(currBasicBlock.getPredecessors()); predecessorsOfCurrBasicBlock.forEach(predecessor => { predecessor.removeSuccessorBlock(currBasicBlock); @@ -90,9 +90,12 @@ export class ConditionBuilder { }); } - private generateBlocksContainConditionalOperatorGroup(sourceStmts: Stmt[], basicBlockSet: Set): { - generatedTopBlock: BasicBlock, - generatedBottomBlocks: BasicBlock[], + private generateBlocksContainConditionalOperatorGroup( + sourceStmts: Stmt[], + basicBlockSet: Set + ): { + generatedTopBlock: BasicBlock; + generatedBottomBlocks: BasicBlock[]; } { const { firstEndPos: firstEndPos } = this.findFirstConditionalOperator(sourceStmts); if (firstEndPos === -1) { @@ -107,12 +110,10 @@ export class ConditionBuilder { let generatedBottomBlocks = firstGeneratedBottomBlocks; firstGeneratedAllBlocks.forEach(block => basicBlockSet.add(block)); const stmtsCnt = sourceStmts.length; - if (firstEndPos !== stmtsCnt - 1) { // need handle other conditional operators - const { - generatedTopBlock: restGeneratedTopBlock, - generatedBottomBlocks: restGeneratedBottomBlocks, - } = this.generateBlocksContainConditionalOperatorGroup( - sourceStmts.slice(firstEndPos + 1, stmtsCnt), basicBlockSet); + if (firstEndPos !== stmtsCnt - 1) { + // need handle other conditional operators + const { generatedTopBlock: restGeneratedTopBlock, generatedBottomBlocks: restGeneratedBottomBlocks } = + this.generateBlocksContainConditionalOperatorGroup(sourceStmts.slice(firstEndPos + 1, stmtsCnt), basicBlockSet); firstGeneratedBottomBlocks.forEach(firstGeneratedBottomBlock => { firstGeneratedBottomBlock.addSuccessorBlock(restGeneratedTopBlock); restGeneratedTopBlock.addPredecessorBlock(firstGeneratedBottomBlock); @@ -125,22 +126,17 @@ export class ConditionBuilder { } private generateBlocksContainSingleConditionalOperator(sourceStmts: Stmt[]): { - generatedTopBlock: BasicBlock, - generatedBottomBlocks: BasicBlock[], - generatedAllBlocks: BasicBlock[], + generatedTopBlock: BasicBlock; + generatedBottomBlocks: BasicBlock[]; + generatedAllBlocks: BasicBlock[]; } { - const { - firstIfTruePos: ifTruePos, - firstIfFalsePos: ifFalsePos, - firstEndPos: endPos, - } = this.findFirstConditionalOperator(sourceStmts); + const { firstIfTruePos: ifTruePos, firstIfFalsePos: ifFalsePos, firstEndPos: endPos } = this.findFirstConditionalOperator(sourceStmts); if (endPos === -1) { return this.generateBlockWithoutConditionalOperator(sourceStmts); } - const { - generatedTopBlock: generatedTopBlock, - generatedAllBlocks: generatedAllBlocks, - } = this.generateBlockWithoutConditionalOperator(sourceStmts.slice(0, ifTruePos)); + const { generatedTopBlock: generatedTopBlock, generatedAllBlocks: generatedAllBlocks } = this.generateBlockWithoutConditionalOperator( + sourceStmts.slice(0, ifTruePos) + ); let generatedBottomBlocks: BasicBlock[] = []; const { generatedTopBlock: generatedTopBlockOfTrueBranch, @@ -162,10 +158,9 @@ export class ConditionBuilder { generatedTopBlock.addSuccessorBlock(generatedTopBlockOfFalseBranch); generatedTopBlockOfFalseBranch.addPredecessorBlock(generatedTopBlock); const stmtsCnt = sourceStmts.length; - if (endPos !== stmtsCnt - 1) { // need create a new basic block for rest statements - const { - generatedTopBlock: extraBlock, - } = this.generateBlockWithoutConditionalOperator(sourceStmts.slice(endPos + 1)); + if (endPos !== stmtsCnt - 1) { + // need create a new basic block for rest statements + const { generatedTopBlock: extraBlock } = this.generateBlockWithoutConditionalOperator(sourceStmts.slice(endPos + 1)); generatedBottomBlocks.forEach(generatedBottomBlock => { generatedBottomBlock.addSuccessorBlock(extraBlock); extraBlock.addPredecessorBlock(generatedBottomBlock); @@ -177,9 +172,9 @@ export class ConditionBuilder { } private generateBlockWithoutConditionalOperator(sourceStmts: Stmt[]): { - generatedTopBlock: BasicBlock, - generatedBottomBlocks: BasicBlock[], - generatedAllBlocks: BasicBlock[], + generatedTopBlock: BasicBlock; + generatedBottomBlocks: BasicBlock[]; + generatedAllBlocks: BasicBlock[]; } { const generatedBlock = new BasicBlock(); sourceStmts.forEach(stmt => generatedBlock.addStmt(stmt)); @@ -194,8 +189,7 @@ export class ConditionBuilder { for (const basicBlock of basicBlockSet) { const stmts = Array.from(basicBlock.getStmts()); for (const stmt of stmts) { - if (stmt instanceof DummyStmt && stmt.toString() - ?.startsWith(ArkIRTransformer.DUMMY_CONDITIONAL_OPERATOR)) { + if (stmt instanceof DummyStmt && stmt.toString()?.startsWith(ArkIRTransformer.DUMMY_CONDITIONAL_OPERATOR)) { basicBlock.remove(stmt); } } @@ -203,7 +197,9 @@ export class ConditionBuilder { } private findFirstConditionalOperator(stmts: Stmt[]): { - firstIfTruePos: number, firstIfFalsePos: number, firstEndPos: number, + firstIfTruePos: number; + firstIfFalsePos: number; + firstEndPos: number; } { let firstIfTruePos = -1; let firstIfFalsePos = -1; @@ -212,17 +208,12 @@ export class ConditionBuilder { for (let i = 0; i < stmts.length; i++) { const stmt = stmts[i]; if (stmt instanceof DummyStmt) { - if (stmt.toString() - .startsWith(ArkIRTransformer.DUMMY_CONDITIONAL_OPERATOR_IF_TRUE_STMT) && firstIfTruePos === - -1) { + if (stmt.toString().startsWith(ArkIRTransformer.DUMMY_CONDITIONAL_OPERATOR_IF_TRUE_STMT) && firstIfTruePos === -1) { firstIfTruePos = i; - firstConditionalOperatorNo = - stmt.toString().replace(ArkIRTransformer.DUMMY_CONDITIONAL_OPERATOR_IF_TRUE_STMT, ''); - } else if (stmt.toString() === ArkIRTransformer.DUMMY_CONDITIONAL_OPERATOR_IF_FALSE_STMT + - firstConditionalOperatorNo) { + firstConditionalOperatorNo = stmt.toString().replace(ArkIRTransformer.DUMMY_CONDITIONAL_OPERATOR_IF_TRUE_STMT, ''); + } else if (stmt.toString() === ArkIRTransformer.DUMMY_CONDITIONAL_OPERATOR_IF_FALSE_STMT + firstConditionalOperatorNo) { firstIfFalsePos = i; - } else if (stmt.toString() === ArkIRTransformer.DUMMY_CONDITIONAL_OPERATOR_END_STMT + - firstConditionalOperatorNo) { + } else if (stmt.toString() === ArkIRTransformer.DUMMY_CONDITIONAL_OPERATOR_END_STMT + firstConditionalOperatorNo) { firstEndPos = i; } } @@ -230,8 +221,7 @@ export class ConditionBuilder { return { firstIfTruePos, firstIfFalsePos, firstEndPos }; } - private removeUnnecessaryBlocksInConditionalOperator(bottomBlock: BasicBlock, - allBlocks: Set): BasicBlock[] { + private removeUnnecessaryBlocksInConditionalOperator(bottomBlock: BasicBlock, allBlocks: Set): BasicBlock[] { const firstStmtInBottom = bottomBlock.getStmts()[0]; if (!(firstStmtInBottom instanceof ArkAssignStmt)) { return [bottomBlock]; @@ -246,29 +236,27 @@ export class ConditionBuilder { const newPredecessors: BasicBlock[] = []; for (const predecessor of oldPredecessors) { predecessor.removeSuccessorBlock(bottomBlock); - newPredecessors.push( - ...this.replaceTempRecursively(predecessor, targetValue as Local, tempResultValue as Local, - allBlocks)); + newPredecessors.push(...this.replaceTempRecursively(predecessor, targetValue as Local, tempResultValue as Local, allBlocks)); } bottomBlock.remove(firstStmtInBottom); - if (bottomBlock.getStmts().length === 0) { // must be a new block without successors + if (bottomBlock.getStmts().length === 0) { + // must be a new block without successors allBlocks.delete(bottomBlock); return newPredecessors; } - oldPredecessors.forEach((oldPredecessor) => { + oldPredecessors.forEach(oldPredecessor => { bottomBlock.removePredecessorBlock(oldPredecessor); }); - newPredecessors.forEach((newPredecessor) => { + newPredecessors.forEach(newPredecessor => { bottomBlock.addPredecessorBlock(newPredecessor); newPredecessor.addSuccessorBlock(bottomBlock); }); return [bottomBlock]; } - private replaceTempRecursively(currBottomBlock: BasicBlock, targetLocal: Local, - tempResultLocal: Local, allBlocks: Set): BasicBlock[] { + private replaceTempRecursively(currBottomBlock: BasicBlock, targetLocal: Local, tempResultLocal: Local, allBlocks: Set): BasicBlock[] { const stmts = currBottomBlock.getStmts(); const stmtsCnt = stmts.length; let tempResultReassignStmt: Stmt | null = null; @@ -290,8 +278,7 @@ export class ConditionBuilder { const prevTempResultLocal = (tempResultReassignStmt as ArkAssignStmt).getRightOp() as Local; for (const predecessor of oldPredecessors) { predecessor.removeSuccessorBlock(currBottomBlock); - newPredecessors.push( - ...this.replaceTempRecursively(predecessor, targetLocal, prevTempResultLocal, allBlocks)); + newPredecessors.push(...this.replaceTempRecursively(predecessor, targetLocal, prevTempResultLocal, allBlocks)); } currBottomBlock.remove(tempResultReassignStmt); @@ -301,7 +288,7 @@ export class ConditionBuilder { allBlocks.delete(currBottomBlock); } else { currBottomBlock.getPredecessors().splice(0, oldPredecessors.length, ...newPredecessors); - newPredecessors.forEach((newPredecessor) => { + newPredecessors.forEach(newPredecessor => { newPredecessor.addSuccessorBlock(currBottomBlock); }); newBottomBlocks = [currBottomBlock]; @@ -311,4 +298,4 @@ export class ConditionBuilder { } return newBottomBlocks; } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/graph/builder/LoopBuilder.ts b/ets2panda/linter/arkanalyzer/src/core/graph/builder/LoopBuilder.ts index df6d7cbad7..f082fe773a 100644 --- a/ets2panda/linter/arkanalyzer/src/core/graph/builder/LoopBuilder.ts +++ b/ets2panda/linter/arkanalyzer/src/core/graph/builder/LoopBuilder.ts @@ -24,9 +24,12 @@ import { BlockBuilder } from './CfgBuilder'; * Builder for loop in CFG */ export class LoopBuilder { - public rebuildBlocksInLoop(blockBuilderToCfgBlock: Map, - blocksContainLoopCondition: Set, - basicBlockSet: Set, blockBuilders: BlockBuilder[]): void { + public rebuildBlocksInLoop( + blockBuilderToCfgBlock: Map, + blocksContainLoopCondition: Set, + basicBlockSet: Set, + blockBuilders: BlockBuilder[] + ): void { for (const blockBuilder of blocksContainLoopCondition) { if (!blockBuilderToCfgBlock.get(blockBuilder)) { continue; @@ -38,8 +41,7 @@ export class LoopBuilder { const stmtsCnt = stmts.length; const { ifStmtIdx, iteratorNextStmtIdx, dummyInitializerStmtIdx } = this.findIteratorIdx(stmts); if (iteratorNextStmtIdx !== -1 || dummyInitializerStmtIdx !== -1) { - const lastStmtIdxBeforeCondition = iteratorNextStmtIdx !== - -1 ? iteratorNextStmtIdx : dummyInitializerStmtIdx; + const lastStmtIdxBeforeCondition = iteratorNextStmtIdx !== -1 ? iteratorNextStmtIdx : dummyInitializerStmtIdx; const stmtsInsertBeforeCondition = stmts.slice(0, lastStmtIdxBeforeCondition); // If the loop body is empty, the loop conditional block should contain its own @@ -51,12 +53,17 @@ export class LoopBuilder { block.addPredecessorBlock(block); } - let prevBlockBuilderContainsLoop = this.doesPrevBlockBuilderContainLoop(blockBuilder, blockId, - blocksContainLoopCondition); + let prevBlockBuilderContainsLoop = this.doesPrevBlockBuilderContainLoop(blockBuilder, blockId, blocksContainLoopCondition); if (prevBlockBuilderContainsLoop) { // should create an extra block when previous block contains loop condition - this.insertBeforeConditionBlockBuilder(blockBuilderToCfgBlock, blockBuilder, - stmtsInsertBeforeCondition, false, basicBlockSet, blockBuilders); + this.insertBeforeConditionBlockBuilder( + blockBuilderToCfgBlock, + blockBuilder, + stmtsInsertBeforeCondition, + false, + basicBlockSet, + blockBuilders + ); } else { const blockBuilderBeforeCondition = blockBuilder.lasts[0]; const blockBeforeCondition = blockBuilderToCfgBlock.get(blockBuilderBeforeCondition) as BasicBlock; @@ -64,8 +71,17 @@ export class LoopBuilder { } if (dummyInitializerStmtIdx !== -1 && ifStmtIdx !== stmtsCnt - 1) { // put incrementor statements into block which reenters condition - this.adjustIncrementorStmts(stmts, ifStmtIdx, blockBuilder, blockId, blockBuilderToCfgBlock, - blocksContainLoopCondition, basicBlockSet, emptyLoopBody, blockBuilders); + this.adjustIncrementorStmts( + stmts, + ifStmtIdx, + blockBuilder, + blockId, + blockBuilderToCfgBlock, + blocksContainLoopCondition, + basicBlockSet, + emptyLoopBody, + blockBuilders + ); } else if (iteratorNextStmtIdx !== -1) { // put statements which get value of iterator into block after condition const blockBuilderAfterCondition = blockBuilder.nexts[0]; @@ -74,16 +90,14 @@ export class LoopBuilder { blockAfterCondition?.getStmts().splice(0, 0, ...stmtsAfterCondition); } // remove statements which should not in condition - const firstStmtIdxInCondition = iteratorNextStmtIdx !== - -1 ? iteratorNextStmtIdx : dummyInitializerStmtIdx + 1; + const firstStmtIdxInCondition = iteratorNextStmtIdx !== -1 ? iteratorNextStmtIdx : dummyInitializerStmtIdx + 1; stmts.splice(0, firstStmtIdxInCondition); stmts.splice(ifStmtIdx - firstStmtIdxInCondition + 1); } } } - private doesPrevBlockBuilderContainLoop(currBlockBuilder: BlockBuilder, currBlockId: number, - blocksContainLoopCondition: Set): boolean { + private doesPrevBlockBuilderContainLoop(currBlockBuilder: BlockBuilder, currBlockId: number, blocksContainLoopCondition: Set): boolean { let prevBlockBuilderContainsLoop = false; for (const prevBlockBuilder of currBlockBuilder.lasts) { if (prevBlockBuilder.id < currBlockId && blocksContainLoopCondition.has(prevBlockBuilder)) { @@ -100,49 +114,68 @@ export class LoopBuilder { stmtsInsertBeforeCondition: Stmt[], collectReenter: Boolean, basicBlockSet: Set, - blockBuilders: BlockBuilder[], + blockBuilders: BlockBuilder[] ): void { if (stmtsInsertBeforeCondition.length === 0) { return; } const blockId = conditionBlockBuilder.id; const block = this.getBlockFromMap(blockBuilderToCfgBlock, conditionBlockBuilder); - const { - blockBuildersBeforeCondition, blocksBeforeCondition, blockBuildersReenterCondition, blocksReenterCondition, - } = this.collectBlocksBeforeAndReenter(blockBuilderToCfgBlock, conditionBlockBuilder, blockId); + const { blockBuildersBeforeCondition, blocksBeforeCondition, blockBuildersReenterCondition, blocksReenterCondition } = + this.collectBlocksBeforeAndReenter(blockBuilderToCfgBlock, conditionBlockBuilder, blockId); - const { - collectedBlockBuilders, collectedBlocks, - } = this.getCollectedBlocks(collectReenter, blockBuildersBeforeCondition, blocksBeforeCondition, - blockBuildersReenterCondition, blocksReenterCondition); + const { collectedBlockBuilders, collectedBlocks } = this.getCollectedBlocks( + collectReenter, + blockBuildersBeforeCondition, + blocksBeforeCondition, + blockBuildersReenterCondition, + blocksReenterCondition + ); const { blockBuilderInsertBeforeCondition, blockInsertBeforeCondition } = this.createAndLinkBlocks( - collectedBlockBuilders, collectedBlocks, conditionBlockBuilder, stmtsInsertBeforeCondition, block); + collectedBlockBuilders, + collectedBlocks, + conditionBlockBuilder, + stmtsInsertBeforeCondition, + block + ); - this.updatePredecessors(collectedBlockBuilders, blockBuilderToCfgBlock, conditionBlockBuilder, - blockBuilderInsertBeforeCondition, blockInsertBeforeCondition); + this.updatePredecessors( + collectedBlockBuilders, + blockBuilderToCfgBlock, + conditionBlockBuilder, + blockBuilderInsertBeforeCondition, + blockInsertBeforeCondition + ); const { newPrevBlockBuildersBeforeCondition, newPrevBlocksBeforeCondition } = this.getNewPrevBlocks( - collectReenter, blockBuildersBeforeCondition, blocksBeforeCondition, blockBuilderInsertBeforeCondition, - blockInsertBeforeCondition, blockBuildersReenterCondition, blocksReenterCondition); + collectReenter, + blockBuildersBeforeCondition, + blocksBeforeCondition, + blockBuilderInsertBeforeCondition, + blockInsertBeforeCondition, + blockBuildersReenterCondition, + blocksReenterCondition + ); this.updateConditionBlockBuilder(conditionBlockBuilder, newPrevBlockBuildersBeforeCondition, block, newPrevBlocksBeforeCondition); this.finalizeInsertion(blockBuilderInsertBeforeCondition, blockInsertBeforeCondition, basicBlockSet, blockBuilderToCfgBlock, blockBuilders); } - private getBlockFromMap(blockBuilderToCfgBlock: Map, - conditionBlockBuilder: BlockBuilder): BasicBlock { + private getBlockFromMap(blockBuilderToCfgBlock: Map, conditionBlockBuilder: BlockBuilder): BasicBlock { return blockBuilderToCfgBlock.get(conditionBlockBuilder) as BasicBlock; } private collectBlocksBeforeAndReenter( blockBuilderToCfgBlock: Map, conditionBlockBuilder: BlockBuilder, - blockId: number, + blockId: number ): { - blockBuildersBeforeCondition: BlockBuilder[], blocksBeforeCondition: BasicBlock[], - blockBuildersReenterCondition: BlockBuilder[], blocksReenterCondition: BasicBlock[] + blockBuildersBeforeCondition: BlockBuilder[]; + blocksBeforeCondition: BasicBlock[]; + blockBuildersReenterCondition: BlockBuilder[]; + blocksReenterCondition: BasicBlock[]; } { const blockBuildersBeforeCondition: BlockBuilder[] = []; const blocksBeforeCondition: BasicBlock[] = []; @@ -159,7 +192,10 @@ export class LoopBuilder { } } return { - blockBuildersBeforeCondition, blocksBeforeCondition, blockBuildersReenterCondition, blocksReenterCondition, + blockBuildersBeforeCondition, + blocksBeforeCondition, + blockBuildersReenterCondition, + blocksReenterCondition, }; } @@ -168,8 +204,8 @@ export class LoopBuilder { blockBuildersBeforeCondition: BlockBuilder[], blocksBeforeCondition: BasicBlock[], blockBuildersReenterCondition: BlockBuilder[], - blocksReenterCondition: BasicBlock[], - ): { collectedBlockBuilders: BlockBuilder[], collectedBlocks: BasicBlock[] } { + blocksReenterCondition: BasicBlock[] + ): { collectedBlockBuilders: BlockBuilder[]; collectedBlocks: BasicBlock[] } { let collectedBlockBuilders: BlockBuilder[] = []; let collectedBlocks: BasicBlock[] = []; if (collectReenter) { @@ -187,8 +223,11 @@ export class LoopBuilder { collectedBlocks: BasicBlock[], conditionBlockBuilder: BlockBuilder, stmtsInsertBeforeCondition: Stmt[], - block: BasicBlock, - ): { blockBuilderInsertBeforeCondition: BlockBuilder, blockInsertBeforeCondition: BasicBlock } { + block: BasicBlock + ): { + blockBuilderInsertBeforeCondition: BlockBuilder; + blockInsertBeforeCondition: BasicBlock; + } { const blockBuilderInsertBeforeCondition = new BlockBuilder(-1, []); blockBuilderInsertBeforeCondition.lasts.push(...collectedBlockBuilders); blockBuilderInsertBeforeCondition.nexts.push(conditionBlockBuilder); @@ -204,7 +243,7 @@ export class LoopBuilder { blockBuilderToCfgBlock: Map, conditionBlockBuilder: BlockBuilder, blockBuilderInsertBeforeCondition: BlockBuilder, - blockInsertBeforeCondition: BasicBlock, + blockInsertBeforeCondition: BasicBlock ): void { for (const prevBlockBuilder of collectedBlockBuilders) { const prevBlock = blockBuilderToCfgBlock.get(prevBlockBuilder) as BasicBlock; @@ -225,8 +264,11 @@ export class LoopBuilder { blockBuilderInsertBeforeCondition: BlockBuilder, blockInsertBeforeCondition: BasicBlock, blockBuildersReenterCondition: BlockBuilder[], - blocksReenterCondition: BasicBlock[], - ): { newPrevBlockBuildersBeforeCondition: BlockBuilder[], newPrevBlocksBeforeCondition: BasicBlock[] } { + blocksReenterCondition: BasicBlock[] + ): { + newPrevBlockBuildersBeforeCondition: BlockBuilder[]; + newPrevBlocksBeforeCondition: BasicBlock[]; + } { let newPrevBlockBuildersBeforeCondition: BlockBuilder[] = []; let newPrevBlocksBeforeCondition: BasicBlock[] = []; if (collectReenter) { @@ -236,14 +278,17 @@ export class LoopBuilder { newPrevBlockBuildersBeforeCondition = [blockBuilderInsertBeforeCondition, ...blockBuildersReenterCondition]; newPrevBlocksBeforeCondition = [blockInsertBeforeCondition, ...blocksReenterCondition]; } - return { newPrevBlockBuildersBeforeCondition, newPrevBlocksBeforeCondition }; + return { + newPrevBlockBuildersBeforeCondition, + newPrevBlocksBeforeCondition, + }; } private updateConditionBlockBuilder( conditionBlockBuilder: BlockBuilder, newPrevBlockBuildersBeforeCondition: BlockBuilder[], block: BasicBlock, - newPrevBlocksBeforeCondition: BasicBlock[], + newPrevBlocksBeforeCondition: BasicBlock[] ): void { conditionBlockBuilder.lasts = newPrevBlockBuildersBeforeCondition; const predecessorsCnt = block.getPredecessors().length; @@ -255,7 +300,7 @@ export class LoopBuilder { blockInsertBeforeCondition: BasicBlock, basicBlockSet: Set, blockBuilderToCfgBlock: Map, - blockBuilders: BlockBuilder[], + blockBuilders: BlockBuilder[] ): void { blockBuilders.push(blockBuilderInsertBeforeCondition); basicBlockSet.add(blockInsertBeforeCondition); @@ -263,7 +308,9 @@ export class LoopBuilder { } private findIteratorIdx(stmts: Stmt[]): { - ifStmtIdx: number, iteratorNextStmtIdx: number, dummyInitializerStmtIdx: number + ifStmtIdx: number; + iteratorNextStmtIdx: number; + dummyInitializerStmtIdx: number; } { let ifStmtIdx = -1; let iteratorNextStmtIdx = -1; @@ -273,8 +320,7 @@ export class LoopBuilder { const stmt = stmts[i]; if (stmt instanceof ArkAssignStmt && stmt.getRightOp() instanceof AbstractInvokeExpr) { const invokeExpr = stmt.getRightOp() as AbstractInvokeExpr; - if (invokeExpr.getMethodSignature().getMethodSubSignature() - .getMethodName() === Builtin.ITERATOR_NEXT) { + if (invokeExpr.getMethodSignature().getMethodSubSignature().getMethodName() === Builtin.ITERATOR_NEXT) { iteratorNextStmtIdx = i; continue; } @@ -295,10 +341,17 @@ export class LoopBuilder { }; } - private adjustIncrementorStmts(stmts: Stmt[], ifStmtIdx: number, currBlockBuilder: BlockBuilder, - currBlockId: number, blockBuilderToCfgBlock: Map, - blocksContainLoopCondition: Set, basicBlockSet: Set, - emptyLoopBody: boolean, blockBuilders: BlockBuilder[]): void { + private adjustIncrementorStmts( + stmts: Stmt[], + ifStmtIdx: number, + currBlockBuilder: BlockBuilder, + currBlockId: number, + blockBuilderToCfgBlock: Map, + blocksContainLoopCondition: Set, + basicBlockSet: Set, + emptyLoopBody: boolean, + blockBuilders: BlockBuilder[] + ): void { const stmtsReenterCondition = stmts.slice(ifStmtIdx + 1); if (emptyLoopBody) { const incrementorBlockBuilder = new BlockBuilder(-1, []); @@ -327,16 +380,13 @@ export class LoopBuilder { } } - if (blockBuildersReenterCondition.length > 1 || blocksContainLoopCondition.has( - blockBuildersReenterCondition[0])) { + if (blockBuildersReenterCondition.length > 1 || blocksContainLoopCondition.has(blockBuildersReenterCondition[0])) { // put incrementor statements into an extra block - this.insertBeforeConditionBlockBuilder(blockBuilderToCfgBlock, currBlockBuilder, - stmtsReenterCondition, true, basicBlockSet, blockBuilders); + this.insertBeforeConditionBlockBuilder(blockBuilderToCfgBlock, currBlockBuilder, stmtsReenterCondition, true, basicBlockSet, blockBuilders); } else { // put incrementor statements into prev reenter block - const blockReenterCondition = blockBuilderToCfgBlock.get( - blockBuildersReenterCondition[0]) as BasicBlock; + const blockReenterCondition = blockBuilderToCfgBlock.get(blockBuildersReenterCondition[0]) as BasicBlock; stmtsReenterCondition.forEach(stmt => blockReenterCondition?.getStmts().push(stmt)); } } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/graph/builder/SwitchBuilder.ts b/ets2panda/linter/arkanalyzer/src/core/graph/builder/SwitchBuilder.ts index 60a231c2c2..3fa74eacf9 100644 --- a/ets2panda/linter/arkanalyzer/src/core/graph/builder/SwitchBuilder.ts +++ b/ets2panda/linter/arkanalyzer/src/core/graph/builder/SwitchBuilder.ts @@ -25,16 +25,18 @@ const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'SwitchBuilder'); * Builder for switch statement in CFG */ export class SwitchBuilder { - public buildSwitch(blockBuilderToCfgBlock: Map, - blockBuildersContainSwitch: BlockBuilder[], - valueAndStmtsOfSwitchAndCasesAll: ValueAndStmts[][], arkIRTransformer: ArkIRTransformer, - basicBlockSet: Set): void { + public buildSwitch( + blockBuilderToCfgBlock: Map, + blockBuildersContainSwitch: BlockBuilder[], + valueAndStmtsOfSwitchAndCasesAll: ValueAndStmts[][], + arkIRTransformer: ArkIRTransformer, + basicBlockSet: Set + ): void { for (let i = 0; i < blockBuildersContainSwitch.length; i++) { const blockBuilderContainSwitch = blockBuildersContainSwitch[i]; if (!blockBuilderToCfgBlock.has(blockBuilderContainSwitch)) { - logger.error( - `can't find basicBlock corresponding to the blockBuilder.`); + logger.error(`can't find basicBlock corresponding to the blockBuilder.`); continue; } @@ -50,7 +52,8 @@ export class SwitchBuilder { const cases = switchStmtBuilder.cases; let nonEmptyCaseCnt = 0; for (const currCase of cases) { - if (currCase.stmt.block) { // there are stmts after this case + if (currCase.stmt.block) { + // there are stmts after this case nonEmptyCaseCnt++; } } @@ -59,16 +62,24 @@ export class SwitchBuilder { } const caseCnt = cases.length; - const caseIfBlocks = this.generateIfBlocksForCases(valueAndStmtsOfSwitchAndCasesAll[i], caseCnt, - blockContainSwitch, basicBlockSet, arkIRTransformer); - this.linkIfBlockAndCaseBlock(blockContainSwitch, caseIfBlocks, switchStmtBuilder, - blockBuilderToCfgBlock); + const caseIfBlocks = this.generateIfBlocksForCases( + valueAndStmtsOfSwitchAndCasesAll[i], + caseCnt, + blockContainSwitch, + basicBlockSet, + arkIRTransformer + ); + this.linkIfBlockAndCaseBlock(blockContainSwitch, caseIfBlocks, switchStmtBuilder, blockBuilderToCfgBlock); } } - private generateIfBlocksForCases(valueAndStmtsOfSwitchAndCases: ValueAndStmts[], caseCnt: number, - blockContainSwitch: BasicBlock, basicBlockSet: Set, - arkIRTransformer: ArkIRTransformer): BasicBlock[] { + private generateIfBlocksForCases( + valueAndStmtsOfSwitchAndCases: ValueAndStmts[], + caseCnt: number, + blockContainSwitch: BasicBlock, + basicBlockSet: Set, + arkIRTransformer: ArkIRTransformer + ): BasicBlock[] { const valueAndStmtsOfSwitch = valueAndStmtsOfSwitchAndCases[0]; const valueOfSwitch = valueAndStmtsOfSwitch.value; const caseIfBlocks: BasicBlock[] = []; @@ -89,9 +100,12 @@ export class SwitchBuilder { caseStmts.forEach((stmt: Stmt) => { caseIfBlock.addStmt(stmt); }); - const caseIfStmts = arkIRTransformer.generateIfStmtForValues(valueOfSwitch, - valueAndStmtsOfSwitch.valueOriginalPositions, caseValue, - caseValueAndStmts.valueOriginalPositions); + const caseIfStmts = arkIRTransformer.generateIfStmtForValues( + valueOfSwitch, + valueAndStmtsOfSwitch.valueOriginalPositions, + caseValue, + caseValueAndStmts.valueOriginalPositions + ); caseIfStmts.forEach((stmt: Stmt) => { caseIfBlock.addStmt(stmt); }); @@ -99,9 +113,12 @@ export class SwitchBuilder { return caseIfBlocks; } - private linkIfBlockAndCaseBlock(blockContainSwitch: BasicBlock, caseIfBlocks: BasicBlock[], - switchStmtBuilder: SwitchStatementBuilder, - blockBuilderToCfgBlock: Map): boolean { + private linkIfBlockAndCaseBlock( + blockContainSwitch: BasicBlock, + caseIfBlocks: BasicBlock[], + switchStmtBuilder: SwitchStatementBuilder, + blockBuilderToCfgBlock: Map + ): boolean { const successorsOfBlockContainSwitch = Array.from(blockContainSwitch.getSuccessors()); const expectedSuccessorsOfCaseIfBlock: BasicBlock[] = []; const defaultStmtBuilder = switchStmtBuilder.default; @@ -121,13 +138,14 @@ export class SwitchBuilder { const currCase = switchStmtBuilder.cases[i]; if (currCase.stmt.block) { expectedSuccessorsOfCaseIfBlock.push(...successorsOfBlockContainSwitch.splice(-1, 1)); - } else { // if there are no stmts after this case, reuse the successor of the next case + } else { + // if there are no stmts after this case, reuse the successor of the next case expectedSuccessorsOfCaseIfBlock.push(...expectedSuccessorsOfCaseIfBlock.slice(-1)); } } expectedSuccessorsOfCaseIfBlock.reverse(); - blockContainSwitch.getSuccessors().forEach((successor) => { + blockContainSwitch.getSuccessors().forEach(successor => { successor.getPredecessors().splice(0, 1); }); blockContainSwitch.getSuccessors().splice(0); @@ -135,7 +153,8 @@ export class SwitchBuilder { const caseIfBlock = caseIfBlocks[j]; caseIfBlock.addSuccessorBlock(expectedSuccessorsOfCaseIfBlock[j]); expectedSuccessorsOfCaseIfBlock[j].addPredecessorBlock(caseIfBlock); - if (j === caseCnt - 1) { // the false branch of last case should be default or block after switch statement + if (j === caseCnt - 1) { + // the false branch of last case should be default or block after switch statement caseIfBlock.addSuccessorBlock(expectedSuccessorsOfCaseIfBlock[j + 1]); expectedSuccessorsOfCaseIfBlock[j + 1].addPredecessorBlock(caseIfBlock); } else { @@ -145,4 +164,4 @@ export class SwitchBuilder { } return true; } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/graph/builder/TrapBuilder.ts b/ets2panda/linter/arkanalyzer/src/core/graph/builder/TrapBuilder.ts index fdb4689601..160df9fdc0 100644 --- a/ets2panda/linter/arkanalyzer/src/core/graph/builder/TrapBuilder.ts +++ b/ets2panda/linter/arkanalyzer/src/core/graph/builder/TrapBuilder.ts @@ -19,15 +19,7 @@ import { Trap } from '../../base/Trap'; import { ArkCaughtExceptionRef } from '../../base/Ref'; import { UnknownType } from '../../base/Type'; import { FullPosition } from '../../base/Position'; -import { - ArkAssignStmt, - ArkIfStmt, - ArkInvokeStmt, - ArkReturnStmt, - ArkReturnVoidStmt, - ArkThrowStmt, - Stmt, -} from '../../base/Stmt'; +import { ArkAssignStmt, ArkIfStmt, ArkInvokeStmt, ArkReturnStmt, ArkReturnVoidStmt, ArkThrowStmt, Stmt } from '../../base/Stmt'; import { BlockBuilder, TryStatementBuilder } from './CfgBuilder'; import Logger, { LOG_MODULE_TYPE } from '../../../utils/logger'; @@ -37,8 +29,12 @@ const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'TrapBuilder'); * Builder for traps from try...catch */ export class TrapBuilder { - public buildTraps(blockBuilderToCfgBlock: Map, blockBuildersBeforeTry: Set, - arkIRTransformer: ArkIRTransformer, basicBlockSet: Set): Trap[] { + public buildTraps( + blockBuilderToCfgBlock: Map, + blockBuildersBeforeTry: Set, + arkIRTransformer: ArkIRTransformer, + basicBlockSet: Set + ): Trap[] { const traps: Trap[] = []; for (const blockBuilderBeforeTry of blockBuildersBeforeTry) { if (blockBuilderBeforeTry.nexts.length === 0) { @@ -53,14 +49,16 @@ export class TrapBuilder { logger.error(`can't find finally block or dummy finally block.`); continue; } - const { bfsBlocks: tryBfsBlocks, tailBlocks: tryTailBlocks } = this.getAllBlocksBFS(blockBuilderToCfgBlock, - blockBuilderContainTry, finallyBlockBuilder); + const { bfsBlocks: tryBfsBlocks, tailBlocks: tryTailBlocks } = this.getAllBlocksBFS( + blockBuilderToCfgBlock, + blockBuilderContainTry, + finallyBlockBuilder + ); let catchBfsBlocks: BasicBlock[] = []; let catchTailBlocks: BasicBlock[] = []; const catchBlockBuilder = tryStmtBuilder.catchStatement?.block; if (catchBlockBuilder) { - ({ bfsBlocks: catchBfsBlocks, tailBlocks: catchTailBlocks } = this.getAllBlocksBFS( - blockBuilderToCfgBlock, catchBlockBuilder)); + ({ bfsBlocks: catchBfsBlocks, tailBlocks: catchTailBlocks } = this.getAllBlocksBFS(blockBuilderToCfgBlock, catchBlockBuilder)); } const finallyStmts = finallyBlockBuilder.stmts; const blockBuilderAfterFinally = tryStmtBuilder.afterFinal?.block; @@ -68,27 +66,49 @@ export class TrapBuilder { logger.error(`can't find block after try...catch.`); continue; } - if (finallyStmts.length === 1 && finallyStmts[0].code === 'dummyFinally') { // no finally block - const trapsIfNoFinally = this.buildTrapsIfNoFinally(tryBfsBlocks, tryTailBlocks, catchBfsBlocks, + if (finallyStmts.length === 1 && finallyStmts[0].code === 'dummyFinally') { + // no finally block + const trapsIfNoFinally = this.buildTrapsIfNoFinally( + tryBfsBlocks, + tryTailBlocks, + catchBfsBlocks, catchTailBlocks, - finallyBlockBuilder, blockBuilderAfterFinally, basicBlockSet, blockBuilderToCfgBlock); + finallyBlockBuilder, + blockBuilderAfterFinally, + basicBlockSet, + blockBuilderToCfgBlock + ); if (trapsIfNoFinally) { traps.push(...trapsIfNoFinally); } } else { - const trapsIfFinallyExist = this.buildTrapsIfFinallyExist(tryBfsBlocks, tryTailBlocks, catchBfsBlocks, - catchTailBlocks, finallyBlockBuilder, blockBuilderAfterFinally, basicBlockSet, arkIRTransformer, - blockBuilderToCfgBlock); + const trapsIfFinallyExist = this.buildTrapsIfFinallyExist( + tryBfsBlocks, + tryTailBlocks, + catchBfsBlocks, + catchTailBlocks, + finallyBlockBuilder, + blockBuilderAfterFinally, + basicBlockSet, + arkIRTransformer, + blockBuilderToCfgBlock + ); traps.push(...trapsIfFinallyExist); } } return traps; } - private buildTrapsIfNoFinally(tryBfsBlocks: BasicBlock[], tryTailBlocks: BasicBlock[], catchBfsBlocks: BasicBlock[], - catchTailBlocks: BasicBlock[], finallyBlockBuilder: BlockBuilder, - blockBuilderAfterFinally: BlockBuilder, basicBlockSet: Set, - blockBuilderToCfgBlock: Map): Trap[] | null { + private buildTrapsIfNoFinally( + tryBfsBlocks: BasicBlock[], + tryTailBlocks: BasicBlock[], + catchBfsBlocks: BasicBlock[], + catchTailBlocks: BasicBlock[], + finallyBlockBuilder: BlockBuilder, + blockBuilderAfterFinally: BlockBuilder, + basicBlockSet: Set, + blockBuilderToCfgBlock: Map + ): Trap[] | null { if (catchBfsBlocks.length === 0) { logger.error(`catch block expected.`); return null; @@ -130,16 +150,23 @@ export class TrapBuilder { return [new Trap(tryBfsBlocks, catchBfsBlocks)]; } - private buildTrapsIfFinallyExist(tryBfsBlocks: BasicBlock[], tryTailBlocks: BasicBlock[], - catchBfsBlocks: BasicBlock[], catchTailBlocks: BasicBlock[], - finallyBlockBuilder: BlockBuilder, blockBuilderAfterFinally: BlockBuilder, - basicBlockSet: Set, arkIRTransformer: ArkIRTransformer, - blockBuilderToCfgBlock: Map): Trap[] { + private buildTrapsIfFinallyExist( + tryBfsBlocks: BasicBlock[], + tryTailBlocks: BasicBlock[], + catchBfsBlocks: BasicBlock[], + catchTailBlocks: BasicBlock[], + finallyBlockBuilder: BlockBuilder, + blockBuilderAfterFinally: BlockBuilder, + basicBlockSet: Set, + arkIRTransformer: ArkIRTransformer, + blockBuilderToCfgBlock: Map + ): Trap[] { const { bfsBlocks: finallyBfsBlocks, tailBlocks: finallyTailBlocks } = this.getAllBlocksBFS( blockBuilderToCfgBlock, - finallyBlockBuilder, blockBuilderAfterFinally); - const copyFinallyBfsBlocks = this.copyFinallyBlocks(finallyBfsBlocks, finallyTailBlocks, basicBlockSet, - arkIRTransformer, blockBuilderToCfgBlock); + finallyBlockBuilder, + blockBuilderAfterFinally + ); + const copyFinallyBfsBlocks = this.copyFinallyBlocks(finallyBfsBlocks, finallyTailBlocks, basicBlockSet, arkIRTransformer, blockBuilderToCfgBlock); const traps: Trap[] = []; if (catchBfsBlocks.length !== 0) { for (const catchTailBlock of catchTailBlocks) { @@ -166,8 +193,11 @@ export class TrapBuilder { return traps; } - private getAllBlocksBFS(blockBuilderToCfgBlock: Map, startBlockBuilder: BlockBuilder, - endBlockBuilder?: BlockBuilder): { bfsBlocks: BasicBlock[], tailBlocks: BasicBlock[] } { + private getAllBlocksBFS( + blockBuilderToCfgBlock: Map, + startBlockBuilder: BlockBuilder, + endBlockBuilder?: BlockBuilder + ): { bfsBlocks: BasicBlock[]; tailBlocks: BasicBlock[] } { const bfsBlocks: BasicBlock[] = []; const tailBlocks: BasicBlock[] = []; const queue: BlockBuilder[] = []; @@ -187,7 +217,7 @@ export class TrapBuilder { bfsBlocks.push(currBlock); const childList = currBlockBuilder.nexts; - if (childList.length === 0 || (childList.length !== 0 && (childList[0] === endBlockBuilder))) { + if (childList.length === 0 || (childList.length !== 0 && childList[0] === endBlockBuilder)) { if (childList[0] === endBlockBuilder) { tailBlocks.push(currBlock); continue; @@ -202,21 +232,21 @@ export class TrapBuilder { return { bfsBlocks, tailBlocks }; } - private copyFinallyBlocks(finallyBfsBlocks: BasicBlock[], finallyTailBlocks: BasicBlock[], - basicBlockSet: Set, arkIRTransformer: ArkIRTransformer, - blockBuilderToCfgBlock: Map): BasicBlock[] { + private copyFinallyBlocks( + finallyBfsBlocks: BasicBlock[], + finallyTailBlocks: BasicBlock[], + basicBlockSet: Set, + arkIRTransformer: ArkIRTransformer, + blockBuilderToCfgBlock: Map + ): BasicBlock[] { const copyFinallyBfsBlocks = this.copyBlocks(finallyBfsBlocks); const caughtExceptionRef = new ArkCaughtExceptionRef(UnknownType.getInstance()); - const { - value: exceptionValue, - stmts: exceptionAssignStmts, - } = arkIRTransformer.generateAssignStmtForValue(caughtExceptionRef, [FullPosition.DEFAULT]); + const { value: exceptionValue, stmts: exceptionAssignStmts } = arkIRTransformer.generateAssignStmtForValue(caughtExceptionRef, [FullPosition.DEFAULT]); copyFinallyBfsBlocks[0].addHead(exceptionAssignStmts); const finallyPredecessorsCnt = copyFinallyBfsBlocks[0].getPredecessors().length; copyFinallyBfsBlocks[0].getPredecessors().splice(0, finallyPredecessorsCnt); const throwStmt = new ArkThrowStmt(exceptionValue); - let copyFinallyTailBlocks = copyFinallyBfsBlocks.splice( - copyFinallyBfsBlocks.length - finallyTailBlocks.length, finallyTailBlocks.length); + let copyFinallyTailBlocks = copyFinallyBfsBlocks.splice(copyFinallyBfsBlocks.length - finallyTailBlocks.length, finallyTailBlocks.length); copyFinallyTailBlocks.forEach((copyFinallyTailBlock: BasicBlock) => { const successorsCnt = copyFinallyTailBlock.getSuccessors().length; copyFinallyTailBlock.getSuccessors().splice(0, successorsCnt); @@ -278,4 +308,4 @@ export class TrapBuilder { } return null; } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/graph/builder/ViewTreeBuilder.ts b/ets2panda/linter/arkanalyzer/src/core/graph/builder/ViewTreeBuilder.ts index a0c37d94bb..bf8482f4c9 100644 --- a/ets2panda/linter/arkanalyzer/src/core/graph/builder/ViewTreeBuilder.ts +++ b/ets2panda/linter/arkanalyzer/src/core/graph/builder/ViewTreeBuilder.ts @@ -81,7 +81,7 @@ function parseObjectLiteral(objectLiteralCls: ArkClass | null, scene: Scene): Ob if (objectLiteralCls?.getCategory() !== ClassCategory.OBJECT) { return map; } - objectLiteralCls?.getFields().forEach((field) => { + objectLiteralCls?.getFields().forEach(field => { let stmts = field.getInitializer(); if (stmts.length === 0) { return; @@ -169,11 +169,7 @@ class StateValuesUtils { return uses; } - private parseMethodUsesStateValues( - methodSignature: MethodSignature, - uses: Set, - visitor: Set = new Set() - ): void { + private parseMethodUsesStateValues(methodSignature: MethodSignature, uses: Set, visitor: Set = new Set()): void { if (visitor.has(methodSignature)) { return; } @@ -332,14 +328,12 @@ class ViewTreeNodeImpl implements ViewTreeNode { this.children.push(child as ViewTreeNodeImpl); } } else { - logger.error( - `ViewTree->changeBuilderParam2BuilderNode ${builder.getSignature().toString()} @Builder viewtree fail.` - ); + logger.error(`ViewTree->changeBuilderParam2BuilderNode ${builder.getSignature().toString()} @Builder viewtree fail.`); } } public hasBuilderParam(): boolean { - return this.walk((item) => { + return this.walk(item => { return (item as ViewTreeNodeImpl).isBuilderParam(); }); } @@ -406,11 +400,7 @@ class ViewTreeNodeImpl implements ViewTreeNode { } } - private getBindValues( - local: Local, - relationValues: (Constant | ArkInstanceFieldRef | MethodSignature)[], - visitor: Set = new Set() - ): void { + private getBindValues(local: Local, relationValues: (Constant | ArkInstanceFieldRef | MethodSignature)[], visitor: Set = new Set()): void { if (visitor.has(local)) { return; } @@ -435,10 +425,8 @@ class ViewTreeNodeImpl implements ViewTreeNode { } public parseStateValues(tree: ViewTreeImpl, stmt: Stmt): void { - let stateValues: Set = StateValuesUtils.getInstance( - tree.getDeclaringArkClass() - ).parseStmtUsesStateValues(stmt); - stateValues.forEach((field) => { + let stateValues: Set = StateValuesUtils.getInstance(tree.getDeclaringArkClass()).parseStmtUsesStateValues(stmt); + stateValues.forEach(field => { this.stateValues.add(field); tree.addStateValue(field, this); }, this); @@ -456,7 +444,7 @@ class TreeNodeStack { /** * @internal */ - public push(node: ViewTreeNodeImpl) { + public push(node: ViewTreeNodeImpl): void { let parent = this.getParent(); node.parent = parent; this.stack.push(node); @@ -470,7 +458,7 @@ class TreeNodeStack { /** * @internal */ - public pop() { + public pop(): void { this.stack.pop(); } @@ -614,7 +602,7 @@ export class ViewTreeImpl extends TreeNodeStack implements ViewTree { /** * @internal */ - public addStateValue(field: ArkField, node: ViewTreeNode) { + public addStateValue(field: ArkField, node: ViewTreeNode): void { if (!this.stateValues.has(field)) { this.stateValues.set(field, new Set()); } @@ -682,7 +670,7 @@ export class ViewTreeImpl extends TreeNodeStack implements ViewTree { this.getDeclaringArkClass() .getDeclaringArkNamespace() ?.getAllMethodsUnderThisNamespace() - .forEach((value) => { + .forEach(value => { if (value.getName() === name) { method = value; } @@ -694,8 +682,8 @@ export class ViewTreeImpl extends TreeNodeStack implements ViewTree { this.getDeclaringArkClass() .getDeclaringArkFile() .getAllNamespacesUnderThisFile() - .forEach((namespace) => { - namespace.getAllMethodsUnderThisNamespace().forEach((value) => { + .forEach(namespace => { + namespace.getAllMethodsUnderThisNamespace().forEach(value => { if (value.getName() === name) { method = value; } @@ -761,20 +749,14 @@ export class ViewTreeImpl extends TreeNodeStack implements ViewTree { /** * @internal */ - private addCustomComponentNode( - cls: ArkClass, - arg: Value | undefined, - builder: ArkMethod | undefined - ): ViewTreeNodeImpl { + private addCustomComponentNode(cls: ArkClass, arg: Value | undefined, builder: ArkMethod | undefined): ViewTreeNodeImpl { let node = ViewTreeNodeImpl.createCustomComponent(); node.signature = cls.getSignature(); node.classSignature = node.signature; node.stateValuesTransfer = this.parseObjectLiteralExpr(cls, arg, builder); if (arg instanceof Local && arg.getType()) { - let stateValues = StateValuesUtils.getInstance(this.getDeclaringArkClass()).parseObjectUsedStateValues( - arg.getType() - ); - stateValues.forEach((field) => { + let stateValues = StateValuesUtils.getInstance(this.getDeclaringArkClass()).parseObjectUsedStateValues(arg.getType()); + stateValues.forEach(field => { node.stateValues.add(field); this.addStateValue(field, node); }); @@ -797,7 +779,7 @@ export class ViewTreeImpl extends TreeNodeStack implements ViewTree { private cloneBuilderParamNode(node: ViewTreeNodeImpl, root: ViewTreeNodeImpl): ViewTreeNodeImpl { root = root.clone(node); if (node.stateValuesTransfer) { - root.walk((item) => { + root.walk(item => { let child = item as ViewTreeNodeImpl; if (!child.isBuilderParam() || !child.builderParam) { return false; @@ -838,7 +820,7 @@ export class ViewTreeImpl extends TreeNodeStack implements ViewTree { private findMethodInvokeBuilderMethod(method: ArkMethod): ArkMethod | undefined { let stmts = method.getCfg()?.getStmts(); if (!stmts) { - return; + return undefined; } for (const stmt of stmts) { let expr: AbstractInvokeExpr | undefined; @@ -861,6 +843,7 @@ export class ViewTreeImpl extends TreeNodeStack implements ViewTree { return method; } } + return undefined; } private parseFieldInObjectLiteral(field: ArkField, cls: ArkClass, transferMap: Map): void { @@ -899,22 +882,18 @@ export class ViewTreeImpl extends TreeNodeStack implements ViewTree { } } - private parseObjectLiteralExpr( - cls: ArkClass, - object: Value | undefined, - builder: ArkMethod | undefined - ): Map | undefined { + private parseObjectLiteralExpr(cls: ArkClass, object: Value | undefined, builder: ArkMethod | undefined): Map | undefined { let transferMap: Map = new Map(); if (object instanceof Local && object.getType() instanceof ClassType) { let anonymousSig = (object.getType() as ClassType).getClassSignature(); let anonymous = this.findClass(anonymousSig); - anonymous?.getFields().forEach((field) => { + anonymous?.getFields().forEach(field => { this.parseFieldInObjectLiteral(field, cls, transferMap); }); } // If the builder exists, there will be a unique BuilderParam if (builder) { - cls.getFields().forEach((value) => { + cls.getFields().forEach(value => { if (value.hasBuilderParamDecorator()) { transferMap.set(value, builder); } @@ -922,19 +901,15 @@ export class ViewTreeImpl extends TreeNodeStack implements ViewTree { } if (transferMap.size === 0) { - return; + return undefined; } return transferMap; } - private viewComponentCreationParser( - name: string, - stmt: Stmt, - expr: AbstractInvokeExpr - ): ViewTreeNodeImpl | undefined { + private viewComponentCreationParser(name: string, stmt: Stmt, expr: AbstractInvokeExpr): ViewTreeNodeImpl | undefined { let temp = expr.getArg(0) as Local; let arg: Value | undefined; - temp.getUsedStmts().forEach((value) => { + temp.getUsedStmts().forEach(value => { if (value instanceof ArkInvokeStmt) { let invokerExpr = value.getInvokeExpr(); let methodName = invokerExpr.getMethodSignature().getMethodSubSignature().getMethodName(); @@ -970,9 +945,7 @@ export class ViewTreeImpl extends TreeNodeStack implements ViewTree { if (cls && cls.hasComponentDecorator()) { return this.addCustomComponentNode(cls, arg, builderMethod); } else { - logger.error( - `ViewTree->viewComponentCreationParser not found class ${clsSignature.toString()}. ${stmt.toString()}` - ); + logger.error(`ViewTree->viewComponentCreationParser not found class ${clsSignature.toString()}. ${stmt.toString()}`); } } return undefined; @@ -1009,10 +982,8 @@ export class ViewTreeImpl extends TreeNodeStack implements ViewTree { let values = expr.getArg(0) as Local; let declaringStmt = values?.getDeclaringStmt(); if (declaringStmt) { - let stateValues = StateValuesUtils.getInstance(this.getDeclaringArkClass()).parseStmtUsesStateValues( - declaringStmt - ); - stateValues.forEach((field) => { + let stateValues = StateValuesUtils.getInstance(this.getDeclaringArkClass()).parseStmtUsesStateValues(declaringStmt); + stateValues.forEach(field => { node.stateValues.add(field); this.addStateValue(field, node); }); @@ -1031,10 +1002,8 @@ export class ViewTreeImpl extends TreeNodeStack implements ViewTree { let arg = expr.getArg(0) as Local; let declaringStmt = arg?.getDeclaringStmt(); if (declaringStmt) { - let stateValues = StateValuesUtils.getInstance(this.getDeclaringArkClass()).parseStmtUsesStateValues( - declaringStmt - ); - stateValues.forEach((field) => { + let stateValues = StateValuesUtils.getInstance(this.getDeclaringArkClass()).parseStmtUsesStateValues(declaringStmt); + stateValues.forEach(field => { node.stateValues.add(field); this.addStateValue(field, node); }); @@ -1048,10 +1017,7 @@ export class ViewTreeImpl extends TreeNodeStack implements ViewTree { return this.addSystemComponentNode(COMPONENT_IF_BRANCH); } - private COMPONENT_CREATE_PARSERS: Map< - string, - (name: string, stmt: Stmt, expr: AbstractInvokeExpr) => ViewTreeNodeImpl | undefined - > = new Map([ + private COMPONENT_CREATE_PARSERS: Map ViewTreeNodeImpl | undefined> = new Map([ ['ForEach.create', this.forEachCreationParser.bind(this)], ['LazyForEach.create', this.forEachCreationParser.bind(this)], ['Repeat.create', this.repeatCreationParser.bind(this)], @@ -1060,12 +1026,7 @@ export class ViewTreeImpl extends TreeNodeStack implements ViewTree { ['WaterFlow.create', this.waterFlowCreationParser.bind(this)], ]); - private componentCreateParse( - componentName: string, - methodName: string, - stmt: Stmt, - expr: ArkStaticInvokeExpr - ): ViewTreeNodeImpl | undefined { + private componentCreateParse(componentName: string, methodName: string, stmt: Stmt, expr: ArkStaticInvokeExpr): ViewTreeNodeImpl | undefined { let parserFn = this.COMPONENT_CREATE_PARSERS.get(`${componentName}.${methodName}`); if (parserFn) { let node = parserFn(componentName, stmt, expr); @@ -1078,11 +1039,7 @@ export class ViewTreeImpl extends TreeNodeStack implements ViewTree { return node; } - private parseStaticInvokeExpr( - local2Node: Map, - stmt: Stmt, - expr: ArkStaticInvokeExpr - ): ViewTreeNodeImpl | undefined { + private parseStaticInvokeExpr(local2Node: Map, stmt: Stmt, expr: ArkStaticInvokeExpr): ViewTreeNodeImpl | undefined { let methodSignature = expr.getMethodSignature(); let method = this.findMethod(methodSignature); if (method?.hasBuilderDecorator()) { @@ -1118,18 +1075,11 @@ export class ViewTreeImpl extends TreeNodeStack implements ViewTree { * @param local2Node * @param expr */ - private parseInstanceInvokeExpr( - local2Node: Map, - stmt: Stmt, - expr: ArkInstanceInvokeExpr - ): ViewTreeNodeImpl | undefined { + private parseInstanceInvokeExpr(local2Node: Map, stmt: Stmt, expr: ArkInstanceInvokeExpr): ViewTreeNodeImpl | undefined { let temp = expr.getBase(); if (local2Node.has(temp)) { let component = local2Node.get(temp); - if ( - component?.name === COMPONENT_REPEAT && - expr.getMethodSignature().getMethodSubSignature().getMethodName() === 'each' - ) { + if (component?.name === COMPONENT_REPEAT && expr.getMethodSignature().getMethodSubSignature().getMethodName() === 'each') { let arg = expr.getArg(0); let type = arg.getType(); if (type instanceof FunctionType) { @@ -1166,18 +1116,11 @@ export class ViewTreeImpl extends TreeNodeStack implements ViewTree { return undefined; } - private parsePtrInvokeExpr( - local2Node: Map, - stmt: Stmt, - expr: ArkPtrInvokeExpr - ): ViewTreeNodeImpl | undefined { + private parsePtrInvokeExpr(local2Node: Map, stmt: Stmt, expr: ArkPtrInvokeExpr): ViewTreeNodeImpl | undefined { let temp = expr.getFuncPtrLocal(); if (temp instanceof Local && local2Node.has(temp)) { let component = local2Node.get(temp); - if ( - component?.name === COMPONENT_REPEAT && - expr.getMethodSignature().getMethodSubSignature().getMethodName() === 'each' - ) { + if (component?.name === COMPONENT_REPEAT && expr.getMethodSignature().getMethodSubSignature().getMethodName() === 'each') { let arg = expr.getArg(0); let type = arg.getType(); if (type instanceof FunctionType) { diff --git a/ets2panda/linter/arkanalyzer/src/core/model/ArkBaseModel.ts b/ets2panda/linter/arkanalyzer/src/core/model/ArkBaseModel.ts index 9d363cdcb4..483acec423 100644 --- a/ets2panda/linter/arkanalyzer/src/core/model/ArkBaseModel.ts +++ b/ets2panda/linter/arkanalyzer/src/core/model/ArkBaseModel.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -220,7 +220,7 @@ export abstract class ArkBaseModel { } public removeDecorator(kind: string): void { - this.decorators?.forEach((value) => { + this.decorators?.forEach(value => { if (value.getKind() === kind) { this.decorators?.delete(value); } @@ -235,7 +235,7 @@ export abstract class ArkBaseModel { if (!this.decorators) { return []; } - return Array.from(this.decorators).filter((item) => { + return Array.from(this.decorators).filter(item => { return COMPONENT_MEMBER_DECORATORS.has(item.getKind()); }) as Decorator[]; } @@ -255,7 +255,7 @@ export abstract class ArkBaseModel { public hasDecorator(kind: string | Set): boolean { let decorators = this.getDecorators(); return ( - decorators.filter((value) => { + decorators.filter(value => { if (kind instanceof Set) { return kind.has(value.getKind()); } @@ -276,7 +276,10 @@ export abstract class ArkBaseModel { return { errCode: ArkErrorCode.OK }; } logger.error(`class fields: ${errs.join(',')} is undefined.`); - return { errCode: ArkErrorCode.CLASS_INSTANCE_FIELD_UNDEFINDED, errMsg: `${errs.join(',')} is undefined.` }; + return { + errCode: ArkErrorCode.CLASS_INSTANCE_FIELD_UNDEFINDED, + errMsg: `${errs.join(',')} is undefined.`, + }; } public abstract validate(): ArkError; diff --git a/ets2panda/linter/arkanalyzer/src/core/model/ArkBody.ts b/ets2panda/linter/arkanalyzer/src/core/model/ArkBody.ts index 100e84ff01..610a3a425f 100644 --- a/ets2panda/linter/arkanalyzer/src/core/model/ArkBody.ts +++ b/ets2panda/linter/arkanalyzer/src/core/model/ArkBody.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -19,6 +19,7 @@ import { AliasType } from '../base/Type'; import { Trap } from '../base/Trap'; import { Value } from '../base/Value'; import { ArkAliasTypeDefineStmt } from '../base/Stmt'; +import { LocalSignature } from './ArkSignature'; export class ArkBody { private locals: Map; @@ -27,8 +28,7 @@ export class ArkBody { private aliasTypeMap?: Map; private traps?: Trap[]; - constructor(locals: Set, cfg: Cfg, aliasTypeMap?: Map, - traps?: Trap[]) { + constructor(locals: Set, cfg: Cfg, aliasTypeMap?: Map, traps?: Trap[]) { this.cfg = cfg; this.aliasTypeMap = aliasTypeMap; this.locals = new Map(); @@ -82,4 +82,13 @@ export class ArkBody { public getTraps(): Trap[] | undefined { return this.traps; } -} \ No newline at end of file + + public getExportLocalByName(name: string): Local | null { + const local = this.locals?.get(name); + if (local) { + local.setSignature(new LocalSignature(name, this.cfg.getDeclaringMethod().getSignature())); + return local; + } + return null; + } +} diff --git a/ets2panda/linter/arkanalyzer/src/core/model/ArkClass.ts b/ets2panda/linter/arkanalyzer/src/core/model/ArkClass.ts index 71584a6492..6b013ddbd5 100644 --- a/ets2panda/linter/arkanalyzer/src/core/model/ArkClass.ts +++ b/ets2panda/linter/arkanalyzer/src/core/model/ArkClass.ts @@ -89,7 +89,7 @@ export class ArkClass extends ArkBaseModel implements ArkExport { * Returns the **string**name of this class. * @returns The name of this class. */ - public getName() { + public getName(): string { return this.classSignature.getClassName(); } @@ -97,11 +97,11 @@ export class ArkClass extends ArkBaseModel implements ArkExport { * Returns the codes of class as a **string.** * @returns the codes of class. */ - public getCode() { + public getCode(): string | undefined { return this.code; } - public setCode(code: string) { + public setCode(code: string): void { this.code = code; } @@ -109,11 +109,11 @@ export class ArkClass extends ArkBaseModel implements ArkExport { * Returns the line position of this class. * @returns The line position of this class. */ - public getLine() { + public getLine(): number { return getLineNo(this.lineCol); } - public setLine(line: number) { + public setLine(line: number): void { this.lineCol = setLine(this.lineCol, line); } @@ -121,11 +121,11 @@ export class ArkClass extends ArkBaseModel implements ArkExport { * Returns the column position of this class. * @returns The column position of this class. */ - public getColumn() { + public getColumn(): number { return getColNo(this.lineCol); } - public setColumn(column: number) { + public setColumn(column: number): void { this.lineCol = setCol(this.lineCol, column); } @@ -147,11 +147,11 @@ export class ArkClass extends ArkBaseModel implements ArkExport { const arkFile = arkClass.getDeclaringArkFile(); ``` */ - public getDeclaringArkFile() { + public getDeclaringArkFile(): ArkFile { return this.declaringArkFile; } - public setDeclaringArkFile(declaringArkFile: ArkFile) { + public setDeclaringArkFile(declaringArkFile: ArkFile): void { this.declaringArkFile = declaringArkFile; } @@ -163,7 +163,7 @@ export class ArkClass extends ArkBaseModel implements ArkExport { return this.declaringArkNamespace; } - public setDeclaringArkNamespace(declaringArkNamespace: ArkNamespace | undefined) { + public setDeclaringArkNamespace(declaringArkNamespace: ArkNamespace | undefined): void { this.declaringArkNamespace = declaringArkNamespace; } @@ -180,11 +180,11 @@ export class ArkClass extends ArkBaseModel implements ArkExport { * The {@link ClassSignature} can uniquely identify a class, according to which we can find the class from the scene. * @returns The class signature. */ - public getSignature() { + public getSignature(): ClassSignature { return this.classSignature; } - public setSignature(classSig: ClassSignature) { + public setSignature(classSig: ClassSignature): void { this.classSignature = classSig; } @@ -218,8 +218,7 @@ export class ArkClass extends ArkBaseModel implements ArkExport { if (type) { type = TypeInference.replaceAliasType(type); } - if (type instanceof ClassType && - (superClass = this.declaringArkFile.getScene().getClass(type.getClassSignature()))) { + if (type instanceof ClassType && (superClass = this.declaringArkFile.getScene().getClass(type.getClassSignature()))) { superClass.addExtendedClass(this); const realGenericTypes = type.getRealGenericTypes(); if (realGenericTypes) { @@ -246,7 +245,7 @@ export class ArkClass extends ArkBaseModel implements ArkExport { return this.extendedClasses; } - public addExtendedClass(extendedClass: ArkClass) { + public addExtendedClass(extendedClass: ArkClass): void { this.extendedClasses.set(extendedClass.getName(), extendedClass); } @@ -257,7 +256,7 @@ export class ArkClass extends ArkBaseModel implements ArkExport { return Array.from(this.heritageClasses.keys()).slice(1); } - public hasImplementedInterface(interfaceName: string) { + public hasImplementedInterface(interfaceName: string): boolean { return this.heritageClasses.has(interfaceName) && this.getSuperClassName() !== interfaceName; } @@ -302,7 +301,7 @@ export class ArkClass extends ArkBaseModel implements ArkExport { return allFields; } - public addField(field: ArkField) { + public addField(field: ArkField): void { if (field.isStatic()) { this.staticFields.set(field.getName(), field); } else { @@ -310,8 +309,8 @@ export class ArkClass extends ArkBaseModel implements ArkExport { } } - public addFields(fields: ArkField[]) { - fields.forEach((field) => { + public addFields(fields: ArkField[]): void { + fields.forEach(field => { this.addField(field); }); } @@ -324,7 +323,7 @@ export class ArkClass extends ArkBaseModel implements ArkExport { return this.genericsTypes ? Array.from(this.genericsTypes) : undefined; } - public addGenericType(gType: GenericType) { + public addGenericType(gType: GenericType): void { if (!this.genericsTypes) { this.genericsTypes = []; } @@ -348,8 +347,7 @@ export class ArkClass extends ArkBaseModel implements ArkExport { ``` */ public getMethods(generated?: boolean): ArkMethod[] { - const allMethods = Array.from(this.methods.values()) - .filter(f => !generated && !f.isGenerated() || generated); + const allMethods = Array.from(this.methods.values()).filter(f => (!generated && !f.isGenerated()) || generated); allMethods.push(...this.staticMethods.values()); return [...new Set(allMethods)]; } @@ -404,7 +402,7 @@ export class ArkClass extends ArkBaseModel implements ArkExport { } } - public setDefaultArkMethod(defaultMethod: ArkMethod) { + public setDefaultArkMethod(defaultMethod: ArkMethod): void { this.defaultMethod = defaultMethod; this.addMethod(defaultMethod); } @@ -413,7 +411,7 @@ export class ArkClass extends ArkBaseModel implements ArkExport { return this.defaultMethod; } - public setViewTree(viewTree: ViewTree) { + public setViewTree(viewTree: ViewTree): void { this.viewTree = viewTree; } @@ -483,11 +481,11 @@ export class ArkClass extends ArkBaseModel implements ArkExport { return globalMap.get(this.declaringArkFile.getFileSignature())!; } - public getAnonymousMethodNumber() { + public getAnonymousMethodNumber(): number { return this.anonymousMethodNumber++; } - public getIndexSignatureNumber() { + public getIndexSignatureNumber(): number { return this.indexSignatureNumber++; } @@ -532,4 +530,4 @@ export class ArkClass extends ArkBaseModel implements ArkExport { public validate(): ArkError { return this.validateFields(['declaringArkFile', 'category', 'classSignature']); } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/model/ArkExport.ts b/ets2panda/linter/arkanalyzer/src/core/model/ArkExport.ts index 3830d69936..8d02d8867f 100644 --- a/ets2panda/linter/arkanalyzer/src/core/model/ArkExport.ts +++ b/ets2panda/linter/arkanalyzer/src/core/model/ArkExport.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -20,6 +20,7 @@ import { DEFAULT } from '../common/TSConst'; import { ArkBaseModel, ModifierType } from './ArkBaseModel'; import { ArkError } from '../common/ArkError'; import { ArkMetadataKind, CommentsMetadata } from './ArkMetadata'; +import { ArkNamespace } from './ArkNamespace'; export type ExportSignature = NamespaceSignature | ClassSignature | MethodSignature | LocalSignature; @@ -29,7 +30,7 @@ export enum ExportType { METHOD = 2, LOCAL = 3, TYPE = 4, - UNKNOWN = 9 + UNKNOWN = 9, } export interface ArkExport extends ArkSignature { @@ -39,7 +40,6 @@ export interface ArkExport extends ArkSignature { getName(): string; getExportType(): ExportType; - } export interface FromInfo { @@ -67,7 +67,7 @@ export class ExportInfo extends ArkBaseModel implements FromInfo { private originTsPosition?: LineColPosition; private tsSourceCode?: string; private declaringArkFile!: ArkFile; - + private declaringArkNamespace?: ArkNamespace; private constructor() { super(); } @@ -103,7 +103,7 @@ export class ExportInfo extends ArkBaseModel implements FromInfo { return this.nameBeforeAs; } - public setArkExport(value: ArkExport | null) { + public setArkExport(value: ArkExport | null): void { this.arkExport = value; } @@ -133,6 +133,10 @@ export class ExportInfo extends ArkBaseModel implements FromInfo { return this.declaringArkFile; } + public getDeclaringArkNamespace(): ArkNamespace | undefined { + return this.declaringArkNamespace; + } + public static Builder = class ArkExportBuilder { exportInfo: ExportInfo = new ExportInfo(); @@ -171,6 +175,11 @@ export class ExportInfo extends ArkBaseModel implements FromInfo { return this; } + public declaringArkNamespace(value: ArkNamespace): ArkExportBuilder { + this.exportInfo.declaringArkNamespace = value; + return this; + } + public arkExport(value: ArkExport): ArkExportBuilder { this.exportInfo.arkExport = value; return this; diff --git a/ets2panda/linter/arkanalyzer/src/core/model/ArkField.ts b/ets2panda/linter/arkanalyzer/src/core/model/ArkField.ts index e85ce04d1a..2fcfc43ced 100644 --- a/ets2panda/linter/arkanalyzer/src/core/model/ArkField.ts +++ b/ets2panda/linter/arkanalyzer/src/core/model/ArkField.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -22,7 +22,6 @@ import { ArkBaseModel, ModifierType } from './ArkBaseModel'; import { ArkError } from '../common/ArkError'; import { Language } from './ArkFile'; - export enum FieldCategory { PROPERTY_DECLARATION = 0, PROPERTY_ASSIGNMENT = 1, @@ -39,7 +38,7 @@ export enum FieldCategory { * @category core/model */ export class ArkField extends ArkBaseModel { - private code: string = ""; + private code: string = ''; private category!: FieldCategory; private declaringClass!: ArkClass; @@ -62,11 +61,11 @@ export class ArkField extends ArkBaseModel { return this.getDeclaringArkClass().getLanguage(); } - public getDeclaringArkClass() { + public getDeclaringArkClass(): ArkClass { return this.declaringClass; } - public setDeclaringArkClass(declaringClass: ArkClass) { + public setDeclaringArkClass(declaringClass: ArkClass): void { this.declaringClass = declaringClass; } @@ -74,11 +73,11 @@ export class ArkField extends ArkBaseModel { * Returns the codes of field as a **string.** * @returns the codes of field. */ - public getCode() { + public getCode(): string { return this.code; } - public setCode(code: string) { + public setCode(code: string): void { this.code = code; } @@ -90,11 +89,11 @@ export class ArkField extends ArkBaseModel { this.category = category; } - public getName() { + public getName(): string { return this.fieldSignature.getFieldName(); } - public getType():Type { + public getType(): Type { return this.fieldSignature.getType(); } @@ -102,7 +101,7 @@ export class ArkField extends ArkBaseModel { return this.fieldSignature; } - public setSignature(fieldSig: FieldSignature) { + public setSignature(fieldSig: FieldSignature): void { this.fieldSignature = fieldSig; } @@ -114,27 +113,27 @@ export class ArkField extends ArkBaseModel { return this.initializer; } - public setInitializer(initializer: Stmt[]) { + public setInitializer(initializer: Stmt[]): void { this.initializer = initializer; } - public setQuestionToken(questionToken: boolean) { + public setQuestionToken(questionToken: boolean): void { this.questionToken = questionToken; } - public setExclamationToken(exclamationToken: boolean) { + public setExclamationToken(exclamationToken: boolean): void { this.exclamationToken = exclamationToken; } - public getQuestionToken() { + public getQuestionToken(): boolean { return this.questionToken; } - public getExclamationToken() { + public getExclamationToken(): boolean { return this.exclamationToken; } - public setOriginPosition(position: LineColPosition) { + public setOriginPosition(position: LineColPosition): void { this.originPosition = position; } @@ -152,12 +151,14 @@ export class ArkField extends ArkBaseModel { // For class field, it is default public if there is not any access modify public isPublic(): boolean { - if (!this.containsModifier(ModifierType.PUBLIC) && + if ( + !this.containsModifier(ModifierType.PUBLIC) && !this.containsModifier(ModifierType.PRIVATE) && !this.containsModifier(ModifierType.PROTECTED) && - this.getDeclaringArkClass().getCategory() === ClassCategory.CLASS) { + this.getDeclaringArkClass().getCategory() === ClassCategory.CLASS + ) { return true; } return this.containsModifier(ModifierType.PUBLIC); } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/model/ArkFile.ts b/ets2panda/linter/arkanalyzer/src/core/model/ArkFile.ts index 897af2e03f..bc2f6352f1 100644 --- a/ets2panda/linter/arkanalyzer/src/core/model/ArkFile.ts +++ b/ets2panda/linter/arkanalyzer/src/core/model/ArkFile.ts @@ -19,16 +19,32 @@ import { ImportInfo } from './ArkImport'; import { ArkClass } from './ArkClass'; import { ArkNamespace } from './ArkNamespace'; import { AliasClassSignature, ClassSignature, FileSignature, NamespaceSignature } from './ArkSignature'; -import { ALL } from "../common/TSConst"; - -export const notStmtOrExprKind = ['ModuleDeclaration', 'ClassDeclaration', 'InterfaceDeclaration', 'EnumDeclaration', 'ExportDeclaration', - 'ExportAssignment', 'MethodDeclaration', 'Constructor', 'FunctionDeclaration', 'GetAccessor', 'SetAccessor', 'ArrowFunction', - 'FunctionExpression', 'MethodSignature', 'ConstructSignature', 'CallSignature']; +import { ALL } from '../common/TSConst'; + +export const notStmtOrExprKind = [ + 'ModuleDeclaration', + 'ClassDeclaration', + 'InterfaceDeclaration', + 'EnumDeclaration', + 'ExportDeclaration', + 'ExportAssignment', + 'MethodDeclaration', + 'Constructor', + 'FunctionDeclaration', + 'GetAccessor', + 'SetAccessor', + 'ArrowFunction', + 'FunctionExpression', + 'MethodSignature', + 'ConstructSignature', + 'CallSignature', +]; export enum Language { TYPESCRIPT = 0, ARKTS1_1 = 1, ARKTS1_2 = 2, + JAVASCRIPT = 3, UNKNOWN = -1, } @@ -78,33 +94,33 @@ export class ArkFile { * Returns the **string** name of the file, which also acts as the file's relative path. * @returns The file's name (also means its relative path). */ - public getName() { + public getName(): string { return this.fileSignature.getFileName(); } - public setScene(scene: Scene) { + public setScene(scene: Scene): void { this.scene = scene; } /** - * Returns the scene (i.e., {@link Scene}) built for the project. The {@link Scene} is the core class of ArkAnalyzer, - * through which users can access all the information of the analyzed code (project), + * Returns the scene (i.e., {@link Scene}) built for the project. The {@link Scene} is the core class of ArkAnalyzer, + * through which users can access all the information of the analyzed code (project), * including file list, class list, method list, property list, etc. * @returns The scene of the file. */ - public getScene() { + public getScene(): Scene { return this.scene; } - public getModuleScene() { + public getModuleScene(): ModuleScene | undefined { return this.moduleScene; } - public setModuleScene(moduleScene: ModuleScene) { + public setModuleScene(moduleScene: ModuleScene): void { this.moduleScene = moduleScene; } - public setProjectDir(projectDir: string) { + public setProjectDir(projectDir: string): void { this.projectDir = projectDir; } @@ -126,11 +142,11 @@ export class ArkFile { return this.absoluteFilePath; } - public setFilePath(absoluteFilePath: string) { + public setFilePath(absoluteFilePath: string): void { this.absoluteFilePath = absoluteFilePath; } - public setCode(code: string) { + public setCode(code: string): void { this.code = code; } @@ -138,19 +154,19 @@ export class ArkFile { * Returns the codes of file as a **string.** * @returns the codes of file. */ - public getCode() { + public getCode(): string { return this.code; } - public addArkClass(arkClass: ArkClass) { + public addArkClass(arkClass: ArkClass): void { this.classes.set(arkClass.getName(), arkClass); } - public getDefaultClass() { + public getDefaultClass(): ArkClass { return this.defaultClass; } - public setDefaultClass(defaultClass: ArkClass) { + public setDefaultClass(defaultClass: ArkClass): void { this.defaultClass = defaultClass; } @@ -173,8 +189,7 @@ export class ArkFile { * @returns A class. If there is no class, the return will be a **null**. */ public getClass(classSignature: ClassSignature): ArkClass | null { - const className = classSignature instanceof AliasClassSignature ? classSignature.getOriginName() - : classSignature.getClassName(); + const className = classSignature instanceof AliasClassSignature ? classSignature.getOriginName() : classSignature.getClassName(); return this.getClassWithName(className); } @@ -186,12 +201,12 @@ export class ArkFile { return Array.from(this.classes.values()); } - public addNamespace(namespace: ArkNamespace) { + public addNamespace(namespace: ArkNamespace): void { this.namespaces.set(namespace.getName(), namespace); } - + /** - * Returns an **array** of import information. + * Returns an **array** of import information. * The import information includes: clause's name, type, modifiers, location where it is imported from, etc. * @returns An **array** of import information. */ @@ -203,7 +218,7 @@ export class ArkFile { return this.importInfoMap.get(name); } - public addImportInfo(importInfo: ImportInfo) { + public addImportInfo(importInfo: ImportInfo): void { this.importInfoMap.set(importInfo.getImportClauseName(), importInfo); } @@ -229,7 +244,7 @@ export class ArkFile { if (key !== ALL || value.getFrom()) { exportInfos.push(value); } - }) + }); return exportInfos; } @@ -286,7 +301,7 @@ export class ArkFile { return currExportInfo; } - public addExportInfo(exportInfo: ExportInfo, key?: string) { + public addExportInfo(exportInfo: ExportInfo, key?: string): void { this.exportInfoMap.set(key ?? exportInfo.getExportClauseName(), exportInfo); } @@ -298,19 +313,19 @@ export class ArkFile { this.exportInfoMap.delete(exportInfo.getExportClauseName()); } - public getProjectName() { + public getProjectName(): string { return this.fileSignature.getProjectName(); } - public getModuleName() { + public getModuleName(): string | undefined { return this.moduleScene?.getModuleName(); } - public setOhPackageJson5Path(ohPackageJson5Path: string[]) { + public setOhPackageJson5Path(ohPackageJson5Path: string[]): void { this.ohPackageJson5Path = ohPackageJson5Path; } - public getOhPackageJson5Path() { + public getOhPackageJson5Path(): string[] { return this.ohPackageJson5Path; } @@ -318,7 +333,7 @@ export class ArkFile { * Returns the file signature of this file. A file signature consists of project's name and file's name. * @returns The file signature of this file. */ - public getFileSignature() { + public getFileSignature(): FileSignature { return this.fileSignature; } @@ -329,13 +344,13 @@ export class ArkFile { public getAllNamespacesUnderThisFile(): ArkNamespace[] { let namespaces: ArkNamespace[] = []; namespaces.push(...this.namespaces.values()); - this.namespaces.forEach((ns) => { + this.namespaces.forEach(ns => { namespaces.push(...ns.getAllNamespacesUnderThisNamespace()); }); return namespaces; } - public getAnonymousClassNumber() { + public getAnonymousClassNumber(): number { return this.anonymousClassNumber++; } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/model/ArkImport.ts b/ets2panda/linter/arkanalyzer/src/core/model/ArkImport.ts index 80c95ddff1..8ff3ff50ac 100644 --- a/ets2panda/linter/arkanalyzer/src/core/model/ArkImport.ts +++ b/ets2panda/linter/arkanalyzer/src/core/model/ArkImport.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ import { ArkFile, Language } from './ArkFile'; import { LineColPosition } from '../base/Position'; import { ExportInfo, FromInfo } from './ArkExport'; -import { findExportInfo } from "../common/ModelUtils"; +import { findExportInfo } from '../common/ModelUtils'; import { ArkBaseModel } from './ArkBaseModel'; import { ArkError } from '../common/ArkError'; @@ -45,8 +45,14 @@ export class ImportInfo extends ArkBaseModel implements FromInfo { return this.getDeclaringArkFile().getLanguage(); } - public build(importClauseName: string, importType: string, importFrom: string, originTsPosition: LineColPosition, - modifiers: number, nameBeforeAs?: string) { + public build( + importClauseName: string, + importType: string, + importFrom: string, + originTsPosition: LineColPosition, + modifiers: number, + nameBeforeAs?: string + ): void { this.setImportClauseName(importClauseName); this.setImportType(importType); this.setImportFrom(importFrom); @@ -60,8 +66,8 @@ export class ImportInfo extends ArkBaseModel implements FromInfo { } /** - * Returns the export information, i.e., the actual reference generated at the time of call. - * The export information includes: clause's name, clause's type, modifiers, location + * Returns the export information, i.e., the actual reference generated at the time of call. + * The export information includes: clause's name, clause's type, modifiers, location * where it is exported from, etc. If the export information could not be found, **null** will be returned. * @returns The export information. If there is no export information, the return will be a **null**. */ @@ -104,7 +110,7 @@ export class ImportInfo extends ArkBaseModel implements FromInfo { return this.nameBeforeAs; } - public setNameBeforeAs(nameBeforeAs: string | undefined) { + public setNameBeforeAs(nameBeforeAs: string | undefined): void { this.nameBeforeAs = nameBeforeAs; } diff --git a/ets2panda/linter/arkanalyzer/src/core/model/ArkMetadata.ts b/ets2panda/linter/arkanalyzer/src/core/model/ArkMetadata.ts index 76e7cd36e6..80cbec966f 100644 --- a/ets2panda/linter/arkanalyzer/src/core/model/ArkMetadata.ts +++ b/ets2panda/linter/arkanalyzer/src/core/model/ArkMetadata.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -20,8 +20,7 @@ export enum ArkMetadataKind { TRAILING_COMMENTS, } -export interface ArkMetadataType { -} +export interface ArkMetadataType {} /** * ArkMetadata @@ -30,7 +29,7 @@ export interface ArkMetadataType { * let stmt: Stmt = xxx; * let comments = stmt.getMetadata(ArkMetadataKind.LEADING_COMMENTS) || []; * comments.forEach((comment) => { - * logger.info(comment); + * logger.info(comment); * }); */ export class ArkMetadata { @@ -49,8 +48,8 @@ export class ArkMetadata { } export type CommentItem = { - content: string, - position: FullPosition + content: string; + position: FullPosition; }; export class CommentsMetadata implements ArkMetadataType { @@ -63,4 +62,4 @@ export class CommentsMetadata implements ArkMetadataType { public getComments(): CommentItem[] { return this.comments; } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/model/ArkMethod.ts b/ets2panda/linter/arkanalyzer/src/core/model/ArkMethod.ts index 0f3f704fc8..f3476d3567 100644 --- a/ets2panda/linter/arkanalyzer/src/core/model/ArkMethod.ts +++ b/ets2panda/linter/arkanalyzer/src/core/model/ArkMethod.ts @@ -15,13 +15,13 @@ import { ArkParameterRef, ArkThisRef } from '../base/Ref'; import { ArkAssignStmt, ArkReturnStmt, Stmt } from '../base/Stmt'; -import { ClassType, FunctionType, GenericType, LiteralType, NumberType, Type, UnionType } from '../base/Type'; +import { ClassType, EnumValueType, FunctionType, GenericType, LiteralType, Type, UnionType } from '../base/Type'; import { Value } from '../base/Value'; import { Cfg } from '../graph/Cfg'; import { ViewTree } from '../graph/ViewTree'; import { ArkBody } from './ArkBody'; import { ArkClass, ClassCategory } from './ArkClass'; -import { MethodSignature } from './ArkSignature'; +import { MethodSignature, MethodSubSignature } from './ArkSignature'; import { BodyBuilder } from './builder/BodyBuilder'; import { ArkExport, ExportType } from './ArkExport'; import { ANONYMOUS_METHOD_PREFIX, DEFAULT_ARK_METHOD_NAME } from '../common/Const'; @@ -32,11 +32,22 @@ import { CALL_BACK } from '../common/EtsConst'; import { Scene } from '../../Scene'; import { Constant } from '../base/Constant'; import { Local } from '../base/Local'; -import { Language } from './ArkFile'; +import { ArkFile, Language } from './ArkFile'; import { CONSTRUCTOR_NAME } from '../common/TSConst'; - -export const arkMethodNodeKind = ['MethodDeclaration', 'Constructor', 'FunctionDeclaration', 'GetAccessor', - 'SetAccessor', 'ArrowFunction', 'FunctionExpression', 'MethodSignature', 'ConstructSignature', 'CallSignature']; +import { MethodParameter } from './builder/ArkMethodBuilder'; + +export const arkMethodNodeKind = [ + 'MethodDeclaration', + 'Constructor', + 'FunctionDeclaration', + 'GetAccessor', + 'SetAccessor', + 'ArrowFunction', + 'FunctionExpression', + 'MethodSignature', + 'ConstructSignature', + 'CallSignature', +]; /** * @category core/model @@ -79,7 +90,7 @@ export class ArkMethod extends ArkBaseModel implements ArkExport { return ExportType.METHOD; } - public getName() { + public getName(): string { return this.getSignature().getMethodSubSignature().getMethodName(); } @@ -87,11 +98,11 @@ export class ArkMethod extends ArkBaseModel implements ArkExport { * Returns the codes of method as a **string.** * @returns the codes of method. */ - public getCode() { + public getCode(): string | undefined { return this.code; } - public setCode(code: string) { + public setCode(code: string): void { this.code = code; } @@ -231,15 +242,15 @@ export class ArkMethod extends ArkBaseModel implements ArkExport { * Returns the declaring class of the method. * @returns The declaring class of the method. */ - public getDeclaringArkClass() { + public getDeclaringArkClass(): ArkClass { return this.declaringArkClass; } - public setDeclaringArkClass(declaringArkClass: ArkClass) { + public setDeclaringArkClass(declaringArkClass: ArkClass): void { this.declaringArkClass = declaringArkClass; } - public getDeclaringArkFile() { + public getDeclaringArkFile(): ArkFile { return this.declaringArkClass.getDeclaringArkFile(); } @@ -251,11 +262,11 @@ export class ArkMethod extends ArkBaseModel implements ArkExport { return this.getName().startsWith(ANONYMOUS_METHOD_PREFIX); } - public getParameters() { + public getParameters(): MethodParameter[] { return this.getSignature().getMethodSubSignature().getParameters(); } - public getReturnType() { + public getReturnType(): Type { return this.getSignature().getType(); } @@ -353,7 +364,7 @@ export class ArkMethod extends ArkBaseModel implements ArkExport { this.methodSignature = signature; } - public getSubSignature() { + public getSubSignature(): MethodSubSignature { return this.getSignature().getMethodSubSignature(); } @@ -398,7 +409,7 @@ export class ArkMethod extends ArkBaseModel implements ArkExport { return this.body; } - public setBody(body: ArkBody) { + public setBody(body: ArkBody): void { this.body = body; } @@ -501,19 +512,23 @@ export class ArkMethod extends ArkBaseModel implements ArkExport { public getReturnValues(): Value[] { // 获取方法体中return值实例 let resultValues: Value[] = []; - this.getCfg()?.getStmts().forEach(stmt => { - if (stmt instanceof ArkReturnStmt) { - resultValues.push(stmt.getOp()); - } - }); + this.getCfg() + ?.getStmts() + .forEach(stmt => { + if (stmt instanceof ArkReturnStmt) { + resultValues.push(stmt.getOp()); + } + }); return resultValues; } public getReturnStmt(): Stmt[] { - return this.getCfg()!.getStmts().filter(stmt => stmt instanceof ArkReturnStmt); + return this.getCfg()! + .getStmts() + .filter(stmt => stmt instanceof ArkReturnStmt); } - public setViewTree(viewTree: ViewTree) { + public setViewTree(viewTree: ViewTree): void { this.viewTree = viewTree; } @@ -525,7 +540,7 @@ export class ArkMethod extends ArkBaseModel implements ArkExport { return this.viewTree !== undefined; } - public setBodyBuilder(bodyBuilder: BodyBuilder) { + public setBodyBuilder(bodyBuilder: BodyBuilder): void { this.bodyBuilder = bodyBuilder; if (this.getDeclaringArkFile().getScene().buildClassDone()) { this.buildBody(); @@ -536,7 +551,7 @@ export class ArkMethod extends ArkBaseModel implements ArkExport { this.bodyBuilder = undefined; } - public buildBody() { + public buildBody(): void { if (this.bodyBuilder) { const arkBody: ArkBody | null = this.bodyBuilder.build(); if (arkBody) { @@ -553,7 +568,7 @@ export class ArkMethod extends ArkBaseModel implements ArkExport { return this.isGeneratedFlag; } - public setIsGeneratedFlag(isGeneratedFlag: boolean) { + public setIsGeneratedFlag(isGeneratedFlag: boolean): void { this.isGeneratedFlag = isGeneratedFlag; } @@ -561,7 +576,7 @@ export class ArkMethod extends ArkBaseModel implements ArkExport { return this.asteriskToken; } - public setAsteriskToken(asteriskToken: boolean) { + public setAsteriskToken(asteriskToken: boolean): void { this.asteriskToken = asteriskToken; } @@ -574,25 +589,25 @@ export class ArkMethod extends ArkBaseModel implements ArkExport { if (declareSignatures === null && signature === null) { return { errCode: ArkErrorCode.METHOD_SIGNATURE_UNDEFINED, - errMsg: 'methodDeclareSignatures and methodSignature are both undefined.' + errMsg: 'methodDeclareSignatures and methodSignature are both undefined.', }; } if ((declareSignatures === null) !== (declareLineCols === null)) { return { errCode: ArkErrorCode.METHOD_SIGNATURE_LINE_UNMATCHED, - errMsg: 'methodDeclareSignatures and methodDeclareLineCols are not matched.' + errMsg: 'methodDeclareSignatures and methodDeclareLineCols are not matched.', }; } if (declareSignatures !== null && declareLineCols !== null && declareSignatures.length !== declareLineCols.length) { return { errCode: ArkErrorCode.METHOD_SIGNATURE_LINE_UNMATCHED, - errMsg: 'methodDeclareSignatures and methodDeclareLineCols are not matched.' + errMsg: 'methodDeclareSignatures and methodDeclareLineCols are not matched.', }; } if ((signature === null) !== (lineCol === null)) { return { errCode: ArkErrorCode.METHOD_SIGNATURE_LINE_UNMATCHED, - errMsg: 'methodSignature and lineCol are not matched.' + errMsg: 'methodSignature and lineCol are not matched.', }; } return this.validateFields(['declaringArkClass']); @@ -609,19 +624,23 @@ export class ArkMethod extends ArkBaseModel implements ArkExport { return args.length >= min && args.length <= max; }); const scene = this.getDeclaringArkFile().getScene(); - return signatures?.find(p => { - const parameters = p.getMethodSubSignature().getParameters(); - for (let i = 0; i < parameters.length; i++) { - if (!args[i]) { - return parameters[i].isOptional(); - } - const isMatched = this.matchParam(parameters[i].getType(), args[i], scene); - if (!isMatched) { - return false; + return ( + signatures?.find(p => { + const parameters = p.getMethodSubSignature().getParameters(); + for (let i = 0; i < parameters.length; i++) { + if (!args[i]) { + return parameters[i].isOptional(); + } + const isMatched = this.matchParam(parameters[i].getType(), args[i], scene); + if (!isMatched) { + return false; + } } - } - return true; - }) ?? signatures?.[0] ?? this.getSignature(); + return true; + }) ?? + signatures?.[0] ?? + this.getSignature() + ); } private matchParam(paramType: Type, arg: Value, scene: Scene): boolean { @@ -643,15 +662,24 @@ export class ArkMethod extends ArkBaseModel implements ArkExport { return matched; } else if (argType instanceof FunctionType && paramType instanceof FunctionType) { return argType.getMethodSignature().getParamLength() === paramType.getMethodSignature().getParamLength(); - } else if (argType instanceof FunctionType && paramType instanceof ClassType && - paramType.getClassSignature().getClassName().includes(CALL_BACK)) { - return true; + } else if (paramType instanceof ClassType && paramType.getClassSignature().getClassName().includes(CALL_BACK)) { + return argType instanceof FunctionType; } else if (paramType instanceof LiteralType && arg instanceof Constant) { - return arg.getValue().replace(/[\"|\']/g, '') === paramType.getLiteralName() - .toString().replace(/[\"|\']/g, ''); - } else if (paramType instanceof NumberType && argType instanceof ClassType && ClassCategory.ENUM === - scene.getClass(argType.getClassSignature())?.getCategory()) { - return true; + return ( + arg.getValue().replace(/[\"|\']/g, '') === + paramType + .getLiteralName() + .toString() + .replace(/[\"|\']/g, '') + ); + } else if (paramType instanceof ClassType && argType instanceof EnumValueType) { + return paramType.getClassSignature() === argType.getFieldSignature().getDeclaringSignature(); + } else if (paramType instanceof EnumValueType) { + if (argType instanceof EnumValueType) { + return paramType.getFieldSignature() === argType.getFieldSignature(); + } else if (argType.constructor === paramType.getConstant()?.getType().constructor && arg instanceof Constant) { + return paramType.getConstant()?.getValue() === arg.getValue(); + } } return argType.constructor === paramType.constructor; } @@ -679,16 +707,18 @@ export class ArkMethod extends ArkBaseModel implements ArkExport { // For class method, if there is no public/private/protected access modifier, it is actually public public isPublic(): boolean { - if (!this.containsModifier(ModifierType.PUBLIC) && + if ( + !this.containsModifier(ModifierType.PUBLIC) && !this.containsModifier(ModifierType.PRIVATE) && !this.containsModifier(ModifierType.PROTECTED) && !this.getDeclaringArkClass().isDefaultArkClass() && !this.isGenerated() && !this.isAnonymousMethod() && this.getName() !== CONSTRUCTOR_NAME && - this.getDeclaringArkClass().getCategory() === ClassCategory.CLASS) { + this.getDeclaringArkClass().getCategory() === ClassCategory.CLASS + ) { return true; } return this.containsModifier(ModifierType.PUBLIC); } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/model/ArkNamespace.ts b/ets2panda/linter/arkanalyzer/src/core/model/ArkNamespace.ts index b6fb1659c6..e855812410 100644 --- a/ets2panda/linter/arkanalyzer/src/core/model/ArkNamespace.ts +++ b/ets2panda/linter/arkanalyzer/src/core/model/ArkNamespace.ts @@ -58,7 +58,7 @@ export class ArkNamespace extends ArkBaseModel implements ArkExport { return this.getDeclaringArkFile().getLanguage(); } - public addNamespace(namespace: ArkNamespace) { + public addNamespace(namespace: ArkNamespace): void { this.namespaces.set(namespace.getName(), namespace); } @@ -79,23 +79,23 @@ export class ArkNamespace extends ArkBaseModel implements ArkExport { this.namespaceSignature = namespaceSignature; } - public getSignature() { + public getSignature(): NamespaceSignature { return this.namespaceSignature; } - public getNamespaceSignature() { + public getNamespaceSignature(): NamespaceSignature { return this.namespaceSignature; } - public getName() { + public getName(): string { return this.namespaceSignature.getNamespaceName(); } - public getCode() { + public getCode(): string { return this.sourceCodes[0]; } - public setCode(sourceCode: string) { + public setCode(sourceCode: string): void { this.sourceCodes[0] = sourceCode; } @@ -118,19 +118,19 @@ export class ArkNamespace extends ArkBaseModel implements ArkExport { this.sourceCodes.push(sourceCode); } - public getLine() { + public getLine(): number { return getLineNo(this.lineCols[0]); } - public setLine(line: number) { + public setLine(line: number): void { this.lineCols[0] = setLine(this.lineCols[0], line); } - public getColumn() { + public getColumn(): number { return getColNo(this.lineCols[0]); } - public setColumn(column: number) { + public setColumn(column: number): void { this.lineCols[0] = setCol(this.lineCols[0], column); } @@ -149,33 +149,32 @@ export class ArkNamespace extends ArkBaseModel implements ArkExport { }); } - public getDeclaringInstance() { + public getDeclaringInstance(): ArkNamespace | ArkFile { return this.declaringInstance; } - public setDeclaringInstance(declaringInstance: ArkFile | ArkNamespace) { + public setDeclaringInstance(declaringInstance: ArkFile | ArkNamespace): void { this.declaringInstance = declaringInstance; } - public getDeclaringArkFile() { + public getDeclaringArkFile(): ArkFile { return this.declaringArkFile; } - public setDeclaringArkFile(declaringArkFile: ArkFile) { + public setDeclaringArkFile(declaringArkFile: ArkFile): void { this.declaringArkFile = declaringArkFile; } - public getDeclaringArkNamespace() { + public getDeclaringArkNamespace(): ArkNamespace | null { return this.declaringArkNamespace; } - public setDeclaringArkNamespace(declaringArkNamespace: ArkNamespace) { + public setDeclaringArkNamespace(declaringArkNamespace: ArkNamespace): void { this.declaringArkNamespace = declaringArkNamespace; } public getClass(classSignature: ClassSignature): ArkClass | null { - const className = classSignature instanceof AliasClassSignature ? classSignature.getOriginName() - : classSignature.getClassName(); + const className = classSignature instanceof AliasClassSignature ? classSignature.getOriginName() : classSignature.getClassName(); return this.getClassWithName(className); } @@ -187,7 +186,7 @@ export class ArkNamespace extends ArkBaseModel implements ArkExport { return Array.from(this.classes.values()); } - public addArkClass(arkClass: ArkClass) { + public addArkClass(arkClass: ArkClass): void { this.classes.set(arkClass.getName(), arkClass); } @@ -205,24 +204,24 @@ export class ArkNamespace extends ArkBaseModel implements ArkExport { return this.exportInfos.get(name); } - public addExportInfo(exportInfo: ExportInfo) { + public addExportInfo(exportInfo: ExportInfo): void { this.exportInfos.set(exportInfo.getExportClauseName(), exportInfo); } - public getDefaultClass() { + public getDefaultClass(): ArkClass { return this.defaultClass; } - public setDefaultClass(defaultClass: ArkClass) { + public setDefaultClass(defaultClass: ArkClass): void { this.defaultClass = defaultClass; } public getAllMethodsUnderThisNamespace(): ArkMethod[] { let methods: ArkMethod[] = []; - this.classes.forEach((cls) => { + this.classes.forEach(cls => { methods.push(...cls.getMethods()); }); - this.namespaces.forEach((ns) => { + this.namespaces.forEach(ns => { methods.push(...ns.getAllMethodsUnderThisNamespace()); }); return methods; @@ -231,7 +230,7 @@ export class ArkNamespace extends ArkBaseModel implements ArkExport { public getAllClassesUnderThisNamespace(): ArkClass[] { let classes: ArkClass[] = []; classes.push(...this.classes.values()); - this.namespaces.forEach((ns) => { + this.namespaces.forEach(ns => { classes.push(...ns.getAllClassesUnderThisNamespace()); }); return classes; @@ -240,13 +239,13 @@ export class ArkNamespace extends ArkBaseModel implements ArkExport { public getAllNamespacesUnderThisNamespace(): ArkNamespace[] { let namespaces: ArkNamespace[] = []; namespaces.push(...this.namespaces.values()); - this.namespaces.forEach((ns) => { + this.namespaces.forEach(ns => { namespaces.push(...ns.getAllNamespacesUnderThisNamespace()); }); return namespaces; } - public getAnonymousClassNumber() { + public getAnonymousClassNumber(): number { return this.anonymousClassNumber++; } @@ -270,4 +269,3 @@ export class ArkNamespace extends ArkBaseModel implements ArkExport { return this.validateFields(['declaringArkFile', 'declaringInstance', 'namespaceSignature', 'defaultClass']); } } - diff --git a/ets2panda/linter/arkanalyzer/src/core/model/ArkSignature.ts b/ets2panda/linter/arkanalyzer/src/core/model/ArkSignature.ts index a7d875221a..16fa6a76b8 100644 --- a/ets2panda/linter/arkanalyzer/src/core/model/ArkSignature.ts +++ b/ets2panda/linter/arkanalyzer/src/core/model/ArkSignature.ts @@ -24,18 +24,11 @@ import { UNKNOWN_CLASS_NAME, UNKNOWN_FILE_NAME, UNKNOWN_NAMESPACE_NAME, - UNKNOWN_PROJECT_NAME + UNKNOWN_PROJECT_NAME, } from '../common/Const'; import { CryptoUtils } from '../../utils/crypto_utils'; -export type Signature = - FileSignature - | NamespaceSignature - | ClassSignature - | MethodSignature - | FieldSignature - | LocalSignature - | AliasTypeSignature; +export type Signature = FileSignature | NamespaceSignature | ClassSignature | MethodSignature | FieldSignature | LocalSignature | AliasTypeSignature; export interface ArkSignature { getSignature(): Signature; @@ -57,11 +50,11 @@ export class FileSignature { this.hashcode = CryptoUtils.hashcode(this.toString()); } - public getProjectName() { + public getProjectName(): string { return this.projectName; } - public getFileName() { + public getFileName(): string { return this.fileName; } @@ -79,25 +72,23 @@ export class NamespaceSignature { private declaringFileSignature: FileSignature; private declaringNamespaceSignature: NamespaceSignature | null; - public static readonly DEFAULT: NamespaceSignature = new NamespaceSignature(UNKNOWN_NAMESPACE_NAME, - FileSignature.DEFAULT, null); + public static readonly DEFAULT: NamespaceSignature = new NamespaceSignature(UNKNOWN_NAMESPACE_NAME, FileSignature.DEFAULT, null); - constructor(namespaceName: string, declaringFileSignature: FileSignature, - declaringNamespaceSignature: NamespaceSignature | null = null) { + constructor(namespaceName: string, declaringFileSignature: FileSignature, declaringNamespaceSignature: NamespaceSignature | null = null) { this.namespaceName = namespaceName; this.declaringFileSignature = declaringFileSignature; this.declaringNamespaceSignature = declaringNamespaceSignature; } - public getNamespaceName() { + public getNamespaceName(): string { return this.namespaceName; } - public getDeclaringFileSignature() { + public getDeclaringFileSignature(): FileSignature { return this.declaringFileSignature; } - public getDeclaringNamespaceSignature() { + public getDeclaringNamespaceSignature(): NamespaceSignature | null { return this.declaringNamespaceSignature; } @@ -123,11 +114,9 @@ export class ClassSignature { private declaringNamespaceSignature: NamespaceSignature | null; private className: string; - public static readonly DEFAULT: ClassSignature = new ClassSignature(UNKNOWN_CLASS_NAME, FileSignature.DEFAULT, - null); + public static readonly DEFAULT: ClassSignature = new ClassSignature(UNKNOWN_CLASS_NAME, FileSignature.DEFAULT, null); - constructor(className: string, declaringFileSignature: FileSignature, - declaringNamespaceSignature: NamespaceSignature | null = null) { + constructor(className: string, declaringFileSignature: FileSignature, declaringNamespaceSignature: NamespaceSignature | null = null) { this.className = className; this.declaringFileSignature = declaringFileSignature; this.declaringNamespaceSignature = declaringNamespaceSignature; @@ -137,7 +126,7 @@ export class ClassSignature { * Returns the declaring file signature. * @returns The declaring file signature. */ - public getDeclaringFileSignature() { + public getDeclaringFileSignature(): FileSignature { return this.declaringFileSignature; } @@ -145,7 +134,7 @@ export class ClassSignature { * Get the declaring namespace's signature. * @returns the declaring namespace's signature. */ - public getDeclaringNamespaceSignature() { + public getDeclaringNamespaceSignature(): NamespaceSignature | null { return this.declaringNamespaceSignature; } @@ -153,7 +142,7 @@ export class ClassSignature { * Get the **string** name of class from the the class signature. The default value is `""`. * @returns The name of this class. */ - public getClassName() { + public getClassName(): string { return this.className; } @@ -172,7 +161,7 @@ export class ClassSignature { return this.className; } - public setClassName(className: string) { + public setClassName(className: string): void { this.className = className; } @@ -238,16 +227,15 @@ export class FieldSignature { this.staticFlag = staticFlag; } - public getDeclaringSignature() { + public getDeclaringSignature(): BaseSignature { return this.declaringSignature; } - public getBaseName() { - return this.declaringSignature instanceof ClassSignature ? this.declaringSignature.getClassName() - : this.declaringSignature.getNamespaceName(); + public getBaseName(): string { + return this.declaringSignature instanceof ClassSignature ? this.declaringSignature.getClassName() : this.declaringSignature.getNamespaceName(); } - public getFieldName() { + public getFieldName(): string { return this.fieldName; } @@ -291,17 +279,17 @@ export class MethodSubSignature { this.staticFlag = staticFlag; } - public getMethodName() { + public getMethodName(): string { return this.methodName; } - public getParameters() { + public getParameters(): MethodParameter[] { return this.parameters; } public getParameterTypes(): Type[] { const parameterTypes: Type[] = []; - this.parameters.forEach((parameter) => { + this.parameters.forEach(parameter => { parameterTypes.push(parameter.getType()); }); return parameterTypes; @@ -320,9 +308,9 @@ export class MethodSubSignature { } public toString(ptrName?: string): string { - let paraStr = ""; - this.getParameterTypes().forEach((parameterType) => { - paraStr += parameterType.toString() + ", "; + let paraStr = ''; + this.getParameterTypes().forEach(parameterType => { + paraStr += parameterType.toString() + ', '; }); paraStr = paraStr.replace(/, $/, ''); let tmpSig = `${ptrName ?? this.getMethodName()}(${paraStr})`; @@ -348,8 +336,10 @@ export class MethodSignature { /** * Return the declaring class signature. * A {@link ClassSignature} includes: - * - File Signature: including the **string** names of the project and file, respectively. The default value of project's name is "%unk" and the default value of file's name is "%unk". - * - Namespace Signature | **null**: it may be a namespace signature or **null**. A namespace signature can indicate its **string** name of namespace and its file signature. + * - File Signature: including the **string** names of the project and file, respectively. + * The default value of project's name is "%unk" and the default value of file's name is "%unk". + * - Namespace Signature | **null**: it may be a namespace signature or **null**. + * A namespace signature can indicate its **string** name of namespace and its file signature. * - Class Name: the **string** name of this class. * @returns The declaring class signature. * @example @@ -361,7 +351,7 @@ export class MethodSignature { ``` * */ - public getDeclaringClassSignature() { + public getDeclaringClassSignature(): ClassSignature { return this.declaringClassSignature; } @@ -371,7 +361,7 @@ export class MethodSignature { * identify the name of the method, its parameters and the return value type. * @returns The sub-signature of this method signature. */ - public getMethodSubSignature() { + public getMethodSubSignature(): MethodSubSignature { return this.methodSubSignature; } @@ -388,12 +378,11 @@ export class MethodSignature { } public isMatch(signature: MethodSignature): boolean { - return ((this.toString() === signature.toString()) && (this.getType().toString() === signature.getType().toString())); + return this.toString() === signature.toString() && this.getType().toString() === signature.getType().toString(); } public getParamLength(): number { - return this.methodSubSignature.getParameters() - .filter(p => !p.getName().startsWith(LEXICAL_ENV_NAME_PREFIX)).length; + return this.methodSubSignature.getParameters().filter(p => !p.getName().startsWith(LEXICAL_ENV_NAME_PREFIX)).length; } } @@ -443,45 +432,48 @@ export class AliasTypeSignature { //TODO, reconstruct export function fieldSignatureCompare(leftSig: FieldSignature, rightSig: FieldSignature): boolean { - if (leftSig.getDeclaringSignature().toString() === rightSig.getDeclaringSignature().toString() && - (leftSig.getFieldName() === rightSig.getFieldName())) { + if (leftSig.getDeclaringSignature().toString() === rightSig.getDeclaringSignature().toString() && leftSig.getFieldName() === rightSig.getFieldName()) { return true; } return false; } export function methodSignatureCompare(leftSig: MethodSignature, rightSig: MethodSignature): boolean { - if (classSignatureCompare(leftSig.getDeclaringClassSignature(), rightSig.getDeclaringClassSignature()) && - methodSubSignatureCompare(leftSig.getMethodSubSignature(), rightSig.getMethodSubSignature())) { + if ( + classSignatureCompare(leftSig.getDeclaringClassSignature(), rightSig.getDeclaringClassSignature()) && + methodSubSignatureCompare(leftSig.getMethodSubSignature(), rightSig.getMethodSubSignature()) + ) { return true; } return false; } export function methodSubSignatureCompare(leftSig: MethodSubSignature, rightSig: MethodSubSignature): boolean { - if ((leftSig.getMethodName() === rightSig.getMethodName()) && arrayCompare(leftSig.getParameterTypes(), - rightSig.getParameterTypes()) && leftSig.getReturnType() === rightSig.getReturnType()) { + if ( + leftSig.getMethodName() === rightSig.getMethodName() && + arrayCompare(leftSig.getParameterTypes(), rightSig.getParameterTypes()) && + leftSig.getReturnType() === rightSig.getReturnType() + ) { return true; } return false; } export function classSignatureCompare(leftSig: ClassSignature, rightSig: ClassSignature): boolean { - if ((fileSignatureCompare(leftSig.getDeclaringFileSignature(), rightSig.getDeclaringFileSignature())) && - (leftSig.getClassName() === rightSig.getClassName())) { + if (fileSignatureCompare(leftSig.getDeclaringFileSignature(), rightSig.getDeclaringFileSignature()) && leftSig.getClassName() === rightSig.getClassName()) { return true; } return false; } export function fileSignatureCompare(leftSig: FileSignature, rightSig: FileSignature): boolean { - if ((leftSig.getFileName() === rightSig.getFileName()) && (leftSig.getProjectName() === rightSig.getProjectName())) { + if (leftSig.getFileName() === rightSig.getFileName() && leftSig.getProjectName() === rightSig.getProjectName()) { return true; } return false; } -function arrayCompare(leftArray: any[], rightArray: any[]) { +function arrayCompare(leftArray: any[], rightArray: any[]): boolean { if (leftArray.length !== rightArray.length) { return false; } @@ -495,4 +487,4 @@ function arrayCompare(leftArray: any[], rightArray: any[]) { export function genSignature4ImportClause(arkFileName: string, importClauseName: string): string { return `<${arkFileName}>.<${importClauseName}>`; -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkClassBuilder.ts b/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkClassBuilder.ts index 62b1f124c0..7c3f169384 100644 --- a/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkClassBuilder.ts +++ b/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkClassBuilder.ts @@ -45,37 +45,40 @@ import { ArkStaticInvokeExpr } from '../../base/Expr'; const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'ArkClassBuilder'); export type ClassLikeNode = - ts.ClassDeclaration | - ts.InterfaceDeclaration | - ts.EnumDeclaration | - ts.ClassExpression | - ts.TypeLiteralNode | - ts.StructDeclaration | - ts.ObjectLiteralExpression; + | ts.ClassDeclaration + | ts.InterfaceDeclaration + | ts.EnumDeclaration + | ts.ClassExpression + | ts.TypeLiteralNode + | ts.StructDeclaration + | ts.ObjectLiteralExpression; type ClassLikeNodeWithMethod = - ts.ClassDeclaration | - ts.InterfaceDeclaration | - ts.EnumDeclaration | - ts.ClassExpression | - ts.TypeLiteralNode | - ts.StructDeclaration; - -export function buildDefaultArkClassFromArkFile(arkFile: ArkFile, defaultClass: ArkClass, astRoot: ts.SourceFile) { + | ts.ClassDeclaration + | ts.InterfaceDeclaration + | ts.EnumDeclaration + | ts.ClassExpression + | ts.TypeLiteralNode + | ts.StructDeclaration; + +export function buildDefaultArkClassFromArkFile(arkFile: ArkFile, defaultClass: ArkClass, astRoot: ts.SourceFile): void { defaultClass.setDeclaringArkFile(arkFile); defaultClass.setCategory(ClassCategory.CLASS); buildDefaultArkClass(defaultClass, astRoot); } -export function buildDefaultArkClassFromArkNamespace(arkNamespace: ArkNamespace, defaultClass: ArkClass, - nsNode: ts.ModuleDeclaration, sourceFile: ts.SourceFile) { +export function buildDefaultArkClassFromArkNamespace( + arkNamespace: ArkNamespace, + defaultClass: ArkClass, + nsNode: ts.ModuleDeclaration, + sourceFile: ts.SourceFile +): void { defaultClass.setDeclaringArkNamespace(arkNamespace); defaultClass.setDeclaringArkFile(arkNamespace.getDeclaringArkFile()); buildDefaultArkClass(defaultClass, sourceFile, nsNode); } -export function buildNormalArkClassFromArkMethod(clsNode: ClassLikeNode, cls: ArkClass, sourceFile: ts.SourceFile, - declaringMethod?: ArkMethod) { +export function buildNormalArkClassFromArkMethod(clsNode: ClassLikeNode, cls: ArkClass, sourceFile: ts.SourceFile, declaringMethod?: ArkMethod): void { const namespace = cls.getDeclaringArkNamespace(); if (namespace) { buildNormalArkClassFromArkNamespace(clsNode, namespace, cls, sourceFile, declaringMethod); @@ -84,14 +87,16 @@ export function buildNormalArkClassFromArkMethod(clsNode: ClassLikeNode, cls: Ar } } -export function buildNormalArkClassFromArkFile(clsNode: ClassLikeNode, arkFile: ArkFile, cls: ArkClass, - sourceFile: ts.SourceFile, declaringMethod?: ArkMethod) { +export function buildNormalArkClassFromArkFile( + clsNode: ClassLikeNode, + arkFile: ArkFile, + cls: ArkClass, + sourceFile: ts.SourceFile, + declaringMethod?: ArkMethod +): void { cls.setDeclaringArkFile(arkFile); cls.setCode(clsNode.getText(sourceFile)); - const { line, character } = ts.getLineAndCharacterOfPosition( - sourceFile, - clsNode.getStart(sourceFile), - ); + const { line, character } = ts.getLineAndCharacterOfPosition(sourceFile, clsNode.getStart(sourceFile)); cls.setLine(line + 1); cls.setColumn(character + 1); @@ -99,15 +104,17 @@ export function buildNormalArkClassFromArkFile(clsNode: ClassLikeNode, arkFile: arkFile.addArkClass(cls); } -export function buildNormalArkClassFromArkNamespace(clsNode: ClassLikeNode, arkNamespace: ArkNamespace, cls: ArkClass, - sourceFile: ts.SourceFile, declaringMethod?: ArkMethod) { +export function buildNormalArkClassFromArkNamespace( + clsNode: ClassLikeNode, + arkNamespace: ArkNamespace, + cls: ArkClass, + sourceFile: ts.SourceFile, + declaringMethod?: ArkMethod +): void { cls.setDeclaringArkNamespace(arkNamespace); cls.setDeclaringArkFile(arkNamespace.getDeclaringArkFile()); cls.setCode(clsNode.getText(sourceFile)); - const { line, character } = ts.getLineAndCharacterOfPosition( - sourceFile, - clsNode.getStart(sourceFile), - ); + const { line, character } = ts.getLineAndCharacterOfPosition(sourceFile, clsNode.getStart(sourceFile)); cls.setLine(line + 1); cls.setColumn(character + 1); @@ -115,21 +122,24 @@ export function buildNormalArkClassFromArkNamespace(clsNode: ClassLikeNode, arkN arkNamespace.addArkClass(cls); } -function buildDefaultArkClass(cls: ArkClass, sourceFile: ts.SourceFile, node?: ts.ModuleDeclaration) { - const defaultArkClassSignature = new ClassSignature(DEFAULT_ARK_CLASS_NAME, - cls.getDeclaringArkFile().getFileSignature(), cls.getDeclaringArkNamespace()?.getSignature() || null); +function buildDefaultArkClass(cls: ArkClass, sourceFile: ts.SourceFile, node?: ts.ModuleDeclaration): void { + const defaultArkClassSignature = new ClassSignature( + DEFAULT_ARK_CLASS_NAME, + cls.getDeclaringArkFile().getFileSignature(), + cls.getDeclaringArkNamespace()?.getSignature() || null + ); cls.setSignature(defaultArkClassSignature); genDefaultArkMethod(cls, sourceFile, node); } -function genDefaultArkMethod(cls: ArkClass, sourceFile: ts.SourceFile, node?: ts.ModuleDeclaration) { +function genDefaultArkMethod(cls: ArkClass, sourceFile: ts.SourceFile, node?: ts.ModuleDeclaration): void { let defaultMethod = new ArkMethod(); buildDefaultArkMethodFromArkClass(cls, defaultMethod, sourceFile, node); cls.setDefaultArkMethod(defaultMethod); } -export function buildNormalArkClass(clsNode: ClassLikeNode, cls: ArkClass, sourceFile: ts.SourceFile, declaringMethod?: ArkMethod) { +export function buildNormalArkClass(clsNode: ClassLikeNode, cls: ArkClass, sourceFile: ts.SourceFile, declaringMethod?: ArkMethod): void { switch (clsNode.kind) { case ts.SyntaxKind.StructDeclaration: buildStruct2ArkClass(clsNode, cls, sourceFile, declaringMethod); @@ -153,19 +163,17 @@ export function buildNormalArkClass(clsNode: ClassLikeNode, cls: ArkClass, sourc buildObjectLiteralExpression2ArkClass(clsNode, cls, sourceFile, declaringMethod); break; default: - ; } IRUtils.setComments(cls, clsNode, sourceFile, cls.getDeclaringArkFile().getScene().getOptions()); } -function init4InstanceInitMethod(cls: ArkClass) { +function init4InstanceInitMethod(cls: ArkClass): void { const instanceInit = new ArkMethod(); instanceInit.setDeclaringArkClass(cls); instanceInit.setIsGeneratedFlag(true); const methodSubSignature = ArkSignatureBuilder.buildMethodSubSignatureFromMethodName(INSTANCE_INIT_METHOD_NAME); methodSubSignature.setReturnType(VoidType.getInstance()); - const methodSignature = new MethodSignature(instanceInit.getDeclaringArkClass().getSignature(), - methodSubSignature); + const methodSignature = new MethodSignature(instanceInit.getDeclaringArkClass().getSignature(), methodSubSignature); instanceInit.setImplementationSignature(methodSignature); instanceInit.setLineCol(0); @@ -174,14 +182,13 @@ function init4InstanceInitMethod(cls: ArkClass) { cls.setInstanceInitMethod(instanceInit); } -function init4StaticInitMethod(cls: ArkClass) { +function init4StaticInitMethod(cls: ArkClass): void { const staticInit = new ArkMethod(); staticInit.setDeclaringArkClass(cls); staticInit.setIsGeneratedFlag(true); const methodSubSignature = ArkSignatureBuilder.buildMethodSubSignatureFromMethodName(STATIC_INIT_METHOD_NAME); methodSubSignature.setReturnType(VoidType.getInstance()); - const methodSignature = new MethodSignature(staticInit.getDeclaringArkClass().getSignature(), - methodSubSignature); + const methodSignature = new MethodSignature(staticInit.getDeclaringArkClass().getSignature(), methodSubSignature); staticInit.setImplementationSignature(methodSignature); staticInit.setLineCol(0); @@ -190,14 +197,13 @@ function init4StaticInitMethod(cls: ArkClass) { cls.setStaticInitMethod(staticInit); } -function buildStruct2ArkClass(clsNode: ts.StructDeclaration, cls: ArkClass, sourceFile: ts.SourceFile, declaringMethod?: ArkMethod) { +function buildStruct2ArkClass(clsNode: ts.StructDeclaration, cls: ArkClass, sourceFile: ts.SourceFile, declaringMethod?: ArkMethod): void { const className = genClassName(clsNode.name ? clsNode.name.text : '', cls, declaringMethod); - const classSignature = new ClassSignature(className, - cls.getDeclaringArkFile().getFileSignature(), cls.getDeclaringArkNamespace()?.getSignature() || null); + const classSignature = new ClassSignature(className, cls.getDeclaringArkFile().getFileSignature(), cls.getDeclaringArkNamespace()?.getSignature() || null); cls.setSignature(classSignature); if (clsNode.typeParameters) { - buildTypeParameters(clsNode.typeParameters, sourceFile, cls).forEach((typeParameter) => { + buildTypeParameters(clsNode.typeParameters, sourceFile, cls).forEach(typeParameter => { cls.addGenericType(typeParameter); }); } @@ -213,14 +219,13 @@ function buildStruct2ArkClass(clsNode: ts.StructDeclaration, cls: ArkClass, sour buildArkClassMembers(clsNode, cls, sourceFile); } -function buildClass2ArkClass(clsNode: ts.ClassDeclaration | ts.ClassExpression, cls: ArkClass, sourceFile: ts.SourceFile, declaringMethod?: ArkMethod) { +function buildClass2ArkClass(clsNode: ts.ClassDeclaration | ts.ClassExpression, cls: ArkClass, sourceFile: ts.SourceFile, declaringMethod?: ArkMethod): void { const className = genClassName(clsNode.name ? clsNode.name.text : '', cls, declaringMethod); - const classSignature = new ClassSignature(className, - cls.getDeclaringArkFile().getFileSignature(), cls.getDeclaringArkNamespace()?.getSignature() || null); + const classSignature = new ClassSignature(className, cls.getDeclaringArkFile().getFileSignature(), cls.getDeclaringArkNamespace()?.getSignature() || null); cls.setSignature(classSignature); if (clsNode.typeParameters) { - buildTypeParameters(clsNode.typeParameters, sourceFile, cls).forEach((typeParameter) => { + buildTypeParameters(clsNode.typeParameters, sourceFile, cls).forEach(typeParameter => { cls.addGenericType(typeParameter); }); } @@ -250,14 +255,13 @@ function initHeritage(heritageClauses: Map, cls: ArkClass): void } } -function buildInterface2ArkClass(clsNode: ts.InterfaceDeclaration, cls: ArkClass, sourceFile: ts.SourceFile, declaringMethod?: ArkMethod) { +function buildInterface2ArkClass(clsNode: ts.InterfaceDeclaration, cls: ArkClass, sourceFile: ts.SourceFile, declaringMethod?: ArkMethod): void { const className = genClassName(clsNode.name ? clsNode.name.text : '', cls, declaringMethod); - const classSignature = new ClassSignature(className, - cls.getDeclaringArkFile().getFileSignature(), cls.getDeclaringArkNamespace()?.getSignature() || null); + const classSignature = new ClassSignature(className, cls.getDeclaringArkFile().getFileSignature(), cls.getDeclaringArkNamespace()?.getSignature() || null); cls.setSignature(classSignature); if (clsNode.typeParameters) { - buildTypeParameters(clsNode.typeParameters, sourceFile, cls).forEach((typeParameter) => { + buildTypeParameters(clsNode.typeParameters, sourceFile, cls).forEach(typeParameter => { cls.addGenericType(typeParameter); }); } @@ -272,10 +276,9 @@ function buildInterface2ArkClass(clsNode: ts.InterfaceDeclaration, cls: ArkClass buildArkClassMembers(clsNode, cls, sourceFile); } -function buildEnum2ArkClass(clsNode: ts.EnumDeclaration, cls: ArkClass, sourceFile: ts.SourceFile, declaringMethod?: ArkMethod) { +function buildEnum2ArkClass(clsNode: ts.EnumDeclaration, cls: ArkClass, sourceFile: ts.SourceFile, declaringMethod?: ArkMethod): void { const className = genClassName(clsNode.name ? clsNode.name.text : '', cls, declaringMethod); - const classSignature = new ClassSignature(className, - cls.getDeclaringArkFile().getFileSignature(), cls.getDeclaringArkNamespace()?.getSignature() || null); + const classSignature = new ClassSignature(className, cls.getDeclaringArkFile().getFileSignature(), cls.getDeclaringArkNamespace()?.getSignature() || null); cls.setSignature(classSignature); cls.setModifiers(buildModifiers(clsNode)); @@ -287,28 +290,28 @@ function buildEnum2ArkClass(clsNode: ts.EnumDeclaration, cls: ArkClass, sourceFi buildArkClassMembers(clsNode, cls, sourceFile); } -function buildTypeLiteralNode2ArkClass(clsNode: ts.TypeLiteralNode, cls: ArkClass, - sourceFile: ts.SourceFile, declaringMethod?: ArkMethod) { +function buildTypeLiteralNode2ArkClass(clsNode: ts.TypeLiteralNode, cls: ArkClass, sourceFile: ts.SourceFile, declaringMethod?: ArkMethod): void { const className = genClassName('', cls, declaringMethod); - const classSignature = new ClassSignature(className, - cls.getDeclaringArkFile().getFileSignature(), cls.getDeclaringArkNamespace()?.getSignature() || null); + const classSignature = new ClassSignature(className, cls.getDeclaringArkFile().getFileSignature(), cls.getDeclaringArkNamespace()?.getSignature() || null); cls.setSignature(classSignature); - cls.setCategory(ClassCategory.TYPE_LITERAL); if (ts.isTypeAliasDeclaration(clsNode.parent) && clsNode.parent.typeParameters) { - buildTypeParameters(clsNode.parent.typeParameters, sourceFile, cls).forEach((typeParameter) => { + buildTypeParameters(clsNode.parent.typeParameters, sourceFile, cls).forEach(typeParameter => { cls.addGenericType(typeParameter); }); } buildArkClassMembers(clsNode, cls, sourceFile); } -function buildObjectLiteralExpression2ArkClass(clsNode: ts.ObjectLiteralExpression, cls: ArkClass, - sourceFile: ts.SourceFile, declaringMethod?: ArkMethod) { +function buildObjectLiteralExpression2ArkClass( + clsNode: ts.ObjectLiteralExpression, + cls: ArkClass, + sourceFile: ts.SourceFile, + declaringMethod?: ArkMethod +): void { const className = genClassName('', cls, declaringMethod); - const classSignature = new ClassSignature(className, - cls.getDeclaringArkFile().getFileSignature(), cls.getDeclaringArkNamespace()?.getSignature() || null); + const classSignature = new ClassSignature(className, cls.getDeclaringArkFile().getFileSignature(), cls.getDeclaringArkNamespace()?.getSignature() || null); cls.setSignature(classSignature); cls.setCategory(ClassCategory.OBJECT); @@ -318,7 +321,7 @@ function buildObjectLiteralExpression2ArkClass(clsNode: ts.ObjectLiteralExpressi init4InstanceInitMethod(cls); const instanceIRTransformer = new ArkIRTransformer(sourceFile, cls.getInstanceInitMethod()); const instanceFieldInitializerStmts: Stmt[] = []; - clsNode.properties.forEach((property) => { + clsNode.properties.forEach(property => { if (ts.isPropertyAssignment(property) || ts.isShorthandPropertyAssignment(property) || ts.isSpreadAssignment(property)) { const arkField = buildProperty2ArkField(property, sourceFile, cls); if (ts.isPropertyAssignment(property)) { @@ -332,7 +335,7 @@ function buildObjectLiteralExpression2ArkClass(clsNode: ts.ObjectLiteralExpressi } }); buildInitMethod(cls.getInstanceInitMethod(), instanceFieldInitializerStmts, instanceIRTransformer.getThisLocal()); - arkMethods.forEach((mtd) => { + arkMethods.forEach(mtd => { checkAndUpdateMethod(mtd, cls); cls.addMethod(mtd); }); @@ -348,7 +351,7 @@ function genClassName(declaringName: string, cls: ArkClass, declaringMethod?: Ar return declaringName + suffix; } -function buildArkClassMembers(clsNode: ClassLikeNode, cls: ArkClass, sourceFile: ts.SourceFile) { +function buildArkClassMembers(clsNode: ClassLikeNode, cls: ArkClass, sourceFile: ts.SourceFile): void { if (ts.isObjectLiteralExpression(clsNode)) { return; } @@ -366,7 +369,7 @@ function buildArkClassMembers(clsNode: ClassLikeNode, cls: ArkClass, sourceFile: const staticInitStmts: Stmt[] = []; const instanceInitStmts: Stmt[] = []; let staticBlockId = 0; - clsNode.members.forEach((member) => { + clsNode.members.forEach(member => { if (ts.isPropertyDeclaration(member) || ts.isPropertySignature(member)) { const arkField = buildProperty2ArkField(member, sourceFile, cls); if (ts.isClassDeclaration(clsNode) || ts.isClassExpression(clsNode) || ts.isStructDeclaration(clsNode)) { @@ -374,8 +377,9 @@ function buildArkClassMembers(clsNode: ClassLikeNode, cls: ArkClass, sourceFile: getInitStmts(staticIRTransformer, arkField, member.initializer); arkField.getInitializer().forEach(stmt => staticInitStmts.push(stmt)); } else { - if (!instanceIRTransformer) + if (!instanceIRTransformer) { console.log(clsNode.getText(sourceFile)); + } getInitStmts(instanceIRTransformer, arkField, member.initializer); arkField.getInitializer().forEach(stmt => instanceInitStmts.push(stmt)); } @@ -406,7 +410,7 @@ function buildArkClassMembers(clsNode: ClassLikeNode, cls: ArkClass, sourceFile: } function buildMethodsForClass(clsNode: ClassLikeNodeWithMethod, cls: ArkClass, sourceFile: ts.SourceFile): void { - clsNode.members.forEach((member) => { + clsNode.members.forEach(member => { if ( ts.isMethodDeclaration(member) || ts.isConstructorDeclaration(member) || @@ -431,7 +435,7 @@ function buildParameterProperty2ArkField(params: ts.NodeArray { + params.forEach(parameter => { if (parameter.modifiers === undefined || !ts.isIdentifier(parameter.name)) { return; } @@ -445,7 +449,7 @@ function buildParameterProperty2ArkField(params: ts.NodeArray { + clsNode.members.forEach(member => { if (ts.isClassStaticBlockDeclaration(member)) { const staticBlockMethod = new ArkMethod(); staticBlockMethod.setDeclaringArkClass(cls); @@ -471,10 +474,7 @@ function buildStaticBlocksForClass(clsNode: ClassLikeNodeWithMethod, cls: ArkCla const methodSignature = new MethodSignature(cls.getSignature(), methodSubSignature); staticBlockMethodSignatures.push(methodSignature); staticBlockMethod.setImplementationSignature(methodSignature); - const { line, character } = ts.getLineAndCharacterOfPosition( - sourceFile, - member.getStart(sourceFile), - ); + const { line, character } = ts.getLineAndCharacterOfPosition(sourceFile, member.getStart(sourceFile)); staticBlockMethod.setLine(line + 1); staticBlockMethod.setColumn(character + 1); @@ -487,18 +487,13 @@ function buildStaticBlocksForClass(clsNode: ClassLikeNodeWithMethod, cls: ArkCla return staticBlockMethodSignatures; } -function getInitStmts(transformer: ArkIRTransformer, field: ArkField, initNode?: ts.Node) { +function getInitStmts(transformer: ArkIRTransformer, field: ArkField, initNode?: ts.Node): void { if (initNode) { const stmts: Stmt[] = []; - let { - value: initValue, - valueOriginalPositions: initPositions, - stmts: initStmts, - } = transformer.tsNodeToValueAndStmts(initNode); + let { value: initValue, valueOriginalPositions: initPositions, stmts: initStmts } = transformer.tsNodeToValueAndStmts(initNode); initStmts.forEach(stmt => stmts.push(stmt)); if (IRUtils.moreThanOneAddress(initValue)) { - ({ value: initValue, valueOriginalPositions: initPositions, stmts: initStmts } = - transformer.generateAssignStmtForValue(initValue, initPositions)); + ({ value: initValue, valueOriginalPositions: initPositions, stmts: initStmts } = transformer.generateAssignStmtForValue(initValue, initPositions)); initStmts.forEach(stmt => stmts.push(stmt)); } diff --git a/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkExportBuilder.ts b/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkExportBuilder.ts index 9bfee8c4c8..c66aa142a4 100644 --- a/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkExportBuilder.ts +++ b/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkExportBuilder.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -23,6 +23,7 @@ import { ArkBaseModel, ModifierType } from '../ArkBaseModel'; import { IRUtils } from '../../common/IRUtils'; import { ArkClass } from '../ArkClass'; import { buildNormalArkClassFromArkFile } from './ArkClassBuilder'; +import { ArkNamespace } from '../ArkNamespace'; export { buildExportInfo, buildExportAssignment, buildExportDeclaration }; @@ -43,8 +44,7 @@ function buildExportInfo(arkInstance: ArkExport, arkFile: ArkFile, line: LineCol .build(); } - -export function buildDefaultExportInfo(im: FromInfo, file: ArkFile, arkExport?: ArkExport) { +export function buildDefaultExportInfo(im: FromInfo, file: ArkFile, arkExport?: ArkExport): ExportInfo { return new ExportInfo.Builder() .exportClauseType(arkExport?.getExportType() ?? ExportType.CLASS) .exportClauseName(im.getOriginName()) @@ -64,7 +64,7 @@ function buildExportDeclaration(node: ts.ExportDeclaration, sourceFile: ts.Sourc let exportInfos: ExportInfo[] = []; // just like: export {xxx as x} from './yy' if (node.exportClause && ts.isNamedExports(node.exportClause) && node.exportClause.elements) { - node.exportClause.elements.forEach((element) => { + node.exportClause.elements.forEach(element => { let builder = new ExportInfo.Builder() .exportClauseType(ExportType.UNKNOWN) .exportClauseName(element.name.text) @@ -93,9 +93,11 @@ function buildExportDeclaration(node: ts.ExportDeclaration, sourceFile: ts.Sourc .setLeadingComments(IRUtils.getCommentsMetadata(node, sourceFile, arkFile.getScene().getOptions(), true)) .setTrailingComments(IRUtils.getCommentsMetadata(node, sourceFile, arkFile.getScene().getOptions(), false)) .originTsPosition(originTsPosition); - if (node.exportClause && ts.isNamespaceExport(node.exportClause) && ts.isIdentifier(node.exportClause.name)) { // just like: export * as xx from './yy' + if (node.exportClause && ts.isNamespaceExport(node.exportClause) && ts.isIdentifier(node.exportClause.name)) { + // just like: export * as xx from './yy' exportInfos.push(builder1.exportClauseName(node.exportClause.name.text).build()); - } else if (!node.exportClause && node.moduleSpecifier) { // just like: export * from './yy' + } else if (!node.exportClause && node.moduleSpecifier) { + // just like: export * from './yy' exportInfos.push(builder1.exportClauseName(ALL).build()); } return exportInfos; @@ -122,17 +124,19 @@ function buildExportAssignment(node: ts.ExportAssignment, sourceFile: ts.SourceF .declaringArkFile(arkFile) .exportClauseName(DEFAULT) .setLeadingComments(IRUtils.getCommentsMetadata(node, sourceFile, arkFile.getScene().getOptions(), true)) - .setTrailingComments(IRUtils.getCommentsMetadata(node, sourceFile, arkFile.getScene().getOptions(), false)) + .setTrailingComments(IRUtils.getCommentsMetadata(node, sourceFile, arkFile.getScene().getOptions(), false)); if (ts.isNewExpression(node.expression) && ts.isClassExpression(node.expression.expression)) { let cls: ArkClass = new ArkClass(); buildNormalArkClassFromArkFile(node.expression.expression, arkFile, cls, sourceFile); } - if (ts.isIdentifier(node.expression)) { // just like: export default xx + if (ts.isIdentifier(node.expression)) { + // just like: export default xx exportInfo.nameBeforeAs(node.expression.text); - } else if (ts.isAsExpression(node.expression)) { // just like: export default xx as YY - exportInfo.nameBeforeAs(node.expression.expression.getText(sourceFile)) + } else if (ts.isAsExpression(node.expression)) { + // just like: export default xx as YY + exportInfo.nameBeforeAs(node.expression.expression.getText(sourceFile)); } exportInfos.push(exportInfo.build()); @@ -145,22 +149,24 @@ function buildExportAssignment(node: ts.ExportAssignment, sourceFile: ts.SourceF * @param sourceFile * @param arkFile */ -export function buildExportVariableStatement(node: ts.VariableStatement, sourceFile: ts.SourceFile, arkFile: ArkFile): ExportInfo[] { +export function buildExportVariableStatement(node: ts.VariableStatement, sourceFile: ts.SourceFile, arkFile: ArkFile, namespace?: ArkNamespace): ExportInfo[] { let exportInfos: ExportInfo[] = []; const originTsPosition = LineColPosition.buildFromNode(node, sourceFile); const modifiers = node.modifiers ? buildModifiers(node) : 0; const tsSourceCode = node.getText(sourceFile); node.declarationList.declarations.forEach(dec => { - const exportInfo = new ExportInfo.Builder() + const exportInfoBuilder = new ExportInfo.Builder() .exportClauseName(dec.name.getText(sourceFile)) .exportClauseType(ExportType.LOCAL) .modifiers(modifiers) .tsSourceCode(tsSourceCode) .originTsPosition(originTsPosition) - .declaringArkFile(arkFile) - .build(); - exportInfos.push(exportInfo); - }) + .declaringArkFile(arkFile); + if (namespace) { + exportInfoBuilder.declaringArkNamespace(namespace); + } + exportInfos.push(exportInfoBuilder.build()); + }); return exportInfos; } diff --git a/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkFieldBuilder.ts b/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkFieldBuilder.ts index f6db292b17..ede55e7c93 100644 --- a/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkFieldBuilder.ts +++ b/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkFieldBuilder.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -29,9 +29,11 @@ const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'ArkFieldBuilder'); export type PropertyLike = ts.PropertyDeclaration | ts.PropertyAssignment; -export function buildProperty2ArkField(member: ts.PropertyDeclaration | ts.PropertyAssignment | ts.ShorthandPropertyAssignment - | ts.SpreadAssignment | ts.PropertySignature | ts.EnumMember, sourceFile: ts.SourceFile, cls: ArkClass): ArkField { - +export function buildProperty2ArkField( + member: ts.PropertyDeclaration | ts.PropertyAssignment | ts.ShorthandPropertyAssignment | ts.SpreadAssignment | ts.PropertySignature | ts.EnumMember, + sourceFile: ts.SourceFile, + cls: ArkClass +): ArkField { let field = new ArkField(); field.setCategory(mapSyntaxKindToFieldOriginType(member.kind) as FieldCategory); field.setCode(member.getText(sourceFile)); @@ -45,7 +47,7 @@ export function buildProperty2ArkField(member: ts.PropertyDeclaration | ts.Prope } else if (ts.isPropertyAccessExpression(member.name.expression)) { fieldName = handlePropertyAccessExpression(member.name.expression); } else { - logger.warn("Other property expression type found!"); + logger.warn('Other property expression type found!'); } } else if (member.name && (ts.isIdentifier(member.name) || ts.isLiteralExpression(member.name))) { fieldName = member.name.text; @@ -54,11 +56,11 @@ export function buildProperty2ArkField(member: ts.PropertyDeclaration | ts.Prope fieldName = propertyName.substring(1); field.addModifier(ModifierType.PRIVATE); } else { - logger.warn("Other type of property name found!"); + logger.warn('Other type of property name found!'); } let fieldType: Type = UnknownType.getInstance(); - if ((ts.isPropertyDeclaration(member) || ts.isPropertySignature(member))) { + if (ts.isPropertyDeclaration(member) || ts.isPropertySignature(member)) { if (member.modifiers) { field.addModifier(buildModifiers(member)); } @@ -85,7 +87,7 @@ export function buildProperty2ArkField(member: ts.PropertyDeclaration | ts.Prope return field; } -export function buildIndexSignature2ArkField(member: ts.IndexSignatureDeclaration, sourceFile: ts.SourceFile, cls: ArkClass) { +export function buildIndexSignature2ArkField(member: ts.IndexSignatureDeclaration, sourceFile: ts.SourceFile, cls: ArkClass): void { const field = new ArkField(); field.setCode(member.getText(sourceFile)); field.setCategory(mapSyntaxKindToFieldOriginType(member.kind) as FieldCategory); @@ -106,7 +108,7 @@ export function buildIndexSignature2ArkField(member: ts.IndexSignatureDeclaratio cls.addField(field); } -export function buildGetAccessor2ArkField(member: ts.GetAccessorDeclaration, mthd: ArkMethod, sourceFile: ts.SourceFile) { +export function buildGetAccessor2ArkField(member: ts.GetAccessorDeclaration, mthd: ArkMethod, sourceFile: ts.SourceFile): void { let cls = mthd.getDeclaringArkClass(); let field = new ArkField(); field.setDeclaringArkClass(cls); @@ -118,8 +120,7 @@ export function buildGetAccessor2ArkField(member: ts.GetAccessorDeclaration, mth let fieldName = member.getText(sourceFile); if (ts.isIdentifier(member.name) || ts.isLiteralExpression(member.name)) { fieldName = member.name.text; - } - else if (ts.isComputedPropertyName(member.name)) { + } else if (ts.isComputedPropertyName(member.name)) { if (ts.isIdentifier(member.name.expression)) { let propertyName = member.name.expression.text; fieldName = propertyName; @@ -128,11 +129,10 @@ export function buildGetAccessor2ArkField(member: ts.GetAccessorDeclaration, mth } else if (ts.isLiteralExpression(member.name.expression)) { fieldName = member.name.expression.text; } else { - logger.warn("Other type of computed property name found!"); + logger.warn('Other type of computed property name found!'); } - } - else { - logger.warn("Please contact developers to support new type of GetAccessor name!"); + } else { + logger.warn('Please contact developers to support new type of GetAccessor name!'); } const fieldType = mthd.getReturnType(); @@ -169,7 +169,6 @@ function mapSyntaxKindToFieldOriginType(syntaxKind: ts.SyntaxKind): FieldCategor fieldOriginType = FieldCategory.GET_ACCESSOR; break; default: - ; } return fieldOriginType; -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkFileBuilder.ts b/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkFileBuilder.ts index 52935cbb5b..1e201453b1 100644 --- a/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkFileBuilder.ts +++ b/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkFileBuilder.ts @@ -40,9 +40,24 @@ import { ARKTS_STATIC_MARK } from '../../common/Const'; const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'ArkFileBuilder'); -export const notStmtOrExprKind = ['ModuleDeclaration', 'ClassDeclaration', 'InterfaceDeclaration', 'EnumDeclaration', 'ExportDeclaration', - 'ExportAssignment', 'MethodDeclaration', 'Constructor', 'FunctionDeclaration', 'GetAccessor', 'SetAccessor', 'ArrowFunction', - 'FunctionExpression', 'MethodSignature', 'ConstructSignature', 'CallSignature']; +export const notStmtOrExprKind = [ + 'ModuleDeclaration', + 'ClassDeclaration', + 'InterfaceDeclaration', + 'EnumDeclaration', + 'ExportDeclaration', + 'ExportAssignment', + 'MethodDeclaration', + 'Constructor', + 'FunctionDeclaration', + 'GetAccessor', + 'SetAccessor', + 'ArrowFunction', + 'FunctionExpression', + 'MethodSignature', + 'ConstructSignature', + 'CallSignature', +]; /** * Entry of building ArkFile instance @@ -50,8 +65,7 @@ export const notStmtOrExprKind = ['ModuleDeclaration', 'ClassDeclaration', 'Inte * @param arkFile * @returns */ -export function buildArkFileFromFile(absoluteFilePath: string, projectDir: string, arkFile: ArkFile, - projectName: string) { +export function buildArkFileFromFile(absoluteFilePath: string, projectDir: string, arkFile: ArkFile, projectName: string): void { arkFile.setFilePath(absoluteFilePath); arkFile.setProjectDir(projectDir); @@ -59,14 +73,7 @@ export function buildArkFileFromFile(absoluteFilePath: string, projectDir: strin arkFile.setFileSignature(fileSignature); arkFile.setCode(fs.readFileSync(arkFile.getFilePath(), 'utf8')); - const sourceFile = ts.createSourceFile( - arkFile.getName(), - arkFile.getCode(), - ts.ScriptTarget.Latest, - true, - undefined, - ETS_COMPILER_OPTIONS, - ); + const sourceFile = ts.createSourceFile(arkFile.getName(), arkFile.getCode(), ts.ScriptTarget.Latest, true, undefined, ETS_COMPILER_OPTIONS); genDefaultArkClass(arkFile, sourceFile); buildArkFile(arkFile, sourceFile); } @@ -78,13 +85,11 @@ export function buildArkFileFromFile(absoluteFilePath: string, projectDir: strin * @param astRoot * @returns */ -function buildArkFile(arkFile: ArkFile, astRoot: ts.SourceFile) { +function buildArkFile(arkFile: ArkFile, astRoot: ts.SourceFile): void { const statements = astRoot.statements; const namespaces: ArkNamespace[] = []; - statements.forEach((child) => { - if ( - ts.isModuleDeclaration(child) - ) { + statements.forEach(child => { + if (ts.isModuleDeclaration(child)) { let ns: ArkNamespace = new ArkNamespace(); ns.setDeclaringArkFile(arkFile); @@ -93,12 +98,7 @@ function buildArkFile(arkFile: ArkFile, astRoot: ts.SourceFile) { if (ns.isExported()) { arkFile.addExportInfo(buildExportInfo(ns, arkFile, LineColPosition.buildFromNode(child, astRoot))); } - } else if ( - ts.isClassDeclaration(child) || - ts.isInterfaceDeclaration(child) || - ts.isEnumDeclaration(child) || - ts.isStructDeclaration(child) - ) { + } else if (ts.isClassDeclaration(child) || ts.isInterfaceDeclaration(child) || ts.isEnumDeclaration(child) || ts.isStructDeclaration(child)) { let cls: ArkClass = new ArkClass(); buildNormalArkClassFromArkFile(child, arkFile, cls, astRoot); @@ -126,15 +126,11 @@ function buildArkFile(arkFile: ArkFile, astRoot: ts.SourceFile) { if (mthd.isExported()) { arkFile.addExportInfo(buildExportInfo(mthd, arkFile, LineColPosition.buildFromNode(child, astRoot))); } - } else if ( - ts.isImportEqualsDeclaration(child) || - ts.isImportDeclaration(child) - ) { + } else if (ts.isImportEqualsDeclaration(child) || ts.isImportDeclaration(child)) { let importInfos = buildImportInfo(child, astRoot, arkFile); - importInfos?.forEach((element) => { + importInfos?.forEach(element => { element.setDeclaringArkFile(arkFile); arkFile.addImportInfo(element); - }); } else if (ts.isExportDeclaration(child)) { buildExportDeclaration(child, astRoot, arkFile).forEach(item => arkFile.addExportInfo(item)); @@ -161,13 +157,10 @@ function buildArkFile(arkFile: ArkFile, astRoot: ts.SourceFile) { }); } -function genDefaultArkClass(arkFile: ArkFile, astRoot: ts.SourceFile) { +function genDefaultArkClass(arkFile: ArkFile, astRoot: ts.SourceFile): void { let defaultClass = new ArkClass(); buildDefaultArkClassFromArkFile(arkFile, defaultClass, astRoot); arkFile.setDefaultClass(defaultClass); arkFile.addArkClass(defaultClass); } - - - diff --git a/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkImportBuilder.ts b/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkImportBuilder.ts index e73d267268..432f64acd1 100644 --- a/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkImportBuilder.ts +++ b/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkImportBuilder.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -20,7 +20,6 @@ import { buildModifiers } from './builderUtils'; import { IRUtils } from '../../common/IRUtils'; import { ArkFile } from '../ArkFile'; - export function buildImportInfo(node: ts.ImportEqualsDeclaration | ts.ImportDeclaration, sourceFile: ts.SourceFile, arkFile: ArkFile): ImportInfo[] { if (ts.isImportDeclaration(node)) { return buildImportDeclarationNode(node, sourceFile, arkFile); @@ -59,9 +58,10 @@ function buildImportDeclarationNode(node: ts.ImportDeclaration, sourceFile: ts.S //just like: import fs from 'fs' if (node.importClause && node.importClause.name && ts.isIdentifier(node.importClause.name)) { let importClauseName = node.importClause.name.text; + const pos = LineColPosition.buildFromNode(node.importClause.name, sourceFile); let importType = 'Identifier'; let importInfo = new ImportInfo(); - importInfo.build(importClauseName, importType, importFrom, originTsPosition, modifiers); + importInfo.build(importClauseName, importType, importFrom, pos, modifiers); importInfo.setTsSourceCode(tsSourceCode); IRUtils.setComments(importInfo, node, sourceFile, arkFile.getScene().getOptions()); importInfos.push(importInfo); @@ -71,18 +71,19 @@ function buildImportDeclarationNode(node: ts.ImportDeclaration, sourceFile: ts.S if (node.importClause && node.importClause.namedBindings && ts.isNamedImports(node.importClause.namedBindings)) { let importType = 'NamedImports'; if (node.importClause.namedBindings.elements) { - node.importClause.namedBindings.elements.forEach((element) => { + node.importClause.namedBindings.elements.forEach(element => { if (element.name && ts.isIdentifier(element.name)) { let importClauseName = element.name.text; + const pos = LineColPosition.buildFromNode(element, sourceFile); if (element.propertyName && ts.isIdentifier(element.propertyName)) { let importInfo = new ImportInfo(); - importInfo.build(importClauseName, importType, importFrom, originTsPosition, modifiers, element.propertyName.text); + importInfo.build(importClauseName, importType, importFrom, pos, modifiers, element.propertyName.text); importInfo.setTsSourceCode(tsSourceCode); IRUtils.setComments(importInfo, node, sourceFile, arkFile.getScene().getOptions()); importInfos.push(importInfo); } else { let importInfo = new ImportInfo(); - importInfo.build(importClauseName, importType, importFrom, originTsPosition, modifiers); + importInfo.build(importClauseName, importType, importFrom, pos, modifiers); importInfo.setTsSourceCode(tsSourceCode); IRUtils.setComments(importInfo, node, sourceFile, arkFile.getScene().getOptions()); importInfos.push(importInfo); @@ -99,7 +100,8 @@ function buildImportDeclarationNode(node: ts.ImportDeclaration, sourceFile: ts.S let importClauseName = node.importClause.namedBindings.name.text; let importInfo = new ImportInfo(); let nameBeforeAs = '*'; - importInfo.build(importClauseName, importType, importFrom, originTsPosition, modifiers, nameBeforeAs); + const pos = LineColPosition.buildFromNode(node.importClause.namedBindings.name, sourceFile); + importInfo.build(importClauseName, importType, importFrom, pos, modifiers, nameBeforeAs); importInfo.setTsSourceCode(tsSourceCode); IRUtils.setComments(importInfo, node, sourceFile, arkFile.getScene().getOptions()); importInfos.push(importInfo); @@ -119,8 +121,12 @@ function buildImportEqualsDeclarationNode(node: ts.ImportEqualsDeclaration, sour if (node.modifiers) { modifiers = buildModifiers(node); } - if (node.moduleReference && ts.isExternalModuleReference(node.moduleReference) && - node.moduleReference.expression && ts.isStringLiteral(node.moduleReference.expression)) { + if ( + node.moduleReference && + ts.isExternalModuleReference(node.moduleReference) && + node.moduleReference.expression && + ts.isStringLiteral(node.moduleReference.expression) + ) { let importFrom = node.moduleReference.expression.text; let importClauseName = node.name.text; let importInfo = new ImportInfo(); diff --git a/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkMethodBuilder.ts b/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkMethodBuilder.ts index d124679e6b..29221c377c 100644 --- a/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkMethodBuilder.ts +++ b/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkMethodBuilder.ts @@ -39,14 +39,7 @@ import { BasicBlock } from '../../graph/BasicBlock'; import { Local } from '../../base/Local'; import { Value } from '../../base/Value'; import { CONSTRUCTOR_NAME, SUPER_NAME, THIS_NAME } from '../../common/TSConst'; -import { - ANONYMOUS_METHOD_PREFIX, - CALL_SIGNATURE_NAME, - DEFAULT_ARK_CLASS_NAME, - DEFAULT_ARK_METHOD_NAME, - NAME_DELIMITER, - NAME_PREFIX, -} from '../../common/Const'; +import { ANONYMOUS_METHOD_PREFIX, CALL_SIGNATURE_NAME, DEFAULT_ARK_CLASS_NAME, DEFAULT_ARK_METHOD_NAME, NAME_DELIMITER, NAME_PREFIX } from '../../common/Const'; import { ArkSignatureBuilder } from './ArkSignatureBuilder'; import { IRUtils } from '../../common/IRUtils'; import { ArkErrorCode } from '../../common/ArkError'; @@ -54,19 +47,18 @@ import { ArkErrorCode } from '../../common/ArkError'; const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'ArkMethodBuilder'); export type MethodLikeNode = - ts.FunctionDeclaration | - ts.MethodDeclaration | - ts.ConstructorDeclaration | - ts.ArrowFunction | - ts.AccessorDeclaration | - ts.FunctionExpression | - ts.MethodSignature | - ts.ConstructSignatureDeclaration | - ts.CallSignatureDeclaration | - ts.FunctionTypeNode; - -export function buildDefaultArkMethodFromArkClass(declaringClass: ArkClass, mtd: ArkMethod, - sourceFile: ts.SourceFile, node?: ts.ModuleDeclaration) { + | ts.FunctionDeclaration + | ts.MethodDeclaration + | ts.ConstructorDeclaration + | ts.ArrowFunction + | ts.AccessorDeclaration + | ts.FunctionExpression + | ts.MethodSignature + | ts.ConstructSignatureDeclaration + | ts.CallSignatureDeclaration + | ts.FunctionTypeNode; + +export function buildDefaultArkMethodFromArkClass(declaringClass: ArkClass, mtd: ArkMethod, sourceFile: ts.SourceFile, node?: ts.ModuleDeclaration): void { mtd.setDeclaringArkClass(declaringClass); const methodSubSignature = ArkSignatureBuilder.buildMethodSubSignatureFromMethodName(DEFAULT_ARK_METHOD_NAME, true); @@ -80,7 +72,13 @@ export function buildDefaultArkMethodFromArkClass(declaringClass: ArkClass, mtd: mtd.setBodyBuilder(bodyBuilder); } -export function buildArkMethodFromArkClass(methodNode: MethodLikeNode, declaringClass: ArkClass, mtd: ArkMethod, sourceFile: ts.SourceFile, declaringMethod?: ArkMethod) { +export function buildArkMethodFromArkClass( + methodNode: MethodLikeNode, + declaringClass: ArkClass, + mtd: ArkMethod, + sourceFile: ts.SourceFile, + declaringMethod?: ArkMethod +): void { mtd.setDeclaringArkClass(declaringClass); declaringMethod !== undefined && mtd.setOuterMethod(declaringMethod); @@ -100,7 +98,7 @@ export function buildArkMethodFromArkClass(methodNode: MethodLikeNode, declaring // build methodDeclareSignatures and methodSignature as well as corresponding positions const methodName = buildMethodName(methodNode, declaringClass, sourceFile, declaringMethod); const methodParameters: MethodParameter[] = []; - buildParameters(methodNode.parameters, mtd, sourceFile).forEach((parameter) => { + buildParameters(methodNode.parameters, mtd, sourceFile).forEach(parameter => { buildGenericType(parameter.getType(), mtd); methodParameters.push(parameter); }); @@ -176,7 +174,7 @@ function buildMethodName(node: MethodLikeNode, declaringClass: ArkClass, sourceF return name; } -function buildAnonymousMethodName(node: MethodLikeNode, declaringClass: ArkClass) { +function buildAnonymousMethodName(node: MethodLikeNode, declaringClass: ArkClass): string { return `${ANONYMOUS_METHOD_PREFIX}${declaringClass.getAnonymousMethodNumber()}`; } @@ -192,30 +190,29 @@ export class ObjectBindingPatternParameter { private name: string = ''; private optional: boolean = false; - constructor() { - } + constructor() {} - public getName() { + public getName(): string { return this.name; } - public setName(name: string) { + public setName(name: string): void { this.name = name; } - public getPropertyName() { + public getPropertyName(): string { return this.propertyName; } - public setPropertyName(propertyName: string) { + public setPropertyName(propertyName: string): void { this.propertyName = propertyName; } - public isOptional() { + public isOptional(): boolean { return this.optional; } - public setOptional(optional: boolean) { + public setOptional(optional: boolean): void { this.optional = optional; } } @@ -225,30 +222,29 @@ export class ArrayBindingPatternParameter { private name: string = ''; private optional: boolean = false; - constructor() { - } + constructor() {} - public getName() { + public getName(): string { return this.name; } - public setName(name: string) { + public setName(name: string): void { this.name = name; } - public getPropertyName() { + public getPropertyName(): string { return this.propertyName; } - public setPropertyName(propertyName: string) { + public setPropertyName(propertyName: string): void { this.propertyName = propertyName; } - public isOptional() { + public isOptional(): boolean { return this.optional; } - public setOptional(optional: boolean) { + public setOptional(optional: boolean): void { this.optional = optional; } } @@ -261,62 +257,61 @@ export class MethodParameter implements Value { private objElements: ObjectBindingPatternParameter[] = []; private arrayElements: ArrayBindingPatternParameter[] = []; - constructor() { - } + constructor() {} - public getName() { + public getName(): string { return this.name; } - public setName(name: string) { + public setName(name: string): void { this.name = name; } - public getType() { + public getType(): Type { return this.type; } - public setType(type: Type) { + public setType(type: Type): void { this.type = type; } - public isOptional() { + public isOptional(): boolean { return this.optional; } - public setOptional(optional: boolean) { + public setOptional(optional: boolean): void { this.optional = optional; } - public hasDotDotDotToken() { + public hasDotDotDotToken(): boolean { return this.dotDotDotToken; } - public setDotDotDotToken(dotDotDotToken: boolean) { + public setDotDotDotToken(dotDotDotToken: boolean): void { this.dotDotDotToken = dotDotDotToken; } - public addObjElement(element: ObjectBindingPatternParameter) { + public addObjElement(element: ObjectBindingPatternParameter): void { this.objElements.push(element); } - public getObjElements() { + public getObjElements(): ObjectBindingPatternParameter[] { return this.objElements; } - public setObjElements(objElements: ObjectBindingPatternParameter[]) { + public setObjElements(objElements: ObjectBindingPatternParameter[]): void { this.objElements = objElements; } - public addArrayElement(element: ArrayBindingPatternParameter) { + public addArrayElement(element: ArrayBindingPatternParameter): void { this.arrayElements.push(element); } - public getArrayElements() { + public getArrayElements(): ArrayBindingPatternParameter[] { return this.arrayElements; } - public setArrayElements(arrayElements: ArrayBindingPatternParameter[]) { + public setArrayElements(arrayElements: ArrayBindingPatternParameter[]): void { this.arrayElements = arrayElements; } @@ -327,10 +322,12 @@ export class MethodParameter implements Value { function needDefaultConstructorInClass(arkClass: ArkClass): boolean { const originClassType = arkClass.getCategory(); - return arkClass.getMethodWithName(CONSTRUCTOR_NAME) === null && + return ( + arkClass.getMethodWithName(CONSTRUCTOR_NAME) === null && (originClassType === ClassCategory.CLASS || originClassType === ClassCategory.OBJECT) && arkClass.getName() !== DEFAULT_ARK_CLASS_NAME && - !arkClass.isDeclare(); + !arkClass.isDeclare() + ); } function recursivelyCheckAndBuildSuperConstructor(arkClass: ArkClass): void { @@ -455,18 +452,21 @@ export function addInitInConstructor(constructor: ArkMethod): void { break; } const initInvokeStmt = new ArkInvokeStmt( - new ArkInstanceInvokeExpr(thisLocal, constructor.getDeclaringArkClass().getInstanceInitMethod().getSignature(), [])); + new ArkInstanceInvokeExpr(thisLocal, constructor.getDeclaringArkClass().getInstanceInitMethod().getSignature(), []) + ); firstBlockStmts.splice(index, 0, initInvokeStmt); } export function isMethodImplementation(node: MethodLikeNode): boolean { - if (ts.isFunctionDeclaration(node) || + if ( + ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node) || ts.isConstructorDeclaration(node) || ts.isGetAccessorDeclaration(node) || ts.isSetAccessorDeclaration(node) || ts.isFunctionExpression(node) || - ts.isArrowFunction(node)) { + ts.isArrowFunction(node) + ) { if (node.body !== undefined) { return true; } @@ -498,7 +498,7 @@ export function checkAndUpdateMethod(method: ArkMethod, cls: ArkClass): void { if (presentDeclareSignatures !== null && presentImplSignature === null) { if (newDeclareSignature === null || presentMethod.getDeclareSignatureIndex(newDeclareSignature[0]) >= 0) { method.setDeclareSignatures(presentDeclareSignatures); - method.setDeclareLineCols((presentDeclareLineCols as number[])); + method.setDeclareLineCols(presentDeclareLineCols as number[]); } else { method.setDeclareSignatures(presentDeclareSignatures.concat(newDeclareSignature)); method.setDeclareLineCols((presentDeclareLineCols as number[]).concat(newDeclareLineCols as number[])); @@ -513,4 +513,3 @@ export function checkAndUpdateMethod(method: ArkMethod, cls: ArkClass): void { return; } } - diff --git a/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkNamespaceBuilder.ts b/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkNamespaceBuilder.ts index a4d4b6428d..930a0bba21 100644 --- a/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkNamespaceBuilder.ts +++ b/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkNamespaceBuilder.ts @@ -21,7 +21,7 @@ import ts from 'ohos-typescript'; import { ArkNamespace } from '../ArkNamespace'; import { buildDecorators, buildModifiers } from './builderUtils'; import Logger, { LOG_MODULE_TYPE } from '../../../utils/logger'; -import { buildExportAssignment, buildExportDeclaration, buildExportInfo } from './ArkExportBuilder'; +import { buildExportAssignment, buildExportDeclaration, buildExportInfo, buildExportVariableStatement, isExported } from './ArkExportBuilder'; import { ArkClass } from '../ArkClass'; import { ArkMethod } from '../ArkMethod'; import { NamespaceSignature } from '../ArkSignature'; @@ -29,7 +29,7 @@ import { IRUtils } from '../../common/IRUtils'; const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'ArkNamespaceBuilder'); -export function buildArkNamespace(node: ts.ModuleDeclaration, declaringInstance: ArkFile | ArkNamespace, ns: ArkNamespace, sourceFile: ts.SourceFile) { +export function buildArkNamespace(node: ts.ModuleDeclaration, declaringInstance: ArkFile | ArkNamespace, ns: ArkNamespace, sourceFile: ts.SourceFile): void { // modifiers if (node.modifiers) { ns.setModifiers(buildModifiers(node)); @@ -44,18 +44,18 @@ export function buildArkNamespace(node: ts.ModuleDeclaration, declaringInstance: } ns.setDeclaringInstance(declaringInstance); const namespaceName = node.name.text; - const namespaceSignature = new NamespaceSignature(namespaceName, ns.getDeclaringArkFile().getFileSignature(), - ns.getDeclaringArkNamespace()?.getSignature() || null); + const namespaceSignature = new NamespaceSignature( + namespaceName, + ns.getDeclaringArkFile().getFileSignature(), + ns.getDeclaringArkNamespace()?.getSignature() || null + ); ns.setSignature(namespaceSignature); // TODO: whether needed? ns.setCode(node.getText(sourceFile)); // set line and column - const { line, character } = ts.getLineAndCharacterOfPosition( - sourceFile, - node.getStart(sourceFile), - ); + const { line, character } = ts.getLineAndCharacterOfPosition(sourceFile, node.getStart(sourceFile)); ns.setLine(line + 1); ns.setColumn(character + 1); @@ -66,7 +66,7 @@ export function buildArkNamespace(node: ts.ModuleDeclaration, declaringInstance: if (ts.isModuleBlock(node.body)) { buildNamespaceMembers(node.body, ns, sourceFile); } - // NamespaceDeclaration extends ModuleDeclaration + // NamespaceDeclaration extends ModuleDeclaration //TODO: Check else if (ts.isModuleDeclaration(node.body)) { logger.warn('This ModuleBody is an NamespaceDeclaration.'); @@ -85,33 +85,25 @@ export function buildArkNamespace(node: ts.ModuleDeclaration, declaringInstance: } // TODO: check and update -function buildNamespaceMembers(node: ts.ModuleBlock, namespace: ArkNamespace, sourceFile: ts.SourceFile) { +function buildNamespaceMembers(node: ts.ModuleBlock, namespace: ArkNamespace, sourceFile: ts.SourceFile): void { const statements = node.statements; const nestedNamespaces: ArkNamespace[] = []; - statements.forEach((child) => { - if ( - ts.isModuleDeclaration(child) - ) { + statements.forEach(child => { + if (ts.isModuleDeclaration(child)) { let childNs: ArkNamespace = new ArkNamespace(); childNs.setDeclaringArkNamespace(namespace); childNs.setDeclaringArkFile(namespace.getDeclaringArkFile()); buildArkNamespace(child, namespace, childNs, sourceFile); nestedNamespaces.push(childNs); - } else if ( - ts.isClassDeclaration(child) || - ts.isInterfaceDeclaration(child) || - ts.isEnumDeclaration(child) || - ts.isStructDeclaration(child) - ) { + } else if (ts.isClassDeclaration(child) || ts.isInterfaceDeclaration(child) || ts.isEnumDeclaration(child) || ts.isStructDeclaration(child)) { let cls: ArkClass = new ArkClass(); buildNormalArkClassFromArkNamespace(child, namespace, cls, sourceFile); namespace.addArkClass(cls); if (cls.isExported()) { - namespace.addExportInfo(buildExportInfo(cls, namespace.getDeclaringArkFile(), - LineColPosition.buildFromNode(child, sourceFile))); + namespace.addExportInfo(buildExportInfo(cls, namespace.getDeclaringArkFile(), LineColPosition.buildFromNode(child, sourceFile))); } } // TODO: Check @@ -122,8 +114,7 @@ function buildNamespaceMembers(node: ts.ModuleBlock, namespace: ArkNamespace, so buildArkMethodFromArkClass(child, namespace.getDefaultClass(), mthd, sourceFile); if (mthd.isExported()) { - namespace.addExportInfo(buildExportInfo(mthd, namespace.getDeclaringArkFile(), - LineColPosition.buildFromNode(child, sourceFile))); + namespace.addExportInfo(buildExportInfo(mthd, namespace.getDeclaringArkFile(), LineColPosition.buildFromNode(child, sourceFile))); } } else if (ts.isFunctionDeclaration(child)) { let mthd: ArkMethod = new ArkMethod(); @@ -131,15 +122,14 @@ function buildNamespaceMembers(node: ts.ModuleBlock, namespace: ArkNamespace, so buildArkMethodFromArkClass(child, namespace.getDefaultClass(), mthd, sourceFile); if (mthd.isExported()) { - namespace.addExportInfo(buildExportInfo(mthd, namespace.getDeclaringArkFile(), - LineColPosition.buildFromNode(child, sourceFile))); + namespace.addExportInfo(buildExportInfo(mthd, namespace.getDeclaringArkFile(), LineColPosition.buildFromNode(child, sourceFile))); } } else if (ts.isExportDeclaration(child)) { - buildExportDeclaration(child, sourceFile, namespace.getDeclaringArkFile()) - .forEach(item => namespace.addExportInfo(item)); + buildExportDeclaration(child, sourceFile, namespace.getDeclaringArkFile()).forEach(item => namespace.addExportInfo(item)); } else if (ts.isExportAssignment(child)) { - buildExportAssignment(child, sourceFile, namespace.getDeclaringArkFile()) - .forEach(item => namespace.addExportInfo(item)); + buildExportAssignment(child, sourceFile, namespace.getDeclaringArkFile()).forEach(item => namespace.addExportInfo(item)); + } else if (ts.isVariableStatement(child) && isExported(child.modifiers)) { + buildExportVariableStatement(child, sourceFile, namespace.getDeclaringArkFile(), namespace).forEach(item => namespace.addExportInfo(item)); } else { logger.info('Child joined default method of arkFile: ', ts.SyntaxKind[child.kind]); // join default method @@ -156,7 +146,7 @@ function buildNamespaceMembers(node: ts.ModuleBlock, namespace: ArkNamespace, so }); } -function genDefaultArkClass(ns: ArkNamespace, node: ts.ModuleDeclaration, sourceFile: ts.SourceFile) { +function genDefaultArkClass(ns: ArkNamespace, node: ts.ModuleDeclaration, sourceFile: ts.SourceFile): void { let defaultClass = new ArkClass(); buildDefaultArkClassFromArkNamespace(ns, defaultClass, node, sourceFile); @@ -164,7 +154,6 @@ function genDefaultArkClass(ns: ArkNamespace, node: ts.ModuleDeclaration, source ns.addArkClass(defaultClass); } - export function mergeNameSpaces(arkNamespaces: ArkNamespace[]): ArkNamespace[] { const namespaceMap = new Map(); for (let i = 0; i < arkNamespaces.length; i++) { diff --git a/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkSignatureBuilder.ts b/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkSignatureBuilder.ts index 1c0ecdaefd..4804a8136c 100644 --- a/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkSignatureBuilder.ts +++ b/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkSignatureBuilder.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -17,8 +17,7 @@ import { ClassSignature, FieldSignature, FileSignature, MethodSignature, MethodS import { UnknownType } from '../../base/Type'; export class ArkSignatureBuilder { - public static buildMethodSignatureFromClassNameAndMethodName(className: string, methodName: string, - staticFlag: boolean = false): MethodSignature { + public static buildMethodSignatureFromClassNameAndMethodName(className: string, methodName: string, staticFlag: boolean = false): MethodSignature { const classSignature = this.buildClassSignatureFromClassName(className); const methodSubSignature = this.buildMethodSubSignatureFromMethodName(methodName, staticFlag); return new MethodSignature(classSignature, methodSubSignature); @@ -29,8 +28,7 @@ export class ArkSignatureBuilder { return new MethodSignature(ClassSignature.DEFAULT, methodSubSignature); } - public static buildMethodSubSignatureFromMethodName(methodName: string, - staticFlag: boolean = false): MethodSubSignature { + public static buildMethodSubSignatureFromMethodName(methodName: string, staticFlag: boolean = false): MethodSubSignature { return new MethodSubSignature(methodName, [], UnknownType.getInstance(), staticFlag); } @@ -41,4 +39,4 @@ export class ArkSignatureBuilder { public static buildFieldSignatureFromFieldName(fieldName: string, staticFlag: boolean = false): FieldSignature { return new FieldSignature(fieldName, ClassSignature.DEFAULT, UnknownType.getInstance(), staticFlag); } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/model/builder/BodyBuilder.ts b/ets2panda/linter/arkanalyzer/src/core/model/builder/BodyBuilder.ts index 67f2d15b4a..77b28a411f 100644 --- a/ets2panda/linter/arkanalyzer/src/core/model/builder/BodyBuilder.ts +++ b/ets2panda/linter/arkanalyzer/src/core/model/builder/BodyBuilder.ts @@ -23,16 +23,7 @@ import { MethodParameter } from './ArkMethodBuilder'; import { LEXICAL_ENV_NAME_PREFIX, NAME_DELIMITER, NAME_PREFIX } from '../../common/Const'; import { ArkParameterRef, ArkStaticFieldRef, ClosureFieldRef, GlobalRef } from '../../base/Ref'; import { ArkAliasTypeDefineStmt, ArkAssignStmt, ArkInvokeStmt, ArkReturnStmt } from '../../base/Stmt'; -import { - AliasType, - ArrayType, - ClosureType, - FunctionType, - LexicalEnvType, - Type, - UnclearReferenceType, - UnionType, -} from '../../base/Type'; +import { AliasType, ArrayType, ClosureType, FunctionType, LexicalEnvType, Type, UnclearReferenceType, UnionType } from '../../base/Type'; import { AbstractInvokeExpr, ArkPtrInvokeExpr } from '../../base/Expr'; type NestedMethodChain = { @@ -121,7 +112,7 @@ export class BodyBuilder { * 4. Recursively do this for all nested method level by level. */ private buildLexicalEnv(childrenChain: NestedMethodChain, baseLocals: Map, index: number): number { - let usedClosures = this.findClosuresUsedInNested(childrenChain, baseLocals, new Map); + let usedClosures = this.findClosuresUsedInNested(childrenChain, baseLocals, new Map()); const nestedMethod = childrenChain.parent; const nestedSignature = nestedMethod.getImplementationSignature(); if (nestedSignature !== null && usedClosures !== null && usedClosures.length > 0) { @@ -259,11 +250,14 @@ export class BodyBuilder { private generateNestedMethodChains(outerMethod: ArkMethod): NestedMethodChain { let candidateMethods: ArkMethod[] = []; - outerMethod.getDeclaringArkClass().getMethods().forEach(method => { - if (method.getName().startsWith(NAME_PREFIX) && method.getName().endsWith(`${NAME_DELIMITER}${outerMethod.getName()}`)) { - candidateMethods.push(method); - } - }); + outerMethod + .getDeclaringArkClass() + .getMethods() + .forEach(method => { + if (method.getName().startsWith(NAME_PREFIX) && method.getName().endsWith(`${NAME_DELIMITER}${outerMethod.getName()}`)) { + candidateMethods.push(method); + } + }); const childrenChains = this.getNestedChildrenChains(outerMethod, candidateMethods); if (childrenChains.length > 0) { return { parent: outerMethod, children: childrenChains }; @@ -278,9 +272,9 @@ export class BodyBuilder { if (outerMethodSignature !== undefined && methodSignatureCompare(parentMethod.getSignature(), outerMethodSignature)) { const childrenChains = this.getNestedChildrenChains(method, candidateMethods); if (childrenChains.length > 0) { - nestedMethodChain.push({parent: method, children: childrenChains}); + nestedMethodChain.push({ parent: method, children: childrenChains }); } else { - nestedMethodChain.push({parent: method, children: null}); + nestedMethodChain.push({ parent: method, children: null }); } } } @@ -344,7 +338,7 @@ export class BodyBuilder { } } - private updateNestedMethodUsedInOuter(nestedChain: NestedMethodChain) : void { + private updateNestedMethodUsedInOuter(nestedChain: NestedMethodChain): void { const nestedMethod = nestedChain.parent; const outerMethod = nestedMethod.getOuterMethod(); if (outerMethod === undefined) { @@ -353,8 +347,10 @@ export class BodyBuilder { const outerLocals = outerMethod.getBody()?.getLocals(); if (outerLocals !== undefined) { for (let local of outerLocals.values()) { - if (local.getType() instanceof LexicalEnvType && - methodSignatureCompare((local.getType() as LexicalEnvType).getNestedMethod(), nestedMethod.getSignature())) { + if ( + local.getType() instanceof LexicalEnvType && + methodSignatureCompare((local.getType() as LexicalEnvType).getNestedMethod(), nestedMethod.getSignature()) + ) { this.updateOuterMethodWithClosures(outerMethod, nestedMethod, local); break; } @@ -369,8 +365,9 @@ export class BodyBuilder { const fieldSignature = new FieldSignature( nestedMethodName, nestedMethod.getDeclaringArkClass().getSignature(), - new FunctionType(nestedMethod.getSignature())); - callGlobal.setRef(new ArkStaticFieldRef((fieldSignature))); + new FunctionType(nestedMethod.getSignature()) + ); + callGlobal.setRef(new ArkStaticFieldRef(fieldSignature)); } const childrenChains = nestedChain.children; @@ -452,8 +449,9 @@ export class BodyBuilder { const fieldSignature = new FieldSignature( methodSignature.getMethodSubSignature().getMethodName(), methodSignature.getDeclaringClassSignature(), - new ClosureType(lexicalEnv, methodSignature)); - globalRef.setRef(new ArkStaticFieldRef((fieldSignature))); + new ClosureType(lexicalEnv, methodSignature) + ); + globalRef.setRef(new ArkStaticFieldRef(fieldSignature)); this.updateAbstractInvokeExprWithClosures(globalRef, outerMethod.getSignature(), nestedMethod.getSignature(), closuresLocal); } @@ -481,8 +479,12 @@ export class BodyBuilder { // 更新所有stmt中调用内层函数处的AbstractInvokeExpr中的函数签名和实参args,加入闭包参数 // 更新所有stmt中定义的函数指针的usedStmt中的函数签名和实参args,加入闭包参数 - private updateAbstractInvokeExprWithClosures(value: Local | GlobalRef, outerMethodSignature: MethodSignature, - nestedMethodSignature: MethodSignature, closuresLocal: Local): void { + private updateAbstractInvokeExprWithClosures( + value: Local | GlobalRef, + outerMethodSignature: MethodSignature, + nestedMethodSignature: MethodSignature, + closuresLocal: Local + ): void { for (const usedStmt of value.getUsedStmts()) { if (usedStmt instanceof ArkInvokeStmt) { this.updateSignatureAndArgsInArkInvokeExpr(usedStmt, nestedMethodSignature, closuresLocal); @@ -515,12 +517,7 @@ export class BodyBuilder { closuresParam.setName(closuresLocal.getName()); closuresParam.setType(closuresLocal.getType()); params.unshift(closuresParam); - let newSubSignature = new MethodSubSignature( - oldSubSignature.getMethodName(), - params, - oldSubSignature.getReturnType(), - oldSubSignature.isStatic() - ); + let newSubSignature = new MethodSubSignature(oldSubSignature.getMethodName(), params, oldSubSignature.getReturnType(), oldSubSignature.isStatic()); return new MethodSignature(oldSignature.getDeclaringClassSignature(), newSubSignature); } @@ -577,7 +574,7 @@ export class BodyBuilder { stmts.splice(index, 0, assignStmt); closuresLocal.setDeclaringStmt(assignStmt); - oldParamRefs?.forEach((paramRef) => { + oldParamRefs?.forEach(paramRef => { index++; paramRef.setIndex(index); }); @@ -598,4 +595,4 @@ export class BodyBuilder { closuresLocal.addUsedStmt(assignStmt); } } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/core/model/builder/builderUtils.ts b/ets2panda/linter/arkanalyzer/src/core/model/builder/builderUtils.ts index 73c93776b2..7e5c218116 100644 --- a/ets2panda/linter/arkanalyzer/src/core/model/builder/builderUtils.ts +++ b/ets2panda/linter/arkanalyzer/src/core/model/builder/builderUtils.ts @@ -33,12 +33,7 @@ import Logger, { LOG_MODULE_TYPE } from '../../../utils/logger'; import { ArkClass } from '../ArkClass'; import { ArkMethod } from '../ArkMethod'; import { Decorator } from '../../base/Decorator'; -import { - ArrayBindingPatternParameter, - buildArkMethodFromArkClass, - MethodParameter, - ObjectBindingPatternParameter, -} from './ArkMethodBuilder'; +import { ArrayBindingPatternParameter, buildArkMethodFromArkClass, MethodParameter, ObjectBindingPatternParameter } from './ArkMethodBuilder'; import { buildNormalArkClassFromArkMethod } from './ArkClassBuilder'; import { Builtin } from '../../common/Builtin'; import { modifierKind2Enum } from '../ArkBaseModel'; @@ -47,12 +42,14 @@ import { KeyofTypeExpr, TypeQueryExpr } from '../../base/TypeExpr'; import { ANY_KEYWORD, BIGINT_KEYWORD, - BOOLEAN_KEYWORD, NEVER_KEYWORD, + BOOLEAN_KEYWORD, + NEVER_KEYWORD, NULL_KEYWORD, NUMBER_KEYWORD, STRING_KEYWORD, THIS_NAME, - UNDEFINED_KEYWORD, VOID_KEYWORD, + UNDEFINED_KEYWORD, + VOID_KEYWORD, } from '../../common/TSConst'; import { ArkSignatureBuilder } from './ArkSignatureBuilder'; import { ArkInstanceFieldRef } from '../../base/Ref'; @@ -89,7 +86,7 @@ export function handlePropertyAccessExpression(node: ts.PropertyAccessExpression export function buildDecorators(node: ts.Node, sourceFile: ts.SourceFile): Set { let decorators: Set = new Set(); - ts.getAllDecorators(node).forEach((decoratorNode) => { + ts.getAllDecorators(node).forEach(decoratorNode => { let decorator = parseDecorator(decoratorNode); if (decorator) { decorator.setContent(decoratorNode.expression.getText(sourceFile)); @@ -128,7 +125,7 @@ export function buildModifiers(node: ts.Node): number { let modifiers: number = 0; if (ts.canHaveModifiers(node)) { - ts.getModifiers(node)?.forEach((modifier) => { + ts.getModifiers(node)?.forEach(modifier => { modifiers |= modifierKind2Enum(modifier.kind); }); } @@ -138,8 +135,8 @@ export function buildModifiers(node: ts.Node): number { export function buildHeritageClauses(heritageClauses?: ts.NodeArray): Map { let heritageClausesMap: Map = new Map(); - heritageClauses?.forEach((heritageClause) => { - heritageClause.types.forEach((type) => { + heritageClauses?.forEach(heritageClause => { + heritageClause.types.forEach(type => { let heritageClauseName: string = ''; if (type.typeArguments) { heritageClauseName = type.getText(); @@ -156,8 +153,11 @@ export function buildHeritageClauses(heritageClauses?: ts.NodeArray, - sourceFile: ts.SourceFile, arkInstance: ArkMethod | ArkClass): GenericType[] { +export function buildTypeParameters( + typeParameters: ts.NodeArray, + sourceFile: ts.SourceFile, + arkInstance: ArkMethod | ArkClass +): GenericType[] { const genericTypes: GenericType[] = []; let index = 0; if (arkInstance instanceof ArkMethod) { @@ -166,7 +166,7 @@ export function buildTypeParameters(typeParameters: ts.NodeArray { + typeParameters.forEach(typeParameter => { const genericType = tsNode2Type(typeParameter, sourceFile, arkInstance); if (genericType instanceof GenericType) { genericType.setIndex(index++); @@ -187,7 +187,7 @@ export function buildTypeParameters(typeParameters: ts.NodeArray { + paramNameNode.elements.forEach(element => { let paraElement = new ObjectBindingPatternParameter(); if (element.propertyName) { if (ts.isIdentifier(element.propertyName)) { @@ -246,7 +246,7 @@ function buildBindingElementOfBindingPatternParam(element: ts.BindingElement, pa function buildArrayBindingPatternParam(methodParameter: MethodParameter, paramNameNode: ts.ArrayBindingPattern): void { methodParameter.setName('ArrayBindingPattern'); let elements: ArrayBindingPatternParameter[] = []; - paramNameNode.elements.forEach((element) => { + paramNameNode.elements.forEach(element => { let paraElement = new ArrayBindingPatternParameter(); if (ts.isBindingElement(element)) { buildBindingElementOfBindingPatternParam(element, paraElement); @@ -260,7 +260,7 @@ function buildArrayBindingPatternParam(methodParameter: MethodParameter, paramNa export function buildParameters(params: ts.NodeArray, arkInstance: ArkMethod | ArkField, sourceFile: ts.SourceFile): MethodParameter[] { let parameters: MethodParameter[] = []; - params.forEach((parameter) => { + params.forEach(parameter => { let methodParameter = new MethodParameter(); // name @@ -317,7 +317,10 @@ export function buildGenericType(type: Type, arkInstance: ArkMethod | ArkField | gType = arkInstance.getGenericTypes()?.find(f => f.getName() === typeName); } if (!gType) { - gType = arkInstance.getDeclaringArkClass().getGenericsTypes()?.find(f => f.getName() === typeName); + gType = arkInstance + .getDeclaringArkClass() + .getGenericsTypes() + ?.find(f => f.getName() === typeName); } } if (gType) { @@ -359,7 +362,7 @@ export function buildGenericType(type: Type, arkInstance: ArkMethod | ArkField | return type; } -export function buildReturnType(node: TypeNode, sourceFile: ts.SourceFile, method: ArkMethod) { +export function buildReturnType(node: TypeNode, sourceFile: ts.SourceFile, method: ArkMethod): Type { if (node) { return tsNode2Type(node, sourceFile, method); } else { @@ -367,8 +370,11 @@ export function buildReturnType(node: TypeNode, sourceFile: ts.SourceFile, metho } } -export function tsNode2Type(typeNode: ts.TypeNode | ts.TypeParameterDeclaration, sourceFile: ts.SourceFile, - arkInstance: ArkMethod | ArkClass | ArkField): Type { +export function tsNode2Type( + typeNode: ts.TypeNode | ts.TypeParameterDeclaration, + sourceFile: ts.SourceFile, + arkInstance: ArkMethod | ArkClass | ArkField +): Type { if (ts.isTypeReferenceNode(typeNode)) { const genericTypes: Type[] = []; if (typeNode.typeArguments) { @@ -389,7 +395,7 @@ export function tsNode2Type(typeNode: ts.TypeNode | ts.TypeParameterDeclaration, } } else if (ts.isUnionTypeNode(typeNode) || ts.isIntersectionTypeNode(typeNode)) { let multipleTypePara: Type[] = []; - typeNode.types.forEach((tmpType) => { + typeNode.types.forEach(tmpType => { multipleTypePara.push(tsNode2Type(tmpType, sourceFile, arkInstance)); }); if (ts.isUnionTypeNode(typeNode)) { @@ -464,7 +470,7 @@ export function tsNode2Type(typeNode: ts.TypeNode | ts.TypeParameterDeclaration, } } -export function buildTypeFromPreStr(preStr: string) { +export function buildTypeFromPreStr(preStr: string): Type { let postStr = ''; switch (preStr) { case 'BooleanKeyword': @@ -515,21 +521,20 @@ export function buildTypeFromPreStr(preStr: string) { return TypeInference.buildTypeFromStr(postStr); } -function buildTypeFromTypeOperator(typeOperatorNode: ts.TypeOperatorNode, sourceFile: ts.SourceFile, - arkInstance: ArkMethod | ArkClass | ArkField): Type { +function buildTypeFromTypeOperator(typeOperatorNode: ts.TypeOperatorNode, sourceFile: ts.SourceFile, arkInstance: ArkMethod | ArkClass | ArkField): Type { const typeNode = typeOperatorNode.type; let type = tsNode2Type(typeNode, sourceFile, arkInstance); switch (typeOperatorNode.operator) { - case (ts.SyntaxKind.ReadonlyKeyword): { + case ts.SyntaxKind.ReadonlyKeyword: { if (type instanceof ArrayType || type instanceof TupleType) { type.setReadonlyFlag(true); } return type; } - case (ts.SyntaxKind.KeyOfKeyword): + case ts.SyntaxKind.KeyOfKeyword: return new KeyofTypeExpr(type); - case (ts.SyntaxKind.UniqueKeyword): + case ts.SyntaxKind.UniqueKeyword: return UnknownType.getInstance(); default: return UnknownType.getInstance(); @@ -543,21 +548,27 @@ function buildTypeFromTypeQuery(typeQueryNode: ts.TypeQueryNode, sourceFile: ts. if (exprNameNode.left.getText(sourceFile) === THIS_NAME) { const fieldName = exprNameNode.right.getText(sourceFile); if (arkInstance instanceof ArkMethod) { - const fieldSignature = arkInstance.getDeclaringArkClass().getFieldWithName(fieldName)?.getSignature() ?? + const fieldSignature = + arkInstance.getDeclaringArkClass().getFieldWithName(fieldName)?.getSignature() ?? ArkSignatureBuilder.buildFieldSignatureFromFieldName(fieldName); - const baseLocal = arkInstance.getBody()?.getLocals().get(THIS_NAME) ?? - new Local(THIS_NAME, new ClassType(arkInstance.getDeclaringArkClass().getSignature(), - arkInstance.getDeclaringArkClass().getGenericsTypes())); + const baseLocal = + arkInstance.getBody()?.getLocals().get(THIS_NAME) ?? + new Local( + THIS_NAME, + new ClassType(arkInstance.getDeclaringArkClass().getSignature(), arkInstance.getDeclaringArkClass().getGenericsTypes()) + ); opValue = new ArkInstanceFieldRef(baseLocal, fieldSignature); } else if (arkInstance instanceof ArkClass) { - const fieldSignature = arkInstance.getFieldWithName(fieldName)?.getSignature() ?? - ArkSignatureBuilder.buildFieldSignatureFromFieldName(fieldName); + const fieldSignature = + arkInstance.getFieldWithName(fieldName)?.getSignature() ?? ArkSignatureBuilder.buildFieldSignatureFromFieldName(fieldName); const baseLocal = new Local(THIS_NAME, new ClassType(arkInstance.getSignature(), arkInstance.getGenericsTypes())); opValue = new ArkInstanceFieldRef(baseLocal, fieldSignature); } else { const fieldSignature = arkInstance.getSignature(); - const baseLocal = new Local(THIS_NAME, new ClassType(arkInstance.getDeclaringArkClass().getSignature(), - arkInstance.getDeclaringArkClass().getGenericsTypes())); + const baseLocal = new Local( + THIS_NAME, + new ClassType(arkInstance.getDeclaringArkClass().getSignature(), arkInstance.getDeclaringArkClass().getGenericsTypes()) + ); opValue = new ArkInstanceFieldRef(baseLocal, fieldSignature); } } else { @@ -576,4 +587,4 @@ function buildTypeFromTypeQuery(typeQueryNode: ts.TypeQueryNode, sourceFile: ts. } } return expr; -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/index.ts b/ets2panda/linter/arkanalyzer/src/index.ts index 174ea7c493..cb13b2d812 100644 --- a/ets2panda/linter/arkanalyzer/src/index.ts +++ b/ets2panda/linter/arkanalyzer/src/index.ts @@ -121,7 +121,6 @@ export * from './utils/AstTreeUtils'; export { LOG_LEVEL, LOG_MODULE_TYPE } from './utils/logger'; export { default as Logger } from './utils/logger'; - //ohos-typescript import ts from 'ohos-typescript'; -export { ts }; \ No newline at end of file +export { ts }; diff --git a/ets2panda/linter/arkanalyzer/src/save/ArkStream.ts b/ets2panda/linter/arkanalyzer/src/save/ArkStream.ts index 51929115b4..a3db074cec 100644 --- a/ets2panda/linter/arkanalyzer/src/save/ArkStream.ts +++ b/ets2panda/linter/arkanalyzer/src/save/ArkStream.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -73,7 +73,7 @@ export class ArkCodeBuffer { return this.output.join(''); } - public clear() { + public clear(): void { this.output = []; } } diff --git a/ets2panda/linter/arkanalyzer/src/save/DotPrinter.ts b/ets2panda/linter/arkanalyzer/src/save/DotPrinter.ts index 2992ff6653..e4f218352f 100644 --- a/ets2panda/linter/arkanalyzer/src/save/DotPrinter.ts +++ b/ets2panda/linter/arkanalyzer/src/save/DotPrinter.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -72,9 +72,7 @@ export class DotMethodPrinter extends Printer { let name = prefix + index++; blockToNode.set(block, name); /** Node0 [label="entry"]; */ - this.printer - .writeIndent() - .writeLine(`${name} [label="${this.getBlockContent(block, this.printer.getIndent())}"];`); + this.printer.writeIndent().writeLine(`${name} [label="${this.getBlockContent(block, this.printer.getIndent())}"];`); } for (let block of blocks) { diff --git a/ets2panda/linter/arkanalyzer/src/save/GraphPrinter.ts b/ets2panda/linter/arkanalyzer/src/save/GraphPrinter.ts index 20f5938165..7016d14036 100644 --- a/ets2panda/linter/arkanalyzer/src/save/GraphPrinter.ts +++ b/ets2panda/linter/arkanalyzer/src/save/GraphPrinter.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -23,7 +23,7 @@ function escapeStr(input: string): string { switch (str[i]) { case '\n': str = str.substring(0, i) + '\\n' + str.substring(i + 1); - ++i; + ++i; break; case '\t': str = str.substring(0, i) + ' ' + str.substring(i + 1); @@ -56,7 +56,6 @@ function escapeStr(input: string): string { ++i; break; default: - ; } } return str; @@ -75,7 +74,7 @@ export class GraphPrinter> extends Print } } - public setStartID(n: NodeID) { + public setStartID(n: NodeID): void { this.startID = n; } @@ -109,27 +108,25 @@ export class GraphPrinter> extends Print itor = nodes.values(); } - for(let node of itor) { + for (let node of itor) { let nodeAttr = node.getDotAttr(); if (nodeAttr === '') { continue; } let nodeLabel = escapeStr(node.getDotLabel()); - this.printer.writeLine(`\tNode${node.getID()} [shape=recode,${nodeAttr},label="${nodeLabel}"];`) + this.printer.writeLine(`\tNode${node.getID()} [shape=recode,${nodeAttr},label="${nodeLabel}"];`); for (let edge of node.getOutgoingEdges()) { this.writeEdge(edge); } } - - } public writeEdge(edge: BaseEdge): void { let edgeAttr = edge.getDotAttr(); if (edgeAttr === '') { - return + return; } this.printer.writeLine(`\tNode${edge.getSrcID()} -> Node${edge.getDstID()}[${edgeAttr}]`); } @@ -140,7 +137,6 @@ export class GraphPrinter> extends Print let graphNameStr = `digraph "${escapeStr(this.title || GraphName || 'unnamed')}" {\n`; this.printer.writeLine(graphNameStr); - let labelStr = `\tlabel="${escapeStr(this.title || GraphName)}";\n`; this.printer.writeLine(labelStr); @@ -148,6 +144,6 @@ export class GraphPrinter> extends Print } public writeFooter(): void { - this.printer.writeLine("}\n"); + this.printer.writeLine('}\n'); } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/save/JsonPrinter.ts b/ets2panda/linter/arkanalyzer/src/save/JsonPrinter.ts index 3f533f2244..283de26011 100644 --- a/ets2panda/linter/arkanalyzer/src/save/JsonPrinter.ts +++ b/ets2panda/linter/arkanalyzer/src/save/JsonPrinter.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -25,7 +25,8 @@ import { AnnotationType, AnnotationTypeQueryType, AnyType, - ArrayType, BigIntType, + ArrayType, + BigIntType, BooleanType, ClassType, FunctionType, @@ -45,15 +46,7 @@ import { VoidType, } from '../core/base/Type'; import { Value } from '../core/base/Value'; -import { - ArkAssignStmt, - ArkIfStmt, - ArkInvokeStmt, - ArkReturnStmt, - ArkReturnVoidStmt, - ArkThrowStmt, - Stmt, -} from '../core/base/Stmt'; +import { ArkAssignStmt, ArkIfStmt, ArkInvokeStmt, ArkReturnStmt, ArkReturnVoidStmt, ArkThrowStmt, Stmt } from '../core/base/Stmt'; import { AbstractBinopExpr, AbstractExpr, @@ -78,14 +71,7 @@ import { Constant } from '../core/base/Constant'; import { MethodParameter } from '../core/model/builder/ArkMethodBuilder'; import { ImportInfo } from '../core/model/ArkImport'; import { ExportInfo } from '../core/model/ArkExport'; -import { - AliasTypeSignature, - ClassSignature, - FieldSignature, - FileSignature, - MethodSignature, - NamespaceSignature, -} from '../core/model/ArkSignature'; +import { AliasTypeSignature, ClassSignature, FieldSignature, FileSignature, MethodSignature, NamespaceSignature } from '../core/model/ArkSignature'; import { LineColPosition } from '../core/base/Position'; import { AbstractFieldRef, AbstractRef, ArkArrayRef, ArkInstanceFieldRef, ArkParameterRef, ArkStaticFieldRef, ArkThisRef } from '../core/base/Ref'; import { Local } from '../core/base/Local'; @@ -108,18 +94,18 @@ export class JsonPrinter extends Printer { private serializeArkFile(file: ArkFile): object { return { signature: this.serializeFileSignature(file.getFileSignature()), - namespaces: file.getNamespaces().map((ns) => this.serializeNamespace(ns)), - classes: file.getClasses().map((cls) => this.serializeClass(cls)), - importInfos: file.getImportInfos().map((info) => this.serializeImportInfo(info)), - exportInfos: file.getExportInfos().map((info) => this.serializeExportInfo(info)), + namespaces: file.getNamespaces().map(ns => this.serializeNamespace(ns)), + classes: file.getClasses().map(cls => this.serializeClass(cls)), + importInfos: file.getImportInfos().map(info => this.serializeImportInfo(info)), + exportInfos: file.getExportInfos().map(info => this.serializeExportInfo(info)), }; } private serializeNamespace(namespace: ArkNamespace): object { return { signature: this.serializeNamespaceSignature(namespace.getSignature()), - classes: namespace.getClasses().map((cls) => this.serializeClass(cls)), - namespaces: namespace.getNamespaces().map((ns) => this.serializeNamespace(ns)), + classes: namespace.getClasses().map(cls => this.serializeClass(cls)), + namespaces: namespace.getNamespaces().map(ns => this.serializeNamespace(ns)), }; } @@ -127,12 +113,12 @@ export class JsonPrinter extends Printer { return { signature: this.serializeClassSignature(clazz.getSignature()), modifiers: clazz.getModifiers(), - decorators: clazz.getDecorators().map((decorator) => this.serializeDecorator(decorator)), - typeParameters: clazz.getGenericsTypes()?.map((type) => this.serializeType(type)), + decorators: clazz.getDecorators().map(decorator => this.serializeDecorator(decorator)), + typeParameters: clazz.getGenericsTypes()?.map(type => this.serializeType(type)), superClassName: clazz.getSuperClassName(), implementedInterfaceNames: clazz.getImplementedInterfaceNames(), - fields: clazz.getFields().map((field) => this.serializeField(field)), - methods: clazz.getMethods(true).map((method) => this.serializeMethod(method)), + fields: clazz.getFields().map(field => this.serializeField(field)), + methods: clazz.getMethods(true).map(method => this.serializeMethod(method)), }; } @@ -140,7 +126,7 @@ export class JsonPrinter extends Printer { return { signature: this.serializeFieldSignature(field.getSignature()), modifiers: field.getModifiers(), - decorators: field.getDecorators().map((decorator) => this.serializeDecorator(decorator)), + decorators: field.getDecorators().map(decorator => this.serializeDecorator(decorator)), questionToken: field.getQuestionToken(), exclamationToken: field.getExclamationToken(), }; @@ -151,7 +137,7 @@ export class JsonPrinter extends Printer { return { signature: this.serializeMethodSignature(method.getSignature()), modifiers: method.getModifiers(), - decorators: method.getDecorators().map((decorator) => this.serializeDecorator(decorator)), + decorators: method.getDecorators().map(decorator => this.serializeDecorator(decorator)), typeParameters: method.getGenericTypes()?.map(type => this.serializeType(type)), body: body && this.serializeMethodBody(body), }; @@ -159,7 +145,7 @@ export class JsonPrinter extends Printer { private serializeMethodBody(body: ArkBody): object { return { - locals: Array.from(body.getLocals().values()).map((local) => this.serializeLocal(local)), + locals: Array.from(body.getLocals().values()).map(local => this.serializeLocal(local)), cfg: this.serializeCfg(body.getCfg()), }; } @@ -232,12 +218,12 @@ export class JsonPrinter extends Printer { } else if (type instanceof UnionType) { return { _: 'UnionType', - types: type.getTypes().map((type) => this.serializeType(type)), + types: type.getTypes().map(type => this.serializeType(type)), }; } else if (type instanceof TupleType) { return { _: 'TupleType', - types: type.getTypes().map((type) => this.serializeType(type)), + types: type.getTypes().map(type => this.serializeType(type)), }; } else if (type instanceof BooleanType) { return { @@ -274,13 +260,13 @@ export class JsonPrinter extends Printer { return { _: 'ClassType', signature: this.serializeClassSignature(type.getClassSignature()), - typeParameters: type.getRealGenericTypes()?.map((type) => this.serializeType(type)), + typeParameters: type.getRealGenericTypes()?.map(type => this.serializeType(type)), }; } else if (type instanceof FunctionType) { return { _: 'FunctionType', signature: this.serializeMethodSignature(type.getMethodSignature()), - typeParameters: type.getRealGenericTypes()?.map((type) => this.serializeType(type)), + typeParameters: type.getRealGenericTypes()?.map(type => this.serializeType(type)), }; } else if (type instanceof ArrayType) { return { @@ -292,7 +278,7 @@ export class JsonPrinter extends Printer { return { _: 'UnclearReferenceType', name: type.getName(), - typeParameters: type.getGenericTypes().map((type) => this.serializeType(type)), + typeParameters: type.getGenericTypes().map(type => this.serializeType(type)), }; } else if (type instanceof GenericType) { let defaultType = type.getDefaultType(); @@ -375,7 +361,7 @@ export class JsonPrinter extends Printer { parameters: method .getMethodSubSignature() .getParameters() - .map((param) => this.serializeMethodParameter(param)), + .map(param => this.serializeMethodParameter(param)), returnType: this.serializeType(method.getType()), }; } @@ -405,20 +391,20 @@ export class JsonPrinter extends Printer { stack.push(...block.getSuccessors()); } return { - blocks: Array.from(visited).map((block) => this.serializeBasicBlock(block)), + blocks: Array.from(visited).map(block => this.serializeBasicBlock(block)), }; } private serializeBasicBlock(block: BasicBlock): object { - const successors = block.getSuccessors().map((succ) => succ.getId()); + const successors = block.getSuccessors().map(succ => succ.getId()); successors.sort((a, b) => a - b); - const predecessors = block.getPredecessors().map((pred) => pred.getId()); + const predecessors = block.getPredecessors().map(pred => pred.getId()); predecessors.sort((a, b) => a - b); return { id: block.getId(), successors, predecessors, - stmts: block.getStmts().map((stmt) => this.serializeStmt(stmt)), + stmts: block.getStmts().map(stmt => this.serializeStmt(stmt)), }; } @@ -493,8 +479,8 @@ export class JsonPrinter extends Printer { const argToBlock = value.getArgToBlock(); return { _: 'PhiExpr', - args: args.map((arg) => this.serializeValue(arg)), - blocks: args.map((arg) => argToBlock.get(arg)!.getId()), + args: args.map(arg => this.serializeValue(arg)), + blocks: args.map(arg => argToBlock.get(arg)!.getId()), type: this.serializeType(value.getType()), }; } else if (value instanceof ArkConditionExpr) { @@ -525,20 +511,20 @@ export class JsonPrinter extends Printer { _: 'InstanceCallExpr', instance: this.serializeValue(value.getBase()), method: this.serializeMethodSignature(value.getMethodSignature()), - args: value.getArgs().map((arg) => this.serializeValue(arg)), + args: value.getArgs().map(arg => this.serializeValue(arg)), }; } else if (value instanceof ArkStaticInvokeExpr) { return { _: 'StaticCallExpr', method: this.serializeMethodSignature(value.getMethodSignature()), - args: value.getArgs().map((arg) => this.serializeValue(arg)), + args: value.getArgs().map(arg => this.serializeValue(arg)), }; } else if (value instanceof ArkPtrInvokeExpr) { return { _: 'PtrCallExpr', ptr: this.serializeValue(value.getFuncPtrLocal()), method: this.serializeMethodSignature(value.getMethodSignature()), - args: value.getArgs().map((arg) => this.serializeValue(arg)), + args: value.getArgs().map(arg => this.serializeValue(arg)), }; } else if (value instanceof AbstractInvokeExpr) { throw new Error('Unhandled CallExpr: ' + util.inspect(value, { showHidden: true, depth: null })); diff --git a/ets2panda/linter/arkanalyzer/src/save/Printer.ts b/ets2panda/linter/arkanalyzer/src/save/Printer.ts index a01b50d55c..fe5087b3f7 100644 --- a/ets2panda/linter/arkanalyzer/src/save/Printer.ts +++ b/ets2panda/linter/arkanalyzer/src/save/Printer.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/ets2panda/linter/arkanalyzer/src/save/PrinterBuilder.ts b/ets2panda/linter/arkanalyzer/src/save/PrinterBuilder.ts index 96420e0501..196d9b77ff 100644 --- a/ets2panda/linter/arkanalyzer/src/save/PrinterBuilder.ts +++ b/ets2panda/linter/arkanalyzer/src/save/PrinterBuilder.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -50,7 +50,7 @@ export class PrinterBuilder { this.outputDir = outputDir; } - public static dump(source: Printer, output: string) { + public static dump(source: Printer, output: string): void { fs.writeFileSync(output, source.dump()); } @@ -62,10 +62,7 @@ export class PrinterBuilder { } } - public dumpToDot( - arkFile: ArkFile, - output: string | undefined = undefined - ): void { + public dumpToDot(arkFile: ArkFile, output: string | undefined = undefined): void { let filename = output; if (filename === undefined) { filename = path.join(this.getOutputDir(arkFile), arkFile.getName() + '.dot'); @@ -76,10 +73,7 @@ export class PrinterBuilder { PrinterBuilder.dump(printer, filename as string); } - public dumpToTs( - arkFile: ArkFile, - output: string | undefined = undefined - ): void { + public dumpToTs(arkFile: ArkFile, output: string | undefined = undefined): void { let filename = output; if (filename === undefined) { filename = path.join(this.getOutputDir(arkFile), arkFile.getName()); @@ -104,17 +98,14 @@ export class PrinterBuilder { PrinterBuilder.dump(printer, filename); } - public dumpToIR( - arkFile: ArkFile, - output: string | undefined = undefined - ): void { + public dumpToIR(arkFile: ArkFile, output: string | undefined = undefined): void { let filename = output; if (filename === undefined) { filename = path.join(this.getOutputDir(arkFile), arkFile.getName()); } - + filename += '.ir'; - + fs.mkdirSync(path.dirname(filename), { recursive: true }); let printer: Printer = new ArkIRFilePrinter(arkFile); @@ -145,26 +136,26 @@ export class ScenePrinter { } } - public dumpToDot() { + public dumpToDot(): void { for (let f of this.scene.getFiles()) { this.printer.dumpToDot(f); } } - public dumpToTs() { + public dumpToTs(): void { for (let f of this.scene.getFiles()) { let relativePath = path.relative(f.getProjectDir(), f.getFilePath()); this.printer.dumpToTs(f, path.join(this.outputDir, relativePath)); } } - public dumpToJson() { + public dumpToJson(): void { for (let f of this.scene.getFiles()) { this.printer.dumpToJson(f); } } - public dumpToIR() { + public dumpToIR(): void { for (let f of this.scene.getFiles()) { this.printer.dumpToIR(f); } diff --git a/ets2panda/linter/arkanalyzer/src/save/ViewTreePrinter.ts b/ets2panda/linter/arkanalyzer/src/save/ViewTreePrinter.ts index 58066a98df..7e5cf2f07b 100644 --- a/ets2panda/linter/arkanalyzer/src/save/ViewTreePrinter.ts +++ b/ets2panda/linter/arkanalyzer/src/save/ViewTreePrinter.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -49,11 +49,7 @@ export class ViewTreePrinter extends Printer { return this.printer.toString(); } - private walk( - item: ViewTreeNode, - parent: ViewTreeNode | null, - map: Map = new Map() - ): void { + private walk(item: ViewTreeNode, parent: ViewTreeNode | null, map: Map = new Map()): void { let skipChildren = this.writeNode(item, parent, map); if (skipChildren) { return; @@ -68,18 +64,12 @@ export class ViewTreePrinter extends Printer { const PRE_FIX_LEN = 5; let label = content.join('|'); if (label.length > MAX_LABEL_LEN) { - return ( - label.substring(0, PRE_FIX_LEN) + '...' + label.substring(label.length - MAX_LABEL_LEN + PRE_FIX_LEN) - ); + return label.substring(0, PRE_FIX_LEN) + '...' + label.substring(label.length - MAX_LABEL_LEN + PRE_FIX_LEN); } return label; } - private writeNode( - item: ViewTreeNode, - parent: ViewTreeNode | null, - map: Map - ): boolean { + private writeNode(item: ViewTreeNode, parent: ViewTreeNode | null, map: Map): boolean { let id = `Node${map.size}`; let hasSameNode = map.has(item) || map.has(item.signature!); @@ -119,7 +109,7 @@ export class ViewTreePrinter extends Printer { if (item.stateValues.size > 0) { let stateValuesId = `${id}val`; let content: string[] = []; - item.stateValues.forEach((value) => { + item.stateValues.forEach(value => { content.push(value.getName()); }); @@ -156,9 +146,7 @@ export class ViewTreePrinter extends Printer { let signatureId = `${id}signature`; let content = [item.signature.toString()]; this.printer.write( - ` ${signatureId} [shape=ellipse label="signature\n${this.escapeDotLabel( - content - )}" fontsize=10 height=.1 style=filled color=".7 .3 1.0" ]\n` + ` ${signatureId} [shape=ellipse label="signature\n${this.escapeDotLabel(content)}" fontsize=10 height=.1 style=filled color=".7 .3 1.0" ]\n` ); this.printer.write(` ${id} -> ${signatureId}\n`); } diff --git a/ets2panda/linter/arkanalyzer/src/save/arkir/ArkIRClassPrinter.ts b/ets2panda/linter/arkanalyzer/src/save/arkir/ArkIRClassPrinter.ts index d8b49f9f27..c67d7e4526 100644 --- a/ets2panda/linter/arkanalyzer/src/save/arkir/ArkIRClassPrinter.ts +++ b/ets2panda/linter/arkanalyzer/src/save/arkir/ArkIRClassPrinter.ts @@ -53,7 +53,7 @@ export class ArkIRClassPrinter extends BasePrinter { const genericsTypes = this.cls.getGenericsTypes(); if (genericsTypes) { - this.printer.write(`<${genericsTypes.map((v) => v.toString()).join(', ')}>`); + this.printer.write(`<${genericsTypes.map(v => v.toString()).join(', ')}>`); } if (this.cls.getSuperClassName() && !this.cls.hasComponentDecorator()) { this.printer.write(` extends ${this.cls.getSuperClassName()}`); diff --git a/ets2panda/linter/arkanalyzer/src/save/arkir/ArkIRMethodPrinter.ts b/ets2panda/linter/arkanalyzer/src/save/arkir/ArkIRMethodPrinter.ts index 9097552396..7b8f7c8b97 100644 --- a/ets2panda/linter/arkanalyzer/src/save/arkir/ArkIRMethodPrinter.ts +++ b/ets2panda/linter/arkanalyzer/src/save/arkir/ArkIRMethodPrinter.ts @@ -59,7 +59,7 @@ export class ArkIRMethodPrinter extends BasePrinter { if (cfg) { cfg.getStmts() .reverse() - .forEach((stmt) => stmts.push(stmt)); + .forEach(stmt => stmts.push(stmt)); } for (const stmt of stmts) { if (stmt.getOriginPositionInfo().getLineNo() > 0) { @@ -104,14 +104,14 @@ export class ArkIRMethodPrinter extends BasePrinter { const genericTypes = method.getGenericTypes(); if (genericTypes && genericTypes.length > 0) { let typeParameters: string[] = []; - genericTypes.forEach((genericType) => { + genericTypes.forEach(genericType => { typeParameters.push(genericType.toString()); }); code.write(`<${genericTypes.join(', ')}>`); } let parameters: string[] = []; - method.getParameters().forEach((parameter) => { + method.getParameters().forEach(parameter => { let str: string = parameter.getName(); if (parameter.hasDotDotDotToken()) { str = `...${parameter.getName()}`; @@ -152,7 +152,7 @@ export class ArkIRMethodPrinter extends BasePrinter { this.printer.incIndent(); if (successors.length === 1) { - block.getStmts().map((stmt) => { + block.getStmts().map(stmt => { this.printer.writeIndent().writeLine(stmt.toString()); }); this.printer.writeIndent().writeLine(`goto label${successors[0].getId()}`); @@ -165,7 +165,7 @@ export class ArkIRMethodPrinter extends BasePrinter { } } } else { - block.getStmts().map((stmt) => { + block.getStmts().map(stmt => { this.printer.writeIndent().writeLine(stmt.toString()); }); } diff --git a/ets2panda/linter/arkanalyzer/src/save/arkir/ArkIRNamespacePrinter.ts b/ets2panda/linter/arkanalyzer/src/save/arkir/ArkIRNamespacePrinter.ts index 3e2fc8d57f..6490cc7f73 100644 --- a/ets2panda/linter/arkanalyzer/src/save/arkir/ArkIRNamespacePrinter.ts +++ b/ets2panda/linter/arkanalyzer/src/save/arkir/ArkIRNamespacePrinter.ts @@ -39,20 +39,17 @@ export class ArkIRNamespacePrinter extends BasePrinter { const commentsMetadata = this.ns.getMetadata(ArkMetadataKind.LEADING_COMMENTS); if (commentsMetadata instanceof CommentsMetadata) { const comments = commentsMetadata.getComments(); - comments.forEach((comment) => { + comments.forEach(comment => { this.printer.writeIndent().writeLine(comment.content); }); } - this.printer.writeIndent().writeSpace(this.modifiersToString(this.ns.getModifiers())) - .writeLine(`namespace ${this.ns.getName()} {`); + this.printer.writeIndent().writeSpace(this.modifiersToString(this.ns.getModifiers())).writeLine(`namespace ${this.ns.getName()} {`); this.printer.incIndent(); let items: Dump[] = []; // print class for (let cls of this.ns.getClasses()) { - items.push(new ArkIRClassPrinter(cls, this.printer.getIndent())); - } // print namespace for (let childNs of this.ns.getNamespaces()) { @@ -60,9 +57,7 @@ export class ArkIRNamespacePrinter extends BasePrinter { } // print exportInfos for (let exportInfo of this.ns.getExportInfos()) { - items.push( - new ExportPrinter(exportInfo, this.printer.getIndent()) - ); + items.push(new ExportPrinter(exportInfo, this.printer.getIndent())); } items.sort((a, b) => a.getLine() - b.getLine()); diff --git a/ets2panda/linter/arkanalyzer/src/save/base/BasePrinter.ts b/ets2panda/linter/arkanalyzer/src/save/base/BasePrinter.ts index 551c2f37f2..306f6301d4 100644 --- a/ets2panda/linter/arkanalyzer/src/save/base/BasePrinter.ts +++ b/ets2panda/linter/arkanalyzer/src/save/base/BasePrinter.ts @@ -42,14 +42,14 @@ export abstract class BasePrinter extends Printer implements Dump { abstract getLine(): number; protected printDecorator(docorator: Decorator[]): void { - docorator.forEach((value) => { + docorator.forEach(value => { this.printer.writeIndent().writeLine(value.toString()); }); } protected printComments(commentsMetadata: CommentsMetadata): void { const comments = commentsMetadata.getComments(); - comments.forEach((comment) => { + comments.forEach(comment => { this.printer.writeIndent().writeLine(comment.content); }); } diff --git a/ets2panda/linter/arkanalyzer/src/save/base/ExportPrinter.ts b/ets2panda/linter/arkanalyzer/src/save/base/ExportPrinter.ts index d76e919e82..aa186fa49b 100644 --- a/ets2panda/linter/arkanalyzer/src/save/base/ExportPrinter.ts +++ b/ets2panda/linter/arkanalyzer/src/save/base/ExportPrinter.ts @@ -35,11 +35,10 @@ export class ExportPrinter extends BasePrinter { if (commentsMetadata instanceof CommentsMetadata) { this.printComments(commentsMetadata); } - + if ( - !this.info.getFrom() && (this.info.isExport() || - this.info.getExportClauseType() === ExportType.LOCAL || - this.info.getExportClauseType() === ExportType.TYPE) + !this.info.getFrom() && + (this.info.isExport() || this.info.getExportClauseType() === ExportType.LOCAL || this.info.getExportClauseType() === ExportType.TYPE) ) { return this.printer.toString(); } @@ -47,9 +46,7 @@ export class ExportPrinter extends BasePrinter { if (this.info.getExportClauseName() === '*') { // just like: export * as xx from './yy' if (this.info.getNameBeforeAs() && this.info.getNameBeforeAs() !== '*') { - this.printer - .writeIndent() - .write(`export ${this.info.getNameBeforeAs()} as ${this.info.getExportClauseName()}`); + this.printer.writeIndent().write(`export ${this.info.getNameBeforeAs()} as ${this.info.getExportClauseName()}`); } else { this.printer.writeIndent().write(`export ${this.info.getExportClauseName()}`); } @@ -68,4 +65,4 @@ export class ExportPrinter extends BasePrinter { return this.printer.toString(); } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/save/base/ImportPrinter.ts b/ets2panda/linter/arkanalyzer/src/save/base/ImportPrinter.ts index 14d08b429b..def5cac29f 100644 --- a/ets2panda/linter/arkanalyzer/src/save/base/ImportPrinter.ts +++ b/ets2panda/linter/arkanalyzer/src/save/base/ImportPrinter.ts @@ -53,9 +53,7 @@ export class ImportPrinter extends BasePrinter { clauseNames.push(`* as ${info.getImportClauseName()}`); } else if (info.getImportType() === 'EqualsImport') { // sample: import mmmm = require('./xxx') - this.printer - .writeIndent() - .writeLine(`import ${info.getImportClauseName()} = require('${info.getFrom() as string}');`); + this.printer.writeIndent().writeLine(`import ${info.getImportClauseName()} = require('${info.getFrom() as string}');`); } else { // sample: import '../xxx' this.printer.writeIndent().writeLine(`import '${info.getFrom() as string}';`); @@ -66,9 +64,7 @@ export class ImportPrinter extends BasePrinter { clauseNames.push(`{${namedImports.join(', ')}}`); } - this.printer - .writeIndent() - .writeLine(`import ${clauseNames.join(', ')} from '${this.infos[0].getFrom() as string}';`); + this.printer.writeIndent().writeLine(`import ${clauseNames.join(', ')} from '${this.infos[0].getFrom() as string}';`); return this.printer.toString(); } @@ -78,7 +74,7 @@ function mergeImportInfos(infos: ImportInfo[]): Map { let map = new Map(); for (let info of infos) { - let key = `${info.getOriginTsPosition().getLineNo()}-${info.getFrom()}` + let key = `${info.getOriginTsPosition().getLineNo()}-${info.getFrom()}`; let merge = map.get(key) || []; merge.push(info); map.set(key, merge); diff --git a/ets2panda/linter/arkanalyzer/src/save/base/PrinterUtils.ts b/ets2panda/linter/arkanalyzer/src/save/base/PrinterUtils.ts index ee019a536e..0f92b23bde 100644 --- a/ets2panda/linter/arkanalyzer/src/save/base/PrinterUtils.ts +++ b/ets2panda/linter/arkanalyzer/src/save/base/PrinterUtils.ts @@ -14,12 +14,7 @@ */ import { Constant } from '../../core/base/Constant'; -import { - ArkInstanceInvokeExpr, - ArkNormalBinopExpr, - ArkStaticInvokeExpr, - NormalBinaryOperator, -} from '../../core/base/Expr'; +import { ArkInstanceInvokeExpr, ArkNormalBinopExpr, ArkStaticInvokeExpr, NormalBinaryOperator } from '../../core/base/Expr'; import { Local } from '../../core/base/Local'; import { ArkAssignStmt, Stmt } from '../../core/base/Stmt'; import { @@ -105,10 +100,7 @@ export class PrinterUtils { let className = invokeExpr.getMethodSignature().getDeclaringClassSignature().getClassName(); let methodName = invokeExpr.getMethodSignature().getMethodSubSignature().getMethodName(); - if ( - methodName === COMPONENT_POP_FUNCTION && - (isEtsSystemComponent(className) || SPECIAL_CONTAINER_COMPONENT.has(className)) - ) { + if (methodName === COMPONENT_POP_FUNCTION && (isEtsSystemComponent(className) || SPECIAL_CONTAINER_COMPONENT.has(className))) { return true; } @@ -119,20 +111,14 @@ export class PrinterUtils { let className = invokeExpr.getMethodSignature().getDeclaringClassSignature().getClassName(); let methodName = invokeExpr.getMethodSignature().getMethodSubSignature().getMethodName(); - if ( - methodName === COMPONENT_CREATE_FUNCTION && - (isEtsSystemComponent(className) || SPECIAL_CONTAINER_COMPONENT.has(className)) - ) { + if (methodName === COMPONENT_CREATE_FUNCTION && (isEtsSystemComponent(className) || SPECIAL_CONTAINER_COMPONENT.has(className))) { return true; } return false; } - public static isComponentAttributeInvoke( - invokeExpr: ArkInstanceInvokeExpr, - visitor: Set = new Set() - ): boolean { + public static isComponentAttributeInvoke(invokeExpr: ArkInstanceInvokeExpr, visitor: Set = new Set()): boolean { if (visitor.has(invokeExpr)) { return false; } diff --git a/ets2panda/linter/arkanalyzer/src/save/serializeArkIR.ts b/ets2panda/linter/arkanalyzer/src/save/serializeArkIR.ts index 1793f879f0..dd859f8d3d 100644 --- a/ets2panda/linter/arkanalyzer/src/save/serializeArkIR.ts +++ b/ets2panda/linter/arkanalyzer/src/save/serializeArkIR.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -62,11 +62,7 @@ export function serializeArkFile(arkFile: ArkFile, output?: string): void { fs.closeSync(fd); } -export function serializeScene( - scene: Scene, - outDir: string, - verbose: boolean = false, -): void { +export function serializeScene(scene: Scene, outDir: string, verbose: boolean = false): void { let files = scene.getFiles(); console.log(`Serializing Scene with ${files.length} files to '${outDir}'...`); for (let f of files) { @@ -161,11 +157,7 @@ function serializeFile(arkFile: ArkFile, output: string, options: any, scene: Sc } } -function serializeMultipleTsFiles( - inputDir: string, - outDir: string, - options: any, -): void { +function serializeMultipleTsFiles(inputDir: string, outDir: string, options: any): void { console.log(`Serializing multiple TS files to JSON: '${inputDir}' -> '${outDir}'`); if (fs.existsSync(outDir) && !fs.statSync(outDir).isDirectory()) { console.error(`ERROR: Output path must be a directory.`); @@ -183,7 +175,7 @@ function serializeMultipleTsFiles( let files = scene.getFiles(); if (options.verbose) { console.log(`Scene contains ${files.length} files`); - files.forEach((f) => console.log(`- '${f.getName()}'`)); + files.forEach(f => console.log(`- '${f.getName()}'`)); } if (options.inferTypes) { @@ -220,11 +212,7 @@ function serializeMultipleTsFiles( console.log('All done!'); } -function serializeTsProject( - inputDir: string, - outDir: string, - options: any, -): void { +function serializeTsProject(inputDir: string, outDir: string, options: any): void { console.log(`Serializing TS project to JSON: '${inputDir}' -> '${outDir}'`); if (fs.existsSync(outDir) && !fs.statSync(outDir).isDirectory()) { @@ -283,7 +271,6 @@ export const program = new Command() .option('-e, --entrypoint', 'Generate entrypoint for the files', false) .option('-v, --verbose', 'Verbose output', false) .action((input: any, output: any, options: any) => { - // Check for invalid combinations of flags if (options.multi && options.project) { console.error(`ERROR: You cannot provide both the '-m' and '-p' flags.`); diff --git a/ets2panda/linter/arkanalyzer/src/save/source/SourceBase.ts b/ets2panda/linter/arkanalyzer/src/save/source/SourceBase.ts index c2d917f9c7..48e794b1ee 100644 --- a/ets2panda/linter/arkanalyzer/src/save/source/SourceBase.ts +++ b/ets2panda/linter/arkanalyzer/src/save/source/SourceBase.ts @@ -23,10 +23,7 @@ import { TransformerContext } from './SourceTransformer'; import { ArkNamespace } from '../../core/model/ArkNamespace'; import { BasePrinter } from '../base/BasePrinter'; -export abstract class SourceBase - extends BasePrinter - implements TransformerContext -{ +export abstract class SourceBase extends BasePrinter implements TransformerContext { protected arkFile: ArkFile; protected inBuilder: boolean = false; @@ -36,7 +33,7 @@ export abstract class SourceBase } public getDeclaringArkNamespace(): ArkNamespace | undefined { - return undefined + return undefined; } public getArkFile(): ArkFile { @@ -72,14 +69,11 @@ export abstract class SourceBase continue; } if (keyword.endsWith('Keyword')) { - keyword = keyword - .substring(0, keyword.length - 'Keyword'.length) - .toLowerCase(); + keyword = keyword.substring(0, keyword.length - 'Keyword'.length).toLowerCase(); } types.push(keyword); } return types.join(' | '); } - } diff --git a/ets2panda/linter/arkanalyzer/src/save/source/SourceBody.ts b/ets2panda/linter/arkanalyzer/src/save/source/SourceBody.ts index 9d048c158e..b33546dce3 100644 --- a/ets2panda/linter/arkanalyzer/src/save/source/SourceBody.ts +++ b/ets2panda/linter/arkanalyzer/src/save/source/SourceBody.ts @@ -223,11 +223,7 @@ export class SourceBody implements StmtPrinterContext { } public getStmts(): SourceStmt[] { - return this.stmts.filter((value) => { - if (!this.skipStmts.has(value.original)) { - return value; - } - }); + return this.stmts.filter(value => !this.skipStmts.has(value.original)); } public pushStmt(stmt: SourceStmt): void { diff --git a/ets2panda/linter/arkanalyzer/src/save/source/SourceClass.ts b/ets2panda/linter/arkanalyzer/src/save/source/SourceClass.ts index 26de605704..99e3d05b88 100644 --- a/ets2panda/linter/arkanalyzer/src/save/source/SourceClass.ts +++ b/ets2panda/linter/arkanalyzer/src/save/source/SourceClass.ts @@ -61,7 +61,7 @@ export class SourceClass extends SourceBase { const commentsMetadata = this.cls.getMetadata(ArkMetadataKind.LEADING_COMMENTS); if (commentsMetadata instanceof CommentsMetadata) { const comments = commentsMetadata.getComments(); - comments.forEach((comment) => { + comments.forEach(comment => { this.printer.writeIndent().writeLine(comment.content); }); } @@ -153,10 +153,7 @@ export class SourceClass extends SourceBase { protected printMethods(): Dump[] { let items: Dump[] = []; for (let method of this.cls.getMethods()) { - if ( - method.isGenerated() || - (PrinterUtils.isConstructorMethod(method.getName()) && this.cls.hasViewTree()) - ) { + if (method.isGenerated() || (PrinterUtils.isConstructorMethod(method.getName()) && this.cls.hasViewTree())) { continue; } diff --git a/ets2panda/linter/arkanalyzer/src/save/source/SourceField.ts b/ets2panda/linter/arkanalyzer/src/save/source/SourceField.ts index 50fb363319..41b24a9942 100644 --- a/ets2panda/linter/arkanalyzer/src/save/source/SourceField.ts +++ b/ets2panda/linter/arkanalyzer/src/save/source/SourceField.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -42,7 +42,7 @@ export class SourceField extends SourceBase { const commentsMetadata = this.field.getMetadata(ArkMetadataKind.LEADING_COMMENTS); if (commentsMetadata instanceof CommentsMetadata) { const comments = commentsMetadata.getComments(); - comments.forEach((comment) => { + comments.forEach(comment => { this.printer.writeIndent().writeLine(comment.content); }); } diff --git a/ets2panda/linter/arkanalyzer/src/save/source/SourceFilePrinter.ts b/ets2panda/linter/arkanalyzer/src/save/source/SourceFilePrinter.ts index 9e7b9c467f..c34fac39d2 100644 --- a/ets2panda/linter/arkanalyzer/src/save/source/SourceFilePrinter.ts +++ b/ets2panda/linter/arkanalyzer/src/save/source/SourceFilePrinter.ts @@ -59,9 +59,7 @@ export class SourceFilePrinter extends Printer { for (let method of cls.getMethods()) { if (method.isDefaultArkMethod()) { this.items.push(...new SourceMethod(method, this.printer.getIndent()).dumpDefaultMethod()); - } else if ( - !PrinterUtils.isAnonymousMethod(method.getName()) - ) { + } else if (!PrinterUtils.isAnonymousMethod(method.getName())) { this.items.push(new SourceMethod(method)); } } diff --git a/ets2panda/linter/arkanalyzer/src/save/source/SourceMethod.ts b/ets2panda/linter/arkanalyzer/src/save/source/SourceMethod.ts index 2d0d70abd0..3fff56c0d2 100644 --- a/ets2panda/linter/arkanalyzer/src/save/source/SourceMethod.ts +++ b/ets2panda/linter/arkanalyzer/src/save/source/SourceMethod.ts @@ -55,7 +55,7 @@ export class SourceMethod extends SourceBase { const commentsMetadata = this.method.getMetadata(ArkMetadataKind.LEADING_COMMENTS); if (commentsMetadata instanceof CommentsMetadata) { const comments = commentsMetadata.getComments(); - comments.forEach((comment) => { + comments.forEach(comment => { this.printer.writeIndent().writeLine(comment.content); }); } @@ -84,7 +84,7 @@ export class SourceMethod extends SourceBase { if (cfg) { cfg.getStmts() .reverse() - .forEach((stmt) => stmts.push(stmt)); + .forEach(stmt => stmts.push(stmt)); } for (const stmt of stmts) { if (stmt.getOriginPositionInfo().getLineNo() > 0) { @@ -163,7 +163,7 @@ export class SourceMethod extends SourceBase { methodSig .getMethodSubSignature() .getParameters() - .forEach((parameter) => { + .forEach(parameter => { let str: string = parameter.getName(); if (parameter.hasDotDotDotToken()) { str = `...${parameter.getName()}`; @@ -174,17 +174,13 @@ export class SourceMethod extends SourceBase { if (parameter.getType()) { str += ': ' + this.transformer.typeToString(parameter.getType()); } - if (!str.startsWith(LEXICAL_ENV_NAME_PREFIX)) - { + if (!str.startsWith(LEXICAL_ENV_NAME_PREFIX)) { parameters.push(str); } }); code.write(`(${parameters.join(', ')})`); const returnType = methodSig.getMethodSubSignature().getReturnType(); - if ( - methodSig.getMethodSubSignature().getMethodName() !== 'constructor' && - !(returnType instanceof UnknownType) - ) { + if (methodSig.getMethodSubSignature().getMethodName() !== 'constructor' && !(returnType instanceof UnknownType)) { code.write(`: ${this.transformer.typeToString(returnType)}`); } if (PrinterUtils.isAnonymousMethod(methodSig.getMethodSubSignature().getMethodName())) { @@ -197,7 +193,7 @@ export class SourceMethod extends SourceBase { let code = new ArkCodeBuffer(); let parameters: string[] = []; - this.method.getParameters().forEach((parameter) => { + this.method.getParameters().forEach(parameter => { let str: string = parameter.getName(); if (parameter.isOptional()) { str += '?'; diff --git a/ets2panda/linter/arkanalyzer/src/save/source/SourceNamespace.ts b/ets2panda/linter/arkanalyzer/src/save/source/SourceNamespace.ts index d1e608120a..4bbaaedc4b 100644 --- a/ets2panda/linter/arkanalyzer/src/save/source/SourceNamespace.ts +++ b/ets2panda/linter/arkanalyzer/src/save/source/SourceNamespace.ts @@ -52,12 +52,11 @@ export class SourceNamespace extends SourceBase { const commentsMetadata = this.ns.getMetadata(ArkMetadataKind.LEADING_COMMENTS); if (commentsMetadata instanceof CommentsMetadata) { const comments = commentsMetadata.getComments(); - comments.forEach((comment) => { + comments.forEach(comment => { this.printer.writeIndent().writeLine(comment.content); }); } - this.printer.writeIndent().writeSpace(this.modifiersToString(this.ns.getModifiers())) - .writeLine(`namespace ${this.ns.getName()} {`); + this.printer.writeIndent().writeSpace(this.modifiersToString(this.ns.getModifiers())).writeLine(`namespace ${this.ns.getName()} {`); this.printer.incIndent(); let items: Dump[] = []; @@ -78,9 +77,7 @@ export class SourceNamespace extends SourceBase { } // print exportInfos for (let exportInfo of this.ns.getExportInfos()) { - items.push( - new ExportPrinter(exportInfo, this.printer.getIndent()) - ); + items.push(new ExportPrinter(exportInfo, this.printer.getIndent())); } items.sort((a, b) => a.getLine() - b.getLine()); diff --git a/ets2panda/linter/arkanalyzer/src/save/source/SourceStmt.ts b/ets2panda/linter/arkanalyzer/src/save/source/SourceStmt.ts index 3007cd765e..6f73ec3dc8 100644 --- a/ets2panda/linter/arkanalyzer/src/save/source/SourceStmt.ts +++ b/ets2panda/linter/arkanalyzer/src/save/source/SourceStmt.ts @@ -14,25 +14,10 @@ */ import { Constant } from '../../core/base/Constant'; -import { - ArkInstanceInvokeExpr, - ArkNewArrayExpr, - ArkNewExpr, - ArkStaticInvokeExpr, - NormalBinaryOperator, -} from '../../core/base/Expr'; +import { ArkInstanceInvokeExpr, ArkNewArrayExpr, ArkNewExpr, ArkStaticInvokeExpr, NormalBinaryOperator } from '../../core/base/Expr'; import { Local } from '../../core/base/Local'; import { ArkArrayRef, ArkInstanceFieldRef, ArkParameterRef, ArkStaticFieldRef, ClosureFieldRef } from '../../core/base/Ref'; -import { - ArkAliasTypeDefineStmt, - ArkAssignStmt, - ArkIfStmt, - ArkInvokeStmt, - ArkReturnStmt, - ArkReturnVoidStmt, - ArkThrowStmt, - Stmt, -} from '../../core/base/Stmt'; +import { ArkAliasTypeDefineStmt, ArkAssignStmt, ArkIfStmt, ArkInvokeStmt, ArkReturnStmt, ArkReturnVoidStmt, ArkThrowStmt, Stmt } from '../../core/base/Stmt'; import { AliasType, ClassType, Type } from '../../core/base/Type'; import { Value } from '../../core/base/Value'; import { BasicBlock } from '../../core/graph/BasicBlock'; @@ -90,7 +75,7 @@ export abstract class SourceStmt implements Dump { return this.line; } - public setLine(line: number) { + public setLine(line: number): void { this.line = line; } @@ -110,7 +95,7 @@ export abstract class SourceStmt implements Dump { const commentsMetadata = this.original.getMetadata(ArkMetadataKind.LEADING_COMMENTS); if (commentsMetadata instanceof CommentsMetadata) { const comments = commentsMetadata.getComments(); - comments.forEach((comment) => { + comments.forEach(comment => { content.push(`${this.printer.getIndent()}${comment.content}\n`); }); } @@ -173,7 +158,8 @@ export class SourceAssignStmt extends SourceStmt { if ( (this.leftOp instanceof Local && this.leftOp.getName() === 'this') || (this.rightOp instanceof Constant && this.rightOp.getValue() === 'undefined') || - this.rightOp instanceof ArkParameterRef || this.rightOp instanceof ClosureFieldRef + this.rightOp instanceof ArkParameterRef || + this.rightOp instanceof ClosureFieldRef ) { this.setText(''); this.dumpType = AssignStmtDumpType.NORMAL; @@ -188,10 +174,7 @@ export class SourceAssignStmt extends SourceStmt { this.transferRightNewArrayExpr(); } else if (this.rightOp instanceof ArkStaticInvokeExpr && PrinterUtils.isComponentCreate(this.rightOp)) { this.transferRightComponentCreate(); - } else if ( - this.rightOp instanceof ArkInstanceInvokeExpr && - PrinterUtils.isComponentAttributeInvoke(this.rightOp) - ) { + } else if (this.rightOp instanceof ArkInstanceInvokeExpr && PrinterUtils.isComponentAttributeInvoke(this.rightOp)) { this.transferRightComponentAttribute(); } else { this.rightCode = this.transformer.valueToString(this.rightOp); @@ -201,10 +184,7 @@ export class SourceAssignStmt extends SourceStmt { this.context.setTempCode((this.leftOp as Local).getName(), this.rightCode); } - if ( - (this.leftOp instanceof ArkInstanceFieldRef && this.leftOp.getBase().getName() === 'this') || - this.leftOp instanceof ArkStaticFieldRef - ) { + if ((this.leftOp instanceof ArkInstanceFieldRef && this.leftOp.getBase().getName() === 'this') || this.leftOp instanceof ArkStaticFieldRef) { this.context.setTempCode(this.leftOp.getFieldName(), this.rightCode); } @@ -241,11 +221,7 @@ export class SourceAssignStmt extends SourceStmt { this.setText(`${this.rightCode};`); return; } - if ( - this.leftOp instanceof Local && - this.context.getLocals().has(this.leftOp.getName()) && - !this.isLocalTempValue(this.leftOp) - ) { + if (this.leftOp instanceof Local && this.context.getLocals().has(this.leftOp.getName()) && !this.isLocalTempValue(this.leftOp)) { if (this.context.isLocalDefined(this.leftOp)) { this.setText(`${this.leftCode} = ${this.rightCode};`); return; @@ -320,20 +296,16 @@ export class SourceAssignStmt extends SourceStmt { private handleConstructorInvoke(instanceInvokeExpr: ArkInstanceInvokeExpr, originType?: number): void { let args: string[] = []; - instanceInvokeExpr.getArgs().forEach((v) => { + instanceInvokeExpr.getArgs().forEach(v => { args.push(this.transformer.valueToString(v)); }); if (originType === CLASS_CATEGORY_COMPONENT) { this.rightCode = `${this.transformer.typeToString(this.rightOp.getType())}(${args.join(', ')})`; } else if (originType === ClassCategory.TYPE_LITERAL || originType === ClassCategory.OBJECT) { - this.rightCode = `${this.transformer.literalObjectToString( - this.rightOp.getType() as ClassType - )}`; + this.rightCode = `${this.transformer.literalObjectToString(this.rightOp.getType() as ClassType)}`; } else { - this.rightCode = `new ${this.transformer.typeToString(this.rightOp.getType())}(${args.join( - ', ' - )})`; + this.rightCode = `new ${this.transformer.typeToString(this.rightOp.getType())}(${args.join(', ')})`; } } @@ -597,9 +569,7 @@ export class SourceWhileStmt extends SourceStmt { this.context.setTempVisit(name); } - this.setText( - `for (let [${arrayValueNames.join(', ')}] of ${this.transformer.valueToString(iterator.getBase())}) {` - ); + this.setText(`for (let [${arrayValueNames.join(', ')}] of ${this.transformer.valueToString(iterator.getBase())}) {`); this.context.setTempVisit((temp3 as Local).getName()); return true; @@ -626,18 +596,12 @@ export class SourceWhileStmt extends SourceStmt { if (!(stmt instanceof ArkAssignStmt)) { continue; } - if ( - PrinterUtils.isDeIncrementStmt(stmt, NormalBinaryOperator.Addition) && - (stmt.getLeftOp() as Local).getName() === value.getName() - ) { + if (PrinterUtils.isDeIncrementStmt(stmt, NormalBinaryOperator.Addition) && (stmt.getLeftOp() as Local).getName() === value.getName()) { this.context.setSkipStmt(stmt); return `${value.getName()}++`; } - if ( - PrinterUtils.isDeIncrementStmt(stmt, NormalBinaryOperator.Subtraction) && - (stmt.getLeftOp() as Local).getName() === value.getName() - ) { + if (PrinterUtils.isDeIncrementStmt(stmt, NormalBinaryOperator.Subtraction) && (stmt.getLeftOp() as Local).getName() === value.getName()) { this.context.setSkipStmt(stmt); return `${value.getName()}--`; } @@ -829,7 +793,9 @@ export class SourceTypeAliasStmt extends SourceStmt { if (typeObject instanceof AliasType) { this.setText(`${modifier}type ${this.aliasType.getName()}${genericTypes} = ${typeOf}${typeObject.getName()}${realGenericTypes};`); } else { - this.setText(`${modifier}type ${this.aliasType.getName()}${genericTypes} = ${typeOf}${this.transformer.typeToString(typeObject)}${realGenericTypes};`); + this.setText( + `${modifier}type ${this.aliasType.getName()}${genericTypes} = ${typeOf}${this.transformer.typeToString(typeObject)}${realGenericTypes};` + ); } return; } @@ -842,7 +808,9 @@ export class SourceTypeAliasStmt extends SourceStmt { return; } if (typeObject instanceof Local) { - this.setText(`${modifier}type ${this.aliasType.getName()}${genericTypes} = ${typeOf}${this.transformer.valueToString(typeObject)}${realGenericTypes};`); + this.setText( + `${modifier}type ${this.aliasType.getName()}${genericTypes} = ${typeOf}${this.transformer.valueToString(typeObject)}${realGenericTypes};` + ); return; } if (typeObject instanceof ArkClass) { @@ -941,7 +909,7 @@ export class SourceNewArrayExpr { this.values = []; } - public addInitValue(value: string) { + public addInitValue(value: string): void { this.values.push(value); } diff --git a/ets2panda/linter/arkanalyzer/src/save/source/SourceTransformer.ts b/ets2panda/linter/arkanalyzer/src/save/source/SourceTransformer.ts index 51b9736218..58c999d85b 100644 --- a/ets2panda/linter/arkanalyzer/src/save/source/SourceTransformer.ts +++ b/ets2panda/linter/arkanalyzer/src/save/source/SourceTransformer.ts @@ -60,12 +60,7 @@ import { SourceClass } from './SourceClass'; import { Value } from '../../core/base/Value'; import { AbstractRef, ArkArrayRef, ArkInstanceFieldRef, ArkStaticFieldRef, ArkThisRef } from '../../core/base/Ref'; import { ArkFile } from '../../core/model/ArkFile'; -import { - COMPONENT_CREATE_FUNCTION, - COMPONENT_CUSTOMVIEW, - COMPONENT_IF, - COMPONENT_POP_FUNCTION, -} from '../../core/common/EtsConst'; +import { COMPONENT_CREATE_FUNCTION, COMPONENT_CUSTOMVIEW, COMPONENT_IF, COMPONENT_POP_FUNCTION } from '../../core/common/EtsConst'; import { INSTANCE_INIT_METHOD_NAME } from '../../core/common/Const'; import { ArkAssignStmt } from '../../core/base/Stmt'; import { ArkNamespace } from '../../core/model/ArkNamespace'; @@ -118,7 +113,7 @@ export class SourceTransformer { return ''; } let args: string[] = []; - invokeExpr.getArgs().forEach((v) => { + invokeExpr.getArgs().forEach(v => { args.push(this.valueToString(v)); }); let genericCode = this.genericTypesToString(invokeExpr.getRealGenericTypes()); @@ -130,8 +125,7 @@ export class SourceTransformer { return `${this.valueToString(invokeExpr.getBase())}.${methodName}${genericCode}(${args.join(', ')})`; } - private transBuilderMethod(className: string, methodName: string, args: string[], - invokeExpr: ArkStaticInvokeExpr, genericCode: string): string | null { + private transBuilderMethod(className: string, methodName: string, args: string[], invokeExpr: ArkStaticInvokeExpr, genericCode: string): string | null { if (className === COMPONENT_CUSTOMVIEW) { if (methodName === COMPONENT_CREATE_FUNCTION) { // Anonymous @Builder method @@ -181,7 +175,7 @@ export class SourceTransformer { let className = PrinterUtils.getStaticInvokeClassFullName(classSignature, this.context.getDeclaringArkNamespace()); let methodName = methodSignature.getMethodSubSignature().getMethodName(); let args: string[] = []; - invokeExpr.getArgs().forEach((v) => { + invokeExpr.getArgs().forEach(v => { args.push(this.valueToString(v)); }); @@ -199,7 +193,7 @@ export class SourceTransformer { } return `${methodName}${genericCode}(${args.join(', ')})`; } - + private genericTypesToString(types: Type[] | undefined): string { if (!types) { return ''; @@ -214,7 +208,7 @@ export class SourceTransformer { public typeArrayToString(types: Type[], split: string = ', '): string { let typesStr: string[] = []; - types.forEach((t) => { + types.forEach(t => { typesStr.push(this.typeToString(t)); }); @@ -301,11 +295,7 @@ export class SourceTransformer { if (value instanceof ArkArrayRef) { let index = value.getIndex(); - if ( - index instanceof Constant && - index.getType() instanceof StringType && - PrinterUtils.isTemp(index.getValue()) - ) { + if (index instanceof Constant && index.getType() instanceof StringType && PrinterUtils.isTemp(index.getValue())) { return `${this.valueToString(value.getBase())}[${this.valueToString(new Local(index.getValue()))}]`; } return `${this.valueToString(value.getBase())}[${this.valueToString(value.getIndex())}]`; @@ -357,11 +347,7 @@ export class SourceTransformer { } } - if ( - operator === NormalBinaryOperator.Division || - operator === NormalBinaryOperator.Multiplication || - operator === NormalBinaryOperator.Remainder - ) { + if (operator === NormalBinaryOperator.Division || operator === NormalBinaryOperator.Multiplication || operator === NormalBinaryOperator.Remainder) { if (PrinterUtils.isTemp(value.getName())) { let stmt = value.getDeclaringStmt(); if (stmt instanceof ArkAssignStmt && stmt.getRightOp() instanceof ArkNormalBinopExpr) { @@ -537,7 +523,7 @@ export class SourceTransformer { private unclearReferenceType2string(type: UnclearReferenceType): string { let genericTypes = type.getGenericTypes(); if (genericTypes.length > 0) { - return `${type.getName()}<${genericTypes.map((value)=>this.typeToString(value)).join(', ')}>`; + return `${type.getName()}<${genericTypes.map(value => this.typeToString(value)).join(', ')}>`; } return type.getName(); } diff --git a/ets2panda/linter/arkanalyzer/src/transformer/FunctionTransformer.ts b/ets2panda/linter/arkanalyzer/src/transformer/FunctionTransformer.ts index 24dbe1869e..4cfc917d2c 100644 --- a/ets2panda/linter/arkanalyzer/src/transformer/FunctionTransformer.ts +++ b/ets2panda/linter/arkanalyzer/src/transformer/FunctionTransformer.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,7 +13,4 @@ * limitations under the License. */ - -class FunctionTransformer extends Transformer{ - -} \ No newline at end of file +class FunctionTransformer extends Transformer {} diff --git a/ets2panda/linter/arkanalyzer/src/transformer/SceneTransformer.ts b/ets2panda/linter/arkanalyzer/src/transformer/SceneTransformer.ts index 7d29148dd4..caeea5c262 100644 --- a/ets2panda/linter/arkanalyzer/src/transformer/SceneTransformer.ts +++ b/ets2panda/linter/arkanalyzer/src/transformer/SceneTransformer.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,7 +13,4 @@ * limitations under the License. */ - -class SceneTransformer extends Transformer{ - -} \ No newline at end of file +class SceneTransformer extends Transformer {} diff --git a/ets2panda/linter/arkanalyzer/src/transformer/StaticSingleAssignmentFormer.ts b/ets2panda/linter/arkanalyzer/src/transformer/StaticSingleAssignmentFormer.ts index 0f930f64ea..2c7e78deec 100644 --- a/ets2panda/linter/arkanalyzer/src/transformer/StaticSingleAssignmentFormer.ts +++ b/ets2panda/linter/arkanalyzer/src/transformer/StaticSingleAssignmentFormer.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -58,9 +58,12 @@ export class StaticSingleAssignmentFormer { } } - private decideBlockToPhiStmts(body: ArkBody, dominanceFinder: DominanceFinder, - blockToDefs: Map>, localToBlocks: Map>): - Map> { + private decideBlockToPhiStmts( + body: ArkBody, + dominanceFinder: DominanceFinder, + blockToDefs: Map>, + localToBlocks: Map> + ): Map> { let blockToPhiStmts = new Map>(); let blockToPhiLocals = new Map>(); let localToPhiBlock = new Map>(); @@ -81,11 +84,15 @@ export class StaticSingleAssignmentFormer { return blockToPhiStmts; } - private handleDf(blockToPhiStmts: Map>, - blockToPhiLocals: Map>, - phiBlocks: Set, df: BasicBlock, local: Local, - blockToDefs: Map>, - blocks: BasicBlock[]): void { + private handleDf( + blockToPhiStmts: Map>, + blockToPhiLocals: Map>, + phiBlocks: Set, + df: BasicBlock, + local: Local, + blockToDefs: Map>, + blocks: BasicBlock[] + ): void { if (!phiBlocks.has(df)) { phiBlocks.add(df); @@ -109,12 +116,14 @@ export class StaticSingleAssignmentFormer { } } - private handleBlockWithSucc(blockToPhiStmts: Map>, - succ: BasicBlock, - blockToDefs: Map>, - block: BasicBlock, - phiArgsNum: Map): void { - for (const phi of (blockToPhiStmts.get(succ) as Set)) { + private handleBlockWithSucc( + blockToPhiStmts: Map>, + succ: BasicBlock, + blockToDefs: Map>, + block: BasicBlock, + phiArgsNum: Map + ): void { + for (const phi of blockToPhiStmts.get(succ) as Set) { let local = phi.getDef() as Local; if (blockToDefs.get(block)?.has(local)) { if (phiArgsNum.has(phi)) { @@ -127,9 +136,7 @@ export class StaticSingleAssignmentFormer { } } - private addPhiStmts(blockToPhiStmts: Map>, cfg: Cfg, - blockToDefs: Map>): void { - + private addPhiStmts(blockToPhiStmts: Map>, cfg: Cfg, blockToDefs: Map>): void { let phiArgsNum = new Map(); for (const block of cfg.getBlocks()) { let succs = Array.from(block.getSuccessors()); @@ -155,8 +162,7 @@ export class StaticSingleAssignmentFormer { } } - private renameUseAndDef(stmt: Stmt, localToNameStack: Map, nextFreeIdx: number, - newLocals: Set, newPhiStmts: Set): number { + private renameUseAndDef(stmt: Stmt, localToNameStack: Map, nextFreeIdx: number, newLocals: Set, newPhiStmts: Set): number { let uses = stmt.getUses(); if (uses.length > 0 && !this.constainsPhiExpr(stmt)) { for (const use of uses) { @@ -185,12 +191,11 @@ export class StaticSingleAssignmentFormer { return nextFreeIdx; } - private renameLocals(body: ArkBody, dominanceTree: DominanceTree, - blockToPhiStmts: Map>): void { + private renameLocals(body: ArkBody, dominanceTree: DominanceTree, blockToPhiStmts: Map>): void { let newLocals = new Set(body.getLocals().values()); let localToNameStack = new Map(); for (const local of newLocals) { - localToNameStack.set(local, new Array()) + localToNameStack.set(local, new Array()); } let blockStack = new Array(); @@ -231,8 +236,7 @@ export class StaticSingleAssignmentFormer { body.setLocals(newLocals); } - private removeVisitedTree(blockStack: BasicBlock[], dominanceTree: DominanceTree, - visited: Set, localToNameStack: Map): void { + private removeVisitedTree(blockStack: BasicBlock[], dominanceTree: DominanceTree, visited: Set, localToNameStack: Map): void { let top = blockStack[blockStack.length - 1]; let children = dominanceTree.getChildren(top); while (this.containsAllChildren(visited, children)) { @@ -308,4 +312,4 @@ export class StaticSingleAssignmentFormer { let phiExpr = new ArkPhiExpr(); return new ArkAssignStmt(local, phiExpr); } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/transformer/Transformer.ts b/ets2panda/linter/arkanalyzer/src/transformer/Transformer.ts index 5b4d7f30bb..790c9319b5 100644 --- a/ets2panda/linter/arkanalyzer/src/transformer/Transformer.ts +++ b/ets2panda/linter/arkanalyzer/src/transformer/Transformer.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,12 +13,9 @@ * limitations under the License. */ - /** - * + * */ class Transformer { - internalTransform() { - - } -} \ No newline at end of file + internalTransform(): void {} +} diff --git a/ets2panda/linter/arkanalyzer/src/utils/AstTreeUtils.ts b/ets2panda/linter/arkanalyzer/src/utils/AstTreeUtils.ts index 8a86f8d57a..8266b8bafe 100644 --- a/ets2panda/linter/arkanalyzer/src/utils/AstTreeUtils.ts +++ b/ets2panda/linter/arkanalyzer/src/utils/AstTreeUtils.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,19 +13,57 @@ * limitations under the License. */ -import { ts } from '..'; +import { ArkFile, ts } from '..'; import { ETS_COMPILER_OPTIONS } from '../core/common/EtsConst'; +import * as crypto from 'crypto'; + +const sourceFileCache: Map = new Map(); export class AstTreeUtils { + /** + * get source file from code segment + * @param fileName source file name + * @param code source code + * @returns ts.SourceFile + */ public static getASTNode(fileName: string, code: string): ts.SourceFile { - const sourceFile = ts.createSourceFile( - fileName, - code, - ts.ScriptTarget.Latest, - true, - undefined, - ETS_COMPILER_OPTIONS - ); + const key = this.getKeyFromCode(code); + let sourceFile = sourceFileCache.get(key); + if (sourceFile) { + return sourceFile; + } + sourceFile = this.createSourceFile(fileName, code); + sourceFileCache.set(key, sourceFile); + return sourceFile; + } + + /** + * get source file from ArkFile + * @param arkFile ArkFile + * @returns ts.SourceFile + */ + public static getSourceFileFromArkFile(arkFile: ArkFile): ts.SourceFile { + const signature = arkFile.getFileSignature().toString(); + const key = this.getKeyFromCode(signature); + let sourceFile = sourceFileCache.get(key); + if (sourceFile) { + return sourceFile; + } + sourceFile = this.createSourceFile(arkFile.getName(), arkFile.getCode()); + sourceFileCache.set(key, sourceFile); return sourceFile; } + + public static createSourceFile(fileName: string, code: string): ts.SourceFile { + return ts.createSourceFile(fileName, code, ts.ScriptTarget.Latest, true, undefined, ETS_COMPILER_OPTIONS); + } + + /** + * convert source code to hash string + * @param code source code + * @returns string + */ + private static getKeyFromCode(code: string): string { + return crypto.createHash('sha256').update(code).digest('hex'); + } } diff --git a/ets2panda/linter/arkanalyzer/src/utils/CfgStructualAnalysis.ts b/ets2panda/linter/arkanalyzer/src/utils/CfgStructualAnalysis.ts index 886b47ad45..01899770e6 100644 --- a/ets2panda/linter/arkanalyzer/src/utils/CfgStructualAnalysis.ts +++ b/ets2panda/linter/arkanalyzer/src/utils/CfgStructualAnalysis.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -81,7 +81,7 @@ export class AbstractFlowGraph { return loop.inc.getBlock()!; } - public preOrder(node: AbstractNode, callback: TraversalCallback, visitor: Set = new Set()) { + public preOrder(node: AbstractNode, callback: TraversalCallback, visitor: Set = new Set()): void { visitor.add(node); node.traversal(callback, CodeBlockType.NORMAL); for (const succ of node.getSucc()) { @@ -456,12 +456,7 @@ export class AbstractFlowGraph { return true; } - if ( - m.getSucc().length === 1 && - loop.control.has(m.getSucc()[0]) && - !loop.control.has(n) && - !this.isIfElseRegion(node, nodeSet) - ) { + if (m.getSucc().length === 1 && loop.control.has(m.getSucc()[0]) && !loop.control.has(n) && !this.isIfElseRegion(node, nodeSet)) { nodeSet.add(node).add(m); return true; } @@ -483,11 +478,7 @@ export class AbstractFlowGraph { if (loop.header === node && loop.getType() === RegionType.FOR_LOOP_REGION) { let forLoop = loop as ForLoopRegion; let blocks = node.getSucc()[0]; - if ( - forLoop.inc.getPred().length === 1 && - forLoop.inc.getPred()[0] === blocks && - blocks.getSucc().length === 1 - ) { + if (forLoop.inc.getPred().length === 1 && forLoop.inc.getPred()[0] === blocks && blocks.getSucc().length === 1) { nodeSet.add(node).add(forLoop.inc).add(blocks); return true; } @@ -507,11 +498,7 @@ export class AbstractFlowGraph { return false; } - private identifyRegionType( - node: AbstractNode, - nodeSet: Set, - scope?: Set - ): RegionType | undefined { + private identifyRegionType(node: AbstractNode, nodeSet: Set, scope?: Set): RegionType | undefined { if (this.isBlockRegion(node, nodeSet, scope)) { return RegionType.BLOCK_REGION; } @@ -668,11 +655,7 @@ export class AbstractFlowGraph { let doWhileLoop = new DoWhileLoopRegion(nodeSet); this.loopMap.set(doWhileLoop.header, doWhileLoop); node = doWhileLoop; - } else if ( - rtype === RegionType.TRY_CATCH_REGION || - rtype === RegionType.TRY_FINALLY_REGION || - rtype === RegionType.TRY_CATCH_FINALLY_REGION - ) { + } else if (rtype === RegionType.TRY_CATCH_REGION || rtype === RegionType.TRY_FINALLY_REGION || rtype === RegionType.TRY_CATCH_FINALLY_REGION) { node = new TrapRegion(nodeSet, rtype); } @@ -727,12 +710,7 @@ export class AbstractFlowGraph { if (!traps) { return []; } - traps.sort( - (a, b) => - a.getTryBlocks().length + - a.getCatchBlocks().length - - (b.getTryBlocks().length + b.getCatchBlocks().length) - ); + traps.sort((a, b) => a.getTryBlocks().length + a.getCatchBlocks().length - (b.getTryBlocks().length + b.getCatchBlocks().length)); let trapRegions: NaturalTrapRegion[] = []; @@ -911,7 +889,7 @@ class AbstractNode { this.type = RegionType.ABSTRACT_NODE; } - public traversal(callback: TraversalCallback, type: CodeBlockType) { + public traversal(callback: TraversalCallback, type: CodeBlockType): void { callback(this.bb, type); } @@ -923,11 +901,11 @@ class AbstractNode { return this.succNodes; } - public addSucc(node: AbstractNode) { + public addSucc(node: AbstractNode): void { this.succNodes.push(node); } - public replaceSucc(src: AbstractNode, dst: AbstractNode) { + public replaceSucc(src: AbstractNode, dst: AbstractNode): void { for (let i = 0; i < this.succNodes.length; i++) { if (this.succNodes[i] === src) { this.succNodes[i] = dst; @@ -936,7 +914,7 @@ class AbstractNode { } } - public removeSucc(src: AbstractNode) { + public removeSucc(src: AbstractNode): void { for (let i = 0; i < this.predNodes.length; i++) { if (this.succNodes[i] === src) { this.succNodes.splice(i, 1); @@ -957,7 +935,7 @@ class AbstractNode { this.predNodes.push(block); } - public replacePred(src: AbstractNode, dst: AbstractNode) { + public replacePred(src: AbstractNode, dst: AbstractNode): void { for (let i = 0; i < this.predNodes.length; i++) { if (this.predNodes[i] === src) { this.predNodes[i] = dst; @@ -966,7 +944,7 @@ class AbstractNode { } } - public removePred(src: AbstractNode) { + public removePred(src: AbstractNode): void { for (let i = 0; i < this.predNodes.length; i++) { if (this.predNodes[i] === src) { this.predNodes.splice(i, 1); @@ -975,7 +953,7 @@ class AbstractNode { } } - public setBlock(bb: BasicBlock) { + public setBlock(bb: BasicBlock): void { this.bb = bb; } @@ -1035,7 +1013,7 @@ class BlockRegion extends Region { this.blocks = Array.from(nset); } - public replace() { + public replace(): void { for (let pred of this.blocks[0].getPred()) { pred.replaceSucc(this.blocks[0], this); this.addPred(pred); @@ -1047,7 +1025,7 @@ class BlockRegion extends Region { } } - public traversal(callback: TraversalCallback) { + public traversal(callback: TraversalCallback): void { for (const node of this.blocks) { node.traversal(callback, CodeBlockType.NORMAL); } @@ -1111,12 +1089,7 @@ abstract class NaturalLoopRegion extends Region { // add node to loop sets for (const node of this.nset) { for (const succ of node.getSucc()) { - if ( - !this.nset.has(succ) && - succ !== this.getExitNode() && - succ.getSucc().length === 1 && - succ.getSucc()[0] === this.getExitNode() - ) { + if (!this.nset.has(succ) && succ !== this.getExitNode() && succ.getSucc().length === 1 && succ.getSucc()[0] === this.getExitNode()) { this.nset.add(succ); } } @@ -1132,7 +1105,7 @@ class SelfLoopRegion extends NaturalLoopRegion { this.back = this.header; } - public replace() { + public replace(): void { for (let pred of this.header.getPred()) { if (pred !== this.header) { pred.replaceSucc(this.header, this); @@ -1158,7 +1131,7 @@ class WhileLoopRegion extends NaturalLoopRegion { super(nset, RegionType.WHILE_LOOP_REGION); } - public traversal(callback: TraversalCallback) { + public traversal(callback: TraversalCallback): void { this.header.traversal(callback, CodeBlockType.WHILE); if (this.header !== this.back) { this.back.traversal(callback, CodeBlockType.NORMAL); @@ -1178,7 +1151,7 @@ class DoWhileLoopRegion extends NaturalLoopRegion { this.control.add(this.back); } - public traversal(callback: TraversalCallback) { + public traversal(callback: TraversalCallback): void { callback(undefined, CodeBlockType.DO); if (this.header !== this.back) { this.header.traversal(callback, CodeBlockType.NORMAL); @@ -1200,7 +1173,7 @@ class ForLoopRegion extends NaturalLoopRegion { this.control.add(this.inc); } - public traversal(callback: TraversalCallback) { + public traversal(callback: TraversalCallback): void { this.header.traversal(callback, CodeBlockType.FOR); for (const node of this.nset) { if (node !== this.header && node !== this.inc) { @@ -1238,7 +1211,7 @@ class IfRegion extends Region { } } - public traversal(callback: TraversalCallback) { + public traversal(callback: TraversalCallback): void { this.contition.traversal(callback, CodeBlockType.IF); this.then.traversal(callback, CodeBlockType.NORMAL); callback(undefined, CodeBlockType.COMPOUND_END); @@ -1260,7 +1233,7 @@ class IfExitRegion extends IfRegion { this.type = RegionType.IF_THEN_EXIT_REGION; } - public replace() { + public replace(): void { this.replaceContitionPred(); let succ = this.contition.getSucc()[1]; @@ -1275,7 +1248,7 @@ class IfBreakRegion extends IfRegion { this.type = RegionType.IF_THEN_BREAK_REGION; } - public replace() { + public replace(): void { this.replaceContitionPred(); let succ = this.contition.getSucc()[1]; @@ -1291,7 +1264,7 @@ class IfBreakRegion extends IfRegion { } } - public traversal(callback: TraversalCallback) { + public traversal(callback: TraversalCallback): void { this.contition.traversal(callback, CodeBlockType.IF); this.then?.traversal(callback, CodeBlockType.NORMAL); callback(undefined, CodeBlockType.BREAK); @@ -1305,7 +1278,7 @@ class IfContinueRegion extends IfBreakRegion { this.type = RegionType.IF_THEN_CONTINUE_REGION; } - public traversal(callback: TraversalCallback) { + public traversal(callback: TraversalCallback): void { this.contition.traversal(callback, CodeBlockType.IF); this.then?.traversal(callback, CodeBlockType.NORMAL); callback(undefined, CodeBlockType.CONTINUE); @@ -1326,7 +1299,7 @@ class IfElseRegion extends Region { this.else = nodes[2]; } - public replace() { + public replace(): void { for (let pred of this.contition.getPred()) { if (pred !== this.contition) { pred.replaceSucc(this.contition, this); @@ -1343,7 +1316,7 @@ class IfElseRegion extends Region { } } - public traversal(callback: TraversalCallback) { + public traversal(callback: TraversalCallback): void { this.contition.traversal(callback, CodeBlockType.IF); this.then.traversal(callback, CodeBlockType.NORMAL); callback(undefined, CodeBlockType.ELSE); @@ -1397,7 +1370,7 @@ class TrapRegion extends Region { } } - public traversal(callback: TraversalCallback) { + public traversal(callback: TraversalCallback): void { callback(undefined, CodeBlockType.TRY); this.tryNode.traversal(callback, CodeBlockType.NORMAL); if (this.catchNode) { diff --git a/ets2panda/linter/arkanalyzer/src/utils/FileUtils.ts b/ets2panda/linter/arkanalyzer/src/utils/FileUtils.ts index 4cf756fc0b..a4837006ed 100644 --- a/ets2panda/linter/arkanalyzer/src/utils/FileUtils.ts +++ b/ets2panda/linter/arkanalyzer/src/utils/FileUtils.ts @@ -25,8 +25,8 @@ const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'FileUtils'); export class FileUtils { public static readonly FILE_FILTER = { ignores: ['.git', '.preview', '.hvigor', '.idea', 'test', 'ohosTest'], - include: /(? { if (!content.dependencies) { return; @@ -72,11 +69,10 @@ export class FileUtils { const key = path.resolve(modulePath, OH_PACKAGE_JSON5); const target = ohPkgContentMap.get(key); if (target) { - moduleMap.set(name, new ModulePath(modulePath, target.main ? - path.resolve(modulePath, target.main as string) : '')); + moduleMap.set(name, new ModulePath(modulePath, target.main ? path.resolve(modulePath, target.main as string) : '')); } }); - }) + }); return moduleMap; } @@ -90,6 +86,8 @@ export class FileUtils { return Language.TYPESCRIPT; case '.ets': return Language.ARKTS1_1; + case '.js': + return Language.JAVASCRIPT; default: return Language.UNKNOWN; } @@ -114,7 +112,7 @@ export function getFileRecursively(srcDir: string, fileName: string, visited: Se } const filesUnderThisDir = fs.readdirSync(srcDir, { withFileTypes: true }); - const realSrc = fs.realpathSync(srcDir) + const realSrc = fs.realpathSync(srcDir); if (visited.has(realSrc)) { return res; } @@ -130,6 +128,7 @@ export function getFileRecursively(srcDir: string, fileName: string, visited: Se } const tmpDir = path.resolve(srcDir, '../'); res = getFileRecursively(tmpDir, fileName, visited); + return res; }); return res; -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/utils/SparseBitVector.ts b/ets2panda/linter/arkanalyzer/src/utils/SparseBitVector.ts index ec36ed6ee8..fcb5c816ac 100644 --- a/ets2panda/linter/arkanalyzer/src/utils/SparseBitVector.ts +++ b/ets2panda/linter/arkanalyzer/src/utils/SparseBitVector.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -120,7 +120,7 @@ class SparseBitVectorElement { // Count the number of set bits in this element count(): number { let numBits = 0; - this.bits.forEach((word) => { + this.bits.forEach(word => { numBits += this.countBits(word); }); return numBits; @@ -354,7 +354,9 @@ export class SparseBitVector { // Find the first set bit in the vector findFirst(): number { - if (this.elements.size === 0) return -1; + if (this.elements.size === 0) { + return -1; + } const firstElement = this.elements.entries().next().value; if (firstElement) { const firstBit = firstElement[1].findFirst(); @@ -385,10 +387,10 @@ export class SparseBitVector { let element = next.value; if (!element) { return { - next() { + next(): { value: undefined; done: true } { return { value: undefined, done: true }; }, - [Symbol.iterator]() { + [Symbol.iterator](): IterableIterator { return this; // Make the iterator itself iterable }, }; @@ -410,7 +412,7 @@ export class SparseBitVector { } return { value: undefined, done: true }; }, - [Symbol.iterator]() { + [Symbol.iterator](): IterableIterator { return this; // Make the iterator itself iterable }, }; @@ -498,7 +500,7 @@ export class SparseBitVector { } if (needDeleteIdx.size > 0) { - needDeleteIdx.forEach((idx) => this.elements.delete(idx)); + needDeleteIdx.forEach(idx => this.elements.delete(idx)); changed = true; } @@ -529,7 +531,7 @@ export class SparseBitVector { } if (needDeleteIdx.size > 0) { - needDeleteIdx.forEach((idx) => this.elements.delete(idx)); + needDeleteIdx.forEach(idx => this.elements.delete(idx)); changed = true; } diff --git a/ets2panda/linter/arkanalyzer/src/utils/callGraphUtils.ts b/ets2panda/linter/arkanalyzer/src/utils/callGraphUtils.ts index d37b14203c..c15236a0b3 100644 --- a/ets2panda/linter/arkanalyzer/src/utils/callGraphUtils.ts +++ b/ets2panda/linter/arkanalyzer/src/utils/callGraphUtils.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -48,25 +48,17 @@ export class MethodSignatureManager { public findInProcessedList(signature: MethodSignature): boolean { let result = this.processedList.find(item => item.toString() === signature.toString()); - return typeof result !== "undefined"; + return typeof result !== 'undefined'; } public addToWorkList(signature: MethodSignature): void { - if (!isItemRegistered( - signature, this.workList, - (a, b) => - a.toString() === b.toString() - )) { + if (!isItemRegistered(signature, this.workList, (a, b) => a.toString() === b.toString())) { this.workList.push(signature); } } public addToProcessedList(signature: MethodSignature): void { - if (!isItemRegistered( - signature, this.processedList, - (a, b) => - a === b - )) { + if (!isItemRegistered(signature, this.processedList, (a, b) => a === b)) { this.processedList.push(signature); } } @@ -110,9 +102,10 @@ export class SceneManager { } public getClass(arkClass: ClassSignature): ArkClass | null { - if (typeof arkClass.getClassName() === "undefined") - return null - let classInstance = this._scene.getClass(arkClass) + if (typeof arkClass.getClassName() === 'undefined') { + return null; + } + let classInstance = this._scene.getClass(arkClass); if (classInstance != null) { return classInstance; } @@ -121,22 +114,23 @@ export class SceneManager { if (sdkOrTargetProjectFile != null) { for (let classUnderFile of ModelUtils.getAllClassesInFile(sdkOrTargetProjectFile)) { if (classUnderFile.getSignature().toString() === arkClass.toString()) { - return classUnderFile + return classUnderFile; } } } - return classInstance + return classInstance; } public getExtendedClasses(arkClass: ClassSignature): ArkClass[] { - let sourceClass = this.getClass(arkClass) - let classList = [sourceClass] // 待处理类 - let extendedClasses: ArkClass[] = [] // 已经处理的类 + let sourceClass = this.getClass(arkClass); + let classList = [sourceClass]; // 待处理类 + let extendedClasses: ArkClass[] = []; // 已经处理的类 while (classList.length > 0) { - let tempClass = classList.shift() - if (tempClass == null) - continue + let tempClass = classList.shift(); + if (tempClass == null) { + continue; + } let firstLevelSubclasses: ArkClass[] = Array.from(tempClass.getExtendedClasses().values()); if (!firstLevelSubclasses) { @@ -144,26 +138,18 @@ export class SceneManager { } for (let subclass of firstLevelSubclasses) { - if (!isItemRegistered( - subclass, extendedClasses, - (a, b) => - a.getSignature().toString() === b.getSignature().toString() - )) { + if (!isItemRegistered(subclass, extendedClasses, (a, b) => a.getSignature().toString() === b.getSignature().toString())) { // 子类未处理,加入到classList - classList.push(subclass) + classList.push(subclass); } } // 当前类处理完毕,标记为已处理 - if (!isItemRegistered( - tempClass, extendedClasses, - (a, b) => - a.getSignature().toString() === b.getSignature().toString() - )) { - extendedClasses.push(tempClass) + if (!isItemRegistered(tempClass, extendedClasses, (a, b) => a.getSignature().toString() === b.getSignature().toString())) { + extendedClasses.push(tempClass); } } - return extendedClasses + return extendedClasses; } } @@ -192,7 +178,7 @@ export function splitStringWithRegex(input: string): string[] { export function printCallGraphDetails(methods: Set, calls: Map, rootDir: string): void { // 打印 Methods - logger.info("Call Graph:\n") + logger.info('Call Graph:\n'); logger.info('\tMethods:'); methods.forEach(method => { logger.info(`\t\t${method}`); @@ -210,7 +196,7 @@ export function printCallGraphDetails(methods: Set, calls: Map< const modifiedCalledMethod = `\t\t<${calledMethods[i]}`; logger.info(`\t\t${modifiedCalledMethod}`); } - logger.info("\n") + logger.info('\n'); }); } @@ -220,5 +206,5 @@ export function extractLastBracketContent(input: string): string { if (match && match[1]) { return match[1].trim(); } - return ""; -} \ No newline at end of file + return ''; +} diff --git a/ets2panda/linter/arkanalyzer/src/utils/crypto_utils.ts b/ets2panda/linter/arkanalyzer/src/utils/crypto_utils.ts index 39a64826f0..9563d475b1 100644 --- a/ets2panda/linter/arkanalyzer/src/utils/crypto_utils.ts +++ b/ets2panda/linter/arkanalyzer/src/utils/crypto_utils.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,6 @@ import * as crypto from 'crypto'; export class CryptoUtils { - public static sha256(content: string): string { return this.hash(content, 'sha256'); } @@ -28,7 +27,7 @@ export class CryptoUtils { public static hashcode(content: string): number { let h = 0; for (let i = 0; i < content.length; i++) { - h = Math.imul(31, h) + content.charCodeAt(i) | 0; + h = (Math.imul(31, h) + content.charCodeAt(i)) | 0; } return h; } diff --git a/ets2panda/linter/arkanalyzer/src/utils/entryMethodUtils.ts b/ets2panda/linter/arkanalyzer/src/utils/entryMethodUtils.ts index c9bfa8e0d6..b908801378 100644 --- a/ets2panda/linter/arkanalyzer/src/utils/entryMethodUtils.ts +++ b/ets2panda/linter/arkanalyzer/src/utils/entryMethodUtils.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -45,25 +45,25 @@ export const LIFECYCLE_METHOD_NAME: string[] = [ 'onConfigurationUpdate', 'onAcquireFormState', 'onWindowStageWillDestroy', - ]; +]; export const CALLBACK_METHOD_NAME: string[] = [ - "onClick", // 点击事件,当用户点击组件时触发 - "onTouch", // 触摸事件,当手指在组件上按下、滑动、抬起时触发 - "onAppear", // 组件挂载显示时触发 - "onDisAppear", // 组件卸载消失时触发 - "onDragStart", // 拖拽开始事件,当组件被长按后开始拖拽时触发 - "onDragEnter", // 拖拽进入组件范围时触发 - "onDragMove", // 拖拽在组件范围内移动时触发 - "onDragLeave", // 拖拽离开组件范围内时触发 - "onDrop", // 拖拽释放目标,当在本组件范围内停止拖拽行为时触发 - "onKeyEvent", // 按键事件,当组件获焦后,按键动作触发 - "onFocus", // 焦点事件,当组件获取焦点时触发 - "onBlur", // 当组件失去焦点时触发的回调 - "onHover", // 鼠标悬浮事件,鼠标进入或退出组件时触发 - "onMouse", // 鼠标事件,当鼠标按键点击或在组件上移动时触发 - "onAreaChange", // 组件区域变化事件,组件尺寸、位置变化时触发 - "onVisibleAreaChange", // 组件可见区域变化事件,组件在屏幕中的显示区域面积变化时触发 - ]; + 'onClick', // 点击事件,当用户点击组件时触发 + 'onTouch', // 触摸事件,当手指在组件上按下、滑动、抬起时触发 + 'onAppear', // 组件挂载显示时触发 + 'onDisAppear', // 组件卸载消失时触发 + 'onDragStart', // 拖拽开始事件,当组件被长按后开始拖拽时触发 + 'onDragEnter', // 拖拽进入组件范围时触发 + 'onDragMove', // 拖拽在组件范围内移动时触发 + 'onDragLeave', // 拖拽离开组件范围内时触发 + 'onDrop', // 拖拽释放目标,当在本组件范围内停止拖拽行为时触发 + 'onKeyEvent', // 按键事件,当组件获焦后,按键动作触发 + 'onFocus', // 焦点事件,当组件获取焦点时触发 + 'onBlur', // 当组件失去焦点时触发的回调 + 'onHover', // 鼠标悬浮事件,鼠标进入或退出组件时触发 + 'onMouse', // 鼠标事件,当鼠标按键点击或在组件上移动时触发 + 'onAreaChange', // 组件区域变化事件,组件尺寸、位置变化时触发 + 'onVisibleAreaChange', // 组件可见区域变化事件,组件在屏幕中的显示区域面积变化时触发 +]; export const COMPONENT_LIFECYCLE_METHOD_NAME: string[] = [ 'build', @@ -82,7 +82,7 @@ export const COMPONENT_LIFECYCLE_METHOD_NAME: string[] = [ 'onFormRecover', 'onBackPress', 'pageTransition', - 'onDidBuild' + 'onDidBuild', ]; export interface AbilityMessage { @@ -93,9 +93,11 @@ export interface AbilityMessage { export function getCallbackMethodFromStmt(stmt: Stmt, scene: Scene): ArkMethod | null { const invokeExpr = stmt.getInvokeExpr(); - if (invokeExpr === undefined || + if ( + invokeExpr === undefined || invokeExpr.getMethodSignature().getDeclaringClassSignature().getClassName() !== '' || - !CALLBACK_METHOD_NAME.includes(invokeExpr.getMethodSignature().getMethodSubSignature().getMethodName())) { + !CALLBACK_METHOD_NAME.includes(invokeExpr.getMethodSignature().getMethodSubSignature().getMethodName()) + ) { return null; } @@ -111,7 +113,7 @@ export function getCallbackMethodFromStmt(stmt: Stmt, scene: Scene): ArkMethod | return null; } -export function addCfg2Stmt(method: ArkMethod) { +export function addCfg2Stmt(method: ArkMethod): void { const cfg = method.getCfg(); if (cfg) { for (const block of cfg.getBlocks()) { @@ -120,4 +122,4 @@ export function addCfg2Stmt(method: ArkMethod) { } } } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/utils/getAllFiles.ts b/ets2panda/linter/arkanalyzer/src/utils/getAllFiles.ts index 17823aea70..fe4af56c9e 100644 --- a/ets2panda/linter/arkanalyzer/src/utils/getAllFiles.ts +++ b/ets2panda/linter/arkanalyzer/src/utils/getAllFiles.ts @@ -27,45 +27,45 @@ const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'getAllFiles'); * @return string[] 提取出的文件的原始路径数组 */ export function getAllFiles( - srcPath: string, - exts: string[], - ignore: string[] = [], - filenameArr: string[] = [], - visited: Set = new Set() + srcPath: string, + exts: string[], + ignore: string[] = [], + filenameArr: string[] = [], + visited: Set = new Set() ): string[] { - let ignoreFiles: Set = new Set(ignore); - // 如果源目录不存在,直接结束程序 - if (!fs.existsSync(srcPath)) { - logger.error(`Input directory ${srcPath} is not exist, please check!`); - return filenameArr; - } - - // 获取src的绝对路径 - const realSrc = fs.realpathSync(srcPath); - if (visited.has(realSrc)) { - return filenameArr; - } - visited.add(realSrc); + let ignoreFiles: Set = new Set(ignore); + // 如果源目录不存在,直接结束程序 + if (!fs.existsSync(srcPath)) { + logger.error(`Input directory ${srcPath} is not exist, please check!`); + return filenameArr; + } - // 遍历src,判断文件类型 - fs.readdirSync(realSrc).forEach(filename => { - if (ignoreFiles.has(filename)) { - return; + // 获取src的绝对路径 + const realSrc = fs.realpathSync(srcPath); + if (visited.has(realSrc)) { + return filenameArr; } - // 拼接文件的绝对路径 - const realFile = path.resolve(realSrc, filename); + visited.add(realSrc); - //TODO: 增加排除文件后缀和目录 + // 遍历src,判断文件类型 + fs.readdirSync(realSrc).forEach(filename => { + if (ignoreFiles.has(filename)) { + return; + } + // 拼接文件的绝对路径 + const realFile = path.resolve(realSrc, filename); - // 如果是目录,递归提取 - if (fs.statSync(realFile).isDirectory()) { - getAllFiles(realFile, exts, ignore, filenameArr, visited); - } else { - // 如果是文件,则判断其扩展名是否在给定的扩展名数组中 - if (exts.includes(path.extname(filename))) { - filenameArr.push(realFile); - } - } - }) - return filenameArr; + //TODO: 增加排除文件后缀和目录 + + // 如果是目录,递归提取 + if (fs.statSync(realFile).isDirectory()) { + getAllFiles(realFile, exts, ignore, filenameArr, visited); + } else { + // 如果是文件,则判断其扩展名是否在给定的扩展名数组中 + if (exts.includes(path.extname(filename))) { + filenameArr.push(realFile); + } + } + }); + return filenameArr; } diff --git a/ets2panda/linter/arkanalyzer/src/utils/json5parser.ts b/ets2panda/linter/arkanalyzer/src/utils/json5parser.ts index 7ca3f86354..4b581a7e42 100644 --- a/ets2panda/linter/arkanalyzer/src/utils/json5parser.ts +++ b/ets2panda/linter/arkanalyzer/src/utils/json5parser.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -19,7 +19,9 @@ import Logger, { LOG_MODULE_TYPE } from './logger'; const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'json5parser'); -export function fetchDependenciesFromFile(filePath: string): { [k: string]: unknown } { +export function fetchDependenciesFromFile(filePath: string): { + [k: string]: unknown; +} { if (!fs.existsSync(filePath)) { return {}; } @@ -62,7 +64,7 @@ function getRootObjectLiteral(file: ts.JsonSourceFile): ts.ObjectLiteralExpressi } const rootObjectLiteralExpression = (expressionStatement as ts.ExpressionStatement).expression; if (!rootObjectLiteralExpression) { - logger.error('The JSON5 file format is incorrect, the first child node is empty.') + logger.error('The JSON5 file format is incorrect, the first child node is empty.'); return undefined; } @@ -100,11 +102,11 @@ function parsePropertyInitializer(node: ts.Expression, file: ts.JsonSourceFile): return undefined; } -function parseArrayLiteral(node: ts.Expression, file: ts.JsonSourceFile) { +function parseArrayLiteral(node: ts.Expression, file: ts.JsonSourceFile): unknown[] { const res: unknown[] = []; (node as ts.ArrayLiteralExpression).elements.forEach(n => { res.push(parsePropertyInitializer(n, file)); - }) + }); return res; } @@ -115,7 +117,6 @@ function parseObjectLiteralExpression(ObjectLiteralExpression: ts.ObjectLiteralE const key = (propNode.name as ts.Identifier).text; const value = parsePropertyInitializer(propNode.initializer, file); res[key] = value; - }) + }); return res; } - diff --git a/ets2panda/linter/arkanalyzer/src/utils/logger.ts b/ets2panda/linter/arkanalyzer/src/utils/logger.ts index 904ffc8a55..0e42ac832c 100644 --- a/ets2panda/linter/arkanalyzer/src/utils/logger.ts +++ b/ets2panda/linter/arkanalyzer/src/utils/logger.ts @@ -32,10 +32,12 @@ export enum LOG_MODULE_TYPE { } export default class ConsoleLogger { - public static configure(logFilePath: string, - arkanalyzer_level: LOG_LEVEL = LOG_LEVEL.ERROR, - tool_level: LOG_LEVEL = LOG_LEVEL.INFO, - use_console: boolean = false): void { + public static configure( + logFilePath: string, + arkanalyzer_level: LOG_LEVEL = LOG_LEVEL.ERROR, + tool_level: LOG_LEVEL = LOG_LEVEL.INFO, + use_console: boolean = false + ): void { let appendersTypes: string[] = []; if (logFilePath) { appendersTypes.push('file'); @@ -96,4 +98,4 @@ export default class ConsoleLogger { logger.addContext('tag', tag); return logger; } -} \ No newline at end of file +} diff --git a/ets2panda/linter/arkanalyzer/src/utils/pathTransfer.ts b/ets2panda/linter/arkanalyzer/src/utils/pathTransfer.ts index 7a491cabb0..65858744c2 100644 --- a/ets2panda/linter/arkanalyzer/src/utils/pathTransfer.ts +++ b/ets2panda/linter/arkanalyzer/src/utils/pathTransfer.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -15,14 +15,6 @@ import path from 'path'; -export function transfer2UnixPath(path2Do: string) { +export function transfer2UnixPath(path2Do: string): string { return path.posix.join(...path2Do.split(/\\/)); } - -export function getArkAnalyzerModulePath(moduleName: string): string | null { - try { - return path.dirname(path.dirname(require.resolve(moduleName))); - } catch (e) { - return null; - } -} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/vitest.config.ts b/ets2panda/linter/arkanalyzer/vitest.config.ts index 2ba68acd21..d098faa737 100644 --- a/ets2panda/linter/arkanalyzer/vitest.config.ts +++ b/ets2panda/linter/arkanalyzer/vitest.config.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,13 +13,13 @@ * limitations under the License. */ -import { defineConfig } from 'vitest/config' +import { defineConfig } from 'vitest/config'; export default defineConfig({ - test: { - include: ["tests/unit/**/*.test.ts"], - coverage: { - include: ["src/**"] - } - } -}) \ No newline at end of file + test: { + include: ['tests/unit/**/*.test.ts'], + coverage: { + include: ['src/**'], + }, + }, +}); diff --git a/ets2panda/linter/build_linter.py b/ets2panda/linter/build_linter.py index 943721cf82..cfc970134c 100755 --- a/ets2panda/linter/build_linter.py +++ b/ets2panda/linter/build_linter.py @@ -19,6 +19,7 @@ import shutil import subprocess import sys import tarfile +import time def copy_files(source_path, dest_path, is_file=False): @@ -45,6 +46,19 @@ def run_cmd(cmd, execution_path=None): return stdout +def run_cmd_with_retry(max_retries, wait_time, cmd, execution_path=None): + retry_count = 0 + while retry_count < max_retries: + try: + run_cmd(cmd, execution_path) + break + except Exception: + retry_count += 1 + time.sleep(wait_time) + if retry_count >= max_retries: + raise Exception("Failed to run cmd: " + cmd) + + def is_npm_newer_than_6(options): cmd = [options.npm, '-v'] stdout = run_cmd(cmd, options.source_path) @@ -115,6 +129,54 @@ def clean_old_packages(directory, prefix, suffix): return res +def backup_package_files(source_path): + package_name = 'package.json' + package_back_name = 'package.json.bak' + aa_path = os.path.join(source_path, 'arkanalyzer') + hc_path = os.path.join(source_path, 'homecheck') + linter_path = source_path + copy_files(os.path.join(aa_path, package_name), os.path.join(aa_path, package_back_name), True) + copy_files(os.path.join(hc_path, package_name), os.path.join(hc_path, package_back_name), True) + copy_files(os.path.join(linter_path, package_name), os.path.join(linter_path, package_back_name), True) + + +def clean_env(source_path): + package_name = 'package.json' + package_back_name = 'package.json.bak' + package_lock_name = 'package-lock.json' + aa_path = os.path.join(source_path, 'arkanalyzer') + hc_path = os.path.join(source_path, 'homecheck') + linter_path = source_path + try: + copy_files(os.path.join(aa_path, package_back_name), os.path.join(aa_path, package_name), True) + copy_files(os.path.join(hc_path, package_back_name), os.path.join(hc_path, package_name), True) + copy_files(os.path.join(linter_path, package_back_name), os.path.join(linter_path, package_name), True) + os.remove(os.path.join(hc_path, package_lock_name)) + os.remove(os.path.join(linter_path, package_lock_name)) + os.remove(os.path.join(aa_path, package_back_name)) + os.remove(os.path.join(hc_path, package_back_name)) + os.remove(os.path.join(linter_path, package_back_name)) + except Exception: + return False + return True + + +def aa_copy_lib_files(options): + aa_path = os.path.join(options.source_path, 'arkanalyzer') + source_file_1 = os.path.join(aa_path, 'node_modules', 'ohos-typescript', 'lib', 'lib.es5.d.ts') + dest_path = os.path.join(aa_path, 'builtIn', 'typescript', 'api', '@internal') + copy_files(source_file_1, dest_path, True) + source_file_2 = os.path.join(aa_path, 'node_modules', 'ohos-typescript', 'lib', 'lib.es2015.collection.d.ts') + copy_files(source_file_2, dest_path, True) + + +def hc_copy_lib_files(options): + hc_path = os.path.join(options.source_path, 'homecheck') + source_file = os.path.join(hc_path, 'node_modules', 'ohos-typescript', 'lib', 'lib.es5.d.ts') + dest_path = os.path.join(hc_path, 'resources', 'internalSdk', '@internal') + copy_files(source_file, dest_path, True) + + def pack_arkanalyzer(options, new_npm): aa_path = os.path.join(options.source_path, 'arkanalyzer') tsc_file = 'file:' + options.typescript @@ -123,17 +185,18 @@ def pack_arkanalyzer(options, new_npm): clean_old_packages(aa_path, pack_prefix, pack_suffix) if new_npm: - ts_install_cmd = [options.npm, 'install', tsc_file, '--legacy-peer-deps', '--offline'] + ts_install_cmd = [options.npm, 'install', '--no-save', tsc_file, '--legacy-peer-deps', '--offline'] else: - ts_install_cmd = [options.npm, 'install', tsc_file] + ts_install_cmd = [options.npm, 'install', '--no-save', tsc_file] compile_cmd = [options.npm, 'run', 'compile'] pack_cmd = [options.npm, 'pack'] run_cmd(ts_install_cmd, aa_path) + aa_copy_lib_files(options) run_cmd(compile_cmd, aa_path) run_cmd(pack_cmd, aa_path) -def install_homecheck(options): +def install_homecheck(options, max_retries, wait_time): new_npm = is_npm_newer_than_6(options) pack_arkanalyzer(options, new_npm) aa_path = os.path.join(options.source_path, 'arkanalyzer') @@ -148,7 +211,7 @@ def install_homecheck(options): aa_install_cmd = [options.npm, 'install', aa_file, '--legacy-peer-deps', '--offline'] else: aa_install_cmd = [options.npm, 'install', aa_file] - run_cmd(aa_install_cmd, hc_path) + run_cmd_with_retry(max_retries, wait_time, aa_install_cmd, hc_path) else: raise Exception('Failed to find arkanalyzer npm package') @@ -160,7 +223,8 @@ def install_homecheck(options): ts_install_cmd = [options.npm, 'install', '--no-save', tsc_file] pack_cmd = [options.npm, 'pack'] compile_cmd = [options.npm, 'run', 'compile'] - run_cmd(ts_install_cmd, hc_path) + run_cmd_with_retry(max_retries, wait_time, ts_install_cmd, hc_path) + hc_copy_lib_files(options) run_cmd(compile_cmd, hc_path) run_cmd(pack_cmd, hc_path) exist_hc_packs = find_files_by_prefix_suffix(hc_path, hc_pack_prefix, pack_suffix) @@ -170,7 +234,7 @@ def install_homecheck(options): hc_install_cmd = [options.npm, 'install', hc_file, '--legacy-peer-deps', '--offline'] else: hc_install_cmd = [options.npm, 'install', hc_file] - run_cmd(hc_install_cmd, options.source_path) + run_cmd_with_retry(max_retries, wait_time, hc_install_cmd, options.source_path) else: raise Exception('Failed to find homecheck npm package') @@ -201,15 +265,15 @@ def parse_args(): def main(): options = parse_args() - install_homecheck(options) + backup_package_files(options.source_path) + install_homecheck(options, 5, 3) install_typescript(options) node_modules_path = os.path.join(options.source_path, "node_modules") extract(options.typescript, node_modules_path, "typescript") build(options) copy_output(options) + clean_env(options.source_path) if __name__ == '__main__': sys.exit(main()) - - diff --git a/ets2panda/linter/eslint.config.mjs b/ets2panda/linter/eslint.config.mjs index d39b40f91a..f5afd19191 100644 --- a/ets2panda/linter/eslint.config.mjs +++ b/ets2panda/linter/eslint.config.mjs @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/ets2panda/linter/homecheck/.prettierrc b/ets2panda/linter/homecheck/.prettierrc new file mode 100644 index 0000000000..727d5c6ae2 --- /dev/null +++ b/ets2panda/linter/homecheck/.prettierrc @@ -0,0 +1,10 @@ +{ + "trailingComma": "es5", + "tabWidth": 4, + "useTabs": false, + "semi": true, + "singleQuote": true, + "printWidth": 160, + "quoteProps": "as-needed", + "arrowParens": "avoid" +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/README.en.md b/ets2panda/linter/homecheck/README.en.md new file mode 100644 index 0000000000..656170858d --- /dev/null +++ b/ets2panda/linter/homecheck/README.en.md @@ -0,0 +1,36 @@ +# arkcheck + +#### Description +ArkTS代码高性能反模式静态扫描工具 + +#### Software Architecture +Software architecture description + +#### Installation + +1. xxxx +2. xxxx +3. xxxx + +#### Instructions + +1. xxxx +2. xxxx +3. xxxx + +#### Contribution + +1. Fork the repository +2. Create Feat_xxx branch +3. Commit your code +4. Create Pull Request + + +#### Gitee Feature + +1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md +2. Gitee blog [blog.gitee.com](https://blog.gitee.com) +3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore) +4. The most valuable open source project [GVP](https://gitee.com/gvp) +5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help) +6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/) diff --git a/ets2panda/linter/homecheck/README.md b/ets2panda/linter/homecheck/README.md new file mode 100644 index 0000000000..63099bd3a4 --- /dev/null +++ b/ets2panda/linter/homecheck/README.md @@ -0,0 +1,201 @@ +# homecheck + +## 项目简介 + +该项目(homecheck)专为提升代码质量而设计,能高效识别代码缺陷并提出方案;其核心功能是对应用工程项目执行静态代码分析,评估代码在安全性、性能等方面上的表现,精准定位问题及其在代码中的位置。 + +## 目录 + +``` +homecheck +├─config/ # 项目配置 +├─document/ # 项目文档 +├─resources/ # 依赖库 +├─src/ +│ ├─checker/ # 项目检测规则功能代码 +│ ├─codeFix/ # 修复 +│ ├─matcher/ # 匹配类型 +│ ├─model/ # 模块 +│ ├─utils/ # 公共接口 +│ └─run.ts # 项目入口 +└─test/ # 测试目录 +``` + +## 项目主体流程 + +1.读取配置文件projectConfig.json和ruleConfig.json + +2.使用**ArkAnalyzer**项目构建**sence** + +3.根据配置文件参数,获取需要检测的文件 + +4.前处理 + +5.进行检测 + +6.后处理 + +## QuickStart + +### 1.下载本项目 + +### 2.进入项目根目录,打开终端 + +``` +cmd +``` + +### 3.安装依赖库 + +``` +npm install +``` + +### 4.修改配置 + +**config\projectConfig.json**中修改项目配置 +示例: + +``` +{ + "projectName": "TestProject", + "projectPath": "/path/to/project", + "logPath": "./HomeCheck.log", + "ohosSdkPath": "/path/to/ohosSdk", + "hmsSdkPath": "/path/to/hmsSdk", + "checkPath": "", + "sdkVersion": 14, + "fix": "true", + "npmPath": "", + "sdksThirdParty": [ + { + "name": "thirdParty", + "path": "./resources/thirdPartyModules", + "moduleName": "" + } + ] +} +``` +字段说明: +``` +projectName:需要检测工程的名字 +projectPath:需要检测工程的路径 +logPath:日志输出路径 +ohosSdkPath:ohossdk路径,比如DevEco Studio安装目录下的sdk\default\openharmony\ets +hmsSdkPath:hmssdk路径,比如DevEco Studio安装目录下的sdk\default\hms\ets +checkPath:解析指定的文件 +sdkVersion:sdk版本 +fix:是否修复 +npmPath:自定义规则npm路径 +sdksThirdParty:sdk三方库,name:库名称,path:库路径,moduleName:模块名称 +``` + +**config\ruleConfig.json**中修改规则配置 +示例: + +``` +{ + "files": [ + "**/*.ets", + "**/*.ts" + ], + "ignore": [ + "**/ohosTest/**/*", + "**/node_modules/**/*", + "**/build/**/*", + "**/hvigorfile/**/*", + "**/oh_modules/**/*", + "**/.preview/**/*" + ], + "rules": { + "@performance/foreach-args-check":3 + }, + "ruleSet": [ + "plugin:@performance/all", + "plugin:@correctness/all" + ], + "overrides": [], + "extRuleSet": [] +} +``` + +字段说明: + +``` +files:待检测文件类型 +ignore:过滤文件 +rules:可以基于ruleSet配置的规则集,新增额外规则项 +ruleSet:规则集 +overrides:定制化检查的规则 +extRuleSet:自定义规则 +``` +extRuleSet:自定义规则,参考[自定义规则](#自定义规则) + +### 5.启动项目 + +注意修改projectConfig.json和ruleConfig.json文件路径 + +#### 5.1 命令行启动,示例: + +根目录下执行 +``` +node -r ts-node/register ./src/run.ts --projectConfigPath=./config/projectConfig.json --configPath=./config/ruleConfig.json +``` + +#### 5.2 vscode启动: + +根目录新建.vscode目录,并新建launch.json文件,内容参考.vscode_sample\launch.json + +点击左侧运行和调试按钮,点击启动程序,开始运行,运行结束查看HomeCheck.log +#### 5.3 webstorm启动: + +## 新增规则 + +### 自定义规则 +参考:[自定义规则开发指南](document/ExtRule自定义规则开发指南.md) + +### 检测规则 +参考:[新增检测规则开发指南](document/规则开发指南.md) + +## api +参考:[api说明](doc/globals.md) + +## 打包 + +根目录下执行命令: + +``` +npm pack +``` +产物,根目录下: + +homecheck-1.0.0.tgz + +## 安装与使用 + +参考:[homecheck安装与使用指南](document/homecheck安装与使用指南.md) + +## HomeCheck附带工具使用指南 + +参考:[HomeCheck附带工具使用指南](document/HomeCheck附带工具使用指南.md) + +### 日志 + +运行结果请查看根目录下的HomeCheck.log + +## 代码上库 +遵守openharmony-sig代码上库规范, 操作方法请参考:[创建pr指南](document/PR指南.md) + +## Issues +提交Issues请参考:[Issues指南](document/Issues指南.md)。 + +## 添加自验证测试用例 +自验证用例请参考:[单元测试用例开发指南](document/单元测试用例开发指南.md) + +## 相关仓 + +[ArkAnalyzer](https://gitcode.com/openharmony-sig/arkanalyzer) + +## 欢迎加入homecheck社区开发讨论 + +![homecheck社区开发讨论](document/img/homecheck社区开发讨论.JPG) \ No newline at end of file diff --git a/ets2panda/linter/homecheck/config/projectConfig.json b/ets2panda/linter/homecheck/config/projectConfig.json index 55aac136da..2bfa7d765f 100644 --- a/ets2panda/linter/homecheck/config/projectConfig.json +++ b/ets2panda/linter/homecheck/config/projectConfig.json @@ -19,5 +19,7 @@ "moduleName": "" } ], - "fileOrFolderToCheck": [ "D:\\arkProject" ] + "fileOrFolderToCheck": [ "D:\\arkProject" ], + "logLevel": "INFO", + "arkAnalyzerLogLevel": "ERROR" } \ No newline at end of file diff --git a/ets2panda/linter/homecheck/config/ruleConfig.json b/ets2panda/linter/homecheck/config/ruleConfig.json index 141445e713..3f724aeebf 100644 --- a/ets2panda/linter/homecheck/config/ruleConfig.json +++ b/ets2panda/linter/homecheck/config/ruleConfig.json @@ -1,7 +1,8 @@ { "files": [ "**/*.ets", - "**/*.ts" + "**/*.ts", + "**/*.js" ], "ignore": [ "**/ohosTest/**/*", diff --git a/ets2panda/linter/homecheck/package.json b/ets2panda/linter/homecheck/package.json index 0a5b274695..ae47a9e950 100644 --- a/ets2panda/linter/homecheck/package.json +++ b/ets2panda/linter/homecheck/package.json @@ -7,15 +7,11 @@ "pack": "npm pack" }, "dependencies": { - "commander": "11.0.0", - "fs-extra": "11.2.0" - }, - "devDependencies": { - "@types/fs-extra": "9.0.13", - "ts-node": "10.9.1", - "typedoc": "^0.25.13", - "vite-tsconfig-paths": "4.3.1", - "vitest": "1.5.1" + "arkanalyzer": "file:../arkanalyzer", + "commander": "^9.4.0", + "fs-extra": "11.2.0", + "log4js": "^6.4.0", + "json5": "2.2.3" }, "name": "homecheck", "version": "0.9.11-arkts1.2", diff --git a/ets2panda/linter/homecheck/resources/internalSdk/@internal/es5.d.ts b/ets2panda/linter/homecheck/resources/internalSdk/@internal/es5.d.ts deleted file mode 100644 index 5972cfdced..0000000000 --- a/ets2panda/linter/homecheck/resources/internalSdk/@internal/es5.d.ts +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the 'License'); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an 'AS IS' BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -interface ObjectConstructor { - new (value?: any): Object; - (): any; - (value: any): any; - - readonly prototype: Object; - - getPrototypeOf(o: any): any; - - getOwnPropertyDescriptor(o: any, p: PropertyKey): PropertyDescriptor | undefined; - - getOwnPropertyNames(o: any): string[]; - - create(o: object | null): any; - - create(o: object | null, properties: PropertyDescriptorMap & ThisType): any; - - defineProperty(o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType): T; - - defineProperties(o: T, properties: PropertyDescriptorMap & ThisType): T; - - seal(o: T): T; - - freeze(f: T): T; - - freeze(o: T): Readonly; - - freeze(o: T): Readonly; - - preventExtensions(o: T): T; - - isSealed(o: any): boolean; - - isFrozen(o: any): boolean; - - isExtensible(o: any): boolean; - - keys(o: object): string[]; -} - -declare var Object: ObjectConstructor; \ No newline at end of file diff --git a/ets2panda/linter/homecheck/resources/thirdPartyModules/@hview/moment/index.d.ts b/ets2panda/linter/homecheck/resources/thirdPartyModules/@hview/moment/index.d.ts index 8e41abd4a3..d5cac4b311 100644 --- a/ets2panda/linter/homecheck/resources/thirdPartyModules/@hview/moment/index.d.ts +++ b/ets2panda/linter/homecheck/resources/thirdPartyModules/@hview/moment/index.d.ts @@ -20,6 +20,6 @@ export default function moment(): moment.Moment; declare namespace moment { interface Moment extends Object { utcOffset(): number; - utcOffset(b: number|string, keepLocalTime?: boolean): Moment; + utcOffset(b: number | string, keepLocalTime?: boolean): Moment; } } \ No newline at end of file diff --git a/ets2panda/linter/homecheck/ruleSet.json b/ets2panda/linter/homecheck/ruleSet.json index 197cfacae1..adfc2898b5 100644 --- a/ets2panda/linter/homecheck/ruleSet.json +++ b/ets2panda/linter/homecheck/ruleSet.json @@ -198,10 +198,16 @@ "plugin:@migration/all": { "@migration/arkts-obj-literal-generate-class-instance": 1, "@migration/arkts-instance-method-bind-this": 1, - "@migration/arkui-data-observation-2": 1, + "@migration/arkts-no-ts-like-as": 1, + "@migration/arkui-data-observation": 1, "@migration/arkui-stateful-appstorage": 1, - "@migration/arkui-no-update-in-rending": 1, - "@migration/arkui-custombuiler": 1, - "@migration/no-method-overriding-field-check": 1 + "@migration/arkui-no-update-in-build": 1, + "@migration/arkui-custombuilder-passing": 1, + "@migration/no-method-overriding-field-check": 1, + "@migration/interop-backward-dfa": 1, + "@migration/interop-dynamic-object-literals": 1, + "@migration/interop-assign": 1, + "@migration/interop-boxed-type-check": 1, + "@migration/interop-js-modify-property": 1 } -} \ No newline at end of file +} diff --git a/ets2panda/linter/homecheck/src/Index.ts b/ets2panda/linter/homecheck/src/Index.ts index f2ca91bcba..6ad78b6bfe 100644 --- a/ets2panda/linter/homecheck/src/Index.ts +++ b/ets2panda/linter/homecheck/src/Index.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -25,7 +25,8 @@ export * from './matcher/Matchers'; // models export { CheckerStorage } from './utils/common/CheckerStorage'; export { Rule } from './model/Rule'; -export { Defects, IssueReport, FileReports } from './model/Defects'; +export { Defects, IssueReport, FileIssues, FileReports } from './model/Defects'; +export { RuleFix } from './model/Fix'; export { Message, MessageType } from './model/Message'; export { ProjectConfig } from './model/ProjectConfig'; export { RuleConfig } from './model/RuleConfig'; @@ -42,4 +43,3 @@ export { Utils } from './utils/common/Utils'; // tools export { runTool, Tools } from './tools/toolEntry'; export { MigrationTool } from './tools/migrationTool/MigrationTool'; -export { ProblemInfo, AutoFix } from './tools/migrationTool/ExportIssue'; \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/Main.ts b/ets2panda/linter/homecheck/src/Main.ts index b706c8e150..0cd340554d 100644 --- a/ets2panda/linter/homecheck/src/Main.ts +++ b/ets2panda/linter/homecheck/src/Main.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,21 +12,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import Logger, { LOG_MODULE_TYPE } from "arkanalyzer/lib/utils/logger"; -import { processAfterCheck } from "./utils/common/AfterCheck"; -import { CheckEntry, checkEntryBuilder, getSelectFileList } from "./utils/common/CheckEntry"; -import { ConfigUtils } from "./utils/common/ConfigUtils"; -import { defaultMessage } from "./model/Message"; -import { Utils } from "./utils/common/Utils"; +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; +import { processAfterCheck } from './utils/common/AfterCheck'; +import { CheckEntry, checkEntryBuilder, getSelectFileList } from './utils/common/CheckEntry'; +import { ConfigUtils } from './utils/common/ConfigUtils'; +import { DefaultMessage } from './model/Message'; +import { Utils } from './utils/common/Utils'; const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'Main'); export async function start(checkEntry: CheckEntry): Promise { // 外部没有建立消息通道,使用默认通道 if (!checkEntry.message) { - checkEntry.message = new defaultMessage(); + checkEntry.message = new DefaultMessage(); } - + // 前处理 if (!await checkEntryBuilder(checkEntry)) { return false; diff --git a/ets2panda/linter/homecheck/src/checker/BaseChecker.ts b/ets2panda/linter/homecheck/src/checker/BaseChecker.ts index 930c88f5c7..fb7d337523 100644 --- a/ets2panda/linter/homecheck/src/checker/BaseChecker.ts +++ b/ets2panda/linter/homecheck/src/checker/BaseChecker.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,10 +13,10 @@ * limitations under the License. */ -import { ArkFile } from "arkanalyzer"; -import { Rule } from "../model/Rule"; -import { MatcherCallback } from "../matcher/Matchers"; -import { IssueReport } from "../model/Defects"; +import { ArkFile } from 'arkanalyzer'; +import { Rule } from '../model/Rule'; +import { MatcherCallback } from '../matcher/Matchers'; +import { IssueReport } from '../model/Defects'; export interface BaseMetaData { severity: number, diff --git a/ets2panda/linter/homecheck/src/checker/migration/AppStorageGetCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/AppStorageGetCheck.ts index 91186ddc1a..693f891412 100644 --- a/ets2panda/linter/homecheck/src/checker/migration/AppStorageGetCheck.ts +++ b/ets2panda/linter/homecheck/src/checker/migration/AppStorageGetCheck.ts @@ -13,41 +13,32 @@ * limitations under the License. */ -import { ArkInstanceInvokeExpr, ArkMethod, ArkStaticInvokeExpr, CallGraph, CallGraphBuilder, Stmt, Value } from 'arkanalyzer/lib'; +import { + ArkInstanceInvokeExpr, + ArkMethod, + ArkStaticInvokeExpr, + CallGraph, + CallGraphBuilder, + Stmt, + Value, +} from 'arkanalyzer/lib'; import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; import { BaseChecker, BaseMetaData } from '../BaseChecker'; import { Rule, Defects, ClassMatcher, MethodMatcher, MatcherTypes, MatcherCallback } from '../../Index'; import { IssueReport } from '../../model/Defects'; +import { CALL_DEPTH_LIMIT, CALLBACK_METHOD_NAME, CallGraphHelper } from './Utils'; +import { WarnInfo } from '../../utils/common/Utils'; const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'AppStorageGetCheck'); const gMetaData: BaseMetaData = { severity: 1, ruleDocPath: '', - description: 'Get State of AppStorage in component build function, it will update UI interface when the state of AppStorage is changed.' + description: + 'Get State of AppStorage in component build function, it will update UI interface when the state of AppStorage is changed', }; -const APP_STORAGE_STR = "AppStorage"; -const API_SET: Set = new Set(['Has', 'has', 'Get', 'get', - 'Keys', 'keys', 'IsMutable', 'Size', 'size']); - -const CALLBACK_METHOD_NAME: string[] = [ - "onClick", // 点击事件,当用户点击组件时触发 - "onTouch", // 触摸事件,当手指在组件上按下、滑动、抬起时触发 - "onAppear", // 组件挂载显示时触发 - "onDisAppear", // 组件卸载消失时触发 - "onDragStart", // 拖拽开始事件,当组件被长按后开始拖拽时触发 - "onDragEnter", // 拖拽进入组件范围时触发 - "onDragMove", // 拖拽在组件范围内移动时触发 - "onDragLeave", // 拖拽离开组件范围内时触发 - "onDrop", // 拖拽释放目标,当在本组件范围内停止拖拽行为时触发 - "onKeyEvent", // 按键事件,当组件获焦后,按键动作触发 - "onFocus", // 焦点事件,当组件获取焦点时触发 - "onBlur", // 当组件失去焦点时触发的回调 - "onHover", // 鼠标悬浮事件,鼠标进入或退出组件时触发 - "onMouse", // 鼠标事件,当鼠标按键点击或在组件上移动时触发 - "onAreaChange", // 组件区域变化事件,组件尺寸、位置变化时触发 - "onVisibleAreaChange", // 组件可见区域变化事件,组件在屏幕中的显示区域面积变化时触发 -]; +const APP_STORAGE_STR = 'AppStorage'; +const API_SET: Set = new Set(['has', 'get', 'keys', 'size']); export class AppStorageGetCheck implements BaseChecker { readonly metaData: BaseMetaData = gMetaData; @@ -63,36 +54,40 @@ export class AppStorageGetCheck implements BaseChecker { private buildMatcher: MethodMatcher = { matcherType: MatcherTypes.METHOD, class: [this.classMatcher], - name: ["build"] + name: ['build'], }; public registerMatchers(): MatcherCallback[] { const matchBuildCb: MatcherCallback = { matcher: this.buildMatcher, - callback: this.check + callback: this.check, }; return [matchBuildCb]; } - public check = (targetMtd: ArkMethod) => { + public check = (targetMtd: ArkMethod): void => { const scene = targetMtd.getDeclaringArkFile().getScene(); - let callGraph = new CallGraph(scene); + let callGraph = CallGraphHelper.getCGInstance(scene); let callGraphBuilder = new CallGraphBuilder(callGraph, scene); - callGraphBuilder.buildClassHierarchyCallGraph([targetMtd.getSignature()], true); + callGraphBuilder.buildClassHierarchyCallGraph([targetMtd.getSignature()]); this.checkMethod(targetMtd, callGraph); - } + }; - private checkMethod(targetMtd: ArkMethod, cg: CallGraph, depth: number = 0) { - if (depth > 2) { + private checkMethod(targetMtd: ArkMethod, cg: CallGraph, depth: number = 0): void { + if (depth > CALL_DEPTH_LIMIT) { return; } const stmts = targetMtd.getBody()?.getCfg().getStmts() ?? []; for (const stmt of stmts) { - this.checkAppStorageGet(stmt) + this.checkAppStorageGet(stmt); const invokeExpr = stmt.getInvokeExpr(); if (invokeExpr && invokeExpr instanceof ArkInstanceInvokeExpr) { - if (CALLBACK_METHOD_NAME.includes(invokeExpr.getMethodSignature().getMethodSubSignature().getMethodName())) { + if ( + CALLBACK_METHOD_NAME.includes( + invokeExpr.getMethodSignature().getMethodSubSignature().getMethodName() + ) + ) { continue; } } @@ -102,11 +97,11 @@ export class AppStorageGetCheck implements BaseChecker { if (callee) { this.checkMethod(callee, cg, depth + 1); } - }) + }); } } - private checkAppStorageGet(stmt: Stmt) { + private checkAppStorageGet(stmt: Stmt): void { let invokeExpr = stmt.getInvokeExpr(); if (!(invokeExpr instanceof ArkStaticInvokeExpr)) { return; @@ -121,15 +116,29 @@ export class AppStorageGetCheck implements BaseChecker { this.addIssueReport(stmt, invokeExpr); } - private addIssueReport(stmt: Stmt, operand: Value) { + private addIssueReport(stmt: Stmt, operand: Value): void { const severity = this.rule.alert ?? this.metaData.severity; const warnInfo = this.getLineAndColumn(stmt, operand); - let defects = new Defects(warnInfo.line, warnInfo.startCol, warnInfo.endCol, this.metaData.description, severity, this.rule.ruleId, - warnInfo.filePath, this.metaData.ruleDocPath, true, false, false); + const problem = 'AppStorageSpecChanged'; + const desc = `${this.metaData.description} (${this.rule.ruleId.replace('@migration/', '')})`; + let defects = new Defects( + warnInfo.line, + warnInfo.startCol, + warnInfo.endCol, + problem, + desc, + severity, + this.rule.ruleId, + warnInfo.filePath, + this.metaData.ruleDocPath, + true, + false, + false + ); this.issues.push(new IssueReport(defects, undefined)); } - private getLineAndColumn(stmt: Stmt, operand: Value) { + private getLineAndColumn(stmt: Stmt, operand: Value): WarnInfo { const arkFile = stmt.getCfg()?.getDeclaringMethod().getDeclaringArkFile(); const originPosition = stmt.getOperandOriginalPosition(operand); if (arkFile && originPosition) { @@ -143,4 +152,4 @@ export class AppStorageGetCheck implements BaseChecker { } return { line: -1, startCol: -1, endCol: -1, filePath: '' }; } -} \ No newline at end of file +} diff --git a/ets2panda/linter/homecheck/src/checker/migration/CustomBuilderCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/CustomBuilderCheck.ts index f022bc63c8..b8dcb06db7 100644 --- a/ets2panda/linter/homecheck/src/checker/migration/CustomBuilderCheck.ts +++ b/ets2panda/linter/homecheck/src/checker/migration/CustomBuilderCheck.ts @@ -13,17 +13,37 @@ * limitations under the License. */ -import { ArkAssignStmt, Scene, Local, Stmt, Type, ArkMethod, AliasType, AbstractInvokeExpr, Value } from "arkanalyzer"; +import { + ArkAssignStmt, + Scene, + Local, + Stmt, + Type, + ArkMethod, + AliasType, + AbstractInvokeExpr, + Value, + ArkFile, + AstTreeUtils, + ts, + FunctionType, + ArkClass, + ANONYMOUS_METHOD_PREFIX, + ArkInvokeStmt, +} from 'arkanalyzer'; import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; -import { BaseChecker, BaseMetaData } from "../BaseChecker"; -import { Rule, Defects, MatcherTypes, MatcherCallback, MethodMatcher } from "../../Index"; -import { IssueReport } from "../../model/Defects"; +import { BaseChecker, BaseMetaData } from '../BaseChecker'; +import { Rule, Defects, MatcherTypes, MatcherCallback, MethodMatcher } from '../../Index'; +import { IssueReport } from '../../model/Defects'; +import { FixInfo, RuleFix } from '../../model/Fix'; +import { FixPosition, FixUtils } from '../../utils/common/FixUtils'; +import { WarnInfo } from '../../utils/common/Utils'; const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'CustomBuilderCheck'); const gMetaData: BaseMetaData = { severity: 1, - ruleDocPath: "", - description: 'The CustomBuilder type parameter only accepts functions annotated with @Builder.' + ruleDocPath: '', + description: 'The CustomBuilder type parameter only accepts functions annotated with @Builder', }; export class CustomBuilderCheck implements BaseChecker { @@ -33,13 +53,13 @@ export class CustomBuilderCheck implements BaseChecker { public issues: IssueReport[] = []; private buildMatcher: MethodMatcher = { - matcherType: MatcherTypes.METHOD + matcherType: MatcherTypes.METHOD, }; public registerMatchers(): MatcherCallback[] { const matchBuildCb: MatcherCallback = { matcher: this.buildMatcher, - callback: this.check + callback: this.check, }; return [matchBuildCb]; } @@ -49,6 +69,7 @@ export class CustomBuilderCheck implements BaseChecker { const stmts = target.getBody()?.getCfg().getStmts() ?? []; let locals = new Set(); for (const stmt of stmts) { + // 场景1:函数调用赋值给CustomBuilder类型的对象 const local = this.isCallToBuilder(stmt, scene); if (local) { locals.add(local); @@ -58,9 +79,52 @@ export class CustomBuilderCheck implements BaseChecker { if (usage) { this.addIssueReport(usage.getDeclaringStmt()!, usage); } + + // 场景2:函数调用包在箭头函数中赋值给CustomBuilder类型的对象 + if (stmt instanceof ArkAssignStmt) { + const arrowMethod = this.findPotentialArrowFunction(stmt, target.getDeclaringArkClass()); + if (arrowMethod !== null && this.isCallToBuilderWrapWithArrow(arrowMethod)) { + this.addIssueReport(stmt, stmt.getRightOp()); + } + } } }; + // 只有当赋值语句leftOp为CustomBuilder类型时,若rightOp是匿名箭头函数,则返回该箭头函数 + private findPotentialArrowFunction(stmt: Stmt, arkClass: ArkClass): ArkMethod | null { + if (!(stmt instanceof ArkAssignStmt) || !this.isCustomBuilderTy(stmt.getLeftOp().getType())) { + return null; + } + + const rightOpType = stmt.getRightOp().getType(); + if (!(rightOpType instanceof FunctionType)) { + return null; + } + + const methodName = rightOpType.getMethodSignature().getMethodSubSignature().getMethodName(); + const method = arkClass.getMethodWithName(methodName); + if (method === null || !method.isAnonymousMethod()) { + return null; + } + return method; + } + + private isCallToBuilderWrapWithArrow(arrowMethod: ArkMethod): boolean { + const scene = arrowMethod.getDeclaringArkFile().getScene(); + const stmts = arrowMethod.getBody()?.getCfg().getStmts() ?? []; + for (const stmt of stmts) { + if (!(stmt instanceof ArkInvokeStmt)) { + continue; + } + const invokeExpr = stmt.getInvokeExpr(); + const method = scene.getMethod(invokeExpr.getMethodSignature()); + if (method && method.hasBuilderDecorator()) { + return true; + } + } + return false; + } + private isCallToBuilder(stmt: Stmt, scene: Scene): Local | undefined { if (!(stmt instanceof ArkAssignStmt)) { return undefined; @@ -80,13 +144,13 @@ export class CustomBuilderCheck implements BaseChecker { return undefined; } - private isCumtomBuilderTy(ty: Type) { + private isCustomBuilderTy(ty: Type): boolean { return ty instanceof AliasType && ty.getName() === 'CustomBuilder'; } private isPassToCustomBuilder(stmt: Stmt, locals: Set): Local | undefined { if (stmt instanceof ArkAssignStmt) { - if (!this.isCumtomBuilderTy(stmt.getLeftOp().getType())) { + if (!this.isCustomBuilderTy(stmt.getLeftOp().getType())) { return undefined; } const rightOp = stmt.getRightOp(); @@ -99,7 +163,7 @@ export class CustomBuilderCheck implements BaseChecker { const paramTys = invokeExpr.getMethodSignature().getMethodSubSignature().getParameterTypes(); const args = invokeExpr.getArgs(); for (let i = 0; i < paramTys.length && i < args.length; ++i) { - if (!this.isCumtomBuilderTy(paramTys[i])) { + if (!this.isCustomBuilderTy(paramTys[i])) { continue; } const arg = args[i]; @@ -111,15 +175,39 @@ export class CustomBuilderCheck implements BaseChecker { return undefined; } - private addIssueReport(stmt: Stmt, operand: Value) { + private addIssueReport(stmt: Stmt, operand: Value): void { const severity = this.rule.alert ?? this.metaData.severity; const warnInfo = this.getLineAndColumn(stmt, operand); - let defects = new Defects(warnInfo.line, warnInfo.startCol, warnInfo.endCol, this.metaData.description, severity, this.rule.ruleId, - warnInfo.filePath, this.metaData.ruleDocPath, true, false, false); - this.issues.push(new IssueReport(defects, undefined)); + const problem = 'CustomBuilderTypeChanged'; + const desc = `${this.metaData.description} (${this.rule.ruleId.replace('@migration/', '')})`; + let defects = new Defects( + warnInfo.line, + warnInfo.startCol, + warnInfo.endCol, + problem, + desc, + severity, + this.rule.ruleId, + warnInfo.filePath, + this.metaData.ruleDocPath, + true, + false, + true + ); + const fixPosition: FixPosition = { + startLine: warnInfo.line, + startCol: warnInfo.startCol, + endLine: -1, + endCol: -1, + }; + const ruleFix = this.generateRuleFix(fixPosition, stmt) ?? undefined; + this.issues.push(new IssueReport(defects, ruleFix)); + if (ruleFix === undefined) { + defects.fixable = false; + } } - private getLineAndColumn(stmt: Stmt, operand: Value) { + private getLineAndColumn(stmt: Stmt, operand: Value): WarnInfo { const arkFile = stmt.getCfg()?.getDeclaringMethod().getDeclaringArkFile(); const originPosition = stmt.getOperandOriginalPosition(operand); if (arkFile && originPosition) { @@ -133,4 +221,65 @@ export class CustomBuilderCheck implements BaseChecker { } return { line: -1, startCol: -1, endCol: -1, filePath: '' }; } -} \ No newline at end of file + + private generateRuleFix(fixPosition: FixPosition, stmt: Stmt): RuleFix | null { + let ruleFix: RuleFix = new RuleFix(); + const endPosition = this.getEndPositionOfStmt(stmt); + if (endPosition) { + fixPosition.endLine = endPosition.line; + fixPosition.endCol = endPosition.col; + } + const arkFile = stmt.getCfg()?.getDeclaringMethod().getDeclaringArkFile(); + const sourceFile = AstTreeUtils.getASTNode(arkFile.getName(), arkFile.getCode()); + const range = FixUtils.getRangeWithAst(sourceFile, fixPosition); + ruleFix.range = range; + const originalText = FixUtils.getSourceWithRange(sourceFile, range); + if (originalText !== null) { + ruleFix.text = this.generateReplaceText(sourceFile, originalText, fixPosition); + } else { + return null; + } + return ruleFix; + } + + private getEndPositionOfStmt(stmt: Stmt): { line: number; col: number } | null { + const allPositions = stmt.getOperandOriginalPositions(); + if (allPositions === undefined) { + return null; + } + let res = { line: -1, col: -1 }; + allPositions.forEach(position => { + if (position.getLastLine() > res.line) { + res = { line: position.getLastLine(), col: position.getLastCol() }; + return; + } + if (position.getLastLine() === res.line && position.getLastCol() > res.col) { + res = { line: position.getLastLine(), col: position.getLastCol() }; + return; + } + }); + return res; + } + + private generateReplaceText(sourceFile: ts.SourceFile, originalText: string, fixPosition: FixPosition): string { + // 已经是箭头函数的场景,无需任何处理 + if (originalText.includes('=>')) { + return originalText; + } + + // 非箭头函数包裹的函数调用,需要使用箭头函数包裹 + const eol = FixUtils.getEolSymbol(sourceFile, fixPosition.startLine); + const startLineIndent = FixUtils.getIndentOfLine(sourceFile, fixPosition.startLine) ?? 0; + const increaseSpaces = FixUtils.getIndentWidth(sourceFile, fixPosition.startLine); + const space = ' '; + + let res = `() => {${eol}`; + const originalLineStrs = originalText.split(eol); + res += `${space.repeat(startLineIndent + increaseSpaces)}${originalLineStrs[0]}${eol}`; + for (let index = 1; index < originalLineStrs.length; index++) { + res += `${space.repeat(increaseSpaces)}${originalLineStrs[index]}${eol}`; + } + res += `${space.repeat(startLineIndent)}}`; + return res; + } +} diff --git a/ets2panda/linter/homecheck/src/checker/migration/InteropAssignCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/InteropAssignCheck.ts new file mode 100644 index 0000000000..e1645a7e6a --- /dev/null +++ b/ets2panda/linter/homecheck/src/checker/migration/InteropAssignCheck.ts @@ -0,0 +1,293 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + Type, + ArkMethod, + ArkAssignStmt, + FieldSignature, + Stmt, + Scene, + Value, + CallGraph, + ArkParameterRef, + ArkInstanceFieldRef, + FunctionType, + ClassType, + ArkNamespace, +} from 'arkanalyzer/lib'; +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; +import { BaseChecker, BaseMetaData } from '../BaseChecker'; +import { Rule, Defects, MatcherCallback } from '../../Index'; +import { IssueReport } from '../../model/Defects'; +import { DVFGNode } from 'arkanalyzer/lib/VFG/DVFG'; +import { CALL_DEPTH_LIMIT, DVFGHelper, GlobalCallGraphHelper } from './Utils'; +import { Language } from 'arkanalyzer/lib/core/model/ArkFile'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'InteropAssignCheck'); +const gMetaData: BaseMetaData = { + severity: 1, + ruleDocPath: '', + description: 'Should not pass or assign a dynamic object to a variable of static type', +}; + +const RULE_ID = 'arkts-interop-s2d-dynamic-args-to-static'; + +export class InteropAssignCheck implements BaseChecker { + readonly metaData: BaseMetaData = gMetaData; + public rule: Rule; + public defects: Defects[] = []; + public issues: IssueReport[] = []; + private cg: CallGraph; + + public registerMatchers(): MatcherCallback[] { + const matchBuildCb: MatcherCallback = { + matcher: undefined, + callback: this.check, + }; + return [matchBuildCb]; + } + + public check = (scene: Scene): void => { + this.cg = GlobalCallGraphHelper.getCGInstance(scene); + + for (let arkFile of scene.getFiles()) { + for (let clazz of arkFile.getClasses()) { + for (let mtd of clazz.getMethods()) { + this.processArkMethod(mtd, scene); + } + } + for (let namespace of arkFile.getAllNamespacesUnderThisFile()) { + this.processNameSpace(namespace, scene); + } + } + }; + + public processNameSpace(namespace: ArkNamespace, scene: Scene): void { + for (let clazz of namespace.getClasses()) { + for (let mtd of clazz.getMethods()) { + this.processArkMethod(mtd, scene); + } + } + } + + public processArkMethod(target: ArkMethod, scene: Scene): void { + if (target.getLanguage() === Language.ARKTS1_2) { + this.checkPassToFunction(target, scene); + } else if (target.getLanguage() === Language.ARKTS1_1) { + this.checkAssignToField(target, scene); + } + } + + private checkPassToFunction(target: ArkMethod, scene: Scene) { + const callsites = this.cg.getInvokeStmtByMethod(target.getSignature()); + callsites.forEach(cs => { + let hasTargetArg = false; + const invoke = cs.getInvokeExpr()!; + const csMethod = cs.getCfg()?.getDeclaringMethod(); + invoke.getArgs().forEach(arg => { + const argTy = arg.getType(); + const argTyLang = this.getTypeDefinedLang(argTy, scene) ?? csMethod?.getLanguage() ?? Language.UNKNOWN; + if (argTyLang === Language.ARKTS1_1) { + hasTargetArg = true; + } + }); + if (!hasTargetArg) { + return; + } + let line = cs.getOriginPositionInfo().getLineNo(); + let column = cs.getOriginPositionInfo().getColNo(); + const problem = 'Interop'; + const desc = `${this.metaData.description} (${RULE_ID})`; + const severity = this.metaData.severity; + const ruleId = this.rule.ruleId; + const filePath = csMethod?.getDeclaringArkFile()?.getFilePath() ?? ''; + const defeats = new Defects( + line, + column, + column, + problem, + desc, + severity, + ruleId, + filePath, + '', + true, + false, + false + ); + this.issues.push(new IssueReport(defeats, undefined)); + }); + } + + private checkAssignToField(target: ArkMethod, scene: Scene) { + const assigns: Stmt[] = this.collectAssignToObjectField(target, scene); + assigns.forEach(assign => { + let result: Stmt[] = []; + let visited: Set = new Set(); + this.checkFromStmt(assign, scene, result, visited); + if (result.length === 0) { + // 这句 a.data = y 右侧的值没有从 1.1 传入的可能 + return; + } + let line = assign.getOriginPositionInfo().getLineNo(); + let column = assign.getOriginPositionInfo().getColNo(); + const problem = 'Interop'; + const desc = `${this.metaData.description} (${RULE_ID})`; + const severity = this.metaData.severity; + const ruleId = this.rule.ruleId; + const filePath = assign.getCfg()?.getDeclaringMethod().getDeclaringArkFile()?.getFilePath() ?? ''; + const defeats = new Defects( + line, + column, + column, + problem, + desc, + severity, + ruleId, + filePath, + '', + true, + false, + false + ); + this.issues.push(new IssueReport(defeats, undefined)); + }); + } + + private collectAssignToObjectField(method: ArkMethod, scene: Scene): Stmt[] { + const res: Stmt[] = []; + const stmts = method.getBody()?.getCfg().getStmts() ?? []; + for (const stmt of stmts) { + if (!(stmt instanceof ArkAssignStmt)) { + continue; + } + const leftOp = stmt.getLeftOp(); + if (!(leftOp instanceof ArkInstanceFieldRef)) { + continue; + } + if (!this.isObjectTy(leftOp.getType())) { + continue; + } + const baseTy = leftOp.getBase().getType(); + if (baseTy instanceof ClassType) { + const klass = scene.getClass(baseTy.getClassSignature()); + if (!klass) { + logger.warn( + `check field of type 'Object' failed: cannot find arkclass by sig ${baseTy + .getClassSignature() + .toString()}` + ); + } else if (klass.getLanguage() === Language.ARKTS1_2) { + res.push(stmt); + } + } else { + logger.warn(`check field of type 'Object' failed: unexpected base type ${baseTy.toString()}`); + } + } + return res; + } + + private checkFromStmt(stmt: Stmt, scene: Scene, res: Stmt[], visited: Set, depth: number = 0): void { + if (depth > CALL_DEPTH_LIMIT) { + return; + } + const node = DVFGHelper.getOrNewDVFGNode(stmt, scene); + let worklist: DVFGNode[] = [node]; + while (worklist.length > 0) { + const current = worklist.shift()!; + const currentStmt = current.getStmt(); + if (visited.has(currentStmt)) { + continue; + } + visited.add(currentStmt); + if (currentStmt instanceof ArkAssignStmt) { + const rightOpTy = currentStmt.getRightOp().getType(); + if (!this.isObjectTy(rightOpTy) && this.getTypeDefinedLang(rightOpTy, scene) === Language.ARKTS1_1) { + res.push(currentStmt); + continue; + } + } + const callsite = this.cg.getCallSiteByStmt(currentStmt); + callsite.forEach(cs => { + const declaringMtd = this.cg.getArkMethodByFuncID(cs.calleeFuncID); + if (!declaringMtd || !declaringMtd.getCfg()) { + return; + } + DVFGHelper.buildSingleDVFG(declaringMtd, scene); + declaringMtd.getReturnStmt().forEach(r => this.checkFromStmt(r, scene, res, visited, depth + 1)); + }); + const paramRef = this.isFromParameter(currentStmt); + if (paramRef) { + const paramIdx = paramRef.getIndex(); + const callsites = this.cg.getInvokeStmtByMethod( + currentStmt.getCfg().getDeclaringMethod().getSignature() + ); + callsites.forEach(cs => { + const declaringMtd = cs.getCfg().getDeclaringMethod(); + DVFGHelper.buildSingleDVFG(declaringMtd, scene); + }); + this.collectArgDefs(paramIdx, callsites, scene).forEach(d => + this.checkFromStmt(d, scene, res, visited, depth + 1) + ); + } + current.getIncomingEdge().forEach(e => worklist.push(e.getSrcNode() as DVFGNode)); + } + } + + private isFromParameter(stmt: Stmt): ArkParameterRef | undefined { + if (!(stmt instanceof ArkAssignStmt)) { + return undefined; + } + const rightOp = stmt.getRightOp(); + if (rightOp instanceof ArkParameterRef) { + return rightOp; + } + return undefined; + } + + private collectArgDefs(argIdx: number, callsites: Stmt[], scene: Scene): Stmt[] { + const getKey = (v: Value): Value | FieldSignature => { + return v instanceof ArkInstanceFieldRef ? v.getFieldSignature() : v; + }; + return callsites.flatMap(callsite => { + const target: Value | FieldSignature = getKey(callsite.getInvokeExpr()!.getArg(argIdx)); + return Array.from(DVFGHelper.getOrNewDVFGNode(callsite, scene).getIncomingEdge()) + .map(e => (e.getSrcNode() as DVFGNode).getStmt()) + .filter(s => { + return s instanceof ArkAssignStmt && target === getKey(s.getLeftOp()); + }); + }); + } + + private isObjectTy(ty: Type): boolean { + return ty instanceof ClassType && ty.getClassSignature().getClassName() === 'Object'; + } + + private getTypeDefinedLang(type: Type, scene: Scene): Language | undefined { + let file = undefined; + if (type instanceof ClassType) { + file = scene.getFile(type.getClassSignature().getDeclaringFileSignature()); + } else if (type instanceof FunctionType) { + file = scene.getFile(type.getMethodSignature().getDeclaringClassSignature().getDeclaringFileSignature()); + } + if (file) { + return file.getLanguage(); + } else { + logger.error(`fail to identify which file the type definition ${type.toString()} is in.`); + } + return undefined; + } +} diff --git a/ets2panda/linter/homecheck/src/checker/migration/InteropBackwardDFACheck.ts b/ets2panda/linter/homecheck/src/checker/migration/InteropBackwardDFACheck.ts new file mode 100644 index 0000000000..d80cc3aeb5 --- /dev/null +++ b/ets2panda/linter/homecheck/src/checker/migration/InteropBackwardDFACheck.ts @@ -0,0 +1,458 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + Type, + ArkMethod, + ArkAssignStmt, + FieldSignature, + Stmt, + Scene, + Value, + CallGraph, + ArkParameterRef, + ArkInstanceFieldRef, + ArkInstanceInvokeExpr, + AnyType, + ClassType, + ArkStaticInvokeExpr, + AbstractInvokeExpr, + FunctionType, + UnknownType, + Local, + ArkClass, +} from 'arkanalyzer/lib'; +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; +import { BaseChecker, BaseMetaData } from '../BaseChecker'; +import { Rule, Defects, MatcherCallback } from '../../Index'; +import { IssueReport } from '../../model/Defects'; +import { DVFGNode } from 'arkanalyzer/lib/VFG/DVFG'; +import { CALL_DEPTH_LIMIT, GlobalCallGraphHelper, DVFGHelper } from './Utils'; +import { findInteropRule } from './InteropRuleInfo'; +import { ArkFile, Language } from 'arkanalyzer/lib/core/model/ArkFile'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'InteropBackwardDFACheck'); +const gMetaData: BaseMetaData = { + severity: 1, + ruleDocPath: '', + description: '', +}; + +const REFLECT_API: Map = new Map([ + ['apply', 0], + ['construct', 0], + ['defineProperty', 0], + ['deleteProperty', 0], + ['get', 0], + ['getOwnPropertyDescriptor', 0], + ['getPrototypeOf', 0], + ['has', 0], + ['isExtensible', 0], + ['ownKeys', 0], + ['preventExtensions', 0], + ['set', 0], + ['setPrototypeOf', 0], +]); + +const OBJECT_API: Map = new Map([ + ['getOwnPropertyDescriptor', 0], + ['getOwnPropertyDescriptors', 0], + ['getOwnPropertyNames', 0], + ['isExtensible', 0], + ['isFrozen', 0], + ['isSealed', 0], + ['keys', 0], + ['setPrototypeOf', 0], + ['values', 0], + ['assign', 1], + ['entries', 0], +]); + +class ObjDefInfo { + problemStmt: Stmt; + objLanguage: Language; +} + +export class InteropBackwardDFACheck implements BaseChecker { + readonly metaData: BaseMetaData = gMetaData; + public rule: Rule; + public defects: Defects[] = []; + public issues: IssueReport[] = []; + private cg: CallGraph; + + public registerMatchers(): MatcherCallback[] { + const matchBuildCb: MatcherCallback = { + matcher: undefined, + callback: this.check, + }; + return [matchBuildCb]; + } + + public check = (scene: Scene): void => { + this.cg = GlobalCallGraphHelper.getCGInstance(scene); + + for (let arkFile of scene.getFiles()) { + const importVarMap: Map = new Map(); + this.collectImportedVar(importVarMap, arkFile, scene); + const topLevelVarMap: Map = new Map(); + this.collectTopLevelVar(topLevelVarMap, arkFile, scene); + + const handleClass = (cls: ArkClass): void => { + cls.getMethods().forEach(m => this.processArkMethod(m, scene, importVarMap, topLevelVarMap)); + }; + + arkFile.getClasses().forEach(cls => handleClass(cls)); + arkFile.getAllNamespacesUnderThisFile().forEach(n => n.getClasses().forEach(cls => handleClass(cls))); + } + }; + + private collectImportedVar(importVarMap: Map, file: ArkFile, scene: Scene) { + file.getImportInfos().forEach(importInfo => { + const exportInfo = importInfo.getLazyExportInfo(); + if (exportInfo === null) { + return; + } + const arkExport = exportInfo.getArkExport(); + if (!arkExport || !(arkExport instanceof Local)) { + return; + } + const declaringStmt = arkExport.getDeclaringStmt(); + if (!declaringStmt) { + return; + } + const definedLang = this.getTypeDefinedLang(arkExport.getType(), scene) ?? file.getLanguage(); + importVarMap.set(arkExport.getName(), definedLang); + }); + } + + private collectTopLevelVar(topLevelVarMap: Map, file: ArkFile, scene: Scene) { + const defaultMethod = file.getDefaultClass().getDefaultArkMethod(); + if (defaultMethod) { + DVFGHelper.buildSingleDVFG(defaultMethod, scene); + const stmts = defaultMethod.getBody()?.getCfg().getStmts() ?? []; + for (const stmt of stmts) { + if (!(stmt instanceof ArkAssignStmt)) { + continue; + } + const leftOp = stmt.getLeftOp(); + if (!(leftOp instanceof Local)) { + continue; + } + const name = leftOp.getName(); + if (name.startsWith('%') || name === 'this') { + continue; + } + topLevelVarMap.set(name, [...(topLevelVarMap.get(name) ?? []), stmt]); + } + } + } + + private processArkMethod( + target: ArkMethod, + scene: Scene, + importVarMap: Map, + topLevelVarMap: Map + ): void { + const currentLang = target.getLanguage(); + if (currentLang === Language.UNKNOWN) { + logger.warn(`cannot find the language for method: ${target.getSignature()}`); + return; + } + const stmts = target.getBody()?.getCfg().getStmts() ?? []; + for (const stmt of stmts) { + const invoke = stmt.getInvokeExpr(); + let isReflect = false; + let paramIdx = -1; + if (invoke && invoke instanceof ArkInstanceInvokeExpr) { + if (invoke.getBase().getName() === 'Reflect') { + isReflect = true; + paramIdx = + REFLECT_API.get(invoke.getMethodSignature().getMethodSubSignature().getMethodName()) ?? -1; + } + } + if (invoke && invoke instanceof ArkStaticInvokeExpr) { + const methodSig = invoke.getMethodSignature(); + const classSig = methodSig.getDeclaringClassSignature(); + if (classSig.getClassName() === 'ObjectConstructor' || classSig.getClassName() === 'Object') { + paramIdx = + OBJECT_API.get(invoke.getMethodSignature().getMethodSubSignature().getMethodName()) ?? -1; + } + } + if (paramIdx === -1) { + continue; + } + DVFGHelper.buildSingleDVFG(target, scene); + + const argDefs = this.findArgumentDef(stmt, paramIdx, currentLang, importVarMap, topLevelVarMap, scene); + if (this.isLanguage(argDefs)) { + this.reportIssue({ problemStmt: stmt, objLanguage: argDefs as Language }, currentLang, isReflect); + } else { + argDefs.forEach(def => { + let result: ObjDefInfo[] = []; + let visited: Set = new Set(); + this.checkFromStmt(def, currentLang, result, visited, importVarMap, topLevelVarMap, scene); + result.forEach(objDefInfo => { + this.reportIssue(objDefInfo, currentLang, isReflect); + }); + }); + } + } + } + + private reportIssue(objDefInfo: ObjDefInfo, apiLang: Language, isReflect: boolean) { + const problemStmt = objDefInfo.problemStmt; + const problemStmtMtd = problemStmt.getCfg()?.getDeclaringMethod(); + const problemStmtLang = problemStmtMtd?.getLanguage(); + const objLanguage = objDefInfo.objLanguage; + if (objLanguage === Language.UNKNOWN || problemStmtLang === Language.UNKNOWN) { + logger.warn(`cannot find the language for def: ${problemStmt.toString()}`); + return; + } + const interopRule = findInteropRule(apiLang, objLanguage, problemStmtLang, isReflect); + if (!interopRule) { + return; + } + const line = problemStmt.getOriginPositionInfo().getLineNo(); + const column = problemStmt.getOriginPositionInfo().getColNo(); + const problem = 'Interop'; + const desc = `${interopRule.description} (${interopRule.ruleId})`; + const severity = interopRule.severity; + const ruleId = this.rule.ruleId; + const filePath = problemStmtMtd?.getDeclaringArkFile()?.getFilePath() ?? ''; + const defeats = new Defects( + line, + column, + column, + problem, + desc, + severity, + ruleId, + filePath, + '', + true, + false, + false + ); + this.issues.push(new IssueReport(defeats, undefined)); + } + + private checkFromStmt( + stmt: Stmt, + apiLanguage: Language, + res: ObjDefInfo[], + visited: Set, + importVarMap: Map, + topLevelVarMap: Map, + scene: Scene, + depth: number = 0 + ): void { + if (depth > CALL_DEPTH_LIMIT) { + return; + } + const node = DVFGHelper.getOrNewDVFGNode(stmt, scene); + let worklist: DVFGNode[] = [node]; + while (worklist.length > 0) { + const current = worklist.shift()!; + const currentStmt = current.getStmt(); + if (visited.has(currentStmt)) { + continue; + } + visited.add(currentStmt); + if (currentStmt instanceof ArkAssignStmt) { + const rightOp = currentStmt.getRightOp(); + if (rightOp instanceof ArkInstanceFieldRef) { + // 处理 Reflect.apply(obj.getName, {a : 12}) + const base = rightOp.getBase(); + if (base instanceof Local && base.getDeclaringStmt()) { + worklist.push(DVFGHelper.getOrNewDVFGNode(base.getDeclaringStmt()!, scene)); + continue; + } + } + if (rightOp instanceof Local && !rightOp.getDeclaringStmt()) { + const name = rightOp.getName(); + if (importVarMap.has(name)) { + res.push({ problemStmt: currentStmt, objLanguage: importVarMap.get(name)! }); + continue; + } + } + const rightOpTy = rightOp.getType(); + if (!this.isIrrelevantType(rightOpTy)) { + const rightOpTyLang = this.getTypeDefinedLang(rightOpTy, scene); + if (rightOpTyLang && rightOpTyLang !== apiLanguage) { + res.push({ problemStmt: currentStmt, objLanguage: rightOpTyLang }); + continue; + } + } + } + const callsite = this.cg.getCallSiteByStmt(currentStmt); + if (callsite.length > 0) { + callsite.forEach(cs => { + const declaringMtd = this.cg.getArkMethodByFuncID(cs.calleeFuncID); + if (!declaringMtd || !declaringMtd.getCfg()) { + return; + } + DVFGHelper.buildSingleDVFG(declaringMtd, scene); + declaringMtd + .getReturnStmt() + .forEach(r => + this.checkFromStmt( + r, + apiLanguage, + res, + visited, + importVarMap, + topLevelVarMap, + scene, + depth + 1 + ) + ); + }); + continue; + } + const paramRef = this.isFromParameter(currentStmt); + if (paramRef) { + const paramIdx = paramRef.getIndex(); + this.cg.getInvokeStmtByMethod(currentStmt.getCfg().getDeclaringMethod().getSignature()).forEach(cs => { + const declaringMtd = cs.getCfg().getDeclaringMethod(); + DVFGHelper.buildSingleDVFG(declaringMtd, scene); + const argDefs = this.findArgumentDef( + cs, + paramIdx, + apiLanguage, + importVarMap, + topLevelVarMap, + scene + ); + if (this.isLanguage(argDefs)) { + // imported var + res.push({ problemStmt: cs, objLanguage: argDefs as Language }); + } else { + argDefs.forEach(d => { + this.checkFromStmt( + d, + apiLanguage, + res, + visited, + importVarMap, + topLevelVarMap, + scene, + depth + 1 + ); + }); + } + }); + continue; + } + current.getIncomingEdge().forEach(e => worklist.push(e.getSrcNode() as DVFGNode)); + if (stmt instanceof ArkAssignStmt) { + const rightOp = stmt.getRightOp(); + if (rightOp instanceof Local && !rightOp.getDeclaringStmt()) { + (topLevelVarMap.get(rightOp.getName()) ?? []).forEach(def => { + worklist.push(DVFGHelper.getOrNewDVFGNode(def, scene)); + }); + } + } + } + } + + private isIrrelevantType(ty: Type): boolean { + const isObjectTy = (ty: Type): boolean => { + return ty instanceof ClassType && ty.getClassSignature().getClassName() === 'Object'; + }; + const isESObjectTy = (ty: Type): boolean => { + return ty.toString() === 'ESObject'; + }; + const isAnyTy = (ty: Type): ty is AnyType => { + return ty instanceof AnyType; + }; + const isUnkwonTy = (ty: Type): ty is UnknownType => { + return ty instanceof UnknownType; + }; + return isObjectTy(ty) || isESObjectTy(ty) || isAnyTy(ty) || isUnkwonTy(ty); + } + + private isFromParameter(stmt: Stmt): ArkParameterRef | undefined { + if (!(stmt instanceof ArkAssignStmt)) { + return undefined; + } + const rightOp = stmt.getRightOp(); + if (rightOp instanceof ArkParameterRef) { + return rightOp; + } + return undefined; + } + + private isLanguage(value: Stmt[] | Language): value is Language { + return Object.values(Language).includes(value as Language); + } + + private findArgumentDef( + stmt: Stmt, + argIdx: number, + apiLanguage: Language, + importVarMap: Map, + topLevelVarMap: Map, + scene: Scene + ): Stmt[] | Language { + const invoke = stmt.getInvokeExpr(); + const getKey = (v: Value): Value | FieldSignature => { + return v instanceof ArkInstanceFieldRef ? v.getFieldSignature() : v; + }; + const arg: Value | FieldSignature = getKey((invoke as AbstractInvokeExpr).getArg(argIdx)); + if (!arg) { + logger.error(`arg${argIdx} of invoke ${stmt.toString()} is undefined`); + return []; + } + if (arg instanceof Local && arg.getDeclaringStmt() instanceof ArkAssignStmt) { + // 特殊处理,obj.getName 的类型有 bug + const rightOp = (arg.getDeclaringStmt() as ArkAssignStmt).getRightOp(); + if (rightOp instanceof ArkInstanceFieldRef) { + const base = rightOp.getBase(); + if (base instanceof Local && base.getDeclaringStmt()) { + return [base.getDeclaringStmt()!]; + } + } + } + const argTy = arg.getType(); + if (!this.isIrrelevantType(argTy)) { + const argTyLang = this.getTypeDefinedLang(argTy, scene); + if (argTyLang && argTyLang !== apiLanguage) { + return argTyLang; + } + } + if (arg instanceof Local && !arg.getDeclaringStmt()) { + const name = arg.getName(); + return topLevelVarMap.get(name) ?? importVarMap.get(name) ?? []; + } + return Array.from(DVFGHelper.getOrNewDVFGNode(stmt, scene).getIncomingEdge()) + .map(e => (e.getSrcNode() as DVFGNode).getStmt()) + .filter(s => { + return s instanceof ArkAssignStmt && arg === getKey(s.getLeftOp()); + }); + } + + private getTypeDefinedLang(type: Type, scene: Scene): Language | undefined { + let file = undefined; + if (type instanceof ClassType) { + file = scene.getFile(type.getClassSignature().getDeclaringFileSignature()); + } else if (type instanceof FunctionType) { + file = scene.getFile(type.getMethodSignature().getDeclaringClassSignature().getDeclaringFileSignature()); + } + if (file) { + return file.getLanguage(); + } + return undefined; + } +} diff --git a/ets2panda/linter/homecheck/src/checker/migration/InteropBoxedTypeCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/InteropBoxedTypeCheck.ts new file mode 100644 index 0000000000..42b4dc0973 --- /dev/null +++ b/ets2panda/linter/homecheck/src/checker/migration/InteropBoxedTypeCheck.ts @@ -0,0 +1,450 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { BaseChecker, BaseMetaData } from '../BaseChecker'; +import { Rule } from '../../model/Rule'; +import { Defects, IssueReport } from '../../model/Defects'; +import { FileMatcher, MatcherCallback, MatcherTypes } from '../../matcher/Matchers'; +import { + AbstractInvokeExpr, + ArkAssignStmt, + ArkClass, + ArkFile, + ArkMethod, + ArkNamespace, + ArkNewExpr, + ClassType, + FunctionType, + ImportInfo, + Local, + LOG_MODULE_TYPE, + Logger, + Scene, + Stmt, + Type, +} from 'arkanalyzer'; +import { ExportType } from 'arkanalyzer/lib/core/model/ArkExport'; +import { WarnInfo } from '../../utils/common/Utils'; +import { Language } from 'arkanalyzer/lib/core/model/ArkFile'; +import { getLanguageStr } from './Utils'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'ObservedDecoratorCheck'); +const gMetaData: BaseMetaData = { + severity: 1, + ruleDocPath: '', + description: '', +}; + +const ruleId: string = '@migration/interop-boxed-type-check'; +const s2dRuleId: string = 'arkts-interop-s2d-boxed-type'; +const d2sRuleId: string = 'arkts-interop-d2s-boxed-type'; +const ts2sRuleId: string = 'arkts-interop-ts2s-boxed-type'; +const js2RuleId: string = 'arkts-interop-js2s-boxed-type'; + +const BOXED_SET: Set = new Set(['String', 'Boolean', 'Number']); + +type CheckedObj = { + namespaces: Map; + classes: Map; + methods: Map; +}; + +export class InteropBoxedTypeCheck implements BaseChecker { + readonly metaData: BaseMetaData = gMetaData; + public rule: Rule; + public defects: Defects[] = []; + public issues: IssueReport[] = []; + + private fileMatcher: FileMatcher = { + matcherType: MatcherTypes.FILE, + }; + + public registerMatchers(): MatcherCallback[] { + const fileMatcher: MatcherCallback = { + matcher: this.fileMatcher, + callback: this.check, + }; + return [fileMatcher]; + } + + public check = (arkFile: ArkFile): void => { + let hasChecked: CheckedObj = { + namespaces: new Map(), + classes: new Map(), + methods: new Map(), + }; + const scene = arkFile.getScene(); + // Import对象对应的Export信息的推导在类型推导过程中是懒加载机制,调用getLazyExportInfo接口会自动进行推导 + arkFile.getImportInfos().forEach(importInfo => { + const exportInfo = importInfo.getLazyExportInfo(); + // TODO: import * from xxx是如何表示的? + if (exportInfo === null) { + // 导入内置库时为null + return; + } + const arkExport = exportInfo.getArkExport(); + if (arkExport === null || arkExport === undefined) { + // 按正常流程,上面的exportInfo不为null时,这里一定会将实际找到的export对象set为arkExport,所以这里应该走不到 + // import三方包时为null,未推导为undefined,推导后无结果为null + return; + } + + const exportType = arkExport.getExportType(); + // 如果import的是sdk,exportType可能是namespace等,但是找不到body体等详细赋值语句等内容,所以不影响如下的判断 + switch (exportType) { + case ExportType.NAME_SPACE: + this.findBoxedTypeInNamespace(importInfo, arkExport as ArkNamespace, scene, hasChecked); + return; + case ExportType.CLASS: + this.findBoxedTypeInClass(importInfo, arkExport as ArkClass, scene, hasChecked); + return; + case ExportType.METHOD: + this.findBoxedTypeWithMethodReturn(importInfo, arkExport as ArkMethod, scene, hasChecked); + return; + case ExportType.LOCAL: + this.findBoxedTypeWithLocal(importInfo, arkExport as Local, scene, hasChecked); + return; + default: + return; + } + }); + }; + + private findBoxedTypeInNamespace( + importInfo: ImportInfo, + arkNamespace: ArkNamespace, + scene: Scene, + hasChecked: CheckedObj + ): boolean | null { + // 判断namespace是否已查找过,避免陷入死循环 + const existing = hasChecked.namespaces.get(arkNamespace.getSignature().toString()); + if (existing !== undefined) { + return existing; + } + hasChecked.namespaces.set(arkNamespace.getSignature().toString(), null); + const exports = arkNamespace.getExportInfos(); + let found: boolean | null = null; + for (const exportInfo of exports) { + const arkExport = exportInfo.getArkExport(); + if (arkExport === undefined) { + continue; + } + + if (arkExport === null) { + // ArkAnalyzer此处有一个问题,无法区分export local是来自arkfile还是arknamespace,导致类型推导推出来是null + continue; + } + if (arkExport instanceof Local) { + found = this.findBoxedTypeWithLocal(importInfo, arkExport, scene, hasChecked); + } else if (arkExport instanceof ArkMethod) { + found = this.findBoxedTypeWithMethodReturn(importInfo, arkExport, scene, hasChecked); + } else if (arkExport instanceof ArkClass) { + found = this.findBoxedTypeInClass(importInfo, arkExport, scene, hasChecked); + } else if (arkExport instanceof ArkNamespace) { + found = this.findBoxedTypeInNamespace(importInfo, arkExport, scene, hasChecked); + } + if (found) { + hasChecked.namespaces.set(arkNamespace.getSignature().toString(), true); + return true; + } + } + hasChecked.namespaces.set(arkNamespace.getSignature().toString(), false); + return false; + } + + private isClassHasBoxedType(arkClass: ArkClass, scene: Scene, hasChecked: CheckedObj): boolean | null { + // step0: 判断class是否已查找过,避免陷入死循环 + const existing = hasChecked.classes.get(arkClass.getSignature().toString()); + if (existing !== undefined) { + return existing; + } + hasChecked.classes.set(arkClass.getSignature().toString(), null); + // step1: 查找class中的所有field,包含static和非static,判断initialized stmts中是否会用boxed类型对象给field赋值 + const allFields = arkClass.getFields(); + for (const field of allFields) { + // 此处不检查field signature中的Type,因为type直接写String时也表示成Class Type,无法区分是否为new String()生成的 + const initializer = field.getInitializer(); + if (initializer.length < 1) { + continue; + } + const lastStmt = initializer[initializer.length - 1]; + if (!(lastStmt instanceof ArkAssignStmt)) { + continue; + } + if (this.isValueAssignedByBoxed(lastStmt, initializer.slice(0, -1).reverse(), scene, hasChecked)) { + // 这里没有顺着field的定义语句中使用到的import对象去寻找原始的Boxed类型定义所在的文件的Language,而是直接使用field所在的语言 + // 应该也是ok的,因为上述import chain如何不合法,也会有告警在其import的地方给出 + hasChecked.classes.set(arkClass.getSignature().toString(), true); + return true; + } + } + + // step2: 查找class中的所有非generated method,判断所有的return操作符类型是否为boxed + const methods = arkClass.getMethods(); + for (const method of methods) { + const found = this.isMethodReturnHasBoxedType(method, scene, hasChecked); + if (found) { + hasChecked.classes.set(arkClass.getSignature().toString(), true); + return true; + } + } + hasChecked.classes.set(arkClass.getSignature().toString(), false); + return false; + } + + private isMethodReturnHasBoxedType(arkMethod: ArkMethod, scene: Scene, hasChecked: CheckedObj): boolean | null { + // 判断method是否已查找过,避免陷入死循环 + const existing = hasChecked.methods.get(arkMethod.getSignature().toString()); + if (existing !== undefined) { + return existing; + } + hasChecked.methods.set(arkMethod.getSignature().toString(), null); + const returnOps = arkMethod.getReturnValues(); + for (const op of returnOps) { + if (this.isBoxedType(op.getType())) { + hasChecked.methods.set(arkMethod.getSignature().toString(), true); + return true; + } + if (op instanceof Local && this.isLocalHasBoxedType(op, scene, hasChecked)) { + hasChecked.methods.set(arkMethod.getSignature().toString(), true); + return true; + } + } + hasChecked.methods.set(arkMethod.getSignature().toString(), false); + return false; + } + + // 此处不检查local的Type,因为type直接写String时也表示成Class Type,无法区分是否为new String()生成的 + private isLocalHasBoxedType(local: Local, scene: Scene, hasChecked: CheckedObj): boolean { + const method = local.getDeclaringStmt()?.getCfg().getDeclaringMethod(); + if (method === undefined) { + return false; + } + const stmts = method.getCfg()?.getStmts().reverse(); + if (stmts === undefined || stmts.length < 1) { + return false; + } + + const declaringStmt = local.getDeclaringStmt(); + if ( + declaringStmt !== null && + declaringStmt instanceof ArkAssignStmt && + this.isValueAssignedByBoxed(declaringStmt, stmts, scene, hasChecked) + ) { + return true; + } + for (const stmt of local.getUsedStmts()) { + if (stmt instanceof ArkAssignStmt) { + const leftOp = stmt.getLeftOp(); + if ( + leftOp instanceof Local && + leftOp.toString() === local.toString() && + this.isValueAssignedByBoxed(stmt, stmts, scene, hasChecked) + ) { + return true; + } + } + } + return false; + } + + private findBoxedTypeInClass( + importInfo: ImportInfo, + arkClass: ArkClass, + scene: Scene, + hasChecked: CheckedObj + ): boolean { + const importOpPosition = importInfo.getOriginTsPosition(); + const warnInfo: WarnInfo = { + line: importOpPosition.getLineNo(), + startCol: importOpPosition.getColNo(), + endCol: importOpPosition.getColNo(), + filePath: importInfo.getDeclaringArkFile().getFilePath(), + }; + const currLanguage = importInfo.getLanguage(); + const result = this.isClassHasBoxedType(arkClass, scene, hasChecked); + if (result) { + this.addIssueReport(warnInfo, currLanguage, arkClass.getLanguage()); + return true; + } + return false; + } + + private findBoxedTypeWithMethodReturn( + importInfo: ImportInfo, + arkMethod: ArkMethod, + scene: Scene, + hasChecked: CheckedObj + ): boolean { + const importOpPostion = importInfo.getOriginTsPosition(); + const warnInfo: WarnInfo = { + line: importOpPostion.getLineNo(), + startCol: importOpPostion.getColNo(), + endCol: importOpPostion.getColNo(), + filePath: importInfo.getDeclaringArkFile().getFilePath(), + }; + const currLanguage = importInfo.getLanguage(); + + // 此处不检查method signature中的return Type,因为return type直接写String时也表示成Class Type,无法区分是否为new String()生成的 + if (this.isMethodReturnHasBoxedType(arkMethod, scene, hasChecked)) { + this.addIssueReport(warnInfo, currLanguage, arkMethod.getLanguage()); + return true; + } + return false; + } + + private findBoxedTypeWithLocal( + importInfo: ImportInfo, + local: Local, + scene: Scene, + hasChecked: CheckedObj + ): boolean { + const importOpPosition = importInfo.getOriginTsPosition(); + const warnInfo: WarnInfo = { + line: importOpPosition.getLineNo(), + startCol: importOpPosition.getColNo(), + endCol: importOpPosition.getColNo(), + filePath: importInfo.getDeclaringArkFile().getFilePath(), + }; + const currLanguage = importInfo.getLanguage(); + const method = local.getDeclaringStmt()?.getCfg().getDeclaringMethod(); + if (method === undefined) { + return false; + } + if (this.isLocalHasBoxedType(local, scene, hasChecked)) { + this.addIssueReport(warnInfo, currLanguage, method.getLanguage()); + return true; + } + return false; + } + + private isBoxedType(checkType: Type): boolean { + // ArkAnalyzer表示new String()形式的类型为ClassType,Class Name为String、Boolean、Number + // TODO: 此处底座有一个bug,表示String()时推导为Unknown Type,正确的应该为string,但是不影响本规则的判断 + return checkType instanceof ClassType && BOXED_SET.has(checkType.getClassSignature().getClassName()); + } + + private addIssueReport(warnInfo: WarnInfo, currLanguage: Language, targetLanguage: Language): void { + const interopRule = this.getInteropRule(currLanguage, targetLanguage); + if (interopRule === null) { + return; + } + const severity = this.metaData.severity; + const currLanStr = getLanguageStr(currLanguage); + const targetLanStr = getLanguageStr(targetLanguage); + const problem = 'Interop'; + const describe = `Could not import object with boxed type from ${targetLanStr} to ${currLanStr} (${interopRule})`; + let defects = new Defects( + warnInfo.line, + warnInfo.startCol, + warnInfo.endCol, + problem, + describe, + severity, + ruleId, + warnInfo.filePath, + this.metaData.ruleDocPath, + true, + false, + false + ); + this.issues.push(new IssueReport(defects, undefined)); + } + + private getInteropRule(currLanguage: Language, targetLanguage: Language): string | null { + if (currLanguage === Language.ARKTS1_1) { + if (targetLanguage === Language.ARKTS1_2) { + return s2dRuleId; + } + } else if (currLanguage === Language.ARKTS1_2) { + if (targetLanguage === Language.TYPESCRIPT) { + return ts2sRuleId; + } + if (targetLanguage === Language.ARKTS1_1) { + return d2sRuleId; + } + if (targetLanguage === Language.JAVASCRIPT) { + return js2RuleId; + } + } + return null; + } + + // lastStmt为当前需要查找的对象的赋值语句,左值为查找对象,右值为往前继续查找的赋值起点 + // reverseStmtChain为以待查找对象为起点,所有一系列赋值语句的倒序排列 + private isValueAssignedByBoxed( + lastStmt: ArkAssignStmt, + previousReverseChain: Stmt[], + scene: Scene, + hasChecked: CheckedObj + ): boolean { + let locals: Set = new Set(); + const targetLocal = lastStmt.getRightOp(); + const targetLocalType = targetLocal.getType(); + if (this.isBoxedType(targetLocalType)) { + return true; + } + if (targetLocalType instanceof ClassType) { + const arkClass = scene.getClass(targetLocalType.getClassSignature()); + if (arkClass !== null && this.isClassHasBoxedType(arkClass, scene, hasChecked)) { + return true; + } + } + if (targetLocalType instanceof FunctionType) { + const arkMethod = scene.getMethod(targetLocalType.getMethodSignature()); + if (arkMethod !== null && this.isMethodReturnHasBoxedType(arkMethod, scene, hasChecked)) { + return true; + } + } + + if (!(targetLocal instanceof Local)) { + return false; + } + locals.add(targetLocal); + + const rightOp = lastStmt.getRightOp(); + if (!(rightOp instanceof Local)) { + return false; + } + locals.add(rightOp); + for (const stmt of previousReverseChain) { + if (!(stmt instanceof ArkAssignStmt)) { + continue; + } + const leftOp = stmt.getLeftOp(); + const rightOp = stmt.getRightOp(); + if (!(leftOp instanceof Local) || !locals.has(leftOp)) { + continue; + } + if (rightOp instanceof Local) { + locals.add(rightOp); + continue; + } + if (rightOp instanceof ArkNewExpr) { + if (this.isBoxedType(rightOp.getClassType())) { + return true; + } + continue; + } + if (rightOp instanceof AbstractInvokeExpr) { + if (this.isBoxedType(rightOp.getType())) { + return true; + } + continue; + } + } + return false; + } +} diff --git a/ets2panda/linter/homecheck/src/checker/migration/InteropDynamicObjectLiteralsCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/InteropDynamicObjectLiteralsCheck.ts new file mode 100644 index 0000000000..3b59046d94 --- /dev/null +++ b/ets2panda/linter/homecheck/src/checker/migration/InteropDynamicObjectLiteralsCheck.ts @@ -0,0 +1,277 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + ArkMethod, + ArkAssignStmt, + FieldSignature, + Stmt, + Scene, + Value, + DVFGBuilder, + ArkInstanceOfExpr, + ArkNewExpr, + CallGraph, + ArkParameterRef, + ArkInstanceFieldRef, + ClassType, + ArkNamespace, +} from 'arkanalyzer/lib'; +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; +import { BaseChecker, BaseMetaData } from '../BaseChecker'; +import { Rule, Defects, MatcherCallback } from '../../Index'; +import { IssueReport } from '../../model/Defects'; +import { DVFG, DVFGNode } from 'arkanalyzer/lib/VFG/DVFG'; +import { CALL_DEPTH_LIMIT, getLanguageStr, getLineAndColumn, GlobalCallGraphHelper } from './Utils'; +import { ClassCategory } from 'arkanalyzer/lib/core/model/ArkClass'; +import { Language } from 'arkanalyzer/lib/core/model/ArkFile'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'InteropObjectLiteralCheck'); +const gMetaData: BaseMetaData = { + severity: 1, + ruleDocPath: '', + description: '', +}; + +const d2sRuleId: string = 'arkts-interop-d2s-object-literal'; +const ts2sRuleId: string = 'arkts-interop-ts2s-object-literal'; + +export class InteropObjectLiteralCheck implements BaseChecker { + readonly metaData: BaseMetaData = gMetaData; + public rule: Rule; + public defects: Defects[] = []; + public issues: IssueReport[] = []; + private cg: CallGraph; + private dvfg: DVFG; + private dvfgBuilder: DVFGBuilder; + private visited: Set = new Set(); + + public registerMatchers(): MatcherCallback[] { + const matchBuildCb: MatcherCallback = { + matcher: undefined, + callback: this.check, + }; + return [matchBuildCb]; + } + + public check = (scene: Scene): void => { + this.cg = GlobalCallGraphHelper.getCGInstance(scene); + + this.dvfg = new DVFG(this.cg); + this.dvfgBuilder = new DVFGBuilder(this.dvfg, scene); + + for (let arkFile of scene.getFiles()) { + if (arkFile.getLanguage() !== Language.ARKTS1_2) { + continue; + } + for (let clazz of arkFile.getClasses()) { + for (let mtd of clazz.getMethods()) { + this.processArkMethod(mtd, scene); + } + } + for (let namespace of arkFile.getAllNamespacesUnderThisFile()) { + this.processNameSpace(namespace, scene); + } + } + }; + + public processNameSpace(namespace: ArkNamespace, scene: Scene): void { + for (let clazz of namespace.getClasses()) { + for (let mtd of clazz.getMethods()) { + this.processArkMethod(mtd, scene); + } + } + } + + public processArkMethod(target: ArkMethod, scene: Scene): void { + const stmts = target.getBody()?.getCfg().getStmts() ?? []; + for (const stmt of stmts) { + if (!(stmt instanceof ArkAssignStmt)) { + continue; + } + const rightOp = stmt.getRightOp(); + if (!(rightOp instanceof ArkInstanceOfExpr)) { + continue; + } + if (!this.visited.has(target)) { + this.dvfgBuilder.buildForSingleMethod(target); + this.visited.add(target); + } + + let result: Stmt[] = []; + let checkAll = { value: true }; + let visited: Set = new Set(); + this.checkFromStmt(stmt, scene, result, checkAll, visited); + // 对于待检查的instanceof语句,其检查对象存在用字面量赋值的情况,需要判断对象声明时的类型注解的来源,满足interop场景时需在此处告警 + if (result.length > 0) { + const opType = rightOp.getOp().getType(); + if (!(opType instanceof ClassType)) { + continue; + } + const opTypeClass = scene.getClass(opType.getClassSignature()); + if (opTypeClass === null || opTypeClass.getCategory() === ClassCategory.OBJECT) { + continue; + } + if ( + opTypeClass.getLanguage() === Language.TYPESCRIPT || + opTypeClass.getLanguage() === Language.ARKTS1_1 + ) { + this.addIssueReport(stmt, rightOp, result, opTypeClass.getLanguage()); + } + } + } + } + + private checkFromStmt( + stmt: Stmt, + scene: Scene, + res: Stmt[], + checkAll: { value: boolean }, + visited: Set, + depth: number = 0 + ): void { + if (depth > CALL_DEPTH_LIMIT) { + checkAll.value = false; + return; + } + const node = this.dvfg.getOrNewDVFGNode(stmt); + let worklist: DVFGNode[] = [node]; + while (worklist.length > 0) { + const current = worklist.shift()!; + const currentStmt = current.getStmt(); + if (visited.has(currentStmt)) { + continue; + } + visited.add(currentStmt); + if (this.isObjectLiteral(currentStmt, scene)) { + res.push(currentStmt); + continue; + } + const callsite = this.cg.getCallSiteByStmt(currentStmt); + callsite.forEach(cs => { + const declaringMtd = this.cg.getArkMethodByFuncID(cs.calleeFuncID); + if (!declaringMtd || !declaringMtd.getCfg()) { + return; + } + if (!this.visited.has(declaringMtd)) { + this.dvfgBuilder.buildForSingleMethod(declaringMtd); + this.visited.add(declaringMtd); + } + declaringMtd + .getReturnStmt() + .forEach(r => this.checkFromStmt(r, scene, res, checkAll, visited, depth + 1)); + }); + const paramRef = this.isFromParameter(currentStmt); + if (paramRef) { + const paramIdx = paramRef.getIndex(); + const callsites = this.cg.getInvokeStmtByMethod( + currentStmt.getCfg().getDeclaringMethod().getSignature() + ); + this.processCallsites(callsites); + this.collectArgDefs(paramIdx, callsites).forEach(d => + this.checkFromStmt(d, scene, res, checkAll, visited, depth + 1) + ); + } + current.getIncomingEdge().forEach(e => worklist.push(e.getSrcNode() as DVFGNode)); + } + } + + private processCallsites(callsites: Stmt[]): void { + callsites.forEach(cs => { + const declaringMtd = cs.getCfg().getDeclaringMethod(); + if (!this.visited.has(declaringMtd)) { + this.dvfgBuilder.buildForSingleMethod(declaringMtd); + this.visited.add(declaringMtd); + } + }); + } + + private isObjectLiteral(stmt: Stmt, scene: Scene): boolean { + if (!(stmt instanceof ArkAssignStmt)) { + return false; + } + const rightOp = stmt.getRightOp(); + if (!(rightOp instanceof ArkNewExpr)) { + return false; + } + const classSig = rightOp.getClassType().getClassSignature(); + return scene.getClass(classSig)?.getCategory() === ClassCategory.OBJECT; + } + + private isFromParameter(stmt: Stmt): ArkParameterRef | undefined { + if (!(stmt instanceof ArkAssignStmt)) { + return undefined; + } + const rightOp = stmt.getRightOp(); + if (rightOp instanceof ArkParameterRef) { + return rightOp; + } + return undefined; + } + + private collectArgDefs(argIdx: number, callsites: Stmt[]): Stmt[] { + const getKey = (v: Value): Value | FieldSignature => { + return v instanceof ArkInstanceFieldRef ? v.getFieldSignature() : v; + }; + return callsites.flatMap(callsite => { + const target: Value | FieldSignature = getKey(callsite.getInvokeExpr()!.getArg(argIdx)); + return Array.from(this.dvfg.getOrNewDVFGNode(callsite).getIncomingEdge()) + .map(e => (e.getSrcNode() as DVFGNode).getStmt()) + .filter(s => { + return s instanceof ArkAssignStmt && target === getKey(s.getLeftOp()); + }); + }); + } + + private addIssueReport(stmt: Stmt, operand: Value, result: Stmt[], targetLanguage: Language): void { + const interopRuleId = this.getInteropRule(targetLanguage); + if (interopRuleId === null) { + return; + } + const severity = this.metaData.severity; + const warnInfo = getLineAndColumn(stmt, operand); + let targetLan = getLanguageStr(targetLanguage); + + const resPos: number[] = []; + result.forEach(stmt => resPos.push(stmt.getOriginPositionInfo().getLineNo())); + const problem = 'Interop'; + const desc = `instanceof including object literal with class type from ${targetLan} (${interopRuleId})`; + let defects = new Defects( + warnInfo.line, + warnInfo.startCol, + warnInfo.endCol, + problem, + desc, + severity, + this.rule.ruleId, + warnInfo.filePath, + this.metaData.ruleDocPath, + true, + false, + false + ); + this.issues.push(new IssueReport(defects, undefined)); + } + + private getInteropRule(targetLanguage: Language): string | null { + if (targetLanguage === Language.TYPESCRIPT) { + return ts2sRuleId; + } + if (targetLanguage === Language.ARKTS1_1) { + return d2sRuleId; + } + return null; + } +} diff --git a/ets2panda/linter/homecheck/src/checker/migration/InteropJSModifyPropertyCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/InteropJSModifyPropertyCheck.ts new file mode 100644 index 0000000000..3b912361f2 --- /dev/null +++ b/ets2panda/linter/homecheck/src/checker/migration/InteropJSModifyPropertyCheck.ts @@ -0,0 +1,309 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + Type, + ArkMethod, + ArkAssignStmt, + Scene, + ArkInstanceFieldRef, + FunctionType, + ClassType, + MethodSignature, + ArkParameterRef, + Value, + Stmt, + ArkDeleteExpr, + FieldSignature, + ArkNamespace, +} from 'arkanalyzer/lib'; +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; +import { BaseChecker, BaseMetaData } from '../BaseChecker'; +import { Rule, Defects, MatcherCallback } from '../../Index'; +import { IssueReport } from '../../model/Defects'; +import { ArkFile, Language } from 'arkanalyzer/lib/core/model/ArkFile'; +import { CALL_DEPTH_LIMIT, DVFGHelper } from './Utils'; +import { DVFGNode } from 'arkanalyzer/lib/VFG/DVFG'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'InteropJSModifyPropertyCheck'); +const gMetaData: BaseMetaData = { + severity: 1, + ruleDocPath: '', + description: 'The layout of staic objects should not be modified', +}; + +const RULE_ID = 'arkts-interop-js2s-js-add-detele-static-prop'; + +class ParamInfo { + flag: boolean; + paramAssign: ArkAssignStmt; + callsites: Set; +} + +export class InteropJSModifyPropertyCheck implements BaseChecker { + readonly metaData: BaseMetaData = gMetaData; + public rule: Rule; + public defects: Defects[] = []; + public issues: IssueReport[] = []; + + public registerMatchers(): MatcherCallback[] { + const matchBuildCb: MatcherCallback = { + matcher: undefined, + callback: this.check, + }; + return [matchBuildCb]; + } + + public check = (scene: Scene): void => { + const targetMethods: Map = new Map(); + this.collectTargetMethods(targetMethods, scene); + this.checkTargetMethods(targetMethods, scene); + }; + + private collectTargetMethods(targetMethods: Map, scene: Scene): void { + scene.getFiles().forEach(file => { + // 只处理 ArkTS1.2 import JS 函数的情况 + if (file.getLanguage() !== Language.ARKTS1_2) { + return; + } + file.getImportInfos().forEach(importInfo => { + const exportInfo = importInfo.getLazyExportInfo(); + if (exportInfo === null) { + return; + } + const arkExport = exportInfo.getArkExport(); + if (arkExport === null || arkExport === undefined) { + return; + } + if (!(arkExport instanceof ArkMethod && arkExport.getLanguage() === Language.JAVASCRIPT)) { + return; + } + // 创建初始化的参数标志位信息(标志位代表该参数是否被传入了 1.2 对象,默认为 false) + const paramInfo = this.createParamInfo(arkExport); + if (paramInfo.length > 0) { + targetMethods.set(arkExport.getSignature(), paramInfo); + } + }); + + // 寻找 JS 函数的被调用点,检查是否传入 ArkTS1.2 类型的对象并维护参数标志位信息 + for (let clazz of file.getClasses()) { + for (let mtd of clazz.getMethods()) { + this.findCallsite(mtd, targetMethods, scene); + } + } + for (let namespace of file.getAllNamespacesUnderThisFile()) { + this.processNameSpace(namespace, targetMethods, scene); + } + }); + + // 跨函数检查 ArkTS1.2 类型对象是否被跨函数传到其他 JS 函数 + for (let i = 0; i < CALL_DEPTH_LIMIT; ++i) { + this.collectInterprocedualCallSites(targetMethods, scene); + } + } + + public processNameSpace( + namespace: ArkNamespace, + targetMethods: Map, + scene: Scene + ): void { + for (let clazz of namespace.getClasses()) { + for (let mtd of clazz.getMethods()) { + this.findCallsite(mtd, targetMethods, scene); + } + } + } + + private createParamInfo(method: ArkMethod): ParamInfo[] { + // 初始化参数标志数组 + const idxFlag = new Array(method.getParameters().length).fill(false); + // 寻找参数对应的 xxx = parameter 语句 + const paramAssigns = (method.getCfg()?.getStmts() ?? []) + .filter(s => s instanceof ArkAssignStmt && s.getRightOp() instanceof ArkParameterRef) + .map(s => s as ArkAssignStmt); + if (idxFlag.length !== paramAssigns.length) { + logger.error('param index num != param assign num'); + return []; + } + const result: ParamInfo[] = []; + for (let i = 0; i < idxFlag.length; i++) { + result.push({ flag: idxFlag[i], paramAssign: paramAssigns[i], callsites: new Set() }); + } + return result; + } + + private findCallsite(method: ArkMethod, targets: Map, scene: Scene): void { + const stmts = method.getBody()?.getCfg().getStmts() ?? []; + for (const stmt of stmts) { + const invoke = stmt.getInvokeExpr(); + if (!invoke) { + continue; + } + const methodSig = invoke.getMethodSignature(); + if (!targets.has(methodSig)) { + continue; + } + invoke.getArgs().forEach((arg, idx): void => { + if (this.getTypeDefinedLang(arg.getType(), method.getDeclaringArkFile(), scene) !== Language.ARKTS1_2) { + return; + } + targets.get(methodSig)![idx].flag = true; + targets.get(methodSig)![idx].callsites.add(stmt); + }); + } + } + + private collectInterprocedualCallSites(targets: Map, scene: Scene): void { + new Map(targets).forEach((paramInfo, sig) => { + const method = scene.getMethod(sig)!; + DVFGHelper.buildSingleDVFG(method, scene); + paramInfo.forEach((paramInfo): void => { + if (paramInfo.flag) { + this.checkIfParamPassedToOtherMethod(paramInfo, targets, scene); + } + }); + }); + } + + private checkIfParamPassedToOtherMethod( + callerParamInfo: ParamInfo, + targets: Map, + scene: Scene + ): void { + const worklist: DVFGNode[] = [DVFGHelper.getOrNewDVFGNode(callerParamInfo.paramAssign, scene)]; + const visited: Set = new Set(); + while (worklist.length > 0) { + const current = worklist.shift()!; + const cunrrentStmt = current.getStmt(); + if (visited.has(cunrrentStmt)) { + continue; + } + visited.add(cunrrentStmt); + if (!(cunrrentStmt instanceof ArkAssignStmt)) { + continue; + } + current.getOutgoingEdges().forEach(edge => { + const dst = edge.getDstNode() as DVFGNode; + const dstStmt = dst.getStmt(); + // 假设有 JS 函数声明: function foo(obj),其中 obj 为受关注的参数 + // 只有类似 let obj2 = obj 或者 goo(obj) 这样的语句受到关注 + if (dstStmt instanceof ArkAssignStmt && dstStmt.getRightOp() === cunrrentStmt.getLeftOp()) { + worklist.push(dst); + return; + } + const invoke = dstStmt.getInvokeExpr(); + if (!invoke) { + return; + } + const calleeSig = invoke.getMethodSignature(); + const callee = scene.getMethod(calleeSig); + if (!callee || !callee.getCfg() || callee.getLanguage() !== Language.JAVASCRIPT) { + return; + } + if (!targets.has(calleeSig)) { + targets.set(calleeSig, this.createParamInfo(callee)); + } + const getKey = (v: Value): Value | FieldSignature => { + return v instanceof ArkInstanceFieldRef ? v.getFieldSignature() : v; + }; + invoke.getArgs().forEach((arg, idx) => { + if (getKey(arg) === getKey(cunrrentStmt.getLeftOp())) { + targets.get(calleeSig)![idx].flag = true; + callerParamInfo.callsites.forEach(cs => { + targets.get(calleeSig)![idx].callsites.add(cs); + }); + } + }); + }); + } + } + + private checkTargetMethods(targetMethods: Map, scene: Scene): void { + targetMethods.forEach((paramInfos, methodSig): void => { + const method = scene.getMethod(methodSig); + if (!method) { + logger.error(`cannot find ark method by method sig: ${methodSig.toString()}`); + return; + } + const targetParams = paramInfos + .filter(paramInfo => paramInfo.flag) + .map(paramInfo => paramInfo.paramAssign.getLeftOp()); + const stmts = method.getBody()?.getCfg().getStmts() ?? []; + for (const stmt of stmts) { + if (!(stmt instanceof ArkAssignStmt)) { + continue; + } + let paramIdx = -1; + const rightOp = stmt.getRightOp(); + if (rightOp instanceof ArkDeleteExpr) { + const fieldRef = rightOp.getField(); + if (fieldRef instanceof ArkInstanceFieldRef) { + paramIdx = targetParams.findIndex(p => p === fieldRef.getBase()); + } + } + const leftOp = stmt.getLeftOp(); + if (leftOp instanceof ArkInstanceFieldRef) { + paramIdx = targetParams.findIndex(p => p === leftOp.getBase()); + } + if (paramIdx !== -1) { + const callers = paramInfos[paramIdx]!; + callers.callsites.forEach(cs => this.reportIssue(cs)); + } + } + }); + } + + private getTypeDefinedLang(type: Type, defaultFile: ArkFile, scene: Scene): Language { + let file; + if (type instanceof ClassType) { + file = scene.getFile(type.getClassSignature().getDeclaringFileSignature()); + } else if (type instanceof FunctionType) { + file = scene.getFile(type.getMethodSignature().getDeclaringClassSignature().getDeclaringFileSignature()); + } else { + file = defaultFile; + } + if (file) { + return file.getLanguage(); + } else { + logger.error(`fail to identify which file the type definition ${type.toString()} is in.`); + return Language.UNKNOWN; + } + } + + private reportIssue(problemStmt: Stmt) { + const line = problemStmt.getOriginPositionInfo().getLineNo(); + const column = problemStmt.getOriginPositionInfo().getColNo(); + const problem = 'Interop'; + const desc = `${this.metaData.description} (${RULE_ID})`; + const severity = this.metaData.severity; + const ruleId = this.rule.ruleId; + const filePath = problemStmt.getCfg()?.getDeclaringMethod().getDeclaringArkFile()?.getFilePath() ?? ''; + const defeats = new Defects( + line, + column, + column, + problem, + desc, + severity, + ruleId, + filePath, + '', + true, + false, + false + ); + this.issues.push(new IssueReport(defeats, undefined)); + } +} diff --git a/ets2panda/linter/homecheck/src/checker/migration/InteropRuleInfo.ts b/ets2panda/linter/homecheck/src/checker/migration/InteropRuleInfo.ts new file mode 100644 index 0000000000..15269d7208 --- /dev/null +++ b/ets2panda/linter/homecheck/src/checker/migration/InteropRuleInfo.ts @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Language } from 'arkanalyzer/lib/core/model/ArkFile'; + +export class InteropRuleInfo { + ruleId: string; + severity: number; + description: string; +} + +// 1.2 import 1.1 +// 1.1 Object => ArkTS 1.2 对象 +export const D2S_DYNAMIC_OBJECT: InteropRuleInfo = { + ruleId: 'arkts-interop-d2s-dynamic-object-on-static-instance', + severity: 1, + description: "ArkTS 1.1 Object's built-in methods work on ArkTS 1.2 objects", +}; + +// 1.2 import 1.1 +// 1.1 Reflect => ArkTS 1.2 对象 +export const D2S_DYNAMIC_REFLECT: InteropRuleInfo = { + ruleId: 'arkts-interop-d2s-dynamic-reflect-on-static-instance', + severity: 1, + description: "ArkTS 1.1 Reflect's built-in methods work on ArkTS 1.2 objects", +}; + +// 1.2 import 1.1 +// 1.2 Object => ArkTS 1.1 对象 +export const D2S_STATIC_OBJECT: InteropRuleInfo = { + ruleId: 'arkts-interop-d2s-static-object-on-dynamic-instance', + severity: 1, + description: "ArkTS 1.2 Object's built-in methods work on ArkTS 1.1 objects", +}; + +// 1.2 import 1.1 +// 1.2 Reflect => ArkTS 1.1 对象 +export const D2S_STATIC_REFLECT: InteropRuleInfo = { + ruleId: 'arkts-interop-d2s-static-reflect-on-dynamic-instance', + severity: 1, + description: "ArkTS 1.2 Reflect's built-in methods work on ArkTS 1.1 objects", +}; + +// 1.1 import 1.2 +// 1.1 Object => ArkTS 1.2 对象 +export const S2D_DYNAMIC_OBJECT: InteropRuleInfo = { + ruleId: 'arkts-interop-s2d-dynamic-object-on-static-instance', + severity: 1, + description: "ArkTS 1.1 Object's built-in methods work on ArkTS 1.2 objects", +}; + +// 1.1 import 1.2 +// 1.1 Reflect => ArkTS 1.2 对象 +export const S2D_DYNAMIC_REFLECT: InteropRuleInfo = { + ruleId: 'arkts-interop-s2d-dynamic-reflect-on-static-instance', + severity: 1, + description: "ArkTS 1.1 Reflect's built-in methods work on ArkTS 1.2 objects", +}; + +// 1.1 import 1.2 +// 1.2 Object => 1.1 对象 +export const S2D_STATIC_OBJECT: InteropRuleInfo = { + ruleId: 'arkts-interop-s2d-static-object-on-dynamic-instance', + severity: 1, + description: "ArkTS 1.2 Object's built-in methods work on ArkTS 1.1 objects", +}; + +// 1.1 import 1.2 +// 1.2 Reflect => 1.1 对象 +export const S2D_STATIC_REFLECT: InteropRuleInfo = { + ruleId: 'arkts-interop-s2d-static-reflect-on-dynamic-instance', + severity: 1, + description: "ArkTS 1.2 Reflect's built-in methods work on ArkTS 1.1 objects", +}; + +export const TS_OBJECT: InteropRuleInfo = { + ruleId: 'arkts-interop-ts2s-ts-object-on-static-instance', + severity: 1, + description: "TypeScript Object's built-in methods work on ArkTS objects", +}; + +export const TS_REFLECT: InteropRuleInfo = { + ruleId: 'arkts-interop-ts2s-ts-reflect-on-static-instance', + severity: 1, + description: "TypeScript Reflect's built-in methods work on ArkTS objects", +}; + +export const JS_OBJECT: InteropRuleInfo = { + ruleId: 'arkts-interop-js2s-js-object-on-static-instance', + severity: 1, + description: "JavaScript Object's built-in methods work on ArkTS objects", +}; + +export const JS_REFLECT: InteropRuleInfo = { + ruleId: 'arkts-interop-js2s-js-reflect-on-static-instance', + severity: 1, + description: "JavaScript Reflect's built-in methods work on ArkTS objects", +}; + +export function findInteropRule( + methodLang: Language, + typeDefLang: Language, + problemStmtLang: Language, + isReflect: boolean +): InteropRuleInfo | undefined { + if (methodLang === Language.ARKTS1_2 && typeDefLang === Language.ARKTS1_1) { + if (problemStmtLang === Language.ARKTS1_1) { + // 包含 object API 的 1.2 函数被导出到 1.1 文件使用 + return isReflect ? S2D_STATIC_REFLECT : S2D_STATIC_OBJECT; + } else { + return isReflect ? D2S_STATIC_REFLECT : D2S_STATIC_OBJECT; + } + } + if (methodLang === Language.ARKTS1_1 && typeDefLang === Language.ARKTS1_2) { + if (problemStmtLang === Language.ARKTS1_2) { + // 包含 object API 的 1.1 函数被导出到 1.2 文件使用 + return isReflect ? D2S_DYNAMIC_REFLECT : D2S_DYNAMIC_OBJECT; + } else { + return isReflect ? S2D_DYNAMIC_REFLECT: S2D_DYNAMIC_OBJECT ; + } + } + if (methodLang === Language.TYPESCRIPT && typeDefLang === Language.ARKTS1_2) { + return isReflect ? TS_REFLECT : TS_OBJECT; + } + if (methodLang === Language.JAVASCRIPT && typeDefLang === Language.ARKTS1_2) { + return isReflect ? JS_REFLECT : JS_OBJECT; + } + return undefined; +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/checker/migration/ModifyStateVarCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/ModifyStateVarCheck.ts index 09e8f03c75..c25cc59611 100644 --- a/ets2panda/linter/homecheck/src/checker/migration/ModifyStateVarCheck.ts +++ b/ets2panda/linter/homecheck/src/checker/migration/ModifyStateVarCheck.ts @@ -13,17 +13,30 @@ * limitations under the License. */ -import { ArkAssignStmt, ArkInstanceFieldRef, Local, Stmt, Value, FieldSignature, ArkMethod } from "arkanalyzer"; +import { + ArkAssignStmt, + ArkInstanceFieldRef, + ArkInstanceInvokeExpr, + CallGraph, + CallGraphBuilder, + Local, + Stmt, + Value, + FieldSignature, + ArkMethod, +} from 'arkanalyzer'; import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; -import { BaseChecker, BaseMetaData } from "../BaseChecker"; -import { Rule, Defects, MatcherTypes, MatcherCallback, ClassMatcher, MethodMatcher } from "../../Index"; -import { IssueReport } from "../../model/Defects"; +import { BaseChecker, BaseMetaData } from '../BaseChecker'; +import { Rule, Defects, MatcherTypes, MatcherCallback, ClassMatcher, MethodMatcher } from '../../Index'; +import { IssueReport } from '../../model/Defects'; +import { CALL_DEPTH_LIMIT, CALLBACK_METHOD_NAME, CallGraphHelper } from './Utils'; +import { WarnInfo } from '../../utils/common/Utils'; const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'ModifyStateVarCheck'); const gMetaData: BaseMetaData = { severity: 1, - ruleDocPath: "", - description: 'It is not allowed to update state when the view is changing.' + ruleDocPath: '', + description: 'It is not allowed to update state when the build function is running', }; export class ModifyStateVarCheck implements BaseChecker { @@ -40,23 +53,58 @@ export class ModifyStateVarCheck implements BaseChecker { private buildMatcher: MethodMatcher = { matcherType: MatcherTypes.METHOD, class: [this.classMatcher], - name: ["build"] + name: ['build'], }; public registerMatchers(): MatcherCallback[] { const matchBuildCb: MatcherCallback = { matcher: this.buildMatcher, - callback: this.check + callback: this.check, }; return [matchBuildCb]; } public check = (target: ArkMethod): void => { + const scene = target.getDeclaringArkFile().getScene(); + let callGraph = CallGraphHelper.getCGInstance(scene); + let callGraphBuilder = new CallGraphBuilder(callGraph, scene); + callGraphBuilder.buildClassHierarchyCallGraph([target.getSignature()]); + const arkClass = target.getDeclaringArkClass(); - const stateVars = new Set(arkClass.getFields().filter(f => f.hasDecorator('State')).map(f => f.getSignature())); + const stateVars = new Set( + arkClass + .getFields() + .filter(f => f.hasDecorator('State')) + .map(f => f.getSignature()) + ); + if (stateVars.size > 0) { + this.checkMethod(target, callGraph, stateVars); + } + }; + + private checkMethod(target: ArkMethod, cg: CallGraph, stateVars: Set, depth: number = 0): void { + if (depth > CALL_DEPTH_LIMIT) { + return; + } let aliases = new Set(); const stmts = target.getBody()?.getCfg().getStmts() ?? []; for (const stmt of stmts) { + const invokeExpr = stmt.getInvokeExpr(); + if (invokeExpr && invokeExpr instanceof ArkInstanceInvokeExpr) { + if ( + CALLBACK_METHOD_NAME.includes( + invokeExpr.getMethodSignature().getMethodSubSignature().getMethodName() + ) + ) { + continue; + } + } + cg.getCallSiteByStmt(stmt).forEach(cs => { + const callee = cg.getArkMethodByFuncID(cs.calleeFuncID); + if (callee) { + this.checkMethod(callee, cg, stateVars, depth + 1); + } + }); if (!(stmt instanceof ArkAssignStmt)) { continue; } @@ -69,7 +117,7 @@ export class ModifyStateVarCheck implements BaseChecker { } } } - }; + } private isAssignToStateVar(stmt: ArkAssignStmt, stateVars: Set, aliases: Set): boolean { const leftOp = stmt.getLeftOp(); @@ -82,7 +130,11 @@ export class ModifyStateVarCheck implements BaseChecker { return false; } - private isAliasOfStateVar(stmt: ArkAssignStmt, stateVars: Set, aliases: Set): Local | undefined { + private isAliasOfStateVar( + stmt: ArkAssignStmt, + stateVars: Set, + aliases: Set + ): Local | undefined { const leftOp = stmt.getLeftOp(); const rightOp = stmt.getRightOp(); if (leftOp instanceof Local && rightOp instanceof ArkInstanceFieldRef) { @@ -96,15 +148,29 @@ export class ModifyStateVarCheck implements BaseChecker { return undefined; } - private addIssueReport(stmt: Stmt, operand: Value) { + private addIssueReport(stmt: Stmt, operand: Value): void { const severity = this.rule.alert ?? this.metaData.severity; const warnInfo = this.getLineAndColumn(stmt, operand); - let defects = new Defects(warnInfo.line, warnInfo.startCol, warnInfo.endCol, this.metaData.description, severity, this.rule.ruleId, - warnInfo.filePath, this.metaData.ruleDocPath, true, false, false); + const problem = 'NoStateUpdateDuringRender'; + const desc = `${this.metaData.description} (${this.rule.ruleId.replace('@migration/', '')})`; + let defects = new Defects( + warnInfo.line, + warnInfo.startCol, + warnInfo.endCol, + problem, + desc, + severity, + this.rule.ruleId, + warnInfo.filePath, + this.metaData.ruleDocPath, + true, + false, + false + ); this.issues.push(new IssueReport(defects, undefined)); } - private getLineAndColumn(stmt: Stmt, operand: Value) { + private getLineAndColumn(stmt: Stmt, operand: Value): WarnInfo { const arkFile = stmt.getCfg()?.getDeclaringMethod().getDeclaringArkFile(); const originPosition = stmt.getOperandOriginalPosition(operand); if (arkFile && originPosition) { @@ -118,4 +184,4 @@ export class ModifyStateVarCheck implements BaseChecker { } return { line: -1, startCol: -1, endCol: -1, filePath: '' }; } -} \ No newline at end of file +} diff --git a/ets2panda/linter/homecheck/src/checker/migration/NoMethodOverridingFieldCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/NoMethodOverridingFieldCheck.ts index aeb6ae0a5a..6c848ece77 100644 --- a/ets2panda/linter/homecheck/src/checker/migration/NoMethodOverridingFieldCheck.ts +++ b/ets2panda/linter/homecheck/src/checker/migration/NoMethodOverridingFieldCheck.ts @@ -13,18 +13,31 @@ * limitations under the License. */ -import { ArkAssignStmt, ArkClass, ArkFile, ArkIfStmt, ArkInstanceFieldRef, ArkInstanceInvokeExpr, ArkMethod, ClassType, FunctionType, Local, Stmt, Value } from "arkanalyzer"; +import { + ArkAssignStmt, + ArkClass, + ArkFile, + ArkIfStmt, + ArkInstanceFieldRef, + ArkInstanceInvokeExpr, + ArkMethod, + ClassType, + FunctionType, + Local, + Stmt, + Value, +} from 'arkanalyzer'; import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; -import { BaseChecker, BaseMetaData } from "../BaseChecker"; -import { Rule, Defects, MatcherTypes, MethodMatcher, MatcherCallback, ClassMatcher } from "../../Index"; -import { IssueReport } from "../../model/Defects"; -import { ClassCategory } from "arkanalyzer/lib/core/model/ArkClass"; +import { BaseChecker, BaseMetaData } from '../BaseChecker'; +import { Rule, Defects, MatcherTypes, MethodMatcher, MatcherCallback, ClassMatcher } from '../../Index'; +import { IssueReport } from '../../model/Defects'; +import { ClassCategory } from 'arkanalyzer/lib/core/model/ArkClass'; const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'NoMethodOverridingFieldCheck'); const gMetaData: BaseMetaData = { severity: 1, - ruleDocPath: "", - description: '' + ruleDocPath: '', + description: '', }; export class NoMethodOverridingFieldCheck implements BaseChecker { @@ -35,28 +48,31 @@ export class NoMethodOverridingFieldCheck implements BaseChecker { private classMetcher: ClassMatcher = { matcherType: MatcherTypes.CLASS, - ClassCategory: [ClassCategory.CLASS] + ClassCategory: [ClassCategory.CLASS], }; public registerMatchers(): MatcherCallback[] { const methodCb: MatcherCallback = { matcher: this.classMetcher, - callback: this.check - } + callback: this.check, + }; return [methodCb]; } - public check = (target: ArkClass) => { + public check = (target: ArkClass): void => { const interfaces = target.getAllHeritageClasses().filter(c => c.getCategory() === ClassCategory.INTERFACE); for (const i of interfaces) { - const fields = i.getFields().filter(f => f.getType() instanceof FunctionType).map(f => f.getName()); + const fields = i + .getFields() + .filter(f => f.getType() instanceof FunctionType) + .map(f => f.getName()); fields.forEach(f => { const method = target.getMethodWithName(f); if (method) { // record class // console.log(`111`) } - }) + }); } - } -} \ No newline at end of file + }; +} diff --git a/ets2panda/linter/homecheck/src/checker/migration/NoOptionalMethodCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/NoOptionalMethodCheck.ts index 252c001dfd..4be0d03726 100644 --- a/ets2panda/linter/homecheck/src/checker/migration/NoOptionalMethodCheck.ts +++ b/ets2panda/linter/homecheck/src/checker/migration/NoOptionalMethodCheck.ts @@ -13,17 +13,17 @@ * limitations under the License. */ -import { ArkClass, ArkMethod} from "arkanalyzer"; +import { ArkClass, ArkMethod } from 'arkanalyzer'; import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; -import { BaseChecker, BaseMetaData } from "../BaseChecker"; -import { Rule, Defects, MatcherTypes, MatcherCallback, ClassMatcher } from "../../Index"; -import { IssueReport } from "../../model/Defects"; +import { BaseChecker, BaseMetaData } from '../BaseChecker'; +import { Rule, Defects, MatcherTypes, MatcherCallback, ClassMatcher } from '../../Index'; +import { IssueReport } from '../../model/Defects'; const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'NoOptionalMethodCheck'); const gMetaData: BaseMetaData = { severity: 1, - ruleDocPath: "", - description: '' + ruleDocPath: '', + description: '', }; export class NoOptionalMethodCheck implements BaseChecker { @@ -33,32 +33,48 @@ export class NoOptionalMethodCheck implements BaseChecker { public issues: IssueReport[] = []; private classMetcher: ClassMatcher = { - matcherType: MatcherTypes.CLASS + matcherType: MatcherTypes.CLASS, }; public registerMatchers(): MatcherCallback[] { const classCb: MatcherCallback = { matcher: this.classMetcher, - callback: this.check - } + callback: this.check, + }; return [classCb]; } - public check = (target: ArkClass) => { - target.getMethods().filter(m => m.getQuestionToken()).forEach(m => { - const posInfo = this.getMethodPos(m); - this.addIssueReport(posInfo); - }); - } + public check = (target: ArkClass): void => { + target + .getMethods() + .filter(m => m.getQuestionToken()) + .forEach(m => { + const posInfo = this.getMethodPos(m); + this.addIssueReport(posInfo); + }); + }; - private addIssueReport(warnInfo: { line: number; startCol: number; endCol: number; filePath: string; }) { + private addIssueReport(warnInfo: { line: number; startCol: number; endCol: number; filePath: string }): void { + const problem = ''; const severity = this.rule.alert ?? this.metaData.severity; - let defects = new Defects(warnInfo.line, warnInfo.startCol, warnInfo.endCol, this.metaData.description, severity, this.rule.ruleId, - warnInfo.filePath, this.metaData.ruleDocPath, true, false, false); + let defects = new Defects( + warnInfo.line, + warnInfo.startCol, + warnInfo.endCol, + problem, + this.metaData.description, + severity, + this.rule.ruleId, + warnInfo.filePath, + this.metaData.ruleDocPath, + true, + false, + false + ); this.issues.push(new IssueReport(defects, undefined)); } - private getMethodPos(cls: ArkMethod): { line: number; startCol: number; endCol: number; filePath: string; } { + private getMethodPos(cls: ArkMethod): { line: number; startCol: number; endCol: number; filePath: string } { const line = cls.getLineCol() ?? -1; const startCol = cls.getColumn() ?? -1; const endCol = startCol; @@ -70,4 +86,4 @@ export class NoOptionalMethodCheck implements BaseChecker { return { line, startCol, endCol, filePath: '' }; } } -} \ No newline at end of file +} diff --git a/ets2panda/linter/homecheck/src/checker/migration/NoTSLikeAsCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/NoTSLikeAsCheck.ts new file mode 100644 index 0000000000..f45c63723c --- /dev/null +++ b/ets2panda/linter/homecheck/src/checker/migration/NoTSLikeAsCheck.ts @@ -0,0 +1,584 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import path from 'path'; +import { + ArkMethod, + ArkAssignStmt, + FieldSignature, + Stmt, + Scene, + Value, + DVFGBuilder, + ArkInstanceOfExpr, + CallGraph, + ArkParameterRef, + ArkInstanceFieldRef, + ArkNamespace, + Local, + ArkCastExpr, + ClassType, + classSignatureCompare, + ArkField, + fileSignatureCompare, + Cfg, + BasicBlock, + ArkIfStmt, + ArkUnopExpr, +} from 'arkanalyzer/lib'; +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; +import { BaseChecker, BaseMetaData } from '../BaseChecker'; +import { Rule, Defects, MatcherCallback } from '../../Index'; +import { IssueReport } from '../../model/Defects'; +import { DVFG, DVFGNode } from 'arkanalyzer/lib/VFG/DVFG'; +import { CALL_DEPTH_LIMIT, getGlobalsDefineInDefaultMethod, GlobalCallGraphHelper } from './Utils'; +import { WarnInfo } from '../../utils/common/Utils'; +import { ClassCategory } from 'arkanalyzer/lib/core/model/ArkClass'; +import { Language } from 'arkanalyzer/lib/core/model/ArkFile'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'NoTSLikeAsCheck'); +const gMetaData: BaseMetaData = { + severity: 1, + ruleDocPath: '', + description: '', +}; + +export class NoTSLikeAsCheck implements BaseChecker { + readonly metaData: BaseMetaData = gMetaData; + public rule: Rule; + public defects: Defects[] = []; + public issues: IssueReport[] = []; + private cg: CallGraph; + private dvfg: DVFG; + private dvfgBuilder: DVFGBuilder; + private visited: Set = new Set(); + + public registerMatchers(): MatcherCallback[] { + const matchBuildCb: MatcherCallback = { + matcher: undefined, + callback: this.check, + }; + return [matchBuildCb]; + } + + public check = (scene: Scene): void => { + this.cg = GlobalCallGraphHelper.getCGInstance(scene); + + this.dvfg = new DVFG(this.cg); + this.dvfgBuilder = new DVFGBuilder(this.dvfg, scene); + + for (let arkFile of scene.getFiles()) { + // 此规则仅对arkts1.1和arkts1.2进行检查,typescript在编译阶段会报错,javascript没有类型断言语法 + if (!(arkFile.getLanguage() === Language.ARKTS1_1 || arkFile.getLanguage() === Language.ARKTS1_2)) { + continue; + } + const defaultMethod = arkFile.getDefaultClass().getDefaultArkMethod(); + let globalVarMap: Map = new Map(); + if (defaultMethod) { + this.dvfgBuilder.buildForSingleMethod(defaultMethod); + globalVarMap = getGlobalsDefineInDefaultMethod(defaultMethod); + } + for (let clazz of arkFile.getClasses()) { + for (let field of clazz.getFields()) { + this.processClassField(field, globalVarMap, scene); + } + for (let mtd of clazz.getMethods()) { + this.processArkMethod(mtd, globalVarMap, scene); + } + } + for (let namespace of arkFile.getAllNamespacesUnderThisFile()) { + this.processNameSpace(namespace, globalVarMap, scene); + } + } + }; + + public processNameSpace(namespace: ArkNamespace, globalVarMap: Map, scene: Scene): void { + for (let ns of namespace.getNamespaces()) { + this.processNameSpace(ns, globalVarMap, scene); + } + for (let clazz of namespace.getClasses()) { + for (let field of clazz.getFields()) { + this.processClassField(field, globalVarMap, scene); + } + for (let mtd of clazz.getMethods()) { + this.processArkMethod(mtd, globalVarMap, scene); + } + } + } + + public processClassField(field: ArkField, globalVarMap: Map, scene: Scene): void { + const stmts = field.getInitializer(); + for (const stmt of stmts) { + const castExpr = this.getCastExpr(stmt); + if (castExpr === null) { + continue; + } + // 判断cast类型断言的类型是否是class,非class的场景不在本规则检查范围内 + if (!(castExpr.getType() instanceof ClassType)) { + continue; + } + let checkAll = { value: true }; + let visited: Set = new Set(); + const result = this.checkFromStmt(stmt, scene, globalVarMap, checkAll, visited); + if (result !== null) { + this.addIssueReport(stmt, castExpr, result); + } else { + if (!checkAll.value) { + this.addIssueReport(stmt, castExpr); + } + } + } + } + + public processArkMethod(target: ArkMethod, globalVarMap: Map, scene: Scene): void { + const stmts = target.getBody()?.getCfg().getStmts() ?? []; + for (const stmt of stmts) { + // cast表达式所在语句为sink点,从该点开始进行逆向数据流分析 + const castExpr = this.getCastExpr(stmt); + if (castExpr === null) { + continue; + } + // 判断cast类型断言的类型是否是class,非class的场景不在本规则检查范围内 + if (!(castExpr.getType() instanceof ClassType)) { + continue; + } + if (this.hasCheckedWithInstanceof(stmt.getCfg(), stmt)) { + continue; + } + if (!this.visited.has(target)) { + this.dvfgBuilder.buildForSingleMethod(target); + this.visited.add(target); + } + + let checkAll = { value: true }; + let visited: Set = new Set(); + const result = this.checkFromStmt(stmt, scene, globalVarMap, checkAll, visited); + if (result !== null) { + this.addIssueReport(stmt, castExpr, result); + } else { + if (!checkAll.value) { + this.addIssueReport(stmt, castExpr); + } + } + } + } + + private hasCheckedWithInstanceof(cfg: Cfg, stmt: Stmt): boolean { + const castExpr = this.getCastExpr(stmt); + if (castExpr === null) { + return false; + } + for (const block of cfg.getBlocks()) { + // 这里仅判断了cast op是否进行了instanceof判断,如果op是由op1赋值,op1进行了instanceof判断,此处不认为是做了有效检查 + // TODO: 还需进行复杂条件中包含类型守卫判断的情况,涉及&&,||等的复合 + const positiveCheck = this.isCastExprWithTypeAssurancePositive(block, castExpr); + const negativeCheck = this.isCastExprWithTypeAssuranceNegative(block, castExpr); + if (!(positiveCheck || negativeCheck)) { + continue; + } + let checkedBB: Set = new Set(); + let needCheckBB: number[] = []; + checkedBB.add(block.getId()); + const allSuccessors = block.getSuccessors(); + if (allSuccessors.length > 0 && positiveCheck) { + needCheckBB.push(allSuccessors[0].getId()); + } + if (allSuccessors.length > 1 && negativeCheck) { + needCheckBB.push(allSuccessors[1].getId()); + } + while (needCheckBB.length > 0) { + const bbId = needCheckBB.shift(); + if (bbId === undefined) { + break; + } + if (checkedBB.has(bbId)) { + continue; + } + checkedBB.add(bbId); + const bb = this.getBlockWithId(bbId, cfg); + if (bb === null) { + continue; + } + if (this.isStmtInBlock(stmt, bb)) { + return true; + } else { + bb.getSuccessors().forEach(b => needCheckBB.push(b.getId())); + } + } + } + return false; + } + + private isStmtInBlock(stmt: Stmt, block: BasicBlock): boolean { + for (const s of block.getStmts()) { + if (s === stmt) { + return true; + } + } + return false; + } + + private getBlockWithId(id: number, cfg: Cfg): BasicBlock | null { + const blocks = cfg.getBlocks(); + for (const bb of blocks) { + if (bb.getId() === id) { + return bb; + } + } + return null; + } + + private isCastExprWithTypeAssurancePositive(bb: BasicBlock, castExpr: ArkCastExpr): boolean { + for (const stmt of bb.getStmts()) { + if (!(stmt instanceof ArkIfStmt)) { + continue; + } + const conditionExpr = stmt.getConditionExpr(); + const op1 = conditionExpr.getOp1(); + const op2 = conditionExpr.getOp2(); + if (op1 instanceof Local) { + const declareStmt = op1.getDeclaringStmt(); + if (declareStmt !== null && this.isStmtWithTypeAssurancePositive(declareStmt, castExpr)) { + return true; + } + } + if (op2 instanceof Local) { + const declareStmt = op2.getDeclaringStmt(); + if (declareStmt !== null && this.isStmtWithTypeAssurancePositive(declareStmt, castExpr)) { + return true; + } + } + } + return false; + } + + private isCastExprWithTypeAssuranceNegative(bb: BasicBlock, castExpr: ArkCastExpr): boolean { + for (const stmt of bb.getStmts()) { + if (!(stmt instanceof ArkIfStmt)) { + continue; + } + const conditionExpr = stmt.getConditionExpr(); + const op1 = conditionExpr.getOp1(); + const op2 = conditionExpr.getOp2(); + if (op1 instanceof Local) { + const declareStmt = op1.getDeclaringStmt(); + if (declareStmt !== null && this.isStmtWithTypeAssuranceNegative(declareStmt, castExpr)) { + return true; + } + } + if (op2 instanceof Local) { + const declareStmt = op2.getDeclaringStmt(); + if (declareStmt !== null && this.isStmtWithTypeAssuranceNegative(declareStmt, castExpr)) { + return true; + } + } + } + return false; + } + + private isStmtWithTypeAssurancePositive(declareStmt: Stmt, castExpr: ArkCastExpr): boolean { + if (!(declareStmt instanceof ArkAssignStmt)) { + return false; + } + const rightOp = declareStmt.getRightOp(); + if (!(rightOp instanceof ArkInstanceOfExpr)) { + return false; + } + const castOp = castExpr.getOp(); + const castType = castExpr.getType(); + const instanceofType = rightOp.getCheckType(); + if (castType.getTypeString() !== instanceofType.getTypeString()) { + return false; + } + const instanceofOp = rightOp.getOp(); + if (!(castOp instanceof Local && instanceofOp instanceof Local)) { + return false; + } + return castOp.getName() === instanceofOp.getName(); + } + + private isStmtWithTypeAssuranceNegative(declareStmt: Stmt, castExpr: ArkCastExpr): boolean { + if (!(declareStmt instanceof ArkAssignStmt)) { + return false; + } + const rightOp = declareStmt.getRightOp(); + if (!(rightOp instanceof ArkUnopExpr && rightOp.getOperator() === '!')) { + return false; + } + const unaryOp = rightOp.getOp(); + if (!(unaryOp instanceof Local)) { + return false; + } + const unaryOpDeclareStmt = unaryOp.getDeclaringStmt(); + if (unaryOpDeclareStmt === null || !(unaryOpDeclareStmt instanceof ArkAssignStmt)) { + return false; + } + const unaryOpRightOp = unaryOpDeclareStmt.getRightOp(); + if (!(unaryOpRightOp instanceof ArkInstanceOfExpr)) { + return false; + } + const castOp = castExpr.getOp(); + const castType = castExpr.getType(); + const instanceofType = unaryOpRightOp.getCheckType(); + if (castType.getTypeString() !== instanceofType.getTypeString()) { + return false; + } + const instanceofOp = unaryOpRightOp.getOp(); + if (!(castOp instanceof Local && instanceofOp instanceof Local)) { + return false; + } + return castOp.getName() === instanceofOp.getName(); + } + + private checkFromStmt( + stmt: Stmt, + scene: Scene, + globalVarMap: Map, + checkAll: { value: boolean }, + visited: Set, + depth: number = 0 + ): Stmt | null { + if (depth > CALL_DEPTH_LIMIT) { + checkAll.value = false; + return null; + } + const node = this.dvfg.getOrNewDVFGNode(stmt); + let worklist: DVFGNode[] = [node]; + while (worklist.length > 0) { + const current = worklist.shift()!; + const currentStmt = current.getStmt(); + if (visited.has(currentStmt)) { + continue; + } + visited.add(currentStmt); + if (this.isWithInterfaceAnnotation(currentStmt, scene)) { + return currentStmt; + } + const gv = this.checkIfCastOpIsGlobalVar(currentStmt); + if (gv) { + const globalDefs = globalVarMap.get(gv.getName()); + if (globalDefs === undefined) { + const importValue = this.checkIfCastOpIsFromImport(currentStmt); + if (importValue && importValue.getDeclaringStmt() !== null) { + worklist.push(this.dvfg.getOrNewDVFGNode(importValue.getDeclaringStmt()!)); + } + } else { + globalDefs.forEach(d => worklist.push(this.dvfg.getOrNewDVFGNode(d))); + } + continue; + } + + const callsite = this.cg.getCallSiteByStmt(currentStmt); + for (const cs of callsite) { + const declaringMtd = this.cg.getArkMethodByFuncID(cs.calleeFuncID); + if (!declaringMtd || !declaringMtd.getCfg()) { + continue; + } + if (!this.visited.has(declaringMtd)) { + this.dvfgBuilder.buildForSingleMethod(declaringMtd); + this.visited.add(declaringMtd); + } + const returnStmts = declaringMtd.getReturnStmt(); + for (const stmt of returnStmts) { + const res = this.checkFromStmt(stmt, scene, globalVarMap, checkAll, visited, depth + 1); + if (res !== null) { + return res; + } + } + } + const paramRef = this.isFromParameter(currentStmt); + if (paramRef) { + const paramIdx = paramRef.getIndex(); + const callsites = this.cg.getInvokeStmtByMethod( + currentStmt.getCfg().getDeclaringMethod().getSignature() + ); + this.processCallsites(callsites); + const argDefs = this.collectArgDefs(paramIdx, callsites); + for (const stmt of argDefs) { + const res = this.checkFromStmt(stmt, scene, globalVarMap, checkAll, visited, depth + 1); + if (res !== null) { + return res; + } + } + } + current.getIncomingEdge().forEach(e => worklist.push(e.getSrcNode() as DVFGNode)); + } + return null; + } + + private checkIfCastOpIsGlobalVar(stmt: Stmt): Local | undefined { + const obj = this.getCastOp(stmt); + if (obj instanceof Local && !obj.getDeclaringStmt()) { + return obj; + } + return undefined; + } + + private checkIfCastOpIsFromImport(stmt: Stmt): Local | undefined { + const obj = this.getCastOp(stmt); + if (obj === null || !(obj instanceof Local)) { + return undefined; + } + const importInfos = stmt.getCfg().getDeclaringMethod().getDeclaringArkFile().getImportInfos(); + for (const importInfo of importInfos) { + if (importInfo.getImportClauseName() === obj.getName()) { + const exportInfo = importInfo.getLazyExportInfo(); + if (exportInfo === null) { + return undefined; + } + const arkExport = exportInfo.getArkExport(); + if (arkExport === null || arkExport === undefined) { + return undefined; + } + if (!(arkExport instanceof Local)) { + return undefined; + } + return arkExport; + } + } + return undefined; + } + + private processCallsites(callsites: Stmt[]): void { + callsites.forEach(cs => { + const declaringMtd = cs.getCfg().getDeclaringMethod(); + if (!this.visited.has(declaringMtd)) { + this.dvfgBuilder.buildForSingleMethod(declaringMtd); + this.visited.add(declaringMtd); + } + }); + } + + // 判断语句是否为赋值语句,且左值的类型注解为Interface,右值的类型与左值不一样 + private isWithInterfaceAnnotation(stmt: Stmt, scene: Scene): boolean { + if (!(stmt instanceof ArkAssignStmt)) { + return false; + } + const leftOpType = stmt.getLeftOp().getType(); + if (!(leftOpType instanceof ClassType)) { + return false; + } + const leftOpTypeclass = scene.getClass(leftOpType.getClassSignature()); + if (leftOpTypeclass === null) { + return false; + } + if (leftOpTypeclass.getCategory() !== ClassCategory.INTERFACE) { + return false; + } + const rightOpType = stmt.getRightOp().getType(); + if (!(rightOpType instanceof ClassType)) { + return true; + } + return !classSignatureCompare(leftOpType.getClassSignature(), rightOpType.getClassSignature()); + } + + private isFromParameter(stmt: Stmt): ArkParameterRef | undefined { + if (!(stmt instanceof ArkAssignStmt)) { + return undefined; + } + const rightOp = stmt.getRightOp(); + if (rightOp instanceof ArkParameterRef) { + return rightOp; + } + return undefined; + } + + private getCastOp(stmt: Stmt): Value | null { + if (!(stmt instanceof ArkAssignStmt)) { + return null; + } + const rightOp = stmt.getRightOp(); + if (!(rightOp instanceof ArkCastExpr)) { + return null; + } + return rightOp.getOp(); + } + + private getCastExpr(stmt: Stmt): ArkCastExpr | null { + // method中使用as断言的地方可能是body体中,函数调用的实参,返回值,均会表示成ArkAssignStmt + if (!(stmt instanceof ArkAssignStmt)) { + return null; + } + const rightOp = stmt.getRightOp(); + if (!(rightOp instanceof ArkCastExpr)) { + return null; + } + return rightOp; + } + + private collectArgDefs(argIdx: number, callsites: Stmt[]): Stmt[] { + const getKey = (v: Value): Value | FieldSignature => { + return v instanceof ArkInstanceFieldRef ? v.getFieldSignature() : v; + }; + return callsites.flatMap(callsite => { + const target: Value | FieldSignature = getKey(callsite.getInvokeExpr()!.getArg(argIdx)); + return Array.from(this.dvfg.getOrNewDVFGNode(callsite).getIncomingEdge()) + .map(e => (e.getSrcNode() as DVFGNode).getStmt()) + .filter(s => { + return s instanceof ArkAssignStmt && target === getKey(s.getLeftOp()); + }); + }); + } + + private addIssueReport(stmt: Stmt, operand: ArkCastExpr, relatedStmt?: Stmt): void { + const severity = this.rule.alert ?? this.metaData.severity; + const warnInfo = this.getLineAndColumn(stmt, operand); + const problem = 'As'; + const descPrefix = 'The value in type assertion is assigned by value with interface annotation'; + let desc = `(${this.rule.ruleId.replace('@migration/', '')})`; + + if (relatedStmt === undefined) { + desc = `Can not find all assignments of the value in type assertion, please check it manually ` + desc; + } else { + const sinkFile = stmt.getCfg().getDeclaringMethod().getDeclaringArkFile(); + const relatedFile = relatedStmt.getCfg().getDeclaringMethod().getDeclaringArkFile(); + if (fileSignatureCompare(sinkFile.getFileSignature(), relatedFile.getFileSignature())) { + desc = `${descPrefix} in Line ${relatedStmt.getOriginPositionInfo().getLineNo()} ` + desc; + } else { + desc = `${descPrefix} in file ${path.normalize(relatedFile.getName())}: ${relatedStmt.getOriginPositionInfo().getLineNo()} ` + desc; + } + } + let defects = new Defects( + warnInfo.line, + warnInfo.startCol, + warnInfo.endCol, + problem, + desc, + severity, + this.rule.ruleId, + warnInfo.filePath, + this.metaData.ruleDocPath, + true, + false, + false + ); + this.issues.push(new IssueReport(defects, undefined)); + } + + private getLineAndColumn(stmt: Stmt, operand: Value): WarnInfo { + const arkFile = stmt.getCfg()?.getDeclaringMethod().getDeclaringArkFile(); + const originPosition = stmt.getOperandOriginalPosition(operand); + if (arkFile && originPosition) { + const originPath = arkFile.getFilePath(); + const line = originPosition.getFirstLine(); + const startCol = originPosition.getFirstCol(); + const endCol = startCol; + return { line, startCol, endCol, filePath: originPath }; + } else { + logger.debug('ArkFile is null.'); + } + return { line: -1, startCol: -1, endCol: -1, filePath: '' }; + } +} diff --git a/ets2panda/linter/homecheck/src/checker/migration/ObjectLiteralCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/ObjectLiteralCheck.ts index f1cb46c499..66a5c66380 100644 --- a/ets2panda/linter/homecheck/src/checker/migration/ObjectLiteralCheck.ts +++ b/ets2panda/linter/homecheck/src/checker/migration/ObjectLiteralCheck.ts @@ -13,18 +13,38 @@ * limitations under the License. */ -import { ArkMethod, ArkAssignStmt, FieldSignature, Stmt, Scene, Value, DVFGBuilder, ArkInstanceOfExpr, ArkNewExpr, CallGraph, CallGraphBuilder, ArkParameterRef, ArkInstanceFieldRef } from "arkanalyzer/lib"; +import { + ArkMethod, + ArkAssignStmt, + FieldSignature, + Stmt, + Scene, + Value, + ArkClass, + ArkFile, + ArkInstanceOfExpr, + ArkNewExpr, + CallGraph, + ArkParameterRef, + ArkInstanceFieldRef, + AbstractFieldRef, + Local, + ArkArrayRef, + ClassSignature, +} from 'arkanalyzer/lib'; import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; -import { BaseChecker, BaseMetaData } from "../BaseChecker"; -import { Rule, Defects, MatcherCallback } from "../../Index"; -import { IssueReport } from "../../model/Defects"; -import { DVFG, DVFGNode } from "arkanalyzer/lib/VFG/DVFG"; +import { BaseChecker, BaseMetaData } from '../BaseChecker'; +import { Rule, Defects, MatcherCallback } from '../../Index'; +import { IssueReport } from '../../model/Defects'; +import { DVFGNode } from 'arkanalyzer/lib/VFG/DVFG'; +import { DVFGHelper, CALL_DEPTH_LIMIT, GlobalCallGraphHelper } from './Utils'; +import { WarnInfo } from '../../utils/common/Utils'; const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'ObjectLiteralCheck'); const gMetaData: BaseMetaData = { severity: 1, - ruleDocPath: "", - description: 'Object literal shall generate instance of a specific class.' + ruleDocPath: '', + description: 'Object literal shall generate instance of a specific class', }; export class ObjectLiteralCheck implements BaseChecker { @@ -33,44 +53,34 @@ export class ObjectLiteralCheck implements BaseChecker { public defects: Defects[] = []; public issues: IssueReport[] = []; private cg: CallGraph; - private dvfg: DVFG; + private visited: Set = new Set(); public registerMatchers(): MatcherCallback[] { const matchBuildCb: MatcherCallback = { matcher: undefined, - callback: this.check - } + callback: this.check, + }; return [matchBuildCb]; } - public check = (scene: Scene) => { - this.cg = new CallGraph(scene); - let cgBuilder = new CallGraphBuilder(this.cg, scene); - cgBuilder.buildDirectCallGraphForScene(); - let entries = this.cg.getEntries().map(funcId => this.cg.getArkMethodByFuncID(funcId)!.getSignature()); - cgBuilder.buildClassHierarchyCallGraph(entries, true); - - this.dvfg = new DVFG(this.cg); - const dvfgBuilder = new DVFGBuilder(this.dvfg, scene); - dvfgBuilder.build(); + public check = (scene: Scene): void => { + this.cg = GlobalCallGraphHelper.getCGInstance(scene); for (let arkFile of scene.getFiles()) { - for (let clazz of arkFile.getClasses()) { - for (let mtd of clazz.getMethods()) { - this.processArkMethod(mtd, scene); - } - } - for (let namespace of arkFile.getAllNamespacesUnderThisFile()) { - for (let clazz of namespace.getClasses()) { - for (let mtd of clazz.getMethods()) { - this.processArkMethod(mtd, scene); - } - } - } + const topLevelVarMap: Map = new Map(); + this.collectImportedVar(topLevelVarMap, arkFile); + this.collectTopLevelVar(topLevelVarMap, arkFile, scene); + + const handleClass = (cls: ArkClass): void => { + cls.getMethods().forEach(m => this.processArkMethod(m, topLevelVarMap, scene)); + }; + + arkFile.getClasses().forEach(cls => handleClass(cls)); + arkFile.getAllNamespacesUnderThisFile().forEach(n => n.getClasses().forEach(cls => handleClass(cls))); } - } + }; - public processArkMethod(target: ArkMethod, scene: Scene) { + public processArkMethod(target: ArkMethod, topLevelVarMap: Map, scene: Scene): void { const stmts = target.getBody()?.getCfg().getStmts() ?? []; for (const stmt of stmts) { if (!(stmt instanceof ArkAssignStmt)) { @@ -80,46 +90,164 @@ export class ObjectLiteralCheck implements BaseChecker { if (!(rightOp instanceof ArkInstanceOfExpr)) { continue; } + if (!this.visited.has(target)) { + DVFGHelper.buildSingleDVFG(target, scene); + this.visited.add(target); + } + let result: Stmt[] = []; let checkAll = { value: true }; - this.checkFromStmt(stmt, scene, result, checkAll); + let visited: Set = new Set(); + this.checkFromStmt(stmt, scene, result, topLevelVarMap, checkAll, visited); result.forEach(s => this.addIssueReport(s, (s as ArkAssignStmt).getRightOp())); if (!checkAll.value) { this.addIssueReport(stmt, rightOp); } } + } + private collectImportedVar(importVarMap: Map, file: ArkFile) { + file.getImportInfos().forEach(importInfo => { + const exportInfo = importInfo.getLazyExportInfo(); + if (exportInfo === null) { + return; + } + const arkExport = exportInfo.getArkExport(); + if (!arkExport || !(arkExport instanceof Local)) { + return; + } + const declaringStmt = arkExport.getDeclaringStmt(); + if (!declaringStmt) { + return; + } + importVarMap.set(arkExport.getName(), [declaringStmt]); + }); } - private checkFromStmt(stmt: Stmt, scene: Scene, res: Stmt[], checkAll: { value: boolean }, depth: number = 0) { - if (depth > 2) { + private collectTopLevelVar(topLevelVarMap: Map, file: ArkFile, scene: Scene) { + const defaultMethod = file.getDefaultClass().getDefaultArkMethod(); + if (!defaultMethod) { + return; + } + DVFGHelper.buildSingleDVFG(defaultMethod, scene); + const stmts = defaultMethod.getBody()?.getCfg().getStmts() ?? []; + for (const stmt of stmts) { + if (!(stmt instanceof ArkAssignStmt)) { + continue; + } + const leftOp = stmt.getLeftOp(); + if (!(leftOp instanceof Local)) { + continue; + } + const name = leftOp.getName(); + if (name.startsWith('%') || name === 'this') { + continue; + } + topLevelVarMap.set(name, [...(topLevelVarMap.get(name) ?? []), stmt]); + } + } + + private checkFromStmt( + stmt: Stmt, + scene: Scene, + res: Stmt[], + topLevelVarMap: Map, + checkAll: { value: boolean }, + visited: Set, + depth: number = 0 + ): void { + if (depth > CALL_DEPTH_LIMIT) { checkAll.value = false; return; } - const node = this.dvfg.getOrNewDVFGNode(stmt); + const node = DVFGHelper.getOrNewDVFGNode(stmt, scene); let worklist: DVFGNode[] = [node]; while (worklist.length > 0) { const current = worklist.shift()!; const currentStmt = current.getStmt(); + if (visited.has(currentStmt)) { + continue; + } + visited.add(currentStmt); if (this.isObjectLiteral(currentStmt, scene)) { res.push(currentStmt); continue; } + const isClsField = this.isClassField(currentStmt, scene); + if (isClsField) { + isClsField.forEach(d => worklist.push(DVFGHelper.getOrNewDVFGNode(d, scene))); + continue; + } + const isArrayField = this.isArrayField(currentStmt, topLevelVarMap); + if (isArrayField) { + isArrayField.forEach(d => worklist.push(DVFGHelper.getOrNewDVFGNode(d, scene))); + continue; + } + const gv = this.checkIfIsTopLevelVar(currentStmt); + if (gv) { + const globalDefs = topLevelVarMap.get(gv.getName()); + globalDefs?.forEach(d => { + worklist.push(DVFGHelper.getOrNewDVFGNode(d, scene)); + }); + continue; + } const callsite = this.cg.getCallSiteByStmt(currentStmt); callsite.forEach(cs => { - let returnStmts = this.cg.getArkMethodByFuncID(cs.calleeFuncID)?.getReturnStmt(); - returnStmts?.forEach(r => this.checkFromStmt(r, scene, res, checkAll, depth + 1)); - }) + const declaringMtd = this.cg.getArkMethodByFuncID(cs.calleeFuncID); + if (!declaringMtd || !declaringMtd.getCfg()) { + return; + } + if (!this.visited.has(declaringMtd)) { + DVFGHelper.buildSingleDVFG(declaringMtd, scene); + this.visited.add(declaringMtd); + } + declaringMtd + .getReturnStmt() + .forEach(r => this.checkFromStmt(r, scene, res, topLevelVarMap, checkAll, visited, depth + 1)); + }); const paramRef = this.isFromParameter(currentStmt); if (paramRef) { const paramIdx = paramRef.getIndex(); - const callsites = this.cg.getInvokeStmtByMethod(currentStmt.getCfg().getDeclaringMethod().getSignature()); - this.collectArgDefs(paramIdx, callsites).forEach(d => this.checkFromStmt(d, scene, res, checkAll, depth + 1)); + const callsites = this.cg.getInvokeStmtByMethod( + currentStmt.getCfg().getDeclaringMethod().getSignature() + ); + this.processCallsites(callsites, scene); + this.collectArgDefs(paramIdx, callsites, scene).forEach(d => + this.checkFromStmt(d, scene, res, topLevelVarMap, checkAll, visited, depth + 1) + ); } current.getIncomingEdge().forEach(e => worklist.push(e.getSrcNode() as DVFGNode)); } } + private checkIfIsTopLevelVar(stmt: Stmt): Local | undefined { + if (!(stmt instanceof ArkAssignStmt)) { + return undefined; + } + const rightOp = stmt.getRightOp(); + if (rightOp instanceof Local && !rightOp.getDeclaringStmt()) { + return rightOp; + } + if (!(rightOp instanceof ArkInstanceOfExpr)) { + return undefined; + } + const obj = rightOp.getOp(); + if (obj instanceof Local && !obj.getDeclaringStmt()) { + return obj; + } + return undefined; + } + + private processCallsites(callsites: Stmt[], scene: Scene): void { + callsites.forEach(cs => { + const declaringMtd = cs.getCfg().getDeclaringMethod(); + if (!this.visited.has(declaringMtd)) { + DVFGHelper.buildSingleDVFG(declaringMtd, scene); + this.visited.add(declaringMtd); + } + }); + } + private isObjectLiteral(stmt: Stmt, scene: Scene): boolean { if (!(stmt instanceof ArkAssignStmt)) { return false; @@ -135,6 +263,77 @@ export class ObjectLiteralCheck implements BaseChecker { return false; } + private isClassField(stmt: Stmt, scene: Scene): Stmt[] | undefined { + if (!(stmt instanceof ArkAssignStmt)) { + return undefined; + } + const clsField = stmt.getRightOp(); + if (!(clsField instanceof AbstractFieldRef)) { + return undefined; + } + if (clsField instanceof ArkInstanceFieldRef && clsField.getBase().getName() !== 'this') { + return undefined; + } + const fieldSig = clsField.getFieldSignature(); + const clsSig = fieldSig.getDeclaringSignature(); + if (!(clsSig instanceof ClassSignature)) { + return undefined; + } + const cls = scene.getClass(clsSig); + if (!cls) { + logger.error(`cannot find class based on class sig: ${clsSig.toString()}`); + return undefined; + } + const field = cls.getField(fieldSig); + if (!field) { + logger.error(`cannot find field based on field sig: ${fieldSig.toString()}`); + return undefined; + } + if (!field.isStatic()) { + DVFGHelper.buildSingleDVFG(cls.getInstanceInitMethod(), scene); + } else { + DVFGHelper.buildSingleDVFG(cls.getStaticInitMethod(), scene); + } + return field.getInitializer().slice(-1); + } + + private isArrayField(stmt: Stmt, topLevelVarMap: Map): Stmt[] | undefined { + if (!(stmt instanceof ArkAssignStmt)) { + return undefined; + } + const arrField = stmt.getRightOp(); + if (!(arrField instanceof ArkArrayRef)) { + return undefined; + } + const arr = arrField.getBase(); + const index = arrField.getIndex(); + let arrDeclarations: Stmt[] = []; + if (arr.getDeclaringStmt()) { + arrDeclarations.push(arr.getDeclaringStmt()!); + } else if (topLevelVarMap.has(arr.getName())) { + arrDeclarations = topLevelVarMap.get(arr.getName())!; + } + const res: Stmt[] = arrDeclarations.flatMap(d => { + // arr = %0 + // %0[0] = ... + if (!(d instanceof ArkAssignStmt)) { + return []; + } + const arrVal = d.getRightOp(); + if (!(arrVal instanceof Local)) { + return []; + } + return arrVal.getUsedStmts().filter(u => { + if (!(u instanceof ArkAssignStmt)) { + return false; + } + const left = u.getLeftOp(); + return left instanceof ArkArrayRef && left.getBase() === arrVal && left.getIndex() === index; + }); + }); + return res; + } + private isFromParameter(stmt: Stmt): ArkParameterRef | undefined { if (!(stmt instanceof ArkAssignStmt)) { return undefined; @@ -146,13 +345,13 @@ export class ObjectLiteralCheck implements BaseChecker { return undefined; } - private collectArgDefs(argIdx: number, callsites: Stmt[]): Stmt[] { - const getKey = (v: Value) => { - return v instanceof ArkInstanceFieldRef ? v.getFieldSignature() : v + private collectArgDefs(argIdx: number, callsites: Stmt[], scene: Scene): Stmt[] { + const getKey = (v: Value): Value | FieldSignature => { + return v instanceof ArkInstanceFieldRef ? v.getFieldSignature() : v; }; return callsites.flatMap(callsite => { const target: Value | FieldSignature = getKey(callsite.getInvokeExpr()!.getArg(argIdx)); - return Array.from(this.dvfg.getOrNewDVFGNode(callsite).getIncomingEdge()) + return Array.from(DVFGHelper.getOrNewDVFGNode(callsite, scene).getIncomingEdge()) .map(e => (e.getSrcNode() as DVFGNode).getStmt()) .filter(s => { return s instanceof ArkAssignStmt && target === getKey(s.getLeftOp()); @@ -160,15 +359,29 @@ export class ObjectLiteralCheck implements BaseChecker { }); } - private addIssueReport(stmt: Stmt, operand: Value) { + private addIssueReport(stmt: Stmt, operand: Value): void { const severity = this.rule.alert ?? this.metaData.severity; const warnInfo = this.getLineAndColumn(stmt, operand); - let defects = new Defects(warnInfo.line, warnInfo.startCol, warnInfo.endCol, this.metaData.description, severity, this.rule.ruleId, - warnInfo.filePath, this.metaData.ruleDocPath, true, false, false); + const problem = 'ObjectLiteral'; + const desc = `${this.metaData.description} (${this.rule.ruleId.replace('@migration/', '')})`; + let defects = new Defects( + warnInfo.line, + warnInfo.startCol, + warnInfo.endCol, + problem, + desc, + severity, + this.rule.ruleId, + warnInfo.filePath, + this.metaData.ruleDocPath, + true, + false, + false + ); this.issues.push(new IssueReport(defects, undefined)); } - private getLineAndColumn(stmt: Stmt, operand: Value) { + private getLineAndColumn(stmt: Stmt, operand: Value): WarnInfo { const arkFile = stmt.getCfg()?.getDeclaringMethod().getDeclaringArkFile(); const originPosition = stmt.getOperandOriginalPosition(operand); if (arkFile && originPosition) { @@ -182,4 +395,4 @@ export class ObjectLiteralCheck implements BaseChecker { } return { line: -1, startCol: -1, endCol: -1, filePath: '' }; } -} \ No newline at end of file +} diff --git a/ets2panda/linter/homecheck/src/checker/migration/ObservedDecoratorCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/ObservedDecoratorCheck.ts index 9b4ed0092e..a6a56e9b4d 100644 --- a/ets2panda/linter/homecheck/src/checker/migration/ObservedDecoratorCheck.ts +++ b/ets2panda/linter/homecheck/src/checker/migration/ObservedDecoratorCheck.ts @@ -13,20 +13,50 @@ * limitations under the License. */ -import { ArkAssignStmt, ArkClass, ArkField, ArkNewExpr, ClassType, Local, Scene } from "arkanalyzer"; +import path from 'path'; +import { + AbstractInvokeExpr, + ArkAssignStmt, + ArkClass, + ArkField, + ArkNewExpr, + ArkReturnStmt, + AstTreeUtils, + ClassType, + fileSignatureCompare, + Local, + Scene, + Type, +} from 'arkanalyzer'; import { ClassCategory } from 'arkanalyzer/lib/core/model/ArkClass'; import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; -import { BaseChecker, BaseMetaData } from "../BaseChecker"; -import { Rule, Defects, ClassMatcher, MatcherTypes, MatcherCallback } from "../../Index"; -import { IssueReport } from "../../model/Defects"; +import { BaseChecker, BaseMetaData } from '../BaseChecker'; +import { Rule, Defects, ClassMatcher, MatcherTypes, MatcherCallback } from '../../Index'; +import { IssueReport } from '../../model/Defects'; +import { RuleFix } from '../../model/Fix'; +import { FixUtils } from '../../utils/common/FixUtils'; +import { WarnInfo } from '../../utils/common/Utils'; const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'ObservedDecoratorCheck'); const gMetaData: BaseMetaData = { severity: 1, - ruleDocPath: "", - description: '' + ruleDocPath: '', + description: '', }; +const DECORATOR_SET: Set = new Set([ + 'State', + 'Prop', + 'Link', + 'Provide', + 'Consume', + 'LocalStorageProp', + 'LocalStorageLink', + 'StorageProp', + 'StorageLink', +]); + +// TODO: 需要考虑type alias、union type、intersection type中涉及class的场景 export class ObservedDecoratorCheck implements BaseChecker { readonly metaData: BaseMetaData = gMetaData; public rule: Rule; @@ -35,12 +65,13 @@ export class ObservedDecoratorCheck implements BaseChecker { private clsMatcher: ClassMatcher = { matcherType: MatcherTypes.CLASS, + category: [ClassCategory.STRUCT], }; public registerMatchers(): MatcherCallback[] { const matchClsCb: MatcherCallback = { matcher: this.clsMatcher, - callback: this.check + callback: this.check, }; return [matchClsCb]; } @@ -48,22 +79,30 @@ export class ObservedDecoratorCheck implements BaseChecker { public check = (arkClass: ArkClass): void => { const scene = arkClass.getDeclaringArkFile().getScene(); for (const field of arkClass.getFields()) { - if (!field.getDecorators().some(d => d.getKind() === 'State')) { + if (!field.getDecorators().some(d => DECORATOR_SET.has(d.getKind()))) { continue; } + // usedClasses用于记录field的初始化中涉及的所有class + let usedClasses: Set = new Set(); + // issueClasses用于记录usedClasses以及他们的所有父类 + let issueClasses: Set = new Set(); + // ArkAnalyzer此处有问题,若field的类型注解为unclear type,会用右边的替换左边的。 const fieldType = field.getType(); - if (!(fieldType instanceof ClassType)) { + const initializers = field.getInitializer(); + let canFindAllTargets = true; + + let locals: Set = new Set(); + + // field的初始化语句的最后一句,一定是将右边的value赋值给field,此处仍然判断一次,排除其他场景或者初始化语句为空的场景 + const lastStmt = initializers[initializers.length - 1]; + if (!(lastStmt instanceof ArkAssignStmt)) { continue; } - const fieldClass = scene.getClass(fieldType.getClassSignature()); - const initializers = field.getInitializer(); - let canfindAllTargets = true; - let targets: Set = new Set(); - if (fieldClass?.getCategory() === ClassCategory.CLASS) { - targets.add(fieldClass); + const start = lastStmt.getRightOp(); + // 直接对属性进行常量赋值属于这种场景 + if (!(start instanceof Local)) { + continue; } - let locals: Set = new Set(); - let start = (initializers[initializers.length - 1] as ArkAssignStmt).getRightOp() as Local; locals.add(start); for (const stmt of initializers.slice(0, -1).reverse()) { if (!(stmt instanceof ArkAssignStmt)) { @@ -81,46 +120,173 @@ export class ObservedDecoratorCheck implements BaseChecker { if (rightOp instanceof Local) { locals.add(rightOp); } else if (rightOp instanceof ArkNewExpr) { - canfindAllTargets = this.handleNewExpr(scene, rightOp, targets); + // 此处需要区分field = new cls()和field = {}两种场景,查找完毕需继续遍历stmts以解析条件表达式造成的多赋值场景 + canFindAllTargets = canFindAllTargets && this.handleNewExpr(scene, fieldType, rightOp, usedClasses); + } else if (rightOp instanceof AbstractInvokeExpr) { + canFindAllTargets = + canFindAllTargets && this.handleInvokeExpr(scene, fieldType, rightOp, usedClasses); } else { - canfindAllTargets = false; + // 对应场景为使用条件表达式cond ? 123 : 456赋值时 + continue; } } - for (const target of targets) { + for (const cls of usedClasses) { + issueClasses.add(cls); + this.getAllSuperClasses( + cls, + superCls => superCls.getCategory() === ClassCategory.CLASS && issueClasses.add(superCls) + ); + } + + for (const target of issueClasses) { + if (target.hasDecorator('Observed')) { + continue; + } const pos = this.getClassPos(target); - this.addIssueReport(pos); + const description = this.generateIssueDescription(field, target); + const ruleFix = this.generateRuleFix(pos, target) ?? undefined; + this.addIssueReport(pos, description, ruleFix); } - if (!canfindAllTargets) { + if (!canFindAllTargets) { const pos = this.getFieldPos(field); - this.addIssueReport(pos); + const description = this.generateIssueDescription(field, null, false); + this.addIssueReport(pos, description); } } }; - private handleNewExpr(scene: Scene, rightOp: ArkNewExpr, targets: Set): boolean { - let canfindAllTargets = true; - + // 此处需要区分field = new cls()和field = {}两种场景 + // 对于field = new cls()场景,需要查找此右边class的所有父class + // 对于field = {}场景,需要查找左边field类型为class时的所有父class + private handleNewExpr(scene: Scene, fieldType: Type, rightOp: ArkNewExpr, targets: Set): boolean { const target = scene.getClass(rightOp.getClassType().getClassSignature()); - if (target && !target.isAnonymousClass()) { + if (target === null) { + return false; + } + + if (!target.isAnonymousClass()) { + // 理论上来说ArkNewExpr中的class一定ClassCategory.CLASS,此处仍然显式的检查一次 + if (target.getCategory() !== ClassCategory.CLASS) { + return true; + } targets.add(target); - const superClasses = target.getAllHeritageClasses(); - for (const superCls of superClasses) { - if (superCls.getCategory() === ClassCategory.CLASS) { - targets.add(superCls); + return true; + } + + // 处理匿名类场景,若右边为object literal时,需考虑左边是什么类型注解,将涉及的class找出 + if (target.getCategory() !== ClassCategory.OBJECT) { + return true; + } + if (!(fieldType instanceof ClassType)) { + return true; + } + const fieldClass = scene.getClass(fieldType.getClassSignature()); + if (fieldClass === null) { + return false; + } + if (fieldClass.getCategory() !== ClassCategory.CLASS) { + return true; + } + targets.add(fieldClass); + return true; + } + + // 遍历此处的调用方法的所有return stmts,查找class + // 此处需要区分返回值为class和object literal两种场景 + // 对于返回值为class的场景,需要查找此class的所有父class + // 对于存在返回值为object literal的场景,需要查找左边field类型为class时的所有父class + private handleInvokeExpr( + scene: Scene, + fieldType: Type, + invokeExpr: AbstractInvokeExpr, + targets: Set + ): boolean { + let canFindAllTargets = true; + const callMethod = scene.getMethod(invokeExpr.getMethodSignature()); + if (callMethod === null) { + return false; + } + const stmts = callMethod.getBody()?.getCfg().getStmts(); + if (stmts === undefined) { + return false; + } + for (const stmt of stmts) { + if (!(stmt instanceof ArkReturnStmt)) { + continue; + } + const opType = stmt.getOp().getType(); + if (!(opType instanceof ClassType)) { + continue; + } + const returnClass = scene.getClass(opType.getClassSignature()); + if (returnClass === null) { + canFindAllTargets = false; + continue; + } + if (returnClass.getCategory() === ClassCategory.CLASS) { + targets.add(returnClass); + } else if (returnClass.getCategory() === ClassCategory.OBJECT) { + if (!(fieldType instanceof ClassType)) { + continue; + } + const leftClass = scene.getClass(fieldType.getClassSignature()); + if (leftClass === null) { + canFindAllTargets = false; + continue; + } + if (leftClass.getCategory() === ClassCategory.CLASS) { + targets.add(leftClass); } } + } + return canFindAllTargets; + } + + // 采用广度优先遍历方式,逐层获取该class的所有父类,一直查找到基类 + // arkanalyzer getAllHeritageClasses有点问题,对于未能推出来的父类会忽略,不加入列表中返回。 + private getAllSuperClasses(arkClass: ArkClass, callback: (value: ArkClass) => void): void { + let superClasses: Set = new Set(); + const classes = arkClass.getAllHeritageClasses(); + while (classes.length > 0) { + const superCls = classes.shift()!; + const superSuperCls = superCls.getAllHeritageClasses(); + callback(superCls); + + if (superSuperCls.length > 0) { + classes.push(...superSuperCls); + } + } + } + + private generateIssueDescription( + field: ArkField, + issueClass: ArkClass | null, + canFindAllTargets: boolean = true + ): string { + if (issueClass === null || !canFindAllTargets) { + return `can not find all classes, please check this field manually`; + } + const fieldLine = field.getOriginPosition().getLineNo(); + const fieldColumn = field.getOriginPosition().getColNo(); + + const fieldFileSig = field.getDeclaringArkClass().getDeclaringArkFile().getFileSignature(); + const issueClassSig = issueClass.getDeclaringArkFile().getFileSignature(); + let res = `but it's not be annotated by @Observed (arkui-data-observation)`; + if (fileSignatureCompare(fieldFileSig, issueClassSig)) { + res = `The class is used by state property in [${fieldLine}, ${fieldColumn}], ` + res; } else { - canfindAllTargets = false; + const filePath = path.normalize(fieldFileSig.getFileName()); + res = `The class is used by state property in file ${filePath} [${fieldLine}, ${fieldColumn}], ` + res; } - return canfindAllTargets; + return res; } - private getClassPos(cls: ArkClass): { line: number; startCol: number; endCol: number; filePath: string; } { + private getClassPos(cls: ArkClass): WarnInfo { const arkFile = cls.getDeclaringArkFile(); if (arkFile) { - const originPath = arkFile.getFilePath(); + const originPath = path.normalize(arkFile.getFilePath()); const line = cls.getLine(); const startCol = cls.getColumn(); const endCol = startCol; @@ -131,7 +297,7 @@ export class ObservedDecoratorCheck implements BaseChecker { } } - private getFieldPos(field: ArkField): { line: number; startCol: number; endCol: number; filePath: string; } { + private getFieldPos(field: ArkField): WarnInfo { const arkFile = field.getDeclaringArkClass().getDeclaringArkFile(); const pos = field.getOriginPosition(); if (arkFile && pos) { @@ -146,10 +312,52 @@ export class ObservedDecoratorCheck implements BaseChecker { } } - private addIssueReport(warnInfo: { line: number; startCol: number; endCol: number; filePath: string; }) { + private addIssueReport(warnInfo: WarnInfo, description: string, ruleFix?: RuleFix): void { + const problem = 'DataObservationNeedObserved'; const severity = this.rule.alert ?? this.metaData.severity; - let defects = new Defects(warnInfo.line, warnInfo.startCol, warnInfo.endCol, this.metaData.description, severity, this.rule.ruleId, - warnInfo.filePath, this.metaData.ruleDocPath, true, false, false); - this.issues.push(new IssueReport(defects, undefined)); + let defects = new Defects( + warnInfo.line, + warnInfo.startCol, + warnInfo.endCol, + problem, + description, + severity, + this.rule.ruleId, + warnInfo.filePath, + this.metaData.ruleDocPath, + true, + false, + true + ); + this.issues.push(new IssueReport(defects, ruleFix)); + if (ruleFix === undefined) { + defects.fixable = false; + } + } + + private generateRuleFix(warnInfo: WarnInfo, targetClass: ArkClass): RuleFix | null { + const arkFile = targetClass.getDeclaringArkFile(); + const sourceFile = AstTreeUtils.getASTNode(arkFile.getName(), arkFile.getCode()); + const startLineRange = FixUtils.getLineRange(sourceFile, warnInfo.line); + if (startLineRange === null) { + return null; + } + + const ruleFix = new RuleFix(); + ruleFix.range = startLineRange; + + const startLineStr = FixUtils.getSourceWithRange(sourceFile, startLineRange); + if (startLineStr === null) { + return null; + } + + const eol = FixUtils.getEolSymbol(sourceFile, warnInfo.line); + const startLineIndent = FixUtils.getIndentOfLine(sourceFile, warnInfo.line); + if (startLineIndent === null) { + return null; + } + const space = ' '; + ruleFix.text = `@Observed${eol}${space.repeat(startLineIndent)}${startLineStr}`; + return ruleFix; } -} \ No newline at end of file +} diff --git a/ets2panda/linter/homecheck/src/checker/migration/ThisBindCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/ThisBindCheck.ts index 65bb480443..d7496fca0a 100644 --- a/ets2panda/linter/homecheck/src/checker/migration/ThisBindCheck.ts +++ b/ets2panda/linter/homecheck/src/checker/migration/ThisBindCheck.ts @@ -13,40 +13,66 @@ * limitations under the License. */ -import { ArkAssignStmt, ArkIfStmt, ArkInstanceFieldRef, ArkInstanceInvokeExpr, ArkMethod, ClassType, FunctionType, Local, Stmt, Value } from "arkanalyzer"; +import { + ArkAssignStmt, + ArkIfStmt, + ArkInstanceFieldRef, + ArkInstanceInvokeExpr, + ArkMethod, + ClassType, + FunctionType, + Local, + Stmt, + Value, + Scene, + ArkNewArrayExpr, + ArkNewExpr, + ArkClass, + ClassSignature, +} from 'arkanalyzer'; import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; -import { BaseChecker, BaseMetaData } from "../BaseChecker"; -import { Rule, Defects, MatcherTypes, MethodMatcher, MatcherCallback } from "../../Index"; -import { IssueReport } from "../../model/Defects"; +import { BaseChecker, BaseMetaData } from '../BaseChecker'; +import { Rule, Defects, MatcherTypes, MethodMatcher, MatcherCallback } from '../../Index'; +import { IssueReport } from '../../model/Defects'; +import { WarnInfo } from '../../utils/common/Utils'; const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'ThisBindCheck'); -const gMetaData: BaseMetaData = { + +const ARKTS_RULE_ID = '@migration/arkts-instance-method-bind-this'; +const arktsMetaData: BaseMetaData = { + severity: 1, + ruleDocPath: '', + description: "Instance method shall bind the 'this' by default", +}; + +const ARKUI_RULE_ID = '@migration/arkui-buildparam-passing'; +const arkuiMetaData: BaseMetaData = { severity: 1, - ruleDocPath: "", - description: 'Instance method shall bind the \'this\' by dafault.' + ruleDocPath: '', + description: 'The execution context of the function annotated with @Builder is determined at the time of declaration. Please check the code carefully to ensure the correct function context', }; export class ThisBindCheck implements BaseChecker { - readonly metaData: BaseMetaData = gMetaData; + readonly metaData: BaseMetaData = arktsMetaData; public rule: Rule; public defects: Defects[] = []; public issues: IssueReport[] = []; private methodMatcher: MethodMatcher = { - matcherType: MatcherTypes.METHOD + matcherType: MatcherTypes.METHOD, }; public registerMatchers(): MatcherCallback[] { const methodCb: MatcherCallback = { matcher: this.methodMatcher, - callback: this.check - } + callback: this.check, + }; return [methodCb]; } - public check = (targetMtd: ArkMethod) => { + public check = (targetMtd: ArkMethod): void => { const file = targetMtd.getDeclaringArkFile(); - if (file.getName().includes("test.ets")) { + if (file.getName().includes('.test.ets')) { return; } const scene = file.getScene(); @@ -74,17 +100,15 @@ export class ThisBindCheck implements BaseChecker { if (!method || !method.getCfg() || !this.useThisInBody(method)) { continue; } - if (base.getName() === "this" && targetMtd.isAnonymousMethod()) { - continue; - } + const isBuilder = method.hasBuilderDecorator() || method.hasDecorator('LocalBuilder'); const leftOp = stmt.getLeftOp(); if (i + 1 >= stmts.length || !this.hasBindThis(leftOp, stmts[i + 1])) { if (!this.isSafeUse(leftOp)) { - this.addIssueReport(stmt, base); + this.addIssueReport(stmt, isBuilder, base, scene); } } } - } + }; private useThisInBody(method: ArkMethod): boolean { const thisInstance = (method.getThisInstance() as Local)!; @@ -128,21 +152,202 @@ export class ThisBindCheck implements BaseChecker { if (rightOp.getBase() !== base) { return false; } - if (rightOp.getMethodSignature().getMethodSubSignature().getMethodName() !== "bind") { + if (rightOp.getMethodSignature().getMethodSubSignature().getMethodName() !== 'bind') { return false; } return true; } - private addIssueReport(stmt: Stmt, operand: Value) { + private addIssueReport(stmt: ArkAssignStmt, isBuilder: boolean, operand: Value, scene: Scene): void { + if (isBuilder && this.isAssignToBuilderParam(stmt, scene)) { + this.reportArkUIIssue(stmt, operand); + } else { + this.reportArkTSIssue(stmt, operand); + } + } + + private isAssignToBuilderParam(assign: ArkAssignStmt, scene: Scene): boolean { + /** + * class CA { + * @Builder builder() { ... } + * build() { + * Column() { CB({ content: this.builder }) } + * } + * } + * class CB { + * @BuilderParam content: () => void + * } + * + * ================================================== + * class %AC2$CA.build { + * constructor() { ... } + * %instInit() { + * %0 = this.builder + * this.content = %0 + * } + * } + * class CA { + * ... + * build() { + * ... + * %3 = new %AC2$CA.build + * %3.constructor() + * %4 = new CB + * %4.constructor(%3) + * ... + * } + * ... + * } + */ + const currentMethod = assign.getCfg().getDeclaringMethod(); + if (currentMethod.getName() !== '%instInit') { + return false; + } + const currentClass = currentMethod.getDeclaringArkClass(); + if (!currentClass.isAnonymousClass()) { + return false; + } + const currentClassSig = currentClass.getSignature(); + + const leftOp = assign.getLeftOp(); + if (!(leftOp instanceof Local)) { + return false; + } + const usedStmts = leftOp.getUsedStmts(); + if (usedStmts.length !== 1) { + return false; + } + const usedStmt = usedStmts[0]; + if (!(usedStmt instanceof ArkAssignStmt)) { + return false; + } + const target = usedStmt.getLeftOp(); + if (!(target instanceof ArkInstanceFieldRef)) { + return false; + } + const baseTy = target.getBase().getType(); + if (!(baseTy instanceof ClassType)) { + return false; + } + if ((baseTy as ClassType).getClassSignature() !== currentClassSig) { + return false; + } + const fieldName = target.getFieldName(); + + const declaringClassName = currentClassSig.getDeclaringClassName(); + if (declaringClassName === currentClass.getName()) { + return false; + } + const declaringClass = currentClass.getDeclaringArkFile().getClassWithName(declaringClassName); + if (!declaringClass) { + return false; + } + let targetClassSig = this.findDefinitionOfAnonymousClass(declaringClass, currentClassSig); + if (!targetClassSig) { + return false; + } + const targetClass = scene.getClass(targetClassSig); + if (!targetClass) { + return false; + } + const arkField = targetClass.getFieldWithName(fieldName); + if (!arkField) { + return false; + } + return arkField.hasBuilderParamDecorator(); + } + + private findDefinitionOfAnonymousClass( + declaringClass: ArkClass, + anonymousClassSig: ClassSignature + ): ClassSignature | undefined { + for (const m of declaringClass.getMethods()) { + const stmts = m.getBody()?.getCfg().getStmts() ?? []; + for (const stmt of stmts) { + if (!(stmt instanceof ArkAssignStmt)) { + continue; + } + const rightOp = stmt.getRightOp(); + if (!(rightOp instanceof ArkNewExpr)) { + continue; + } + if (rightOp.getClassType().getClassSignature() !== anonymousClassSig) { + continue; + } + const local = stmt.getLeftOp() as Local; + const classSignature = this.processUsedStmts(local, anonymousClassSig); + if (!classSignature) { + continue; + } + return classSignature; + } + } + return undefined; + } + + private processUsedStmts(local: Local, anonymousClassSig: ClassSignature): ClassSignature | null { + for (const usedStmt of local.getUsedStmts()) { + const invoke = usedStmt.getInvokeExpr(); + if (!invoke) { + continue; + } + const sig = invoke.getMethodSignature(); + if (sig.getMethodSubSignature().getMethodName() !== 'constructor') { + continue; + } + if (sig.getDeclaringClassSignature() === anonymousClassSig) { + continue; + } + return sig.getDeclaringClassSignature(); + } + return null; + } + + private reportArkTSIssue(stmt: ArkAssignStmt, operand: Value): void { const severity = this.rule.alert ?? this.metaData.severity; const warnInfo = this.getLineAndColumn(stmt, operand); - let defects = new Defects(warnInfo.line, warnInfo.startCol, warnInfo.endCol, this.metaData.description, severity, this.rule.ruleId, - warnInfo.filePath, this.metaData.ruleDocPath, true, false, false); + const problem = 'DefaultBindThis'; + const desc = `${this.metaData.description} (${this.rule.ruleId.replace('@migration/', '')})`; + let defects = new Defects( + warnInfo.line, + warnInfo.startCol, + warnInfo.endCol, + problem, + desc, + severity, + ARKTS_RULE_ID, + warnInfo.filePath, + this.metaData.ruleDocPath, + true, + false, + false + ); + this.issues.push(new IssueReport(defects, undefined)); + } + + private reportArkUIIssue(stmt: ArkAssignStmt, operand: Value): void { + const severity = this.rule.alert ?? arkuiMetaData.severity; + const warnInfo = this.getLineAndColumn(stmt, operand); + const problem = 'BuilderParamContextChanged'; + const desc = `${arkuiMetaData.description} (${ARKUI_RULE_ID.replace('@migration/', '')})`; + let defects = new Defects( + warnInfo.line, + warnInfo.startCol, + warnInfo.endCol, + problem, + desc, + severity, + ARKUI_RULE_ID, + warnInfo.filePath, + arkuiMetaData.ruleDocPath, + true, + false, + false + ); this.issues.push(new IssueReport(defects, undefined)); } - private getLineAndColumn(stmt: Stmt, operand: Value) { + private getLineAndColumn(stmt: ArkAssignStmt, operand: Value): WarnInfo { const arkFile = stmt.getCfg()?.getDeclaringMethod().getDeclaringArkFile(); const originPosition = stmt.getOperandOriginalPosition(operand); if (arkFile && originPosition) { @@ -156,4 +361,4 @@ export class ThisBindCheck implements BaseChecker { } return { line: -1, startCol: -1, endCol: -1, filePath: '' }; } -} \ No newline at end of file +} diff --git a/ets2panda/linter/homecheck/src/checker/migration/Utils.ts b/ets2panda/linter/homecheck/src/checker/migration/Utils.ts new file mode 100644 index 0000000000..0992bcbe88 --- /dev/null +++ b/ets2panda/linter/homecheck/src/checker/migration/Utils.ts @@ -0,0 +1,152 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArkAssignStmt, ArkMethod, CallGraph, CallGraphBuilder, Local, LOG_MODULE_TYPE, Logger, Scene, Stmt, Value } from 'arkanalyzer/lib'; +import { WarnInfo } from '../../utils/common/Utils'; +import { Language } from 'arkanalyzer/lib/core/model/ArkFile'; +import { DVFG, DVFGNode } from 'arkanalyzer/lib/VFG/DVFG'; +import { DVFGBuilder } from 'arkanalyzer/lib/VFG/builder/DVFGBuilder'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'Utils'); + +export const CALL_DEPTH_LIMIT = 2; +export class CallGraphHelper { + private static cgInstance: CallGraph | null = null; + + public static getCGInstance(scene: Scene): CallGraph { + if (!this.cgInstance) { + this.cgInstance = new CallGraph(scene); + } + return this.cgInstance; + } +} + +export class GlobalCallGraphHelper { + private static cgInstance: CallGraph | null = null; + + public static getCGInstance(scene: Scene): CallGraph { + if (!this.cgInstance) { + this.cgInstance = new CallGraph(scene); + let cgBuilder = new CallGraphBuilder(this.cgInstance, scene); + cgBuilder.buildCHA4WholeProject(true); + } + return this.cgInstance; + } +} + +export class DVFGHelper { + private static dvfgInstance: DVFG; + private static dvfgBuilder: DVFGBuilder; + private static built: Set = new Set(); + + private static createDVFGInstance(scene: Scene): void { + if (!this.dvfgInstance) { + this.dvfgInstance = new DVFG(GlobalCallGraphHelper.getCGInstance(scene)); + this.dvfgBuilder = new DVFGBuilder(this.dvfgInstance, scene); + } + } + + public static buildSingleDVFG(method: ArkMethod, scene: Scene): void { + if (!this.dvfgInstance) { + this.createDVFGInstance(scene); + } + if (!this.built.has(method)) { + this.dvfgBuilder.buildForSingleMethod(method); + this.built.add(method); + } + } + + public static getOrNewDVFGNode(stmt: Stmt, scene: Scene): DVFGNode { + if (!this.dvfgInstance) { + this.createDVFGInstance(scene); + } + return this.dvfgInstance!.getOrNewDVFGNode(stmt); + } +} + +export const CALLBACK_METHOD_NAME: string[] = [ + 'onClick', // 点击事件,当用户点击组件时触发 + 'onTouch', // 触摸事件,当手指在组件上按下、滑动、抬起时触发 + 'onAppear', // 组件挂载显示时触发 + 'onDisAppear', // 组件卸载消失时触发 + 'onDragStart', // 拖拽开始事件,当组件被长按后开始拖拽时触发 + 'onDragEnter', // 拖拽进入组件范围时触发 + 'onDragMove', // 拖拽在组件范围内移动时触发 + 'onDragLeave', // 拖拽离开组件范围内时触发 + 'onDrop', // 拖拽释放目标,当在本组件范围内停止拖拽行为时触发 + 'onKeyEvent', // 按键事件,当组件获焦后,按键动作触发 + 'onFocus', // 焦点事件,当组件获取焦点时触发 + 'onBlur', // 当组件失去焦点时触发的回调 + 'onHover', // 鼠标悬浮事件,鼠标进入或退出组件时触发 + 'onMouse', // 鼠标事件,当鼠标按键点击或在组件上移动时触发 + 'onAreaChange', // 组件区域变化事件,组件尺寸、位置变化时触发 + 'onVisibleAreaChange', // 组件可见区域变化事件,组件在屏幕中的显示区域面积变化时触发 +]; + +export function getLanguageStr(language: Language): string { + let targetLan: string = ''; + switch (language) { + case Language.JAVASCRIPT: + targetLan = 'javascript'; + break; + case Language.TYPESCRIPT: + targetLan = 'typescript'; + break; + case Language.ARKTS1_1: + targetLan = 'arkts1.1'; + break; + case Language.ARKTS1_2: + targetLan = 'arkts1.2'; + break; + default: + break; + } + return targetLan; +} + +export function getLineAndColumn(stmt: Stmt, operand: Value): WarnInfo { + const arkFile = stmt.getCfg()?.getDeclaringMethod().getDeclaringArkFile(); + const originPosition = stmt.getOperandOriginalPosition(operand); + if (arkFile && originPosition) { + const originPath = arkFile.getFilePath(); + const line = originPosition.getFirstLine(); + const startCol = originPosition.getFirstCol(); + const endCol = startCol; + return { line, startCol, endCol, filePath: originPath }; + } else { + logger.debug('ArkFile is null.'); + } + return { line: -1, startCol: -1, endCol: -1, filePath: '' }; +} + +export function getGlobalsDefineInDefaultMethod(defaultMethod: ArkMethod): Map { + const globalVarMap: Map = new Map(); + const stmts = defaultMethod.getBody()?.getCfg().getStmts() ?? []; + for (const stmt of stmts) { + if (!(stmt instanceof ArkAssignStmt)) { + continue; + } + const leftOp = stmt.getLeftOp(); + if (!(leftOp instanceof Local)) { + continue; + } + const name = leftOp.getName(); + if (name.startsWith('%') || name === 'this') { + continue; + } + globalVarMap.set(name, [...(globalVarMap.get(name) ?? []), stmt]); + } + return globalVarMap; +} diff --git a/ets2panda/linter/homecheck/src/codeFix/FixEngine.ts b/ets2panda/linter/homecheck/src/codeFix/FixEngine.ts index 6b312508d7..483a60a3de 100644 --- a/ets2panda/linter/homecheck/src/codeFix/FixEngine.ts +++ b/ets2panda/linter/homecheck/src/codeFix/FixEngine.ts @@ -13,11 +13,11 @@ * limitations under the License. */ -import { Engine } from "../model/Engine"; -import { FixMode } from "../model/Fix"; -import { AIFixEngine } from "./engines/AIFixEngine"; -import { EsLintFixEngine } from "./engines/EsLintFixEngine"; -import { HomeCheckFixEngine } from "./engines/HomeCheckFixEngine"; +import { Engine } from '../model/Engine'; +import { FixMode } from '../model/Fix'; +import { AIFixEngine } from './engines/AIFixEngine'; +import { EsLintFixEngine } from './engines/EsLintFixEngine'; +import { HomeCheckFixEngine } from './engines/HomeCheckFixEngine'; export class FixEngine { public getEngine(mode: FixMode): Engine { diff --git a/ets2panda/linter/homecheck/src/codeFix/engines/AIFixEngine.ts b/ets2panda/linter/homecheck/src/codeFix/engines/AIFixEngine.ts index bcfd58c7a5..786d2863f3 100644 --- a/ets2panda/linter/homecheck/src/codeFix/engines/AIFixEngine.ts +++ b/ets2panda/linter/homecheck/src/codeFix/engines/AIFixEngine.ts @@ -13,10 +13,10 @@ * limitations under the License. */ -import { ArkFile } from "arkanalyzer"; -import { FileReports, IssueReport } from "../../model/Defects"; -import { Engine } from "../../model/Engine"; -import Logger, { LOG_MODULE_TYPE } from "arkanalyzer/lib/utils/logger"; +import { ArkFile } from 'arkanalyzer'; +import { FileReports, IssueReport } from '../../model/Defects'; +import { Engine } from '../../model/Engine'; +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'EsLintFixEngine'); diff --git a/ets2panda/linter/homecheck/src/codeFix/engines/EsLintFixEngine.ts b/ets2panda/linter/homecheck/src/codeFix/engines/EsLintFixEngine.ts index 0c1583ed96..a5f055289c 100644 --- a/ets2panda/linter/homecheck/src/codeFix/engines/EsLintFixEngine.ts +++ b/ets2panda/linter/homecheck/src/codeFix/engines/EsLintFixEngine.ts @@ -13,12 +13,12 @@ * limitations under the License. */ -import { ArkFile } from "arkanalyzer"; -import { FileReports, IssueReport } from "../../model/Defects"; -import { Engine } from "../../model/Engine"; -import { RuleFix } from "../../model/Fix"; -import Logger, { LOG_MODULE_TYPE } from "arkanalyzer/lib/utils/logger"; -import { FixUtils } from "../../utils/common/FixUtils"; +import { ArkFile } from 'arkanalyzer'; +import { FileReports, IssueReport } from '../../model/Defects'; +import { Engine } from '../../model/Engine'; +import { RuleFix } from '../../model/Fix'; +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; +import { FixUtils } from '../../utils/common/FixUtils'; const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'EsLintFixEngine'); const BOM = '\uFEFF'; @@ -28,9 +28,10 @@ let eof = '\r\n'; export class EsLintFixEngine implements Engine { applyFix(arkFile: ArkFile, fixIssues: IssueReport[], remainIssues: IssueReport[]): FileReports { let sourceText = arkFile.getCode(); - const bom = sourceText.startsWith(BOM) ? BOM : "", - text = bom ? sourceText.slice(1) : sourceText; - let lastPos = Number.NEGATIVE_INFINITY, output = bom; + const bom = sourceText.startsWith(BOM) ? BOM : ''; + let text = bom ? sourceText.slice(1) : sourceText; + let lastPos = Number.NEGATIVE_INFINITY; + let output = bom; eof = FixUtils.getTextEof(text) || eof; // issue非法数据检查及排序 const ret = this.checkAndSortIssues(fixIssues, remainIssues); @@ -53,11 +54,12 @@ export class EsLintFixEngine implements Engine { this.updateRemainIssues(text, issue, remainIssues, remainIssuesCopy); } output += text.slice(Math.max(0, lastPos)); - return { defects: remainIssues.map((issue => issue.defect)), output: bom + output, filePath: arkFile.getFilePath() } + return { defects: remainIssues.map((issue => issue.defect)), output: bom + output, filePath: arkFile.getFilePath() }; } private checkAndSortIssues(fixIssues: IssueReport[], remainIssues: IssueReport[]): { - fixIssues: IssueReport[], remainIssues: IssueReport[] } { + fixIssues: IssueReport[], remainIssues: IssueReport[] + } { const fixIssuesValid: IssueReport[] = []; fixIssues.forEach((issue) => { const fix = issue.fix as RuleFix; @@ -70,7 +72,7 @@ export class EsLintFixEngine implements Engine { return { fixIssues: fixIssuesValid.sort(this.compareIssueByRange), remainIssues: remainIssues.sort(this.compareIssueByLocation) }; } - private compareIssueByRange(issue1: IssueReport, issue2: IssueReport) { + private compareIssueByRange(issue1: IssueReport, issue2: IssueReport): number { let fix1 = issue1.fix; let fix2 = issue2.fix; if (FixUtils.isRuleFix(fix1) && FixUtils.isRuleFix(fix2)) { @@ -80,7 +82,7 @@ export class EsLintFixEngine implements Engine { } } - private compareIssueByLocation(a: IssueReport, b: IssueReport) { + private compareIssueByLocation(a: IssueReport, b: IssueReport): number { return a.defect.reportLine - b.defect.reportLine || a.defect.reportColumn - b.defect.reportColumn; } diff --git a/ets2panda/linter/homecheck/src/codeFix/engines/HomeCheckFixEngine.ts b/ets2panda/linter/homecheck/src/codeFix/engines/HomeCheckFixEngine.ts index bb634e8eb6..51268a1bc4 100644 --- a/ets2panda/linter/homecheck/src/codeFix/engines/HomeCheckFixEngine.ts +++ b/ets2panda/linter/homecheck/src/codeFix/engines/HomeCheckFixEngine.ts @@ -13,15 +13,16 @@ * limitations under the License. */ -import { ArkFile, SourceFilePrinter } from "arkanalyzer"; -import { FileReports, IssueReport } from "../../model/Defects"; -import { Engine } from "../../model/Engine"; -import { FunctionFix } from "../../model/Fix"; -import path from "path"; -import { removeSync } from "fs-extra"; -import { FileUtils, WriteFileMode } from "../../utils/common/FileUtils"; -import Logger, { LOG_MODULE_TYPE } from "arkanalyzer/lib/utils/logger"; -import { FixUtils } from "../../utils/common/FixUtils"; +import { ArkFile, SourceFilePrinter } from 'arkanalyzer'; +import { FileReports, IssueReport } from '../../model/Defects'; +import { Engine } from '../../model/Engine'; +import { FunctionFix } from '../../model/Fix'; +import path from 'path'; +// @ts-ignore +import { removeSync } from 'fs-extra'; +import { FileUtils, WriteFileMode } from '../../utils/common/FileUtils'; +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; +import { FixUtils } from '../../utils/common/FixUtils'; const FIX_OUTPUT_DIR = './fixedCode'; @@ -61,7 +62,7 @@ export class HomeCheckFixEngine implements Engine { break; } } - return {defects: remainIssues.map((issue => issue.defect)), output: '', filePath: fixPath}; + return { defects: remainIssues.map((issue => issue.defect)), output: '', filePath: fixPath }; } private arkFileToFile(arkFile: ArkFile, outputPath: string): boolean { diff --git a/ets2panda/linter/homecheck/src/matcher/Matchers.ts b/ets2panda/linter/homecheck/src/matcher/Matchers.ts index c817e6c135..2a651d2d1f 100644 --- a/ets2panda/linter/homecheck/src/matcher/Matchers.ts +++ b/ets2panda/linter/homecheck/src/matcher/Matchers.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,8 +13,8 @@ * limitations under the License. */ -import { ArkField, ArkFile, ArkMethod, ArkNamespace, Scene } from "arkanalyzer"; -import { ArkClass, ClassCategory } from "arkanalyzer/lib/core/model/ArkClass"; +import { ArkField, ArkFile, ArkMethod, ArkNamespace, Scene } from 'arkanalyzer'; +import { ArkClass, ClassCategory } from 'arkanalyzer/lib/core/model/ArkClass'; export enum MethodCategory { Accessor = 0, diff --git a/ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchClass.ts b/ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchClass.ts index e9bb0cf523..1e1565a7c1 100644 --- a/ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchClass.ts +++ b/ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchClass.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ import { ArkClass, ArkFile } from 'arkanalyzer'; import { ClassMatcher, isMatchedFile, isMatchedNamespace, isMatchedClass } from '../Matchers'; -export function matchClass(arkFiles: ArkFile[], matcher: ClassMatcher, callback: Function) { +export function matchClass(arkFiles: ArkFile[], matcher: ClassMatcher, callback: Function): void { for (let arkFile of arkFiles) { if (matcher.file && !isMatchedFile(arkFile, matcher.file)) { continue; @@ -31,7 +31,7 @@ export function matchClass(arkFiles: ArkFile[], matcher: ClassMatcher, callback: } } -function matchClassProcess(matcher: ClassMatcher, classes: ArkClass[], callback: Function) { +function matchClassProcess(matcher: ClassMatcher, classes: ArkClass[], callback: Function): void { for (const arkClass of classes) { if (isMatchedClass(arkClass, [matcher])) { callback(arkClass); diff --git a/ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchFields.ts b/ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchFields.ts index 5e4d3496ab..f42fd5d703 100644 --- a/ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchFields.ts +++ b/ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchFields.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -17,7 +17,7 @@ import { ArkClass, ArkFile } from 'arkanalyzer'; import { isMatchedFile, isMatchedNamespace, isMatchedClass, FieldMatcher, isMatchedField } from '../Matchers'; -export function matchFields(arkFiles: ArkFile[], matcher: FieldMatcher, callback: Function) { +export function matchFields(arkFiles: ArkFile[], matcher: FieldMatcher, callback: Function): void { for (let arkFile of arkFiles) { if (matcher.file && !isMatchedFile(arkFile, matcher.file)) { continue; @@ -32,7 +32,7 @@ export function matchFields(arkFiles: ArkFile[], matcher: FieldMatcher, callback } } -function matchFieldsInClasses(matcher: FieldMatcher, classes: ArkClass[], callback: Function) { +function matchFieldsInClasses(matcher: FieldMatcher, classes: ArkClass[], callback: Function): void { for (const arkClass of classes) { if (matcher.class && !isMatchedClass(arkClass, matcher.class)) { continue; diff --git a/ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchFiles.ts b/ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchFiles.ts index cd56ad20d0..560fa54470 100644 --- a/ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchFiles.ts +++ b/ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchFiles.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ import { ArkFile } from 'arkanalyzer'; import { FileMatcher, isMatchedFile } from '../Matchers'; -export function matchFiles(arkFiles: ArkFile[], matcher: FileMatcher, callback: Function) { +export function matchFiles(arkFiles: ArkFile[], matcher: FileMatcher, callback: Function): void { for (let arkFile of arkFiles) { if (isMatchedFile(arkFile, [matcher])) { callback(arkFile); diff --git a/ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchMethods.ts b/ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchMethods.ts index 881cab942f..de9b782bf6 100644 --- a/ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchMethods.ts +++ b/ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchMethods.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -17,7 +17,7 @@ import { ArkClass, ArkFile } from 'arkanalyzer'; import { MethodMatcher, isMatchedFile, isMatchedNamespace, isMatchedClass, isMatchedMethod } from '../Matchers'; -export function matchMethods(arkFiles: ArkFile[], matcher: MethodMatcher, callback: Function) { +export function matchMethods(arkFiles: ArkFile[], matcher: MethodMatcher, callback: Function): void { for (let arkFile of arkFiles) { if (matcher.file && !isMatchedFile(arkFile, matcher.file)) { continue; @@ -32,7 +32,7 @@ export function matchMethods(arkFiles: ArkFile[], matcher: MethodMatcher, callba } } -function matchMethodsInClasses(matcher: MethodMatcher, classes: ArkClass[], callback: Function) { +function matchMethodsInClasses(matcher: MethodMatcher, classes: ArkClass[], callback: Function): void { for (const arkClass of classes) { if (matcher.class && !isMatchedClass(arkClass, matcher.class)) { continue; diff --git a/ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchNameSpaces.ts b/ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchNameSpaces.ts index 4b628c28ba..82b42d2ad6 100644 --- a/ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchNameSpaces.ts +++ b/ets2panda/linter/homecheck/src/matcher/matcherAdapter/matchNameSpaces.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,7 @@ import { ArkFile } from 'arkanalyzer'; import { NamespaceMatcher, isMatchedFile, isMatchedNamespace } from '../Matchers'; -export function matchNameSpaces(arkFiles: ArkFile[], matcher: NamespaceMatcher, callback: Function) { +export function matchNameSpaces(arkFiles: ArkFile[], matcher: NamespaceMatcher, callback: Function): void { for (let arkFile of arkFiles) { if (matcher.file && !isMatchedFile(arkFile, matcher.file)) { continue; diff --git a/ets2panda/linter/homecheck/src/model/Defects.ts b/ets2panda/linter/homecheck/src/model/Defects.ts index 0338b8ae30..cf38e10aff 100644 --- a/ets2panda/linter/homecheck/src/model/Defects.ts +++ b/ets2panda/linter/homecheck/src/model/Defects.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,31 +12,33 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { AIFix, FunctionFix, RuleFix } from "./Fix"; +import { AIFix, FunctionFix, RuleFix } from './Fix'; export const engine = { engineName: '' -} +}; export class Defects { reportLine: number; reportColumn: number; + problem: string = ''; description: string = ''; - severity: number = -1; // 0:info, 1:warning, 2:error + severity: number = -1; // 0:info, 1:warning, 2:error ruleId: string = '@perforce/'; - mergeKey: string = ''; // 文件路径%行号%开始列号%结束列号%规则%规则描述 + mergeKey: string = ''; // 文件路径%行号%开始列号%结束列号%规则%规则描述 ruleDocPath: string = 'doc/.md'; disabled: boolean = true; checked: boolean = false; - fixable: boolean = false; // 是否可以修复 - fixKey: string = ''; // 行号%开始列号%结束列号%规则id + fixable: boolean = false; // 是否可以修复 + fixKey: string = ''; // 行号%开始列号%结束列号%规则id showIgnoreIcon: boolean = true; engineName: string = engine.engineName; - constructor(reportLine: number, reportColumn: number, endColumn: number, description: string, severity: number, ruleId: string, + constructor(reportLine: number, reportColumn: number, endColumn: number, problem: string, description: string, severity: number, ruleId: string, filePath: string, ruleDocPath: string, disabled: boolean, checked: boolean, fixable: boolean, showIgnoreIcon: boolean = true) { this.reportLine = reportLine; this.reportColumn = reportColumn; + this.problem = problem; this.description = description; this.severity = severity; this.ruleId = ruleId; diff --git a/ets2panda/linter/homecheck/src/model/Engine.ts b/ets2panda/linter/homecheck/src/model/Engine.ts index 64c09751f9..7231f9fadd 100644 --- a/ets2panda/linter/homecheck/src/model/Engine.ts +++ b/ets2panda/linter/homecheck/src/model/Engine.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,8 +13,8 @@ * limitations under the License. */ -import { ArkFile } from "arkanalyzer"; -import { FileReports, IssueReport } from "./Defects"; +import { ArkFile } from 'arkanalyzer'; +import { FileReports, IssueReport } from './Defects'; export interface Engine { /** diff --git a/ets2panda/linter/homecheck/src/model/File2Check.ts b/ets2panda/linter/homecheck/src/model/File2Check.ts index 87465db69c..ecfc86270a 100644 --- a/ets2panda/linter/homecheck/src/model/File2Check.ts +++ b/ets2panda/linter/homecheck/src/model/File2Check.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,24 +12,24 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { ArkFile } from "arkanalyzer"; -import { BaseChecker } from "../checker/BaseChecker"; -import { MatcherTypes } from "../matcher/Matchers"; -import { matchFiles } from "../matcher/matcherAdapter/matchFiles"; -import { matchNameSpaces } from "../matcher/matcherAdapter/matchNameSpaces"; -import { matchClass } from "../matcher/matcherAdapter/matchClass"; -import { matchMethods } from "../matcher/matcherAdapter/matchMethods"; -import { matchFields } from "../matcher/matcherAdapter/matchFields"; -import { FileUtils } from "../utils/common/FileUtils"; -import { filterDisableIssue } from "../utils/common/Disable"; -import Logger, { LOG_MODULE_TYPE } from "arkanalyzer/lib/utils/logger"; -import { IssueReport } from "./Defects"; +import { ArkFile } from 'arkanalyzer'; +import { BaseChecker } from '../checker/BaseChecker'; +import { MatcherTypes } from '../matcher/Matchers'; +import { matchFiles } from '../matcher/matcherAdapter/matchFiles'; +import { matchNameSpaces } from '../matcher/matcherAdapter/matchNameSpaces'; +import { matchClass } from '../matcher/matcherAdapter/matchClass'; +import { matchMethods } from '../matcher/matcherAdapter/matchMethods'; +import { matchFields } from '../matcher/matcherAdapter/matchFields'; +import { FileUtils } from '../utils/common/FileUtils'; +import { filterDisableIssue } from '../utils/common/Disable'; +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; +import { IssueReport } from './Defects'; const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'File2Check'); export class File2Check { public arkFile: ArkFile; - public enabledRuleCheckerMap: Map = new Map(); // TODO: key改为枚举 + public enabledRuleCheckerMap: Map = new Map(); // TODO: key改为枚举 public issues: IssueReport[] = []; private flMatcherMap = new Map(); @@ -38,14 +38,13 @@ export class File2Check { private mtdMatcherMap = new Map(); private fieldMatcherMap = new Map(); - constructor() { - } + constructor() {} - public addChecker(ruleId: string, checker: BaseChecker) { + public addChecker(ruleId: string, checker: BaseChecker): void { this.enabledRuleCheckerMap.set(ruleId, checker); } - public collectMatcherCallbacks() { + public collectMatcherCallbacks(): void { this.enabledRuleCheckerMap.forEach(checker => { const matcherCallbacks = checker.registerMatchers(); matcherCallbacks.forEach(obj => { @@ -68,50 +67,52 @@ export class File2Check { this.fieldMatcherMap.set(matcher, callback); break; } - }) + }); }); } - public async emitCheck() { + public async emitCheck(): Promise { this.flMatcherMap.forEach((callback, matcher) => { - matchFiles([this.arkFile], matcher, callback) + matchFiles([this.arkFile], matcher, callback); }); this.nsMatcherMap.forEach((callback, matcher) => { - matchNameSpaces([this.arkFile], matcher, callback) + matchNameSpaces([this.arkFile], matcher, callback); }); this.clsMatcherMap.forEach((callback, matcher) => { - matchClass([this.arkFile], matcher, callback) + matchClass([this.arkFile], matcher, callback); }); this.mtdMatcherMap.forEach((callback, matcher) => { - matchMethods([this.arkFile], matcher, callback) + matchMethods([this.arkFile], matcher, callback); }); this.fieldMatcherMap.forEach((callback, matcher) => { - matchFields([this.arkFile], matcher, callback) + matchFields([this.arkFile], matcher, callback); }); } - public collectIssues() { + public collectIssues(): void { this.enabledRuleCheckerMap.forEach((v, k) => { - this.issues.push(...(v.issues?.reduce((acc, cur) => { - if (acc.some((item) => item.defect.mergeKey === cur.defect.mergeKey)) { - logger.debug('Skip the repeated issue, please check. issue.mergeKey = ' + cur.defect.mergeKey); - } else { - acc.push(cur); - } - return acc; - }, [] as IssueReport[]))); + this.issues.push( + ...v.issues?.reduce((acc, cur) => { + if (acc.some(item => item.defect.mergeKey === cur.defect.mergeKey)) { + logger.debug('Skip the repeated issue, please check. issue.mergeKey = ' + cur.defect.mergeKey); + } else { + acc.push(cur); + } + return acc; + }, [] as IssueReport[]) + ); }); } - public async checkDisable() { + public async checkDisable(): Promise { const fileLineList = await FileUtils.readLinesFromFile(this.arkFile.getFilePath()); - this.issues = filterDisableIssue(fileLineList, this.issues); + this.issues = await filterDisableIssue(fileLineList, this.issues, this.arkFile.getFilePath()); } - public async run() { + public async run(): Promise { this.collectMatcherCallbacks(); await this.emitCheck(); this.collectIssues(); await this.checkDisable(); } -} \ No newline at end of file +} diff --git a/ets2panda/linter/homecheck/src/model/Fix.ts b/ets2panda/linter/homecheck/src/model/Fix.ts index 12dcdc4152..459037c220 100644 --- a/ets2panda/linter/homecheck/src/model/Fix.ts +++ b/ets2panda/linter/homecheck/src/model/Fix.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/ets2panda/linter/homecheck/src/model/Interfaces.ts b/ets2panda/linter/homecheck/src/model/Interfaces.ts index f0da83d853..e357b58377 100644 --- a/ets2panda/linter/homecheck/src/model/Interfaces.ts +++ b/ets2panda/linter/homecheck/src/model/Interfaces.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -21,11 +21,11 @@ export interface ImageInfo { export type ImagesInfo = { images?: ImageInfo[] -} & ImageInfo +} & ImageInfo; export interface ImageData { validate: (intput: Uint8Array) => boolean; - calculate: (input: Uint8Array, filepath?: string) => ImagesInfo + calculate: (input: Uint8Array, filepath?: string) => ImagesInfo; } export interface IAttributes { diff --git a/ets2panda/linter/homecheck/src/model/Message.ts b/ets2panda/linter/homecheck/src/model/Message.ts index a0a3a4d16d..b559150354 100644 --- a/ets2panda/linter/homecheck/src/model/Message.ts +++ b/ets2panda/linter/homecheck/src/model/Message.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -25,7 +25,7 @@ export interface Message { progressNotify(progress: number, msg: string): void; } -export class defaultMessage implements Message { +export class DefaultMessage implements Message { /** * 发送消息 * diff --git a/ets2panda/linter/homecheck/src/model/NumberValue.ts b/ets2panda/linter/homecheck/src/model/NumberValue.ts index 67d6cf4995..bf79103645 100644 --- a/ets2panda/linter/homecheck/src/model/NumberValue.ts +++ b/ets2panda/linter/homecheck/src/model/NumberValue.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/ets2panda/linter/homecheck/src/model/Project2Check.ts b/ets2panda/linter/homecheck/src/model/Project2Check.ts index 6aad5f1aae..3e9c1bf9ed 100644 --- a/ets2panda/linter/homecheck/src/model/Project2Check.ts +++ b/ets2panda/linter/homecheck/src/model/Project2Check.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,25 +12,28 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { ArkFile } from "arkanalyzer"; -import { BaseChecker } from "../checker/BaseChecker"; -import Logger, { LOG_MODULE_TYPE } from "arkanalyzer/lib/utils/logger"; -import { MatcherTypes } from "../matcher/Matchers"; -import { matchFiles } from "../matcher/matcherAdapter/matchFiles"; -import { matchNameSpaces } from "../matcher/matcherAdapter/matchNameSpaces"; -import { matchClass } from "../matcher/matcherAdapter/matchClass"; -import { matchMethods } from "../matcher/matcherAdapter/matchMethods"; -import { matchFields } from "../matcher/matcherAdapter/matchFields"; -import { FileUtils } from "../utils/common/FileUtils"; -import { filterDisableIssue } from "../utils/common/Disable"; -import { IssueReport } from "./Defects"; -import { Rule } from "./Rule"; + +import * as fs from 'fs'; +import { ArkFile } from 'arkanalyzer'; +import { BaseChecker } from '../checker/BaseChecker'; +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; +import { MatcherTypes } from '../matcher/Matchers'; +import { matchFiles } from '../matcher/matcherAdapter/matchFiles'; +import { matchNameSpaces } from '../matcher/matcherAdapter/matchNameSpaces'; +import { matchClass } from '../matcher/matcherAdapter/matchClass'; +import { matchMethods } from '../matcher/matcherAdapter/matchMethods'; +import { matchFields } from '../matcher/matcherAdapter/matchFields'; +import { FileUtils } from '../utils/common/FileUtils'; +import { filterDisableIssue } from '../utils/common/Disable'; +import { IssueReport } from './Defects'; +import { Rule } from './Rule'; const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'Project2Check'); export class Project2Check { public arkFiles: ArkFile[]; - public enabledRuleCheckerMap: Map = new Map(); // TODO: key改为枚举 + // TODO: key改为枚举 + public enabledRuleCheckerMap: Map = new Map(); public issues: IssueReport[] = []; public ruleMap: Map = new Map(); @@ -44,11 +47,11 @@ export class Project2Check { constructor() { } - public addChecker(ruleId: string, checker: BaseChecker) { + public addChecker(ruleId: string, checker: BaseChecker): void { this.enabledRuleCheckerMap.set(ruleId, checker); } - public collectMatcherCallbacks() { + public collectMatcherCallbacks(): void { this.enabledRuleCheckerMap.forEach(checker => { const matcherCallbacks = checker.registerMatchers(); matcherCallbacks.forEach(obj => { @@ -77,28 +80,28 @@ export class Project2Check { default: break; } - }) + }); }); } - public async emitCheck() { + public async emitCheck(): Promise { await Promise.all(Array.from(this.enabledRuleCheckerMap.values()).map(checker => { try { this.processSceneCallbacks(); this.flMatcherMap.forEach((callback, matcher) => { - matchFiles(this.arkFiles, matcher, callback) + matchFiles(this.arkFiles, matcher, callback); }); this.nsMatcherMap.forEach((callback, matcher) => { - matchNameSpaces(this.arkFiles, matcher, callback) + matchNameSpaces(this.arkFiles, matcher, callback); }); this.clsMatcherMap.forEach((callback, matcher) => { - matchClass(this.arkFiles, matcher, callback) + matchClass(this.arkFiles, matcher, callback); }); this.mtdMatcherMap.forEach((callback, matcher) => { - matchMethods(this.arkFiles, matcher, callback) + matchMethods(this.arkFiles, matcher, callback); }); this.fieldMatcherMap.forEach((callback, matcher) => { - matchFields(this.arkFiles, matcher, callback) + matchFields(this.arkFiles, matcher, callback); }); } catch (error) { logger.error(`Checker ${checker.rule.ruleId} error: `, error); @@ -118,7 +121,7 @@ export class Project2Check { } } - public collectIssues() { + public collectIssues(): void { this.enabledRuleCheckerMap.forEach((v, k) => { this.issues.push(...(v.issues?.reduce((acc, cur) => { if (acc.some((item) => item.defect.mergeKey === cur.defect.mergeKey)) { @@ -157,12 +160,15 @@ export class Project2Check { this.issues = Array.from(issueMap.values()); } - public async checkDisable() { + public async checkDisable(): Promise { let filtedIssues: IssueReport[] = []; for (const issue of this.issues) { const filePath = issue.defect.mergeKey.split('%')[0]; + if (!fs.existsSync(filePath)) { + continue; + } const fileLineList = await FileUtils.readLinesFromFile(filePath); - const filtedResult = filterDisableIssue(fileLineList, [issue]); + const filtedResult = await filterDisableIssue(fileLineList, [issue], filePath); if (filtedResult.length > 0) { filtedIssues = filtedIssues.concat(filtedResult[0]); } @@ -170,7 +176,7 @@ export class Project2Check { this.issues = filtedIssues; } - public async run() { + public async run(): Promise { this.collectMatcherCallbacks(); await this.emitCheck(); this.collectIssues(); diff --git a/ets2panda/linter/homecheck/src/model/ProjectConfig.ts b/ets2panda/linter/homecheck/src/model/ProjectConfig.ts index 5d17f94620..7a5c7cbdfb 100644 --- a/ets2panda/linter/homecheck/src/model/ProjectConfig.ts +++ b/ets2panda/linter/homecheck/src/model/ProjectConfig.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,6 +13,7 @@ * limitations under the License. */ +import { LOG_LEVEL } from 'arkanalyzer'; import { Language } from 'arkanalyzer/lib/core/model/ArkFile'; export class ProjectConfig { @@ -31,6 +32,9 @@ export class ProjectConfig { sdksThirdParty: string[]; arkCheckPath: string; product: string; + logLevel: LOG_LEVEL; + arkAnalyzerLogLevel: LOG_LEVEL; + // [filePath, languageTag] or [folderPath, languageTag] languageTags: Map; @@ -55,6 +59,8 @@ export class ProjectConfig { this.product = config.product ?? ''; this.languageTags = config.languageTags ?? new Map(); this.fileOrFolderToCheck = config.fileOrFolderToCheck ?? []; + this.logLevel = config.logLevel ?? LOG_LEVEL.INFO; + this.arkAnalyzerLogLevel = config.arkAnalyzerLogLevel ?? LOG_LEVEL.ERROR; } } diff --git a/ets2panda/linter/homecheck/src/model/Rule.ts b/ets2panda/linter/homecheck/src/model/Rule.ts index 71a912835f..b0275c3c4f 100644 --- a/ets2panda/linter/homecheck/src/model/Rule.ts +++ b/ets2panda/linter/homecheck/src/model/Rule.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,9 +16,9 @@ export class Rule { ruleId: string; alert: ALERT_LEVEL; - allowExpressions: boolean - ignoreRestArgs: boolean - option: Object[] = [] + allowExpressions: boolean; + ignoreRestArgs: boolean; + option: Object[] = []; constructor(ruleId: string, alert: ALERT_LEVEL = ALERT_LEVEL.SUGGESTION) { this.ruleId = ruleId; diff --git a/ets2panda/linter/homecheck/src/model/RuleConfig.ts b/ets2panda/linter/homecheck/src/model/RuleConfig.ts index 281f4bc08a..16d5f737aa 100644 --- a/ets2panda/linter/homecheck/src/model/RuleConfig.ts +++ b/ets2panda/linter/homecheck/src/model/RuleConfig.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,7 +13,7 @@ * limitations under the License. */ -import { GlobMatch } from "../utils/common/GlobMatch"; +import { GlobMatch } from '../utils/common/GlobMatch'; export class RuleConfig { public files: GlobMatch; diff --git a/ets2panda/linter/homecheck/src/model/Scope.ts b/ets2panda/linter/homecheck/src/model/Scope.ts index 0710a9a41f..3f4a98ca50 100644 --- a/ets2panda/linter/homecheck/src/model/Scope.ts +++ b/ets2panda/linter/homecheck/src/model/Scope.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,9 +12,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { BasicBlock } from "arkanalyzer"; +import { BasicBlock } from 'arkanalyzer'; import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; -import { Variable } from "./Variable"; +import { Variable } from './Variable'; const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'Scope'); diff --git a/ets2panda/linter/homecheck/src/model/SparseArrayValue.ts b/ets2panda/linter/homecheck/src/model/SparseArrayValue.ts index 59f6931abd..16aa478599 100644 --- a/ets2panda/linter/homecheck/src/model/SparseArrayValue.ts +++ b/ets2panda/linter/homecheck/src/model/SparseArrayValue.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -24,11 +24,11 @@ export class SparseArrayValue { this.baseStr = baseStr; this.valStr = valStr; this.fulBaseStr = this.baseStr + this.valStr; - if (this.sparseArrayType == SparseArrayType.NEW_ARRAY) { + if (this.sparseArrayType === SparseArrayType.NEW_ARRAY) { this.fulStmtStr = this.fulBaseStr + ')'; - } else if (this.sparseArrayType == SparseArrayType.ARRAY_RIGHT) { + } else if (this.sparseArrayType === SparseArrayType.ARRAY_RIGHT) { this.fulStmtStr = this.fulBaseStr + ']'; - } else if (this.sparseArrayType == SparseArrayType.ARRAY_LEFT) { + } else if (this.sparseArrayType === SparseArrayType.ARRAY_LEFT) { this.fulStmtStr = this.fulBaseStr + ']'; } else { this.fulStmtStr = this.fulBaseStr; diff --git a/ets2panda/linter/homecheck/src/model/StmtExt.ts b/ets2panda/linter/homecheck/src/model/StmtExt.ts index 2d87c87ae4..4cc5550103 100644 --- a/ets2panda/linter/homecheck/src/model/StmtExt.ts +++ b/ets2panda/linter/homecheck/src/model/StmtExt.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,8 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { Stmt } from "arkanalyzer"; -import { Scope } from "./Scope"; +import { Stmt } from 'arkanalyzer'; +import { Scope } from './Scope'; export class StmtExt extends Stmt { scope: Scope; diff --git a/ets2panda/linter/homecheck/src/model/VarInfo.ts b/ets2panda/linter/homecheck/src/model/VarInfo.ts index 33534649b2..f0b4d33849 100644 --- a/ets2panda/linter/homecheck/src/model/VarInfo.ts +++ b/ets2panda/linter/homecheck/src/model/VarInfo.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,8 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { Stmt } from "arkanalyzer"; -import { Scope } from "./Scope"; +import { Stmt } from 'arkanalyzer'; +import { Scope } from './Scope'; export class VarInfo { stmt: Stmt; diff --git a/ets2panda/linter/homecheck/src/model/Variable.ts b/ets2panda/linter/homecheck/src/model/Variable.ts index 2066a30d58..b9d4ea86e6 100644 --- a/ets2panda/linter/homecheck/src/model/Variable.ts +++ b/ets2panda/linter/homecheck/src/model/Variable.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,8 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { Local, Stmt } from "arkanalyzer"; -import { VarInfo } from "./VarInfo"; +import { Local, Stmt } from 'arkanalyzer'; +import { VarInfo } from './VarInfo'; export class Variable { defStmt: Stmt; @@ -27,6 +27,6 @@ export class Variable { } public getName(): string { - return (this.defStmt.getDef() as Local).getName(); + return (this.defStmt.getDef() as Local).getName(); } } \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/run.ts b/ets2panda/linter/homecheck/src/run.ts index 5196e1de7d..6b468c1088 100644 --- a/ets2panda/linter/homecheck/src/run.ts +++ b/ets2panda/linter/homecheck/src/run.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,6 +13,6 @@ * limitations under the License. */ -import { run } from "./Main"; +import { run } from './Main'; run(); \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/runTool.ts b/ets2panda/linter/homecheck/src/runTool.ts index 530d825115..766a459f7c 100644 --- a/ets2panda/linter/homecheck/src/runTool.ts +++ b/ets2panda/linter/homecheck/src/runTool.ts @@ -13,9 +13,9 @@ * limitations under the License. */ -import { ConfigUtils } from "./utils/common/ConfigUtils"; -import { Utils } from "./utils/common/Utils"; -import { MigrationTool } from "./tools/migrationTool/MigrationTool"; +import { ConfigUtils } from './utils/common/ConfigUtils'; +import { Utils } from './utils/common/Utils'; +import { MigrationTool } from './tools/migrationTool/MigrationTool'; async function run(): Promise { const argvObj = Utils.parseCliOptions(process.argv); diff --git a/ets2panda/linter/homecheck/src/tools/BuildModuleChains.ts b/ets2panda/linter/homecheck/src/tools/BuildModuleChains.ts index 1bb83d4672..2d0d6ef9c4 100644 --- a/ets2panda/linter/homecheck/src/tools/BuildModuleChains.ts +++ b/ets2panda/linter/homecheck/src/tools/BuildModuleChains.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,10 +13,12 @@ * limitations under the License. */ -import { AbstractFieldRef, ArkAssignStmt, ArkFile, ArkIfStmt, ArkInvokeStmt, ArkMethod, ArkNamespace, ArkNewExpr, +import { + AbstractFieldRef, ArkAssignStmt, ArkFile, ArkIfStmt, ArkInvokeStmt, ArkMethod, ArkNamespace, ArkNewExpr, ArkNormalBinopExpr, ArkStaticInvokeExpr, ArkUnopExpr, ClassSignature, ClassType, DEFAULT_ARK_CLASS_NAME, FunctionType, LocalSignature, MethodSignature, NamespaceSignature, Scene, Signature, TEMP_LOCAL_PREFIX, Value, - transfer2UnixPath } from 'arkanalyzer'; + transfer2UnixPath +} from 'arkanalyzer'; import { ArkClass, ClassCategory } from 'arkanalyzer/lib/core/model/ArkClass'; import { ExportSignature } from 'arkanalyzer/lib/core/model/ArkExport'; import { Local } from 'arkanalyzer/lib/core/base/Local'; @@ -70,7 +72,7 @@ export function buildModuleChains(scene: Scene, arkFiles: ArkFile[], outputDirPa return isOutput; } -function clearGlobalMem() { +function clearGlobalMem(): void { gFinishScanMap.clear(); gNodeMap.clear(); gModuleIdMap.clear(); @@ -93,7 +95,7 @@ function genUniqueId(): string { return Math.random().toString(36).substring(2); } -function genJsonNode(scene: Scene, module: ModuleSignature, uniqueId: string) { +function genJsonNode(scene: Scene, module: ModuleSignature, uniqueId: string): void { const nodeInfo = genNodeInfo(scene, module); if (nodeInfo) { gNodeMap.set(uniqueId, { nodeInfo: nodeInfo, nextNodes: [] }); @@ -166,7 +168,7 @@ function genNodeInfo(scene: Scene, module: ModuleSignature): NodeInfo | null { } else if (module instanceof MethodSignature) { let className = module.getDeclaringClassSignature()?.getClassName(); if (className === DEFAULT_ARK_CLASS_NAME) { - className = module.getDeclaringClassSignature().getDeclaringNamespaceSignature()?.getNamespaceName() ?? '' + className = module.getDeclaringClassSignature().getDeclaringNamespaceSignature()?.getNamespaceName() ?? ''; } let methodName = module.getMethodSubSignature().getMethodName(); const methodLine = scene.getMethod(module)?.getLine(); @@ -225,7 +227,7 @@ function genResultForChains(arkFile: ArkFile): boolean { return false; } -function genChain(module: ModuleSignature, headChain: string = '') { +function genChain(module: ModuleSignature, headChain: string = ''): void { const nextNodes = gFinishScanMap.get(module); if (nextNodes) { for (const nextNode of nextNodes) { @@ -241,7 +243,7 @@ function genChain(module: ModuleSignature, headChain: string = '') { } } -function fileProcess(arkFile: ArkFile, busyArray: Array) { +function fileProcess(arkFile: ArkFile, busyArray: Array): void { const filePath = path.join('@' + arkFile.getProjectName(), transfer2UnixPath(arkFile.getName())); if (!busyArray.includes(filePath) && !repeatFilePath.includes(filePath)) { repeatFilePath.push(filePath); @@ -268,7 +270,7 @@ function fileProcess(arkFile: ArkFile, busyArray: Array) { } } -function findGlobalDef(dfltMethod: ArkMethod | null, busyArray: Array) { +function findGlobalDef(dfltMethod: ArkMethod | null, busyArray: Array): void { const stmts = dfltMethod?.getBody()?.getCfg().getStmts(); for (const stmt of stmts ?? []) { if (stmt instanceof ArkInvokeStmt) { @@ -279,7 +281,7 @@ function findGlobalDef(dfltMethod: ArkMethod | null, busyArray: Array, scene: Scene ) { +function moduleDeeplyProcess(moduleSign: Signature, busyArray: Array, scene: Scene): void { if (moduleSign instanceof ClassSignature) { classProcess(scene.getClass(moduleSign), busyArray); } else if (moduleSign instanceof MethodSignature) { @@ -293,7 +295,7 @@ function moduleDeeplyProcess(moduleSign: Signature, busyArray: Array) { +function namespaceProcess(ns: ArkNamespace | null, busyArray: Array): void { if (!ns || busyArray.includes(ns.getSignature())) { return; } @@ -321,7 +323,7 @@ function namespaceProcess(ns: ArkNamespace | null, busyArray: Array) { +function classProcess(arkClass: ArkClass | null, busyArray: Array): void { if (!arkClass || busyArray.includes(arkClass.getSignature())) { return; } @@ -330,7 +332,7 @@ function classProcess(arkClass: ArkClass | null, busyArray: Array) { +function methodProcess(arkMethod: ArkMethod | null | undefined, busyArray: Array): void { if (!arkMethod || busyArray.includes(arkMethod.getSignature())) { return; } @@ -388,7 +390,7 @@ function methodProcess(arkMethod: ArkMethod | null | undefined, busyArray: Array busyArray.pop(); } -function staticExprProcess(invokeExpr: ArkStaticInvokeExpr, arkFile: ArkFile, busyArray: Array) { +function staticExprProcess(invokeExpr: ArkStaticInvokeExpr, arkFile: ArkFile, busyArray: Array): void { const methodSignature = invokeExpr.getMethodSignature(); const classSignature = methodSignature.getDeclaringClassSignature(); const methodName = methodSignature.getMethodSubSignature().getMethodName(); @@ -413,7 +415,7 @@ function staticExprProcess(invokeExpr: ArkStaticInvokeExpr, arkFile: ArkFile, bu } } -function ifStmtProcess(stmt: ArkIfStmt, curFile: ArkFile, busyArray: Array) { +function ifStmtProcess(stmt: ArkIfStmt, curFile: ArkFile, busyArray: Array): void { const op1 = stmt.getConditionExpr().getOp1(); const op2 = stmt.getConditionExpr().getOp2(); if (op1 instanceof Local) { @@ -424,7 +426,7 @@ function ifStmtProcess(stmt: ArkIfStmt, curFile: ArkFile, busyArray: Array) { +function superClassProcess(arkClass: ArkClass, busyArray: Array): void { const superName = arkClass.getSuperClass()?.getName(); if (!superName || busyArray.includes(arkClass.getSuperClass()?.getSignature()!)) { return; @@ -437,9 +439,9 @@ function superClassProcess(arkClass: ArkClass, busyArray: Array } } -function arkFieldProcess(arkClass: ArkClass, busyArray: Array) { +function arkFieldProcess(arkClass: ArkClass, busyArray: Array): void { const arkFields = arkClass.getFields(); - for ( const arkField of arkFields) { + for (const arkField of arkFields) { const fieldStmts = arkField.getInitializer(); for (const stmt of fieldStmts) { if (stmt instanceof ArkAssignStmt) { @@ -449,7 +451,7 @@ function arkFieldProcess(arkClass: ArkClass, busyArray: Array) } } -function rightOpProcess(rightOp: Value, curFile: ArkFile, busyArray: Array) { +function rightOpProcess(rightOp: Value, curFile: ArkFile, busyArray: Array): void { if (rightOp instanceof ArkNewExpr) { // 右值为new class场景 const type = rightOp.getType(); @@ -484,7 +486,7 @@ function rightOpProcess(rightOp: Value, curFile: ArkFile, busyArray: Array) { +function newExprProcess(type: ClassType, arkFile: ArkFile, busyArray: Array): void { const classSign = type.getClassSignature(); const className = classSign.getClassName(); const curFilePath = arkFile.getFilePath(); @@ -507,7 +509,7 @@ function newExprProcess(type: ClassType, arkFile: ArkFile, busyArray: Array) { +function localProcess(rightOp: Local, curFile: ArkFile, busyArray: Array): void { const type = rightOp.getType(); // todo: Local变量为方法或者类地址,let a = class1,目前右值type为unknown,走else分支 if (type instanceof ClassType) { @@ -532,7 +534,7 @@ function isAnonymous(module: ModuleSignature): boolean { return module.toString().includes('%A'); } -function addLastNodeToMap(busyArray: Array) { +function addLastNodeToMap(busyArray: Array): void { let index = busyArray.length - 2; let lastModule = busyArray[index]; while (isAnonymous(lastModule) && index > 0) { @@ -561,7 +563,7 @@ function outputNodeList(fileName: string): boolean { } } -function outputStorage() { +function outputStorage(): boolean { try { FileUtils.writeToFile(path.join(gOutPutDirPath, FILE_NAME_CHAINS_TXT), gOutStorage); return true; diff --git a/ets2panda/linter/homecheck/src/tools/depGraph/builder.ts b/ets2panda/linter/homecheck/src/tools/depGraph/builder.ts index 720b240465..b234cf945f 100644 --- a/ets2panda/linter/homecheck/src/tools/depGraph/builder.ts +++ b/ets2panda/linter/homecheck/src/tools/depGraph/builder.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/ets2panda/linter/homecheck/src/tools/depGraph/fileComponent.ts b/ets2panda/linter/homecheck/src/tools/depGraph/fileComponent.ts index 04e8ad97ac..efeed1febe 100644 --- a/ets2panda/linter/homecheck/src/tools/depGraph/fileComponent.ts +++ b/ets2panda/linter/homecheck/src/tools/depGraph/fileComponent.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/ets2panda/linter/homecheck/src/tools/depGraph/fileDeps.ts b/ets2panda/linter/homecheck/src/tools/depGraph/fileDeps.ts index 2e3f9a5304..1b6d7bb842 100644 --- a/ets2panda/linter/homecheck/src/tools/depGraph/fileDeps.ts +++ b/ets2panda/linter/homecheck/src/tools/depGraph/fileDeps.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/ets2panda/linter/homecheck/src/tools/depGraph/moduleComponent.ts b/ets2panda/linter/homecheck/src/tools/depGraph/moduleComponent.ts index 61e8f671a1..e44b256cc7 100644 --- a/ets2panda/linter/homecheck/src/tools/depGraph/moduleComponent.ts +++ b/ets2panda/linter/homecheck/src/tools/depGraph/moduleComponent.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/ets2panda/linter/homecheck/src/tools/depGraph/moduleDeps.ts b/ets2panda/linter/homecheck/src/tools/depGraph/moduleDeps.ts index 1a84a2c289..d603a7b8bd 100644 --- a/ets2panda/linter/homecheck/src/tools/depGraph/moduleDeps.ts +++ b/ets2panda/linter/homecheck/src/tools/depGraph/moduleDeps.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/ets2panda/linter/homecheck/src/tools/depGraph/utils.ts b/ets2panda/linter/homecheck/src/tools/depGraph/utils.ts index 0fbd2ae0af..a71dd51775 100644 --- a/ets2panda/linter/homecheck/src/tools/depGraph/utils.ts +++ b/ets2panda/linter/homecheck/src/tools/depGraph/utils.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/ets2panda/linter/homecheck/src/tools/migrationTool/ExportIssue.ts b/ets2panda/linter/homecheck/src/tools/migrationTool/ExportIssue.ts deleted file mode 100644 index 7d3b3bb62f..0000000000 --- a/ets2panda/linter/homecheck/src/tools/migrationTool/ExportIssue.ts +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { CheckEntry } from '../../utils/common/CheckEntry'; - -export interface ProblemInfo { - line: number; - column: number, - endLine: number; - endColumn: number; - start?: number; - end?: number; - type?: string; - severity: number; - problem: string; - suggest: string; - rule: string; - ruleTag: number; - autofixable?: boolean; - aotufix?: AutoFix[]; - autofixTitle?: string; -} - -export interface AutoFix { - replacementText: string; - start: number; - end: number; -} - -export async function exportIssues(checkEntry: CheckEntry): Promise> { - let result = new Map(); - checkEntry.sortIssues().forEach(fileIssue => { - const problemInfos: ProblemInfo[] = fileIssue.issues.map(issueReport => { - const defect = issueReport.defect; - const line = defect.reportLine; - const column = defect.reportColumn; - const endLine = line; - const endColumn = column; - const severity = defect.severity; - const problem = defect.description; - const suggest = ''; - const rule = defect.ruleId; - const ruleTag = -1; - const autofixable = false; - return { line, column, endLine, endColumn, severity, problem, suggest, rule, ruleTag, autofixable }; - }); - result.set(fileIssue.filePath, problemInfos); - }); - return result; -} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/tools/migrationTool/MigrationTool.ts b/ets2panda/linter/homecheck/src/tools/migrationTool/MigrationTool.ts index 6c5ab6f581..5c3f6478ed 100644 --- a/ets2panda/linter/homecheck/src/tools/migrationTool/MigrationTool.ts +++ b/ets2panda/linter/homecheck/src/tools/migrationTool/MigrationTool.ts @@ -20,8 +20,8 @@ import { Utils } from '../../utils/common/Utils'; import { CheckerStorage } from '../../utils/common/CheckerStorage'; import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; import { FileUtils } from '../../utils/common/FileUtils'; -import { defaultMessage } from '../../model/Message'; -import { exportIssues, ProblemInfo } from './ExportIssue'; +import { DefaultMessage } from '../../model/Message'; +import { FileIssues } from "../../model/Defects"; const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'MigrationTool'); @@ -37,10 +37,12 @@ export class MigrationTool { } public async buildCheckEntry(): Promise { - logger.info(`buildCheckEntry start`); // 日志配置 const logPath = this.checkEntry.projectConfig.logPath; - Utils.setLogPath(logPath.length === 0 ? './HomeCheck.log' : logPath); + Utils.setLogConfig(logPath.length === 0 ? './HomeCheck.log' : logPath, + this.checkEntry.projectConfig.arkAnalyzerLogLevel, + this.checkEntry.projectConfig.logLevel); + logger.info(`buildCheckEntry start`); // api版本配置 CheckerStorage.getInstance().setApiVersion(this.checkEntry.projectConfig.apiVersion); // product配置 @@ -50,7 +52,7 @@ export class MigrationTool { // 外部没有建立消息通道,使用默认通道 if (!this.checkEntry.message) { - this.checkEntry.message = new defaultMessage(); + this.checkEntry.message = new DefaultMessage(); } // 前处理 @@ -61,11 +63,11 @@ export class MigrationTool { return true; } - public async start(): Promise> { + public async start(): Promise { logger.info(`MigrationTool run start`); await this.checkEntry.runAll(); - let result = await exportIssues(this.checkEntry); + let result = this.checkEntry.sortIssues(); logger.info(`MigrationTool run end`); return result; } diff --git a/ets2panda/linter/homecheck/src/tools/toolEntry.ts b/ets2panda/linter/homecheck/src/tools/toolEntry.ts index 1fc8811c89..797900cece 100644 --- a/ets2panda/linter/homecheck/src/tools/toolEntry.ts +++ b/ets2panda/linter/homecheck/src/tools/toolEntry.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/ets2panda/linter/homecheck/src/tools/toolRun.ts b/ets2panda/linter/homecheck/src/tools/toolRun.ts index c896db61da..37d80e9a22 100644 --- a/ets2panda/linter/homecheck/src/tools/toolRun.ts +++ b/ets2panda/linter/homecheck/src/tools/toolRun.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,10 +13,10 @@ * limitations under the License. */ -import {Utils} from '../utils/common/Utils'; -import {runTool, Tools} from './toolEntry'; +import { Utils } from '../utils/common/Utils'; +import { runTool, Tools } from './toolEntry'; -(function run() { +(function run(): void { const argvObj = Utils.parseCliOptions(process.argv); runTool(Tools.DepGraph, argvObj); })(); \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/utils/checker/AbilityInterface.ts b/ets2panda/linter/homecheck/src/utils/checker/AbilityInterface.ts index 0055d844d5..8ec07bce61 100644 --- a/ets2panda/linter/homecheck/src/utils/checker/AbilityInterface.ts +++ b/ets2panda/linter/homecheck/src/utils/checker/AbilityInterface.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/ets2panda/linter/homecheck/src/utils/checker/BytesUtils.ts b/ets2panda/linter/homecheck/src/utils/checker/BytesUtils.ts index 4be9d506a1..3da521fffc 100644 --- a/ets2panda/linter/homecheck/src/utils/checker/BytesUtils.ts +++ b/ets2panda/linter/homecheck/src/utils/checker/BytesUtils.ts @@ -18,40 +18,40 @@ export const toUTF8String = ( input: Uint8Array, start = 0, end = input.length -) => decoder.decode(input.slice(start, end)); +): string => decoder.decode(input.slice(start, end)); export const toHexString = ( input: Uint8Array, start = 0, end = input.length -) => input.slice(start, end).reduce((memo, i) => memo + `0${i.toString(16)}`.slice(-2), ''); +): string => input.slice(start, end).reduce((memo, i) => memo + `0${i.toString(16)}`.slice(-2), ''); const getView = ( input: Uint8Array, offset: number -) => new DataView(input.buffer, input.byteOffset + offset); +): DataView => new DataView(input.buffer, input.byteOffset + offset); -export const readInt16LE = (input: Uint8Array, offset = 0) => +export const readInt16LE = (input: Uint8Array, offset = 0): number => getView(input, offset).getInt16(0, true); -export const readUInt16BE = (input: Uint8Array, offset = 0) => +export const readUInt16BE = (input: Uint8Array, offset = 0): number => getView(input, offset).getUint16(0, false); -export const readUInt16LE = (input: Uint8Array, offset = 0) => +export const readUInt16LE = (input: Uint8Array, offset = 0): number => getView(input, offset).getUint16(0, true); -export const readUInt24LE = (input: Uint8Array, offset = 0) => { +export const readUInt24LE = (input: Uint8Array, offset = 0): number => { const view = getView(input, offset); return view.getUint16(0, true) + (view.getUint8(2) << 16); }; -export const readInt32LE = (input: Uint8Array, offset = 0) => +export const readInt32LE = (input: Uint8Array, offset = 0): number => getView(input, offset).getInt32(0, true); -export const readUInt32BE = (input: Uint8Array, offset = 0) => +export const readUInt32BE = (input: Uint8Array, offset = 0): number => getView(input, offset).getUint32(0, false); -export const readUInt32LE = (input: Uint8Array, offset = 0) => +export const readUInt32LE = (input: Uint8Array, offset = 0): number => getView(input, offset).getUint32(0, true); export const readUInt64 = ( @@ -65,7 +65,7 @@ const methods = { readUInt16LE, readUInt32BE, readUInt32LE -} as const +} as const; type MethodName = keyof typeof methods; @@ -92,7 +92,7 @@ const units: Record = { pc: 96 / 72 / 12, pt: 96 / 72, px: 1, -} +}; const unitsReg = new RegExp(`^([0-9.]+(?:e\\d+)?)(${Object.keys(units).join('|')})?$`,); export function getLength(len: string): number | undefined { diff --git a/ets2panda/linter/homecheck/src/utils/checker/CheckerUtils.ts b/ets2panda/linter/homecheck/src/utils/checker/CheckerUtils.ts index 97e7ff487a..58d2028b5f 100644 --- a/ets2panda/linter/homecheck/src/utils/checker/CheckerUtils.ts +++ b/ets2panda/linter/homecheck/src/utils/checker/CheckerUtils.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/ets2panda/linter/homecheck/src/utils/checker/ImageUtils.ts b/ets2panda/linter/homecheck/src/utils/checker/ImageUtils.ts index bd90155706..f4d35c2464 100644 --- a/ets2panda/linter/homecheck/src/utils/checker/ImageUtils.ts +++ b/ets2panda/linter/homecheck/src/utils/checker/ImageUtils.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -42,7 +42,7 @@ const keys = Object.keys(typeHandlers) as imageType[]; export function readImageInfo(filePath: string): ImageInfo | undefined { const input = readFileSync(filePath); - if (!input) return undefined; + if (!input) { return undefined; } const type = detector(input); if (typeof type === 'undefined') { return undefined; @@ -91,7 +91,7 @@ function detector(input: Uint8Array): imageType | undefined { return type; } } - const finder = (key: imageType) => typeHandlers[key].validate(input); + const finder = (key: imageType): boolean => typeHandlers[key].validate(input); return keys.find(finder); } catch (error) { return undefined; diff --git a/ets2panda/linter/homecheck/src/utils/checker/NumberUtils.ts b/ets2panda/linter/homecheck/src/utils/checker/NumberUtils.ts index c8cc62f88e..4afca0d4f3 100644 --- a/ets2panda/linter/homecheck/src/utils/checker/NumberUtils.ts +++ b/ets2panda/linter/homecheck/src/utils/checker/NumberUtils.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,16 +13,16 @@ * limitations under the License. */ -import { AbstractExpr, ArkAssignStmt, ArkFile, ArkNormalBinopExpr, ArkStaticFieldRef, ArkUnopExpr, ClassSignature, Constant, ImportInfo, Local, NumberType, Stmt, Value } from "arkanalyzer"; -import { VarInfo } from "../../model/VarInfo"; -import { CheckerStorage } from "../common/CheckerStorage"; -import { NumberValue, ValueType } from "../../model/NumberValue"; -import { StmtExt } from "../../model/StmtExt"; +import { AbstractExpr, ArkAssignStmt, ArkFile, ArkNormalBinopExpr, ArkStaticFieldRef, ArkUnopExpr, ClassSignature, Constant, ImportInfo, Local, NumberType, Stmt, Value } from 'arkanalyzer'; +import { VarInfo } from '../../model/VarInfo'; +import { CheckerStorage } from '../common/CheckerStorage'; +import { NumberValue, ValueType } from '../../model/NumberValue'; +import { StmtExt } from '../../model/StmtExt'; export class NumberUtils { - public static readonly mBinopList: string[] = ["+", "-", "*", "/", "%", "<<", ">>", "&", "|", "^", ">>>"]; + public static readonly mBinopList: string[] = ['+', '-', '*', '/', '%', '<<', '>>', '&', '|', '^', '>>>']; - private static isSupportOperator(operator: string) { + private static isSupportOperator(operator: string): boolean { return this.mBinopList.includes(operator); } @@ -39,12 +39,12 @@ export class NumberUtils { } else if (value instanceof AbstractExpr && value.getType() instanceof NumberType) { return NumberUtils.isExprSupportCalculate(arkFile, valueStmtInfo, value); } else if (value instanceof ArkStaticFieldRef && value.getType() instanceof NumberType) { - return true + return true; } return false; } - private static isExprSupportCalculate(arkFile: ArkFile, valueStmtInfo: VarInfo, value: AbstractExpr) { + private static isExprSupportCalculate(arkFile: ArkFile, valueStmtInfo: VarInfo, value: AbstractExpr): boolean { if (value instanceof ArkNormalBinopExpr && this.isSupportOperator(value.getOperator())) { return NumberUtils.isValueSupportCalculation(arkFile, valueStmtInfo, value.getOp1()) && NumberUtils.isValueSupportCalculation(arkFile, valueStmtInfo, value.getOp2()); @@ -94,7 +94,7 @@ export class NumberUtils { return false; } - private static isImportValueSupportCalculate(arkFile: ArkFile, importInfo: ImportInfo, value: Local) { + private static isImportValueSupportCalculate(arkFile: ArkFile, importInfo: ImportInfo, value: Local): boolean { let exportInfo = importInfo.getLazyExportInfo(); let importArkFile = exportInfo?.getDeclaringArkFile(); if (!importArkFile) { @@ -106,7 +106,7 @@ export class NumberUtils { } for (let varDef of scope.defList) { if (varDef.getName() !== value.getName()) { - continue + continue; } let stmt = varDef.defStmt; if (stmt instanceof ArkAssignStmt) { @@ -118,10 +118,10 @@ export class NumberUtils { return false; } - private static getValueImportInfo(arkFile: ArkFile, value: Local) { + private static getValueImportInfo(arkFile: ArkFile, value: Local): any { let importInfos = arkFile.getImportInfos(); for (let importInfo of importInfos) { - if (importInfo.getImportClauseName() == value.getName()) { + if (importInfo.getImportClauseName() === value.getName()) { return importInfo; } } @@ -133,21 +133,21 @@ export class NumberUtils { let valueStr = value.getValue(); let numberValue = Number(valueStr); if (valueStr.includes('.')) { - return new NumberValue(numberValue, ValueType.DOUBLE) + return new NumberValue(numberValue, ValueType.DOUBLE); } else { - return new NumberValue(numberValue, ValueType.INT) + return new NumberValue(numberValue, ValueType.INT); } } else if (value instanceof Local) { let importInfo = this.getValueImportInfo(arkFile, value); if (importInfo) { - return this.getImportNumberValue(arkFile, importInfo, value) + return this.getImportNumberValue(arkFile, importInfo, value); } else { - return this.getMethodNumberValue(arkFile, valueStmtInfo, value) + return this.getMethodNumberValue(arkFile, valueStmtInfo, value); } } else if (value instanceof AbstractExpr && value.getType() instanceof NumberType) { - return this.getExprNumberValue(arkFile, valueStmtInfo, value) + return this.getExprNumberValue(arkFile, valueStmtInfo, value); } else if (value instanceof ArkStaticFieldRef && value.getType() instanceof NumberType) { - return this.getStaticNumberValue(arkFile, valueStmtInfo, value) + return this.getStaticNumberValue(arkFile, valueStmtInfo, value); } return new NumberValue(0, ValueType.UNKNOWN); } @@ -170,7 +170,7 @@ export class NumberUtils { if (stmt instanceof ArkAssignStmt) { let defStmtInfo = new VarInfo(stmt, scope); let rightOp = stmt.getRightOp(); - return this.getNumberByScope(importArkFile, defStmtInfo, rightOp) + return this.getNumberByScope(importArkFile, defStmtInfo, rightOp); } } return new NumberValue(0, ValueType.UNKNOWN); @@ -204,18 +204,18 @@ export class NumberUtils { let stmt = nearReDefStmtInfo.stmt; if (stmt instanceof ArkAssignStmt) { let rightOp = stmt.getRightOp(); - return this.getNumberByScope(arkFile, nearReDefStmtInfo, rightOp) + return this.getNumberByScope(arkFile, nearReDefStmtInfo, rightOp); } } if (!hasFind && scope.parentScope != null) { let defStmtInfo = new VarInfo(valueStmt, scope.parentScope); - return this.getNumberByScope(arkFile, defStmtInfo, value) + return this.getNumberByScope(arkFile, defStmtInfo, value); } return new NumberValue(0, ValueType.UNKNOWN); } - private static getExprNumberValue(arkFile: ArkFile, stmeInfo: VarInfo, value: AbstractExpr) { + private static getExprNumberValue(arkFile: ArkFile, stmeInfo: VarInfo, value: AbstractExpr): NumberValue { if (value instanceof ArkNormalBinopExpr) { if (this.isSupportOperator(value.getOperator())) { let valueOfOp1 = this.getNumberByScope(arkFile, stmeInfo, value.getOp1()); @@ -258,7 +258,7 @@ export class NumberUtils { return new NumberValue(0, ValueType.UNKNOWN); } - private static getStaticNumberValue(arkFile: ArkFile, valueStmtInfo: VarInfo, value: ArkStaticFieldRef) { + private static getStaticNumberValue(arkFile: ArkFile, valueStmtInfo: VarInfo, value: ArkStaticFieldRef): NumberValue { let classSignature = value.getFieldSignature().getDeclaringSignature(); if (!(classSignature instanceof ClassSignature)) { return new NumberValue(0, ValueType.UNKNOWN); @@ -284,7 +284,7 @@ export class NumberUtils { } let stmt = stmts[0]; - new VarInfo(stmt, (stmt as StmtExt).scope) + new VarInfo(stmt, (stmt as StmtExt).scope); if (!(stmt instanceof ArkAssignStmt)) { return new NumberValue(0, ValueType.UNKNOWN); } @@ -298,7 +298,7 @@ export class NumberUtils { public static getOriginalValueText(stmt: Stmt, value: Value): string { let valStr = ''; if (value instanceof Constant) { - valStr = value.toString() + valStr = value.toString(); } else if (value instanceof Local) { if (!value.toString().includes('%')) { valStr = value.toString(); @@ -314,13 +314,13 @@ export class NumberUtils { } else { let originalPosition = stmt.getOperandOriginalPosition(value); if (!originalPosition) { - return this.getOriginalValueText(stmt, value.getOp1()) + ' ' + value.getOperator() + ' ' - + this.getOriginalValueText(stmt, value.getOp2()); + return this.getOriginalValueText(stmt, value.getOp1()) + ' ' + value.getOperator() + ' ' + + this.getOriginalValueText(stmt, value.getOp2()); } const text = stmt.getOriginalText(); if (!text || text.length === 0) { - return this.getOriginalValueText(stmt, value.getOp1()) + ' ' + value.getOperator() + ' ' - + this.getOriginalValueText(stmt, value.getOp2()); + return this.getOriginalValueText(stmt, value.getOp1()) + ' ' + value.getOperator() + ' ' + + this.getOriginalValueText(stmt, value.getOp2()); } let startColum = stmt.getOriginPositionInfo().getColNo(); return text.substring(originalPosition.getFirstCol() - startColum, originalPosition.getLastCol() - startColum); diff --git a/ets2panda/linter/homecheck/src/utils/checker/StringUtils.ts b/ets2panda/linter/homecheck/src/utils/checker/StringUtils.ts index 9d20691027..f6ddea74b0 100644 --- a/ets2panda/linter/homecheck/src/utils/checker/StringUtils.ts +++ b/ets2panda/linter/homecheck/src/utils/checker/StringUtils.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,12 +13,12 @@ * limitations under the License. */ -import { AbstractExpr, ArkAssignStmt, ArkFile, ArkNormalBinopExpr, ArkStaticFieldRef, ClassSignature, ClassType, Constant, ImportInfo, Local, Stmt, StringType, Value } from "arkanalyzer"; -import { ClassCategory } from "arkanalyzer/lib/core/model/ArkClass"; -import { VarInfo } from "../../model/VarInfo"; -import { StmtExt } from "../../model/StmtExt"; -import { CheckerStorage } from "../common/CheckerStorage"; -import { Scope } from "../../model/Scope"; +import { AbstractExpr, ArkAssignStmt, ArkFile, ArkNormalBinopExpr, ArkStaticFieldRef, ClassSignature, ClassType, Constant, ImportInfo, Local, Stmt, StringType, Value } from 'arkanalyzer'; +import { ClassCategory } from 'arkanalyzer/lib/core/model/ArkClass'; +import { VarInfo } from '../../model/VarInfo'; +import { StmtExt } from '../../model/StmtExt'; +import { CheckerStorage } from '../common/CheckerStorage'; +import { Scope } from '../../model/Scope'; export class StringUtils { public static getStringByScope(arkFile: ArkFile, valueStmtInfo: VarInfo, value: Value): string { diff --git a/ets2panda/linter/homecheck/src/utils/checker/TypeUtils.ts b/ets2panda/linter/homecheck/src/utils/checker/TypeUtils.ts index f535e04f48..d592f86fc1 100644 --- a/ets2panda/linter/homecheck/src/utils/checker/TypeUtils.ts +++ b/ets2panda/linter/homecheck/src/utils/checker/TypeUtils.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -import { AliasType, ArrayType, ClassType, FunctionType, GenericType, TupleType, Type, UnclearReferenceType, UnionType } from "arkanalyzer"; +import { AliasType, ArrayType, ClassType, FunctionType, GenericType, TupleType, Type, UnclearReferenceType, UnionType } from 'arkanalyzer'; /** * 检查类型是否为指定类型 diff --git a/ets2panda/linter/homecheck/src/utils/checker/ViewTreeTool.ts b/ets2panda/linter/homecheck/src/utils/checker/ViewTreeTool.ts index b69f6e7b0e..b0efc7e602 100644 --- a/ets2panda/linter/homecheck/src/utils/checker/ViewTreeTool.ts +++ b/ets2panda/linter/homecheck/src/utils/checker/ViewTreeTool.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,11 +12,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { ViewTreeNode } from "arkanalyzer" -import { ArkClass } from "arkanalyzer" +import { ViewTreeNode } from 'arkanalyzer'; +import { ArkClass } from 'arkanalyzer'; export class ViewTreeTool { - private recordMap: Map + private recordMap: Map; constructor() { this.recordMap = new Map(); diff --git a/ets2panda/linter/homecheck/src/utils/checker/imageFormat/bmp.ts b/ets2panda/linter/homecheck/src/utils/checker/imageFormat/bmp.ts index 6a3d40e359..58a20fcc46 100644 --- a/ets2panda/linter/homecheck/src/utils/checker/imageFormat/bmp.ts +++ b/ets2panda/linter/homecheck/src/utils/checker/imageFormat/bmp.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/ets2panda/linter/homecheck/src/utils/checker/imageFormat/jpg.ts b/ets2panda/linter/homecheck/src/utils/checker/imageFormat/jpg.ts index aaa92f977a..0495056034 100644 --- a/ets2panda/linter/homecheck/src/utils/checker/imageFormat/jpg.ts +++ b/ets2panda/linter/homecheck/src/utils/checker/imageFormat/jpg.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -33,37 +33,38 @@ function extractSize(input: Uint8Array, index: number): ImageInfo { return { height: readUInt16BE(input, index), width: readUInt16BE(input, index + 2), - } + }; } -function extractOrientation(exifBlock: Uint8Array, isBigEndian: boolean) { +function extractOrientation(exifBlock: Uint8Array, isBigEndian: boolean): number | undefined { const idfOffset = 8; const offset = EXIF_HEADER_BYTES + idfOffset; const idfDirectoryEntries = readUInt(exifBlock, 16, offset, isBigEndian); - for(let directoryEntryNumber = 0; directoryEntryNumber < idfDirectoryEntries; directoryEntryNumber++) { + for (let directoryEntryNumber = 0; directoryEntryNumber < idfDirectoryEntries; directoryEntryNumber++) { const start = offset + NUM_DIRECTORY_ENTRIES_BYTES + directoryEntryNumber * IDF_ENTRY_BYTES; const end = start + IDF_ENTRY_BYTES; if (start > exifBlock.length) { - return; + return undefined; } const block = exifBlock.slice(start, end); const tagNumber = readUInt(block, 16, 0, isBigEndian); if (tagNumber === 274) { const dataFormat = readUInt(block, 16, 2, isBigEndian); if (dataFormat !== 3) { - return; + return undefined; } const numberOfComponents = readUInt(block, 32, 4, isBigEndian); if (numberOfComponents !== 1) { - return; + return undefined; } return readUInt(block, 16, 8, isBigEndian); } } + return undefined; } -function validateExifBlock(input: Uint8Array, index: number) { +function validateExifBlock(input: Uint8Array, index: number): number | undefined { const exifBlock = input.slice(APP1_DATA_SIZE_BYTES, index); const byteAlign = toHexString(exifBlock, EXIF_HEADER_BYTES, EXIF_HEADER_BYTES + TIFF_BYTE_ALIGN_BYTES); const isBigEndian = byteAlign === BIG_ENDIAN_BYTE_ALIGN; @@ -71,6 +72,7 @@ function validateExifBlock(input: Uint8Array, index: number) { if (isBigEndian || isLittleEndian) { return extractOrientation(exifBlock, isBigEndian); } + return undefined; } function validateInput(input: Uint8Array, index: number): void { @@ -86,13 +88,13 @@ export const JPG: ImageData = { let input = _input.slice(4); let orientation: number | undefined; let next: number; - while(input.length) { + while (input.length) { const i = readUInt16BE(input, 0); if (input[i] !== 0xff) { input = input.slice(1); continue; } - if(isEXIF(input)) { + if (isEXIF(input)) { orientation = validateExifBlock(input, i); } validateInput(input, i); @@ -106,7 +108,7 @@ export const JPG: ImageData = { height: size.height, orientation, width: size.width, - } + }; } input = input.slice(i + 2); } diff --git a/ets2panda/linter/homecheck/src/utils/checker/imageFormat/png.ts b/ets2panda/linter/homecheck/src/utils/checker/imageFormat/png.ts index 3da4803055..81b12981e4 100644 --- a/ets2panda/linter/homecheck/src/utils/checker/imageFormat/png.ts +++ b/ets2panda/linter/homecheck/src/utils/checker/imageFormat/png.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -40,11 +40,11 @@ export const PNG: ImageData = { return { height: readUInt32BE(input, 36), width: readUInt32BE(input, 32), - } + }; } return { height: readUInt32BE(input, 20), width: readUInt32BE(input, 16), - } + }; }, }; \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/utils/checker/imageFormat/svg.ts b/ets2panda/linter/homecheck/src/utils/checker/imageFormat/svg.ts index ea97b3179e..7c68128942 100644 --- a/ets2panda/linter/homecheck/src/utils/checker/imageFormat/svg.ts +++ b/ets2panda/linter/homecheck/src/utils/checker/imageFormat/svg.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -28,8 +28,8 @@ function parseViewbox(viewbox: string): IAttributes | undefined { const bounds = viewbox.split(' '); let tmpWeight = getLength(bounds[3]); let tmpWidth = getLength(bounds[2]); - if(tmpWidth && tmpWeight) { - return {height: tmpWeight, width: tmpWidth}; + if (tmpWidth && tmpWeight) { + return { height: tmpWeight, width: tmpWidth }; } return undefined; } @@ -46,7 +46,7 @@ function getAttirbutes(root: string): IAttributes | undefined { height: heights && tempHeight, viewbox: viewbox && parseViewbox(viewbox[2]), width: widths && tmpWidth, - } + }; } } return undefined; @@ -56,7 +56,7 @@ function calculateByDimensions(attrs: IAttributes): ImageInfo { return { height: attrs.height as number, width: attrs.width as number, - } + }; } function calculateByViewbox(attrs: IAttributes, viewbox: IAttributes): ImageInfo { @@ -65,17 +65,17 @@ function calculateByViewbox(attrs: IAttributes, viewbox: IAttributes): ImageInfo return { height: attrs.height, width: Math.floor(attrs.height * ratio) - } + }; } else if (attrs.width) { return { height: Math.floor(attrs.width * ratio), width: attrs.width, - } + }; } else { return { height: viewbox.height as number, width: viewbox.width as number, - } + }; } } diff --git a/ets2panda/linter/homecheck/src/utils/checker/imageFormat/webp.ts b/ets2panda/linter/homecheck/src/utils/checker/imageFormat/webp.ts index 2c575cc595..554281816f 100644 --- a/ets2panda/linter/homecheck/src/utils/checker/imageFormat/webp.ts +++ b/ets2panda/linter/homecheck/src/utils/checker/imageFormat/webp.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,25 +16,25 @@ import type { ImageInfo, ImageData } from '../../../model/Interfaces'; import { readInt16LE, readUInt24LE, toHexString, toUTF8String } from '../BytesUtils'; -function calculateExtended(input: Uint8Array) : ImageInfo { +function calculateExtended(input: Uint8Array): ImageInfo { return { height: 1 + readUInt24LE(input, 7), width: 1 + readUInt24LE(input, 4), - } + }; } function calculateLossLess(input: Uint8Array): ImageInfo { return { height: 1 + (((input[4] & 0xf) << 10) | (input[3] << 2) | ((input[2] & 0xc0) >> 6)), width: 1 + (((input[2] & 0x3f) << 8) | input[1]), - } + }; } function calculateLossy(input: Uint8Array): ImageInfo { return { height: readInt16LE(input, 8) & 0x3fff, width: readInt16LE(input, 6) & 0x3fff, - } + }; } export const WEBP: ImageData = { diff --git a/ets2panda/linter/homecheck/src/utils/common/AfterCheck.ts b/ets2panda/linter/homecheck/src/utils/common/AfterCheck.ts index 72257923bc..762f512320 100644 --- a/ets2panda/linter/homecheck/src/utils/common/AfterCheck.ts +++ b/ets2panda/linter/homecheck/src/utils/common/AfterCheck.ts @@ -13,10 +13,10 @@ * limitations under the License. */ -import { FileReports } from "../../Index"; -import { CheckEntry } from "./CheckEntry"; +import { FileReports } from '../../Index'; +import { CheckEntry } from './CheckEntry'; -export async function processAfterCheck(checkEntry: CheckEntry) { +export async function processAfterCheck(checkEntry: CheckEntry): Promise { // 按规则维度统计告警信息,按文件维度汇总告警信息 const fileIssues = checkEntry.sortIssues(); let fileReports: FileReports[] = []; diff --git a/ets2panda/linter/homecheck/src/utils/common/CheckBuilder.ts b/ets2panda/linter/homecheck/src/utils/common/CheckBuilder.ts index cbc34a3e42..1fa55aca99 100644 --- a/ets2panda/linter/homecheck/src/utils/common/CheckBuilder.ts +++ b/ets2panda/linter/homecheck/src/utils/common/CheckBuilder.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,17 +12,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import Logger, { LOG_MODULE_TYPE } from "arkanalyzer/lib/utils/logger"; -import { ArkFile } from "arkanalyzer"; -import { Rule, BaseChecker } from "../../Index"; -import { File2Check } from "../../model/File2Check"; -import { Project2Check } from "../../model/Project2Check"; -import { CheckerFactory } from "./CheckerFactory"; +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; +import { ArkFile } from 'arkanalyzer'; +import { Rule, BaseChecker } from '../../Index'; +import { File2Check } from '../../model/File2Check'; +import { Project2Check } from '../../model/Project2Check'; +import { CheckerFactory } from './CheckerFactory'; const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'CheckBuilder'); -export function fileCheckBuilder(arkFile: ArkFile, enabledRules: Rule[]) { +export function fileCheckBuilder(arkFile: ArkFile, enabledRules: Rule[]): File2Check { let checkIns = new File2Check(); checkIns.arkFile = arkFile; enabledRules.forEach(rule => { @@ -36,7 +36,7 @@ export function fileCheckBuilder(arkFile: ArkFile, enabledRules: Rule[]) { return checkIns; } -export function projectCheckBuilder(arkFiles: ArkFile[], enabledRules: Rule[]) { +export function projectCheckBuilder(arkFiles: ArkFile[], enabledRules: Rule[]): Project2Check { let checkIns = new Project2Check(); checkIns.arkFiles = arkFiles; enabledRules.forEach(rule => { diff --git a/ets2panda/linter/homecheck/src/utils/common/CheckEntry.ts b/ets2panda/linter/homecheck/src/utils/common/CheckEntry.ts index 6b3fa93aa3..e08dbb90f7 100644 --- a/ets2panda/linter/homecheck/src/utils/common/CheckEntry.ts +++ b/ets2panda/linter/homecheck/src/utils/common/CheckEntry.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,24 +13,24 @@ * limitations under the License. */ -import { Scene } from "arkanalyzer"; -import Logger, { LOG_MODULE_TYPE } from "arkanalyzer/lib/utils/logger"; -import { SceneConfig } from "arkanalyzer"; -import { fileRuleMapping } from "./FileRuleMapping"; -import { RuleConfig } from "../../model/RuleConfig"; -import { ProjectConfig, SelectedFileInfo } from "../../model/ProjectConfig"; -import { Project2Check } from "../../model/Project2Check"; -import { File2Check } from "../../model/File2Check"; -import { DisableText } from "./Disable"; -import { Message } from "../../model/Message"; -import { FileUtils } from "./FileUtils"; -import { ScopeHelper } from "./ScopeHelper"; -import { RuleListUtil } from "./DefectsList"; -import { FixMode } from "../../model/Fix"; -import { FileIssues, FileReports, IssueReport, engine } from "../../model/Defects"; -import { FixUtils } from "./FixUtils"; -import { FixEngine } from "../../codeFix/FixEngine"; -import { CheckerUtils } from "../checker/CheckerUtils"; +import { Scene } from 'arkanalyzer'; +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; +import { SceneConfig } from 'arkanalyzer'; +import { fileRuleMapping } from './FileRuleMapping'; +import { RuleConfig } from '../../model/RuleConfig'; +import { ProjectConfig, SelectedFileInfo } from '../../model/ProjectConfig'; +import { Project2Check } from '../../model/Project2Check'; +import { File2Check } from '../../model/File2Check'; +import { DisableText } from './Disable'; +import { Message } from '../../model/Message'; +import { FileUtils } from './FileUtils'; +import { ScopeHelper } from './ScopeHelper'; +import { RuleListUtil } from './DefectsList'; +import { FixMode } from '../../model/Fix'; +import { FileIssues, FileReports, IssueReport, engine } from '../../model/Defects'; +import { FixUtils } from './FixUtils'; +import { FixEngine } from '../../codeFix/FixEngine'; +import { CheckerUtils } from '../checker/CheckerUtils'; const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'CheckEntry'); @@ -210,12 +210,12 @@ export async function checkEntryBuilder(checkEntry: CheckEntry): Promise file.filePath); if (checkFileList.length === 0) { - checkFileList = FileUtils.getAllFiles(checkEntry.projectConfig.projectPath, ['.ts', '.ets', '.json5']); + checkFileList = FileUtils.getAllFiles(checkEntry.projectConfig.projectPath, ['.ts', '.ets', '.js', '.json5']); } - + // 2、文件过滤和文件级屏蔽处理 checkFileList = await FileUtils.getFiltedFiles(checkFileList, checkEntry.ruleConfig); - logger.info("File count: " + checkFileList.length); + logger.info('File count: ' + checkFileList.length); if (checkFileList.length === 0) { checkEntry.message?.progressNotify(1, 'No file to check.'); return false; @@ -236,7 +236,7 @@ export async function checkEntryBuilder(checkEntry: CheckEntry): Promise = new Map(Object.entries(fileRu export const project2CheckRuleMap: Map = new Map(Object.entries(projectRules)); export class ProxyChecker { - static getClass(ruleId: string) { + static getClass(ruleId: string): any { const checker = file2CheckRuleMap.get(ruleId) ?? project2CheckRuleMap.get(ruleId); if (!checker) { logger.error(`${ruleId} is not matched to any checker`); @@ -51,4 +63,4 @@ export class ProxyChecker { } return new checker(); } -} \ No newline at end of file +} diff --git a/ets2panda/linter/homecheck/src/utils/common/CheckerStorage.ts b/ets2panda/linter/homecheck/src/utils/common/CheckerStorage.ts index e21b994bbb..f3bedd5017 100644 --- a/ets2panda/linter/homecheck/src/utils/common/CheckerStorage.ts +++ b/ets2panda/linter/homecheck/src/utils/common/CheckerStorage.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,7 +13,7 @@ * limitations under the License. */ -import { Scope } from "../../model/Scope"; +import { Scope } from '../../model/Scope'; export class CheckerStorage { private static instance: CheckerStorage; @@ -45,7 +45,7 @@ export class CheckerStorage { * 设置Scope映射 * @param scopeMap - Scope映射,类型为 Map */ - public setScopeMap(scopeMap: Map) { + public setScopeMap(scopeMap: Map): void { this.scopeMap = scopeMap; } diff --git a/ets2panda/linter/homecheck/src/utils/common/ConfigUtils.ts b/ets2panda/linter/homecheck/src/utils/common/ConfigUtils.ts index f79ac650d1..79d18b7197 100644 --- a/ets2panda/linter/homecheck/src/utils/common/ConfigUtils.ts +++ b/ets2panda/linter/homecheck/src/utils/common/ConfigUtils.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,21 +12,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { ALERT_LEVEL, ExtRuleSet, Rule } from "../../model/Rule"; -import { FileUtils } from "./FileUtils"; +import { ALERT_LEVEL, ExtRuleSet, Rule } from '../../model/Rule'; +import { FileUtils } from './FileUtils'; import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; -import { Utils } from "./Utils"; -import { execSync } from "child_process"; -import { Json5parser } from "./Json5parser"; -import { OptionValues } from "commander"; -import { CheckerStorage } from "./CheckerStorage"; -import path from "path"; -import { CheckEntry } from "./CheckEntry"; -import { RuleConfig } from "../../model/RuleConfig"; -import { ProjectConfig } from "../../model/ProjectConfig"; -import { file2CheckRuleMap, project2CheckRuleMap } from "./CheckerIndex"; -import fs from "fs"; -import { Message, MessageType } from "../../model/Message"; +import { Utils } from './Utils'; +import { execSync } from 'child_process'; +import { Json5parser } from './Json5parser'; +import { OptionValues } from 'commander'; +import { CheckerStorage } from './CheckerStorage'; +import path from 'path'; +import { CheckEntry } from './CheckEntry'; +import { RuleConfig } from '../../model/RuleConfig'; +import { ProjectConfig } from '../../model/ProjectConfig'; +import { file2CheckRuleMap, project2CheckRuleMap } from './CheckerIndex'; +import fs from 'fs'; +import { Message, MessageType } from '../../model/Message'; const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'ConfigUtils'); @@ -125,7 +125,7 @@ export class ConfigUtils { // 解析自定义规则集配置 this.parseExtRuleConfig(ruleConfig, projectConfig, message, allRules, ruleMap); - return ruleMap;; + return ruleMap; } /** @@ -197,7 +197,7 @@ export class ConfigUtils { } /** - * 通过单个规则配置生成Rule对象,eg: "@ruleSet/ruleName": "error" | ["error", []...] + * 通过单个规则配置生成Rule对象,eg: '@ruleSet/ruleName': 'error' | ['error', []...] * @param ruleCfg - 规则配置,格式为 [string, any] * @returns Rule | null - 生成的规则对象或 null */ @@ -242,7 +242,7 @@ export class ConfigUtils { */ static isOnlineRule(ruleId: string, allRules: Map): boolean { for (const [ruleSet, rules] of allRules) { - if (rules.hasOwnProperty(ruleId)) { + if (Object.keys(rules).includes(ruleId)) { return true; } } diff --git a/ets2panda/linter/homecheck/src/utils/common/DefectsList.ts b/ets2panda/linter/homecheck/src/utils/common/DefectsList.ts index 4d798e5ddc..e21b56f6de 100644 --- a/ets2panda/linter/homecheck/src/utils/common/DefectsList.ts +++ b/ets2panda/linter/homecheck/src/utils/common/DefectsList.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -7,24 +7,24 @@ * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an 'AS IS' BASIS, + * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { Defects } from '../../model/Defects'; -import Logger, { LOG_MODULE_TYPE } from "arkanalyzer/lib/utils/logger"; +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'CheckEntry'); namespace DefectsList { let defects: Defects[] = []; - export function add(defect: Defects) { + export function add(defect: Defects): void { defects.push(defect); } - export function updateDefectByIndex(index: number, defect: Defects) { + export function updateDefectByIndex(index: number, defect: Defects): void { defects[index] = defect; } @@ -32,20 +32,20 @@ namespace DefectsList { return defects; } - export function clear() { + export function clear(): void { defects = []; } } export class RuleListUtil { - static push(defect: Defects) { + static push(defect: Defects): void { } - static updateDefect(defect: Defects) { + static updateDefect(defect: Defects): void { } - static printDefects() { + static printDefects(): void { } static isFilter(ruleId: string): boolean { diff --git a/ets2panda/linter/homecheck/src/utils/common/Disable.ts b/ets2panda/linter/homecheck/src/utils/common/Disable.ts index 9ed537c699..e8f86a2618 100644 --- a/ets2panda/linter/homecheck/src/utils/common/Disable.ts +++ b/ets2panda/linter/homecheck/src/utils/common/Disable.ts @@ -13,25 +13,36 @@ * limitations under the License. */ -import { IssueReport } from "../../model/Defects"; +import * as fs from 'fs'; +import path from 'path'; +import { IssueReport } from '../../model/Defects'; +import { FileUtils } from '../../Index'; export const DisableText = { - FILE_DISABLE_TEXT: "\/* homecheck-disable *\/", - NEXT_LINE_DISABLE_TEXT: "\/\/ homecheck-disable-next-line ", + FILE_DISABLE_TEXT: '\/* homecheck-disable *\/', + NEXT_LINE_DISABLE_TEXT: '\/\/ homecheck-disable-next-line ', }; -export function filterDisableIssue(lineList: string[], issues: IssueReport[]): IssueReport[] { +export async function filterDisableIssue(lineList: string[], issues: IssueReport[], filePath: string): Promise { let filtedIssues: IssueReport[] = []; - issues.forEach(issue => { + for (const issue of issues) { + // @migration/arkui-data-observation规则的自动修复是在定义处,存在跨文件场景 + const actualFilePath = path.normalize(issue.defect.mergeKey.split('%')[0]); + if (path.normalize(actualFilePath) !== path.normalize(filePath)) { + if (!fs.existsSync(actualFilePath)) { + continue; + } + lineList = await FileUtils.readLinesFromFile(actualFilePath); + } // 有些特殊规则允许返回行列号为0 if (issue.defect.reportLine < 0 || issue.defect.reportLine - 1 > lineList.length) { - return; + continue; } const text = lineList[issue.defect.reportLine - 2]; if (!isDisableIssue(text, issue.defect.ruleId)) { filtedIssues.push(issue); } - }); + } return filtedIssues; } diff --git a/ets2panda/linter/homecheck/src/utils/common/FileRuleMapping.ts b/ets2panda/linter/homecheck/src/utils/common/FileRuleMapping.ts index 548a248142..b78400ff29 100644 --- a/ets2panda/linter/homecheck/src/utils/common/FileRuleMapping.ts +++ b/ets2panda/linter/homecheck/src/utils/common/FileRuleMapping.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,16 +13,16 @@ * limitations under the License. */ -import { ArkFile } from "arkanalyzer"; -import { CheckEntry } from "./CheckEntry"; -import { ConfigUtils } from "./ConfigUtils"; -import { CheckerUtils } from "../checker/CheckerUtils"; -import { file2CheckRuleMap, project2CheckRuleMap } from "./CheckerIndex"; -import { Rule } from "../../model/Rule"; -import { RuleConfig } from "../../model/RuleConfig"; -import { fileCheckBuilder, projectCheckBuilder } from "./CheckBuilder"; +import { ArkFile } from 'arkanalyzer'; +import { CheckEntry } from './CheckEntry'; +import { ConfigUtils } from './ConfigUtils'; +import { CheckerUtils } from '../checker/CheckerUtils'; +import { file2CheckRuleMap, project2CheckRuleMap } from './CheckerIndex'; +import { Rule } from '../../model/Rule'; +import { RuleConfig } from '../../model/RuleConfig'; +import { fileCheckBuilder, projectCheckBuilder } from './CheckBuilder'; import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; -import { FileUtils } from "./FileUtils"; +import { FileUtils } from './FileUtils'; const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'fileRuleMapping'); @@ -30,7 +30,7 @@ export async function fileRuleMapping(checkFileList: string[], checkEntry: Check // 获取规则配置文件的规则,除了override const allRulesMap = ConfigUtils.getRuleMap(checkEntry.ruleConfig, checkEntry.projectConfig, checkEntry.message); if (allRulesMap.size === 0) { - checkEntry.message?.progressNotify(1, "No rule to check"); + checkEntry.message?.progressNotify(1, 'No rule to check'); return false; } diff --git a/ets2panda/linter/homecheck/src/utils/common/FileUtils.ts b/ets2panda/linter/homecheck/src/utils/common/FileUtils.ts index 5b32b9f048..48b06a414d 100644 --- a/ets2panda/linter/homecheck/src/utils/common/FileUtils.ts +++ b/ets2panda/linter/homecheck/src/utils/common/FileUtils.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,15 +12,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import * as fs from "fs"; -import * as path from "path"; -import { createInterface } from "readline"; -import { DisableText } from "./Disable"; -import { Sdk } from "arkanalyzer/lib/Config"; +import * as fs from 'fs'; +import * as path from 'path'; +import { createInterface, Interface } from 'readline'; +import { DisableText } from './Disable'; +import { Sdk } from 'arkanalyzer/lib/Config'; import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; import { FileToCheck, ProjectConfig, SelectedFileInfo } from '../../model/ProjectConfig'; -import { RuleConfig } from "../../model/RuleConfig"; -import { GlobMatch } from "./GlobMatch"; +import { RuleConfig } from '../../model/RuleConfig'; +import { GlobMatch } from './GlobMatch'; const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'FileUtils'); export class FileUtils { @@ -91,8 +91,9 @@ export class FileUtils { let lines: string[] = []; let readLineNo = 1; - let rl = createInterface({ - input: fs.createReadStream(filePath), + const readStream = fs.createReadStream(filePath); + const rl = createInterface({ + input: readStream, crlfDelay: Infinity }); @@ -111,13 +112,36 @@ export class FileUtils { rl.on('line', handleLine); rl.on('close', () => { + readStream.destroy(); resolve(lines); }); rl.on('error', (err) => { + readStream.destroy(); reject(err); }); - }) + + readStream.on('error', (err) => { + rl.close(); + reject(err); + }); + }); + } + + private processHandleLine(lineNo: number | undefined, readLineNo: number, lines: string[], rl: Interface): void { + const handleLine = (line: string): void => { + if (lineNo) { + if (readLineNo === lineNo) { + lines.push(line); + rl.close(); + } + } else { + lines.push(line); + } + readLineNo++; + }; + + rl.on('line', handleLine); } /** @@ -153,15 +177,15 @@ export class FileUtils { public static getFileInfoFromFileList(fileOrFolderList: string[]): SelectedFileInfo[] { const fileInfoList: SelectedFileInfo[] = []; fileOrFolderList.forEach((fileOrFolderPath) => { - if (fs.statSync(fileOrFolderPath).isFile()){ - fileInfoList.push(new FileToCheck(fileOrFolderPath)) - }else { + if (fs.statSync(fileOrFolderPath).isFile()) { + fileInfoList.push(new FileToCheck(fileOrFolderPath)); + } else { const filesInFolder = FileUtils.getAllFiles(fileOrFolderPath, []); filesInFolder.forEach((filePath) => { - fileInfoList.push(new FileToCheck(filePath)) - }) + fileInfoList.push(new FileToCheck(filePath)); + }); } - }) + }); return fileInfoList; } @@ -203,7 +227,7 @@ export class FileUtils { filenameArr.push(realFile); } } - }) + }); return filenameArr; } @@ -268,7 +292,7 @@ export class FileUtils { * @param content 写入的内容 * @param mode 写入模式,不传默认为追加模式 **/ - public static writeToFile(filePath: string, content: string, mode: WriteFileMode = WriteFileMode.APPEND) { + public static writeToFile(filePath: string, content: string, mode: WriteFileMode = WriteFileMode.APPEND): void { const dirName = path.dirname(filePath); if (!fs.existsSync(dirName)) { fs.mkdirSync(dirName, { recursive: true }); diff --git a/ets2panda/linter/homecheck/src/utils/common/FixUtils.ts b/ets2panda/linter/homecheck/src/utils/common/FixUtils.ts index 234825a056..3dc2fc6673 100644 --- a/ets2panda/linter/homecheck/src/utils/common/FixUtils.ts +++ b/ets2panda/linter/homecheck/src/utils/common/FixUtils.ts @@ -13,8 +13,15 @@ * limitations under the License. */ -import { ArkClass, ArkFile, ArkMethod, ExportInfo, ImportInfo, Stmt } from "arkanalyzer"; -import { AIFix, FunctionFix, RuleFix } from "../../model/Fix"; +import { ArkClass, ArkFile, ArkMethod, AstTreeUtils, ExportInfo, ImportInfo, Stmt, ts } from 'arkanalyzer'; +import { AIFix, FunctionFix, Range, RuleFix } from '../../model/Fix'; + +export type FixPosition = { + startLine: number, + startCol: number, + endLine: number, + endCol: number +}; export class FixUtils { @@ -26,11 +33,11 @@ export class FixUtils { lineNum = originalPosition.getLineNo(); startColumn = originalPosition.getColNo(); } else if (codeNode instanceof ArkMethod) { - lineNum = codeNode.getLine()?? 0; - startColumn = codeNode.getColumn()?? 0; + lineNum = codeNode.getLine() ?? 0; + startColumn = codeNode.getColumn() ?? 0; } else if (codeNode instanceof ArkClass) { - lineNum = codeNode.getLine()?? 0; - startColumn = codeNode.getColumn()?? 0; + lineNum = codeNode.getLine() ?? 0; + startColumn = codeNode.getColumn() ?? 0; } else if (codeNode instanceof ExportInfo) { let originalPosition = codeNode.getOriginTsPosition(); lineNum = originalPosition.getLineNo(); @@ -46,7 +53,7 @@ export class FixUtils { let lineBreak = this.getTextEof(code); let cnt = 0; if (lineBreak.length > 0) { - for(let index = 1; index !== lineNum; index++) { + for (let index = 1; index !== lineNum; index++) { cnt = code.indexOf(lineBreak, cnt + 1); } } @@ -54,6 +61,125 @@ export class FixUtils { return start; } + // 根据输入的代码片段的起始、结束行列号信息,计算此代码片段在该文件中的起始偏移量、结束偏移量数据 + public static getRangeWithAst(sourceFile: ts.SourceFile, fixPosition: FixPosition): Range { + const startNumber = ts.getPositionOfLineAndCharacter(sourceFile, fixPosition.startLine - 1, fixPosition.startCol - 1); + const endNumber = ts.getPositionOfLineAndCharacter(sourceFile, fixPosition.endLine - 1, fixPosition.endCol - 1); + return [startNumber, endNumber]; + } + + // 根据输入的起始行号信息,计算该行的起始偏移量、结束偏移量数据 + public static getLineRange(sourceFile: ts.SourceFile, lineNumber: number): Range | null { + const lineStarts = sourceFile.getLineStarts(); + + // 验证行号范围 + if (lineNumber < 1 || lineNumber > lineStarts.length) { + return null; + } + + const startPos = lineStarts[lineNumber - 1]; + let endPos: number; + + // 处理文件最后一行 + if (lineNumber === lineStarts.length) { + endPos = sourceFile.text.length; + } else { + endPos = lineStarts[lineNumber] - 1; + } + return [startPos, endPos]; + } + + // 根据给定的起始、结束偏移量数据,获取此段代码片段的源码字符串,位置信息不合法则返回null + public static getSourceWithRange(sourceFile: ts.SourceFile, range: Range): string | null { + const start = range[0]; + const end = range[1]; + if (start < 0 || end > sourceFile.text.length || start > end) { + return null; + } + return sourceFile.text.substring(start, end); + } + + // 根据给定的行号,获取该行的源码字符串,行号不合法则返回null + public static getLineText(sourceFile: ts.SourceFile, lineNumber: number): string | null { + const range = this.getLineRange(sourceFile, lineNumber); + if (range === null) { + return null; + } + + return sourceFile.text.substring(range[0], range[1]); + } + + // 根据给定的行号,获取该行的换行符,获取失败则使用默认的'\n'换行符 + public static getEolSymbol(sourceFile: ts.SourceFile, lineNumber: number): string { + let res = '\n'; + const lineStr = this.getLineText(sourceFile, lineNumber); + if (lineStr === null) { + return res; + } + + const lfIndex = lineStr.indexOf('\n'); + if (lfIndex > 0 && lineStr[lfIndex - 1] === '\r') { + res = '\r\n'; + } + return res; + } + + // 根据给定的行号,获取该行的缩进数量,采用空格缩进时为空格数量,采用tab缩进时为tab数量,行号不合法则返回null + public static getIndentOfLine(sourceFile: ts.SourceFile, lineNumber: number): number | null { + const lineStr = this.getLineText(sourceFile, lineNumber); + if (lineStr === null) { + return null; + } + + const space = ' '; + let res = 0; + for (const char of lineStr) { + if (char === space) { + res++; + } else { + break; + } + } + return res; + } + + // 根据给定的行号,获取该行附近的缩进宽度,采用空格缩进时为空格数量,采用tab缩进时为tab数量,无法找到则返回2 + public static getIndentWidth(sourceFile: ts.SourceFile, lineNumber: number): number { + const lineIndent = FixUtils.getIndentOfLine(sourceFile, lineNumber); + let indentWidth = 0; + + // 从当前行向上寻找最近的缩进量 + let currLineIndent = lineIndent; + let previousLine = lineNumber - 1; + while (indentWidth <= 0 && previousLine > 0 && currLineIndent !== null) { + const previousLineIndent = FixUtils.getIndentOfLine(sourceFile, previousLine); + if (previousLineIndent !== null) { + indentWidth = Math.abs(currLineIndent - previousLineIndent); + } + currLineIndent = previousLineIndent; + previousLine--; + } + if (indentWidth > 0) { + return indentWidth; + } + + // 从当前行向下寻找最近的缩进量 + currLineIndent = lineIndent; + let nextLine = lineNumber + 1; + while (indentWidth <= 0 && nextLine < sourceFile.getLineStarts().length && currLineIndent !== null) { + const nextLineIndent = FixUtils.getIndentOfLine(sourceFile, nextLine); + if (nextLineIndent !== null) { + indentWidth = Math.abs(nextLineIndent - currLineIndent); + } + currLineIndent = nextLineIndent; + nextLine++; + } + if (indentWidth > 0) { + return indentWidth; + } + return 2; + } + public static getTextEof(text: string): string { if (text.includes('\r\n')) { return '\r\n'; @@ -67,18 +193,18 @@ export class FixUtils { } public static isRuleFix(object: any): object is RuleFix { - return typeof object === "object" && 'range' in object && 'text' in object; + return typeof object === 'object' && 'range' in object && 'text' in object; } public static isFunctionFix(object: any): object is FunctionFix { - return typeof object === "object" && 'fix' in object; + return typeof object === 'object' && 'fix' in object; } public static isAIFix(object: any): object is AIFix { - return typeof object === "object" && 'text' in object; + return typeof object === 'object' && 'text' in object; } - public static hasOwnProperty(object: any, key: string): boolean { - return typeof object === "object" && key in object; + public static hasOwnPropertyOwn(object: any, key: string): boolean { + return typeof object === 'object' && key in object; } } diff --git a/ets2panda/linter/homecheck/src/utils/common/GeneratingJsonFile.ts b/ets2panda/linter/homecheck/src/utils/common/GeneratingJsonFile.ts index 33c2b38193..7df577806f 100644 --- a/ets2panda/linter/homecheck/src/utils/common/GeneratingJsonFile.ts +++ b/ets2panda/linter/homecheck/src/utils/common/GeneratingJsonFile.ts @@ -23,7 +23,7 @@ const severitys: string[] = ['OFF', 'WARN', 'ERROR', 'SUGGESTION']; const FILE_NAMING_RULE = '@hw-stylistic/file-naming-convention'; export class GeneratingJsonFile { - public static generatingJsonFile(filePath: string, fileReports: FileReports[]) { + public static generatingJsonFile(filePath: string, fileReports: FileReports[]): void { const fileDefectInfos = this.format(fileReports); let results: Map = new Map(); for (let fileDefectInfo of fileDefectInfos) { @@ -49,7 +49,7 @@ export class GeneratingJsonFile { const fileDefectInfo: FileDefectInfo = { filePath: fileReport.filePath, defects: [] - } + }; for (const defect of fileReport.defects) { const defectInfo: DefectInfo = { reportLine: defect.reportLine, @@ -59,7 +59,7 @@ export class GeneratingJsonFile { mergeKey: defect.mergeKey, description: defect.description, ruleDocPath: defect.ruleDocPath - } + }; fileDefectInfo.defects.push(defectInfo); } fileDefectInfos.push(fileDefectInfo); @@ -67,7 +67,7 @@ export class GeneratingJsonFile { return fileDefectInfos; } - private static addResult(defect: FileDefectInfo, results: Map) { + private static addResult(defect: FileDefectInfo, results: Map): void { const normalizedPath = path.normalize(defect.filePath).toLocaleLowerCase(); if (!results.has(normalizedPath)) { results.set(normalizedPath, defect); @@ -92,13 +92,13 @@ export class GeneratingJsonFile { }); } - private static format2(results: Map) { + private static format2(results: Map): string { const jsonResults: JsonResult[] = []; for (let result of results) { const oneResult: JsonResult = { filePath: '', messages: [] - } + }; oneResult.filePath = result[1].filePath; let defects = result[1].defects; for (let defect of defects) { @@ -108,7 +108,7 @@ export class GeneratingJsonFile { severity: '', message: '', rule: '', - } + }; oneDefect.line = defect.reportLine; oneDefect.column = defect.reportColumn; oneDefect.severity = defect.severity; diff --git a/ets2panda/linter/homecheck/src/utils/common/GlobMatch.ts b/ets2panda/linter/homecheck/src/utils/common/GlobMatch.ts index c1f25cdc7c..4b45e07d3a 100644 --- a/ets2panda/linter/homecheck/src/utils/common/GlobMatch.ts +++ b/ets2panda/linter/homecheck/src/utils/common/GlobMatch.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -34,14 +34,14 @@ export class GlobMatch { const char = glob[i]; if (char === '*') { if (!isStar) { - regexp += '.*'; // 匹配任意字符序列,包括空字符串。 + regexp += '.*'; // 匹配任意字符序列,包括空字符串。 } isStar = true; continue; } else if (char === '?') { - regexp += '.'; // 匹配任意单个字符。 + regexp += '.'; // 匹配任意单个字符。 } else if (specialChars.has(char)) { - regexp += `\\${char}`; // 转义特殊字符。 + regexp += `\\${char}`; // 转义特殊字符。 } else { regexp += char; } diff --git a/ets2panda/linter/homecheck/src/utils/common/Json5parser.ts b/ets2panda/linter/homecheck/src/utils/common/Json5parser.ts index 78d4ef7bdf..712ee7728b 100644 --- a/ets2panda/linter/homecheck/src/utils/common/Json5parser.ts +++ b/ets2panda/linter/homecheck/src/utils/common/Json5parser.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,7 +13,7 @@ * limitations under the License. */ -import { ts } from "arkanalyzer"; +import { ts } from 'arkanalyzer'; import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'Json5parser'); @@ -106,7 +106,7 @@ export class Json5parser { * @param file - 所属的 JSON 源文件 * @returns 解析后的数组 */ - private static parseArrayLiteral(node: ts.Expression, file: ts.JsonSourceFile) { + private static parseArrayLiteral(node: ts.Expression, file: ts.JsonSourceFile): unknown[] { const res: unknown[] = []; (node as ts.ArrayLiteralExpression).elements.forEach(n => { res.push(this.parsePropertyInitializer(n, file)); diff --git a/ets2panda/linter/homecheck/src/utils/common/ScopeHelper.ts b/ets2panda/linter/homecheck/src/utils/common/ScopeHelper.ts index 9bf9c65260..4c481600dd 100644 --- a/ets2panda/linter/homecheck/src/utils/common/ScopeHelper.ts +++ b/ets2panda/linter/homecheck/src/utils/common/ScopeHelper.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,12 +12,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { ArkArrayRef, ArkAssignStmt, ArkClass, ArkIfStmt, ArkThisRef, BasicBlock, DEFAULT_ARK_METHOD_NAME, Local, Scene, Stmt } from "arkanalyzer"; +import { ArkArrayRef, ArkAssignStmt, ArkClass, ArkIfStmt, ArkThisRef, BasicBlock, DEFAULT_ARK_METHOD_NAME, Local, Scene, Stmt } from 'arkanalyzer'; import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; -import { CheckerStorage, CheckerUtils, Scope, ScopeType, TempLocation } from "../../Index"; -import { Variable } from "../../model/Variable"; -import { VarInfo } from "../../model/VarInfo"; -import { FixUtils } from "./FixUtils"; +import { CheckerStorage, CheckerUtils, Scope, ScopeType, TempLocation } from '../../Index'; +import { Variable } from '../../model/Variable'; +import { VarInfo } from '../../model/VarInfo'; +import { FixUtils } from './FixUtils'; const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'ScopeHelper'); @@ -49,7 +49,7 @@ export class ScopeHelper { this.finishBlockSet = new Set(); this.firstBlock = method.getBody()?.getCfg()?.getStartingBlock(); if (!this.firstBlock) { - logger.debug(`${clazz.getName()}::${method.getName()} has no body.`); + logger.trace(`${clazz.getName()}::${method.getName()} has no body.`); continue; } let curScope = firstScope; @@ -84,7 +84,7 @@ export class ScopeHelper { curScope = this.genChildScope(curScope, ScopeType.FOR_CONDITION_TYPE); nextScopeType = ScopeType.UNKNOWN_TYPE; } - if (!FixUtils.hasOwnProperty(stmt, 'scope')) { + if (!FixUtils.hasOwnPropertyOwn(stmt, 'scope')) { Object.defineProperty(stmt, 'scope', { value: curScope }); } if (stmt instanceof ArkAssignStmt && !this.assignStmtProcess(stmt, curScope)) { diff --git a/ets2panda/linter/homecheck/src/utils/common/Utils.ts b/ets2panda/linter/homecheck/src/utils/common/Utils.ts index 555f05ec86..3dcd8e695d 100644 --- a/ets2panda/linter/homecheck/src/utils/common/Utils.ts +++ b/ets2panda/linter/homecheck/src/utils/common/Utils.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,8 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import Logger, {LOG_LEVEL, LOG_MODULE_TYPE} from 'arkanalyzer/lib/utils/logger'; -import {Command, OptionValues} from 'commander'; +import Logger, { LOG_LEVEL, LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; +import { Command, OptionValues } from 'commander'; const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'Utils'); @@ -48,10 +48,17 @@ export class Utils { * 设置日志路径 * @param logPath 日志路径 */ - static setLogPath(logPath: string) { + static setLogPath(logPath: string): void { Logger.configure(logPath, LOG_LEVEL.INFO, LOG_LEVEL.INFO); } + /** + * 设置日志信息,包含路径、arkanalyzer日志级别、homecheck日志级别 + */ + static setLogConfig(logPath: string, aaLevel: LOG_LEVEL, hcLevel: LOG_LEVEL): void { + Logger.configure(logPath, aaLevel, hcLevel); + } + /** * 获取枚举类型的值 * @param value - 枚举值,可以是字符串或数字 @@ -60,7 +67,7 @@ export class Utils { */ static getEnumValues(value: string | number, enumType: any): any { const key = Object.keys(enumType).find(k => k.toLowerCase() === value || enumType[k as string] === value); - return enumType[key as string] + return enumType[key as string]; } /** @@ -78,3 +85,10 @@ export class Utils { return colA - colB; } } + +export type WarnInfo = { + line: number, + startCol: number, + endCol: number, + filePath: string +}; diff --git a/ets2panda/linter/homecheck/vitest.config.ts b/ets2panda/linter/homecheck/vitest.config.ts index fe1725a625..211d2a840e 100644 --- a/ets2panda/linter/homecheck/vitest.config.ts +++ b/ets2panda/linter/homecheck/vitest.config.ts @@ -13,8 +13,8 @@ * limitations under the License. */ -import tsconfigPaths from 'vite-tsconfig-paths' -import { defineConfig } from 'vitest/config' +import tsconfigPaths from 'vite-tsconfig-paths'; +import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { @@ -23,4 +23,4 @@ export default defineConfig({ plugins: [ tsconfigPaths() ] -}) \ No newline at end of file +}); \ No newline at end of file diff --git a/ets2panda/linter/package.json b/ets2panda/linter/package.json index e56918d6e1..73dd2a4180 100644 --- a/ets2panda/linter/package.json +++ b/ets2panda/linter/package.json @@ -16,15 +16,15 @@ "compile": "npm run tsc", "postcompile": "node scripts/testRunner/post-compile.mjs", "build": "npm run clean && npm run compile && npm run webpack && npm run pack:linter", - "preinstall": "npm install --prefix arkanalyzer && npm install --prefix homecheck", "install-ohos-typescript": "node scripts/install-ohos-typescript-and-homecheck.mjs", "pack:linter": "rimraf bundle && mkdir bundle && npm pack --pack-destination bundle", "pretest": " npm run fix", "test": "npm run test_all && npm run test_ts_import_ets", - "test_all": "npm run testrunner -- -d test/main,test/rules,test/regression,test/extended_features,test/ohmurl,test/interop,test/sdkwhite", + "test_all": "npm run testrunner -- -d test/main,test/rules,test/regression,test/extended_features,test/migration,test/ohmurl,test/interop,test/sdkwhite,test/concurrent,test/builtin", "test_main": "npm run testrunner -- -d test/main", "test_ohmurl": "npm run testrunner -- -d test/ohmurl", "test_interop": "npm run testrunner -- -d test/interop", + "test_concurrent": "npm run testrunner -- -d test/concurrent", "test_rules": "npm run testrunner -- -d test/rules", "test_regression": "npm run testrunner -- -d test/regression", "test_extended_features": "npm run testrunner -- -d test/extended_features", @@ -33,9 +33,9 @@ "test_regression_sdk": "npm run testrunner -- -d test/regression --sdk", "test_rules_sdk": "npm run testrunner -- -d test/rules --sdk", "test_ts_import_ets": "npm run testrunner -- -d test/ts_import_ets/ts --sdk --interop-mode", - "test_migration": "npm run testrunner -- -d test/migrate", + "test_migration": "npm run testrunner -- -d test/migration", "testrunner": "npm run compile && node build/testRunner/TestRunner.js", - "update-tests": "node scripts/update-test-results.mjs test/main test/rules test/regression test/extended_features test/ts_import_ets/ts", + "update-tests": "node scripts/update-test-results.mjs test/main test/rules test/regression test/extended_features test/ts_import_ets/ts test/migration test/ohmurl test/interop test/sdkwhite test/concurrent test/builtin", "eslint-check": "npx eslint .", "eslint-fix": "npm run eslint-check -- --fix", "prettier-fix": "npx prettier --write .", @@ -43,8 +43,11 @@ }, "dependencies": { "commander": "^9.4.0", + "homecheck": "file:./homecheck", "log4js": "^6.4.0", - "yup": "^1.4.0" + "yup": "^1.4.0", + "fs-extra": "11.2.0", + "json5": "2.2.3" }, "devDependencies": { "@eslint/compat": "latest", diff --git a/ets2panda/linter/scripts/install-ohos-typescript-and-homecheck.mjs b/ets2panda/linter/scripts/install-ohos-typescript-and-homecheck.mjs index 912c5c599a..5fc2c55baa 100644 --- a/ets2panda/linter/scripts/install-ohos-typescript-and-homecheck.mjs +++ b/ets2panda/linter/scripts/install-ohos-typescript-and-homecheck.mjs @@ -34,13 +34,17 @@ function sleep(waitTime) { function detectOS() { let windowsPlatforms = ['win32', 'win64', 'windows', 'wince'] let linuxPlatforms = ['linux'] + let macosPlatforms = ['darwin'] + let detectedOS = null - const opetaringSystemName = os.platform().toLowerCase() + const operatingSystemName = os.platform().toLowerCase() - if (windowsPlatforms.indexOf(opetaringSystemName) !== -1) { + if (windowsPlatforms.indexOf(operatingSystemName) !== -1) { detectedOS = 'Windows' - } else if (linuxPlatforms.indexOf(opetaringSystemName) !== -1) { + } else if (linuxPlatforms.indexOf(operatingSystemName) !== -1) { detectedOS = 'Linux' + } else if (macosPlatforms.indexOf(operatingSystemName) !== -1) { + detectedOS = 'macOS' } return detectedOS @@ -49,12 +53,12 @@ function detectOS() { function backupPackageJson(dirPath) { const pkgPath = path.join(dirPath, 'package.json') const backupName = `package.json.bak-${Date.now()}` - + if (!fs.existsSync(pkgPath)) { console.error(`[ERROR] package.json not found in ${dirPath}`) process.exit(1) } - + fs.copyFileSync(pkgPath, path.join(dirPath, backupName)) return backupName } @@ -75,20 +79,20 @@ function restorePackageJson(dirPath, backupFile) { function getTypescript(detectedOS) { const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); - + const linter = __dirname + '/..' const third_party = __dirname + '/../third_party' const typescript_dir = third_party + '/third_party_typescript' const arkanalyzer = __dirname + '/../arkanalyzer' const homecheck = __dirname + '/../homecheck' - + if (!fs.existsSync(third_party)) { fs.mkdirSync(third_party); } let branch = process.env.TYPESCRIPT_BRANCH ?? 'OpenHarmony_feature_20250328' - if (detectedOS === 'Linux') { + if (detectedOS === 'Linux' || detectedOS === 'macOS') { let timeToWait = 5000 const iterations = 4 if (!fs.existsSync(typescript_dir)) { @@ -131,9 +135,9 @@ function getTypescript(detectedOS) { console.log('OS was detected, but was not expected') exit(1) } - + const npm_typescript_package = shell.exec('npm pack').stdout.trim() - + shell.cd(arkanalyzer) const arkanalyzerBackFile = backupPackageJson(arkanalyzer) shell.exec(`npm install ${typescript_dir}/${npm_typescript_package}`) @@ -141,7 +145,7 @@ function getTypescript(detectedOS) { const npm_arkanalyzer_package = shell.exec('npm pack').stdout.trim() restorePackageJson(arkanalyzer, arkanalyzerBackFile) shell.rm('-rf', 'lib') - + shell.cd(homecheck) const homecheckBackFile = backupPackageJson(homecheck) @@ -154,11 +158,15 @@ function getTypescript(detectedOS) { shell.cd(linter) shell.exec(`npm install --no-save ${typescript_dir}/${npm_typescript_package} ${homecheck}/${npm_homecheck_package}`) - + const node_modules = linter + '/node_modules' - + fs.rmSync(node_modules + '/typescript', {recursive: true, force: true}) - shell.exec(`tar -xzf "${typescript_dir}/${npm_typescript_package}" -C node_modules --strip-components 1 --one-top-level=typescript`) + + const targetDir = path.join('node_modules', 'typescript') + fs.mkdirSync(targetDir, { recursive: true }) + + shell.exec(`tar -xzf "${typescript_dir}/${npm_typescript_package}" -C "${targetDir}" --strip-components 1`) shell.rm(`${typescript_dir}/${npm_typescript_package}`) shell.rm(`${arkanalyzer}/${npm_arkanalyzer_package}`) shell.rm(`${homecheck}/${npm_homecheck_package}`) diff --git a/ets2panda/linter/scripts/update-test-results.mjs b/ets2panda/linter/scripts/update-test-results.mjs index a76bc1b09d..19cbb231f3 100644 --- a/ets2panda/linter/scripts/update-test-results.mjs +++ b/ets2panda/linter/scripts/update-test-results.mjs @@ -17,24 +17,26 @@ import * as fs from 'node:fs'; import * as path from 'node:path'; const TS_EXT = ".ts"; -const ETS_EXT = ".ets"; -const TSX_EXT = ".tsx"; -const ETSX_EXT = ".etsx"; const D_TS_EXT = '.d.ts'; +const TSX_EXT = ".tsx"; +const ETS_EXT = ".ets"; class Mode { - static DEFAULT = 1; - static AUTOFIX = 2; - static ARKTS2 = 3; + static DEFAULT = 1; + static AUTOFIX = 2; + static ARKTS2 = 3; + static MIGRATE = 4; } -const RESULT_EXT = []; -RESULT_EXT[Mode.DEFAULT] = '.json'; -RESULT_EXT[Mode.AUTOFIX] = '.autofix.json'; -RESULT_EXT[Mode.ARKTS2] = '.arkts2.json'; +const LINT_RESULT_EXT = []; +LINT_RESULT_EXT[Mode.DEFAULT] = '.json'; +LINT_RESULT_EXT[Mode.AUTOFIX] = '.autofix.json'; +LINT_RESULT_EXT[Mode.ARKTS2] = '.arkts2.json'; +LINT_RESULT_EXT[Mode.MIGRATE] = '.migrate.json'; const DIFF_EXT = '.diff'; const RESULTS_DIR = 'results'; const TEST_ARGS_EXT = '.args.json'; +const MIGRATE_RESULT_SUFFIX = '.migrate'; let testDirs = []; @@ -42,96 +44,138 @@ let testDirs = []; let force_update = false; for (let arg of process.argv.slice(2)) { - if (arg === '--force') - force_update = true; - else - testDirs.push(arg); + if (arg === '--force') + force_update = true; + else + testDirs.push(arg); } -const DEFAULT_COPYRIGHT = [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." +const DEFAULT_COPYRIGHT = [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." ]; function readJsonFile(filePath) { - try { - let resultFile = fs.readFileSync(filePath).toString(); - return JSON.parse(resultFile); - } catch (error) { - return undefined; - } + try { + let resultFile = fs.readFileSync(filePath).toString(); + return JSON.parse(resultFile); + } catch (error) { + return undefined; + } } function updateTestFile(testDir, testFile) { - let testModes = [Mode.DEFAULT]; - - const testArgsFile = path.join(testDir, testFile + TEST_ARGS_EXT); - if (fs.existsSync(testArgsFile)) { - const testArgs = readJsonFile(testArgsFile); - if (testArgs?.mode?.autofix !== undefined) testModes.push(Mode.AUTOFIX); - if (testArgs?.mode?.arkts2 !== undefined) testModes.push(Mode.ARKTS2); - } - - for (const mode of testModes) { - updateTest(testDir, testFile, mode); - } + let testModes = [Mode.DEFAULT]; + + const testArgsFile = path.join(testDir, testFile + TEST_ARGS_EXT); + if (fs.existsSync(testArgsFile)) { + const testArgs = readJsonFile(testArgsFile); + if (testArgs?.mode?.autofix !== undefined) testModes.push(Mode.AUTOFIX); + if (testArgs?.mode?.arkts2 !== undefined) testModes.push(Mode.ARKTS2); + if (testArgs?.mode?.migrate !== undefined) testModes.push(Mode.MIGRATE); + } + + for (const mode of testModes) { + updateTest(testDir, testFile, mode); + } } function updateTest(testDir, testFile, mode) { - let resultExt = RESULT_EXT[mode]; - let resultFileWithExt = testFile + resultExt; - let resultFilePath = path.join(testDir, resultFileWithExt); - - // Update test result when: - // - '.diff' exists - // - expected '.json' for specified test mode doesn't exist - // - 'force' option is enabled - if (fs.existsSync(resultFilePath) && !fs.existsSync(path.join(testDir, RESULTS_DIR, resultFileWithExt + DIFF_EXT)) && !force_update) { - return; - } - - let expectedResult = readJsonFile(resultFilePath); - - const copyright = expectedResult?.copyright ?? DEFAULT_COPYRIGHT; - - let actualResult = readJsonFile(path.join(testDir, RESULTS_DIR, resultFileWithExt)); - if (!actualResult || !actualResult.result) { - console.log(`Failed to update ${resultFileWithExt}: couldn't process ACTUAL result file.`); - return; - } - - // Write file with actual test results. - let newResultJSON = JSON.stringify({ copyright, result: actualResult.result }, null, 4); + updateLintResult(testDir, testFile, mode); + if (mode === Mode.MIGRATE) { + updateMigrateResult(testDir, testFile); + } +} + +function updateLintResult(testDir, testFile, mode) { + let resultExt = LINT_RESULT_EXT[mode]; + let resultFileWithExt = testFile + resultExt; + let resultFilePath = path.join(testDir, resultFileWithExt); + + // Update test result when: + // - '.diff' exists + // - expected '.json' for specified test mode doesn't exist + // - 'force' option is enabled + if (fs.existsSync(resultFilePath) && !fs.existsSync(path.join(testDir, RESULTS_DIR, resultFileWithExt + DIFF_EXT)) && !force_update) { + return; + } + + let expectedResult = readJsonFile(resultFilePath); + + const copyright = expectedResult?.copyright ?? DEFAULT_COPYRIGHT; + + let actualResult = readJsonFile(path.join(testDir, RESULTS_DIR, resultFileWithExt)); + if (!actualResult || !actualResult.result) { + console.log(`Failed to update ${resultFileWithExt}: couldn't process ACTUAL result file.`); + return; + } + + // Write file with actual test results. + try { + const newResultJSON = JSON.stringify({ copyright, result: actualResult.result }, null, 4); fs.writeFileSync(resultFilePath, newResultJSON); + } + catch (e) { + console.log(`Failed to update ${resultFileWithExt}: ${e.message || e}`); + return; + } + + + console.log(`Updated ${resultFileWithExt}`); +} - console.log(`Updated ${resultFileWithExt}`); +function updateMigrateResult(testDir, testFile) { + let resultExt = MIGRATE_RESULT_SUFFIX + path.extname(testFile); + let resultFileWithExt = testFile + resultExt; + let resultFilePath = path.join(testDir, resultFileWithExt); + + // Update test result when: + // - '.diff' exists + // - expected result file doesn't exist + // - 'force' option is enabled + if (fs.existsSync(resultFilePath) && !fs.existsSync(path.join(testDir, RESULTS_DIR, resultFileWithExt + DIFF_EXT)) && !force_update) { + return; + } + + try { + const actualResultFilePath = path.join(testDir, RESULTS_DIR, resultFileWithExt); + fs.copyFileSync(actualResultFilePath, resultFilePath); + } + catch (e) { + console.log(`Failed to update ${resultFileWithExt}: ${e.message || e}`); + return; + } + + console.log(`Updated ${resultFileWithExt}`); } for (let testDir of testDirs) { - if (!fs.existsSync(path.join(testDir, RESULTS_DIR))) continue; - - // Get tests from test directory. - let testFiles = fs.readdirSync(testDir).filter(x => - (x.trimEnd().endsWith(TS_EXT) && !x.trimEnd().endsWith(D_TS_EXT)) || - x.trimEnd().endsWith(TSX_EXT) || - x.trimEnd().endsWith(ETS_EXT) || - x.trimEnd().endsWith(ETSX_EXT) - ); - - if (!testFiles) continue; - - // Update result for each test: - for (let testFile of testFiles) { - updateTestFile(testDir, testFile); - } + if (!fs.existsSync(path.join(testDir, RESULTS_DIR))) continue; + + // Get tests from test directory. + let testFiles = fs.readdirSync(testDir).filter(x => { + const file = x.trimEnd(); + return ( + (file.endsWith(TS_EXT) && !file.endsWith(D_TS_EXT)) || + file.endsWith(TSX_EXT) || + file.endsWith(ETS_EXT) + ) && !file.endsWith(MIGRATE_RESULT_SUFFIX + path.extname(file)) + }); + + if (!testFiles) continue; + + // Update result for each test: + for (let testFile of testFiles) { + updateTestFile(testDir, testFile); + } } \ No newline at end of file diff --git a/ets2panda/linter/src/cli/CommandLineParser.ts b/ets2panda/linter/src/cli/CommandLineParser.ts index 1c82cf92eb..d7af2c1be3 100644 --- a/ets2panda/linter/src/cli/CommandLineParser.ts +++ b/ets2panda/linter/src/cli/CommandLineParser.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2024 Huawei Device Co., Ltd. + * Copyright (c) 2023-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,6 +16,7 @@ import { Logger } from '../lib/Logger'; import { logTscDiagnostic } from '../lib/utils/functions/LogTscDiagnostic'; import type { CommandLineOptions } from '../lib/CommandLineOptions'; +import { ARKTS_IGNORE_DIRS_OH_MODULES } from '../lib/utils/consts/ArktsIgnorePaths'; import type { OptionValues } from 'commander'; import { Command, Option } from 'commander'; import * as ts from 'typescript'; @@ -25,6 +26,7 @@ import * as path from 'node:path'; const TS_EXT = '.ts'; const TSX_EXT = '.tsx'; const ETS_EXT = '.ets'; +const JS_EXT = '.js'; interface CommanderParseOptions { exitOnFail?: boolean; @@ -43,6 +45,9 @@ interface ParsedCommand { const getFiles = (dir: string): string[] => { const resultFiles: string[] = []; + if (dir.includes(ARKTS_IGNORE_DIRS_OH_MODULES)) { + return []; + } const files = fs.readdirSync(dir); for (let i = 0; i < files.length; ++i) { @@ -51,7 +56,7 @@ const getFiles = (dir: string): string[] => { resultFiles.push(...getFiles(name)); } else { const extension = path.extname(name); - if (extension === TS_EXT || extension === TSX_EXT || extension === ETS_EXT) { + if (extension === TS_EXT || extension === TSX_EXT || extension === ETS_EXT || extension === JS_EXT) { resultFiles.push(name); } } @@ -87,18 +92,36 @@ function parseCommand(program: Command, cmdArgs: string[]): ParsedCommand { }; } -function formOptionPaths(cmdlOptions: CommandLineOptions, options: OptionValues): CommandLineOptions { - const opts = cmdlOptions; - if (options.sdkExternalApiPath) { - opts.sdkExternalApiPath = options.sdkExternalApiPath; +function formSdkOptions(cmdOptions: CommandLineOptions, commanderOpts: OptionValues): void { + if (commanderOpts.sdkExternalApiPath) { + cmdOptions.sdkExternalApiPath = commanderOpts.sdkExternalApiPath; } - if (options.sdkDefaultApiPath) { - opts.sdkDefaultApiPath = options.sdkDefaultApiPath; + if (commanderOpts.sdkDefaultApiPath) { + cmdOptions.sdkDefaultApiPath = commanderOpts.sdkDefaultApiPath; } - if (options.arktsWholeProjectPath) { - opts.arktsWholeProjectPath = options.arktsWholeProjectPath; + if (commanderOpts.arktsWholeProjectPath) { + cmdOptions.arktsWholeProjectPath = commanderOpts.arktsWholeProjectPath; + } +} + +function formMigrateOptions(cmdOptions: CommandLineOptions, commanderOpts: OptionValues): void { + if (commanderOpts.migrate) { + cmdOptions.linterOptions.migratorMode = true; + cmdOptions.linterOptions.enableAutofix = true; + } + if (commanderOpts.migrationBackupFile === false) { + cmdOptions.linterOptions.noMigrationBackupFile = true; + } + if (commanderOpts.migrationMaxPass) { + const num = Number(commanderOpts.migrationMaxPass); + cmdOptions.linterOptions.migrationMaxPass = isNaN(num) ? 0 : num; + } + if (commanderOpts.migrationReport) { + cmdOptions.linterOptions.migrationReport = true; + } + if (commanderOpts.arktsWholeProjectPath) { + cmdOptions.linterOptions.wholeProjectPath = commanderOpts.arktsWholeProjectPath; } - return opts; } function formCommandLineOptions(parsedCmd: ParsedCommand): CommandLineOptions { @@ -114,7 +137,7 @@ function formCommandLineOptions(parsedCmd: ParsedCommand): CommandLineOptions { opts.logTscErrors = true; } if (options.devecoPluginMode) { - opts.linterOptions.ideMode = true; + opts.devecoPluginModeDeprecated = true; } if (options.checkTsAsSource !== undefined) { opts.linterOptions.checkTsAsSource = options.checkTsAsSource; @@ -140,14 +163,15 @@ function formCommandLineOptions(parsedCmd: ParsedCommand): CommandLineOptions { if (options.ideInteractive) { opts.linterOptions.ideInteractive = true; } - if (options.migrate !== undefined) { - opts.linterOptions.migratorMode = options.migrate; - opts.linterOptions.enableAutofix = true; + if (options.checkTsAndJs) { + opts.linterOptions.checkTsAndJs = true; } if (options.homecheck) { opts.homecheck = true; } - return formOptionPaths(opts, options); + formSdkOptions(opts, options); + formMigrateOptions(opts, options); + return opts; } function createCommand(): Command { @@ -161,7 +185,6 @@ function createCommand(): Command { program. option('-E, --TSC_Errors', 'show error messages from Tsc'). option('--check-ts-as-source', 'check TS files as source files'). - option('--deveco-plugin-mode', 'run as IDE plugin'). option('-p, --project ', 'path to TS project config file'). option( '-f, --project-folder ', @@ -178,6 +201,10 @@ function createCommand(): Command { option('-w, --arkts-whole-project-path ', 'path to whole project'). option('--migrate', 'run as ArkTS migrator'). option('--homecheck', 'added homecheck rule validation'). + option('--no-migration-backup-file', 'Disable the backup files in migration mode'). + option('--migration-max-pass ', 'Maximum number of migration passes'). + option('--migration-report', 'Generate migration report'). + option('--check-ts-and-js', 'check ts and js files'). addOption(new Option('--warnings-as-errors', 'treat warnings as errors').hideHelp(true)). addOption(new Option('--no-check-ts-as-source', 'check TS files as third-party libary').hideHelp(true)). addOption(new Option('--no-use-rt-logic', 'run linter with SDK logic').hideHelp(true)). diff --git a/ets2panda/linter/src/cli/LinterCLI.ts b/ets2panda/linter/src/cli/LinterCLI.ts index 5738d48662..b5e9817221 100644 --- a/ets2panda/linter/src/cli/LinterCLI.ts +++ b/ets2panda/linter/src/cli/LinterCLI.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2024 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -21,14 +21,12 @@ import type { CommandLineOptions } from '../lib/CommandLineOptions'; import { lint } from '../lib/LinterRunner'; import { Logger } from '../lib/Logger'; import type { ProblemInfo } from '../lib/ProblemInfo'; -import { TypeScriptLinter } from '../lib/TypeScriptLinter'; import { parseCommandLine } from './CommandLineParser'; -import { compileLintOptions } from './Compiler'; -import type { LinterConfig } from '../lib/LinterConfig'; +import { compileLintOptions, getEtsLoaderPath } from '../lib/ts-compiler/Compiler'; +import { logStatistics } from '../lib/statistics/StatisticsLogger'; import { arkts2Rules } from '../lib/utils/consts/ArkTS2Rules'; -import type { ProblemInfo as HomeCheckProblemInfo } from 'homecheck'; import { MigrationTool } from 'homecheck'; -import { getHomeCheckConfigInfo } from '../lib/HomeCheck'; +import { getHomeCheckConfigInfo, transferIssues2ProblemInfo } from '../lib/HomeCheck'; export function run(): void { const commandLineArgs = process.argv.slice(2); @@ -39,30 +37,32 @@ export function run(): void { const cmdOptions = parseCommandLine(commandLineArgs); - TypeScriptLinter.initGlobals(); - - if (!cmdOptions.linterOptions.ideMode && !cmdOptions.linterOptions.ideInteractive) { - const compileOptions = compileLintOptions(cmdOptions); - const result = lint(compileOptions, getEtsLoaderPath(compileOptions)); - process.exit(result.errorNodes > 0 ? 1 : 0); + if (cmdOptions.devecoPluginModeDeprecated) { + runIdeModeDeprecated(cmdOptions); } else if (cmdOptions.linterOptions.ideInteractive) { - runMigrationCliMode(cmdOptions); + runIdeInteractiveMode(cmdOptions); } else { - runIDEMode(cmdOptions); + const compileOptions = compileLintOptions(cmdOptions); + const result = lint(compileOptions); + logStatistics(result.projectStats); + process.exit(result.hasErrors ? 1 : 0); } } -async function runMigrationCliMode(cmdOptions: CommandLineOptions): Promise { +async function runIdeInteractiveMode(cmdOptions: CommandLineOptions): Promise { + cmdOptions.followSdkSettings = true; + cmdOptions.disableStrictDiagnostics = true; const compileOptions = compileLintOptions(cmdOptions); - const result = lint(compileOptions, getEtsLoaderPath(compileOptions)); - const mergedProblems = new Map(); + let homeCheckResult = new Map(); + const mergedProblems = new Map(); if (cmdOptions.homecheck === true) { const { ruleConfigInfo, projectConfigInfo } = getHomeCheckConfigInfo(cmdOptions); const migrationTool = new MigrationTool(ruleConfigInfo, projectConfigInfo); await migrationTool.buildCheckEntry(); - const homeCheckResult = await migrationTool.start(); + const result = await migrationTool.start(); + homeCheckResult = transferIssues2ProblemInfo(result); for (const [filePath, problems] of homeCheckResult) { if (!mergedProblems.has(filePath)) { mergedProblems.set(filePath, []); @@ -70,30 +70,40 @@ async function runMigrationCliMode(cmdOptions: CommandLineOptions): Promise { - return arkts2Rules.includes(problem.ruleTag); - }); + let filteredProblems = problems; + if (cmdOptions.linterOptions.arkts2) { + filteredProblems = problems.filter((problem) => { + return arkts2Rules.includes(problem.ruleTag); + }); + } mergedProblems.get(filePath)!.push(...filteredProblems); } + const reportData = Object.fromEntries(mergedProblems); + await generateReportFile(reportData); for (const [filePath, problems] of mergedProblems) { - await processSyncOut( - JSON.stringify({ - filePath, - problems - }) + '\n' - ); + const reportLine = JSON.stringify({ filePath, problems }) + '\n'; + await processSyncOut(reportLine); } await processSyncErr('{"content":"report finish","messageType":1,"indictor":1}\n'); process.exit(0); } +async function generateReportFile(reportData): Promise { + const reportFilePath = path.join('scan-report.json'); + try { + await fs.promises.writeFile(reportFilePath, JSON.stringify(reportData, null, 2)); + } catch (error) { + console.error('Error generating report file:', error); + } +} + async function processSyncOut(message: string): Promise { await new Promise((resolve) => { process.stdout.write(message, () => { @@ -131,8 +141,7 @@ function showJSONMessage(problems: ProblemInfo[][]): void { Logger.info(`{"linter messages":${JSON.stringify(jsonMessage)}}`); } -function runIDEMode(cmdOptions: CommandLineOptions): void { - cmdOptions.linterOptions.ideMode = true; +function runIdeModeDeprecated(cmdOptions: CommandLineOptions): void { const tmpFileName = getTempFileName(); // read data from stdin const writeStream = fs.createWriteStream(tmpFileName, { flags: 'w' }); @@ -153,7 +162,7 @@ function runIDEMode(cmdOptions: CommandLineOptions): void { cmdOptions.parsedConfigFile.fileNames.push(tmpFileName); } const compileOptions = compileLintOptions(cmdOptions); - const result = lint(compileOptions, getEtsLoaderPath(compileOptions)); + const result = lint(compileOptions); const problems = Array.from(result.problemsInfos.values()); if (problems.length === 1) { showJSONMessage(problems); @@ -163,8 +172,3 @@ function runIDEMode(cmdOptions: CommandLineOptions): void { fs.unlinkSync(tmpFileName); }); } - -export function getEtsLoaderPath(linterConfig: LinterConfig): string | undefined { - const tsProgram = linterConfig.tscCompiledProgram.getProgram(); - return tsProgram.getCompilerOptions().etsLoaderPath; -} diff --git a/ets2panda/linter/src/lib/BaseTypeScriptLinter.ts b/ets2panda/linter/src/lib/BaseTypeScriptLinter.ts new file mode 100644 index 0000000000..82bf349ba6 --- /dev/null +++ b/ets2panda/linter/src/lib/BaseTypeScriptLinter.ts @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type * as ts from 'typescript'; +import type { LinterOptions } from './LinterOptions'; +import type { ProblemInfo } from './ProblemInfo'; +import type { Autofix } from './autofixes/Autofixer'; +import { FileStatistics } from './statistics/FileStatistics'; +import { TsUtils } from './utils/TsUtils'; +import { cookBookRefToFixTitle } from './autofixes/AutofixTitles'; +import { faultDesc } from './FaultDesc'; +import { TypeScriptLinterConfig } from './TypeScriptLinterConfig'; +import { faultsAttrs } from './FaultAttrs'; +import { cookBookTag } from './CookBookMsg'; +import { FaultID } from './Problems'; +import { ProblemSeverity } from './ProblemSeverity'; + +export abstract class BaseTypeScriptLinter { + problemsInfos: ProblemInfo[] = []; + fileStats: FileStatistics; + tsUtils: TsUtils; + + constructor( + protected readonly tsTypeChecker: ts.TypeChecker, + readonly options: LinterOptions, + protected sourceFile: ts.SourceFile + ) { + this.tsUtils = new TsUtils(this.tsTypeChecker, options); + this.fileStats = new FileStatistics(sourceFile, this.problemsInfos); + } + + protected getLineAndCharacterOfNode(node: ts.Node | ts.CommentRange): ts.LineAndCharacter { + const startPos = TsUtils.getStartPos(node); + const { line, character } = this.sourceFile.getLineAndCharacterOfPosition(startPos); + // TSC counts lines and columns from zero + return { line: line + 1, character: character + 1 }; + } + + abstract lint(): void; + + protected updateFileStats(faultId: number, line: number): void { + this.fileStats.nodeCounters[faultId]++; + this.fileStats.lineCounters[faultId].add(line); + } + + protected static addLineColumnInfoInAutofix( + autofix: Autofix[], + startPos: ts.LineAndCharacter, + endPos: ts.LineAndCharacter + ): Autofix[] { + return autofix?.map((autofixElem) => { + autofixElem.line = startPos.line + 1; + autofixElem.column = startPos.character + 1; + autofixElem.endLine = endPos.line + 1; + autofixElem.endColumn = endPos.character + 1; + return autofixElem; + }); + } + + protected incrementCounters(node: ts.Node | ts.CommentRange, faultId: number, autofix?: Autofix[]): void { + const [startOffset, endOffset] = TsUtils.getHighlightRange(node, faultId); + const startPos = this.sourceFile.getLineAndCharacterOfPosition(startOffset); + const endPos = this.sourceFile.getLineAndCharacterOfPosition(endOffset); + + const faultDescr = faultDesc[faultId]; + const faultType = TypeScriptLinterConfig.tsSyntaxKindNames[node.kind]; + + const cookBookMsgNum = faultsAttrs[faultId] ? faultsAttrs[faultId].cookBookRef : 0; + const cookBookTg = cookBookTag[cookBookMsgNum]; + const severity = faultsAttrs[faultId]?.severity ?? ProblemSeverity.ERROR; + const isMsgNumValid = cookBookMsgNum > 0; + autofix = autofix ? BaseTypeScriptLinter.addLineColumnInfoInAutofix(autofix, startPos, endPos) : autofix; + const badNodeInfo: ProblemInfo = { + line: startPos.line + 1, + column: startPos.character + 1, + endLine: endPos.line + 1, + endColumn: endPos.character + 1, + start: startOffset, + end: endOffset, + type: faultType, + severity: severity, + faultId: faultId, + problem: FaultID[faultId], + suggest: '', + // eslint-disable-next-line no-nested-ternary + rule: isMsgNumValid && cookBookTg !== '' ? cookBookTg : faultDescr ? faultDescr : faultType, + ruleTag: cookBookMsgNum, + autofixable: !!autofix, + autofix: autofix, + autofixTitle: isMsgNumValid && autofix !== undefined ? cookBookRefToFixTitle.get(cookBookMsgNum) : undefined + }; + this.problemsInfos.push(badNodeInfo); + this.updateFileStats(faultId, badNodeInfo.line); + + // problems with autofixes might be collected separately + if (this.options.reportAutofixCb && badNodeInfo.autofix) { + this.options.reportAutofixCb(badNodeInfo); + } + } +} diff --git a/ets2panda/linter/src/lib/CommandLineOptions.ts b/ets2panda/linter/src/lib/CommandLineOptions.ts index 6468a28327..2e959dff1a 100644 --- a/ets2panda/linter/src/lib/CommandLineOptions.ts +++ b/ets2panda/linter/src/lib/CommandLineOptions.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2024 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -26,4 +26,7 @@ export interface CommandLineOptions { sdkExternalApiPath?: string[]; arktsWholeProjectPath?: string; homecheck?: boolean; + followSdkSettings?: boolean; + devecoPluginModeDeprecated?: boolean; + disableStrictDiagnostics?: boolean; } diff --git a/ets2panda/linter/src/lib/CookBookMsg.ts b/ets2panda/linter/src/lib/CookBookMsg.ts index 2426d7321f..cd0f7e6fc9 100644 --- a/ets2panda/linter/src/lib/CookBookMsg.ts +++ b/ets2panda/linter/src/lib/CookBookMsg.ts @@ -16,10 +16,6 @@ export const cookBookMsg: string[] = []; export const cookBookTag: string[] = []; -for (let i = 0; i <= 344; i++) { - cookBookMsg[i] = ''; -} - cookBookTag[1] = 'Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)'; cookBookTag[2] = '"Symbol()" API is not supported (arkts-no-symbol)'; @@ -233,24 +229,30 @@ cookBookTag[187] = 'function "Math.pow()" behavior for ArkTS differs from Typescript version (arkts-math-pow-standard-diff)'; cookBookTag[189] = 'Numeric semantics is different for integer values (arkts-numeric-semantic)'; cookBookTag[190] = 'Stricter assignments into variables of function type (arkts-incompatible-function-types)'; +cookBookTag[191] = 'ASON is not supported. (arkts-no-need-stdlib-ason)'; cookBookTag[192] = 'Type "void" has no instances.(arkts-limited-void-type)'; cookBookTag[193] = '"void" operator is not supported (arkts-no-void-operator)'; cookBookTag[198] = 'Class TS overloading is not supported(arkts-no-ts-overload)'; +cookBookTag[199] = 'Sendable containers are not supported (arkts-no-need-stdlib-sendable-containers)'; cookBookTag[202] = 'Literal types are restricted(arkts-limited-literal-types)'; cookBookTag[203] = 'exponent opartions "**" and "**=" are disabled (arkts-no-exponent-op)'; cookBookTag[206] = '"debugger" is not supported (arkts-no-debugger-stmt)'; cookBookTag[207] = 'Special arguments object inside functions are not supported (arkts-no-arguments-obj)'; cookBookTag[208] = 'Tagged templates are not supported (arkts-no-tagged-templates)'; cookBookTag[209] = 'The index expression must be of a numeric type (arkts-array-index-expr-type)'; -cookBookTag[210] = 'The switch expression type must be of type number,string or enum (arkts-switch-expr)'; +cookBookTag[210] = + 'The switch expression type must be of type char, byte, short, int, long, string or enum (arkts-switch-expr)'; cookBookTag[211] = 'No two case constant expressions have identical values.(arkts-case-expr)'; cookBookTag[212] = 'The index expression must be zero or positive value.(arkts-array-index-negative)'; +cookBookTag[213] = 'Class cannot have static codeblocks. (arkts-class-lazy-import)'; +cookBookTag[214] = 'The Class object does not have a constructor. (arkts-no-arkts-constructor)'; +cookBookTag[215] = 'Array bound not checked. (arkts-runtime-array-check)'; cookBookTag[222] = 'Import for side-effect only is prohibited.(arkts-no-side-effect-import)'; cookBookTag[232] = 'Lazy import is not supported(arkts-no-lazy-import)'; cookBookTag[233] = 'Dynamic import is not supported(arkts-no-dynamic-import)'; cookBookTag[234] = 'Decorators are not supported(arkts-no-ts-decorators)'; cookBookTag[235] = 'Avoid using union types (arkts-common-union-member-access)'; -cookBookTag[236] = 'Method cant\'t override filed in interface implemented (arkts-no-method-overriding-field)'; +cookBookTag[236] = 'Method can\'t override filed in interface implemented (arkts-no-method-overriding-field)'; cookBookTag[237] = 'Array and tuple are different type(arkts-no-tuples-arrays)'; cookBookTag[238] = 'The static property has no initializer (arkts-class-static-initialization)'; cookBookTag[239] = 'This keyword cannot be used as identifiers (arkts-invalid-identifier)'; @@ -265,19 +267,36 @@ cookBookTag[257] = cookBookTag[258] = 'Data observation needs to add "@Observed" (arkui-data-observation)'; cookBookTag[259] = 'ArkUI interface should be imported before using (arkui-modular-interface)'; cookBookTag[260] = 'The "@Entry" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)'; +cookBookTag[261] = + 'The "Prop", "StorageProp", and "LocalStorageProp" decorators, as well as the "prop" and "setAndProp" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)'; +cookBookTag[262] = 'The makeObserved function is not supported (arkui-no-makeobserved-function)'; cookBookTag[263] = 'The "@Provide" annotation does not support dynamic parameters (arkui-provide-annotation-parameters)'; -cookBookTag[300] = 'The function type should be explicit (arkts-no-ts-like-function)'; +cookBookTag[264] = 'Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)'; +cookBookTag[265] = 'Direct inheritance of interop JS classes is not supported (arkts-interop-js2s-inherit-js-class)'; +cookBookTag[266] = 'Direct usage of interop JS objects is not supported (arkts-interop-js2s-traverse-js-instance)'; +cookBookTag[267] = 'Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-call-static-function)'; +cookBookTag[268] = 'Direct usage of interop JS objects is not supported (arkts-interop-js2s-condition-judgment)'; +cookBookTag[269] = + 'Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-expand-static-instance)'; +cookBookTag[270] = 'Trying to catch JS errors is not permitted (arkts-interop-js2s-js-exception)'; +cookBookTag[271] = 'No support for static dynamic import (arkts-interop-d2s-dynamic-import)'; +cookBookTag[272] = 'No support for static dynamic import (arkts-interop-ts2s-dynamic-import-ts)'; +cookBookTag[273] = 'No support for static dynamic import (arkts-interop-js2s-dynamic-import-js)'; +cookBookTag[274] = + 'The subclass constructor must call the parent class\'s parametered constructor (arkts-subclass-must-call-super-constructor-with-args)'; +cookBookTag[275] = + 'Custom components with custom layout capability need to add the "@Layoutable" decorator (arkui-custom-layout-need-add-decorator)'; +cookBookTag[300] = 'The function type should be explicit (arkts-no-ts-like-function-call)'; cookBookTag[301] = 'Importing from "oh module" requires specifying full path (arkts-ohmurl-full-path)'; cookBookTag[302] = - 'Class type is not compatible with "Object" parameter in interop call (arkts-interop-call-object-param)'; + 'Class type is not compatible with "Object" parameter in interop call (arkts-interop-d2s-static-object-on-dynamic-instance)'; cookBookTag[303] = - 'Reflect API usage is not allowed in interop calls when an "Object" parameter receives a class instance (arkts-interop-call-reflect)'; + 'Reflect API usage is not allowed in interop calls when an "Object" parameter receives a class instance (arkts-interop-d2s-static-reflect-on-dynamic-instance)'; cookBookTag[304] = 'Duplicate function name in namespace are not allowed (arkts-no-duplicate-function-name)'; -cookBookTag[305] = 'Typescript class decorators are not allowed (arkts-interop-no-decorators)'; -cookBookTag[306] = 'Cannot access typescript types directly (arkts-interop-access-ts-types)'; -cookBookTag[307] = 'Cannot invoke functions implemented in TypeScript (arkts-interop-ts-function)'; -cookBookTag[308] = 'Type "void" has no instances.(arkts-sdk-limited-void-type)'; +cookBookTag[306] = 'Cannot access typescript types directly (arkts-interop-ts2s-static-access-ts-type)'; +cookBookTag[307] = 'Trying to catch typescript errors is not permitted (arkts-interop-ts2s-ts-exception)'; +cookBookTag[308] = 'Type "void" has no instances.(sdk-limited-void-type)'; cookBookTag[309] = 'API no longer supports optional methods (sdk-optional-methods)'; cookBookTag[310] = 'Properties in "Sendable" classes and interfaces must have a Sendable data type (sdk-no-sendable-prop-types)'; @@ -286,25 +305,69 @@ cookBookTag[312] = 'Indexed access is not supported for fields (sdk-no-props-by- cookBookTag[313] = 'Constructor types are not supported - use lambda functions instead. (sdk-constructor-funcs)'; cookBookTag[314] = 'Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)'; -cookBookTag[315] = - 'API path have changed - please update your imports accordingly (arkts-sdk-no-decl-with-duplicate-name)'; -cookBookTag[316] = 'Using typeof as a type is not allowed in this API (arkts-sdk-Type-Query)'; -cookBookTag[319] = 'Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)'; +cookBookTag[315] = 'API path have changed - please update your imports accordingly (sdk-no-decl-with-duplicate-name)'; +cookBookTag[316] = 'Using typeof as a type is not allowed in this API (sdk-type-query)'; +cookBookTag[317] = '"use shared" is not supported (arkts-limited-stdlib-no-use-shared)'; +cookBookTag[318] = '"use concurrent" is not supported (arkts-limited-stdlib-no-use-concurrent)'; +cookBookTag[319] = + 'Overridden method parameters and return types must respect type inheritance principles (arkts-method-inherit-rule)'; cookBookTag[321] = 'Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)'; -cookBookTag[330] = 'Importing directly from "JS" module is not supported (arkts-no-js-import)'; -cookBookTag[331] = 'ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)'; -cookBookTag[332] = 'Properties of interop objects can\'t be accessed directly (arkts-no-js-obj-property)'; -cookBookTag[333] = 'Casting interop JS objects to "number" type is not allowed (arkts-no-js-number-import)'; -cookBookTag[334] = 'The "typeof" expression can\'t be used with interop JS objects (arkts-interop-import-typeof-js)'; -cookBookTag[335] = 'Interop object does not have property num (arkts-interop-does-not-have-num)'; -cookBookTag[336] = 'Binary operations on js objects (arkts-no-js-obj-binary-operation)'; +cookBookTag[322] = 'isConcurrent is not supported (arkts-limited-stdlib-no-support-isConcurrent)'; +cookBookTag[323] = 'Direct export of interop JS objects is not supported (arkts-interop-js2s-export-js)'; +cookBookTag[324] = 'Direct export of interop ArkTS1.0 objects is not supported (arkts-interop-d2s-export-entity)'; +cookBookTag[325] = + 'Default parameters must be placed after mandatory parameters (arkts-default-args-behind-required-args)'; +cookBookTag[326] = 'It is not allowed to create object literal in interop calls (arkts-interop-s2d-object-literal)'; +cookBookTag[327] = + 'Object literal not compatible with target union type. (arkts-interop-d2s-object-literal-no-ambiguity)'; +cookBookTag[328] = + 'Object literal cannot be directly assigned to class with a constructor. (arkts-interop-d2s-object-literal-no-args-constructor)'; +cookBookTag[329] = 'Enum cannot get member name by member value (arkts-unsupport-prop-name-from-value)'; +cookBookTag[330] = 'Importing directly from "JS" module is not supported (arkts-interop-js2s-import-js)'; +cookBookTag[331] = 'ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)'; +cookBookTag[332] = 'Properties of interop objects can\'t be accessed directly (arkts-interop-js2s-access-js-prop)'; +cookBookTag[333] = 'Casting interop JS objects to primitive types is not allowed (arkts-interop-js2s-convert-js-type)'; +cookBookTag[334] = 'The "typeof" expression can\'t be used with interop JS objects (arkts-interop-js2s-typeof-js-type)'; +cookBookTag[335] = 'Interop object does not have property num (arkts-interop-js2s-unary-op)'; +cookBookTag[336] = 'Binary operations on js objects (arkts-interop-js2s-binary-op)'; cookBookTag[337] = - 'Importing data directly from the "JS" module for comparison is not supported (arkts-js-data-compare)'; + 'Importing data directly from the "JS" module for comparison is not supported (arkts-interop-js2s-compare-js-data)'; cookBookTag[338] = - '"JS" objects can\'t be used directly as operands of the equality operators (arkts-js-equality-judgment)'; -cookBookTag[339] = 'Interop objects can\'t be indexed directly (arkts-no-js-index-import)'; -cookBookTag[340] = '"Await" operator can\'t be used with interop objects (arkts-no-import-await)'; -cookBookTag[341] = 'ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)'; -cookBookTag[342] = 'Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)'; -cookBookTag[343] = 'Usage of "instanceof" operator is not allowed with interop objects (arkts-no-import-obj-type)'; -cookBookTag[344] = 'Interop objects can\'t be incremented or decremented (arkts-no-js-obj-increases-decreases)'; + '"JS" objects can\'t be used directly as operands of the equality operators (arkts-interop-js2s-equality-judgment)'; +cookBookTag[339] = 'Interop objects can\'t be indexed directly (arkts-interop-js2s-access-js-index)'; +cookBookTag[340] = '"Await" operator can\'t be used with interop objects (arkts-interop-js2s-await-js-promise)'; +cookBookTag[341] = 'ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)'; +cookBookTag[342] = + 'Calling methods of JS Object directly in interop is not allowed (arkts-interop-js2s-call-js-method)'; +cookBookTag[343] = + 'Usage of "instanceof" operator is not allowed with interop objects (arkts-interop-js2s-instanceof-js-type)'; +cookBookTag[344] = 'Interop objects can\'t be incremented or decremented (arkts-interop-js2s-self-addtion-reduction)'; +cookBookTag[345] = 'Using thisArgs as a type is not allowed in this API (arkts-builtin-thisArgs)'; +cookBookTag[346] = 'Using "Symbol.iterator" is not allowed in this API (arkts-builtin-symbol-iterator)'; +cookBookTag[347] = 'Not support propertydescriptor (arkts-builtin-no-property-descriptor)'; +cookBookTag[348] = 'API is not support ctor signature and func (arkts-builtin-cotr)'; +cookBookTag[349] = 'SharedArrayBuffer is not supported (arkts-no-need-stdlib-sharedArrayBuffer)'; +cookBookTag[350] = + 'The taskpool setCloneList interface is deleted from ArkTS1.2 (arkts-limited-stdlib-no-setCloneList)'; +cookBookTag[351] = + 'The taskpool setTransferList interface is deleted from ArkTS1.2 (arkts-limited-stdlib-no-setTransferList)'; +cookBookTag[355] = 'Usage of standard library is restricted(arkts-limited-stdlib-no-sendable-decorator)'; +cookBookTag[356] = 'Usage of standard library is restricted(arkts-limited-stdlib-no-concurrent-decorator)'; +cookBookTag[357] = 'Worker are not supported(arkts-no-need-stdlib-worker)'; +cookBookTag[358] = + 'Using "Object.getOwnPropertyNames" is not allowed in this API (arkts-builtin-object-getOwnPropertyNames))'; +cookBookTag[359] = '"@LocalBuilder" Decorator is not supported (arkui-no-localbuilder-decorator)'; +cookBookTag[370] = 'Sparse array are not supported (arkts-no-sparse-array)'; +cookBookTag[371] = 'Enum prop as type are not supported (arkts-no-enum-prop-as-type)'; +cookBookTag[372] = 'Smart type differences (arkts-no-ts-like-smart-type)'; +cookBookTag[373] = 'Array types follow the principle of invariance (arkts-array-type-immutable)'; +cookBookTag[374] = 'ArkTS creating primitive types is not supported (arkts-primitive-type-normalization)'; +cookBookTag[375] = 'TS catch type are not supported (arkts-no-ts-like-catch-type)'; +cookBookTag[376] = 'Not supporting comparison between number type and bigint type (arkts-numeric-bigint-compare)'; +cookBookTag[377] = + 'Non-decimal BigInt literals (0x/0o/0b) are not supported. Use decimal format instead (arkts-only-support-decimal-bigint-literal)'; +cookBookTag[378] = 'Operator is not support (arkts-unsupport-operator)'; + +for (let i = 0; i <= cookBookTag.length; i++) { + cookBookMsg[i] = ''; +} diff --git a/ets2panda/linter/src/lib/FaultAttrs.ts b/ets2panda/linter/src/lib/FaultAttrs.ts index 42628f67a1..cc8cb7c218 100644 --- a/ets2panda/linter/src/lib/FaultAttrs.ts +++ b/ets2panda/linter/src/lib/FaultAttrs.ts @@ -148,9 +148,11 @@ faultsAttrs[FaultID.DynamicCtorCall] = new FaultAttributes(186); faultsAttrs[FaultID.MathPow] = new FaultAttributes(187); faultsAttrs[FaultID.NumericSemantics] = new FaultAttributes(189); faultsAttrs[FaultID.IncompationbleFunctionType] = new FaultAttributes(190); +faultsAttrs[FaultID.LimitedStdLibNoASON] = new FaultAttributes(191); faultsAttrs[FaultID.LimitedVoidType] = new FaultAttributes(192); faultsAttrs[FaultID.VoidOperator] = new FaultAttributes(193); faultsAttrs[FaultID.TsOverload] = new FaultAttributes(198); +faultsAttrs[FaultID.NoNeedStdLibSendableContainer] = new FaultAttributes(199); faultsAttrs[FaultID.LimitedLiteralType] = new FaultAttributes(202); faultsAttrs[FaultID.ExponentOp] = new FaultAttributes(203); faultsAttrs[FaultID.DebuggerStatement] = new FaultAttributes(206); @@ -160,6 +162,9 @@ faultsAttrs[FaultID.ArrayIndexExprType] = new FaultAttributes(209); faultsAttrs[FaultID.SwitchExpression] = new FaultAttributes(210); faultsAttrs[FaultID.CaseExpression] = new FaultAttributes(211); faultsAttrs[FaultID.IndexNegative] = new FaultAttributes(212); +faultsAttrs[FaultID.NoStaticOnClass] = new FaultAttributes(213); +faultsAttrs[FaultID.NoConstructorOnClass] = new FaultAttributes(214); +faultsAttrs[FaultID.RuntimeArrayCheck] = new FaultAttributes(215); faultsAttrs[FaultID.NoSideEffectImport] = new FaultAttributes(222); faultsAttrs[FaultID.ImportLazyIdentifier] = new FaultAttributes(232); faultsAttrs[FaultID.DynamicImport] = new FaultAttributes(233); @@ -179,13 +184,26 @@ faultsAttrs[FaultID.AnimatableExtendDecoratorTransform] = new FaultAttributes(25 faultsAttrs[FaultID.DataObservation] = new FaultAttributes(258); faultsAttrs[FaultID.UIInterfaceImport] = new FaultAttributes(259); faultsAttrs[FaultID.EntryAnnotation] = new FaultAttributes(260); +faultsAttrs[FaultID.PropDecoratorsAndInterfacesAreNotSupported] = new FaultAttributes(261); +faultsAttrs[FaultID.MakeObservedIsNotSupported] = new FaultAttributes(262); faultsAttrs[FaultID.ProvideAnnotation] = new FaultAttributes(263); +faultsAttrs[FaultID.InteropJsObjectUsage] = new FaultAttributes(264); +faultsAttrs[FaultID.InteropJsObjectInheritance] = new FaultAttributes(265); +faultsAttrs[FaultID.InteropJsObjectTraverseJsInstance] = new FaultAttributes(266); +faultsAttrs[FaultID.InteropJsObjectCallStaticFunc] = new FaultAttributes(267); +faultsAttrs[FaultID.InteropJsObjectConditionJudgment] = new FaultAttributes(268); +faultsAttrs[FaultID.InteropJsObjectExpandStaticInstance] = new FaultAttributes(269); +faultsAttrs[FaultID.InteropJSFunctionInvoke] = new FaultAttributes(270); +faultsAttrs[FaultID.InteropDynamicImport] = new FaultAttributes(271); +faultsAttrs[FaultID.InteropDynamicImportTs] = new FaultAttributes(272); +faultsAttrs[FaultID.InteropDynamicImportJs] = new FaultAttributes(273); +faultsAttrs[FaultID.MissingSuperCall] = new FaultAttributes(274); +faultsAttrs[FaultID.CustomLayoutNeedAddDecorator] = new FaultAttributes(275); faultsAttrs[FaultID.ExplicitFunctionType] = new FaultAttributes(300); faultsAttrs[FaultID.OhmUrlFullPath] = new FaultAttributes(301); faultsAttrs[FaultID.InteropCallObjectParam] = new FaultAttributes(302); faultsAttrs[FaultID.InteropCallReflect] = new FaultAttributes(303); faultsAttrs[FaultID.NoDuplicateFunctionName] = new FaultAttributes(304); -faultsAttrs[FaultID.InteropNoDecorators] = new FaultAttributes(305); faultsAttrs[FaultID.InteropDirectAccessToTSTypes] = new FaultAttributes(306); faultsAttrs[FaultID.InteropTSFunctionInvoke] = new FaultAttributes(307); faultsAttrs[FaultID.LimitedVoidTypeFromSdk] = new FaultAttributes(308); @@ -195,10 +213,20 @@ faultsAttrs[FaultID.ConstructorIfaceFromSdk] = new FaultAttributes(311); faultsAttrs[FaultID.PropertyAccessByIndexFromSdk] = new FaultAttributes(312); faultsAttrs[FaultID.ConstructorTypesDeprecated] = new FaultAttributes(313); faultsAttrs[FaultID.QuotedHyphenPropsDeprecated] = new FaultAttributes(314); -faultsAttrs[FaultID.ApiPathChanged] = new FaultAttributes(315); +faultsAttrs[FaultID.DuplicateDeclNameFromSdk] = new FaultAttributes(315); faultsAttrs[FaultID.SdkTypeQuery] = new FaultAttributes(316); -faultsAttrs[FaultID.InteropJsObjectUsage] = new FaultAttributes(319); +faultsAttrs[FaultID.UseSharedDeprecated] = new FaultAttributes(317); +faultsAttrs[FaultID.UseConcurrentDeprecated] = new FaultAttributes(318); +faultsAttrs[FaultID.MethodInheritRule] = new FaultAttributes(319); faultsAttrs[FaultID.LimitedStdLibNoImportConcurrency] = new FaultAttributes(321); +faultsAttrs[FaultID.IsConcurrentDeprecated] = new FaultAttributes(322); +faultsAttrs[FaultID.InteropJsObjectExport] = new FaultAttributes(323); +faultsAttrs[FaultID.InteropArkTs1ObjectExport] = new FaultAttributes(324); +faultsAttrs[FaultID.DefaultArgsBehindRequiredArgs] = new FaultAttributes(325); +faultsAttrs[FaultID.InteropStaticObjectLiterals] = new FaultAttributes(326); +faultsAttrs[FaultID.InteropObjectLiteralAmbiguity] = new FaultAttributes(327); +faultsAttrs[FaultID.InteropObjectLiteralClass] = new FaultAttributes(328); +faultsAttrs[FaultID.UnsupportPropNameFromValue] = new FaultAttributes(329); faultsAttrs[FaultID.InterOpImportJs] = new FaultAttributes(330); faultsAttrs[FaultID.CallJSFunction] = new FaultAttributes(331); faultsAttrs[FaultID.InteropObjectProperty] = new FaultAttributes(332); @@ -209,8 +237,29 @@ faultsAttrs[FaultID.BinaryOperations] = new FaultAttributes(336); faultsAttrs[FaultID.InterOpImportJsDataCompare] = new FaultAttributes(337); faultsAttrs[FaultID.InteropEqualityJudgment] = new FaultAttributes(338); faultsAttrs[FaultID.InterOpImportJsIndex] = new FaultAttributes(339); -faultsAttrs[FaultID.NoJsImportAwait] = new FaultAttributes(340); +faultsAttrs[FaultID.NoAwaitJsPromise] = new FaultAttributes(340); faultsAttrs[FaultID.InstantiatedJsOjbect] = new FaultAttributes(341); faultsAttrs[FaultID.InteropCallObjectMethods] = new FaultAttributes(342); faultsAttrs[FaultID.InteropJsInstanceof] = new FaultAttributes(343); faultsAttrs[FaultID.InteropIncrementDecrement] = new FaultAttributes(344); +faultsAttrs[FaultID.BuiltinThisArgs] = new FaultAttributes(345); +faultsAttrs[FaultID.BuiltinSymbolIterator] = new FaultAttributes(346); +faultsAttrs[FaultID.NoPropertyDescriptor] = new FaultAttributes(347); +faultsAttrs[FaultID.BuiltinNoCtorFunc] = new FaultAttributes(348); +faultsAttrs[FaultID.SharedArrayBufferDeprecated] = new FaultAttributes(349); +faultsAttrs[FaultID.SetCloneListDeprecated] = new FaultAttributes(350); +faultsAttrs[FaultID.SetTransferListDeprecated] = new FaultAttributes(351); +faultsAttrs[FaultID.LimitedStdLibNoSendableDecorator] = new FaultAttributes(355); +faultsAttrs[FaultID.LimitedStdLibNoDoncurrentDecorator] = new FaultAttributes(356); +faultsAttrs[FaultID.NoNeedStdlibWorker] = new FaultAttributes(357); +faultsAttrs[FaultID.BuiltinGetOwnPropertyNames] = new FaultAttributes(358); +faultsAttrs[FaultID.LocalBuilderDecoratorNotSupported] = new FaultAttributes(359); +faultsAttrs[FaultID.NosparseArray] = new FaultAttributes(370); +faultsAttrs[FaultID.NoEnumPropAsType] = new FaultAttributes(371); +faultsAttrs[FaultID.NoTsLikeSmartType] = new FaultAttributes(372); +faultsAttrs[FaultID.ArrayTypeImmutable] = new FaultAttributes(373); +faultsAttrs[FaultID.CreatingPrimitiveTypes] = new FaultAttributes(374); +faultsAttrs[FaultID.TsLikeCatchType] = new FaultAttributes(375); +faultsAttrs[FaultID.NumericBigintCompare] = new FaultAttributes(376); +faultsAttrs[FaultID.NondecimalBigint] = new FaultAttributes(377); +faultsAttrs[FaultID.UnsupportOperator] = new FaultAttributes(378); diff --git a/ets2panda/linter/src/lib/FaultDesc.ts b/ets2panda/linter/src/lib/FaultDesc.ts index 9257b62772..820afd8a22 100644 --- a/ets2panda/linter/src/lib/FaultDesc.ts +++ b/ets2panda/linter/src/lib/FaultDesc.ts @@ -65,6 +65,9 @@ faultDesc[FaultID.NonDeclarationInNamespace] = 'Non-declaration statements in na faultDesc[FaultID.GeneratorFunction] = 'Generator functions'; faultDesc[FaultID.FunctionContainsThis] = 'Functions containing "this"'; faultDesc[FaultID.PropertyAccessByIndex] = 'property access by index'; +faultDesc[FaultID.NoStaticOnClass] = 'No static blocks on classes'; +faultDesc[FaultID.NoConstructorOnClass] = 'No constructor field on object'; +faultDesc[FaultID.RuntimeArrayCheck] = 'Array bound not checked'; faultDesc[FaultID.JsxElement] = 'JSX Elements'; faultDesc[FaultID.EnumMemberNonConstInit] = 'Enum members with non-constant initializer'; faultDesc[FaultID.ImplementsClass] = 'Class type mentioned in "implements" clause'; @@ -93,6 +96,8 @@ faultDesc[FaultID.ConstAssertion] = '"as const" assertion'; faultDesc[FaultID.ImportAssertion] = 'Import assertion'; faultDesc[FaultID.SpreadOperator] = 'Spread operation'; faultDesc[FaultID.LimitedStdLibApi] = 'Limited standard library API'; +faultDesc[FaultID.LimitedStdLibNoASON] = 'Cannot find symbol ASON.'; +faultDesc[FaultID.NoNeedStdLibSendableContainer] = 'Sendable Containers not supported'; faultDesc[FaultID.ErrorSuppression] = 'Error suppression annotation'; faultDesc[FaultID.StrictDiagnostic] = 'Strict diagnostic'; faultDesc[FaultID.ImportAfterStatement] = 'Import declaration after other declaration or statement'; @@ -156,6 +161,9 @@ faultDesc[FaultID.DoubleDollarBindingNotSupported] = 'Incorrect bidirectional da faultDesc[FaultID.DollarBindingNotSupported] = 'Link decorator passing'; faultDesc[FaultID.ExtendDecoratorNotSupported] = '"@Extend" decorator'; faultDesc[FaultID.MethodOverridingField] = '"Method overriding field" to keep style consistent'; +faultDesc[FaultID.InteropJsObjectConditionJudgment] = 'Interop JS Object usage in a condition'; +faultDesc[FaultID.InteropJsObjectExpandStaticInstance] = 'Interop JS function usage'; +faultDesc[FaultID.InteropJSFunctionInvoke] = 'Interop JS function invoke'; faultDesc[FaultID.ExplicitFunctionType] = 'Not explicit function type'; faultDesc[FaultID.ClassstaticInitialization] = 'The static properties of a class need to have initial values'; faultDesc[FaultID.AvoidUnionTypes] = 'Union types'; @@ -164,7 +172,9 @@ faultDesc[FaultID.InvalidIdentifier] = 'Invalid identifiers'; faultDesc[FaultID.ExtendsExpression] = 'Extends Expression'; faultDesc[FaultID.NumericSemantics] = 'Numeric semantics'; faultDesc[FaultID.AnimatableExtendDecoratorTransform] = '"@AnimatableExtend" decorator'; -faultDesc[FaultID.InteropJsObjectUsage] = 'Interop JS object usage'; +faultDesc[FaultID.InteropJsObjectExport] = 'Interop JS object export'; +faultDesc[FaultID.InteropArkTs1ObjectExport] = 'Interop ArkTS1.0 object export'; +faultDesc[FaultID.DefaultArgsBehindRequiredArgs] = 'Default parameters before mandatory'; faultDesc[FaultID.NoDuplicateFunctionName] = 'No duplicate function name'; faultDesc[FaultID.OhmUrlFullPath] = 'Require full path file name'; faultDesc[FaultID.UIInterfaceImport] = 'UI interface'; @@ -172,33 +182,72 @@ faultDesc[FaultID.StylesDecoratorNotSupported] = '"@Styles" decorator'; faultDesc[FaultID.DataObservation] = 'Data observation'; faultDesc[FaultID.InteropCallReflect] = 'Interop call with Reflect API'; faultDesc[FaultID.InteropCallObjectParam] = 'Interop call with "Object" parameter'; -faultDesc[FaultID.InteropNoDecorators] = 'Interop decorators not supported'; faultDesc[FaultID.InteropDirectAccessToTSTypes] = 'TS Types Access'; faultDesc[FaultID.InteropTSFunctionInvoke] = 'TS Function Invoke'; faultDesc[FaultID.LimitedVoidTypeFromSdk] = 'Limited void type from sdk'; +faultDesc[FaultID.UseSharedDeprecated] = '"use shared" is not supported'; +faultDesc[FaultID.UseConcurrentDeprecated] = '"use concurrent" is not supported'; +faultDesc[FaultID.MethodInheritRule] = 'Method parameters/returns violate inheritance principles'; faultDesc[FaultID.EntryAnnotation] = '"@Entry" decorator parameter'; faultDesc[FaultID.ProvideAnnotation] = '"@Provide" decorator parameter'; +faultDesc[FaultID.InteropJsObjectUsage] = 'Interop JS object usage'; +faultDesc[FaultID.InteropJsObjectInheritance] = 'Interop JS class inheritance'; +faultDesc[FaultID.InteropJsObjectTraverseJsInstance] = 'Interop JS object traverse usage'; +faultDesc[FaultID.InteropJsObjectCallStaticFunc] = 'Interop JS function usage'; faultDesc[FaultID.OptionalMethodFromSdk] = 'Optional method from sdk'; faultDesc[FaultID.SendablePropTypeFromSdk] = 'ISendable is no longer supported'; faultDesc[FaultID.ConstructorIfaceFromSdk] = 'Construct signatures are not supported in interfaces from sdk'; faultDesc[FaultID.PropertyAccessByIndexFromSdk] = 'property access by index from sdk'; faultDesc[FaultID.ConstructorTypesDeprecated] = 'Constructor funcs'; faultDesc[FaultID.QuotedHyphenPropsDeprecated] = 'Quoted hyphen props deprecated'; -faultDesc[FaultID.ApiPathChanged] = 'API path have changed'; -faultDesc[FaultID.SdkTypeQuery] = 'NO typeof as a type in API'; +faultDesc[FaultID.DuplicateDeclNameFromSdk] = 'The API path has been changed due to the duplicate names in sdk.'; +faultDesc[FaultID.SdkTypeQuery] = 'No typeof as a type in API'; +faultDesc[FaultID.IsConcurrentDeprecated] = 'isConcurrent is not supported'; +faultDesc[FaultID.InteropStaticObjectLiterals] = 'Interop call object literals'; faultDesc[FaultID.LimitedStdLibNoImportConcurrency] = 'Import Concurrency Deprecated'; +faultDesc[FaultID.InteropDynamicImport] = 'Interop import await is not allowed'; +faultDesc[FaultID.InteropDynamicImportTs] = 'Interop import await is not allowed'; +faultDesc[FaultID.InteropDynamicImportJs] = 'Interop import await is not allowed'; +faultDesc[FaultID.MissingSuperCall] = 'Missing super call with args'; faultDesc[FaultID.InterOpImportJs] = 'No JS import'; +faultDesc[FaultID.InteropObjectLiteralAmbiguity] = 'Interop Object Literal ambiguity'; +faultDesc[FaultID.InteropObjectLiteralClass] = 'Interop Object Literal incompatible with class'; +faultDesc[FaultID.UnsupportPropNameFromValue] = 'Enum cannot get member name by value'; faultDesc[FaultID.CallJSFunction] = 'Call JS Function'; faultDesc[FaultID.InteropObjectProperty] = 'Interop property access'; -faultDesc[FaultID.InterOpConvertImport] = 'No import number from js file'; +faultDesc[FaultID.InterOpConvertImport] = 'No import primitive types from js file'; faultDesc[FaultID.InterOpImportJsForTypeOf] = 'TypeOf import from JS'; faultDesc[FaultID.InteropNoHaveNum] = 'Interop obj with "num" property'; faultDesc[FaultID.BinaryOperations] = 'Binary operations on js objects'; faultDesc[FaultID.InterOpImportJsDataCompare] = 'NO js import data compare'; faultDesc[FaultID.InteropEqualityJudgment] = 'Equality operator with JS objects'; faultDesc[FaultID.InterOpImportJsIndex] = 'No js index import'; -faultDesc[FaultID.NoJsImportAwait] = 'No js import await'; faultDesc[FaultID.InstantiatedJsOjbect] = 'Instantiated js ojbect'; faultDesc[FaultID.InteropCallObjectMethods] = 'Interop call methods in object'; faultDesc[FaultID.InteropJsInstanceof] = 'Instanceof operator with interop'; faultDesc[FaultID.InteropIncrementDecrement] = 'Interop increment or decrement'; +faultDesc[FaultID.BuiltinThisArgs] = 'No thisArgs as a type in API'; +faultDesc[FaultID.BuiltinSymbolIterator] = 'No "Symbol.iterator" in API'; +faultDesc[FaultID.NoPropertyDescriptor] = 'Not support property descriptor'; +faultDesc[FaultID.BuiltinNoCtorFunc] = 'Api is not support ctor-signature and call-signature'; +faultDesc[FaultID.SharedArrayBufferDeprecated] = 'SharedArrayBuffer is not supported'; +faultDesc[FaultID.SetCloneListDeprecated] = 'setCloneList is not supported'; +faultDesc[FaultID.SetTransferListDeprecated] = 'setTransferList is not supported'; +faultDesc[FaultID.LimitedStdLibNoSendableDecorator] = 'Limited stdlib no sendable decorator'; +faultDesc[FaultID.LimitedStdLibNoDoncurrentDecorator] = 'Limited stdlib no concurrent decorator'; +faultDesc[FaultID.NoNeedStdlibWorker] = 'No need stdlib worker'; +faultDesc[FaultID.BuiltinGetOwnPropertyNames] = 'No "Object.getOwnPropertyNames" in API'; +faultDesc[FaultID.LocalBuilderDecoratorNotSupported] = '"@LocalBuilder" decorator'; +faultDesc[FaultID.MakeObservedIsNotSupported] = 'MakeObserved is not supported'; +faultDesc[FaultID.PropDecoratorsAndInterfacesAreNotSupported] = 'Prop decorators and interfaces are not supported'; +faultDesc[FaultID.NoEnumPropAsType] = 'No enum prop as type'; +faultDesc[FaultID.NoAwaitJsPromise] = 'No await js promise'; +faultDesc[FaultID.NosparseArray] = 'No sparse array'; +faultDesc[FaultID.NoTsLikeSmartType] = 'No ts like smart type'; +faultDesc[FaultID.ArrayTypeImmutable] = 'Array type immutable'; +faultDesc[FaultID.CreatingPrimitiveTypes] = 'Creating primitive types'; +faultDesc[FaultID.TsLikeCatchType] = 'TS like catch type'; +faultDesc[FaultID.NumericBigintCompare] = 'No Comparison number between bigint'; +faultDesc[FaultID.NondecimalBigint] = 'No non decimal'; +faultDesc[FaultID.UnsupportOperator] = 'Unsupport operator'; +faultDesc[FaultID.CustomLayoutNeedAddDecorator] = 'Custom layout need add decorator'; diff --git a/ets2panda/linter/src/lib/HomeCheck.ts b/ets2panda/linter/src/lib/HomeCheck.ts index 1ebb9fbd7c..cbbdd29885 100644 --- a/ets2panda/linter/src/lib/HomeCheck.ts +++ b/ets2panda/linter/src/lib/HomeCheck.ts @@ -12,7 +12,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + +import * as path from 'node:path'; +import type { FileIssues, RuleFix } from 'homecheck'; import type { CommandLineOptions } from './CommandLineOptions'; +import type { ProblemInfo } from './ProblemInfo'; +import { FaultID } from './Problems'; interface RuleConfigInfo { ruleSet: string[]; @@ -36,11 +41,9 @@ export function getHomeCheckConfigInfo(cmdOptions: CommandLineOptions): { } { const languageTags = new Map(); const inputFiles = cmdOptions.inputFiles; - inputFiles.forEach((file) => { - languageTags.set(file, 2); - }); const ruleConfigInfo = { - ruleSet: ['plugin:@migration/all'] + ruleSet: ['plugin:@migration/all'], + files: ['**/*.ets', '**/*.ts', '**/*.js'] }; const projectConfigInfo = { projectName: cmdOptions.arktsWholeProjectPath, @@ -55,3 +58,41 @@ export function getHomeCheckConfigInfo(cmdOptions: CommandLineOptions): { }; return { ruleConfigInfo, projectConfigInfo }; } + +export function transferIssues2ProblemInfo(fileIssuesArray: FileIssues[]): Map { + const result = new Map(); + fileIssuesArray.forEach((fileIssues) => { + fileIssues.issues.forEach((issueReport) => { + const defect = issueReport.defect; + const problemInfo: ProblemInfo = { + line: defect.reportLine, + column: defect.reportColumn, + endLine: defect.reportLine, + endColumn: defect.reportColumn, + start: 0, + end: 0, + type: '', + severity: defect.severity, + faultId: FaultID.LAST_ID, + problem: defect.problem, + suggest: '', + rule: defect.description, + ruleTag: -1, + autofixable: defect.fixable + }; + if (problemInfo.autofixable) { + const fix = issueReport.fix as RuleFix; + const replacementText = fix.text; + const start = fix.range[0]; + const end = fix.range[1]; + problemInfo.autofix = [{ replacementText, start, end }]; + problemInfo.autofixTitle = defect.ruleId; + } + const filePath = path.normalize(defect.mergeKey.split('%')[0]); + const problems = result.get(filePath) || []; + problems.push(problemInfo); + result.set(filePath, problems); + }); + }); + return result; +} diff --git a/ets2panda/linter/src/lib/InteropTypescriptLinter.ts b/ets2panda/linter/src/lib/InteropTypescriptLinter.ts index f171370910..c9247e36ea 100644 --- a/ets2panda/linter/src/lib/InteropTypescriptLinter.ts +++ b/ets2panda/linter/src/lib/InteropTypescriptLinter.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2024 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -15,21 +15,14 @@ import * as fs from 'fs'; import * as path from 'node:path'; import * as ts from 'typescript'; -import { cookBookTag } from './CookBookMsg'; -import { faultsAttrs } from './FaultAttrs'; -import { faultDesc } from './FaultDesc'; -import { Logger } from './Logger'; -import type { ProblemInfo } from './ProblemInfo'; -import { ProblemSeverity } from './ProblemSeverity'; import { FaultID } from './Problems'; -import { LinterConfig } from './TypeScriptLinterConfig'; -import { cookBookRefToFixTitle } from './autofixes/AutofixTitles'; -import type { Autofix } from './autofixes/Autofixer'; +import { TypeScriptLinterConfig } from './TypeScriptLinterConfig'; import { TsUtils } from './utils/TsUtils'; import { ARKTS_COLLECTIONS_D_ETS, ARKTS_LANG_D_ETS } from './utils/consts/SupportedDetsIndexableTypes'; import { D_ETS, D_TS, ETS, KIT } from './utils/consts/TsSuffix'; import { forEachNodeInSubtree } from './utils/functions/ForEachNodeInSubtree'; import type { LinterOptions } from './LinterOptions'; +import { BaseTypeScriptLinter } from './BaseTypeScriptLinter'; export interface KitSymbol { source: string; @@ -42,24 +35,7 @@ export interface KitInfo { symbols?: KitSymbols; } -export class InteropTypescriptLinter { - totalVisitedNodes: number = 0; - nodeCounters: number[] = []; - lineCounters: number[] = []; - - totalErrorLines: number = 0; - errorLineNumbersString: string = ''; - totalWarningLines: number = 0; - warningLineNumbersString: string = ''; - - problemsInfos: ProblemInfo[] = []; - - tsUtils: TsUtils; - - currentErrorLine: number; - currentWarningLine: number; - - private sourceFile?: ts.SourceFile; +export class InteropTypescriptLinter extends BaseTypeScriptLinter { private isInSdk?: boolean; static kitInfos = new Map(); private static etsLoaderPath?: string; @@ -69,25 +45,15 @@ export class InteropTypescriptLinter { InteropTypescriptLinter.kitInfos = new Map(); } - private initCounters(): void { - for (let i = 0; i < FaultID.LAST_ID; i++) { - this.nodeCounters[i] = 0; - this.lineCounters[i] = 0; - } - } - constructor( - private readonly tsTypeChecker: ts.TypeChecker, - private readonly compileOptions: ts.CompilerOptions, - readonly options: LinterOptions, - etsLoaderPath: string | undefined + tsTypeChecker: ts.TypeChecker, + readonly compileOptions: ts.CompilerOptions, + options: LinterOptions, + sourceFile: ts.SourceFile ) { - this.tsUtils = new TsUtils(this.tsTypeChecker, options); - this.currentErrorLine = 0; - this.currentWarningLine = 0; - InteropTypescriptLinter.etsLoaderPath = etsLoaderPath; - InteropTypescriptLinter.sdkPath = etsLoaderPath ? path.resolve(etsLoaderPath, '../..') : undefined; - this.initCounters(); + super(tsTypeChecker, options, sourceFile); + InteropTypescriptLinter.etsLoaderPath = options.etsLoaderPath; + InteropTypescriptLinter.sdkPath = options.etsLoaderPath ? path.resolve(options.etsLoaderPath, '../..') : undefined; } readonly handlersMap = new Map([ @@ -102,84 +68,9 @@ export class InteropTypescriptLinter { [ts.SyntaxKind.ExportAssignment, this.handleExportAssignment] ]); - private getLineAndCharacterOfNode(node: ts.Node | ts.CommentRange): ts.LineAndCharacter { - const startPos = TsUtils.getStartPos(node); - const { line, character } = this.sourceFile!.getLineAndCharacterOfPosition(startPos); - // TSC counts lines and columns from zero - return { line: line + 1, character: character + 1 }; - } - - incrementCounters(node: ts.Node | ts.CommentRange, faultId: number, autofix?: Autofix[]): void { - this.nodeCounters[faultId]++; - const { line, character } = this.getLineAndCharacterOfNode(node); - if (this.options.ideMode) { - this.incrementCountersIdeMode(node, faultId, autofix); - } else { - const faultDescr = faultDesc[faultId]; - const faultType = LinterConfig.tsSyntaxKindNames[node.kind]; - Logger.info( - `Warning: ${this.sourceFile!.fileName} (${line}, ${character}): ${faultDescr ? faultDescr : faultType}` - ); - } - this.lineCounters[faultId]++; - switch (faultsAttrs[faultId].severity) { - case ProblemSeverity.ERROR: { - this.currentErrorLine = line; - ++this.totalErrorLines; - this.errorLineNumbersString += line + ', '; - break; - } - case ProblemSeverity.WARNING: { - if (line === this.currentWarningLine) { - break; - } - this.currentWarningLine = line; - ++this.totalWarningLines; - this.warningLineNumbersString += line + ', '; - break; - } - default: - } - } - - private incrementCountersIdeMode(node: ts.Node | ts.CommentRange, faultId: number, autofix?: Autofix[]): void { - if (!this.options.ideMode) { - return; - } - const [startOffset, endOffset] = TsUtils.getHighlightRange(node, faultId); - const startPos = this.sourceFile!.getLineAndCharacterOfPosition(startOffset); - const endPos = this.sourceFile!.getLineAndCharacterOfPosition(endOffset); - - const faultDescr = faultDesc[faultId]; - const faultType = LinterConfig.tsSyntaxKindNames[node.kind]; - - const cookBookMsgNum = faultsAttrs[faultId] ? faultsAttrs[faultId].cookBookRef : 0; - const cookBookTg = cookBookTag[cookBookMsgNum]; - const severity = faultsAttrs[faultId]?.severity ?? ProblemSeverity.ERROR; - const isMsgNumValid = cookBookMsgNum > 0; - const badNodeInfo: ProblemInfo = { - line: startPos.line + 1, - column: startPos.character + 1, - endLine: endPos.line + 1, - endColumn: endPos.character + 1, - start: startOffset, - end: endOffset, - type: faultType, - severity: severity, - problem: FaultID[faultId], - suggest: '', - // eslint-disable-next-line no-nested-ternary - rule: isMsgNumValid && cookBookTg !== '' ? cookBookTg : faultDescr ? faultDescr : faultType, - ruleTag: cookBookMsgNum, - autofix: autofix, - autofixTitle: isMsgNumValid && autofix !== undefined ? cookBookRefToFixTitle.get(cookBookMsgNum) : undefined - }; - this.problemsInfos.push(badNodeInfo); - } - private visitSourceFile(sf: ts.SourceFile): void { const callback = (node: ts.Node): void => { - this.totalVisitedNodes++; + this.fileStats.visitedNodes++; const handler = this.handlersMap.get(node.kind); if (handler !== undefined) { @@ -194,7 +85,7 @@ export class InteropTypescriptLinter { if (!node) { return true; } - if (LinterConfig.terminalTokens.has(node.kind)) { + if (TypeScriptLinterConfig.terminalTokens.has(node.kind)) { return true; } return false; @@ -545,8 +436,7 @@ export class InteropTypescriptLinter { kitInfo.symbols[element.name.text].source; } - lint(sourceFile: ts.SourceFile): void { - this.sourceFile = sourceFile; + lint(): void { this.isInSdk = InteropTypescriptLinter.sdkPath ? path.normalize(this.sourceFile.fileName).indexOf(InteropTypescriptLinter.sdkPath) === 0 : false; diff --git a/ets2panda/linter/src/lib/LintRunResult.ts b/ets2panda/linter/src/lib/LintRunResult.ts index d3d6ff56fc..3397a3941a 100644 --- a/ets2panda/linter/src/lib/LintRunResult.ts +++ b/ets2panda/linter/src/lib/LintRunResult.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2024 Huawei Device Co., Ltd. + * Copyright (c) 2023-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -14,8 +14,10 @@ */ import type { ProblemInfo } from './ProblemInfo'; +import type { ProjectStatistics } from './statistics/ProjectStatistics'; export interface LintRunResult { - errorNodes: number; + hasErrors: boolean; problemsInfos: Map; + projectStats: ProjectStatistics; } diff --git a/ets2panda/linter/src/lib/LinterOptions.ts b/ets2panda/linter/src/lib/LinterOptions.ts index d8cc2cdc46..f6124ac4ab 100644 --- a/ets2panda/linter/src/lib/LinterOptions.ts +++ b/ets2panda/linter/src/lib/LinterOptions.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -22,7 +22,6 @@ import type { ReportAutofixCallback } from './autofixes/ReportAutofixCallback'; // Common options interface, additional fields may be used by plugins export interface LinterOptions { checkTsAsSource?: boolean; - ideMode?: boolean; ideInteractive?: boolean; migratorMode?: boolean; warningsAsErrors?: boolean; @@ -39,4 +38,11 @@ export interface LinterOptions { interopCheckMode?: boolean; compatibleSdkVersion?: number; compatibleSdkVersionStage?: string; + etsLoaderPath?: string; + migrationMaxPass?: number; + migrationFilePathMap?: Map; + noMigrationBackupFile?: boolean; + migrationReport?: boolean; + wholeProjectPath?: string; + checkTsAndJs?: boolean; } diff --git a/ets2panda/linter/src/lib/LinterRunner.ts b/ets2panda/linter/src/lib/LinterRunner.ts index d7950d10d9..532cea2cca 100644 --- a/ets2panda/linter/src/lib/LinterRunner.ts +++ b/ets2panda/linter/src/lib/LinterRunner.ts @@ -13,19 +13,16 @@ * limitations under the License. */ +import * as fs from 'node:fs'; import * as path from 'node:path'; -import type * as ts from 'typescript'; +import * as ts from 'typescript'; import type { CommandLineOptions } from './CommandLineOptions'; -import { faultsAttrs } from './FaultAttrs'; -import { faultDesc } from './FaultDesc'; import { InteropTypescriptLinter } from './InteropTypescriptLinter'; import type { LinterConfig } from './LinterConfig'; import type { LinterOptions } from './LinterOptions'; import type { LintRunResult } from './LintRunResult'; import { Logger } from './Logger'; import type { ProblemInfo } from './ProblemInfo'; -import { ProblemSeverity } from './ProblemSeverity'; -import { FaultID } from './Problems'; import { TypeScriptLinter } from './TypeScriptLinter'; import { getTscDiagnostics } from './ts-diagnostics/GetTscDiagnostics'; import { transformTscDiagnostics } from './ts-diagnostics/TransformTscDiagnostics'; @@ -34,22 +31,15 @@ import { ARKTS_IGNORE_DIRS_OH_MODULES, ARKTS_IGNORE_FILES } from './utils/consts/ArktsIgnorePaths'; +import { EXTNAME_TS, EXTNAME_JS } from './utils/consts/ExtensionName'; import { mergeArrayMaps } from './utils/functions/MergeArrayMaps'; import { clearPathHelperCache, pathContainsDirectory } from './utils/functions/PathHelper'; import { LibraryTypeCallDiagnosticChecker } from './utils/functions/LibraryTypeCallDiagnosticChecker'; -import { compileLintOptions } from '../cli/Compiler'; +import type { createProgramCallback } from './ts-compiler/Compiler'; +import { compileLintOptions } from './ts-compiler/Compiler'; import * as qEd from './autofixes/QuasiEditor'; - -export function consoleLog(linterOptions: LinterOptions, ...args: unknown[]): void { - if (linterOptions.ideMode || linterOptions.ideInteractive) { - return; - } - let outLine = ''; - for (let k = 0; k < args.length; k++) { - outLine += `${args[k]} `; - } - Logger.info(outLine); -} +import { ProjectStatistics } from './statistics/ProjectStatistics'; +import type { BaseTypeScriptLinter } from './BaseTypeScriptLinter'; function prepareInputFilesList(cmdOptions: CommandLineOptions): string[] { let inputFiles = cmdOptions.inputFiles; @@ -81,28 +71,19 @@ function prepareInputFilesList(cmdOptions: CommandLineOptions): string[] { return inputFiles; } -function countProblems(linter: TypeScriptLinter | InteropTypescriptLinter): [number, number] { - let errorNodesTotal = 0; - let warningNodes = 0; - for (let i = 0; i < FaultID.LAST_ID; i++) { - switch (faultsAttrs[i].severity) { - case ProblemSeverity.ERROR: - errorNodesTotal += linter.nodeCounters[i]; - break; - case ProblemSeverity.WARNING: - warningNodes += linter.nodeCounters[i]; - break; - default: - } +export function lint( + config: LinterConfig, + etsLoaderPath?: string, + hcResults?: Map +): LintRunResult { + if (etsLoaderPath) { + config.cmdOptions.linterOptions.etsLoaderPath = etsLoaderPath; } - - return [errorNodesTotal, warningNodes]; + const lintResult = lintImpl(config); + return config.cmdOptions.linterOptions.migratorMode ? migrate(config, lintResult, hcResults) : lintResult; } -let linterConfig: LinterConfig; - -export function lint(config: LinterConfig, etsLoaderPath: string | undefined): LintRunResult { - linterConfig = config; +function lintImpl(config: LinterConfig): LintRunResult { const { cmdOptions, tscCompiledProgram } = config; const tsProgram = tscCompiledProgram.getProgram(); const options = cmdOptions.linterOptions; @@ -122,178 +103,144 @@ export function lint(config: LinterConfig, etsLoaderPath: string | undefined): L const tscStrictDiagnostics = getTscDiagnostics(tscCompiledProgram, srcFiles); LibraryTypeCallDiagnosticChecker.instance.rebuildTscDiagnostics(tscStrictDiagnostics); - const linter = !options.interopCheckMode ? - new TypeScriptLinter(tsProgram.getTypeChecker(), options, tscStrictDiagnostics) : - new InteropTypescriptLinter(tsProgram.getTypeChecker(), tsProgram.getCompilerOptions(), options, etsLoaderPath); - const { errorNodes, problemsInfos } = lintFiles(srcFiles, linter); + const lintResult = lintFiles(tsProgram, srcFiles, options, tscStrictDiagnostics); LibraryTypeCallDiagnosticChecker.instance.clear(); - consoleLog(options, '\n\n\nFiles scanned: ', srcFiles.length); - consoleLog(options, '\nFiles with problems: ', errorNodes); - const [errorNodesTotal, warningNodes] = countProblems(linter); - logTotalProblemsInfo(errorNodesTotal, warningNodes, linter); - logProblemsPercentageByFeatures(linter); + if (!options.ideInteractive) { + lintResult.problemsInfos = mergeArrayMaps(lintResult.problemsInfos, transformTscDiagnostics(tscStrictDiagnostics)); + } freeMemory(); - let problemsInfosValues = problemsInfos; - if (!options.ideInteractive) { - problemsInfosValues = mergeArrayMaps(problemsInfos, transformTscDiagnostics(tscStrictDiagnostics)); + return lintResult; +} + +function lintFiles( + tsProgram: ts.Program, + srcFiles: ts.SourceFile[], + options: LinterOptions, + tscStrictDiagnostics: Map +): LintRunResult { + const projectStats: ProjectStatistics = new ProjectStatistics(); + const problemsInfos: Map = new Map(); + + TypeScriptLinter.initGlobals(); + InteropTypescriptLinter.initGlobals(); + + for (const srcFile of srcFiles) { + const linter: BaseTypeScriptLinter = !options.interopCheckMode ? + new TypeScriptLinter(tsProgram.getTypeChecker(), options, srcFile, tscStrictDiagnostics) : + new InteropTypescriptLinter(tsProgram.getTypeChecker(), tsProgram.getCompilerOptions(), options, srcFile); + linter.lint(); + const problems = linter.problemsInfos; + problemsInfos.set(path.normalize(srcFile.fileName), [...problems]); + projectStats.fileStats.push(linter.fileStats); } return { - errorNodes: errorNodesTotal, - problemsInfos: problemsInfosValues + hasErrors: projectStats.hasError(), + problemsInfos, + projectStats }; } -function applyFixes(srcFile: ts.SourceFile, linter: TypeScriptLinter | InteropTypescriptLinter): void { - for (let pass = 0; pass < qEd.MAX_AUTOFIX_PASSES; pass++) { - const qe: qEd.QuasiEditor = new qEd.QuasiEditor(srcFile); - if (pass === 0) { - qe.backupSrcFile(); - } - qe.fix(linter.problemsInfos); - if (qe.wasError) { - Logger.error(`Error: fix-all converged for (${srcFile.fileName}) on pass #${pass}`); - break; - } - const tmpLinterConfig = compileLintOptions(linterConfig.cmdOptions); - const recompiledFile = tmpLinterConfig.tscCompiledProgram.getProgram().getSourceFile(srcFile.fileName); +function migrate( + initialConfig: LinterConfig, + initialLintResult: LintRunResult, + hcResults?: Map +): LintRunResult { + let linterConfig = initialConfig; + const { cmdOptions } = initialConfig; + const updatedSourceTexts: Map = new Map(); + let lintResult: LintRunResult = initialLintResult; + const problemsInfosBeforeMigrate = lintResult.problemsInfos; + + for (let pass = 0; pass < (cmdOptions.linterOptions.migrationMaxPass ?? qEd.DEFAULT_MAX_AUTOFIX_PASSES); pass++) { + const appliedFix = fix(linterConfig, lintResult, updatedSourceTexts, hcResults); + hcResults = undefined; - if (!recompiledFile) { - Logger.error(`Error: recompilation failed for (${srcFile.fileName}) on pass #${pass}`); + if (!appliedFix) { + // No fixes were applied, migration is finished. break; } - linter.problemsInfos = []; - linter.lint(recompiledFile); - } -} -function lintFiles(srcFiles: ts.SourceFile[], linter: TypeScriptLinter | InteropTypescriptLinter): LintRunResult { - let problemFiles = 0; - const problemsInfos: Map = new Map(); + // Re-compile and re-lint project after applying the fixes. + linterConfig = compileLintOptions(cmdOptions, getMigrationCreateProgramCallback(updatedSourceTexts)); + lintResult = lintImpl(linterConfig); + } - for (const srcFile of srcFiles) { - if (linter instanceof TypeScriptLinter) { - linter.initSdkInfo(); - } - const prevVisitedNodes = linter.totalVisitedNodes; - const prevErrorLines = linter.totalErrorLines; - const prevWarningLines = linter.totalWarningLines; - linter.errorLineNumbersString = ''; - linter.warningLineNumbersString = ''; - const nodeCounters: number[] = []; - - for (let i = 0; i < FaultID.LAST_ID; i++) { - nodeCounters[i] = linter.nodeCounters[i]; + // Write new text for updated source files. + updatedSourceTexts.forEach((newText, fileName) => { + if (!cmdOptions.linterOptions.noMigrationBackupFile) { + qEd.QuasiEditor.backupSrcFile(fileName); } - linter.lint(srcFile); - const problemsInfosBeforeMigrate = linter.problemsInfos; - if (linter.options.migratorMode) { - applyFixes(srcFile, linter); - } - if (linter.options.ideInteractive) { - problemsInfos.set(path.normalize(srcFile.fileName), [...problemsInfosBeforeMigrate]); - } else { - problemsInfos.set(path.normalize(srcFile.fileName), [...linter.problemsInfos]); - } - linter.problemsInfos.length = 0; - problemFiles = countProblemFiles( - nodeCounters, - problemFiles, - srcFile, - linter.totalVisitedNodes - prevVisitedNodes, - linter.totalErrorLines - prevErrorLines, - linter.totalWarningLines - prevWarningLines, - linter - ); + const filePathMap = cmdOptions.linterOptions.migrationFilePathMap; + const writeFileName = filePathMap?.get(fileName) ?? fileName; + fs.writeFileSync(writeFileName, newText); + }); + + if (cmdOptions.linterOptions.ideInteractive) { + lintResult.problemsInfos = problemsInfosBeforeMigrate; } - return { - errorNodes: problemFiles, - problemsInfos: problemsInfos - }; + + return lintResult; } -// eslint-disable-next-line max-lines-per-function, max-params -function countProblemFiles( - nodeCounters: number[], - filesNumber: number, - tsSrcFile: ts.SourceFile, - fileNodes: number, - fileErrorLines: number, - fileWarningLines: number, - linter: TypeScriptLinter | InteropTypescriptLinter -): number { - let errorNodes = 0; - let warningNodes = 0; - for (let i = 0; i < FaultID.LAST_ID; i++) { - const nodeCounterDiff = linter.nodeCounters[i] - nodeCounters[i]; - switch (faultsAttrs[i].severity) { - case ProblemSeverity.ERROR: - errorNodes += nodeCounterDiff; - break; - case ProblemSeverity.WARNING: - warningNodes += nodeCounterDiff; - break; - default: +function fix( + linterConfig: LinterConfig, + lintResult: LintRunResult, + updatedSourceTexts: Map, + hcResults?: Map +): boolean { + const program = linterConfig.tscCompiledProgram.getProgram(); + let appliedFix = false; + const mergedProblems = lintResult.problemsInfos; + if (hcResults !== undefined) { + for (const [filePath, problems] of hcResults) { + if (mergedProblems.has(filePath)) { + mergedProblems.get(filePath)!.push(...problems); + } else { + mergedProblems.set(filePath, problems); + } } } - if (errorNodes > 0) { - // eslint-disable-next-line no-param-reassign - filesNumber++; - const errorRate = (errorNodes / fileNodes * 100).toFixed(2); - const warningRate = (warningNodes / fileNodes * 100).toFixed(2); - consoleLog(linter.options, tsSrcFile.fileName, ': ', '\n\tError lines: ', linter.errorLineNumbersString); - consoleLog(linter.options, tsSrcFile.fileName, ': ', '\n\tWarning lines: ', linter.warningLineNumbersString); - consoleLog( - linter.options, - '\n\tError constructs (%): ', - errorRate, - '\t[ of ', - fileNodes, - ' constructs ], \t', - fileErrorLines, - ' lines' - ); - consoleLog( - linter.options, - '\n\tWarning constructs (%): ', - warningRate, - '\t[ of ', - fileNodes, - ' constructs ], \t', - fileWarningLines, - ' lines' - ); - } - return filesNumber; -} + mergedProblems.forEach((problemInfos, fileName) => { + // If nothing to fix, skip file + if (!qEd.QuasiEditor.hasAnyAutofixes(problemInfos)) { + return; + } -function logTotalProblemsInfo( - errorNodes: number, - warningNodes: number, - linter: TypeScriptLinter | InteropTypescriptLinter -): void { - const errorRate = (errorNodes / linter.totalVisitedNodes * 100).toFixed(2); - const warningRate = (warningNodes / linter.totalVisitedNodes * 100).toFixed(2); - consoleLog(linter.options, '\nTotal error constructs (%): ', errorRate); - consoleLog(linter.options, '\nTotal warning constructs (%): ', warningRate); - consoleLog(linter.options, '\nTotal error lines:', linter.totalErrorLines, ' lines\n'); - consoleLog(linter.options, '\nTotal warning lines:', linter.totalWarningLines, ' lines\n'); -} + const srcFile = program.getSourceFile(fileName); + if (!srcFile) { + Logger.error(`Failed to retrieve source file: ${fileName}`); + return; + } -function logProblemsPercentageByFeatures(linter: TypeScriptLinter | InteropTypescriptLinter): void { - consoleLog(linter.options, '\nPercent by features: '); - for (let i = 0; i < FaultID.LAST_ID; i++) { - const nodes = linter.nodeCounters[i]; - const lines = linter.lineCounters[i]; - const pecentage = (nodes / linter.totalVisitedNodes * 100).toFixed(2).padEnd(7, ' '); + const qe: qEd.QuasiEditor = new qEd.QuasiEditor(fileName, srcFile.text, linterConfig.cmdOptions.linterOptions); + updatedSourceTexts.set(fileName, qe.fix(problemInfos)); + appliedFix = true; + }); - consoleLog(linter.options, faultDesc[i].padEnd(55, ' '), pecentage, '[', nodes, ' constructs / ', lines, ' lines]'); - } + return appliedFix; +} + +function getMigrationCreateProgramCallback(updatedSourceTexts: Map): createProgramCallback { + return (createProgramOptions: ts.CreateProgramOptions): ts.Program => { + const compilerHost = createProgramOptions.host || ts.createCompilerHost(createProgramOptions.options, true); + const originalReadFile = compilerHost.readFile; + compilerHost.readFile = (fileName: string): string | undefined => { + const newText = updatedSourceTexts.get(path.normalize(fileName)); + return newText || originalReadFile(fileName); + }; + createProgramOptions.host = compilerHost; + return ts.createProgram(createProgramOptions); + }; } function shouldProcessFile(options: LinterOptions, fileFsPath: string): boolean { + if (!options.checkTsAndJs && (path.extname(fileFsPath) === EXTNAME_TS || path.extname(fileFsPath) === EXTNAME_JS)) { + return false; + } + if ( ARKTS_IGNORE_FILES.some((ignore) => { return path.basename(fileFsPath) === ignore; diff --git a/ets2panda/linter/src/lib/ProblemInfo.ts b/ets2panda/linter/src/lib/ProblemInfo.ts index f146ac4d28..955579e4be 100644 --- a/ets2panda/linter/src/lib/ProblemInfo.ts +++ b/ets2panda/linter/src/lib/ProblemInfo.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2024 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -14,6 +14,7 @@ */ import type { Autofix } from './autofixes/Autofixer'; +import type { FaultID } from './Problems'; export interface ProblemInfo { line: number; @@ -24,6 +25,7 @@ export interface ProblemInfo { end: number; type: string; severity: number; + faultId: FaultID; problem: string; suggest: string; rule: string; diff --git a/ets2panda/linter/src/lib/Problems.ts b/ets2panda/linter/src/lib/Problems.ts index 9b149207d4..2608582dc6 100644 --- a/ets2panda/linter/src/lib/Problems.ts +++ b/ets2panda/linter/src/lib/Problems.ts @@ -66,6 +66,9 @@ export enum FaultID { JsxElement, EnumMemberNonConstInit, ImplementsClass, + NoStaticOnClass, + NoConstructorOnClass, + RuntimeArrayCheck, MethodReassignment, MultipleStaticBlocks, ThisType, @@ -94,6 +97,8 @@ export enum FaultID { ImportAssertion, SpreadOperator, LimitedStdLibApi, + LimitedStdLibNoASON, + NoNeedStdLibSendableContainer, ErrorSuppression, StrictDiagnostic, ImportAfterStatement, @@ -157,6 +162,8 @@ export enum FaultID { DollarBindingNotSupported, ExtendDecoratorNotSupported, MethodOverridingField, + InteropJsObjectConditionJudgment, + InteropJsObjectExpandStaticInstance, ExplicitFunctionType, ClassstaticInitialization, TaggedTemplates, @@ -172,22 +179,40 @@ export enum FaultID { DataObservation, InteropCallReflect, InteropCallObjectParam, - InteropNoDecorators, InteropDirectAccessToTSTypes, InteropTSFunctionInvoke, + InteropJSFunctionInvoke, LimitedVoidTypeFromSdk, EntryAnnotation, ProvideAnnotation, + UseSharedDeprecated, + UseConcurrentDeprecated, + MethodInheritRule, OptionalMethodFromSdk, SendablePropTypeFromSdk, ConstructorIfaceFromSdk, PropertyAccessByIndexFromSdk, ConstructorTypesDeprecated, QuotedHyphenPropsDeprecated, - ApiPathChanged, + DuplicateDeclNameFromSdk, SdkTypeQuery, + IsConcurrentDeprecated, + InteropStaticObjectLiterals, InteropJsObjectUsage, + InteropJsObjectInheritance, + InteropJsObjectTraverseJsInstance, + InteropJsObjectCallStaticFunc, + InteropJsObjectExport, + InteropArkTs1ObjectExport, + DefaultArgsBehindRequiredArgs, LimitedStdLibNoImportConcurrency, + InteropDynamicImport, + InteropDynamicImportTs, + InteropDynamicImportJs, + MissingSuperCall, + InteropObjectLiteralAmbiguity, + InteropObjectLiteralClass, + UnsupportPropNameFromValue, InterOpImportJs, CallJSFunction, InteropObjectProperty, @@ -198,11 +223,35 @@ export enum FaultID { InterOpImportJsDataCompare, InteropEqualityJudgment, InterOpImportJsIndex, - NoJsImportAwait, InstantiatedJsOjbect, InteropCallObjectMethods, InteropJsInstanceof, InteropIncrementDecrement, + BuiltinThisArgs, + BuiltinSymbolIterator, + NoPropertyDescriptor, + BuiltinNoCtorFunc, + SharedArrayBufferDeprecated, + SetCloneListDeprecated, + SetTransferListDeprecated, + LimitedStdLibNoSendableDecorator, + LimitedStdLibNoDoncurrentDecorator, + NoNeedStdlibWorker, + BuiltinGetOwnPropertyNames, + LocalBuilderDecoratorNotSupported, + MakeObservedIsNotSupported, + PropDecoratorsAndInterfacesAreNotSupported, + NoEnumPropAsType, + NoAwaitJsPromise, + NosparseArray, + NoTsLikeSmartType, + ArrayTypeImmutable, + CreatingPrimitiveTypes, + TsLikeCatchType, + NumericBigintCompare, + NondecimalBigint, + UnsupportOperator, + CustomLayoutNeedAddDecorator, // this should always be last enum LAST_ID } diff --git a/ets2panda/linter/src/lib/TypeScriptLinter.ts b/ets2panda/linter/src/lib/TypeScriptLinter.ts index d1b09c5367..907593e726 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -15,29 +15,27 @@ import * as path from 'node:path'; import * as ts from 'typescript'; -import { cookBookTag } from './CookBookMsg'; -import { faultsAttrs } from './FaultAttrs'; -import { faultDesc } from './FaultDesc'; -import { Logger } from './Logger'; -import type { ProblemInfo } from './ProblemInfo'; -import { ProblemSeverity } from './ProblemSeverity'; import { FaultID } from './Problems'; -import { LinterConfig } from './TypeScriptLinterConfig'; -import { cookBookRefToFixTitle } from './autofixes/AutofixTitles'; +import { TypeScriptLinterConfig } from './TypeScriptLinterConfig'; import type { Autofix } from './autofixes/Autofixer'; import { Autofixer } from './autofixes/Autofixer'; import { SYMBOL, SYMBOL_CONSTRUCTOR, TsUtils } from './utils/TsUtils'; import { FUNCTION_HAS_NO_RETURN_ERROR_CODE } from './utils/consts/FunctionHasNoReturnErrorCode'; import { LIMITED_STANDARD_UTILITY_TYPES } from './utils/consts/LimitedStandardUtilityTypes'; import { LIKE_FUNCTION } from './utils/consts/LikeFunction'; +import { METHOD_DECLARATION } from './utils/consts/MethodDeclaration'; +import { METHOD_SIGNATURE } from './utils/consts/MethodSignature'; +import { OPTIONAL_METHOD } from './utils/consts/OptionalMethod'; import { STRINGLITERAL_NUMBER, STRINGLITERAL_STRING, STRINGLITERAL_INT, - STRINGLITERAL_ANY, STRINGLITERAL_BYTE, STRINGLITERAL_SHORT, - STRINGLITERAL_LONG + STRINGLITERAL_CHAR, + STRINGLITERAL_LONG, + STRINGLITERAL_FROM, + STRINGLITERAL_ARRAY } from './utils/consts/StringLiteral'; import { NON_INITIALIZABLE_PROPERTY_CLASS_DECORATORS, @@ -48,6 +46,8 @@ import { NON_RETURN_FUNCTION_DECORATORS } from './utils/consts/NonReturnFunction import { PROPERTY_HAS_NO_INITIALIZER_ERROR_CODE } from './utils/consts/PropertyHasNoInitializerErrorCode'; import { CONCURRENT_DECORATOR, + ISCONCURRENT, + TASKPOOL, SENDABLE_DECORATOR, SENDABLE_DECORATOR_NODES, SENDABLE_FUNCTION_UNSUPPORTED_STAGES_IN_API12, @@ -80,6 +80,8 @@ import { BUILTIN_GENERIC_CONSTRUCTORS } from './utils/consts/BuiltinGenericConst import { DEFAULT_DECORATOR_WHITE_LIST } from './utils/consts/DefaultDecoratorWhitelist'; import { INVALID_IDENTIFIER_KEYWORDS } from './utils/consts/InValidIndentifierKeywords'; import { WORKER_MODULES, WORKER_TEXT } from './utils/consts/WorkerAPI'; +import { COLLECTIONS_TEXT, COLLECTIONS_MODULES } from './utils/consts/CollectionsAPI'; +import { ASON_TEXT, ASON_MODULES, JSON_TEXT } from './utils/consts/ArkTSUtilsAPI'; import { ETS_PART, PATH_SEPARATOR } from './utils/consts/OhmUrl'; import { DOUBLE_DOLLAR_IDENTIFIER, @@ -90,16 +92,46 @@ import { skipImportDecoratorName, ENTRY_DECORATOR_NAME, PROVIDE_DECORATOR_NAME, - PROVIDE_ALLOW_OVERRIDE_PROPERTY_NAME + PROVIDE_ALLOW_OVERRIDE_PROPERTY_NAME, + ARKUI_PACKAGE_NAME, + MAKE_OBSERVED, + ARKUI_STATE_MANAGEMENT, + deepCopyDecoratorName, + deepCopyFunctionName, + StorageTypeName, + customLayoutFunctionName } from './utils/consts/ArkuiConstants'; import { arkuiImportList } from './utils/consts/ArkuiImportList'; -import { REFLECT_PROPERTIES, USE_STATIC } from './utils/consts/InteropAPI'; +import { InteropType, REFLECT_PROPERTIES, USE_STATIC } from './utils/consts/InteropAPI'; import { EXTNAME_TS, EXTNAME_D_TS, EXTNAME_JS } from './utils/consts/ExtensionName'; import { ARKTS_IGNORE_DIRS_OH_MODULES } from './utils/consts/ArktsIgnorePaths'; import type { ApiInfo, ApiListItem } from './utils/consts/SdkWhitelist'; -import { ApiList } from './utils/consts/SdkWhitelist'; +import { ApiList, SdkProblem, SdkNameInfo } from './utils/consts/SdkWhitelist'; import * as apiWhiteList from './data/SdkWhitelist.json'; -import { SdkProblem, ARKTS_WHITE_API_PATH_TEXTSTYLE } from './utils/consts/WhiteListProblemType'; +import * as builtinWhiteList from './data/BuiltinList.json'; +import { + BuiltinProblem, + SYMBOL_ITERATOR, + BUILTIN_DISABLE_CALLSIGNATURE, + GET_OWN_PROPERTY_NAMES_TEXT +} from './utils/consts/BuiltinWhiteList'; +import { + USE_SHARED, + USE_CONCURRENT, + ESLIB_SHAREDMEMORY_FILENAME, + ESLIB_SHAREDARRAYBUFFER, + TASKPOOL_MODULES +} from './utils/consts/ConcurrentAPI'; +import { + DEPRECATED_TASKPOOL_METHOD_SETCLONELIST, + DEPRECATED_TASKPOOL_METHOD_SETTRANSFERLIST, + STDLIB_TASK_CLASS_NAME, + STDLIB_TASKPOOL_OBJECT_NAME +} from './utils/consts/TaskpoolAPI'; +import { BaseTypeScriptLinter } from './BaseTypeScriptLinter'; +import type { ArrayAccess, UncheckedIdentifier, CheckedIdentifier } from './utils/consts/RuntimeCheckAPI'; +import { CheckResult } from './utils/consts/RuntimeCheckAPI'; +import { NUMBER_LITERAL } from './utils/consts/RuntimeCheckAPI'; interface InterfaceSymbolTypeResult { propNames: string[]; @@ -110,28 +142,13 @@ interface InterfaceSymbolTypePropertyNames { propertyNames: string[]; typeNames: string[]; } -export class TypeScriptLinter { - totalVisitedNodes: number = 0; - nodeCounters: number[] = []; - lineCounters: number[] = []; - - totalErrorLines: number = 0; - errorLineNumbersString: string = ''; - totalWarningLines: number = 0; - warningLineNumbersString: string = ''; - problemsInfos: ProblemInfo[] = []; - - tsUtils: TsUtils; - - currentErrorLine: number; - currentWarningLine: number; +export class TypeScriptLinter extends BaseTypeScriptLinter { supportedStdCallApiChecker: SupportedStdCallApiChecker; autofixer: Autofixer | undefined; private fileExportDeclCaches: Set | undefined; - private sourceFile?: ts.SourceFile; private useStatic?: boolean; private readonly compatibleSdkVersion: number; @@ -139,22 +156,66 @@ export class TypeScriptLinter { private static sharedModulesCache: Map; static nameSpaceFunctionCache: Map>; private readonly constVariableInitCache: Map = new Map(); - private funcMap: Map> = new Map>(); + static funcMap: Map>> = new Map>>(); private interfaceMap: Map> = new Map>(); static pathMap: Map>; static indexedTypeSet: Set; + static globalApiInfo: Map>; + static symbotIterSet: Set; + static missingAttributeSet: Set; + static literalAsPropertyNameTypeSet: Set; + private localApiListItem: ApiListItem | undefined = undefined; static initGlobals(): void { TypeScriptLinter.sharedModulesCache = new Map(); TypeScriptLinter.nameSpaceFunctionCache = new Map>(); TypeScriptLinter.pathMap = new Map>(); + TypeScriptLinter.globalApiInfo = new Map>(); + TypeScriptLinter.funcMap = new Map>>(); + TypeScriptLinter.symbotIterSet = new Set(); + TypeScriptLinter.missingAttributeSet = new Set(); + TypeScriptLinter.initSdkWhitelist(); + TypeScriptLinter.initSdkBuiltinInfo(); + TypeScriptLinter.initBuiltinlist(); } initSdkInfo(): void { - this.funcMap = new Map>(); this.interfaceMap = new Map>(); } + static initSdkBuiltinInfo(): void { + const list: ApiList = new ApiList(builtinWhiteList); + if (list?.api_list?.length > 0) { + for (const item of list.api_list) { + switch (item.api_info.problem) { + case BuiltinProblem.MissingAttributes: + TypeScriptLinter.missingAttributeSet.add(item.file_path); + break; + case BuiltinProblem.SymbolIterator: + TypeScriptLinter.symbotIterSet.add(item.file_path); + break; + case BuiltinProblem.LimitedThisArg: + TypeScriptLinter.initSdkBuiltinThisArgsWhitelist(item); + break; + default: + } + } + } + } + + static initSdkBuiltinThisArgsWhitelist(item: ApiListItem): void { + if (item.file_path === '' || !item.api_info.api_name) { + return; + } + + let funcApiInfos: Map> | undefined = TypeScriptLinter.funcMap.get(item.api_info.api_name); + if (!funcApiInfos) { + funcApiInfos = new Map>(); + TypeScriptLinter.funcMap.set(item.api_info.api_name, funcApiInfos); + } + TypeScriptLinter.addOrUpdateData(funcApiInfos, item.file_path, item.api_info); + } + private initEtsHandlers(): void { /* @@ -167,31 +228,54 @@ export class TypeScriptLinter { } } - private initCounters(): void { - for (let i = 0; i < FaultID.LAST_ID; i++) { - this.nodeCounters[i] = 0; - this.lineCounters[i] = 0; - } - } - private static addSdkIndexedTypeSetData(item: ApiListItem): void { if (item.api_info.problem === SdkProblem.IndexedAccessType) { TypeScriptLinter.indexedTypeSet.add(item); } } + private static addSdkliteralAsPropertyNameTypeSetData(item: ApiListItem): void { + if (item.api_info.problem === SdkProblem.LiteralAsPropertyName) { + TypeScriptLinter.literalAsPropertyNameTypeSet.add(item); + } + } + + private static addGlobalApiInfosCollocetionData(item: ApiListItem): void { + const problemType = item.api_info.problem; + const isGlobal = item.is_global; + if (isGlobal) { + if (!TypeScriptLinter.globalApiInfo.has(problemType)) { + TypeScriptLinter.globalApiInfo.set(problemType, new Set()); + } + const setApiListItem = TypeScriptLinter.globalApiInfo.get(problemType); + setApiListItem?.add(item); + } + } + private static initSdkWhitelist(): void { TypeScriptLinter.indexedTypeSet = new Set(); + TypeScriptLinter.literalAsPropertyNameTypeSet = new Set(); const list: ApiList = new ApiList(apiWhiteList); if (list?.api_list?.length > 0) { for (const item of list.api_list) { - item.file_path.forEach((path) => { - TypeScriptLinter.addOrUpdateData(TypeScriptLinter.pathMap, `'${path}'`, item.api_info); - }); + if (item.file_path !== '') { + TypeScriptLinter.addOrUpdateData(TypeScriptLinter.pathMap, `'${item.file_path}'`, item.api_info); + } item.import_path.forEach((path) => { TypeScriptLinter.addOrUpdateData(TypeScriptLinter.pathMap, `'${path}'`, item.api_info); }); TypeScriptLinter.addSdkIndexedTypeSetData(item); + TypeScriptLinter.addSdkliteralAsPropertyNameTypeSetData(item); + TypeScriptLinter.addGlobalApiInfosCollocetionData(item); + } + } + } + + private static initBuiltinlist(): void { + const list: ApiList = new ApiList(builtinWhiteList); + if (list?.api_list?.length > 0) { + for (const item of list.api_list) { + TypeScriptLinter.addGlobalApiInfosCollocetionData(item); } } } @@ -206,19 +290,17 @@ export class TypeScriptLinter { } constructor( - private readonly tsTypeChecker: ts.TypeChecker, - readonly options: LinterOptions, - private readonly tscStrictDiagnostics?: Map + tsTypeChecker: ts.TypeChecker, + options: LinterOptions, + sourceFile: ts.SourceFile, + readonly tscStrictDiagnostics?: Map ) { - this.tsUtils = new TsUtils(this.tsTypeChecker, options); - this.currentErrorLine = 0; - this.currentWarningLine = 0; + super(tsTypeChecker, options, sourceFile); this.supportedStdCallApiChecker = new SupportedStdCallApiChecker(this.tsUtils, this.tsTypeChecker); this.compatibleSdkVersion = options.compatibleSdkVersion || DEFAULT_COMPATIBLE_SDK_VERSION; this.compatibleSdkVersionStage = options.compatibleSdkVersionStage || DEFAULT_COMPATIBLE_SDK_VERSION_STAGE; this.initEtsHandlers(); - this.initCounters(); - TypeScriptLinter.initSdkWhitelist(); + this.initSdkInfo(); } readonly handlersMap = new Map([ @@ -227,11 +309,13 @@ export class TypeScriptLinter { [ts.SyntaxKind.Parameter, this.handleParameter], [ts.SyntaxKind.EnumDeclaration, this.handleEnumDeclaration], [ts.SyntaxKind.InterfaceDeclaration, this.handleInterfaceDeclaration], + [ts.SyntaxKind.TryStatement, this.handleTryStatement], [ts.SyntaxKind.ThrowStatement, this.handleThrowStatement], [ts.SyntaxKind.ImportClause, this.handleImportClause], [ts.SyntaxKind.ForStatement, this.handleForStatement], [ts.SyntaxKind.ForInStatement, this.handleForInStatement], [ts.SyntaxKind.ForOfStatement, this.handleForOfStatement], + [ts.SyntaxKind.IfStatement, this.handleIfStatement], [ts.SyntaxKind.ImportDeclaration, this.handleImportDeclaration], [ts.SyntaxKind.PropertyAccessExpression, this.handlePropertyAccessExpression], [ts.SyntaxKind.PropertyDeclaration, this.handlePropertyDeclaration], @@ -268,6 +352,7 @@ export class TypeScriptLinter { [ts.SyntaxKind.SpreadAssignment, this.handleSpreadOp], [ts.SyntaxKind.GetAccessor, this.handleGetAccessor], [ts.SyntaxKind.SetAccessor, this.handleSetAccessor], + [ts.SyntaxKind.StringLiteral, this.handleStringLiteral], [ts.SyntaxKind.ConstructSignature, this.handleConstructSignature], [ts.SyntaxKind.ExpressionWithTypeArguments, this.handleExpressionWithTypeArguments], [ts.SyntaxKind.ComputedPropertyName, this.handleComputedPropertyName], @@ -295,142 +380,31 @@ export class TypeScriptLinter { [ts.SyntaxKind.StructDeclaration, this.handleStructDeclaration], [ts.SyntaxKind.TypeOfExpression, this.handleInterOpImportJsOnTypeOfNode], [ts.SyntaxKind.AwaitExpression, this.handleAwaitExpression], - [ts.SyntaxKind.PostfixUnaryExpression, this.handlePostfixUnaryExpression] + [ts.SyntaxKind.PostfixUnaryExpression, this.handlePostfixUnaryExpression], + [ts.SyntaxKind.BigIntLiteral, this.handleBigIntLiteral] ]); - private getLineAndCharacterOfNode(node: ts.Node | ts.CommentRange): ts.LineAndCharacter { - const startPos = TsUtils.getStartPos(node); - const { line, character } = this.sourceFile!.getLineAndCharacterOfPosition(startPos); - // TSC counts lines and columns from zero - return { line: line + 1, character: character + 1 }; - } - - incrementCounters(node: ts.Node | ts.CommentRange, faultId: number, autofix?: Autofix[]): void { - this.nodeCounters[faultId]++; - const { line, character } = this.getLineAndCharacterOfNode(node); - if ((this.options.ideMode || this.options.migratorMode) && !this.options.ideInteractive) { - this.incrementCountersIdeMode(node, faultId, autofix); - } else if (this.options.ideInteractive) { - this.incrementCountersIdeInteractiveMode(node, faultId, autofix); - } else { - const faultDescr = faultDesc[faultId]; - const faultType = LinterConfig.tsSyntaxKindNames[node.kind]; - Logger.info( - `Warning: ${this.sourceFile!.fileName} (${line}, ${character}): ${faultDescr ? faultDescr : faultType}` - ); - } - this.lineCounters[faultId]++; - switch (faultsAttrs[faultId].severity) { - case ProblemSeverity.ERROR: { - this.currentErrorLine = line; - ++this.totalErrorLines; - this.errorLineNumbersString += line + ', '; - break; - } - case ProblemSeverity.WARNING: { - if (line === this.currentWarningLine) { - break; - } - this.currentWarningLine = line; - ++this.totalWarningLines; - this.warningLineNumbersString += line + ', '; - break; - } - default: - } - } - - private incrementCountersIdeMode(node: ts.Node | ts.CommentRange, faultId: number, autofix?: Autofix[]): void { - if (!this.options.ideMode && !this.options.migratorMode) { - return; - } - const [startOffset, endOffset] = TsUtils.getHighlightRange(node, faultId); - const startPos = this.sourceFile!.getLineAndCharacterOfPosition(startOffset); - const endPos = this.sourceFile!.getLineAndCharacterOfPosition(endOffset); - - const faultDescr = faultDesc[faultId]; - const faultType = LinterConfig.tsSyntaxKindNames[node.kind]; - - const cookBookMsgNum = faultsAttrs[faultId] ? faultsAttrs[faultId].cookBookRef : 0; - const cookBookTg = cookBookTag[cookBookMsgNum]; - const severity = faultsAttrs[faultId]?.severity ?? ProblemSeverity.ERROR; - const isMsgNumValid = cookBookMsgNum > 0; - const badNodeInfo: ProblemInfo = { - line: startPos.line + 1, - column: startPos.character + 1, - endLine: endPos.line + 1, - endColumn: endPos.character + 1, - start: startOffset, - end: endOffset, - type: faultType, - severity: severity, - problem: FaultID[faultId], - suggest: '', - // eslint-disable-next-line no-nested-ternary - rule: isMsgNumValid && cookBookTg !== '' ? cookBookTg : faultDescr ? faultDescr : faultType, - ruleTag: cookBookMsgNum, - autofix: autofix, - autofixTitle: isMsgNumValid && autofix !== undefined ? cookBookRefToFixTitle.get(cookBookMsgNum) : undefined - }; - this.problemsInfos.push(badNodeInfo); - // problems with autofixes might be collected separately - if (this.options.reportAutofixCb && badNodeInfo.autofix) { - this.options.reportAutofixCb(badNodeInfo); + lint(): void { + if (this.options.enableAutofix || this.options.migratorMode) { + this.autofixer = new Autofixer(this.tsTypeChecker, this.tsUtils, this.sourceFile, this.options.cancellationToken); } - } - private incrementCountersIdeInteractiveMode( - node: ts.Node | ts.CommentRange, - faultId: number, - autofix?: Autofix[] - ): void { - if (!this.options.ideInteractive) { - return; - } - const [startOffset, endOffset] = TsUtils.getHighlightRange(node, faultId); - const startPos = this.sourceFile!.getLineAndCharacterOfPosition(startOffset); - const endPos = this.sourceFile!.getLineAndCharacterOfPosition(endOffset); - - const faultDescr = faultDesc[faultId]; - const faultType = LinterConfig.tsSyntaxKindNames[node.kind]; - - const cookBookMsgNum = faultsAttrs[faultId] ? faultsAttrs[faultId].cookBookRef : 0; - const cookBookTg = cookBookTag[cookBookMsgNum]; - const severity = faultsAttrs[faultId]?.severity ?? ProblemSeverity.ERROR; - const isMsgNumValid = cookBookMsgNum > 0; - const badNodeInfo: ProblemInfo = { - line: startPos.line + 1, - column: startPos.character + 1, - endLine: endPos.line + 1, - endColumn: endPos.character + 1, - start: startOffset, - end: endOffset, - type: faultType, - severity: severity, - problem: FaultID[faultId], - suggest: '', - // eslint-disable-next-line no-nested-ternary - rule: isMsgNumValid && cookBookTg !== '' ? cookBookTg : faultDescr ? faultDescr : faultType, - ruleTag: cookBookMsgNum, - autofixable: !!autofix, - autofix: autofix, - autofixTitle: isMsgNumValid && autofix !== undefined ? cookBookRefToFixTitle.get(cookBookMsgNum) : undefined - }; - this.problemsInfos.push(badNodeInfo); - // problems with autofixes might be collected separately - if (this.options.reportAutofixCb && badNodeInfo.autofix) { - this.options.reportAutofixCb(badNodeInfo); - } + this.useStatic = TsUtils.isArkts12File(this.sourceFile); + this.fileExportDeclCaches = undefined; + this.extractImportedNames(this.sourceFile); + this.visitSourceFile(this.sourceFile); + this.handleCommentDirectives(this.sourceFile); + this.processInterfacesToImport(this.sourceFile); } private visitSourceFile(sf: ts.SourceFile): void { const callback = (node: ts.Node): void => { - this.totalVisitedNodes++; + this.fileStats.visitedNodes++; if (isStructDeclaration(node)) { // early exit via exception if cancellation was requested this.options.cancellationToken?.throwIfCancellationRequested(); } - const incrementedType = LinterConfig.incrementOnlyTokens.get(node.kind); + const incrementedType = TypeScriptLinterConfig.incrementOnlyTokens.get(node.kind); if (incrementedType !== undefined) { this.incrementCounters(node, incrementedType); } else { @@ -456,7 +430,7 @@ export class TypeScriptLinter { if (node.parent && isStructDeclaration(node.parent) && ts.isConstructorDeclaration(node)) { return true; } - if (LinterConfig.terminalTokens.has(node.kind)) { + if (TypeScriptLinterConfig.terminalTokens.has(node.kind)) { return true; } return false; @@ -612,15 +586,24 @@ export class TypeScriptLinter { objectLiteralType: ts.Type | undefined, objectLiteralExpr: ts.ObjectLiteralExpression ): void { - const isRecordObject = objectLiteralType && this.tsUtils.isStdRecordType(objectLiteralType); - for (const prop of objectLiteralExpr.properties) { - if ( - isRecordObject && !(prop.name && this.tsUtils.isValidRecordObjectLiteralKey(prop.name)) || - !isRecordObject && !(ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name)) - ) { - const faultNode = ts.isPropertyAssignment(prop) ? prop.name : prop; - this.incrementCounters(faultNode, FaultID.ObjectLiteralProperty); - } + let objLiteralAutofix: Autofix[] | undefined; + const invalidProps = objectLiteralExpr.properties.filter((prop) => { + return !ts.isPropertyAssignment(prop); + }); + + if ( + invalidProps.some((prop) => { + return ts.isMethodDeclaration(prop) || ts.isAccessor(prop); + }) + ) { + objLiteralAutofix = this.autofixer?.fixTypedObjectLiteral(objectLiteralExpr, objectLiteralType); + } + + for (const prop of invalidProps) { + const autofix = ts.isShorthandPropertyAssignment(prop) ? + this.autofixer?.fixShorthandPropertyAssignment(prop) : + objLiteralAutofix; + this.incrementCounters(prop, FaultID.ObjectLiteralProperty, autofix); } } @@ -661,6 +644,9 @@ export class TypeScriptLinter { if (elementContextType) { this.checkAssignmentMatching(element, elementContextType, element, true); } + if (this.options.arkts2 && ts.isOmittedExpression(element)) { + this.incrementCounters(element, FaultID.NosparseArray); + } } if (emptyContextTypeForArrayLiteral) { this.incrementCounters(node, FaultID.ArrayLiteralNoContextType); @@ -671,6 +657,7 @@ export class TypeScriptLinter { if (!this.options.arkts2) { return; } + this.handleStructDeclarationForLayout(node); this.handleInvalidIdentifier(node); } @@ -682,10 +669,12 @@ export class TypeScriptLinter { this.handleDeclarationDestructuring(tsParam); this.handleDeclarationInferredType(tsParam); this.handleInvalidIdentifier(tsParam); + this.handleSdkDuplicateDeclName(tsParam); const typeNode = tsParam.type; if (this.options.arkts2 && typeNode && typeNode.kind === ts.SyntaxKind.VoidKeyword) { this.incrementCounters(typeNode, FaultID.LimitedVoidType); } + this.handlePropertyDescriptorInScenarios(tsParam); } private handleEnumDeclaration(node: ts.Node): void { @@ -763,6 +752,81 @@ export class TypeScriptLinter { this.countDeclarationsWithDuplicateName(interfaceNode.name, interfaceNode); } + private handleTryStatement(node: ts.TryStatement): void { + if (!this.options.arkts2) { + return; + } + + for (const stmt of node.tryBlock.statements) { + if (!ts.isExpressionStatement(stmt)) { + continue; + } + const callExpr = stmt.expression; + if (!ts.isCallExpression(callExpr)) { + continue; + } + const ident = callExpr.expression; + if (!ts.isIdentifier(ident)) { + continue; + } + + this.handleTsInterop(ident, () => { + this.tsFunctionInteropHandler(callExpr); + }); + + this.handleJsInterop(ident, () => { + this.jsFunctionInteropHandler(callExpr); + }); + } + } + + private tsFunctionInteropHandler(callExpr: ts.CallExpression): void { + this.checkInteropFunctionThrows(callExpr, FaultID.InteropTSFunctionInvoke); + } + + private jsFunctionInteropHandler(callExpr: ts.CallExpression): void { + this.checkInteropFunctionThrows(callExpr, FaultID.InteropJSFunctionInvoke); + } + + private checkInteropFunctionThrows(callExpr: ts.CallExpression, faultId: FaultID): void { + const signature = this.tsTypeChecker.getResolvedSignature(callExpr); + if (!signature) { + return; + } + + if (!signature.declaration) { + return; + } + + const functionSymbol = this.getFunctionSymbol(signature.declaration); + const functionDeclaration = functionSymbol?.valueDeclaration; + if (!functionDeclaration) { + return; + } + + if (!TypeScriptLinter.isFunctionLike(functionDeclaration)) { + return; + } + if (this.containsThrowNonError(functionDeclaration)) { + this.incrementCounters(callExpr, faultId); + } + } + + private containsThrowNonError(node: ts.FunctionDeclaration | ts.MethodDeclaration | ts.FunctionExpression): boolean { + if (!node.body) { + return false; + } + + const statements = node.body.statements; + for (const stmt of statements) { + if (!ts.isThrowStatement(stmt)) { + continue; + } + return this.tsUtils.checkStatementForErrorClass(stmt); + } + return false; + } + private handleThrowStatement(node: ts.Node): void { const throwStmt = node as ts.ThrowStatement; const throwExprType = this.tsTypeChecker.getTypeAtLocation(throwStmt.expression); @@ -789,174 +853,452 @@ export class TypeScriptLinter { } } - private handleForStatement(node: ts.Node): void { - const tsForStmt = node as ts.ForStatement; - const tsForInit = tsForStmt.initializer; - if (tsForInit) { - this.checkForLoopDestructuring(tsForInit); + /* + * this should report the point of access to the array + * and also should report the identifier type + */ + private checkElementAccessOfArray(statement: ts.Node): ArrayAccess | false { + if (ts.isElementAccessExpression(statement)) { + return this.isElementAccessOfArray(statement); } - } - - private handleForInStatement(node: ts.Node): void { - const tsForInStmt = node as ts.ForInStatement; - const tsForInInit = tsForInStmt.initializer; - this.checkForLoopDestructuring(tsForInInit); - this.incrementCounters(node, FaultID.ForInStatement); - } - - private handleForOfStatement(node: ts.Node): void { - const tsForOfStmt = node as ts.ForOfStatement; - const tsForOfInit = tsForOfStmt.initializer; - this.checkForLoopDestructuring(tsForOfInit); - } - private updateDataSdkJsonInfo(importDeclNode: ts.ImportDeclaration, importClause: ts.ImportClause): void { - const sdkInfo = TypeScriptLinter.pathMap.get(importDeclNode.moduleSpecifier.getText()); - if (sdkInfo && importClause.namedBindings) { - const namedImports = importClause.namedBindings as ts.NamedImports; - namedImports.elements.forEach((element) => { - const elementName = element.name.getText(); - sdkInfo.forEach((info) => { - TypeScriptLinter.addOrUpdateData(this.interfaceMap, elementName, info); - }); - }); + for (const children of statement.getChildren()) { + return this.checkElementAccessOfArray(children); } + return false; } - private handleImportDeclaration(node: ts.Node): void { - // early exit via exception if cancellation was requested - this.options.cancellationToken?.throwIfCancellationRequested(); - const importDeclNode = node as ts.ImportDeclaration; - this.handleImportModule(importDeclNode); - if (this.options.arkts2) { - const importClause = importDeclNode.importClause; - if (!importClause || !importClause.name && !importClause.namedBindings) { - this.incrementCounters(node, FaultID.NoSideEffectImport); - } else { - this.updateDataSdkJsonInfo(importDeclNode, importClause); - } + private isElementAccessOfArray(expr: ts.ElementAccessExpression): false | ArrayAccess { + if (!ts.isIdentifier(expr.expression)) { + return false; } - for (const stmt of importDeclNode.parent.statements) { - if (stmt === importDeclNode) { - break; - } - if (!ts.isImportDeclaration(stmt)) { - this.incrementCounters(node, FaultID.ImportAfterStatement); - break; - } + const type = this.tsTypeChecker.getTypeAtLocation(expr.expression); + if (!this.tsUtils.isArray(type)) { + return false; + } + const accessArgument = expr.argumentExpression; + if (ts.isNumericLiteral(accessArgument)) { + return { + pos: expr.getEnd(), + accessingIdentifier: NUMBER_LITERAL, + arrayIdent: expr.expression + }; } - const expr = importDeclNode.moduleSpecifier; - if (expr.kind === ts.SyntaxKind.StringLiteral) { - if (importDeclNode.assertClause) { - this.incrementCounters(importDeclNode.assertClause, FaultID.ImportAssertion); - } - const stringLiteral = expr as ts.StringLiteral; - this.handleSdkSendable(stringLiteral); + if (ts.isIdentifier(accessArgument)) { + return { + pos: expr.getEnd(), + accessingIdentifier: accessArgument, + arrayIdent: expr.expression + }; } + return false; + } - // handle no side effect import in sendable module - this.handleSharedModuleNoSideEffectImport(importDeclNode); - this.handleInvalidIdentifier(importDeclNode); - this.checkWorkerImport(importDeclNode); - this.checkStdLibConcurrencyImport(importDeclNode); - this.handleInterOpImportJs(importDeclNode); + private handleForStatement(node: ts.Node): void { + const tsForStmt = node as ts.ForStatement; + const tsForInit = tsForStmt.initializer; + if (tsForInit) { + this.checkStaticArrayControl(tsForStmt); + this.checkForLoopDestructuring(tsForInit); + } } - private handleSdkSendable(tsStringLiteral: ts.StringLiteral): void { - if (!this.options.arkts2) { + private checkStaticArrayControl(tsForStmt: ts.ForStatement): void { + if (!this.options.arkts2 || !this.useStatic) { return; } - const moduleSpecifierValue = tsStringLiteral.getText(); - const sdkInfos = TypeScriptLinter.pathMap.get(moduleSpecifierValue); + if (!ts.isBlock(tsForStmt.statement)) { + return; + } - if (!sdkInfos || sdkInfos.size === 0) { + const loopBody = tsForStmt.statement; + const arrayAccessInfo = this.checkBodyHasArrayAccess(loopBody); + const loopCondition = tsForStmt.condition; + + if (!arrayAccessInfo) { return; } - if (moduleSpecifierValue.includes('sendable')) { - this.incrementCounters(tsStringLiteral, FaultID.SendablePropTypeFromSdk); + if (!loopCondition) { + this.incrementCounters(arrayAccessInfo.arrayIdent.parent, FaultID.RuntimeArrayCheck); + return; } - } - - private handleImportModule(importDeclNode: ts.ImportDeclaration): void { - if (!this.options.arkts2) { + const arraySymbol = this.tsUtils.trueSymbolAtLocation(arrayAccessInfo.arrayIdent); + if (!arraySymbol) { return; } - if (!importDeclNode.importClause) { + const arrayCheckedAgainst = this.checkConditionForArrayAccess(loopCondition, arraySymbol); + if (!arrayCheckedAgainst) { + this.incrementCounters(arrayAccessInfo.arrayIdent.parent, FaultID.RuntimeArrayCheck); return; } - const modulePath = importDeclNode.moduleSpecifier.getText().slice(1, -1); - if (modulePath.startsWith('./') || modulePath.startsWith('../')) { + this.checkIfAccessAndCheckVariablesMatch(arrayAccessInfo, arrayCheckedAgainst); + } - /* - * Reason for this method to check the oh module imports, - * We do not use relative paths when importing from OhModules, - * So we do not check the relative paths - */ + private checkIfAccessAndCheckVariablesMatch(accessInfo: ArrayAccess, checkedAgainst: CheckedIdentifier): void { + const { arrayIdent, accessingIdentifier } = accessInfo; + + if (accessingIdentifier === NUMBER_LITERAL) { + if (checkedAgainst === NUMBER_LITERAL) { + return; + } + this.incrementCounters(arrayIdent.parent, FaultID.RuntimeArrayCheck); return; } - if (this.checkFileExists(importDeclNode.importClause)) { + if (checkedAgainst === NUMBER_LITERAL) { + this.incrementCounters(arrayIdent.parent, FaultID.RuntimeArrayCheck); return; } - if (TsUtils.isValidOhModulePath(modulePath) || !TsUtils.isOhModule(modulePath)) { - // Valid or paths that we do not check because they are not ohModules + const checkedAgainstSym = this.tsUtils.trueSymbolAtLocation(checkedAgainst); + if (!checkedAgainstSym) { return; } - const pathParts = modulePath.split(PATH_SEPARATOR); - const etsIdx = pathParts.indexOf(ETS_PART); + const accessingIdentSym = this.tsUtils.trueSymbolAtLocation(accessingIdentifier); - if (etsIdx === 0) { - const autofix = Autofixer.addDefaultModuleToPath(pathParts, importDeclNode); - this.incrementCounters(importDeclNode, FaultID.OhmUrlFullPath, autofix); + if (checkedAgainstSym !== accessingIdentSym) { + this.incrementCounters(arrayIdent.parent, FaultID.RuntimeArrayCheck); return; } - const autofix = Autofixer.fixImportPath(pathParts, etsIdx, importDeclNode); - this.incrementCounters(importDeclNode, FaultID.OhmUrlFullPath, autofix); + if (this.isChangedAfterCheck(arrayIdent.getSourceFile(), checkedAgainstSym)) { + this.incrementCounters(arrayIdent.parent, FaultID.RuntimeArrayCheck); + } } - private checkFileExists(importClause: ts.ImportClause): boolean { + private checkConditionForArrayAccess(condition: ts.Expression, arraySymbol: ts.Symbol): UncheckedIdentifier { + if (!ts.isBinaryExpression(condition)) { + return undefined; + } + const { left, right } = condition; + + if (ts.isBinaryExpression(left)) { + return this.checkConditionForArrayAccess(left, arraySymbol); + } + if (ts.isBinaryExpression(right)) { + return this.checkConditionForArrayAccess(right, arraySymbol); + } - /* - * TODO: what would have a symbol on this context - * would the moduleSpecifier? I don't think so - * I think it would be the identifier - * Which would be the expression - * - * We get the symbol from import clause - * get a identifier inside the import clause and check if that file exists or not - */ - for (const child of importClause.getChildren()) { - if (child.kind !== ts.SyntaxKind.Identifier) { - continue; + if (this.isArrayLengthAccess(left, arraySymbol)) { + if (ts.isNumericLiteral(right)) { + return NUMBER_LITERAL; } - const declNode = this.tsUtils.getDeclarationNode(child); - if (declNode) { - // this is a valid path that and the file should not be checked - return true; + if (!ts.isIdentifier(right)) { + return undefined; } + return right; } - return false; - } - private handleSharedModuleNoSideEffectImport(node: ts.ImportDeclaration): void { - // check 'use shared' - if (TypeScriptLinter.inSharedModule(node) && !node.importClause) { - this.incrementCounters(node, FaultID.SharedNoSideEffectImport); + if (this.isArrayLengthAccess(right, arraySymbol)) { + if (ts.isNumericLiteral(left)) { + return NUMBER_LITERAL; + } + if (!ts.isIdentifier(left)) { + return undefined; + } + return left; } + + return undefined; } - private static inSharedModule(node: ts.Node): boolean { - const sourceFile: ts.SourceFile = node.getSourceFile(); - const modulePath = path.normalize(sourceFile.fileName); - if (TypeScriptLinter.sharedModulesCache.has(modulePath)) { - return TypeScriptLinter.sharedModulesCache.get(modulePath)!; + private isArrayLengthAccess(expr: ts.Expression, arraySymbol: ts.Symbol): boolean { + if (!ts.isPropertyAccessExpression(expr)) { + return false; + } + if (this.tsUtils.trueSymbolAtLocation(expr.expression) !== arraySymbol) { + return false; + } + if (expr.name.text !== 'length') { + return false; + } + + return true; + } + + private checkBodyHasArrayAccess(loopBody: ts.Block): ArrayAccess | undefined { + let arrayAccessResult: undefined | ArrayAccess; + // check if this element access expression is of an array. + for (const child of loopBody.statements) { + const result = this.checkElementAccessOfArray(child); + if (!result) { + continue; + } + arrayAccessResult = result; + } + return arrayAccessResult; + } + + private checkArrayUsageWithoutBound(accessExpr: ts.ElementAccessExpression): void { + if (!this.options.arkts2 || !this.useStatic) { + return; + } + + const arrayAccessInfo = this.isElementAccessOfArray(accessExpr); + if (!arrayAccessInfo) { + return; + } + + const { arrayIdent } = arrayAccessInfo; + const arraySym = this.tsUtils.trueSymbolAtLocation(arrayIdent); + if (!arraySym) { + return; + } + const sourceFile = arrayIdent.getSourceFile(); + + for (const statement of sourceFile.statements) { + if (this.checkStatementForArrayAccess(statement, arrayAccessInfo, arraySym) === CheckResult.SKIP) { + continue; + } + } + } + + private checkStatementForArrayAccess( + statement: ts.Statement, + accessInfo: ArrayAccess, + arraySym: ts.Symbol + ): CheckResult { + if (!ts.isIfStatement(statement)) { + return CheckResult.SKIP; + } + + if (this.checkBodyHasArrayAccess(statement.thenStatement as ts.Block) !== undefined) { + return CheckResult.SKIP; + } + + const checkedAgainst = this.checkConditionForArrayAccess(statement.expression, arraySym); + if (!checkedAgainst) { + return CheckResult.SKIP; + } + + this.checkIfAccessAndCheckVariablesMatch(accessInfo, checkedAgainst); + return CheckResult.CHECKED; + } + + private isChangedAfterCheck(sourceFile: ts.SourceFile, sym: ts.Symbol): boolean { + for (const statement of sourceFile.statements) { + if (!ts.isExpressionStatement(statement)) { + continue; + } + if (!ts.isBinaryExpression(statement.expression)) { + continue; + } + if (!ts.isIdentifier(statement.expression.left)) { + continue; + } + if (statement.expression.operatorToken.kind !== ts.SyntaxKind.EqualsToken) { + continue; + } + + const leftSym = this.tsUtils.trueSymbolAtLocation(statement.expression.left); + if (!leftSym) { + continue; + } + + if (leftSym === sym) { + return true; + } + continue; + } + + return false; + } + + private handleForInStatement(node: ts.Node): void { + const tsForInStmt = node as ts.ForInStatement; + const tsForInInit = tsForInStmt.initializer; + this.checkForLoopDestructuring(tsForInInit); + this.incrementCounters(node, FaultID.ForInStatement); + } + + private handleForOfStatement(node: ts.Node): void { + const tsForOfStmt = node as ts.ForOfStatement; + const tsForOfInit = tsForOfStmt.initializer; + this.checkForLoopDestructuring(tsForOfInit); + } + + private handleIfStatement(ifStatement: ts.IfStatement): void { + if (this.options.arkts2 && this.useStatic) { + this.checkIfStatementForArrayUsage(ifStatement); + } + } + + private checkIfStatementForArrayUsage(ifStatement: ts.IfStatement): void { + if (!ts.isBlock(ifStatement.thenStatement)) { + return; + } + + const accessInfo = this.checkBodyHasArrayAccess(ifStatement.thenStatement); + if (!accessInfo) { + return; + } + const { arrayIdent } = accessInfo; + + const arraySymbol = this.tsUtils.trueSymbolAtLocation(arrayIdent); + if (!arraySymbol) { + return; + } + + const checkedAgainst = this.checkConditionForArrayAccess(ifStatement.expression, arraySymbol); + if (!checkedAgainst) { + return; + } + + this.checkIfAccessAndCheckVariablesMatch(accessInfo, checkedAgainst); + } + + private updateDataSdkJsonInfo(importDeclNode: ts.ImportDeclaration, importClause: ts.ImportClause): void { + const sdkInfo = TypeScriptLinter.pathMap.get(importDeclNode.moduleSpecifier.getText()); + if (sdkInfo && importClause.namedBindings) { + const namedImports = importClause.namedBindings as ts.NamedImports; + if (!namedImports.elements) { + return; + } + namedImports.elements.forEach((element) => { + const elementName = element.name.getText(); + sdkInfo.forEach((info) => { + TypeScriptLinter.addOrUpdateData(this.interfaceMap, elementName, info); + }); + }); + } + } + + private handleImportDeclaration(node: ts.Node): void { + // early exit via exception if cancellation was requested + this.options.cancellationToken?.throwIfCancellationRequested(); + const importDeclNode = node as ts.ImportDeclaration; + this.handleImportModule(importDeclNode); + if (this.options.arkts2) { + const importClause = importDeclNode.importClause; + if (!importClause || !importClause.name && !importClause.namedBindings) { + this.incrementCounters(node, FaultID.NoSideEffectImport); + } else { + this.updateDataSdkJsonInfo(importDeclNode, importClause); + } + } + if (importDeclNode.parent.statements) { + for (const stmt of importDeclNode.parent.statements) { + if (stmt === importDeclNode) { + break; + } + if (!ts.isImportDeclaration(stmt)) { + this.incrementCounters(node, FaultID.ImportAfterStatement); + break; + } + } + } + + const expr = importDeclNode.moduleSpecifier; + if (expr.kind === ts.SyntaxKind.StringLiteral) { + if (importDeclNode.assertClause) { + this.incrementCounters(importDeclNode.assertClause, FaultID.ImportAssertion); + } + const stringLiteral = expr as ts.StringLiteral; + this.handleSdkSendable(stringLiteral); + } + + // handle no side effect import in sendable module + this.handleSharedModuleNoSideEffectImport(importDeclNode); + this.handleInvalidIdentifier(importDeclNode); + this.checkStdLibConcurrencyImport(importDeclNode); + this.handleInterOpImportJs(importDeclNode); + this.checkForDeprecatedModules(node); + } + + private checkForDeprecatedModules(node: ts.Node): void { + if (!ts.isImportDeclaration(node)) { + return; + } + + const deprecatedModules = ['@ohos.file.sendablePhotoAccessHelper']; + + const importDecl = node; + const moduleSpecifier = importDecl.moduleSpecifier; + + if (ts.isStringLiteral(moduleSpecifier)) { + const moduleName = moduleSpecifier.text; + if (deprecatedModules.includes(moduleName)) { + this.incrementCounters(moduleSpecifier, FaultID.SdkTypeQuery); + } + } + } + + private handleSdkSendable(tsStringLiteral: ts.StringLiteral): void { + if (!this.options.arkts2) { + return; + } + + const moduleSpecifierValue = tsStringLiteral.getText(); + const sdkInfos = TypeScriptLinter.pathMap.get(moduleSpecifierValue); + + if (!sdkInfos || sdkInfos.size === 0) { + return; + } + if (moduleSpecifierValue.includes('sendable')) { + this.incrementCounters(tsStringLiteral, FaultID.SendablePropTypeFromSdk); + } + } + + private handleImportModule(importDeclNode: ts.ImportDeclaration): void { + if (!this.options.arkts2) { + return; + } + + const modulePath = importDeclNode.moduleSpecifier.getText().slice(1, -1); + if (modulePath.startsWith('./') || modulePath.startsWith('../')) { + + /* + * Reason for this method to check the oh module imports, + * We do not use relative paths when importing from OhModules, + * So we do not check the relative paths + */ + return; + } + if (!importDeclNode.importClause) { + return; + } + + const pathParts = modulePath.split(PATH_SEPARATOR); + const etsIdx = pathParts.indexOf(ETS_PART); + + if (this.options.wholeProjectPath) { + if (TsUtils.checkFileExists(etsIdx !== 0, importDeclNode, modulePath, this.options.wholeProjectPath)) { + return; + } + } + + if (TsUtils.isValidOhModulePath(modulePath) || !TsUtils.isOhModule(modulePath)) { + // Valid or paths that we do not check because they are not ohModules + return; + } + + if (etsIdx === 0) { + const autofix = this.autofixer?.addDefaultModuleToPath(pathParts, importDeclNode); + this.incrementCounters(importDeclNode, FaultID.OhmUrlFullPath, autofix); + return; + } + + const autofix = this.autofixer?.fixImportPath(pathParts, etsIdx, importDeclNode); + this.incrementCounters(importDeclNode, FaultID.OhmUrlFullPath, autofix); + } + + private handleSharedModuleNoSideEffectImport(node: ts.ImportDeclaration): void { + // check 'use shared' + if (TypeScriptLinter.inSharedModule(node) && !node.importClause) { + this.incrementCounters(node, FaultID.SharedNoSideEffectImport); + } + } + + private static inSharedModule(node: ts.Node): boolean { + const sourceFile: ts.SourceFile = node.getSourceFile(); + const modulePath = path.normalize(sourceFile.fileName); + if (TypeScriptLinter.sharedModulesCache.has(modulePath)) { + return TypeScriptLinter.sharedModulesCache.get(modulePath)!; } const isSharedModule: boolean = TsUtils.isSharedModule(sourceFile); TypeScriptLinter.sharedModulesCache.set(modulePath, isSharedModule); @@ -964,9 +1306,16 @@ export class TypeScriptLinter { } private handlePropertyAccessExpression(node: ts.Node): void { + this.handleMakeObserved(node as ts.PropertyAccessExpression); + this.handleStateStyles(node as ts.PropertyAccessExpression); this.handleDoubleDollar(node); + this.handleQuotedHyphenPropsDeprecated(node as ts.PropertyAccessExpression); this.handleSdkTypeQuery(node as ts.PropertyAccessExpression); this.checkUnionTypes(node as ts.PropertyAccessExpression); + this.handleLimitedVoidTypeFromSdkOnPropertyAccessExpression(node as ts.PropertyAccessExpression); + this.checkDepricatedIsConcurrent(node as ts.PropertyAccessExpression); + this.propertyAccessExpressionForBuiltin(node as ts.PropertyAccessExpression); + if (ts.isCallExpression(node.parent) && node === node.parent.expression) { return; } @@ -982,7 +1331,6 @@ export class TypeScriptLinter { if (this.isPrototypePropertyAccess(propertyAccessNode, exprSym, baseExprSym, baseExprType)) { this.incrementCounters(propertyAccessNode.name, FaultID.Prototype); } - if ( !this.options.arkts2 && !!exprSym && @@ -992,7 +1340,6 @@ export class TypeScriptLinter { this.incrementCounters(propertyAccessNode, FaultID.SymbolType); } if (this.options.advancedClassChecks && this.tsUtils.isClassObjectExpression(propertyAccessNode.expression)) { - // missing exact rule this.incrementCounters(propertyAccessNode.expression, FaultID.ClassAsObject); } @@ -1009,6 +1356,13 @@ export class TypeScriptLinter { this.handleArkTSPropertyAccess(propertyAccessNode); } + propertyAccessExpressionForBuiltin(decl: ts.PropertyAccessExpression): void { + if (this.options.arkts2) { + this.handleSymbolIterator(decl); + this.handleGetOwnPropertyNames(decl); + } + } + propertyAccessExpressionForInterop( exprSym: ts.Symbol | undefined, propertyAccessNode: ts.PropertyAccessExpression @@ -1030,6 +1384,45 @@ export class TypeScriptLinter { } } + private checkDepricatedIsConcurrent(node: ts.PropertyAccessExpression): void { + if (!this.options.arkts2) { + return; + } + if (!ts.isCallExpression(node.parent)) { + return; + } + + const methodName = node.name.getText(); + + if (methodName !== ISCONCURRENT) { + return; + } + + const symbol = this.tsUtils.trueSymbolAtLocation(node.expression); + if (!symbol) { + return; + } + + if (symbol.name === TASKPOOL) { + const decl = TsUtils.getDeclaration(symbol); + + if (!decl) { + return; + } + + const sourceFile = decl.getSourceFile(); + const fileName = path.basename(sourceFile.fileName); + + if ( + TASKPOOL_MODULES.some((moduleName) => { + return fileName.startsWith(moduleName); + }) + ) { + this.incrementCounters(node.name, FaultID.IsConcurrentDeprecated); + } + } + } + checkFunctionProperty( node: ts.PropertyAccessExpression, baseExprSym: ts.Symbol | undefined, @@ -1068,7 +1461,7 @@ export class TypeScriptLinter { const rhs = binaryExpr.right; const lhs = binaryExpr.left as ts.PropertyAccessExpression; - const autofix = Autofixer.fixInteropTsType(binaryExpr, lhs, rhs); + const autofix = this.autofixer?.fixInteropTsType(binaryExpr, lhs, rhs); this.incrementCounters(pan, FaultID.InteropDirectAccessToTSTypes, autofix); } @@ -1129,7 +1522,6 @@ export class TypeScriptLinter { } private handlePropertyDeclaration(node: ts.PropertyDeclaration): void { - this.handleDataObservation(node); const propName = node.name; this.handleLiteralAsPropertyName(node); const decorators = ts.getDecorators(node); @@ -1161,7 +1553,8 @@ export class TypeScriptLinter { this.checkAssignmentNumericSemanticslyPro(node); this.handleInvalidIdentifier(node); this.handleStructPropertyDecl(node); - this.handleApipathChanged(node); + this.handlePropertyDeclarationForProp(node); + this.handleSdkDuplicateDeclName(node); } private handleSendableClassProperty(node: ts.PropertyDeclaration): void { @@ -1186,8 +1579,9 @@ export class TypeScriptLinter { private handlePropertyAssignment(node: ts.PropertyAssignment): void { this.handleDollarBind(node); + this.handleQuotedHyphenPropsDeprecated(node); const propName = node.name; - if (!(!!propName && ts.isNumericLiteral(propName))) { + if (!propName || !(ts.isNumericLiteral(propName) || this.options.arkts2 && ts.isStringLiteral(propName))) { return; } @@ -1241,6 +1635,10 @@ export class TypeScriptLinter { this.handleLiteralAsPropertyName(node); this.handleSendableInterfaceProperty(node); this.handleInvalidIdentifier(node); + const typeNode = node.type; + if (this.options.arkts2 && typeNode && typeNode.kind === ts.SyntaxKind.VoidKeyword) { + this.incrementCounters(typeNode, FaultID.LimitedVoidType); + } } private handleInterfaceProperty(node: ts.PropertySignature): void { @@ -1248,8 +1646,8 @@ export class TypeScriptLinter { if (node.type && ts.isFunctionTypeNode(node.type)) { const interfaceName = node.parent.name.getText(); const propertyName = node.name.getText(); - const allClasses = TypeScriptLinter.getAllClassesFromSourceFile(this.sourceFile!); - const allInterfaces = TypeScriptLinter.getAllInterfaceFromSourceFile(this.sourceFile!); + const allClasses = TypeScriptLinter.getAllClassesFromSourceFile(this.sourceFile); + const allInterfaces = TypeScriptLinter.getAllInterfaceFromSourceFile(this.sourceFile); this.visitClassMembers(allClasses, interfaceName, propertyName); this.visitInterfaceMembers(allInterfaces, interfaceName, propertyName); } @@ -1266,7 +1664,7 @@ export class TypeScriptLinter { const implementsClause = this.getExtendsClause(interfaceDecl); if ( implementsClause?.types.some((type) => { - return type.getText() === interfaceName; + return type.expression.getText() === interfaceName; }) ) { this.checkInterfaceForProperty(interfaceDecl, propertyName); @@ -1310,7 +1708,7 @@ export class TypeScriptLinter { const implementsClause = this.getImplementsClause(classDecl); if ( implementsClause?.types.some((type) => { - return type.getText() === interfaceName; + return type.expression.getText() === interfaceName; }) ) { this.checkClassForProperty(classDecl, propertyName); @@ -1422,6 +1820,7 @@ export class TypeScriptLinter { this.handleMissingReturnType(arrowFunc); } } + this.checkDefaultParamBeforeRequired(arrowFunc); } private handleFunctionDeclaration(node: ts.Node): void { @@ -1466,6 +1865,7 @@ export class TypeScriptLinter { this.handleTSOverload(tsFunctionDeclaration); this.checkAssignmentNumericSemanticsFuntion(tsFunctionDeclaration); this.handleInvalidIdentifier(tsFunctionDeclaration); + this.checkDefaultParamBeforeRequired(tsFunctionDeclaration); } private handleMissingReturnType( @@ -1577,12 +1977,20 @@ export class TypeScriptLinter { } private handleInteropOperand(tsUnaryArithm: ts.PrefixUnaryExpression): void { - if (ts.isPropertyAccessExpression(tsUnaryArithm.operand)) { - const exprSym = this.tsUtils.trueSymbolAtLocation(tsUnaryArithm.operand); - const declaration = exprSym?.declarations?.[0]; - this.checkAndProcessDeclaration(declaration, tsUnaryArithm); - } - } + const processPropertyAccess = (expr: ts.PropertyAccessExpression | ts.ParenthesizedExpression): void => { + const propertyAccess = ts.isParenthesizedExpression(expr) ? expr.expression : expr; + + if (ts.isPropertyAccessExpression(propertyAccess)) { + const exprSym = this.tsUtils.trueSymbolAtLocation(propertyAccess); + const declaration = exprSym?.declarations?.[0]; + this.checkAndProcessDeclaration(declaration, tsUnaryArithm); + } + }; + + if (ts.isPropertyAccessExpression(tsUnaryArithm.operand) || ts.isParenthesizedExpression(tsUnaryArithm.operand)) { + processPropertyAccess(tsUnaryArithm.operand); + } + } private checkAndProcessDeclaration( declaration: ts.Declaration | undefined, @@ -1667,12 +2075,21 @@ export class TypeScriptLinter { this.checkAssignmentMatching(tsBinaryExpr, leftOperandType, tsRhsExpr); this.checkFunctionTypeCompatible(typeNode, tsRhsExpr); this.handleEsObjectAssignment(tsBinaryExpr, typeNode, tsRhsExpr); + this.handleSdkDuplicateDeclName(tsBinaryExpr); + this.checkArrayTypeImmutable(tsBinaryExpr); + break; + case ts.SyntaxKind.AmpersandAmpersandEqualsToken: + case ts.SyntaxKind.QuestionQuestionEqualsToken: + case ts.SyntaxKind.BarBarEqualsToken: + if (this.options.arkts2) { + this.incrementCounters(tsBinaryExpr.operatorToken, FaultID.UnsupportOperator); + } break; default: } - this.checkNumericSemantics(tsBinaryExpr); this.checkInterOpImportJsDataCompare(tsBinaryExpr); this.checkInteropEqualityJudgment(tsBinaryExpr); + this.handleNumericBigintCompare(tsBinaryExpr); } private checkInterOpImportJsDataCompare(expr: ts.BinaryExpression): void { @@ -1694,7 +2111,6 @@ export class TypeScriptLinter { if (!initializer) { return false; } - return isJsFileExpression(initializer); }; @@ -1708,7 +2124,7 @@ export class TypeScriptLinter { const processExpression = (expr: ts.Expression): void => { const symbol = this.tsUtils.trueSymbolAtLocation(expr); - if (isJsFileSymbol(symbol)) { + if (isJsFileSymbol(symbol) || isJsFileExpression(expr)) { this.incrementCounters(expr, FaultID.InterOpImportJsDataCompare); } }; @@ -1722,8 +2138,7 @@ export class TypeScriptLinter { ts.SyntaxKind.GreaterThanToken, ts.SyntaxKind.LessThanToken, ts.SyntaxKind.GreaterThanEqualsToken, - ts.SyntaxKind.LessThanEqualsToken, - ts.SyntaxKind.EqualsToken + ts.SyntaxKind.LessThanEqualsToken ].includes(kind); } @@ -1745,7 +2160,7 @@ export class TypeScriptLinter { } private handleTsInterop(nodeToCheck: ts.Node, handler: { (): void }): void { - if (!this.options.arkts2) { + if (!this.options.arkts2 || !this.useStatic) { return; } @@ -1769,6 +2184,31 @@ export class TypeScriptLinter { handler(); } + private handleJsInterop(nodeToCheck: ts.Node, handler: { (): void }): void { + if (!this.options.arkts2 || !this.useStatic) { + return; + } + + const declarationNode = this.tsUtils.getDeclarationNode(nodeToCheck); + if (!declarationNode) { + return; + } + + const fileName = declarationNode.getSourceFile().fileName; + if (fileName.includes(ARKTS_IGNORE_DIRS_OH_MODULES)) { + return; + } + if (!fileName.endsWith(EXTNAME_JS)) { + return; + } + + if (fileName.endsWith(EXTNAME_D_TS)) { + return; + } + + handler(); + } + private processBinaryAssignment( binaryExpr: ts.BinaryExpression, tsLhsExpr: ts.Expression, @@ -1793,30 +2233,6 @@ export class TypeScriptLinter { } } - private checkNumericSemantics(binaryExpr: ts.BinaryExpression): void { - if (!this.options.arkts2) { - return; - } - if (isAssignmentOperator(binaryExpr.operatorToken)) { - this.checkAssignmentNumericSemantics(binaryExpr); - } else if (binaryExpr.operatorToken.kind === ts.SyntaxKind.SlashToken) { - this.checkDivisionNumericSemantics(binaryExpr); - } - } - - private checkAssignmentNumericSemantics(binaryExpr: ts.BinaryExpression): void { - const sym = this.tsTypeChecker.getSymbolAtLocation(binaryExpr.left); - if (this.tsUtils.isIntegerVariable(sym) && !this.tsUtils.isIntegerValue(binaryExpr.right)) { - this.incrementCounters(binaryExpr, FaultID.NumericSemantics); - } - } - - private checkDivisionNumericSemantics(binaryExpr: ts.BinaryExpression): void { - if (this.tsUtils.isIntegerValue(binaryExpr.left) && this.tsUtils.isIntegerValue(binaryExpr.right)) { - this.incrementCounters(binaryExpr, FaultID.NumericSemantics); - } - } - private checkAssignmentNumericSemanticsly(node: ts.VariableDeclaration): void { if (!this.options.arkts2) { return; @@ -1832,6 +2248,14 @@ export class TypeScriptLinter { return; } + if ( + ts.isBinaryExpression(initializer) && + ts.isCallExpression(initializer.left) && + TsUtils.isAppStorageAccess(initializer.left) + ) { + return; + } + const sym = this.tsTypeChecker.getSymbolAtLocation(name); if (!sym) { return; @@ -2066,6 +2490,7 @@ export class TypeScriptLinter { private handleVariableDeclaration(node: ts.Node): void { const tsVarDecl = node as ts.VariableDeclaration; + this.handleVariableDeclarationForProp(tsVarDecl); if ( !this.options.useRtLogic || ts.isVariableDeclarationList(tsVarDecl.parent) && ts.isVariableStatement(tsVarDecl.parent.parent) @@ -2092,6 +2517,49 @@ export class TypeScriptLinter { this.checkAssignmentNumericSemanticsly(tsVarDecl); this.checkTypeFromSdk(tsVarDecl.type); this.handleNoStructuralTyping(tsVarDecl); + this.handleObjectLiteralforUnionTypeInterop(tsVarDecl); + this.handleObjectLiteralAssignmentToClass(tsVarDecl); + this.handleObjectLiteralAssignment(tsVarDecl); + this.handlePropertyDescriptorInScenarios(tsVarDecl); + this.handleSdkDuplicateDeclName(tsVarDecl); + this.checkArrayTypeImmutable(tsVarDecl); + } + + private checkArrayTypeImmutable(node: ts.VariableDeclaration | ts.BinaryExpression): void { + if (!this.options.arkts2) { + return; + } + if (ts.isVariableDeclaration(node)) { + if (!node.initializer || ts.isArrayLiteralExpression(node.initializer)) { + return; + } + if (node.type && ts.isArrayTypeNode(node.type)) { + const varDeclType = this.tsTypeChecker.typeToString(this.tsTypeChecker.getTypeAtLocation(node.name)); + const initializerType = this.tsTypeChecker.typeToString(this.tsTypeChecker.getTypeAtLocation(node.initializer)); + if (varDeclType !== initializerType) { + this.incrementCounters(node, FaultID.ArrayTypeImmutable); + } + } + } else { + this.checkArrayTypeImmutableForBinaryExpression(node); + } + } + + private checkArrayTypeImmutableForBinaryExpression(node: ts.BinaryExpression): void { + const sym = this.tsTypeChecker.getSymbolAtLocation(node.left); + const declaration = sym?.declarations?.[0]; + if ( + declaration && + (ts.isVariableDeclaration(declaration) || ts.isParameter(declaration) || ts.isPropertyDeclaration(declaration)) + ) { + if (declaration.type && ts.isArrayTypeNode(declaration.type) && !ts.isArrayLiteralExpression(node.right)) { + const leftType = this.tsTypeChecker.typeToString(this.tsTypeChecker.getTypeAtLocation(node.left)); + const rightType = this.tsTypeChecker.typeToString(this.tsTypeChecker.getTypeAtLocation(node.right)); + if (leftType !== rightType) { + this.incrementCounters(node, FaultID.ArrayTypeImmutable); + } + } + } } private checkTypeFromSdk(type: ts.TypeNode | undefined): void { @@ -2107,7 +2575,7 @@ export class TypeScriptLinter { } for (const sdkInfo of sdkInfos) { - if (nameArr.includes(sdkInfo.api_name)) { + if (sdkInfo.api_name && nameArr.includes(sdkInfo.api_name)) { this.incrementCounters(type, FaultID.LimitedVoidTypeFromSdk); return; } @@ -2393,13 +2861,21 @@ export class TypeScriptLinter { const autofix = this.autofixer?.dropTypeOnVarDecl(tsCatch.variableDeclaration); this.incrementCounters(node, FaultID.CatchWithUnsupportedType, autofix); } + + if ( + this.options.arkts2 && + tsCatch.variableDeclaration && + TsUtils.isAnyType(this.tsTypeChecker.getTypeAtLocation(tsCatch.variableDeclaration)) + ) { + this.incrementCounters(node, FaultID.TsLikeCatchType); + } } private handleClassExtends(tsClassDecl: ts.ClassDeclaration): void { if (!this.options.arkts2) { return; } - const allClasses = TypeScriptLinter.getAllClassesFromSourceFile(this.sourceFile!); + const allClasses = TypeScriptLinter.getAllClassesFromSourceFile(this.sourceFile); const classMap = new Map(); allClasses.forEach((classDecl) => { if (classDecl.name && !classDecl.heritageClauses) { @@ -2477,35 +2953,53 @@ export class TypeScriptLinter { this.processClassStaticBlocks(tsClassDecl); this.handleInvalidIdentifier(tsClassDecl); this.handleSdkMethod(tsClassDecl); + this.handleNotsLikeSmartType(tsClassDecl); } private static findFinalExpression(typeNode: ts.TypeNode): ts.Node { let currentNode = typeNode; - /* CC-OFFNXT(no_explicit_any) std lib */ - // Handle comment directive '@ts-nocheck' + + /* + * CC-OFFNXT(no_explicit_any) std lib + * Handle comment directive '@ts-nocheck' + */ while ((currentNode as any).expression) { - /* CC-OFFNXT(no_explicit_any) std lib */ - // Handle comment directive '@ts-nocheck' + + /* + * CC-OFFNXT(no_explicit_any) std lib + * Handle comment directive '@ts-nocheck' + */ currentNode = (currentNode as any).expression; } return currentNode; } - private processSdkMethodClauseTypes(tsClassDecl: ts.ClassDeclaration, heritageClause: ts.HeritageClause): void { - for (const type of heritageClause.types) { + private processSdkMethodClauseTypes( + tsClassDecl: ts.ClassDeclaration, + heritageClause: ts.HeritageClause, + methodName?: string + ): boolean { + return heritageClause.types.some((type) => { const fullTypeName = TypeScriptLinter.findFinalExpression(type).getText(); const sdkInfos = this.interfaceMap.get(fullTypeName); if (!sdkInfos || sdkInfos.size === 0) { - continue; + return false; } - for (const sdkInfo of sdkInfos) { - if (sdkInfo.api_type !== 'MethodSignature') { - continue; + return Array.from(sdkInfos).some((sdkInfo) => { + if (sdkInfo.api_type !== METHOD_SIGNATURE && sdkInfo.api_type !== METHOD_DECLARATION) { + return false; } - this.processSdkInfoWithMembers(sdkInfo, tsClassDecl.members); - } - } + + if (!methodName) { + this.processSdkInfoWithMembers(sdkInfo, tsClassDecl.members,tsClassDecl); + return false; + } + + const symbol = this.tsTypeChecker.getSymbolAtLocation(type.expression); + return TypeScriptLinter.isHeritageClauseisThirdPartyBySymbol(symbol) && sdkInfo.api_name === methodName; + }); + }); } private handleSdkMethod(tsClassDecl: ts.ClassDeclaration): void { @@ -2527,7 +3021,7 @@ export class TypeScriptLinter { } } - private processSdkInfoWithMembers(sdkInfo: ApiInfo, members: ts.NodeArray): void { + private processSdkInfoWithMembers(sdkInfo: ApiInfo, members: ts.NodeArray,tsClassDecl:ts.ClassDeclaration): void { for (const member of members) { if (!ts.isMethodDeclaration(member)) { continue; @@ -2535,12 +3029,14 @@ export class TypeScriptLinter { const memberName = member.name?.getText(); if (sdkInfo.api_name === memberName) { - if (TypeScriptLinter.areParametersEqual(sdkInfo.api_func_args, member.parameters)) { - this.incrementCounters( - member, - sdkInfo.problem === 'OptionalMethod' ? FaultID.OptionalMethodFromSdk : FaultID.LimitedVoidTypeFromSdk - ); + if (!TypeScriptLinter.areParametersEqual(sdkInfo.api_func_args ?? [], member.parameters) && + !TypeScriptLinter.areGenericsParametersEqual(sdkInfo.api_func_args ?? [], tsClassDecl)) { + return; } + this.incrementCounters( + member, + sdkInfo.problem === OPTIONAL_METHOD ? FaultID.OptionalMethodFromSdk : FaultID.LimitedVoidTypeFromSdk + ); } } } @@ -2564,6 +3060,85 @@ export class TypeScriptLinter { return true; } + private processLimitedVoidTypeFromSdkOnClassDeclaration( + tsClassDecl: ts.ClassDeclaration, + methodName?: string + ): boolean { + if ( + !this.options.arkts2 || + !tsClassDecl.heritageClauses || + tsClassDecl.heritageClauses.length === 0 || + !tsClassDecl.members || + tsClassDecl.members.length === 0 + ) { + return false; + } + let res: boolean = false; + for (const heritageClause of tsClassDecl.heritageClauses) { + if (heritageClause.types?.length) { + res = this.processSdkMethodClauseTypes(tsClassDecl, heritageClause, methodName); + break; + } + } + return res; + } + + private static isHeritageClauseisThirdPartyBySymbol(symbol: ts.Symbol | undefined): boolean { + if (!symbol) { + return false; + } + const declarations = symbol.getDeclarations(); + if (declarations && declarations.length > 0) { + const firstDeclaration = declarations[0]; + if (ts.isImportSpecifier(firstDeclaration)) { + return true; + } + } + return false; + } + + private handleLimitedVoidTypeFromSdkOnPropertyAccessExpression(node: ts.PropertyAccessExpression): void { + if (!this.options.arkts2) { + return; + } + const sym = this.getOriginalSymbol(node.name); + if (!sym) { + return; + } + const methodName = node.name.getText(); + const declaration = sym.declarations?.[0]; + if (declaration && ts.isClassDeclaration(declaration.parent)) { + if (this.processLimitedVoidTypeFromSdkOnClassDeclaration(declaration.parent, methodName)) { + this.incrementCounters(node, FaultID.LimitedVoidTypeFromSdk); + } + } + } + private static areGenericsParametersEqual( + sdkFuncArgs: { name: string; type: string }[], + node: ts.ClassDeclaration + ): boolean { + if (!ts.isClassDeclaration(node)) { + return false; + } + const apiParamCout = sdkFuncArgs.length; + const typeParameters = node.typeParameters; + if (!typeParameters) { + return false; + } + typeParameters.forEach(typeParam => { + if (!typeParam.constraint) { + return false; + } + for (let i = 0; i < apiParamCout; i++) { + if (!typeParam.constraint.getText().match(sdkFuncArgs[i].type)) { + return false; + } + } + return true; + }); + return true; + } + private handleNotSupportCustomDecorators(decorator: ts.Decorator): void { if (!this.options.arkts2) { return; @@ -2633,6 +3208,9 @@ export class TypeScriptLinter { const staticBlockNodes: ts.Node[] = []; for (const element of classDecl.members) { if (ts.isClassStaticBlockDeclaration(element)) { + if (this.options.arkts2 && this.useStatic) { + this.incrementCounters(element, FaultID.NoStaticOnClass); + } staticBlockNodes[staticBlocksCntr] = element; staticBlocksCntr++; } @@ -2790,7 +3368,8 @@ export class TypeScriptLinter { private handleImportClause(node: ts.Node): void { const tsImportClause = node as ts.ImportClause; if (this.options.arkts2 && tsImportClause.isLazy) { - this.incrementCounters(node, FaultID.ImportLazyIdentifier); + const autofix = this.autofixer?.fixImportClause(tsImportClause); + this.incrementCounters(node, FaultID.ImportLazyIdentifier, autofix); } if (tsImportClause.name) { this.countDeclarationsWithDuplicateName(tsImportClause.name, tsImportClause); @@ -2853,6 +3432,147 @@ export class TypeScriptLinter { if (!this.tsUtils.isAbstractMethodInAbstractClass(node)) { this.handleTSOverload(tsMethodDecl); } + this.checkDefaultParamBeforeRequired(tsMethodDecl); + this.handleMethodInherit(tsMethodDecl); + } + + private checkDefaultParamBeforeRequired(node: ts.FunctionLikeDeclarationBase): void { + if (!this.options.arkts2) { + return; + } + + const params = node.parameters; + let seenRequired = false; + + for (let i = params.length - 1; i >= 0; i--) { + const param = params[i]; + + const isOptional = !!param.initializer || !!param.questionToken; + + if (!isOptional) { + seenRequired = true; + continue; + } + + if (seenRequired && param.initializer) { + this.incrementCounters(param.name, FaultID.DefaultArgsBehindRequiredArgs); + } + } + } + + private handleMethodInherit(node: ts.MethodDeclaration): void { + if (!this.options.arkts2 || !node.name || !ts.isIdentifier(node.name)) { + return; + } + + const classDecl = node.parent; + if (!ts.isClassDeclaration(classDecl)) { + return; + } + + const classType = this.tsTypeChecker.getTypeAtLocation(classDecl); + const baseTypes = classType.getBaseTypes(); + if (!baseTypes || baseTypes.length === 0) { + return; + } + + const methodName = node.name.text; + + for (const baseType of baseTypes) { + const baseMethod = baseType.getProperty(methodName); + if (!baseMethod) { + continue; + } + + const baseMethodDecl = baseMethod.declarations?.find(ts.isMethodDeclaration); + if (!baseMethodDecl) { + continue; + } + + // Check parameter compatibility + this.checkMethodParameters(node, baseMethodDecl); + + // Check return type compatibility + this.checkMethodReturnType(node, baseMethodDecl); + + break; + } + } + + /** + * Checks if child parameters accept at least as many types as parent parameters. + * (Child parameter type should be same or wider than parent.) + */ + private checkMethodParameters(derivedMethod: ts.MethodDeclaration, baseMethod: ts.MethodDeclaration): void { + const derivedParams = derivedMethod.parameters; + const baseParams = baseMethod.parameters; + + const paramCount = Math.min(derivedParams.length, baseParams.length); + + for (let i = 0; i < paramCount; i++) { + const baseParamType = this.tsTypeChecker.getTypeAtLocation(baseParams[i]); + const derivedParamType = this.tsTypeChecker.getTypeAtLocation(derivedParams[i]); + + if (!this.isTypeSameOrWider(baseParamType, derivedParamType)) { + this.incrementCounters(derivedParams[i], FaultID.MethodInheritRule); + } + } + } + + /** + * Checks return type covariance between base and derived methods. + * (Derived return type must be assignable to base return type.) + */ + private checkMethodReturnType(derivedMethod: ts.MethodDeclaration, baseMethod: ts.MethodDeclaration): void { + if (!baseMethod.type || !derivedMethod.type) { + return; + } + + const baseReturnType = this.tsTypeChecker.getTypeAtLocation(baseMethod.type); + const derivedReturnType = this.tsTypeChecker.getTypeAtLocation(derivedMethod.type); + + if (!this.isTypeAssignable(derivedReturnType, baseReturnType)) { + this.incrementCounters(derivedMethod.type, FaultID.MethodInheritRule); + } + } + + /** + * Child type should include all types of parent type (be same or wider). + * Returns true if every type in baseType is also included in derivedType. + */ + private isTypeSameOrWider(baseType: ts.Type, derivedType: ts.Type): boolean { + const baseTypeSet = new Set(this.flattenUnionTypes(baseType)); + const derivedTypeSet = new Set(this.flattenUnionTypes(derivedType)); + + // Check if every type in baseType is also present in derivedType + for (const typeStr of baseTypeSet) { + if (!derivedTypeSet.has(typeStr)) { + return false; + } + } + + return true; + } + + // Checks structural assignability between two types. + private isTypeAssignable(fromType: ts.Type, toType: ts.Type): boolean { + const fromTypes = this.flattenUnionTypes(fromType); + const toTypes = new Set(this.flattenUnionTypes(toType)); + + // All types in `fromTypes` should exist in `toTypes` for assignability. + return fromTypes.every((typeStr) => { + return toTypes.has(typeStr); + }); + } + + // Converts union types into an array of type strings for easy comparison. + private flattenUnionTypes(type: ts.Type): string[] { + if (type.isUnion()) { + return type.types.map((t) => { + return this.tsTypeChecker.typeToString(t); + }); + } + return [this.tsTypeChecker.typeToString(type)]; } private checkClassImplementsMethod(classDecl: ts.ClassDeclaration, methodName: string): boolean { @@ -2871,8 +3591,8 @@ export class TypeScriptLinter { if (this.options.arkts2 && ts.isInterfaceDeclaration(node.parent)) { const methodName = node.name.getText(); const interfaceName = node.parent.name.getText(); - const allClasses = TypeScriptLinter.getAllClassesFromSourceFile(this.sourceFile!); - const allInterfaces = TypeScriptLinter.getAllInterfaceFromSourceFile(this.sourceFile!); + const allClasses = TypeScriptLinter.getAllClassesFromSourceFile(this.sourceFile); + const allInterfaces = TypeScriptLinter.getAllInterfaceFromSourceFile(this.sourceFile); allClasses.forEach((classDecl) => { if (this.classImplementsInterface(classDecl, interfaceName)) { this.checkClassImplementsMethod(classDecl, methodName); @@ -2973,41 +3693,116 @@ export class TypeScriptLinter { if (isArkTs2 && this.tsTypeChecker.isArgumentsSymbol(tsIdentSym)) { this.incrementCounters(node, FaultID.ArgumentsObject); } - if (isArkTs2 && tsIdentifier.text === LIKE_FUNCTION && isStdLibrarySymbol(tsIdentSym)) { - this.incrementCounters(node, FaultID.ExplicitFunctionType); + + if (isArkTs2) { + this.checkWorkerSymbol(tsIdentSym, node); + this.checkCollectionsSymbol(tsIdentSym, node); + this.checkAsonSymbol(tsIdentSym, node); } } - private handleGlobalThisCase(node: ts.Identifier, isArkTs2: boolean | undefined): void { - let faultId = FaultID.GlobalThis; - let autofix: Autofix[] | undefined; - let targetNode: ts.Node = node; + private handlePropertyDescriptorInScenarios(node: ts.Node): void { + if (ts.isVariableDeclaration(node)) { + const name = node.name; + this.handlePropertyDescriptor(name); - if (!isArkTs2) { - this.incrementCounters(targetNode, faultId); - return; + const type = node.type; + if (!type || !ts.isTypeReferenceNode(type)) { + return; + } + const typeName = type.typeName; + this.handlePropertyDescriptor(typeName); } - faultId = FaultID.GlobalThisError; - if (ts.isPropertyAccessExpression(node.parent)) { - const parentExpression = node.parent.parent; - if ( - parentExpression && - ts.isBinaryExpression(parentExpression) && - parentExpression.operatorToken.kind === ts.SyntaxKind.EqualsToken - ) { - targetNode = parentExpression; - autofix = this.autofixer?.fixGlobalThisSet(targetNode as ts.BinaryExpression); - } else { - targetNode = node.parent; - autofix = this.autofixer?.fixGlobalThisGet(targetNode as ts.PropertyAccessExpression); + if (ts.isParameter(node)) { + const name = node.name; + this.handlePropertyDescriptor(name); + + const type = node.type; + if (!type || !ts.isTypeReferenceNode(type)) { + return; } + const typeName = type.typeName; + this.handlePropertyDescriptor(typeName); } - this.incrementCounters(targetNode, faultId, autofix); + if (ts.isPropertyAccessExpression(node)) { + const name = node.name; + this.handlePropertyDescriptor(name); + + const expression = node.expression; + this.handlePropertyDescriptor(expression); + } } - // hard-coded alternative to TypeScriptLinter.advancedClassChecks + private handlePropertyDescriptor(node: ts.Node): void { + if (!this.options.arkts2) { + return; + } + + const symbol = this.tsUtils.trueSymbolAtLocation(node); + if (!symbol || !ts.isIdentifier(node)) { + return; + } + const tsIdentifier = node; + const type = this.tsTypeChecker.getTypeOfSymbolAtLocation(symbol, tsIdentifier); + + const typeSymbol = type.getSymbol(); + const typeName = typeSymbol ? typeSymbol.getName() : symbol.getName(); + + const noPropertyDescriptorSet = TypeScriptLinter.globalApiInfo.get(BuiltinProblem.BuiltinNoPropertyDescriptor); + if (!noPropertyDescriptorSet) { + return; + } + + const matchedApi = [...noPropertyDescriptorSet].some((apiInfoItem) => { + if (apiInfoItem.api_info.parent_api?.length <= 0) { + return false; + } + const apiInfoParentName = apiInfoItem.api_info.parent_api[0].api_name; + const apiTypeName = apiInfoItem.api_info.method_return_type; + const isSameApi = apiInfoParentName === typeName || apiTypeName === typeName; + const decl = TsUtils.getDeclaration(typeSymbol ? typeSymbol : symbol); + const sourceFileName = path.normalize(decl?.getSourceFile().fileName || ''); + const isSameFile = sourceFileName.endsWith(path.normalize(apiInfoItem.file_path)); + return isSameFile && isSameApi; + }); + + if (matchedApi) { + this.incrementCounters(tsIdentifier, FaultID.NoPropertyDescriptor); + } + } + + private handleGlobalThisCase(node: ts.Identifier, isArkTs2: boolean | undefined): void { + let faultId = FaultID.GlobalThis; + let autofix: Autofix[] | undefined; + let targetNode: ts.Node = node; + + if (!isArkTs2) { + this.incrementCounters(targetNode, faultId); + return; + } + faultId = FaultID.GlobalThisError; + + if (ts.isPropertyAccessExpression(node.parent)) { + const parentExpression = node.parent.parent; + if ( + parentExpression && + ts.isBinaryExpression(parentExpression) && + parentExpression.operatorToken.kind === ts.SyntaxKind.EqualsToken + ) { + targetNode = parentExpression; + autofix = this.autofixer?.fixGlobalThisSet(targetNode as ts.BinaryExpression); + } else { + targetNode = node.parent; + autofix = this.autofixer?.fixGlobalThisGet(targetNode as ts.PropertyAccessExpression); + } + } + + this.incrementCounters(targetNode, faultId, autofix); + } + + // hard-coded alternative to TypeScriptLinter.advancedClassChecks private isAllowedClassValueContext(tsIdentifier: ts.Identifier): boolean { let ctx: ts.Node = tsIdentifier; while (ts.isPropertyAccessExpression(ctx.parent) || ts.isQualifiedName(ctx.parent)) { @@ -3175,9 +3970,11 @@ export class TypeScriptLinter { if (this.tsUtils.isOrDerivedFrom(tsElemAccessBaseExprType, this.tsUtils.isIndexableArray)) { this.handleIndexNegative(node); } + this.checkArrayUsageWithoutBound(tsElementAccessExpr); this.checkArrayIndexType(tsElemAccessBaseExprType, tsElemAccessArgType, tsElementAccessExpr); this.fixJsImportElementAccessExpression(tsElementAccessExpr); this.checkInterOpImportJsIndex(tsElementAccessExpr); + this.checkEnumGetMemberValue(tsElementAccessExpr); } private checkInterOpImportJsIndex(expr: ts.ElementAccessExpression): void { @@ -3225,12 +4022,17 @@ export class TypeScriptLinter { } const argExpr = TypeScriptLinter.getUnwrappedArgumentExpression(expr.argumentExpression); - - const validStringLiteralTypes = [STRINGLITERAL_INT, STRINGLITERAL_BYTE, STRINGLITERAL_SHORT, STRINGLITERAL_LONG]; + const validStringLiteralTypes = [ + STRINGLITERAL_INT, + STRINGLITERAL_BYTE, + STRINGLITERAL_SHORT, + STRINGLITERAL_LONG, + STRINGLITERAL_CHAR + ]; const argTypeString = this.tsTypeChecker.typeToString(argType); if (this.tsUtils.isNumberLikeType(argType)) { - this.handleNumericArgument(argExpr); + this.handleNumericArgument(argExpr, expr.argumentExpression, argType); } else if (!validStringLiteralTypes.includes(argTypeString)) { this.incrementCounters(argExpr, FaultID.ArrayIndexExprType); } @@ -3240,15 +4042,33 @@ export class TypeScriptLinter { return argExpr.kind === ts.SyntaxKind.AsExpression ? (argExpr as ts.AsExpression).expression : argExpr; } - private handleNumericArgument(argExpr: ts.Expression): void { - if ( - ts.isNumericLiteral(argExpr) && !Number.isInteger(Number(argExpr.text)) || - argExpr.kind === ts.SyntaxKind.CallExpression - ) { - this.incrementCounters(argExpr, FaultID.ArrayIndexExprType); + private handleNumericArgument(argExpr: ts.Expression, asExpr: ts.Expression, argType: ts.Type): void { + const isNumericLiteral = ts.isNumericLiteral(argExpr); + const isAsExpression = asExpr.kind === ts.SyntaxKind.AsExpression; + const argText = argExpr.getText(); + const argValue = Number(argText); + + if (isNumericLiteral) { + const isInteger = Number.isInteger(argValue); + const containsDot = argText.includes('.'); + + if (!isInteger || containsDot) { + const autofix = this.autofixer?.fixArrayIndexExprType(isAsExpression ? asExpr : argExpr); + this.incrementCounters(argExpr, FaultID.ArrayIndexExprType, autofix); + } + } else if (this.tsTypeChecker.typeToString(argType) === 'number') { + if (this.isArrayIndexValidNumber(argExpr)) { + return; + } + const autofix = this.autofixer?.fixArrayIndexExprType(argExpr); + this.incrementCounters(argExpr, FaultID.ArrayIndexExprType, autofix); + } else { + this.checkNumericArgumentDeclaration(argExpr); } - this.checkNumericArgumentDeclaration(argExpr); + if (ts.isConditionalExpression(argExpr)) { + this.incrementCounters(argExpr, FaultID.ArrayIndexExprType); + } } private checkNumericArgumentDeclaration(argExpr: ts.Expression): void { @@ -3269,15 +4089,77 @@ export class TypeScriptLinter { const isNumericInitializer = initializer && ts.isNumericLiteral(initializer); const initializerNumber = isNumericInitializer ? Number(initializerText) : NaN; const isUnsafeNumber = isNumericInitializer && !Number.isInteger(initializerNumber); - const isConstDeclaration = firstDeclaration.parent.flags === ts.NodeFlags.Let; - const isUndefinedButNotMaxSafeInteger = initializerText === 'undefined'; - if ( - isUnsafeNumber || - firstDeclaration.parent.flags === ts.NodeFlags.Const && isUnsafeNumber || - isConstDeclaration || - isUndefinedButNotMaxSafeInteger - ) { + if (isUnsafeNumber) { + const autofix = this.autofixer?.fixArrayIndexExprType(argExpr); + this.incrementCounters(argExpr, FaultID.ArrayIndexExprType, autofix); + } + + if (initializerText === 'undefined') { + this.handleUndefinedInitializer(argExpr, firstDeclaration); + } + } + + private evaluateValueFromDeclaration(argExpr: ts.Expression): number | null { + const declaration = this.tsUtils.getDeclarationNode(argExpr); + if (!declaration) { + return null; + } + + if (!ts.isVariableDeclaration(declaration)) { + return null; + } + + const initializer = declaration.initializer; + if (!initializer) { + return null; + } + + if (!ts.isNumericLiteral(initializer)) { + return null; + } + + const numericValue = Number(initializer.text); + if (!Number.isInteger(numericValue)) { + return null; + } + + return numericValue; + } + + private isArrayIndexValidNumber(argExpr: ts.Expression): boolean { + let evaluatedValue: number | null = null; + if (ts.isParenthesizedExpression(argExpr)) { + return this.isArrayIndexValidNumber(argExpr.expression); + } + + if (ts.isBinaryExpression(argExpr)) { + evaluatedValue = this.evaluateNumericValueFromBinaryExpression(argExpr); + } else { + evaluatedValue = this.evaluateValueFromDeclaration(argExpr); + } + const valueString = String(evaluatedValue); + + if (evaluatedValue === null) { + return false; + } + + if (!Number.isInteger(evaluatedValue)) { + return false; + } + // floating points that can be converted to int should be fine, so as long as no floating point is here, we should be fine. + if (valueString.includes('.') && !valueString.endsWith('.0')) { + return false; + } + + return evaluatedValue >= 0 && !valueString.includes('.'); + } + + private handleUndefinedInitializer(argExpr: ts.Expression, declaration: ts.VariableDeclaration): void { + if (ts.isParameter(declaration)) { + const autofix = this.autofixer?.fixArrayIndexExprType(argExpr); + this.incrementCounters(argExpr, FaultID.ArrayIndexExprType, autofix); + } else { this.incrementCounters(argExpr, FaultID.ArrayIndexExprType); } } @@ -3377,9 +4259,13 @@ export class TypeScriptLinter { } private processCalleeSym(calleeSym: ts.Symbol, tsCallExpr: ts.CallExpression): void { + const name = calleeSym.getName(); + const parName = this.tsUtils.getParentSymbolName(calleeSym); if (!this.options.arkts2) { - this.handleStdlibAPICall(tsCallExpr, calleeSym); + this.handleStdlibAPICall(tsCallExpr, calleeSym, name, parName); this.handleFunctionApplyBindPropCall(tsCallExpr, calleeSym); + } else { + this.handleBuiltinThisArgs(tsCallExpr, calleeSym, name, parName); } if (TsUtils.symbolHasEsObjectType(calleeSym)) { const faultId = this.options.arkts2 ? FaultID.EsObjectTypeError : FaultID.EsObjectType; @@ -3421,8 +4307,7 @@ export class TypeScriptLinter { return false; } const declFileFromJson = path.normalize(interfaceDecl.getSourceFile().fileName); - const declFileFromSdk = - indexedTypeSdkInfo.file_path.length > 0 ? path.normalize(indexedTypeSdkInfo.file_path[0]) : ''; + const declFileFromSdk = path.normalize(indexedTypeSdkInfo.file_path); const isSameSdkFilePath = declFileFromJson.endsWith(declFileFromSdk); const interfaceNameData = indexedTypeSdkInfo.api_info.parent_api[0].api_name; const isSameInterfaceName = interfaceDecl.name.getText() === interfaceNameData; @@ -3434,18 +4319,50 @@ export class TypeScriptLinter { } } + private handleBuiltinCtorCallSignature(tsCallExpr: ts.CallExpression | ts.TypeReferenceNode): void { + if (!this.options.arkts2) { + return; + } + const node = ts.isCallExpression(tsCallExpr) ? tsCallExpr.expression : tsCallExpr.typeName; + const constructorType = this.tsTypeChecker.getTypeAtLocation(node); + const callSignatures = constructorType.getCallSignatures(); + if (callSignatures.length === 0 || BUILTIN_DISABLE_CALLSIGNATURE.includes(node.getText())) { + return; + } + const isSameApi = callSignatures.some((callSignature) => { + const callSignatureDecl = callSignature.getDeclaration(); + if (!ts.isCallSignatureDeclaration(callSignatureDecl)) { + return false; + } + const parentDecl = callSignatureDecl.parent; + const parentName = ts.isInterfaceDeclaration(parentDecl) ? parentDecl.name.getText() : ''; + const BultinNoCtorFuncApiInfoSet = TypeScriptLinter.globalApiInfo.get(BuiltinProblem.BuiltinNoCtorFunc); + if (!BultinNoCtorFuncApiInfoSet) { + return false; + } + const isSameApi = [...BultinNoCtorFuncApiInfoSet].some((apiInfoItem) => { + if (apiInfoItem.api_info.parent_api?.length <= 0) { + return false; + } + const apiInfoParentName = apiInfoItem.api_info.parent_api[0].api_name; + return apiInfoParentName === parentName; + }); + return isSameApi; + }); + if (isSameApi) { + this.incrementCounters(node, FaultID.BuiltinNoCtorFunc); + } + } + private handleCallExpression(node: ts.Node): void { const tsCallExpr = node as ts.CallExpression; this.handleStateStyles(tsCallExpr); + this.handleBuiltinCtorCallSignature(tsCallExpr); + this.handleInteropAwaitImport(tsCallExpr); if (this.options.arkts2 && tsCallExpr.typeArguments !== undefined) { this.handleSdkPropertyAccessByIndex(tsCallExpr); } - - this.handleTsInterop(tsCallExpr.expression, () => { - this.checkInteropFunctionCall(tsCallExpr); - }); - const calleeSym = this.tsUtils.trueSymbolAtLocation(tsCallExpr.expression); const callSignature = this.tsTypeChecker.getResolvedSignature(tsCallExpr); this.handleImportCall(tsCallExpr); @@ -3453,13 +4370,16 @@ export class TypeScriptLinter { if (calleeSym !== undefined) { this.processCalleeSym(calleeSym, tsCallExpr); } - if (callSignature !== undefined && !this.tsUtils.isLibrarySymbol(calleeSym)) { - this.handleGenericCallWithNoTypeArgs(tsCallExpr, callSignature); - this.handleStructIdentAndUndefinedInArgs(tsCallExpr, callSignature); + if (callSignature !== undefined) { + if (!this.tsUtils.isLibrarySymbol(calleeSym)) { + this.handleStructIdentAndUndefinedInArgs(tsCallExpr, callSignature); + this.handleGenericCallWithNoTypeArgs(tsCallExpr, callSignature); + } else if (this.options.arkts2) { + this.handleGenericCallWithNoTypeArgs(tsCallExpr, callSignature); + } } this.handleInteropForCallExpression(tsCallExpr); this.handleLibraryTypeCall(tsCallExpr); - if ( ts.isPropertyAccessExpression(tsCallExpr.expression) && this.tsUtils.hasEsObjectType(tsCallExpr.expression.expression) @@ -3470,46 +4390,68 @@ export class TypeScriptLinter { if ( !ts.isExpressionStatement(tsCallExpr.parent) && !ts.isVoidExpression(tsCallExpr.parent) && - !ts.isArrowFunction(tsCallExpr.parent) + !ts.isArrowFunction(tsCallExpr.parent) && + !(ts.isConditionalExpression(tsCallExpr.parent) && ts.isExpressionStatement(tsCallExpr.parent.parent)) ) { this.handleLimitedVoidWithCall(tsCallExpr); } - this.checkArkTSObjectInterop(tsCallExpr); this.handleAppStorageCallExpression(tsCallExpr); this.fixJsImportCallExpression(tsCallExpr); - this.handleCallJSFunction(tsCallExpr, calleeSym, callSignature); - this.handleInteropForCallObjectMethods(tsCallExpr, calleeSym, callSignature); + this.handleInteropForCallJSExpression(tsCallExpr, calleeSym, callSignature); + this.handleNoTsLikeFunctionCall(tsCallExpr); + this.handleObjectLiteralInFunctionArgs(tsCallExpr); + this.handleTaskPoolDeprecatedUsages(tsCallExpr); + this.handleSdkDuplicateDeclName(tsCallExpr); } - private handleAppStorageCallExpression(tsCallExpr: ts.CallExpression): void { - if (!this.options.arkts2 || !tsCallExpr) { + handleNoTsLikeFunctionCall(callExpr: ts.CallExpression): void { + if (!this.options.arkts2) { return; } - if ( - !ts.isBinaryExpression(tsCallExpr.parent) || - tsCallExpr.parent.operatorToken.kind !== ts.SyntaxKind.QuestionQuestionToken - ) { + + const expression = callExpr.expression; + const type = this.tsTypeChecker.getTypeAtLocation(expression); + const typeText = this.tsTypeChecker.typeToString(type); + if (typeText === LIKE_FUNCTION) { + const autofix = this.autofixer?.fixNoTsLikeFunctionCall(expression); + this.incrementCounters(expression, FaultID.ExplicitFunctionType, autofix); + } + } + + private handleAppStorageCallExpression(tsCallExpr: ts.CallExpression): void { + if (!this.options.arkts2 || !tsCallExpr) { return; } - const varDecl = tsCallExpr.parent.parent; - if (!ts.isVariableDeclaration(varDecl)) { + if (!TsUtils.isAppStorageAccess(tsCallExpr)) { return; } - if (varDecl.type && ts.isTypeReferenceNode(varDecl.type)) { - if (varDecl.type.typeName.getText() === STRINGLITERAL_ANY) { - return; + let varDecl: ts.VariableDeclaration | undefined; + let parent = tsCallExpr.parent; + + while (parent) { + if (ts.isVariableDeclaration(parent)) { + varDecl = parent; + break; } + parent = parent.parent; } + if (!varDecl || varDecl.type) { + return; + } const callReturnType = this.tsTypeChecker.getTypeAtLocation(tsCallExpr); const isNumberReturnType = callReturnType.flags & ts.TypeFlags.Number; const isNumberGeneric = ((): boolean => { if (tsCallExpr.typeArguments?.length !== 1) { return false; } + const callText = tsCallExpr.getText(); + if (callText.startsWith('Array<') || callText.startsWith('Set<') || callText.startsWith('Map<')) { + return false; + } const typeArg = tsCallExpr.typeArguments[0]; if (typeArg.kind === ts.SyntaxKind.NumberKeyword) { return true; @@ -3527,7 +4469,7 @@ export class TypeScriptLinter { } } - handleCallJSFunction( + handleInteropForCallJSExpression( tsCallExpr: ts.CallExpression, sym: ts.Symbol | undefined, callSignature: ts.Signature | undefined @@ -3535,20 +4477,29 @@ export class TypeScriptLinter { if (!callSignature) { return; } - if (TypeScriptLinter.isDeclaredInArkTs2(callSignature) && this.options.arkts2) { + if (!TypeScriptLinter.isDeclaredInArkTs2(callSignature) && this.options.arkts2) { if (sym?.declarations?.[0]?.getSourceFile().fileName.endsWith(EXTNAME_JS)) { - this.incrementCounters(tsCallExpr, FaultID.CallJSFunction); + this.incrementCounters( + tsCallExpr, + ts.isPropertyAccessExpression(tsCallExpr.expression) ? + FaultID.InteropCallObjectMethods : + FaultID.CallJSFunction + ); } } } private handleInteropForCallExpression(tsCallExpr: ts.CallExpression): void { + if (!this.options.arkts2 || !this.useStatic) { + return; + } + const callSignature = this.tsTypeChecker.getResolvedSignature(tsCallExpr); if (!callSignature) { return; } - if (TypeScriptLinter.isDeclaredInArkTs2(callSignature)) { + if (!TypeScriptLinter.isDeclaredInArkTs2(callSignature)) { return; } @@ -3556,19 +4507,43 @@ export class TypeScriptLinter { this.checkForReflectAPIUse(callSignature, tsCallExpr); } - private handleInteropForCallObjectMethods( - tsCallExpr: ts.CallExpression, - sym: ts.Symbol | undefined, - callSignature: ts.Signature | undefined - ): void { - if (!callSignature) { - return; + private isExportedEntityDeclaredInJs(exportDecl: ts.ExportDeclaration): boolean { + if (!this.options.arkts2 || !this.useStatic) { + return false; } - if (TypeScriptLinter.isDeclaredInArkTs2(callSignature) && this.options.arkts2) { - if (sym?.declarations?.[0]?.getSourceFile().fileName.endsWith(EXTNAME_JS)) { - this.incrementCounters(tsCallExpr, FaultID.InteropCallObjectMethods); + + if (!exportDecl.exportClause || !ts.isNamedExports(exportDecl.exportClause)) { + return false; + } + + for (const exportSpecifier of exportDecl.exportClause.elements) { + const identifier = exportSpecifier.name; + if (this.tsUtils.isImportedFromJS(identifier)) { + return true; + } + } + + return false; + } + + private isExportedEntityDeclaredInArkTs1(exportDecl: ts.ExportDeclaration): boolean | undefined { + if (!this.options.arkts2 || !this.useStatic) { + return false; + } + + if (!exportDecl.exportClause || !ts.isNamedExports(exportDecl.exportClause)) { + return false; + } + + for (const exportSpecifier of exportDecl.exportClause.elements) { + const identifier = exportSpecifier.name; + + if (this.tsUtils.isExportImportedFromArkTs1(identifier, exportDecl)) { + return true; } } + + return false; } private static isDeclaredInArkTs2(callSignature: ts.Signature): boolean | undefined { @@ -3580,7 +4555,7 @@ export class TypeScriptLinter { return undefined; } // check for 'use static' at the start of the file this function declared at - if (declarationSourceFile.statements[0].getText() !== USE_STATIC) { + if (declarationSourceFile.statements[0].getText() === USE_STATIC) { return true; } return false; @@ -3600,7 +4575,6 @@ export class TypeScriptLinter { } if (this.tsTypeChecker.getTypeAtLocation(argument).isClass()) { - // return error this.incrementCounters(tsCallExpr, FaultID.InteropCallObjectParam); return; } @@ -3681,7 +4655,8 @@ export class TypeScriptLinter { * for a detailed analysis. */ if (this.options.arkts2 && TypeScriptLinter.isInvalidBuiltinGenericConstructorCall(callLikeExpr)) { - this.incrementCounters(callLikeExpr, FaultID.GenericCallNoTypeArgs); + const autofix = this.autofixer?.fixGenericCallNoTypeArgs(callLikeExpr as ts.NewExpression); + this.incrementCounters(callLikeExpr, FaultID.GenericCallNoTypeArgs, autofix); return; } this.checkTypeArgumentsForGenericCallWithNoTypeArgs(callLikeExpr, callSignature); @@ -3700,6 +4675,9 @@ export class TypeScriptLinter { callLikeExpr: ts.CallExpression | ts.NewExpression, callSignature: ts.Signature ): void { + if (ts.isNewExpression(callLikeExpr) && this.isNonGenericClass(callLikeExpr)) { + return; + } const tsSyntaxKind = ts.isNewExpression(callLikeExpr) ? ts.SyntaxKind.Constructor : ts.SyntaxKind.FunctionDeclaration; @@ -3717,7 +4695,8 @@ export class TypeScriptLinter { const startTypeArg = callLikeExpr.typeArguments?.length ?? 0; if (this.options.arkts2 && callLikeExpr.kind === ts.SyntaxKind.NewExpression) { if (startTypeArg !== resolvedTypeArgs.length) { - this.incrementCounters(callLikeExpr, FaultID.GenericCallNoTypeArgs); + const autofix = this.autofixer?.fixGenericCallNoTypeArgs(callLikeExpr); + this.incrementCounters(callLikeExpr, FaultID.GenericCallNoTypeArgs, autofix); } } else { for (let i = startTypeArg; i < resolvedTypeArgs.length; ++i) { @@ -3738,10 +4717,19 @@ export class TypeScriptLinter { } } + private isNonGenericClass(expression: ts.NewExpression): boolean { + const declaration = this.tsUtils.getDeclarationNode(expression.expression); + return !!declaration && ts.isClassDeclaration(declaration) && !declaration.typeParameters; + } + checkTypeArgumentsForGenericCallWithNoTypeArgsNumber( callLikeExpr: ts.CallExpression | ts.NewExpression, callSignature: ts.Signature ): void { + if (TypeScriptLinter.isArrayFromCall(callLikeExpr)) { + return; + } + const tsSyntaxKind = ts.isNewExpression(callLikeExpr) ? ts.SyntaxKind.Constructor : ts.SyntaxKind.FunctionDeclaration; @@ -3781,6 +4769,16 @@ export class TypeScriptLinter { } } + static isArrayFromCall(callLikeExpr: ts.CallExpression | ts.NewExpression): boolean { + return ( + ts.isCallExpression(callLikeExpr) && + ts.isPropertyAccessExpression(callLikeExpr.expression) && + callLikeExpr.expression.name.text === STRINGLITERAL_FROM && + ts.isIdentifier(callLikeExpr.expression.expression) && + callLikeExpr.expression.expression.text === STRINGLITERAL_ARRAY + ); + } + private static readonly listFunctionApplyCallApis = [ 'Function.apply', 'Function.call', @@ -3843,9 +4841,12 @@ export class TypeScriptLinter { [SYMBOL_CONSTRUCTOR, { arr: null, fault: FaultID.SymbolType }] ]); - private handleStdlibAPICall(callExpr: ts.CallExpression, calleeSym: ts.Symbol): void { - const name = calleeSym.getName(); - const parName = this.tsUtils.getParentSymbolName(calleeSym); + private handleStdlibAPICall( + callExpr: ts.CallExpression, + calleeSym: ts.Symbol, + name: string, + parName: string | undefined + ): void { if (parName === undefined) { if (LIMITED_STD_GLOBAL_API.includes(name)) { this.incrementCounters(callExpr, FaultID.LimitedStdLibApi); @@ -3867,6 +4868,43 @@ export class TypeScriptLinter { } } + private handleBuiltinThisArgs( + callExpr: ts.CallExpression, + calleeSym: ts.Symbol, + name: string, + parName: string | undefined + ): void { + if (parName === undefined) { + return; + } + + const builtinThisArgsInfos = TypeScriptLinter.funcMap.get(name); + if (!builtinThisArgsInfos) { + return; + } + + const sourceFile = calleeSym?.declarations?.[0]?.getSourceFile(); + if (!sourceFile) { + return; + } + + const fileName = path.basename(sourceFile.fileName); + const builtinInfos = builtinThisArgsInfos.get(fileName); + if (!(builtinInfos && builtinInfos.size > 0)) { + return; + } + for (const info of builtinInfos) { + const needReport = + info.parent_api.length > 0 && + info.parent_api[0].api_name === parName && + info?.api_func_args?.length === callExpr.arguments.length; + if (needReport) { + this.incrementCounters(callExpr, FaultID.BuiltinThisArgs); + return; + } + } + } + private checkLimitedStdlibApi(node: ts.Identifier, symbol: ts.Symbol): void { const parName = this.tsUtils.getParentSymbolName(symbol); const entries = LIMITED_STD_API.get(parName); @@ -3928,9 +4966,49 @@ export class TypeScriptLinter { ); } + private checkConstrutorAccess(newExpr: ts.NewExpression): void { + if (!this.options.arkts2 || !this.useStatic) { + return; + } + + if (!ts.isPropertyAccessExpression(newExpr.parent)) { + return; + } + + if (newExpr.parent.name.text === 'constructor') { + this.incrementCounters(newExpr.parent, FaultID.NoConstructorOnClass); + } + } + + private checkForInterfaceInitialization(newExpression: ts.NewExpression): void { + if (!this.options.arkts2 || !this.useStatic) { + return; + } + + if (!ts.isReturnStatement(newExpression.parent)) { + return; + } + + const calleeExpr = newExpression.expression; + if (!ts.isIdentifier(calleeExpr)) { + return; + } + + const type = this.tsTypeChecker.getTypeAtLocation(calleeExpr); + if (type.isClassOrInterface()) { + this.incrementCounters(calleeExpr, FaultID.ConstructorIface); + } + } + private handleNewExpression(node: ts.Node): void { const tsNewExpr = node as ts.NewExpression; + this.checkForInterfaceInitialization(tsNewExpr); + this.handleSharedArrayBuffer(tsNewExpr); + this.handleSdkDuplicateDeclName(tsNewExpr); + this.checkConstrutorAccess(tsNewExpr); + this.checkCreatingPrimitiveTypes(tsNewExpr); + if (this.options.advancedClassChecks || this.options.arkts2) { const calleeExpr = tsNewExpr.expression; const calleeType = this.tsTypeChecker.getTypeAtLocation(calleeExpr); @@ -3947,14 +5025,29 @@ export class TypeScriptLinter { } const sym = this.tsUtils.trueSymbolAtLocation(tsNewExpr.expression); const callSignature = this.tsTypeChecker.getResolvedSignature(tsNewExpr); - if (callSignature !== undefined && !this.tsUtils.isLibrarySymbol(sym)) { - this.handleStructIdentAndUndefinedInArgs(tsNewExpr, callSignature); - this.handleGenericCallWithNoTypeArgs(tsNewExpr, callSignature); + if (callSignature !== undefined) { + if (!this.tsUtils.isLibrarySymbol(sym)) { + this.handleStructIdentAndUndefinedInArgs(tsNewExpr, callSignature); + this.handleGenericCallWithNoTypeArgs(tsNewExpr, callSignature); + } else if (this.options.arkts2) { + this.handleGenericCallWithNoTypeArgs(tsNewExpr, callSignature); + } } this.handleSendableGenericTypes(tsNewExpr); this.handleInstantiatedJsObject(tsNewExpr, sym); } + private checkCreatingPrimitiveTypes(tsNewExpr: ts.NewExpression): void { + if (!this.options.arkts2) { + return; + } + const typeStr = this.tsTypeChecker.typeToString(this.tsTypeChecker.getTypeAtLocation(tsNewExpr)); + const primitiveTypes = ['Number', 'String', 'Boolean']; + if (primitiveTypes.includes(typeStr)) { + this.incrementCounters(tsNewExpr, FaultID.CreatingPrimitiveTypes); + } + } + handleInstantiatedJsObject(tsNewExpr: ts.NewExpression, sym: ts.Symbol | undefined): void { if (this.useStatic && this.options.arkts2) { if (sym?.declarations?.[0]?.getSourceFile().fileName.endsWith(EXTNAME_JS)) { @@ -4016,18 +5109,19 @@ export class TypeScriptLinter { this.incrementCounters(node, FaultID.StructuralIdentity); } } - this.handleAsExpressionNumber(tsAsExpr); + this.handleAsExpressionImport(tsAsExpr); + this.handleNoTuplesArrays(node, targetType, exprType); } - private handleAsExpressionNumber(tsAsExpr): void { + private handleAsExpressionImport(tsAsExpr: ts.AsExpression): void { const type = tsAsExpr.type; - - if ( - this.useStatic && - this.options.arkts2 && - ts.isAsExpression(tsAsExpr) && - type.kind === ts.SyntaxKind.NumberKeyword - ) { + const restrictedTypes = [ + ts.SyntaxKind.NumberKeyword, + ts.SyntaxKind.BooleanKeyword, + ts.SyntaxKind.StringKeyword, + ts.SyntaxKind.BigIntKeyword + ]; + if (this.useStatic && this.options.arkts2 && restrictedTypes.includes(type.kind)) { const expr = ts.isPropertyAccessExpression(tsAsExpr.expression) ? tsAsExpr.expression.expression : tsAsExpr.expression; @@ -4065,9 +5159,40 @@ export class TypeScriptLinter { } } - private handleTypeReference(node: ts.Node): void { - const typeRef = node as ts.TypeReferenceNode; - + private handleSharedArrayBuffer(node: ts.TypeReferenceNode | ts.NewExpression): void { + if (!this.options.arkts2) { + return; + } + + const typeNameIdentifier = ts.isTypeReferenceNode(node) ? node.typeName : node.expression; + if (!ts.isIdentifier(typeNameIdentifier) || typeNameIdentifier.getText() !== ESLIB_SHAREDARRAYBUFFER) { + return; + } + + const decls = this.tsUtils.trueSymbolAtLocation(typeNameIdentifier)?.getDeclarations(); + const isSharedMemoryEsLib = decls?.some((decl) => { + const srcFileName = decl.getSourceFile().fileName; + return srcFileName.endsWith(ESLIB_SHAREDMEMORY_FILENAME); + }); + if (!isSharedMemoryEsLib) { + return; + } + if (ts.isNewExpression(node)) { + const autofix = this.autofixer?.fixSharedArrayBufferConstructor(node); + this.incrementCounters(node.expression, FaultID.SharedArrayBufferDeprecated, autofix); + } else { + const autofix = this.autofixer?.fixSharedArrayBufferTypeReference(node); + this.incrementCounters(node, FaultID.SharedArrayBufferDeprecated, autofix); + } + } + + private handleTypeReference(node: ts.Node): void { + const typeRef = node as ts.TypeReferenceNode; + + this.handleBuiltinCtorCallSignature(typeRef); + this.handleSharedArrayBuffer(typeRef); + this.handleSdkDuplicateDeclName(typeRef); + this.handleSdkConstructorIface(typeRef); const isESObject = TsUtils.isEsObjectType(typeRef); @@ -4094,7 +5219,30 @@ export class TypeScriptLinter { if (this.tsUtils.isSendableClassOrInterface(typeNameType)) { this.checkSendableTypeArguments(typeRef); } - this.handleQuotedHyphenPropsDeprecated(typeRef); + + this.checkNoEnumProp(typeRef); + } + + private checkNoEnumProp(typeRef: ts.TypeReferenceNode): void { + if (!this.options.arkts2) { + return; + } + if (ts.isQualifiedName(typeRef.typeName)) { + const symbol = this.tsTypeChecker.getSymbolAtLocation(typeRef.typeName.right); + + if (!symbol) { + return; + } + + const declarations = symbol.getDeclarations(); + if (!declarations || declarations.length === 0) { + return; + } + + if (ts.isEnumMember(declarations[0])) { + this.incrementCounters(typeRef, FaultID.NoEnumPropAsType); + } + } } private checkPartialType(node: ts.Node): void { @@ -4176,6 +5324,7 @@ export class TypeScriptLinter { const faultId = this.options.arkts2 ? FaultID.EsObjectTypeError : FaultID.EsObjectType; this.incrementCounters(tsTypeExpr, faultId); } + this.handleSdkDuplicateDeclName(tsTypeExpr); } private handleComputedPropertyName(node: ts.Node): void { @@ -4608,20 +5757,6 @@ export class TypeScriptLinter { return this.fileExportDeclCaches.has(decl); } - lint(sourceFile: ts.SourceFile): void { - if (this.options.enableAutofix) { - this.autofixer = new Autofixer(this.tsTypeChecker, this.tsUtils, sourceFile, this.options.cancellationToken); - } - - this.sourceFile = sourceFile; - this.useStatic = TsUtils.isArkts12File(sourceFile); - this.fileExportDeclCaches = undefined; - this.extractImportedNames(this.sourceFile); - this.visitSourceFile(this.sourceFile); - this.handleCommentDirectives(this.sourceFile); - this.processInterfacesToImport(this.sourceFile); - } - private handleExportKeyword(node: ts.Node): void { const parentNode = node.parent; if (!TypeScriptLinter.inSharedModule(node) || ts.isModuleBlock(parentNode.parent)) { @@ -4655,11 +5790,22 @@ export class TypeScriptLinter { } private handleExportDeclaration(node: ts.Node): void { + const exportDecl = node as ts.ExportDeclaration; + + if (this.isExportedEntityDeclaredInJs(exportDecl)) { + this.incrementCounters(node, FaultID.InteropJsObjectExport); + return; + } + + if (this.isExportedEntityDeclaredInArkTs1(exportDecl)) { + this.incrementCounters(node, FaultID.InteropArkTs1ObjectExport); + return; + } + if (!TypeScriptLinter.inSharedModule(node) || ts.isModuleBlock(node.parent)) { return; } - const exportDecl = node as ts.ExportDeclaration; if (exportDecl.exportClause === undefined) { this.incrementCounters(exportDecl, FaultID.SharedModuleNoWildcardExport); return; @@ -4691,6 +5837,7 @@ export class TypeScriptLinter { return; } this.checkAssignmentMatching(node, lhsType, expr, true); + this.handleObjectLiteralInReturn(returnStat); } /** @@ -4724,11 +5871,11 @@ export class TypeScriptLinter { this.handleExtendDecorator(node); this.handleEntryDecorator(node); this.handleProvideDecorator(node); + this.handleLocalBuilderDecorator(node); const decorator: ts.Decorator = node as ts.Decorator; this.checkSendableAndConcurrentDecorator(decorator); this.handleStylesDecorator(decorator); - this.handleTypescriptDecorators(decorator); if (TsUtils.getDecoratorName(decorator) === SENDABLE_DECORATOR) { const parent: ts.Node = decorator.parent; if (!parent || !SENDABLE_DECORATOR_NODES.includes(parent.kind)) { @@ -4914,9 +6061,9 @@ export class TypeScriptLinter { return; } const switchStatement = node as ts.SwitchStatement; - if (!this.isValidSwitchExpr(switchStatement)) { - this.incrementCounters(switchStatement.expression, FaultID.SwitchExpression); - } + + this.validateSwitchExpression(switchStatement); + const duplicateCases = this.findDuplicateCases(switchStatement); if (duplicateCases.length > 0) { for (const duplicateCase of duplicateCases) { @@ -4925,6 +6072,71 @@ export class TypeScriptLinter { } } + private validateSwitchExpression(switchStatement: ts.SwitchStatement): void { + const nodeType = this.tsTypeChecker.getTypeAtLocation(switchStatement.expression); + const typeName = this.tsTypeChecker.typeToString(nodeType); + const isUnionType = (nodeType.flags & ts.TypeFlags.Union) !== 0; + + const { isLiteralInitialized, isFloatLiteral, hasExplicitTypeAnnotation } = this.getDeclarationInfo( + switchStatement.expression + ); + + const isAllowed = + !isUnionType && + (nodeType.flags & ts.TypeFlags.StringLike || + typeName === 'String' || + nodeType.flags & ts.TypeFlags.NumberLike && (/^\d+$/).test(typeName) || + isLiteralInitialized && !hasExplicitTypeAnnotation && !isFloatLiteral || + nodeType.flags & ts.TypeFlags.EnumLike); + + if (!isAllowed) { + this.incrementCounters(switchStatement.expression, FaultID.SwitchExpression); + } + } + + private getDeclarationInfo(expression: ts.Expression): { + isLiteralInitialized: boolean; + isFloatLiteral: boolean; + hasExplicitTypeAnnotation: boolean; + } { + const symbol = this.tsTypeChecker.getSymbolAtLocation(expression); + const declaration = symbol?.valueDeclaration; + + if (!declaration || !ts.isVariableDeclaration(declaration)) { + return { isLiteralInitialized: false, isFloatLiteral: false, hasExplicitTypeAnnotation: false }; + } + + const hasExplicitTypeAnnotation = !!declaration.type; + const initializerInfo = TypeScriptLinter.getInitializerInfo(declaration.initializer); + + return { + isLiteralInitialized: initializerInfo.isLiteralInitialized, + isFloatLiteral: initializerInfo.isFloatLiteral, + hasExplicitTypeAnnotation + }; + } + + private static getInitializerInfo(initializer?: ts.Expression): { + isLiteralInitialized: boolean; + isFloatLiteral: boolean; + } { + if (!initializer) { + return { isLiteralInitialized: false, isFloatLiteral: false }; + } + + const isLiteralInitialized = ts.isNumericLiteral(initializer) || ts.isStringLiteral(initializer); + + let isFloatLiteral = false; + if (ts.isNumericLiteral(initializer)) { + const literalText = initializer.getText(); + if (!(/^0[xX]/).test(literalText)) { + isFloatLiteral = (/\.|e[-+]|\dE[-+]/i).test(literalText); + } + } + + return { isLiteralInitialized, isFloatLiteral }; + } + private findDuplicateCases(switchStatement: ts.SwitchStatement): ts.CaseClause[] { const seenValues = new Map(); const duplicates: ts.CaseClause[] = []; @@ -4964,87 +6176,6 @@ export class TypeScriptLinter { } } - private isValidSwitchExpr(switchStatement: ts.SwitchStatement): boolean { - const expressionType = this.tsTypeChecker.getTypeAtLocation(switchStatement.expression); - if (!expressionType) { - return false; - } - if (this.isSwitchAllowedType(expressionType, switchStatement.expression)) { - return true; - } - if (expressionType.isUnion()) { - const unionTypes = expressionType.types; - return unionTypes.every((t) => { - return this.isSwitchAllowedType(t, switchStatement.expression); - }); - } - return false; - } - - private isSwitchAllowedType(type: ts.Type, node: ts.Node): boolean { - if (type.flags & (ts.TypeFlags.StringLike | ts.TypeFlags.EnumLike)) { - return true; - } - - if (type.flags & (ts.TypeFlags.Number | ts.TypeFlags.NumberLiteral)) { - if (type.isNumberLiteral()) { - const value = type.value; - return TypeScriptLinter.isValidNumber(value); - } - if (ts.isIdentifier(node)) { - const refValue = this.getNumberReferenceValue(node); - if (refValue !== null && !TypeScriptLinter.isValidNumber(refValue)) { - return false; - } - } - return true; - } - - const typeString = this.tsTypeChecker.typeToString(type); - return typeString === 'String' || typeString === 'int'; - } - - private static isValidNumber(value: number): boolean { - const forbiddenValues = [ - Number.NaN, - Number.POSITIVE_INFINITY, - Number.NEGATIVE_INFINITY, - Number.MAX_VALUE, - Number.MIN_VALUE - ]; - - return !forbiddenValues.includes(value) && Number.isInteger(value); - } - - private getNumberReferenceValue(node: ts.Identifier): number | null { - const symbol = this.tsTypeChecker.getSymbolAtLocation(node); - if (!symbol) { - return null; - } - - for (const decl of symbol.getDeclarations() || []) { - if (!ts.isVariableDeclaration(decl) || !decl.initializer) { - continue; - } - if (ts.isPropertyAccessExpression(decl.initializer)) { - const propName = decl.initializer.name.text; - const numberProps: Record = { - NaN: Number.NaN, - POSITIVE_INFINITY: Number.POSITIVE_INFINITY, - NEGATIVE_INFINITY: Number.NEGATIVE_INFINITY, - MAX_VALUE: Number.MAX_VALUE, - MIN_VALUE: Number.MIN_VALUE - }; - if (propName in numberProps) { - return numberProps[propName]; - } - } else if (ts.isNumericLiteral(decl.initializer)) { - return Number(decl.initializer.text); - } - } - return null; - } - private handleLimitedLiteralType(literalTypeNode: ts.LiteralTypeNode): void { if (!this.options.arkts2 || !literalTypeNode) { return; @@ -5219,7 +6350,9 @@ export class TypeScriptLinter { } if ( this.tsUtils.isOrDerivedFrom(lhsType, this.tsUtils.isArray) && - this.tsUtils.isOrDerivedFrom(rhsType, TsUtils.isTuple) + this.tsUtils.isOrDerivedFrom(rhsType, TsUtils.isTuple) || + this.tsUtils.isOrDerivedFrom(rhsType, this.tsUtils.isArray) && + this.tsUtils.isOrDerivedFrom(lhsType, TsUtils.isTuple) ) { this.incrementCounters(node, FaultID.NoTuplesArrays); } @@ -5317,14 +6450,17 @@ export class TypeScriptLinter { return; } - if (ts.isPropertyAssignment(node)) { - const text = node.initializer.getText(); - if (!(/^\$\w+$/).test(text)) { - return; - } - const autofix = this.autofixer?.fixDollarBind(node); - this.incrementCounters(node, FaultID.DollarBindingNotSupported, autofix); + if (!ts.isPropertyAssignment(node) || !ts.isIdentifier(node.initializer)) { + return; + } + + const text = node.initializer.getText(); + if (!(/^\$.+$/).test(text)) { + return; } + + const autofix = this.autofixer?.fixDollarBind(node); + this.incrementCounters(node, FaultID.DollarBindingNotSupported, autofix); } private handleExtendDecorator(node: ts.Node): void { @@ -5385,8 +6521,33 @@ export class TypeScriptLinter { } const isStatic = TsUtils.hasModifier(propDecl.modifiers, ts.SyntaxKind.StaticKeyword); const hasNoInitializer = !propDecl.initializer; - if (isStatic && hasNoInitializer) { - this.incrementCounters(propDecl, FaultID.ClassstaticInitialization); + const isOptional = !!propDecl.questionToken; + + const defaultSkipTypeCheck = (typeNode: ts.TypeNode | undefined): boolean => { + if (!typeNode) { + return false; + } + + const typeText = typeNode.getText(); + if (ts.isLiteralTypeNode(typeNode) || ['boolean', 'number', 'null', 'undefined'].includes(typeText)) { + return true; + } + + if (ts.isUnionTypeNode(typeNode)) { + return typeNode.types.some((t) => { + const tText = t.getText(); + return tText === 'undefined'; + }); + } + + return false; + }; + + const shouldSkipCheck = isOptional || defaultSkipTypeCheck(propDecl.type); + + if (isStatic && hasNoInitializer && !shouldSkipCheck) { + const autofix = this.autofixer?.fixStaticPropertyInitializer(propDecl); + this.incrementCounters(propDecl, FaultID.ClassstaticInitialization, autofix); } } @@ -5448,7 +6609,8 @@ export class TypeScriptLinter { } private handleHeritageClause(node: ts.HeritageClause): void { - if (!this.options.arkts2) { + this.checkEWTArgumentsForSdkDuplicateDeclName(node); + if (!this.options.arkts2 || !this.useStatic) { return; } if (node.token === ts.SyntaxKind.ExtendsKeyword || node.token === ts.SyntaxKind.ImplementsKeyword) { @@ -5468,6 +6630,8 @@ export class TypeScriptLinter { this.fixJsImportExtendsClass(node.parent, expr); } }); + + this.handleMissingSuperCallInExtendedClass(node); } } @@ -5477,61 +6641,87 @@ export class TypeScriptLinter { } private checkSendableAndConcurrentDecorator(decorator: ts.Decorator): void { - if (!this.options.arkts2) { + if (!this.options.arkts2 || !this.useStatic) { return; } const decoratorName = TsUtils.getDecoratorName(decorator); - if (decoratorName === SENDABLE_DECORATOR || decoratorName === CONCURRENT_DECORATOR) { - const autofix = this.autofixer?.removeNode(decorator); - this.incrementCounters(decorator, FaultID.LimitedStdLibApi, autofix); + const autofix = this.autofixer?.removeNode(decorator); + if (decoratorName === SENDABLE_DECORATOR) { + this.incrementCounters(decorator, FaultID.LimitedStdLibNoSendableDecorator, autofix); } - } - private handleTypescriptDecorators(decorator: ts.Decorator): void { - if (!this.options.arkts2) { - return; - } - if (!ts.isClassDeclaration(decorator.parent)) { - return; + if (decoratorName === CONCURRENT_DECORATOR) { + this.incrementCounters(decorator, FaultID.LimitedStdLibNoDoncurrentDecorator, autofix); } + } - const decoratorExpression = decorator.expression; - const symbol = this.tsUtils.trueSymbolAtLocation(decoratorExpression); - if (!symbol) { - return; - } + private checkAsonSymbol(symbol: ts.Symbol, node: ts.Node): void { + const cb = (): void => { + let autofix: Autofix[] | undefined; + const parent = node.parent; + autofix = this.autofixer?.replaceNode(parent ? parent : node, JSON_TEXT); - const decl = TsUtils.getDeclaration(symbol); - if (!decl) { - return; - } + if (ts.isImportSpecifier(parent) && ts.isIdentifier(node)) { + autofix = this.autofixer?.removeImport(node, parent); + } - const sourceFile = decl.getSourceFile(); - if (sourceFile.fileName.endsWith(EXTNAME_TS)) { - this.incrementCounters(decorator, FaultID.InteropNoDecorators); - } + this.incrementCounters(node, FaultID.LimitedStdLibNoASON, autofix); + }; + this.checkSymbolAndExecute(symbol, ASON_TEXT, ASON_MODULES, cb); } - private checkWorkerImport(node: ts.ImportDeclaration): void { - if (!this.options.arkts2) { - return; - } - const moduleSpecifier = (node.moduleSpecifier as ts.StringLiteral).text; - if (!WORKER_MODULES.includes(moduleSpecifier)) { - return; - } + private checkCollectionsSymbol(symbol: ts.Symbol, node: ts.Node): void { + const cb = (): void => { + const parent = node.parent; + if (!parent) { + return; + } + if (ts.isPropertyAccessExpression(parent)) { + const autofix = this.autofixer?.replaceNode(parent, parent.name.text); + this.incrementCounters(node, FaultID.NoNeedStdLibSendableContainer, autofix); + } - const namedBindings = node.importClause?.namedBindings; - if (!namedBindings || namedBindings.kind !== ts.SyntaxKind.NamedImports) { - return; - } - const elements = namedBindings.elements; - for (const el of elements) { - const importedName = el.propertyName?.text ?? el.name.text; - if (importedName === WORKER_TEXT) { - this.incrementCounters(node, FaultID.LimitedStdLibApi); + if (ts.isQualifiedName(parent)) { + const autofix = this.autofixer?.replaceNode(parent, parent.right.text); + this.incrementCounters(node, FaultID.NoNeedStdLibSendableContainer, autofix); + } + + if (ts.isImportSpecifier(parent) && ts.isIdentifier(node)) { + const autofix = this.autofixer?.removeImport(node, parent); + this.incrementCounters(node, FaultID.NoNeedStdLibSendableContainer, autofix); + } + }; + + this.checkSymbolAndExecute(symbol, COLLECTIONS_TEXT, COLLECTIONS_MODULES, cb); + } + + private checkWorkerSymbol(symbol: ts.Symbol, node: ts.Node): void { + const cb = (): void => { + this.incrementCounters(node, FaultID.NoNeedStdlibWorker); + }; + + this.checkSymbolAndExecute(symbol, WORKER_TEXT, WORKER_MODULES, cb); + } + + private checkSymbolAndExecute(symbol: ts.Symbol, symbolName: string, modules: string[], cb: () => void): void { + void this; + if (symbol.name === symbolName) { + const decl = TsUtils.getDeclaration(symbol); + + if (!decl) { return; } + + const sourceFile = decl.getSourceFile(); + const fileName = path.basename(sourceFile.fileName); + + if ( + modules.some((moduleName) => { + return fileName.startsWith(moduleName); + }) + ) { + cb(); + } } } @@ -5648,34 +6838,50 @@ export class TypeScriptLinter { const decl = node.parent; const declName = decl.name?.getText(); if (ts.isFunctionDeclaration(decl)) { - const functionCalls = TypeScriptLinter.findDeclarationCalls(this.sourceFile as ts.SourceFile, declName as string); + const functionCalls = TypeScriptLinter.findDeclarationCalls(this.sourceFile, declName as string); const autofix = this.autofixer?.fixStylesDecoratorGlobal(decl, functionCalls, this.interfacesNeedToImport); this.incrementCounters(decl, FaultID.StylesDecoratorNotSupported, autofix); } if (ts.isMethodDeclaration(decl)) { - const methodCalls = TypeScriptLinter.findDeclarationCalls(this.sourceFile as ts.SourceFile, declName as string); + const methodCalls = TypeScriptLinter.findDeclarationCalls(this.sourceFile, declName as string); const autofix = this.autofixer?.fixStylesDecoratorStruct(decl, methodCalls, this.interfacesNeedToImport); this.incrementCounters(decl, FaultID.StylesDecoratorNotSupported, autofix); } } - private handleStateStyles(node: ts.CallExpression): void { + private handleStateStyles(node: ts.CallExpression | ts.PropertyAccessExpression): void { if (!this.options.arkts2) { return; } - if (node.expression.getText() !== STATE_STYLES) { - return; + let args: ts.Expression[] = []; + let startNode: ts.Node | undefined; + if (ts.isCallExpression(node)) { + if (node.expression.getText() !== STATE_STYLES) { + return; + } + startNode = node.expression; + args = Array.from(node.arguments); } - const args = node.arguments; - if (args.length === 0) { + if (ts.isPropertyAccessExpression(node)) { + if (node.name.getText() !== STATE_STYLES) { + return; + } + if (!ts.isCallExpression(node.parent)) { + return; + } + startNode = node.name; + args = Array.from(node.parent.arguments); + } + + if (args.length === 0 || !startNode) { return; } const object = args[0]; - if (!ts.isObjectLiteralExpression(object)) { + if (!object || !ts.isObjectLiteralExpression(object)) { return; } @@ -5683,28 +6889,81 @@ export class TypeScriptLinter { if (properties.length === 0) { return; } - const property = properties[0] as ts.PropertyAssignment; - if (!ts.isObjectLiteralExpression(property.initializer)) { + + if (!TypeScriptLinter.hasAnonBlock(properties)) { + return; + } + + const autofix = this.autofixer?.fixStateStyles(object, startNode, this.interfacesNeedToImport); + this.incrementCounters(object, FaultID.StylesDecoratorNotSupported, autofix); + } + + private static hasAnonBlock(properties: ts.NodeArray): boolean { + let anonBlockCount = 0; + + properties.forEach((property) => { + if (ts.isPropertyAssignment(property) && ts.isObjectLiteralExpression(property.initializer)) { + anonBlockCount++; + } + }); + + return anonBlockCount !== 0; + } + + private handleStringLiteral(node: ts.StringLiteral): void { + if (!this.options.arkts2) { + return; + } + + this.checkForConcurrentExpressions(node); + } + + private checkForConcurrentExpressions(stringLiteral: ts.StringLiteral): void { + if (!stringLiteral.parent) { + return; + } + + if (!ts.isExpressionStatement(stringLiteral.parent)) { return; } - const autofix = this.autofixer?.fixStateStyles(object, this.interfacesNeedToImport); - this.incrementCounters(node, FaultID.StylesDecoratorNotSupported, autofix); + const text = stringLiteral.text; + const autofix = this.autofixer?.removeNode(stringLiteral); + + if (text === USE_CONCURRENT) { + this.incrementCounters(stringLiteral, FaultID.UseConcurrentDeprecated, autofix); + } + + if (text === USE_SHARED) { + this.incrementCounters(stringLiteral, FaultID.UseSharedDeprecated, autofix); + } } - private static findDeclarationCalls(sourceFile: ts.SourceFile, declName: string): ts.CallExpression[] { - const functionCalls: ts.CallExpression[] = []; + private static findDeclarationCalls(sourceFile: ts.SourceFile, declName: string): ts.Identifier[] { + const functionCalls: ts.Identifier[] = []; function traverse(node: ts.Node): void { - if (ts.isCallExpression(node)) { - const callName = node.expression.getText(); - if (callName === declName) { - functionCalls.push(node); - } + const identifier = getIdentifierFromNode(node); + if (identifier && identifier.getText() === declName) { + functionCalls.push(identifier); } + ts.forEachChild(node, traverse); } + function getIdentifierFromNode(node: ts.Node): ts.Identifier | undefined { + if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) { + return node.expression; + } + if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.name)) { + if (node.expression.getText() === THIS_IDENTIFIER) { + return undefined; + } + return node.name; + } + return undefined; + } + traverse(sourceFile); return functionCalls; } @@ -5865,7 +7124,7 @@ export class TypeScriptLinter { return; } - if (TypeScriptLinter.isDeclaredInArkTs2(callSignature)) { + if (!TypeScriptLinter.isDeclaredInArkTs2(callSignature)) { return; } @@ -5887,14 +7146,6 @@ export class TypeScriptLinter { } } - private checkInteropFunctionCall(node: ts.CallExpression): void { - if (!this.options.arkts2) { - return; - } - - this.incrementCounters(node, FaultID.InteropTSFunctionInvoke); - } - private hasObjectParameter(callSignature: ts.Signature, tsCallExpr: ts.CallExpression): boolean { for (const [index, param] of callSignature.parameters.entries()) { const paramType = this.tsTypeChecker.getTypeOfSymbolAtLocation(param, tsCallExpr); @@ -5978,108 +7229,330 @@ export class TypeScriptLinter { this.incrementCounters(node, FaultID.BinaryOperations); } } + this.handlePropertyDescriptorInScenarios(node); } - private handleQuotedHyphenPropsDeprecated(typeRef: ts.TypeReferenceNode): void { - if (!this.options.arkts2 || !ts.isQualifiedName(typeRef.typeName)) { - return; - } - const qualNode = typeRef.typeName; - const parent = typeRef.parent; - const sdkInfos = this.interfaceMap.get(qualNode.left.getText()); - if (!sdkInfos || sdkInfos.size === 0) { + private handleQuotedHyphenPropsDeprecated(node: ts.PropertyAccessExpression | ts.PropertyAssignment): void { + if (!this.options.arkts2 || !node) { return; } - - for (const sdkInfo of sdkInfos) { - this.processQuotedHyphenPropsDeprecated(parent, sdkInfo.api_name); - } - } - - private processQuotedHyphenPropsDeprecated(node: ts.Node, apiName: string): void { - if (ts.isVariableDeclaration(node)) { - this.handleQuotedHyphenPropsDeprecatedOnVarDecl(node, apiName); - } else if (ts.isFunctionDeclaration(node)) { - this.handleQuotedHyphenPropsDeprecatedOnFunDecl(node, apiName); - } + const literalAsPropertyNameInfos = Array.from(TypeScriptLinter.literalAsPropertyNameTypeSet); + literalAsPropertyNameInfos.some((literalAsPropertyNameInfo) => { + this.localApiListItem = literalAsPropertyNameInfo; + const api_name = literalAsPropertyNameInfo.api_info.api_name; + if (api_name !== (ts.isPropertyAccessExpression(node) ? node.name.text : node.name.getText())) { + return false; + } + const parentSym = this.getFinalSymOnQuotedHyphenPropsDeprecated( + ts.isPropertyAccessExpression(node) ? node.expression : node + ); + if (parentSym && this.shouldWarn(parentSym)) { + this.incrementCounters(node, FaultID.QuotedHyphenPropsDeprecated); + return true; + } + return false; + }); } - private handleQuotedHyphenPropsDeprecatedOnVarDecl(node: ts.VariableDeclaration, apiName: string): void { - const initializer = node.initializer; - if (!(initializer && ts.isObjectLiteralExpression(initializer))) { - return; + private shouldWarn(symbol: ts.Symbol): boolean { + const parentApiName = this.getLocalApiListItemByKey(SdkNameInfo.ParentApiName); + return symbol && this.isHeritageClauseisThirdPartyBySymbol(symbol) || symbol.name === parentApiName; + } + + private getFinalSymOnQuotedHyphenPropsDeprecated(node: ts.Node): ts.Symbol | undefined { + let currentNode = node; + while (currentNode) { + const symbol = this.checkNodeTypeOnQuotedHyphenPropsDeprecated(currentNode); + if (symbol) { + return symbol; + } + currentNode = currentNode.parent; } - initializer.properties.forEach((property) => { - if (!ts.isPropertyAssignment(property)) { - return; + return undefined; + } + + private checkNodeTypeOnQuotedHyphenPropsDeprecated(node: ts.Node): ts.Symbol | undefined { + if (ts.isVariableDeclaration(node)) { + return this.getTypeOfVariable(node); + } + + if (ts.isPropertySignature(node)) { + return this.tsTypeChecker.getTypeAtLocation(node.type!).getSymbol(); + } + + const nodesWithResolvableType = [ + ts.isFunctionDeclaration(node) && node.type, + ts.isMethodDeclaration(node) && node.type, + ts.isTypeReferenceNode(node) && node, + ts.isParameter(node) && node.type + ].filter(Boolean); + + for (const typeNode of nodesWithResolvableType) { + return typeNode ? this.resolveTypeNodeSymbol(typeNode) : undefined; + } + + if (ts.isIdentifier(node)) { + const symbol = this.tsTypeChecker.getSymbolAtLocation(node); + const declaration = symbol?.getDeclarations()?.[0]; + if (declaration) { + return this.getFinalSymOnQuotedHyphenPropsDeprecated(declaration); } - const propertyName = property.name.getText(); - if (propertyName === apiName) { - this.incrementCounters(property.name, FaultID.QuotedHyphenPropsDeprecated); + } + + return undefined; + } + + private getTypeOfVariable(variable: ts.VariableDeclaration): ts.Symbol | undefined { + if (variable.type) { + return ts.isArrayTypeNode(variable.type) ? + this.resolveTypeNodeSymbol(variable.type.elementType) : + this.resolveTypeNodeSymbol(variable.type); + } + return variable.initializer ? this.tsTypeChecker.getTypeAtLocation(variable.initializer).getSymbol() : undefined; + } + + private resolveTypeNodeSymbol(typeNode: ts.TypeNode): ts.Symbol | undefined { + if (!ts.isTypeReferenceNode(typeNode)) { + return undefined; + } + const symbol = this.tsTypeChecker.getTypeAtLocation(typeNode).getSymbol(); + if (!symbol) { + return this.resolveTypeNoSymbol(typeNode); + } + const declarations = symbol.getDeclarations(); + if (declarations && declarations.length > 0) { + const declaration = declarations[0]; + if (ts.isTypeAliasDeclaration(declaration)) { + return this.resolveTypeNodeSymbol(declaration.type); + } else if (ts.isInterfaceDeclaration(declaration)) { + const heritageSymbol = this.processQuotedHyphenPropsDeprecatedOnInterfaceDeclaration(declaration); + return heritageSymbol; } - }); + } + return this.tsTypeChecker.getTypeAtLocation(typeNode).getSymbol(); } - private handleQuotedHyphenPropsDeprecatedOnFunDecl(node: ts.FunctionDeclaration, apiName: string): void { - const body = node.body; - if (!body || !ts.isBlock(body)) { - return; + private resolveTypeNoSymbol(typeNode: ts.TypeReferenceNode): ts.Symbol | undefined { + if (!typeNode.typeName) { + return undefined; + } + if (ts.isQualifiedName(typeNode.typeName)) { + return this.tsTypeChecker.getSymbolAtLocation(typeNode.typeName.right); + } + const sym = this.tsUtils.trueSymbolAtLocation(typeNode.typeName); + if (sym) { + const globalDeclaration = sym.getDeclarations()?.[0]; + if (globalDeclaration && ts.isTypeAliasDeclaration(globalDeclaration)) { + return this.resolveTypeNodeSymbol(globalDeclaration.type); + } } - body.statements.forEach(this.processStatement.bind(this, apiName)); + return this.tsTypeChecker.getTypeAtLocation(typeNode).getSymbol(); } - private processStatement(apiName: string, statement: ts.Statement): void { - if (!ts.isReturnStatement(statement)) { - return; + private isHeritageClauseisThirdPartyBySymbol(symbol: ts.Symbol): boolean { + const declarations = symbol.getDeclarations(); + if (declarations && declarations.length > 0) { + const firstDeclaration = declarations[0]; + if (ts.isImportSpecifier(firstDeclaration)) { + const importDecl = firstDeclaration.parent.parent.parent; + const importPath = importDecl.moduleSpecifier.getText(); + const import_path = this.getLocalApiListItemByKey(SdkNameInfo.ImportPath); + if (import_path && JSON.stringify(import_path).includes(importPath)) { + return true; + } + } + } + return false; + } + + private getLocalApiListItemByKey(key: string): string | string[] { + if (!this.localApiListItem) { + return ''; + } + if (SdkNameInfo.ParentApiName === key) { + return this.localApiListItem.api_info.parent_api[0].api_name; + } else if (SdkNameInfo.ImportPath === key) { + return this.localApiListItem.import_path; + } + return ''; + } + + private processQuotedHyphenPropsDeprecatedOnInterfaceDeclaration( + node: ts.InterfaceDeclaration + ): ts.Symbol | undefined { + const heritageSymbol = this.processHeritageClauses(node); + if (heritageSymbol) { + return heritageSymbol; } + return this.processMembers(node); + } + + private processHeritageClauses(node: ts.InterfaceDeclaration): ts.Symbol | undefined { + if (!node.heritageClauses) { + return undefined; + } + for (const heritageClause of node.heritageClauses) { + return this.processHeritageClause(heritageClause); + } + + return undefined; + } + + private processHeritageClause(heritageClause: ts.HeritageClause): ts.Symbol | undefined { + for (const type of heritageClause.types) { + if (!type.expression) { + return undefined; + } + if (ts.isPropertyAccessExpression(type.expression)) { + return this.processPropertyAccessExpression(type.expression); + } + } + return undefined; + } - const returnValue = statement.expression; - if (!returnValue || !ts.isObjectLiteralExpression(returnValue)) { + private processPropertyAccessExpression(expression: ts.PropertyAccessExpression): ts.Symbol | undefined { + const heritageSymbol = this.tsTypeChecker.getSymbolAtLocation(expression.expression); + if (heritageSymbol && expression.name.text === this.getLocalApiListItemByKey(SdkNameInfo.ParentApiName)) { + return heritageSymbol; + } + return undefined; + } + + private processMembers(node: ts.InterfaceDeclaration): ts.Symbol | undefined { + if (!node.members) { + return undefined; + } + for (const member of node.members) { + if (ts.isPropertySignature(member) && member.type) { + return this.resolveTypeNodeSymbol(member.type); + } + } + return undefined; + } + + private processApiNodeSdkDuplicateDeclName(apiName: string, errorNode: ts.Node): void { + const setApiListItem = TypeScriptLinter.globalApiInfo.get(SdkProblem.DeclWithDuplicateName); + if (!setApiListItem) { + return; + } + const apiNamesArr = [...setApiListItem]; + const hasSameApiName = apiNamesArr.some((apilistItem) => { + return apilistItem.api_info.api_name === errorNode.getText(); + }); + if (!hasSameApiName) { return; } - returnValue.properties.forEach(this.processProperty.bind(this, apiName)); + if (ts.isTypeReferenceNode(errorNode)) { + errorNode = errorNode.typeName; + } + + const matchedApi = apiNamesArr.some((sdkInfo) => { + const isSameName = sdkInfo.api_info.api_name === apiName; + const isGlobal = sdkInfo.is_global; + return isSameName && isGlobal; + }); + + if (matchedApi) { + this.incrementCounters(errorNode, FaultID.DuplicateDeclNameFromSdk); + } } - private processProperty(apiName: string, property: ts.ObjectLiteralElementLike): void { - if (!ts.isPropertyAssignment(property)) { + private handleSdkDuplicateDeclName( + node: + | ts.TypeReferenceNode + | ts.NewExpression + | ts.VariableDeclaration + | ts.PropertyDeclaration + | ts.ParameterDeclaration + | ts.CallExpression + | ts.BinaryExpression + | ts.ExpressionWithTypeArguments + | ts.Identifier + ): void { + if (!this.options.arkts2) { return; } + switch (node.kind) { + case ts.SyntaxKind.TypeReference: + this.checkTypeReferenceForSdkDuplicateDeclName(node); + break; + case ts.SyntaxKind.NewExpression: + this.checkNewExpressionForSdkDuplicateDeclName(node); + break; + case ts.SyntaxKind.Identifier: + this.checkHeritageClauseForSdkDuplicateDeclName(node); + break; + case ts.SyntaxKind.VariableDeclaration: + case ts.SyntaxKind.PropertyDeclaration: + case ts.SyntaxKind.Parameter: + this.checkDeclarationForSdkDuplicateDeclName(node); + break; + case ts.SyntaxKind.CallExpression: + this.checkCallExpressionForSdkDuplicateDeclName(node); + break; + case ts.SyntaxKind.BinaryExpression: + this.checkBinaryExpressionForSdkDuplicateDeclName(node); + break; + default: + } + } + + private checkTypeReferenceForSdkDuplicateDeclName(node: ts.TypeReferenceNode): void { + const typeName = node.typeName; + if (ts.isIdentifier(typeName)) { + this.processApiNodeSdkDuplicateDeclName(typeName.text, node); + } + } + + private checkNewExpressionForSdkDuplicateDeclName(node: ts.NewExpression): void { + const expression = node.expression; + if (ts.isIdentifier(expression)) { + this.processApiNodeSdkDuplicateDeclName(expression.text, expression); + } + } + + private checkHeritageClauseForSdkDuplicateDeclName(node: ts.Identifier): void { + if (ts.isIdentifier(node)) { + this.processApiNodeSdkDuplicateDeclName(node.text, node); + } + } + + private checkDeclarationForSdkDuplicateDeclName( + node: ts.VariableDeclaration | ts.PropertyDeclaration | ts.ParameterDeclaration + ): void { + const expression = node.initializer; + if (expression && ts.isIdentifier(expression)) { + this.processApiNodeSdkDuplicateDeclName(expression.text, expression); + } + } + + private checkCallExpressionForSdkDuplicateDeclName(node: ts.CallExpression): void { + if (ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression)) { + const expression = node.expression.expression; + this.processApiNodeSdkDuplicateDeclName(expression.text, expression); + } + } - const isMatch = property.name.getText() === apiName; - if (isMatch) { - this.incrementCounters(property.name, FaultID.QuotedHyphenPropsDeprecated); + private checkBinaryExpressionForSdkDuplicateDeclName(node: ts.BinaryExpression): void { + const expression = node.right; + if (ts.isIdentifier(expression)) { + this.processApiNodeSdkDuplicateDeclName(expression.text, expression); } } - private handleApipathChanged(node: ts.PropertyDeclaration): void { - if (!this.options.arkts2 || !ts.isPropertyDeclaration(node)) { + private checkEWTArgumentsForSdkDuplicateDeclName(node: ts.HeritageClause): void { + if (!this.options.arkts2) { return; } - const processApiNode = (apiName: string, errorNode: ts.Node): void => { - const sdkInfos = TypeScriptLinter.pathMap.get(`'${ARKTS_WHITE_API_PATH_TEXTSTYLE}'`); - if (!sdkInfos) { - return; - } - const matchedApi = [...sdkInfos].find((sdkInfo) => { - return sdkInfo.api_name === apiName; + if (node.token === ts.SyntaxKind.ExtendsKeyword || node.token === ts.SyntaxKind.ImplementsKeyword) { + node.types.forEach((type) => { + const expr = type.expression; + if (ts.isIdentifier(expr)) { + this.processApiNodeSdkDuplicateDeclName(expr.text, expr); + } }); - if (matchedApi) { - this.incrementCounters(errorNode, FaultID.ApiPathChanged); - } - }; - if (node.type && ts.isTypeReferenceNode(node.type)) { - const typeName = node.type.typeName; - if (ts.isIdentifier(typeName)) { - processApiNode(typeName.text, node.type); - } - } - if (node.initializer && ts.isNewExpression(node.initializer)) { - const expression = node.initializer.expression; - if (ts.isIdentifier(expression)) { - processApiNode(expression.text, expression); - } } } @@ -6156,24 +7629,95 @@ export class TypeScriptLinter { if (!this.options.arkts2 || !ts.isPropertyAccessExpression(decl)) { return; } - if (ts.isPropertyAccessExpression(decl.expression)) { - const importApiName = ts.isIdentifier(decl.expression.expression) && decl.expression.expression.text || ''; - const sdkInfos = importApiName && this.interfaceMap.get(importApiName); - if (!sdkInfos) { - return; - } - const apiName = ts.isIdentifier(decl.name) && decl.name.text || ''; - const matchedApi = [...sdkInfos].find((sdkInfo) => { - return sdkInfo.api_name === apiName; - }); - if (matchedApi) { + + if (this.handleSelfPropertyAccess(decl)) { + return; + } + + if (ts.isPropertyAccessExpression(decl)) { + const deprecatedProperties = [ + 'position', + 'subtype', + 'movingPhotoEffectMode', + 'dynamicRangeType', + 'thumbnailVisible' + ]; + + const propertyName = ts.isIdentifier(decl.name) ? decl.name.text : ''; + if (deprecatedProperties.includes(propertyName)) { this.incrementCounters(decl.name, FaultID.SdkTypeQuery); + return; } } + + this.handleImportApiPropertyAccess(decl); + } + + private handleSelfPropertyAccess(decl: ts.PropertyAccessExpression): boolean { + if (!ts.isPropertyAccessExpression(decl.expression)) { + return false; + } + + const propertyName = ts.isIdentifier(decl.expression.name) && decl.expression.name.text || ''; + if (propertyName !== 'self') { + return false; + } + + this.incrementCounters(decl.name, FaultID.SdkTypeQuery); + return true; + } + + private handleImportApiPropertyAccess(decl: ts.PropertyAccessExpression): void { + if (!ts.isPropertyAccessExpression(decl.expression)) { + return; + } + + const importApiName = ts.isIdentifier(decl.expression.expression) && decl.expression.expression.text || ''; + const sdkInfos = importApiName && this.interfaceMap.get(importApiName); + if (!sdkInfos) { + return; + } + + const apiName = ts.isIdentifier(decl.name) && decl.name.text || ''; + const matchedApi = [...sdkInfos].find((sdkInfo) => { + return sdkInfo.api_name === apiName; + }); + + if (matchedApi) { + this.incrementCounters(decl.name, FaultID.SdkTypeQuery); + } + } + + private handleGetOwnPropertyNames(decl: ts.PropertyAccessExpression): void { + if (this.checkPropertyAccessExpression(decl, GET_OWN_PROPERTY_NAMES_TEXT, TypeScriptLinter.missingAttributeSet)) { + const autofix = this.autofixer?.fixMissingAttribute(decl); + this.incrementCounters(decl, FaultID.BuiltinGetOwnPropertyNames, autofix); + } + } + + private handleSymbolIterator(decl: ts.PropertyAccessExpression): void { + if (this.checkPropertyAccessExpression(decl, SYMBOL_ITERATOR, TypeScriptLinter.symbotIterSet)) { + this.incrementCounters(decl, FaultID.BuiltinSymbolIterator); + } + } + + private checkPropertyAccessExpression(decl: ts.PropertyAccessExpression, name: string, set: Set): boolean { + if (set.size === 0 || decl.getText() !== name) { + return false; + } + + const symbol = this.tsUtils.trueSymbolAtLocation(decl); + const sourceFile = symbol?.declarations?.[0]?.getSourceFile(); + if (!sourceFile) { + return false; + } + + const fileName = path.basename(sourceFile.fileName); + return set.has(fileName); } private fixJsImportCallExpression(callExpr: ts.CallExpression): void { - if (!this.options.arkts2) { + if (!this.options.arkts2 || !this.useStatic) { return; } @@ -6186,7 +7730,16 @@ export class TypeScriptLinter { return; } - this.incrementCounters(callExpr, FaultID.InteropJsObjectUsage); + // check if any argument is a `new` expression + const hasNewExpressionArg = callExpr.arguments.some((arg) => { + return ts.isNewExpression(arg); + }); + + const faultId = hasNewExpressionArg ? + FaultID.InteropJsObjectExpandStaticInstance : + FaultID.InteropJsObjectCallStaticFunc; + + this.incrementCounters(callExpr, faultId); } private fixJsImportExtendsClass( @@ -6205,11 +7758,11 @@ export class TypeScriptLinter { if (!className) { return; } - this.incrementCounters(node, FaultID.InteropJsObjectUsage); + this.incrementCounters(node, FaultID.InteropJsObjectInheritance); } private fixJsImportPropertyAccessExpression(node: ts.Node): void { - if (!this.options.arkts2) { + if (!this.options.arkts2 || !this.useStatic) { return; } @@ -6223,7 +7776,12 @@ export class TypeScriptLinter { const autofix = this.autofixer?.createReplacementForJsImportPropertyAccessExpression( node as ts.PropertyAccessExpression ); - this.incrementCounters(node, FaultID.InteropJsObjectUsage, autofix); + + this.incrementCounters( + node, + TsUtils.isInsideIfCondition(node) ? FaultID.InteropJsObjectConditionJudgment : FaultID.InteropJsObjectUsage, + autofix + ); return; } @@ -6238,7 +7796,7 @@ export class TypeScriptLinter { } private fixJsImportElementAccessExpression(elementAccessExpr: ts.ElementAccessExpression): void { - if (!this.options.arkts2) { + if (!this.options.arkts2 || !this.useStatic) { return; } @@ -6265,7 +7823,67 @@ export class TypeScriptLinter { elementAccessExpr.expression as ts.Identifier ); - this.incrementCounters(elementAccessExpr, FaultID.InteropJsObjectUsage, autofix); + this.incrementCounters(elementAccessExpr, FaultID.InteropJsObjectTraverseJsInstance, autofix); + } + + private handleTaskPoolDeprecatedUsages(node: ts.CallExpression): void { + if (!this.options.arkts2 || !this.useStatic) { + return; + } + + if (!ts.isPropertyAccessExpression(node.expression)) { + return; + } + + const propertyAccess = node.expression; + const objectExpr = propertyAccess.expression; + + // Step 1: Must be either setCloneList or setTransferList + if (!TypeScriptLinter.isDeprecatedTaskPoolMethodCall(propertyAccess)) { + return; + } + + if (!ts.isIdentifier(objectExpr)) { + return; + } + + // Step 2: Resolve declaration of task + const variableDecl = this.tsUtils.findVariableDeclaration(objectExpr); + if (!variableDecl?.initializer || !ts.isNewExpression(variableDecl.initializer)) { + return; + } + + // Step 3: Check new taskpool.Task() + const taskpoolExpr = variableDecl.initializer.expression; + if (!TypeScriptLinter.isTaskPoolTaskCreation(taskpoolExpr)) { + return; + } + + const faultId = + propertyAccess.name.text === DEPRECATED_TASKPOOL_METHOD_SETCLONELIST ? + FaultID.SetCloneListDeprecated : + FaultID.SetTransferListDeprecated; + this.incrementCounters(node.parent, faultId); + } + + private static isDeprecatedTaskPoolMethodCall(propertyAccess: ts.PropertyAccessExpression): boolean { + if (!ts.isIdentifier(propertyAccess.expression)) { + return false; + } + const methodName = propertyAccess.name.text; + return ( + methodName === DEPRECATED_TASKPOOL_METHOD_SETCLONELIST || + methodName === DEPRECATED_TASKPOOL_METHOD_SETTRANSFERLIST + ); + } + + private static isTaskPoolTaskCreation(taskpoolExpr: ts.Expression): boolean { + return ( + ts.isPropertyAccessExpression(taskpoolExpr) && + ts.isIdentifier(taskpoolExpr.expression) && + taskpoolExpr.expression.text === STDLIB_TASKPOOL_OBJECT_NAME && + taskpoolExpr.name.text === STDLIB_TASK_CLASS_NAME + ); } private checkStdLibConcurrencyImport(importDeclaration: ts.ImportDeclaration): void { @@ -6284,32 +7902,156 @@ export class TypeScriptLinter { return; } + const defaultImport = importClause.name; const namedBindings = importClause.namedBindings; - const defaultImportName = importClause.name?.getText(); - if (defaultImportName && expectedImports.includes(defaultImportName)) { - this.incrementCounters(importDeclaration, FaultID.LimitedStdLibNoImportConcurrency); + const namedImports = namedBindings && ts.isNamedImports(namedBindings) ? namedBindings.elements : []; + + const defaultIsForbidden = defaultImport && expectedImports.includes(defaultImport.getText()); + const forbiddenNamed = namedImports.filter((spec) => { + const name = spec.propertyName ? spec.propertyName.getText() : spec.name.getText(); + return expectedImports.includes(name); + }); + + if ( + TypeScriptLinter.shouldRemoveWholeImport( + defaultIsForbidden, + forbiddenNamed.length, + namedImports.length, + defaultImport + ) + ) { + const autofix = this.autofixer?.removeNode(importDeclaration); + this.incrementCounters(importDeclaration, FaultID.LimitedStdLibNoImportConcurrency, autofix); + return; } - if (namedBindings && ts.isNamedImports(namedBindings)) { - for (const element of namedBindings.elements) { - const name = element.name.getText(); - if (expectedImports.includes(name)) { - this.incrementCounters(importDeclaration, FaultID.LimitedStdLibNoImportConcurrency); - } - } + if (defaultIsForbidden) { + const autofix = this.autofixer?.removeDefaultImport(importDeclaration, defaultImport); + this.incrementCounters(defaultImport, FaultID.LimitedStdLibNoImportConcurrency, autofix); + } + + for (const spec of forbiddenNamed) { + const autofix = this.autofixer?.removeImportSpecifier(spec, importDeclaration); + this.incrementCounters(spec, FaultID.LimitedStdLibNoImportConcurrency, autofix); } } - private handleInterOpImportJs(importDecl: ts.ImportDeclaration): void { - if (!this.options.arkts2 || !importDecl || !this.useStatic) { + private static shouldRemoveWholeImport( + defaultIsForbidden: boolean | undefined, + forbiddenNamedCount: number, + namedImportsCount: number, + defaultImport: ts.Identifier | undefined + ): boolean { + return ( + defaultIsForbidden && forbiddenNamedCount === namedImportsCount || + defaultIsForbidden && namedImportsCount === 0 || + !defaultImport && forbiddenNamedCount === namedImportsCount && namedImportsCount > 0 + ); + } + + /** + * Checks for missing super() call in child classes that extend a parent class + * with parameterized constructors. If parent class only has parameterized constructors + * and the child class does not call super() in its constructor, report a fault. + * + * This ensures safe and correct subclassing behavior. + * + * @param node The HeritageClause node (extends clause) to analyze. + */ + private handleMissingSuperCallInExtendedClass(node: ts.HeritageClause): void { + if (!this.options.arkts2 || !this.useStatic) { return; } - const importClause = importDecl.importClause; - if (!importClause) { + + // We are only interested in 'extends' clauses + if (node.token !== ts.SyntaxKind.ExtendsKeyword) { return; } - const namedBindings = importClause.namedBindings; + + // Get the parent class declaration (what the child class extends) + const parentClass = this.getParentClassDeclaration(node); + if (!parentClass) { + return; + } + + // If parent class has a parameterless constructor (or no constructor at all), child is fine + if (TypeScriptLinter.parentHasParameterlessConstructor(parentClass)) { + return; + } + + // The child class node (the one extending) + const childClass = node.parent; + if (!ts.isClassDeclaration(childClass)) { + return; + } + + // Look for child class constructor + const childConstructor = childClass.members.find(ts.isConstructorDeclaration); + + /* + * If child has no constructor → error (super() cannot be called) + * If child constructor exists but does not contain super() → error + */ + if (!childConstructor?.body || !TypeScriptLinter.childHasSuperCall(childConstructor)) { + this.incrementCounters(node, FaultID.MissingSuperCall); + } + } + + /** + * Retrieves the parent class declaration node from an extends heritage clause. + */ + private getParentClassDeclaration(node: ts.HeritageClause): ts.ClassDeclaration | undefined { + const parentExpr = node.types[0]?.expression; + if (!parentExpr) { + return undefined; + } + const parentSymbol = this.tsUtils.trueSymbolAtLocation(parentExpr); + return parentSymbol?.declarations?.find(ts.isClassDeclaration); + } + + /** + * Determines if a parent class has a parameterless constructor. + * If it has no constructor at all, that counts as parameterless. + */ + private static parentHasParameterlessConstructor(parentClass: ts.ClassDeclaration): boolean { + const constructors = parentClass.members.filter(ts.isConstructorDeclaration); + return ( + constructors.length === 0 || + constructors.some((ctor) => { + return ctor.parameters.length === 0; + }) + ); + } + + private static childHasSuperCall(constructor: ts.ConstructorDeclaration): boolean { + let superCalled = false; + + if (!constructor.body) { + return false; + } + + ts.forEachChild(constructor.body, (stmt) => { + if ( + ts.isExpressionStatement(stmt) && + ts.isCallExpression(stmt.expression) && + stmt.expression.expression.kind === ts.SyntaxKind.SuperKeyword + ) { + superCalled = true; + } + }); + return superCalled; + } + + private handleInterOpImportJs(importDecl: ts.ImportDeclaration): void { + if (!this.options.arkts2 || !importDecl || !this.useStatic) { + return; + } + const importClause = importDecl.importClause; + if (!importClause) { + return; + } + const namedBindings = importClause.namedBindings; let symbol: ts.Symbol | undefined; let defaultSymbol: ts.Symbol | undefined; if (importClause.name) { @@ -6371,22 +8113,42 @@ export class TypeScriptLinter { return false; } - private handleAwaitExpression(node: ts.Node): void { + private handleInteropAwaitImport(callExpr: ts.CallExpression): void { if (!this.options.arkts2 || !this.useStatic) { return; } - const awaitExpr = node as ts.AwaitExpression; - const checkAndReportJsImportAwait = (targetNode: ts.Node): boolean => { - if (ts.isIdentifier(targetNode) && this.tsUtils.isJsImport(targetNode)) { - this.incrementCounters(node, FaultID.NoJsImportAwait); - return true; - } - return false; - }; - const expr = awaitExpr.expression; - checkAndReportJsImportAwait(expr); - if (ts.isCallExpression(expr)) { - checkAndReportJsImportAwait(expr.expression); + + if (callExpr.expression.kind !== ts.SyntaxKind.ImportKeyword) { + return; + } + + if (ts.isAwaitExpression(callExpr.parent) || ts.isPropertyAccessExpression(callExpr.parent)) { + this.checkInteropForDynamicImport(callExpr); + } + } + + private checkInteropForDynamicImport(callExpr: ts.CallExpression): void { + const interopType = TsUtils.resolveModuleAndCheckInterop( + this.options.wholeProjectPath ?? path.resolve(TsUtils.getCurrentModule(callExpr.getSourceFile().fileName)), + callExpr + ); + + if (!interopType) { + return; + } + + switch (interopType) { + case InteropType.JS: + this.incrementCounters(callExpr.parent, FaultID.InteropDynamicImportJs); + break; + case InteropType.TS: + this.incrementCounters(callExpr.parent, FaultID.InteropDynamicImportTs); + break; + case InteropType.LEGACY: + this.incrementCounters(callExpr.parent, FaultID.InteropDynamicImport); + break; + default: + break; } } @@ -6416,4 +8178,581 @@ export class TypeScriptLinter { } } } + + private handleObjectLiteralforUnionTypeInterop(node: ts.VariableDeclaration): void { + if (!this.options.arkts2 || !this.useStatic) { + return; + } + + if (!node.type || !ts.isUnionTypeNode(node.type)) { + return; + } + + if (!node.initializer || node.initializer.kind !== ts.SyntaxKind.ObjectLiteralExpression) { + return; + } + + const typeNodes = node.type.types; + + const isDefected = typeNodes.some((tNode) => { + if (!ts.isTypeReferenceNode(tNode)) { + return false; + } + const type = this.tsTypeChecker.getTypeAtLocation(tNode); + const symbol = type.getSymbol(); + if (!symbol) { + return false; + } + for (const declaration of symbol.declarations ?? []) { + if (!TsUtils.isArkts12File(declaration.getSourceFile())) { + return true; + } + } + return false; + }); + + if (isDefected) { + this.incrementCounters(node, FaultID.InteropObjectLiteralAmbiguity); + } + } + + private handleObjectLiteralAssignmentToClass(node: ts.VariableDeclaration): void { + if (!this.options.arkts2 || !this.useStatic) { + return; + } + if (!node.initializer || node.initializer.kind !== ts.SyntaxKind.ObjectLiteralExpression) { + return; + } + if (!node.type) { + return; + } + + const type = this.tsTypeChecker.getTypeAtLocation(node.type); + const symbol = type.getSymbol(); + if (!symbol) { + return; + } + + const declarations = symbol.declarations ?? []; + + const isClass = declarations.some(ts.isClassDeclaration); + if (!isClass) { + return; + } + + const isFromArkTs2 = declarations.some((decl) => { + return TsUtils.isArkts12File(decl.getSourceFile()); + }); + + if (isFromArkTs2) { + return; + } + + const hasConstructor = declarations.some((decl) => { + return ts.isClassDeclaration(decl) && decl.members.some(ts.isConstructorDeclaration); + }); + + if (hasConstructor) { + this.incrementCounters(node, FaultID.InteropObjectLiteralClass); + } + } + + private isObjectLiteralAssignedToArkts12Type(node: ts.Expression, expectedTypeNode?: ts.TypeNode): boolean { + if (node.kind !== ts.SyntaxKind.ObjectLiteralExpression) { + return false; + } + + let type: ts.Type; + if (expectedTypeNode) { + type = this.tsTypeChecker.getTypeAtLocation(expectedTypeNode); + } else { + type = this.tsTypeChecker.getContextualType(node) ?? this.tsTypeChecker.getTypeAtLocation(node); + } + + if (!type) { + return false; + } + + return TypeScriptLinter.isTypeFromArkts12(type); + } + + private static isTypeFromArkts12(type: ts.Type): boolean { + const symbol = type?.getSymbol(); + if (!symbol) { + return false; + } + + const isFromArkts12 = (symbol.declarations ?? []).some((decl) => { + return TsUtils.isArkts12File(decl.getSourceFile()); + }); + + if (isFromArkts12) { + return true; + } + return false; + } + + private processNestedObjectLiterals(objLiteral: ts.Expression, parentType?: ts.Type): void { + if (!ts.isObjectLiteralExpression(objLiteral)) { + return; + } + + objLiteral.properties.forEach((prop) => { + if (!ts.isPropertyAssignment(prop) || !ts.isObjectLiteralExpression(prop.initializer)) { + return; + } + + if (this.isObjectLiteralAssignedToArkts12Type(prop.initializer)) { + this.incrementCounters(prop.initializer, FaultID.InteropStaticObjectLiterals); + return; + } + + this.checkPropertyTypeFromParent(prop, parentType); + this.processNestedObjectLiterals(prop.initializer); + }); + } + + private checkPropertyTypeFromParent(prop: ts.PropertyAssignment, parentType?: ts.Type): void { + if (!parentType) { + return; + } + if (!ts.isObjectLiteralExpression(prop.initializer)) { + return; + } + + const propName = prop.name.getText(); + const property = parentType.getProperty(propName); + + if (!property?.valueDeclaration) { + return; + } + + const propType = this.tsTypeChecker.getTypeOfSymbolAtLocation(property, property.valueDeclaration); + + if (TypeScriptLinter.isTypeFromArkts12(propType)) { + this.incrementCounters(prop.initializer, FaultID.InteropStaticObjectLiterals); + } + } + + private handleObjectLiteralAssignment(node: ts.VariableDeclaration): void { + if (TsUtils.isArkts12File(node.getSourceFile())) { + return; + } + + if (!node.initializer) { + return; + } + + if ( + ts.isObjectLiteralExpression(node.initializer) && + this.isObjectLiteralAssignedToArkts12Type(node.initializer, node.type) + ) { + this.incrementCounters(node.initializer, FaultID.InteropStaticObjectLiterals); + return; + } + + const parentType = node.type ? + this.tsTypeChecker.getTypeAtLocation(node.type) : + this.tsTypeChecker.getTypeAtLocation(node.initializer); + + this.processNestedObjectLiterals(node.initializer, parentType); + } + + private handleObjectLiteralInFunctionArgs(node: ts.CallExpression): void { + if (TsUtils.isArkts12File(node.getSourceFile())) { + return; + } + const signature = this.tsTypeChecker.getResolvedSignature(node); + if (!signature) { + return; + } + + const params = signature.getParameters(); + + node.arguments.forEach((arg, index) => { + if (!ts.isObjectLiteralExpression(arg)) { + return; + } + + if (index < params.length) { + const param = params[index]; + if (!param.valueDeclaration) { + return; + } + + const paramType = this.tsTypeChecker.getTypeOfSymbolAtLocation(param, param.valueDeclaration); + + if (TypeScriptLinter.isTypeFromArkts12(paramType)) { + this.incrementCounters(arg, FaultID.InteropStaticObjectLiterals); + } + } else if (this.isObjectLiteralAssignedToArkts12Type(arg)) { + this.incrementCounters(arg, FaultID.InteropStaticObjectLiterals); + } + }); + } + + private handleObjectLiteralInReturn(node: ts.ReturnStatement): void { + if (TsUtils.isArkts12File(node.getSourceFile())) { + return; + } + + if (!node.expression || !ts.isObjectLiteralExpression(node.expression)) { + return; + } + + let current: ts.Node = node; + let functionNode: ts.FunctionLikeDeclaration | undefined; + + while (current && !functionNode) { + current = current.parent; + if ( + current && + (ts.isFunctionDeclaration(current) || + ts.isMethodDeclaration(current) || + ts.isFunctionExpression(current) || + ts.isArrowFunction(current)) + ) { + functionNode = current; + } + } + + if (functionNode?.type) { + const returnType = this.tsTypeChecker.getTypeAtLocation(functionNode.type); + if (TypeScriptLinter.isTypeFromArkts12(returnType)) { + this.incrementCounters(node.expression, FaultID.InteropStaticObjectLiterals); + } + } else if (this.isObjectLiteralAssignedToArkts12Type(node.expression)) { + this.incrementCounters(node.expression, FaultID.InteropStaticObjectLiterals); + } + } + + private handleLocalBuilderDecorator(node: ts.Node): void { + if (!this.options.arkts2) { + return; + } + if (!ts.isDecorator(node) || !ts.isIdentifier(node.expression)) { + return; + } + const decoratorName = node.expression.getText(); + if (decoratorName === CustomDecoratorName.LocalBuilder) { + const autofix = this.autofixer?.fixBuilderDecorators(node); + this.incrementCounters(node, FaultID.LocalBuilderDecoratorNotSupported, autofix); + } + } + + private checkEnumGetMemberValue(node: ts.ElementAccessExpression): void { + if (!this.options.arkts2) { + return; + } + + if (!ts.isIdentifier(node.expression) || !ts.isNumericLiteral(node.argumentExpression)) { + return; + } + + const symbol = this.tsUtils.trueSymbolAtLocation(node.expression); + if (!symbol?.declarations) { + return; + } + + for (const decl of symbol.declarations) { + if (ts.isEnumDeclaration(decl)) { + this.incrementCounters(node, FaultID.UnsupportPropNameFromValue); + return; + } + } + } + + private handleMakeObserved(node: ts.PropertyAccessExpression): void { + if (!this.options.arkts2) { + return; + } + + const name = node.name; + if (name.getText() !== MAKE_OBSERVED) { + return; + } + + const expr = node.expression; + const symbol = this.tsTypeChecker.getSymbolAtLocation(expr); + const importSpecifier = TsUtils.getDeclaration(symbol); + if (!importSpecifier || !ts.isImportSpecifier(importSpecifier)) { + return; + } + + const importDecl = ts.findAncestor(importSpecifier, ts.isImportDeclaration); + if (!importDecl) { + return; + } + + const moduleSpecifier = importDecl.moduleSpecifier; + if (!ts.isStringLiteral(moduleSpecifier)) { + return; + } + if (moduleSpecifier.text !== ARKUI_PACKAGE_NAME && moduleSpecifier.text !== ARKUI_STATE_MANAGEMENT) { + return; + } + + this.incrementCounters(node, FaultID.MakeObservedIsNotSupported); + } + + private handlePropertyDeclarationForProp(node: ts.PropertyDeclaration): void { + if (!this.options.arkts2) { + return; + } + + const decorators = ts.getDecorators(node); + if (!decorators || decorators.length === 0) { + return; + } + + let decoratorName: string | undefined; + if (ts.isIdentifier(decorators[0].expression)) { + decoratorName = decorators[0].expression.getText(); + } else if (ts.isCallExpression(decorators[0].expression) && ts.isIdentifier(decorators[0].expression.expression)) { + decoratorName = decorators[0].expression.expression.getText(); + } + + if (!decoratorName || !deepCopyDecoratorName.has(decoratorName)) { + return; + } + + this.incrementCounters(node, FaultID.PropDecoratorsAndInterfacesAreNotSupported); + } + + private handleVariableDeclarationForProp(node: ts.VariableDeclaration): void { + if (!this.options.arkts2) { + return; + } + + const callExpr = node.initializer; + if (!callExpr || !ts.isCallExpression(callExpr)) { + return; + } + + const propertyAccessExpr = callExpr.expression; + if (!ts.isPropertyAccessExpression(propertyAccessExpr)) { + return; + } + + const storage = propertyAccessExpr.expression; + if ( + !ts.isIdentifier(storage) || + !this.isTargetStorageType(storage, [StorageTypeName.LocalStorage, StorageTypeName.AppStorage]) + ) { + return; + } + + const functionName = propertyAccessExpr.name; + if (!deepCopyFunctionName.has(functionName.getText())) { + return; + } + + this.incrementCounters(node, FaultID.PropDecoratorsAndInterfacesAreNotSupported); + } + + private isTargetStorageType(storage: ts.Identifier, targetTypes: string[]): boolean { + const decl = this.tsUtils.getDeclarationNode(storage); + if (!decl) { + if (targetTypes.includes(storage.getText())) { + return true; + } + return false; + } + + if (!ts.isVariableDeclaration(decl)) { + return false; + } + + let storageType: ts.Node | undefined; + if (decl.initializer) { + if (ts.isNewExpression(decl.initializer)) { + storageType = decl.initializer.expression; + } else if (ts.isCallExpression(decl.initializer) && ts.isPropertyAccessExpression(decl.initializer.expression)) { + storageType = decl.initializer.expression.expression; + } + } + + if (!storageType || !ts.isIdentifier(storageType)) { + return false; + } + + return targetTypes.includes(storageType.getText()); + } + + private handleAwaitExpression(node: ts.Node): void { + if (!this.options.arkts2 || !this.useStatic) { + return + } + const awaitExpr = node as ts.AwaitExpression; + const checkAndReportJsImportAwait = (targetNode: ts.Node): boolean => { + if (ts.isIdentifier(targetNode) && this.tsUtils.isJsImport(targetNode)) { + this.incrementCounters(node, FaultID.NoAwaitJsPromise); + return true; + } + return false; + }; + const expr = awaitExpr.expression; + checkAndReportJsImportAwait(expr); + if (ts.isCallExpression(expr)) { + checkAndReportJsImportAwait(expr.expression); + } + } + + private handleNotsLikeSmartType(classDecl: ts.ClassDeclaration): void { + if (!this.options.arkts2) { + return; + } + const className = classDecl.name?.getText(); + classDecl.members.forEach(member => { + if (ts.isMethodDeclaration(member)) { + this.checkMethod(member, className); + } + }) + } + + private checkMethod(methodNode: ts.MethodDeclaration, className: string | undefined): void { + const variableDeclarations = new Map(); + const returnStatements: ts.ReturnStatement[] = []; + if (methodNode.body) { + ts.forEachChild(methodNode.body, (node) => { + this.visitMethodBody(node, variableDeclarations, returnStatements); + }); + } + + const isStaticPropertyAccess=(node: ts.Expression, className: string): boolean => { + return ts.isPropertyAccessExpression(node) && + ts.isIdentifier(node.expression) && + node.expression.text === className; + } + + const isInstancePropertyAccess=(node: ts.Expression): boolean=> { + return ts.isPropertyAccessExpression(node) && + node.expression.kind === ts.SyntaxKind.ThisKeyword; + } + + this.checkReturnStatements(returnStatements, className, isStaticPropertyAccess, isInstancePropertyAccess); + } + + private visitMethodBody(node: ts.Node, variableDeclarations: Map, returnStatements: ts.ReturnStatement[]): void { + if (ts.isVariableStatement(node)) { + node.declarationList.declarations.forEach(decl => { + if (ts.isIdentifier(decl.name)) { + variableDeclarations.set(decl.name.text, decl.type); + } + }); + } + + if (ts.isReturnStatement(node)) { + returnStatements.push(node); + } + + ts.forEachChild(node, (child) => { + this.visitMethodBody(child, variableDeclarations, returnStatements); + }); + } + + private checkReturnStatements(returnStatements: ts.ReturnStatement[], className: string | undefined, + isStaticPropertyAccess: (node: ts.Expression, className: string) => boolean, + isInstancePropertyAccess: (node: ts.Expression) => boolean): void { + returnStatements.forEach(returnStmt => { + if (!returnStmt.expression) { + return; + } + + if (className && isStaticPropertyAccess(returnStmt.expression, className)) { + this.incrementCounters(returnStmt, FaultID.NoTsLikeSmartType); + } + + if (isInstancePropertyAccess(returnStmt.expression)) { + this.incrementCounters(returnStmt, FaultID.NoTsLikeSmartType); + } + }); + } + + private handleNumericBigintCompare(node: ts.BinaryExpression): void { + if (!this.options.arkts2) { + return; + } + switch(node.operatorToken.kind) { + case ts.SyntaxKind.LessThanEqualsToken: + case ts.SyntaxKind.EqualsEqualsToken: + case ts.SyntaxKind.GreaterThanEqualsToken: + case ts.SyntaxKind.ExclamationEqualsToken: + case ts.SyntaxKind.ExclamationEqualsEqualsToken: + case ts.SyntaxKind.EqualsEqualsEqualsToken: + case ts.SyntaxKind.GreaterThanToken: + case ts.SyntaxKind.LessThanToken: + this.reportNumericBigintCompare(node); + break; + default: + } + } + + private reportNumericBigintCompare(node: ts.BinaryExpression): void { + const leftType = this.tsTypeChecker.getTypeAtLocation(node.left); + const rightType = this.tsTypeChecker.getTypeAtLocation(node.right); + + const isLeftNumber = (leftType.flags & ts.TypeFlags.Number) !== 0; + const isLeftBigInt = (leftType.flags & ts.TypeFlags.BigInt) !== 0; + + const isRightNumber = (rightType.flags & ts.TypeFlags.Number) !== 0; + const isRightBigInt = (rightType.flags & ts.TypeFlags.BigInt) !== 0; + + const valid = (isLeftNumber && isRightBigInt) || (isLeftBigInt && isRightNumber); + if (valid) { + this.incrementCounters(node, FaultID.NumericBigintCompare); + } + } + + private handleBigIntLiteral(node: ts.BigIntLiteral): void { + if (!this.options.arkts2) { + return; + } + const literalText = node.getText(); + + if ((/^0[box]/i).test(literalText)) { + this.incrementCounters(node, FaultID.NondecimalBigint); + } + } + + private handleStructDeclarationForLayout(node: ts.StructDeclaration): void { + if (!this.options.arkts2) { + return; + } + + if (!node.name) { + return; + } + + let hasTargetFunc = false; + + const members = node.members; + for (const member of members) { + if (!ts.isMethodDeclaration(member)) { + continue; + } + + if (customLayoutFunctionName.has(member.name.getText())) { + hasTargetFunc = true; + break; + } + } + + if (!hasTargetFunc) { + return; + } + + const decorators = ts.getDecorators(node); + if (decorators) { + for (const decorator of decorators) { + const decoratorName = TsUtils.getDecoratorName(decorator); + if (decoratorName && decoratorName === CustomDecoratorName.Layoutable) { + return; + } + } + } + + const autofix = this.autofixer?.fixCustomLayout(node); + this.incrementCounters(node.name, FaultID.CustomLayoutNeedAddDecorator, autofix); + } } diff --git a/ets2panda/linter/src/lib/TypeScriptLinterConfig.ts b/ets2panda/linter/src/lib/TypeScriptLinterConfig.ts index ade75c42e5..e43ee6219c 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinterConfig.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinterConfig.ts @@ -16,7 +16,7 @@ import * as ts from 'typescript'; import { FaultID } from './Problems'; -export class LinterConfig { +export class TypeScriptLinterConfig { /* * The SyntaxKind enum defines additional elements at the end of the enum @@ -31,7 +31,7 @@ export class LinterConfig { static tsSyntaxKindNames: string[] = []; static { - LinterConfig.initTsSyntaxKindNames(); + TypeScriptLinterConfig.initTsSyntaxKindNames(); } private static initTsSyntaxKindNames(): void { @@ -41,8 +41,8 @@ export class LinterConfig { for (let i = 0; i < values.length; i++) { const val = values[i]; const kindNum = typeof val === 'string' ? parseInt(val) : val; - if (kindNum && !LinterConfig.tsSyntaxKindNames[kindNum]) { - LinterConfig.tsSyntaxKindNames[kindNum] = keys[i]; + if (kindNum && !TypeScriptLinterConfig.tsSyntaxKindNames[kindNum]) { + TypeScriptLinterConfig.tsSyntaxKindNames[kindNum] = keys[i]; } } } diff --git a/ets2panda/linter/src/lib/autofixes/AutofixReportHtmlHelper.ts b/ets2panda/linter/src/lib/autofixes/AutofixReportHtmlHelper.ts new file mode 100644 index 0000000000..4b6908e292 --- /dev/null +++ b/ets2panda/linter/src/lib/autofixes/AutofixReportHtmlHelper.ts @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const AUTOFIX_HTML_TEMPLATE_TEXT = 'this is replace content'; +export const AutofixHtmlTemplate = ` + + + + AutoFixes + + + +
+ + + +`; diff --git a/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts b/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts index 8d4c45bfd1..6a0d3826c6 100644 --- a/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts +++ b/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts @@ -21,6 +21,7 @@ export const cookBookRefToFixTitle: Map = new Map([ [16, 'Combine static block statements into one static block'], [25, 'Replace with field declaration'], [29, 'Replace with dot notation'], + [34, 'Add type annotation'], [37, 'Replace with \'new Regexp()\' stdlib API call'], [38, 'Add interface definition'], [40, 'Replace with interface'], @@ -39,6 +40,8 @@ export const cookBookRefToFixTitle: Map = new Map([ [189, 'Add type annotations to numerical variables'], [193, 'Replace with arrow function'], [206, 'Replace with a special library to call'], + [209, 'Transform "number" to "int"'], + [238, 'Replace with explicit static initializer'], [251, 'Transform "!!" to "$$()"'], [252, 'Transform "$$" to "$$()"'], [253, '"$value" transform to "this.value"'], @@ -49,11 +52,15 @@ export const cookBookRefToFixTitle: Map = new Map([ [259, 'Add UI Interface Import'], [260, '"@Entry" annotaion fixed'], [263, '"@Provide" annotation fixed'], + [275, 'Custom layout need add decorator'], + [300, 'Replace calling method of the TS-like `Function` type'], [330, 'Convert import named objects from JS to ESObject'], [332, 'Using the ESObject interface to access properties'], [334, 'Call typeOf function'], [335, 'Call toNumber function to convert'], [338, 'Replace with library function call'], [339, 'Using \'ESObject\' interface call'], - [341, 'Create JS objects using instantite'] + [341, 'Create JS objects using instantite'], + [358, 'Replace missing attribute'], + [359, '"@LocalBuilder" transform to "@Builder"'] ]); diff --git a/ets2panda/linter/src/lib/autofixes/Autofixer.ts b/ets2panda/linter/src/lib/autofixes/Autofixer.ts index c67f4ca381..5a368e5400 100644 --- a/ets2panda/linter/src/lib/autofixes/Autofixer.ts +++ b/ets2panda/linter/src/lib/autofixes/Autofixer.ts @@ -16,7 +16,6 @@ import * as ts from 'typescript'; import { TsUtils } from '../utils/TsUtils'; import { scopeContainsThis } from '../utils/functions/ContainsThis'; -import { forEachNodeInSubtree } from '../utils/functions/ForEachNodeInSubtree'; import { NameGenerator } from '../utils/functions/NameGenerator'; import { isAssignmentOperator } from '../utils/functions/isAssignmentOperator'; import { SymbolCache } from './SymbolCache'; @@ -55,12 +54,24 @@ import { INSTANTIATE, TO_NUMBER } from '../utils/consts/InteropAPI'; +import { ESLIB_SHAREDARRAYBUFFER } from '../utils/consts/ConcurrentAPI'; const UNDEFINED_NAME = 'undefined'; +const LINE_FEED = '\n'; +const CARRIAGE_RETURN_LINE_FEED = '\r\n'; + +const NEW_LINE_SEARCH_REGEX = /\r\n|\n|\r/; + const GENERATED_OBJECT_LITERAL_INTERFACE_NAME = 'GeneratedObjectLiteralInterface_'; const GENERATED_OBJECT_LITERAL_INTERFACE_TRESHOLD = 1000; +const GENERATED_OBJECT_LITERAL_CLASS_NAME = 'GeneratedObjectLiteralClass_'; +const GENERATED_OBJECT_LITERAL_CLASS_TRESHOLD = 1000; + +const GENERATED_OBJECT_LITERAL_INIT_INTERFACE_NAME = 'GeneratedObjectLiteralInitInterface_'; +const GENERATED_OBJECT_LITERAL_INIT_INTERFACE_TRESHOLD = 1000; + const GENERATED_TYPE_LITERAL_INTERFACE_NAME = 'GeneratedTypeLiteralInterface_'; const GENERATED_TYPE_LITERAL_INTERFACE_TRESHOLD = 1000; @@ -75,24 +86,32 @@ const GENERATED_IMPORT_VARIABLE_TRESHOLD = 1000; const SPECIAL_LIB_NAME = 'specialAutofixLib'; +const OBJECT_LITERAL_CLASS_CONSTRUCTOR_PARAM_NAME = 'init'; + +const METHOD_KEYS = 'keys'; + +interface CreateClassPropertyForObjectLiteralParams { + prop: ts.PropertyAssignment | ts.ShorthandPropertyAssignment; + enclosingStmt: ts.Node; + classFields: ts.PropertyDeclaration[]; + ctorBodyStmts: ts.Statement[]; + ctorInitProps: ts.PropertyAssignment[]; +} + export interface Autofix { replacementText: string; start: number; end: number; + line?: number; + column?: number; + endLine?: number; + endColumn?: number; } export class Autofixer { - private readonly printer: ts.Printer = ts.createPrinter({ - omitTrailingSemicolon: false, - removeComments: false, - newLine: ts.NewLineKind.LineFeed - }); - - private readonly nonCommentPrinter: ts.Printer = ts.createPrinter({ - omitTrailingSemicolon: false, - removeComments: true, - newLine: ts.NewLineKind.LineFeed - }); + private readonly printer: ts.Printer; + + private readonly nonCommentPrinter: ts.Printer; private readonly typeLiteralInterfaceNameGenerator = new NameGenerator( GENERATED_TYPE_LITERAL_INTERFACE_NAME, @@ -114,6 +133,16 @@ export class Autofixer { GENERATED_OBJECT_LITERAL_INTERFACE_TRESHOLD ); + private readonly objectLiteralClassNameGenerator = new NameGenerator( + GENERATED_OBJECT_LITERAL_CLASS_NAME, + GENERATED_OBJECT_LITERAL_CLASS_TRESHOLD + ); + + private readonly objectLiteralInitInterfaceNameGenerator = new NameGenerator( + GENERATED_OBJECT_LITERAL_INIT_INTERFACE_NAME, + GENERATED_OBJECT_LITERAL_INIT_INTERFACE_TRESHOLD + ); + private readonly importVarNameGenerator = new NameGenerator( GENERATED_IMPORT_VARIABLE_NAME, GENERATED_IMPORT_VARIABLE_TRESHOLD @@ -132,6 +161,8 @@ export class Autofixer { private readonly sendableDecoratorCache = new Map(); + private readonly newLine: string; + constructor( private readonly typeChecker: ts.TypeChecker, private readonly utils: TsUtils, @@ -139,6 +170,29 @@ export class Autofixer { readonly cancellationToken?: ts.CancellationToken ) { this.symbolCache = new SymbolCache(this.typeChecker, this.utils, sourceFile, cancellationToken); + this.newLine = Autofixer.getNewLineCharacterFromSrcFile(sourceFile); + + const tsNewLineKind = + this.newLine === CARRIAGE_RETURN_LINE_FEED ? ts.NewLineKind.CarriageReturnLineFeed : ts.NewLineKind.LineFeed; + this.printer = ts.createPrinter({ + omitTrailingSemicolon: false, + removeComments: false, + newLine: tsNewLineKind + }); + this.nonCommentPrinter = ts.createPrinter({ + omitTrailingSemicolon: false, + removeComments: true, + newLine: tsNewLineKind + }); + } + + private static getNewLineCharacterFromSrcFile(srcFile: ts.SourceFile): string { + const match = srcFile.text.match(NEW_LINE_SEARCH_REGEX); + return match ? match[0] : LINE_FEED; + } + + private getNewLine(srcFile?: ts.SourceFile): string { + return srcFile ? Autofixer.getNewLineCharacterFromSrcFile(srcFile) : this.newLine; } /** @@ -150,7 +204,7 @@ export class Autofixer { * @param sourceFile - Source file from which the nodes are taken. * @returns The generated destructuring text. */ - private static genDestructElementTextForObjDecls( + private genDestructElementTextForObjDecls( variableDeclarationMap: Map, newObjectName: string, declarationFlags: ts.NodeFlags, @@ -182,7 +236,7 @@ export class Autofixer { // Print the variable statement to text and append it const text = printer.printNode(ts.EmitHint.Unspecified, variableStatement, sourceFile); - destructElementText += text; + destructElementText += text + this.getNewLine(); }); return destructElementText; @@ -195,7 +249,7 @@ export class Autofixer { * @param destructElementText - Generated text for destructuring elements. * @returns Array of autofix suggestions or undefined. */ - private static genAutofixForObjDecls( + private genAutofixForObjDecls( variableDeclaration: ts.VariableDeclaration, newObjectName: string | undefined, destructElementText: string, @@ -221,7 +275,7 @@ export class Autofixer { end: variableDeclaration.name.getEnd() }; destructElementReplaceText = { - replacementText: destructElementText, + replacementText: this.getNewLine() + destructElementText, start: variableDeclaration.parent.parent.getEnd(), end: variableDeclaration.parent.parent.getEnd() }; @@ -295,7 +349,7 @@ export class Autofixer { return undefined; } const declarationFlags = ts.getCombinedNodeFlags(variableDeclaration); - const destructElementText = Autofixer.genDestructElementTextForObjDecls( + const destructElementText = this.genDestructElementTextForObjDecls( variableDeclarationMap, newObjectName, declarationFlags, @@ -304,7 +358,7 @@ export class Autofixer { ); // Generate and return autofix suggestions for the object declarations - return Autofixer.genAutofixForObjDecls(variableDeclaration, newObjectName, destructElementText, isIdentifier); + return this.genAutofixForObjDecls(variableDeclaration, newObjectName, destructElementText, isIdentifier); } /** @@ -316,7 +370,7 @@ export class Autofixer { * @param sourceFile - Source file from which the nodes are taken. * @returns The generated destructuring text. */ - private static genDestructElementTextForArrayDecls( + private genDestructElementTextForArrayDecls( variableNames: string[], newArrayName: string, declarationFlags: ts.NodeFlags, @@ -352,7 +406,7 @@ export class Autofixer { // Print the variable statement to text and append it const text = printer.printNode(ts.EmitHint.Unspecified, variableStatement, sourceFile); - destructElementText += text; + destructElementText += text + this.getNewLine(); } return destructElementText; @@ -365,7 +419,7 @@ export class Autofixer { * @param destructElementText - Generated text for destructuring elements. * @returns Array of autofix suggestions. */ - private static genAutofixForArrayDecls( + private genAutofixForArrayDecls( variableDeclaration: ts.VariableDeclaration, newArrayName: string | undefined, destructElementText: string, @@ -391,7 +445,7 @@ export class Autofixer { end: variableDeclaration.name.getEnd() }; destructElementReplaceText = { - replacementText: destructElementText, + replacementText: this.getNewLine() + destructElementText, start: variableDeclaration.parent.parent.getEnd(), end: variableDeclaration.parent.parent.getEnd() }; @@ -478,7 +532,7 @@ export class Autofixer { // Get the combined node flags for the variable declaration const declarationFlags = ts.getCombinedNodeFlags(variableDeclaration); // Generate the destructuring element text for the array declaration - const destructElementText = Autofixer.genDestructElementTextForArrayDecls( + const destructElementText = this.genDestructElementTextForArrayDecls( variableNames, newArrayName, declarationFlags, @@ -487,7 +541,7 @@ export class Autofixer { ); // Generate and return autofix suggestions for the array declarations - return Autofixer.genAutofixForArrayDecls( + return this.genAutofixForArrayDecls( variableDeclaration, newArrayName, destructElementText, @@ -503,7 +557,7 @@ export class Autofixer { * @param sourceFile - Source file from which the nodes are taken. * @returns The generated destructuring assignment text. */ - private static genDestructElementTextForArrayAssignment( + private genDestructElementTextForArrayAssignment( variableNames: string[], newArrayName: string | undefined, printer: ts.Printer, @@ -534,7 +588,7 @@ export class Autofixer { // Print the expression statement to text and append it const text = printer.printNode(ts.EmitHint.Unspecified, expressionStatement, sourceFile); - destructElementText += text; + destructElementText += text + this.getNewLine(); } return destructElementText; @@ -547,7 +601,7 @@ export class Autofixer { * @param destructElementText - Generated text for destructuring assignments. * @returns Array of autofix suggestions. */ - private static genAutofixForArrayAssignment( + private genAutofixForArrayAssignment( assignmentExpr: ts.BinaryExpression, newArrayName: string | undefined, destructElementText: string, @@ -574,7 +628,7 @@ export class Autofixer { end: assignmentExpr.left.getEnd() }; destructElementReplaceText = { - replacementText: destructElementText, + replacementText: this.getNewLine() + destructElementText, start: assignmentExpr.parent.getEnd(), end: assignmentExpr.parent.getEnd() }; @@ -658,14 +712,14 @@ export class Autofixer { } // Generate the text for destructuring assignments - const destructElementText = Autofixer.genDestructElementTextForArrayAssignment( + const destructElementText = this.genDestructElementTextForArrayAssignment( variableNames, newArrayName, this.printer, sourceFile ); - return Autofixer.genAutofixForArrayAssignment( + return this.genAutofixForArrayAssignment( assignmentExpr, newArrayName, destructElementText, @@ -711,7 +765,7 @@ export class Autofixer { * @param printer - TypeScript printer instance for printing nodes. * @returns The generated text for destructuring assignments. */ - private static genDestructElementTextForObjAssignment( + private genDestructElementTextForObjAssignment( tsVarDeclMap: Map, needParentheses: boolean[], newObjName: string, @@ -740,7 +794,8 @@ export class Autofixer { ts.factory.createExpressionStatement(assignmentExpr); // Append the generated text for the destructuring assignment - destructElementText += printer.printNode(ts.EmitHint.Unspecified, statement, binaryExpr.getSourceFile()); + destructElementText += + printer.printNode(ts.EmitHint.Unspecified, statement, binaryExpr.getSourceFile()) + this.getNewLine(); index++; }); @@ -782,7 +837,7 @@ export class Autofixer { * @param destructElementText - Generated text for destructuring assignments. * @returns Array of autofix suggestions or undefined if no fixes are needed. */ - private static createAutofixForObjAssignment( + private createAutofixForObjAssignment( binaryExpr: ts.BinaryExpression, declNameReplaceText: string, destructElementText: string, @@ -807,7 +862,7 @@ export class Autofixer { end: binaryExpr.parent.getEnd() }; destructElementReplaceTextAutofix = { - replacementText: destructElementText, + replacementText: this.getNewLine() + destructElementText, start: binaryExpr.parent.parent.getEnd(), end: binaryExpr.parent.parent.getEnd() }; @@ -867,7 +922,7 @@ export class Autofixer { return undefined; } // Create the text for destructuring elements - const destructElementText = Autofixer.genDestructElementTextForObjAssignment( + const destructElementText = this.genDestructElementTextForObjAssignment( tsVarDeclMap, needParentheses, newObjName, @@ -879,7 +934,7 @@ export class Autofixer { const declNameReplaceText = Autofixer.genDeclNameReplaceTextForObjAssignment(binaryExpr, newObjName, this.printer); // Generate autofix suggestions - return Autofixer.createAutofixForObjAssignment(binaryExpr, declNameReplaceText, destructElementText, isIdentifier); + return this.createAutofixForObjAssignment(binaryExpr, declNameReplaceText, destructElementText, isIdentifier); } fixLiteralAsPropertyNamePropertyAssignment(node: ts.PropertyAssignment): Autofix[] | undefined { @@ -963,7 +1018,8 @@ export class Autofixer { return result; } - static addDefaultModuleToPath(parts: string[], importDeclNode: ts.ImportDeclaration): Autofix[] | undefined { + addDefaultModuleToPath(parts: string[], importDeclNode: ts.ImportDeclaration): Autofix[] | undefined { + void this; const moduleSpecifier = importDeclNode.moduleSpecifier; /* @@ -979,7 +1035,8 @@ export class Autofixer { return [{ start: moduleSpecifier.getStart(), end: moduleSpecifier.getEnd(), replacementText: newPathString }]; } - static fixImportPath(parts: string[], index: number, importDeclNode: ts.ImportDeclaration): Autofix[] | undefined { + fixImportPath(parts: string[], index: number, importDeclNode: ts.ImportDeclaration): Autofix[] | undefined { + void this; const moduleSpecifier = importDeclNode.moduleSpecifier; const beforeEts = parts.slice(0, index); @@ -1345,11 +1402,11 @@ export class Autofixer { if (tsExprNode.left.kind === ts.SyntaxKind.BinaryExpression) { text += this.recursiveCommaOperator(tsExprNode.left as ts.BinaryExpression); - text += '\n' + tsExprNode.right.getFullText() + ';'; + text += this.getNewLine() + tsExprNode.right.getFullText() + ';'; } else { const leftText = tsExprNode.left.getFullText(); const rightText = tsExprNode.right.getFullText(); - text = leftText + ';\n' + rightText + ';'; + text = leftText + ';' + this.getNewLine() + rightText + ';'; } return text; @@ -1460,13 +1517,7 @@ export class Autofixer { const autofixes: Autofix[] = [{ start: newFieldPos, end: newFieldPos, replacementText: '' }]; for (let i = 0; i < ctorDecl.parameters.length; i++) { - this.fixCtorParameterPropertiesProcessParam( - ctorDecl.parameters[i], - paramTypes[i], - ctorDecl.getSourceFile(), - fieldInitStmts, - autofixes - ); + this.fixCtorParameterPropertiesProcessParam(ctorDecl.parameters[i], paramTypes[i], fieldInitStmts, autofixes); } // Note: Bodyless ctors can't have parameter properties. @@ -1524,7 +1575,6 @@ export class Autofixer { private fixCtorParameterPropertiesProcessParam( param: ts.ParameterDeclaration, paramType: ts.TypeNode, - sourceFile: ts.SourceFile, fieldInitStmts: ts.Statement[], autofixes: Autofix[] ): void { @@ -1547,7 +1597,8 @@ export class Autofixer { paramType, undefined ); - const newFieldText = this.printer.printNode(ts.EmitHint.Unspecified, newFieldNode, sourceFile) + '\n'; + const newFieldText = + this.printer.printNode(ts.EmitHint.Unspecified, newFieldNode, param.getSourceFile()) + this.getNewLine(); autofixes[0].replacementText += newFieldText; const newParamDecl = ts.factory.createParameterDeclaration( @@ -1558,7 +1609,7 @@ export class Autofixer { param.type, param.initializer ); - const newParamText = this.printer.printNode(ts.EmitHint.Unspecified, newParamDecl, sourceFile); + const newParamText = this.printer.printNode(ts.EmitHint.Unspecified, newParamDecl, param.getSourceFile()); autofixes.push({ start: param.getStart(), end: param.getEnd(), replacementText: newParamText }); fieldInitStmts.push( @@ -1794,7 +1845,11 @@ export class Autofixer { return this.fixRecordObjectLiteral(objectLiteralExpr); } - // Can't fix when object literal has a contextual type. + // Here, we only fix object literal that doesn't have a contextual type. + return undefined; + } + + if (Autofixer.hasUnfixableProperty(objectLiteralExpr)) { return undefined; } @@ -1803,6 +1858,28 @@ export class Autofixer { return undefined; } + if (Autofixer.hasMethodsOrAccessors(objectLiteralExpr)) { + return this.fixObjectLiteralAsClass(objectLiteralExpr, undefined, enclosingStmt); + } + return this.fixUntypedObjectLiteralAsInterface(objectLiteralExpr, enclosingStmt); + } + + private static hasUnfixableProperty(objectLiteralExpr: ts.ObjectLiteralExpression): boolean { + return objectLiteralExpr.properties.some((prop) => { + return ts.isSpreadAssignment(prop) || !ts.isIdentifier(prop.name); + }); + } + + private static hasMethodsOrAccessors(objectLiteralExpr: ts.ObjectLiteralExpression): boolean { + return objectLiteralExpr.properties.some((prop) => { + return ts.isMethodDeclaration(prop) || ts.isAccessor(prop); + }); + } + + private fixUntypedObjectLiteralAsInterface( + objectLiteralExpr: ts.ObjectLiteralExpression, + enclosingStmt: ts.Node + ): Autofix[] | undefined { const newInterfaceProps = this.getInterfacePropertiesFromObjectLiteral(objectLiteralExpr, enclosingStmt); if (!newInterfaceProps) { return undefined; @@ -1815,7 +1892,7 @@ export class Autofixer { } return [ - this.createNewInterface(srcFile, newInterfaceName, newInterfaceProps, enclosingStmt.getStart()), + this.createNewInterfaceForObjectLiteral(srcFile, newInterfaceName, newInterfaceProps, enclosingStmt.getStart()), this.fixObjectLiteralExpression(srcFile, newInterfaceName, objectLiteralExpr) ]; } @@ -1851,7 +1928,7 @@ export class Autofixer { return undefined; } - if (Autofixer.propertyTypeIsCapturedFromEnclosingLocalScope(propType, enclosingStmt)) { + if (TsUtils.typeIsCapturedFromEnclosingLocalScope(propType, enclosingStmt)) { return undefined; } @@ -1869,21 +1946,7 @@ export class Autofixer { return newProp; } - private static propertyTypeIsCapturedFromEnclosingLocalScope(type: ts.Type, enclosingStmt: ts.Node): boolean { - const sym = type.getSymbol(); - let symNode: ts.Node | undefined = TsUtils.getDeclaration(sym); - - while (symNode) { - if (symNode === enclosingStmt) { - return true; - } - symNode = symNode.parent; - } - - return false; - } - - private createNewInterface( + private createNewInterfaceForObjectLiteral( srcFile: ts.SourceFile, interfaceName: string, members: ts.TypeElement[], @@ -1896,7 +1959,7 @@ export class Autofixer { undefined, members ); - const text = this.printer.printNode(ts.EmitHint.Unspecified, newInterfaceDecl, srcFile) + '\n'; + const text = this.printer.printNode(ts.EmitHint.Unspecified, newInterfaceDecl, srcFile) + this.getNewLine(); return { start: pos, end: pos, replacementText: text }; } @@ -1945,6 +2008,286 @@ export class Autofixer { return (decl.exclamationToken || decl.name).getEnd(); } + private fixObjectLiteralAsClass( + objectLiteralExpr: ts.ObjectLiteralExpression, + typeDecl: ts.ClassDeclaration | ts.InterfaceDeclaration | undefined, + enclosingStmt: ts.Node + ): Autofix[] | undefined { + if (this.utils.nodeCapturesValueFromEnclosingLocalScope(objectLiteralExpr, enclosingStmt)) { + return undefined; + } + + const srcFile = objectLiteralExpr.getSourceFile(); + const newClassName = TsUtils.generateUniqueName(this.objectLiteralClassNameGenerator, srcFile); + if (!newClassName) { + return undefined; + } + const newInitInterfaceName = TsUtils.generateUniqueName(this.objectLiteralInitInterfaceNameGenerator, srcFile); + if (!newInitInterfaceName) { + return undefined; + } + + const classDeclAndCtorInitProps = this.createClassDeclForObjectLiteral( + objectLiteralExpr, + enclosingStmt, + newClassName, + newInitInterfaceName, + typeDecl + ); + if (!classDeclAndCtorInitProps) { + return undefined; + } + const { classDecl, ctorInitProps } = classDeclAndCtorInitProps; + let classDeclText = + this.printer.printNode(ts.EmitHint.Unspecified, classDecl, srcFile) + this.getNewLine() + this.getNewLine(); + + const ctorArgs: ts.Expression[] = []; + if (ctorInitProps.length) { + classDeclText += this.createInitInterfaceForObjectLiteral(srcFile, newInitInterfaceName, classDecl); + classDeclText += this.getNewLine() + this.getNewLine(); + ctorArgs.push(ts.factory.createObjectLiteralExpression(ctorInitProps, ctorInitProps.length > 1)); + } + const newExpr = ts.factory.createNewExpression(ts.factory.createIdentifier(newClassName), undefined, ctorArgs); + const newExprText = this.printer.printNode(ts.EmitHint.Unspecified, newExpr, srcFile); + const ctorCallAutofix = { + start: objectLiteralExpr.getStart(), + end: objectLiteralExpr.getEnd(), + replacementText: newExprText + }; + const classDeclPos = enclosingStmt.getStart(); + return [{ start: classDeclPos, end: classDeclPos, replacementText: classDeclText }, ctorCallAutofix]; + } + + private createClassDeclForObjectLiteral( + objectLiteralExpr: ts.ObjectLiteralExpression, + enclosingStmt: ts.Node, + newClassName: string, + newInitInterfaceName: string, + typeDecl: ts.ClassDeclaration | ts.InterfaceDeclaration | undefined + ): { classDecl: ts.ClassDeclaration; ctorInitProps: ts.PropertyAssignment[] } | undefined { + const classFields: ts.PropertyDeclaration[] = []; + const classMethods: (ts.MethodDeclaration | ts.AccessorDeclaration)[] = []; + const ctorBodyStmts: ts.Statement[] = []; + const ctorInitProps: ts.PropertyAssignment[] = []; + + Autofixer.addSuperCallToObjectLiteralConstructor(typeDecl, ctorBodyStmts); + + for (const prop of objectLiteralExpr.properties) { + if (ts.isSpreadAssignment(prop) || !ts.isIdentifier(prop.name)) { + return undefined; + } + if (ts.isMethodDeclaration(prop) || ts.isAccessor(prop)) { + classMethods.push(prop); + continue; + } + const created = this.createClassPropertyForObjectLiteral({ + prop, + enclosingStmt, + classFields, + ctorBodyStmts, + ctorInitProps + }); + if (!created) { + return undefined; + } + } + + const classElements: ts.ClassElement[] = [...classFields]; + if (ctorInitProps.length) { + classElements.push(Autofixer.createClassConstructorForObjectLiteral(newInitInterfaceName, ctorBodyStmts)); + } + classElements.push(...classMethods); + + const heritageClauses = Autofixer.createHeritageClausesForObjectLiteralClass(typeDecl); + + return { + classDecl: ts.factory.createClassDeclaration(undefined, newClassName, undefined, heritageClauses, classElements), + ctorInitProps + }; + } + + private static addSuperCallToObjectLiteralConstructor( + typeDecl: ts.ClassDeclaration | ts.InterfaceDeclaration | undefined, + ctorBodyStmts: ts.Statement[] + ): void { + if (typeDecl && ts.isClassDeclaration(typeDecl)) { + const superCall = ts.factory.createExpressionStatement( + ts.factory.createCallExpression(ts.factory.createSuper(), undefined, []) + ); + ctorBodyStmts.push(superCall); + } + } + + private createClassPropertyForObjectLiteral( + createClassPropParams: CreateClassPropertyForObjectLiteralParams + ): boolean { + const { prop, enclosingStmt, classFields, ctorBodyStmts, ctorInitProps } = createClassPropParams; + if (!ts.isIdentifier(prop.name)) { + return false; + } + const propType = this.typeChecker.getTypeAtLocation(prop); + + // Can't capture generic type parameters of enclosing declarations. + if (this.utils.hasGenericTypeParameter(propType)) { + return false; + } + + if (TsUtils.typeIsCapturedFromEnclosingLocalScope(propType, enclosingStmt)) { + return false; + } + + const propTypeNode = this.typeChecker.typeToTypeNode(propType, undefined, ts.NodeBuilderFlags.None); + if (!propTypeNode || !this.utils.isSupportedType(propTypeNode)) { + return false; + } + + const propName = ts.factory.createIdentifier(prop.name.text); + classFields.push(ts.factory.createPropertyDeclaration(undefined, propName, undefined, propTypeNode, undefined)); + ctorBodyStmts.push( + ts.factory.createExpressionStatement( + ts.factory.createBinaryExpression( + ts.factory.createPropertyAccessExpression(ts.factory.createThis(), propName), + ts.factory.createToken(ts.SyntaxKind.EqualsToken), + ts.factory.createPropertyAccessExpression( + ts.factory.createIdentifier(OBJECT_LITERAL_CLASS_CONSTRUCTOR_PARAM_NAME), + propName + ) + ) + ) + ); + ctorInitProps.push(ts.isPropertyAssignment(prop) ? prop : ts.factory.createPropertyAssignment(prop.name, propName)); + return true; + } + + private static createHeritageClausesForObjectLiteralClass( + typeDecl: ts.ClassDeclaration | ts.InterfaceDeclaration | undefined + ): ts.HeritageClause[] | undefined { + if (!typeDecl?.name) { + return undefined; + } + + return [ + ts.factory.createHeritageClause( + ts.isClassDeclaration(typeDecl) ? ts.SyntaxKind.ExtendsKeyword : ts.SyntaxKind.ImplementsKeyword, + [ts.factory.createExpressionWithTypeArguments(typeDecl.name, undefined)] + ) + ]; + } + + private static createClassConstructorForObjectLiteral( + newInitInterfaceName: string, + ctorBodyStmts: ts.Statement[] + ): ts.ConstructorDeclaration { + const ctorParams: ts.ParameterDeclaration[] = []; + ctorParams.push( + ts.factory.createParameterDeclaration( + undefined, + undefined, + OBJECT_LITERAL_CLASS_CONSTRUCTOR_PARAM_NAME, + undefined, + ts.factory.createTypeReferenceNode(newInitInterfaceName) + ) + ); + return ts.factory.createConstructorDeclaration(undefined, ctorParams, ts.factory.createBlock(ctorBodyStmts, true)); + } + + private createInitInterfaceForObjectLiteral( + srcFile: ts.SourceFile, + interfaceName: string, + newClassDecl: ts.ClassDeclaration + ): string { + const props: ts.PropertySignature[] = []; + newClassDecl.members.forEach((prop) => { + if (ts.isPropertyDeclaration(prop)) { + props.push(ts.factory.createPropertySignature(undefined, prop.name, undefined, prop.type)); + } + }); + const newInterfaceDecl = ts.factory.createInterfaceDeclaration( + undefined, + interfaceName, + undefined, + undefined, + props + ); + return this.printer.printNode(ts.EmitHint.Unspecified, newInterfaceDecl, srcFile); + } + + fixTypedObjectLiteral( + objectLiteralExpr: ts.ObjectLiteralExpression, + objectLiteralType: ts.Type | undefined + ): Autofix[] | undefined { + // Here we only try to fix typed object literal. Other case is handled by 'fixUntypedObjectLiteral' method. + + if (!objectLiteralType || !this.utils.validateObjectLiteralType(objectLiteralType)) { + return undefined; + } + + const typeDecl = TsUtils.getDeclaration(objectLiteralType.getSymbol()); + if (!typeDecl || !ts.isClassDeclaration(typeDecl) && !ts.isInterfaceDeclaration(typeDecl) || !typeDecl.name) { + return undefined; + } + + if (Autofixer.hasUnfixableProperty(objectLiteralExpr)) { + return undefined; + } + + if (this.hasMethodOverridingProperty(objectLiteralExpr, objectLiteralType)) { + return undefined; + } + + const enclosingStmt = TsUtils.getEnclosingTopLevelStatement(objectLiteralExpr); + if (!enclosingStmt) { + return undefined; + } + + return this.fixObjectLiteralAsClass(objectLiteralExpr, typeDecl, enclosingStmt); + } + + private hasMethodOverridingProperty( + objectLiteralExpr: ts.ObjectLiteralExpression, + objectLiteralType: ts.Type + ): boolean { + const typeProps = this.typeChecker.getPropertiesOfType(objectLiteralType); + for (const objProp of objectLiteralExpr.properties) { + if ( + ts.isPropertyAssignment(objProp) && + typeProps.some((typeProp) => { + const typePropDecl = TsUtils.getDeclaration(typeProp); + return ( + !!typePropDecl && + (ts.isMethodSignature(typePropDecl) || ts.isMethodDeclaration(typePropDecl)) && + typePropDecl.name === objProp.name + ); + }) + ) { + return true; + } + + if ( + ts.isMethodDeclaration(objProp) && + typeProps.some((typeProp) => { + const typePropDecl = TsUtils.getDeclaration(typeProp); + return ( + !!typePropDecl && + (ts.isPropertyDeclaration(typePropDecl) || ts.isPropertySignature(typePropDecl)) && + typePropDecl.name.getText() === objProp.name.getText() + ); + }) + ) { + return true; + } + } + + return false; + } + + fixShorthandPropertyAssignment(prop: ts.ShorthandPropertyAssignment): Autofix[] { + const newName = ts.factory.createIdentifier(prop.name.text); + const newProp = ts.factory.createPropertyAssignment(newName, newName); + const replacementText = this.printer.printNode(ts.EmitHint.Unspecified, newProp, prop.getSourceFile()); + return [{ start: prop.getStart(), end: prop.getEnd(), replacementText }]; + } + /* * In case of type alias initialized with type literal, replace * entire type alias with identical interface declaration. @@ -1981,7 +2324,7 @@ export class Autofixer { return undefined; } - if (this.typeLiteralCapturesTypeFromEnclosingLocalScope(typeLiteral, enclosingStmt)) { + if (this.utils.nodeCapturesValueFromEnclosingLocalScope(typeLiteral, enclosingStmt)) { return undefined; } @@ -1997,7 +2340,8 @@ export class Autofixer { undefined, typeLiteral.members ); - const interfaceText = this.printer.printNode(ts.EmitHint.Unspecified, newInterfaceDecl, srcFile) + '\n'; + const interfaceText = + this.printer.printNode(ts.EmitHint.Unspecified, newInterfaceDecl, srcFile) + this.getNewLine(); return [ { start: newInterfacePos, end: newInterfacePos, replacementText: interfaceText }, @@ -2005,39 +2349,79 @@ export class Autofixer { ]; } - typeLiteralCapturesTypeFromEnclosingLocalScope(typeLiteral: ts.TypeLiteralNode, enclosingStmt: ts.Node): boolean { - let found = false; + removeNode(node: ts.Node): Autofix[] { + void this; + return [{ start: node.getStart(), end: node.getEnd(), replacementText: '' }]; + } - const callback = (node: ts.Node): void => { - if (!ts.isIdentifier(node)) { - return; - } - const sym = this.typeChecker.getSymbolAtLocation(node); - let symNode: ts.Node | undefined = TsUtils.getDeclaration(sym); - while (symNode) { - if (symNode === typeLiteral) { - return; - } - if (symNode === enclosingStmt) { - found = true; - return; - } - symNode = symNode.parent; + replaceNode(node: ts.Node, replacementText: string): Autofix[] { + void this; + return [{ start: node.getStart(), end: node.getEnd(), replacementText }]; + } + + removeImportSpecifier( + specToRemove: ts.ImportSpecifier, + importDeclaration: ts.ImportDeclaration + ): Autofix[] | undefined { + if (!importDeclaration) { + return undefined; + } + + const importClause = importDeclaration.importClause; + if (!importClause?.namedBindings || !ts.isNamedImports(importClause.namedBindings)) { + return undefined; + } + + const namedBindings = importClause.namedBindings; + const allSpecifiers = namedBindings.elements; + const remainingSpecifiers = allSpecifiers.filter((spec) => { + return spec !== specToRemove; + }); + + // If none are valid, remove all named imports. + if (remainingSpecifiers.length === 0) { + if (importClause.name) { + const start = importClause.name.end; + const end = namedBindings.end; + return [{ start, end, replacementText: '' }]; } - }; + return this.removeNode(importDeclaration); + } - const stopCondition = (node: ts.Node): boolean => { - void node; - return found; - }; + const specIndex = allSpecifiers.findIndex((spec) => { + return spec === specToRemove; + }); + const isLast = specIndex === allSpecifiers.length - 1; + const isFirst = specIndex === 0; + + let start = specToRemove.getStart(); + let end = specToRemove.getEnd(); - forEachNodeInSubtree(typeLiteral, callback, stopCondition); - return found; + if (!isLast) { + end = allSpecifiers[specIndex + 1].getStart(); + } else if (!isFirst) { + const prev = allSpecifiers[specIndex - 1]; + start = prev.getEnd(); + } + + return [{ start, end, replacementText: '' }]; } - removeNode(node: ts.Node): Autofix[] { - void this; - return [{ start: node.getStart(), end: node.getEnd(), replacementText: '' }]; + removeDefaultImport(importDecl: ts.ImportDeclaration, defaultImport: ts.Identifier): Autofix[] | undefined { + const importClause = importDecl.importClause; + if (!importClause || !defaultImport) { + return undefined; + } + + const namedBindings = importClause.namedBindings; + + if (!namedBindings) { + return this.removeNode(importDecl); + } + const start = defaultImport.getStart(); + const end = namedBindings.getStart(); + + return [{ start, end, replacementText: '' }]; } fixSendableExplicitFieldType(node: ts.PropertyDeclaration): Autofix[] | undefined { @@ -2052,19 +2436,9 @@ export class Autofixer { return undefined; } - const questionOrExclamationToken: ts.ExclamationToken | ts.QuestionToken | undefined = - node.questionToken ?? node.exclamationToken ?? undefined; - - const newPropDecl: ts.PropertyDeclaration = ts.factory.createPropertyDeclaration( - node.modifiers, - node.name, - questionOrExclamationToken, - propTypeNode, - initializer - ); - - const text = this.printer.printNode(ts.EmitHint.Unspecified, newPropDecl, node.getSourceFile()); - return [{ start: node.getFullStart(), end: node.getEnd(), replacementText: text }]; + const pos = (node.questionToken || node.exclamationToken || node.name).getEnd(); + const text = ': ' + this.printer.printNode(ts.EmitHint.Unspecified, propTypeNode, node.getSourceFile()); + return [{ start: pos, end: pos, replacementText: text }]; } addClassSendableDecorator( @@ -2085,7 +2459,7 @@ export class Autofixer { addSendableDecorator(node: ts.Node): Autofix[] { void this; - const text = '@' + SENDABLE_DECORATOR + '\n'; + const text = '@' + SENDABLE_DECORATOR + this.getNewLine(); const pos = node.getStart(); return [{ start: pos, end: pos, replacementText: text }]; } @@ -2153,12 +2527,13 @@ export class Autofixer { fixRegularExpressionLiteral(node: ts.RegularExpressionLiteral | ts.CallExpression): Autofix[] | undefined { const srcFile = node.getSourceFile(); - let pattern: string; + let patternNode: ts.Expression | undefined; let flag: string | undefined; + if (ts.isRegularExpressionLiteral(node)) { const literalText = node.getText(); const parts = Autofixer.extractRegexParts(literalText); - pattern = parts.pattern; + patternNode = ts.factory.createStringLiteral(parts.pattern); flag = parts.flag; } else if (ts.isCallExpression(node)) { const args = node.arguments; @@ -2166,10 +2541,11 @@ export class Autofixer { return undefined; } const patternArg = args[0]; - if (!ts.isStringLiteral(patternArg)) { + if (!this.isStaticStringExpression(patternArg)) { return undefined; } - pattern = patternArg.text; + patternNode = patternArg; + if (args.length > 1) { const flagArg = args[1]; if (ts.isStringLiteral(flagArg)) { @@ -2181,13 +2557,47 @@ export class Autofixer { } else { return undefined; } - const args = [ts.factory.createStringLiteral(pattern)]; - if (flag) { - args.push(ts.factory.createStringLiteral(flag)); + + const newArgs: ts.Expression[] = [patternNode]; + if (flag !== undefined) { + newArgs.push(ts.factory.createStringLiteral(flag)); } - const newExpression = ts.factory.createNewExpression(ts.factory.createIdentifier('RegExp'), undefined, args); + const newExpression = ts.factory.createNewExpression(ts.factory.createIdentifier('RegExp'), undefined, newArgs); + const text = this.printer.printNode(ts.EmitHint.Unspecified, newExpression, srcFile); - return [{ start: node.getStart(), end: node.getEnd(), replacementText: text }]; + return [ + { + start: node.getStart(), + end: node.getEnd(), + replacementText: text + } + ]; + } + + private isStaticStringExpression(node: ts.Node): boolean { + if (ts.isStringLiteral(node)) { + return true; + } + if (ts.isBinaryExpression(node)) { + return ( + node.operatorToken.kind === ts.SyntaxKind.PlusToken && + this.isStaticStringExpression(node.left) && + this.isStaticStringExpression(node.right) + ); + } + if (ts.isCallExpression(node)) { + const expression = node.expression; + if ( + ts.isPropertyAccessExpression(expression) && + expression.name.text === 'concat' && + this.isStaticStringExpression(expression.expression) + ) { + return node.arguments.every((arg) => { + return this.isStaticStringExpression(arg); + }); + } + } + return false; } private static extractRegexParts(literalText: string): { @@ -2209,7 +2619,7 @@ export class Autofixer { fixDebuggerStatement(debuggerStmt: ts.DebuggerStatement): Autofix[] { void this; - const text = SPECIAL_LIB_NAME + '.debugger()'; + const text = SPECIAL_LIB_NAME + '.debugger();'; return [{ start: debuggerStmt.getStart(), end: debuggerStmt.getEnd(), replacementText: text }]; } @@ -2327,7 +2737,7 @@ export class Autofixer { const newExpr = ts.factory.createObjectLiteralExpression([assignment1, assignment2], true); let text = this.printer.printNode(ts.EmitHint.Unspecified, newExpr, originalExpr.getSourceFile()); const startPos = this.sourceFile.getLineAndCharacterOfPosition(originalExpr.parent.getStart()).character; - text = Autofixer.adjustIndentation(text, startPos); + text = this.adjustIndentation(text, startPos); return [{ start: originalExpr.getStart(), end: originalExpr.getEnd(), replacementText: text }]; } @@ -2392,7 +2802,7 @@ export class Autofixer { const newFuncDecl = Autofixer.createFunctionDeclaration(funcDecl, undefined, parameDecl, returnType, newBlock); let text = this.printer.printNode(ts.EmitHint.Unspecified, newFuncDecl, funcDecl.getSourceFile()); if (preserveDecorator) { - text = '@' + CustomDecoratorName.AnimatableExtend + '\n' + text; + text = '@' + CustomDecoratorName.AnimatableExtend + this.getNewLine() + text; } return [{ start: funcDecl.getStart(), end: funcDecl.getEnd(), replacementText: text }]; } @@ -2425,7 +2835,7 @@ export class Autofixer { fixedEntryDecorator, parentNode.getSourceFile() ); - text = text + '\n' + fixedEntryDecoratorText; + text = text + this.getNewLine() + fixedEntryDecoratorText; return [{ start: entryDecorator.getStart(), end: entryDecorator.getEnd(), replacementText: text }]; } return undefined; @@ -2863,6 +3273,36 @@ export class Autofixer { }); } + removeImport(ident: ts.Identifier, importSpecifier: ts.ImportSpecifier): Autofix[] | undefined { + const namedImports = importSpecifier.parent; + const importClause = namedImports.parent; + const importDeclaration = importClause.parent; + if (!importDeclaration || !importClause) { + return undefined; + } + + if (namedImports.elements.length === 1 && !importClause.name) { + return this.removeNode(importDeclaration); + } + + if (namedImports.elements.length <= 0) { + return undefined; + } + + const specifiers = namedImports.elements.filter((specifier) => { + return specifier.name.text !== ident.text; + }); + + const newClause = ts.factory.createImportClause( + importClause.isTypeOnly, + importClause.name, + ts.factory.createNamedImports(specifiers) + ); + + const replacementText = this.printer.printNode(ts.EmitHint.Unspecified, newClause, ident.getSourceFile()); + return [{ start: importClause.getStart(), end: importClause.getEnd(), replacementText }]; + } + fixInterfaceImport( interfacesNeedToImport: Set, interfacesAlreadyImported: Set, @@ -2893,19 +3333,19 @@ export class Autofixer { let text = this.printer.printNode(ts.EmitHint.Unspecified, importDeclaration, sourceFile); if (annotationEndPos !== 0) { - text = '\n\n' + text; + text = this.getNewLine() + this.getNewLine() + text; } const codeStartLine = sourceFile.getLineAndCharacterOfPosition(sourceFile.getStart()).line; for (let i = 2; i > codeStartLine - annotationEndLine; i--) { - text = text + '\n'; + text = text + this.getNewLine(); } return [{ start: annotationEndPos, end: annotationEndPos, replacementText: text }]; } fixStylesDecoratorGlobal( funcDecl: ts.FunctionDeclaration, - calls: ts.CallExpression[], + calls: ts.Identifier[], needImport: Set ): Autofix[] | undefined { const block = funcDecl.body; @@ -2933,7 +3373,7 @@ export class Autofixer { fixStylesDecoratorStruct( methodDecl: ts.MethodDeclaration, - calls: ts.CallExpression[], + calls: ts.Identifier[], needImport: Set ): Autofix[] | undefined { const block = methodDecl.body; @@ -2962,7 +3402,7 @@ export class Autofixer { needImport.add(COMMON_METHOD_IDENTIFIER); let text = this.printer.printNode(ts.EmitHint.Unspecified, expr, methodDecl.getSourceFile()); const startPos = this.sourceFile.getLineAndCharacterOfPosition(methodDecl.getStart()).character; - text = Autofixer.adjustIndentation(text, startPos); + text = this.adjustIndentation(text, startPos); const autofix = [{ start: methodDecl.getStart(), end: methodDecl.getEnd(), replacementText: text }]; const argument = ts.factory.createPropertyAccessExpression( ts.factory.createThis(), @@ -2972,8 +3412,8 @@ export class Autofixer { return autofix; } - private static adjustIndentation(text: string, startPos: number): string { - const lines = text.split('\n'); + private adjustIndentation(text: string, startPos: number): string { + const lines = text.split(this.getNewLine()); if (lines.length <= 1) { return text; } @@ -2991,34 +3431,50 @@ export class Autofixer { }); const lastLine = ' '.repeat(startPos) + lines[lines.length - 1]; - return [firstLine, ...middleLines, lastLine].join('\n'); + return [firstLine, ...middleLines, lastLine].join(this.getNewLine()); } - private addAutofixFromCalls(calls: ts.CallExpression[], autofix: Autofix[], argument: ts.Expression): void { + private addAutofixFromCalls(calls: ts.Identifier[], autofix: Autofix[], argument: ts.Expression): void { calls.forEach((call) => { const callExpr = ts.factory.createCallExpression( ts.factory.createIdentifier(APPLY_STYLES_IDENTIFIER), undefined, [argument] ); + + const start: number = call.getStart(); + let end: number = 0; + const expr = call.parent; + if (ts.isCallExpression(expr)) { + end = expr.getEnd(); + } + if (ts.isPropertyAccessExpression(expr) && ts.isCallExpression(expr.parent)) { + end = expr.parent.getEnd(); + } + if (end === 0) { + return; + } const text = this.printer.printNode(ts.EmitHint.Unspecified, callExpr, call.getSourceFile()); - autofix.push({ start: call.getStart(), end: call.getEnd(), replacementText: text }); + autofix.push({ start: start, end: end, replacementText: text }); }); } - fixStateStyles(object: ts.ObjectLiteralExpression, needImport: Set): Autofix[] | undefined { + fixStateStyles( + object: ts.ObjectLiteralExpression, + startNode: ts.Node, + needImport: Set + ): Autofix[] | undefined { const properties = object.properties; - const stateStyles: ts.Identifier[] = []; - const stateParams: ts.MemberName[][] = []; - const stateValues: ts.Expression[][][] = []; + const assignments: ts.PropertyAssignment[] = []; for (let i = 0; i < properties.length; i++) { const property = properties[i]; const stateStyle = property.name; - if (stateStyle && ts.isIdentifier(stateStyle)) { - stateStyles.push(stateStyle); + if (!stateStyle || !ts.isIdentifier(stateStyle) || !ts.isPropertyAssignment(property)) { + return undefined; } - if (!ts.isPropertyAssignment(property) || !ts.isObjectLiteralExpression(property.initializer)) { - return []; + if (!ts.isObjectLiteralExpression(property.initializer)) { + assignments.push(property); + continue; } const propAssignments = property.initializer.properties; const parameters: ts.MemberName[] = []; @@ -3042,33 +3498,23 @@ export class Autofixer { values.push(tempVals[k]); } } - stateParams.push(parameters); - stateValues.push(values); + const assignment = Autofixer.createPropertyAssignment(parameters, values, stateStyle); + assignments.push(assignment); } needImport.add(COMMON_METHOD_IDENTIFIER); - const newExpr = ts.factory.createObjectLiteralExpression( - Autofixer.createPropertyAssignments(stateParams, stateValues, stateStyles), - true - ); + const newExpr = ts.factory.createObjectLiteralExpression(assignments, true); let text = this.printer.printNode(ts.EmitHint.Unspecified, newExpr, object.getSourceFile()); - const startPos = this.sourceFile.getLineAndCharacterOfPosition(object.parent.getStart()).character - 1; - text = Autofixer.adjustIndentation(text, startPos); + const startPos = this.sourceFile.getLineAndCharacterOfPosition(startNode.getStart()).character - 1; + text = this.adjustIndentation(text, startPos); return [{ start: object.getStart(), end: object.getEnd(), replacementText: text }]; } - private static createPropertyAssignments( - stateParams: ts.MemberName[][], - sateValues: ts.Expression[][][], - stateStyles: ts.Identifier[] - ): ts.PropertyAssignment[] { - const blocks: ts.Block[] = []; - for (let i = 0; i < stateParams.length; i++) { - const parameters = stateParams[i]; - const values = sateValues[i]; - const block = Autofixer.createBlock(parameters, values, ts.factory.createIdentifier(INSTANCE_IDENTIFIER)); - blocks.push(block); - } - + private static createPropertyAssignment( + stateParam: ts.MemberName[], + sateValue: ts.Expression[][], + stateStyle: ts.Identifier + ): ts.PropertyAssignment { + const block = Autofixer.createBlock(stateParam, sateValue, ts.factory.createIdentifier(INSTANCE_IDENTIFIER)); const parameterDecl = ts.factory.createParameterDeclaration( undefined, undefined, @@ -3079,15 +3525,11 @@ export class Autofixer { ); const voidToken = ts.factory.createToken(ts.SyntaxKind.VoidKeyword); const arrowToken = ts.factory.createToken(ts.SyntaxKind.EqualsGreaterThanToken); - const newProperties: ts.PropertyAssignment[] = []; - for (let i = 0; i < blocks.length; i++) { - const property = ts.factory.createPropertyAssignment( - stateStyles[i], - ts.factory.createArrowFunction(undefined, undefined, [parameterDecl], voidToken, arrowToken, blocks[i]) - ); - newProperties.push(property); - } - return newProperties; + const property = ts.factory.createPropertyAssignment( + stateStyle, + ts.factory.createArrowFunction(undefined, undefined, [parameterDecl], voidToken, arrowToken, block) + ); + return property; } fixDataObservation(classDecls: ts.ClassDeclaration[]): Autofix[] | undefined { @@ -3095,18 +3537,19 @@ export class Autofixer { classDecls.forEach((classDecl) => { const observedDecorator = ts.factory.createDecorator(ts.factory.createIdentifier(CustomDecoratorName.Observed)); const sourceFile = classDecl.getSourceFile(); - const text = this.printer.printNode(ts.EmitHint.Unspecified, observedDecorator, sourceFile) + '\n'; + const text = this.printer.printNode(ts.EmitHint.Unspecified, observedDecorator, sourceFile) + this.getNewLine(); const autofix = { start: classDecl.getStart(), end: classDecl.getStart(), replacementText: text }; autofixes.push(autofix); }); return autofixes.length !== 0 ? autofixes : undefined; } - static fixInteropTsType( + fixInteropTsType( binaryExpr: ts.BinaryExpression, lhs: ts.PropertyAccessExpression, rhs: ts.Expression ): Autofix[] | undefined { + void this; const base = lhs.expression.getText(); const prop = lhs.name.text; const replacementText = `${base}.setPropertyByName('${prop}',ESObject.wrap(${rhs.getText()}))`; @@ -3165,6 +3608,32 @@ export class Autofixer { return [{ replacementText, start, end }]; } + fixSharedArrayBufferConstructor(node: ts.NewExpression): Autofix[] | undefined { + void this; + + // Ensure it's a constructor call to SharedArrayBuffer + if (!ts.isIdentifier(node.expression) || node.expression.text !== ESLIB_SHAREDARRAYBUFFER) { + return undefined; + } + + // Construct replacement + const replacementText = 'ArrayBuffer'; + + return [{ replacementText, start: node.expression.getStart(), end: node.expression.getEnd() }]; + } + + fixSharedArrayBufferTypeReference(node: ts.TypeReferenceNode): Autofix[] | undefined { + void this; + + if (!ts.isIdentifier(node.typeName) || node.typeName.text !== ESLIB_SHAREDARRAYBUFFER) { + return undefined; + } + + const replacementText = 'ArrayBuffer'; + + return [{ replacementText, start: node.getStart(), end: node.getEnd() }]; + } + fixAppStorageCallExpression(callExpr: ts.CallExpression): Autofix[] | undefined { const varDecl = Autofixer.findParentVariableDeclaration(callExpr); if (!varDecl || varDecl.type) { @@ -3309,7 +3778,11 @@ export class Autofixer { } return [ { start: importDecl.getStart(), end: importDecl.getEnd(), replacementText: '' }, - { start: lastImportEnd, end: lastImportEnd, replacementText: statements.join('\n') } + { + start: lastImportEnd, + end: lastImportEnd, + replacementText: statements.join(this.getNewLine()) + this.getNewLine() + } ]; } @@ -3441,28 +3914,58 @@ export class Autofixer { } fixInteropInterfaceConvertNum(express: ts.PrefixUnaryExpression): Autofix[] | undefined { - let text = ''; - if (ts.isPropertyAccessExpression(express.operand)) { - const states = ts.factory.createCallExpression( + const createConversionExpression = (propertyAccess: ts.PropertyAccessExpression): ts.Expression => { + const getPropertyCall = ts.factory.createCallExpression( ts.factory.createPropertyAccessExpression( - ts.factory.createCallExpression( - ts.factory.createPropertyAccessExpression( - ts.factory.createIdentifier(express.operand.expression.getText()), - ts.factory.createIdentifier(GET_PROPERTY_BY_NAME) - ), - undefined, - [ts.factory.createStringLiteral(express.operand.name.getText())] - ), - ts.factory.createIdentifier(TO_NUMBER) + ts.factory.createIdentifier(propertyAccess.expression.getText()), + ts.factory.createIdentifier(GET_PROPERTY_BY_NAME) ), undefined, + [ts.factory.createStringLiteral(propertyAccess.name.getText())] + ); + + return ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression(getPropertyCall, ts.factory.createIdentifier(TO_NUMBER)), + undefined, [] ); - text = this.printer.printNode(ts.EmitHint.Unspecified, states, express.getSourceFile()); + }; + + let replacementExpression: ts.Expression | undefined; + if (ts.isPropertyAccessExpression(express.operand)) { + replacementExpression = createConversionExpression(express.operand); + } else if ( + ts.isParenthesizedExpression(express.operand) && + ts.isPropertyAccessExpression(express.operand.expression) + ) { + replacementExpression = ts.factory.createParenthesizedExpression( + createConversionExpression(express.operand.expression) + ); + } + + if (!replacementExpression) { + return undefined; } + + const text = this.printer.printNode(ts.EmitHint.Unspecified, replacementExpression, express.getSourceFile()); + return [{ start: express.operand.getStart(), end: express.operand.getEnd(), replacementText: text }]; } + fixImportClause(tsImportClause: ts.ImportClause): Autofix[] { + const newImportClause = ts.factory.createImportClause( + tsImportClause.isTypeOnly, + tsImportClause.name, + tsImportClause.namedBindings + ); + const replacementText = this.printer.printNode( + ts.EmitHint.Unspecified, + newImportClause, + tsImportClause.getSourceFile() + ); + return [{ start: tsImportClause.getStart(), end: tsImportClause.getEnd(), replacementText }]; + } + fixInteropEqualityOperator( tsBinaryExpr: ts.BinaryExpression, binaryOperator: ts.BinaryOperator @@ -3518,4 +4021,308 @@ export class Autofixer { return undefined; } } + + fixArrayIndexExprType(argExpr: ts.Expression): Autofix[] | undefined { + void this; + if (ts.isAsExpression(argExpr)) { + const innerExpr = argExpr.expression; + return [ + { + start: argExpr.getStart(), + end: argExpr.getEnd(), + replacementText: `${innerExpr ? innerExpr.getText() : ''} as int` + } + ]; + } + + if (ts.isBinaryExpression(argExpr)) { + return [{ start: argExpr.getStart(), end: argExpr.getEnd(), replacementText: `(${argExpr.getText()}) as int` }]; + } + + return [{ start: argExpr.getStart(), end: argExpr.getEnd(), replacementText: `${argExpr.getText()} as int` }]; + } + + fixNoTsLikeFunctionCall(identifier: ts.Node): Autofix[] { + void this; + const funcName = identifier.getText(); + const replacementText = `${funcName}.unSafeCall`; + return [ + { + replacementText, + start: identifier.getStart(), + end: identifier.getEnd() + } + ]; + } + + fixStaticPropertyInitializer(propDecl: ts.PropertyDeclaration): Autofix[] | undefined { + const srcFile = propDecl.getSourceFile(); + const startPos = srcFile.getLineAndCharacterOfPosition(propDecl.getStart()).character; + + const newPropDecl = Autofixer.createUltimateFixedProperty(propDecl); + if (!newPropDecl) { + return undefined; + } + let text = this.printer.printNode(ts.EmitHint.Unspecified, newPropDecl, srcFile); + text = this.adjustIndentation(text, startPos); + + return [ + { + start: propDecl.getStart(), + end: propDecl.getEnd(), + replacementText: text + } + ]; + } + + private static createUltimateFixedProperty(propDecl: ts.PropertyDeclaration): ts.PropertyDeclaration | undefined { + const type = propDecl.type; + + if (!type) { + return undefined; + } + + switch (type.kind) { + case ts.SyntaxKind.TypeLiteral: + return Autofixer.handleTypeLiteralProperty(propDecl, type as ts.TypeLiteralNode); + case ts.SyntaxKind.TypeReference: + return Autofixer.handleTypeReferenceProperty(propDecl, type as ts.TypeReferenceNode); + case ts.SyntaxKind.ArrayType: + return Autofixer.handleArrayTypeProperty(propDecl, type as ts.ArrayTypeNode); + case ts.SyntaxKind.StringKeyword: + return Autofixer.handleStringProperty(propDecl, type); + default: + return undefined; + } + } + + private static handleTypeLiteralProperty( + propDecl: ts.PropertyDeclaration, + type: ts.TypeLiteralNode + ): ts.PropertyDeclaration { + return ts.factory.updatePropertyDeclaration( + propDecl, + propDecl.modifiers, + propDecl.name, + propDecl.questionToken, + type, + Autofixer.createExactObjectInitializer(type) + ); + } + + private static handleTypeReferenceProperty( + propDecl: ts.PropertyDeclaration, + type: ts.TypeReferenceNode + ): ts.PropertyDeclaration | undefined { + if (Autofixer.isUserDefinedClass(type)) { + return Autofixer.handleCustomClassProperty(propDecl, type); + } + const newInit = Autofixer.createBuiltInTypeInitializer(type); + if (!newInit) { + return undefined; + } + return ts.factory.updatePropertyDeclaration( + propDecl, + propDecl.modifiers, + propDecl.name, + propDecl.questionToken, + type, + newInit + ); + } + + private static handleCustomClassProperty( + propDecl: ts.PropertyDeclaration, + type: ts.TypeReferenceNode + ): ts.PropertyDeclaration | undefined { + const nullableType = ts.factory.createUnionTypeNode([ + type, + ts.factory.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword) + ]); + + return ts.factory.updatePropertyDeclaration( + propDecl, + propDecl.modifiers, + propDecl.name, + undefined, + nullableType, + ts.factory.createIdentifier('undefined') + ); + } + + private static handleArrayTypeProperty( + propDecl: ts.PropertyDeclaration, + type: ts.ArrayTypeNode + ): ts.PropertyDeclaration { + return ts.factory.updatePropertyDeclaration( + propDecl, + propDecl.modifiers, + propDecl.name, + propDecl.questionToken, + type, + ts.factory.createArrayLiteralExpression([], false) + ); + } + + private static handleStringProperty(propDecl: ts.PropertyDeclaration, type: ts.TypeNode): ts.PropertyDeclaration { + return ts.factory.updatePropertyDeclaration( + propDecl, + propDecl.modifiers, + propDecl.name, + propDecl.questionToken, + type, + ts.factory.createStringLiteral('') + ); + } + + private static createBuiltInTypeInitializer(type: ts.TypeReferenceNode): ts.Expression | undefined { + const typeName = type.typeName.getText(); + + switch (typeName) { + case 'Date': + return ts.factory.createNewExpression(ts.factory.createIdentifier('Date'), undefined, []); + case 'Map': + case 'Set': + return ts.factory.createNewExpression(ts.factory.createIdentifier(typeName), type.typeArguments, []); + case 'Promise': + return ts.factory.createIdentifier('undefined'); + default: + return this.isNullableType(type) ? ts.factory.createIdentifier('undefined') : undefined; + } + } + + private static isNullableType(type: ts.TypeNode): boolean { + if (type.kind === ts.SyntaxKind.UndefinedKeyword) { + return true; + } + + if (ts.isUnionTypeNode(type)) { + return type.types.some((t) => { + return t.kind === ts.SyntaxKind.UndefinedKeyword; + }); + } + + return false; + } + + private static createExactObjectInitializer(type: ts.TypeLiteralNode): ts.ObjectLiteralExpression { + const properties = type.members. + filter((member): member is ts.PropertySignature => { + return ts.isPropertySignature(member); + }). + map((member) => { + const initializer = Autofixer.createInitializerForPropertySignature(member); + if (initializer) { + return ts.factory.createPropertyAssignment(member.name, initializer); + } + return null; + }). + filter((property): property is ts.PropertyAssignment => { + return property !== null; + }); + + return ts.factory.createObjectLiteralExpression(properties, true); + } + + private static createInitializerForPropertySignature(member: ts.PropertySignature): ts.Expression | undefined { + return member.type ? Autofixer.createTypeBasedInitializer(member.type) : undefined; + } + + private static createTypeBasedInitializer(type?: ts.TypeNode): ts.Expression | undefined { + if (!type) { + return undefined; + } + + switch (type.kind) { + case ts.SyntaxKind.StringKeyword: + return ts.factory.createStringLiteral(''); + case ts.SyntaxKind.TypeLiteral: + return Autofixer.createExactObjectInitializer(type as ts.TypeLiteralNode); + case ts.SyntaxKind.ArrayType: + return ts.factory.createArrayLiteralExpression([], false); + case ts.SyntaxKind.TypeReference: + return Autofixer.createBuiltInTypeInitializer(type as ts.TypeReferenceNode); + default: + return this.isNullableType(type) ? ts.factory.createIdentifier('undefined') : undefined; + } + } + + private static isUserDefinedClass(type: ts.TypeReferenceNode): boolean { + const builtInTypes = new Set(['Date', 'Array', 'Map', 'Set', 'Promise', 'RegExp', 'Function']); + return !builtInTypes.has(type.typeName.getText()); + } + + fixGenericCallNoTypeArgs(node: ts.NewExpression): Autofix[] | undefined { + const typeNode = this.getTypeNodeForNewExpression(node); + if (!typeNode || !ts.isTypeReferenceNode(typeNode) || typeNode.typeName.getText() !== node.expression.getText()) { + return undefined; + } + + const reference: ts.TypeReferenceNode[] = []; + typeNode.typeArguments?.forEach((arg) => { + return reference.push(ts.factory.createTypeReferenceNode(arg.getText())); + }); + const srcFile = node.getSourceFile(); + const identifier = node.expression; + const args = node.arguments; + const newExpression = ts.factory.createNewExpression(identifier, reference, args); + const text = this.printer.printNode(ts.EmitHint.Unspecified, newExpression, srcFile); + return [{ start: node.getStart(), end: node.getEnd(), replacementText: text }]; + } + + private getTypeNodeForNewExpression(node: ts.NewExpression): ts.TypeNode | undefined { + if (ts.isVariableDeclaration(node.parent) || ts.isPropertyDeclaration(node.parent)) { + return node.parent.type; + } else if (ts.isBinaryExpression(node.parent)) { + return this.utils.getDeclarationTypeNode(node.parent.left); + } else if (ts.isReturnStatement(node.parent) && ts.isBlock(node.parent.parent)) { + const funcNode = node.parent.parent.parent; + const isFunc = ts.isFunctionDeclaration(funcNode) || ts.isMethodDeclaration(funcNode); + if (!isFunc || !funcNode.type) { + return undefined; + } + + const isAsync = TsUtils.hasModifier(funcNode.modifiers, ts.SyntaxKind.AsyncKeyword); + if (isAsync) { + if (ts.isTypeReferenceNode(funcNode.type) && funcNode.type.typeName.getText() === 'Promise') { + return funcNode.type?.typeArguments?.[0]; + } + } + return funcNode.type; + } + return undefined; + } + + fixMissingAttribute(node: ts.PropertyAccessExpression): Autofix[] { + const exprName = node.expression.getText(); + const propertyAccessExpr = ts.factory.createPropertyAccessExpression( + ts.factory.createIdentifier(exprName), + ts.factory.createIdentifier(METHOD_KEYS) + ); + const replacement = this.printer.printNode(ts.EmitHint.Unspecified, propertyAccessExpr, node.getSourceFile()); + return [{ start: node.getStart(), end: node.getEnd(), replacementText: replacement }]; + } + + fixBuilderDecorators(decorator: ts.Decorator): Autofix[] | undefined { + const newDecorator = ts.factory.createDecorator(ts.factory.createIdentifier('Builder')); + const text = this.printer.printNode(ts.EmitHint.Unspecified, newDecorator, decorator.getSourceFile()); + return [{ start: decorator.getStart(), end: decorator.getEnd(), replacementText: text }]; + } + + fixCustomLayout(node: ts.StructDeclaration): Autofix[] { + const startPos = Autofixer.getStartPositionWithoutDecorators(node); + const decorator = ts.factory.createDecorator(ts.factory.createIdentifier(CustomDecoratorName.Layoutable)); + + const text = this.getNewLine() + this.printer.printNode(ts.EmitHint.Unspecified, decorator, node.getSourceFile()); + return [{ start: startPos, end: startPos, replacementText: text }]; + } + + private static getStartPositionWithoutDecorators(node: ts.StructDeclaration): number { + const decorators = ts.getDecorators(node); + if (!decorators || decorators.length === 0) { + return node.getStart(); + } + + return decorators[decorators.length - 1].getEnd(); + } } diff --git a/ets2panda/linter/src/lib/autofixes/QuasiEditor.ts b/ets2panda/linter/src/lib/autofixes/QuasiEditor.ts index 3605f29a37..1d05ac4792 100644 --- a/ets2panda/linter/src/lib/autofixes/QuasiEditor.ts +++ b/ets2panda/linter/src/lib/autofixes/QuasiEditor.ts @@ -14,94 +14,109 @@ */ import * as fs from 'node:fs'; -import { Logger } from '../Logger'; import type * as ts from 'typescript'; +import { Logger } from '../Logger'; import type { ProblemInfo } from '../ProblemInfo'; import type { Autofix } from './Autofixer'; +import type { LinterOptions } from '../LinterOptions'; +import { AUTOFIX_HTML_TEMPLATE_TEXT, AutofixHtmlTemplate } from './AutofixReportHtmlHelper'; const BACKUP_AFFIX = '~'; -const EOL = '\n'; -export const MAX_AUTOFIX_PASSES = 10; +export const DEFAULT_MAX_AUTOFIX_PASSES = 10; export class QuasiEditor { - private textBuffer: string; - private readonly dataBuffer: Buffer; - private readonly srcFileName: string; - wasError: boolean = false; - constructor( - readonly sourceFile: ts.SourceFile, - readonly passNumber?: number, + readonly srcFileName: string, + readonly sourceText: string, + readonly linterOpts: LinterOptions, readonly cancellationToken?: ts.CancellationToken - ) { - this.srcFileName = this.sourceFile.fileName; + ) {} - /* - * need to backup only once "this.backupSrcFile();" - * load text into buffer - */ - this.dataBuffer = fs.readFileSync(this.srcFileName); - this.textBuffer = this.dataBuffer.toString(); - if (!passNumber) { - passNumber = 1; - } + private static getBackupFileName(filePath: string): string { + return filePath + BACKUP_AFFIX; } - backupSrcFile(): void { - fs.copyFileSync(this.srcFileName, this.srcFileName + BACKUP_AFFIX); + static backupSrcFile(filePath: string): void { + fs.copyFileSync(filePath, QuasiEditor.getBackupFileName(filePath)); } - backupSrcFileDebug(pass: number): void { - fs.copyFileSync(this.srcFileName, this.srcFileName + BACKUP_AFFIX + pass.toString()); + static hasAnyAutofixes(problemInfos: ProblemInfo[]): boolean { + return problemInfos.some((problemInfo) => { + return problemInfo.autofix !== undefined; + }); } - private saveText(): void { - fs.truncateSync(this.srcFileName); + private generateReport(acceptedPatches: Autofix[]): void { + const report = { + filePath: this.srcFileName, + fixCount: acceptedPatches.length, + fixes: acceptedPatches.map((fix) => { + return { + line: fix.line, + colum: fix.column, + endLine: fix.endLine, + endColum: fix.endColumn, + start: fix.start, + end: fix.end, + replacement: fix.replacementText, + original: this.sourceText.slice(fix.start, fix.end) + }; + }) + }; - const srcLines = this.textBuffer.split(EOL); - for (let i = 0; i < srcLines.length - 1; i++) { - fs.appendFileSync(this.srcFileName, srcLines[i] + EOL); - } - // check if last line is empty out of loop to optimize - if (srcLines[srcLines.length - 1] !== '') { - fs.appendFileSync(this.srcFileName, srcLines[srcLines.length - 1] + EOL); + const reportPath = './autofix-report.html'; + const getOldJsonArray = (reportPath: string): Set => { + try { + const RegexCaptureBraketFirst = 1; + const rawData = fs.readFileSync(reportPath, 'utf-8'); + const rawContent = rawData.match(/`([\s\S]*?)`/)?.[RegexCaptureBraketFirst] ?? ''; + return new Set(JSON.parse(rawContent) || []); + } catch { + return new Set(); + } + }; + + try { + const existingReports = getOldJsonArray(reportPath); + existingReports.add(report); + const str = JSON.stringify([...existingReports], null, 2); + const HtmlContent = AutofixHtmlTemplate.replace(AUTOFIX_HTML_TEMPLATE_TEXT, str); + fs.writeFileSync(reportPath, HtmlContent, { encoding: 'utf-8' }); + } catch (error) { + Logger.error(`Failed to update autofix report: ${(error as Error).message}`); } } - private static hasAnyAutofixes(problemInfos: ProblemInfo[]): boolean { - return problemInfos.some((problemInfo) => { - return problemInfo.autofix !== undefined; - }); - } + fix(problemInfos: ProblemInfo[]): string { + const acceptedPatches = QuasiEditor.sortAndRemoveIntersections(problemInfos); + const result = this.applyFixes(acceptedPatches); - fix(problemInfos: ProblemInfo[]): void { - if (!QuasiEditor.hasAnyAutofixes(problemInfos)) { - return; + if (this.linterOpts.migrationReport) { + this.generateReport(acceptedPatches); } - const acceptedPatches = QuasiEditor.sortAndRemoveIntersections(problemInfos); - this.textBuffer = this.applyFixes(acceptedPatches); - this.saveText(); + + return result; } private applyFixes(autofixes: Autofix[]): string { let output: string = ''; - let lastPos = Number.NEGATIVE_INFINITY; + let lastFixEnd = Number.NEGATIVE_INFINITY; const doFix = (fix: Autofix): void => { const { replacementText, start, end } = fix; - if (lastPos >= start || start > end) { + if (lastFixEnd > start || start > end) { Logger.error(`Failed to apply autofix in range [${start}, ${end}] at ${this.srcFileName}`); return; } - output += this.textBuffer.slice(Math.max(0, lastPos), Math.max(0, start)); + output += this.sourceText.slice(Math.max(0, lastFixEnd), Math.max(0, start)); output += replacementText; - lastPos = end; + lastFixEnd = end; }; autofixes.forEach(doFix); - output += this.textBuffer.slice(Math.max(0, lastPos)); + output += this.sourceText.slice(Math.max(0, lastFixEnd)); return output; } @@ -109,7 +124,7 @@ export class QuasiEditor { private static sortAndRemoveIntersections(problemInfos: ProblemInfo[]): Autofix[] { let acceptedPatches: Autofix[] = []; - problemInfos.forEach((problemInfo) => { + problemInfos.forEach((problemInfo): void => { if (!problemInfo.autofix) { return; } @@ -127,7 +142,7 @@ export class QuasiEditor { } private static sortAutofixes(autofixes: Autofix[]): Autofix[] { - return autofixes.sort((a, b) => { + return autofixes.sort((a, b): number => { return a.start - b.start; }); } diff --git a/ets2panda/linter/src/lib/autofixes/SymbolCache.ts b/ets2panda/linter/src/lib/autofixes/SymbolCache.ts index 9a16be4fd0..7724bce448 100644 --- a/ets2panda/linter/src/lib/autofixes/SymbolCache.ts +++ b/ets2panda/linter/src/lib/autofixes/SymbolCache.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2024 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -14,7 +14,7 @@ */ import * as ts from 'typescript'; -import { LinterConfig } from '../TypeScriptLinterConfig'; +import { TypeScriptLinterConfig } from '../TypeScriptLinterConfig'; import { forEachNodeInSubtree } from '../utils/functions/ForEachNodeInSubtree'; import { isStructDeclaration } from '../utils/functions/IsStruct'; import type { TsUtils } from '../utils/TsUtils'; @@ -39,7 +39,7 @@ export class SymbolCache { }; const stopCondition = (node: ts.Node): boolean => { - return !node || LinterConfig.terminalTokens.has(node.kind); + return !node || TypeScriptLinterConfig.terminalTokens.has(node.kind); }; forEachNodeInSubtree(sourceFile, callback, stopCondition); diff --git a/ets2panda/linter/src/lib/data/BuiltinList.json b/ets2panda/linter/src/lib/data/BuiltinList.json new file mode 100644 index 0000000000..3ba53f2cbb --- /dev/null +++ b/ets2panda/linter/src/lib/data/BuiltinList.json @@ -0,0 +1,4631 @@ +{ + "api_list": [ + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 107, + "problem": "BuiltinAll", + "api_name": "PropertyKey", + "api_type": "TypeAliasDeclaration", + "api_func_args": [], + "parent_api": [], + "code_kind": 268, + "api_property_type": "string | number | symbol" + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 110, + "problem": "NoPropertyDescriptor", + "api_name": "configurable", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "PropertyDescriptor", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "boolean" + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 111, + "problem": "NoPropertyDescriptor", + "api_name": "enumerable", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "PropertyDescriptor", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "boolean" + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 112, + "problem": "NoPropertyDescriptor", + "api_name": "value", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "PropertyDescriptor", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "any" + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 113, + "problem": "NoPropertyDescriptor", + "api_name": "writable", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "PropertyDescriptor", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "boolean" + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 114, + "problem": "NoPropertyDescriptor", + "api_name": "get", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [], + "parent_api": [ + { + "api_name": "PropertyDescriptor", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "any", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 115, + "problem": "NoPropertyDescriptor", + "api_name": "set", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "v", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "PropertyDescriptor", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 133, + "problem": "BuiltinAll", + "api_name": "valueOf", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [], + "parent_api": [ + { + "api_name": "Object", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "Object", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 174, + "problem": "MissingAttributes", + "api_name": "getOwnPropertyNames", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [], + "parent_api": [ + { + "api_name": "ObjectConstructor", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "string[]", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 156, + "problem": "BuiltinAll", + "api_type": "CallSignature", + "parent_api": [ + { + "api_name": "ObjectConstructor", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 179 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 157, + "problem": "BuiltinAll", + "api_type": "CallSignature", + "parent_api": [ + { + "api_name": "ObjectConstructor", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 179 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 392, + "problem": "BuiltinAll", + "api_name": "length", + "api_type": "PropertySignature", + "api_optional": false, + "parent_api": [ + { + "api_name": "IArguments", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "number" + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 393, + "problem": "BuiltinAll", + "api_name": "callee", + "api_type": "PropertySignature", + "api_optional": false, + "parent_api": [ + { + "api_name": "IArguments", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "Function" + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 522, + "problem": "BuiltinNoCtorFunc", + "api_type": "CallSignature", + "parent_api": [ + { + "api_name": "StringConstructor", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 179 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 539, + "problem": "BuiltinNoCtorFunc", + "api_type": "CallSignature", + "parent_api": [ + { + "api_name": "BooleanConstructor", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 179 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 576, + "problem": "BuiltinNoCtorFunc", + "api_type": "CallSignature", + "parent_api": [ + { + "api_name": "NumberConstructor", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 179 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 608, + "problem": "BuiltinAll", + "api_name": "raw", + "api_type": "PropertySignature", + "api_optional": false, + "parent_api": [ + { + "api_name": "TemplateStringsArray", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "readonly string[]" + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 916, + "problem": "BuiltinNoCtorFunc", + "api_type": "CallSignature", + "parent_api": [ + { + "api_name": "DateConstructor", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 179 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1005, + "problem": "BuiltinNoCtorFunc", + "api_type": "CallSignature", + "parent_api": [ + { + "api_name": "RegExpConstructor", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 179 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1006, + "problem": "BuiltinNoCtorFunc", + "api_type": "CallSignature", + "parent_api": [ + { + "api_name": "RegExpConstructor", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 179 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1060, + "problem": "BuiltinNoCtorFunc", + "api_type": "CallSignature", + "parent_api": [ + { + "api_name": "ErrorConstructor", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 179 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1071, + "problem": "BuiltinNoCtorFunc", + "api_type": "CallSignature", + "parent_api": [ + { + "api_name": "EvalErrorConstructor", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 179 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1082, + "problem": "BuiltinNoCtorFunc", + "api_type": "CallSignature", + "parent_api": [ + { + "api_name": "RangeErrorConstructor", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 179 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1093, + "problem": "BuiltinNoCtorFunc", + "api_type": "CallSignature", + "parent_api": [ + { + "api_name": "ReferenceErrorConstructor", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 179 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1104, + "problem": "BuiltinNoCtorFunc", + "api_type": "CallSignature", + "parent_api": [ + { + "api_name": "SyntaxErrorConstructor", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 179 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1115, + "problem": "BuiltinNoCtorFunc", + "api_type": "CallSignature", + "parent_api": [ + { + "api_name": "TypeErrorConstructor", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 179 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1126, + "problem": "BuiltinNoCtorFunc", + "api_type": "CallSignature", + "parent_api": [ + { + "api_name": "URIErrorConstructor", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 179 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1139, + "problem": "BuiltinAll", + "api_name": "parse", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "text", + "type": "string", + "is_optional": false, + "has_default": false + }, + { + "name": "reviver", + "type": "(this: any, key: string, value: any) => any", + "is_optional": true, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "JSON", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "any", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1188, + "problem": "BuiltinAll", + "api_name": "concat", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "items", + "type": "(T | ConcatArray)[]", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "ReadonlyArray", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "T[]", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1220, + "problem": "ThisArg", + "api_name": "every", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: T, index: number, array: readonly T[]) => value is S", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "ReadonlyArray", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "boolean", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1229, + "problem": "ThisArg", + "api_name": "every", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: T, index: number, array: readonly T[]) => unknown", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "ReadonlyArray", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "boolean", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1238, + "problem": "ThisArg", + "api_name": "some", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: T, index: number, array: readonly T[]) => unknown", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "ReadonlyArray", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "boolean", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1244, + "problem": "ThisArg", + "api_name": "forEach", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "callbackfn", + "type": "(value: T, index: number, array: readonly T[]) => void", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "ReadonlyArray", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1250, + "problem": "ThisArg", + "api_name": "map", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "callbackfn", + "type": "(value: T, index: number, array: readonly T[]) => U", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "ReadonlyArray", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "U[]", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1256, + "problem": "ThisArg", + "api_name": "filter", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: T, index: number, array: readonly T[]) => value is S", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "ReadonlyArray", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "S[]", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1262, + "problem": "ThisArg", + "api_name": "filter", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: T, index: number, array: readonly T[]) => unknown", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "ReadonlyArray", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "T[]", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1304, + "problem": "BuiltinAll", + "api_name": "length", + "api_type": "PropertySignature", + "api_optional": false, + "parent_api": [ + { + "api_name": "Array", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "number" + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1334, + "problem": "BuiltinAll", + "api_name": "concat", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "items", + "type": "(T | ConcatArray)[]", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "T[]", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1411, + "problem": "ThisArg", + "api_name": "every", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: T, index: number, array: T[]) => value is S", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "boolean", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1420, + "problem": "ThisArg", + "api_name": "every", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: T, index: number, array: T[]) => unknown", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "boolean", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1429, + "problem": "ThisArg", + "api_name": "some", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: T, index: number, array: T[]) => unknown", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "boolean", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1435, + "problem": "ThisArg", + "api_name": "forEach", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "callbackfn", + "type": "(value: T, index: number, array: T[]) => void", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1441, + "problem": "ThisArg", + "api_name": "map", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "callbackfn", + "type": "(value: T, index: number, array: T[]) => U", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "U[]", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1453, + "problem": "ThisArg", + "api_name": "filter", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: T, index: number, array: T[]) => unknown", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "T[]", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1490, + "problem": "BuiltinNoCtorFunc", + "api_type": "CallSignature", + "parent_api": [ + { + "api_name": "ArrayConstructor", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 179 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1498, + "problem": "NoPropertyDescriptor", + "api_name": "enumerable", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "TypedPropertyDescriptor", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "boolean" + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1499, + "problem": "NoPropertyDescriptor", + "api_name": "configurable", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "TypedPropertyDescriptor", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "boolean" + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1500, + "problem": "NoPropertyDescriptor", + "api_name": "writable", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "TypedPropertyDescriptor", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "boolean" + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1501, + "problem": "NoPropertyDescriptor", + "api_name": "value", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "TypedPropertyDescriptor", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "T" + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1502, + "problem": "NoPropertyDescriptor", + "api_name": "get", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "TypedPropertyDescriptor", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "() => T" + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1503, + "problem": "NoPropertyDescriptor", + "api_name": "set", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "TypedPropertyDescriptor", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "(value: T) => void" + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1506, + "problem": "BuiltinAll", + "api_name": "ClassDecorator", + "api_type": "TypeAliasDeclaration", + "api_func_args": [ + { + "name": "target", + "type": "TFunction", + "is_optional": false + } + ], + "parent_api": [], + "method_return_type": "TFunction | void", + "code_kind": 268 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1507, + "problem": "BuiltinAll", + "api_name": "PropertyDecorator", + "api_type": "TypeAliasDeclaration", + "api_func_args": [ + { + "name": "target", + "type": "Object", + "is_optional": false + }, + { + "name": "propertyKey", + "type": "string | symbol", + "is_optional": false + } + ], + "parent_api": [], + "method_return_type": "void", + "code_kind": 268 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1508, + "problem": "NoPropertyDescriptor", + "api_name": "MethodDecorator", + "api_type": "TypeAliasDeclaration", + "api_func_args": [ + { + "name": "target", + "type": "Object", + "is_optional": false + }, + { + "name": "propertyKey", + "type": "string | symbol", + "is_optional": false + }, + { + "name": "descriptor", + "type": "TypedPropertyDescriptor", + "is_optional": false + } + ], + "parent_api": [], + "method_return_type": "TypedPropertyDescriptor | void", + "code_kind": 268 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1509, + "problem": "BuiltinAll", + "api_name": "ParameterDecorator", + "api_type": "TypeAliasDeclaration", + "api_func_args": [ + { + "name": "target", + "type": "Object", + "is_optional": false + }, + { + "name": "propertyKey", + "type": "string | symbol", + "is_optional": false + }, + { + "name": "parameterIndex", + "type": "number", + "is_optional": false + } + ], + "parent_api": [], + "method_return_type": "void", + "code_kind": 268 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1681, + "problem": "BuiltinAll", + "api_name": "ArrayBuffer", + "api_type": "PropertySignature", + "api_optional": false, + "parent_api": [ + { + "api_name": "ArrayBufferTypes", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "ArrayBuffer" + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1887, + "problem": "ThisArg", + "api_name": "every", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, array: Int8Array) => unknown", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Int8Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "boolean", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1906, + "problem": "ThisArg", + "api_name": "filter", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, array: Int8Array) => any", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Int8Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "Int8Array", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1917, + "problem": "ThisArg", + "api_name": "find", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, obj: Int8Array) => boolean", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Int8Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "number | undefined", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1928, + "problem": "ThisArg", + "api_name": "findIndex", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, obj: Int8Array) => boolean", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Int8Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "number", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1937, + "problem": "ThisArg", + "api_name": "forEach", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "callbackfn", + "type": "(value: number, index: number, array: Int8Array) => void", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Int8Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 1975, + "problem": "ThisArg", + "api_name": "map", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "callbackfn", + "type": "(value: number, index: number, array: Int8Array) => number", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Int8Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "Int8Array", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 2054, + "problem": "ThisArg", + "api_name": "some", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, array: Int8Array) => unknown", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Int8Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "boolean", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 2169, + "problem": "ThisArg", + "api_name": "every", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, array: Uint8Array) => unknown", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Uint8Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "boolean", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 2188, + "problem": "ThisArg", + "api_name": "filter", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, array: Uint8Array) => any", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Uint8Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "Uint8Array", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 2199, + "problem": "ThisArg", + "api_name": "find", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, obj: Uint8Array) => boolean", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Uint8Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "number | undefined", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 2210, + "problem": "ThisArg", + "api_name": "findIndex", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, obj: Uint8Array) => boolean", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Uint8Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "number", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 2219, + "problem": "ThisArg", + "api_name": "forEach", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "callbackfn", + "type": "(value: number, index: number, array: Uint8Array) => void", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Uint8Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 2257, + "problem": "ThisArg", + "api_name": "map", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "callbackfn", + "type": "(value: number, index: number, array: Uint8Array) => number", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Uint8Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "Uint8Array", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 2336, + "problem": "ThisArg", + "api_name": "some", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, array: Uint8Array) => unknown", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Uint8Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "boolean", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 2451, + "problem": "ThisArg", + "api_name": "every", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, array: Uint8ClampedArray) => unknown", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Uint8ClampedArray", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "boolean", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 2470, + "problem": "ThisArg", + "api_name": "filter", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, array: Uint8ClampedArray) => any", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Uint8ClampedArray", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "Uint8ClampedArray", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 2481, + "problem": "ThisArg", + "api_name": "find", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, obj: Uint8ClampedArray) => boolean", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Uint8ClampedArray", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "number | undefined", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 2492, + "problem": "ThisArg", + "api_name": "findIndex", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, obj: Uint8ClampedArray) => boolean", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Uint8ClampedArray", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "number", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 2501, + "problem": "ThisArg", + "api_name": "forEach", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "callbackfn", + "type": "(value: number, index: number, array: Uint8ClampedArray) => void", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Uint8ClampedArray", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 2539, + "problem": "ThisArg", + "api_name": "map", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "callbackfn", + "type": "(value: number, index: number, array: Uint8ClampedArray) => number", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Uint8ClampedArray", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "Uint8ClampedArray", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 2618, + "problem": "ThisArg", + "api_name": "some", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, array: Uint8ClampedArray) => unknown", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Uint8ClampedArray", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "boolean", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 2732, + "problem": "ThisArg", + "api_name": "every", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, array: Int16Array) => unknown", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Int16Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "boolean", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 2751, + "problem": "ThisArg", + "api_name": "filter", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, array: Int16Array) => any", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Int16Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "Int16Array", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 2762, + "problem": "ThisArg", + "api_name": "find", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, obj: Int16Array) => boolean", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Int16Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "number | undefined", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 2773, + "problem": "ThisArg", + "api_name": "findIndex", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, obj: Int16Array) => boolean", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Int16Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "number", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 2782, + "problem": "ThisArg", + "api_name": "forEach", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "callbackfn", + "type": "(value: number, index: number, array: Int16Array) => void", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Int16Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 2819, + "problem": "ThisArg", + "api_name": "map", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "callbackfn", + "type": "(value: number, index: number, array: Int16Array) => number", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Int16Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "Int16Array", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 2898, + "problem": "ThisArg", + "api_name": "some", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, array: Int16Array) => unknown", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Int16Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "boolean", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 3014, + "problem": "ThisArg", + "api_name": "every", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, array: Uint16Array) => unknown", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Uint16Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "boolean", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 3033, + "problem": "ThisArg", + "api_name": "filter", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, array: Uint16Array) => any", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Uint16Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "Uint16Array", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 3044, + "problem": "ThisArg", + "api_name": "find", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, obj: Uint16Array) => boolean", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Uint16Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "number | undefined", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 3055, + "problem": "ThisArg", + "api_name": "findIndex", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, obj: Uint16Array) => boolean", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Uint16Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "number", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 3064, + "problem": "ThisArg", + "api_name": "forEach", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "callbackfn", + "type": "(value: number, index: number, array: Uint16Array) => void", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Uint16Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 3102, + "problem": "ThisArg", + "api_name": "map", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "callbackfn", + "type": "(value: number, index: number, array: Uint16Array) => number", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Uint16Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "Uint16Array", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 3181, + "problem": "ThisArg", + "api_name": "some", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, array: Uint16Array) => unknown", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Uint16Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "boolean", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 3296, + "problem": "ThisArg", + "api_name": "every", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, array: Int32Array) => unknown", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Int32Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "boolean", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 3315, + "problem": "ThisArg", + "api_name": "filter", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, array: Int32Array) => any", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Int32Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "Int32Array", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 3326, + "problem": "ThisArg", + "api_name": "find", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, obj: Int32Array) => boolean", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Int32Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "number | undefined", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 3337, + "problem": "ThisArg", + "api_name": "findIndex", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, obj: Int32Array) => boolean", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Int32Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "number", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 3346, + "problem": "ThisArg", + "api_name": "forEach", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "callbackfn", + "type": "(value: number, index: number, array: Int32Array) => void", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Int32Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 3384, + "problem": "ThisArg", + "api_name": "map", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "callbackfn", + "type": "(value: number, index: number, array: Int32Array) => number", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Int32Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "Int32Array", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 3463, + "problem": "ThisArg", + "api_name": "some", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, array: Int32Array) => unknown", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Int32Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "boolean", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 3578, + "problem": "ThisArg", + "api_name": "every", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, array: Uint32Array) => unknown", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Uint32Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "boolean", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 3597, + "problem": "ThisArg", + "api_name": "filter", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, array: Uint32Array) => any", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Uint32Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "Uint32Array", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 3608, + "problem": "ThisArg", + "api_name": "find", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, obj: Uint32Array) => boolean", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Uint32Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "number | undefined", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 3619, + "problem": "ThisArg", + "api_name": "findIndex", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, obj: Uint32Array) => boolean", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Uint32Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "number", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 3628, + "problem": "ThisArg", + "api_name": "forEach", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "callbackfn", + "type": "(value: number, index: number, array: Uint32Array) => void", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Uint32Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 3665, + "problem": "ThisArg", + "api_name": "map", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "callbackfn", + "type": "(value: number, index: number, array: Uint32Array) => number", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Uint32Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "Uint32Array", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 3744, + "problem": "ThisArg", + "api_name": "some", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, array: Uint32Array) => unknown", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Uint32Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "boolean", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 3859, + "problem": "ThisArg", + "api_name": "every", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, array: Float32Array) => unknown", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Float32Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "boolean", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 3878, + "problem": "ThisArg", + "api_name": "filter", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, array: Float32Array) => any", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Float32Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "Float32Array", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 3889, + "problem": "ThisArg", + "api_name": "find", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, obj: Float32Array) => boolean", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Float32Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "number | undefined", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 3900, + "problem": "ThisArg", + "api_name": "findIndex", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, obj: Float32Array) => boolean", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Float32Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "number", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 3909, + "problem": "ThisArg", + "api_name": "forEach", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "callbackfn", + "type": "(value: number, index: number, array: Float32Array) => void", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Float32Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 3947, + "problem": "ThisArg", + "api_name": "map", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "callbackfn", + "type": "(value: number, index: number, array: Float32Array) => number", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Float32Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "Float32Array", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 4026, + "problem": "ThisArg", + "api_name": "some", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, array: Float32Array) => unknown", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Float32Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "boolean", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 4142, + "problem": "ThisArg", + "api_name": "every", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, array: Float64Array) => unknown", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Float64Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "boolean", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 4161, + "problem": "ThisArg", + "api_name": "filter", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, array: Float64Array) => any", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Float64Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "Float64Array", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 4172, + "problem": "ThisArg", + "api_name": "find", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, obj: Float64Array) => boolean", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Float64Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "number | undefined", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 4183, + "problem": "ThisArg", + "api_name": "findIndex", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, obj: Float64Array) => boolean", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Float64Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "number", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 4192, + "problem": "ThisArg", + "api_name": "forEach", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "callbackfn", + "type": "(value: number, index: number, array: Float64Array) => void", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Float64Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 4230, + "problem": "ThisArg", + "api_name": "map", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "callbackfn", + "type": "(value: number, index: number, array: Float64Array) => number", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Float64Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "Float64Array", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 4309, + "problem": "ThisArg", + "api_name": "some", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: number, index: number, array: Float64Array) => unknown", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Float64Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "boolean", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 4439, + "problem": "BuiltinAll", + "api_name": "prototype", + "api_type": "PropertySignature", + "api_optional": false, + "parent_api": [ + { + "api_name": "Intl", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "NumberFormat" + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es5.d.ts", + "api_info": { + "line": 4483, + "problem": "BuiltinAll", + "api_name": "prototype", + "api_type": "PropertySignature", + "api_optional": false, + "parent_api": [ + { + "api_name": "Intl", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "DateTimeFormat" + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2015.iterable.d.ts", + "api_info": { + "line": 46, + "problem": "BuiltinAll", + "api_name": "return", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "value", + "type": "TReturn", + "is_optional": true, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Iterator", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "IteratorResult", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2015.iterable.d.ts", + "api_info": { + "line": 47, + "problem": "BuiltinAll", + "api_name": "throw", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "e", + "type": "any", + "is_optional": true, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Iterator", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "IteratorResult", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2015.iterable.d.ts", + "api_info": { + "line": 51, + "problem": "SymbolIterator", + "api_name": "[Symbol.iterator]", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [], + "parent_api": [ + { + "api_name": "Iterable", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "Iterator", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2015.iterable.d.ts", + "api_info": { + "line": 55, + "problem": "SymbolIterator", + "api_name": "[Symbol.iterator]", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [], + "parent_api": [ + { + "api_name": "IterableIterator", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "IterableIterator", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2015.iterable.d.ts", + "api_info": { + "line": 60, + "problem": "SymbolIterator", + "api_name": "[Symbol.iterator]", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [], + "parent_api": [ + { + "api_name": "Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "IterableIterator", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2015.iterable.d.ts", + "api_info": { + "line": 96, + "problem": "SymbolIterator", + "api_name": "[Symbol.iterator]", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [], + "parent_api": [ + { + "api_name": "ReadonlyArray", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "IterableIterator", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2015.iterable.d.ts", + "api_info": { + "line": 116, + "problem": "SymbolIterator", + "api_name": "[Symbol.iterator]", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [], + "parent_api": [ + { + "api_name": "IArguments", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "IterableIterator", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2015.iterable.d.ts", + "api_info": { + "line": 121, + "problem": "SymbolIterator", + "api_name": "[Symbol.iterator]", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [], + "parent_api": [ + { + "api_name": "Map", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "IterableIterator<[K, V]>", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2015.iterable.d.ts", + "api_info": { + "line": 141, + "problem": "SymbolIterator", + "api_name": "[Symbol.iterator]", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [], + "parent_api": [ + { + "api_name": "ReadonlyMap", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "IterableIterator<[K, V]>", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2015.iterable.d.ts", + "api_info": { + "line": 172, + "problem": "SymbolIterator", + "api_name": "[Symbol.iterator]", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [], + "parent_api": [ + { + "api_name": "Set", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "IterableIterator", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2015.iterable.d.ts", + "api_info": { + "line": 190, + "problem": "SymbolIterator", + "api_name": "[Symbol.iterator]", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [], + "parent_api": [ + { + "api_name": "ReadonlySet", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "IterableIterator", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2015.iterable.d.ts", + "api_info": { + "line": 240, + "problem": "SymbolIterator", + "api_name": "[Symbol.iterator]", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [], + "parent_api": [ + { + "api_name": "String", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "IterableIterator", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2015.iterable.d.ts", + "api_info": { + "line": 244, + "problem": "SymbolIterator", + "api_name": "[Symbol.iterator]", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [], + "parent_api": [ + { + "api_name": "Int8Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "IterableIterator", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2015.iterable.d.ts", + "api_info": { + "line": 272, + "problem": "SymbolIterator", + "api_name": "[Symbol.iterator]", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [], + "parent_api": [ + { + "api_name": "Uint8Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "IterableIterator", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2015.iterable.d.ts", + "api_info": { + "line": 300, + "problem": "SymbolIterator", + "api_name": "[Symbol.iterator]", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [], + "parent_api": [ + { + "api_name": "Uint8ClampedArray", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "IterableIterator", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2015.iterable.d.ts", + "api_info": { + "line": 331, + "problem": "SymbolIterator", + "api_name": "[Symbol.iterator]", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [], + "parent_api": [ + { + "api_name": "Int16Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "IterableIterator", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2015.iterable.d.ts", + "api_info": { + "line": 361, + "problem": "SymbolIterator", + "api_name": "[Symbol.iterator]", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [], + "parent_api": [ + { + "api_name": "Uint16Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "IterableIterator", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2015.iterable.d.ts", + "api_info": { + "line": 389, + "problem": "SymbolIterator", + "api_name": "[Symbol.iterator]", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [], + "parent_api": [ + { + "api_name": "Int32Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "IterableIterator", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2015.iterable.d.ts", + "api_info": { + "line": 417, + "problem": "SymbolIterator", + "api_name": "[Symbol.iterator]", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [], + "parent_api": [ + { + "api_name": "Uint32Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "IterableIterator", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2015.iterable.d.ts", + "api_info": { + "line": 445, + "problem": "SymbolIterator", + "api_name": "[Symbol.iterator]", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [], + "parent_api": [ + { + "api_name": "Float32Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "IterableIterator", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2015.iterable.d.ts", + "api_info": { + "line": 473, + "problem": "SymbolIterator", + "api_name": "[Symbol.iterator]", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [], + "parent_api": [ + { + "api_name": "Float64Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "IterableIterator", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2020.bigint.d.ts", + "api_info": { + "line": 126, + "problem": "BuiltinNoCtorFunc", + "api_type": "CallSignature", + "parent_api": [ + { + "api_name": "BigIntConstructor", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 179 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2020.bigint.d.ts", + "api_info": { + "line": 186, + "problem": "ThisArg", + "api_name": "every", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: bigint, index: number, array: BigInt64Array) => boolean", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "BigInt64Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "boolean", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2020.bigint.d.ts", + "api_info": { + "line": 205, + "problem": "ThisArg", + "api_name": "filter", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: bigint, index: number, array: BigInt64Array) => any", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "BigInt64Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "BigInt64Array", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2020.bigint.d.ts", + "api_info": { + "line": 216, + "problem": "ThisArg", + "api_name": "find", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: bigint, index: number, array: BigInt64Array) => boolean", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "BigInt64Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "bigint | undefined", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2020.bigint.d.ts", + "api_info": { + "line": 227, + "problem": "ThisArg", + "api_name": "findIndex", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: bigint, index: number, array: BigInt64Array) => boolean", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "BigInt64Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "number", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2020.bigint.d.ts", + "api_info": { + "line": 236, + "problem": "ThisArg", + "api_name": "forEach", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "callbackfn", + "type": "(value: bigint, index: number, array: BigInt64Array) => void", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "BigInt64Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2020.bigint.d.ts", + "api_info": { + "line": 282, + "problem": "ThisArg", + "api_name": "map", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "callbackfn", + "type": "(value: bigint, index: number, array: BigInt64Array) => bigint", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "BigInt64Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "BigInt64Array", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2020.bigint.d.ts", + "api_info": { + "line": 357, + "problem": "ThisArg", + "api_name": "some", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: bigint, index: number, array: BigInt64Array) => boolean", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "BigInt64Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "boolean", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2020.bigint.d.ts", + "api_info": { + "line": 385, + "problem": "SymbolIterator", + "api_name": "[Symbol.iterator]", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [], + "parent_api": [ + { + "api_name": "BigInt64Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "IterableIterator", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2020.bigint.d.ts", + "api_info": { + "line": 458, + "problem": "ThisArg", + "api_name": "every", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: bigint, index: number, array: BigUint64Array) => boolean", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "BigUint64Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "boolean", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2020.bigint.d.ts", + "api_info": { + "line": 477, + "problem": "ThisArg", + "api_name": "filter", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: bigint, index: number, array: BigUint64Array) => any", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "BigUint64Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "BigUint64Array", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2020.bigint.d.ts", + "api_info": { + "line": 488, + "problem": "ThisArg", + "api_name": "find", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: bigint, index: number, array: BigUint64Array) => boolean", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "BigUint64Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "bigint | undefined", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2020.bigint.d.ts", + "api_info": { + "line": 499, + "problem": "ThisArg", + "api_name": "findIndex", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: bigint, index: number, array: BigUint64Array) => boolean", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "BigUint64Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "number", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2020.bigint.d.ts", + "api_info": { + "line": 508, + "problem": "ThisArg", + "api_name": "forEach", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "callbackfn", + "type": "(value: bigint, index: number, array: BigUint64Array) => void", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "BigUint64Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2020.bigint.d.ts", + "api_info": { + "line": 554, + "problem": "ThisArg", + "api_name": "map", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "callbackfn", + "type": "(value: bigint, index: number, array: BigUint64Array) => bigint", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "BigUint64Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "BigUint64Array", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2020.bigint.d.ts", + "api_info": { + "line": 629, + "problem": "ThisArg", + "api_name": "some", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "predicate", + "type": "(value: bigint, index: number, array: BigUint64Array) => boolean", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "BigUint64Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "boolean", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2020.bigint.d.ts", + "api_info": { + "line": 657, + "problem": "SymbolIterator", + "api_name": "[Symbol.iterator]", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [], + "parent_api": [ + { + "api_name": "BigUint64Array", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "IterableIterator", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2015.collection.d.ts", + "api_info": { + "line": 31, + "problem": "ThisArg", + "api_name": "forEach", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "callbackfn", + "type": "(value: V, key: K, map: Map) => void", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Map", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2015.collection.d.ts", + "api_info": { + "line": 59, + "problem": "ThisArg", + "api_name": "forEach", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "callbackfn", + "type": "(value: V, key: K, map: ReadonlyMap) => void", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "ReadonlyMap", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2015.collection.d.ts", + "api_info": { + "line": 107, + "problem": "ThisArg", + "api_name": "forEach", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "callbackfn", + "type": "(value: T, value2: T, set: Set) => void", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "Set", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "lib.es2015.collection.d.ts", + "api_info": { + "line": 125, + "problem": "ThisArg", + "api_name": "forEach", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "callbackfn", + "type": "(value: T, value2: T, set: ReadonlySet) => void", + "is_optional": false, + "has_default": false + }, + { + "name": "thisArg", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "ReadonlySet", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/src/lib/data/SdkWhitelist.json b/ets2panda/linter/src/lib/data/SdkWhitelist.json index 8aee8281b8..b0c83d5696 100644 --- a/ets2panda/linter/src/lib/data/SdkWhitelist.json +++ b/ets2panda/linter/src/lib/data/SdkWhitelist.json @@ -1,41 +1,21 @@ { "api_list": [ { - "import_path": ["@ohos.arkui.Prefetcher", "@kit.ArkUI"], - "file_path": ["api/@ohos.arkui.Prefetcher.d.ts"], - "is_global": false, + "file_path": "api/@hms.collaboration.rcp.d.ts", "api_info": { - "problem": "", - "api_name": "prefetch", + "line": 84, + "problem": "LimitedVoidType", + "api_name": "write", "api_type": "MethodSignature", "api_optional": false, - "api_auto_fix": false, - "api_auto_fix_context": "", - "target_type": "", - "api_func_args": [{ "name": "index", "type": "number", "is_optional": false, "hasDefault": false }], - "parent_api": [ + "api_func_args": [ { - "api_name": "IDataSourcePrefetching", - "api_type": "InterfaceDeclaration" + "name": "buffer", + "type": "ArrayBuffer", + "is_optional": false, + "has_default": false } ], - "methd_return_type": "void | Promise", - "codeKind": 173 - } - }, - { - "import_path": ["@hms.collaboration.rcp", "@kit.RemoteCommunicationKit"], - "file_path": ["api/@hms.collaboration.rcp.d.ts"], - "is_global": false, - "api_info": { - "problem": "LimitiedVoidType", - "api_name": "write", - "api_type": "MethodSignature", - "api_optional": false, - "api_auto_fix": false, - "api_auto_fix_context": "", - "target_type": "", - "api_func_args": [{ "name": "buffer", "type": "ArrayBuffer", "is_optional": false, "hasDefault": false }], "parent_api": [ { "api_name": "WriteFile", @@ -46,250 +26,226 @@ "api_type": "ModuleDeclaration" } ], - "methd_return_type": "void | Promise", - "codeKind": 115 - } + "method_return_type": "Promise", + "code_kind": 173 + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false }, { - "import_path": ["@hms.collaboration.rcp", "@kit.RemoteCommunicationKit"], - "file_path": ["api/@hms.collaboration.rcp.d.ts"], - "is_global": false, + "file_path": "api/@hms.collaboration.rcp.d.ts", "api_info": { - "problem": "LimitiedVoidType", - "api_name": "IncomingDataCallback", - "api_type": "TypeAliasDeclaration", + "line": 116, + "problem": "LimitedVoidType", + "api_name": "write", + "api_type": "MethodSignature", "api_optional": false, - "api_auto_fix": false, - "api_auto_fix_context": "", - "target_type": "", - "api_func_args": [{ "name": "incomingData", "type": "ArrayBuffer", "is_optional": false, "hasDefault": false }], - "parent_api": [ + "api_func_args": [ { - "api_name": "rcp", - "api_type": "ModuleDeclaration" + "name": "buffer", + "type": "ArrayBuffer", + "is_optional": false, + "has_default": false } ], - "methd_return_type": "void | Promise", - "codeKind": 115 - } - }, - { - "import_path": ["@ohos.web.webview", "@kit.ArkWeb"], - "file_path": ["api/@ohos.web.webview.d.ts"], - "is_global": false, - "api_info": { - "problem": "OptionalMethod", - "api_name": "resumePlayer", - "api_type": "MethodSignature", - "api_optional": true, - "api_auto_fix": false, - "api_auto_fix_context": "", - "target_type": "", - "api_func_args": [], "parent_api": [ { - "api_name": "NativeMediaPlayerBridge", + "api_name": "WriteStream", "api_type": "InterfaceDeclaration" }, { - "api_name": "webview", + "api_name": "rcp", "api_type": "ModuleDeclaration" } ], - "methd_return_type": "void", - "codeKind": 173 - } + "method_return_type": "Promise", + "code_kind": 173 + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false }, { - "import_path": ["@ohos.web.webview", "@kit.ArkWeb"], - "file_path": ["api/@ohos.web.webview.d.ts"], - "is_global": false, + "file_path": "api/@hms.collaboration.rcp.d.ts", "api_info": { - "problem": "OptionalMethod", - "api_name": "suspendPlayer", + "line": 132, + "problem": "LimitedVoidType", + "api_name": "writeSync", "api_type": "MethodSignature", - "api_optional": true, - "api_auto_fix": false, - "api_auto_fix_context": "", - "target_type": "", + "api_optional": false, "api_func_args": [ - { "name": "type", "type": "SuspendType", "is_optional": false, "hasDefault": false } + { + "name": "buffer", + "type": "ArrayBuffer", + "is_optional": false, + "has_default": false + } ], "parent_api": [ { - "api_name": "NativeMediaPlayerBridge", + "api_name": "SyncWriteStream", "api_type": "InterfaceDeclaration" }, { - "api_name": "webview", + "api_name": "rcp", "api_type": "ModuleDeclaration" } ], - "methd_return_type": "void", - "codeKind": 173 - } + "method_return_type": "number | void", + "code_kind": 173 + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false }, { - "import_path": ["@ohos.file.sendablePhotoAccessHelper", "@kit.MediaLibraryKit"], - "file_path": ["api/@ohos.file.sendablePhotoAccessHelper.d.ets"], - "is_global": false, + "file_path": "api/@hms.collaboration.rcp.d.ts", "api_info": { - "problem": "SendablePropType", - "api_name": "position", - "api_type": "PropertySignatrue", - "api_optional": false, - "api_auto_fix": false, - "api_auto_fix_context": "", - "target_type": "", - "api_func_args": [], + "line": 229, + "problem": "LimitedVoidType", + "api_name": "IncomingDataCallback", + "api_type": "TypeAliasDeclaration", + "api_func_args": [ + { + "name": "incomingData", + "type": "ArrayBuffer", + "is_optional": false + } + ], "parent_api": [ - { - "api_name": "SharedPhotoAsset", - "api_type": "InterfaceDeclaration" - }, - { - "api_name": "sendablePhotoAccessHelper", - "api_type": "ModuleDeclaration" - } - ], - "methd_return_type": "", - "codeKind": 170 - } - }, - { - "import_path": [], - "file_path": ["component/progress.d.ts"], - "is_global": true, - "api_info": { - "problem": "ComputedPropertyName", - "api_name": "[ProgressType.Linear]", - "api_type": "PropertySignatrue", - "api_optional": false, - "api_auto_fix": false, - "api_auto_fix_context": "", - "target_type": "", - "api_func_args": [], - "parent_api": [ - { - "api_name": "ProgressStyleMap", - "api_type": "InterfaceDeclaration" - } + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "method_return_type": "void | Promise", + "code_kind": 268 + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" ], - "methd_return_type": "", - "codeKind": 170 - } + "is_global": false }, { - "import_path": [], - "file_path": ["component/progress.d.ts"], - "is_global": true, + "file_path": "api/@hms.collaboration.rcp.d.ts", "api_info": { - "problem": "ComputedPropertyName", - "api_name": "[ProgressType.Ring]", - "api_type": "PropertySignatrue", + "line": 351, + "problem": "ConstructorIface", + "api_type": "ConstructSignature", "api_optional": false, - "api_auto_fix": false, - "api_auto_fix_context": "", - "target_type": "", "api_func_args": [], "parent_api": [ { - "api_name": "ProgressStyleMap", + "api_name": "NetworkOutputQueueConstructor", "api_type": "InterfaceDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" } ], - "methd_return_type": "", - "codeKind": 170 - } + "method_return_type": "INetworkOutputQueue", + "code_kind": 180 + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false }, { - "import_path": [], - "file_path": ["component/progress.d.ts"], - "is_global": true, + "file_path": "api/@hms.collaboration.rcp.d.ts", "api_info": { - "problem": "ComputedPropertyName", - "api_name": "[ProgressType.Eclipse]", - "api_type": "PropertySignatrue", + "line": 359, + "problem": "ConstructorIface", + "api_type": "ConstructSignature", "api_optional": false, - "api_auto_fix": false, - "api_auto_fix_context": "", - "target_type": "", - "api_func_args": [], - "parent_api": [ - { - "api_name": "ProgressStyleMap", - "api_type": "InterfaceDeclaration" - } + "api_func_args": [ + { + "name": "maxSize", + "type": "number", + "is_optional": false, + "has_default": false + } ], - "methd_return_type": "", - "codeKind": 170 - } - }, - { - "import_path": [], - "file_path": ["component/progress.d.ts"], - "is_global": true, - "api_info": { - "problem": "ComputedPropertyName", - "api_name": "[ProgressType.ScaleRing]", - "api_type": "PropertySignatrue", - "api_optional": false, - "api_auto_fix": false, - "api_auto_fix_context": "", - "target_type": "", - "api_func_args": [], "parent_api": [ - { - "api_name": "ProgressStyleMap", - "api_type": "InterfaceDeclaration" - } + { + "api_name": "NetworkOutputQueueConstructor", + "api_type": "InterfaceDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } ], - "methd_return_type": "", - "codeKind": 170 - } + "method_return_type": "INetworkOutputQueue", + "code_kind": 180 + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false }, { - "import_path": [], - "file_path": ["component/progress.d.ts"], - "is_global": true, + "file_path": "api/@hms.collaboration.rcp.d.ts", "api_info": { - "problem": "ComputedPropertyName", - "api_name": "[ProgressType.Capsule]", - "api_type": "PropertySignatrue", + "line": 368, + "problem": "ConstructorIface", + "api_type": "ConstructSignature", "api_optional": false, - "api_auto_fix": false, - "api_auto_fix_context": "", - "target_type": "", - "api_func_args": [], + "api_func_args": [ + { + "name": "maxSize", + "type": "number", + "is_optional": false, + "has_default": false + }, + { + "name": "pausePolicyOverride", + "type": "ReceivingPausePolicy", + "is_optional": false, + "has_default": false + } + ], "parent_api": [ - { - "api_name": "ProgressStyleMap", - "api_type": "InterfaceDeclaration" - } + { + "api_name": "NetworkOutputQueueConstructor", + "api_type": "InterfaceDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } ], - "methd_return_type": "", - "codeKind": 170 - } - }, - { + "method_return_type": "INetworkOutputQueue", + "code_kind": 180 + }, "import_path": [ "@hms.collaboration.rcp", "@kit.RemoteCommunicationKit" ], - "file_path": ["api/@hms.collaboration.rcp.d.ts"], - "is_global": false, + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", "api_info": { + "line": 386, "problem": "ConstructorIface", - "api_name": "", "api_type": "ConstructSignature", "api_optional": false, - "api_auto_fix": false, - "api_auto_fix_context": "", - "target_type": "", "api_func_args": [], "parent_api": [ { - "api_name": "NetworkOutputQueueConstructor", + "api_name": "NetworkInputQueueConstructor", "api_type": "InterfaceDeclaration" }, { @@ -297,127 +253,97 @@ "api_type": "ModuleDeclaration" } ], - "methd_return_type": "INetworkOutputQueue", - "codeKind": 180 - } - }, - { + "method_return_type": "INetworkInputQueue", + "code_kind": 180 + }, "import_path": [ - "@ohos.application.AccessibilityExtensionAbility", - "@kit.AccessibilityKit" + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" ], - "file_path": ["api/application/AccessibilityExtensionContext.d.ts"], - "is_global": false, + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", "api_info": { - "problem": "IndexedAccessType", - "api_name": "attributeValue", - "api_type": "MethodSignature", + "line": 394, + "problem": "ConstructorIface", + "api_type": "ConstructSignature", "api_optional": false, - "api_auto_fix": false, - "api_auto_fix_context": "", - "target_type": "", "api_func_args": [ { - "name": "attributeName", - "type": "T", + "name": "maxSize", + "type": "number", "is_optional": false, - "hasDefault": false + "has_default": false } ], "parent_api": [ { - "api_name": "AccessibilityElement", + "api_name": "NetworkInputQueueConstructor", "api_type": "InterfaceDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" } ], - "methd_return_type": "Promise", - "codeKind": 173 - } - }, - { + "method_return_type": "INetworkInputQueue", + "code_kind": 180 + }, "import_path": [ - "@ohos.application.AccessibilityExtensionAbility", - "@kit.AccessibilityKit" + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" ], - "file_path": ["api/application/AccessibilityExtensionContext.d.ts"], - "is_global": false, + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", "api_info": { - "problem": "IndexedAccessType", - "api_name": "attributeValue", - "api_type": "MethodSignature", + "line": 404, + "problem": "ConstructorIface", + "api_type": "ConstructSignature", "api_optional": false, - "api_auto_fix": false, - "api_auto_fix_context": "", - "target_type": "", "api_func_args": [ { - "name": "attributeName", - "type": "T", + "name": "maxSize", + "type": "number", + "is_optional": false, + "has_default": false + }, + { + "name": "pausePolicyOverride", + "type": "SendingPausePolicy", "is_optional": false, - "hasDefault": false + "has_default": false } ], "parent_api": [ { - "api_name": "AccessibilityElement", + "api_name": "NetworkInputQueueConstructor", "api_type": "InterfaceDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" } ], - "methd_return_type": "Promise", - "codeKind": 173 - } - }, - { + "method_return_type": "INetworkInputQueue", + "code_kind": 180 + }, "import_path": [ - "@hms.core.deviceCloudGateway.cloudDatabase", - "@kit.CloudFoundationKit" - ], - "file_path": [ - "api/@hms.core.deviceCloudGateway.cloudDatabase.d.ts" + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" ], - "is_global": false, - "api_info": { - "problem": "ConstructorFuncs", - "api_name": "DatabaseQuery", - "api_type": "ClassDeclaration", - "api_optional": false, - "api_auto_fix": false, - "api_auto_fix_context": "", - "target_type": "", - "api_func_args": [ - { - "name": "entityClass", - "type": "new () => T", - "is_optional": false, - "hasDefault": false - } - ], - "parent_api": [ - { - "api_name": "cloudDatabase", - "api_type": "ModuleDeclaration" - } - ], - "methd_return_type": "DatabaseQuery", - "codeKind": 264 - } + "is_global": false }, { - "import_path": [ - "@hms.collaboration.rcp.d.ts", - "@kit.RemoteCommunicationKit" - ], - "file_path": ["api/@hms.collaboration.rcp.d.ts"], - "is_global": false, + "file_path": "api/@hms.collaboration.rcp.d.ts", "api_info": { + "line": 536, "problem": "LiteralAsPropertyName", "api_name": "'authorization'", "api_type": "PropertySignature", "api_optional": true, - "api_auto_fix": false, - "api_auto_fix_context": "", - "target_type": "", - "api_func_args": [], "parent_api": [ { "api_name": "RequestHeaders", @@ -428,26 +354,23 @@ "api_type": "ModuleDeclaration" } ], - "methd_return_type": "string", - "codeKind": 170 - } - }, - { + "code_kind": 170, + "api_property_type": "string" + }, "import_path": [ - "@hms.collaboration.rcp.d.ts", + "@hms.collaboration.rcp", "@kit.RemoteCommunicationKit" ], - "file_path": ["api/@hms.collaboration.rcp.d.ts"], - "is_global": false, + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", "api_info": { + "line": 536, "problem": "LiteralAsPropertyName", - "api_name": "'content-type'", + "api_name": "'authorization'", "api_type": "PropertySignature", "api_optional": true, - "api_auto_fix": false, - "api_auto_fix_context": "", - "target_type": "", - "api_func_args": [], "parent_api": [ { "api_name": "RequestHeaders", @@ -458,26 +381,23 @@ "api_type": "ModuleDeclaration" } ], - "methd_return_type": "string", - "codeKind": 170 - } - }, - { + "code_kind": 170, + "api_property_type": "string" + }, "import_path": [ - "@hms.collaboration.rcp.d.ts", + "@hms.collaboration.rcp", "@kit.RemoteCommunicationKit" ], - "file_path": ["api/@hms.collaboration.rcp.d.ts"], - "is_global": false, + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", "api_info": { + "line": 537, "problem": "LiteralAsPropertyName", "api_name": "'accept'", "api_type": "PropertySignature", "api_optional": true, - "api_auto_fix": false, - "api_auto_fix_context": "", - "target_type": "", - "api_func_args": [], "parent_api": [ { "api_name": "RequestHeaders", @@ -488,26 +408,23 @@ "api_type": "ModuleDeclaration" } ], - "methd_return_type": "ContentType | ContentType[]", - "codeKind": 170 - } - }, - { + "code_kind": 170, + "api_property_type": "ContentType | ContentType[]" + }, "import_path": [ - "@hms.collaboration.rcp.d.ts", + "@hms.collaboration.rcp", "@kit.RemoteCommunicationKit" ], - "file_path": ["api/@hms.collaboration.rcp.d.ts"], - "is_global": false, + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", "api_info": { + "line": 537, "problem": "LiteralAsPropertyName", - "api_name": "'cache-control'", + "api_name": "'accept'", "api_type": "PropertySignature", "api_optional": true, - "api_auto_fix": false, - "api_auto_fix_context": "", - "target_type": "", - "api_func_args": [], "parent_api": [ { "api_name": "RequestHeaders", @@ -518,26 +435,23 @@ "api_type": "ModuleDeclaration" } ], - "methd_return_type": "string | string[]", - "codeKind": 170 - } - }, - { + "code_kind": 170, + "api_property_type": "ContentType | ContentType[]" + }, "import_path": [ - "@hms.collaboration.rcp.d.ts", + "@hms.collaboration.rcp", "@kit.RemoteCommunicationKit" ], - "file_path": ["api/@hms.collaboration.rcp.d.ts"], - "is_global": false, + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", "api_info": { + "line": 538, "problem": "LiteralAsPropertyName", - "api_name": "'user-agent'", + "api_name": "'accept-charset'", "api_type": "PropertySignature", "api_optional": true, - "api_auto_fix": false, - "api_auto_fix_context": "", - "target_type": "", - "api_func_args": [], "parent_api": [ { "api_name": "RequestHeaders", @@ -548,60 +462,8005 @@ "api_type": "ModuleDeclaration" } ], - "methd_return_type": "string", - "codeKind": 170 - } + "code_kind": 170, + "api_property_type": "string | string[]" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false }, { - "import_path": [], - "file_path": ["component/styled_string.d.ts"], - "is_global": true, + "file_path": "api/@hms.collaboration.rcp.d.ts", "api_info": { - "problem": "DeclWithDuplicateName", - "api_name": "TextStyle", - "api_type": "ClassDeclaration", - "api_optional": false, - "api_auto_fix": false, - "api_auto_fix_context": "", - "target_type": "", - "api_func_args": [ + "line": 538, + "problem": "LiteralAsPropertyName", + "api_name": "'accept-charset'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ { - "name": "value", - "type": "TextStyleInterface", - "is_optional": true, - "hasDefault": false + "api_name": "RequestHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" } ], - "parent_api": [], - "methd_return_type": "TextStyle", - "codeKind": 264 - } - }, - { + "code_kind": 170, + "api_property_type": "string | string[]" + }, "import_path": [ - "@ohos.worker.d.ts", - "@kit.ArkTS" + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 539, + "problem": "LiteralAsPropertyName", + "api_name": "'accept-encoding'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "RequestHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "ContentCoding | ContentCoding[]" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 539, + "problem": "LiteralAsPropertyName", + "api_name": "'accept-encoding'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "RequestHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "ContentCoding | ContentCoding[]" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 540, + "problem": "LiteralAsPropertyName", + "api_name": "'accept-language'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "RequestHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "string | string[]" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 540, + "problem": "LiteralAsPropertyName", + "api_name": "'accept-language'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "RequestHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "string | string[]" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 541, + "problem": "LiteralAsPropertyName", + "api_name": "'cache-control'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "RequestHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "string | string[]" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 541, + "problem": "LiteralAsPropertyName", + "api_name": "'cache-control'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "RequestHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "string | string[]" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 542, + "problem": "LiteralAsPropertyName", + "api_name": "'cookie'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "RequestHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "string | string[]" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 542, + "problem": "LiteralAsPropertyName", + "api_name": "'cookie'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "RequestHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "string | string[]" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 543, + "problem": "LiteralAsPropertyName", + "api_name": "'range'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "RequestHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "string | string[]" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 543, + "problem": "LiteralAsPropertyName", + "api_name": "'range'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "RequestHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "string | string[]" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 544, + "problem": "LiteralAsPropertyName", + "api_name": "'upgrade'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "RequestHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "string | string[]" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 544, + "problem": "LiteralAsPropertyName", + "api_name": "'upgrade'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "RequestHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "string | string[]" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" ], - "file_path": ["api/@ohos.worker.d.ts"], - "is_global": false, + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 545, + "problem": "LiteralAsPropertyName", + "api_name": "'user-agent'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "RequestHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "string" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 545, + "problem": "LiteralAsPropertyName", + "api_name": "'user-agent'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "RequestHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "string" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 546, + "problem": "LiteralAsPropertyName", + "api_name": "'content-type'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "RequestHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "ContentType" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 546, + "problem": "LiteralAsPropertyName", + "api_name": "'content-type'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "RequestHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "ContentType" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 556, + "problem": "LiteralAsPropertyName", + "api_name": "'accept-ranges'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "ResponseHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "'none' | 'bytes' | (string & NonNullable)" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 556, + "problem": "LiteralAsPropertyName", + "api_name": "'accept-ranges'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "ResponseHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "'none' | 'bytes' | (string & NonNullable)" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 557, + "problem": "LiteralAsPropertyName", + "api_name": "'allow'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "ResponseHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "HttpMethod | HttpMethod[]" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 557, + "problem": "LiteralAsPropertyName", + "api_name": "'allow'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "ResponseHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "HttpMethod | HttpMethod[]" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 558, + "problem": "LiteralAsPropertyName", + "api_name": "'cache-control'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "ResponseHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "string | string[]" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 558, + "problem": "LiteralAsPropertyName", + "api_name": "'cache-control'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "ResponseHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "string | string[]" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 559, + "problem": "LiteralAsPropertyName", + "api_name": "'content-encoding'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "ResponseHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "ContentCoding" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 559, + "problem": "LiteralAsPropertyName", + "api_name": "'content-encoding'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "ResponseHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "ContentCoding" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 560, + "problem": "LiteralAsPropertyName", + "api_name": "'content-range'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "ResponseHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "string" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 560, + "problem": "LiteralAsPropertyName", + "api_name": "'content-range'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "ResponseHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "string" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 561, + "problem": "LiteralAsPropertyName", + "api_name": "'content-type'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "ResponseHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "ContentType" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 561, + "problem": "LiteralAsPropertyName", + "api_name": "'content-type'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "ResponseHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "ContentType" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 562, + "problem": "LiteralAsPropertyName", + "api_name": "'date'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "ResponseHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "string" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 562, + "problem": "LiteralAsPropertyName", + "api_name": "'date'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "ResponseHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "string" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 563, + "problem": "LiteralAsPropertyName", + "api_name": "'etag'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "ResponseHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "string" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 563, + "problem": "LiteralAsPropertyName", + "api_name": "'etag'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "ResponseHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "string" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 564, + "problem": "LiteralAsPropertyName", + "api_name": "'expires'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "ResponseHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "string" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 564, + "problem": "LiteralAsPropertyName", + "api_name": "'expires'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "ResponseHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "string" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 565, + "problem": "LiteralAsPropertyName", + "api_name": "'location'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "ResponseHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "string" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 565, + "problem": "LiteralAsPropertyName", + "api_name": "'location'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "ResponseHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "string" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 566, + "problem": "LiteralAsPropertyName", + "api_name": "'retry-after'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "ResponseHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "string" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 566, + "problem": "LiteralAsPropertyName", + "api_name": "'retry-after'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "ResponseHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "string" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 567, + "problem": "LiteralAsPropertyName", + "api_name": "'set-cookie'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "ResponseHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "string | string[]" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 567, + "problem": "LiteralAsPropertyName", + "api_name": "'set-cookie'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "ResponseHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "string | string[]" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 568, + "problem": "LiteralAsPropertyName", + "api_name": "'server'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "ResponseHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "string" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 568, + "problem": "LiteralAsPropertyName", + "api_name": "'server'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "ResponseHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "string" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 569, + "problem": "LiteralAsPropertyName", + "api_name": "'www-authenticate'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "ResponseHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "string | string[]" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 569, + "problem": "LiteralAsPropertyName", + "api_name": "'www-authenticate'", + "api_type": "PropertySignature", + "api_optional": true, + "parent_api": [ + { + "api_name": "ResponseHeaders", + "api_type": "TypeAliasDeclaration" + }, + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "string | string[]" + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.collaboration.rcp.d.ts", + "api_info": { + "line": 1355, + "problem": "LimitedVoidType", + "api_name": "OnDataReceive", + "api_type": "TypeAliasDeclaration", + "api_func_args": [ + { + "name": "incomingData", + "type": "ArrayBuffer", + "is_optional": false + } + ], + "parent_api": [ + { + "api_name": "rcp", + "api_type": "ModuleDeclaration" + } + ], + "method_return_type": "number | void | Promise", + "code_kind": 268 + }, + "import_path": [ + "@hms.collaboration.rcp", + "@kit.RemoteCommunicationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.core.deviceCloudGateway.cloudDatabase.d.ts", + "api_info": { + "line": 285, + "problem": "ConstructorFuncs", + "api_name": "DatabaseQuery", + "api_type": "ClassDeclaration", + "api_func_args": [ + { + "name": "entityClass", + "type": "new () => T", + "is_optional": false + } + ], + "parent_api": [ + { + "api_name": "cloudDatabase", + "api_type": "ModuleDeclaration" + } + ], + "method_return_type": "DatabaseQuery", + "code_kind": 264 + }, + "import_path": [ + "@hms.core.deviceCloudGateway.cloudDatabase", + "@kit.CloudFoundationKit" + ], + "is_global": false + }, + { + "file_path": "api/@hms.core.map.mapCommon.d.ts", + "api_info": { + "line": 1877, + "problem": "OptionalMethod", + "api_name": "getCustomIcon", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "clusterItems", + "type": "Array", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "ClusterOverlayParams", + "api_type": "InterfaceDeclaration" + }, + { + "api_name": "mapCommon", + "api_type": "ModuleDeclaration" + } + ], + "method_return_type": "Promise", + "code_kind": 173 + }, + "import_path": [ + "@hms.core.map.mapCommon", + "@kit.MapKit" + ], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 54, + "problem": "OptionalMethod", + "api_name": "onCreate", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "want", + "type": "Want", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "LifecycleForm", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "FormBindingData", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 63, + "problem": "OptionalMethod", + "api_name": "onCastToNormal", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "formId", + "type": "string", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "LifecycleForm", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 72, + "problem": "OptionalMethod", + "api_name": "onUpdate", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "formId", + "type": "string", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "LifecycleForm", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 104, + "problem": "OptionalMethod", + "api_name": "onVisibilityChange", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "newStatus", + "type": "Record", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "LifecycleForm", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 117, + "problem": "OptionalMethod", + "api_name": "onEvent", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "formId", + "type": "string", + "is_optional": false, + "has_default": false + }, + { + "name": "message", + "type": "string", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "LifecycleForm", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 127, + "problem": "OptionalMethod", + "api_name": "onDestroy", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "formId", + "type": "string", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "LifecycleForm", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 141, + "problem": "OptionalMethod", + "api_name": "onAcquireFormState", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "want", + "type": "Want", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "LifecycleForm", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "FormState", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 159, + "problem": "OptionalMethod", + "api_name": "onShow", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [], + "parent_api": [ + { + "api_name": "LifecycleApp", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 167, + "problem": "OptionalMethod", + "api_name": "onHide", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [], + "parent_api": [ + { + "api_name": "LifecycleApp", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 175, + "problem": "OptionalMethod", + "api_name": "onDestroy", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [], + "parent_api": [ + { + "api_name": "LifecycleApp", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 183, + "problem": "OptionalMethod", + "api_name": "onCreate", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [], + "parent_api": [ + { + "api_name": "LifecycleApp", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 192, + "problem": "OptionalMethod", + "api_name": "onStartContinuation", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [], + "parent_api": [ + { + "api_name": "LifecycleApp", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "boolean", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 204, + "problem": "OptionalMethod", + "api_name": "onSaveData", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "data", + "type": "Object", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "LifecycleApp", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "boolean", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 216, + "problem": "OptionalMethod", + "api_name": "onCompleteContinuation", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "result", + "type": "number", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "LifecycleApp", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 227, + "problem": "OptionalMethod", + "api_name": "onRestoreData", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "data", + "type": "Object", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "LifecycleApp", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 236, + "problem": "OptionalMethod", + "api_name": "onRemoteTerminated", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [], + "parent_api": [ + { + "api_name": "LifecycleApp", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 248, + "problem": "OptionalMethod", + "api_name": "onSaveAbilityState", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "outState", + "type": "PacMap", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "LifecycleApp", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 260, + "problem": "OptionalMethod", + "api_name": "onRestoreAbilityState", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "inState", + "type": "PacMap", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "LifecycleApp", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 269, + "problem": "OptionalMethod", + "api_name": "onInactive", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [], + "parent_api": [ + { + "api_name": "LifecycleApp", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 277, + "problem": "OptionalMethod", + "api_name": "onActive", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [], + "parent_api": [ + { + "api_name": "LifecycleApp", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 286, + "problem": "OptionalMethod", + "api_name": "onNewWant", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "want", + "type": "Want", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "LifecycleApp", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 296, + "problem": "OptionalMethod", + "api_name": "onMemoryLevel", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "level", + "type": "number", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "LifecycleApp", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 315, + "problem": "OptionalMethod", + "api_name": "onStart", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [], + "parent_api": [ + { + "api_name": "LifecycleService", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 327, + "problem": "OptionalMethod", + "api_name": "onCommand", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "want", + "type": "Want", + "is_optional": false, + "has_default": false + }, + { + "name": "startId", + "type": "number", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "LifecycleService", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 335, + "problem": "OptionalMethod", + "api_name": "onStop", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [], + "parent_api": [ + { + "api_name": "LifecycleService", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 345, + "problem": "OptionalMethod", + "api_name": "onConnect", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "want", + "type": "Want", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "LifecycleService", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "RemoteObject", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 354, + "problem": "OptionalMethod", + "api_name": "onDisconnect", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "want", + "type": "Want", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "LifecycleService", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 366, + "problem": "OptionalMethod", + "api_name": "onReconnect", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "want", + "type": "Want", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "LifecycleService", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 390, + "problem": "OptionalMethod", + "api_name": "update", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "uri", + "type": "string", + "is_optional": false, + "has_default": false + }, + { + "name": "valueBucket", + "type": "rdb.ValuesBucket", + "is_optional": false, + "has_default": false + }, + { + "name": "predicates", + "type": "dataAbility.DataAbilityPredicates", + "is_optional": false, + "has_default": false + }, + { + "name": "callback", + "type": "AsyncCallback", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "LifecycleData", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 405, + "problem": "OptionalMethod", + "api_name": "query", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "uri", + "type": "string", + "is_optional": false, + "has_default": false + }, + { + "name": "columns", + "type": "Array", + "is_optional": false, + "has_default": false + }, + { + "name": "predicates", + "type": "dataAbility.DataAbilityPredicates", + "is_optional": false, + "has_default": false + }, + { + "name": "callback", + "type": "AsyncCallback", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "LifecycleData", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 418, + "problem": "OptionalMethod", + "api_name": "delete", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "uri", + "type": "string", + "is_optional": false, + "has_default": false + }, + { + "name": "predicates", + "type": "dataAbility.DataAbilityPredicates", + "is_optional": false, + "has_default": false + }, + { + "name": "callback", + "type": "AsyncCallback", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "LifecycleData", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 431, + "problem": "OptionalMethod", + "api_name": "normalizeUri", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "uri", + "type": "string", + "is_optional": false, + "has_default": false + }, + { + "name": "callback", + "type": "AsyncCallback", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "LifecycleData", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 443, + "problem": "OptionalMethod", + "api_name": "batchInsert", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "uri", + "type": "string", + "is_optional": false, + "has_default": false + }, + { + "name": "valueBuckets", + "type": "Array", + "is_optional": false, + "has_default": false + }, + { + "name": "callback", + "type": "AsyncCallback", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "LifecycleData", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 455, + "problem": "OptionalMethod", + "api_name": "denormalizeUri", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "uri", + "type": "string", + "is_optional": false, + "has_default": false + }, + { + "name": "callback", + "type": "AsyncCallback", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "LifecycleData", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 467, + "problem": "OptionalMethod", + "api_name": "insert", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "uri", + "type": "string", + "is_optional": false, + "has_default": false + }, + { + "name": "valueBucket", + "type": "rdb.ValuesBucket", + "is_optional": false, + "has_default": false + }, + { + "name": "callback", + "type": "AsyncCallback", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "LifecycleData", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 483, + "problem": "OptionalMethod", + "api_name": "openFile", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "uri", + "type": "string", + "is_optional": false, + "has_default": false + }, + { + "name": "mode", + "type": "string", + "is_optional": false, + "has_default": false + }, + { + "name": "callback", + "type": "AsyncCallback", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "LifecycleData", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 499, + "problem": "OptionalMethod", + "api_name": "getFileTypes", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "uri", + "type": "string", + "is_optional": false, + "has_default": false + }, + { + "name": "mimeTypeFilter", + "type": "string", + "is_optional": false, + "has_default": false + }, + { + "name": "callback", + "type": "AsyncCallback>", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "LifecycleData", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 508, + "problem": "OptionalMethod", + "api_name": "onInitialized", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "info", + "type": "AbilityInfo", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "LifecycleData", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 521, + "problem": "OptionalMethod", + "api_name": "getType", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "uri", + "type": "string", + "is_optional": false, + "has_default": false + }, + { + "name": "callback", + "type": "AsyncCallback", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "LifecycleData", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 534, + "problem": "OptionalMethod", + "api_name": "executeBatch", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "ops", + "type": "Array", + "is_optional": false, + "has_default": false + }, + { + "name": "callback", + "type": "AsyncCallback>", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "LifecycleData", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@internal/full/lifecycle.d.ts", + "api_info": { + "line": 547, + "problem": "OptionalMethod", + "api_name": "call", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "method", + "type": "string", + "is_optional": false, + "has_default": false + }, + { + "name": "arg", + "type": "string", + "is_optional": false, + "has_default": false + }, + { + "name": "extras", + "type": "PacMap", + "is_optional": false, + "has_default": false + }, + { + "name": "callback", + "type": "AsyncCallback", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "LifecycleData", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/@ohos.app.ability.AbilityLifecycleCallback.d.ts", + "api_info": { + "line": 83, + "problem": "OptionalMethod", + "api_name": "onAbilityWillCreate", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "ability", + "type": "UIAbility", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "AbilityLifecycleCallback", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.app.ability.AbilityLifecycleCallback", + "@kit.AbilityKit" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.app.ability.AbilityLifecycleCallback.d.ts", + "api_info": { + "line": 125, + "problem": "OptionalMethod", + "api_name": "onWindowStageWillCreate", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "ability", + "type": "UIAbility", + "is_optional": false, + "has_default": false + }, + { + "name": "windowStage", + "type": "window.WindowStage", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "AbilityLifecycleCallback", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.app.ability.AbilityLifecycleCallback", + "@kit.AbilityKit" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.app.ability.AbilityLifecycleCallback.d.ts", + "api_info": { + "line": 135, + "problem": "OptionalMethod", + "api_name": "onWillNewWant", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "ability", + "type": "UIAbility", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "AbilityLifecycleCallback", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.app.ability.AbilityLifecycleCallback", + "@kit.AbilityKit" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.app.ability.AbilityLifecycleCallback.d.ts", + "api_info": { + "line": 145, + "problem": "OptionalMethod", + "api_name": "onNewWant", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "ability", + "type": "UIAbility", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "AbilityLifecycleCallback", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.app.ability.AbilityLifecycleCallback", + "@kit.AbilityKit" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.app.ability.AbilityLifecycleCallback.d.ts", + "api_info": { + "line": 227, + "problem": "OptionalMethod", + "api_name": "onWindowStageWillDestroy", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "ability", + "type": "UIAbility", + "is_optional": false, + "has_default": false + }, + { + "name": "windowStage", + "type": "window.WindowStage", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "AbilityLifecycleCallback", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.app.ability.AbilityLifecycleCallback", + "@kit.AbilityKit" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.app.ability.AbilityLifecycleCallback.d.ts", + "api_info": { + "line": 265, + "problem": "OptionalMethod", + "api_name": "onAbilityWillDestroy", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "ability", + "type": "UIAbility", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "AbilityLifecycleCallback", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.app.ability.AbilityLifecycleCallback", + "@kit.AbilityKit" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.app.ability.AbilityLifecycleCallback.d.ts", + "api_info": { + "line": 303, + "problem": "OptionalMethod", + "api_name": "onAbilityWillForeground", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "ability", + "type": "UIAbility", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "AbilityLifecycleCallback", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.app.ability.AbilityLifecycleCallback", + "@kit.AbilityKit" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.app.ability.AbilityLifecycleCallback.d.ts", + "api_info": { + "line": 341, + "problem": "OptionalMethod", + "api_name": "onAbilityWillBackground", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "ability", + "type": "UIAbility", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "AbilityLifecycleCallback", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.app.ability.AbilityLifecycleCallback", + "@kit.AbilityKit" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.app.ability.AbilityLifecycleCallback.d.ts", + "api_info": { + "line": 369, + "problem": "OptionalMethod", + "api_name": "onAbilityWillContinue", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "ability", + "type": "UIAbility", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "AbilityLifecycleCallback", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.app.ability.AbilityLifecycleCallback", + "@kit.AbilityKit" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.app.ability.AbilityLifecycleCallback.d.ts", + "api_info": { + "line": 380, + "problem": "OptionalMethod", + "api_name": "onWindowStageWillRestore", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "ability", + "type": "UIAbility", + "is_optional": false, + "has_default": false + }, + { + "name": "windowStage", + "type": "window.WindowStage", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "AbilityLifecycleCallback", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.app.ability.AbilityLifecycleCallback", + "@kit.AbilityKit" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.app.ability.AbilityLifecycleCallback.d.ts", + "api_info": { + "line": 391, + "problem": "OptionalMethod", + "api_name": "onWindowStageRestore", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "ability", + "type": "UIAbility", + "is_optional": false, + "has_default": false + }, + { + "name": "windowStage", + "type": "window.WindowStage", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "AbilityLifecycleCallback", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.app.ability.AbilityLifecycleCallback", + "@kit.AbilityKit" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.app.ability.AbilityLifecycleCallback.d.ts", + "api_info": { + "line": 401, + "problem": "OptionalMethod", + "api_name": "onAbilityWillSaveState", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "ability", + "type": "UIAbility", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "AbilityLifecycleCallback", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.app.ability.AbilityLifecycleCallback", + "@kit.AbilityKit" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.app.ability.AbilityLifecycleCallback.d.ts", + "api_info": { + "line": 411, + "problem": "OptionalMethod", + "api_name": "onAbilitySaveState", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "ability", + "type": "UIAbility", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "AbilityLifecycleCallback", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.app.ability.AbilityLifecycleCallback", + "@kit.AbilityKit" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.app.ability.DriverExtensionAbility.d.ts", + "api_info": { + "line": 78, + "problem": "LimitedVoidType", + "api_name": "onDisconnect", + "api_type": "MethodDeclaration", + "api_optional": false, + "api_func_args": [ + { + "name": "want", + "type": "Want", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "DriverExtensionAbility", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void | Promise", + "code_kind": 174 + }, + "import_path": [ + "@ohos.app.ability.DriverExtensionAbility", + "@kit.DriverDevelopmentKit" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.app.ability.PhotoEditorExtensionAbility.d.ts", + "api_info": { + "line": 73, + "problem": "LimitedVoidType", + "api_name": "onDestroy", + "api_type": "MethodDeclaration", + "api_optional": false, + "api_func_args": [], + "parent_api": [ + { + "api_name": "PhotoEditorExtensionAbility", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void | Promise", + "code_kind": 174 + }, + "import_path": [ + "@ohos.app.ability.PhotoEditorExtensionAbility", + "@kit.AbilityKit" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.app.ability.UIAbility.d.ts", + "api_info": { + "line": 472, + "problem": "LimitedVoidType", + "api_name": "onDestroy", + "api_type": "MethodDeclaration", + "api_optional": false, + "api_func_args": [], + "parent_api": [ + { + "api_name": "UIAbility", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void | Promise", + "code_kind": 174 + }, + "import_path": [ + "@ohos.app.ability.UIAbility", + "@kit.AbilityKit" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.app.ability.UIExtensionAbility.d.ts", + "api_info": { + "line": 101, + "problem": "LimitedVoidType", + "api_name": "onDestroy", + "api_type": "MethodDeclaration", + "api_optional": false, + "api_func_args": [], + "parent_api": [ + { + "api_name": "UIExtensionAbility", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void | Promise", + "code_kind": 174 + }, + "import_path": [ + "@ohos.app.ability.UIExtensionAbility", + "@kit.AbilityKit" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.app.appstartup.StartupConfigEntry.d.ts", + "api_info": { + "line": 36, + "problem": "OptionalMethod", + "api_name": "onConfig", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [], + "parent_api": [ + { + "api_name": "StartupConfigEntry", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "StartupConfig", + "code_kind": 174 + }, + "import_path": [ + "@ohos.app.appstartup.StartupConfigEntry", + "@kit.AbilityKit" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.app.appstartup.StartupListener.d.ts", + "api_info": { + "line": 36, + "problem": "OptionalMethod", + "api_name": "onCompleted", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "error", + "type": "BusinessError", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "StartupListener", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.app.appstartup.StartupListener", + "@kit.AbilityKit" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.app.appstartup.StartupTask.d.ets", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "onDependencyCompleted", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "dependency", + "type": "string", + "is_optional": false, + "has_default": false + }, + { + "name": "result", + "type": "Object", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "StartupTask", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.app.appstartup.StartupTask", + "@kit.AbilityKit" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.app.appstartup.StartupTask.d.ets", + "api_info": { + "line": 49, + "problem": "LimitedVoidType", + "api_name": "init", + "api_type": "MethodDeclaration", + "api_optional": false, + "api_func_args": [ + { + "name": "context", + "type": "AbilityStageContext", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "StartupTask", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "Promise", + "code_kind": 174 + }, + "import_path": [ + "@ohos.app.appstartup.StartupTask", + "@kit.AbilityKit" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.app.form.FormExtensionAbility.d.ts", + "api_info": { + "line": 253, + "problem": "OptionalMethod", + "api_name": "onAcquireFormState", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "want", + "type": "Want", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "FormExtensionAbility", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "FormState", + "code_kind": 174 + }, + "import_path": [ + "@ohos.app.form.FormExtensionAbility", + "@kit.FormKit" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.app.form.FormExtensionAbility.d.ts", + "api_info": { + "line": 262, + "problem": "OptionalMethod", + "api_name": "onStop", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [], + "parent_api": [ + { + "api_name": "FormExtensionAbility", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.app.form.FormExtensionAbility", + "@kit.FormKit" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.arkui.Prefetcher.d.ts", + "api_info": { + "line": 41, + "problem": "LimitedVoidType", + "api_name": "prefetch", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "index", + "type": "number", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "IDataSourcePrefetching", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void | Promise", + "code_kind": 173 + }, + "import_path": [ + "@ohos.arkui.Prefetcher", + "@kit.ArkUI" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.arkui.Prefetcher.d.ts", + "api_info": { + "line": 53, + "problem": "OptionalMethod", + "api_name": "cancel", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "index", + "type": "number", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "IDataSourcePrefetching", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void | Promise", + "code_kind": 173 + }, + "import_path": [ + "@ohos.arkui.Prefetcher", + "@kit.ArkUI" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.arkui.Prefetcher.d.ts", + "api_info": { + "line": 53, + "problem": "LimitedVoidType", + "api_name": "cancel", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "index", + "type": "number", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "IDataSourcePrefetching", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void | Promise", + "code_kind": 173 + }, + "import_path": [ + "@ohos.arkui.Prefetcher", + "@kit.ArkUI" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.arkui.StateManagement.d.ts", + "api_info": { + "line": 47, + "problem": "ConstructorIface", + "api_type": "ConstructSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "args", + "type": "any", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "TypeConstructorWithArgs", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "T", + "code_kind": 180 + }, + "import_path": [ + "@ohos.arkui.StateManagement", + "@kit.ArkUI" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.arkui.StateManagement.d.ts", + "api_info": { + "line": 156, + "problem": "ConstructorIface", + "api_type": "ConstructSignature", + "api_optional": false, + "api_func_args": [], + "parent_api": [ + { + "api_name": "TypeConstructor", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "T", + "code_kind": 180 + }, + "import_path": [ + "@ohos.arkui.StateManagement", + "@kit.ArkUI" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.multimedia.audio.d.ts", + "api_info": { + "line": 5120, + "problem": "LimitedVoidType", + "api_name": "AudioRendererWriteDataCallback", + "api_type": "TypeAliasDeclaration", + "api_func_args": [ + { + "name": "data", + "type": "ArrayBuffer", + "is_optional": false + } + ], + "parent_api": [ + { + "api_name": "audio", + "api_type": "ModuleDeclaration" + } + ], + "method_return_type": "AudioDataCallbackResult | void", + "code_kind": 268 + }, + "import_path": [ + "@ohos.multimedia.audio", + "@kit.AudioKit" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.web.webview.d.ts", + "api_info": { + "line": 6490, + "problem": "OptionalMethod", + "api_name": "resumePlayer", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [], + "parent_api": [ + { + "api_name": "NativeMediaPlayerBridge", + "api_type": "InterfaceDeclaration" + }, + { + "api_name": "webview", + "api_type": "ModuleDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [ + "@ohos.web.webview", + "@kit.ArkWeb" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.web.webview.d.ts", + "api_info": { + "line": 6500, + "problem": "OptionalMethod", + "api_name": "suspendPlayer", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "type", + "type": "SuspendType", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "NativeMediaPlayerBridge", + "api_type": "InterfaceDeclaration" + }, + { + "api_name": "webview", + "api_type": "ModuleDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [ + "@ohos.web.webview", + "@kit.ArkWeb" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.worker.d.ts", + "api_info": { + "line": 492, + "problem": "LimitedVoidType", + "api_name": "EventListener", + "api_type": "InterfaceDeclaration", + "parent_api": [], + "code_kind": 267 + }, + "import_path": [ + "@ohos.worker", + "@kit.ArkTS" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.worker.d.ts", + "api_info": { + "line": 561, + "problem": "LimitedVoidType", + "api_name": "WorkerEventListener", + "api_type": "InterfaceDeclaration", + "parent_api": [], + "code_kind": 267 + }, + "import_path": [ + "@ohos.worker", + "@kit.ArkTS" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.worker.d.ts", + "api_info": { + "line": 869, + "problem": "TypeQuery", + "api_name": "self", + "api_type": "PropertySignature", + "api_optional": false, + "parent_api": [ + { + "api_name": "DedicatedWorkerGlobalScope", + "api_type": "InterfaceDeclaration" + }, + { + "api_name": "WorkerGlobalScope", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "WorkerGlobalScope & typeof globalThis" + }, + "import_path": [ + "@ohos.worker", + "@kit.ArkTS" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.worker.d.ts", + "api_info": { + "line": 869, + "problem": "GlobalThisError", + "api_name": "self", + "api_type": "PropertySignature", + "api_optional": false, + "parent_api": [ + { + "api_name": "DedicatedWorkerGlobalScope", + "api_type": "InterfaceDeclaration" + }, + { + "api_name": "WorkerGlobalScope", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "WorkerGlobalScope & typeof globalThis" + }, + "import_path": [ + "@ohos.worker", + "@kit.ArkTS" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.worker.d.ts", + "api_info": { + "line": 970, + "problem": "TypeQuery", + "api_name": "self", + "api_type": "PropertySignature", + "api_optional": false, + "parent_api": [ + { + "api_name": "ThreadWorkerGlobalScope", + "api_type": "InterfaceDeclaration" + }, + { + "api_name": "GlobalScope", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "GlobalScope & typeof globalThis" + }, + "import_path": [ + "@ohos.worker", + "@kit.ArkTS" + ], + "is_global": false + }, + { + "file_path": "api/@ohos.worker.d.ts", + "api_info": { + "line": 970, + "problem": "GlobalThisError", + "api_name": "self", + "api_type": "PropertySignature", + "api_optional": false, + "parent_api": [ + { + "api_name": "ThreadWorkerGlobalScope", + "api_type": "InterfaceDeclaration" + }, + { + "api_name": "GlobalScope", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "GlobalScope & typeof globalThis" + }, + "import_path": [ + "@ohos.worker", + "@kit.ArkTS" + ], + "is_global": false + }, + { + "file_path": "api/app/context.d.ts", + "api_info": { + "line": 39, + "problem": "InterfaceExtendsClass", + "api_name": "Context", + "api_type": "InterfaceDeclaration", + "parent_api": [], + "code_kind": 267 + }, + "import_path": [], + "is_global": false + }, + { + "file_path": "api/application/AbilityStartCallback.d.ts", + "api_info": { + "line": 49, + "problem": "OptionalMethod", + "api_name": "onResult", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "parameter", + "type": "AbilityResult", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "AbilityStartCallback", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.app.ability.common" + ], + "is_global": false + }, + { + "file_path": "api/application/AccessibilityExtensionContext.d.ts", + "api_info": { + "line": 275, + "problem": "IndexedAccessType", + "api_name": "attributeValue", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "attributeName", + "type": "T", + "is_optional": false, + "has_default": false + }, + { + "name": "callback", + "type": "AsyncCallback", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "AccessibilityElement", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [ + "@ohos.application.AccessibilityExtensionAbility", + "@kit.AccessibilityKit" + ], + "is_global": false + }, + { + "file_path": "api/application/AccessibilityExtensionContext.d.ts", + "api_info": { + "line": 290, + "problem": "IndexedAccessType", + "api_name": "attributeValue", + "api_type": "MethodSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "attributeName", + "type": "T", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "AccessibilityElement", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "Promise", + "code_kind": 173 + }, + "import_path": [ + "@ohos.application.AccessibilityExtensionAbility", + "@kit.AccessibilityKit" + ], + "is_global": false + }, + { + "file_path": "api/application/ErrorObserver.d.ts", + "api_info": { + "line": 64, + "problem": "OptionalMethod", + "api_name": "onException", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "errObject", + "type": "Error", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "ErrorObserver", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.app.ability.errorManager" + ], + "is_global": false + }, + { + "file_path": "api/application/LoopObserver.d.ts", + "api_info": { + "line": 36, + "problem": "OptionalMethod", + "api_name": "onLoopTimeOut", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "timeout", + "type": "number", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "LoopObserver", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [ + "@ohos.app.ability.errorManager" + ], + "is_global": false + }, + { + "file_path": "api/arkui/AlphabetIndexerModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "AlphabetIndexerAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "AlphabetIndexerModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/AttributeUpdater.d.ts", + "api_info": { + "line": 49, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "T", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "AttributeUpdater", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/BlankModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "BlankAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "BlankModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/ButtonModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "ButtonAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "ButtonModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/CalendarPickerModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "CalendarPickerAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "CalendarPickerModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/CheckboxGroupModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "CheckboxGroupAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "CheckboxGroupModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/CheckboxModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "CheckboxAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "CheckboxModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/ColumnModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "ColumnAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "ColumnModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/ColumnSplitModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "ColumnSplitAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "ColumnSplitModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/CommonModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "CommonAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "CommonModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/ContainerSpanModifier.d.ts", + "api_info": { + "line": 39, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "containerSpanAttribute", + "type": "ContainerSpanAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "ContainerSpanModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/CounterModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "CounterAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "CounterModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/DataPanelModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "DataPanelAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "DataPanelModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/DatePickerModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "DatePickerAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "DatePickerModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/DividerModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "DividerAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "DividerModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/FrameNode.d.ts", + "api_info": { + "line": 545, + "problem": "OptionalMethod", + "api_name": "onDraw", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "context", + "type": "DrawContext", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "FrameNode", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/FrameNode.d.ts", + "api_info": { + "line": 722, + "problem": "InterfaceExtendsClass", + "api_name": "TypedFrameNode", + "api_type": "InterfaceDeclaration", + "parent_api": [], + "code_kind": 267 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/FrameNode.d.ts", + "api_info": { + "line": 1606, + "problem": "OptionalMethod", + "api_name": "onAttachToNode", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "target", + "type": "FrameNode", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "NodeAdapter", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/FrameNode.d.ts", + "api_info": { + "line": 1615, + "problem": "OptionalMethod", + "api_name": "onDetachFromNode", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [], + "parent_api": [ + { + "api_name": "NodeAdapter", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/FrameNode.d.ts", + "api_info": { + "line": 1626, + "problem": "OptionalMethod", + "api_name": "onGetChildId", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "index", + "type": "number", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "NodeAdapter", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "number", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/FrameNode.d.ts", + "api_info": { + "line": 1637, + "problem": "OptionalMethod", + "api_name": "onCreateChild", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "index", + "type": "number", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "NodeAdapter", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "FrameNode", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/FrameNode.d.ts", + "api_info": { + "line": 1648, + "problem": "OptionalMethod", + "api_name": "onDisposeChild", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "id", + "type": "number", + "is_optional": false, + "has_default": false + }, + { + "name": "node", + "type": "FrameNode", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "NodeAdapter", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/FrameNode.d.ts", + "api_info": { + "line": 1659, + "problem": "OptionalMethod", + "api_name": "onUpdateChild", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "id", + "type": "number", + "is_optional": false, + "has_default": false + }, + { + "name": "node", + "type": "FrameNode", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "NodeAdapter", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/GaugeModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "GaugeAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "GaugeModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/GridColModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "GridColAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "GridColModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/GridItemModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "GridItemAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "GridItemModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/GridModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "GridAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "GridModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/GridRowModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "GridRowAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "GridRowModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/HyperlinkModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "HyperlinkAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "HyperlinkModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/ImageAnimatorModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "ImageAnimatorAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "ImageAnimatorModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/ImageModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "ImageAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "ImageModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/ImageSpanModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "ImageSpanAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "ImageSpanModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/LineModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "LineAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "LineModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/ListItemGroupModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "ListItemGroupAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "ListItemGroupModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/ListItemModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "ListItemAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "ListItemModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/ListModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "ListAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "ListModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/LoadingProgressModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "LoadingProgressAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "LoadingProgressModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/MarqueeModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "MarqueeAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "MarqueeModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/MenuItemModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "MenuItemAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "MenuItemModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/MenuModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "MenuAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "MenuModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/NavDestinationModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "NavDestinationAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "NavDestinationModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/NavigationModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "NavigationAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "NavigationModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/NavigatorModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "NavigatorAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "NavigatorModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/NavRouterModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "NavRouterAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "NavRouterModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/NodeController.d.ts", + "api_info": { + "line": 81, + "problem": "OptionalMethod", + "api_name": "aboutToResize", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "size", + "type": "Size", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "NodeController", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/NodeController.d.ts", + "api_info": { + "line": 97, + "problem": "OptionalMethod", + "api_name": "aboutToAppear", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [], + "parent_api": [ + { + "api_name": "NodeController", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/NodeController.d.ts", + "api_info": { + "line": 113, + "problem": "OptionalMethod", + "api_name": "aboutToDisappear", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [], + "parent_api": [ + { + "api_name": "NodeController", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/NodeController.d.ts", + "api_info": { + "line": 147, + "problem": "OptionalMethod", + "api_name": "onTouchEvent", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "event", + "type": "TouchEvent", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "NodeController", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/PanelModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "PanelAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "PanelModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/ParticleModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "particleAttribute", + "type": "ParticleAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "ParticleModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/PathModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "PathAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "PathModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/PatternLockModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "PatternLockAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "PatternLockModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/PolygonModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "PolygonAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "PolygonModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/PolylineModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "PolylineAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "PolylineModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/ProgressModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "ProgressAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "ProgressModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/QRCodeModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "QRCodeAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "QRCodeModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/RadioModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "RadioAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "RadioModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/RatingModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "RatingAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "RatingModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/RectModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "RectAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "RectModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/RefreshModifier.d.ts", + "api_info": { + "line": 39, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "RefreshAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "RefreshModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/RichEditorModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "RichEditorAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "RichEditorModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/RowModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "RowAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "RowModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/RowSplitModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "RowSplitAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "RowSplitModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/ScrollModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "ScrollAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "ScrollModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/SearchModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "SearchAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "SearchModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/SelectModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "SelectAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "SelectModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/ShapeModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "ShapeAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "ShapeModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/SideBarContainerModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "SideBarContainerAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "SideBarContainerModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/SliderModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "SliderAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "SliderModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/SpanModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "SpanAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "SpanModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/StackModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "StackAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "StackModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/StepperItemModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "StepperItemAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "StepperItemModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/SwiperModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "SwiperAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "SwiperModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/SymbolGlyphModifier.d.ts", + "api_info": { + "line": 46, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "SymbolGlyphAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "SymbolGlyphModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/SymbolSpanModifier.d.ts", + "api_info": { + "line": 46, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "attribute", + "type": "SymbolSpanAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "SymbolSpanModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/TabsModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "TabsAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "TabsModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/TextAreaModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "TextAreaAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "TextAreaModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/TextClockModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "TextClockAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "TextClockModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/TextInputModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "TextInputAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "TextInputModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/TextModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "TextAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "TextModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/TextPickerModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "TextPickerAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "TextPickerModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/TextTimerModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "TextTimerAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "TextTimerModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/TimePickerModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "TimePickerAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "TimePickerModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/ToggleModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "ToggleAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "ToggleModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/VideoModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "VideoAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "VideoModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "api/arkui/WaterFlowModifier.d.ts", + "api_info": { + "line": 38, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "WaterFlowAttribute", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "WaterFlowModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [ + "@ohos.arkui.modifier" + ], + "is_global": true + }, + { + "file_path": "declarations/alert_dialog.d.ts", + "api_info": { + "line": 502, + "problem": "DeclWithDuplicateName", + "api_name": "TextStyle", + "api_type": "InterfaceDeclaration", + "parent_api": [], + "code_kind": 267 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/canvas.d.ts", + "api_info": { + "line": 529, + "problem": "DeclWithDuplicateName", + "api_name": "CanvasPath", + "api_type": "ClassDeclaration", + "api_func_args": [], + "parent_api": [], + "method_return_type": "CanvasPath", + "code_kind": 264 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/canvas.d.ts", + "api_info": { + "line": 1215, + "problem": "DeclWithDuplicateName", + "api_name": "CanvasPattern", + "api_type": "InterfaceDeclaration", + "parent_api": [], + "code_kind": 267 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/canvas.d.ts", + "api_info": { + "line": 1286, + "problem": "DeclWithDuplicateName", + "api_name": "TextMetrics", + "api_type": "InterfaceDeclaration", + "parent_api": [], + "code_kind": 267 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/circle.d.ts", + "api_info": { + "line": 198, + "problem": "ConstructorIface", + "api_type": "ConstructSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "value", + "type": "CircleOptions", + "is_optional": true, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "CircleInterface", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "CircleAttribute", + "code_kind": 180 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 3882, + "problem": "OptionalMethod", + "api_name": "drawBehind", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "drawContext", + "type": "DrawContext", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "DrawModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 3893, + "problem": "OptionalMethod", + "api_name": "drawContent", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "drawContext", + "type": "DrawContext", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "DrawModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 3903, + "problem": "OptionalMethod", + "api_name": "drawFront", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "drawContext", + "type": "DrawContext", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "DrawModifier", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 3931, + "problem": "IndexedAccessType", + "api_name": "TransitionEffect", + "api_type": "ClassDeclaration", + "api_func_args": [ + { + "name": "type", + "type": "Type", + "is_optional": false + }, + { + "name": "effect", + "type": "Effect", + "is_optional": false + } + ], + "parent_api": [], + "method_return_type": "TransitionEffect", + "code_kind": 264 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 3931, + "problem": "IndexedAccessType", + "api_name": "TransitionEffect", + "api_type": "ClassDeclaration", + "api_func_args": [ + { + "name": "type", + "type": "Type", + "is_optional": false + }, + { + "name": "effect", + "type": "Effect", + "is_optional": false + } + ], + "parent_api": [], + "method_return_type": "TransitionEffect", + "code_kind": 264 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 5167, + "problem": "DeclWithDuplicateName", + "api_name": "EventTarget", + "api_type": "InterfaceDeclaration", + "parent_api": [], + "code_kind": 267 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 7610, + "problem": "OptionalMethod", + "api_name": "getModifierKeyState", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "keys", + "type": "Array", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "BaseEvent", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "boolean", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 8211, + "problem": "DeclWithDuplicateName", + "api_name": "MouseEvent", + "api_type": "InterfaceDeclaration", + "parent_api": [], + "code_kind": 267 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 8866, + "problem": "DeclWithDuplicateName", + "api_name": "TouchEvent", + "api_type": "InterfaceDeclaration", + "parent_api": [], + "code_kind": 267 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 9942, + "problem": "DeclWithDuplicateName", + "api_name": "DragEvent", + "api_type": "InterfaceDeclaration", + "parent_api": [], + "code_kind": 267 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 10303, + "problem": "OptionalMethod", + "api_name": "getModifierKeyState", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "keys", + "type": "Array", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "DragEvent", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "boolean", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 10640, + "problem": "OptionalMethod", + "api_name": "getModifierKeyState", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "keys", + "type": "Array", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "KeyEvent", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "boolean", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 14270, + "problem": "OptionalMethod", + "api_name": "applyNormalAttribute", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "T", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "AttributeModifier", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 14288, + "problem": "OptionalMethod", + "api_name": "applyPressedAttribute", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "T", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "AttributeModifier", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 14306, + "problem": "OptionalMethod", + "api_name": "applyFocusedAttribute", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "T", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "AttributeModifier", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 14324, + "problem": "OptionalMethod", + "api_name": "applyDisabledAttribute", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "T", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "AttributeModifier", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 14342, + "problem": "OptionalMethod", + "api_name": "applySelectedAttribute", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "instance", + "type": "T", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "AttributeModifier", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 20453, + "problem": "LimitedVoidType", + "api_name": "CustomBuilder", + "api_type": "TypeAliasDeclaration", + "api_func_args": [], + "parent_api": [], + "code_kind": 268 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 21123, + "problem": "DeclWithDuplicateName", + "api_name": "LinearGradient", + "api_type": "InterfaceDeclaration", + "parent_api": [], + "code_kind": 267 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 22047, + "problem": "OptionalMethod", + "api_name": "aboutToAppear", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [], + "parent_api": [ + { + "api_name": "CustomComponent", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 22086, + "problem": "OptionalMethod", + "api_name": "aboutToDisappear", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [], + "parent_api": [ + { + "api_name": "CustomComponent", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 22104, + "problem": "OptionalMethod", + "api_name": "aboutToReuse", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "params", + "type": "{\n [key: string]: unknown;\n }", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "CustomComponent", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 22122, + "problem": "OptionalMethod", + "api_name": "aboutToRecycle", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [], + "parent_api": [ + { + "api_name": "CustomComponent", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 22132, + "problem": "OptionalMethod", + "api_name": "onWillApplyTheme", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "theme", + "type": "Theme", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "CustomComponent", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 22144, + "problem": "OptionalMethod", + "api_name": "onLayout", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "children", + "type": "Array", + "is_optional": false, + "has_default": false + }, + { + "name": "constraint", + "type": "ConstraintSizeOptions", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "CustomComponent", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 22166, + "problem": "OptionalMethod", + "api_name": "onPlaceChildren", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "selfLayoutInfo", + "type": "GeometryInfo", + "is_optional": false, + "has_default": false + }, + { + "name": "children", + "type": "Array", + "is_optional": false, + "has_default": false + }, + { + "name": "constraint", + "type": "ConstraintSizeOptions", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "CustomComponent", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 22178, + "problem": "OptionalMethod", + "api_name": "onMeasure", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "children", + "type": "Array", + "is_optional": false, + "has_default": false + }, + { + "name": "constraint", + "type": "ConstraintSizeOptions", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "CustomComponent", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 22200, + "problem": "OptionalMethod", + "api_name": "onMeasureSize", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "selfLayoutInfo", + "type": "GeometryInfo", + "is_optional": false, + "has_default": false + }, + { + "name": "children", + "type": "Array", + "is_optional": false, + "has_default": false + }, + { + "name": "constraint", + "type": "ConstraintSizeOptions", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "CustomComponent", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "SizeResult", + "code_kind": 174 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 22228, + "problem": "OptionalMethod", + "api_name": "onPageShow", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [], + "parent_api": [ + { + "api_name": "CustomComponent", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 22256, + "problem": "OptionalMethod", + "api_name": "onPageHide", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [], + "parent_api": [ + { + "api_name": "CustomComponent", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 22280, + "problem": "OptionalMethod", + "api_name": "onFormRecycle", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [], + "parent_api": [ + { + "api_name": "CustomComponent", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "string", + "code_kind": 174 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 22300, + "problem": "OptionalMethod", + "api_name": "onFormRecover", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [ + { + "name": "statusData", + "type": "string", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "CustomComponent", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 22335, + "problem": "OptionalMethod", + "api_name": "onBackPress", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [], + "parent_api": [ + { + "api_name": "CustomComponent", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "boolean | void", + "code_kind": 174 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 22335, + "problem": "LimitedVoidType", + "api_name": "onBackPress", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [], + "parent_api": [ + { + "api_name": "CustomComponent", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "boolean | void", + "code_kind": 174 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 22360, + "problem": "OptionalMethod", + "api_name": "pageTransition", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [], + "parent_api": [ + { + "api_name": "CustomComponent", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 22437, + "problem": "OptionalMethod", + "api_name": "onDidBuild", + "api_type": "MethodDeclaration", + "api_optional": true, + "api_func_args": [], + "parent_api": [ + { + "api_name": "CustomComponent", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 174 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/common.d.ts", + "api_info": { + "line": 23015, + "problem": "LimitedVoidType", + "api_name": "OnWillScrollCallback", + "api_type": "TypeAliasDeclaration", + "api_func_args": [ + { + "name": "scrollOffset", + "type": "number", + "is_optional": false + }, + { + "name": "scrollState", + "type": "ScrollState", + "is_optional": false + }, + { + "name": "scrollSource", + "type": "ScrollSource", + "is_optional": false + } + ], + "parent_api": [], + "method_return_type": "void | ScrollResult", + "code_kind": 268 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/data_panel.d.ts", + "api_info": { + "line": 180, + "problem": "DeclWithDuplicateName", + "api_name": "LinearGradient", + "api_type": "ClassDeclaration", + "api_func_args": [ + { + "name": "colorStops", + "type": "ColorStop[]", + "is_optional": false + } + ], + "parent_api": [], + "method_return_type": "LinearGradient", + "code_kind": 264 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/ellipse.d.ts", + "api_info": { + "line": 92, + "problem": "ConstructorIface", + "api_type": "ConstructSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "value", + "type": "{\n width?: string | number;\n height?: string | number;\n }", + "is_optional": true, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "EllipseInterface", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "EllipseAttribute", + "code_kind": 180 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/grid.d.ts", + "api_info": { + "line": 925, + "problem": "LimitedVoidType", + "api_name": "onItemDragStart", + "api_type": "MethodDeclaration", + "api_optional": false, + "api_func_args": [ + { + "name": "event", + "type": "(event: ItemDragInfo, itemIndex: number) => (() => any) | void", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "GridAttribute", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "GridAttribute", + "code_kind": 174 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/hyperlink.d.ts", + "api_info": { + "line": 34, + "problem": "DeclWithDuplicateName", + "api_name": "HyperlinkInterface", + "api_type": "InterfaceDeclaration", + "parent_api": [], + "code_kind": 267 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/hyperlink.d.ts", + "api_info": { + "line": 122, + "problem": "DeclWithDuplicateName", + "api_name": "HyperlinkInterface", + "api_type": "FirstStatement", + "parent_api": [], + "code_kind": 244, + "api_property_type": "HyperlinkAttribute" + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/line.d.ts", + "api_info": { + "line": 100, + "problem": "ConstructorIface", + "api_type": "ConstructSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "value", + "type": "{\n width?: string | number;\n height?: string | number;\n }", + "is_optional": true, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "LineInterface", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "LineAttribute", + "code_kind": 180 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/list.d.ts", + "api_info": { + "line": 1643, + "problem": "LimitedVoidType", + "api_name": "onItemDragStart", + "api_type": "MethodDeclaration", + "api_optional": false, + "api_func_args": [ + { + "name": "event", + "type": "(event: ItemDragInfo, itemIndex: number) => ((() => any) | void)", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "ListAttribute", + "api_type": "ClassDeclaration" + } + ], + "method_return_type": "ListAttribute", + "code_kind": 174 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/navigation.d.ts", + "api_info": { + "line": 2873, + "problem": "OptionalMethod", + "api_name": "cancelTransition", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [], + "parent_api": [ + { + "api_name": "NavigationTransitionProxy", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/navigation.d.ts", + "api_info": { + "line": 2883, + "problem": "OptionalMethod", + "api_name": "updateTransition", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [ + { + "name": "progress", + "type": "number", + "is_optional": false, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "NavigationTransitionProxy", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "void", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/page_transition.d.ts", + "api_info": { + "line": 554, + "problem": "InterfaceExtendsClass", + "api_name": "PageTransitionEnterInterface", + "api_type": "InterfaceDeclaration", + "parent_api": [], + "code_kind": 267 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/page_transition.d.ts", + "api_info": { + "line": 638, + "problem": "InterfaceExtendsClass", + "api_name": "PageTransitionExitInterface", + "api_type": "InterfaceDeclaration", + "parent_api": [], + "code_kind": 267 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/particle.d.ts", "api_info": { - "problem": "TypeQuery", - "api_name": "self", + "line": 438, + "problem": "IndexedAccessType", + "api_name": "config", + "api_type": "PropertySignature", + "api_optional": false, + "parent_api": [ + { + "api_name": "EmitterOptions", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "ParticleConfigs[PARTICLE]" + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/particle.d.ts", + "api_info": { + "line": 696, + "problem": "IndexedAccessType", + "api_name": "config", + "api_type": "PropertySignature", + "api_optional": false, + "parent_api": [ + { + "api_name": "ParticlePropertyOptions", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "ParticlePropertyUpdaterConfigs[UPDATER]" + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/particle.d.ts", + "api_info": { + "line": 849, + "problem": "IndexedAccessType", + "api_name": "config", + "api_type": "PropertySignature", + "api_optional": false, + "parent_api": [ + { + "api_name": "ParticleColorPropertyOptions", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "ParticleColorPropertyUpdaterConfigs[UPDATER]" + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/path.d.ts", + "api_info": { + "line": 92, + "problem": "ConstructorIface", + "api_type": "ConstructSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "value", + "type": "{\n width?: number | string;\n height?: number | string;\n commands?: string;\n }", + "is_optional": true, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "PathInterface", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "PathAttribute", + "code_kind": 180 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/polygon.d.ts", + "api_info": { + "line": 83, + "problem": "ConstructorIface", + "api_type": "ConstructSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "value", + "type": "{\n width?: string | number;\n height?: string | number;\n }", + "is_optional": true, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "PolygonInterface", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "PolygonAttribute", + "code_kind": 180 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/polyline.d.ts", + "api_info": { + "line": 84, + "problem": "ConstructorIface", + "api_type": "ConstructSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "value", + "type": "{\n width?: string | number;\n height?: string | number;\n }", + "is_optional": true, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "PolylineInterface", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "PolylineAttribute", + "code_kind": 180 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/progress.d.ts", + "api_info": { + "line": 1176, + "problem": "ComputedPropertyName", + "api_name": "[ProgressType.Linear]", + "api_type": "PropertySignature", + "api_optional": false, + "parent_api": [ + { + "api_name": "ProgressStyleMap", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "LinearStyleOptions | ProgressStyleOptions" + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/progress.d.ts", + "api_info": { + "line": 1191, + "problem": "ComputedPropertyName", + "api_name": "[ProgressType.Ring]", + "api_type": "PropertySignature", + "api_optional": false, + "parent_api": [ + { + "api_name": "ProgressStyleMap", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "RingStyleOptions | ProgressStyleOptions" + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/progress.d.ts", + "api_info": { + "line": 1206, + "problem": "ComputedPropertyName", + "api_name": "[ProgressType.Eclipse]", + "api_type": "PropertySignature", + "api_optional": false, + "parent_api": [ + { + "api_name": "ProgressStyleMap", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "EclipseStyleOptions | ProgressStyleOptions" + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/progress.d.ts", + "api_info": { + "line": 1221, + "problem": "ComputedPropertyName", + "api_name": "[ProgressType.ScaleRing]", + "api_type": "PropertySignature", + "api_optional": false, + "parent_api": [ + { + "api_name": "ProgressStyleMap", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "ScaleRingStyleOptions | ProgressStyleOptions" + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/progress.d.ts", + "api_info": { + "line": 1236, + "problem": "ComputedPropertyName", + "api_name": "[ProgressType.Capsule]", "api_type": "PropertySignature", "api_optional": false, - "api_auto_fix": false, - "api_auto_fix_context": "", - "target_type": "", + "parent_api": [ + { + "api_name": "ProgressStyleMap", + "api_type": "InterfaceDeclaration" + } + ], + "code_kind": 170, + "api_property_type": "CapsuleStyleOptions | ProgressStyleOptions" + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/progress.d.ts", + "api_info": { + "line": 1347, + "problem": "IndexedAccessType", + "api_name": "ProgressAttribute", + "api_type": "ClassDeclaration", + "api_func_args": [], + "parent_api": [], + "method_return_type": "ProgressAttribute", + "code_kind": 264 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/progress.d.ts", + "api_info": { + "line": 1347, + "problem": "IndexedAccessType", + "api_name": "ProgressAttribute", + "api_type": "ClassDeclaration", "api_func_args": [], + "parent_api": [], + "method_return_type": "ProgressAttribute", + "code_kind": 264 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/rect.d.ts", + "api_info": { + "line": 92, + "problem": "ConstructorIface", + "api_type": "ConstructSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "value", + "type": "{\n width?: number | string;\n height?: number | string;\n radius?: number | string | Array;\n } | {\n width?: number | string;\n height?: number | string;\n radiusWidth?: number | string;\n radiusHeight?: number | string;\n }", + "is_optional": true, + "has_default": false + } + ], "parent_api": [ { - "api_name": "DedicatedWorkerGlobalScope", + "api_name": "RectInterface", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "RectAttribute", + "code_kind": 180 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/scroll.d.ts", + "api_info": { + "line": 1397, + "problem": "LimitedVoidType", + "api_name": "ScrollOnWillScrollCallback", + "api_type": "TypeAliasDeclaration", + "api_func_args": [ + { + "name": "xOffset", + "type": "number", + "is_optional": false + }, + { + "name": "yOffset", + "type": "number", + "is_optional": false + }, + { + "name": "scrollState", + "type": "ScrollState", + "is_optional": false + }, + { + "name": "scrollSource", + "type": "ScrollSource", + "is_optional": false + } + ], + "parent_api": [], + "method_return_type": "void | OffsetResult", + "code_kind": 268 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/shape.d.ts", + "api_info": { + "line": 75, + "problem": "ConstructorIface", + "api_type": "ConstructSignature", + "api_optional": false, + "api_func_args": [ + { + "name": "value", + "type": "PixelMap", + "is_optional": true, + "has_default": false + } + ], + "parent_api": [ + { + "api_name": "ShapeInterface", + "api_type": "InterfaceDeclaration" + } + ], + "method_return_type": "ShapeAttribute", + "code_kind": 180 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/styled_string.d.ts", + "api_info": { + "line": 244, + "problem": "DeclWithDuplicateName", + "api_name": "TextStyle", + "api_type": "ClassDeclaration", + "api_func_args": [ + { + "name": "value", + "type": "TextStyleInterface", + "is_optional": true + } + ], + "parent_api": [], + "method_return_type": "TextStyle", + "code_kind": 264 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/text_common.d.ts", + "api_info": { + "line": 468, + "problem": "OptionalMethod", + "api_name": "getPreviewText", + "api_type": "MethodSignature", + "api_optional": true, + "api_func_args": [], + "parent_api": [ + { + "api_name": "TextEditControllerEx", "api_type": "InterfaceDeclaration" } ], - "methd_return_type": "WorkerGlobalScope & typeof globalThis", - "codeKind": 170 - } + "method_return_type": "PreviewText", + "code_kind": 173 + }, + "import_path": [], + "is_global": true + }, + { + "file_path": "declarations/text_input.d.ts", + "api_info": { + "line": 623, + "problem": "DeclWithDuplicateName", + "api_name": "SubmitEvent", + "api_type": "InterfaceDeclaration", + "parent_api": [], + "code_kind": 267 + }, + "import_path": [], + "is_global": true } ] } \ No newline at end of file diff --git a/ets2panda/linter/src/lib/statistics/FileProblemStatistics.ts b/ets2panda/linter/src/lib/statistics/FileProblemStatistics.ts new file mode 100644 index 0000000000..8b95c12d27 --- /dev/null +++ b/ets2panda/linter/src/lib/statistics/FileProblemStatistics.ts @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export interface FileProblemStatistics { + errors: number; + warnings: number; + errorLines: number; + warningLines: number; + errorLineNumbersString: string; + warningLineNumbersString: string; +} diff --git a/ets2panda/linter/src/lib/statistics/FileStatistics.ts b/ets2panda/linter/src/lib/statistics/FileStatistics.ts new file mode 100644 index 0000000000..f9395d9c0a --- /dev/null +++ b/ets2panda/linter/src/lib/statistics/FileStatistics.ts @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type * as ts from 'typescript'; +import type { ProblemInfo } from '../ProblemInfo'; +import { FaultID } from '../Problems'; + +export class FileStatistics { + visitedNodes: number = 0; + nodeCounters: number[] = []; + lineCounters: Set[] = []; + srcFileName: string; + problems: ProblemInfo[]; + + constructor(srcFile: ts.SourceFile, problems: ProblemInfo[]) { + this.srcFileName = srcFile.fileName; + this.problems = problems; + + for (let i = 0; i < FaultID.LAST_ID; i++) { + this.nodeCounters[i] = 0; + this.lineCounters[i] = new Set(); + } + } +} diff --git a/ets2panda/linter/src/lib/statistics/ProjectStatistics.ts b/ets2panda/linter/src/lib/statistics/ProjectStatistics.ts new file mode 100644 index 0000000000..1b2193729b --- /dev/null +++ b/ets2panda/linter/src/lib/statistics/ProjectStatistics.ts @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { faultsAttrs } from '../FaultAttrs'; +import type { ProblemInfo } from '../ProblemInfo'; +import { ProblemSeverity } from '../ProblemSeverity'; +import type { FileStatistics } from './FileStatistics'; + +export class ProjectStatistics { + fileStats: FileStatistics[] = []; + + hasError(): boolean { + return this.fileStats.some((fileStats) => { + return fileStats.problems.some((problemInfo: ProblemInfo) => { + return faultsAttrs[problemInfo.faultId].severity === ProblemSeverity.ERROR; + }); + }); + } +} diff --git a/ets2panda/linter/src/lib/statistics/StatisticsLogger.ts b/ets2panda/linter/src/lib/statistics/StatisticsLogger.ts new file mode 100644 index 0000000000..da586f7a91 --- /dev/null +++ b/ets2panda/linter/src/lib/statistics/StatisticsLogger.ts @@ -0,0 +1,180 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { faultsAttrs } from '../FaultAttrs'; +import { Logger } from '../Logger'; +import { FaultID } from '../Problems'; +import { ProblemSeverity } from '../ProblemSeverity'; +import type { ProblemInfo } from '../ProblemInfo'; +import { faultDesc } from '../FaultDesc'; +import type { FileStatistics } from './FileStatistics'; +import type { FileProblemStatistics } from './FileProblemStatistics'; +import type { ProjectStatistics } from './ProjectStatistics'; + +export function log(...args: unknown[]): void { + let outLine = ''; + for (let k = 0; k < args.length; k++) { + outLine += `${args[k]} `; + } + Logger.info(outLine); +} + +function logReport(srcFileName: string, problemInfo: ProblemInfo): void { + const faultDescr = faultDesc[problemInfo.faultId]; + const faultType = problemInfo.type; + Logger.info( + `Warning: ${srcFileName} (${problemInfo.line}, ${problemInfo.column}): ${faultDescr ? faultDescr : faultType}` + ); +} + +function logFileProblems(fileStats: FileStatistics): void { + for (const problem of fileStats.problems) { + logReport(fileStats.srcFileName, problem); + } +} + +function countProblemStats(fileStats: FileStatistics): FileProblemStatistics { + let errors = 0; + let warnings = 0; + const errorLines = new Set(); + const warningLines = new Set(); + fileStats.problems.forEach((problemInfo: ProblemInfo) => { + const line = problemInfo.line; + switch (faultsAttrs[problemInfo.faultId].severity) { + case ProblemSeverity.ERROR: { + errors++; + errorLines.add(line); + break; + } + case ProblemSeverity.WARNING: { + warnings++; + warningLines.add(line); + break; + } + default: + } + }); + const sortFunc = (a, b): number => { + return a - b; + }; + let errorLineNumbersString = ''; + Array.from(errorLines). + sort(sortFunc). + forEach((line) => { + errorLineNumbersString += line + ', '; + }); + let warningLineNumbersString = ''; + Array.from(warningLines). + sort(sortFunc). + forEach((line) => { + warningLineNumbersString += line + ', '; + }); + return { + errors, + warnings, + errorLines: errorLines.size, + warningLines: warningLines.size, + errorLineNumbersString, + warningLineNumbersString + }; +} + +function logProblemFileInfo(fileStats: FileStatistics, problemStats: FileProblemStatistics): void { + if (problemStats.errors > 0) { + const errorRate = (problemStats.errors / fileStats.visitedNodes * 100).toFixed(2); + const warningRate = (problemStats.warnings / fileStats.visitedNodes * 100).toFixed(2); + log(fileStats.srcFileName, ': ', '\n\tError lines: ', problemStats.errorLineNumbersString); + log(fileStats.srcFileName, ': ', '\n\tWarning lines: ', problemStats.warningLineNumbersString); + log( + '\n\tError constructs (%): ', + errorRate, + '\t[ of ', + fileStats.visitedNodes, + ' constructs ], \t', + problemStats.errorLines, + ' lines' + ); + log( + '\n\tWarning constructs (%): ', + warningRate, + '\t[ of ', + fileStats.visitedNodes, + ' constructs ], \t', + problemStats.warningLines, + ' lines' + ); + } +} + +function logTotalProblemsInfo( + totalErrors: number, + totalWarnings: number, + totalErrorLines: number, + totalWarningLines: number, + totalVisitedNodes: number +): void { + const errorRate = (totalErrors / totalVisitedNodes * 100).toFixed(2); + const warningRate = (totalWarnings / totalVisitedNodes * 100).toFixed(2); + log('\nTotal error constructs (%): ', errorRate); + log('\nTotal warning constructs (%): ', warningRate); + log('\nTotal error lines:', totalErrorLines, ' lines\n'); + log('\nTotal warning lines:', totalWarningLines, ' lines\n'); +} + +function logProblemsPercentageByFeatures(projectStats: ProjectStatistics, totalVisitedNodes: number): void { + log('\nPercent by features: '); + for (let i = 0; i < FaultID.LAST_ID; i++) { + let nodes = 0; + let lines = 0; + for (const fileStats of projectStats.fileStats) { + nodes += fileStats.nodeCounters[i]; + lines += fileStats.lineCounters[i].size; + } + const pecentage = (nodes / totalVisitedNodes * 100).toFixed(2).padEnd(7, ' '); + log(faultDesc[i].padEnd(55, ' '), pecentage, '[', nodes, ' constructs / ', lines, ' lines]'); + } +} + +export function logStatistics(projectStats: ProjectStatistics): void { + let filesWithErrors = 0; + let totalErrors = 0; + let totalWarnings = 0; + let totalErrorLines = 0; + let totalWarningLines = 0; + let totalVisitedNodes = 0; + + for (const fileStats of projectStats.fileStats) { + logFileProblems(fileStats); + + const problemStats = countProblemStats(fileStats); + logProblemFileInfo(fileStats, problemStats); + + if (problemStats.errors > 0) { + filesWithErrors++; + } + + totalErrors += problemStats.errors; + totalWarnings += problemStats.warnings; + totalErrorLines += problemStats.errorLines; + totalWarningLines += problemStats.warningLines; + totalVisitedNodes += fileStats.visitedNodes; + } + + log('\n\n\nFiles scanned: ', projectStats.fileStats.length); + log('\nFiles with problems: ', filesWithErrors); + + logTotalProblemsInfo(totalErrors, totalWarnings, totalErrorLines, totalWarningLines, totalVisitedNodes); + logProblemsPercentageByFeatures(projectStats, totalVisitedNodes); +} diff --git a/ets2panda/linter/src/cli/Compiler.ts b/ets2panda/linter/src/lib/ts-compiler/Compiler.ts similarity index 44% rename from ets2panda/linter/src/cli/Compiler.ts rename to ets2panda/linter/src/lib/ts-compiler/Compiler.ts index b37a0996a4..7708b647da 100644 --- a/ets2panda/linter/src/cli/Compiler.ts +++ b/ets2panda/linter/src/lib/ts-compiler/Compiler.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2024 Huawei Device Co., Ltd. + * Copyright (c) 2023-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -14,16 +14,22 @@ */ import * as ts from 'typescript'; -import type { CommandLineOptions } from '../lib/CommandLineOptions'; -import { formTscOptions } from './ts-compiler/FormTscOptions'; -import { logTscDiagnostic } from '../lib/utils/functions/LogTscDiagnostic'; -import type { LinterConfig } from '../lib/LinterConfig'; -import { TSCCompiledProgramWithDiagnostics } from '../lib/ts-diagnostics/TSCCompiledProgram'; -import { Logger } from '../lib/Logger'; - -function compile(cmdOptions: CommandLineOptions, overrideCompilerOptions: ts.CompilerOptions): ts.Program { +import type { CommandLineOptions } from '../CommandLineOptions'; +import { formTscOptions } from './FormTscOptions'; +import { logTscDiagnostic } from '../utils/functions/LogTscDiagnostic'; +import type { LinterConfig } from '../LinterConfig'; +import { TSCCompiledProgramSimple, TSCCompiledProgramWithDiagnostics } from '../ts-diagnostics/TSCCompiledProgram'; +import { Logger } from '../Logger'; + +export type createProgramCallback = (createProgramOptions: ts.CreateProgramOptions) => ts.Program; + +function compile( + cmdOptions: CommandLineOptions, + overrideCompilerOptions: ts.CompilerOptions, + createProgramCb?: createProgramCallback +): ts.Program { const createProgramOptions = formTscOptions(cmdOptions, overrideCompilerOptions); - const program = ts.createProgram(createProgramOptions); + const program = createProgramCb ? createProgramCb(createProgramOptions) : ts.createProgram(createProgramOptions); // Log Tsc errors if needed if (cmdOptions.logTscErrors) { const diagnostics = ts.getPreEmitDiagnostics(program); @@ -32,9 +38,32 @@ function compile(cmdOptions: CommandLineOptions, overrideCompilerOptions: ts.Com return program; } -export function compileLintOptions(cmdOptions: CommandLineOptions): LinterConfig { - const strict = compile(cmdOptions, getOverrideCompilerOptions(true)); - const nonStrict = compile(cmdOptions, getOverrideCompilerOptions(false)); +export function compileLintOptions( + cmdOptions: CommandLineOptions, + createProgramCb?: createProgramCallback +): LinterConfig { + const linterConfig = cmdOptions.disableStrictDiagnostics ? + compileSimpleProgram(cmdOptions, createProgramCb) : + compileWithStrictDiagnostics(cmdOptions, createProgramCb); + + linterConfig.cmdOptions.linterOptions.etsLoaderPath = getEtsLoaderPath(linterConfig); + return linterConfig; +} + +function compileSimpleProgram(cmdOptions: CommandLineOptions, createProgramCb?: createProgramCallback): LinterConfig { + const program = compile(cmdOptions, getOverrideCompilerOptions(true), createProgramCb); + return { + cmdOptions: cmdOptions, + tscCompiledProgram: new TSCCompiledProgramSimple(program) + }; +} + +function compileWithStrictDiagnostics( + cmdOptions: CommandLineOptions, + createProgramCb?: createProgramCallback +): LinterConfig { + const strict = compile(cmdOptions, getOverrideCompilerOptions(true), createProgramCb); + const nonStrict = compile(cmdOptions, getOverrideCompilerOptions(false), createProgramCb); return { cmdOptions: cmdOptions, tscCompiledProgram: new TSCCompiledProgramWithDiagnostics(strict, nonStrict, cmdOptions.inputFiles) @@ -55,3 +84,8 @@ function getOverrideCompilerOptions(strict: boolean): ts.CompilerOptions { noImplicitReturns: strict }; } + +export function getEtsLoaderPath(linterConfig: LinterConfig): string | undefined { + const tsProgram = linterConfig.tscCompiledProgram.getProgram(); + return tsProgram.getCompilerOptions().etsLoaderPath; +} diff --git a/ets2panda/linter/src/cli/ts-compiler/FormTscOptions.ts b/ets2panda/linter/src/lib/ts-compiler/FormTscOptions.ts similarity index 66% rename from ets2panda/linter/src/cli/ts-compiler/FormTscOptions.ts rename to ets2panda/linter/src/lib/ts-compiler/FormTscOptions.ts index 1494a294fa..b29b42f3bb 100644 --- a/ets2panda/linter/src/cli/ts-compiler/FormTscOptions.ts +++ b/ets2panda/linter/src/lib/ts-compiler/FormTscOptions.ts @@ -14,8 +14,19 @@ */ import * as ts from 'typescript'; -import type { CommandLineOptions } from '../../lib/CommandLineOptions'; -import { createCompilerHost } from './ResolveSdks'; +import type { CommandLineOptions } from '../CommandLineOptions'; +import { createCompilerHost, readDeclareFiles } from './ResolveSdks'; + +function getTargetESVersionLib(optionsTarget: ts.ScriptTarget): string[] { + switch (optionsTarget) { + case ts.ScriptTarget.ES2017: + return ['lib.es2017.d.ts']; + case ts.ScriptTarget.ES2021: + return ['lib.es2021.d.ts']; + default: + return ['lib.es2021.d.ts']; + } +} export function formTscOptions( cmdOptions: CommandLineOptions, @@ -31,13 +42,18 @@ export function formTscOptions( options.options = Object.assign(options.options, overrideCompilerOptions); return options; } + const rootNames = cmdOptions.inputFiles.concat(readDeclareFiles(cmdOptions.sdkDefaultApiPath ?? '')); + const ESVersion = cmdOptions.followSdkSettings ? ts.ScriptTarget.ES2021 : ts.ScriptTarget.Latest; + const ESVersionLib = cmdOptions.followSdkSettings ? getTargetESVersionLib(ESVersion) : undefined; + const isCheckJs = !cmdOptions.followSdkSettings; const options: ts.CreateProgramOptions = { - rootNames: cmdOptions.inputFiles, + rootNames: rootNames, options: { - target: ts.ScriptTarget.Latest, + target: ESVersion, module: ts.ModuleKind.CommonJS, allowJs: true, - checkJs: true + checkJs: isCheckJs, + lib: ESVersionLib } }; if (cmdOptions.sdkDefaultApiPath && cmdOptions.arktsWholeProjectPath && cmdOptions.sdkExternalApiPath) { diff --git a/ets2panda/linter/src/cli/ts-compiler/ResolveSdks.ts b/ets2panda/linter/src/lib/ts-compiler/ResolveSdks.ts similarity index 92% rename from ets2panda/linter/src/cli/ts-compiler/ResolveSdks.ts rename to ets2panda/linter/src/lib/ts-compiler/ResolveSdks.ts index f4a11b5fc7..290326c0fc 100644 --- a/ets2panda/linter/src/cli/ts-compiler/ResolveSdks.ts +++ b/ets2panda/linter/src/lib/ts-compiler/ResolveSdks.ts @@ -15,7 +15,7 @@ import * as path from 'node:path'; import * as fs from 'fs'; import * as ts from 'typescript'; -import { EXTNAME_JS, EXTNAME_TS, EXTNAME_D_ETS, EXTNAME_D_TS, EXTNAME_ETS } from '../../lib/utils/consts/ExtensionName'; +import { EXTNAME_JS, EXTNAME_TS, EXTNAME_D_ETS, EXTNAME_D_TS, EXTNAME_ETS } from '../utils/consts/ExtensionName'; interface ResolutionContext { sdkContext: SdkContext; @@ -30,6 +30,23 @@ interface SdkContext { sdkDefaultApiPath: string; } +export function readDeclareFiles(SdkPath: string): string[] { + if (SdkPath === '') { + return []; + } + const declarationsFileNames: string[] = []; + const declarationsPath = path.resolve(SdkPath, './build-tools/ets-loader/declarations'); + if (!fs.existsSync(declarationsPath)) { + throw new Error('get wrong sdkDefaultApiPath, declarationsPath not found'); + } + fs.readdirSync(declarationsPath).forEach((fileName: string) => { + if ((/\.d\.ts$/).test(fileName)) { + declarationsFileNames.push(path.resolve(SdkPath, './build-tools/ets-loader/declarations', fileName)); + } + }); + return declarationsFileNames; +} + export function createCompilerHost( sdkDefaultApiPath: string, sdkExternalApiPath: string[], @@ -298,28 +315,16 @@ function createResolutionContext(sdkContext: SdkContext, projectPath: string): R return { sdkContext, projectPath, - compilerOptions: createCompilerOptions(projectPath) + compilerOptions: createCompilerOptions(sdkContext, projectPath) }; } -function createCompilerOptions(projectPath: string): ts.CompilerOptions { +function createCompilerOptions(sdkContext: SdkContext, projectPath: string): ts.CompilerOptions { const compilerOptions: ts.CompilerOptions = ((): ts.CompilerOptions => { - let configPath: string | null = null; - let currentDir: string = __dirname; - - while (currentDir) { - const filePath = path.resolve(currentDir, 'tsconfig.json'); - if (fs.existsSync(filePath)) { - configPath = filePath; - break; - } - currentDir = path.dirname(currentDir); + const configPath = path.resolve(sdkContext.sdkDefaultApiPath, './build-tools/ets-loader/tsconfig.json'); + if (!fs.existsSync(configPath)) { + throw new Error('get wrong sdkDefaultApiPath, tsconfig.json not found'); } - - if (!configPath) { - throw new Error('tsconfig.json not found'); - } - const configFile = ts.readConfigFile(configPath, ts.sys.readFile); return configFile.config.compilerOptions; })(); diff --git a/ets2panda/linter/src/lib/ts-diagnostics/TSCCompiledProgram.ts b/ets2panda/linter/src/lib/ts-diagnostics/TSCCompiledProgram.ts index c4b5a7a19b..c3719cc50a 100644 --- a/ets2panda/linter/src/lib/ts-diagnostics/TSCCompiledProgram.ts +++ b/ets2panda/linter/src/lib/ts-diagnostics/TSCCompiledProgram.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2024 Huawei Device Co., Ltd. + * Copyright (c) 2023-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -97,6 +97,7 @@ export function transformDiagnostic(diagnostic: ts.Diagnostic): ProblemInfo { end: endPos, type: 'StrictModeError', // expect strict options to always present + faultId: faultId, severity: diagnostic.category === ts.DiagnosticCategory.Warning ? ProblemSeverity.WARNING : ProblemSeverity.ERROR, problem: FaultID[faultId], suggest: messageText, diff --git a/ets2panda/linter/src/lib/utils/TsUtils.ts b/ets2panda/linter/src/lib/utils/TsUtils.ts index 386623e475..6365fab13f 100644 --- a/ets2panda/linter/src/lib/utils/TsUtils.ts +++ b/ets2panda/linter/src/lib/utils/TsUtils.ts @@ -15,6 +15,7 @@ import * as path from 'node:path'; import * as ts from 'typescript'; +import * as fs from 'fs'; import type { IsEtsFileCallback } from '../IsEtsFileCallback'; import { FaultID } from '../Problems'; import { ARKTS_IGNORE_DIRS, ARKTS_IGNORE_DIRS_OH_MODULES, ARKTS_IGNORE_FILES } from './consts/ArktsIgnorePaths'; @@ -43,9 +44,10 @@ import { isIntrinsicObjectType } from './functions/isIntrinsicObjectType'; import type { LinterOptions } from '../LinterOptions'; import { ETS } from './consts/TsSuffix'; import { STRINGLITERAL_NUMBER, STRINGLITERAL_NUMBER_ARRAY } from './consts/StringLiteral'; -import { ETS_MODULE, VALID_OHM_COMPONENTS_MODULE_PATH } from './consts/OhmUrl'; -import { EXTNAME_JS } from './consts/ExtensionName'; -import { USE_STATIC } from './consts/InteropAPI'; +import { InteropType, USE_STATIC } from './consts/InteropAPI'; +import { ETS_MODULE, PATH_SEPARATOR, VALID_OHM_COMPONENTS_MODULE_PATH } from './consts/OhmUrl'; +import { EXTNAME_D_TS, EXTNAME_ETS, EXTNAME_JS, EXTNAME_TS } from './consts/ExtensionName'; +import { STRING_ERROR_LITERAL } from './consts/Literals'; export const SYMBOL = 'Symbol'; export const SYMBOL_CONSTRUCTOR = 'SymbolConstructor'; @@ -231,6 +233,54 @@ export class TsUtils { ); } + checkStatementForErrorClass(stmt: ts.ThrowStatement): boolean { + const newExpr = stmt.expression; + if (!ts.isNewExpression(newExpr)) { + return true; + } + const ident = newExpr.expression; + if (!ts.isIdentifier(ident)) { + return true; + } + + if (ident.text === STRING_ERROR_LITERAL) { + return false; + } + + const declaration = this.getDeclarationNode(ident); + if (!declaration) { + return true; + } + + if (!ts.isClassDeclaration(declaration)) { + return true; + } + + if (!declaration.heritageClauses) { + return true; + } + + return !this.includesErrorClass(declaration.heritageClauses); + } + + includesErrorClass(hClauses: ts.NodeArray): boolean { + void this; + let includesErrorClass = false; + + for (const hClause of hClauses) { + for (const type of hClause.types) { + if (!ts.isIdentifier(type.expression)) { + continue; + } + if (type.expression.text === 'Error') { + includesErrorClass = true; + } + } + } + + return includesErrorClass; + } + static isPrimitiveLiteralType(type: ts.Type): boolean { return !!( type.flags & @@ -624,6 +674,9 @@ export class TsUtils { if (this.processExtendedParentTypes(typeA, typeB)) { return true; } + if (this.isStdIterableType(typeB) && this.hasSymbolIteratorMethod(typeA)) { + return true; + } if (!typeADecl.heritageClauses) { return false; } @@ -636,6 +689,25 @@ export class TsUtils { return false; } + hasSymbolIteratorMethod(type: ts.Type): boolean { + const rhsTypeProps = this.tsTypeChecker.getPropertiesOfType(type); + return rhsTypeProps.some((prop) => { + const propDecl = TsUtils.getDeclaration(prop); + return ( + propDecl && + (ts.isMethodSignature(propDecl) || ts.isMethodDeclaration(propDecl)) && + ts.isComputedPropertyName(propDecl.name) && + this.isSymbolIteratorExpression(propDecl.name.expression) + ); + }); + } + + isStdIterableType(type: ts.Type): boolean { + void this; + const sym = type.getSymbol(); + return !!sym && sym.getName() === 'Iterable' && isStdLibrarySymbol(sym); + } + static reduceReference(t: ts.Type): ts.Type { return TsUtils.isTypeReference(t) && t.target !== t ? t.target : t; } @@ -922,10 +994,25 @@ export class TsUtils { return result; } - private static hasDefaultCtor(type: ts.Type): boolean { + private hasDefaultCtor(type: ts.Type): boolean { + const checkBaseTypes = (type: ts.Type): boolean => { + if (!this.options.arkts2) { + return true; + } + const baseTypes = type.getBaseTypes()?.filter((baseType) => { + return baseType.isClass(); + }); + if (!baseTypes || baseTypes.length === 0) { + return true; + } + return baseTypes.some((baseType: ts.Type) => { + return this.hasDefaultCtor(baseType); + }); + }; + // No members -> no explicit constructors -> there is default ctor if (type.symbol.members === undefined) { - return true; + return checkBaseTypes(type); } // has any constructor @@ -950,7 +1037,11 @@ export class TsUtils { }); // Has no any explicit constructor -> has implicit default constructor. - return !hasCtor || hasDefaultCtor; + if (!hasCtor) { + return checkBaseTypes(type); + } + + return hasDefaultCtor; } private static isAbstractClass(type: ts.Type): boolean { @@ -982,7 +1073,7 @@ export class TsUtils { return false; } - static validateObjectLiteralType(type: ts.Type | undefined): boolean { + validateObjectLiteralType(type: ts.Type | undefined): boolean { if (!type) { return false; } @@ -990,7 +1081,7 @@ export class TsUtils { type = TsUtils.reduceReference(type); return ( type.isClassOrInterface() && - TsUtils.hasDefaultCtor(type) && + this.hasDefaultCtor(type) && !TsUtils.hasReadonlyFields(type) && !TsUtils.isAbstractClass(type) ); @@ -1096,7 +1187,7 @@ export class TsUtils { return this.validateRecordObjectKeys(rhsExpr); } return ( - TsUtils.validateObjectLiteralType(lhsType) && !this.hasMethods(lhsType) && this.validateFields(lhsType, rhsExpr) + this.validateObjectLiteralType(lhsType) && !this.hasMethods(lhsType) && this.validateFields(lhsType, rhsExpr) ); } @@ -1798,6 +1889,22 @@ export class TsUtils { } getVariableDeclarationTypeNode(node: ts.Node): ts.TypeNode | undefined { + const sym = this.trueSymbolAtLocation(node); + if (sym === undefined) { + return undefined; + } + return TsUtils.getVariableSymbolDeclarationTypeNode(sym); + } + + static getVariableSymbolDeclarationTypeNode(sym: ts.Symbol): ts.TypeNode | undefined { + const decl = TsUtils.getDeclaration(sym); + if (!!decl && ts.isVariableDeclaration(decl)) { + return decl.type; + } + return undefined; + } + + getDeclarationTypeNode(node: ts.Node): ts.TypeNode | undefined { const sym = this.trueSymbolAtLocation(node); if (sym === undefined) { return undefined; @@ -1807,7 +1914,7 @@ export class TsUtils { static getSymbolDeclarationTypeNode(sym: ts.Symbol): ts.TypeNode | undefined { const decl = TsUtils.getDeclaration(sym); - if (!!decl && ts.isVariableDeclaration(decl)) { + if (!!decl && (ts.isVariableDeclaration(decl) || ts.isPropertyDeclaration(decl))) { return decl.type; } return undefined; @@ -1819,7 +1926,7 @@ export class TsUtils { } static symbolHasEsObjectType(sym: ts.Symbol): boolean { - const typeNode = TsUtils.getSymbolDeclarationTypeNode(sym); + const typeNode = TsUtils.getVariableSymbolDeclarationTypeNode(sym); return typeNode !== undefined && TsUtils.isEsObjectType(typeNode); } @@ -2065,7 +2172,9 @@ export class TsUtils { } } // We allow computed property names if expression is string literal or string Enum member - return ts.isStringLiteralLike(expr) || this.isEnumStringLiteral(computedProperty.expression); + return ( + !this.options.arkts2 && (ts.isStringLiteralLike(expr) || this.isEnumStringLiteral(computedProperty.expression)) + ); } skipPropertyInferredTypeCheck( @@ -3330,6 +3439,23 @@ export class TsUtils { ); } + static isAppStorageAccess(tsCallExpr: ts.CallExpression): boolean { + const propertyAccessExpr = tsCallExpr.expression; + if (!ts.isPropertyAccessExpression(propertyAccessExpr)) { + return false; + } + const accessedExpr = propertyAccessExpr.expression; + if (!ts.isIdentifier(accessedExpr)) { + return false; + } + + if (accessedExpr.text !== 'AppStorage') { + return false; + } + + return true; + } + static isArithmeticOperator(op: ts.BinaryOperatorToken): boolean { switch (op.kind) { case ts.SyntaxKind.PlusToken: @@ -3392,6 +3518,34 @@ export class TsUtils { return sanitizedDirectories[sanitizedDirectories.length - 1]; } + static checkFileExists( + importIncludesModule: boolean, + currentNode: ts.Node, + importFilePath: string, + projectPath: string, + extension: string = EXTNAME_ETS + ): boolean { + const currentModule = TsUtils.getModuleName(currentNode); + + /* + * some imports are like this + * ets/pages/test1 + * in this case, they are in the same module as the file we are trying to import to + * so we add the current module back in + */ + if (!importIncludesModule) { + if (!currentModule) { + return false; + } + + projectPath.concat(PATH_SEPARATOR + currentModule); + } + + const importedFile = path.resolve(projectPath, importFilePath + extension); + + return fs.existsSync(importedFile); + } + isImportedFromJS(identifier: ts.Identifier): boolean { const sym = this.trueSymbolAtLocation(identifier); const declaration = sym?.declarations?.[0]; @@ -3488,6 +3642,17 @@ export class TsUtils { return conversionMethod; } + static isInsideIfCondition(node: ts.Node): boolean { + let current: ts.Node | undefined = node; + while (current) { + if (ts.isIfStatement(current)) { + return true; + } + current = current.parent; + } + return false; + } + static isOhModule(path: string): boolean { return path.includes(ETS_MODULE); } @@ -3518,8 +3683,43 @@ export class TsUtils { return undefined; } + /** + * Checks whether an exported identifier is imported from an ArkTS1 file. + * @param exportIdentifier The exported identifier to check. + * @param node The node where the export occurs (used to get the current source file). + * @returns true if imported from ArkTS1, false if not, undefined if undetermined. + */ + isExportImportedFromArkTs1(exportIdentifier: ts.Identifier, node: ts.Node): boolean | undefined { + // Get the symbol associated with the identifier. + const symbol = this.tsTypeChecker.getSymbolAtLocation(exportIdentifier); + if (!symbol) { + return undefined; + } + + // If the symbol is an alias (imported), resolve the real symbol. + const realSymbol = + (symbol.flags & ts.SymbolFlags.Alias) !== 0 ? this.tsTypeChecker.getAliasedSymbol(symbol) : undefined; + + const declarations = realSymbol?.getDeclarations(); + if (!declarations || declarations.length === 0) { + return undefined; + } + + // Get the source file where the declaration is located. + const importSourceFile = declarations[0].getSourceFile(); + + // Ensure import is from ArkTS1 file and usage is in ArkTS1.2 file + const currentSourceFile = node.getSourceFile(); + return ( + importSourceFile.fileName.endsWith(EXTNAME_ETS) && + currentSourceFile.fileName.endsWith(EXTNAME_ETS) && + !TsUtils.isArkts12File(importSourceFile) && + TsUtils.isArkts12File(currentSourceFile) + ); + } + static isArkts12File(sourceFile: ts.SourceFile): boolean { - if (!sourceFile || !sourceFile.statements.length) { + if (!sourceFile?.statements.length) { return false; } const statements = sourceFile.statements; @@ -3544,16 +3744,115 @@ export class TsUtils { return str; } + static getCurrentModule(currentFileName: string): string { + const parts = currentFileName.split(PATH_SEPARATOR); + parts.pop(); + const currentModule = parts.join(PATH_SEPARATOR); + return currentModule; + } + + static resolveModuleAndCheckInterop(wholeProjectPath: string, callExpr: ts.CallExpression): InteropType | undefined { + const moduleName = callExpr.arguments[0]; + if (!ts.isStringLiteral(moduleName)) { + return undefined; + } + + const importedModule = path.resolve(wholeProjectPath, moduleName.text); + + const importedFile = TsUtils.resolveImportModule(importedModule); + if (!importedFile) { + return undefined; + } + + const importSource = ts.sys.readFile(importedFile); + if (!importSource) { + return undefined; + } + + return TsUtils.checkFileForInterop(importedFile, importSource); + } + + static resolveImportModule(importedModule: string): string | undefined { + const extensions = ['.ts', '.js', '.ets']; + for (const ext of extensions) { + const tryPath = path.resolve(importedModule + ext); + if (fs.existsSync(tryPath)) { + return tryPath; + } + } + + return undefined; + } + + static checkFileForInterop(fileName: string, importSource: string): InteropType { + if (fileName.endsWith(EXTNAME_JS)) { + return InteropType.JS; + } + + if (fileName.endsWith(EXTNAME_TS) && !fileName.endsWith(EXTNAME_D_TS)) { + return InteropType.TS; + } + + if (fileName.endsWith(EXTNAME_ETS) && !importSource.includes('\'use static\'')) { + return InteropType.LEGACY; + } + + return InteropType.NONE; + } + isJsImport(node: ts.Node): boolean { const symbol = this.trueSymbolAtLocation(node); if (symbol) { const declaration = symbol.declarations?.[0]; if (declaration) { const sourceFile = declaration.getSourceFile(); - const isFromJs = sourceFile.fileName.endsWith(EXTNAME_JS); - return isFromJs; + return sourceFile.fileName.endsWith(EXTNAME_JS); + } + } + return false; + } + + static typeIsCapturedFromEnclosingLocalScope(type: ts.Type, enclosingStmt: ts.Node): boolean { + let symNode: ts.Node | undefined = TsUtils.getDeclaration(type.getSymbol()); + + while (symNode) { + if (symNode === enclosingStmt) { + return true; } + symNode = symNode.parent; } + return false; } + + nodeCapturesValueFromEnclosingLocalScope(targetNode: ts.Node, enclosingStmt: ts.Node): boolean { + let found = false; + + const callback = (node: ts.Node): void => { + if (!ts.isIdentifier(node)) { + return; + } + const sym = this.tsTypeChecker.getSymbolAtLocation(node); + let symNode: ts.Node | undefined = TsUtils.getDeclaration(sym); + while (symNode) { + if (symNode === targetNode) { + // Symbol originated from the target node. Skip and continue to search + return; + } + if (symNode === enclosingStmt) { + found = true; + return; + } + symNode = symNode.parent; + } + }; + + const stopCondition = (node: ts.Node): boolean => { + void node; + return found; + }; + + forEachNodeInSubtree(targetNode, callback, stopCondition); + return found; + } } diff --git a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts index 14327f018d..f1a9c97b6b 100644 --- a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts +++ b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts @@ -64,37 +64,5 @@ export const arkts2Rules: number[] = [ 263, 300, 301, - 302, - 303, 304, - 305, - 306, - 307, - 308, - 309, - 310, - 311, - 312, - 313, - 314, - 315, - 316, - 319, - 320, - 321, - 330, - 331, - 332, - 333, - 334, - 335, - 336, - 337, - 338, - 339, - 340, - 341, - 342, - 343, - 344 ]; diff --git a/ets2panda/linter/src/lib/utils/consts/ArkTSUtilsAPI.ts b/ets2panda/linter/src/lib/utils/consts/ArkTSUtilsAPI.ts new file mode 100644 index 0000000000..dcddab08b5 --- /dev/null +++ b/ets2panda/linter/src/lib/utils/consts/ArkTSUtilsAPI.ts @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const ASON_TEXT = 'ASON'; +export const ASON_MODULES = ['@arkts.utils', '@kit.ArkTS']; +export const JSON_TEXT = 'JSON'; diff --git a/ets2panda/linter/src/lib/utils/consts/ArkuiConstants.ts b/ets2panda/linter/src/lib/utils/consts/ArkuiConstants.ts index aab38266ad..ec5b3df504 100644 --- a/ets2panda/linter/src/lib/utils/consts/ArkuiConstants.ts +++ b/ets2panda/linter/src/lib/utils/consts/ArkuiConstants.ts @@ -23,13 +23,22 @@ export const STATE_STYLES = 'stateStyles'; export const ARKUI_PACKAGE_NAME = '@kit.ArkUI'; export const VALUE_IDENTIFIER = 'value'; export const INDENT_STEP = 2; +export const MAKE_OBSERVED = 'makeObserved'; +export const ARKUI_STATE_MANAGEMENT = '@ohos.arkui.StateManagement'; export enum CustomDecoratorName { Extend = 'Extend', + LocalBuilder = 'LocalBuilder', Styles = 'Styles', AnimatableExtend = 'AnimatableExtend', Memo = 'Memo', - Observed = 'Observed' + Observed = 'Observed', + Layoutable = 'Layoutable' +} + +export enum StorageTypeName { + LocalStorage = 'LocalStorage', + AppStorage = 'AppStorage' } export const observedDecoratorName: Set = new Set([ @@ -45,7 +54,19 @@ export const observedDecoratorName: Set = new Set([ 'Track' ]); -export const skipImportDecoratorName: Set = new Set(['Extend', 'Styles', 'Sendable', 'Concurrent']); +export const skipImportDecoratorName: Set = new Set([ + 'Extend', + 'Styles', + 'Sendable', + 'Concurrent', + 'LocalBuilder' +]); + +export const deepCopyDecoratorName: Set = new Set(['Prop', 'StorageProp', 'LocalStorageProp']); + +export const deepCopyFunctionName: Set = new Set(['prop', 'setAndProp']); + +export const customLayoutFunctionName: Set = new Set(['onMeasureSize', 'onPlaceChildren']); export const ENTRY_DECORATOR_NAME = 'Entry'; export const ENTRY_STORAGE_PROPERITY = 'storage'; diff --git a/ets2panda/linter/src/lib/utils/consts/BuiltinGenericConstructor.ts b/ets2panda/linter/src/lib/utils/consts/BuiltinGenericConstructor.ts index dbadef70d4..211a86e886 100755 --- a/ets2panda/linter/src/lib/utils/consts/BuiltinGenericConstructor.ts +++ b/ets2panda/linter/src/lib/utils/consts/BuiltinGenericConstructor.ts @@ -19,5 +19,14 @@ export const BUILTIN_GENERIC_CONSTRUCTORS = new Set([ 'ReadonlyArray', 'Promise', 'WeakMap', - 'WeakSet' + 'WeakSet', + 'Deque', + 'ArrayList', + 'HashMap', + 'HashSet', + 'LinkedList', + 'PlainArray', + 'TreeMap', + 'TreeSet', + 'Queue' ]); diff --git a/ets2panda/linter/src/lib/utils/consts/BuiltinWhiteList.ts b/ets2panda/linter/src/lib/utils/consts/BuiltinWhiteList.ts new file mode 100644 index 0000000000..d4e4898557 --- /dev/null +++ b/ets2panda/linter/src/lib/utils/consts/BuiltinWhiteList.ts @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export enum BuiltinProblem { + LimitedThisArg = 'ThisArg', + SymbolIterator = 'SymbolIterator', + BuiltinNoCtorFunc = 'BuiltinNoCtorFunc', + BuiltinNoPropertyDescriptor = 'NoPropertyDescriptor', + MissingAttributes = 'MissingAttributes' +} + +export const SYMBOL_ITERATOR: string = 'Symbol.iterator'; + +export const GET_OWN_PROPERTY_NAMES_TEXT: string = 'Object.getOwnPropertyNames'; + +export const BUILTIN_DISABLE_CALLSIGNATURE = [ + 'AggregateError', + 'Array', + 'Array', + 'BigInt', + 'Boolean', + 'Date', + 'Error', + 'EvalError', + 'Number', + 'RangeError', + 'ReferenceError', + 'RegExp', + 'RegExp', + 'RegExp', + 'String', + 'SyntaxError', + 'TypeError', + 'URIError' +]; diff --git a/ets2panda/linter/src/lib/utils/consts/CollectionsAPI.ts b/ets2panda/linter/src/lib/utils/consts/CollectionsAPI.ts new file mode 100644 index 0000000000..a7c1698e3b --- /dev/null +++ b/ets2panda/linter/src/lib/utils/consts/CollectionsAPI.ts @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const COLLECTIONS_TEXT = 'collections'; +export const COLLECTIONS_MODULES = ['@arkts.collections', '@kit.ArkTS']; diff --git a/ets2panda/linter/src/lib/utils/consts/ConcurrentAPI.ts b/ets2panda/linter/src/lib/utils/consts/ConcurrentAPI.ts new file mode 100644 index 0000000000..5fc45d2e96 --- /dev/null +++ b/ets2panda/linter/src/lib/utils/consts/ConcurrentAPI.ts @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const USE_CONCURRENT = 'use concurrent'; +export const USE_SHARED = 'use shared'; +export const ESLIB_SHAREDARRAYBUFFER = 'SharedArrayBuffer'; +export const ESLIB_SHAREDMEMORY_FILENAME = 'lib.es2017.sharedmemory.d.ts'; +export const TASKPOOL_MODULES = ['@kit.ArkTS', '@ohos.taskpool']; diff --git a/ets2panda/linter/src/lib/utils/consts/InteropAPI.ts b/ets2panda/linter/src/lib/utils/consts/InteropAPI.ts index 5aa9c0be54..1d7f1f6745 100644 --- a/ets2panda/linter/src/lib/utils/consts/InteropAPI.ts +++ b/ets2panda/linter/src/lib/utils/consts/InteropAPI.ts @@ -40,3 +40,10 @@ export const SET_PROPERTY_BY_NAME = 'setPropertyByName'; export const GET_PROPERTY_BY_INDEX = 'getPropertyByIndex'; export const SET_PROPERTY_BY_INDEX = 'setPropertyByIndex'; export const TO_NUMBER = 'toNumber'; + +export enum InteropType { + TS = 'TS', + JS = 'JS', + LEGACY = '1.0', + NONE = 'none' +} diff --git a/ets2panda/linter/src/lib/utils/consts/LimitedStdAPI.ts b/ets2panda/linter/src/lib/utils/consts/LimitedStdAPI.ts index fb9fcb6e2c..ca9bdcd843 100644 --- a/ets2panda/linter/src/lib/utils/consts/LimitedStdAPI.ts +++ b/ets2panda/linter/src/lib/utils/consts/LimitedStdAPI.ts @@ -153,6 +153,7 @@ export const LIMITED_STD_API = new Map = { - '@kit.ArkTS': ['taskpool', 'ArkTSUtils'], - '@ohos.process': ['process'] + '@kit.ArkTS': ['taskpool', 'ArkTSUtils', 'process'], + '@ohos.process': ['process'], + '@ohos.taskpool': ['taskpool'] }; diff --git a/ets2panda/linter/test/sdkwhite/GlobalThisError&TypeQuery.ets b/ets2panda/linter/src/lib/utils/consts/Literals.ts similarity index 93% rename from ets2panda/linter/test/sdkwhite/GlobalThisError&TypeQuery.ets rename to ets2panda/linter/src/lib/utils/consts/Literals.ts index 359249a5ec..3ca262e108 100644 --- a/ets2panda/linter/test/sdkwhite/GlobalThisError&TypeQuery.ets +++ b/ets2panda/linter/src/lib/utils/consts/Literals.ts @@ -13,4 +13,4 @@ * limitations under the License. */ -import { worker } from '@kit.ArkTS'; // Error \ No newline at end of file +export const STRING_ERROR_LITERAL = 'ERROR'; diff --git a/ets2panda/linter/test/sdkwhite/SendablePropType.ets b/ets2panda/linter/src/lib/utils/consts/MethodDeclaration.ts similarity index 85% rename from ets2panda/linter/test/sdkwhite/SendablePropType.ets rename to ets2panda/linter/src/lib/utils/consts/MethodDeclaration.ts index 02860a5f30..7705ae690e 100644 --- a/ets2panda/linter/test/sdkwhite/SendablePropType.ets +++ b/ets2panda/linter/src/lib/utils/consts/MethodDeclaration.ts @@ -13,4 +13,4 @@ * limitations under the License. */ -import sendablePhotoAccessHelper from "@ohos.file.sendablePhotoAccessHelper" // Error +export const METHOD_DECLARATION = 'MethodDeclaration'; diff --git a/ets2panda/linter/test/interop/oh_modules/ts_decorator.ts b/ets2panda/linter/src/lib/utils/consts/MethodSignature.ts similarity index 84% rename from ets2panda/linter/test/interop/oh_modules/ts_decorator.ts rename to ets2panda/linter/src/lib/utils/consts/MethodSignature.ts index 511202fa79..d1a2ad228e 100644 --- a/ets2panda/linter/test/interop/oh_modules/ts_decorator.ts +++ b/ets2panda/linter/src/lib/utils/consts/MethodSignature.ts @@ -1,17 +1,16 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -export function MyClassDecorator(klass: Object) { } -export function MyClassDecorator2(target: Function) { } \ No newline at end of file +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const METHOD_SIGNATURE = 'MethodSignature'; \ No newline at end of file diff --git a/ets2panda/linter/src/lib/utils/consts/OptionalMethod.ts b/ets2panda/linter/src/lib/utils/consts/OptionalMethod.ts new file mode 100644 index 0000000000..a262a88b17 --- /dev/null +++ b/ets2panda/linter/src/lib/utils/consts/OptionalMethod.ts @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const OPTIONAL_METHOD = 'OptionalMethod'; \ No newline at end of file diff --git a/ets2panda/linter/src/lib/utils/consts/RuntimeCheckAPI.ts b/ets2panda/linter/src/lib/utils/consts/RuntimeCheckAPI.ts new file mode 100644 index 0000000000..48678d03cc --- /dev/null +++ b/ets2panda/linter/src/lib/utils/consts/RuntimeCheckAPI.ts @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type ts from 'typescript'; + +export type ArrayAccess = { + pos: number; + accessingIdentifier: 'number' | ts.Identifier; + arrayIdent: ts.Identifier; +}; + +export type UncheckedIdentifier = ts.Identifier | typeof NUMBER_LITERAL | undefined; +export type CheckedIdentifier = ts.Identifier | typeof NUMBER_LITERAL; + +export const NUMBER_LITERAL = 'number'; + +export enum LoopConditionChecked { + LEFT, + RIGHT, + NOT_CHECKED +} + +export enum CheckResult { + SKIP, + CHECKED +} diff --git a/ets2panda/linter/src/lib/utils/consts/SdkWhitelist.ts b/ets2panda/linter/src/lib/utils/consts/SdkWhitelist.ts index 3c8dd7b5cf..da2140601b 100644 --- a/ets2panda/linter/src/lib/utils/consts/SdkWhitelist.ts +++ b/ets2panda/linter/src/lib/utils/consts/SdkWhitelist.ts @@ -13,18 +13,40 @@ * limitations under the License. */ +export enum SdkProblem { + LimitedVoidType = 'LimitedVoidType', + ConstructorIface = 'ConstructorIface', + LiteralAsPropertyName = 'LiteralAsPropertyName', + OptionalMethod = 'OptionalMethod', + ConstructorFuncs = 'ConstructorFuncs', + IndexedAccessType = 'IndexedAccessType', + SendablePropType = 'SendablePropType', + TypeQuery = 'TypeQuery', + GlobalThisError = 'GlobalThisError', + InterfaceExtendsClass = 'InterfaceExtendsClass', + DeclWithDuplicateName = 'DeclWithDuplicateName', + ComputedPropertyName = 'ComputedPropertyName' +} + +export enum SdkNameInfo { + ParentApiName = 'parent_api_name', + ImportPath = 'import_path' +} + +export const ARKTS_WHITE_API_PATH_TEXTSTYLE = 'component/styled_string.d.ts'; + // Define function argument class export class ApiFuncArg { name: string; type: string; is_optional: boolean; - hasDefault: boolean; + has_default?: boolean; constructor(data: Partial) { this.name = data.name || ''; this.type = data.type || ''; this.is_optional = data.is_optional || false; - this.hasDefault = data.hasDefault || false; + this.has_default = data.has_default || undefined; } } @@ -42,46 +64,49 @@ export class ParentApi { // Define the API information class export class ApiInfo { problem: string; - api_name: string; + api_name?: string; api_type: string; - api_optional: boolean; - api_auto_fix: boolean; - api_auto_fix_context: string; - target_type: string; - api_func_args: ApiFuncArg[]; + api_optional?: boolean; + api_auto_fix?: boolean; + api_auto_fix_context?: string; + api_func_args?: ApiFuncArg[]; parent_api: ParentApi[]; - methd_return_type: string; - codeKind: number; + method_return_type?: string; + api_property_type?: string; + code_kind: number; constructor(data: Partial) { this.problem = data.problem || ''; - this.api_name = data.api_name || ''; + this.api_name = data.api_name || undefined; this.api_type = data.api_type || ''; - this.api_optional = data.api_optional || false; - this.api_auto_fix = data.api_auto_fix || false; - this.api_auto_fix_context = data.api_auto_fix_context || ''; - this.target_type = data.target_type || ''; - this.api_func_args = (data.api_func_args || []).map((arg) => { - return new ApiFuncArg(arg); - }); + this.api_optional = data.api_optional || undefined; + this.api_auto_fix = data.api_auto_fix || undefined; + this.api_auto_fix_context = data.api_auto_fix_context || undefined; + this.api_func_args = + (data.api_func_args || []).map((arg) => { + return new ApiFuncArg(arg); + }) || undefined; this.parent_api = (data.parent_api || []).map((parent) => { return new ParentApi(parent); }); - this.methd_return_type = data.methd_return_type || ''; - this.codeKind = data.codeKind || 0; + this.method_return_type = data.method_return_type || undefined; + this.api_property_type = data.api_property_type || undefined; + this.code_kind = data.code_kind || 0; } } // Define the API list item class export class ApiListItem { import_path: string[]; - file_path: string[]; + file_path: string; api_info: ApiInfo; + is_global: boolean; constructor(data: Partial) { this.import_path = data.import_path || []; - this.file_path = data.file_path || []; + this.file_path = data.file_path || ''; this.api_info = new ApiInfo(data.api_info || {}); + this.is_global = data.is_global || false; } } diff --git a/ets2panda/linter/src/lib/utils/consts/SendableAPI.ts b/ets2panda/linter/src/lib/utils/consts/SendableAPI.ts index e6a6cdae37..2809e8afab 100644 --- a/ets2panda/linter/src/lib/utils/consts/SendableAPI.ts +++ b/ets2panda/linter/src/lib/utils/consts/SendableAPI.ts @@ -17,6 +17,8 @@ import * as ts from 'typescript'; export const SENDABLE_DECORATOR = 'Sendable'; export const CONCURRENT_DECORATOR = 'Concurrent'; +export const TASKPOOL = 'taskpool'; +export const ISCONCURRENT = 'isConcurrent'; export const SENDABLE_DECORATOR_NODES = [ ts.SyntaxKind.ClassDeclaration, diff --git a/ets2panda/linter/src/lib/utils/consts/StringLiteral.ts b/ets2panda/linter/src/lib/utils/consts/StringLiteral.ts index 4b1653fb1f..a525f8d321 100644 --- a/ets2panda/linter/src/lib/utils/consts/StringLiteral.ts +++ b/ets2panda/linter/src/lib/utils/consts/StringLiteral.ts @@ -20,4 +20,8 @@ export const STRINGLITERAL_INT = 'int'; export const STRINGLITERAL_BYTE = 'byte'; export const STRINGLITERAL_SHORT = 'short'; export const STRINGLITERAL_LONG = 'long'; +export const STRINGLITERAL_CHAR = 'char'; export const STRINGLITERAL_ANY = 'ANY'; +export const STRINGLITERAL_ENUM = 'enum'; +export const STRINGLITERAL_FROM = 'from'; +export const STRINGLITERAL_ARRAY = 'Array'; \ No newline at end of file diff --git a/ets2panda/linter/src/lib/utils/consts/TaskpoolAPI.ts b/ets2panda/linter/src/lib/utils/consts/TaskpoolAPI.ts new file mode 100644 index 0000000000..5414202732 --- /dev/null +++ b/ets2panda/linter/src/lib/utils/consts/TaskpoolAPI.ts @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const STDLIB_TASKPOOL_OBJECT_NAME = 'taskpool'; +export const STDLIB_TASK_CLASS_NAME = 'Task'; + +export const DEPRECATED_TASKPOOL_METHOD_SETCLONELIST = 'setCloneList'; +export const DEPRECATED_TASKPOOL_METHOD_SETTRANSFERLIST = 'setTransferList'; diff --git a/ets2panda/linter/src/lib/utils/functions/ArrayUtils.ts b/ets2panda/linter/src/lib/utils/functions/ArrayUtils.ts index ffd5a98fa4..83a75ea2ce 100644 --- a/ets2panda/linter/src/lib/utils/functions/ArrayUtils.ts +++ b/ets2panda/linter/src/lib/utils/functions/ArrayUtils.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/ets2panda/linter/src/lib/utils/functions/IsStruct.ts b/ets2panda/linter/src/lib/utils/functions/IsStruct.ts index b766931529..7b450748c1 100644 --- a/ets2panda/linter/src/lib/utils/functions/IsStruct.ts +++ b/ets2panda/linter/src/lib/utils/functions/IsStruct.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2024 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -14,7 +14,7 @@ */ import type * as ts from 'typescript'; -import { LinterConfig } from '../../TypeScriptLinterConfig'; +import { TypeScriptLinterConfig } from '../../TypeScriptLinterConfig'; export function isStruct(symbol: ts.Symbol): boolean { if (!symbol.declarations) { @@ -29,7 +29,7 @@ export function isStruct(symbol: ts.Symbol): boolean { } export function isStructDeclarationKind(kind: ts.SyntaxKind): boolean { - return LinterConfig.tsSyntaxKindNames[kind] === 'StructDeclaration'; + return TypeScriptLinterConfig.tsSyntaxKindNames[kind] === 'StructDeclaration'; } export function isStructDeclaration(node: ts.Node): boolean { diff --git a/ets2panda/linter/src/lib/utils/functions/LibraryTypeCallDiagnosticChecker.ts b/ets2panda/linter/src/lib/utils/functions/LibraryTypeCallDiagnosticChecker.ts index 9d38e6e663..453f5f7e9a 100644 --- a/ets2panda/linter/src/lib/utils/functions/LibraryTypeCallDiagnosticChecker.ts +++ b/ets2panda/linter/src/lib/utils/functions/LibraryTypeCallDiagnosticChecker.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Huawei Device Co., Ltd. + * Copyright (c) 2023-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/ets2panda/linter/src/sdk/linter_1_1/LintParameter.ts b/ets2panda/linter/src/sdk/linter_1_1/LintParameter.ts index ed31ce04a2..f3cdd6f08f 100644 --- a/ets2panda/linter/src/sdk/linter_1_1/LintParameter.ts +++ b/ets2panda/linter/src/sdk/linter_1_1/LintParameter.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -14,16 +14,15 @@ */ import type * as ts from 'typescript'; -import type { InteropTypescriptLinter } from '../../lib/InteropTypescriptLinter'; -import type { TypeScriptLinter } from '../../lib/TypeScriptLinter'; import type { IncrementalLinterState } from './IncrementalLinter'; +import type { SdkOptions } from './SdkOptions'; export interface LintParameter { incrementalLinterState: IncrementalLinterState; - typeScriptLinter: TypeScriptLinter; - interopTypescriptLinter: InteropTypescriptLinter; tscStrictDiagnostics: Map; diagnostics: ts.Diagnostic[]; etsLoaderPath?: string; tsImportSendableEnable?: boolean; + program: ts.Program; + sdkOptions?: SdkOptions; } diff --git a/ets2panda/linter/src/sdk/linter_1_1/RunArkTSLinter.ts b/ets2panda/linter/src/sdk/linter_1_1/RunArkTSLinter.ts index 2f950ae644..cb6a206c37 100644 --- a/ets2panda/linter/src/sdk/linter_1_1/RunArkTSLinter.ts +++ b/ets2panda/linter/src/sdk/linter_1_1/RunArkTSLinter.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -76,18 +76,17 @@ export function runArkTSLinter( timePrinterInstance.appendTime(TimePhase.GET_TSC_DIAGNOSTICS); const etsLoaderPath = program.getCompilerOptions().etsLoaderPath; const tsImportSendableEnable = program.getCompilerOptions().tsImportSendableEnable; - const typeScriptLinter = createTypeScriptLinter(program, tscStrictDiagnostics, sdkOptions); LibraryTypeCallDiagnosticChecker.instance.rebuildTscDiagnostics(tscStrictDiagnostics); - const interopTypescriptLinter = createInteropTypescriptLinter(program, !!sdkOptions?.isUseRtLogic); - processFiles(srcFiles, { + const lintParam: LintParameter = { incrementalLinterState, - typeScriptLinter, - interopTypescriptLinter, tscStrictDiagnostics, diagnostics, etsLoaderPath, - tsImportSendableEnable - }); + tsImportSendableEnable, + program, + sdkOptions + }; + processFiles(srcFiles, lintParam, tscStrictDiagnostics); timePrinterInstance.appendTime(TimePhase.LINT); if (buildInfoWriteFile) { IncrementalLinterState.emitBuildInfo(buildInfoWriteFile, tscDiagnosticsLinter.getBuilderProgram()); @@ -97,14 +96,18 @@ export function runArkTSLinter( return diagnostics; } -function processFiles(srcFiles: ts.SourceFile[], lintParameter: LintParameter): void { +function processFiles( + srcFiles: ts.SourceFile[], + lintParameter: LintParameter, + tscStrictDiagnostics: Map +): void { for (const fileToLint of srcFiles) { const scriptKind = getScriptKind(fileToLint); if (scriptKind !== ts.ScriptKind.ETS && scriptKind !== ts.ScriptKind.TS) { continue; } - const currentDiagnostics = getDiagnostic(fileToLint, scriptKind, lintParameter); + const currentDiagnostics = getDiagnostic(fileToLint, scriptKind, lintParameter, tscStrictDiagnostics); lintParameter.diagnostics.push(...currentDiagnostics); lintParameter.incrementalLinterState.updateDiagnostics(fileToLint, currentDiagnostics); } @@ -113,19 +116,20 @@ function processFiles(srcFiles: ts.SourceFile[], lintParameter: LintParameter): function getDiagnostic( fileToLint: ts.SourceFile, scriptKind: ts.ScriptKind, - lintParameter: LintParameter + lintParameter: LintParameter, + tscStrictDiagnostics: Map ): ts.Diagnostic[] { let currentDiagnostics: ts.Diagnostic[] = []; if (lintParameter.incrementalLinterState.isFileChanged(fileToLint)) { if (scriptKind === ts.ScriptKind.ETS) { - lintParameter.typeScriptLinter.lint(fileToLint); + const typeScriptLinter = createTypeScriptLinter(fileToLint, lintParameter, tscStrictDiagnostics); + typeScriptLinter.lint(); // Get list of bad nodes from the current run. currentDiagnostics = lintParameter.tscStrictDiagnostics.get(path.normalize(fileToLint.fileName)) ?? []; - lintParameter.typeScriptLinter.problemsInfos.forEach((x) => { + typeScriptLinter.problemsInfos.forEach((x) => { return currentDiagnostics.push(translateDiag(fileToLint, x)); }); - lintParameter.typeScriptLinter.problemsInfos.length = 0; } else { if ( path.basename(fileToLint.fileName).toLowerCase(). @@ -145,11 +149,11 @@ function getDiagnostic( return currentDiagnostics; } - lintParameter.interopTypescriptLinter.lint(fileToLint); - lintParameter.interopTypescriptLinter.problemsInfos.forEach((x) => { + const interopTypescriptLinter = createInteropTypescriptLinter(lintParameter.program, fileToLint, lintParameter); + interopTypescriptLinter.lint(); + interopTypescriptLinter.problemsInfos.forEach((x) => { return currentDiagnostics.push(translateDiag(fileToLint, x)); }); - lintParameter.interopTypescriptLinter.problemsInfos.length = 0; } } else { // Get diagnostics from old run. @@ -169,34 +173,38 @@ function getSrcFiles(program: ts.Program, srcFile?: ts.SourceFile): ts.SourceFil } function createTypeScriptLinter( - program: ts.Program, - tscStrictDiagnostics: Map, - sdkOptions?: SdkOptions + sourceFile: ts.SourceFile, + lintParameter: LintParameter, + tscStrictDiagnostics: Map ): TypeScriptLinter { TypeScriptLinter.initGlobals(); return new TypeScriptLinter( - program.getLinterTypeChecker(), + lintParameter.program.getLinterTypeChecker(), { - ideMode: true, - enableAutofix: sdkOptions?.needAutoFix, - useRtLogic: sdkOptions?.isUseRtLogic, - compatibleSdkVersion: program.getCompilerOptions().compatibleSdkVersion, - compatibleSdkVersionStage: program.getCompilerOptions().compatibleSdkVersionStage + enableAutofix: lintParameter.sdkOptions?.needAutoFix, + useRtLogic: lintParameter.sdkOptions?.isUseRtLogic, + compatibleSdkVersion: lintParameter.program.getCompilerOptions().compatibleSdkVersion, + compatibleSdkVersionStage: lintParameter.program.getCompilerOptions().compatibleSdkVersionStage }, + sourceFile, tscStrictDiagnostics ); } -function createInteropTypescriptLinter(program: ts.Program, useRtLogic: boolean): InteropTypescriptLinter { +function createInteropTypescriptLinter( + program: ts.Program, + sourceFile: ts.SourceFile, + lintParameter: LintParameter +): InteropTypescriptLinter { InteropTypescriptLinter.initGlobals(); return new InteropTypescriptLinter( program.getLinterTypeChecker(), program.getCompilerOptions(), { - ideMode: true, - useRtLogic: useRtLogic + etsLoaderPath: lintParameter.etsLoaderPath, + useRtLogic: lintParameter.sdkOptions?.isUseRtLogic }, - program.getCompilerOptions().etsLoaderPath + sourceFile ); } diff --git a/ets2panda/linter/src/testRunner/Consts.ts b/ets2panda/linter/src/testRunner/Consts.ts new file mode 100644 index 0000000000..cc5c33ea35 --- /dev/null +++ b/ets2panda/linter/src/testRunner/Consts.ts @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const TAB = ' '; +export const RESULTS_DIR = 'results'; + +export const DIFF_EXT = '.diff'; +export const TEST_EXTENSION_ETS = '.ets'; +export const TEST_EXTENSION_D_ETS = '.d.ets'; + +export const MIGRATE_RESULT_SUFFIX = '.migrate'; diff --git a/ets2panda/linter/src/testRunner/FileUtil.ts b/ets2panda/linter/src/testRunner/FileUtil.ts new file mode 100644 index 0000000000..2d21d616d3 --- /dev/null +++ b/ets2panda/linter/src/testRunner/FileUtil.ts @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as fs from 'node:fs'; + +export function readLines(filePath: string): string[] { + const text = fs.readFileSync(filePath).toString(); + return text.split(/\r\n|\n|\r/); +} diff --git a/ets2panda/linter/src/testRunner/LintTest.ts b/ets2panda/linter/src/testRunner/LintTest.ts new file mode 100644 index 0000000000..02db53dd49 --- /dev/null +++ b/ets2panda/linter/src/testRunner/LintTest.ts @@ -0,0 +1,199 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import type { CommandLineOptions } from '../lib/CommandLineOptions'; +import type { LinterConfig } from '../lib/LinterConfig'; +import { lint } from '../lib/LinterRunner'; +import { Logger } from '../lib/Logger'; +import { compileLintOptions } from '../lib/ts-compiler/Compiler'; +import type { TestModeProperties } from './TestMode'; +import { TestMode } from './TestMode'; +import { transformProblemInfos } from './TestUtil'; +import type { TestProblemInfo, TestResult } from './TestResult'; +import { validateTestResult } from './TestResult'; +import type { LintRunResult } from '../lib/LintRunResult'; +import { DIFF_EXT, RESULTS_DIR, TAB } from './Consts'; +import type { Autofix } from '../lib/autofixes/Autofixer'; +import type { CreateLintTestOptions } from './TestFactory'; + +export class LintTest { + readonly testDir: string; + readonly testFile: string; + readonly testModeProps: TestModeProperties; + readonly cmdOptions: CommandLineOptions; + + constructor(createLintTestOpts: CreateLintTestOptions) { + this.testDir = createLintTestOpts.testDir; + this.testFile = createLintTestOpts.testFile; + this.testModeProps = createLintTestOpts.testModeProps; + this.cmdOptions = createLintTestOpts.cmdOptions; + } + + run(): boolean { + Logger.info(`Running test ${this.testFile} (${TestMode[this.testModeProps.mode]} mode)`); + + const linterConfig = this.compile(); + const linterResult = lint(linterConfig); + return this.validate(linterResult); + } + + compile(): LinterConfig { + return compileLintOptions(this.cmdOptions); + } + + validate(actualLinterResult: LintRunResult): boolean { + // Get actual test results. + const fileProblems = actualLinterResult.problemsInfos.get(path.normalize(this.cmdOptions.inputFiles[0])); + if (fileProblems === undefined) { + return true; + } + const actualResult = transformProblemInfos(fileProblems, this.testModeProps.mode); + + // Read file with expected test result. + const resultDiff = this.compareLintResult(actualResult); + + // Write file with actual test results. + this.writeLintResultFile(actualResult, resultDiff); + return !resultDiff; + } + + private static readLintResultFile(testDir: string, testResultFileName: string): TestProblemInfo[] { + const filePath = path.join(testDir, testResultFileName); + try { + const testResult = fs.readFileSync(filePath).toString(); + return validateTestResult(JSON.parse(testResult)).result; + } catch (error) { + throw new Error(`Failed to process ${filePath}: ${(error as Error).message}`); + } + } + + private compareLintResult(actual: TestProblemInfo[]): string { + // Read file with expected test result. + let diff: string = ''; + const testResultFileName = this.testFile + this.testModeProps.resultFileExt; + try { + let expected = LintTest.readLintResultFile(this.testDir, testResultFileName); + + /** + * The exclusive field is added to identify whether the use case is exclusive to the RT or SDK + * RT means the RT exclusive + * SDK means the SDK exclusive + * undefined means shared + */ + expected = expected.filter((x) => { + return !x?.exclusive || x.exclusive === (this.cmdOptions.linterOptions.useRtLogic ? 'RT' : 'SDK'); + }); + + if (!expected || expected.length !== actual.length) { + const expectedResultCount = expected ? expected.length : 0; + diff = `Expected count: ${expectedResultCount} vs actual count: ${actual.length}`; + } else { + diff = LintTest.expectedAndActualMatch(expected, actual); + } + + if (diff) { + Logger.info(`${TAB}Lint test failed. Expected and actual results differ:\n${diff}`); + } + } catch (error) { + // Write error message to diff, as non-empty diff indicates that test has failed. + diff = (error as Error).message; + Logger.info(`${TAB}Failed to compare expected and actual results. ` + diff); + } + + return diff; + } + + private static expectedAndActualMatch(expectedNodes: TestProblemInfo[], actualNodes: TestProblemInfo[]): string { + // Compare expected and actual results. + for (let i = 0; i < actualNodes.length; i++) { + const actual = actualNodes[i]; + const expected = expectedNodes[i]; + if (!LintTest.locationMatch(expected, actual) || actual.problem !== expected.problem) { + return LintTest.reportLintResultDiff(expected, actual); + } + if (!LintTest.autofixArraysMatch(expected.autofix, actual.autofix)) { + return LintTest.reportLintResultDiff(expected, actual); + } + if (expected.suggest && actual.suggest !== expected.suggest) { + return LintTest.reportLintResultDiff(expected, actual); + } + if (expected.rule && actual.rule !== expected.rule) { + return LintTest.reportLintResultDiff(expected, actual); + } + if (expected.severity && actual.severity !== expected.severity) { + return LintTest.reportLintResultDiff(expected, actual); + } + } + + return ''; + } + + private static locationMatch(expected: TestProblemInfo, actual: TestProblemInfo): boolean { + return ( + actual.line === expected.line && + actual.column === expected.column && + (!expected.endLine || actual.endLine === expected.endLine) && + (!expected.endColumn || actual.endColumn === expected.endColumn) + ); + } + + private static autofixArraysMatch(expected: Autofix[] | undefined, actual: Autofix[] | undefined): boolean { + if (!expected && !actual) { + return true; + } + if (!(expected && actual) || expected.length !== actual.length) { + return false; + } + for (let i = 0; i < actual.length; ++i) { + if ( + actual[i].start !== expected[i].start || + actual[i].end !== expected[i].end || + actual[i].replacementText !== expected[i].replacementText + ) { + return false; + } + } + return true; + } + + private writeLintResultFile(actual: TestProblemInfo[], diff: string): void { + const actualResultsDir = path.join(this.testDir, RESULTS_DIR); + if (!fs.existsSync(actualResultsDir)) { + fs.mkdirSync(actualResultsDir); + } + + const actualTestResult: TestResult = { result: actual }; + const actualResultJSON = JSON.stringify(actualTestResult, null, 4); + fs.writeFileSync(path.join(actualResultsDir, this.testFile + this.testModeProps.resultFileExt), actualResultJSON); + + if (diff) { + fs.writeFileSync(path.join(actualResultsDir, this.testFile + this.testModeProps.resultFileExt + DIFF_EXT), diff); + } + } + + private static reportLintResultDiff(expected: TestProblemInfo, actual: TestProblemInfo): string { + const expectedNode = JSON.stringify({ nodes: [expected] }, null, 4); + const actualNode = JSON.stringify({ nodes: [actual] }, null, 4); + + const diff = `Expected: +${expectedNode} +Actual: +${actualNode}`; + + return diff; + } +} diff --git a/ets2panda/linter/src/testRunner/MigrateTest.ts b/ets2panda/linter/src/testRunner/MigrateTest.ts new file mode 100644 index 0000000000..a849e1db74 --- /dev/null +++ b/ets2panda/linter/src/testRunner/MigrateTest.ts @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import type { LinterConfig } from '../lib/LinterConfig'; +import { Logger } from '../lib/Logger'; +import { compileLintOptions } from '../lib/ts-compiler/Compiler'; +import type { LintRunResult } from '../lib/LintRunResult'; +import { DIFF_EXT, MIGRATE_RESULT_SUFFIX, RESULTS_DIR, TAB } from './Consts'; +import { LintTest } from './LintTest'; +import type { CreateLintTestOptions } from './TestFactory'; +import { readLines } from './FileUtil'; + +export class MigrateTest extends LintTest { + constructor(createLintTestOpts: CreateLintTestOptions) { + super(createLintTestOpts); + } + + compile(): LinterConfig { + this.cmdOptions.linterOptions.migratorMode = true; + + // Set filepath mapping to write migration result at 'results' dir instead of modifying original test file + const filePathMap = new Map(); + filePathMap.set( + path.normalize(path.join(this.testDir, this.testFile)), + path.normalize(this.getActualMigrateResultsFilePath()) + ); + this.cmdOptions.linterOptions.migrationFilePathMap = filePathMap; + + return compileLintOptions(this.cmdOptions); + } + + validate(actualLinterResult: LintRunResult): boolean { + const validateBase = super.validate(actualLinterResult); + const validateMigrateResult = this.validateMigrateResult(); + return validateBase && validateMigrateResult; + } + + private validateMigrateResult(): boolean { + this.writeMigrationResultForUnchangedFiles(); + const resultDiff = this.compareMigrateResult(); + if (resultDiff) { + this.writeMigrateDiff(resultDiff); + } + return !resultDiff; + } + + private compareMigrateResult(): string { + let diff: string = ''; + try { + const expectedResult = readFileLines(this.getExpectedMigrateResultsFilePath()); + const actualResult = readFileLines(this.getActualMigrateResultsFilePath()); + + if (expectedResult.length !== actualResult.length) { + diff = `Expected lines: ${expectedResult.length} vs actual lines: ${actualResult.length}`; + } else { + diff = MigrateTest.compareTextLines(expectedResult, actualResult); + } + + if (diff) { + Logger.info(`${TAB}Migration test failed. Expected and actual results differ:\n${diff}`); + } + } catch (error) { + // Write error message to diff, as non-empty diff indicates that test has failed. + diff = (error as Error).message; + Logger.info(`${TAB}Failed to compare expected and actual results. ` + diff); + } + + return diff; + } + + private static compareTextLines(expected: string[], actual: string[]): string { + for (let i = 0; i < expected.length && i < actual.length; i++) { + if (expected[i] !== actual[i]) { + const diff = `Difference at line ${i + 1} +Expected: +${expected[i]} +Actual: +${actual[i]}`; + return diff; + } + } + return ''; + } + + writeMigrateDiff(diff: string): void { + fs.writeFileSync(this.getActualMigrateResultsFilePath() + DIFF_EXT, diff); + } + + writeMigrationResultForUnchangedFiles(): void { + + /* + * If test file doesn't produce any autofix, the migration result won't be created. + * In such case, use original text of the test file as migration result. + */ + const filePathMap = this.cmdOptions.linterOptions.migrationFilePathMap; + if (!filePathMap) { + return; + } + filePathMap.forEach((targetFile, srcFile) => { + if (fs.existsSync(targetFile)) { + return; + } + fs.copyFileSync(srcFile, targetFile); + }); + } + + private getMigrateResultFileName(): string { + return this.testFile + MIGRATE_RESULT_SUFFIX + path.extname(this.testFile); + } + + private getExpectedMigrateResultsFilePath(): string { + return path.join(this.testDir, this.getMigrateResultFileName()); + } + + private getActualMigrateResultsFilePath(): string { + return path.join(this.testDir, RESULTS_DIR, this.getMigrateResultFileName()); + } +} + +function readFileLines(filePath: string): string[] { + try { + return readLines(filePath); + } catch (error) { + throw new Error(`Failed to process ${filePath}: ${(error as Error).message}`); + } +} diff --git a/ets2panda/linter/src/testRunner/RunTestFileOptions.ts b/ets2panda/linter/src/testRunner/RunTestFileOptions.ts new file mode 100644 index 0000000000..0f894ccaf7 --- /dev/null +++ b/ets2panda/linter/src/testRunner/RunTestFileOptions.ts @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { TestRunnerOptions } from './TestRunnerOptions'; + +export interface RunTestFileOptions { + testDir: string; + testFile: string; + testRunnerOpts: TestRunnerOptions; +} diff --git a/ets2panda/linter/src/testRunner/TestArgs.ts b/ets2panda/linter/src/testRunner/TestArgs.ts index d18564e118..f29c782f7b 100644 --- a/ets2panda/linter/src/testRunner/TestArgs.ts +++ b/ets2panda/linter/src/testRunner/TestArgs.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,8 +13,11 @@ * limitations under the License. */ +import * as fs from 'node:fs'; +import * as path from 'node:path'; import * as yup from 'yup'; +const ARGS_CONFIG_EXT = '.args.json'; const TAB = ' '; /** @@ -60,6 +63,7 @@ export interface TestArguments { /** * Enables 'migrate' mode, runs test with '--migrate' option. + * Performs code migration and produces new test code. */ migrate?: string; }; @@ -90,3 +94,17 @@ export function validateTestArgs(value: object): TestArguments { throw error; } } + +export function readTestArgsFile(testDir: string, testFile: string): TestArguments | undefined { + const argsFileName = path.join(testDir, testFile + ARGS_CONFIG_EXT); + if (fs.existsSync(argsFileName)) { + try { + const data = fs.readFileSync(argsFileName).toString(); + const json = JSON.parse(data); + return validateTestArgs(json); + } catch (error) { + throw new Error(`Failed to process ${argsFileName}: ${(error as Error).message}`); + } + } + return undefined; +} diff --git a/ets2panda/linter/src/testRunner/TestFactory.ts b/ets2panda/linter/src/testRunner/TestFactory.ts new file mode 100644 index 0000000000..ef4a2906ab --- /dev/null +++ b/ets2panda/linter/src/testRunner/TestFactory.ts @@ -0,0 +1,134 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'node:path'; +import type { CommandLineOptions } from '../lib/CommandLineOptions'; +import type { LinterOptions } from '../lib/LinterOptions'; +import { LintTest } from './LintTest'; +import type { RunTestFileOptions } from './RunTestFileOptions'; +import { parseCommandLine } from '../cli/CommandLineParser'; +import { getCommandLineArguments } from './CommandLineUtil'; +import type { TestModeProperties } from './TestMode'; +import { DEFAULT_MODE_PROPERTIES, TestMode, testModePropsMap } from './TestMode'; +import type { TestArguments } from './TestArgs'; +import { readTestArgsFile } from './TestArgs'; +import { MigrateTest } from './MigrateTest'; + +interface CreateTestOptions { + runTestFileOpts: RunTestFileOptions; + testModeProps: TestModeProperties; + testModeArgs?: string; + testCommonOpts?: LinterOptions; +} + +export interface CreateLintTestOptions { + testDir: string; + testFile: string; + testModeProps: TestModeProperties; + cmdOptions: CommandLineOptions; +} + +export function createTests(runTestFileOpts: RunTestFileOptions): LintTest[] { + const testArgs = readTestArgsFile(runTestFileOpts.testDir, runTestFileOpts.testFile); + return testArgs ? + createTestsFromTestArgs(runTestFileOpts, testArgs) : + [createTest({ runTestFileOpts, testModeProps: DEFAULT_MODE_PROPERTIES })]; +} + +function createTestsFromTestArgs(runTestFileOpts: RunTestFileOptions, testArgs: TestArguments): LintTest[] { + const tests: LintTest[] = []; + const testCommonOpts = testArgs.commonArgs ? getLinterOptionsFromCommandLine(testArgs.commonArgs) : undefined; + + addDefaultModeIfNeeded(testArgs); + + if (testArgs.mode) { + for (const mode of Object.keys(testArgs.mode)) { + const testModeProps = testModePropsMap.get(mode); + if (!testModeProps) { + throw new Error(`Failed to create test. Unknown mode: '${mode}'`); + } + const testModeArgs: string | undefined = testArgs.mode[mode]; + tests.push(createTest({ runTestFileOpts, testModeProps, testCommonOpts, testModeArgs })); + } + } + + return tests; +} + +function addDefaultModeIfNeeded(testArgs: TestArguments): void { + if (testArgs.mode?.default === undefined) { + // For convenience, always add 'default' mode as first + testArgs.mode = Object.assign({ default: '' }, testArgs.mode); + } +} + +function createTest(createTestOpts: CreateTestOptions): LintTest { + const opts = createCreateLintTestOpts(createTestOpts); + if (createTestOpts.testModeProps.mode === TestMode.MIGRATE) { + return new MigrateTest(opts); + } + return new LintTest(opts); +} + +function createCreateLintTestOpts(createTestConfigOpts: CreateTestOptions): CreateLintTestOptions { + const { runTestFileOpts, testCommonOpts, testModeArgs, testModeProps } = createTestConfigOpts; + const { testDir, testFile, testRunnerOpts } = runTestFileOpts; + + /* + * Test options are formed in the following order (from lowest to highest priority): + * - default test options; + * - [test_args_file] --> 'commonArgs'; + * - [test_args_file] --> the arguments specified for a mode; + * - options specified by TestRunner command-line arguments; + * - options that enable specific mode. + */ + const linterOpts = getDefaultTestOptions(); + if (testCommonOpts) { + Object.assign(linterOpts, testCommonOpts); + } + if (testModeArgs) { + Object.assign(linterOpts, getLinterOptionsFromCommandLine(testModeArgs)); + } + Object.assign(linterOpts, testRunnerOpts.linterOptions); + Object.assign(linterOpts, testModeProps.modeOpts); + + const cmdOptions: CommandLineOptions = { + inputFiles: [path.join(testDir, testFile)], + linterOptions: linterOpts + }; + + return { + testDir, + testFile, + testModeProps, + cmdOptions + }; +} + +function getLinterOptionsFromCommandLine(cmdLine: string): LinterOptions { + return parseCommandLine(getCommandLineArguments(cmdLine), { exitOnFail: false, disableErrorOutput: true }). + linterOptions; +} + +function getDefaultTestOptions(): LinterOptions { + return { + useRtLogic: true, + checkTsAsSource: + true /* By default, treat any test file with '.ts' extension as a source file (as opposed to library) */, + compatibleSdkVersion: 12, + compatibleSdkVersionStage: 'beta3', + checkTsAndJs: true + }; +} diff --git a/ets2panda/linter/src/testRunner/TestMode.ts b/ets2panda/linter/src/testRunner/TestMode.ts new file mode 100644 index 0000000000..7bec4187e5 --- /dev/null +++ b/ets2panda/linter/src/testRunner/TestMode.ts @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { LinterOptions } from '../lib/LinterOptions'; + +export enum TestMode { + DEFAULT, + AUTOFIX, + ARKTS2, + MIGRATE +} + +export interface TestModeProperties { + resultFileExt: string; + mode: TestMode; + modeOpts: LinterOptions; +} + +export const DEFAULT_MODE_PROPERTIES: TestModeProperties = { + resultFileExt: '.json', + mode: TestMode.DEFAULT, + modeOpts: {} +}; +const AUTOFIX_MODE_PROPERTIES: TestModeProperties = { + resultFileExt: '.autofix.json', + mode: TestMode.AUTOFIX, + modeOpts: { + enableAutofix: true + } +}; +const ARKTS2_MODE_PROPERTIES: TestModeProperties = { + resultFileExt: '.arkts2.json', + mode: TestMode.ARKTS2, + modeOpts: { + arkts2: true + } +}; +const MIGRATE_MODE_PROPERTIES: TestModeProperties = { + resultFileExt: '.migrate.json', + mode: TestMode.MIGRATE, + modeOpts: { + migratorMode: true, + noMigrationBackupFile: true + } +}; + +export const testModePropsMap: Map = new Map([ + ['default', DEFAULT_MODE_PROPERTIES], + ['autofix', AUTOFIX_MODE_PROPERTIES], + ['arkts2', ARKTS2_MODE_PROPERTIES], + ['migrate', MIGRATE_MODE_PROPERTIES] +]); diff --git a/ets2panda/linter/src/testRunner/TestResult.ts b/ets2panda/linter/src/testRunner/TestResult.ts index 37e064e22d..d1754cdeba 100644 --- a/ets2panda/linter/src/testRunner/TestResult.ts +++ b/ets2panda/linter/src/testRunner/TestResult.ts @@ -38,7 +38,11 @@ export interface TestProblemInfo { const autofixResultSchema: yup.ObjectSchema = yup.object({ replacementText: yup.string().defined(), start: yup.number().required(), - end: yup.number().required() + end: yup.number().required(), + line: yup.number().optional(), + column: yup.number().optional(), + endLine: yup.number().optional(), + endColumn: yup.number().optional() }); const testResultSchema: yup.ObjectSchema = yup.object({ diff --git a/ets2panda/linter/src/testRunner/TestRunner.ts b/ets2panda/linter/src/testRunner/TestRunner.ts index 62ce4f9d44..4d3639fb32 100755 --- a/ets2panda/linter/src/testRunner/TestRunner.ts +++ b/ets2panda/linter/src/testRunner/TestRunner.ts @@ -13,118 +13,29 @@ * limitations under the License. */ -import { Logger } from '../lib/Logger'; -import { LoggerImpl } from '../cli/LoggerImpl'; import * as fs from 'node:fs'; import * as path from 'node:path'; import * as ts from 'typescript'; -import type { CommandLineOptions } from '../lib/CommandLineOptions'; -import { lint } from '../lib/LinterRunner'; -import { TypeScriptLinter } from '../lib/TypeScriptLinter'; -import { InteropTypescriptLinter } from '../lib/InteropTypescriptLinter'; -import type { Autofix } from '../lib/autofixes/Autofixer'; -import { parseCommandLine as parseLinterCommandLine } from '../cli/CommandLineParser'; -import { compileLintOptions } from '../cli/Compiler'; -import { getEtsLoaderPath } from '../cli/LinterCLI'; -import { ProblemSeverity } from '../lib/ProblemSeverity'; -import type { ProblemInfo } from '../lib/ProblemInfo'; -import type { TestArguments } from './TestArgs'; -import { validateTestArgs } from './TestArgs'; -import type { LinterOptions } from '../lib/LinterOptions'; +import { Logger } from '../lib/Logger'; +import { LoggerImpl } from '../cli/LoggerImpl'; import { Command } from 'commander'; import { rimrafSync } from 'rimraf'; -import type { TestProblemInfo, TestResult } from './TestResult'; -import { validateTestResult } from './TestResult'; import { globSync } from 'glob'; import type { Path } from 'path-scurry'; import { PathScurry } from 'path-scurry'; -import { getCommandLineArguments } from './CommandLineUtil'; +import { createTests } from './TestFactory'; +import type { LintTest } from './LintTest'; +import type { TestRunnerOptions } from './TestRunnerOptions'; +import type { RunTestFileOptions } from './RunTestFileOptions'; +import { MIGRATE_RESULT_SUFFIX, RESULTS_DIR, TAB } from './Consts'; Logger.init(new LoggerImpl()); -const TAB = ' '; -const RESULTS_DIR = 'results'; - -const ARGS_CONFIG_EXT = '.args.json'; -const DIFF_EXT = '.diff'; -const TEST_EXTENSION_ETS = '.ets'; -const TEST_EXTENSION_ETSX = '.etsx'; -const TEST_EXTENSION_D_ETS = '.d.ets'; - interface TestStatistics { passed: number; failed: number; } -enum TestMode { - DEFAULT, - AUTOFIX, - ARKTS2, - MIGRATE -} - -interface CreateTestConfigurationOptions { - runTestFileOpts: RunTestFileOptions; - testModeProps: TestModeProperties; - testModeArgs?: string; - testCommonOpts?: LinterOptions; -} - -interface TestRunnerOptions { - linterOptions: LinterOptions; - testDirs: string[]; - testPattern?: string; -} - -interface RunTestFileOptions { - testDir: string; - testFile: string; - testRunnerOpts: TestRunnerOptions; -} - -interface TestModeProperties { - resultFileExt: string; - mode: TestMode; - modeOpts: LinterOptions; -} - -const DEFAULT_MODE_PROPERTIES: TestModeProperties = { - resultFileExt: '.json', - mode: TestMode.DEFAULT, - modeOpts: {} -}; -const AUTOFIX_MODE_PROPERTIES: TestModeProperties = { - resultFileExt: '.autofix.json', - mode: TestMode.AUTOFIX, - modeOpts: { - enableAutofix: true - } -}; -const ARKTS2_MODE_PROPERTIES: TestModeProperties = { - resultFileExt: '.arkts2.json', - mode: TestMode.ARKTS2, - modeOpts: { - arkts2: true - } -}; - -const MIGRATE_MODE_PROPERTIES: TestModeProperties = { - resultFileExt: '.migrate.json', - mode: TestMode.MIGRATE, - modeOpts: { - arkts2: true, - migratorMode: true, - ideMode: false - } -}; - -interface TestConfiguration { - testDir: string; - testFile: string; - testModeProps: TestModeProperties; - cmdOptions: CommandLineOptions; -} - export function getSdkConfigOptions(configFile: string): ts.CompilerOptions { // initial configuration const options = ts.readConfigFile(configFile, ts.sys.readFile).config.compilerOptions; @@ -219,12 +130,12 @@ function runTests(): boolean { collectTestFilesWithGlob(testDir, testRunnerOpts.testPattern) : fs.readdirSync(testDir); testFiles = testFiles.filter((x) => { + const file = x.trimEnd(); return ( - x.trimEnd().endsWith(ts.Extension.Ts) && !x.trimEnd().endsWith(ts.Extension.Dts) || - x.trimEnd().endsWith(ts.Extension.Tsx) || - x.trimEnd().endsWith(ts.Extension.Ets) || - x.trimEnd().endsWith(TEST_EXTENSION_ETS) && !x.trimEnd().endsWith(TEST_EXTENSION_D_ETS) || - x.trimEnd().endsWith(TEST_EXTENSION_ETSX) + (file.endsWith(ts.Extension.Ts) && !file.endsWith(ts.Extension.Dts) || + file.endsWith(ts.Extension.Tsx) || + file.endsWith(ts.Extension.Ets)) && + !file.endsWith(MIGRATE_RESULT_SUFFIX + path.extname(file)) ); }); runTestFiles(testFiles, testDir, testRunnerOpts, testStats); @@ -264,41 +175,10 @@ function runTestFiles( } function runTestFile(runTestFileOpts: RunTestFileOptions, testStats: TestStatistics): void { - const testConfigs: TestConfiguration[] = []; - - const testArgs = processTestArgsFile(runTestFileOpts.testDir, runTestFileOpts.testFile); - if (testArgs) { - const testCommonOpts = testArgs.commonArgs ? getLinterOptionsFromCommandLine(testArgs.commonArgs) : undefined; - addTestConfiguration(testConfigs, { - runTestFileOpts, - testModeProps: DEFAULT_MODE_PROPERTIES, - testModeArgs: testArgs.mode?.default, - testCommonOpts - }); - addTestConfiguration(testConfigs, { - runTestFileOpts, - testModeProps: AUTOFIX_MODE_PROPERTIES, - testModeArgs: testArgs.mode?.autofix, - testCommonOpts - }); - addTestConfiguration(testConfigs, { - runTestFileOpts, - testModeProps: ARKTS2_MODE_PROPERTIES, - testModeArgs: testArgs.mode?.arkts2, - testCommonOpts - }); - addTestConfiguration(testConfigs, { - runTestFileOpts, - testModeProps: MIGRATE_MODE_PROPERTIES, - testModeArgs: testArgs.mode?.migrate, - testCommonOpts - }); - } else { - addTestConfiguration(testConfigs, { runTestFileOpts, testModeProps: DEFAULT_MODE_PROPERTIES }); - } + const tests: LintTest[] = createTests(runTestFileOpts); - testConfigs.forEach((config: TestConfiguration) => { - if (runTest(config)) { + tests.forEach((test: LintTest) => { + if (test.run()) { ++testStats.passed; } else { ++testStats.failed; @@ -306,259 +186,4 @@ function runTestFile(runTestFileOpts: RunTestFileOptions, testStats: TestStatist }); } -function processTestArgsFile(testDir: string, testFile: string): TestArguments | undefined { - const argsFileName = path.join(testDir, testFile + ARGS_CONFIG_EXT); - if (fs.existsSync(argsFileName)) { - try { - const data = fs.readFileSync(argsFileName).toString(); - const json = JSON.parse(data); - return validateTestArgs(json); - } catch (error) { - throw new Error(`Failed to process ${argsFileName}: ${(error as Error).message}`); - } - } - return undefined; -} - -function addTestConfiguration( - testConfigs: TestConfiguration[], - createTestConfigOpts: CreateTestConfigurationOptions -): void { - const { runTestFileOpts, testModeProps, testModeArgs, testCommonOpts } = createTestConfigOpts; - const { testDir, testFile, testRunnerOpts } = runTestFileOpts; - - if (testModeArgs === undefined && testModeProps.mode !== TestMode.DEFAULT) { - return; - } - - /* - * Test options are formed in the following order (from lowest to highest priority): - * - default test options; - * - [test_args_file] --> 'commonArgs'; - * - [test_args_file] --> the arguments specified for a mode; - * - options specified by TestRunner command-line arguments; - * - options that enable specific mode. - */ - const linterOpts = getDefaultTestOptions(); - if (testCommonOpts) { - Object.assign(linterOpts, testCommonOpts); - } - if (testModeArgs) { - Object.assign(linterOpts, getLinterOptionsFromCommandLine(testModeArgs)); - } - Object.assign(linterOpts, testRunnerOpts.linterOptions); - Object.assign(linterOpts, testModeProps.modeOpts); - - const cmdOptions: CommandLineOptions = { - inputFiles: [path.join(testDir, testFile)], - linterOptions: linterOpts - }; - - testConfigs.push({ - testDir, - testFile, - testModeProps, - cmdOptions - }); -} - -function getDefaultTestOptions(): LinterOptions { - - /* - * Set the IDE mode manually to enable storing information - * about found bad nodes and also disable the log output. - */ - return { - ideMode: true, - useRtLogic: true, - checkTsAsSource: true /* Currently, tests have '.ts' extension, therefore, enable this flag by default */, - compatibleSdkVersion: 12, - compatibleSdkVersionStage: 'beta3' - }; -} - -function getLinterOptionsFromCommandLine(cmdLine: string): LinterOptions { - return parseLinterCommandLine(getCommandLineArguments(cmdLine), { exitOnFail: false, disableErrorOutput: true }). - linterOptions; -} - -function runTest(testConfig: TestConfiguration): boolean { - Logger.info(`Running test ${testConfig.testFile} (${TestMode[testConfig.testModeProps.mode]} mode)`); - - TypeScriptLinter.initGlobals(); - InteropTypescriptLinter.initGlobals(); - - const linterConfig = compileLintOptions(testConfig.cmdOptions); - const linterResult = lint(linterConfig, getEtsLoaderPath(linterConfig)); - - // Get actual test results. - const fileProblems = linterResult.problemsInfos.get(path.normalize(testConfig.cmdOptions.inputFiles[0])); - if (fileProblems === undefined) { - return true; - } - const actualResult = transformProblemInfos(fileProblems, testConfig.testModeProps.mode); - - // Read file with expected test result. - const resultDiff = compareExpectedAndActual(testConfig, actualResult); - - // Write file with actual test results. - writeActualResultFile(testConfig, actualResult, resultDiff); - - return !resultDiff; -} - -function readTestResultFile(testDir: string, testResultFileName: string): TestProblemInfo[] { - const filePath = path.join(testDir, testResultFileName); - try { - const testResult = fs.readFileSync(filePath).toString(); - return validateTestResult(JSON.parse(testResult)).result; - } catch (error) { - throw new Error(`Failed to process ${filePath}: ${(error as Error).message}`); - } -} - -function transformProblemInfos(fileProblems: ProblemInfo[], mode: TestMode): TestProblemInfo[] { - return fileProblems.map((x) => { - return { - line: x.line, - column: x.column, - endLine: x.endLine, - endColumn: x.endColumn, - problem: x.problem, - autofix: mode === TestMode.AUTOFIX ? x.autofix : undefined, - suggest: x.suggest, - rule: x.rule, - severity: ProblemSeverity[x.severity] - }; - }); -} - -function compareExpectedAndActual(testConfig: TestConfiguration, actual: TestProblemInfo[]): string { - const { - testDir, - testFile, - cmdOptions: { linterOptions }, - testModeProps: { resultFileExt } - } = testConfig; - - // Read file with expected test result. - let diff: string = ''; - const testResultFileName = testFile + resultFileExt; - try { - let expected = readTestResultFile(testDir, testResultFileName); - - /** - * The exclusive field is added to identify whether the use case is exclusive to the RT or SDK - * RT means the RT exclusive - * SDK means the SDK exclusive - * undefined means shared - */ - expected = expected.filter((x) => { - return !x?.exclusive || x.exclusive === (linterOptions.useRtLogic ? 'RT' : 'SDK'); - }); - - if (!expected || expected.length !== actual.length) { - const expectedResultCount = expected ? expected.length : 0; - diff = `Expected count: ${expectedResultCount} vs actual count: ${actual.length}`; - Logger.info(`${TAB}${diff}`); - } else { - diff = expectedAndActualMatch(expected, actual); - } - - if (diff) { - Logger.info(`${TAB}Test failed. Expected and actual results differ.`); - } - } catch (error) { - // Write error message to diff, as non-empty diff indicates that test has failed. - diff = (error as Error).message; - Logger.info(`${TAB}Failed to compare expected and actual results. ` + diff); - } - - return diff; -} - -function expectedAndActualMatch(expectedNodes: TestProblemInfo[], actualNodes: TestProblemInfo[]): string { - // Compare expected and actual results. - for (let i = 0; i < actualNodes.length; i++) { - const actual = actualNodes[i]; - const expect = expectedNodes[i]; - if (!locationMatch(expect, actual) || actual.problem !== expect.problem) { - return reportDiff(expect, actual); - } - if (!autofixArraysMatch(expect.autofix, actual.autofix)) { - return reportDiff(expect, actual); - } - if (expect.suggest && actual.suggest !== expect.suggest) { - return reportDiff(expect, actual); - } - if (expect.rule && actual.rule !== expect.rule) { - return reportDiff(expect, actual); - } - if (expect.severity && actual.severity !== expect.severity) { - return reportDiff(expect, actual); - } - } - - return ''; -} - -function locationMatch(expected: TestProblemInfo, actual: TestProblemInfo): boolean { - return ( - actual.line === expected.line && - actual.column === expected.column && - (!expected.endLine || actual.endLine === expected.endLine) && - (!expected.endColumn || actual.endColumn === expected.endColumn) - ); -} - -function autofixArraysMatch(expected: Autofix[] | undefined, actual: Autofix[] | undefined): boolean { - if (!expected && !actual) { - return true; - } - if (!(expected && actual) || expected.length !== actual.length) { - return false; - } - for (let i = 0; i < actual.length; ++i) { - if ( - actual[i].start !== expected[i].start || - actual[i].end !== expected[i].end || - actual[i].replacementText !== expected[i].replacementText - ) { - return false; - } - } - return true; -} - -function writeActualResultFile(testConfig: TestConfiguration, actual: TestProblemInfo[], diff: string): void { - const { - testModeProps: { resultFileExt } - } = testConfig; - const actualResultsDir = path.join(testConfig.testDir, RESULTS_DIR); - if (!fs.existsSync(actualResultsDir)) { - fs.mkdirSync(actualResultsDir); - } - - const actualTestResult: TestResult = { result: actual }; - const actualResultJSON = JSON.stringify(actualTestResult, null, 4); - fs.writeFileSync(path.join(actualResultsDir, testConfig.testFile + resultFileExt), actualResultJSON); - - if (diff) { - fs.writeFileSync(path.join(actualResultsDir, testConfig.testFile + resultFileExt + DIFF_EXT), diff); - } -} - -function reportDiff(expected: TestProblemInfo, actual: TestProblemInfo): string { - const expectedNode = JSON.stringify({ nodes: [expected] }, null, 4); - const actualNode = JSON.stringify({ nodes: [actual] }, null, 4); - - const diff = `Expected: -${expectedNode} -Actual: -${actualNode}`; - - Logger.info(diff); - return diff; -} - runTests(); diff --git a/ets2panda/linter/src/testRunner/TestRunnerOptions.ts b/ets2panda/linter/src/testRunner/TestRunnerOptions.ts new file mode 100644 index 0000000000..bae4b12fd8 --- /dev/null +++ b/ets2panda/linter/src/testRunner/TestRunnerOptions.ts @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { LinterOptions } from '../lib/LinterOptions'; + +export interface TestRunnerOptions { + linterOptions: LinterOptions; + testDirs: string[]; + testPattern?: string; +} diff --git a/ets2panda/linter/src/lib/utils/consts/WhiteListProblemType.ts b/ets2panda/linter/src/testRunner/TestUtil.ts similarity index 47% rename from ets2panda/linter/src/lib/utils/consts/WhiteListProblemType.ts rename to ets2panda/linter/src/testRunner/TestUtil.ts index 084fa5f156..aab666fef0 100644 --- a/ets2panda/linter/src/lib/utils/consts/WhiteListProblemType.ts +++ b/ets2panda/linter/src/testRunner/TestUtil.ts @@ -13,19 +13,23 @@ * limitations under the License. */ -export enum SdkProblem { - LimitedVoidType = 'LimitedVoidType', - ConstructorIface = 'ConstructorIface', - LiteralAsPropertyName = 'LiteralAsPropertyName', - OptionalMethod = 'OptionalMethod', - ConstructorFuncs = 'ConstructorFuncs', - IndexedAccessType = 'IndexedAccessType', - SendablePropType = 'SendablePropType', - TypeQuery = 'TypeQuery', - GlobalThisError = 'GlobalThisError', - InterfaceExtendsClass = 'InterfaceExtendsClass', - DeclWithDuplicateName = 'DeclWithDuplicateName', - ComputedPropertyName = 'ComputedPropertyName' -} +import type { ProblemInfo } from '../lib/ProblemInfo'; +import { ProblemSeverity } from '../lib/ProblemSeverity'; +import { TestMode } from './TestMode'; +import type { TestProblemInfo } from './TestResult'; -export const ARKTS_WHITE_API_PATH_TEXTSTYLE = 'component/styled_string.d.ts'; +export function transformProblemInfos(fileProblems: ProblemInfo[], mode: TestMode): TestProblemInfo[] { + return fileProblems.map((x) => { + return { + line: x.line, + column: x.column, + endLine: x.endLine, + endColumn: x.endColumn, + problem: x.problem, + autofix: mode === TestMode.AUTOFIX ? x.autofix : undefined, + suggest: x.suggest, + rule: x.rule, + severity: ProblemSeverity[x.severity] + }; + }); +} diff --git a/ets2panda/linter/test/builtin/builtin_callsignature.ets b/ets2panda/linter/test/builtin/builtin_callsignature.ets new file mode 100644 index 0000000000..ccb7f4de95 --- /dev/null +++ b/ets2panda/linter/test/builtin/builtin_callsignature.ets @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +function createArray(ctor: ArrayConstructor) { // ERROR + return ctor(1, 2, 3); // ERROR +} +function createArrayDirect() { + return Array(1, 2, 3) +} + +function createBigInt(ctor: BigIntConstructor) { // ERROR + return ctor(1); // ERROR +} +function createBigIntDirect() { + return BigInt(1); +} + +function anotherName(ctorName0: BigIntConstructor) { // ERROR + ctorName0(1); // ERROR + const ctorName1 = ctorName0 + const rs1 = ctorName1(1); // ERROR + type BigIntConstructor1 = BigIntConstructor; // ERROR + let ctorName2:BigIntConstructor1 = ctorName1 // ERROR + const rs2 = ctorName2(1); // ERROR +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/ConstructorIface4.ets.args.json b/ets2panda/linter/test/builtin/builtin_callsignature.ets.args.json similarity index 100% rename from ets2panda/linter/test/sdkwhite/ConstructorIface4.ets.args.json rename to ets2panda/linter/test/builtin/builtin_callsignature.ets.args.json diff --git a/ets2panda/linter/test/builtin/builtin_callsignature.ets.arkts2.json b/ets2panda/linter/test/builtin/builtin_callsignature.ets.arkts2.json new file mode 100644 index 0000000000..8263890683 --- /dev/null +++ b/ets2panda/linter/test/builtin/builtin_callsignature.ets.arkts2.json @@ -0,0 +1,118 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 28, + "endLine": 16, + "endColumn": 44, + "problem": "BuiltinNoCtorFunc", + "suggest": "", + "rule": "API is not support ctor signature and func (arkts-builtin-cotr)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 10, + "endLine": 17, + "endColumn": 14, + "problem": "BuiltinNoCtorFunc", + "suggest": "", + "rule": "API is not support ctor signature and func (arkts-builtin-cotr)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 29, + "endLine": 23, + "endColumn": 46, + "problem": "BuiltinNoCtorFunc", + "suggest": "", + "rule": "API is not support ctor signature and func (arkts-builtin-cotr)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 10, + "endLine": 24, + "endColumn": 14, + "problem": "BuiltinNoCtorFunc", + "suggest": "", + "rule": "API is not support ctor signature and func (arkts-builtin-cotr)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 33, + "endLine": 30, + "endColumn": 50, + "problem": "BuiltinNoCtorFunc", + "suggest": "", + "rule": "API is not support ctor signature and func (arkts-builtin-cotr)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 3, + "endLine": 31, + "endColumn": 12, + "problem": "BuiltinNoCtorFunc", + "suggest": "", + "rule": "API is not support ctor signature and func (arkts-builtin-cotr)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 15, + "endLine": 33, + "endColumn": 24, + "problem": "BuiltinNoCtorFunc", + "suggest": "", + "rule": "API is not support ctor signature and func (arkts-builtin-cotr)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 29, + "endLine": 34, + "endColumn": 46, + "problem": "BuiltinNoCtorFunc", + "suggest": "", + "rule": "API is not support ctor signature and func (arkts-builtin-cotr)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 17, + "endLine": 35, + "endColumn": 35, + "problem": "BuiltinNoCtorFunc", + "suggest": "", + "rule": "API is not support ctor signature and func (arkts-builtin-cotr)", + "severity": "ERROR" + }, + { + "line": 36, + "column": 15, + "endLine": 36, + "endColumn": 24, + "problem": "BuiltinNoCtorFunc", + "suggest": "", + "rule": "API is not support ctor signature and func (arkts-builtin-cotr)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/concurrent_decorator_arkts2.ets.json b/ets2panda/linter/test/builtin/builtin_callsignature.ets.json similarity index 100% rename from ets2panda/linter/test/main/concurrent_decorator_arkts2.ets.json rename to ets2panda/linter/test/builtin/builtin_callsignature.ets.json diff --git a/ets2panda/linter/test/builtin/builtin_not_support_property_descriptor.ets b/ets2panda/linter/test/builtin/builtin_not_support_property_descriptor.ets new file mode 100644 index 0000000000..bbcf905f52 --- /dev/null +++ b/ets2panda/linter/test/builtin/builtin_not_support_property_descriptor.ets @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +function f(a: PropertyDescriptor) { + a.configurable; + a.enumerable; + a.value; + a.writable; + a.get; + a.set; +} + +let desc: TypedPropertyDescriptor = { + value:1, + get():number {return this.value}, + set(v): void {this.value = v}, + enumerable: false, + configurable: false, + writable: true +} + +type MyPropertyDescriptor = PropertyDescriptor; +type MyTypedPropertyDescriptor = TypedPropertyDescriptor; + +function f(a: MyPropertyDescriptor) { + a.configurable; + a.enumerable; + a.value; + a.writable; + a.get; + a.set; +} + +let desc: MyTypedPropertyDescriptor = { + value: 1, + get(): number { return this.value; }, + set(v): void {this.value = v}, + enumerable: false, + configurable: false, + writable: true +}; + +interface APropertyDescriptor {} +interface PropertyDescriptorA {} +interface PropertyDescriptor {} + +let a1: APropertyDescriptor = {} +let a2: PropertyDescriptorA = {} +let a3: PropertyDescriptor = {} \ No newline at end of file diff --git a/ets2panda/linter/test/builtin/builtin_not_support_property_descriptor.ets.args.json b/ets2panda/linter/test/builtin/builtin_not_support_property_descriptor.ets.args.json new file mode 100644 index 0000000000..1b80aa9e73 --- /dev/null +++ b/ets2panda/linter/test/builtin/builtin_not_support_property_descriptor.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } + } \ No newline at end of file diff --git a/ets2panda/linter/test/migrate/function_expression.ts.json b/ets2panda/linter/test/builtin/builtin_not_support_property_descriptor.ets.arkts2.json similarity index 31% rename from ets2panda/linter/test/migrate/function_expression.ts.json rename to ets2panda/linter/test/builtin/builtin_not_support_property_descriptor.ets.arkts2.json index cd0c60aca7..1903c3e2db 100644 --- a/ets2panda/linter/test/migrate/function_expression.ts.json +++ b/ets2panda/linter/test/builtin/builtin_not_support_property_descriptor.ets.arkts2.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2022-2024 Huawei Device Co., Ltd.", + "Copyright (c) 2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -16,332 +16,292 @@ "result": [ { "line": 16, - "column": 15, - "endLine": 16, - "endColumn": 29, - "problem": "FunctionExpression", - "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", - "severity": "ERROR" - }, - { - "line": 18, - "column": 18, - "endLine": 20, + "column": 1, + "endLine": 23, "endColumn": 2, - "problem": "FunctionExpression", + "problem": "TsOverload", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "Class TS overloading is not supported(arkts-no-ts-overload)", "severity": "ERROR" }, { - "line": 18, - "column": 39, - "endLine": 18, - "endColumn": 40, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 23, - "column": 10, - "endLine": 25, - "endColumn": 4, - "problem": "FunctionExpression", + "line": 16, + "column": 12, + "endLine": 16, + "endColumn": 13, + "problem": "NoPropertyDescriptor", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "Not support propertydescriptor (arkts-builtin-no-property-descriptor)", "severity": "ERROR" }, { - "line": 28, - "column": 17, - "endLine": 30, - "endColumn": 2, - "problem": "FunctionExpression", + "line": 16, + "column": 15, + "endLine": 16, + "endColumn": 33, + "problem": "NoPropertyDescriptor", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "Not support propertydescriptor (arkts-builtin-no-property-descriptor)", "severity": "ERROR" }, { - "line": 32, + "line": 17, "column": 2, - "endLine": 34, - "endColumn": 2, - "problem": "FunctionExpression", + "endLine": 17, + "endColumn": 3, + "problem": "NoPropertyDescriptor", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "Not support propertydescriptor (arkts-builtin-no-property-descriptor)", "severity": "ERROR" }, { - "line": 36, - "column": 7, - "endLine": 38, - "endColumn": 2, - "problem": "FunctionExpression", - "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", - "severity": "ERROR" - }, - { - "line": 41, - "column": 26, - "endLine": 43, - "endColumn": 2, - "problem": "FunctionExpression", + "line": 18, + "column": 2, + "endLine": 18, + "endColumn": 3, + "problem": "NoPropertyDescriptor", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "Not support propertydescriptor (arkts-builtin-no-property-descriptor)", "severity": "ERROR" }, { - "line": 44, - "column": 27, - "endLine": 46, - "endColumn": 2, - "problem": "FunctionExpression", + "line": 19, + "column": 2, + "endLine": 19, + "endColumn": 3, + "problem": "NoPropertyDescriptor", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "Not support propertydescriptor (arkts-builtin-no-property-descriptor)", "severity": "ERROR" }, { - "line": 48, - "column": 22, - "endLine": 50, - "endColumn": 2, - "problem": "FunctionExpression", + "line": 20, + "column": 2, + "endLine": 20, + "endColumn": 3, + "problem": "NoPropertyDescriptor", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "Not support propertydescriptor (arkts-builtin-no-property-descriptor)", "severity": "ERROR" }, { - "line": 48, - "column": 22, - "endLine": 50, - "endColumn": 2, - "problem": "LimitedReturnTypeInference", + "line": 21, + "column": 2, + "endLine": 21, + "endColumn": 3, + "problem": "NoPropertyDescriptor", "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "Not support propertydescriptor (arkts-builtin-no-property-descriptor)", "severity": "ERROR" }, { - "line": 48, - "column": 35, - "endLine": 48, - "endColumn": 38, - "problem": "AnyType", + "line": 22, + "column": 2, + "endLine": 22, + "endColumn": 3, + "problem": "NoPropertyDescriptor", "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "rule": "Not support propertydescriptor (arkts-builtin-no-property-descriptor)", "severity": "ERROR" }, { - "line": 52, - "column": 19, - "endLine": 54, - "endColumn": 2, - "problem": "FunctionExpression", + "line": 25, + "column": 5, + "endLine": 25, + "endColumn": 9, + "problem": "NoPropertyDescriptor", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "Not support propertydescriptor (arkts-builtin-no-property-descriptor)", "severity": "ERROR" }, { - "line": 52, - "column": 19, - "endLine": 54, - "endColumn": 2, - "problem": "GeneratorFunction", + "line": 25, + "column": 11, + "endLine": 25, + "endColumn": 34, + "problem": "NoPropertyDescriptor", "suggest": "", - "rule": "Generator functions are not supported (arkts-no-generators)", + "rule": "Not support propertydescriptor (arkts-builtin-no-property-descriptor)", "severity": "ERROR" }, { - "line": 53, + "line": 27, "column": 3, - "endLine": 53, - "endColumn": 10, - "problem": "YieldExpression", + "endLine": 27, + "endColumn": 35, + "problem": "ObjectLiteralProperty", "suggest": "", - "rule": "Generator functions are not supported (arkts-no-generators)", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 56, - "column": 17, - "endLine": 58, - "endColumn": 2, - "problem": "FunctionExpression", + "line": 28, + "column": 3, + "endLine": 28, + "endColumn": 32, + "problem": "ObjectLiteralProperty", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 60, - "column": 18, - "endLine": 62, + "line": 37, + "column": 1, + "endLine": 44, "endColumn": 2, - "problem": "FunctionExpression", + "problem": "TsOverload", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "Class TS overloading is not supported(arkts-no-ts-overload)", "severity": "ERROR" }, { - "line": 64, - "column": 19, - "endLine": 66, - "endColumn": 2, - "problem": "FunctionExpression", + "line": 37, + "column": 12, + "endLine": 37, + "endColumn": 13, + "problem": "NoPropertyDescriptor", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "Not support propertydescriptor (arkts-builtin-no-property-descriptor)", "severity": "ERROR" }, { - "line": 71, - "column": 25, - "endLine": 76, - "endColumn": 2, - "problem": "FunctionExpression", + "line": 38, + "column": 5, + "endLine": 38, + "endColumn": 6, + "problem": "NoPropertyDescriptor", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "Not support propertydescriptor (arkts-builtin-no-property-descriptor)", "severity": "ERROR" }, { - "line": 78, - "column": 12, - "endLine": 80, - "endColumn": 2, - "problem": "FunctionExpression", + "line": 39, + "column": 5, + "endLine": 39, + "endColumn": 6, + "problem": "NoPropertyDescriptor", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "Not support propertydescriptor (arkts-builtin-no-property-descriptor)", "severity": "ERROR" }, { - "line": 82, + "line": 40, "column": 5, - "endLine": 84, - "endColumn": 5, - "problem": "AnyType", + "endLine": 40, + "endColumn": 6, + "problem": "NoPropertyDescriptor", "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "rule": "Not support propertydescriptor (arkts-builtin-no-property-descriptor)", "severity": "ERROR" }, { - "line": 82, - "column": 19, - "endLine": 84, - "endColumn": 5, - "problem": "PropertyAccessByIndex", + "line": 41, + "column": 5, + "endLine": 41, + "endColumn": 6, + "problem": "NoPropertyDescriptor", "suggest": "", - "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", + "rule": "Not support propertydescriptor (arkts-builtin-no-property-descriptor)", "severity": "ERROR" }, { - "line": 82, - "column": 19, - "endLine": 84, - "endColumn": 2, - "problem": "FunctionExpression", + "line": 42, + "column": 5, + "endLine": 42, + "endColumn": 6, + "problem": "NoPropertyDescriptor", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "Not support propertydescriptor (arkts-builtin-no-property-descriptor)", "severity": "ERROR" }, { - "line": 86, - "column": 6, - "endLine": 88, - "endColumn": 2, - "problem": "FunctionExpression", + "line": 43, + "column": 5, + "endLine": 43, + "endColumn": 6, + "problem": "NoPropertyDescriptor", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "Not support propertydescriptor (arkts-builtin-no-property-descriptor)", "severity": "ERROR" }, { - "line": 91, - "column": 9, - "endLine": 93, - "endColumn": 4, - "problem": "FunctionExpression", + "line": 46, + "column": 5, + "endLine": 46, + "endColumn": 9, + "problem": "NoPropertyDescriptor", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "Not support propertydescriptor (arkts-builtin-no-property-descriptor)", "severity": "ERROR" }, { - "line": 96, - "column": 25, - "endLine": 98, - "endColumn": 2, - "problem": "FunctionExpression", + "line": 48, + "column": 5, + "endLine": 48, + "endColumn": 41, + "problem": "ObjectLiteralProperty", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 102, - "column": 9, - "endLine": 104, - "endColumn": 17, - "problem": "AnyType", + "line": 49, + "column": 5, + "endLine": 49, + "endColumn": 34, + "problem": "ObjectLiteralProperty", "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 104, - "column": 7, - "endLine": 104, - "endColumn": 17, - "problem": "FunctionBind", - "suggest": "", - "rule": "'Function.bind' is not supported (arkts-no-func-bind)", - "severity": "WARNING" - }, - { - "line": 102, - "column": 15, - "endLine": 104, - "endColumn": 6, - "problem": "FunctionExpression", + "line": 57, + "column": 11, + "endLine": 57, + "endColumn": 29, + "problem": "InvalidIdentifier", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", "severity": "ERROR" }, { - "line": 108, - "column": 16, - "endLine": 108, - "endColumn": 55, - "problem": "FunctionExpression", + "line": 57, + "column": 1, + "endLine": 57, + "endColumn": 32, + "problem": "InterfaceMerging", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "Declaration merging is not supported (arkts-no-decl-merging)", "severity": "ERROR" }, { - "line": 109, - "column": 24, - "endLine": 109, - "endColumn": 75, - "problem": "FunctionExpression", + "line": 61, + "column": 5, + "endLine": 61, + "endColumn": 7, + "problem": "NoPropertyDescriptor", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "Not support propertydescriptor (arkts-builtin-no-property-descriptor)", "severity": "ERROR" }, { - "line": 112, - "column": 5, - "endLine": 112, - "endColumn": 45, - "problem": "FunctionExpression", + "line": 61, + "column": 9, + "endLine": 61, + "endColumn": 27, + "problem": "NoPropertyDescriptor", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "Not support propertydescriptor (arkts-builtin-no-property-descriptor)", "severity": "ERROR" }, { - "line": 113, - "column": 10, - "endLine": 113, - "endColumn": 50, - "problem": "FunctionExpression", + "line": 61, + "column": 30, + "endLine": 61, + "endColumn": 31, + "problem": "ObjectLiteralNoContextType", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/builtin/builtin_not_support_property_descriptor.ets.json b/ets2panda/linter/test/builtin/builtin_not_support_property_descriptor.ets.json new file mode 100644 index 0000000000..5308874540 --- /dev/null +++ b/ets2panda/linter/test/builtin/builtin_not_support_property_descriptor.ets.json @@ -0,0 +1,38 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 57, + "column": 1, + "endLine": 57, + "endColumn": 32, + "problem": "InterfaceMerging", + "suggest": "", + "rule": "Declaration merging is not supported (arkts-no-decl-merging)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 30, + "endLine": 61, + "endColumn": 31, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/builtin/builtin_object_getownpropertynames.ets b/ets2panda/linter/test/builtin/builtin_object_getownpropertynames.ets new file mode 100755 index 0000000000..331af9c7c1 --- /dev/null +++ b/ets2panda/linter/test/builtin/builtin_object_getownpropertynames.ets @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class MyClass {} +const myClass = new MyClass(); +Object.getOwnPropertyNames(a); diff --git a/ets2panda/linter/test/builtin/builtin_object_getownpropertynames.ets.args.json b/ets2panda/linter/test/builtin/builtin_object_getownpropertynames.ets.args.json new file mode 100755 index 0000000000..6958168fef --- /dev/null +++ b/ets2panda/linter/test/builtin/builtin_object_getownpropertynames.ets.args.json @@ -0,0 +1,21 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2", + "migrate": "--arkts-2" + } +} diff --git a/ets2panda/linter/test/builtin/builtin_object_getownpropertynames.ets.arkts2.json b/ets2panda/linter/test/builtin/builtin_object_getownpropertynames.ets.arkts2.json new file mode 100755 index 0000000000..699eba3d85 --- /dev/null +++ b/ets2panda/linter/test/builtin/builtin_object_getownpropertynames.ets.arkts2.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 27, + "problem": "BuiltinGetOwnPropertyNames", + "suggest": "", + "rule": "Using \"Object.getOwnPropertyNames\" is not allowed in this API (arkts-builtin-object-getOwnPropertyNames))", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/builtin/builtin_object_getownpropertynames.ets.autofix.json b/ets2panda/linter/test/builtin/builtin_object_getownpropertynames.ets.autofix.json new file mode 100644 index 0000000000..f2aa6d9af0 --- /dev/null +++ b/ets2panda/linter/test/builtin/builtin_object_getownpropertynames.ets.autofix.json @@ -0,0 +1,35 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 27, + "problem": "BuiltinGetOwnPropertyNames", + "autofix": [ + { + "start": 653, + "end": 679, + "replacementText": "Object.keys" + } + ], + "suggest": "", + "rule": "Using \"Object.getOwnPropertyNames\" is not allowed in this API (arkts-builtin-object-getOwnPropertyNames))", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/api_path_changed.ets.json b/ets2panda/linter/test/builtin/builtin_object_getownpropertynames.ets.json similarity index 100% rename from ets2panda/linter/test/sdkwhite/api_path_changed.ets.json rename to ets2panda/linter/test/builtin/builtin_object_getownpropertynames.ets.json diff --git a/ets2panda/linter/test/builtin/builtin_object_getownpropertynames.ets.migrate.ets b/ets2panda/linter/test/builtin/builtin_object_getownpropertynames.ets.migrate.ets new file mode 100644 index 0000000000..eecf3e8f2a --- /dev/null +++ b/ets2panda/linter/test/builtin/builtin_object_getownpropertynames.ets.migrate.ets @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class MyClass {} +const myClass = new MyClass(); +Object.keys(a); diff --git a/ets2panda/linter/test/interop/ts_decorator.ets.json b/ets2panda/linter/test/builtin/builtin_object_getownpropertynames.ets.migrate.json similarity index 100% rename from ets2panda/linter/test/interop/ts_decorator.ets.json rename to ets2panda/linter/test/builtin/builtin_object_getownpropertynames.ets.migrate.json diff --git a/ets2panda/linter/test/builtin/builtin_symbol_iterator.ets b/ets2panda/linter/test/builtin/builtin_symbol_iterator.ets new file mode 100755 index 0000000000..2b2843d8b1 --- /dev/null +++ b/ets2panda/linter/test/builtin/builtin_symbol_iterator.ets @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +let map: Map = new Map(); +let iterFromReflect = Reflect.get(map, Symbol.iterator); +let iterFromProp = map[Symbol.iterator](); + +let symbolIter = Symbol.iterator; diff --git a/ets2panda/linter/test/interop/no_js_await.ets.args.json b/ets2panda/linter/test/builtin/builtin_symbol_iterator.ets.args.json similarity index 100% rename from ets2panda/linter/test/interop/no_js_await.ets.args.json rename to ets2panda/linter/test/builtin/builtin_symbol_iterator.ets.args.json diff --git a/ets2panda/linter/test/builtin/builtin_symbol_iterator.ets.arkts2.json b/ets2panda/linter/test/builtin/builtin_symbol_iterator.ets.arkts2.json new file mode 100755 index 0000000000..3625415854 --- /dev/null +++ b/ets2panda/linter/test/builtin/builtin_symbol_iterator.ets.arkts2.json @@ -0,0 +1,58 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 40, + "endLine": 17, + "endColumn": 55, + "problem": "BuiltinSymbolIterator", + "suggest": "", + "rule": "Using \"Symbol.iterator\" is not allowed in this API (arkts-builtin-symbol-iterator)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 20, + "endLine": 18, + "endColumn": 40, + "problem": "PropertyAccessByIndex", + "suggest": "", + "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 24, + "endLine": 18, + "endColumn": 39, + "problem": "BuiltinSymbolIterator", + "suggest": "", + "rule": "Using \"Symbol.iterator\" is not allowed in this API (arkts-builtin-symbol-iterator)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 18, + "endLine": 20, + "endColumn": 33, + "problem": "BuiltinSymbolIterator", + "suggest": "", + "rule": "Using \"Symbol.iterator\" is not allowed in this API (arkts-builtin-symbol-iterator)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/builtin/builtin_symbol_iterator.ets.json b/ets2panda/linter/test/builtin/builtin_symbol_iterator.ets.json new file mode 100755 index 0000000000..8af4f78669 --- /dev/null +++ b/ets2panda/linter/test/builtin/builtin_symbol_iterator.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/builtin/builtin_thisArgs.ets b/ets2panda/linter/test/builtin/builtin_thisArgs.ets new file mode 100755 index 0000000000..2a73669055 --- /dev/null +++ b/ets2panda/linter/test/builtin/builtin_thisArgs.ets @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +Class MyClass { + base: number; + constructor(base: number) { + this.base = base; + } + compare((value: number, index:number, arr: Array)) { + return value < this.base + } +} + +let arr: Array = new Array(1, 2, 3); +let a = new MyClass(2); +let b = new MyClass(3); +arr.filter(a.compare, a); +arr.filter(a.compare); +arr.filter(a.compare, b); \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/api_path_changed.ets.args.json b/ets2panda/linter/test/builtin/builtin_thisArgs.ets.args.json similarity index 100% rename from ets2panda/linter/test/sdkwhite/api_path_changed.ets.args.json rename to ets2panda/linter/test/builtin/builtin_thisArgs.ets.args.json diff --git a/ets2panda/linter/test/builtin/builtin_thisArgs.ets.arkts2.json b/ets2panda/linter/test/builtin/builtin_thisArgs.ets.arkts2.json new file mode 100755 index 0000000000..937b8aef5e --- /dev/null +++ b/ets2panda/linter/test/builtin/builtin_thisArgs.ets.arkts2.json @@ -0,0 +1,118 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 21, + "column": 11, + "endLine": 21, + "endColumn": 60, + "problem": "LimitedReturnTypeInference", + "suggest": "", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 5, + "endLine": 27, + "endColumn": 23, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 13, + "endLine": 27, + "endColumn": 20, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 5, + "endLine": 28, + "endColumn": 23, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 13, + "endLine": 28, + "endColumn": 20, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 1, + "endLine": 29, + "endColumn": 25, + "problem": "BuiltinThisArgs", + "suggest": "", + "rule": "Using thisArgs as a type is not allowed in this API (arkts-builtin-thisArgs)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 1, + "endLine": 29, + "endColumn": 25, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 1, + "endLine": 30, + "endColumn": 22, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 1, + "endLine": 31, + "endColumn": 25, + "problem": "BuiltinThisArgs", + "suggest": "", + "rule": "Using thisArgs as a type is not allowed in this API (arkts-builtin-thisArgs)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 1, + "endLine": 31, + "endColumn": 25, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/builtin/builtin_thisArgs.ets.json b/ets2panda/linter/test/builtin/builtin_thisArgs.ets.json new file mode 100755 index 0000000000..132dc5e988 --- /dev/null +++ b/ets2panda/linter/test/builtin/builtin_thisArgs.ets.json @@ -0,0 +1,48 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 21, + "column": 11, + "endLine": 21, + "endColumn": 60, + "problem": "LimitedReturnTypeInference", + "suggest": "", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 5, + "endLine": 27, + "endColumn": 23, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 5, + "endLine": 28, + "endColumn": 23, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/concurrent_decorator_arkts2.ets b/ets2panda/linter/test/concurrent/concurrent_decorator_arkts2.ets similarity index 87% rename from ets2panda/linter/test/main/concurrent_decorator_arkts2.ets rename to ets2panda/linter/test/concurrent/concurrent_decorator_arkts2.ets index a51746c471..91b0af1466 100644 --- a/ets2panda/linter/test/main/concurrent_decorator_arkts2.ets +++ b/ets2panda/linter/test/concurrent/concurrent_decorator_arkts2.ets @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Copyright (c) 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +'use static' @Concurrent // ERROR function func() {} @@ -24,4 +25,4 @@ let n18: a2 = 10; type funtType1 = () => void @Concurrent -type funtType2 = () => void | number \ No newline at end of file +type funtType2 = () => void | number diff --git a/ets2panda/linter/test/main/concurrent_decorator_arkts2.ets.args.json b/ets2panda/linter/test/concurrent/concurrent_decorator_arkts2.ets.args.json similarity index 92% rename from ets2panda/linter/test/main/concurrent_decorator_arkts2.ets.args.json rename to ets2panda/linter/test/concurrent/concurrent_decorator_arkts2.ets.args.json index 4e9dc628f7..571ee6bb76 100644 --- a/ets2panda/linter/test/main/concurrent_decorator_arkts2.ets.args.json +++ b/ets2panda/linter/test/concurrent/concurrent_decorator_arkts2.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } diff --git a/ets2panda/linter/test/main/concurrent_decorator_arkts2.ets.arkts2.json b/ets2panda/linter/test/concurrent/concurrent_decorator_arkts2.ets.arkts2.json similarity index 64% rename from ets2panda/linter/test/main/concurrent_decorator_arkts2.ets.arkts2.json rename to ets2panda/linter/test/concurrent/concurrent_decorator_arkts2.ets.arkts2.json index 7989c221a5..a392b58e69 100644 --- a/ets2panda/linter/test/main/concurrent_decorator_arkts2.ets.arkts2.json +++ b/ets2panda/linter/test/concurrent/concurrent_decorator_arkts2.ets.arkts2.json @@ -15,49 +15,49 @@ ], "result": [ { - "line": 16, + "line": 17, "column": 1, - "endLine": 16, + "endLine": 17, "endColumn": 12, - "problem": "LimitedStdLibApi", + "problem": "LimitedStdLibNoDoncurrentDecorator", "suggest": "", - "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", + "rule": "Usage of standard library is restricted(arkts-limited-stdlib-no-concurrent-decorator)", "severity": "ERROR" }, { - "line": 19, + "line": 20, "column": 1, - "endLine": 19, + "endLine": 20, "endColumn": 12, - "problem": "LimitedStdLibApi", + "problem": "LimitedStdLibNoDoncurrentDecorator", "suggest": "", - "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", + "rule": "Usage of standard library is restricted(arkts-limited-stdlib-no-concurrent-decorator)", "severity": "ERROR" }, { - "line": 23, + "line": 24, "column": 1, - "endLine": 23, + "endLine": 24, "endColumn": 12, - "problem": "LimitedStdLibApi", + "problem": "LimitedStdLibNoDoncurrentDecorator", "suggest": "", - "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", + "rule": "Usage of standard library is restricted(arkts-limited-stdlib-no-concurrent-decorator)", "severity": "ERROR" }, { - "line": 26, + "line": 27, "column": 1, - "endLine": 26, + "endLine": 27, "endColumn": 12, - "problem": "LimitedStdLibApi", + "problem": "LimitedStdLibNoDoncurrentDecorator", "suggest": "", - "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", + "rule": "Usage of standard library is restricted(arkts-limited-stdlib-no-concurrent-decorator)", "severity": "ERROR" }, { - "line": 27, + "line": 28, "column": 24, - "endLine": 27, + "endLine": 28, "endColumn": 28, "problem": "LimitedVoidType", "suggest": "", @@ -65,4 +65,4 @@ "severity": "ERROR" } ] -} \ No newline at end of file +} diff --git a/ets2panda/linter/test/main/concurrent_decorator_arkts2.ets.autofix.json b/ets2panda/linter/test/concurrent/concurrent_decorator_arkts2.ets.autofix.json similarity index 64% rename from ets2panda/linter/test/main/concurrent_decorator_arkts2.ets.autofix.json rename to ets2panda/linter/test/concurrent/concurrent_decorator_arkts2.ets.autofix.json index 586af08091..3a526714e4 100644 --- a/ets2panda/linter/test/main/concurrent_decorator_arkts2.ets.autofix.json +++ b/ets2panda/linter/test/concurrent/concurrent_decorator_arkts2.ets.autofix.json @@ -15,77 +15,77 @@ ], "result": [ { - "line": 16, + "line": 17, "column": 1, - "endLine": 16, + "endLine": 17, "endColumn": 12, - "problem": "LimitedStdLibApi", + "problem": "LimitedStdLibNoDoncurrentDecorator", "autofix": [ { - "start": 610, - "end": 621, + "start": 618, + "end": 629, "replacementText": "" } ], "suggest": "", - "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", + "rule": "Usage of standard library is restricted(arkts-limited-stdlib-no-concurrent-decorator)", "severity": "ERROR" }, { - "line": 19, + "line": 20, "column": 1, - "endLine": 19, + "endLine": 20, "endColumn": 12, - "problem": "LimitedStdLibApi", + "problem": "LimitedStdLibNoDoncurrentDecorator", "autofix": [ { - "start": 651, - "end": 662, + "start": 659, + "end": 670, "replacementText": "" } ], "suggest": "", - "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", + "rule": "Usage of standard library is restricted(arkts-limited-stdlib-no-concurrent-decorator)", "severity": "ERROR" }, { - "line": 23, + "line": 24, "column": 1, - "endLine": 23, + "endLine": 24, "endColumn": 12, - "problem": "LimitedStdLibApi", + "problem": "LimitedStdLibNoDoncurrentDecorator", "autofix": [ { - "start": 699, - "end": 710, + "start": 707, + "end": 718, "replacementText": "" } ], "suggest": "", - "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", + "rule": "Usage of standard library is restricted(arkts-limited-stdlib-no-concurrent-decorator)", "severity": "ERROR" }, { - "line": 26, + "line": 27, "column": 1, - "endLine": 26, + "endLine": 27, "endColumn": 12, - "problem": "LimitedStdLibApi", + "problem": "LimitedStdLibNoDoncurrentDecorator", "autofix": [ { - "start": 740, - "end": 751, + "start": 748, + "end": 759, "replacementText": "" } ], "suggest": "", - "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", + "rule": "Usage of standard library is restricted(arkts-limited-stdlib-no-concurrent-decorator)", "severity": "ERROR" }, { - "line": 27, + "line": 28, "column": 24, - "endLine": 27, + "endLine": 28, "endColumn": 28, "problem": "LimitedVoidType", "suggest": "", @@ -93,4 +93,4 @@ "severity": "ERROR" } ] -} \ No newline at end of file +} diff --git a/ets2panda/linter/test/main/sendable_class_interface_property_sdk.ets.json b/ets2panda/linter/test/concurrent/concurrent_decorator_arkts2.ets.json similarity index 100% rename from ets2panda/linter/test/main/sendable_class_interface_property_sdk.ets.json rename to ets2panda/linter/test/concurrent/concurrent_decorator_arkts2.ets.json diff --git a/ets2panda/linter/test/concurrent/concurrent_decorator_arkts2.ets.migrate.ets b/ets2panda/linter/test/concurrent/concurrent_decorator_arkts2.ets.migrate.ets new file mode 100644 index 0000000000..6364fb63ab --- /dev/null +++ b/ets2panda/linter/test/concurrent/concurrent_decorator_arkts2.ets.migrate.ets @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +'use static' + + // ERROR +function func() {} + + +type a2 = number +let n18: a2 = 10; + + +type funtType1 = () => void + + +type funtType2 = () => void | number diff --git a/ets2panda/linter/test/concurrent/concurrent_decorator_arkts2.ets.migrate.json b/ets2panda/linter/test/concurrent/concurrent_decorator_arkts2.ets.migrate.json new file mode 100644 index 0000000000..1dde4c017f --- /dev/null +++ b/ets2panda/linter/test/concurrent/concurrent_decorator_arkts2.ets.migrate.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 28, + "column": 24, + "endLine": 28, + "endColumn": 28, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets b/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets new file mode 100644 index 0000000000..d3e0b2ca58 --- /dev/null +++ b/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +let typeName: SharedArrayBuffer; // ERROR +let sab: SharedArrayBuffer = new SharedArrayBuffer(0) // 2 ERROR + +type NewTypeName = SharedArrayBuffer // ERROR +let newTypeName: NewTypeName +// disable use new NewTypeName() +let ntn: NewTypeName = new SharedArrayBuffer(0) // ERROR + +function foo(atmo: Atomics) {} // NOT ERROR \ No newline at end of file diff --git a/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets.args.json b/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets.args.json new file mode 100644 index 0000000000..571ee6bb76 --- /dev/null +++ b/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets.args.json @@ -0,0 +1,21 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2", + "migrate": "--arkts-2" + } +} diff --git a/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets.arkts2.json b/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets.arkts2.json new file mode 100644 index 0000000000..4914a0e04a --- /dev/null +++ b/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets.arkts2.json @@ -0,0 +1,68 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 15, + "endLine": 16, + "endColumn": 32, + "problem": "SharedArrayBufferDeprecated", + "suggest": "", + "rule": "SharedArrayBuffer is not supported (arkts-no-need-stdlib-sharedArrayBuffer)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 10, + "endLine": 17, + "endColumn": 27, + "problem": "SharedArrayBufferDeprecated", + "suggest": "", + "rule": "SharedArrayBuffer is not supported (arkts-no-need-stdlib-sharedArrayBuffer)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 34, + "endLine": 17, + "endColumn": 51, + "problem": "SharedArrayBufferDeprecated", + "suggest": "", + "rule": "SharedArrayBuffer is not supported (arkts-no-need-stdlib-sharedArrayBuffer)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 20, + "endLine": 19, + "endColumn": 37, + "problem": "SharedArrayBufferDeprecated", + "suggest": "", + "rule": "SharedArrayBuffer is not supported (arkts-no-need-stdlib-sharedArrayBuffer)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 28, + "endLine": 22, + "endColumn": 45, + "problem": "SharedArrayBufferDeprecated", + "suggest": "", + "rule": "SharedArrayBuffer is not supported (arkts-no-need-stdlib-sharedArrayBuffer)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets.autofix.json b/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets.autofix.json new file mode 100644 index 0000000000..da0b259374 --- /dev/null +++ b/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets.autofix.json @@ -0,0 +1,103 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 15, + "endLine": 16, + "endColumn": 32, + "problem": "SharedArrayBufferDeprecated", + "autofix": [ + { + "replacementText": "ArrayBuffer", + "start": 624, + "end": 641 + } + ], + "suggest": "", + "rule": "SharedArrayBuffer is not supported (arkts-no-need-stdlib-sharedArrayBuffer)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 10, + "endLine": 17, + "endColumn": 27, + "problem": "SharedArrayBufferDeprecated", + "autofix": [ + { + "replacementText": "ArrayBuffer", + "start": 661, + "end": 678 + } + ], + "suggest": "", + "rule": "SharedArrayBuffer is not supported (arkts-no-need-stdlib-sharedArrayBuffer)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 34, + "endLine": 17, + "endColumn": 51, + "problem": "SharedArrayBufferDeprecated", + "autofix": [ + { + "replacementText": "ArrayBuffer", + "start": 685, + "end": 702 + } + ], + "suggest": "", + "rule": "SharedArrayBuffer is not supported (arkts-no-need-stdlib-sharedArrayBuffer)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 20, + "endLine": 19, + "endColumn": 37, + "problem": "SharedArrayBufferDeprecated", + "autofix": [ + { + "replacementText": "ArrayBuffer", + "start": 737, + "end": 754 + } + ], + "suggest": "", + "rule": "SharedArrayBuffer is not supported (arkts-no-need-stdlib-sharedArrayBuffer)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 28, + "endLine": 22, + "endColumn": 45, + "problem": "SharedArrayBufferDeprecated", + "autofix": [ + { + "replacementText": "ArrayBuffer", + "start": 853, + "end": 870 + } + ], + "suggest": "", + "rule": "SharedArrayBuffer is not supported (arkts-no-need-stdlib-sharedArrayBuffer)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/sdkwhite/constructor_types_deprecated_sdk.ets.json b/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets.json old mode 100755 new mode 100644 similarity index 100% rename from ets2panda/linter/test/sdkwhite/constructor_types_deprecated_sdk.ets.json rename to ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets.json diff --git a/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets.migrate.ets b/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets.migrate.ets new file mode 100644 index 0000000000..6eaad40c1a --- /dev/null +++ b/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets.migrate.ets @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +let typeName: ArrayBuffer; // ERROR +let sab: ArrayBuffer = new ArrayBuffer(0) // 2 ERROR + +type NewTypeName = ArrayBuffer // ERROR +let newTypeName: NewTypeName +// disable use new NewTypeName() +let ntn: NewTypeName = new ArrayBuffer(0) // ERROR + +function foo(atmo: Atomics) {} // NOT ERROR \ No newline at end of file diff --git a/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets.migrate.json b/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets.migrate.json new file mode 100644 index 0000000000..43cb4a27bc --- /dev/null +++ b/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets.migrate.json @@ -0,0 +1,3 @@ +{ + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/concurrent/no_support_isconcurrent.ets b/ets2panda/linter/test/concurrent/no_support_isconcurrent.ets new file mode 100644 index 0000000000..40c096babb --- /dev/null +++ b/ets2panda/linter/test/concurrent/no_support_isconcurrent.ets @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { taskpool } from '../main/oh_modules/@kit.ArkTS' +import { taskpool as tp } from '../main/oh_modules/@ohos.taskpool' +import { taskpool as kp } from '@some.module' + +@Concurrent +function test() { } + +let result: Boolean = taskpool.isConcurrent(test); + +let result2: Boolean = tp.isConcurrent(test); + +let result3: Boolean = kp.isConcurrent(test); + +let result4: Boolean = taskpool.foo(test); + +class testObject { + isConcurrent(): string { + return "Test"; + } +}; + +const result: string = testObject.isConcurrent(); diff --git a/ets2panda/linter/test/concurrent/no_support_isconcurrent.ets.args.json b/ets2panda/linter/test/concurrent/no_support_isconcurrent.ets.args.json new file mode 100644 index 0000000000..e2b903f0aa --- /dev/null +++ b/ets2panda/linter/test/concurrent/no_support_isconcurrent.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } + } \ No newline at end of file diff --git a/ets2panda/linter/test/concurrent/no_support_isconcurrent.ets.arkts2.json b/ets2panda/linter/test/concurrent/no_support_isconcurrent.ets.arkts2.json new file mode 100644 index 0000000000..ca28292f8e --- /dev/null +++ b/ets2panda/linter/test/concurrent/no_support_isconcurrent.ets.arkts2.json @@ -0,0 +1,38 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 23, + "column": 32, + "endLine": 23, + "endColumn": 44, + "problem": "IsConcurrentDeprecated", + "suggest": "", + "rule": "isConcurrent is not supported (arkts-limited-stdlib-no-support-isConcurrent)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 27, + "endLine": 25, + "endColumn": 39, + "problem": "IsConcurrentDeprecated", + "suggest": "", + "rule": "isConcurrent is not supported (arkts-limited-stdlib-no-support-isConcurrent)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/concurrent/no_support_isconcurrent.ets.json b/ets2panda/linter/test/concurrent/no_support_isconcurrent.ets.json new file mode 100644 index 0000000000..b9331d05ba --- /dev/null +++ b/ets2panda/linter/test/concurrent/no_support_isconcurrent.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] + } \ No newline at end of file diff --git a/ets2panda/linter/test/concurrent/use_limited_and_concurrent.ets b/ets2panda/linter/test/concurrent/use_limited_and_concurrent.ets new file mode 100644 index 0000000000..22ef20b645 --- /dev/null +++ b/ets2panda/linter/test/concurrent/use_limited_and_concurrent.ets @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +"use shared" +export function sharedFunction() {} + +function concurrentFunc() { + "use concurrent" +} + +function normal() {} + +normal('use concurrent'); + +const variable = 'use concurrent'; + +switch (variable) { + case 'use concurrent: + break; +} + +normal('use shared'); + +const variable2 = 'use shared'; + +switch (variable2) { + case 'use shared': + break; +} diff --git a/ets2panda/linter/test/concurrent/use_limited_and_concurrent.ets.args.json b/ets2panda/linter/test/concurrent/use_limited_and_concurrent.ets.args.json new file mode 100644 index 0000000000..6958168fef --- /dev/null +++ b/ets2panda/linter/test/concurrent/use_limited_and_concurrent.ets.args.json @@ -0,0 +1,21 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2", + "migrate": "--arkts-2" + } +} diff --git a/ets2panda/linter/test/concurrent/use_limited_and_concurrent.ets.arkts2.json b/ets2panda/linter/test/concurrent/use_limited_and_concurrent.ets.arkts2.json new file mode 100644 index 0000000000..0a82914a53 --- /dev/null +++ b/ets2panda/linter/test/concurrent/use_limited_and_concurrent.ets.arkts2.json @@ -0,0 +1,48 @@ +{ + "copyright": [ + "Copyright (c) 2023-2024 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 13, + "problem": "UseSharedDeprecated", + "suggest": "", + "rule": "\"use shared\" is not supported (arkts-limited-stdlib-no-use-shared)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 17, + "endLine": 17, + "endColumn": 31, + "problem": "SharedModuleExports", + "suggest": "", + "rule": "Only \"Sendable\" entities can be exported in shared module (arkts-shared-module-exports)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 5, + "endLine": 20, + "endColumn": 21, + "problem": "UseConcurrentDeprecated", + "suggest": "", + "rule": "\"use concurrent\" is not supported (arkts-limited-stdlib-no-use-concurrent)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/concurrent/use_limited_and_concurrent.ets.autofix.json b/ets2panda/linter/test/concurrent/use_limited_and_concurrent.ets.autofix.json new file mode 100644 index 0000000000..052fc5f382 --- /dev/null +++ b/ets2panda/linter/test/concurrent/use_limited_and_concurrent.ets.autofix.json @@ -0,0 +1,62 @@ +{ + "copyright": [ + "Copyright (c) 2023-2024 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 13, + "problem": "UseSharedDeprecated", + "autofix": [ + { + "start": 605, + "end": 617, + "replacementText": "" + } + ], + "suggest": "", + "rule": "\"use shared\" is not supported (arkts-limited-stdlib-no-use-shared)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 17, + "endLine": 17, + "endColumn": 31, + "problem": "SharedModuleExports", + "suggest": "", + "rule": "Only \"Sendable\" entities can be exported in shared module (arkts-shared-module-exports)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 5, + "endLine": 20, + "endColumn": 21, + "problem": "UseConcurrentDeprecated", + "autofix": [ + { + "start": 687, + "end": 703, + "replacementText": "" + } + ], + "suggest": "", + "rule": "\"use concurrent\" is not supported (arkts-limited-stdlib-no-use-concurrent)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/concurrent/use_limited_and_concurrent.ets.json b/ets2panda/linter/test/concurrent/use_limited_and_concurrent.ets.json new file mode 100644 index 0000000000..443a9bc21b --- /dev/null +++ b/ets2panda/linter/test/concurrent/use_limited_and_concurrent.ets.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 17, + "endLine": 17, + "endColumn": 31, + "problem": "SharedModuleExports", + "suggest": "", + "rule": "Only \"Sendable\" entities can be exported in shared module (arkts-shared-module-exports)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/concurrent/use_limited_and_concurrent.ets.migrate.ets b/ets2panda/linter/test/concurrent/use_limited_and_concurrent.ets.migrate.ets new file mode 100644 index 0000000000..5224e3b79f --- /dev/null +++ b/ets2panda/linter/test/concurrent/use_limited_and_concurrent.ets.migrate.ets @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +export function sharedFunction() {} + +function concurrentFunc() { + +} + +function normal() {} + +normal('use concurrent'); + +const variable = 'use concurrent'; + +switch (variable) { + case 'use concurrent: + break; +} + +normal('use shared'); + +const variable2 = 'use shared'; + +switch (variable2) { + case 'use shared': + break; +} diff --git a/ets2panda/linter/test/main/data_observation_1.ets.json b/ets2panda/linter/test/concurrent/use_limited_and_concurrent.ets.migrate.json similarity index 100% rename from ets2panda/linter/test/main/data_observation_1.ets.json rename to ets2panda/linter/test/concurrent/use_limited_and_concurrent.ets.migrate.json diff --git a/ets2panda/linter/test/interop/binary_operation_js_obj.ets.args.json b/ets2panda/linter/test/interop/binary_operation_js_obj.ets.args.json index 64b4d19108..3318ebbbcf 100755 --- a/ets2panda/linter/test/interop/binary_operation_js_obj.ets.args.json +++ b/ets2panda/linter/test/interop/binary_operation_js_obj.ets.args.json @@ -14,6 +14,8 @@ "limitations under the License." ], "mode": { - "arkts2": "" + "arkts2": "", + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } diff --git a/ets2panda/linter/test/interop/binary_operation_js_obj.ets.arkts2.json b/ets2panda/linter/test/interop/binary_operation_js_obj.ets.arkts2.json index b47ee3c9b5..cf8ab0e5ee 100755 --- a/ets2panda/linter/test/interop/binary_operation_js_obj.ets.arkts2.json +++ b/ets2panda/linter/test/interop/binary_operation_js_obj.ets.arkts2.json @@ -31,7 +31,7 @@ "endColumn": 49, "problem": "InterOpImportJs", "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -41,7 +41,7 @@ "endColumn": 14, "problem": "InteropObjectProperty", "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -61,7 +61,7 @@ "endColumn": 14, "problem": "BinaryOperations", "suggest": "", - "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { @@ -71,7 +71,7 @@ "endColumn": 14, "problem": "InteropObjectProperty", "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -91,7 +91,7 @@ "endColumn": 14, "problem": "BinaryOperations", "suggest": "", - "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { diff --git a/ets2panda/linter/test/interop/binary_operation_js_obj.ets.autofix.json b/ets2panda/linter/test/interop/binary_operation_js_obj.ets.autofix.json index 895325b061..39d941b73f 100755 --- a/ets2panda/linter/test/interop/binary_operation_js_obj.ets.autofix.json +++ b/ets2panda/linter/test/interop/binary_operation_js_obj.ets.autofix.json @@ -14,5 +14,142 @@ "limitations under the License." ], "result": [ + { + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 49, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 49, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 617, + "end": 665, + "replacementText": "" + }, + { + "start": 665, + "end": 665, + "replacementText": "let GeneratedImportVar_1 = ESObject.load('./binary_operation_js_obj_js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');\n" + } + ], + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 9, + "endLine": 17, + "endColumn": 14, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 674, + "end": 679, + "replacementText": "foo.getPropertyByName(\"a\")" + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 9, + "endLine": 17, + "endColumn": 14, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "foo.getPropertyByName('a').toNumber()", + "start": 674, + "end": 679 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 9, + "endLine": 17, + "endColumn": 14, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 9, + "endLine": 18, + "endColumn": 14, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 688, + "end": 693, + "replacementText": "foo.getPropertyByName(\"b\")" + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 9, + "endLine": 18, + "endColumn": 14, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "foo.getPropertyByName('b').toNumber()", + "start": 688, + "end": 693 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 9, + "endLine": 18, + "endColumn": 14, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 3, + "endLine": 24, + "endColumn": 5, + "problem": "ExponentOp", + "autofix": [ + { + "replacementText": "Math.pow(a, b)", + "start": 724, + "end": 730 + } + ], + "suggest": "", + "rule": "exponent opartions \"**\" and \"**=\" are disabled (arkts-no-exponent-op)", + "severity": "ERROR" + } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/ComputedPropertyName.ets b/ets2panda/linter/test/interop/binary_operation_js_obj.ets.migrate.ets similarity index 70% rename from ets2panda/linter/test/sdkwhite/ComputedPropertyName.ets rename to ets2panda/linter/test/interop/binary_operation_js_obj.ets.migrate.ets index ea2407ae1b..b8312ed47e 100644 --- a/ets2panda/linter/test/sdkwhite/ComputedPropertyName.ets +++ b/ets2panda/linter/test/interop/binary_operation_js_obj.ets.migrate.ets @@ -1,32 +1,26 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -const styleMap: ProgressStyleMap = { - 1: { // Error - strokeWidth: 1, - }, - 2: { // Error - strokeWidth: 1, - }, - 3: { // Error - strokeWidth: 1, - }, - 4: { // Error - strokeWidth: 1, - }, - 0: { // Error - - } -}; +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +'use static' +let GeneratedImportVar_1 = ESObject.load('./binary_operation_js_obj_js'); +let foo = GeneratedImportVar_1.getPropertyByName('foo'); + +let a = foo.getPropertyByName("a") +let b = foo.getPropertyByName("b") +a + b +a - b +a * b +a / b +a % b +Math.pow(a, b) \ No newline at end of file diff --git a/ets2panda/linter/test/interop/binary_operation_js_obj.ets.migrate.json b/ets2panda/linter/test/interop/binary_operation_js_obj.ets.migrate.json new file mode 100644 index 0000000000..2d5cf16415 --- /dev/null +++ b/ets2panda/linter/test/interop/binary_operation_js_obj.ets.migrate.json @@ -0,0 +1,68 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 5, + "endLine": 16, + "endColumn": 73, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 5, + "endLine": 17, + "endColumn": 56, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 5, + "endLine": 19, + "endColumn": 35, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 5, + "endLine": 20, + "endColumn": 35, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 1, + "endLine": 26, + "endColumn": 15, + "problem": "MathPow", + "suggest": "", + "rule": "function \"Math.pow()\" behavior for ArkTS differs from Typescript version (arkts-math-pow-standard-diff)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/call_function.ets.arkts2.json b/ets2panda/linter/test/interop/call_function.ets.arkts2.json index 64199c1b99..7ab8a8de0e 100644 --- a/ets2panda/linter/test/interop/call_function.ets.arkts2.json +++ b/ets2panda/linter/test/interop/call_function.ets.arkts2.json @@ -31,7 +31,7 @@ "endColumn": 43, "problem": "InterOpImportJs", "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -39,9 +39,9 @@ "column": 1, "endLine": 18, "endColumn": 6, - "problem": "InteropJsObjectUsage", + "problem": "InteropJsObjectCallStaticFunc", "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-call-static-function)", "severity": "ERROR" }, { @@ -51,17 +51,7 @@ "endColumn": 6, "problem": "CallJSFunction", "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", - "severity": "ERROR" - }, - { - "line": 18, - "column": 1, - "endLine": 18, - "endColumn": 6, - "problem": "InteropCallObjectMethods", - "suggest": "", - "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", "severity": "ERROR" }, { @@ -69,9 +59,9 @@ "column": 1, "endLine": 19, "endColumn": 9, - "problem": "InteropJsObjectUsage", + "problem": "InteropJsObjectCallStaticFunc", "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-call-static-function)", "severity": "ERROR" }, { @@ -81,17 +71,7 @@ "endColumn": 9, "problem": "CallJSFunction", "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", - "severity": "ERROR" - }, - { - "line": 19, - "column": 1, - "endLine": 19, - "endColumn": 9, - "problem": "InteropCallObjectMethods", - "suggest": "", - "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/interop/call_object_methods.ets b/ets2panda/linter/test/interop/call_object_methods.ets index f1aeeec2f2..ee45f2bcf3 100644 --- a/ets2panda/linter/test/interop/call_object_methods.ets +++ b/ets2panda/linter/test/interop/call_object_methods.ets @@ -1,19 +1,19 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -'use static' -import { foo } from "./call_object_methods_js" - -foo.bar(123) - +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +'use static' +import { foo } from "./call_object_methods_js" + +foo.bar(123) + diff --git a/ets2panda/linter/test/interop/call_object_methods.ets.args.json b/ets2panda/linter/test/interop/call_object_methods.ets.args.json index 70f3351f7e..b023016d6b 100644 --- a/ets2panda/linter/test/interop/call_object_methods.ets.args.json +++ b/ets2panda/linter/test/interop/call_object_methods.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix":"--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/interop/call_object_methods.ets.arkts2.json b/ets2panda/linter/test/interop/call_object_methods.ets.arkts2.json index c80f4a095b..db5e5b5f97 100644 --- a/ets2panda/linter/test/interop/call_object_methods.ets.arkts2.json +++ b/ets2panda/linter/test/interop/call_object_methods.ets.arkts2.json @@ -31,7 +31,7 @@ "endColumn": 47, "problem": "InterOpImportJs", "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -39,19 +39,9 @@ "column": 1, "endLine": 18, "endColumn": 13, - "problem": "InteropJsObjectUsage", + "problem": "InteropJsObjectCallStaticFunc", "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 18, - "column": 1, - "endLine": 18, - "endColumn": 13, - "problem": "CallJSFunction", - "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-call-static-function)", "severity": "ERROR" }, { @@ -61,7 +51,7 @@ "endColumn": 13, "problem": "InteropCallObjectMethods", "suggest": "", - "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-js2s-call-js-method)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/interop/call_object_methods.ets.autofix.json b/ets2panda/linter/test/interop/call_object_methods.ets.autofix.json index 75701bd0cf..5831cf0510 100644 --- a/ets2panda/linter/test/interop/call_object_methods.ets.autofix.json +++ b/ets2panda/linter/test/interop/call_object_methods.ets.autofix.json @@ -1,4 +1,3 @@ - { "copyright": [ "Copyright (c) 2025 Huawei Device Co., Ltd.", @@ -33,18 +32,18 @@ "problem": "InterOpImportJs", "autofix": [ { - "start": 632, - "end": 678, + "start": 617, + "end": 663, "replacementText": "" }, { - "start": 678, - "end": 678, - "replacementText": "let GeneratedImportVar_1 = ESObject.load('./call_object_methods_js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');" + "start": 663, + "end": 663, + "replacementText": "let GeneratedImportVar_1 = ESObject.load('./call_object_methods_js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');\n" } ], "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -52,19 +51,9 @@ "column": 1, "endLine": 18, "endColumn": 13, - "problem": "InteropJsObjectUsage", + "problem": "InteropJsObjectCallStaticFunc", "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 18, - "column": 1, - "endLine": 18, - "endColumn": 13, - "problem": "CallJSFunction", - "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-call-static-function)", "severity": "ERROR" }, { @@ -74,7 +63,7 @@ "endColumn": 13, "problem": "InteropCallObjectMethods", "suggest": "", - "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-js2s-call-js-method)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/interop/call_object_methods.ets.migrate.ets b/ets2panda/linter/test/interop/call_object_methods.ets.migrate.ets new file mode 100644 index 0000000000..68b5f0fb6e --- /dev/null +++ b/ets2panda/linter/test/interop/call_object_methods.ets.migrate.ets @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +'use static' +let GeneratedImportVar_1 = ESObject.load('./call_object_methods_js'); +let foo = GeneratedImportVar_1.getPropertyByName('foo'); + + +foo.bar(123) + diff --git a/ets2panda/linter/test/interop/call_object_methods.ets.migrate.json b/ets2panda/linter/test/interop/call_object_methods.ets.migrate.json new file mode 100644 index 0000000000..eb6c6ba8e7 --- /dev/null +++ b/ets2panda/linter/test/interop/call_object_methods.ets.migrate.json @@ -0,0 +1,38 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 5, + "endLine": 16, + "endColumn": 69, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 5, + "endLine": 17, + "endColumn": 56, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/ignore_files/unique_types.ts b/ets2panda/linter/test/interop/ignore_files/unique_types.ts index 795b8bd665..1c19752b63 100644 --- a/ets2panda/linter/test/interop/ignore_files/unique_types.ts +++ b/ets2panda/linter/test/interop/ignore_files/unique_types.ts @@ -30,5 +30,7 @@ export let mixedEnumType: X; export let intersectionType: SomeType & X; export let templateLiteralType: TemplateLiteralType; -export function tsFunction() {}; +export function tsFunction() { + throw 123; +}; export let stringType: string; diff --git a/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.args.json b/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.args.json index 64b4d19108..3318ebbbcf 100755 --- a/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.args.json +++ b/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.args.json @@ -14,6 +14,8 @@ "limitations under the License." ], "mode": { - "arkts2": "" + "arkts2": "", + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } diff --git a/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.arkts2.json b/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.arkts2.json index 7b34fd236b..188523c143 100755 --- a/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.arkts2.json +++ b/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.arkts2.json @@ -31,7 +31,7 @@ "endColumn": 52, "problem": "InterOpImportJs", "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -41,7 +41,7 @@ "endColumn": 14, "problem": "InteropIncrementDecrement", "suggest": "", - "rule": "Interop objects can't be incremented or decremented (arkts-no-js-obj-increases-decreases)", + "rule": "Interop objects can't be incremented or decremented (arkts-interop-js2s-self-addtion-reduction)", "severity": "ERROR" }, { @@ -51,7 +51,7 @@ "endColumn": 12, "problem": "InteropObjectProperty", "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -71,7 +71,7 @@ "endColumn": 12, "problem": "BinaryOperations", "suggest": "", - "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { @@ -81,7 +81,7 @@ "endColumn": 14, "problem": "InteropIncrementDecrement", "suggest": "", - "rule": "Interop objects can't be incremented or decremented (arkts-no-js-obj-increases-decreases)", + "rule": "Interop objects can't be incremented or decremented (arkts-interop-js2s-self-addtion-reduction)", "severity": "ERROR" }, { @@ -91,7 +91,7 @@ "endColumn": 14, "problem": "InteropObjectProperty", "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -111,7 +111,7 @@ "endColumn": 14, "problem": "BinaryOperations", "suggest": "", - "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { @@ -121,7 +121,7 @@ "endColumn": 14, "problem": "InteropIncrementDecrement", "suggest": "", - "rule": "Interop objects can't be incremented or decremented (arkts-no-js-obj-increases-decreases)", + "rule": "Interop objects can't be incremented or decremented (arkts-interop-js2s-self-addtion-reduction)", "severity": "ERROR" }, { @@ -131,7 +131,7 @@ "endColumn": 12, "problem": "InteropObjectProperty", "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -151,7 +151,7 @@ "endColumn": 12, "problem": "BinaryOperations", "suggest": "", - "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { @@ -161,7 +161,7 @@ "endColumn": 14, "problem": "InteropIncrementDecrement", "suggest": "", - "rule": "Interop objects can't be incremented or decremented (arkts-no-js-obj-increases-decreases)", + "rule": "Interop objects can't be incremented or decremented (arkts-interop-js2s-self-addtion-reduction)", "severity": "ERROR" }, { @@ -171,7 +171,7 @@ "endColumn": 14, "problem": "InteropObjectProperty", "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -191,7 +191,7 @@ "endColumn": 14, "problem": "BinaryOperations", "suggest": "", - "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.autofix.json b/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.autofix.json index 895325b061..4afb86a932 100755 --- a/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.autofix.json +++ b/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.autofix.json @@ -14,5 +14,253 @@ "limitations under the License." ], "result": [ + { + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 52, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 52, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 617, + "end": 668, + "replacementText": "" + }, + { + "start": 668, + "end": 668, + "replacementText": "let GeneratedImportVar_1 = ESObject.load('./increases_decreases_js_obj_js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');\n" + } + ], + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 5, + "endLine": 18, + "endColumn": 14, + "problem": "InteropIncrementDecrement", + "suggest": "", + "rule": "Interop objects can't be incremented or decremented (arkts-interop-js2s-self-addtion-reduction)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 5, + "endLine": 18, + "endColumn": 12, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 690, + "end": 697, + "replacementText": "foo.getPropertyByName(\"num\")" + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 5, + "endLine": 18, + "endColumn": 12, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "foo.getPropertyByName('num').toNumber()", + "start": 690, + "end": 697 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 5, + "endLine": 18, + "endColumn": 12, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 5, + "endLine": 19, + "endColumn": 14, + "problem": "InteropIncrementDecrement", + "suggest": "", + "rule": "Interop objects can't be incremented or decremented (arkts-interop-js2s-self-addtion-reduction)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 7, + "endLine": 19, + "endColumn": 14, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 706, + "end": 713, + "replacementText": "foo.getPropertyByName(\"num\")" + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 7, + "endLine": 19, + "endColumn": 14, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "foo.getPropertyByName('num').toNumber()", + "start": 706, + "end": 713 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 7, + "endLine": 19, + "endColumn": 14, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 5, + "endLine": 20, + "endColumn": 14, + "problem": "InteropIncrementDecrement", + "suggest": "", + "rule": "Interop objects can't be incremented or decremented (arkts-interop-js2s-self-addtion-reduction)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 5, + "endLine": 20, + "endColumn": 12, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 718, + "end": 725, + "replacementText": "foo.getPropertyByName(\"num\")" + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 5, + "endLine": 20, + "endColumn": 12, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "foo.getPropertyByName('num').toNumber()", + "start": 718, + "end": 725 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 5, + "endLine": 20, + "endColumn": 12, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 5, + "endLine": 21, + "endColumn": 14, + "problem": "InteropIncrementDecrement", + "suggest": "", + "rule": "Interop objects can't be incremented or decremented (arkts-interop-js2s-self-addtion-reduction)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 7, + "endLine": 21, + "endColumn": 14, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 734, + "end": 741, + "replacementText": "foo.getPropertyByName(\"num\")" + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 7, + "endLine": 21, + "endColumn": 14, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "foo.getPropertyByName('num').toNumber()", + "start": 734, + "end": 741 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 7, + "endLine": 21, + "endColumn": 14, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.migrate.ets b/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.migrate.ets new file mode 100644 index 0000000000..6abfb3b85c --- /dev/null +++ b/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.migrate.ets @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +'use static' +let GeneratedImportVar_1 = ESObject.load('./increases_decreases_js_obj_js'); +let foo = GeneratedImportVar_1.getPropertyByName('foo'); + +let a: number =0 +a = foo.getPropertyByName("num")++ +a = ++foo.getPropertyByName("num") +a = foo.getPropertyByName("num")-- +a = --foo.getPropertyByName("num") diff --git a/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.migrate.json b/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.migrate.json new file mode 100644 index 0000000000..3cbe2b5da3 --- /dev/null +++ b/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.migrate.json @@ -0,0 +1,38 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 5, + "endLine": 16, + "endColumn": 76, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 5, + "endLine": 17, + "endColumn": 56, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/instantiated_js_obj.ets.args.json b/ets2panda/linter/test/interop/instantiated_js_obj.ets.args.json index e237d4be28..06cb3b9046 100644 --- a/ets2panda/linter/test/interop/instantiated_js_obj.ets.args.json +++ b/ets2panda/linter/test/interop/instantiated_js_obj.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/interop/instantiated_js_obj.ets.arkts2.json b/ets2panda/linter/test/interop/instantiated_js_obj.ets.arkts2.json index ed6c8b7f73..20dfb7a06a 100644 --- a/ets2panda/linter/test/interop/instantiated_js_obj.ets.arkts2.json +++ b/ets2panda/linter/test/interop/instantiated_js_obj.ets.arkts2.json @@ -31,7 +31,7 @@ "endColumn": 51, "problem": "InterOpImportJs", "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -41,7 +41,7 @@ "endColumn": 13, "problem": "InstantiatedJsOjbect", "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", "severity": "ERROR" }, { @@ -51,7 +51,7 @@ "endColumn": 17, "problem": "InstantiatedJsOjbect", "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", "severity": "ERROR" }, { @@ -61,7 +61,7 @@ "endColumn": 17, "problem": "InstantiatedJsOjbect", "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", "severity": "ERROR" }, { @@ -71,7 +71,7 @@ "endColumn": 15, "problem": "InstantiatedJsOjbect", "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", "severity": "ERROR" }, { @@ -81,7 +81,7 @@ "endColumn": 11, "problem": "InstantiatedJsOjbect", "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", "severity": "ERROR" }, { @@ -91,7 +91,7 @@ "endColumn": 16, "problem": "InstantiatedJsOjbect", "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", "severity": "ERROR" }, { @@ -101,7 +101,7 @@ "endColumn": 23, "problem": "InstantiatedJsOjbect", "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/interop/instantiated_js_obj.ets.autofix.json b/ets2panda/linter/test/interop/instantiated_js_obj.ets.autofix.json index d426879406..a71b9e42ad 100644 --- a/ets2panda/linter/test/interop/instantiated_js_obj.ets.autofix.json +++ b/ets2panda/linter/test/interop/instantiated_js_obj.ets.autofix.json @@ -39,11 +39,11 @@ { "start": 668, "end": 668, - "replacementText": "let GeneratedImportVar_1 = ESObject.load('./instantiated_js_obj_js');\nlet Foo = GeneratedImportVar_1.getPropertyByName('Foo');\nlet Foo1 = GeneratedImportVar_1.getPropertyByName('Foo1');" + "replacementText": "let GeneratedImportVar_1 = ESObject.load('./instantiated_js_obj_js');\nlet Foo = GeneratedImportVar_1.getPropertyByName('Foo');\nlet Foo1 = GeneratedImportVar_1.getPropertyByName('Foo1');\n" } ], "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -60,7 +60,7 @@ } ], "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", "severity": "ERROR" }, { @@ -77,7 +77,7 @@ } ], "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", "severity": "ERROR" }, { @@ -94,7 +94,7 @@ } ], "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", "severity": "ERROR" }, { @@ -111,7 +111,7 @@ } ], "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", "severity": "ERROR" }, { @@ -128,7 +128,7 @@ } ], "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", "severity": "ERROR" }, { @@ -145,7 +145,7 @@ } ], "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", "severity": "ERROR" }, { @@ -162,7 +162,7 @@ } ], "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/interop/instantiated_js_obj.ets.migrate.ets b/ets2panda/linter/test/interop/instantiated_js_obj.ets.migrate.ets new file mode 100644 index 0000000000..3baba970a3 --- /dev/null +++ b/ets2panda/linter/test/interop/instantiated_js_obj.ets.migrate.ets @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use static' +let GeneratedImportVar_1 = ESObject.load('./instantiated_js_obj_js'); +let Foo = GeneratedImportVar_1.getPropertyByName('Foo'); +let Foo1 = GeneratedImportVar_1.getPropertyByName('Foo1'); + +class A { + num: number = 1; + constructor() { + } +} +Foo.instantiate(ESObject.wrap(123)) +Foo.instantiate(ESObject.wrap('hello')) +Foo.instantiate(ESObject.wrap(new A())) +let a: A = new A(); +Foo.instantiate(ESObject.wrap(a.num)) +Foo.instantiate(ESObject.wrap(a)) +function test(): number { + return 1; +} +Foo.instantiate(ESObject.wrap(test())) +Foo1.instantiate(ESObject.wrap(123), ESObject.wrap('hello')) \ No newline at end of file diff --git a/ets2panda/linter/test/interop/instantiated_js_obj.ets.migrate.json b/ets2panda/linter/test/interop/instantiated_js_obj.ets.migrate.json new file mode 100644 index 0000000000..bb4772469b --- /dev/null +++ b/ets2panda/linter/test/interop/instantiated_js_obj.ets.migrate.json @@ -0,0 +1,48 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 5, + "endLine": 17, + "endColumn": 69, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 5, + "endLine": 18, + "endColumn": 56, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 5, + "endLine": 19, + "endColumn": 58, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_convert_import.ets b/ets2panda/linter/test/interop/interop_convert_import.ets index 15717d92cc..296d7bb3ed 100755 --- a/ets2panda/linter/test/interop/interop_convert_import.ets +++ b/ets2panda/linter/test/interop/interop_convert_import.ets @@ -14,6 +14,9 @@ */ 'use static' - import {foo} from "./interop_convert_import_js.js" + import {foo, foo2, foo3, foo4} from "./interop_convert_import_js.js" - let a: number = foo.num as number \ No newline at end of file + let a: number = foo.num as number + let a: boolean = foo2.bool as boolean + let a: string = foo3.str as string + let a: bigint = foo4.big as bigint" \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_convert_import.ets.arkts2.json b/ets2panda/linter/test/interop/interop_convert_import.ets.arkts2.json index 038f42ab25..ffc1d767e8 100755 --- a/ets2panda/linter/test/interop/interop_convert_import.ets.arkts2.json +++ b/ets2panda/linter/test/interop/interop_convert_import.ets.arkts2.json @@ -18,7 +18,7 @@ "line": 17, "column": 2, "endLine": 17, - "endColumn": 52, + "endColumn": 70, "problem": "ImportAfterStatement", "suggest": "", "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", @@ -28,10 +28,10 @@ "line": 17, "column": 2, "endLine": 17, - "endColumn": 52, + "endColumn": 70, "problem": "InterOpImportJs", "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -41,7 +41,7 @@ "endColumn": 35, "problem": "InterOpConvertImport", "suggest": "", - "rule": "Casting interop JS objects to \"number\" type is not allowed (arkts-no-js-number-import)", + "rule": "Casting interop JS objects to primitive types is not allowed (arkts-interop-js2s-convert-js-type)", "severity": "ERROR" }, { @@ -61,7 +61,127 @@ "endColumn": 25, "problem": "BinaryOperations", "suggest": "", - "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 19, + "endLine": 20, + "endColumn": 40, + "problem": "InterOpConvertImport", + "suggest": "", + "rule": "Casting interop JS objects to primitive types is not allowed (arkts-interop-js2s-convert-js-type)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 19, + "endLine": 20, + "endColumn": 28, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 19, + "endLine": 20, + "endColumn": 28, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 19, + "endLine": 20, + "endColumn": 28, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 18, + "endLine": 21, + "endColumn": 37, + "problem": "InterOpConvertImport", + "suggest": "", + "rule": "Casting interop JS objects to primitive types is not allowed (arkts-interop-js2s-convert-js-type)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 18, + "endLine": 21, + "endColumn": 26, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 18, + "endLine": 21, + "endColumn": 26, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 18, + "endLine": 21, + "endColumn": 26, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 18, + "endLine": 22, + "endColumn": 37, + "problem": "InterOpConvertImport", + "suggest": "", + "rule": "Casting interop JS objects to primitive types is not allowed (arkts-interop-js2s-convert-js-type)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 18, + "endLine": 22, + "endColumn": 26, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 18, + "endLine": 22, + "endColumn": 26, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 18, + "endLine": 22, + "endColumn": 26, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/interop/interop_convert_import.ets.json b/ets2panda/linter/test/interop/interop_convert_import.ets.json index a543d16416..1d059f0d38 100755 --- a/ets2panda/linter/test/interop/interop_convert_import.ets.json +++ b/ets2panda/linter/test/interop/interop_convert_import.ets.json @@ -18,7 +18,7 @@ "line": 17, "column": 2, "endLine": 17, - "endColumn": 52, + "endColumn": 70, "problem": "ImportAfterStatement", "suggest": "", "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", diff --git a/ets2panda/linter/test/interop/interop_convert_import_js.js b/ets2panda/linter/test/interop/interop_convert_import_js.js index 16cbaf6cf8..f3895baaa7 100755 --- a/ets2panda/linter/test/interop/interop_convert_import_js.js +++ b/ets2panda/linter/test/interop/interop_convert_import_js.js @@ -13,4 +13,7 @@ * limitations under the License. */ -export let foo = {name: 123} \ No newline at end of file +export let foo = {name: 123} +export let foo2 = {bool: true} +export let foo3 = {str: '123'} +export let foo4 = {big: 123n} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_equality_judgment.ets.args.json b/ets2panda/linter/test/interop/interop_equality_judgment.ets.args.json index a2c0f14eb2..ef3938e967 100644 --- a/ets2panda/linter/test/interop/interop_equality_judgment.ets.args.json +++ b/ets2panda/linter/test/interop/interop_equality_judgment.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_equality_judgment.ets.arkts2.json b/ets2panda/linter/test/interop/interop_equality_judgment.ets.arkts2.json index 5f133df9b9..916e1b51ca 100644 --- a/ets2panda/linter/test/interop/interop_equality_judgment.ets.arkts2.json +++ b/ets2panda/linter/test/interop/interop_equality_judgment.ets.arkts2.json @@ -31,7 +31,7 @@ "endColumn": 52, "problem": "InterOpImportJs", "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -41,7 +41,7 @@ "endColumn": 7, "problem": "InteropEqualityJudgment", "suggest": "", - "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-js-equality-judgment)", + "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-interop-js2s-equality-judgment)", "severity": "ERROR" }, { @@ -51,7 +51,7 @@ "endColumn": 7, "problem": "InteropEqualityJudgment", "suggest": "", - "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-js-equality-judgment)", + "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-interop-js2s-equality-judgment)", "severity": "ERROR" }, { @@ -61,7 +61,7 @@ "endColumn": 8, "problem": "InteropEqualityJudgment", "suggest": "", - "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-js-equality-judgment)", + "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-interop-js2s-equality-judgment)", "severity": "ERROR" }, { @@ -71,7 +71,7 @@ "endColumn": 8, "problem": "InteropEqualityJudgment", "suggest": "", - "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-js-equality-judgment)", + "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-interop-js2s-equality-judgment)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/interop/interop_equality_judgment.ets.autofix.json b/ets2panda/linter/test/interop/interop_equality_judgment.ets.autofix.json index cbfed6ea9e..9c6a9f3e31 100644 --- a/ets2panda/linter/test/interop/interop_equality_judgment.ets.autofix.json +++ b/ets2panda/linter/test/interop/interop_equality_judgment.ets.autofix.json @@ -39,11 +39,11 @@ { "start": 669, "end": 669, - "replacementText": "let GeneratedImportVar_1 = ESObject.load('./interop_equality_judgment_js');\nlet a = GeneratedImportVar_1.getPropertyByName('a');\nlet b = GeneratedImportVar_1.getPropertyByName('b');" + "replacementText": "let GeneratedImportVar_1 = ESObject.load('./interop_equality_judgment_js');\nlet a = GeneratedImportVar_1.getPropertyByName('a');\nlet b = GeneratedImportVar_1.getPropertyByName('b');\n" } ], "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -60,7 +60,7 @@ } ], "suggest": "", - "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-js-equality-judgment)", + "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-interop-js2s-equality-judgment)", "severity": "ERROR" }, { @@ -77,7 +77,7 @@ } ], "suggest": "", - "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-js-equality-judgment)", + "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-interop-js2s-equality-judgment)", "severity": "ERROR" }, { @@ -94,7 +94,7 @@ } ], "suggest": "", - "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-js-equality-judgment)", + "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-interop-js2s-equality-judgment)", "severity": "ERROR" }, { @@ -111,7 +111,7 @@ } ], "suggest": "", - "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-js-equality-judgment)", + "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-interop-js2s-equality-judgment)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/interop/interop_equality_judgment.ets.migrate.ets b/ets2panda/linter/test/interop/interop_equality_judgment.ets.migrate.ets new file mode 100644 index 0000000000..50a1b8457a --- /dev/null +++ b/ets2panda/linter/test/interop/interop_equality_judgment.ets.migrate.ets @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use static' +let GeneratedImportVar_1 = ESObject.load('./interop_equality_judgment_js'); +let a = GeneratedImportVar_1.getPropertyByName('a'); +let b = GeneratedImportVar_1.getPropertyByName('b'); + +a.areEqual(b) +!a.areEqual(b) +a.areStrictlyEqual(b) +!a.areStrictlyEqual(b) \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_equality_judgment.ets.migrate.json b/ets2panda/linter/test/interop/interop_equality_judgment.ets.migrate.json new file mode 100644 index 0000000000..543f81469d --- /dev/null +++ b/ets2panda/linter/test/interop/interop_equality_judgment.ets.migrate.json @@ -0,0 +1,48 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 5, + "endLine": 17, + "endColumn": 75, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 5, + "endLine": 18, + "endColumn": 52, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 5, + "endLine": 19, + "endColumn": 52, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_export_js_rules.ets b/ets2panda/linter/test/interop/interop_export_js_rules.ets new file mode 100644 index 0000000000..5c9355e6c8 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_export_js_rules.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +'use static' + +import { ff1 } from "./interop_import_js_rules_js" + +export {ff1} // imported from js. Error is shown + +export { ff2 } from "./interop_import_js_rules_js" // ff2 is imported from js. Error is shown + +export { MyDecorator } from "./oh_modules/ets_decorator" // MyDecorator is imported from arkts1. Error is shown + +export { foo as bar } from "./oh_modules/reflect_export" // foo is imported from arkts1.2. No error. diff --git a/ets2panda/linter/test/interop/interop_export_js_rules.ets.args.json b/ets2panda/linter/test/interop/interop_export_js_rules.ets.args.json new file mode 100644 index 0000000000..6958168fef --- /dev/null +++ b/ets2panda/linter/test/interop/interop_export_js_rules.ets.args.json @@ -0,0 +1,21 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2", + "migrate": "--arkts-2" + } +} diff --git a/ets2panda/linter/test/interop/interop_export_js_rules.ets.arkts2.json b/ets2panda/linter/test/interop/interop_export_js_rules.ets.arkts2.json new file mode 100644 index 0000000000..8aafb129da --- /dev/null +++ b/ets2panda/linter/test/interop/interop_export_js_rules.ets.arkts2.json @@ -0,0 +1,68 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 51, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 51, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 13, + "problem": "InteropJsObjectExport", + "suggest": "", + "rule": "Direct export of interop JS objects is not supported (arkts-interop-js2s-export-js)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 51, + "problem": "InteropJsObjectExport", + "suggest": "", + "rule": "Direct export of interop JS objects is not supported (arkts-interop-js2s-export-js)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 1, + "endLine": 23, + "endColumn": 57, + "problem": "InteropArkTs1ObjectExport", + "suggest": "", + "rule": "Direct export of interop ArkTS1.0 objects is not supported (arkts-interop-d2s-export-entity)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_export_js_rules.ets.autofix.json b/ets2panda/linter/test/interop/interop_export_js_rules.ets.autofix.json new file mode 100644 index 0000000000..58c2313941 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_export_js_rules.ets.autofix.json @@ -0,0 +1,88 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 51, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 51, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 618, + "end": 668, + "replacementText": "", + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 51 + }, + { + "start": 668, + "end": 668, + "replacementText": "let GeneratedImportVar_1 = ESObject.load('./interop_import_js_rules_js');\nlet ff1 = GeneratedImportVar_1.getPropertyByName('ff1');\n", + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 51 + } + ], + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 13, + "problem": "InteropJsObjectExport", + "suggest": "", + "rule": "Direct export of interop JS objects is not supported (arkts-interop-js2s-export-js)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 51, + "problem": "InteropJsObjectExport", + "suggest": "", + "rule": "Direct export of interop JS objects is not supported (arkts-interop-js2s-export-js)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 1, + "endLine": 23, + "endColumn": 57, + "problem": "InteropArkTs1ObjectExport", + "suggest": "", + "rule": "Direct export of interop ArkTS1.0 objects is not supported (arkts-interop-d2s-export-entity)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/interop/interop_export_js_rules.ets.json b/ets2panda/linter/test/interop/interop_export_js_rules.ets.json new file mode 100644 index 0000000000..91f5b61ed1 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_export_js_rules.ets.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 51, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/interop/interop_export_js_rules.ets.migrate.ets b/ets2panda/linter/test/interop/interop_export_js_rules.ets.migrate.ets new file mode 100644 index 0000000000..ad8d86948b --- /dev/null +++ b/ets2panda/linter/test/interop/interop_export_js_rules.ets.migrate.ets @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +'use static' + +let GeneratedImportVar_1 = ESObject.load('./interop_import_js_rules_js'); +let ff1 = GeneratedImportVar_1.getPropertyByName('ff1'); + + +export {ff1} // imported from js. Error is shown + +export { ff2 } from "./interop_import_js_rules_js" // ff2 is imported from js. Error is shown + +export { MyDecorator } from "./oh_modules/ets_decorator" // MyDecorator is imported from arkts1. Error is shown + +export { foo as bar } from "./oh_modules/reflect_export" // foo is imported from arkts1.2. No error. diff --git a/ets2panda/linter/test/interop/interop_export_js_rules.ets.migrate.json b/ets2panda/linter/test/interop/interop_export_js_rules.ets.migrate.json new file mode 100644 index 0000000000..1291e15d5e --- /dev/null +++ b/ets2panda/linter/test/interop/interop_export_js_rules.ets.migrate.json @@ -0,0 +1,58 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 5, + "endLine": 17, + "endColumn": 73, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 5, + "endLine": 18, + "endColumn": 56, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 1, + "endLine": 23, + "endColumn": 51, + "problem": "InteropJsObjectExport", + "suggest": "", + "rule": "Direct export of interop JS objects is not supported (arkts-interop-js2s-export-js)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 1, + "endLine": 25, + "endColumn": 57, + "problem": "InteropArkTs1ObjectExport", + "suggest": "", + "rule": "Direct export of interop ArkTS1.0 objects is not supported (arkts-interop-d2s-export-entity)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/interop/interop_import_js.ets.args.json b/ets2panda/linter/test/interop/interop_import_js.ets.args.json index 815373beb6..df6e67a5c9 100755 --- a/ets2panda/linter/test/interop/interop_import_js.ets.args.json +++ b/ets2panda/linter/test/interop/interop_import_js.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_import_js.ets.arkts2.json b/ets2panda/linter/test/interop/interop_import_js.ets.arkts2.json index d8a70abf60..17f26fd8dc 100755 --- a/ets2panda/linter/test/interop/interop_import_js.ets.arkts2.json +++ b/ets2panda/linter/test/interop/interop_import_js.ets.arkts2.json @@ -31,7 +31,7 @@ "endColumn": 38, "problem": "InterOpImportJs", "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -51,7 +51,7 @@ "endColumn": 38, "problem": "InterOpImportJs", "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -71,7 +71,7 @@ "endColumn": 64, "problem": "InterOpImportJs", "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -91,7 +91,7 @@ "endColumn": 44, "problem": "InterOpImportJs", "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -111,7 +111,7 @@ "endColumn": 57, "problem": "InterOpImportJs", "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -131,7 +131,7 @@ "endColumn": 53, "problem": "InterOpImportJs", "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -151,7 +151,7 @@ "endColumn": 59, "problem": "InterOpImportJs", "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/interop/interop_import_js.ets.autofix.json b/ets2panda/linter/test/interop/interop_import_js.ets.autofix.json index f1de093cb7..947b0ed85e 100755 --- a/ets2panda/linter/test/interop/interop_import_js.ets.autofix.json +++ b/ets2panda/linter/test/interop/interop_import_js.ets.autofix.json @@ -39,11 +39,11 @@ { "start": 971, "end": 971, - "replacementText": "let GeneratedImportVar_1 = ESObject.load('../main/js_lib');\nlet Cjs = GeneratedImportVar_1.getPropertyByName('Cjs');" + "replacementText": "let GeneratedImportVar_1 = ESObject.load('../main/js_lib');\nlet Cjs = GeneratedImportVar_1.getPropertyByName('Cjs');\n" } ], "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -71,11 +71,11 @@ { "start": 971, "end": 971, - "replacementText": "let GeneratedImportVar_2 = ESObject.load('../main/js_lib');\nlet fjs = GeneratedImportVar_2.getPropertyByName('fjs');" + "replacementText": "let GeneratedImportVar_2 = ESObject.load('../main/js_lib');\nlet fjs = GeneratedImportVar_2.getPropertyByName('fjs');\n" } ], "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -103,11 +103,11 @@ { "start": 971, "end": 971, - "replacementText": "let GeneratedImportVar_3 = ESObject.load('./jsfiles/preview_import_js');\nlet CPreview = GeneratedImportVar_3.getPropertyByName('CPreview');\nlet bar = GeneratedImportVar_3.getPropertyByName('bar');\nlet foo = GeneratedImportVar_3.getPropertyByName('foo');" + "replacementText": "let GeneratedImportVar_3 = ESObject.load('./jsfiles/preview_import_js');\nlet CPreview = GeneratedImportVar_3.getPropertyByName('CPreview');\nlet bar = GeneratedImportVar_3.getPropertyByName('bar');\nlet foo = GeneratedImportVar_3.getPropertyByName('foo');\n" } ], "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -135,11 +135,11 @@ { "start": 971, "end": 971, - "replacementText": "let GeneratedImportVar_4 = ESObject.load('./interop_import_js_js');\nlet myAaa = GeneratedImportVar_4.getPropertyByName('aaa');" + "replacementText": "let GeneratedImportVar_4 = ESObject.load('./interop_import_js_js');\nlet myAaa = GeneratedImportVar_4.getPropertyByName('aaa');\n" } ], "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -167,11 +167,11 @@ { "start": 971, "end": 971, - "replacementText": "let GeneratedImportVar_5 = ESObject.load('./interop_import_js_js');\nlet myAaa = GeneratedImportVar_5.getPropertyByName('aaa');\nlet ClassA = GeneratedImportVar_5.getPropertyByName('ClassA');\nlet Dog = GeneratedImportVar_5.getPropertyByName('Dog');" + "replacementText": "let GeneratedImportVar_5 = ESObject.load('./interop_import_js_js');\nlet myAaa = GeneratedImportVar_5.getPropertyByName('aaa');\nlet ClassA = GeneratedImportVar_5.getPropertyByName('ClassA');\nlet Dog = GeneratedImportVar_5.getPropertyByName('Dog');\n" } ], "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -199,11 +199,11 @@ { "start": 971, "end": 971, - "replacementText": "let GeneratedImportVar_6 = ESObject.load('./interop_import_js_js');" + "replacementText": "let GeneratedImportVar_6 = ESObject.load('./interop_import_js_js');\n" } ], "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -231,11 +231,11 @@ { "start": 971, "end": 971, - "replacementText": "let GeneratedImportVar_7 = ESObject.load('./interop_import_js_js');\nlet Wiki = GeneratedImportVar_7.getPropertyByName('Wiki');\nlet Doge = GeneratedImportVar_7.getPropertyByName('Dog');" + "replacementText": "let GeneratedImportVar_7 = ESObject.load('./interop_import_js_js');\nlet Wiki = GeneratedImportVar_7.getPropertyByName('Wiki');\nlet Doge = GeneratedImportVar_7.getPropertyByName('Dog');\n" } ], "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/interop/interop_import_js.ets.migrate.ets b/ets2panda/linter/test/interop/interop_import_js.ets.migrate.ets new file mode 100644 index 0000000000..fb72fa1882 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_js.ets.migrate.ets @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use static' + + + + + + +let GeneratedImportVar_7 = ESObject.load('./interop_import_js_js'); +let Wiki = GeneratedImportVar_7.getPropertyByName('Wiki'); +let Doge = GeneratedImportVar_7.getPropertyByName('Dog'); +let GeneratedImportVar_6 = ESObject.load('./interop_import_js_js'); +let GeneratedImportVar_5 = ESObject.load('./interop_import_js_js'); +let myAaa = GeneratedImportVar_5.getPropertyByName('aaa'); +let ClassA = GeneratedImportVar_5.getPropertyByName('ClassA'); +let Dog = GeneratedImportVar_5.getPropertyByName('Dog'); +let GeneratedImportVar_4 = ESObject.load('./interop_import_js_js'); +let myAaa = GeneratedImportVar_4.getPropertyByName('aaa'); +let GeneratedImportVar_3 = ESObject.load('./jsfiles/preview_import_js'); +let CPreview = GeneratedImportVar_3.getPropertyByName('CPreview'); +let bar = GeneratedImportVar_3.getPropertyByName('bar'); +let foo = GeneratedImportVar_3.getPropertyByName('foo'); +let GeneratedImportVar_2 = ESObject.load('../main/js_lib'); +let fjs = GeneratedImportVar_2.getPropertyByName('fjs'); +let GeneratedImportVar_1 = ESObject.load('../main/js_lib'); +let Cjs = GeneratedImportVar_1.getPropertyByName('Cjs'); diff --git a/ets2panda/linter/test/interop/interop_import_js.ets.migrate.json b/ets2panda/linter/test/interop/interop_import_js.ets.migrate.json new file mode 100644 index 0000000000..c1173895c4 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_js.ets.migrate.json @@ -0,0 +1,198 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 23, + "column": 5, + "endLine": 23, + "endColumn": 67, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 5, + "endLine": 24, + "endColumn": 58, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 5, + "endLine": 25, + "endColumn": 57, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 5, + "endLine": 26, + "endColumn": 67, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 5, + "endLine": 27, + "endColumn": 67, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 5, + "endLine": 28, + "endColumn": 58, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 5, + "endLine": 29, + "endColumn": 62, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 5, + "endLine": 30, + "endColumn": 56, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 5, + "endLine": 31, + "endColumn": 67, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 5, + "endLine": 32, + "endColumn": 58, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 5, + "endLine": 33, + "endColumn": 72, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 5, + "endLine": 34, + "endColumn": 66, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 5, + "endLine": 35, + "endColumn": 56, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 36, + "column": 5, + "endLine": 36, + "endColumn": 56, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 5, + "endLine": 37, + "endColumn": 59, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 5, + "endLine": 38, + "endColumn": 56, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 5, + "endLine": 39, + "endColumn": 59, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 40, + "column": 5, + "endLine": 40, + "endColumn": 56, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_import_js_compare.ets b/ets2panda/linter/test/interop/interop_import_js_compare.ets index 7b719e70d0..496fe91c55 100644 --- a/ets2panda/linter/test/interop/interop_import_js_compare.ets +++ b/ets2panda/linter/test/interop/interop_import_js_compare.ets @@ -39,4 +39,6 @@ let x2 = bar.a, y2 = bar.b; x2 > y2; x2 < y2; x2 >= y2; -x2 <= y2; \ No newline at end of file +x2 <= y2; + +foo.a > foo.b; \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_import_js_compare.ets.arkts2.json b/ets2panda/linter/test/interop/interop_import_js_compare.ets.arkts2.json index db1438446c..083e145c47 100644 --- a/ets2panda/linter/test/interop/interop_import_js_compare.ets.arkts2.json +++ b/ets2panda/linter/test/interop/interop_import_js_compare.ets.arkts2.json @@ -31,7 +31,7 @@ "endColumn": 57, "problem": "InterOpImportJs", "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -41,7 +41,7 @@ "endColumn": 14, "problem": "InteropObjectProperty", "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -61,7 +61,7 @@ "endColumn": 14, "problem": "BinaryOperations", "suggest": "", - "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { @@ -71,7 +71,7 @@ "endColumn": 14, "problem": "InteropObjectProperty", "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -91,7 +91,7 @@ "endColumn": 14, "problem": "BinaryOperations", "suggest": "", - "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { @@ -101,7 +101,7 @@ "endColumn": 2, "problem": "InterOpImportJsDataCompare", "suggest": "", - "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-js-data-compare)", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-interop-js2s-compare-js-data)", "severity": "ERROR" }, { @@ -111,7 +111,7 @@ "endColumn": 6, "problem": "InterOpImportJsDataCompare", "suggest": "", - "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-js-data-compare)", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-interop-js2s-compare-js-data)", "severity": "ERROR" }, { @@ -121,7 +121,7 @@ "endColumn": 2, "problem": "InterOpImportJsDataCompare", "suggest": "", - "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-js-data-compare)", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-interop-js2s-compare-js-data)", "severity": "ERROR" }, { @@ -131,7 +131,7 @@ "endColumn": 6, "problem": "InterOpImportJsDataCompare", "suggest": "", - "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-js-data-compare)", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-interop-js2s-compare-js-data)", "severity": "ERROR" }, { @@ -141,7 +141,7 @@ "endColumn": 2, "problem": "InterOpImportJsDataCompare", "suggest": "", - "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-js-data-compare)", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-interop-js2s-compare-js-data)", "severity": "ERROR" }, { @@ -151,7 +151,7 @@ "endColumn": 7, "problem": "InterOpImportJsDataCompare", "suggest": "", - "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-js-data-compare)", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-interop-js2s-compare-js-data)", "severity": "ERROR" }, { @@ -161,7 +161,7 @@ "endColumn": 2, "problem": "InterOpImportJsDataCompare", "suggest": "", - "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-js-data-compare)", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-interop-js2s-compare-js-data)", "severity": "ERROR" }, { @@ -171,17 +171,7 @@ "endColumn": 7, "problem": "InterOpImportJsDataCompare", "suggest": "", - "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-js-data-compare)", - "severity": "ERROR" - }, - { - "line": 25, - "column": 1, - "endLine": 25, - "endColumn": 2, - "problem": "InterOpImportJsDataCompare", - "suggest": "", - "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-js-data-compare)", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-interop-js2s-compare-js-data)", "severity": "ERROR" }, { @@ -191,7 +181,7 @@ "endColumn": 2, "problem": "InterOpImportJsDataCompare", "suggest": "", - "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-js-data-compare)", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-interop-js2s-compare-js-data)", "severity": "ERROR" }, { @@ -201,17 +191,7 @@ "endColumn": 6, "problem": "InterOpImportJsDataCompare", "suggest": "", - "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-js-data-compare)", - "severity": "ERROR" - }, - { - "line": 28, - "column": 1, - "endLine": 28, - "endColumn": 2, - "problem": "InterOpImportJsDataCompare", - "suggest": "", - "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-js-data-compare)", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-interop-js2s-compare-js-data)", "severity": "ERROR" }, { @@ -263,6 +243,86 @@ "suggest": "", "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" + }, + { + "line": 44, + "column": 1, + "endLine": 44, + "endColumn": 6, + "problem": "InterOpImportJsDataCompare", + "suggest": "", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-interop-js2s-compare-js-data)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 9, + "endLine": 44, + "endColumn": 14, + "problem": "InterOpImportJsDataCompare", + "suggest": "", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-interop-js2s-compare-js-data)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 1, + "endLine": 44, + "endColumn": 6, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 1, + "endLine": 44, + "endColumn": 6, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 1, + "endLine": 44, + "endColumn": 6, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 9, + "endLine": 44, + "endColumn": 14, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 9, + "endLine": 44, + "endColumn": 14, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 9, + "endLine": 44, + "endColumn": 14, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_import_js_index.ets.args.json b/ets2panda/linter/test/interop/interop_import_js_index.ets.args.json index 6bbb5430dd..fb061d2224 100644 --- a/ets2panda/linter/test/interop/interop_import_js_index.ets.args.json +++ b/ets2panda/linter/test/interop/interop_import_js_index.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_import_js_index.ets.arkts2.json b/ets2panda/linter/test/interop/interop_import_js_index.ets.arkts2.json index c8e9598d33..8049b29933 100644 --- a/ets2panda/linter/test/interop/interop_import_js_index.ets.arkts2.json +++ b/ets2panda/linter/test/interop/interop_import_js_index.ets.arkts2.json @@ -31,7 +31,7 @@ "endColumn": 49, "problem": "InterOpImportJs", "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -41,7 +41,7 @@ "endColumn": 18, "problem": "InteropObjectProperty", "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -61,7 +61,7 @@ "endColumn": 18, "problem": "BinaryOperations", "suggest": "", - "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { @@ -69,9 +69,9 @@ "column": 1, "endLine": 19, "endColumn": 7, - "problem": "InteropJsObjectUsage", + "problem": "InteropJsObjectTraverseJsInstance", "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js2s-traverse-js-instance)", "severity": "ERROR" }, { @@ -81,7 +81,7 @@ "endColumn": 7, "problem": "InterOpImportJsIndex", "suggest": "", - "rule": "Interop objects can't be indexed directly (arkts-no-js-index-import)", + "rule": "Interop objects can't be indexed directly (arkts-interop-js2s-access-js-index)", "severity": "ERROR" }, { @@ -89,9 +89,9 @@ "column": 1, "endLine": 20, "endColumn": 7, - "problem": "InteropJsObjectUsage", + "problem": "InteropJsObjectTraverseJsInstance", "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js2s-traverse-js-instance)", "severity": "ERROR" }, { @@ -101,7 +101,7 @@ "endColumn": 11, "problem": "InterOpImportJsIndex", "suggest": "", - "rule": "Interop objects can't be indexed directly (arkts-no-js-index-import)", + "rule": "Interop objects can't be indexed directly (arkts-interop-js2s-access-js-index)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/interop/interop_import_js_index.ets.autofix.json b/ets2panda/linter/test/interop/interop_import_js_index.ets.autofix.json index 9e8c533fc2..7b4806fa65 100644 --- a/ets2panda/linter/test/interop/interop_import_js_index.ets.autofix.json +++ b/ets2panda/linter/test/interop/interop_import_js_index.ets.autofix.json @@ -39,11 +39,11 @@ { "start": 667, "end": 667, - "replacementText": "let GeneratedImportVar_1 = ESObject.load('./interop_import_js_index_js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');" + "replacementText": "let GeneratedImportVar_1 = ESObject.load('./interop_import_js_index_js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');\n" } ], "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -60,7 +60,7 @@ } ], "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -87,7 +87,7 @@ "endColumn": 18, "problem": "BinaryOperations", "suggest": "", - "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { @@ -95,7 +95,7 @@ "column": 1, "endLine": 19, "endColumn": 7, - "problem": "InteropJsObjectUsage", + "problem": "InteropJsObjectTraverseJsInstance", "autofix": [ { "replacementText": "arr.getPropertyByIndex(1).toNumber()", @@ -104,7 +104,7 @@ } ], "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js2s-traverse-js-instance)", "severity": "ERROR" }, { @@ -121,7 +121,7 @@ } ], "suggest": "", - "rule": "Interop objects can't be indexed directly (arkts-no-js-index-import)", + "rule": "Interop objects can't be indexed directly (arkts-interop-js2s-access-js-index)", "severity": "ERROR" }, { @@ -129,7 +129,7 @@ "column": 1, "endLine": 20, "endColumn": 7, - "problem": "InteropJsObjectUsage", + "problem": "InteropJsObjectTraverseJsInstance", "autofix": [ { "replacementText": "arr.setPropertyByIndex(3, ESObject.wrap(4))", @@ -138,7 +138,7 @@ } ], "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js2s-traverse-js-instance)", "severity": "ERROR" }, { @@ -155,7 +155,7 @@ } ], "suggest": "", - "rule": "Interop objects can't be indexed directly (arkts-no-js-index-import)", + "rule": "Interop objects can't be indexed directly (arkts-interop-js2s-access-js-index)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/interop/interop_import_js_index.ets.migrate.ets b/ets2panda/linter/test/interop/interop_import_js_index.ets.migrate.ets new file mode 100644 index 0000000000..17caa7fd96 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_js_index.ets.migrate.ets @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use static' +let GeneratedImportVar_1 = ESObject.load('./interop_import_js_index_js'); +let foo = GeneratedImportVar_1.getPropertyByName('foo'); + +let arr = foo.getPropertyByName("arr") +arr.getPropertyByIndex(1).toNumber() +arr.setPropertyByIndex(3, ESObject.wrap(4)) \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_import_js_index.ets.migrate.json b/ets2panda/linter/test/interop/interop_import_js_index.ets.migrate.json new file mode 100644 index 0000000000..a9df6f95e7 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_js_index.ets.migrate.json @@ -0,0 +1,48 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 5, + "endLine": 17, + "endColumn": 73, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 5, + "endLine": 18, + "endColumn": 56, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 5, + "endLine": 20, + "endColumn": 39, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_import_js_rules.ets b/ets2panda/linter/test/interop/interop_import_js_rules.ets index 9962b58ee5..3b88109fc2 100644 --- a/ets2panda/linter/test/interop/interop_import_js_rules.ets +++ b/ets2panda/linter/test/interop/interop_import_js_rules.ets @@ -12,18 +12,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +'use static'; -import { foo } from "./oh_modules/interop_import_js_rules" -import { ff1, ff2 } from "./oh_modules/interop_import_js_rules" +import { foo } from "./interop_import_js_rules_js" +import { ff1, ff2 } from "./interop_import_js_rules_js" -import { A } from "./oh_modules/interop_import_js_rules" -import { C } from "./oh_modules/interop_import_js_rules" +import { A } from "./interop_import_js_rules_js" +import { C } from "./interop_import_js_rules_js" -import { ff3 } from "./oh_modules/interop_import_js_rules" +import { ff3 } from "./interop_import_js_rules_js" -import { ff4 } from "./oh_modules/interop_import_js_rules" +import { ff4 } from "./interop_import_js_rules_js" -import { handle } from "./oh_modules/interop_import_js_rules" +import { handle } from "./interop_import_js_rules_js" + +import { expand } from "./interop_import_js_rules_js" if (foo.isGood) {} @@ -59,3 +62,6 @@ let lambda = (p: Person) => {} handle(foo2) handle(lambda) + +class X{a = 1; b= 2; c= 3} +expand(new X()) // ERROR expand-static diff --git a/ets2panda/linter/test/interop/interop_import_js_rules.ets.arkts2.json b/ets2panda/linter/test/interop/interop_import_js_rules.ets.arkts2.json index aff72256ec..ad917d5f3c 100644 --- a/ets2panda/linter/test/interop/interop_import_js_rules.ets.arkts2.json +++ b/ets2panda/linter/test/interop/interop_import_js_rules.ets.arkts2.json @@ -14,185 +14,485 @@ "limitations under the License." ], "result": [ - { - "line": 28, - "column": 5, - "endLine": 28, - "endColumn": 15, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 30, - "column": 5, - "endLine": 30, - "endColumn": 11, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 34, - "column": 1, - "endLine": 34, - "endColumn": 21, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 38, - "column": 1, - "endLine": 38, - "endColumn": 21, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 41, - "column": 3, - "endLine": 41, - "endColumn": 8, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 41, - "column": 3, - "endLine": 41, - "endColumn": 8, - "problem": "CallJSFunction", - "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", - "severity": "ERROR" - }, - { - "line": 41, - "column": 3, - "endLine": 41, - "endColumn": 8, - "problem": "InteropCallObjectMethods", - "suggest": "", - "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", - "severity": "ERROR" - }, - { - "line": 46, - "column": 11, - "endLine": 46, - "endColumn": 18, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 47, - "column": 11, - "endLine": 47, - "endColumn": 21, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 48, - "column": 10, - "endLine": 48, - "endColumn": 15, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 49, - "column": 11, - "endLine": 49, - "endColumn": 17, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 50, - "column": 3, - "endLine": 50, - "endColumn": 9, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 60, - "column": 1, - "endLine": 60, - "endColumn": 13, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 60, - "column": 1, - "endLine": 60, - "endColumn": 13, - "problem": "CallJSFunction", - "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", - "severity": "ERROR" - }, - { - "line": 60, - "column": 1, - "endLine": 60, - "endColumn": 13, - "problem": "InteropCallObjectMethods", - "suggest": "", - "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", - "severity": "ERROR" - }, - { - "line": 61, - "column": 1, - "endLine": 61, - "endColumn": 15, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 61, - "column": 1, - "endLine": 61, - "endColumn": 15, - "problem": "CallJSFunction", - "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", - "severity": "ERROR" - }, - { - "line": 61, - "column": 1, - "endLine": 61, - "endColumn": 15, - "problem": "InteropCallObjectMethods", - "suggest": "", - "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", - "severity": "ERROR" - } - ] -} \ No newline at end of file + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 51, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 51, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 56, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 56, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 49, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 49, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 49, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 49, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 1, + "endLine": 23, + "endColumn": 51, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 1, + "endLine": 23, + "endColumn": 51, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 1, + "endLine": 25, + "endColumn": 51, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 1, + "endLine": 25, + "endColumn": 51, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 1, + "endLine": 27, + "endColumn": 54, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 1, + "endLine": 27, + "endColumn": 54, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 1, + "endLine": 29, + "endColumn": 54, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 1, + "endLine": 29, + "endColumn": 54, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 5, + "endLine": 31, + "endColumn": 15, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 5, + "endLine": 31, + "endColumn": 15, + "problem": "InteropJsObjectConditionJudgment", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js2s-condition-judgment)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 5, + "endLine": 31, + "endColumn": 15, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 5, + "endLine": 33, + "endColumn": 11, + "problem": "InterOpImportJsDataCompare", + "suggest": "", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-interop-js2s-compare-js-data)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 5, + "endLine": 33, + "endColumn": 11, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 5, + "endLine": 33, + "endColumn": 11, + "problem": "InteropJsObjectConditionJudgment", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js2s-condition-judgment)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 5, + "endLine": 33, + "endColumn": 11, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 1, + "endLine": 37, + "endColumn": 21, + "problem": "InteropJsObjectInheritance", + "suggest": "", + "rule": "Direct inheritance of interop JS classes is not supported (arkts-interop-js2s-inherit-js-class)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 1, + "endLine": 41, + "endColumn": 21, + "problem": "InteropJsObjectInheritance", + "suggest": "", + "rule": "Direct inheritance of interop JS classes is not supported (arkts-interop-js2s-inherit-js-class)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 3, + "endLine": 44, + "endColumn": 8, + "problem": "InteropJSFunctionInvoke", + "suggest": "", + "rule": "Trying to catch JS errors is not permitted (arkts-interop-js2s-js-exception)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 3, + "endLine": 44, + "endColumn": 8, + "problem": "InteropJsObjectCallStaticFunc", + "suggest": "", + "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-call-static-function)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 3, + "endLine": 44, + "endColumn": 8, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 3, + "endLine": 47, + "endColumn": 2, + "problem": "TsLikeCatchType", + "suggest": "", + "rule": "TS catch type are not supported (arkts-no-ts-like-catch-type)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 11, + "endLine": 49, + "endColumn": 18, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 11, + "endLine": 49, + "endColumn": 18, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 11, + "endLine": 49, + "endColumn": 18, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + }, + { + "line": 50, + "column": 11, + "endLine": 50, + "endColumn": 21, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 53, + "column": 3, + "endLine": 53, + "endColumn": 9, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 51, + "column": 10, + "endLine": 51, + "endColumn": 15, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 52, + "column": 11, + "endLine": 52, + "endColumn": 17, + "problem": "InteropJsObjectTraverseJsInstance", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js2s-traverse-js-instance)", + "severity": "ERROR" + }, + { + "line": 52, + "column": 11, + "endLine": 52, + "endColumn": 17, + "problem": "InterOpImportJsIndex", + "suggest": "", + "rule": "Interop objects can't be indexed directly (arkts-interop-js2s-access-js-index)", + "severity": "ERROR" + }, + { + "line": 53, + "column": 3, + "endLine": 53, + "endColumn": 9, + "problem": "InteropJsObjectTraverseJsInstance", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js2s-traverse-js-instance)", + "severity": "ERROR" + }, + { + "line": 53, + "column": 3, + "endLine": 53, + "endColumn": 13, + "problem": "InterOpImportJsIndex", + "suggest": "", + "rule": "Interop objects can't be indexed directly (arkts-interop-js2s-access-js-index)", + "severity": "ERROR" + }, + { + "line": 63, + "column": 1, + "endLine": 63, + "endColumn": 13, + "problem": "InteropJsObjectCallStaticFunc", + "suggest": "", + "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-call-static-function)", + "severity": "ERROR" + }, + { + "line": 63, + "column": 1, + "endLine": 63, + "endColumn": 13, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", + "severity": "ERROR" + }, + { + "line": 64, + "column": 1, + "endLine": 64, + "endColumn": 15, + "problem": "InteropJsObjectCallStaticFunc", + "suggest": "", + "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-call-static-function)", + "severity": "ERROR" + }, + { + "line": 64, + "column": 1, + "endLine": 64, + "endColumn": 15, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", + "severity": "ERROR" + }, + { + "line": 66, + "column": 9, + "endLine": 66, + "endColumn": 15, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 66, + "column": 16, + "endLine": 66, + "endColumn": 21, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 66, + "column": 22, + "endLine": 66, + "endColumn": 26, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 67, + "column": 1, + "endLine": 67, + "endColumn": 16, + "problem": "InteropJsObjectExpandStaticInstance", + "suggest": "", + "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-expand-static-instance)", + "severity": "ERROR" + }, + { + "line": 67, + "column": 1, + "endLine": 67, + "endColumn": 16, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/interop/interop_import_js_rules.ets.autofix.json b/ets2panda/linter/test/interop/interop_import_js_rules.ets.autofix.json index bd63525409..ec42a706b8 100644 --- a/ets2panda/linter/test/interop/interop_import_js_rules.ets.autofix.json +++ b/ets2panda/linter/test/interop/interop_import_js_rules.ets.autofix.json @@ -14,234 +14,810 @@ "limitations under the License." ], "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 51, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 51, + "problem": "InterOpImportJs", + "autofix": [ { - "line": 28, - "column": 5, - "endLine": 28, - "endColumn": 15, - "problem": "InteropJsObjectUsage", - "autofix": [ - { - "replacementText": "foo.getPropertyByName('isGood').toBoolean()", - "start": 1031, - "end": 1041 - } - ], - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" + "start": 619, + "end": 669, + "replacementText": "", + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 51 }, { - "line": 30, - "column": 5, - "endLine": 30, - "endColumn": 11, - "problem": "InteropJsObjectUsage", - "autofix": [ - { - "replacementText": "ff1.getPropertyByName('f1').toNumber()", - "start": 1051, - "end": 1057 - } - ], - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, + "start": 1038, + "end": 1038, + "replacementText": "let GeneratedImportVar_1 = ESObject.load('./interop_import_js_rules_js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');\n", + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 51 + } + ], + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 56, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 56, + "problem": "InterOpImportJs", + "autofix": [ { - "line": 34, - "column": 1, - "endLine": 34, - "endColumn": 21, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" + "start": 670, + "end": 725, + "replacementText": "", + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 56 }, { - "line": 38, - "column": 1, - "endLine": 38, - "endColumn": 21, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, + "start": 1038, + "end": 1038, + "replacementText": "let GeneratedImportVar_2 = ESObject.load('./interop_import_js_rules_js');\nlet ff1 = GeneratedImportVar_2.getPropertyByName('ff1');\nlet ff2 = GeneratedImportVar_2.getPropertyByName('ff2');\n", + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 56 + } + ], + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 49, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 49, + "problem": "InterOpImportJs", + "autofix": [ { - "line": 41, - "column": 3, - "endLine": 41, - "endColumn": 8, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" + "start": 727, + "end": 775, + "replacementText": "", + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 49 }, { - "line": 41, - "column": 3, - "endLine": 41, - "endColumn": 8, - "problem": "CallJSFunction", - "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", - "severity": "ERROR" - }, + "start": 1038, + "end": 1038, + "replacementText": "let GeneratedImportVar_3 = ESObject.load('./interop_import_js_rules_js');\nlet A = GeneratedImportVar_3.getPropertyByName('A');\n", + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 49 + } + ], + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 49, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 49, + "problem": "InterOpImportJs", + "autofix": [ { - "line": 41, - "column": 3, - "endLine": 41, - "endColumn": 8, - "problem": "InteropCallObjectMethods", - "suggest": "", - "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", - "severity": "ERROR" + "start": 776, + "end": 824, + "replacementText": "", + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 49 }, { - "line": 46, - "column": 11, - "endLine": 46, - "endColumn": 18, - "problem": "InteropJsObjectUsage", - "autofix": [ - { - "replacementText": "ff3.getPropertyByName('arr')", - "start": 1277, - "end": 1284 - } - ], - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, + "start": 1038, + "end": 1038, + "replacementText": "let GeneratedImportVar_4 = ESObject.load('./interop_import_js_rules_js');\nlet C = GeneratedImportVar_4.getPropertyByName('C');\n", + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 49 + } + ], + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 1, + "endLine": 23, + "endColumn": 51, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 1, + "endLine": 23, + "endColumn": 51, + "problem": "InterOpImportJs", + "autofix": [ { - "line": 47, - "column": 11, - "endLine": 47, - "endColumn": 21, - "problem": "InteropJsObjectUsage", - "autofix": [ - { - "replacementText": "arr.getPropertyByName('length').toNumber()", - "start": 1295, - "end": 1315 - } - ], - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" + "start": 826, + "end": 876, + "replacementText": "", + "line": 23, + "column": 1, + "endLine": 23, + "endColumn": 51 }, { - "line": 48, - "column": 10, - "endLine": 48, - "endColumn": 15, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 1325, - "end": 1330, - "replacementText": "i: number = 0" - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, + "start": 1038, + "end": 1038, + "replacementText": "let GeneratedImportVar_5 = ESObject.load('./interop_import_js_rules_js');\nlet ff3 = GeneratedImportVar_5.getPropertyByName('ff3');\n", + "line": 23, + "column": 1, + "endLine": 23, + "endColumn": 51 + } + ], + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 1, + "endLine": 25, + "endColumn": 51, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 1, + "endLine": 25, + "endColumn": 51, + "problem": "InterOpImportJs", + "autofix": [ { - "line": 49, - "column": 11, - "endLine": 49, - "endColumn": 17, - "problem": "InteropJsObjectUsage", - "autofix": [ - { - "replacementText": "arr.getPropertyByIndex(i).toNumber()", - "start": 1358, - "end": 1364 - } - ], - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" + "start": 878, + "end": 928, + "replacementText": "", + "line": 25, + "column": 1, + "endLine": 25, + "endColumn": 51 }, { - "line": 50, - "column": 3, - "endLine": 50, - "endColumn": 9, - "problem": "InteropJsObjectUsage", - "autofix": [ - { - "replacementText": "arr.setPropertyByIndex(i, ESObject.wrap(0))", - "start": 1367, - "end": 1377 - } - ], - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, + "start": 1038, + "end": 1038, + "replacementText": "let GeneratedImportVar_6 = ESObject.load('./interop_import_js_rules_js');\nlet ff4 = GeneratedImportVar_6.getPropertyByName('ff4');\n", + "line": 25, + "column": 1, + "endLine": 25, + "endColumn": 51 + } + ], + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 1, + "endLine": 27, + "endColumn": 54, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 1, + "endLine": 27, + "endColumn": 54, + "problem": "InterOpImportJs", + "autofix": [ { - "line": 60, - "column": 1, - "endLine": 60, - "endColumn": 13, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" + "start": 930, + "end": 983, + "replacementText": "", + "line": 27, + "column": 1, + "endLine": 27, + "endColumn": 54 }, { - "line": 60, - "column": 1, - "endLine": 60, - "endColumn": 13, - "problem": "CallJSFunction", - "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", - "severity": "ERROR" - }, + "start": 1038, + "end": 1038, + "replacementText": "let GeneratedImportVar_7 = ESObject.load('./interop_import_js_rules_js');\nlet handle = GeneratedImportVar_7.getPropertyByName('handle');\n", + "line": 27, + "column": 1, + "endLine": 27, + "endColumn": 54 + } + ], + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 1, + "endLine": 29, + "endColumn": 54, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 1, + "endLine": 29, + "endColumn": 54, + "problem": "InterOpImportJs", + "autofix": [ { - "line": 60, - "column": 1, - "endLine": 60, - "endColumn": 13, - "problem": "InteropCallObjectMethods", - "suggest": "", - "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", - "severity": "ERROR" + "start": 985, + "end": 1038, + "replacementText": "", + "line": 29, + "column": 1, + "endLine": 29, + "endColumn": 54 }, { - "line": 61, - "column": 1, - "endLine": 61, - "endColumn": 15, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, + "start": 1038, + "end": 1038, + "replacementText": "let GeneratedImportVar_8 = ESObject.load('./interop_import_js_rules_js');\nlet expand = GeneratedImportVar_8.getPropertyByName('expand');\n", + "line": 29, + "column": 1, + "endLine": 29, + "endColumn": 54 + } + ], + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 5, + "endLine": 31, + "endColumn": 15, + "problem": "InteropObjectProperty", + "autofix": [ { - "line": 61, - "column": 1, - "endLine": 61, - "endColumn": 15, - "problem": "CallJSFunction", - "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", - "severity": "ERROR" - }, + "start": 1044, + "end": 1054, + "replacementText": "foo.getPropertyByName(\"isGood\")", + "line": 31, + "column": 5, + "endLine": 31, + "endColumn": 15 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 5, + "endLine": 31, + "endColumn": 15, + "problem": "InteropJsObjectConditionJudgment", + "autofix": [ { - "line": 61, - "column": 1, - "endLine": 61, - "endColumn": 15, - "problem": "InteropCallObjectMethods", - "suggest": "", - "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", - "severity": "ERROR" - } - ] -} \ No newline at end of file + "replacementText": "foo.getPropertyByName('isGood').toBoolean()", + "start": 1044, + "end": 1054, + "line": 31, + "column": 5, + "endLine": 31, + "endColumn": 15 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js2s-condition-judgment)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 5, + "endLine": 31, + "endColumn": 15, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 5, + "endLine": 33, + "endColumn": 11, + "problem": "InterOpImportJsDataCompare", + "suggest": "", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-interop-js2s-compare-js-data)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 5, + "endLine": 33, + "endColumn": 11, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 1064, + "end": 1070, + "replacementText": "ff1.getPropertyByName(\"f1\")", + "line": 33, + "column": 5, + "endLine": 33, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 5, + "endLine": 33, + "endColumn": 11, + "problem": "InteropJsObjectConditionJudgment", + "autofix": [ + { + "replacementText": "ff1.getPropertyByName('f1').toNumber()", + "start": 1064, + "end": 1070, + "line": 33, + "column": 5, + "endLine": 33, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js2s-condition-judgment)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 5, + "endLine": 33, + "endColumn": 11, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 1, + "endLine": 37, + "endColumn": 21, + "problem": "InteropJsObjectInheritance", + "suggest": "", + "rule": "Direct inheritance of interop JS classes is not supported (arkts-interop-js2s-inherit-js-class)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 1, + "endLine": 41, + "endColumn": 21, + "problem": "InteropJsObjectInheritance", + "suggest": "", + "rule": "Direct inheritance of interop JS classes is not supported (arkts-interop-js2s-inherit-js-class)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 3, + "endLine": 44, + "endColumn": 8, + "problem": "InteropJSFunctionInvoke", + "suggest": "", + "rule": "Trying to catch JS errors is not permitted (arkts-interop-js2s-js-exception)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 3, + "endLine": 44, + "endColumn": 8, + "problem": "InteropJsObjectCallStaticFunc", + "suggest": "", + "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-call-static-function)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 3, + "endLine": 44, + "endColumn": 8, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 3, + "endLine": 47, + "endColumn": 2, + "problem": "TsLikeCatchType", + "suggest": "", + "rule": "TS catch type are not supported (arkts-no-ts-like-catch-type)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 11, + "endLine": 49, + "endColumn": 18, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 1290, + "end": 1297, + "replacementText": "ff3.getPropertyByName(\"arr\")", + "line": 49, + "column": 11, + "endLine": 49, + "endColumn": 18 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 11, + "endLine": 49, + "endColumn": 18, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "ff3.getPropertyByName('arr')", + "start": 1290, + "end": 1297, + "line": 49, + "column": 11, + "endLine": 49, + "endColumn": 18 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 11, + "endLine": 49, + "endColumn": 18, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + }, + { + "line": 50, + "column": 11, + "endLine": 50, + "endColumn": 21, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "arr.getPropertyByName('length').toNumber()", + "start": 1308, + "end": 1328, + "line": 50, + "column": 11, + "endLine": 50, + "endColumn": 21 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 53, + "column": 3, + "endLine": 53, + "endColumn": 9, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 51, + "column": 10, + "endLine": 51, + "endColumn": 15, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1338, + "end": 1343, + "replacementText": "i: number = 0", + "line": 51, + "column": 10, + "endLine": 51, + "endColumn": 15 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 52, + "column": 11, + "endLine": 52, + "endColumn": 17, + "problem": "InteropJsObjectTraverseJsInstance", + "autofix": [ + { + "replacementText": "arr.getPropertyByIndex(i).toNumber()", + "start": 1371, + "end": 1377, + "line": 52, + "column": 11, + "endLine": 52, + "endColumn": 17 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js2s-traverse-js-instance)", + "severity": "ERROR" + }, + { + "line": 52, + "column": 11, + "endLine": 52, + "endColumn": 17, + "problem": "InterOpImportJsIndex", + "autofix": [ + { + "start": 1371, + "end": 1377, + "replacementText": "arr.getPropertyByIndex(i)", + "line": 52, + "column": 11, + "endLine": 52, + "endColumn": 17 + } + ], + "suggest": "", + "rule": "Interop objects can't be indexed directly (arkts-interop-js2s-access-js-index)", + "severity": "ERROR" + }, + { + "line": 53, + "column": 3, + "endLine": 53, + "endColumn": 9, + "problem": "InteropJsObjectTraverseJsInstance", + "autofix": [ + { + "replacementText": "arr.setPropertyByIndex(i, ESObject.wrap(0))", + "start": 1380, + "end": 1390, + "line": 53, + "column": 3, + "endLine": 53, + "endColumn": 9 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js2s-traverse-js-instance)", + "severity": "ERROR" + }, + { + "line": 53, + "column": 3, + "endLine": 53, + "endColumn": 13, + "problem": "InterOpImportJsIndex", + "autofix": [ + { + "start": 1380, + "end": 1390, + "replacementText": "arr.setPropertyByIndex(i, ESObject.wrap(0))", + "line": 53, + "column": 3, + "endLine": 53, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "Interop objects can't be indexed directly (arkts-interop-js2s-access-js-index)", + "severity": "ERROR" + }, + { + "line": 63, + "column": 1, + "endLine": 63, + "endColumn": 13, + "problem": "InteropJsObjectCallStaticFunc", + "suggest": "", + "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-call-static-function)", + "severity": "ERROR" + }, + { + "line": 63, + "column": 1, + "endLine": 63, + "endColumn": 13, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", + "severity": "ERROR" + }, + { + "line": 64, + "column": 1, + "endLine": 64, + "endColumn": 15, + "problem": "InteropJsObjectCallStaticFunc", + "suggest": "", + "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-call-static-function)", + "severity": "ERROR" + }, + { + "line": 64, + "column": 1, + "endLine": 64, + "endColumn": 15, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", + "severity": "ERROR" + }, + { + "line": 66, + "column": 9, + "endLine": 66, + "endColumn": 15, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1528, + "end": 1534, + "replacementText": "a: number = 1;", + "line": 66, + "column": 9, + "endLine": 66, + "endColumn": 15 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 66, + "column": 16, + "endLine": 66, + "endColumn": 21, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1535, + "end": 1540, + "replacementText": "b: number = 2;", + "line": 66, + "column": 16, + "endLine": 66, + "endColumn": 21 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 66, + "column": 22, + "endLine": 66, + "endColumn": 26, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1541, + "end": 1545, + "replacementText": "c: number = 3;", + "line": 66, + "column": 22, + "endLine": 66, + "endColumn": 26 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 67, + "column": 1, + "endLine": 67, + "endColumn": 16, + "problem": "InteropJsObjectExpandStaticInstance", + "suggest": "", + "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-expand-static-instance)", + "severity": "ERROR" + }, + { + "line": 67, + "column": 1, + "endLine": 67, + "endColumn": 16, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/interop/interop_import_js_rules.ets.json b/ets2panda/linter/test/interop/interop_import_js_rules.ets.json index dd03fcf544..a3db4edec8 100644 --- a/ets2panda/linter/test/interop/interop_import_js_rules.ets.json +++ b/ets2panda/linter/test/interop/interop_import_js_rules.ets.json @@ -13,5 +13,86 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "result": [] + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 51, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 56, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 49, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 49, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 1, + "endLine": 23, + "endColumn": 51, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 1, + "endLine": 25, + "endColumn": 51, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 1, + "endLine": 27, + "endColumn": 54, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 1, + "endLine": 29, + "endColumn": 54, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + } + ] } diff --git a/ets2panda/linter/test/interop/oh_modules/interop_import_js_rules.js b/ets2panda/linter/test/interop/interop_import_js_rules_js.js similarity index 92% rename from ets2panda/linter/test/interop/oh_modules/interop_import_js_rules.js rename to ets2panda/linter/test/interop/interop_import_js_rules_js.js index 13f6e3cd58..31951e24a4 100644 --- a/ets2panda/linter/test/interop/oh_modules/interop_import_js_rules.js +++ b/ets2panda/linter/test/interop/interop_import_js_rules_js.js @@ -30,3 +30,8 @@ export function handle(cb) { let p = {name: 'hello'} cb(p) } + +export function expand(obj) { + let x = obj; + let {a, b, c} = obj; +} diff --git a/ets2panda/linter/test/interop/interop_import_typeof_js.ets.args.json b/ets2panda/linter/test/interop/interop_import_typeof_js.ets.args.json index 815373beb6..df6e67a5c9 100755 --- a/ets2panda/linter/test/interop/interop_import_typeof_js.ets.args.json +++ b/ets2panda/linter/test/interop/interop_import_typeof_js.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_import_typeof_js.ets.arkts2.json b/ets2panda/linter/test/interop/interop_import_typeof_js.ets.arkts2.json index dbe38c107a..fa257d85ca 100755 --- a/ets2panda/linter/test/interop/interop_import_typeof_js.ets.arkts2.json +++ b/ets2panda/linter/test/interop/interop_import_typeof_js.ets.arkts2.json @@ -31,7 +31,7 @@ "endColumn": 69, "problem": "InterOpImportJs", "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -51,7 +51,7 @@ "endColumn": 54, "problem": "InterOpImportJs", "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -71,7 +71,7 @@ "endColumn": 55, "problem": "InterOpImportJs", "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -81,7 +81,7 @@ "endColumn": 15, "problem": "InterOpImportJsForTypeOf", "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", "severity": "ERROR" }, { @@ -89,9 +89,9 @@ "column": 8, "endLine": 21, "endColumn": 15, - "problem": "InteropJsObjectUsage", + "problem": "InteropJsObjectCallStaticFunc", "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-call-static-function)", "severity": "ERROR" }, { @@ -101,17 +101,7 @@ "endColumn": 15, "problem": "CallJSFunction", "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", - "severity": "ERROR" - }, - { - "line": 21, - "column": 8, - "endLine": 21, - "endColumn": 15, - "problem": "InteropCallObjectMethods", - "suggest": "", - "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", "severity": "ERROR" }, { @@ -119,9 +109,9 @@ "column": 11, "endLine": 22, "endColumn": 18, - "problem": "InteropJsObjectUsage", + "problem": "InteropJsObjectCallStaticFunc", "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-call-static-function)", "severity": "ERROR" }, { @@ -131,17 +121,7 @@ "endColumn": 18, "problem": "CallJSFunction", "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", - "severity": "ERROR" - }, - { - "line": 22, - "column": 11, - "endLine": 22, - "endColumn": 18, - "problem": "InteropCallObjectMethods", - "suggest": "", - "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", "severity": "ERROR" }, { @@ -151,7 +131,7 @@ "endColumn": 11, "problem": "InterOpImportJsForTypeOf", "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", "severity": "ERROR" }, { @@ -161,7 +141,7 @@ "endColumn": 19, "problem": "InterOpImportJsForTypeOf", "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", "severity": "ERROR" }, { @@ -179,9 +159,9 @@ "column": 8, "endLine": 25, "endColumn": 19, - "problem": "InteropJsObjectUsage", + "problem": "InteropJsObjectCallStaticFunc", "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-call-static-function)", "severity": "ERROR" }, { @@ -191,17 +171,7 @@ "endColumn": 19, "problem": "CallJSFunction", "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", - "severity": "ERROR" - }, - { - "line": 25, - "column": 8, - "endLine": 25, - "endColumn": 19, - "problem": "InteropCallObjectMethods", - "suggest": "", - "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", "severity": "ERROR" }, { @@ -211,7 +181,7 @@ "endColumn": 20, "problem": "InterOpImportJsForTypeOf", "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", "severity": "ERROR" }, { @@ -229,9 +199,9 @@ "column": 8, "endLine": 26, "endColumn": 20, - "problem": "InteropJsObjectUsage", + "problem": "InteropJsObjectCallStaticFunc", "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-call-static-function)", "severity": "ERROR" }, { @@ -241,17 +211,7 @@ "endColumn": 20, "problem": "CallJSFunction", "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", - "severity": "ERROR" - }, - { - "line": 26, - "column": 8, - "endLine": 26, - "endColumn": 20, - "problem": "InteropCallObjectMethods", - "suggest": "", - "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", "severity": "ERROR" }, { @@ -261,7 +221,7 @@ "endColumn": 12, "problem": "InterOpImportJsForTypeOf", "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", "severity": "ERROR" }, { @@ -271,7 +231,7 @@ "endColumn": 17, "problem": "InterOpImportJsForTypeOf", "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", "severity": "ERROR" }, { @@ -281,7 +241,7 @@ "endColumn": 17, "problem": "InteropObjectProperty", "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -301,7 +261,7 @@ "endColumn": 17, "problem": "BinaryOperations", "suggest": "", - "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { @@ -311,7 +271,7 @@ "endColumn": 12, "problem": "InterOpImportJsForTypeOf", "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", "severity": "ERROR" }, { @@ -321,7 +281,7 @@ "endColumn": 20, "problem": "InteropObjectProperty", "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -341,7 +301,7 @@ "endColumn": 20, "problem": "BinaryOperations", "suggest": "", - "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { @@ -351,7 +311,7 @@ "endColumn": 35, "problem": "InstantiatedJsOjbect", "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", "severity": "ERROR" }, { @@ -361,7 +321,7 @@ "endColumn": 20, "problem": "InterOpImportJsForTypeOf", "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", "severity": "ERROR" }, { @@ -371,7 +331,7 @@ "endColumn": 20, "problem": "InstantiatedJsOjbect", "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", "severity": "ERROR" }, { @@ -381,7 +341,7 @@ "endColumn": 33, "problem": "InstantiatedJsOjbect", "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", "severity": "ERROR" }, { @@ -391,17 +351,7 @@ "endColumn": 22, "problem": "InteropObjectProperty", "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", - "severity": "ERROR" - }, - { - "line": 37, - "column": 12, - "endLine": 37, - "endColumn": 28, - "problem": "CallJSFunction", - "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -411,17 +361,7 @@ "endColumn": 28, "problem": "InteropCallObjectMethods", "suggest": "", - "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", - "severity": "ERROR" - }, - { - "line": 40, - "column": 12, - "endLine": 40, - "endColumn": 28, - "problem": "CallJSFunction", - "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-js2s-call-js-method)", "severity": "ERROR" }, { @@ -431,7 +371,7 @@ "endColumn": 28, "problem": "InteropCallObjectMethods", "suggest": "", - "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-js2s-call-js-method)", "severity": "ERROR" }, { @@ -444,16 +384,6 @@ "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", "severity": "ERROR" }, - { - "line": 43, - "column": 12, - "endLine": 43, - "endColumn": 30, - "problem": "CallJSFunction", - "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", - "severity": "ERROR" - }, { "line": 43, "column": 12, @@ -461,7 +391,7 @@ "endColumn": 30, "problem": "InteropCallObjectMethods", "suggest": "", - "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-js2s-call-js-method)", "severity": "ERROR" }, { @@ -471,7 +401,7 @@ "endColumn": 24, "problem": "InterOpImportJsForTypeOf", "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", "severity": "ERROR" }, { @@ -481,7 +411,7 @@ "endColumn": 24, "problem": "InstantiatedJsOjbect", "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", "severity": "ERROR" }, { @@ -494,16 +424,6 @@ "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", "severity": "ERROR" }, - { - "line": 48, - "column": 21, - "endLine": 48, - "endColumn": 39, - "problem": "CallJSFunction", - "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", - "severity": "ERROR" - }, { "line": 48, "column": 21, @@ -511,7 +431,7 @@ "endColumn": 39, "problem": "InteropCallObjectMethods", "suggest": "", - "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-js2s-call-js-method)", "severity": "ERROR" }, { @@ -531,7 +451,7 @@ "endColumn": 21, "problem": "InterOpImportJsForTypeOf", "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", "severity": "ERROR" }, { @@ -541,7 +461,7 @@ "endColumn": 21, "problem": "InteropObjectProperty", "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -561,7 +481,7 @@ "endColumn": 21, "problem": "BinaryOperations", "suggest": "", - "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { @@ -571,7 +491,7 @@ "endColumn": 47, "problem": "InterOpImportJsForTypeOf", "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", "severity": "ERROR" }, { @@ -581,7 +501,7 @@ "endColumn": 47, "problem": "InstantiatedJsOjbect", "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", "severity": "ERROR" }, { @@ -591,7 +511,7 @@ "endColumn": 13, "problem": "InterOpImportJsForTypeOf", "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", "severity": "ERROR" }, { @@ -601,7 +521,7 @@ "endColumn": 25, "problem": "InterOpImportJsForTypeOf", "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", "severity": "ERROR" }, { @@ -611,7 +531,7 @@ "endColumn": 25, "problem": "InteropObjectProperty", "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -631,7 +551,7 @@ "endColumn": 20, "problem": "InstantiatedJsOjbect", "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", "severity": "ERROR" }, { @@ -641,7 +561,7 @@ "endColumn": 30, "problem": "InterOpImportJsForTypeOf", "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", "severity": "ERROR" }, { @@ -649,19 +569,9 @@ "column": 8, "endLine": 72, "endColumn": 30, - "problem": "InteropJsObjectUsage", + "problem": "InteropJsObjectCallStaticFunc", "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 72, - "column": 8, - "endLine": 72, - "endColumn": 30, - "problem": "CallJSFunction", - "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-call-static-function)", "severity": "ERROR" }, { @@ -671,7 +581,7 @@ "endColumn": 30, "problem": "InteropCallObjectMethods", "suggest": "", - "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-js2s-call-js-method)", "severity": "ERROR" }, { @@ -681,7 +591,7 @@ "endColumn": 20, "problem": "InstantiatedJsOjbect", "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", "severity": "ERROR" }, { @@ -691,7 +601,7 @@ "endColumn": 31, "problem": "InterOpImportJsForTypeOf", "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", "severity": "ERROR" }, { @@ -709,19 +619,9 @@ "column": 8, "endLine": 73, "endColumn": 31, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 73, - "column": 8, - "endLine": 73, - "endColumn": 31, - "problem": "CallJSFunction", + "problem": "InteropJsObjectCallStaticFunc", "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-call-static-function)", "severity": "ERROR" }, { @@ -731,7 +631,7 @@ "endColumn": 31, "problem": "InteropCallObjectMethods", "suggest": "", - "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-js2s-call-js-method)", "severity": "ERROR" }, { @@ -741,7 +641,7 @@ "endColumn": 20, "problem": "InstantiatedJsOjbect", "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/interop/interop_import_typeof_js.ets.autofix.json b/ets2panda/linter/test/interop/interop_import_typeof_js.ets.autofix.json index b362958715..3f09bf75b9 100755 --- a/ets2panda/linter/test/interop/interop_import_typeof_js.ets.autofix.json +++ b/ets2panda/linter/test/interop/interop_import_typeof_js.ets.autofix.json @@ -39,11 +39,11 @@ { "start": 796, "end": 796, - "replacementText": "let GeneratedImportVar_1 = ESObject.load('./interop_import_js_js');\nlet myAaa = GeneratedImportVar_1.getPropertyByName('aaa');\nlet ClassA = GeneratedImportVar_1.getPropertyByName('ClassA');\nlet Dog = GeneratedImportVar_1.getPropertyByName('Dog');\nlet Person = GeneratedImportVar_1.getPropertyByName('Person');\nlet Wiki = GeneratedImportVar_1.getPropertyByName('Wiki');" + "replacementText": "let GeneratedImportVar_1 = ESObject.load('./interop_import_js_js');\nlet myAaa = GeneratedImportVar_1.getPropertyByName('aaa');\nlet ClassA = GeneratedImportVar_1.getPropertyByName('ClassA');\nlet Dog = GeneratedImportVar_1.getPropertyByName('Dog');\nlet Person = GeneratedImportVar_1.getPropertyByName('Person');\nlet Wiki = GeneratedImportVar_1.getPropertyByName('Wiki');\n" } ], "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -71,11 +71,11 @@ { "start": 796, "end": 796, - "replacementText": "let GeneratedImportVar_2 = ESObject.load('./interop_import_js_js');\nlet Doge = GeneratedImportVar_2.getPropertyByName('Dog');" + "replacementText": "let GeneratedImportVar_2 = ESObject.load('./interop_import_js_js');\nlet Doge = GeneratedImportVar_2.getPropertyByName('Dog');\n" } ], "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -103,11 +103,11 @@ { "start": 796, "end": 796, - "replacementText": "let GeneratedImportVar_3 = ESObject.load('./interop_import_js_js');\nlet wiki = GeneratedImportVar_3.getPropertyByName('Wiki');" + "replacementText": "let GeneratedImportVar_3 = ESObject.load('./interop_import_js_js');\nlet wiki = GeneratedImportVar_3.getPropertyByName('Wiki');\n" } ], "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -124,7 +124,7 @@ } ], "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", "severity": "ERROR" }, { @@ -132,9 +132,9 @@ "column": 8, "endLine": 21, "endColumn": 15, - "problem": "InteropJsObjectUsage", + "problem": "InteropJsObjectCallStaticFunc", "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-call-static-function)", "severity": "ERROR" }, { @@ -144,17 +144,7 @@ "endColumn": 15, "problem": "CallJSFunction", "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", - "severity": "ERROR" - }, - { - "line": 21, - "column": 8, - "endLine": 21, - "endColumn": 15, - "problem": "InteropCallObjectMethods", - "suggest": "", - "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", "severity": "ERROR" }, { @@ -162,9 +152,9 @@ "column": 11, "endLine": 22, "endColumn": 18, - "problem": "InteropJsObjectUsage", + "problem": "InteropJsObjectCallStaticFunc", "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-call-static-function)", "severity": "ERROR" }, { @@ -174,17 +164,7 @@ "endColumn": 18, "problem": "CallJSFunction", "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", - "severity": "ERROR" - }, - { - "line": 22, - "column": 11, - "endLine": 22, - "endColumn": 18, - "problem": "InteropCallObjectMethods", - "suggest": "", - "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", "severity": "ERROR" }, { @@ -201,7 +181,7 @@ } ], "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", "severity": "ERROR" }, { @@ -218,7 +198,7 @@ } ], "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", "severity": "ERROR" }, { @@ -236,9 +216,9 @@ "column": 8, "endLine": 25, "endColumn": 19, - "problem": "InteropJsObjectUsage", + "problem": "InteropJsObjectCallStaticFunc", "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-call-static-function)", "severity": "ERROR" }, { @@ -248,17 +228,7 @@ "endColumn": 19, "problem": "CallJSFunction", "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", - "severity": "ERROR" - }, - { - "line": 25, - "column": 8, - "endLine": 25, - "endColumn": 19, - "problem": "InteropCallObjectMethods", - "suggest": "", - "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", "severity": "ERROR" }, { @@ -275,7 +245,7 @@ } ], "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", "severity": "ERROR" }, { @@ -293,9 +263,9 @@ "column": 8, "endLine": 26, "endColumn": 20, - "problem": "InteropJsObjectUsage", + "problem": "InteropJsObjectCallStaticFunc", "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-call-static-function)", "severity": "ERROR" }, { @@ -305,17 +275,7 @@ "endColumn": 20, "problem": "CallJSFunction", "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", - "severity": "ERROR" - }, - { - "line": 26, - "column": 8, - "endLine": 26, - "endColumn": 20, - "problem": "InteropCallObjectMethods", - "suggest": "", - "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", "severity": "ERROR" }, { @@ -332,7 +292,7 @@ } ], "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", "severity": "ERROR" }, { @@ -349,7 +309,7 @@ } ], "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", "severity": "ERROR" }, { @@ -366,7 +326,7 @@ } ], "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -393,7 +353,7 @@ "endColumn": 17, "problem": "BinaryOperations", "suggest": "", - "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { @@ -410,7 +370,7 @@ } ], "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", "severity": "ERROR" }, { @@ -427,7 +387,7 @@ } ], "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -454,7 +414,7 @@ "endColumn": 20, "problem": "BinaryOperations", "suggest": "", - "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { @@ -471,7 +431,7 @@ } ], "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", "severity": "ERROR" }, { @@ -488,7 +448,7 @@ } ], "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", "severity": "ERROR" }, { @@ -505,7 +465,7 @@ } ], "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", "severity": "ERROR" }, { @@ -522,7 +482,7 @@ } ], "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", "severity": "ERROR" }, { @@ -539,17 +499,7 @@ } ], "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", - "severity": "ERROR" - }, - { - "line": 37, - "column": 12, - "endLine": 37, - "endColumn": 28, - "problem": "CallJSFunction", - "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -559,17 +509,7 @@ "endColumn": 28, "problem": "InteropCallObjectMethods", "suggest": "", - "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", - "severity": "ERROR" - }, - { - "line": 40, - "column": 12, - "endLine": 40, - "endColumn": 28, - "problem": "CallJSFunction", - "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-js2s-call-js-method)", "severity": "ERROR" }, { @@ -579,7 +519,7 @@ "endColumn": 28, "problem": "InteropCallObjectMethods", "suggest": "", - "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-js2s-call-js-method)", "severity": "ERROR" }, { @@ -592,16 +532,6 @@ "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", "severity": "ERROR" }, - { - "line": 43, - "column": 12, - "endLine": 43, - "endColumn": 30, - "problem": "CallJSFunction", - "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", - "severity": "ERROR" - }, { "line": 43, "column": 12, @@ -609,7 +539,7 @@ "endColumn": 30, "problem": "InteropCallObjectMethods", "suggest": "", - "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-js2s-call-js-method)", "severity": "ERROR" }, { @@ -626,7 +556,7 @@ } ], "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", "severity": "ERROR" }, { @@ -643,7 +573,7 @@ } ], "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", "severity": "ERROR" }, { @@ -656,16 +586,6 @@ "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", "severity": "ERROR" }, - { - "line": 48, - "column": 21, - "endLine": 48, - "endColumn": 39, - "problem": "CallJSFunction", - "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", - "severity": "ERROR" - }, { "line": 48, "column": 21, @@ -673,7 +593,7 @@ "endColumn": 39, "problem": "InteropCallObjectMethods", "suggest": "", - "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-js2s-call-js-method)", "severity": "ERROR" }, { @@ -700,7 +620,7 @@ } ], "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", "severity": "ERROR" }, { @@ -717,7 +637,7 @@ } ], "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -744,7 +664,7 @@ "endColumn": 21, "problem": "BinaryOperations", "suggest": "", - "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { @@ -761,7 +681,7 @@ } ], "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", "severity": "ERROR" }, { @@ -778,7 +698,7 @@ } ], "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", "severity": "ERROR" }, { @@ -795,7 +715,7 @@ } ], "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", "severity": "ERROR" }, { @@ -812,7 +732,7 @@ } ], "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", "severity": "ERROR" }, { @@ -829,7 +749,7 @@ } ], "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -863,7 +783,7 @@ } ], "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", "severity": "ERROR" }, { @@ -880,7 +800,7 @@ } ], "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", "severity": "ERROR" }, { @@ -888,19 +808,9 @@ "column": 8, "endLine": 72, "endColumn": 30, - "problem": "InteropJsObjectUsage", + "problem": "InteropJsObjectCallStaticFunc", "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 72, - "column": 8, - "endLine": 72, - "endColumn": 30, - "problem": "CallJSFunction", - "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-call-static-function)", "severity": "ERROR" }, { @@ -910,7 +820,7 @@ "endColumn": 30, "problem": "InteropCallObjectMethods", "suggest": "", - "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-js2s-call-js-method)", "severity": "ERROR" }, { @@ -927,7 +837,7 @@ } ], "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", "severity": "ERROR" }, { @@ -944,7 +854,7 @@ } ], "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-import-typeof-js)", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", "severity": "ERROR" }, { @@ -962,19 +872,9 @@ "column": 8, "endLine": 73, "endColumn": 31, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 73, - "column": 8, - "endLine": 73, - "endColumn": 31, - "problem": "CallJSFunction", + "problem": "InteropJsObjectCallStaticFunc", "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", + "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-call-static-function)", "severity": "ERROR" }, { @@ -984,7 +884,7 @@ "endColumn": 31, "problem": "InteropCallObjectMethods", "suggest": "", - "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-js2s-call-js-method)", "severity": "ERROR" }, { @@ -1001,7 +901,7 @@ } ], "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-no-js-obj-instantiated)", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/interop/interop_import_typeof_js.ets.migrate.ets b/ets2panda/linter/test/interop/interop_import_typeof_js.ets.migrate.ets new file mode 100644 index 0000000000..5914b7dfda --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_typeof_js.ets.migrate.ets @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use static' + + +let GeneratedImportVar_3 = ESObject.load('./interop_import_js_js'); +let wiki = GeneratedImportVar_3.getPropertyByName('Wiki'); +let GeneratedImportVar_2 = ESObject.load('./interop_import_js_js'); +let Doge = GeneratedImportVar_2.getPropertyByName('Dog'); +let GeneratedImportVar_1 = ESObject.load('./interop_import_js_js'); +let myAaa = GeneratedImportVar_1.getPropertyByName('aaa'); +let ClassA = GeneratedImportVar_1.getPropertyByName('ClassA'); +let Dog = GeneratedImportVar_1.getPropertyByName('Dog'); +let Person = GeneratedImportVar_1.getPropertyByName('Person'); +let Wiki = GeneratedImportVar_1.getPropertyByName('Wiki'); + + +myAaa.invoke().typeOf(); //error +let fun = myAaa(); +typeof fun; +Dog.typeOf(); //error +Dog.invoke(ESObject.wrap('doge')).typeOf(); //error +Doge.invoke(ESObject.wrap('doge')).typeOf(); //error +Wiki.typeOf() //error +Wiki.getPropertyByName('name').typeOf() //error +wiki.typeOf() //error +let val = wiki.getPropertyByName("name") +typeof val; +const aClass:ClassA = ClassA.instantiate() +ClassA.instantiate().typeOf() //error +typeof aClass; +let person:Person = Person.instantiate(); +let name =person.getPropertyByName("name") +let name2 =person.getName() +function getPersonInfo(){ + typeof person; + typeof person.getName(); + typeof name2; + typeof name; + typeof person.setAge(111); + typeof person; + Person.instantiate().typeOf(); //error +} + +const age = typeof person.setAge(111); +let person2 = typeof person +class Object { + code: string = "www" + location: string = typeof ('123') + getLocation(){ + console.log(`nameType=${ typeof code} `); + return typeof this.location; + } + setLocation(location: string){ + this.location = location; + typeof location; + } + tips(){ + wiki.getPropertyByName('name').typeOf(); //error + typeof age; + typeof person2; + typeof fun; + console.log(`ClassA=${ ClassA.instantiate().typeOf()} `); //error + } +} + +myAaa.typeOf(); //error +Person.instantiate().getPropertyByName('name').typeOf() //error +Person.instantiate().getPropertyByName('getName').invoke().typeOf() //error +Person.instantiate().getPropertyByName('setAge').invoke(ESObject.wrap(22)).typeOf() //error diff --git a/ets2panda/linter/test/interop/interop_import_typeof_js.ets.migrate.json b/ets2panda/linter/test/interop/interop_import_typeof_js.ets.migrate.json new file mode 100644 index 0000000000..a2ce72e941 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_typeof_js.ets.migrate.json @@ -0,0 +1,168 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 19, + "column": 5, + "endLine": 19, + "endColumn": 67, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 5, + "endLine": 20, + "endColumn": 58, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 5, + "endLine": 21, + "endColumn": 67, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 5, + "endLine": 22, + "endColumn": 57, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 5, + "endLine": 23, + "endColumn": 67, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 5, + "endLine": 24, + "endColumn": 58, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 5, + "endLine": 25, + "endColumn": 62, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 5, + "endLine": 26, + "endColumn": 56, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 5, + "endLine": 27, + "endColumn": 62, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 5, + "endLine": 28, + "endColumn": 58, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 5, + "endLine": 32, + "endColumn": 18, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 40, + "column": 5, + "endLine": 40, + "endColumn": 41, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 46, + "column": 5, + "endLine": 46, + "endColumn": 43, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 47, + "column": 5, + "endLine": 47, + "endColumn": 28, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 60, + "column": 7, + "endLine": 60, + "endColumn": 13, + "problem": "InvalidIdentifier", + "suggest": "", + "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.args.json b/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.args.json index a2c0f14eb2..ef3938e967 100755 --- a/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.args.json +++ b/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.arkts2.json b/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.arkts2.json index dbcf35243f..62322a01ef 100755 --- a/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.arkts2.json +++ b/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.arkts2.json @@ -13,7 +13,7 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "result": [ + "result": [ { "line": 17, "column": 1, @@ -31,7 +31,7 @@ "endColumn": 59, "problem": "InterOpImportJs", "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -41,7 +41,7 @@ "endColumn": 9, "problem": "InteropObjectProperty", "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -61,7 +61,7 @@ "endColumn": 9, "problem": "BinaryOperations", "suggest": "", - "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { @@ -71,7 +71,7 @@ "endColumn": 17, "problem": "InteropObjectProperty", "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -91,7 +91,7 @@ "endColumn": 9, "problem": "BinaryOperations", "suggest": "", - "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { @@ -101,7 +101,7 @@ "endColumn": 16, "problem": "InteropObjectProperty", "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -121,7 +121,7 @@ "endColumn": 11, "problem": "BinaryOperations", "suggest": "", - "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { @@ -131,7 +131,7 @@ "endColumn": 21, "problem": "InteropObjectProperty", "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -151,7 +151,7 @@ "endColumn": 12, "problem": "BinaryOperations", "suggest": "", - "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.autofix.json b/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.autofix.json index 3b827973a4..f849dbbe04 100755 --- a/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.autofix.json +++ b/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.autofix.json @@ -39,11 +39,11 @@ { "start": 676, "end": 676, - "replacementText": "let GeneratedImportVar_1 = ESObject.load('./interop_not_have_property_js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');\nlet person = GeneratedImportVar_1.getPropertyByName('person');" + "replacementText": "let GeneratedImportVar_1 = ESObject.load('./interop_not_have_property_js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');\nlet person = GeneratedImportVar_1.getPropertyByName('person');\n" } ], "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -60,7 +60,7 @@ } ], "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -87,7 +87,7 @@ "endColumn": 9, "problem": "BinaryOperations", "suggest": "", - "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { @@ -104,7 +104,7 @@ } ], "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -131,7 +131,7 @@ "endColumn": 9, "problem": "BinaryOperations", "suggest": "", - "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { @@ -148,7 +148,7 @@ } ], "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -175,7 +175,7 @@ "endColumn": 11, "problem": "BinaryOperations", "suggest": "", - "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { @@ -192,7 +192,7 @@ } ], "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -219,7 +219,7 @@ "endColumn": 12, "problem": "BinaryOperations", "suggest": "", - "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.migrate.ets b/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.migrate.ets new file mode 100644 index 0000000000..a96b2c80b7 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.migrate.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +'use static' + +let GeneratedImportVar_1 = ESObject.load('./interop_not_have_property_js'); +let foo = GeneratedImportVar_1.getPropertyByName('foo'); +let person = GeneratedImportVar_1.getPropertyByName('person'); + + +foo.getPropertyByName("name") +foo.setPropertyByName("name", ESObject.wrap("456")) +person.setPropertyByName("age", ESObject.wrap(23)) +person.setPropertyByName("male", ESObject.wrap([2, 3])) \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.migrate.json b/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.migrate.json new file mode 100644 index 0000000000..bc6054f745 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.migrate.json @@ -0,0 +1,48 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 5, + "endLine": 17, + "endColumn": 75, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 5, + "endLine": 18, + "endColumn": 56, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 5, + "endLine": 19, + "endColumn": 62, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets b/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets index 319ea1ded3..1049aac0f0 100755 --- a/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets +++ b/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets @@ -19,4 +19,8 @@ import {foo} from "./interop_property_num_js" +foo.num; -foo.num; !foo.num; -~foo.num; \ No newline at end of file +~foo.num; ++(foo.num); +-(foo.num); +!(foo.num); +~(foo.num); \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.args.json b/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.args.json index a2c0f14eb2..ef3938e967 100755 --- a/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.args.json +++ b/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.arkts2.json b/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.arkts2.json index 91c86ce667..bf5ffbc331 100755 --- a/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.arkts2.json +++ b/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.arkts2.json @@ -31,7 +31,7 @@ "endColumn": 46, "problem": "InterOpImportJs", "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -41,7 +41,7 @@ "endColumn": 9, "problem": "InteropNoHaveNum", "suggest": "", - "rule": "Interop object does not have property num (arkts-interop-does-not-have-num)", + "rule": "Interop object does not have property num (arkts-interop-js2s-unary-op)", "severity": "ERROR" }, { @@ -51,7 +51,7 @@ "endColumn": 9, "problem": "InteropObjectProperty", "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -71,7 +71,7 @@ "endColumn": 9, "problem": "BinaryOperations", "suggest": "", - "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { @@ -81,7 +81,7 @@ "endColumn": 9, "problem": "InteropNoHaveNum", "suggest": "", - "rule": "Interop object does not have property num (arkts-interop-does-not-have-num)", + "rule": "Interop object does not have property num (arkts-interop-js2s-unary-op)", "severity": "ERROR" }, { @@ -91,7 +91,7 @@ "endColumn": 9, "problem": "InteropObjectProperty", "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -111,7 +111,7 @@ "endColumn": 9, "problem": "BinaryOperations", "suggest": "", - "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { @@ -121,7 +121,7 @@ "endColumn": 9, "problem": "InteropNoHaveNum", "suggest": "", - "rule": "Interop object does not have property num (arkts-interop-does-not-have-num)", + "rule": "Interop object does not have property num (arkts-interop-js2s-unary-op)", "severity": "ERROR" }, { @@ -131,7 +131,7 @@ "endColumn": 9, "problem": "InteropObjectProperty", "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -151,7 +151,7 @@ "endColumn": 9, "problem": "BinaryOperations", "suggest": "", - "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { @@ -161,7 +161,7 @@ "endColumn": 9, "problem": "InteropNoHaveNum", "suggest": "", - "rule": "Interop object does not have property num (arkts-interop-does-not-have-num)", + "rule": "Interop object does not have property num (arkts-interop-js2s-unary-op)", "severity": "ERROR" }, { @@ -171,7 +171,7 @@ "endColumn": 9, "problem": "InteropObjectProperty", "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -191,7 +191,167 @@ "endColumn": 9, "problem": "BinaryOperations", "suggest": "", - "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 1, + "endLine": 23, + "endColumn": 11, + "problem": "InteropNoHaveNum", + "suggest": "", + "rule": "Interop object does not have property num (arkts-interop-js2s-unary-op)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 3, + "endLine": 23, + "endColumn": 10, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 3, + "endLine": 23, + "endColumn": 10, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 3, + "endLine": 23, + "endColumn": 10, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 1, + "endLine": 24, + "endColumn": 11, + "problem": "InteropNoHaveNum", + "suggest": "", + "rule": "Interop object does not have property num (arkts-interop-js2s-unary-op)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 3, + "endLine": 24, + "endColumn": 10, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 3, + "endLine": 24, + "endColumn": 10, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 3, + "endLine": 24, + "endColumn": 10, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 1, + "endLine": 25, + "endColumn": 11, + "problem": "InteropNoHaveNum", + "suggest": "", + "rule": "Interop object does not have property num (arkts-interop-js2s-unary-op)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 3, + "endLine": 25, + "endColumn": 10, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 3, + "endLine": 25, + "endColumn": 10, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 3, + "endLine": 25, + "endColumn": 10, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 1, + "endLine": 26, + "endColumn": 11, + "problem": "InteropNoHaveNum", + "suggest": "", + "rule": "Interop object does not have property num (arkts-interop-js2s-unary-op)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 3, + "endLine": 26, + "endColumn": 10, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 3, + "endLine": 26, + "endColumn": 10, + "problem": "InteropJsObjectUsage", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 3, + "endLine": 26, + "endColumn": 10, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.autofix.json b/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.autofix.json index b52102f1f9..a5900c6c1f 100755 --- a/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.autofix.json +++ b/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.autofix.json @@ -39,11 +39,11 @@ { "start": 663, "end": 663, - "replacementText": "let GeneratedImportVar_1 = ESObject.load('./interop_property_num_js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');" + "replacementText": "let GeneratedImportVar_1 = ESObject.load('./interop_property_num_js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');\n" } ], "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -60,7 +60,7 @@ } ], "suggest": "", - "rule": "Interop object does not have property num (arkts-interop-does-not-have-num)", + "rule": "Interop object does not have property num (arkts-interop-js2s-unary-op)", "severity": "ERROR" }, { @@ -77,7 +77,7 @@ } ], "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -104,7 +104,7 @@ "endColumn": 9, "problem": "BinaryOperations", "suggest": "", - "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { @@ -121,7 +121,7 @@ } ], "suggest": "", - "rule": "Interop object does not have property num (arkts-interop-does-not-have-num)", + "rule": "Interop object does not have property num (arkts-interop-js2s-unary-op)", "severity": "ERROR" }, { @@ -138,7 +138,7 @@ } ], "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -165,7 +165,7 @@ "endColumn": 9, "problem": "BinaryOperations", "suggest": "", - "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { @@ -182,7 +182,7 @@ } ], "suggest": "", - "rule": "Interop object does not have property num (arkts-interop-does-not-have-num)", + "rule": "Interop object does not have property num (arkts-interop-js2s-unary-op)", "severity": "ERROR" }, { @@ -199,7 +199,7 @@ } ], "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -226,7 +226,7 @@ "endColumn": 9, "problem": "BinaryOperations", "suggest": "", - "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { @@ -243,7 +243,7 @@ } ], "suggest": "", - "rule": "Interop object does not have property num (arkts-interop-does-not-have-num)", + "rule": "Interop object does not have property num (arkts-interop-js2s-unary-op)", "severity": "ERROR" }, { @@ -260,7 +260,7 @@ } ], "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-no-js-obj-property)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -287,7 +287,251 @@ "endColumn": 9, "problem": "BinaryOperations", "suggest": "", - "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 1, + "endLine": 23, + "endColumn": 11, + "problem": "InteropNoHaveNum", + "autofix": [ + { + "start": 706, + "end": 715, + "replacementText": "(foo.getPropertyByName(\"num\").toNumber())" + } + ], + "suggest": "", + "rule": "Interop object does not have property num (arkts-interop-js2s-unary-op)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 3, + "endLine": 23, + "endColumn": 10, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 707, + "end": 714, + "replacementText": "foo.getPropertyByName(\"num\")" + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 3, + "endLine": 23, + "endColumn": 10, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "foo.getPropertyByName('num').toNumber()", + "start": 707, + "end": 714 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 3, + "endLine": 23, + "endColumn": 10, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 1, + "endLine": 24, + "endColumn": 11, + "problem": "InteropNoHaveNum", + "autofix": [ + { + "start": 718, + "end": 727, + "replacementText": "(foo.getPropertyByName(\"num\").toNumber())" + } + ], + "suggest": "", + "rule": "Interop object does not have property num (arkts-interop-js2s-unary-op)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 3, + "endLine": 24, + "endColumn": 10, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 719, + "end": 726, + "replacementText": "foo.getPropertyByName(\"num\")" + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 3, + "endLine": 24, + "endColumn": 10, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "foo.getPropertyByName('num').toNumber()", + "start": 719, + "end": 726 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 3, + "endLine": 24, + "endColumn": 10, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 1, + "endLine": 25, + "endColumn": 11, + "problem": "InteropNoHaveNum", + "autofix": [ + { + "start": 730, + "end": 739, + "replacementText": "(foo.getPropertyByName(\"num\").toNumber())" + } + ], + "suggest": "", + "rule": "Interop object does not have property num (arkts-interop-js2s-unary-op)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 3, + "endLine": 25, + "endColumn": 10, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 731, + "end": 738, + "replacementText": "foo.getPropertyByName(\"num\")" + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 3, + "endLine": 25, + "endColumn": 10, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "foo.getPropertyByName('num').toNumber()", + "start": 731, + "end": 738 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 3, + "endLine": 25, + "endColumn": 10, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 1, + "endLine": 26, + "endColumn": 11, + "problem": "InteropNoHaveNum", + "autofix": [ + { + "start": 742, + "end": 751, + "replacementText": "(foo.getPropertyByName(\"num\").toNumber())" + } + ], + "suggest": "", + "rule": "Interop object does not have property num (arkts-interop-js2s-unary-op)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 3, + "endLine": 26, + "endColumn": 10, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 743, + "end": 750, + "replacementText": "foo.getPropertyByName(\"num\")" + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 3, + "endLine": 26, + "endColumn": 10, + "problem": "InteropJsObjectUsage", + "autofix": [ + { + "replacementText": "foo.getPropertyByName('num').toNumber()", + "start": 743, + "end": 750 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 3, + "endLine": 26, + "endColumn": 10, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.migrate.ets b/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.migrate.ets new file mode 100644 index 0000000000..ade780f491 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.migrate.ets @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +'use static' + +let GeneratedImportVar_1 = ESObject.load('./interop_property_num_js'); +let foo = GeneratedImportVar_1.getPropertyByName('foo'); + + ++foo.getPropertyByName("num").toNumber(); +-foo.getPropertyByName("num").toNumber(); +!foo.getPropertyByName("num").toNumber(); +~foo.getPropertyByName("num").toNumber(); ++(foo.getPropertyByName("num").toNumber()); +-(foo.getPropertyByName("num").toNumber()); +!(foo.getPropertyByName("num").toNumber()); +~(foo.getPropertyByName("num").toNumber()); \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.migrate.json b/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.migrate.json new file mode 100644 index 0000000000..c3adb86224 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.migrate.json @@ -0,0 +1,98 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 5, + "endLine": 17, + "endColumn": 70, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 5, + "endLine": 18, + "endColumn": 56, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 41, + "problem": "UnaryArithmNotNumber", + "suggest": "", + "rule": "Unary operators \"+\", \"-\" and \"~\" work only on numbers (arkts-no-polymorphic-unops)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 1, + "endLine": 22, + "endColumn": 41, + "problem": "UnaryArithmNotNumber", + "suggest": "", + "rule": "Unary operators \"+\", \"-\" and \"~\" work only on numbers (arkts-no-polymorphic-unops)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 1, + "endLine": 24, + "endColumn": 41, + "problem": "UnaryArithmNotNumber", + "suggest": "", + "rule": "Unary operators \"+\", \"-\" and \"~\" work only on numbers (arkts-no-polymorphic-unops)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 1, + "endLine": 25, + "endColumn": 43, + "problem": "UnaryArithmNotNumber", + "suggest": "", + "rule": "Unary operators \"+\", \"-\" and \"~\" work only on numbers (arkts-no-polymorphic-unops)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 1, + "endLine": 26, + "endColumn": 43, + "problem": "UnaryArithmNotNumber", + "suggest": "", + "rule": "Unary operators \"+\", \"-\" and \"~\" work only on numbers (arkts-no-polymorphic-unops)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 1, + "endLine": 28, + "endColumn": 43, + "problem": "UnaryArithmNotNumber", + "suggest": "", + "rule": "Unary operators \"+\", \"-\" and \"~\" work only on numbers (arkts-no-polymorphic-unops)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/no_js_await.ets b/ets2panda/linter/test/interop/no_await_js_promise.ets similarity index 86% rename from ets2panda/linter/test/interop/no_js_await.ets rename to ets2panda/linter/test/interop/no_await_js_promise.ets index 1df1f4f9e9..9247c363b4 100755 --- a/ets2panda/linter/test/interop/no_js_await.ets +++ b/ets2panda/linter/test/interop/no_await_js_promise.ets @@ -1,71 +1,65 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -'use static' - -import { p, foo, pFuncCall, arrowFunc, pArrowCall } from "./no_import_awai.js"; - -// 1. 基础 Promise -async function awaitPromise() { - return await p; -} - -// 2. 异步函数调用 -async function awaitFunctionCall() { - return await foo(); -} - -async function awaitFuncResult() { - return await pFuncCall; -} - -// 3. 箭头函数 -async function awaitArrowCall() { - return await arrowFunc(); -} - -async function awaitArrowResult() { - return await pArrowCall; -} - -// 4. 类中使用 -class ExampleClass { - async classMethod() { - return await p; - } - - handler = async () => { - return await pFuncCall; - }; -} - -// 5. 对象方法 -const exampleObj = { - async objMethod() { - return await pArrowCall; - }, - - arrowHandler: async () => { - return await foo(); - } -}; - -// 6. 立即执行函数 -(async function() { - console.log("IIFE result:", await p); -})(); - -(async () => { - console.log("IIFE Arrow result:", await arrowFunc()); +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +'use static' + +import { p, foo, pFuncCall, arrowFunc, pArrowCall } from "./no_await_js_promise_export"; + +async function awaitPromise() { + return await p; +} + +async function awaitFunctionCall() { + return await foo(); +} + +async function awaitFuncResult() { + return await pFuncCall; +} + +async function awaitArrowCall() { + return await arrowFunc(); +} + +async function awaitArrowResult() { + return await pArrowCall; +} + +class ExampleClass { + async classMethod() { + return await p; + } + + handler = async () => { + return await pFuncCall; + }; +} + +const exampleObj = { + async objMethod() { + return await pArrowCall; + }, + + arrowHandler: async () => { + return await foo(); + } +}; + +(async function() { + console.log("IIFE result:", await p); +})(); + +(async () => { + console.log("IIFE Arrow result:", await arrowFunc()); })(); \ No newline at end of file diff --git a/ets2panda/linter/test/interop/no_await_js_promise.ets.args.json b/ets2panda/linter/test/interop/no_await_js_promise.ets.args.json new file mode 100755 index 0000000000..66fb88f859 --- /dev/null +++ b/ets2panda/linter/test/interop/no_await_js_promise.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} diff --git a/ets2panda/linter/test/interop/no_await_js_promise.ets.arkts2.json b/ets2panda/linter/test/interop/no_await_js_promise.ets.arkts2.json new file mode 100755 index 0000000000..54dff3eb92 --- /dev/null +++ b/ets2panda/linter/test/interop/no_await_js_promise.ets.arkts2.json @@ -0,0 +1,258 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 89, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 89, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 10, + "endLine": 20, + "endColumn": 17, + "problem": "NoAwaitJsPromise", + "suggest": "", + "rule": "\"Await\" operator can't be used with interop objects (arkts-interop-js2s-await-js-promise)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 10, + "endLine": 24, + "endColumn": 21, + "problem": "NoAwaitJsPromise", + "suggest": "", + "rule": "\"Await\" operator can't be used with interop objects (arkts-interop-js2s-await-js-promise)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 16, + "endLine": 24, + "endColumn": 21, + "problem": "InteropJsObjectCallStaticFunc", + "suggest": "", + "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-call-static-function)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 16, + "endLine": 24, + "endColumn": 21, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 10, + "endLine": 28, + "endColumn": 25, + "problem": "NoAwaitJsPromise", + "suggest": "", + "rule": "\"Await\" operator can't be used with interop objects (arkts-interop-js2s-await-js-promise)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 10, + "endLine": 32, + "endColumn": 27, + "problem": "NoAwaitJsPromise", + "suggest": "", + "rule": "\"Await\" operator can't be used with interop objects (arkts-interop-js2s-await-js-promise)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 16, + "endLine": 32, + "endColumn": 27, + "problem": "InteropJsObjectCallStaticFunc", + "suggest": "", + "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-call-static-function)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 16, + "endLine": 32, + "endColumn": 27, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", + "severity": "ERROR" + }, + { + "line": 36, + "column": 10, + "endLine": 36, + "endColumn": 26, + "problem": "NoAwaitJsPromise", + "suggest": "", + "rule": "\"Await\" operator can't be used with interop objects (arkts-interop-js2s-await-js-promise)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 12, + "endLine": 41, + "endColumn": 19, + "problem": "NoAwaitJsPromise", + "suggest": "", + "rule": "\"Await\" operator can't be used with interop objects (arkts-interop-js2s-await-js-promise)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 12, + "endLine": 45, + "endColumn": 27, + "problem": "NoAwaitJsPromise", + "suggest": "", + "rule": "\"Await\" operator can't be used with interop objects (arkts-interop-js2s-await-js-promise)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 20, + "endLine": 49, + "endColumn": 21, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 50, + "column": 3, + "endLine": 52, + "endColumn": 4, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 51, + "column": 12, + "endLine": 51, + "endColumn": 28, + "problem": "NoAwaitJsPromise", + "suggest": "", + "rule": "\"Await\" operator can't be used with interop objects (arkts-interop-js2s-await-js-promise)", + "severity": "ERROR" + }, + { + "line": 55, + "column": 12, + "endLine": 55, + "endColumn": 23, + "problem": "NoAwaitJsPromise", + "suggest": "", + "rule": "\"Await\" operator can't be used with interop objects (arkts-interop-js2s-await-js-promise)", + "severity": "ERROR" + }, + { + "line": 55, + "column": 18, + "endLine": 55, + "endColumn": 23, + "problem": "InteropJsObjectCallStaticFunc", + "suggest": "", + "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-call-static-function)", + "severity": "ERROR" + }, + { + "line": 55, + "column": 18, + "endLine": 55, + "endColumn": 23, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", + "severity": "ERROR" + }, + { + "line": 59, + "column": 2, + "endLine": 61, + "endColumn": 2, + "problem": "FunctionExpression", + "suggest": "", + "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "severity": "ERROR" + }, + { + "line": 60, + "column": 31, + "endLine": 60, + "endColumn": 38, + "problem": "NoAwaitJsPromise", + "suggest": "", + "rule": "\"Await\" operator can't be used with interop objects (arkts-interop-js2s-await-js-promise)", + "severity": "ERROR" + }, + { + "line": 64, + "column": 37, + "endLine": 64, + "endColumn": 54, + "problem": "NoAwaitJsPromise", + "suggest": "", + "rule": "\"Await\" operator can't be used with interop objects (arkts-interop-js2s-await-js-promise)", + "severity": "ERROR" + }, + { + "line": 64, + "column": 43, + "endLine": 64, + "endColumn": 54, + "problem": "InteropJsObjectCallStaticFunc", + "suggest": "", + "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-call-static-function)", + "severity": "ERROR" + }, + { + "line": 64, + "column": 43, + "endLine": 64, + "endColumn": 54, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/no_js_await.ets.json b/ets2panda/linter/test/interop/no_await_js_promise.ets.json similarity index 92% rename from ets2panda/linter/test/interop/no_js_await.ets.json rename to ets2panda/linter/test/interop/no_await_js_promise.ets.json index 145ba7afed..5285bc41f6 100755 --- a/ets2panda/linter/test/interop/no_js_await.ets.json +++ b/ets2panda/linter/test/interop/no_await_js_promise.ets.json @@ -18,16 +18,16 @@ "line": 17, "column": 1, "endLine": 17, - "endColumn": 80, + "endColumn": 89, "problem": "ImportAfterStatement", "suggest": "", "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", "severity": "ERROR" }, { - "line": 54, + "line": 49, "column": 20, - "endLine": 54, + "endLine": 49, "endColumn": 21, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -35,9 +35,9 @@ "severity": "ERROR" }, { - "line": 65, + "line": 59, "column": 2, - "endLine": 67, + "endLine": 61, "endColumn": 2, "problem": "FunctionExpression", "suggest": "", diff --git a/ets2panda/linter/test/interop/no_js_awai.js b/ets2panda/linter/test/interop/no_await_js_promise_export.js similarity index 100% rename from ets2panda/linter/test/interop/no_js_awai.js rename to ets2panda/linter/test/interop/no_await_js_promise_export.js diff --git a/ets2panda/linter/test/interop/no_js_instanceof.ets.arkts2.json b/ets2panda/linter/test/interop/no_js_instanceof.ets.arkts2.json index d50f0569e1..38edbb0189 100755 --- a/ets2panda/linter/test/interop/no_js_instanceof.ets.arkts2.json +++ b/ets2panda/linter/test/interop/no_js_instanceof.ets.arkts2.json @@ -31,7 +31,7 @@ "endColumn": 88, "problem": "InterOpImportJs", "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-no-js-import)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -41,7 +41,7 @@ "endColumn": 22, "problem": "InteropJsInstanceof", "suggest": "", - "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-import-obj-type)", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-interop-js2s-instanceof-js-type)", "severity": "ERROR" }, { @@ -51,7 +51,7 @@ "endColumn": 23, "problem": "InteropJsInstanceof", "suggest": "", - "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-import-obj-type)", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-interop-js2s-instanceof-js-type)", "severity": "ERROR" }, { @@ -61,7 +61,7 @@ "endColumn": 23, "problem": "InteropJsInstanceof", "suggest": "", - "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-import-obj-type)", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-interop-js2s-instanceof-js-type)", "severity": "ERROR" }, { @@ -69,9 +69,9 @@ "column": 28, "endLine": 39, "endColumn": 50, - "problem": "InteropJsObjectUsage", + "problem": "InteropJsObjectCallStaticFunc", "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-call-static-function)", "severity": "ERROR" }, { @@ -81,17 +81,7 @@ "endColumn": 50, "problem": "CallJSFunction", "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", - "severity": "ERROR" - }, - { - "line": 39, - "column": 28, - "endLine": 39, - "endColumn": 50, - "problem": "InteropCallObjectMethods", - "suggest": "", - "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", "severity": "ERROR" }, { @@ -101,7 +91,7 @@ "endColumn": 34, "problem": "InteropJsInstanceof", "suggest": "", - "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-import-obj-type)", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-interop-js2s-instanceof-js-type)", "severity": "ERROR" }, { @@ -111,7 +101,7 @@ "endColumn": 38, "problem": "InteropJsInstanceof", "suggest": "", - "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-import-obj-type)", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-interop-js2s-instanceof-js-type)", "severity": "ERROR" }, { @@ -121,7 +111,7 @@ "endColumn": 38, "problem": "InteropJsInstanceof", "suggest": "", - "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-import-obj-type)", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-interop-js2s-instanceof-js-type)", "severity": "ERROR" }, { @@ -131,7 +121,7 @@ "endColumn": 42, "problem": "InteropJsInstanceof", "suggest": "", - "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-import-obj-type)", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-interop-js2s-instanceof-js-type)", "severity": "ERROR" }, { @@ -141,7 +131,7 @@ "endColumn": 22, "problem": "InteropJsInstanceof", "suggest": "", - "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-import-obj-type)", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-interop-js2s-instanceof-js-type)", "severity": "ERROR" }, { @@ -151,7 +141,7 @@ "endColumn": 24, "problem": "InteropJsInstanceof", "suggest": "", - "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-import-obj-type)", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-interop-js2s-instanceof-js-type)", "severity": "ERROR" }, { @@ -159,9 +149,9 @@ "column": 4, "endLine": 69, "endColumn": 7, - "problem": "InteropJsObjectUsage", + "problem": "InteropJsObjectCallStaticFunc", "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-call-static-function)", "severity": "ERROR" }, { @@ -171,17 +161,7 @@ "endColumn": 7, "problem": "CallJSFunction", "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-no-call-js-function)", - "severity": "ERROR" - }, - { - "line": 69, - "column": 4, - "endLine": 69, - "endColumn": 7, - "problem": "InteropCallObjectMethods", - "suggest": "", - "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-no-call-class-method)", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", "severity": "ERROR" }, { @@ -211,7 +191,7 @@ "endColumn": 51, "problem": "BinaryOperations", "suggest": "", - "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { @@ -221,7 +201,7 @@ "endColumn": 37, "problem": "InteropJsInstanceof", "suggest": "", - "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-no-import-obj-type)", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-interop-js2s-instanceof-js-type)", "severity": "ERROR" }, { @@ -229,9 +209,9 @@ "column": 22, "endLine": 75, "endColumn": 37, - "problem": "InteropJsObjectUsage", + "problem": "InteropJsObjectConditionJudgment", "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js2s-condition-judgment)", "severity": "ERROR" }, { @@ -241,7 +221,7 @@ "endColumn": 37, "problem": "BinaryOperations", "suggest": "", - "rule": "Binary operations on js objects (arkts-no-js-obj-binary-operation)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/interop/object_built_in.ets b/ets2panda/linter/test/interop/object_built_in.ets index 52776ecdd4..7797930ffd 100644 --- a/ets2panda/linter/test/interop/object_built_in.ets +++ b/ets2panda/linter/test/interop/object_built_in.ets @@ -12,9 +12,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +'use static' -import { foo } from "./oh_modules/object_built_in" +import { X } from "./oh_modules/object_built_in" -class X { a = 1 }; +export function foo(prx: Object) { + Object.assign({}, prx); + Object.entries(prx); + Object.keys(prx); + Object.values(prx); + prx.hasOwnProperty("a"); +} foo(new X()); // Illegal diff --git a/ets2panda/linter/test/interop/object_built_in.ets.args.json b/ets2panda/linter/test/interop/object_built_in.ets.args.json index 0adede204e..aac366be5e 100644 --- a/ets2panda/linter/test/interop/object_built_in.ets.args.json +++ b/ets2panda/linter/test/interop/object_built_in.ets.args.json @@ -14,5 +14,6 @@ "limitations under the License." ], "mode": { + "arkts2": "" } } diff --git a/ets2panda/linter/test/interop/object_built_in.ets.arkts2.json b/ets2panda/linter/test/interop/object_built_in.ets.arkts2.json new file mode 100644 index 0000000000..0e40297d99 --- /dev/null +++ b/ets2panda/linter/test/interop/object_built_in.ets.arkts2.json @@ -0,0 +1,69 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 49, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 12, + "endLine": 20, + "endColumn": 18, + "problem": "LimitedStdLibApi", + "suggest": "", + "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 19, + "endLine": 20, + "endColumn": 20, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 9, + "endLine": 24, + "endColumn": 23, + "problem": "LimitedStdLibApi", + "suggest": "", + "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 1, + "endLine": 27, + "endColumn": 13, + "problem": "InteropCallObjectParam", + "suggest": "", + "rule": "Class type is not compatible with \"Object\" parameter in interop call (arkts-interop-d2s-static-object-on-dynamic-instance)", + "severity": "ERROR" + } + ] +} + diff --git a/ets2panda/linter/test/interop/object_built_in.ets.json b/ets2panda/linter/test/interop/object_built_in.ets.json index f40eed4436..582a700d94 100644 --- a/ets2panda/linter/test/interop/object_built_in.ets.json +++ b/ets2panda/linter/test/interop/object_built_in.ets.json @@ -14,14 +14,44 @@ "limitations under the License." ], "result": [ - { - "line": 20, + { + "line": 17, "column": 1, + "endLine": 17, + "endColumn": 49, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 5, + "endLine": 20, + "endColumn": 27, + "problem": "LimitedStdLibApi", + "suggest": "", + "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 19, "endLine": 20, - "endColumn": 13, - "problem": "InteropCallObjectParam", + "endColumn": 20, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 5, + "endLine": 24, + "endColumn": 28, + "problem": "LimitedStdLibApi", "suggest": "", - "rule": "Class type is not compatible with \"Object\" parameter in interop call (arkts-interop-call-object-param)", + "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/interop/object_literal_constructor.ets b/ets2panda/linter/test/interop/object_literal_constructor.ets new file mode 100644 index 0000000000..c60cfdf0eb --- /dev/null +++ b/ets2panda/linter/test/interop/object_literal_constructor.ets @@ -0,0 +1,25 @@ +'use static' +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { User, Person, Fruit, Apple } from "./oh_modules/object_literal_constructor" + +let user: User = { id: 1 } + +let fruit: Fruit = new Fruit("fruit"); // legal + +let person: Person = { name: "Furkan", age: "25" } + +let apple: Apple = { name: "apple", color: "green" } \ No newline at end of file diff --git a/ets2panda/linter/test/interop/ts_decorator.ets.args.json b/ets2panda/linter/test/interop/object_literal_constructor.ets.args.json similarity index 100% rename from ets2panda/linter/test/interop/ts_decorator.ets.args.json rename to ets2panda/linter/test/interop/object_literal_constructor.ets.args.json diff --git a/ets2panda/linter/test/interop/object_literal_constructor.ets.arkts2.json b/ets2panda/linter/test/interop/object_literal_constructor.ets.arkts2.json new file mode 100644 index 0000000000..1891f69fe3 --- /dev/null +++ b/ets2panda/linter/test/interop/object_literal_constructor.ets.arkts2.json @@ -0,0 +1,58 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 85, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 5, + "endLine": 19, + "endColumn": 27, + "problem": "InteropObjectLiteralClass", + "suggest": "", + "rule": "Object literal cannot be directly assigned to class with a constructor. (arkts-interop-d2s-object-literal-no-args-constructor)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 5, + "endLine": 23, + "endColumn": 51, + "problem": "InteropObjectLiteralClass", + "suggest": "", + "rule": "Object literal cannot be directly assigned to class with a constructor. (arkts-interop-d2s-object-literal-no-args-constructor)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 5, + "endLine": 25, + "endColumn": 53, + "problem": "InteropObjectLiteralClass", + "suggest": "", + "rule": "Object literal cannot be directly assigned to class with a constructor. (arkts-interop-d2s-object-literal-no-args-constructor)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/object_literal_constructor.ets.json b/ets2panda/linter/test/interop/object_literal_constructor.ets.json new file mode 100644 index 0000000000..c57b713f15 --- /dev/null +++ b/ets2panda/linter/test/interop/object_literal_constructor.ets.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 85, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/object_literal_union_type.ets b/ets2panda/linter/test/interop/object_literal_union_type.ets new file mode 100644 index 0000000000..f57fd51379 --- /dev/null +++ b/ets2panda/linter/test/interop/object_literal_union_type.ets @@ -0,0 +1,29 @@ +'use static' +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {X, Y, Z} from "./oh_modules/object_literal_union_type" + +import {A, B} from "./oh_modules/object_literal_union_type_arkts2" + +let xy: X | Y = { name: "xy" } + +let yz: Y | Z = { name: "yz" } + +let xyz: X | Y | Z = { name: "xyz" } + +let ab: A | B = { name: "hello" } // legal + +let y: X | Y = { name: "hello" } as Y; // legal \ No newline at end of file diff --git a/ets2panda/linter/test/main/sendable_class_interface_property_sdk.ets.args.json b/ets2panda/linter/test/interop/object_literal_union_type.ets.args.json similarity index 100% rename from ets2panda/linter/test/main/sendable_class_interface_property_sdk.ets.args.json rename to ets2panda/linter/test/interop/object_literal_union_type.ets.args.json diff --git a/ets2panda/linter/test/interop/object_literal_union_type.ets.arkts2.json b/ets2panda/linter/test/interop/object_literal_union_type.ets.arkts2.json new file mode 100644 index 0000000000..5c02f0cb4d --- /dev/null +++ b/ets2panda/linter/test/interop/object_literal_union_type.ets.arkts2.json @@ -0,0 +1,68 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 63, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 67, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 5, + "endLine": 21, + "endColumn": 31, + "problem": "InteropObjectLiteralAmbiguity", + "suggest": "", + "rule": "Object literal not compatible with target union type. (arkts-interop-d2s-object-literal-no-ambiguity)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 5, + "endLine": 23, + "endColumn": 31, + "problem": "InteropObjectLiteralAmbiguity", + "suggest": "", + "rule": "Object literal not compatible with target union type. (arkts-interop-d2s-object-literal-no-ambiguity)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 5, + "endLine": 25, + "endColumn": 37, + "problem": "InteropObjectLiteralAmbiguity", + "suggest": "", + "rule": "Object literal not compatible with target union type. (arkts-interop-d2s-object-literal-no-ambiguity)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/object_literal_union_type.ets.json b/ets2panda/linter/test/interop/object_literal_union_type.ets.json new file mode 100644 index 0000000000..25154ac0c6 --- /dev/null +++ b/ets2panda/linter/test/interop/object_literal_union_type.ets.json @@ -0,0 +1,38 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 63, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 67, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/oh_modules/object_built_in.ets b/ets2panda/linter/test/interop/oh_modules/object_built_in.ets index 0d30fa2156..e06b3e23f9 100644 --- a/ets2panda/linter/test/interop/oh_modules/object_built_in.ets +++ b/ets2panda/linter/test/interop/oh_modules/object_built_in.ets @@ -1,5 +1,3 @@ -'use static' - /* * Copyright (c) 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,13 +13,6 @@ * limitations under the License. */ -export function foo(prx: Object) { - Object.assign({}, prx); - Object.entries(prx); - Object.keys(prx); - Object.values(prx); - prx.hasOwnProperty("a"); -} - +export class X { a = 1 }; diff --git a/ets2panda/linter/test/interop/oh_modules/object_literal_constructor.ets b/ets2panda/linter/test/interop/oh_modules/object_literal_constructor.ets new file mode 100644 index 0000000000..3ffe607d9d --- /dev/null +++ b/ets2panda/linter/test/interop/oh_modules/object_literal_constructor.ets @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export class User { + id: number; + constructor(arg: number) { + this.id = arg + } +} +export class Person { + name: string; + age: number; + constructor(arg1: string, arg2: number) { + this.name = arg1; + this.age = arg2; + } +} +export class Fruit { + name: string; + constructor(arg: string) { + this.name = arg; + } +} +export class Apple extends Fruit { + color: string; + constructor(string: string, arg2: string) { + super(string) + this.color = arg2; + } +} diff --git a/ets2panda/linter/test/interop/oh_modules/object_literal_union_type.ets b/ets2panda/linter/test/interop/oh_modules/object_literal_union_type.ets new file mode 100644 index 0000000000..34b50528bd --- /dev/null +++ b/ets2panda/linter/test/interop/oh_modules/object_literal_union_type.ets @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export class X { + name: string = '' + str: string = '' +} + +export class Y { + name: string = '' + bool: boolean = false +} + +export interface Z {name: string, age: number} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/oh_modules/object_literal_union_type_arkts2.ets b/ets2panda/linter/test/interop/oh_modules/object_literal_union_type_arkts2.ets new file mode 100644 index 0000000000..dad32c88ba --- /dev/null +++ b/ets2panda/linter/test/interop/oh_modules/object_literal_union_type_arkts2.ets @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +'use static' + +export class A { name: string = '' } +export interface B { name: string, age?: number } diff --git a/ets2panda/linter/test/interop/oh_modules/reflect_export.ets b/ets2panda/linter/test/interop/oh_modules/reflect_export.ets index d7e2351412..4fd2894dd8 100644 --- a/ets2panda/linter/test/interop/oh_modules/reflect_export.ets +++ b/ets2panda/linter/test/interop/oh_modules/reflect_export.ets @@ -24,3 +24,7 @@ export function bar(obj: Object) { return Reflect.has(obj, 'prop'); } +export class X { + a: string = 'hello' + getName() { return this.a } +} diff --git a/ets2panda/linter/test/interop/oh_modules/static_object_literals_export.ets b/ets2panda/linter/test/interop/oh_modules/static_object_literals_export.ets new file mode 100644 index 0000000000..2191e01971 --- /dev/null +++ b/ets2panda/linter/test/interop/oh_modules/static_object_literals_export.ets @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +'use static' + +export class X { name: string = '' } + +export interface Y { data: number } + +export function foo(arg: X) {} + +export function bar(arg: Y) {} + +export function CreateY(d: number): Y { + let y: Y = {data: d} + return y +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/reflect_built_in.ets b/ets2panda/linter/test/interop/reflect_built_in.ets index b108f1bc48..96b0800185 100644 --- a/ets2panda/linter/test/interop/reflect_built_in.ets +++ b/ets2panda/linter/test/interop/reflect_built_in.ets @@ -12,32 +12,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +'use static' -import { foo, bar, safe } from "./oh_modules/reflect_export" -import { safeVersion } from "./oh_modules/reflect_export_safe" +import { X } from "./oh_modules/reflect_export" -class X { - a: string = 'hello' - getName() { return this.a } +export function foo(prx: Object) { + Reflect.get(prx, 'a') // 'hello' + Reflect.set(prx, 'a', 'world') // true + Reflect.ownKeys(prx) // ['a'] } -foo(new X()); - -class Y { - prop = 42; -} - -bar(new Y()); - -class Z { - a: string = 'hello'; - getName() { return this.a; } +export function bar(obj: Object) { + return Reflect.has(obj, 'prop'); } -safe(new Z()); //legal - -class A { - prop = 34; -} +foo(new X()); //illegal -safeVersion(new A()) //legal \ No newline at end of file +bar(new X()); //illegal diff --git a/ets2panda/linter/test/interop/reflect_built_in.ets.args.json b/ets2panda/linter/test/interop/reflect_built_in.ets.args.json index c90ca155ab..bc4d2071da 100644 --- a/ets2panda/linter/test/interop/reflect_built_in.ets.args.json +++ b/ets2panda/linter/test/interop/reflect_built_in.ets.args.json @@ -13,5 +13,7 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "mode": {} -} \ No newline at end of file + "mode": { + "arkts2": "" + } +} diff --git a/ets2panda/linter/test/interop/reflect_built_in.ets.arkts2.json b/ets2panda/linter/test/interop/reflect_built_in.ets.arkts2.json new file mode 100644 index 0000000000..851c3577e7 --- /dev/null +++ b/ets2panda/linter/test/interop/reflect_built_in.ets.arkts2.json @@ -0,0 +1,68 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 48, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 1, + "endLine": 29, + "endColumn": 13, + "problem": "InteropCallObjectParam", + "suggest": "", + "rule": "Class type is not compatible with \"Object\" parameter in interop call (arkts-interop-d2s-static-object-on-dynamic-instance)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 1, + "endLine": 29, + "endColumn": 14, + "problem": "InteropCallReflect", + "suggest": "", + "rule": "Reflect API usage is not allowed in interop calls when an \"Object\" parameter receives a class instance (arkts-interop-d2s-static-reflect-on-dynamic-instance)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 1, + "endLine": 31, + "endColumn": 13, + "problem": "InteropCallObjectParam", + "suggest": "", + "rule": "Class type is not compatible with \"Object\" parameter in interop call (arkts-interop-d2s-static-object-on-dynamic-instance)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 1, + "endLine": 31, + "endColumn": 14, + "problem": "InteropCallReflect", + "suggest": "", + "rule": "Reflect API usage is not allowed in interop calls when an \"Object\" parameter receives a class instance (arkts-interop-d2s-static-reflect-on-dynamic-instance)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/interop/reflect_built_in.ets.json b/ets2panda/linter/test/interop/reflect_built_in.ets.json index 3dd802b2f5..0ee87e87fb 100644 --- a/ets2panda/linter/test/interop/reflect_built_in.ets.json +++ b/ets2panda/linter/test/interop/reflect_built_in.ets.json @@ -15,63 +15,13 @@ ], "result": [ { - "line": 24, + "line": 17, "column": 1, - "endLine": 24, - "endColumn": 13, - "problem": "InteropCallObjectParam", + "endLine": 17, + "endColumn": 48, + "problem": "ImportAfterStatement", "suggest": "", - "rule": "Class type is not compatible with \"Object\" parameter in interop call (arkts-interop-call-object-param)", - "severity": "ERROR" - }, - { - "line": 24, - "column": 1, - "endLine": 24, - "endColumn": 14, - "problem": "InteropCallReflect", - "suggest": "", - "rule": "Reflect API usage is not allowed in interop calls when an \"Object\" parameter receives a class instance (arkts-interop-call-reflect)", - "severity": "ERROR" - }, - { - "line": 24, - "column": 1, - "endLine": 24, - "endColumn": 14, - "problem": "InteropCallReflect", - "suggest": "", - "rule": "Reflect API usage is not allowed in interop calls when an \"Object\" parameter receives a class instance (arkts-interop-call-reflect)", - "severity": "ERROR" - }, - { - "line": 30, - "column": 1, - "endLine": 30, - "endColumn": 13, - "problem": "InteropCallObjectParam", - "suggest": "", - "rule": "Class type is not compatible with \"Object\" parameter in interop call (arkts-interop-call-object-param)", - "severity": "ERROR" - }, - { - "line": 30, - "column": 1, - "endLine": 30, - "endColumn": 14, - "problem": "InteropCallReflect", - "suggest": "", - "rule": "Reflect API usage is not allowed in interop calls when an \"Object\" parameter receives a class instance (arkts-interop-call-reflect)", - "severity": "ERROR" - }, - { - "line": 30, - "column": 1, - "endLine": 30, - "endColumn": 14, - "problem": "InteropCallReflect", - "suggest": "", - "rule": "Reflect API usage is not allowed in interop calls when an \"Object\" parameter receives a class instance (arkts-interop-call-reflect)", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/interop/static_dynamic_import.ets b/ets2panda/linter/test/interop/static_dynamic_import.ets new file mode 100644 index 0000000000..2e2c993747 --- /dev/null +++ b/ets2panda/linter/test/interop/static_dynamic_import.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +'use static' + +let arkTsMod = await import('./test_files/dummy_arkts1_file'); +let tsModule = await import('./test_files/dummy_ts_file'); +let jsModule = await import('./test_files/dummy_js_file'); + +function main(): void { + import('./test_files/dummy_ts_file').then((m) => { + console.log(m.Data.name) + }) +} diff --git a/ets2panda/linter/test/interop/static_dynamic_import.ets.args.json b/ets2panda/linter/test/interop/static_dynamic_import.ets.args.json new file mode 100644 index 0000000000..d8d3390ad9 --- /dev/null +++ b/ets2panda/linter/test/interop/static_dynamic_import.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/static_dynamic_import.ets.arkts2.json b/ets2panda/linter/test/interop/static_dynamic_import.ets.arkts2.json new file mode 100644 index 0000000000..3b87fbdb1f --- /dev/null +++ b/ets2panda/linter/test/interop/static_dynamic_import.ets.arkts2.json @@ -0,0 +1,98 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 16, + "endLine": 17, + "endColumn": 62, + "problem": "InteropDynamicImport", + "suggest": "", + "rule": "No support for static dynamic import (arkts-interop-d2s-dynamic-import)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 22, + "endLine": 17, + "endColumn": 62, + "problem": "DynamicImport", + "suggest": "", + "rule": "Dynamic import is not supported(arkts-no-dynamic-import)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 17, + "endLine": 18, + "endColumn": 59, + "problem": "InteropDynamicImportTs", + "suggest": "", + "rule": "No support for static dynamic import (arkts-interop-ts2s-dynamic-import-ts)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 23, + "endLine": 18, + "endColumn": 59, + "problem": "DynamicImport", + "suggest": "", + "rule": "Dynamic import is not supported(arkts-no-dynamic-import)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 16, + "endLine": 19, + "endColumn": 58, + "problem": "InteropDynamicImportJs", + "suggest": "", + "rule": "No support for static dynamic import (arkts-interop-js2s-dynamic-import-js)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 22, + "endLine": 19, + "endColumn": 58, + "problem": "DynamicImport", + "suggest": "", + "rule": "Dynamic import is not supported(arkts-no-dynamic-import)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 3, + "endLine": 22, + "endColumn": 44, + "problem": "InteropDynamicImportTs", + "suggest": "", + "rule": "No support for static dynamic import (arkts-interop-ts2s-dynamic-import-ts)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 3, + "endLine": 22, + "endColumn": 39, + "problem": "DynamicImport", + "suggest": "", + "rule": "Dynamic import is not supported(arkts-no-dynamic-import)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/main/data_observation_2.ets.arkts2.json b/ets2panda/linter/test/interop/static_dynamic_import.ets.json similarity index 100% rename from ets2panda/linter/test/main/data_observation_2.ets.arkts2.json rename to ets2panda/linter/test/interop/static_dynamic_import.ets.json diff --git a/ets2panda/linter/test/interop/static_object_literals.ets b/ets2panda/linter/test/interop/static_object_literals.ets new file mode 100644 index 0000000000..82b3db8dd1 --- /dev/null +++ b/ets2panda/linter/test/interop/static_object_literals.ets @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { X, Y, foo, bar } from "./oh_modules/static_object_literals_export" + +let x: X = { name: "hello" } + +let a: X = new X("hello") // legal + +let y: Y = { data: 123 } + +let b: Y = createY(123) // legal + +foo({ name: "world" }); + +foo(new X("world")) // legal + +bar({ data: 456 }); + +bar(createY(456)) // legal + +function zoo(): X { + return { name: "hello" } +} + +interface Z { x: X } + +let z: Z = { x: { name: "hello" } } + + + + diff --git a/ets2panda/linter/test/sdkwhite/GlobalThisError&TypeQuery.ets.arkts2.json b/ets2panda/linter/test/interop/static_object_literals.ets.args.json similarity index 95% rename from ets2panda/linter/test/sdkwhite/GlobalThisError&TypeQuery.ets.arkts2.json rename to ets2panda/linter/test/interop/static_object_literals.ets.args.json index 5e75d5b3e7..c90ca155ab 100644 --- a/ets2panda/linter/test/sdkwhite/GlobalThisError&TypeQuery.ets.arkts2.json +++ b/ets2panda/linter/test/interop/static_object_literals.ets.args.json @@ -13,7 +13,5 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "result": [ - - ] + "mode": {} } \ No newline at end of file diff --git a/ets2panda/linter/test/interop/static_object_literals.ets.json b/ets2panda/linter/test/interop/static_object_literals.ets.json new file mode 100644 index 0000000000..12d46c0860 --- /dev/null +++ b/ets2panda/linter/test/interop/static_object_literals.ets.json @@ -0,0 +1,78 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 12, + "endLine": 18, + "endColumn": 29, + "problem": "InteropStaticObjectLiterals", + "suggest": "", + "rule": "It is not allowed to create object literal in interop calls (arkts-interop-s2d-object-literal)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 12, + "endLine": 22, + "endColumn": 25, + "problem": "InteropStaticObjectLiterals", + "suggest": "", + "rule": "It is not allowed to create object literal in interop calls (arkts-interop-s2d-object-literal)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 5, + "endLine": 26, + "endColumn": 22, + "problem": "InteropStaticObjectLiterals", + "suggest": "", + "rule": "It is not allowed to create object literal in interop calls (arkts-interop-s2d-object-literal)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 5, + "endLine": 30, + "endColumn": 18, + "problem": "InteropStaticObjectLiterals", + "suggest": "", + "rule": "It is not allowed to create object literal in interop calls (arkts-interop-s2d-object-literal)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 12, + "endLine": 35, + "endColumn": 29, + "problem": "InteropStaticObjectLiterals", + "suggest": "", + "rule": "It is not allowed to create object literal in interop calls (arkts-interop-s2d-object-literal)", + "severity": "ERROR" + }, + { + "line": 40, + "column": 17, + "endLine": 40, + "endColumn": 34, + "problem": "InteropStaticObjectLiterals", + "suggest": "", + "rule": "It is not allowed to create object literal in interop calls (arkts-interop-s2d-object-literal)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/test_files/dummy_arkts1_file.ets b/ets2panda/linter/test/interop/test_files/dummy_arkts1_file.ets new file mode 100644 index 0000000000..5aad017834 --- /dev/null +++ b/ets2panda/linter/test/interop/test_files/dummy_arkts1_file.ets @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export module arkts {} diff --git a/ets2panda/linter/test/interop/test_files/dummy_js_file.js b/ets2panda/linter/test/interop/test_files/dummy_js_file.js new file mode 100644 index 0000000000..fa09fbb12c --- /dev/null +++ b/ets2panda/linter/test/interop/test_files/dummy_js_file.js @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export {} diff --git a/ets2panda/linter/test/interop/test_files/dummy_ts_file.ts b/ets2panda/linter/test/interop/test_files/dummy_ts_file.ts new file mode 100644 index 0000000000..e2f4a0e44b --- /dev/null +++ b/ets2panda/linter/test/interop/test_files/dummy_ts_file.ts @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export module tsModule {} diff --git a/ets2panda/linter/test/interop/unique_types.ets b/ets2panda/linter/test/interop/unique_types.ets index 6f7517f43c..35f8bae391 100644 --- a/ets2panda/linter/test/interop/unique_types.ets +++ b/ets2panda/linter/test/interop/unique_types.ets @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +'use static' import { objectLiteralType, @@ -25,7 +26,10 @@ objectLiteralType.name = "test" intersectionType.name = "test"; +try { tsFunction(); +} catch (e) { +} stringType = "test" //should pass diff --git a/ets2panda/linter/test/interop/unique_types.ets.args.json b/ets2panda/linter/test/interop/unique_types.ets.args.json index 49519d7bde..d3ae885df4 100644 --- a/ets2panda/linter/test/interop/unique_types.ets.args.json +++ b/ets2panda/linter/test/interop/unique_types.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "autofix": "--arkts-2", + "migrate": "--arkts-2", "arkts2": "" } } diff --git a/ets2panda/linter/test/interop/unique_types.ets.arkts2.json b/ets2panda/linter/test/interop/unique_types.ets.arkts2.json index 320d717b2f..30f972d757 100644 --- a/ets2panda/linter/test/interop/unique_types.ets.arkts2.json +++ b/ets2panda/linter/test/interop/unique_types.ets.arkts2.json @@ -15,44 +15,64 @@ ], "result": [ { - "line": 24, + "line": 17, "column": 1, - "endLine": 24, + "endLine": 23, + "endColumn": 38, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 1, + "endLine": 25, "endColumn": 23, "problem": "InteropDirectAccessToTSTypes", "suggest": "", - "rule": "Cannot access typescript types directly (arkts-interop-access-ts-types)", + "rule": "Cannot access typescript types directly (arkts-interop-ts2s-static-access-ts-type)", "severity": "ERROR" }, { - "line": 26, + "line": 27, "column": 1, - "endLine": 26, + "endLine": 27, "endColumn": 22, "problem": "InteropDirectAccessToTSTypes", "suggest": "", - "rule": "Cannot access typescript types directly (arkts-interop-access-ts-types)", + "rule": "Cannot access typescript types directly (arkts-interop-ts2s-static-access-ts-type)", "severity": "ERROR" }, { - "line": 28, + "line": 30, "column": 1, - "endLine": 28, + "endLine": 30, "endColumn": 13, "problem": "InteropTSFunctionInvoke", "suggest": "", - "rule": "Cannot invoke functions implemented in TypeScript (arkts-interop-ts-function)", + "rule": "Trying to catch typescript errors is not permitted (arkts-interop-ts2s-ts-exception)", "severity": "ERROR" - }, - { - "line": 30, + }, + { + "line": 31, + "column": 3, + "endLine": 32, + "endColumn": 2, + "problem": "TsLikeCatchType", + "suggest": "", + "rule": "TS catch type are not supported (arkts-no-ts-like-catch-type)", + "severity": "ERROR" + }, + { + "line": 34, "column": 1, - "endLine": 30, + "endLine": 34, "endColumn": 20, "problem": "InteropDirectAccessToTSTypes", "suggest": "", - "rule": "Cannot access typescript types directly (arkts-interop-access-ts-types)", + "rule": "Cannot access typescript types directly (arkts-interop-ts2s-static-access-ts-type)", "severity": "ERROR" - } + } ] -} +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/unique_types.ets.autofix.json b/ets2panda/linter/test/interop/unique_types.ets.autofix.json index 7442071b22..14ba376bad 100644 --- a/ets2panda/linter/test/interop/unique_types.ets.autofix.json +++ b/ets2panda/linter/test/interop/unique_types.ets.autofix.json @@ -15,58 +15,86 @@ ], "result": [ { - "line": 24, + "line": 17, "column": 1, - "endLine": 24, + "endLine": 23, + "endColumn": 38, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 1, + "endLine": 25, "endColumn": 23, "problem": "InteropDirectAccessToTSTypes", "autofix": [ { - "start": 731, - "end": 762, - "replacementText": "objectLiteralType.setPropertyByName('name',ESObject.wrap(\"test\"))" + "start": 744, + "end": 775, + "replacementText": "objectLiteralType.setPropertyByName('name',ESObject.wrap(\"test\"))", + "line": 25, + "column": 1, + "endLine": 25, + "endColumn": 23 } ], "suggest": "", - "rule": "Cannot access typescript types directly (arkts-interop-access-ts-types)", + "rule": "Cannot access typescript types directly (arkts-interop-ts2s-static-access-ts-type)", "severity": "ERROR" }, { - "line": 26, + "line": 27, "column": 1, - "endLine": 26, + "endLine": 27, "endColumn": 22, "problem": "InteropDirectAccessToTSTypes", "autofix": [ { - "start": 764, - "end": 794, - "replacementText": "intersectionType.setPropertyByName('name',ESObject.wrap(\"test\"))" + "start": 777, + "end": 807, + "replacementText": "intersectionType.setPropertyByName('name',ESObject.wrap(\"test\"))", + "line": 27, + "column": 1, + "endLine": 27, + "endColumn": 22 } ], "suggest": "", - "rule": "Cannot access typescript types directly (arkts-interop-access-ts-types)", + "rule": "Cannot access typescript types directly (arkts-interop-ts2s-static-access-ts-type)", "severity": "ERROR" }, { - "line": 28, + "line": 30, "column": 1, - "endLine": 28, + "endLine": 30, "endColumn": 13, "problem": "InteropTSFunctionInvoke", "suggest": "", - "rule": "Cannot invoke functions implemented in TypeScript (arkts-interop-ts-function)", + "rule": "Trying to catch typescript errors is not permitted (arkts-interop-ts2s-ts-exception)", "severity": "ERROR" - }, - { - "line": 30, + }, + { + "line": 31, + "column": 3, + "endLine": 32, + "endColumn": 2, + "problem": "TsLikeCatchType", + "suggest": "", + "rule": "TS catch type are not supported (arkts-no-ts-like-catch-type)", + "severity": "ERROR" + }, + { + "line": 34, "column": 1, - "endLine": 30, + "endLine": 34, "endColumn": 20, "problem": "InteropDirectAccessToTSTypes", "suggest": "", - "rule": "Cannot access typescript types directly (arkts-interop-access-ts-types)", + "rule": "Cannot access typescript types directly (arkts-interop-ts2s-static-access-ts-type)", "severity": "ERROR" - } + } ] -} +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/unique_types.ets.json b/ets2panda/linter/test/interop/unique_types.ets.json index 9f305c86d7..3e8e488310 100644 --- a/ets2panda/linter/test/interop/unique_types.ets.json +++ b/ets2panda/linter/test/interop/unique_types.ets.json @@ -1,17 +1,14 @@ { - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "result": [] -} + "result": [ + { + "line": 17, + "column": 1, + "endLine": 23, + "endColumn": 38, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/unique_types.ets.migrate.ets b/ets2panda/linter/test/interop/unique_types.ets.migrate.ets new file mode 100644 index 0000000000..76dc6876cc --- /dev/null +++ b/ets2panda/linter/test/interop/unique_types.ets.migrate.ets @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ +'use static' + +import { + objectLiteralType, + intersectionType, + tsFunction, + stringType, + enumType +} from "./ignore_files/unique_types"; + +objectLiteralType.setPropertyByName('name',ESObject.wrap("test")) + +intersectionType.setPropertyByName('name',ESObject.wrap("test")); + +try { +tsFunction(); +} catch (e) { +} + +stringType = "test" //should pass + +enumType = "A"; //should fail diff --git a/ets2panda/linter/test/interop/unique_types.ets.migrate.json b/ets2panda/linter/test/interop/unique_types.ets.migrate.json new file mode 100644 index 0000000000..6e09d425c5 --- /dev/null +++ b/ets2panda/linter/test/interop/unique_types.ets.migrate.json @@ -0,0 +1,58 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 23, + "endColumn": 38, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 1, + "endLine": 30, + "endColumn": 13, + "problem": "InteropTSFunctionInvoke", + "suggest": "", + "rule": "Trying to catch typescript errors is not permitted (arkts-interop-ts2s-ts-exception)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 3, + "endLine": 32, + "endColumn": 2, + "problem": "TsLikeCatchType", + "suggest": "", + "rule": "TS catch type are not supported (arkts-no-ts-like-catch-type)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 1, + "endLine": 34, + "endColumn": 20, + "problem": "InteropDirectAccessToTSTypes", + "suggest": "", + "rule": "Cannot access typescript types directly (arkts-interop-ts2s-static-access-ts-type)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/animatable_extend_decorator_1.ets.args.json b/ets2panda/linter/test/main/animatable_extend_decorator_1.ets.args.json index 5efbceacdc..e7a5dbc614 100644 --- a/ets2panda/linter/test/main/animatable_extend_decorator_1.ets.args.json +++ b/ets2panda/linter/test/main/animatable_extend_decorator_1.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/animatable_extend_decorator_1.ets.migrate.ets b/ets2panda/linter/test/main/animatable_extend_decorator_1.ets.migrate.ets new file mode 100644 index 0000000000..1c0c40caa7 --- /dev/null +++ b/ets2panda/linter/test/main/animatable_extend_decorator_1.ets.migrate.ets @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { TextAttribute, AnimatableExtend, Entry, Component, State, Column, Text, Curve, Button } from '@kit.ArkUI'; + +@AnimatableExtend +function animatableWidth(this: TextAttribute, width: number): this { + this.width(width); + return this; +} + +@Entry +@Component +struct AnimatablePropertyExample { + @State textWidth: number = 80; + + build() { + Column() { + Text("AnimatableProperty") + .animatableWidth(this.textWidth) + .animation({ duration: 2000, curve: Curve.Ease }) + Button("Play") + .onClick(() => { + this.textWidth = this.textWidth == 80 ? 160 : 80; + }) + }.width("100%") + .padding(10) + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/animatable_extend_decorator_1.ets.migrate.json b/ets2panda/linter/test/main/animatable_extend_decorator_1.ets.migrate.json new file mode 100644 index 0000000000..32075de8ac --- /dev/null +++ b/ets2panda/linter/test/main/animatable_extend_decorator_1.ets.migrate.json @@ -0,0 +1,58 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 20, + "column": 5, + "endLine": 20, + "endColumn": 9, + "problem": "FunctionContainsThis", + "suggest": "", + "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 12, + "endLine": 21, + "endColumn": 16, + "problem": "FunctionContainsThis", + "suggest": "", + "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 26, + "endLine": 19, + "endColumn": 30, + "problem": "InvalidIdentifier", + "suggest": "", + "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 63, + "endLine": 19, + "endColumn": 67, + "problem": "ThisType", + "suggest": "", + "rule": "Type notation using \"this\" is not supported (arkts-no-typing-with-this)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/animatable_extend_decorator_2.ets.args.json b/ets2panda/linter/test/main/animatable_extend_decorator_2.ets.args.json index 5efbceacdc..e7a5dbc614 100644 --- a/ets2panda/linter/test/main/animatable_extend_decorator_2.ets.args.json +++ b/ets2panda/linter/test/main/animatable_extend_decorator_2.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/animatable_extend_decorator_2.ets.migrate.ets b/ets2panda/linter/test/main/animatable_extend_decorator_2.ets.migrate.ets new file mode 100644 index 0000000000..eebe111df2 --- /dev/null +++ b/ets2panda/linter/test/main/animatable_extend_decorator_2.ets.migrate.ets @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { AnimatableExtend, TextAttribute, Entry, Component, State, Column, Text, Curve, Button } from '@kit.ArkUI'; + +@AnimatableExtend +function animatableWidth(this: TextAttribute, width: number): this { + this.width(width); + return this; +} + +@Entry +@Component +struct AnimatablePropertyExample { + @State textWidth: number = 80; + + build() { + Column() { + Text("AnimatableProperty") + .animatableWidth(this.textWidth) + .animation({ duration: 2000, curve: Curve.Ease }) + Button("Play") + .onClick(() => { + this.textWidth = this.textWidth == 80 ? 160 : 80; + }) + }.width("100%") + .padding(10) + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/animatable_extend_decorator_2.ets.migrate.json b/ets2panda/linter/test/main/animatable_extend_decorator_2.ets.migrate.json new file mode 100644 index 0000000000..4e365eb63e --- /dev/null +++ b/ets2panda/linter/test/main/animatable_extend_decorator_2.ets.migrate.json @@ -0,0 +1,58 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 20, + "column": 3, + "endLine": 20, + "endColumn": 7, + "problem": "FunctionContainsThis", + "suggest": "", + "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 10, + "endLine": 21, + "endColumn": 14, + "problem": "FunctionContainsThis", + "suggest": "", + "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 26, + "endLine": 19, + "endColumn": 30, + "problem": "InvalidIdentifier", + "suggest": "", + "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 63, + "endLine": 19, + "endColumn": 67, + "problem": "ThisType", + "suggest": "", + "rule": "Type notation using \"this\" is not supported (arkts-no-typing-with-this)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/arkts-array-type-immutable.ets b/ets2panda/linter/test/main/arkts-array-type-immutable.ets new file mode 100644 index 0000000000..75a02116dd --- /dev/null +++ b/ets2panda/linter/test/main/arkts-array-type-immutable.ets @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +let a: number[] = [1] +let b: (number | string)[] = a // error + +let a1: (number | string)[] = [1] +let b1: (number | string)[] = a1 // ok + +let b2: (number | string)[]; +b2 = a // error + +class A { + a: (number | string)[] = [1]; +} + +let aA: A = new A(); +aA.a = a; // error + +let a3: (number | string)[] = new Array(1, 2); // error + +function test(a: number[]): void { + let b: (number | string)[] = [1]; + b = a; // error +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/arkts-array-type-immutable.ets.args.json b/ets2panda/linter/test/main/arkts-array-type-immutable.ets.args.json new file mode 100644 index 0000000000..d8d3390ad9 --- /dev/null +++ b/ets2panda/linter/test/main/arkts-array-type-immutable.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/arkts-array-type-immutable.ets.arkts2.json b/ets2panda/linter/test/main/arkts-array-type-immutable.ets.arkts2.json new file mode 100644 index 0000000000..802ecf8492 --- /dev/null +++ b/ets2panda/linter/test/main/arkts-array-type-immutable.ets.arkts2.json @@ -0,0 +1,68 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 5, + "endLine": 17, + "endColumn": 31, + "problem": "ArrayTypeImmutable", + "suggest": "", + "rule": "Array types follow the principle of invariance (arkts-array-type-immutable)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 1, + "endLine": 23, + "endColumn": 7, + "problem": "ArrayTypeImmutable", + "suggest": "", + "rule": "Array types follow the principle of invariance (arkts-array-type-immutable)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 1, + "endLine": 30, + "endColumn": 9, + "problem": "ArrayTypeImmutable", + "suggest": "", + "rule": "Array types follow the principle of invariance (arkts-array-type-immutable)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 5, + "endLine": 32, + "endColumn": 54, + "problem": "ArrayTypeImmutable", + "suggest": "", + "rule": "Array types follow the principle of invariance (arkts-array-type-immutable)", + "severity": "ERROR" + }, + { + "line": 36, + "column": 3, + "endLine": 36, + "endColumn": 8, + "problem": "ArrayTypeImmutable", + "suggest": "", + "rule": "Array types follow the principle of invariance (arkts-array-type-immutable)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/data_observation_2.ets.autofix.json b/ets2panda/linter/test/main/arkts-array-type-immutable.ets.json similarity index 100% rename from ets2panda/linter/test/main/data_observation_2.ets.autofix.json rename to ets2panda/linter/test/main/arkts-array-type-immutable.ets.json diff --git a/ets2panda/linter/test/main/arkts-primitive-type-normalization.ets b/ets2panda/linter/test/main/arkts-primitive-type-normalization.ets new file mode 100644 index 0000000000..4e05df4b07 --- /dev/null +++ b/ets2panda/linter/test/main/arkts-primitive-type-normalization.ets @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +typeof new Number(1) // error +new Number(1) == new Number(1) // error +if (new Boolean(false)) {} // error +let a = new String('111') // error +new Boolean // error +new String // error +new Number // error \ No newline at end of file diff --git a/ets2panda/linter/test/main/arkts-primitive-type-normalization.ets.args.json b/ets2panda/linter/test/main/arkts-primitive-type-normalization.ets.args.json new file mode 100644 index 0000000000..1b80aa9e73 --- /dev/null +++ b/ets2panda/linter/test/main/arkts-primitive-type-normalization.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } + } \ No newline at end of file diff --git a/ets2panda/linter/test/main/arkts-primitive-type-normalization.ets.arkts2.json b/ets2panda/linter/test/main/arkts-primitive-type-normalization.ets.arkts2.json new file mode 100644 index 0000000000..1b81953cde --- /dev/null +++ b/ets2panda/linter/test/main/arkts-primitive-type-normalization.ets.arkts2.json @@ -0,0 +1,98 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 8, + "endLine": 16, + "endColumn": 21, + "problem": "CreatingPrimitiveTypes", + "suggest": "", + "rule": "ArkTS creating primitive types is not supported (arkts-primitive-type-normalization)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 14, + "problem": "CreatingPrimitiveTypes", + "suggest": "", + "rule": "ArkTS creating primitive types is not supported (arkts-primitive-type-normalization)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 18, + "endLine": 17, + "endColumn": 31, + "problem": "CreatingPrimitiveTypes", + "suggest": "", + "rule": "ArkTS creating primitive types is not supported (arkts-primitive-type-normalization)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 5, + "endLine": 18, + "endColumn": 23, + "problem": "CreatingPrimitiveTypes", + "suggest": "", + "rule": "ArkTS creating primitive types is not supported (arkts-primitive-type-normalization)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 9, + "endLine": 19, + "endColumn": 26, + "problem": "CreatingPrimitiveTypes", + "suggest": "", + "rule": "ArkTS creating primitive types is not supported (arkts-primitive-type-normalization)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 12, + "problem": "CreatingPrimitiveTypes", + "suggest": "", + "rule": "ArkTS creating primitive types is not supported (arkts-primitive-type-normalization)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 11, + "problem": "CreatingPrimitiveTypes", + "suggest": "", + "rule": "ArkTS creating primitive types is not supported (arkts-primitive-type-normalization)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 1, + "endLine": 22, + "endColumn": 11, + "problem": "CreatingPrimitiveTypes", + "suggest": "", + "rule": "ArkTS creating primitive types is not supported (arkts-primitive-type-normalization)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/data_observation_2.ets.json b/ets2panda/linter/test/main/arkts-primitive-type-normalization.ets.json similarity index 100% rename from ets2panda/linter/test/main/data_observation_2.ets.json rename to ets2panda/linter/test/main/arkts-primitive-type-normalization.ets.json diff --git a/ets2panda/linter/test/main/arktsutils_module.ets b/ets2panda/linter/test/main/arktsutils_module.ets new file mode 100644 index 0000000000..3bfeec6005 --- /dev/null +++ b/ets2panda/linter/test/main/arktsutils_module.ets @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { utils } from './oh_modules/@arkts.utils'; + +import { utils as ArkTSUtilsAlias } from './oh_modules/@arkts.utils'; + +import { utils as kitArkTSUtils } from './oh_modules/@kit.ArkTS'; + +import { utils as definedArkTSUtils } from 'user_defined_worker'; //legal + +export { utils } from './oh_modules/@arkts.utils'; + +function tesCollectionsUsage() { + + const utils1: string = utils.ASON.stringify(1); + + const utils2 = ArkTSUtilsAlias.ASON.stringify(1); + + const utils3 = kitArkTSUtils.ASON.stringify(1); + + const utils4: string = ArkTSUtilsAlias.ASON.stringify(1); +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/arktsutils_module.ets.args.json b/ets2panda/linter/test/main/arktsutils_module.ets.args.json new file mode 100644 index 0000000000..b13bb90d5b --- /dev/null +++ b/ets2panda/linter/test/main/arktsutils_module.ets.args.json @@ -0,0 +1,21 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2", + "migrate": "--arkts-2" + } +} diff --git a/ets2panda/linter/test/main/arktsutils_module.ets.arkts2.json b/ets2panda/linter/test/main/arktsutils_module.ets.arkts2.json new file mode 100644 index 0000000000..6f9939410a --- /dev/null +++ b/ets2panda/linter/test/main/arktsutils_module.ets.arkts2.json @@ -0,0 +1,58 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 28, + "column": 32, + "endLine": 28, + "endColumn": 36, + "problem": "LimitedStdLibNoASON", + "suggest": "", + "rule": "ASON is not supported. (arkts-no-need-stdlib-ason)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 34, + "endLine": 30, + "endColumn": 38, + "problem": "LimitedStdLibNoASON", + "suggest": "", + "rule": "ASON is not supported. (arkts-no-need-stdlib-ason)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 32, + "endLine": 32, + "endColumn": 36, + "problem": "LimitedStdLibNoASON", + "suggest": "", + "rule": "ASON is not supported. (arkts-no-need-stdlib-ason)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 42, + "endLine": 34, + "endColumn": 46, + "problem": "LimitedStdLibNoASON", + "suggest": "", + "rule": "ASON is not supported. (arkts-no-need-stdlib-ason)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/main/arktsutils_module.ets.autofix.json b/ets2panda/linter/test/main/arktsutils_module.ets.autofix.json new file mode 100644 index 0000000000..05eac65f01 --- /dev/null +++ b/ets2panda/linter/test/main/arktsutils_module.ets.autofix.json @@ -0,0 +1,86 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 28, + "column": 32, + "endLine": 28, + "endColumn": 36, + "problem": "LimitedStdLibNoASON", + "suggest": "", + "autofix": [ + { + "start": 981, + "end": 991, + "replacementText": "JSON" + } + ], + "rule": "ASON is not supported. (arkts-no-need-stdlib-ason)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 34, + "endLine": 30, + "endColumn": 38, + "problem": "LimitedStdLibNoASON", + "suggest": "", + "autofix": [ + { + "start": 1024, + "end": 1044, + "replacementText": "JSON" + } + ], + "rule": "ASON is not supported. (arkts-no-need-stdlib-ason)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 32, + "endLine": 32, + "endColumn": 36, + "problem": "LimitedStdLibNoASON", + "suggest": "", + "autofix": [ + { + "start": 1077, + "end": 1095, + "replacementText": "JSON" + } + ], + "rule": "ASON is not supported. (arkts-no-need-stdlib-ason)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 42, + "endLine": 34, + "endColumn": 46, + "problem": "LimitedStdLibNoASON", + "suggest": "", + "autofix": [ + { + "start": 1136, + "end": 1156, + "replacementText": "JSON" + } + ], + "rule": "ASON is not supported. (arkts-no-need-stdlib-ason)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/sdkwhite/ConstructorIface4.ets.json b/ets2panda/linter/test/main/arktsutils_module.ets.json similarity index 100% rename from ets2panda/linter/test/sdkwhite/ConstructorIface4.ets.json rename to ets2panda/linter/test/main/arktsutils_module.ets.json diff --git a/ets2panda/linter/test/main/arktsutils_module.ets.migrate.ets b/ets2panda/linter/test/main/arktsutils_module.ets.migrate.ets new file mode 100644 index 0000000000..c44acf5845 --- /dev/null +++ b/ets2panda/linter/test/main/arktsutils_module.ets.migrate.ets @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { utils } from './oh_modules/@arkts.utils'; + +import { utils as ArkTSUtilsAlias } from './oh_modules/@arkts.utils'; + +import { utils as kitArkTSUtils } from './oh_modules/@kit.ArkTS'; + +import { utils as definedArkTSUtils } from 'user_defined_worker'; //legal + +export { utils } from './oh_modules/@arkts.utils'; + +function tesCollectionsUsage() { + + const utils1: string = JSON.stringify(1); + + const utils2 = JSON.stringify(1); + + const utils3 = JSON.stringify(1); + + const utils4: string = JSON.stringify(1); +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/arktsutils_module.ets.migrate.json b/ets2panda/linter/test/main/arktsutils_module.ets.migrate.json new file mode 100644 index 0000000000..9f305c86d7 --- /dev/null +++ b/ets2panda/linter/test/main/arktsutils_module.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} diff --git a/ets2panda/linter/test/main/array_index_expr_type.ets b/ets2panda/linter/test/main/array_index_expr_type.ets index c8eed0c0d8..fe370c16cd 100644 --- a/ets2panda/linter/test/main/array_index_expr_type.ets +++ b/ets2panda/linter/test/main/array_index_expr_type.ets @@ -78,8 +78,8 @@ let c:int = 1; let d:long = 1; let arr:number[] = [1,2,3] - +arr[true?1.3:1.2] arr[a] = 1; arr[b] = 1; arr[c] = 1; -arr[d] = 1; \ No newline at end of file +arr[d] = 1; diff --git a/ets2panda/linter/test/main/array_index_expr_type.ets.args.json b/ets2panda/linter/test/main/array_index_expr_type.ets.args.json index 1b80aa9e73..e7a5dbc614 100644 --- a/ets2panda/linter/test/main/array_index_expr_type.ets.args.json +++ b/ets2panda/linter/test/main/array_index_expr_type.ets.args.json @@ -14,6 +14,8 @@ "limitations under the License." ], "mode": { - "arkts2": "" + "arkts2": "", + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/array_index_expr_type.ets.arkts2.json b/ets2panda/linter/test/main/array_index_expr_type.ets.arkts2.json index 16b8d6a258..5bf7d76719 100644 --- a/ets2panda/linter/test/main/array_index_expr_type.ets.arkts2.json +++ b/ets2panda/linter/test/main/array_index_expr_type.ets.arkts2.json @@ -54,6 +54,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 19, + "column": 21, + "endLine": 19, + "endColumn": 30, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, { "line": 20, "column": 7, @@ -64,6 +74,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 20, + "column": 21, + "endLine": 20, + "endColumn": 32, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, { "line": 21, "column": 7, @@ -194,6 +214,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 27, + "column": 20, + "endLine": 27, + "endColumn": 23, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, { "line": 28, "column": 7, @@ -204,6 +234,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 28, + "column": 20, + "endLine": 28, + "endColumn": 24, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, { "line": 29, "column": 7, @@ -373,6 +413,16 @@ "suggest": "", "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", "severity": "ERROR" + }, + { + "line": 81, + "column": 5, + "endLine": 81, + "endColumn": 17, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" } ] -} \ No newline at end of file +} diff --git a/ets2panda/linter/test/main/array_index_expr_type.ets.autofix.json b/ets2panda/linter/test/main/array_index_expr_type.ets.autofix.json new file mode 100644 index 0000000000..e6e11862be --- /dev/null +++ b/ets2panda/linter/test/main/array_index_expr_type.ets.autofix.json @@ -0,0 +1,631 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 7, + "endLine": 17, + "endColumn": 25, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 639, + "end": 657, + "replacementText": "an_array: number[] = [1, 2, 3]" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 7, + "endLine": 18, + "endColumn": 26, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 664, + "end": 683, + "replacementText": "a: number = an_array[index]" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 20, + "endLine": 18, + "endColumn": 25, + "problem": "ArrayIndexExprType", + "autofix": [ + { + "start": 677, + "end": 682, + "replacementText": "index as int" + } + ], + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 7, + "endLine": 19, + "endColumn": 31, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 690, + "end": 714, + "replacementText": "a1: number = an_array[index + 1]" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 21, + "endLine": 19, + "endColumn": 30, + "problem": "ArrayIndexExprType", + "autofix": [ + { + "start": 704, + "end": 713, + "replacementText": "(index + 1) as int" + } + ], + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 7, + "endLine": 20, + "endColumn": 33, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 721, + "end": 747, + "replacementText": "a2: number = an_array[index + 1.1]" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 21, + "endLine": 20, + "endColumn": 32, + "problem": "ArrayIndexExprType", + "autofix": [ + { + "start": 735, + "end": 746, + "replacementText": "(index + 1.1) as int" + } + ], + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 7, + "endLine": 21, + "endColumn": 25, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 754, + "end": 772, + "replacementText": "b: number = an_array[1.23]" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 20, + "endLine": 21, + "endColumn": 24, + "problem": "ArrayIndexExprType", + "autofix": [ + { + "start": 767, + "end": 771, + "replacementText": "1.23 as int" + } + ], + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 7, + "endLine": 22, + "endColumn": 25, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 20, + "endLine": 22, + "endColumn": 24, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 7, + "endLine": 23, + "endColumn": 28, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 20, + "endLine": 23, + "endColumn": 27, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 7, + "endLine": 24, + "endColumn": 30, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 20, + "endLine": 24, + "endColumn": 29, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 7, + "endLine": 25, + "endColumn": 25, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 20, + "endLine": 25, + "endColumn": 24, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 7, + "endLine": 26, + "endColumn": 21, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 887, + "end": 901, + "replacementText": "g: number = an_array[]" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 20, + "endLine": 26, + "endColumn": 20, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 7, + "endLine": 27, + "endColumn": 24, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 908, + "end": 925, + "replacementText": "h: number = an_array[12.]" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 20, + "endLine": 27, + "endColumn": 23, + "problem": "ArrayIndexExprType", + "autofix": [ + { + "start": 921, + "end": 924, + "replacementText": "12. as int" + } + ], + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 7, + "endLine": 28, + "endColumn": 25, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 932, + "end": 950, + "replacementText": "i: number = an_array[12.0]" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 20, + "endLine": 28, + "endColumn": 24, + "problem": "ArrayIndexExprType", + "autofix": [ + { + "start": 945, + "end": 949, + "replacementText": "12.0 as int" + } + ], + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 7, + "endLine": 29, + "endColumn": 22, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 957, + "end": 972, + "replacementText": "j: number = an_array[0]" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 7, + "endLine": 30, + "endColumn": 37, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 979, + "end": 1009, + "replacementText": "k: number = an_array[Number.MAX_VALUE]" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 20, + "endLine": 30, + "endColumn": 36, + "problem": "ArrayIndexExprType", + "autofix": [ + { + "start": 992, + "end": 1008, + "replacementText": "Number.MAX_VALUE as int" + } + ], + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 7, + "endLine": 31, + "endColumn": 37, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1016, + "end": 1046, + "replacementText": "l: number = an_array[Number.MIN_VALUE]" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 20, + "endLine": 31, + "endColumn": 36, + "problem": "ArrayIndexExprType", + "autofix": [ + { + "start": 1029, + "end": 1045, + "replacementText": "Number.MIN_VALUE as int" + } + ], + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 7, + "endLine": 32, + "endColumn": 44, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1053, + "end": 1090, + "replacementText": "m: number = an_array[Number.MAX_SAFE_INTEGER]" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 20, + "endLine": 32, + "endColumn": 43, + "problem": "ArrayIndexExprType", + "autofix": [ + { + "start": 1066, + "end": 1089, + "replacementText": "Number.MAX_SAFE_INTEGER as int" + } + ], + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 5, + "endLine": 35, + "endColumn": 20, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1098, + "end": 1113, + "replacementText": "array: number[] = [1, 2, 3]" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 7, + "endLine": 39, + "endColumn": 14, + "problem": "ArrayIndexExprType", + "autofix": [ + { + "start": 1201, + "end": 1208, + "replacementText": "index_1 as int" + } + ], + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 40, + "column": 7, + "endLine": 40, + "endColumn": 14, + "problem": "ArrayIndexExprType", + "autofix": [ + { + "start": 1217, + "end": 1224, + "replacementText": "index_2 as int" + } + ], + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 50, + "column": 5, + "endLine": 50, + "endColumn": 23, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1391, + "end": 1409, + "replacementText": "array1: number[] = [1, 2, 3]" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 51, + "column": 8, + "endLine": 51, + "endColumn": 18, + "problem": "ArrayIndexExprType", + "autofix": [ + { + "start": 1418, + "end": 1428, + "replacementText": "getIndex() as int" + } + ], + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 53, + "column": 5, + "endLine": 53, + "endColumn": 23, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1436, + "end": 1454, + "replacementText": "array2: number[] = [1, 2, 3]" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 64, + "column": 3, + "endLine": 64, + "endColumn": 12, + "problem": "EnumMemberNonConstInit", + "suggest": "", + "rule": "Enumeration members can be initialized only with compile time expressions of the same type (arkts-no-enum-mixed-types)", + "severity": "ERROR" + }, + { + "line": 67, + "column": 6, + "endLine": 67, + "endColumn": 11, + "problem": "ArrayIndexExprType", + "autofix": [ + { + "start": 1678, + "end": 1683, + "replacementText": "TE.AA as int" + } + ], + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 1, + "endLine": 72, + "endColumn": 9, + "problem": "IndexNegative", + "suggest": "", + "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 6, + "endLine": 73, + "endColumn": 9, + "problem": "ArrayIndexExprType", + "autofix": [ + { + "start": 1744, + "end": 1757, + "replacementText": "1.1 as int" + } + ], + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 81, + "column": 5, + "endLine": 81, + "endColumn": 17, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/main/array_index_expr_type.ets.migrate.ets b/ets2panda/linter/test/main/array_index_expr_type.ets.migrate.ets new file mode 100644 index 0000000000..0d5918aee1 --- /dev/null +++ b/ets2panda/linter/test/main/array_index_expr_type.ets.migrate.ets @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +function foo(index:number){ + let an_array: number[] = [1, 2, 3] + let a: number = an_array[index as int] + let a1: number = an_array[(index + 1) as int] + let a2: number = an_array[(index + 1.1) as int] + let b: number = an_array[1.23 as int] + let c = an_array[true] + let d = an_array['index'] + let e = an_array[undefined] + let f = an_array[null] + let g: number = an_array[] + let h: number = an_array[12. as int] + let i: number = an_array[12.0 as int] + let j: number = an_array[0] + let k: number = an_array[Number.MAX_VALUE as int] + let l: number = an_array[Number.MIN_VALUE as int] + let m: number = an_array[Number.MAX_SAFE_INTEGER as int] +} + +let array: number[] = [1, 2, 3] +const index_1: number = 1.3; +let index_2: number = 1.3; +let index_3: number = 1; +array[index_1 as int]; +array[index_2 as int]; +array[index_3]; +let index_4: int = 2 +array[index_4]; +const index_5: number = 1.0; +array[index_5]; + +function getIndex(): number { + return Math.random() * 10; +} +let array1: number[] = [1, 2, 3]; +array1[getIndex() as int]; + +let array2: number[] = [1, 2, 3]; +for (let i: number = 0; i < array2.length; i++) { + console.log(array2[i]); +} + +for (let i: int = 0; i < array2.length; i++) { + console.log(array2[i]); +} + +let arr1:number[] = [1, 2, 3] +enum TE{ + AA = 1.12 + BB = 0 +} +arr1[TE.AA as int]; +arr1[TE.BB]; +arr1[+0]; +arr1[-0]; +arr1[+1]; +arr1[-1]; +arr1[1.1 as int]; + +let a:short = 1; +let b:byte = 1; +let c:int = 1; +let d:long = 1; + +let arr:number[] = [1,2,3] +arr[true?1.3:1.2] +arr[a] = 1; +arr[b] = 1; +arr[c] = 1; +arr[d] = 1; diff --git a/ets2panda/linter/test/main/array_index_expr_type.ets.migrate.json b/ets2panda/linter/test/main/array_index_expr_type.ets.migrate.json new file mode 100644 index 0000000000..8407a76e0f --- /dev/null +++ b/ets2panda/linter/test/main/array_index_expr_type.ets.migrate.json @@ -0,0 +1,138 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 22, + "column": 7, + "endLine": 22, + "endColumn": 25, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 20, + "endLine": 22, + "endColumn": 24, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 7, + "endLine": 23, + "endColumn": 28, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 20, + "endLine": 23, + "endColumn": 27, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 7, + "endLine": 24, + "endColumn": 30, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 20, + "endLine": 24, + "endColumn": 29, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 7, + "endLine": 25, + "endColumn": 25, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 20, + "endLine": 25, + "endColumn": 24, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 28, + "endLine": 26, + "endColumn": 28, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 64, + "column": 3, + "endLine": 64, + "endColumn": 12, + "problem": "EnumMemberNonConstInit", + "suggest": "", + "rule": "Enumeration members can be initialized only with compile time expressions of the same type (arkts-no-enum-mixed-types)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 1, + "endLine": 72, + "endColumn": 9, + "problem": "IndexNegative", + "suggest": "", + "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", + "severity": "ERROR" + }, + { + "line": 81, + "column": 5, + "endLine": 81, + "endColumn": 17, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/case_expr.ets.arkts2.json b/ets2panda/linter/test/main/case_expr.ets.arkts2.json index feece0064b..6aac05a29b 100755 --- a/ets2panda/linter/test/main/case_expr.ets.arkts2.json +++ b/ets2panda/linter/test/main/case_expr.ets.arkts2.json @@ -61,7 +61,7 @@ "endColumn": 12, "problem": "SwitchExpression", "suggest": "", - "rule": "The switch expression type must be of type number,string or enum (arkts-switch-expr)", + "rule": "The switch expression type must be of type char, byte, short, int, long, string or enum (arkts-switch-expr)", "severity": "ERROR" }, { diff --git a/ets2panda/linter/test/main/catch_clause.ets.args.json b/ets2panda/linter/test/main/catch_clause.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/main/catch_clause.ets.args.json +++ b/ets2panda/linter/test/main/catch_clause.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/main/catch_clause.ets.migrate.ets b/ets2panda/linter/test/main/catch_clause.ets.migrate.ets new file mode 100644 index 0000000000..0559c93caa --- /dev/null +++ b/ets2panda/linter/test/main/catch_clause.ets.migrate.ets @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +try { + if (true) throw "Catch with 'any' type"; +} catch (e) { + console.log(e); +} + +try { + if (true) throw "Catch with 'unknown' type"; +} catch (e) { + console.log(e); +} + +try { + if (true) throw 'Catch without explicit type'; +} catch (e) { + console.log(e); +} diff --git a/ets2panda/linter/test/main/catch_clause.ets.migrate.json b/ets2panda/linter/test/main/catch_clause.ets.migrate.json new file mode 100644 index 0000000000..1ad3035275 --- /dev/null +++ b/ets2panda/linter/test/main/catch_clause.ets.migrate.json @@ -0,0 +1,48 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 13, + "endLine": 17, + "endColumn": 43, + "problem": "ThrowStatement", + "suggest": "", + "rule": "\"throw\" statements cannot accept values of arbitrary types (arkts-limited-throw)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 13, + "endLine": 23, + "endColumn": 47, + "problem": "ThrowStatement", + "suggest": "", + "rule": "\"throw\" statements cannot accept values of arbitrary types (arkts-limited-throw)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 13, + "endLine": 29, + "endColumn": 49, + "problem": "ThrowStatement", + "suggest": "", + "rule": "\"throw\" statements cannot accept values of arbitrary types (arkts-limited-throw)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/class_as_object.ets.arkts2.json b/ets2panda/linter/test/main/class_as_object.ets.arkts2.json index 743b046cc0..368d6ea3ca 100644 --- a/ets2panda/linter/test/main/class_as_object.ets.arkts2.json +++ b/ets2panda/linter/test/main/class_as_object.ets.arkts2.json @@ -234,6 +234,16 @@ "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", "severity": "ERROR" }, + { + "line": 81, + "column": 14, + "endLine": 81, + "endColumn": 35, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, { "line": 87, "column": 10, @@ -344,16 +354,6 @@ "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", "severity": "ERROR" }, - { - "line": 128, - "column": 15, - "endLine": 128, - "endColumn": 23, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, { "line": 129, "column": 15, @@ -774,16 +774,6 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, - { - "line": 178, - "column": 14, - "endLine": 178, - "endColumn": 22, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, { "line": 179, "column": 7, @@ -841,7 +831,7 @@ "endColumn": 12, "problem": "SwitchExpression", "suggest": "", - "rule": "The switch expression type must be of type number,string or enum (arkts-switch-expr)", + "rule": "The switch expression type must be of type char, byte, short, int, long, string or enum (arkts-switch-expr)", "severity": "ERROR" }, { diff --git a/ets2panda/linter/test/main/class_no_constructor.ets b/ets2panda/linter/test/main/class_no_constructor.ets new file mode 100644 index 0000000000..c13aa9b54a --- /dev/null +++ b/ets2panda/linter/test/main/class_no_constructor.ets @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +'use static' + +class A {} + +const variable = new A().constructor diff --git a/ets2panda/linter/test/main/class_no_constructor.ets.args.json b/ets2panda/linter/test/main/class_no_constructor.ets.args.json new file mode 100644 index 0000000000..8a4be28991 --- /dev/null +++ b/ets2panda/linter/test/main/class_no_constructor.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "migrate": "--arkts-2" + } +} diff --git a/ets2panda/linter/test/main/class_no_constructor.ets.arkts2.json b/ets2panda/linter/test/main/class_no_constructor.ets.arkts2.json new file mode 100644 index 0000000000..12f07f6aef --- /dev/null +++ b/ets2panda/linter/test/main/class_no_constructor.ets.arkts2.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 19, + "column": 18, + "endLine": 19, + "endColumn": 37, + "problem": "NoConstructorOnClass", + "suggest": "", + "rule": "The Class object does not have a constructor. (arkts-no-arkts-constructor)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/main/class_no_constructor.ets.json b/ets2panda/linter/test/main/class_no_constructor.ets.json new file mode 100644 index 0000000000..bd1b7140ca --- /dev/null +++ b/ets2panda/linter/test/main/class_no_constructor.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} diff --git a/ets2panda/linter/test/main/class_no_constructor.ets.migrate.ets b/ets2panda/linter/test/main/class_no_constructor.ets.migrate.ets new file mode 100644 index 0000000000..c13aa9b54a --- /dev/null +++ b/ets2panda/linter/test/main/class_no_constructor.ets.migrate.ets @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +'use static' + +class A {} + +const variable = new A().constructor diff --git a/ets2panda/linter/test/main/class_no_constructor.ets.migrate.json b/ets2panda/linter/test/main/class_no_constructor.ets.migrate.json new file mode 100644 index 0000000000..12f07f6aef --- /dev/null +++ b/ets2panda/linter/test/main/class_no_constructor.ets.migrate.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 19, + "column": 18, + "endLine": 19, + "endColumn": 37, + "problem": "NoConstructorOnClass", + "suggest": "", + "rule": "The Class object does not have a constructor. (arkts-no-arkts-constructor)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/main/class_static_block.ets.args.json b/ets2panda/linter/test/main/class_static_block.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/main/class_static_block.ets.args.json +++ b/ets2panda/linter/test/main/class_static_block.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/migrate/class_static_block.sts b/ets2panda/linter/test/main/class_static_block.ets.migrate.ets similarity index 93% rename from ets2panda/linter/test/migrate/class_static_block.sts rename to ets2panda/linter/test/main/class_static_block.ets.migrate.ets index 2e9ad55a38..111e4f30bb 100644 --- a/ets2panda/linter/test/migrate/class_static_block.sts +++ b/ets2panda/linter/test/main/class_static_block.ets.migrate.ets @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -17,12 +17,11 @@ class C { static s: string; static { C.s = 'string'; - } + C.n = C.s.length; +} static n: number; - static { - C.n = C.s.length; - } + } class B { diff --git a/ets2panda/linter/test/sdkwhite/DeclWithDuplicateName5.ets.json b/ets2panda/linter/test/main/class_static_block.ets.migrate.json similarity index 100% rename from ets2panda/linter/test/sdkwhite/DeclWithDuplicateName5.ets.json rename to ets2panda/linter/test/main/class_static_block.ets.migrate.json diff --git a/ets2panda/linter/test/main/class_static_init.ets b/ets2panda/linter/test/main/class_static_init.ets index 29c91f9a86..c74ec693d9 100755 --- a/ets2panda/linter/test/main/class_static_init.ets +++ b/ets2panda/linter/test/main/class_static_init.ets @@ -50,4 +50,128 @@ struct Index { .height('100%') .width('100%') } -} \ No newline at end of file +} + +// Top 0 case +class BB {} + +class AA { + static b: BB; +} + +class CC { + static count: number; +} + +class DD { + static config: { theme: string}; +} + +class EE { + static name: string; + constructor() { + E.name = "default" + } +} + +// Basic Types +class PrimitiveTypes { + static uninitializedString: string; + static uninitializedNumber: number; + static uninitializedBoolean: boolean; +} + +// Array Types +class ArrayTypes { + static uninitializedStringArray: string[]; + static uninitializedNumberArray: number[]; + static uninitializedObjectArray: { id: number }[]; + static uninitializedUnionArray: (string | number)[]; +} + +// Object Types +class ObjectTypes { + static uninitializedSimpleObject: { name: string; age: number }; + static uninitializedNestedObject: { + id: number; + metadata: { + createdAt: Date; + tags: string[]; + }; + }; +} + +// Special Built-in Types +class BuiltInTypes { + static uninitializedDate: Date; + static uninitializedMap: Map; + static uninitializedSet: Set; + static uninitializedPromise: Promise; +} + +// Union and Intersection Types +class AdvancedTypes { + static uninitializedUnion: string | number; + static uninitializedIntersection: { name: string } & { age: number }; + static uninitializedLiteralUnion: 'success' | 'error'; +} + +// Optional and Nullable Types +class NullableTypes { + static uninitializedOptional?: string; + static uninitializedNull: null; + static uninitializedUndefined: undefined; +} + +// Generic Types +class GenericTypes { + static uninitializedGenericArray: T[]; + static uninitializedGenericValue: T; +} + +// Function Types +class FunctionTypes { + static uninitializedFunction: () => void; + static uninitializedCallback: (result: string) => number; +} + +// Complex Combined Types +class ComplexTypes { + static uninitializedComplexArray: Array<{ id: number; data: Map> }>; + static uninitializedRecord: Record; + static uninitializedTuple: [string, number, boolean?]; +} + +// Custom Class Types +class User { + id: number; + name: string; +} + +class CustomClassTypes { + static uninitializedUser: User; + static uninitializedUsers: User[]; +} + +// Enum Types +enum Status { + Active, + Inactive +} + +class EnumTypes { + static uninitializedStatus: Status; + static uninitializedStatusArray: Status[]; +} + +// Never and Unknown Types +class SpecialTypes { + static uninitializedNever: never; + static uninitializedUnknown: unknown; + static uninitializedAny: any; +} + + +class Test1 { + static count: string | undefined; +} diff --git a/ets2panda/linter/test/main/class_static_init.ets.args.json b/ets2panda/linter/test/main/class_static_init.ets.args.json index 3ef4496a81..4e9dc628f7 100755 --- a/ets2panda/linter/test/main/class_static_init.ets.args.json +++ b/ets2panda/linter/test/main/class_static_init.ets.args.json @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "arkts2": "" + "arkts2": "", + "autofix": "--arkts-2" } } diff --git a/ets2panda/linter/test/main/class_static_init.ets.arkts2.json b/ets2panda/linter/test/main/class_static_init.ets.arkts2.json index 2b682eca6e..17db245900 100755 --- a/ets2panda/linter/test/main/class_static_init.ets.arkts2.json +++ b/ets2panda/linter/test/main/class_static_init.ets.arkts2.json @@ -64,6 +64,436 @@ "rule": "The static property has no initializer (arkts-class-static-initialization)", "severity": "ERROR" }, + { + "line": 59, + "column": 3, + "endLine": 59, + "endColumn": 16, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 67, + "column": 3, + "endLine": 67, + "endColumn": 35, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 67, + "column": 18, + "endLine": 67, + "endColumn": 19, + "problem": "ObjectTypeLiteral", + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 3, + "endLine": 71, + "endColumn": 23, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 79, + "column": 3, + "endLine": 79, + "endColumn": 38, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 86, + "column": 3, + "endLine": 86, + "endColumn": 45, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 87, + "column": 3, + "endLine": 87, + "endColumn": 45, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 88, + "column": 3, + "endLine": 88, + "endColumn": 53, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 88, + "column": 36, + "endLine": 88, + "endColumn": 37, + "problem": "ObjectTypeLiteral", + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 89, + "column": 3, + "endLine": 89, + "endColumn": 55, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 94, + "column": 3, + "endLine": 94, + "endColumn": 67, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 94, + "column": 37, + "endLine": 94, + "endColumn": 38, + "problem": "ObjectTypeLiteral", + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 95, + "column": 3, + "endLine": 101, + "endColumn": 5, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 95, + "column": 37, + "endLine": 95, + "endColumn": 38, + "problem": "ObjectTypeLiteral", + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 97, + "column": 15, + "endLine": 97, + "endColumn": 16, + "problem": "ObjectTypeLiteral", + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 106, + "column": 3, + "endLine": 106, + "endColumn": 34, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 107, + "column": 3, + "endLine": 107, + "endColumn": 48, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 108, + "column": 3, + "endLine": 108, + "endColumn": 40, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 109, + "column": 3, + "endLine": 109, + "endColumn": 46, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 114, + "column": 3, + "endLine": 114, + "endColumn": 46, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 115, + "column": 3, + "endLine": 115, + "endColumn": 72, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 115, + "column": 37, + "endLine": 115, + "endColumn": 71, + "problem": "IntersectionType", + "suggest": "", + "rule": "Use inheritance instead of intersection types (arkts-no-intersection-types)", + "severity": "ERROR" + }, + { + "line": 115, + "column": 37, + "endLine": 115, + "endColumn": 38, + "problem": "ObjectTypeLiteral", + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 115, + "column": 56, + "endLine": 115, + "endColumn": 57, + "problem": "ObjectTypeLiteral", + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 116, + "column": 3, + "endLine": 116, + "endColumn": 57, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 128, + "column": 3, + "endLine": 128, + "endColumn": 41, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 129, + "column": 3, + "endLine": 129, + "endColumn": 39, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 134, + "column": 3, + "endLine": 134, + "endColumn": 44, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 135, + "column": 3, + "endLine": 135, + "endColumn": 60, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 140, + "column": 3, + "endLine": 140, + "endColumn": 91, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 140, + "column": 43, + "endLine": 140, + "endColumn": 44, + "problem": "ObjectTypeLiteral", + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 141, + "column": 3, + "endLine": 141, + "endColumn": 65, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 141, + "column": 46, + "endLine": 141, + "endColumn": 47, + "problem": "ObjectTypeLiteral", + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 142, + "column": 3, + "endLine": 142, + "endColumn": 57, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 152, + "column": 3, + "endLine": 152, + "endColumn": 34, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 153, + "column": 3, + "endLine": 153, + "endColumn": 37, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 163, + "column": 3, + "endLine": 163, + "endColumn": 38, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 164, + "column": 3, + "endLine": 164, + "endColumn": 45, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 169, + "column": 3, + "endLine": 169, + "endColumn": 36, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 170, + "column": 3, + "endLine": 170, + "endColumn": 40, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 170, + "column": 32, + "endLine": 170, + "endColumn": 39, + "problem": "UnknownType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 171, + "column": 3, + "endLine": 171, + "endColumn": 32, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 171, + "column": 28, + "endLine": 171, + "endColumn": 31, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, { "line": 42, "column": 2, @@ -103,6 +533,26 @@ "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" + }, + { + "line": 147, + "column": 3, + "endLine": 147, + "endColumn": 5, + "problem": "StrictDiagnostic", + "suggest": "Property 'id' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'id' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 148, + "column": 3, + "endLine": 148, + "endColumn": 7, + "problem": "StrictDiagnostic", + "suggest": "Property 'name' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'name' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/class_static_init.ets.autofix.json b/ets2panda/linter/test/main/class_static_init.ets.autofix.json new file mode 100644 index 0000000000..2be737a16e --- /dev/null +++ b/ets2panda/linter/test/main/class_static_init.ets.autofix.json @@ -0,0 +1,876 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 21, + "column": 3, + "endLine": 21, + "endColumn": 14, + "problem": "ClassstaticInitialization", + "autofix": [ + { + "start": 641, + "end": 652, + "replacementText": "static a: A | undefined = undefined;" + } + ], + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 3, + "endLine": 25, + "endColumn": 14, + "problem": "ClassstaticInitialization", + "autofix": [ + { + "start": 668, + "end": 679, + "replacementText": "static g: G | undefined = undefined;" + } + ], + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 3, + "endLine": 32, + "endColumn": 15, + "problem": "ClassstaticInitialization", + "autofix": [ + { + "start": 753, + "end": 765, + "replacementText": "static g: G | undefined = undefined;" + } + ], + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 36, + "column": 3, + "endLine": 36, + "endColumn": 14, + "problem": "ClassstaticInitialization", + "autofix": [ + { + "start": 781, + "end": 792, + "replacementText": "static a: A | undefined = undefined;" + } + ], + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 46, + "column": 3, + "endLine": 46, + "endColumn": 29, + "problem": "ClassstaticInitialization", + "autofix": [ + { + "start": 933, + "end": 959, + "replacementText": "public static abc: string = \"\";" + } + ], + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 59, + "column": 3, + "endLine": 59, + "endColumn": 16, + "problem": "ClassstaticInitialization", + "autofix": [ + { + "start": 1088, + "end": 1101, + "replacementText": "static b: BB | undefined = undefined;" + } + ], + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 67, + "column": 3, + "endLine": 67, + "endColumn": 35, + "problem": "ClassstaticInitialization", + "autofix": [ + { + "start": 1156, + "end": 1188, + "replacementText": "static config: {\n theme: string;\n} = {\n theme: \"\"\n };" + } + ], + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 67, + "column": 18, + "endLine": 67, + "endColumn": 19, + "problem": "ObjectTypeLiteral", + "autofix": [ + { + "start": 1143, + "end": 1143, + "replacementText": "interface GeneratedTypeLiteralInterface_1 {\n theme: string;\n}\n" + }, + { + "start": 1171, + "end": 1187, + "replacementText": "GeneratedTypeLiteralInterface_1" + } + ], + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 3, + "endLine": 71, + "endColumn": 23, + "problem": "ClassstaticInitialization", + "autofix": [ + { + "start": 1205, + "end": 1225, + "replacementText": "static name: string = \"\";" + } + ], + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 79, + "column": 3, + "endLine": 79, + "endColumn": 38, + "problem": "ClassstaticInitialization", + "autofix": [ + { + "start": 1314, + "end": 1349, + "replacementText": "static uninitializedString: string = \"\";" + } + ], + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 86, + "column": 3, + "endLine": 86, + "endColumn": 45, + "problem": "ClassstaticInitialization", + "autofix": [ + { + "start": 1467, + "end": 1509, + "replacementText": "static uninitializedStringArray: string[] = [];" + } + ], + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 87, + "column": 3, + "endLine": 87, + "endColumn": 45, + "problem": "ClassstaticInitialization", + "autofix": [ + { + "start": 1512, + "end": 1554, + "replacementText": "static uninitializedNumberArray: number[] = [];" + } + ], + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 88, + "column": 3, + "endLine": 88, + "endColumn": 53, + "problem": "ClassstaticInitialization", + "autofix": [ + { + "start": 1557, + "end": 1607, + "replacementText": "static uninitializedObjectArray: {\n id: number;\n }[] = [];" + } + ], + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 88, + "column": 36, + "endLine": 88, + "endColumn": 37, + "problem": "ObjectTypeLiteral", + "autofix": [ + { + "start": 1446, + "end": 1446, + "replacementText": "interface GeneratedTypeLiteralInterface_2 {\n id: number;\n}\n" + }, + { + "start": 1590, + "end": 1604, + "replacementText": "GeneratedTypeLiteralInterface_2" + } + ], + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 89, + "column": 3, + "endLine": 89, + "endColumn": 55, + "problem": "ClassstaticInitialization", + "autofix": [ + { + "start": 1610, + "end": 1662, + "replacementText": "static uninitializedUnionArray: (string | number)[] = [];" + } + ], + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 94, + "column": 3, + "endLine": 94, + "endColumn": 67, + "problem": "ClassstaticInitialization", + "autofix": [ + { + "start": 1704, + "end": 1768, + "replacementText": "static uninitializedSimpleObject: {\n name: string;\n age: number;\n} = {\n name: \"\"\n };" + } + ], + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 94, + "column": 37, + "endLine": 94, + "endColumn": 38, + "problem": "ObjectTypeLiteral", + "autofix": [ + { + "start": 1682, + "end": 1682, + "replacementText": "interface GeneratedTypeLiteralInterface_3 {\n name: string;\n age: number;\n}\n" + }, + { + "start": 1738, + "end": 1767, + "replacementText": "GeneratedTypeLiteralInterface_3" + } + ], + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 95, + "column": 3, + "endLine": 101, + "endColumn": 5, + "problem": "ClassstaticInitialization", + "autofix": [ + { + "start": 1771, + "end": 1895, + "replacementText": "static uninitializedNestedObject: {\n id: number;\n metadata: {\n createdAt: Date;\n tags: string[];\n };\n} = {\n metadata: {\n createdAt: new Date(),\n tags: []\n }\n };" + } + ], + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 95, + "column": 37, + "endLine": 95, + "endColumn": 38, + "problem": "ObjectTypeLiteral", + "autofix": [ + { + "start": 1682, + "end": 1682, + "replacementText": "interface GeneratedTypeLiteralInterface_4 {\n id: number;\n metadata: {\n createdAt: Date;\n tags: string[];\n };\n}\n" + }, + { + "start": 1805, + "end": 1894, + "replacementText": "GeneratedTypeLiteralInterface_4" + } + ], + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 97, + "column": 15, + "endLine": 97, + "endColumn": 16, + "problem": "ObjectTypeLiteral", + "autofix": [ + { + "start": 1682, + "end": 1682, + "replacementText": "interface GeneratedTypeLiteralInterface_5 {\n createdAt: Date;\n tags: string[];\n}\n" + }, + { + "start": 1837, + "end": 1889, + "replacementText": "GeneratedTypeLiteralInterface_5" + } + ], + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 106, + "column": 3, + "endLine": 106, + "endColumn": 34, + "problem": "ClassstaticInitialization", + "autofix": [ + { + "start": 1948, + "end": 1979, + "replacementText": "static uninitializedDate: Date = new Date();" + } + ], + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 107, + "column": 3, + "endLine": 107, + "endColumn": 48, + "problem": "ClassstaticInitialization", + "autofix": [ + { + "start": 1982, + "end": 2027, + "replacementText": "static uninitializedMap: Map = new Map();" + } + ], + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 108, + "column": 3, + "endLine": 108, + "endColumn": 40, + "problem": "ClassstaticInitialization", + "autofix": [ + { + "start": 2030, + "end": 2067, + "replacementText": "static uninitializedSet: Set = new Set();" + } + ], + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 109, + "column": 3, + "endLine": 109, + "endColumn": 46, + "problem": "ClassstaticInitialization", + "autofix": [ + { + "start": 2070, + "end": 2113, + "replacementText": "static uninitializedPromise: Promise = undefined;" + } + ], + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 114, + "column": 3, + "endLine": 114, + "endColumn": 46, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 115, + "column": 3, + "endLine": 115, + "endColumn": 72, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 115, + "column": 37, + "endLine": 115, + "endColumn": 71, + "problem": "IntersectionType", + "suggest": "", + "rule": "Use inheritance instead of intersection types (arkts-no-intersection-types)", + "severity": "ERROR" + }, + { + "line": 115, + "column": 37, + "endLine": 115, + "endColumn": 38, + "problem": "ObjectTypeLiteral", + "autofix": [ + { + "start": 2149, + "end": 2149, + "replacementText": "interface GeneratedTypeLiteralInterface_6 {\n name: string;\n}\n" + }, + { + "start": 2253, + "end": 2269, + "replacementText": "GeneratedTypeLiteralInterface_6" + } + ], + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 115, + "column": 56, + "endLine": 115, + "endColumn": 57, + "problem": "ObjectTypeLiteral", + "autofix": [ + { + "start": 2149, + "end": 2149, + "replacementText": "interface GeneratedTypeLiteralInterface_7 {\n age: number;\n}\n" + }, + { + "start": 2272, + "end": 2287, + "replacementText": "GeneratedTypeLiteralInterface_7" + } + ], + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 116, + "column": 3, + "endLine": 116, + "endColumn": 57, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 128, + "column": 3, + "endLine": 128, + "endColumn": 41, + "problem": "ClassstaticInitialization", + "autofix": [ + { + "start": 2567, + "end": 2605, + "replacementText": "static uninitializedGenericArray: T[] = [];" + } + ], + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 129, + "column": 3, + "endLine": 129, + "endColumn": 39, + "problem": "ClassstaticInitialization", + "autofix": [ + { + "start": 2608, + "end": 2644, + "replacementText": "static uninitializedGenericValue: T | undefined = undefined;" + } + ], + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 134, + "column": 3, + "endLine": 134, + "endColumn": 44, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 135, + "column": 3, + "endLine": 135, + "endColumn": 60, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 140, + "column": 3, + "endLine": 140, + "endColumn": 91, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 140, + "column": 43, + "endLine": 140, + "endColumn": 44, + "problem": "ObjectTypeLiteral", + "autofix": [ + { + "start": 2821, + "end": 2821, + "replacementText": "interface GeneratedTypeLiteralInterface_8 {\n id: number;\n data: Map>;\n}\n" + }, + { + "start": 2884, + "end": 2930, + "replacementText": "GeneratedTypeLiteralInterface_8" + } + ], + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 141, + "column": 3, + "endLine": 141, + "endColumn": 65, + "problem": "ClassstaticInitialization", + "autofix": [ + { + "start": 2935, + "end": 2997, + "replacementText": "static uninitializedRecord: Record | undefined = undefined;" + } + ], + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 141, + "column": 46, + "endLine": 141, + "endColumn": 47, + "problem": "ObjectTypeLiteral", + "autofix": [ + { + "start": 2821, + "end": 2821, + "replacementText": "interface GeneratedTypeLiteralInterface_9 {\n value: number;\n}\n" + }, + { + "start": 2978, + "end": 2995, + "replacementText": "GeneratedTypeLiteralInterface_9" + } + ], + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 142, + "column": 3, + "endLine": 142, + "endColumn": 57, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 152, + "column": 3, + "endLine": 152, + "endColumn": 34, + "problem": "ClassstaticInitialization", + "autofix": [ + { + "start": 3153, + "end": 3184, + "replacementText": "static uninitializedUser: User | undefined = undefined;" + } + ], + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 153, + "column": 3, + "endLine": 153, + "endColumn": 37, + "problem": "ClassstaticInitialization", + "autofix": [ + { + "start": 3187, + "end": 3221, + "replacementText": "static uninitializedUsers: User[] = [];" + } + ], + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 163, + "column": 3, + "endLine": 163, + "endColumn": 38, + "problem": "ClassstaticInitialization", + "autofix": [ + { + "start": 3297, + "end": 3332, + "replacementText": "static uninitializedStatus: Status | undefined = undefined;" + } + ], + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 164, + "column": 3, + "endLine": 164, + "endColumn": 45, + "problem": "ClassstaticInitialization", + "autofix": [ + { + "start": 3335, + "end": 3377, + "replacementText": "static uninitializedStatusArray: Status[] = [];" + } + ], + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 169, + "column": 3, + "endLine": 169, + "endColumn": 36, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 170, + "column": 3, + "endLine": 170, + "endColumn": 40, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 170, + "column": 32, + "endLine": 170, + "endColumn": 39, + "problem": "UnknownType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 171, + "column": 3, + "endLine": 171, + "endColumn": 32, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 171, + "column": 28, + "endLine": 171, + "endColumn": 31, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 42, + "column": 2, + "endLine": 42, + "endColumn": 7, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, State, Text } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 43, + "column": 2, + "endLine": 43, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, State, Text } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 4, + "endLine": 45, + "endColumn": 9, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, State, Text } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 7, + "endLine": 49, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, State, Text } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 147, + "column": 3, + "endLine": 147, + "endColumn": 5, + "problem": "StrictDiagnostic", + "suggest": "Property 'id' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'id' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 148, + "column": 3, + "endLine": 148, + "endColumn": 7, + "problem": "StrictDiagnostic", + "suggest": "Property 'name' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'name' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/class_static_init.ets.json b/ets2panda/linter/test/main/class_static_init.ets.json index ca88f857e9..d9c1c79cdc 100755 --- a/ets2panda/linter/test/main/class_static_init.ets.json +++ b/ets2panda/linter/test/main/class_static_init.ets.json @@ -13,5 +13,146 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "result": [] + "result": [ + { + "line": 67, + "column": 18, + "endLine": 67, + "endColumn": 19, + "problem": "ObjectTypeLiteral", + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 88, + "column": 36, + "endLine": 88, + "endColumn": 37, + "problem": "ObjectTypeLiteral", + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 94, + "column": 37, + "endLine": 94, + "endColumn": 38, + "problem": "ObjectTypeLiteral", + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 95, + "column": 37, + "endLine": 95, + "endColumn": 38, + "problem": "ObjectTypeLiteral", + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 97, + "column": 15, + "endLine": 97, + "endColumn": 16, + "problem": "ObjectTypeLiteral", + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 115, + "column": 37, + "endLine": 115, + "endColumn": 71, + "problem": "IntersectionType", + "suggest": "", + "rule": "Use inheritance instead of intersection types (arkts-no-intersection-types)", + "severity": "ERROR" + }, + { + "line": 115, + "column": 37, + "endLine": 115, + "endColumn": 38, + "problem": "ObjectTypeLiteral", + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 115, + "column": 56, + "endLine": 115, + "endColumn": 57, + "problem": "ObjectTypeLiteral", + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 140, + "column": 43, + "endLine": 140, + "endColumn": 44, + "problem": "ObjectTypeLiteral", + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 141, + "column": 46, + "endLine": 141, + "endColumn": 47, + "problem": "ObjectTypeLiteral", + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 170, + "column": 32, + "endLine": 170, + "endColumn": 39, + "problem": "UnknownType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 171, + "column": 28, + "endLine": 171, + "endColumn": 31, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 147, + "column": 3, + "endLine": 147, + "endColumn": 5, + "problem": "StrictDiagnostic", + "suggest": "Property 'id' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'id' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 148, + "column": 3, + "endLine": 148, + "endColumn": 7, + "problem": "StrictDiagnostic", + "suggest": "Property 'name' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'name' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + } + ] } \ No newline at end of file diff --git a/ets2panda/linter/test/migrate/void_operator.sts b/ets2panda/linter/test/main/collections_module.ets similarity index 45% rename from ets2panda/linter/test/migrate/void_operator.sts rename to ets2panda/linter/test/main/collections_module.ets index 1d0ace9453..5fba982f6b 100644 --- a/ets2panda/linter/test/migrate/void_operator.sts +++ b/ets2panda/linter/test/main/collections_module.ets @@ -13,60 +13,26 @@ * limitations under the License. */ -void 0; +import { collections } from './oh_modules/@arkts.collections'; -void 'hello'; +import { collections as collectionsAlias } from './oh_modules/@arkts.collections'; -void (1 + 2); +import { collections as kitCollections } from './oh_modules/@kit.ArkTS'; -void { a: 1, b: 2 }; +import { collections as definedCollections } from 'user_defined_worker'; //legal -void [1, 2, 3]; +function tesCollectionsUsage() { -void console.log('expression evaluated'); + const collections1: collections.Array = new collections.Array(); -const undefined_value = void 1; + const collections2 = new collectionsAlias.Array(); -const undefined_value2: undefined = void 2; + const collections3 = new kitCollections.Array(); -const undefined_value3: number | undefined = void 3; + let collections4: collectionsAlias.Array; -void void 1; + const collections5: collectionsAlias.Array = new collectionsAlias.Array(); -void function () { - console.log('foo'); -}; + let collections6: definedCollections.Array; // legal -void function () { - console.log("bar!"); -}(); - -void (function () { - console.log('baz!'); -})(); - -void class {}; - -void (class {}); - -void (() => {}); - -function foo() { - let a = 1; - void a++; - - let b = [1, 2, 3]; - void console.log(b.filter(x => x % 2 !== 0)); - - void function() { - console.log('foo'); - }; - - void function localFun() { - console.log('foo'); - }; - - void class {}; - - void class localClass{}; } diff --git a/ets2panda/linter/test/main/collections_module.ets.args.json b/ets2panda/linter/test/main/collections_module.ets.args.json new file mode 100644 index 0000000000..b13bb90d5b --- /dev/null +++ b/ets2panda/linter/test/main/collections_module.ets.args.json @@ -0,0 +1,21 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2", + "migrate": "--arkts-2" + } +} diff --git a/ets2panda/linter/test/main/collections_module.ets.arkts2.json b/ets2panda/linter/test/main/collections_module.ets.arkts2.json new file mode 100644 index 0000000000..584e375a01 --- /dev/null +++ b/ets2panda/linter/test/main/collections_module.ets.arkts2.json @@ -0,0 +1,138 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 10, + "endLine": 16, + "endColumn": 21, + "problem": "NoNeedStdLibSendableContainer", + "suggest": "", + "rule": "Sendable containers are not supported (arkts-no-need-stdlib-sendable-containers)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 10, + "endLine": 18, + "endColumn": 21, + "problem": "NoNeedStdLibSendableContainer", + "suggest": "", + "rule": "Sendable containers are not supported (arkts-no-need-stdlib-sendable-containers)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 25, + "endLine": 18, + "endColumn": 41, + "problem": "NoNeedStdLibSendableContainer", + "suggest": "", + "rule": "Sendable containers are not supported (arkts-no-need-stdlib-sendable-containers)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 10, + "endLine": 20, + "endColumn": 21, + "problem": "NoNeedStdLibSendableContainer", + "suggest": "", + "rule": "Sendable containers are not supported (arkts-no-need-stdlib-sendable-containers)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 25, + "endLine": 20, + "endColumn": 39, + "problem": "NoNeedStdLibSendableContainer", + "suggest": "", + "rule": "Sendable containers are not supported (arkts-no-need-stdlib-sendable-containers)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 23, + "endLine": 26, + "endColumn": 34, + "problem": "NoNeedStdLibSendableContainer", + "suggest": "", + "rule": "Sendable containers are not supported (arkts-no-need-stdlib-sendable-containers)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 55, + "endLine": 26, + "endColumn": 66, + "problem": "NoNeedStdLibSendableContainer", + "suggest": "", + "rule": "Sendable containers are not supported (arkts-no-need-stdlib-sendable-containers)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 28, + "endLine": 28, + "endColumn": 44, + "problem": "NoNeedStdLibSendableContainer", + "suggest": "", + "rule": "Sendable containers are not supported (arkts-no-need-stdlib-sendable-containers)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 28, + "endLine": 30, + "endColumn": 42, + "problem": "NoNeedStdLibSendableContainer", + "suggest": "", + "rule": "Sendable containers are not supported (arkts-no-need-stdlib-sendable-containers)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 21, + "endLine": 32, + "endColumn": 37, + "problem": "NoNeedStdLibSendableContainer", + "suggest": "", + "rule": "Sendable containers are not supported (arkts-no-need-stdlib-sendable-containers)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 23, + "endLine": 34, + "endColumn": 39, + "problem": "NoNeedStdLibSendableContainer", + "suggest": "", + "rule": "Sendable containers are not supported (arkts-no-need-stdlib-sendable-containers)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 60, + "endLine": 34, + "endColumn": 76, + "problem": "NoNeedStdLibSendableContainer", + "suggest": "", + "rule": "Sendable containers are not supported (arkts-no-need-stdlib-sendable-containers)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/main/collections_module.ets.autofix.json b/ets2panda/linter/test/main/collections_module.ets.autofix.json new file mode 100644 index 0000000000..3b091c13f4 --- /dev/null +++ b/ets2panda/linter/test/main/collections_module.ets.autofix.json @@ -0,0 +1,222 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 10, + "endLine": 16, + "endColumn": 21, + "problem": "NoNeedStdLibSendableContainer", + "autofix": [ + { + "start": 605, + "end": 667, + "replacementText": "" + } + ], + "suggest": "", + "rule": "Sendable containers are not supported (arkts-no-need-stdlib-sendable-containers)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 10, + "endLine": 18, + "endColumn": 21, + "problem": "NoNeedStdLibSendableContainer", + "autofix": [ + { + "start": 669, + "end": 751, + "replacementText": "" + } + ], + "suggest": "", + "rule": "Sendable containers are not supported (arkts-no-need-stdlib-sendable-containers)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 25, + "endLine": 18, + "endColumn": 41, + "problem": "NoNeedStdLibSendableContainer", + "autofix": [ + { + "start": 669, + "end": 751, + "replacementText": "" + } + ], + "suggest": "", + "rule": "Sendable containers are not supported (arkts-no-need-stdlib-sendable-containers)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 10, + "endLine": 20, + "endColumn": 21, + "problem": "NoNeedStdLibSendableContainer", + "autofix": [ + { + "start": 753, + "end": 825, + "replacementText": "" + } + ], + "suggest": "", + "rule": "Sendable containers are not supported (arkts-no-need-stdlib-sendable-containers)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 25, + "endLine": 20, + "endColumn": 39, + "problem": "NoNeedStdLibSendableContainer", + "autofix": [ + { + "start": 753, + "end": 825, + "replacementText": "" + } + ], + "suggest": "", + "rule": "Sendable containers are not supported (arkts-no-need-stdlib-sendable-containers)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 23, + "endLine": 26, + "endColumn": 34, + "problem": "NoNeedStdLibSendableContainer", + "autofix": [ + { + "start": 965, + "end": 982, + "replacementText": "Array" + } + ], + "suggest": "", + "rule": "Sendable containers are not supported (arkts-no-need-stdlib-sendable-containers)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 55, + "endLine": 26, + "endColumn": 66, + "problem": "NoNeedStdLibSendableContainer", + "autofix": [ + { + "start": 997, + "end": 1014, + "replacementText": "Array" + } + ], + "suggest": "", + "rule": "Sendable containers are not supported (arkts-no-need-stdlib-sendable-containers)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 28, + "endLine": 28, + "endColumn": 44, + "problem": "NoNeedStdLibSendableContainer", + "autofix": [ + { + "start": 1054, + "end": 1076, + "replacementText": "Array" + } + ], + "suggest": "", + "rule": "Sendable containers are not supported (arkts-no-need-stdlib-sendable-containers)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 28, + "endLine": 30, + "endColumn": 42, + "problem": "NoNeedStdLibSendableContainer", + "autofix": [ + { + "start": 1116, + "end": 1136, + "replacementText": "Array" + } + ], + "suggest": "", + "rule": "Sendable containers are not supported (arkts-no-need-stdlib-sendable-containers)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 21, + "endLine": 32, + "endColumn": 37, + "problem": "NoNeedStdLibSendableContainer", + "autofix": [ + { + "start": 1169, + "end": 1191, + "replacementText": "Array" + } + ], + "suggest": "", + "rule": "Sendable containers are not supported (arkts-no-need-stdlib-sendable-containers)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 23, + "endLine": 34, + "endColumn": 39, + "problem": "NoNeedStdLibSendableContainer", + "autofix": [ + { + "start": 1224, + "end": 1246, + "replacementText": "Array" + } + ], + "suggest": "", + "rule": "Sendable containers are not supported (arkts-no-need-stdlib-sendable-containers)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 60, + "endLine": 34, + "endColumn": 76, + "problem": "NoNeedStdLibSendableContainer", + "autofix": [ + { + "start": 1261, + "end": 1283, + "replacementText": "Array" + } + ], + "suggest": "", + "rule": "Sendable containers are not supported (arkts-no-need-stdlib-sendable-containers)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/sdkwhite/GlobalThisError&TypeQuery.ets.json b/ets2panda/linter/test/main/collections_module.ets.json similarity index 100% rename from ets2panda/linter/test/sdkwhite/GlobalThisError&TypeQuery.ets.json rename to ets2panda/linter/test/main/collections_module.ets.json diff --git a/ets2panda/linter/test/main/collections_module.ets.migrate.ets b/ets2panda/linter/test/main/collections_module.ets.migrate.ets new file mode 100644 index 0000000000..02fc9aaad5 --- /dev/null +++ b/ets2panda/linter/test/main/collections_module.ets.migrate.ets @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + + + +import { collections as definedCollections } from 'user_defined_worker'; //legal + +function tesCollectionsUsage() { + + const collections1: Array = new Array(); + + const collections2: number[] = new Array(); + + const collections3: number[] = new Array(); + + let collections4: Array; + + const collections5: Array = new Array(); + + let collections6: definedCollections.Array; // legal + +} diff --git a/ets2panda/linter/test/main/collections_module.ets.migrate.json b/ets2panda/linter/test/main/collections_module.ets.migrate.json new file mode 100644 index 0000000000..4dcf9e56db --- /dev/null +++ b/ets2panda/linter/test/main/collections_module.ets.migrate.json @@ -0,0 +1,18 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} + diff --git a/ets2panda/linter/test/main/custom_layout.ets b/ets2panda/linter/test/main/custom_layout.ets new file mode 100644 index 0000000000..233a5aaa79 --- /dev/null +++ b/ets2panda/linter/test/main/custom_layout.ets @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@Entry +@Component +struct Index { + build() { + Column() { + CustomLayout1({ builder: ColumnChildren }) + CustomLayout2({ builder: ColumnChildren }) + } + } +} + +@Builder +function ColumnChildren() { + ForEach([1, 2, 3], (index: number) => { //暂不支持lazyForEach的写法 + Text('S' + index) + .fontSize(30) + .width(100) + .height(100) + .borderWidth(2) + .offset({ x: 10, y: 20 }) + }) +} + +@Component +struct CustomLayout1 { + @Builder + doNothingBuilder() { + }; + + @BuilderParam builder: () => void = this.doNothingBuilder; + @State startSize: number = 100; + result: SizeResult = { + width: 0, + height: 0 + }; + + onPlaceChildren(selfLayoutInfo: GeometryInfo, children: Array, constraint: ConstraintSizeOptions) { + let startPos = 300; + children.forEach((child) => { + let pos = startPos - child.measureResult.height; + child.layout({ x: pos, y: pos }) + }) + } + + build() { + this.builder() + } +} + +@Component +struct CustomLayout2 { + @Builder + doNothingBuilder() { + }; + + @BuilderParam builder: () => void = this.doNothingBuilder; + @State startSize: number = 100; + result: SizeResult = { + width: 0, + height: 0 + }; + + onMeasureSize(selfLayoutInfo: GeometryInfo, children: Array, constraint: ConstraintSizeOptions) { + let size = 100; + children.forEach((child) => { + let result: MeasureResult = child.measure({ minHeight: size, minWidth: size, maxWidth: size, maxHeight: size }) + size += result.width / 2 + ; + }) + this.result.width = 100; + this.result.height = 400; + return this.result; + } + + build() { + this.builder() + } +} + +@Component +struct CustomLayout3 { + build { + + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/custom_layout.ets.args.json b/ets2panda/linter/test/main/custom_layout.ets.args.json new file mode 100644 index 0000000000..ef3938e967 --- /dev/null +++ b/ets2panda/linter/test/main/custom_layout.ets.args.json @@ -0,0 +1,21 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2", + "migrate": "--arkts-2" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/data_observation_1.ets.arkts2.json b/ets2panda/linter/test/main/custom_layout.ets.arkts2.json similarity index 61% rename from ets2panda/linter/test/main/data_observation_1.ets.arkts2.json rename to ets2panda/linter/test/main/custom_layout.ets.arkts2.json index da9c036907..7491a643b3 100644 --- a/ets2panda/linter/test/main/data_observation_1.ets.arkts2.json +++ b/ets2panda/linter/test/main/custom_layout.ets.arkts2.json @@ -15,149 +15,109 @@ ], "result": [ { - "line": 55, - "column": 3, - "endLine": 55, - "endColumn": 42, - "problem": "DataObservation", - "suggest": "", - "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", - "severity": "ERROR" - }, - { - "line": 56, - "column": 3, - "endLine": 56, - "endColumn": 44, - "problem": "DataObservation", - "suggest": "", - "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", - "severity": "ERROR" - }, - { - "line": 57, - "column": 3, - "endLine": 57, - "endColumn": 43, - "problem": "DataObservation", - "suggest": "", - "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", - "severity": "ERROR" - }, - { - "line": 58, - "column": 3, - "endLine": 58, - "endColumn": 39, - "problem": "DataObservation", - "suggest": "", - "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", - "severity": "ERROR" - }, - { - "line": 59, - "column": 3, - "endLine": 59, - "endColumn": 41, - "problem": "DataObservation", + "line": 40, + "column": 8, + "endLine": 40, + "endColumn": 21, + "problem": "CustomLayoutNeedAddDecorator", "suggest": "", - "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", + "rule": "Custom components with custom layout capability need to add the \"@Layoutable\" decorator (arkui-custom-layout-need-add-decorator)", "severity": "ERROR" }, { - "line": 61, - "column": 3, - "endLine": 61, - "endColumn": 48, - "problem": "DataObservation", + "line": 53, + "column": 9, + "endLine": 53, + "endColumn": 23, + "problem": "NumericSemantics", "suggest": "", - "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { - "line": 62, - "column": 3, - "endLine": 62, - "endColumn": 41, - "problem": "DataObservation", + "line": 55, + "column": 11, + "endLine": 55, + "endColumn": 54, + "problem": "NumericSemantics", "suggest": "", - "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { - "line": 64, - "column": 3, - "endLine": 64, - "endColumn": 63, - "problem": "DataObservation", + "line": 66, + "column": 8, + "endLine": 66, + "endColumn": 21, + "problem": "CustomLayoutNeedAddDecorator", "suggest": "", - "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", + "rule": "Custom components with custom layout capability need to add the \"@Layoutable\" decorator (arkui-custom-layout-need-add-decorator)", "severity": "ERROR" }, { - "line": 65, - "column": 3, - "endLine": 65, - "endColumn": 73, - "problem": "DataObservation", + "line": 79, + "column": 9, + "endLine": 79, + "endColumn": 19, + "problem": "NumericSemantics", "suggest": "", - "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { - "line": 66, + "line": 97, "column": 3, - "endLine": 66, - "endColumn": 58, - "problem": "DataObservation", + "endLine": 97, + "endColumn": 8, + "problem": "AnyType", "suggest": "", - "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, { - "line": 67, - "column": 3, - "endLine": 67, - "endColumn": 61, - "problem": "DataObservation", + "line": 16, + "column": 2, + "endLine": 16, + "endColumn": 7, + "problem": "UIInterfaceImport", "suggest": "", - "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 76, - "column": 3, - "endLine": 76, - "endColumn": 24, - "problem": "DataObservation", + "line": 17, + "column": 2, + "endLine": 17, + "endColumn": 11, + "problem": "UIInterfaceImport", "suggest": "", - "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 36, - "column": 2, - "endLine": 36, - "endColumn": 10, + "line": 20, + "column": 5, + "endLine": 20, + "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 45, + "line": 27, "column": 2, - "endLine": 45, - "endColumn": 10, + "endLine": 27, + "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 48, - "column": 2, - "endLine": 48, + "line": 29, + "column": 3, + "endLine": 29, "endColumn": 10, "problem": "UIInterfaceImport", "suggest": "", @@ -165,19 +125,19 @@ "severity": "ERROR" }, { - "line": 51, - "column": 2, - "endLine": 51, - "endColumn": 7, + "line": 30, + "column": 5, + "endLine": 30, + "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 52, + "line": 39, "column": 2, - "endLine": 52, + "endLine": 39, "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", @@ -185,29 +145,29 @@ "severity": "ERROR" }, { - "line": 54, + "line": 41, "column": 4, - "endLine": 54, - "endColumn": 9, + "endLine": 41, + "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 55, + "line": 45, "column": 4, - "endLine": 55, - "endColumn": 9, + "endLine": 45, + "endColumn": 16, "problem": "UIInterfaceImport", "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 56, + "line": 46, "column": 4, - "endLine": 56, + "endLine": 46, "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", @@ -215,139 +175,139 @@ "severity": "ERROR" }, { - "line": 57, - "column": 4, - "endLine": 57, - "endColumn": 9, + "line": 47, + "column": 11, + "endLine": 47, + "endColumn": 21, "problem": "UIInterfaceImport", "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 58, - "column": 4, - "endLine": 58, - "endColumn": 9, + "line": 52, + "column": 35, + "endLine": 52, + "endColumn": 47, "problem": "UIInterfaceImport", "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 59, - "column": 4, - "endLine": 59, - "endColumn": 8, + "line": 52, + "column": 65, + "endLine": 52, + "endColumn": 75, "problem": "UIInterfaceImport", "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 60, - "column": 4, - "endLine": 60, - "endColumn": 8, + "line": 52, + "column": 90, + "endLine": 52, + "endColumn": 111, "problem": "UIInterfaceImport", "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 61, - "column": 4, - "endLine": 61, - "endColumn": 8, + "line": 65, + "column": 2, + "endLine": 65, + "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 62, + "line": 67, "column": 4, - "endLine": 62, - "endColumn": 8, + "endLine": 67, + "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 63, + "line": 71, "column": 4, - "endLine": 63, - "endColumn": 11, + "endLine": 71, + "endColumn": 16, "problem": "UIInterfaceImport", "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 64, + "line": 72, "column": 4, - "endLine": 64, - "endColumn": 15, + "endLine": 72, + "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 65, - "column": 4, - "endLine": 65, - "endColumn": 20, + "line": 73, + "column": 11, + "endLine": 73, + "endColumn": 21, "problem": "UIInterfaceImport", "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 66, - "column": 4, - "endLine": 66, - "endColumn": 15, + "line": 78, + "column": 33, + "endLine": 78, + "endColumn": 45, "problem": "UIInterfaceImport", "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 67, - "column": 4, - "endLine": 67, - "endColumn": 20, + "line": 78, + "column": 63, + "endLine": 78, + "endColumn": 73, "problem": "UIInterfaceImport", "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 74, - "column": 2, - "endLine": 74, - "endColumn": 11, + "line": 78, + "column": 88, + "endLine": 78, + "endColumn": 109, "problem": "UIInterfaceImport", "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 76, - "column": 4, - "endLine": 76, - "endColumn": 8, + "line": 81, + "column": 19, + "endLine": 81, + "endColumn": 32, "problem": "UIInterfaceImport", "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 77, - "column": 4, - "endLine": 77, + "line": 95, + "column": 2, + "endLine": 95, "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", diff --git a/ets2panda/linter/test/main/data_observation_1.ets.autofix.json b/ets2panda/linter/test/main/custom_layout.ets.autofix.json similarity index 51% rename from ets2panda/linter/test/main/data_observation_1.ets.autofix.json rename to ets2panda/linter/test/main/custom_layout.ets.autofix.json index 272ff28a6c..05aaabc6d8 100644 --- a/ets2panda/linter/test/main/data_observation_1.ets.autofix.json +++ b/ets2panda/linter/test/main/custom_layout.ets.autofix.json @@ -15,198 +15,145 @@ ], "result": [ { - "line": 55, - "column": 3, - "endLine": 55, - "endColumn": 42, - "problem": "DataObservation", + "line": 40, + "column": 8, + "endLine": 40, + "endColumn": 21, + "problem": "CustomLayoutNeedAddDecorator", "autofix": [ { - "start": 605, - "end": 605, - "replacementText": "@Observed\n" + "start": 1027, + "end": 1027, + "replacementText": "\n@Layoutable" } ], "suggest": "", - "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", + "rule": "Custom components with custom layout capability need to add the \"@Layoutable\" decorator (arkui-custom-layout-need-add-decorator)", "severity": "ERROR" }, { - "line": 56, - "column": 3, - "endLine": 56, - "endColumn": 44, - "problem": "DataObservation", + "line": 53, + "column": 9, + "endLine": 53, + "endColumn": 23, + "problem": "NumericSemantics", "autofix": [ { - "start": 624, - "end": 624, - "replacementText": "@Observed\n" + "start": 1367, + "end": 1381, + "replacementText": "startPos: number = 300" } ], "suggest": "", - "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { - "line": 57, - "column": 3, - "endLine": 57, - "endColumn": 43, - "problem": "DataObservation", + "line": 55, + "column": 11, + "endLine": 55, + "endColumn": 54, + "problem": "NumericSemantics", "autofix": [ { - "start": 760, - "end": 760, - "replacementText": "@Observed\n" - }, - { - "start": 722, - "end": 722, - "replacementText": "@Observed\n" - }, - { - "start": 684, - "end": 684, - "replacementText": "@Observed\n" - }, + "start": 1427, + "end": 1470, + "replacementText": "pos: number = startPos - child.measureResult.height" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 66, + "column": 8, + "endLine": 66, + "endColumn": 21, + "problem": "CustomLayoutNeedAddDecorator", + "autofix": [ { - "start": 664, - "end": 664, - "replacementText": "@Observed\n" + "start": 1571, + "end": 1571, + "replacementText": "\n@Layoutable" } ], "suggest": "", - "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", + "rule": "Custom components with custom layout capability need to add the \"@Layoutable\" decorator (arkui-custom-layout-need-add-decorator)", "severity": "ERROR" }, { - "line": 58, - "column": 3, - "endLine": 58, - "endColumn": 39, - "problem": "DataObservation", + "line": 79, + "column": 9, + "endLine": 79, + "endColumn": 19, + "problem": "NumericSemantics", "autofix": [ { - "start": 854, - "end": 854, - "replacementText": "@Observed\n" + "start": 1909, + "end": 1919, + "replacementText": "size: number = 100" } ], "suggest": "", - "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { - "line": 59, + "line": 97, "column": 3, - "endLine": 59, - "endColumn": 41, - "problem": "DataObservation", + "endLine": 97, + "endColumn": 8, + "problem": "AnyType", "suggest": "", - "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, { - "line": 61, - "column": 3, - "endLine": 61, - "endColumn": 48, - "problem": "DataObservation", + "line": 16, + "column": 2, + "endLine": 16, + "endColumn": 7, + "problem": "UIInterfaceImport", "autofix": [ { - "start": 919, - "end": 919, - "replacementText": "@Observed\n" - }, - { - "start": 938, - "end": 938, - "replacementText": "@Observed\n" + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';" } ], "suggest": "", - "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 62, - "column": 3, - "endLine": 62, - "endColumn": 41, - "problem": "DataObservation", + "line": 17, + "column": 2, + "endLine": 17, + "endColumn": 11, + "problem": "UIInterfaceImport", "autofix": [ { - "start": 957, - "end": 957, - "replacementText": "@Observed\n" + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';" } ], "suggest": "", - "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", - "severity": "ERROR" - }, - { - "line": 64, - "column": 3, - "endLine": 64, - "endColumn": 63, - "problem": "DataObservation", - "suggest": "", - "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", - "severity": "ERROR" - }, - { - "line": 65, - "column": 3, - "endLine": 65, - "endColumn": 73, - "problem": "DataObservation", - "suggest": "", - "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", - "severity": "ERROR" - }, - { - "line": 66, - "column": 3, - "endLine": 66, - "endColumn": 58, - "problem": "DataObservation", - "suggest": "", - "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", - "severity": "ERROR" - }, - { - "line": 67, - "column": 3, - "endLine": 67, - "endColumn": 61, - "problem": "DataObservation", - "suggest": "", - "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", - "severity": "ERROR" - }, - { - "line": 76, - "column": 3, - "endLine": 76, - "endColumn": 24, - "problem": "DataObservation", - "suggest": "", - "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 36, - "column": 2, - "endLine": 36, - "endColumn": 10, + "line": 20, + "column": 5, + "endLine": 20, + "endColumn": 11, "problem": "UIInterfaceImport", "autofix": [ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';" } ], "suggest": "", @@ -214,16 +161,16 @@ "severity": "ERROR" }, { - "line": 45, + "line": 27, "column": 2, - "endLine": 45, - "endColumn": 10, + "endLine": 27, + "endColumn": 9, "problem": "UIInterfaceImport", "autofix": [ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';" } ], "suggest": "", @@ -231,16 +178,16 @@ "severity": "ERROR" }, { - "line": 48, - "column": 2, - "endLine": 48, + "line": 29, + "column": 3, + "endLine": 29, "endColumn": 10, "problem": "UIInterfaceImport", "autofix": [ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';" } ], "suggest": "", @@ -248,16 +195,16 @@ "severity": "ERROR" }, { - "line": 51, - "column": 2, - "endLine": 51, - "endColumn": 7, + "line": 30, + "column": 5, + "endLine": 30, + "endColumn": 9, "problem": "UIInterfaceImport", "autofix": [ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';" } ], "suggest": "", @@ -265,16 +212,16 @@ "severity": "ERROR" }, { - "line": 52, + "line": 39, "column": 2, - "endLine": 52, + "endLine": 39, "endColumn": 11, "problem": "UIInterfaceImport", "autofix": [ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';" } ], "suggest": "", @@ -282,16 +229,16 @@ "severity": "ERROR" }, { - "line": 54, + "line": 41, "column": 4, - "endLine": 54, - "endColumn": 9, + "endLine": 41, + "endColumn": 11, "problem": "UIInterfaceImport", "autofix": [ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';" } ], "suggest": "", @@ -299,16 +246,16 @@ "severity": "ERROR" }, { - "line": 55, + "line": 45, "column": 4, - "endLine": 55, - "endColumn": 9, + "endLine": 45, + "endColumn": 16, "problem": "UIInterfaceImport", "autofix": [ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';" } ], "suggest": "", @@ -316,16 +263,16 @@ "severity": "ERROR" }, { - "line": 56, + "line": 46, "column": 4, - "endLine": 56, + "endLine": 46, "endColumn": 9, "problem": "UIInterfaceImport", "autofix": [ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';" } ], "suggest": "", @@ -333,16 +280,16 @@ "severity": "ERROR" }, { - "line": 57, - "column": 4, - "endLine": 57, - "endColumn": 9, + "line": 47, + "column": 11, + "endLine": 47, + "endColumn": 21, "problem": "UIInterfaceImport", "autofix": [ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';" } ], "suggest": "", @@ -350,16 +297,16 @@ "severity": "ERROR" }, { - "line": 58, - "column": 4, - "endLine": 58, - "endColumn": 9, + "line": 52, + "column": 35, + "endLine": 52, + "endColumn": 47, "problem": "UIInterfaceImport", "autofix": [ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';" } ], "suggest": "", @@ -367,16 +314,16 @@ "severity": "ERROR" }, { - "line": 59, - "column": 4, - "endLine": 59, - "endColumn": 8, + "line": 52, + "column": 65, + "endLine": 52, + "endColumn": 75, "problem": "UIInterfaceImport", "autofix": [ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';" } ], "suggest": "", @@ -384,16 +331,16 @@ "severity": "ERROR" }, { - "line": 60, - "column": 4, - "endLine": 60, - "endColumn": 8, + "line": 52, + "column": 90, + "endLine": 52, + "endColumn": 111, "problem": "UIInterfaceImport", "autofix": [ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';" } ], "suggest": "", @@ -401,16 +348,16 @@ "severity": "ERROR" }, { - "line": 61, - "column": 4, - "endLine": 61, - "endColumn": 8, + "line": 65, + "column": 2, + "endLine": 65, + "endColumn": 11, "problem": "UIInterfaceImport", "autofix": [ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';" } ], "suggest": "", @@ -418,16 +365,16 @@ "severity": "ERROR" }, { - "line": 62, + "line": 67, "column": 4, - "endLine": 62, - "endColumn": 8, + "endLine": 67, + "endColumn": 11, "problem": "UIInterfaceImport", "autofix": [ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';" } ], "suggest": "", @@ -435,16 +382,16 @@ "severity": "ERROR" }, { - "line": 63, + "line": 71, "column": 4, - "endLine": 63, - "endColumn": 11, + "endLine": 71, + "endColumn": 16, "problem": "UIInterfaceImport", "autofix": [ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';" } ], "suggest": "", @@ -452,16 +399,16 @@ "severity": "ERROR" }, { - "line": 64, + "line": 72, "column": 4, - "endLine": 64, - "endColumn": 15, + "endLine": 72, + "endColumn": 9, "problem": "UIInterfaceImport", "autofix": [ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';" } ], "suggest": "", @@ -469,16 +416,16 @@ "severity": "ERROR" }, { - "line": 65, - "column": 4, - "endLine": 65, - "endColumn": 20, + "line": 73, + "column": 11, + "endLine": 73, + "endColumn": 21, "problem": "UIInterfaceImport", "autofix": [ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';" } ], "suggest": "", @@ -486,16 +433,16 @@ "severity": "ERROR" }, { - "line": 66, - "column": 4, - "endLine": 66, - "endColumn": 15, + "line": 78, + "column": 33, + "endLine": 78, + "endColumn": 45, "problem": "UIInterfaceImport", "autofix": [ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';" } ], "suggest": "", @@ -503,16 +450,16 @@ "severity": "ERROR" }, { - "line": 67, - "column": 4, - "endLine": 67, - "endColumn": 20, + "line": 78, + "column": 63, + "endLine": 78, + "endColumn": 73, "problem": "UIInterfaceImport", "autofix": [ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';" } ], "suggest": "", @@ -520,16 +467,16 @@ "severity": "ERROR" }, { - "line": 74, - "column": 2, - "endLine": 74, - "endColumn": 11, + "line": 78, + "column": 88, + "endLine": 78, + "endColumn": 109, "problem": "UIInterfaceImport", "autofix": [ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';" } ], "suggest": "", @@ -537,16 +484,16 @@ "severity": "ERROR" }, { - "line": 76, - "column": 4, - "endLine": 76, - "endColumn": 8, + "line": 81, + "column": 19, + "endLine": 81, + "endColumn": 32, "problem": "UIInterfaceImport", "autofix": [ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';" } ], "suggest": "", @@ -554,16 +501,16 @@ "severity": "ERROR" }, { - "line": 77, - "column": 4, - "endLine": 77, + "line": 95, + "column": 2, + "endLine": 95, "endColumn": 11, "problem": "UIInterfaceImport", "autofix": [ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';" } ], "suggest": "", diff --git a/ets2panda/linter/test/main/custom_layout.ets.json b/ets2panda/linter/test/main/custom_layout.ets.json new file mode 100644 index 0000000000..5d769b466b --- /dev/null +++ b/ets2panda/linter/test/main/custom_layout.ets.json @@ -0,0 +1,38 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 78, + "column": 3, + "endLine": 78, + "endColumn": 16, + "problem": "LimitedReturnTypeInference", + "suggest": "", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "severity": "ERROR" + }, + { + "line": 97, + "column": 3, + "endLine": 97, + "endColumn": 8, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/custom_layout.ets.migrate.ets b/ets2panda/linter/test/main/custom_layout.ets.migrate.ets new file mode 100644 index 0000000000..2d98301abf --- /dev/null +++ b/ets2panda/linter/test/main/custom_layout.ets.migrate.ets @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI'; + +@Entry +@Component +struct Index { + build() { + Column() { + CustomLayout1({ builder: ColumnChildren }) + CustomLayout2({ builder: ColumnChildren }) + } + } +} + +@Builder +function ColumnChildren() { + ForEach([1, 2, 3], (index: number) => { //暂不支持lazyForEach的写法 + Text('S' + index) + .fontSize(30) + .width(100) + .height(100) + .borderWidth(2) + .offset({ x: 10, y: 20 }) + }) +} + +@Component +@Layoutable +struct CustomLayout1 { + @Builder + doNothingBuilder() { + }; + + @BuilderParam builder: () => void = this.doNothingBuilder; + @State startSize: number = 100; + result: SizeResult = { + width: 0, + height: 0 + }; + + onPlaceChildren(selfLayoutInfo: GeometryInfo, children: Array, constraint: ConstraintSizeOptions) { + let startPos: number = 300; + children.forEach((child) => { + let pos: number = startPos - child.measureResult.height; + child.layout({ x: pos, y: pos }) + }) + } + + build() { + this.builder() + } +} + +@Component +@Layoutable +struct CustomLayout2 { + @Builder + doNothingBuilder() { + }; + + @BuilderParam builder: () => void = this.doNothingBuilder; + @State startSize: number = 100; + result: SizeResult = { + width: 0, + height: 0 + }; + + onMeasureSize(selfLayoutInfo: GeometryInfo, children: Array, constraint: ConstraintSizeOptions) { + let size: number = 100; + children.forEach((child) => { + let result: MeasureResult = child.measure({ minHeight: size, minWidth: size, maxWidth: size, maxHeight: size }) + size += result.width / 2 + ; + }) + this.result.width = 100; + this.result.height = 400; + return this.result; + } + + build() { + this.builder() + } +} + +@Component +struct CustomLayout3 { + build { + + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/custom_layout.ets.migrate.json b/ets2panda/linter/test/main/custom_layout.ets.migrate.json new file mode 100644 index 0000000000..6c283c3ef1 --- /dev/null +++ b/ets2panda/linter/test/main/custom_layout.ets.migrate.json @@ -0,0 +1,48 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 42, + "column": 1, + "endLine": 42, + "endColumn": 12, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 69, + "column": 1, + "endLine": 69, + "endColumn": 12, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 101, + "column": 3, + "endLine": 101, + "endColumn": 8, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/debugger_statememt.ets.args.json b/ets2panda/linter/test/main/debugger_statememt.ets.args.json index 5cdfe96f7a..f56752f228 100644 --- a/ets2panda/linter/test/main/debugger_statememt.ets.args.json +++ b/ets2panda/linter/test/main/debugger_statememt.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/debugger_statememt.ets.autofix.json b/ets2panda/linter/test/main/debugger_statememt.ets.autofix.json index f972e0b8b5..6c9d73e3d1 100644 --- a/ets2panda/linter/test/main/debugger_statememt.ets.autofix.json +++ b/ets2panda/linter/test/main/debugger_statememt.ets.autofix.json @@ -24,7 +24,7 @@ { "start": 605, "end": 614, - "replacementText": "specialAutofixLib.debugger()" + "replacementText": "specialAutofixLib.debugger();" } ], "suggest": "", @@ -41,7 +41,7 @@ { "start": 633, "end": 642, - "replacementText": "specialAutofixLib.debugger()" + "replacementText": "specialAutofixLib.debugger();" } ], "suggest": "", diff --git a/ets2panda/linter/test/sdkwhite/InterfaceExtendsClass.ets b/ets2panda/linter/test/main/debugger_statememt.ets.migrate.ets similarity index 84% rename from ets2panda/linter/test/sdkwhite/InterfaceExtendsClass.ets rename to ets2panda/linter/test/main/debugger_statememt.ets.migrate.ets index 6606e1f3b9..04eeeb8969 100644 --- a/ets2panda/linter/test/sdkwhite/InterfaceExtendsClass.ets +++ b/ets2panda/linter/test/main/debugger_statememt.ets.migrate.ets @@ -1,20 +1,22 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { TypedFrameNode } from '@kit.ArkUI'; - -class nodes implements TypedFrameNode{ // Error - -} +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +specialAutofixLib.debugger(); + +function a() { + specialAutofixLib.debugger(); +} + +console.log('debugger'); \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/InterfaceExtendsClass.ets.json b/ets2panda/linter/test/main/debugger_statememt.ets.migrate.json similarity index 100% rename from ets2panda/linter/test/sdkwhite/InterfaceExtendsClass.ets.json rename to ets2panda/linter/test/main/debugger_statememt.ets.migrate.json diff --git a/ets2panda/linter/test/main/default_required_args.ets b/ets2panda/linter/test/main/default_required_args.ets new file mode 100644 index 0000000000..cbccdb42cf --- /dev/null +++ b/ets2panda/linter/test/main/default_required_args.ets @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +function foo(left: number = 0, right: number): number { + return left + right +} + +function foo3(a: number, b: number = 5, c: number): number { + return a + b + c; +} + +function foo4(a: number = 1, b: number = 2, c: number): number { + return a + b + c; +} + +function foo5(a: number = 1, b: number = 2, c: number = 3): number { //legal + return a + b + c; +} + +const bar = (x: boolean = true, y: boolean) => { + return x && y; +}; + +class MyClass { + myMethod(x: number = 0, y: number) { + return x + y; + } +} + +function fooLegal(a: number, b: number = 0): number { //legal + return a + b; +} + +function greetLegal(name: string, message: string = "Hi"): string { //legal + return message + ", " + name; +} + +const barLegal = (x: boolean, y: boolean = false) => { //legal + return x && y; +}; + +function log(level: string = 'info', some: string, message?: string): void { + console.log(`${some} [${level.toUpperCase()}] ${message ?? 'No message'}`); +} + +function config(debug: boolean = true, verbose?: boolean): string { //legal + return `Debug: ${debug ?? false}, Verbose: ${verbose ?? false}`; +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/default_required_args.ets.args.json b/ets2panda/linter/test/main/default_required_args.ets.args.json new file mode 100644 index 0000000000..9b16bb93a4 --- /dev/null +++ b/ets2panda/linter/test/main/default_required_args.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/default_required_args.ets.arkts2.json b/ets2panda/linter/test/main/default_required_args.ets.arkts2.json new file mode 100644 index 0000000000..73fb6559a8 --- /dev/null +++ b/ets2panda/linter/test/main/default_required_args.ets.arkts2.json @@ -0,0 +1,88 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 14, + "endLine": 16, + "endColumn": 18, + "problem": "DefaultArgsBehindRequiredArgs", + "suggest": "", + "rule": "Default parameters must be placed after mandatory parameters (arkts-default-args-behind-required-args)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 26, + "endLine": 20, + "endColumn": 27, + "problem": "DefaultArgsBehindRequiredArgs", + "suggest": "", + "rule": "Default parameters must be placed after mandatory parameters (arkts-default-args-behind-required-args)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 30, + "endLine": 24, + "endColumn": 31, + "problem": "DefaultArgsBehindRequiredArgs", + "suggest": "", + "rule": "Default parameters must be placed after mandatory parameters (arkts-default-args-behind-required-args)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 15, + "endLine": 24, + "endColumn": 16, + "problem": "DefaultArgsBehindRequiredArgs", + "suggest": "", + "rule": "Default parameters must be placed after mandatory parameters (arkts-default-args-behind-required-args)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 14, + "endLine": 32, + "endColumn": 15, + "problem": "DefaultArgsBehindRequiredArgs", + "suggest": "", + "rule": "Default parameters must be placed after mandatory parameters (arkts-default-args-behind-required-args)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 12, + "endLine": 37, + "endColumn": 13, + "problem": "DefaultArgsBehindRequiredArgs", + "suggest": "", + "rule": "Default parameters must be placed after mandatory parameters (arkts-default-args-behind-required-args)", + "severity": "ERROR" + }, + { + "line": 54, + "column": 14, + "endLine": 54, + "endColumn": 19, + "problem": "DefaultArgsBehindRequiredArgs", + "suggest": "", + "rule": "Default parameters must be placed after mandatory parameters (arkts-default-args-behind-required-args)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/default_required_args.ets.json b/ets2panda/linter/test/main/default_required_args.ets.json new file mode 100644 index 0000000000..9f305c86d7 --- /dev/null +++ b/ets2panda/linter/test/main/default_required_args.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} diff --git a/ets2panda/linter/test/main/destructuring_assignments.ets.args.json b/ets2panda/linter/test/main/destructuring_assignments.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/main/destructuring_assignments.ets.args.json +++ b/ets2panda/linter/test/main/destructuring_assignments.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/main/destructuring_assignments.ets.autofix.json b/ets2panda/linter/test/main/destructuring_assignments.ets.autofix.json index 376b05b6dc..a9c281d2f3 100644 --- a/ets2panda/linter/test/main/destructuring_assignments.ets.autofix.json +++ b/ets2panda/linter/test/main/destructuring_assignments.ets.autofix.json @@ -47,7 +47,7 @@ "end": 736 }, { - "replacementText": "a = GeneratedDestructObj_1.a;b = GeneratedDestructObj_1.b;s = GeneratedDestructObj_1.s;", + "replacementText": "\na = GeneratedDestructObj_1.a;\nb = GeneratedDestructObj_1.b;\ns = GeneratedDestructObj_1.s;\n", "start": 737, "end": 737 } @@ -119,7 +119,7 @@ "end": 892 }, { - "replacementText": "a = GeneratedDestructObj_2.a;({ c, d: s } = GeneratedDestructObj_2.b);", + "replacementText": "\na = GeneratedDestructObj_2.a;\n({ c, d: s } = GeneratedDestructObj_2.b);\n", "start": 893, "end": 893 } @@ -213,7 +213,7 @@ "end": 1047 }, { - "replacementText": "a = GeneratedDestructObj_3.a;b = GeneratedDestructObj_3.b;", + "replacementText": "\na = GeneratedDestructObj_3.a;\nb = GeneratedDestructObj_3.b;\n", "start": 1048, "end": 1048 } @@ -235,7 +235,7 @@ "end": 1092 }, { - "replacementText": "a = GeneratedDestructArray_1[0];b = GeneratedDestructArray_1[1];c = GeneratedDestructArray_1[2];", + "replacementText": "\na = GeneratedDestructArray_1[0];\nb = GeneratedDestructArray_1[1];\nc = GeneratedDestructArray_1[2];\n", "start": 1108, "end": 1108 } @@ -267,7 +267,7 @@ "end": 1155 }, { - "replacementText": "[a1, a2] = GeneratedDestructArray_2[0];[b1, b2] = GeneratedDestructArray_2[1];[c1, c2] = GeneratedDestructArray_2[2];", + "replacementText": "\n[a1, a2] = GeneratedDestructArray_2[0];\n[b1, b2] = GeneratedDestructArray_2[1];\n[c1, c2] = GeneratedDestructArray_2[2];\n", "start": 1183, "end": 1183 } @@ -289,7 +289,7 @@ "end": 1192 }, { - "replacementText": "a = GeneratedDestructArray_3[0];b = GeneratedDestructArray_3[1];", + "replacementText": "\na = GeneratedDestructArray_3[0];\nb = GeneratedDestructArray_3[1];\n", "start": 1202, "end": 1202 } @@ -391,7 +391,7 @@ "end": 1506 }, { - "replacementText": "a = GeneratedDestructArray_4[0];b = GeneratedDestructArray_4[1];", + "replacementText": "\na = GeneratedDestructArray_4[0];\nb = GeneratedDestructArray_4[1];\n", "start": 1520, "end": 1520 } @@ -565,7 +565,7 @@ "end": 1953 }, { - "replacementText": "a = GeneratedDestructObj_4.a;[c, d] = GeneratedDestructObj_4.b;", + "replacementText": "\na = GeneratedDestructObj_4.a;\n[c, d] = GeneratedDestructObj_4.b;\n", "start": 1954, "end": 1954 } @@ -597,7 +597,7 @@ "end": 2051 }, { - "replacementText": "a = GeneratedDestructObj_5.a;({\n s,\n c: [d, f],\n } = GeneratedDestructObj_5.b);", + "replacementText": "\na = GeneratedDestructObj_5.a;\n({\n s,\n c: [d, f],\n } = GeneratedDestructObj_5.b);\n", "start": 2052, "end": 2052 } @@ -739,7 +739,7 @@ "end": 2525 }, { - "replacementText": "a = GeneratedDestructObj_6.a;b = GeneratedDestructObj_6.b;s = GeneratedDestructObj_6.s;", + "replacementText": "\na = GeneratedDestructObj_6.a;\nb = GeneratedDestructObj_6.b;\ns = GeneratedDestructObj_6.s;\n", "start": 2526, "end": 2526 } diff --git a/ets2panda/linter/test/migrate/destructuring_assignments.sts b/ets2panda/linter/test/main/destructuring_assignments.ets.migrate.ets similarity index 41% rename from ets2panda/linter/test/migrate/destructuring_assignments.sts rename to ets2panda/linter/test/main/destructuring_assignments.ets.migrate.ets index e40bde0f0b..e3835ceaeb 100644 --- a/ets2panda/linter/test/migrate/destructuring_assignments.sts +++ b/ets2panda/linter/test/main/destructuring_assignments.ets.migrate.ets @@ -16,22 +16,69 @@ // Object destructuring let a = 5, b = 10, c = 15, d = 20, s = 'foo'; let rest, rest2; -({ a, b, s } = { a: 100, b: 200, s: 'bar' }); // NOT OK +interface GeneratedObjectLiteralInterface_2 { + a: number; + b: number; + s: string; +} +let GeneratedDestructObj_1: GeneratedObjectLiteralInterface_2 = { a: 100, b: 200, s: 'bar' }; +a = GeneratedDestructObj_1.a; +b = GeneratedDestructObj_1.b; +s = GeneratedDestructObj_1.s; + // NOT OK ({ a, b, s } = {}); // NOT OK, not fixable ({ a, ...rest } = { a: 1, b: 2 }); // NOT OK -({ a, b: { c, d: s } } = { a: 1, b: { c: 3, d: 'baz' }}); // NOT OK +interface GeneratedObjectLiteralInterface_3 { + c: number; + d: string; +} +interface GeneratedObjectLiteralInterface_6 { + a: number; + b: GeneratedObjectLiteralInterface_3; +} +let GeneratedDestructObj_2: GeneratedObjectLiteralInterface_6 = { a: 1, b: ({ c: 3, d: 'baz' } as GeneratedObjectLiteralInterface_3) }; +a = GeneratedDestructObj_2.a; +let GeneratedDestructObj_7 = GeneratedDestructObj_2.b; +c = GeneratedDestructObj_7.c; +s = GeneratedDestructObj_7.d; + + // NOT OK ({ a, b: { ...rest } } = { a: 1, b: { c: 3, d: 'bah' }}); // NOT OK +interface GeneratedObjectLiteralInterface_1 { + a: number; + b: number; +} function getObject() { - return { a: 1, b: 2 }; + return ({ a: 1, b: 2 } as GeneratedObjectLiteralInterface_1); } -({ a, b } = getObject()); // NOT OK +let GeneratedDestructObj_3 = getObject(); +a = GeneratedDestructObj_3.a; +b = GeneratedDestructObj_3.b; + // NOT OK // Array destructuring -[a, b, c] = [10, 20, 30]; +let GeneratedDestructArray_1 = [10, 20, 30]; +a = GeneratedDestructArray_1[0]; +b = GeneratedDestructArray_1[1]; +c = GeneratedDestructArray_1[2]; + [a, b, c] = []; -[[a1, a2], [b1, b2], [c1, c2]] = [[1, 2], [3, 4], [5, 6]]; -[a, b] = [b, a]; +let GeneratedDestructArray_2 = [[1, 2], [3, 4], [5, 6]]; +a1 = GeneratedDestructArray_2[0][0]; +a2 = GeneratedDestructArray_2[0][1]; + +b1 = GeneratedDestructArray_2[1][0]; +b2 = GeneratedDestructArray_2[1][1]; + +c1 = GeneratedDestructArray_2[2][0]; +c2 = GeneratedDestructArray_2[2][1]; + + +let GeneratedDestructArray_3 = [b, a]; +a = GeneratedDestructArray_3[0]; +b = GeneratedDestructArray_3[1]; + [a, b, ...rest] = [10, 20, 30, 40, 50]; // NOT OK [a, b, [c, d]] = [10, 20, [300, 400], 50]; [a, b, [c, ...rest]] = [10, 20, [30, 40, 50]]; // NOT OK @@ -41,7 +88,10 @@ let tuple: [number, string, number] = [1, '2', 3]; [a, ...rest] = tuple; // NOT OK const getArray = (): number[] => [1, 2, 3]; -[a, b] = getArray(); +let GeneratedDestructArray_4 = getArray(); +a = GeneratedDestructArray_4[0]; +b = GeneratedDestructArray_4[1]; + const set: Set = new Set([1, 2, 3, 4]); [a, b, c] = set; // NOT OK @@ -50,19 +100,43 @@ const map: Map = new Map(); [[a, b], [c, d]] = map; // NOT OK // Mixed destructuring -let e: number, f: number, x: { e: number }, g; +interface GeneratedTypeLiteralInterface_1 { + e: number; +} +let e: number, f: number, x: GeneratedTypeLiteralInterface_1, g; [a, b, [x, { f }]] = [1, 2, [{ e: 20 }, { f: 5 }]]; // NOT OK [a, b, {e, e: f, ...g}] = [1, 2, {e: 10}]; // NOT OK [a, b, ...{length}] = [1, 2, {e: 10}]; // NOT OK -({ a, b : [c, d] } = { a: 1, b: [2, 3] }); // NOT OK -({ - a, - b: { - s, - c: [d, f], - }, -} = { a: 10, b: { s: 'foo', c: [30, 40] } }); // NOT OK +interface GeneratedObjectLiteralInterface_4 { + a: number; + b: number[]; +} +let GeneratedDestructObj_4: GeneratedObjectLiteralInterface_4 = { a: 1, b: [2, 3] }; +a = GeneratedDestructObj_4.a; +let GeneratedDestructArray_5 = GeneratedDestructObj_4.b; +c = GeneratedDestructArray_5[0]; +d = GeneratedDestructArray_5[1]; + + // NOT OK +interface GeneratedObjectLiteralInterface_5 { + s: string; + c: number[]; +} +interface GeneratedObjectLiteralInterface_7 { + a: number; + b: GeneratedObjectLiteralInterface_5; +} +let GeneratedDestructObj_5: GeneratedObjectLiteralInterface_7 = { a: 10, b: ({ s: 'foo', c: [30, 40] } as GeneratedObjectLiteralInterface_5) }; +a = GeneratedDestructObj_5.a; +let GeneratedDestructObj_8 = GeneratedDestructObj_5.b; +s = GeneratedDestructObj_8.s; +let GeneratedDestructArray_6 = GeneratedDestructObj_8.c; +d = GeneratedDestructArray_6[0]; +f = GeneratedDestructArray_6[1]; + + + // NOT OK // test for default value ({ a, b = 7, s } = { a: 100, b: 200, s: 'bar' }); // NOT OK @@ -84,5 +158,9 @@ class C { public s: string = "0000"; } -({ a, b, s } = new C()); // NOT OK +let GeneratedDestructObj_6 = new C(); +a = GeneratedDestructObj_6.a; +b = GeneratedDestructObj_6.b; +s = GeneratedDestructObj_6.s; + // NOT OK diff --git a/ets2panda/linter/test/migrate/destructuring_assignments.ts.json b/ets2panda/linter/test/main/destructuring_assignments.ets.migrate.json similarity index 60% rename from ets2panda/linter/test/migrate/destructuring_assignments.ts.json rename to ets2panda/linter/test/main/destructuring_assignments.ets.migrate.json index ed8cdee78e..9627371dd3 100644 --- a/ets2panda/linter/test/migrate/destructuring_assignments.ts.json +++ b/ets2panda/linter/test/main/destructuring_assignments.ets.migrate.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -35,29 +35,9 @@ "severity": "ERROR" }, { - "line": 19, + "line": 29, "column": 2, - "endLine": 19, - "endColumn": 44, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 19, - "column": 16, - "endLine": 19, - "endColumn": 17, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 20, - "column": 2, - "endLine": 20, + "endLine": 29, "endColumn": 18, "problem": "DestructuringAssignment", "suggest": "", @@ -65,9 +45,9 @@ "severity": "ERROR" }, { - "line": 20, + "line": 29, "column": 16, - "endLine": 20, + "endLine": 29, "endColumn": 17, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -75,9 +55,9 @@ "severity": "ERROR" }, { - "line": 21, + "line": 30, "column": 2, - "endLine": 21, + "endLine": 30, "endColumn": 33, "problem": "DestructuringAssignment", "suggest": "", @@ -85,9 +65,9 @@ "severity": "ERROR" }, { - "line": 21, + "line": 30, "column": 7, - "endLine": 21, + "endLine": 30, "endColumn": 14, "problem": "SpreadOperator", "suggest": "", @@ -95,9 +75,9 @@ "severity": "ERROR" }, { - "line": 22, + "line": 46, "column": 2, - "endLine": 22, + "endLine": 46, "endColumn": 56, "problem": "DestructuringAssignment", "suggest": "", @@ -105,39 +85,9 @@ "severity": "ERROR" }, { - "line": 22, - "column": 26, - "endLine": 22, - "endColumn": 27, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 22, - "column": 37, - "endLine": 22, - "endColumn": 38, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 23, - "column": 2, - "endLine": 23, - "endColumn": 56, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 23, + "line": 46, "column": 12, - "endLine": 23, + "endLine": 46, "endColumn": 19, "problem": "SpreadOperator", "suggest": "", @@ -145,9 +95,9 @@ "severity": "ERROR" }, { - "line": 23, + "line": 46, "column": 26, - "endLine": 23, + "endLine": 46, "endColumn": 27, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -155,39 +105,9 @@ "severity": "ERROR" }, { - "line": 26, - "column": 10, - "endLine": 26, - "endColumn": 11, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 28, - "column": 2, - "endLine": 28, - "endColumn": 24, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 31, - "column": 1, - "endLine": 31, - "endColumn": 25, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 32, + "line": 66, "column": 1, - "endLine": 32, + "endLine": 66, "endColumn": 15, "problem": "DestructuringAssignment", "suggest": "", @@ -195,29 +115,9 @@ "severity": "ERROR" }, { - "line": 33, - "column": 1, - "endLine": 33, - "endColumn": 58, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 34, - "column": 1, - "endLine": 34, - "endColumn": 16, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 35, + "line": 82, "column": 1, - "endLine": 35, + "endLine": 82, "endColumn": 39, "problem": "DestructuringAssignment", "suggest": "", @@ -225,9 +125,9 @@ "severity": "ERROR" }, { - "line": 35, + "line": 82, "column": 8, - "endLine": 35, + "endLine": 82, "endColumn": 15, "problem": "SpreadOperator", "suggest": "", @@ -235,9 +135,9 @@ "severity": "ERROR" }, { - "line": 36, + "line": 83, "column": 1, - "endLine": 36, + "endLine": 83, "endColumn": 42, "problem": "DestructuringAssignment", "suggest": "", @@ -245,9 +145,9 @@ "severity": "ERROR" }, { - "line": 37, + "line": 84, "column": 1, - "endLine": 37, + "endLine": 84, "endColumn": 46, "problem": "DestructuringAssignment", "suggest": "", @@ -255,9 +155,9 @@ "severity": "ERROR" }, { - "line": 37, + "line": 84, "column": 12, - "endLine": 37, + "endLine": 84, "endColumn": 19, "problem": "SpreadOperator", "suggest": "", @@ -265,9 +165,9 @@ "severity": "ERROR" }, { - "line": 40, + "line": 87, "column": 1, - "endLine": 40, + "endLine": 87, "endColumn": 17, "problem": "DestructuringAssignment", "suggest": "", @@ -275,9 +175,9 @@ "severity": "ERROR" }, { - "line": 41, + "line": 88, "column": 1, - "endLine": 41, + "endLine": 88, "endColumn": 21, "problem": "DestructuringAssignment", "suggest": "", @@ -285,9 +185,9 @@ "severity": "ERROR" }, { - "line": 41, + "line": 88, "column": 5, - "endLine": 41, + "endLine": 88, "endColumn": 12, "problem": "SpreadOperator", "suggest": "", @@ -295,19 +195,9 @@ "severity": "ERROR" }, { - "line": 44, - "column": 1, - "endLine": 44, - "endColumn": 20, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 47, + "line": 97, "column": 1, - "endLine": 47, + "endLine": 97, "endColumn": 16, "problem": "DestructuringAssignment", "suggest": "", @@ -315,9 +205,9 @@ "severity": "ERROR" }, { - "line": 50, + "line": 100, "column": 1, - "endLine": 50, + "endLine": 100, "endColumn": 23, "problem": "DestructuringAssignment", "suggest": "", @@ -325,29 +215,19 @@ "severity": "ERROR" }, { - "line": 53, - "column": 30, - "endLine": 53, - "endColumn": 31, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 53, - "column": 45, - "endLine": 53, - "endColumn": 46, + "line": 106, + "column": 63, + "endLine": 106, + "endColumn": 64, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, { - "line": 54, + "line": 107, "column": 1, - "endLine": 54, + "endLine": 107, "endColumn": 51, "problem": "DestructuringAssignment", "suggest": "", @@ -355,9 +235,9 @@ "severity": "ERROR" }, { - "line": 54, + "line": 107, "column": 29, - "endLine": 54, + "endLine": 107, "endColumn": 50, "problem": "ArrayLiteralNoContextType", "suggest": "", @@ -365,19 +245,9 @@ "severity": "ERROR" }, { - "line": 54, - "column": 30, - "endLine": 54, - "endColumn": 31, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 54, + "line": 107, "column": 41, - "endLine": 54, + "endLine": 107, "endColumn": 42, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -385,9 +255,9 @@ "severity": "ERROR" }, { - "line": 55, + "line": 108, "column": 1, - "endLine": 55, + "endLine": 108, "endColumn": 42, "problem": "DestructuringAssignment", "suggest": "", @@ -395,9 +265,9 @@ "severity": "ERROR" }, { - "line": 55, + "line": 108, "column": 18, - "endLine": 55, + "endLine": 108, "endColumn": 22, "problem": "SpreadOperator", "suggest": "", @@ -405,9 +275,9 @@ "severity": "ERROR" }, { - "line": 56, + "line": 109, "column": 1, - "endLine": 56, + "endLine": 109, "endColumn": 38, "problem": "DestructuringAssignment", "suggest": "", @@ -415,9 +285,9 @@ "severity": "ERROR" }, { - "line": 56, + "line": 109, "column": 8, - "endLine": 56, + "endLine": 109, "endColumn": 19, "problem": "SpreadOperator", "suggest": "", @@ -425,9 +295,9 @@ "severity": "ERROR" }, { - "line": 56, + "line": 109, "column": 23, - "endLine": 56, + "endLine": 109, "endColumn": 38, "problem": "ArrayLiteralNoContextType", "suggest": "", @@ -435,9 +305,9 @@ "severity": "ERROR" }, { - "line": 56, + "line": 109, "column": 30, - "endLine": 56, + "endLine": 109, "endColumn": 31, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -445,59 +315,9 @@ "severity": "ERROR" }, { - "line": 58, + "line": 142, "column": 2, - "endLine": 58, - "endColumn": 41, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 58, - "column": 22, - "endLine": 58, - "endColumn": 23, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 59, - "column": 2, - "endLine": 65, - "endColumn": 44, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 65, - "column": 5, - "endLine": 65, - "endColumn": 6, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 65, - "column": 17, - "endLine": 65, - "endColumn": 18, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 68, - "column": 2, - "endLine": 68, + "endLine": 142, "endColumn": 48, "problem": "DestructuringAssignment", "suggest": "", @@ -505,9 +325,9 @@ "severity": "ERROR" }, { - "line": 68, + "line": 142, "column": 20, - "endLine": 68, + "endLine": 142, "endColumn": 21, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -515,9 +335,9 @@ "severity": "ERROR" }, { - "line": 69, + "line": 143, "column": 2, - "endLine": 69, + "endLine": 143, "endColumn": 60, "problem": "DestructuringAssignment", "suggest": "", @@ -525,9 +345,9 @@ "severity": "ERROR" }, { - "line": 69, + "line": 143, "column": 30, - "endLine": 69, + "endLine": 143, "endColumn": 31, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -535,9 +355,9 @@ "severity": "ERROR" }, { - "line": 69, + "line": 143, "column": 41, - "endLine": 69, + "endLine": 143, "endColumn": 42, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -545,9 +365,9 @@ "severity": "ERROR" }, { - "line": 70, + "line": 144, "column": 2, - "endLine": 70, + "endLine": 144, "endColumn": 45, "problem": "DestructuringAssignment", "suggest": "", @@ -555,9 +375,9 @@ "severity": "ERROR" }, { - "line": 70, + "line": 144, "column": 26, - "endLine": 70, + "endLine": 144, "endColumn": 27, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -565,9 +385,9 @@ "severity": "ERROR" }, { - "line": 71, + "line": 145, "column": 2, - "endLine": 77, + "endLine": 151, "endColumn": 44, "problem": "DestructuringAssignment", "suggest": "", @@ -575,9 +395,9 @@ "severity": "ERROR" }, { - "line": 77, + "line": 151, "column": 5, - "endLine": 77, + "endLine": 151, "endColumn": 6, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -585,9 +405,9 @@ "severity": "ERROR" }, { - "line": 77, + "line": 151, "column": 17, - "endLine": 77, + "endLine": 151, "endColumn": 18, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -595,19 +415,9 @@ "severity": "ERROR" }, { - "line": 87, - "column": 2, - "endLine": 87, - "endColumn": 23, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 32, + "line": 66, "column": 2, - "endLine": 32, + "endLine": 66, "endColumn": 3, "problem": "StrictDiagnostic", "suggest": "Type 'undefined' is not assignable to type 'number'.", @@ -615,9 +425,9 @@ "severity": "ERROR" }, { - "line": 32, + "line": 66, "column": 5, - "endLine": 32, + "endLine": 66, "endColumn": 6, "problem": "StrictDiagnostic", "suggest": "Type 'undefined' is not assignable to type 'number'.", @@ -625,9 +435,9 @@ "severity": "ERROR" }, { - "line": 32, + "line": 66, "column": 8, - "endLine": 32, + "endLine": 66, "endColumn": 9, "problem": "StrictDiagnostic", "suggest": "Type 'undefined' is not assignable to type 'number'.", diff --git a/ets2panda/linter/test/main/destructuring_declarations.ets.args.json b/ets2panda/linter/test/main/destructuring_declarations.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/main/destructuring_declarations.ets.args.json +++ b/ets2panda/linter/test/main/destructuring_declarations.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/main/destructuring_declarations.ets.autofix.json b/ets2panda/linter/test/main/destructuring_declarations.ets.autofix.json index a76a73dd10..d4bd32c57f 100644 --- a/ets2panda/linter/test/main/destructuring_declarations.ets.autofix.json +++ b/ets2panda/linter/test/main/destructuring_declarations.ets.autofix.json @@ -27,7 +27,7 @@ "end": 644 }, { - "replacementText": "let a = GeneratedDestructObj_1.a;let b = GeneratedDestructObj_1.b;let c = GeneratedDestructObj_1.c;", + "replacementText": "\nlet a = GeneratedDestructObj_1.a;\nlet b = GeneratedDestructObj_1.b;\nlet c = GeneratedDestructObj_1.c;\n", "start": 676, "end": 676 } @@ -79,7 +79,7 @@ "end": 768 }, { - "replacementText": "let a3 = GeneratedDestructObj_2.a3;let { c3, d3: e3 } = GeneratedDestructObj_2.b3;", + "replacementText": "\nlet a3 = GeneratedDestructObj_2.a3;\nlet { c3, d3: e3 } = GeneratedDestructObj_2.b3;\n", "start": 806, "end": 806 } @@ -193,7 +193,7 @@ "end": 1007 }, { - "replacementText": "let a5 = GeneratedDestructObj_3.a5;let b5 = GeneratedDestructObj_3.b5;", + "replacementText": "\nlet a5 = GeneratedDestructObj_3.a5;\nlet b5 = GeneratedDestructObj_3.b5;\n", "start": 1022, "end": 1022 } @@ -215,7 +215,7 @@ "end": 1075 }, { - "replacementText": "const a6 = GeneratedDestructArray_1[0];const b6 = GeneratedDestructArray_1[1];const c6 = GeneratedDestructArray_1[2];", + "replacementText": "\nconst a6 = GeneratedDestructArray_1[0];\nconst b6 = GeneratedDestructArray_1[1];\nconst c6 = GeneratedDestructArray_1[2];\n", "start": 1091, "end": 1091 } @@ -267,7 +267,7 @@ "end": 1308 }, { - "replacementText": "const [a1, a2] = GeneratedDestructArray_2[0];const [b1, b2] = GeneratedDestructArray_2[1];const [c1, c2] = GeneratedDestructArray_2[2];", + "replacementText": "\nconst [a1, a2] = GeneratedDestructArray_2[0];\nconst [b1, b2] = GeneratedDestructArray_2[1];\nconst [c1, c2] = GeneratedDestructArray_2[2];\n", "start": 1336, "end": 1336 } @@ -289,7 +289,7 @@ "end": 1387 }, { - "replacementText": "const [a1, a2, a3] = GeneratedDestructArray_3[0];const [b1, b2, b3] = GeneratedDestructArray_3[1];const [c1, c2, c3] = GeneratedDestructArray_3[2];", + "replacementText": "\nconst [a1, a2, a3] = GeneratedDestructArray_3[0];\nconst [b1, b2, b3] = GeneratedDestructArray_3[1];\nconst [c1, c2, c3] = GeneratedDestructArray_3[2];\n", "start": 1424, "end": 1424 } @@ -331,7 +331,7 @@ "end": 1603 }, { - "replacementText": "let a12 = GeneratedDestructArray_4[0];let b12 = GeneratedDestructArray_4[1];", + "replacementText": "\nlet a12 = GeneratedDestructArray_4[0];\nlet b12 = GeneratedDestructArray_4[1];\n", "start": 1617, "end": 1617 } @@ -443,7 +443,7 @@ "end": 2055 }, { - "replacementText": "let a18 = GeneratedDestructObj_4.a18;let [c18, d18] = GeneratedDestructObj_4.b18;", + "replacementText": "\nlet a18 = GeneratedDestructObj_4.a18;\nlet [c18, d18] = GeneratedDestructObj_4.b18;\n", "start": 2082, "end": 2082 } @@ -475,7 +475,7 @@ "end": 2151 }, { - "replacementText": "let a19 = GeneratedDestructObj_5.a19;let {\n c19,\n d19: [e19, f19],\n } = GeneratedDestructObj_5.b19;", + "replacementText": "\nlet a19 = GeneratedDestructObj_5.a19;\nlet {\n c19,\n d19: [e19, f19],\n } = GeneratedDestructObj_5.b19;\n", "start": 2202, "end": 2202 } @@ -627,7 +627,7 @@ "end": 2760 }, { - "replacementText": "let a = GeneratedDestructObj_6.a;let b = GeneratedDestructObj_6.b;let s = GeneratedDestructObj_6.s;", + "replacementText": "\nlet a = GeneratedDestructObj_6.a;\nlet b = GeneratedDestructObj_6.b;\nlet s = GeneratedDestructObj_6.s;\n", "start": 2771, "end": 2771 } diff --git a/ets2panda/linter/test/migrate/destructuring_declarations.sts b/ets2panda/linter/test/main/destructuring_declarations.ets.migrate.ets similarity index 39% rename from ets2panda/linter/test/migrate/destructuring_declarations.sts rename to ets2panda/linter/test/main/destructuring_declarations.ets.migrate.ets index 0ee8cd3537..709d135068 100644 --- a/ets2panda/linter/test/migrate/destructuring_declarations.sts +++ b/ets2panda/linter/test/main/destructuring_declarations.ets.migrate.ets @@ -14,33 +14,93 @@ */ // Object destructuring -let { a, b, c } = { a: 100, b: 200, c: 'bar' }; // NOT OK +interface GeneratedObjectLiteralInterface_2 { + a: number; + b: number; + c: string; +} +let GeneratedDestructObj_1: GeneratedObjectLiteralInterface_2 = { a: 100, b: 200, c: 'bar' }; +let a = GeneratedDestructObj_1.a; +let b = GeneratedDestructObj_1.b; +let c = GeneratedDestructObj_1.c; + // NOT OK let { a2, ...rest2 } = { a2: 1, b2: 2 }; // NOT OK -let { a3, b3: { c3, d3: e3 } } = { a3: 1, b3: { c3: 3, d3: 'baz' }}; // NOT OK +interface GeneratedObjectLiteralInterface_3 { + c3: number; + d3: string; +} +interface GeneratedObjectLiteralInterface_6 { + a3: number; + b3: GeneratedObjectLiteralInterface_3; +} +let GeneratedDestructObj_2: GeneratedObjectLiteralInterface_6 = { a3: 1, b3: ({ c3: 3, d3: 'baz' } as GeneratedObjectLiteralInterface_3)}; +let a3 = GeneratedDestructObj_2.a3; +let GeneratedDestructObj_7 = GeneratedDestructObj_2.b3; +let c3 = GeneratedDestructObj_7.c3; +let e3 = GeneratedDestructObj_7.d3; + + // NOT OK let { a4, b4: { ...rest4 } } = { a4: 1, b4: { c4: 3, d4: 'bah' }}; // NOT OK let { a, b, c } = {}; // NOT OK, not fixable +interface GeneratedObjectLiteralInterface_1 { + a5: number; + b5: number; +} function getObject() { - return { a5: 1, b5: 2 }; + return ({ a5: 1, b5: 2 } as GeneratedObjectLiteralInterface_1); } -let { a5, b5 } = getObject(); // NOT OK +let GeneratedDestructObj_3 = getObject(); +let a5 = GeneratedDestructObj_3.a5; +let b5 = GeneratedDestructObj_3.b5; + // NOT OK // Array destructuring -const [a6, b6, c6] = [10, 20, 30]; +const GeneratedDestructArray_1 = [10, 20, 30]; +const a6 = GeneratedDestructArray_1[0]; +const b6 = GeneratedDestructArray_1[1]; +const c6 = GeneratedDestructArray_1[2]; + const [a7, b7, ...rest7] = [10, 20, 30, 40, 50]; // NOT OK const [a8, b8, [c8, e8]] = [10, 20, [300, 400], 50]; const [a9, b9, [c9, ...rest9]] = [10, 20, [30, 40, 50]]; // NOT OK -const [[a1, a2], [b1, b2], [c1, c2]] = [[1, 2], [3, 4], [5, 6]]; -const [[a1, a2, a3], [b1, b2, b3], [c1, c2, c3]] = [[1, 2, 3], [3, 4, 5], [5, 6, 7]]; +const GeneratedDestructArray_2 = [[1, 2], [3, 4], [5, 6]]; +const a1 = GeneratedDestructArray_2[0][0]; +const a2 = GeneratedDestructArray_2[0][1]; + +const b1 = GeneratedDestructArray_2[1][0]; +const b2 = GeneratedDestructArray_2[1][1]; + +const c1 = GeneratedDestructArray_2[2][0]; +const c2 = GeneratedDestructArray_2[2][1]; + + +const GeneratedDestructArray_3 = [[1, 2, 3], [3, 4, 5], [5, 6, 7]]; +const a1 = GeneratedDestructArray_3[0][0]; +const a2 = GeneratedDestructArray_3[0][1]; +const a3 = GeneratedDestructArray_3[0][2]; + +const b1 = GeneratedDestructArray_3[1][0]; +const b2 = GeneratedDestructArray_3[1][1]; +const b3 = GeneratedDestructArray_3[1][2]; + +const c1 = GeneratedDestructArray_3[2][0]; +const c2 = GeneratedDestructArray_3[2][1]; +const c3 = GeneratedDestructArray_3[2][2]; + + let tuple: [number, string, number] = [1, '2', 3]; let [a10, , b10] = tuple; let [a11, ...rest11] = tuple; // NOT OK const getArray = (): number[] => [1, 2, 3]; -let [a12, b12] = getArray(); +let GeneratedDestructArray_4 = getArray(); +let a12 = GeneratedDestructArray_4[0]; +let b12 = GeneratedDestructArray_4[1]; + const set: Set = new Set([1, 2, 3, 4]); let [a13, b13, c13] = set; // NOT OK @@ -53,14 +113,35 @@ let [a15, b15, [x15, { f15 }]] = [1, 2, [{ e15: 20 }, { f15: 5 }]]; // NOT OK let [a16, b16, {e16, e16: f16, ...g16}] = [1, 2, {e16: 10}]; // NOT OK { let [a17, b17, ...{length}] = [1, 2, 3, 4]; } // NOT OK -let { a18, b18: [c18, d18] } = { a18: 1, b18: [2, 3] }; // NOT OK -let { - a19, - b19: { - c19, - d19: [e19, f19], - }, -} = { a19: 10, b19: { c19: 'foo', d19: [30, 40] } }; // NOT OK +interface GeneratedObjectLiteralInterface_4 { + a18: number; + b18: number[]; +} +let GeneratedDestructObj_4: GeneratedObjectLiteralInterface_4 = { a18: 1, b18: [2, 3] }; +let a18 = GeneratedDestructObj_4.a18; +let GeneratedDestructArray_5 = GeneratedDestructObj_4.b18; +let c18 = GeneratedDestructArray_5[0]; +let d18 = GeneratedDestructArray_5[1]; + + // NOT OK +interface GeneratedObjectLiteralInterface_5 { + c19: string; + d19: number[]; +} +interface GeneratedObjectLiteralInterface_7 { + a19: number; + b19: GeneratedObjectLiteralInterface_5; +} +let GeneratedDestructObj_5: GeneratedObjectLiteralInterface_7 = { a19: 10, b19: ({ c19: 'foo', d19: [30, 40] } as GeneratedObjectLiteralInterface_5) }; +let a19 = GeneratedDestructObj_5.a19; +let GeneratedDestructObj_8 = GeneratedDestructObj_5.b19; +let c19 = GeneratedDestructObj_8.c19; +let GeneratedDestructArray_6 = GeneratedDestructObj_8.d19; +let e19 = GeneratedDestructArray_6[0]; +let f19 = GeneratedDestructArray_6[1]; + + + // NOT OK // test for default value let { a, b, c = 9 } = { a: 100, b: 200, c: 'bar' }; // NOT OK @@ -82,4 +163,8 @@ class C { public s: string = "0000"; } -let { a, b, s } = new C(); // NOT OK \ No newline at end of file +let GeneratedDestructObj_6 = new C(); +let a = GeneratedDestructObj_6.a; +let b = GeneratedDestructObj_6.b; +let s = GeneratedDestructObj_6.s; + // NOT OK \ No newline at end of file diff --git a/ets2panda/linter/test/migrate/destructuring_declarations.ts.json b/ets2panda/linter/test/main/destructuring_declarations.ets.migrate.json similarity index 58% rename from ets2panda/linter/test/migrate/destructuring_declarations.ts.json rename to ets2panda/linter/test/main/destructuring_declarations.ets.migrate.json index 2d0805cb0e..825250c726 100644 --- a/ets2panda/linter/test/migrate/destructuring_declarations.ts.json +++ b/ets2panda/linter/test/main/destructuring_declarations.ets.migrate.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -15,29 +15,9 @@ ], "result": [ { - "line": 17, - "column": 5, - "endLine": 17, - "endColumn": 47, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 17, - "column": 19, - "endLine": 17, - "endColumn": 20, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 18, + "line": 27, "column": 5, - "endLine": 18, + "endLine": 27, "endColumn": 40, "problem": "DestructuringDeclaration", "suggest": "", @@ -45,9 +25,9 @@ "severity": "ERROR" }, { - "line": 18, + "line": 27, "column": 24, - "endLine": 18, + "endLine": 27, "endColumn": 25, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -55,39 +35,9 @@ "severity": "ERROR" }, { - "line": 19, - "column": 5, - "endLine": 19, - "endColumn": 68, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 19, - "column": 34, - "endLine": 19, - "endColumn": 35, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 19, - "column": 47, - "endLine": 19, - "endColumn": 48, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 20, + "line": 43, "column": 5, - "endLine": 20, + "endLine": 43, "endColumn": 66, "problem": "DestructuringDeclaration", "suggest": "", @@ -95,9 +45,9 @@ "severity": "ERROR" }, { - "line": 20, + "line": 43, "column": 32, - "endLine": 20, + "endLine": 43, "endColumn": 33, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -105,9 +55,9 @@ "severity": "ERROR" }, { - "line": 20, + "line": 43, "column": 45, - "endLine": 20, + "endLine": 43, "endColumn": 46, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -115,9 +65,9 @@ "severity": "ERROR" }, { - "line": 22, + "line": 45, "column": 5, - "endLine": 22, + "endLine": 45, "endColumn": 21, "problem": "DestructuringDeclaration", "suggest": "", @@ -125,9 +75,9 @@ "severity": "ERROR" }, { - "line": 22, + "line": 45, "column": 19, - "endLine": 22, + "endLine": 45, "endColumn": 20, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -135,39 +85,9 @@ "severity": "ERROR" }, { - "line": 25, - "column": 10, - "endLine": 25, - "endColumn": 11, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 27, - "column": 5, - "endLine": 27, - "endColumn": 29, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 30, + "line": 65, "column": 7, - "endLine": 30, - "endColumn": 34, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 31, - "column": 7, - "endLine": 31, + "endLine": 65, "endColumn": 48, "problem": "DestructuringDeclaration", "suggest": "", @@ -175,9 +95,9 @@ "severity": "ERROR" }, { - "line": 32, + "line": 66, "column": 7, - "endLine": 32, + "endLine": 66, "endColumn": 52, "problem": "DestructuringDeclaration", "suggest": "", @@ -185,9 +105,9 @@ "severity": "ERROR" }, { - "line": 33, + "line": 67, "column": 7, - "endLine": 33, + "endLine": 67, "endColumn": 56, "problem": "DestructuringDeclaration", "suggest": "", @@ -195,29 +115,9 @@ "severity": "ERROR" }, { - "line": 35, - "column": 7, - "endLine": 35, - "endColumn": 64, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 36, - "column": 7, - "endLine": 36, - "endColumn": 85, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 39, + "line": 96, "column": 5, - "endLine": 39, + "endLine": 96, "endColumn": 25, "problem": "DestructuringDeclaration", "suggest": "", @@ -225,9 +125,9 @@ "severity": "ERROR" }, { - "line": 40, + "line": 97, "column": 5, - "endLine": 40, + "endLine": 97, "endColumn": 29, "problem": "DestructuringDeclaration", "suggest": "", @@ -235,19 +135,9 @@ "severity": "ERROR" }, { - "line": 43, - "column": 5, - "endLine": 43, - "endColumn": 28, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 46, + "line": 106, "column": 5, - "endLine": 46, + "endLine": 106, "endColumn": 26, "problem": "DestructuringDeclaration", "suggest": "", @@ -255,9 +145,9 @@ "severity": "ERROR" }, { - "line": 49, + "line": 109, "column": 5, - "endLine": 49, + "endLine": 109, "endColumn": 35, "problem": "DestructuringDeclaration", "suggest": "", @@ -265,9 +155,9 @@ "severity": "ERROR" }, { - "line": 52, + "line": 112, "column": 5, - "endLine": 52, + "endLine": 112, "endColumn": 67, "problem": "DestructuringDeclaration", "suggest": "", @@ -275,9 +165,9 @@ "severity": "ERROR" }, { - "line": 52, + "line": 112, "column": 41, - "endLine": 52, + "endLine": 112, "endColumn": 66, "problem": "ArrayLiteralNoContextType", "suggest": "", @@ -285,9 +175,9 @@ "severity": "ERROR" }, { - "line": 52, + "line": 112, "column": 55, - "endLine": 52, + "endLine": 112, "endColumn": 56, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -295,9 +185,9 @@ "severity": "ERROR" }, { - "line": 53, + "line": 113, "column": 5, - "endLine": 53, + "endLine": 113, "endColumn": 60, "problem": "DestructuringDeclaration", "suggest": "", @@ -305,9 +195,9 @@ "severity": "ERROR" }, { - "line": 53, + "line": 113, "column": 43, - "endLine": 53, + "endLine": 113, "endColumn": 60, "problem": "ArrayLiteralNoContextType", "suggest": "", @@ -315,9 +205,9 @@ "severity": "ERROR" }, { - "line": 53, + "line": 113, "column": 50, - "endLine": 53, + "endLine": 113, "endColumn": 51, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -325,9 +215,9 @@ "severity": "ERROR" }, { - "line": 54, + "line": 114, "column": 7, - "endLine": 54, + "endLine": 114, "endColumn": 45, "problem": "DestructuringDeclaration", "suggest": "", @@ -335,59 +225,9 @@ "severity": "ERROR" }, { - "line": 56, - "column": 5, - "endLine": 56, - "endColumn": 55, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 56, - "column": 32, - "endLine": 56, - "endColumn": 33, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 57, - "column": 5, - "endLine": 63, - "endColumn": 52, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 63, - "column": 5, - "endLine": 63, - "endColumn": 6, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 63, - "column": 21, - "endLine": 63, - "endColumn": 22, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 66, + "line": 147, "column": 5, - "endLine": 66, + "endLine": 147, "endColumn": 51, "problem": "DestructuringDeclaration", "suggest": "", @@ -395,9 +235,9 @@ "severity": "ERROR" }, { - "line": 66, + "line": 147, "column": 23, - "endLine": 66, + "endLine": 147, "endColumn": 24, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -405,9 +245,9 @@ "severity": "ERROR" }, { - "line": 67, + "line": 148, "column": 5, - "endLine": 67, + "endLine": 148, "endColumn": 73, "problem": "DestructuringDeclaration", "suggest": "", @@ -415,9 +255,9 @@ "severity": "ERROR" }, { - "line": 67, + "line": 148, "column": 39, - "endLine": 67, + "endLine": 148, "endColumn": 40, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -425,9 +265,9 @@ "severity": "ERROR" }, { - "line": 67, + "line": 148, "column": 52, - "endLine": 67, + "endLine": 148, "endColumn": 53, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -435,9 +275,9 @@ "severity": "ERROR" }, { - "line": 68, + "line": 149, "column": 5, - "endLine": 68, + "endLine": 149, "endColumn": 33, "problem": "DestructuringDeclaration", "suggest": "", @@ -445,9 +285,9 @@ "severity": "ERROR" }, { - "line": 69, + "line": 150, "column": 5, - "endLine": 69, + "endLine": 150, "endColumn": 60, "problem": "DestructuringDeclaration", "suggest": "", @@ -455,9 +295,9 @@ "severity": "ERROR" }, { - "line": 69, + "line": 150, "column": 37, - "endLine": 69, + "endLine": 150, "endColumn": 38, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -465,9 +305,9 @@ "severity": "ERROR" }, { - "line": 70, + "line": 151, "column": 5, - "endLine": 76, + "endLine": 157, "endColumn": 52, "problem": "DestructuringDeclaration", "suggest": "", @@ -475,9 +315,9 @@ "severity": "ERROR" }, { - "line": 76, + "line": 157, "column": 5, - "endLine": 76, + "endLine": 157, "endColumn": 6, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -485,24 +325,14 @@ "severity": "ERROR" }, { - "line": 76, + "line": 157, "column": 21, - "endLine": 76, + "endLine": 157, "endColumn": 22, "problem": "ObjectLiteralNoContextType", "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" - }, - { - "line": 85, - "column": 5, - "endLine": 85, - "endColumn": 26, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/destructuring_parameters.ets.args.json b/ets2panda/linter/test/main/destructuring_parameters.ets.args.json index 4ce1a4c45c..12b3ca8dec 100644 --- a/ets2panda/linter/test/main/destructuring_parameters.ets.args.json +++ b/ets2panda/linter/test/main/destructuring_parameters.ets.args.json @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/main/destructuring_parameters.ets.migrate.ets b/ets2panda/linter/test/main/destructuring_parameters.ets.migrate.ets new file mode 100644 index 0000000000..5c3acdce95 --- /dev/null +++ b/ets2panda/linter/test/main/destructuring_parameters.ets.migrate.ets @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// issue: 24982: Enable 'autofix' mode for this test to ensure it finishes without crashing + +function drawText({ text = '', position: [x, y] = [0, 0] }): void { // NOT OK + // Draw text +} +drawText({ text: 'Figure 1', position: [10, 20] }); + +interface GeneratedTypeLiteralInterface_1 { + firstName: string; + lastName: string; +} +const hello = ({ // NOT OK + firstName, + lastName, +}: GeneratedTypeLiteralInterface_1): string => `Hello ${firstName} ${lastName}`; +console.log(hello({ firstName: 'Karl', lastName: 'Marks' })); + +interface GeneratedObjectLiteralInterface_1 { + firstName: string; + lastName: string; +} +const person: GeneratedObjectLiteralInterface_1 = { firstName: 'Adam', lastName: 'Smith' }; +console.log(hello(person)); + +interface I { + d: number +} + +function f1({d = 1}: I) { // NOT OK +} +f1({d:2}) + +interface GeneratedTypeLiteralInterface_2 { + d: number; +} +function f2({d = 1}: GeneratedTypeLiteralInterface_2) { // NOT OK +} +f2({d:2}) + +function f3({x, ...y}) { // NOT OK + console.log(x); + Object.keys(y).forEach(k => console.log(k, y[k])) +} +f3({x: 1, b: 2, c: 3}) + +function f4([a, b]): void { + console.log(a, b); +} +f4(['Hello', 'Wolrd']); + +function f5([a, b]: number[]): void { + console.log(a, b); +} +f5([1, 2, 3]); + +function f6([a, [b, c]]): void { + console.log(a, b, c); +} +f6([1, [2, 3]]); + +function f7([a, b, ...c]) { // NOT OK + console.log(a, b, c); +} +f7([1, 2, 3, 4]) + +function f8([a, b, [c, ...d]]) { // NOT OK + console.log(a, b, c, d); +} +f8([1, 2, [3, 4, 5]]) + +function f9([a, {b, c}]): void { // NOT OK + console.log(a, b, c); +} +f9([1, {b: 2, c: 3}]); + +function f10([a, [b, {c: d, e: f}]]): void { // NOT OK + console.log(a, b, d, f); +} +f10([1, [2, {c : 3, e: 4}]]); + +function f11([a, b]: Set): void { // NOT OK + console.log(a, b); +} +f11(new Set([1, 2, 3, 4])); diff --git a/ets2panda/linter/test/main/destructuring_parameters.ets.migrate.json b/ets2panda/linter/test/main/destructuring_parameters.ets.migrate.json new file mode 100644 index 0000000000..ca33c3f499 --- /dev/null +++ b/ets2panda/linter/test/main/destructuring_parameters.ets.migrate.json @@ -0,0 +1,228 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 19, + "endLine": 18, + "endColumn": 59, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 10, + "endLine": 21, + "endColumn": 11, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 16, + "endLine": 30, + "endColumn": 35, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 19, + "endLine": 38, + "endColumn": 25, + "problem": "StructuralIdentity", + "suggest": "", + "rule": "Structural typing is not supported (arkts-no-structural-typing)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 13, + "endLine": 44, + "endColumn": 23, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 51, + "column": 13, + "endLine": 51, + "endColumn": 53, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 55, + "column": 13, + "endLine": 55, + "endColumn": 22, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 57, + "column": 46, + "endLine": 57, + "endColumn": 50, + "problem": "PropertyAccessByIndex", + "suggest": "", + "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", + "severity": "ERROR" + }, + { + "line": 59, + "column": 4, + "endLine": 59, + "endColumn": 5, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 13, + "endLine": 61, + "endColumn": 19, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 66, + "column": 13, + "endLine": 66, + "endColumn": 29, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 13, + "endLine": 71, + "endColumn": 24, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 76, + "column": 13, + "endLine": 76, + "endColumn": 25, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 81, + "column": 13, + "endLine": 81, + "endColumn": 30, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 86, + "column": 13, + "endLine": 86, + "endColumn": 24, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 89, + "column": 4, + "endLine": 89, + "endColumn": 21, + "problem": "ArrayLiteralNoContextType", + "suggest": "", + "rule": "Array literals must contain elements of only inferrable types (arkts-no-noninferrable-arr-literals)", + "severity": "ERROR" + }, + { + "line": 89, + "column": 8, + "endLine": 89, + "endColumn": 9, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 91, + "column": 14, + "endLine": 91, + "endColumn": 36, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + }, + { + "line": 94, + "column": 9, + "endLine": 94, + "endColumn": 27, + "problem": "ArrayLiteralNoContextType", + "suggest": "", + "rule": "Array literals must contain elements of only inferrable types (arkts-no-noninferrable-arr-literals)", + "severity": "ERROR" + }, + { + "line": 94, + "column": 13, + "endLine": 94, + "endColumn": 14, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 96, + "column": 14, + "endLine": 96, + "endColumn": 33, + "problem": "DestructuringParameter", + "suggest": "", + "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/dollar_binding_1.ets b/ets2panda/linter/test/main/dollar_binding_1.ets index 6ba7a322f1..e2b25273da 100644 --- a/ets2panda/linter/test/main/dollar_binding_1.ets +++ b/ets2panda/linter/test/main/dollar_binding_1.ets @@ -16,12 +16,16 @@ @Component struct MyComponent { @State count: number = 0 + @State $$: number = 0 build() { Column() { MyCounter({ count: $count }) + MyCounter({ + count: $$$ + }) } } } diff --git a/ets2panda/linter/test/main/dollar_binding_1.ets.args.json b/ets2panda/linter/test/main/dollar_binding_1.ets.args.json index 60cb1832f2..30973c00a2 100644 --- a/ets2panda/linter/test/main/dollar_binding_1.ets.args.json +++ b/ets2panda/linter/test/main/dollar_binding_1.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/dollar_binding_1.ets.arkts2.json b/ets2panda/linter/test/main/dollar_binding_1.ets.arkts2.json index 2d1bdf9c5a..367b3ca344 100644 --- a/ets2panda/linter/test/main/dollar_binding_1.ets.arkts2.json +++ b/ets2panda/linter/test/main/dollar_binding_1.ets.arkts2.json @@ -15,15 +15,25 @@ ], "result": [ { - "line": 23, + "line": 24, "column": 9, - "endLine": 23, + "endLine": 24, "endColumn": 22, "problem": "DollarBindingNotSupported", "suggest": "", "rule": "\"${variable}\" for decorator binding is not supported (arkui-link-decorator-passing)", "severity": "ERROR" }, + { + "line": 27, + "column": 9, + "endLine": 27, + "endColumn": 19, + "problem": "DollarBindingNotSupported", + "suggest": "", + "rule": "\"${variable}\" for decorator binding is not supported (arkui-link-decorator-passing)", + "severity": "ERROR" + }, { "line": 16, "column": 2, @@ -45,9 +55,19 @@ "severity": "ERROR" }, { - "line": 21, + "line": 19, + "column": 4, + "endLine": 19, + "endColumn": 9, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 22, "column": 5, - "endLine": 21, + "endLine": 22, "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", @@ -55,9 +75,9 @@ "severity": "ERROR" }, { - "line": 29, + "line": 33, "column": 2, - "endLine": 29, + "endLine": 33, "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", @@ -65,9 +85,9 @@ "severity": "ERROR" }, { - "line": 31, + "line": 35, "column": 4, - "endLine": 31, + "endLine": 35, "endColumn": 8, "problem": "UIInterfaceImport", "suggest": "", @@ -75,9 +95,9 @@ "severity": "ERROR" }, { - "line": 34, + "line": 38, "column": 5, - "endLine": 34, + "endLine": 38, "endColumn": 8, "problem": "UIInterfaceImport", "suggest": "", @@ -85,9 +105,9 @@ "severity": "ERROR" }, { - "line": 35, + "line": 39, "column": 7, - "endLine": 35, + "endLine": 39, "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", diff --git a/ets2panda/linter/test/main/dollar_binding_1.ets.autofix.json b/ets2panda/linter/test/main/dollar_binding_1.ets.autofix.json index b07e1eb473..89ffaf32c0 100644 --- a/ets2panda/linter/test/main/dollar_binding_1.ets.autofix.json +++ b/ets2panda/linter/test/main/dollar_binding_1.ets.autofix.json @@ -1,29 +1,29 @@ { "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." ], "result": [ { - "line": 23, + "line": 24, "column": 9, - "endLine": 23, + "endLine": 24, "endColumn": 22, "problem": "DollarBindingNotSupported", "autofix": [ { - "start": 725, - "end": 731, + "start": 749, + "end": 755, "replacementText": "this.count" } ], @@ -31,6 +31,23 @@ "rule": "\"${variable}\" for decorator binding is not supported (arkui-link-decorator-passing)", "severity": "ERROR" }, + { + "line": 27, + "column": 9, + "endLine": 27, + "endColumn": 19, + "problem": "DollarBindingNotSupported", + "autofix": [ + { + "start": 798, + "end": 801, + "replacementText": "this.$$" + } + ], + "suggest": "", + "rule": "\"${variable}\" for decorator binding is not supported (arkui-link-decorator-passing)", + "severity": "ERROR" + }, { "line": 16, "column": 2, @@ -66,9 +83,26 @@ "severity": "ERROR" }, { - "line": 21, + "line": 19, + "column": 4, + "endLine": 19, + "endColumn": 9, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Link, Row, Text } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 22, "column": 5, - "endLine": 21, + "endLine": 22, "endColumn": 11, "problem": "UIInterfaceImport", "autofix": [ @@ -83,9 +117,9 @@ "severity": "ERROR" }, { - "line": 29, + "line": 33, "column": 2, - "endLine": 29, + "endLine": 33, "endColumn": 11, "problem": "UIInterfaceImport", "autofix": [ @@ -100,9 +134,9 @@ "severity": "ERROR" }, { - "line": 31, + "line": 35, "column": 4, - "endLine": 31, + "endLine": 35, "endColumn": 8, "problem": "UIInterfaceImport", "autofix": [ @@ -117,9 +151,9 @@ "severity": "ERROR" }, { - "line": 34, + "line": 38, "column": 5, - "endLine": 34, + "endLine": 38, "endColumn": 8, "problem": "UIInterfaceImport", "autofix": [ @@ -134,9 +168,9 @@ "severity": "ERROR" }, { - "line": 35, + "line": 39, "column": 7, - "endLine": 35, + "endLine": 39, "endColumn": 11, "problem": "UIInterfaceImport", "autofix": [ diff --git a/ets2panda/linter/test/main/dollar_binding_1.ets.migrate.ets b/ets2panda/linter/test/main/dollar_binding_1.ets.migrate.ets new file mode 100644 index 0000000000..244e4156a9 --- /dev/null +++ b/ets2panda/linter/test/main/dollar_binding_1.ets.migrate.ets @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Component, State, Column, Link, Row, Text } from '@kit.ArkUI'; + +@Component +struct MyComponent { + @State count: number = 0 + @State $$: number = 0 + + build() { + Column() { + MyCounter({ + count: this.count + }) + MyCounter({ + count: this.$$ + }) + } + } +} + +@Component +struct MyCounter { + @Link count: number + + build() { + Row() { + Text(`${this.count}`) + } + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/LiteralAsPropertyName2.ets.json b/ets2panda/linter/test/main/dollar_binding_1.ets.migrate.json similarity index 100% rename from ets2panda/linter/test/sdkwhite/LiteralAsPropertyName2.ets.json rename to ets2panda/linter/test/main/dollar_binding_1.ets.migrate.json diff --git a/ets2panda/linter/test/main/dollar_binding_2.ets b/ets2panda/linter/test/main/dollar_binding_2.ets index f776eb8d17..244e4156a9 100644 --- a/ets2panda/linter/test/main/dollar_binding_2.ets +++ b/ets2panda/linter/test/main/dollar_binding_2.ets @@ -18,12 +18,16 @@ import { Component, State, Column, Link, Row, Text } from '@kit.ArkUI'; @Component struct MyComponent { @State count: number = 0 + @State $$: number = 0 build() { Column() { MyCounter({ count: this.count }) + MyCounter({ + count: this.$$ + }) } } } diff --git a/ets2panda/linter/test/main/dollar_binding_2.ets.args.json b/ets2panda/linter/test/main/dollar_binding_2.ets.args.json index 60cb1832f2..30973c00a2 100644 --- a/ets2panda/linter/test/main/dollar_binding_2.ets.args.json +++ b/ets2panda/linter/test/main/dollar_binding_2.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/dollar_binding_2.ets.migrate.ets b/ets2panda/linter/test/main/dollar_binding_2.ets.migrate.ets new file mode 100644 index 0000000000..244e4156a9 --- /dev/null +++ b/ets2panda/linter/test/main/dollar_binding_2.ets.migrate.ets @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Component, State, Column, Link, Row, Text } from '@kit.ArkUI'; + +@Component +struct MyComponent { + @State count: number = 0 + @State $$: number = 0 + + build() { + Column() { + MyCounter({ + count: this.count + }) + MyCounter({ + count: this.$$ + }) + } + } +} + +@Component +struct MyCounter { + @Link count: number + + build() { + Row() { + Text(`${this.count}`) + } + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/OptionalMethod1.ets.json b/ets2panda/linter/test/main/dollar_binding_2.ets.migrate.json similarity index 100% rename from ets2panda/linter/test/sdkwhite/OptionalMethod1.ets.json rename to ets2panda/linter/test/main/dollar_binding_2.ets.migrate.json diff --git a/ets2panda/linter/test/main/double_dollar_binding_1.ets.args.json b/ets2panda/linter/test/main/double_dollar_binding_1.ets.args.json index 5cdfe96f7a..ee0734c0fc 100644 --- a/ets2panda/linter/test/main/double_dollar_binding_1.ets.args.json +++ b/ets2panda/linter/test/main/double_dollar_binding_1.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/double_dollar_binding_1.ets.migrate.ets b/ets2panda/linter/test/main/double_dollar_binding_1.ets.migrate.ets new file mode 100644 index 0000000000..e598afe1a5 --- /dev/null +++ b/ets2panda/linter/test/main/double_dollar_binding_1.ets.migrate.ets @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Component, State, Row, Slider, $$, Checkbox, Blank, Text } from '@kit.ArkUI'; + +@Component +struct MyComponent { + @State value: number = 0 + + build() { + Row() { + Slider({ + value: $$(this.value) + }) + } + } +} + +@Component +struct Test { + @State checked: boolean = false + + build() { + Row() { + Checkbox().select($$(this.checked)) + Blank() + Text(this.checked ? '开启': '关闭') + } + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/SendablePropType.ets.json b/ets2panda/linter/test/main/double_dollar_binding_1.ets.migrate.json similarity index 100% rename from ets2panda/linter/test/sdkwhite/SendablePropType.ets.json rename to ets2panda/linter/test/main/double_dollar_binding_1.ets.migrate.json diff --git a/ets2panda/linter/test/main/double_dollar_binding_2.ets.args.json b/ets2panda/linter/test/main/double_dollar_binding_2.ets.args.json index 5cdfe96f7a..ee0734c0fc 100644 --- a/ets2panda/linter/test/main/double_dollar_binding_2.ets.args.json +++ b/ets2panda/linter/test/main/double_dollar_binding_2.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/double_dollar_binding_2.ets.migrate.ets b/ets2panda/linter/test/main/double_dollar_binding_2.ets.migrate.ets new file mode 100644 index 0000000000..e598afe1a5 --- /dev/null +++ b/ets2panda/linter/test/main/double_dollar_binding_2.ets.migrate.ets @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Component, State, Row, Slider, $$, Checkbox, Blank, Text } from '@kit.ArkUI'; + +@Component +struct MyComponent { + @State value: number = 0 + + build() { + Row() { + Slider({ + value: $$(this.value) + }) + } + } +} + +@Component +struct Test { + @State checked: boolean = false + + build() { + Row() { + Checkbox().select($$(this.checked)) + Blank() + Text(this.checked ? '开启': '关闭') + } + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/ConstructorFuncs.ets.arkts2.json b/ets2panda/linter/test/main/double_dollar_binding_2.ets.migrate.json similarity index 95% rename from ets2panda/linter/test/sdkwhite/ConstructorFuncs.ets.arkts2.json rename to ets2panda/linter/test/main/double_dollar_binding_2.ets.migrate.json index 5e75d5b3e7..ca88f857e9 100644 --- a/ets2panda/linter/test/sdkwhite/ConstructorFuncs.ets.arkts2.json +++ b/ets2panda/linter/test/main/double_dollar_binding_2.ets.migrate.json @@ -13,7 +13,5 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "result": [ - - ] + "result": [] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/double_excla_binding_1.ets.args.json b/ets2panda/linter/test/main/double_excla_binding_1.ets.args.json index 60cb1832f2..30973c00a2 100644 --- a/ets2panda/linter/test/main/double_excla_binding_1.ets.args.json +++ b/ets2panda/linter/test/main/double_excla_binding_1.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/double_excla_binding_1.ets.migrate.ets b/ets2panda/linter/test/main/double_excla_binding_1.ets.migrate.ets new file mode 100644 index 0000000000..30d62a9467 --- /dev/null +++ b/ets2panda/linter/test/main/double_excla_binding_1.ets.migrate.ets @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI'; + +import { MyCard } from './' + +@Component +struct MyComponent1 { + @State value: number = 0 + + build() { + Row() { + Slider({ + value: $$(this.value) + }) + } + } +} + +@Component +struct Test { + @State checked: boolean = false + + build() { + Row() { + Checkbox().select($$(this.checked)) + Blank() + Text(this.checked ? '开启': '关闭') + } + } +} + +@Component +struct MyComponent2 { + @State value: number = 0; + build() { + Row() { + Slider({ + value: this.value!!! + }) + } + } +} + +@Component +struct MyComponent3 { + @State value: number = 0; + build() { + Row() { + Slider({ + value: this.value!!!! + }) + } + } +} + +@Component +struct MyComponent4 { + @State value: number = 0; + build() { + Row() { + Slider({ + value: this.value!!!!! + }) + } + } +} + +@Entry +@ComponentV2 +struct Index { + @Local value: number = 0; + @Local str: string = ''; + + build() { + Column() { + Text(`${this.value}`) + Button(`change value`).onClick(() => { + this.value++; + }) + Star({ + value: this.value, + $value: value => { + this.value = value; + } + }) + MyCard({ + str: this.str, + $str: value => { + this.str = value; + } + }) + } + } +} + + +@ComponentV2 +struct Star { + @Param value: number = 0; + @Event $value: (val: number) => void = (val: number) => {}; + + build() { + Column() { + Text(`${this.value}`) + Button(`change value `).onClick(() => { + this.$value(10); + }) + } + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/double_excla_binding_1.ets.migrate.json b/ets2panda/linter/test/main/double_excla_binding_1.ets.migrate.json new file mode 100644 index 0000000000..c697fe6484 --- /dev/null +++ b/ets2panda/linter/test/main/double_excla_binding_1.ets.migrate.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 102, + "column": 15, + "endLine": 102, + "endColumn": 20, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/double_excla_binding_2.ets.args.json b/ets2panda/linter/test/main/double_excla_binding_2.ets.args.json index 60cb1832f2..30973c00a2 100644 --- a/ets2panda/linter/test/main/double_excla_binding_2.ets.args.json +++ b/ets2panda/linter/test/main/double_excla_binding_2.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/double_excla_binding_2.ets.migrate.ets b/ets2panda/linter/test/main/double_excla_binding_2.ets.migrate.ets new file mode 100644 index 0000000000..3f5d8563a9 --- /dev/null +++ b/ets2panda/linter/test/main/double_excla_binding_2.ets.migrate.ets @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI'; + +import { MyCard } from './' + +@Component +struct MyComponent { + @State value: number = 0 + + build() { + Row() { + Slider({ + value: $$(this.value) + }) + } + } +} + +@Component +struct Test { + @State checked: boolean = false + + build() { + Row() { + Checkbox().select($$(this.checked)) + Blank() + Text(this.checked ? '开启': '关闭') + } + } +} + +@Component +struct MyComponent2 { + @State value: number = 0; + build() { + Row() { + Slider({ + value: this.value!!! + }) + } + } +} + +@Component +struct MyComponent3 { + @State value: number = 0; + build() { + Row() { + Slider({ + value: this.value!!!! + }) + } + } +} + +@Component +struct MyComponent4 { + @State value: number = 0; + build() { + Row() { + Slider({ + value: this.value!!!!! + }) + } + } +} + +@Entry +@ComponentV2 +struct Index { + @Local value: number = 0; + + build() { + Column() { + Text(`${this.value}`) + Button(`change value`).onClick(() => { + this.value++; + }) + Star({ + value: this.value, + $value: value => { + this.value = value; + } + }) + MyCard({ + str: this.str, + $str: value => { + this.str = value; + } + }) + } + } +} + + +@ComponentV2 +struct Star { + @Param value: number = 0; + @Event $value: (val: number) => void = (val: number) => {}; + + build() { + Column() { + Text(`${this.value}`) + Button(`change value `).onClick(() => { + this.$value(10); + }) + } + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/double_excla_binding_2.ets.migrate.json b/ets2panda/linter/test/main/double_excla_binding_2.ets.migrate.json new file mode 100644 index 0000000000..9ce7a7e139 --- /dev/null +++ b/ets2panda/linter/test/main/double_excla_binding_2.ets.migrate.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 101, + "column": 15, + "endLine": 101, + "endColumn": 20, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test10_1.ets b/ets2panda/linter/test/main/entry_annotation_test10_1.ets index 898d571593..1e06295870 100644 --- a/ets2panda/linter/test/main/entry_annotation_test10_1.ets +++ b/ets2panda/linter/test/main/entry_annotation_test10_1.ets @@ -1,25 +1,25 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; -import { getLocalStorage } from './storage-manager'; - -@Entry({storage: getLocalStorage(1)}) -@Component -struct MyPage { - build() { - Text("Hello World") - } +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; +import { getLocalStorage } from './storage-manager'; + +@Entry({storage: getLocalStorage(1)}) +@Component +struct MyPage { + build() { + Text("Hello World") + } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test10_1.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test10_1.ets.args.json index 66e8f07a19..95b475ab3c 100644 --- a/ets2panda/linter/test/main/entry_annotation_test10_1.ets.args.json +++ b/ets2panda/linter/test/main/entry_annotation_test10_1.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test10_1.ets.autofix.json b/ets2panda/linter/test/main/entry_annotation_test10_1.ets.autofix.json index e47b36f325..dbe2ad5dbe 100644 --- a/ets2panda/linter/test/main/entry_annotation_test10_1.ets.autofix.json +++ b/ets2panda/linter/test/main/entry_annotation_test10_1.ets.autofix.json @@ -1,35 +1,35 @@ -{ - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "result": [ - { - "line": 19, - "column": 1, - "endLine": 19, - "endColumn": 38, - "problem": "EntryAnnotation", - "autofix": [ - { - "start": 756, - "end": 793, - "replacementText": "const __get_local_storage__ = (): LocalStorage => getLocalStorage(1);\n@Entry({ storage: \"__get_local_storage__\" })" - } - ], - "suggest": "", - "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", - "severity": "ERROR" - } - ] +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 38, + "problem": "EntryAnnotation", + "autofix": [ + { + "start": 738, + "end": 775, + "replacementText": "const __get_local_storage__ = (): LocalStorage => getLocalStorage(1);\n@Entry({ storage: \"__get_local_storage__\" })" + } + ], + "suggest": "", + "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", + "severity": "ERROR" + } + ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test10_1.ets.migrate.ets b/ets2panda/linter/test/main/entry_annotation_test10_1.ets.migrate.ets new file mode 100644 index 0000000000..59b5cc120a --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test10_1.ets.migrate.ets @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; +import { getLocalStorage } from './storage-manager'; + +const __get_local_storage__ = (): LocalStorage => getLocalStorage(1); +@Entry({ storage: "__get_local_storage__" }) +@Component +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/DeclWithDuplicateName5.ets.arkts2.json b/ets2panda/linter/test/main/entry_annotation_test10_1.ets.migrate.json similarity index 95% rename from ets2panda/linter/test/sdkwhite/DeclWithDuplicateName5.ets.arkts2.json rename to ets2panda/linter/test/main/entry_annotation_test10_1.ets.migrate.json index 5e75d5b3e7..ca88f857e9 100644 --- a/ets2panda/linter/test/sdkwhite/DeclWithDuplicateName5.ets.arkts2.json +++ b/ets2panda/linter/test/main/entry_annotation_test10_1.ets.migrate.json @@ -13,7 +13,5 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "result": [ - - ] + "result": [] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test10_2.ets b/ets2panda/linter/test/main/entry_annotation_test10_2.ets index b6345be4c3..59984ecfef 100644 --- a/ets2panda/linter/test/main/entry_annotation_test10_2.ets +++ b/ets2panda/linter/test/main/entry_annotation_test10_2.ets @@ -1,26 +1,26 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; -import { getLocalStorage } from './storage-manager'; - -const __get_local_storage__ = (): LocalStorage => getLocalStorage(1); -@Entry({storage: "__get_local_storage__"}) -@Component -struct MyPage { - build() { - Text("Hello World") - } +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; +import { getLocalStorage } from './storage-manager'; + +const __get_local_storage__ = (): LocalStorage => getLocalStorage(1); +@Entry({storage: "__get_local_storage__"}) +@Component +struct MyPage { + build() { + Text("Hello World") + } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test10_2.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test10_2.ets.args.json index 66e8f07a19..95b475ab3c 100644 --- a/ets2panda/linter/test/main/entry_annotation_test10_2.ets.args.json +++ b/ets2panda/linter/test/main/entry_annotation_test10_2.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test10_2.ets.migrate.ets b/ets2panda/linter/test/main/entry_annotation_test10_2.ets.migrate.ets new file mode 100644 index 0000000000..b6345be4c3 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test10_2.ets.migrate.ets @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; +import { getLocalStorage } from './storage-manager'; + +const __get_local_storage__ = (): LocalStorage => getLocalStorage(1); +@Entry({storage: "__get_local_storage__"}) +@Component +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/ComputedPropertyName.ets.arkts2.json b/ets2panda/linter/test/main/entry_annotation_test10_2.ets.migrate.json similarity index 95% rename from ets2panda/linter/test/sdkwhite/ComputedPropertyName.ets.arkts2.json rename to ets2panda/linter/test/main/entry_annotation_test10_2.ets.migrate.json index 5e75d5b3e7..ca88f857e9 100644 --- a/ets2panda/linter/test/sdkwhite/ComputedPropertyName.ets.arkts2.json +++ b/ets2panda/linter/test/main/entry_annotation_test10_2.ets.migrate.json @@ -13,7 +13,5 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "result": [ - - ] + "result": [] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test1_1.ets b/ets2panda/linter/test/main/entry_annotation_test1_1.ets index e62f535cac..1d6b599d24 100644 --- a/ets2panda/linter/test/main/entry_annotation_test1_1.ets +++ b/ets2panda/linter/test/main/entry_annotation_test1_1.ets @@ -1,24 +1,24 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Entry, Component, Text } from '@ohos.arkui.components'; - -@Entry -@Component -struct MyPage { - build() { - Text("Hello World") - } +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text } from '@ohos.arkui.components'; + +@Entry +@Component +struct MyPage { + build() { + Text("Hello World") + } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test1_1.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test1_1.ets.args.json index 66e8f07a19..95b475ab3c 100644 --- a/ets2panda/linter/test/main/entry_annotation_test1_1.ets.args.json +++ b/ets2panda/linter/test/main/entry_annotation_test1_1.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/DeclWithDuplicateName5.ets b/ets2panda/linter/test/main/entry_annotation_test1_1.ets.migrate.ets similarity index 82% rename from ets2panda/linter/test/sdkwhite/DeclWithDuplicateName5.ets rename to ets2panda/linter/test/main/entry_annotation_test1_1.ets.migrate.ets index fb83e2bfe2..e62f535cac 100644 --- a/ets2panda/linter/test/sdkwhite/DeclWithDuplicateName5.ets +++ b/ets2panda/linter/test/main/entry_annotation_test1_1.ets.migrate.ets @@ -13,11 +13,12 @@ * limitations under the License. */ +import { Entry, Component, Text } from '@ohos.arkui.components'; + @Entry @Component -struct Index { - fontStyleAttr1: TextStyle = new TextStyle({ fontColor: Color.Blue }); // Error +struct MyPage { build() { - Text() + Text("Hello World") } -} +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test1_1.ets.migrate.json b/ets2panda/linter/test/main/entry_annotation_test1_1.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test1_1.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test1_2.ets b/ets2panda/linter/test/main/entry_annotation_test1_2.ets index e62f535cac..1d6b599d24 100644 --- a/ets2panda/linter/test/main/entry_annotation_test1_2.ets +++ b/ets2panda/linter/test/main/entry_annotation_test1_2.ets @@ -1,24 +1,24 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Entry, Component, Text } from '@ohos.arkui.components'; - -@Entry -@Component -struct MyPage { - build() { - Text("Hello World") - } +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text } from '@ohos.arkui.components'; + +@Entry +@Component +struct MyPage { + build() { + Text("Hello World") + } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test1_2.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test1_2.ets.args.json index 66e8f07a19..95b475ab3c 100644 --- a/ets2panda/linter/test/main/entry_annotation_test1_2.ets.args.json +++ b/ets2panda/linter/test/main/entry_annotation_test1_2.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test1_2.ets.migrate.ets b/ets2panda/linter/test/main/entry_annotation_test1_2.ets.migrate.ets new file mode 100644 index 0000000000..e62f535cac --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test1_2.ets.migrate.ets @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text } from '@ohos.arkui.components'; + +@Entry +@Component +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test1_2.ets.migrate.json b/ets2panda/linter/test/main/entry_annotation_test1_2.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test1_2.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test2_1.ets b/ets2panda/linter/test/main/entry_annotation_test2_1.ets index 09b330e06c..8a6b6e367a 100644 --- a/ets2panda/linter/test/main/entry_annotation_test2_1.ets +++ b/ets2panda/linter/test/main/entry_annotation_test2_1.ets @@ -1,25 +1,25 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; - -const storage = new LocalStorage(); -@Entry(storage) -@Component -struct MyPage { - build() { - Text("Hello World") - } +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const storage = new LocalStorage(); +@Entry(storage) +@Component +struct MyPage { + build() { + Text("Hello World") + } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test2_1.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test2_1.ets.args.json index 66e8f07a19..95b475ab3c 100644 --- a/ets2panda/linter/test/main/entry_annotation_test2_1.ets.args.json +++ b/ets2panda/linter/test/main/entry_annotation_test2_1.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test2_1.ets.autofix.json b/ets2panda/linter/test/main/entry_annotation_test2_1.ets.autofix.json index 5fcc9d49f5..5430117ee1 100644 --- a/ets2panda/linter/test/main/entry_annotation_test2_1.ets.autofix.json +++ b/ets2panda/linter/test/main/entry_annotation_test2_1.ets.autofix.json @@ -1,55 +1,55 @@ -{ - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "result": [ - { - "line": 18, - "column": 7, - "endLine": 18, - "endColumn": 35, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 18, - "column": 21, - "endLine": 18, - "endColumn": 33, - "problem": "DynamicCtorCall", - "suggest": "", - "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", - "severity": "ERROR" - }, - { - "line": 19, - "column": 1, - "endLine": 19, - "endColumn": 16, - "problem": "EntryAnnotation", - "autofix": [ - { - "start": 739, - "end": 754, - "replacementText": "const __get_local_storage__ = (): LocalStorage => storage;\n@Entry({ storage: \"__get_local_storage__\" })" - } - ], - "suggest": "", - "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", - "severity": "ERROR" - } - ] +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 7, + "endLine": 18, + "endColumn": 35, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 21, + "endLine": 18, + "endColumn": 33, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 16, + "problem": "EntryAnnotation", + "autofix": [ + { + "start": 721, + "end": 736, + "replacementText": "const __get_local_storage__ = (): LocalStorage => storage;\n@Entry({ storage: \"__get_local_storage__\" })" + } + ], + "suggest": "", + "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", + "severity": "ERROR" + } + ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test2_1.ets.migrate.ets b/ets2panda/linter/test/main/entry_annotation_test2_1.ets.migrate.ets new file mode 100644 index 0000000000..1a7d2611b8 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test2_1.ets.migrate.ets @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const storage = new LocalStorage(); +const __get_local_storage__ = (): LocalStorage => storage; +@Entry({ storage: "__get_local_storage__" }) +@Component +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test2_1.ets.migrate.json b/ets2panda/linter/test/main/entry_annotation_test2_1.ets.migrate.json new file mode 100644 index 0000000000..d9d95f3937 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test2_1.ets.migrate.json @@ -0,0 +1,38 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 7, + "endLine": 18, + "endColumn": 35, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 21, + "endLine": 18, + "endColumn": 33, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test2_2.ets b/ets2panda/linter/test/main/entry_annotation_test2_2.ets index 52bd3e4f78..b188329f6f 100644 --- a/ets2panda/linter/test/main/entry_annotation_test2_2.ets +++ b/ets2panda/linter/test/main/entry_annotation_test2_2.ets @@ -1,25 +1,25 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; - -const storage = new LocalStorage(); -const __get_local_storage__ = (): LocalStorage => storage; -@Entry({storage: "__get_local_storage__"}) -struct MyPage { - build() { - Text("Hello World") - } +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const storage = new LocalStorage(); +const __get_local_storage__ = (): LocalStorage => storage; +@Entry({storage: "__get_local_storage__"}) +struct MyPage { + build() { + Text("Hello World") + } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test2_2.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test2_2.ets.args.json index 66e8f07a19..95b475ab3c 100644 --- a/ets2panda/linter/test/main/entry_annotation_test2_2.ets.args.json +++ b/ets2panda/linter/test/main/entry_annotation_test2_2.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test2_2.ets.migrate.ets b/ets2panda/linter/test/main/entry_annotation_test2_2.ets.migrate.ets new file mode 100644 index 0000000000..52bd3e4f78 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test2_2.ets.migrate.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const storage = new LocalStorage(); +const __get_local_storage__ = (): LocalStorage => storage; +@Entry({storage: "__get_local_storage__"}) +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test2_2.ets.migrate.json b/ets2panda/linter/test/main/entry_annotation_test2_2.ets.migrate.json new file mode 100644 index 0000000000..d9d95f3937 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test2_2.ets.migrate.json @@ -0,0 +1,38 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 7, + "endLine": 18, + "endColumn": 35, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 21, + "endLine": 18, + "endColumn": 33, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test3_1.ets b/ets2panda/linter/test/main/entry_annotation_test3_1.ets index 6dbca25bda..adae2542f2 100644 --- a/ets2panda/linter/test/main/entry_annotation_test3_1.ets +++ b/ets2panda/linter/test/main/entry_annotation_test3_1.ets @@ -1,24 +1,24 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; - -@Entry(new LocalStorage()) -@Component -struct MyPage { - build() { - Text("Hello World") - } +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +@Entry(new LocalStorage()) +@Component +struct MyPage { + build() { + Text("Hello World") + } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test3_1.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test3_1.ets.args.json index 66e8f07a19..95b475ab3c 100644 --- a/ets2panda/linter/test/main/entry_annotation_test3_1.ets.args.json +++ b/ets2panda/linter/test/main/entry_annotation_test3_1.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test3_1.ets.autofix.json b/ets2panda/linter/test/main/entry_annotation_test3_1.ets.autofix.json index b61a99047a..177c74ca80 100644 --- a/ets2panda/linter/test/main/entry_annotation_test3_1.ets.autofix.json +++ b/ets2panda/linter/test/main/entry_annotation_test3_1.ets.autofix.json @@ -1,45 +1,45 @@ -{ - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "result": [ - { - "line": 18, - "column": 1, - "endLine": 18, - "endColumn": 27, - "problem": "EntryAnnotation", - "autofix": [ - { - "start": 702, - "end": 728, - "replacementText": "const __get_local_storage__ = (): LocalStorage => new LocalStorage();\n@Entry({ storage: \"__get_local_storage__\" })" - } - ], - "suggest": "", - "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", - "severity": "ERROR" - }, - { - "line": 18, - "column": 12, - "endLine": 18, - "endColumn": 24, - "problem": "DynamicCtorCall", - "suggest": "", - "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", - "severity": "ERROR" - } - ] +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 27, + "problem": "EntryAnnotation", + "autofix": [ + { + "start": 685, + "end": 711, + "replacementText": "const __get_local_storage__ = (): LocalStorage => new LocalStorage();\n@Entry({ storage: \"__get_local_storage__\" })" + } + ], + "suggest": "", + "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 12, + "endLine": 18, + "endColumn": 24, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + } + ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test3_1.ets.migrate.ets b/ets2panda/linter/test/main/entry_annotation_test3_1.ets.migrate.ets new file mode 100644 index 0000000000..3d30dad8c7 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test3_1.ets.migrate.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const __get_local_storage__ = (): LocalStorage => new LocalStorage(); +@Entry({ storage: "__get_local_storage__" }) +@Component +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test3_1.ets.migrate.json b/ets2panda/linter/test/main/entry_annotation_test3_1.ets.migrate.json new file mode 100644 index 0000000000..8ecb23f92c --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test3_1.ets.migrate.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 55, + "endLine": 18, + "endColumn": 67, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test3_2.ets b/ets2panda/linter/test/main/entry_annotation_test3_2.ets index 5d9cf9c567..14d0661094 100644 --- a/ets2panda/linter/test/main/entry_annotation_test3_2.ets +++ b/ets2panda/linter/test/main/entry_annotation_test3_2.ets @@ -1,25 +1,25 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; - -const __get_local_storage__ = (): LocalStorage => new LocalStorage(); -@Entry({storage: "__get_local_storage__"}) -@Component -struct MyPage { - build() { - Text("Hello World") - } +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const __get_local_storage__ = (): LocalStorage => new LocalStorage(); +@Entry({storage: "__get_local_storage__"}) +@Component +struct MyPage { + build() { + Text("Hello World") + } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test3_2.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test3_2.ets.args.json index 66e8f07a19..95b475ab3c 100644 --- a/ets2panda/linter/test/main/entry_annotation_test3_2.ets.args.json +++ b/ets2panda/linter/test/main/entry_annotation_test3_2.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test3_2.ets.migrate.ets b/ets2panda/linter/test/main/entry_annotation_test3_2.ets.migrate.ets new file mode 100644 index 0000000000..5d9cf9c567 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test3_2.ets.migrate.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const __get_local_storage__ = (): LocalStorage => new LocalStorage(); +@Entry({storage: "__get_local_storage__"}) +@Component +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test3_2.ets.migrate.json b/ets2panda/linter/test/main/entry_annotation_test3_2.ets.migrate.json new file mode 100644 index 0000000000..8ecb23f92c --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test3_2.ets.migrate.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 55, + "endLine": 18, + "endColumn": 67, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test4_1.ets b/ets2panda/linter/test/main/entry_annotation_test4_1.ets index c6c4d34956..b0e972cd29 100644 --- a/ets2panda/linter/test/main/entry_annotation_test4_1.ets +++ b/ets2panda/linter/test/main/entry_annotation_test4_1.ets @@ -1,24 +1,24 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; - -@Entry(LocalStorage.getShared()) -@Component -struct MyPage { - build() { - Text("Hello World") - } +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +@Entry(LocalStorage.getShared()) +@Component +struct MyPage { + build() { + Text("Hello World") + } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test4_1.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test4_1.ets.args.json index 66e8f07a19..95b475ab3c 100644 --- a/ets2panda/linter/test/main/entry_annotation_test4_1.ets.args.json +++ b/ets2panda/linter/test/main/entry_annotation_test4_1.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test4_1.ets.autofix.json b/ets2panda/linter/test/main/entry_annotation_test4_1.ets.autofix.json index e765741f4c..845f1133f9 100644 --- a/ets2panda/linter/test/main/entry_annotation_test4_1.ets.autofix.json +++ b/ets2panda/linter/test/main/entry_annotation_test4_1.ets.autofix.json @@ -1,35 +1,35 @@ -{ - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "result": [ - { - "line": 18, - "column": 1, - "endLine": 18, - "endColumn": 33, - "problem": "EntryAnnotation", - "autofix": [ - { - "start": 702, - "end": 734, - "replacementText": "const __get_local_storage__ = (): LocalStorage => LocalStorage.getShared();\n@Entry({ storage: \"__get_local_storage__\" })" - } - ], - "suggest": "", - "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", - "severity": "ERROR" - } - ] +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 33, + "problem": "EntryAnnotation", + "autofix": [ + { + "start": 685, + "end": 717, + "replacementText": "const __get_local_storage__ = (): LocalStorage => LocalStorage.getShared();\n@Entry({ storage: \"__get_local_storage__\" })" + } + ], + "suggest": "", + "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", + "severity": "ERROR" + } + ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test4_1.ets.migrate.ets b/ets2panda/linter/test/main/entry_annotation_test4_1.ets.migrate.ets new file mode 100644 index 0000000000..fe0711cbc5 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test4_1.ets.migrate.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const __get_local_storage__ = (): LocalStorage => LocalStorage.getShared(); +@Entry({ storage: "__get_local_storage__" }) +@Component +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test4_1.ets.migrate.json b/ets2panda/linter/test/main/entry_annotation_test4_1.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test4_1.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test4_2.ets b/ets2panda/linter/test/main/entry_annotation_test4_2.ets index 6638d8b755..33c63bb35c 100644 --- a/ets2panda/linter/test/main/entry_annotation_test4_2.ets +++ b/ets2panda/linter/test/main/entry_annotation_test4_2.ets @@ -1,25 +1,25 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; - -const __get_local_storage__ = (): LocalStorage => LocalStorage.getShared(); -@Entry({storage: "__get_local_storage__"}) -@Component -struct MyPage { - build() { - Text("Hello World") - } +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const __get_local_storage__ = (): LocalStorage => LocalStorage.getShared(); +@Entry({storage: "__get_local_storage__"}) +@Component +struct MyPage { + build() { + Text("Hello World") + } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test4_2.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test4_2.ets.args.json index 66e8f07a19..95b475ab3c 100644 --- a/ets2panda/linter/test/main/entry_annotation_test4_2.ets.args.json +++ b/ets2panda/linter/test/main/entry_annotation_test4_2.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test4_2.ets.migrate.ets b/ets2panda/linter/test/main/entry_annotation_test4_2.ets.migrate.ets new file mode 100644 index 0000000000..6638d8b755 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test4_2.ets.migrate.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const __get_local_storage__ = (): LocalStorage => LocalStorage.getShared(); +@Entry({storage: "__get_local_storage__"}) +@Component +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test4_2.ets.migrate.json b/ets2panda/linter/test/main/entry_annotation_test4_2.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test4_2.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test5_1.ets b/ets2panda/linter/test/main/entry_annotation_test5_1.ets index 7bea704097..b5a754f0e2 100644 --- a/ets2panda/linter/test/main/entry_annotation_test5_1.ets +++ b/ets2panda/linter/test/main/entry_annotation_test5_1.ets @@ -1,25 +1,25 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; - -const storage = new LocalStorage(); -@Entry({storage: storage}) -@Component -struct MyPage { - build() { - Text("Hello World") - } +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const storage = new LocalStorage(); +@Entry({storage: storage}) +@Component +struct MyPage { + build() { + Text("Hello World") + } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test5_1.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test5_1.ets.args.json index 66e8f07a19..95b475ab3c 100644 --- a/ets2panda/linter/test/main/entry_annotation_test5_1.ets.args.json +++ b/ets2panda/linter/test/main/entry_annotation_test5_1.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test5_1.ets.autofix.json b/ets2panda/linter/test/main/entry_annotation_test5_1.ets.autofix.json index f6c124af23..ee459b5f4a 100644 --- a/ets2panda/linter/test/main/entry_annotation_test5_1.ets.autofix.json +++ b/ets2panda/linter/test/main/entry_annotation_test5_1.ets.autofix.json @@ -1,55 +1,55 @@ -{ - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "result": [ - { - "line": 18, - "column": 7, - "endLine": 18, - "endColumn": 35, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 18, - "column": 21, - "endLine": 18, - "endColumn": 33, - "problem": "DynamicCtorCall", - "suggest": "", - "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", - "severity": "ERROR" - }, - { - "line": 19, - "column": 1, - "endLine": 19, - "endColumn": 27, - "problem": "EntryAnnotation", - "autofix": [ - { - "start": 739, - "end": 765, - "replacementText": "const __get_local_storage__ = (): LocalStorage => storage;\n@Entry({ storage: \"__get_local_storage__\" })" - } - ], - "suggest": "", - "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", - "severity": "ERROR" - } - ] +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 7, + "endLine": 18, + "endColumn": 35, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 21, + "endLine": 18, + "endColumn": 33, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 27, + "problem": "EntryAnnotation", + "autofix": [ + { + "start": 721, + "end": 747, + "replacementText": "const __get_local_storage__ = (): LocalStorage => storage;\n@Entry({ storage: \"__get_local_storage__\" })" + } + ], + "suggest": "", + "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", + "severity": "ERROR" + } + ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test5_1.ets.migrate.ets b/ets2panda/linter/test/main/entry_annotation_test5_1.ets.migrate.ets new file mode 100644 index 0000000000..1a7d2611b8 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test5_1.ets.migrate.ets @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const storage = new LocalStorage(); +const __get_local_storage__ = (): LocalStorage => storage; +@Entry({ storage: "__get_local_storage__" }) +@Component +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test5_1.ets.migrate.json b/ets2panda/linter/test/main/entry_annotation_test5_1.ets.migrate.json new file mode 100644 index 0000000000..d9d95f3937 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test5_1.ets.migrate.json @@ -0,0 +1,38 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 7, + "endLine": 18, + "endColumn": 35, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 21, + "endLine": 18, + "endColumn": 33, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test5_2.ets b/ets2panda/linter/test/main/entry_annotation_test5_2.ets index 52bd3e4f78..b188329f6f 100644 --- a/ets2panda/linter/test/main/entry_annotation_test5_2.ets +++ b/ets2panda/linter/test/main/entry_annotation_test5_2.ets @@ -1,25 +1,25 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; - -const storage = new LocalStorage(); -const __get_local_storage__ = (): LocalStorage => storage; -@Entry({storage: "__get_local_storage__"}) -struct MyPage { - build() { - Text("Hello World") - } +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const storage = new LocalStorage(); +const __get_local_storage__ = (): LocalStorage => storage; +@Entry({storage: "__get_local_storage__"}) +struct MyPage { + build() { + Text("Hello World") + } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test5_2.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test5_2.ets.args.json index 66e8f07a19..95b475ab3c 100644 --- a/ets2panda/linter/test/main/entry_annotation_test5_2.ets.args.json +++ b/ets2panda/linter/test/main/entry_annotation_test5_2.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test5_2.ets.migrate.ets b/ets2panda/linter/test/main/entry_annotation_test5_2.ets.migrate.ets new file mode 100644 index 0000000000..52bd3e4f78 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test5_2.ets.migrate.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const storage = new LocalStorage(); +const __get_local_storage__ = (): LocalStorage => storage; +@Entry({storage: "__get_local_storage__"}) +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test5_2.ets.migrate.json b/ets2panda/linter/test/main/entry_annotation_test5_2.ets.migrate.json new file mode 100644 index 0000000000..d9d95f3937 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test5_2.ets.migrate.json @@ -0,0 +1,38 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 7, + "endLine": 18, + "endColumn": 35, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 21, + "endLine": 18, + "endColumn": 33, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test6_1.ets b/ets2panda/linter/test/main/entry_annotation_test6_1.ets index e17333cbff..570e2082a9 100644 --- a/ets2panda/linter/test/main/entry_annotation_test6_1.ets +++ b/ets2panda/linter/test/main/entry_annotation_test6_1.ets @@ -1,24 +1,24 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; - -@Entry({storage: new LocalStorage()}) -@Component -struct MyPage { - build() { - Text("Hello World") - } +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +@Entry({storage: new LocalStorage()}) +@Component +struct MyPage { + build() { + Text("Hello World") + } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test6_1.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test6_1.ets.args.json index 66e8f07a19..95b475ab3c 100644 --- a/ets2panda/linter/test/main/entry_annotation_test6_1.ets.args.json +++ b/ets2panda/linter/test/main/entry_annotation_test6_1.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test6_1.ets.autofix.json b/ets2panda/linter/test/main/entry_annotation_test6_1.ets.autofix.json index 0c300530e8..838b1b21a4 100644 --- a/ets2panda/linter/test/main/entry_annotation_test6_1.ets.autofix.json +++ b/ets2panda/linter/test/main/entry_annotation_test6_1.ets.autofix.json @@ -1,45 +1,45 @@ -{ - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "result": [ - { - "line": 18, - "column": 1, - "endLine": 18, - "endColumn": 38, - "problem": "EntryAnnotation", - "autofix": [ - { - "start": 702, - "end": 739, - "replacementText": "const __get_local_storage__ = (): LocalStorage => new LocalStorage();\n@Entry({ storage: \"__get_local_storage__\" })" - } - ], - "suggest": "", - "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", - "severity": "ERROR" - }, - { - "line": 18, - "column": 22, - "endLine": 18, - "endColumn": 34, - "problem": "DynamicCtorCall", - "suggest": "", - "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", - "severity": "ERROR" - } - ] +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 38, + "problem": "EntryAnnotation", + "autofix": [ + { + "start": 685, + "end": 722, + "replacementText": "const __get_local_storage__ = (): LocalStorage => new LocalStorage();\n@Entry({ storage: \"__get_local_storage__\" })" + } + ], + "suggest": "", + "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 22, + "endLine": 18, + "endColumn": 34, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + } + ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test6_1.ets.migrate.ets b/ets2panda/linter/test/main/entry_annotation_test6_1.ets.migrate.ets new file mode 100644 index 0000000000..3d30dad8c7 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test6_1.ets.migrate.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const __get_local_storage__ = (): LocalStorage => new LocalStorage(); +@Entry({ storage: "__get_local_storage__" }) +@Component +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test6_1.ets.migrate.json b/ets2panda/linter/test/main/entry_annotation_test6_1.ets.migrate.json new file mode 100644 index 0000000000..8ecb23f92c --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test6_1.ets.migrate.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 55, + "endLine": 18, + "endColumn": 67, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test6_2.ets b/ets2panda/linter/test/main/entry_annotation_test6_2.ets index 5d9cf9c567..14d0661094 100644 --- a/ets2panda/linter/test/main/entry_annotation_test6_2.ets +++ b/ets2panda/linter/test/main/entry_annotation_test6_2.ets @@ -1,25 +1,25 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; - -const __get_local_storage__ = (): LocalStorage => new LocalStorage(); -@Entry({storage: "__get_local_storage__"}) -@Component -struct MyPage { - build() { - Text("Hello World") - } +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const __get_local_storage__ = (): LocalStorage => new LocalStorage(); +@Entry({storage: "__get_local_storage__"}) +@Component +struct MyPage { + build() { + Text("Hello World") + } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test6_2.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test6_2.ets.args.json index 66e8f07a19..95b475ab3c 100644 --- a/ets2panda/linter/test/main/entry_annotation_test6_2.ets.args.json +++ b/ets2panda/linter/test/main/entry_annotation_test6_2.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test6_2.ets.migrate.ets b/ets2panda/linter/test/main/entry_annotation_test6_2.ets.migrate.ets new file mode 100644 index 0000000000..5d9cf9c567 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test6_2.ets.migrate.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const __get_local_storage__ = (): LocalStorage => new LocalStorage(); +@Entry({storage: "__get_local_storage__"}) +@Component +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test6_2.ets.migrate.json b/ets2panda/linter/test/main/entry_annotation_test6_2.ets.migrate.json new file mode 100644 index 0000000000..8ecb23f92c --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test6_2.ets.migrate.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 55, + "endLine": 18, + "endColumn": 67, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test7_1.ets b/ets2panda/linter/test/main/entry_annotation_test7_1.ets index 5de5fc213a..b246bb8381 100644 --- a/ets2panda/linter/test/main/entry_annotation_test7_1.ets +++ b/ets2panda/linter/test/main/entry_annotation_test7_1.ets @@ -1,24 +1,24 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; - -@Entry({storage: LocalStorage.getShared()}) -@Component -struct MyPage { - build() { - Text("Hello World") - } +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +@Entry({storage: LocalStorage.getShared()}) +@Component +struct MyPage { + build() { + Text("Hello World") + } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test7_1.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test7_1.ets.args.json index 66e8f07a19..95b475ab3c 100644 --- a/ets2panda/linter/test/main/entry_annotation_test7_1.ets.args.json +++ b/ets2panda/linter/test/main/entry_annotation_test7_1.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test7_1.ets.autofix.json b/ets2panda/linter/test/main/entry_annotation_test7_1.ets.autofix.json index 655059a71d..45c5a879bc 100644 --- a/ets2panda/linter/test/main/entry_annotation_test7_1.ets.autofix.json +++ b/ets2panda/linter/test/main/entry_annotation_test7_1.ets.autofix.json @@ -1,35 +1,35 @@ -{ - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "result": [ - { - "line": 18, - "column": 1, - "endLine": 18, - "endColumn": 44, - "problem": "EntryAnnotation", - "autofix": [ - { - "start": 702, - "end": 745, - "replacementText": "const __get_local_storage__ = (): LocalStorage => LocalStorage.getShared();\n@Entry({ storage: \"__get_local_storage__\" })" - } - ], - "suggest": "", - "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", - "severity": "ERROR" - } - ] +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 44, + "problem": "EntryAnnotation", + "autofix": [ + { + "start": 685, + "end": 728, + "replacementText": "const __get_local_storage__ = (): LocalStorage => LocalStorage.getShared();\n@Entry({ storage: \"__get_local_storage__\" })" + } + ], + "suggest": "", + "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", + "severity": "ERROR" + } + ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test7_1.ets.migrate.ets b/ets2panda/linter/test/main/entry_annotation_test7_1.ets.migrate.ets new file mode 100644 index 0000000000..fe0711cbc5 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test7_1.ets.migrate.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const __get_local_storage__ = (): LocalStorage => LocalStorage.getShared(); +@Entry({ storage: "__get_local_storage__" }) +@Component +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test7_1.ets.migrate.json b/ets2panda/linter/test/main/entry_annotation_test7_1.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test7_1.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test7_2.ets b/ets2panda/linter/test/main/entry_annotation_test7_2.ets index 6638d8b755..33c63bb35c 100644 --- a/ets2panda/linter/test/main/entry_annotation_test7_2.ets +++ b/ets2panda/linter/test/main/entry_annotation_test7_2.ets @@ -1,25 +1,25 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; - -const __get_local_storage__ = (): LocalStorage => LocalStorage.getShared(); -@Entry({storage: "__get_local_storage__"}) -@Component -struct MyPage { - build() { - Text("Hello World") - } +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const __get_local_storage__ = (): LocalStorage => LocalStorage.getShared(); +@Entry({storage: "__get_local_storage__"}) +@Component +struct MyPage { + build() { + Text("Hello World") + } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test7_2.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test7_2.ets.args.json index 66e8f07a19..95b475ab3c 100644 --- a/ets2panda/linter/test/main/entry_annotation_test7_2.ets.args.json +++ b/ets2panda/linter/test/main/entry_annotation_test7_2.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test7_2.ets.migrate.ets b/ets2panda/linter/test/main/entry_annotation_test7_2.ets.migrate.ets new file mode 100644 index 0000000000..6638d8b755 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test7_2.ets.migrate.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const __get_local_storage__ = (): LocalStorage => LocalStorage.getShared(); +@Entry({storage: "__get_local_storage__"}) +@Component +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test7_2.ets.migrate.json b/ets2panda/linter/test/main/entry_annotation_test7_2.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test7_2.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test8_1.ets b/ets2panda/linter/test/main/entry_annotation_test8_1.ets index f5895dae8c..2db526a740 100644 --- a/ets2panda/linter/test/main/entry_annotation_test8_1.ets +++ b/ets2panda/linter/test/main/entry_annotation_test8_1.ets @@ -1,25 +1,25 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; - -const source = globalThis.localStorage; -@Entry({storage: source}) -@Component -struct MyPage { - build() { - Text("Hello World") - } +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const source = globalThis.localStorage; +@Entry({storage: source}) +@Component +struct MyPage { + build() { + Text("Hello World") + } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test8_1.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test8_1.ets.args.json index 66e8f07a19..95b475ab3c 100644 --- a/ets2panda/linter/test/main/entry_annotation_test8_1.ets.args.json +++ b/ets2panda/linter/test/main/entry_annotation_test8_1.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test8_1.ets.autofix.json b/ets2panda/linter/test/main/entry_annotation_test8_1.ets.autofix.json index 9f9ef341aa..c1e82092cb 100644 --- a/ets2panda/linter/test/main/entry_annotation_test8_1.ets.autofix.json +++ b/ets2panda/linter/test/main/entry_annotation_test8_1.ets.autofix.json @@ -1,52 +1,52 @@ -{ - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "result": [ - { - "line": 18, - "column": 16, - "endLine": 18, - "endColumn": 39, - "problem": "GlobalThisError", - "autofix": [ - { - "start": 717, - "end": 740, - "replacementText": "specialAutofixLib.globalThis.get(\"localStorage\")" - } - ], - "suggest": "", - "rule": "\"globalThis\" is not supported (arkts-no-globalthis)", - "severity": "ERROR" - }, - { - "line": 19, - "column": 1, - "endLine": 19, - "endColumn": 26, - "problem": "EntryAnnotation", - "autofix": [ - { - "start": 743, - "end": 768, - "replacementText": "const __get_local_storage__ = (): LocalStorage => source;\n@Entry({ storage: \"__get_local_storage__\" })" - } - ], - "suggest": "", - "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", - "severity": "ERROR" - } - ] +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 16, + "endLine": 18, + "endColumn": 39, + "problem": "GlobalThisError", + "autofix": [ + { + "start": 700, + "end": 723, + "replacementText": "specialAutofixLib.globalThis.get(\"localStorage\")" + } + ], + "suggest": "", + "rule": "\"globalThis\" is not supported (arkts-no-globalthis)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 26, + "problem": "EntryAnnotation", + "autofix": [ + { + "start": 725, + "end": 750, + "replacementText": "const __get_local_storage__ = (): LocalStorage => source;\n@Entry({ storage: \"__get_local_storage__\" })" + } + ], + "suggest": "", + "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", + "severity": "ERROR" + } + ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test8_1.ets.migrate.ets b/ets2panda/linter/test/main/entry_annotation_test8_1.ets.migrate.ets new file mode 100644 index 0000000000..1159381e1c --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test8_1.ets.migrate.ets @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const source = specialAutofixLib.globalThis.get("localStorage"); +const __get_local_storage__ = (): LocalStorage => source; +@Entry({ storage: "__get_local_storage__" }) +@Component +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test8_1.ets.migrate.json b/ets2panda/linter/test/main/entry_annotation_test8_1.ets.migrate.json new file mode 100644 index 0000000000..045feeac1b --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test8_1.ets.migrate.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 7, + "endLine": 18, + "endColumn": 64, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test8_2.ets b/ets2panda/linter/test/main/entry_annotation_test8_2.ets index 1120a5a860..435ff1addf 100644 --- a/ets2panda/linter/test/main/entry_annotation_test8_2.ets +++ b/ets2panda/linter/test/main/entry_annotation_test8_2.ets @@ -1,26 +1,26 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; - -const source = globalThis.localStorage; -const __get_local_storage__ = (): LocalStorage => source; -@Entry({storage: "__get_local_storage__"}) -@Component -struct MyPage { - build() { - Text("Hello World") - } +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const source = globalThis.localStorage; +const __get_local_storage__ = (): LocalStorage => source; +@Entry({storage: "__get_local_storage__"}) +@Component +struct MyPage { + build() { + Text("Hello World") + } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test8_2.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test8_2.ets.args.json index 66e8f07a19..95b475ab3c 100644 --- a/ets2panda/linter/test/main/entry_annotation_test8_2.ets.args.json +++ b/ets2panda/linter/test/main/entry_annotation_test8_2.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test8_2.ets.autofix.json b/ets2panda/linter/test/main/entry_annotation_test8_2.ets.autofix.json index e111a09d28..f73277ba2c 100644 --- a/ets2panda/linter/test/main/entry_annotation_test8_2.ets.autofix.json +++ b/ets2panda/linter/test/main/entry_annotation_test8_2.ets.autofix.json @@ -1,35 +1,35 @@ -{ - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "result": [ - { - "line": 18, - "column": 16, - "endLine": 18, - "endColumn": 39, - "problem": "GlobalThisError", - "autofix": [ - { - "start": 717, - "end": 740, - "replacementText": "specialAutofixLib.globalThis.get(\"localStorage\")" - } - ], - "suggest": "", - "rule": "\"globalThis\" is not supported (arkts-no-globalthis)", - "severity": "ERROR" - } - ] +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 16, + "endLine": 18, + "endColumn": 39, + "problem": "GlobalThisError", + "autofix": [ + { + "start": 700, + "end": 723, + "replacementText": "specialAutofixLib.globalThis.get(\"localStorage\")" + } + ], + "suggest": "", + "rule": "\"globalThis\" is not supported (arkts-no-globalthis)", + "severity": "ERROR" + } + ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test8_2.ets.migrate.ets b/ets2panda/linter/test/main/entry_annotation_test8_2.ets.migrate.ets new file mode 100644 index 0000000000..0c20666abf --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test8_2.ets.migrate.ets @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const source = specialAutofixLib.globalThis.get("localStorage"); +const __get_local_storage__ = (): LocalStorage => source; +@Entry({storage: "__get_local_storage__"}) +@Component +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test8_2.ets.migrate.json b/ets2panda/linter/test/main/entry_annotation_test8_2.ets.migrate.json new file mode 100644 index 0000000000..045feeac1b --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test8_2.ets.migrate.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 7, + "endLine": 18, + "endColumn": 64, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test9_1.ets b/ets2panda/linter/test/main/entry_annotation_test9_1.ets index 6d77c4401b..24563d7f73 100644 --- a/ets2panda/linter/test/main/entry_annotation_test9_1.ets +++ b/ets2panda/linter/test/main/entry_annotation_test9_1.ets @@ -1,24 +1,24 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; - -@Entry({storage: globalThis.localStorage}) -@Component -struct MyPage { - build() { - Text("Hello World") - } +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +@Entry({storage: globalThis.localStorage}) +@Component +struct MyPage { + build() { + Text("Hello World") + } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test9_1.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test9_1.ets.args.json index 66e8f07a19..95b475ab3c 100644 --- a/ets2panda/linter/test/main/entry_annotation_test9_1.ets.args.json +++ b/ets2panda/linter/test/main/entry_annotation_test9_1.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test9_1.ets.autofix.json b/ets2panda/linter/test/main/entry_annotation_test9_1.ets.autofix.json index b2105691ce..f8e2a1ef6c 100644 --- a/ets2panda/linter/test/main/entry_annotation_test9_1.ets.autofix.json +++ b/ets2panda/linter/test/main/entry_annotation_test9_1.ets.autofix.json @@ -1,52 +1,52 @@ -{ - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "result": [ - { - "line": 18, - "column": 1, - "endLine": 18, - "endColumn": 43, - "problem": "EntryAnnotation", - "autofix": [ - { - "start": 702, - "end": 744, - "replacementText": "const __get_local_storage__ = (): LocalStorage => globalThis.localStorage;\n@Entry({ storage: \"__get_local_storage__\" })" - } - ], - "suggest": "", - "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", - "severity": "ERROR" - }, - { - "line": 18, - "column": 18, - "endLine": 18, - "endColumn": 41, - "problem": "GlobalThisError", - "autofix": [ - { - "start": 719, - "end": 742, - "replacementText": "specialAutofixLib.globalThis.get(\"localStorage\")" - } - ], - "suggest": "", - "rule": "\"globalThis\" is not supported (arkts-no-globalthis)", - "severity": "ERROR" - } - ] +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 43, + "problem": "EntryAnnotation", + "autofix": [ + { + "start": 685, + "end": 727, + "replacementText": "const __get_local_storage__ = (): LocalStorage => globalThis.localStorage;\n@Entry({ storage: \"__get_local_storage__\" })" + } + ], + "suggest": "", + "rule": "The \"@Entry\" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 18, + "endLine": 18, + "endColumn": 41, + "problem": "GlobalThisError", + "autofix": [ + { + "start": 702, + "end": 725, + "replacementText": "specialAutofixLib.globalThis.get(\"localStorage\")" + } + ], + "suggest": "", + "rule": "\"globalThis\" is not supported (arkts-no-globalthis)", + "severity": "ERROR" + } + ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test9_1.ets.migrate.ets b/ets2panda/linter/test/main/entry_annotation_test9_1.ets.migrate.ets new file mode 100644 index 0000000000..8c9d2b2012 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test9_1.ets.migrate.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const __get_local_storage__ = (): LocalStorage => specialAutofixLib.globalThis.get("localStorage"); +@Entry({ storage: "__get_local_storage__" }) +@Component +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test9_1.ets.migrate.json b/ets2panda/linter/test/main/entry_annotation_test9_1.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test9_1.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test9_2.ets b/ets2panda/linter/test/main/entry_annotation_test9_2.ets index f6f5bf039f..20d1b06bd9 100644 --- a/ets2panda/linter/test/main/entry_annotation_test9_2.ets +++ b/ets2panda/linter/test/main/entry_annotation_test9_2.ets @@ -1,25 +1,25 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; - -const __get_local_storage__ = (): LocalStorage => globalThis.localStorage; -@Entry({storage: "__get_local_storage__"}) -@Component -struct MyPage { - build() { - Text("Hello World") - } +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const __get_local_storage__ = (): LocalStorage => globalThis.localStorage; +@Entry({storage: "__get_local_storage__"}) +@Component +struct MyPage { + build() { + Text("Hello World") + } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test9_2.ets.args.json b/ets2panda/linter/test/main/entry_annotation_test9_2.ets.args.json index 66e8f07a19..95b475ab3c 100644 --- a/ets2panda/linter/test/main/entry_annotation_test9_2.ets.args.json +++ b/ets2panda/linter/test/main/entry_annotation_test9_2.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test9_2.ets.autofix.json b/ets2panda/linter/test/main/entry_annotation_test9_2.ets.autofix.json index 0727f2fce6..17f6fcde03 100644 --- a/ets2panda/linter/test/main/entry_annotation_test9_2.ets.autofix.json +++ b/ets2panda/linter/test/main/entry_annotation_test9_2.ets.autofix.json @@ -1,35 +1,35 @@ -{ - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "result": [ - { - "line": 18, - "column": 51, - "endLine": 18, - "endColumn": 74, - "problem": "GlobalThisError", - "autofix": [ - { - "start": 752, - "end": 775, - "replacementText": "specialAutofixLib.globalThis.get(\"localStorage\")" - } - ], - "suggest": "", - "rule": "\"globalThis\" is not supported (arkts-no-globalthis)", - "severity": "ERROR" - } - ] +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 51, + "endLine": 18, + "endColumn": 74, + "problem": "GlobalThisError", + "autofix": [ + { + "start": 735, + "end": 758, + "replacementText": "specialAutofixLib.globalThis.get(\"localStorage\")" + } + ], + "suggest": "", + "rule": "\"globalThis\" is not supported (arkts-no-globalthis)", + "severity": "ERROR" + } + ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test9_2.ets.migrate.ets b/ets2panda/linter/test/main/entry_annotation_test9_2.ets.migrate.ets new file mode 100644 index 0000000000..9f1162ccfd --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test9_2.ets.migrate.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; + +const __get_local_storage__ = (): LocalStorage => specialAutofixLib.globalThis.get("localStorage"); +@Entry({storage: "__get_local_storage__"}) +@Component +struct MyPage { + build() { + Text("Hello World") + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/entry_annotation_test9_2.ets.migrate.json b/ets2panda/linter/test/main/entry_annotation_test9_2.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/entry_annotation_test9_2.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/equals_token_option.ets b/ets2panda/linter/test/main/equals_token_option.ets new file mode 100755 index 0000000000..0c3da5b257 --- /dev/null +++ b/ets2panda/linter/test/main/equals_token_option.ets @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let a =1; +a &&=2; +a ||=2; +a ??=2; +typeof (a ||=2); +let person = { name: "Alice", age: 30 }; + +function setAge(){ + person.age &&= - 1; +} +person.age = 0; +person.age &&= 5; + +let count: number | null = null; +count ??= 10; + +count = 0; +count ??= 5; +console.log((count ??= 5)+'') +function getCount(){ + return (count ??= 5); +} +let message: string | null = null; + +message ||= "msg"; +console.log(message); + +message = "msg1"; +message ||= "newMsg"; +console.log(message); +class Demo{ + constructor() { + message ||= "defaultMsg"; + } + setMes(){ + message ||= "defaultMsg"; + } + getMes(){ + return message ??= "newMsg"; + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/IndexedAccessType.ets.args.json b/ets2panda/linter/test/main/equals_token_option.ets.args.json old mode 100644 new mode 100755 similarity index 100% rename from ets2panda/linter/test/sdkwhite/IndexedAccessType.ets.args.json rename to ets2panda/linter/test/main/equals_token_option.ets.args.json diff --git a/ets2panda/linter/test/main/equals_token_option.ets.arkts2.json b/ets2panda/linter/test/main/equals_token_option.ets.arkts2.json new file mode 100755 index 0000000000..7100f9b797 --- /dev/null +++ b/ets2panda/linter/test/main/equals_token_option.ets.arkts2.json @@ -0,0 +1,198 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 15, + "column": 5, + "endLine": 15, + "endColumn": 9, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 16, + "column": 3, + "endLine": 16, + "endColumn": 6, + "problem": "UnsupportOperator", + "suggest": "", + "rule": "Operator is not support (arkts-unsupport-operator)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 3, + "endLine": 17, + "endColumn": 6, + "problem": "UnsupportOperator", + "suggest": "", + "rule": "Operator is not support (arkts-unsupport-operator)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 3, + "endLine": 18, + "endColumn": 6, + "problem": "UnsupportOperator", + "suggest": "", + "rule": "Operator is not support (arkts-unsupport-operator)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 12, + "endLine": 19, + "endColumn": 15, + "problem": "UnsupportOperator", + "suggest": "", + "rule": "Operator is not support (arkts-unsupport-operator)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 14, + "endLine": 20, + "endColumn": 15, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 14, + "endLine": 23, + "endColumn": 17, + "problem": "UnsupportOperator", + "suggest": "", + "rule": "Operator is not support (arkts-unsupport-operator)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 12, + "endLine": 26, + "endColumn": 15, + "problem": "UnsupportOperator", + "suggest": "", + "rule": "Operator is not support (arkts-unsupport-operator)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 7, + "endLine": 29, + "endColumn": 10, + "problem": "UnsupportOperator", + "suggest": "", + "rule": "Operator is not support (arkts-unsupport-operator)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 7, + "endLine": 32, + "endColumn": 10, + "problem": "UnsupportOperator", + "suggest": "", + "rule": "Operator is not support (arkts-unsupport-operator)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 20, + "endLine": 33, + "endColumn": 23, + "problem": "UnsupportOperator", + "suggest": "", + "rule": "Operator is not support (arkts-unsupport-operator)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 1, + "endLine": 36, + "endColumn": 2, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 17, + "endLine": 35, + "endColumn": 20, + "problem": "UnsupportOperator", + "suggest": "", + "rule": "Operator is not support (arkts-unsupport-operator)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 9, + "endLine": 39, + "endColumn": 12, + "problem": "UnsupportOperator", + "suggest": "", + "rule": "Operator is not support (arkts-unsupport-operator)", + "severity": "ERROR" + }, + { + "line": 43, + "column": 9, + "endLine": 43, + "endColumn": 12, + "problem": "UnsupportOperator", + "suggest": "", + "rule": "Operator is not support (arkts-unsupport-operator)", + "severity": "ERROR" + }, + { + "line": 47, + "column": 13, + "endLine": 47, + "endColumn": 16, + "problem": "UnsupportOperator", + "suggest": "", + "rule": "Operator is not support (arkts-unsupport-operator)", + "severity": "ERROR" + }, + { + "line": 50, + "column": 13, + "endLine": 50, + "endColumn": 16, + "problem": "UnsupportOperator", + "suggest": "", + "rule": "Operator is not support (arkts-unsupport-operator)", + "severity": "ERROR" + }, + { + "line": 53, + "column": 20, + "endLine": 53, + "endColumn": 23, + "problem": "UnsupportOperator", + "suggest": "", + "rule": "Operator is not support (arkts-unsupport-operator)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/equals_token_option.ets.json b/ets2panda/linter/test/main/equals_token_option.ets.json new file mode 100755 index 0000000000..4dccd5bab8 --- /dev/null +++ b/ets2panda/linter/test/main/equals_token_option.ets.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 20, + "column": 14, + "endLine": 20, + "endColumn": 15, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/explicit_function_type.ets b/ets2panda/linter/test/main/explicit_function_type.ets index ee7f99ecd5..9b44052197 100755 --- a/ets2panda/linter/test/main/explicit_function_type.ets +++ b/ets2panda/linter/test/main/explicit_function_type.ets @@ -161,4 +161,15 @@ function compose45(...fns: Function[]): Function { } export let add: (a: number, b: number) => number; -export let add1: (a: string) => object; \ No newline at end of file +export let add1: (a: string) => object; + +f1(); + +class AB3 { + fn3: Function = () => {}; +} +let ab3 = new AB3(); +ab3.fn3(); + +const fn29: Function[] = []; +fn29[1](); \ No newline at end of file diff --git a/ets2panda/linter/test/main/explicit_function_type.ets.args.json b/ets2panda/linter/test/main/explicit_function_type.ets.args.json index 4d93062f69..a89d885810 100755 --- a/ets2panda/linter/test/main/explicit_function_type.ets.args.json +++ b/ets2panda/linter/test/main/explicit_function_type.ets.args.json @@ -14,6 +14,8 @@ "limitations under the License." ], "mode": { - "arkts2": "" + "arkts2": "", + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } diff --git a/ets2panda/linter/test/main/explicit_function_type.ets.arkts2.json b/ets2panda/linter/test/main/explicit_function_type.ets.arkts2.json index 0260c350e1..1d761807b3 100755 --- a/ets2panda/linter/test/main/explicit_function_type.ets.arkts2.json +++ b/ets2panda/linter/test/main/explicit_function_type.ets.arkts2.json @@ -14,535 +14,225 @@ "limitations under the License." ], "result": [ - { - "line": 15, - "column": 9, - "endLine": 15, - "endColumn": 17, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 16, - "column": 9, - "endLine": 16, - "endColumn": 17, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 16, - "column": 20, - "endLine": 16, - "endColumn": 33, - "problem": "FunctionExpression", - "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", - "severity": "ERROR" - }, - { - "line": 17, - "column": 9, - "endLine": 17, - "endColumn": 17, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 17, - "column": 24, - "endLine": 17, - "endColumn": 32, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 18, - "column": 10, - "endLine": 18, - "endColumn": 23, - "problem": "FunctionExpression", - "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", - "severity": "ERROR" - }, - { - "line": 19, - "column": 14, - "endLine": 19, - "endColumn": 22, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 37, - "column": 7, - "endLine": 37, - "endColumn": 15, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 41, - "column": 10, - "endLine": 41, - "endColumn": 18, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 45, - "column": 7, - "endLine": 45, - "endColumn": 15, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 53, - "column": 7, - "endLine": 53, - "endColumn": 15, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 56, - "column": 19, - "endLine": 56, - "endColumn": 27, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 60, - "column": 26, - "endLine": 60, - "endColumn": 34, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 65, - "column": 17, - "endLine": 65, - "endColumn": 25, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 69, - "column": 25, - "endLine": 69, - "endColumn": 33, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 70, - "column": 12, - "endLine": 70, - "endColumn": 20, - "problem": "ClassAsObjectError", - "suggest": "", - "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", - "severity": "ERROR" - }, - { - "line": 70, - "column": 12, - "endLine": 70, - "endColumn": 20, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 75, - "column": 20, - "endLine": 75, - "endColumn": 28, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 79, - "column": 11, - "endLine": 79, - "endColumn": 19, - "problem": "ClassAsObjectError", - "suggest": "", - "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", - "severity": "ERROR" - }, - { - "line": 79, - "column": 11, - "endLine": 79, - "endColumn": 19, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 87, - "column": 12, - "endLine": 87, - "endColumn": 20, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 96, - "column": 21, - "endLine": 96, - "endColumn": 29, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 101, - "column": 22, - "endLine": 101, - "endColumn": 30, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 101, - "column": 38, - "endLine": 101, - "endColumn": 46, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 101, - "column": 56, - "endLine": 101, - "endColumn": 64, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 105, - "column": 23, - "endLine": 105, - "endColumn": 31, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 109, - "column": 27, - "endLine": 109, - "endColumn": 35, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 114, - "column": 80, - "endLine": 114, - "endColumn": 88, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 118, - "column": 16, - "endLine": 118, - "endColumn": 24, - "problem": "ClassAsObjectError", - "suggest": "", - "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", - "severity": "ERROR" - }, - { - "line": 118, - "column": 16, - "endLine": 118, - "endColumn": 24, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 121, - "column": 3, - "endLine": 121, - "endColumn": 10, - "problem": "TsOverload", - "suggest": "", - "rule": "Class TS overloading is not supported(arkts-no-ts-overload)", - "severity": "ERROR" - }, - { - "line": 122, - "column": 3, - "endLine": 122, - "endColumn": 35, - "problem": "TsOverload", - "suggest": "", - "rule": "Class TS overloading is not supported(arkts-no-ts-overload)", - "severity": "ERROR" - }, - { - "line": 122, - "column": 12, - "endLine": 122, - "endColumn": 20, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 123, - "column": 3, - "endLine": 125, - "endColumn": 4, - "problem": "TsOverload", - "suggest": "", - "rule": "Class TS overloading is not supported(arkts-no-ts-overload)", - "severity": "ERROR" - }, - { - "line": 123, - "column": 13, - "endLine": 123, - "endColumn": 21, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 128, - "column": 21, - "endLine": 128, - "endColumn": 29, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 128, - "column": 31, - "endLine": 128, - "endColumn": 32, - "problem": "LimitedLiteralType", - "suggest": "", - "rule": "Literal types are restricted(arkts-limited-literal-types)", - "severity": "ERROR" - }, - { - "line": 128, - "column": 33, - "endLine": 128, - "endColumn": 37, - "problem": "LimitedLiteralType", - "suggest": "", - "rule": "Literal types are restricted(arkts-limited-literal-types)", - "severity": "ERROR" - }, - { - "line": 128, - "column": 39, - "endLine": 128, - "endColumn": 44, - "problem": "LimitedLiteralType", - "suggest": "", - "rule": "Literal types are restricted(arkts-limited-literal-types)", - "severity": "ERROR" - }, - { - "line": 128, - "column": 57, - "endLine": 128, - "endColumn": 65, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 132, - "column": 3, - "endLine": 132, - "endColumn": 11, - "problem": "InvalidIdentifier", - "suggest": "", - "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", - "severity": "ERROR" - }, - { - "line": 138, - "column": 34, - "endLine": 138, - "endColumn": 42, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 142, - "column": 11, - "endLine": 142, - "endColumn": 19, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 143, - "column": 36, - "endLine": 143, - "endColumn": 44, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 150, - "column": 16, - "endLine": 150, - "endColumn": 21, - "problem": "LimitedReturnTypeInference", - "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", - "severity": "ERROR" - }, - { - "line": 151, - "column": 14, - "endLine": 151, - "endColumn": 22, - "problem": "DynamicCtorCall", - "suggest": "", - "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", - "severity": "ERROR" - }, - { - "line": 153, - "column": 20, - "endLine": 153, - "endColumn": 28, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 154, - "column": 9, - "endLine": 154, - "endColumn": 31, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 155, - "column": 17, - "endLine": 155, - "endColumn": 25, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 159, - "column": 28, - "endLine": 159, - "endColumn": 36, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 159, - "column": 41, - "endLine": 159, - "endColumn": 49, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 160, - "column": 47, - "endLine": 160, - "endColumn": 55, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 160, - "column": 85, - "endLine": 160, - "endColumn": 93, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - } - ] -} + { + "line": 16, + "column": 20, + "endLine": 16, + "endColumn": 33, + "problem": "FunctionExpression", + "suggest": "", + "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 10, + "endLine": 18, + "endColumn": 23, + "problem": "FunctionExpression", + "suggest": "", + "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "severity": "ERROR" + }, + { + "line": 57, + "column": 3, + "endLine": 57, + "endColumn": 5, + "problem": "ExplicitFunctionType", + "suggest": "", + "rule": "The function type should be explicit (arkts-no-ts-like-function-call)", + "severity": "ERROR" + }, + { + "line": 70, + "column": 12, + "endLine": 70, + "endColumn": 20, + "problem": "ClassAsObjectError", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "ERROR" + }, + { + "line": 79, + "column": 11, + "endLine": 79, + "endColumn": 19, + "problem": "ClassAsObjectError", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "ERROR" + }, + { + "line": 118, + "column": 16, + "endLine": 118, + "endColumn": 24, + "problem": "ClassAsObjectError", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "ERROR" + }, + { + "line": 121, + "column": 3, + "endLine": 121, + "endColumn": 10, + "problem": "TsOverload", + "suggest": "", + "rule": "Class TS overloading is not supported(arkts-no-ts-overload)", + "severity": "ERROR" + }, + { + "line": 122, + "column": 3, + "endLine": 122, + "endColumn": 35, + "problem": "TsOverload", + "suggest": "", + "rule": "Class TS overloading is not supported(arkts-no-ts-overload)", + "severity": "ERROR" + }, + { + "line": 123, + "column": 3, + "endLine": 125, + "endColumn": 4, + "problem": "TsOverload", + "suggest": "", + "rule": "Class TS overloading is not supported(arkts-no-ts-overload)", + "severity": "ERROR" + }, + { + "line": 128, + "column": 31, + "endLine": 128, + "endColumn": 32, + "problem": "LimitedLiteralType", + "suggest": "", + "rule": "Literal types are restricted(arkts-limited-literal-types)", + "severity": "ERROR" + }, + { + "line": 128, + "column": 33, + "endLine": 128, + "endColumn": 37, + "problem": "LimitedLiteralType", + "suggest": "", + "rule": "Literal types are restricted(arkts-limited-literal-types)", + "severity": "ERROR" + }, + { + "line": 128, + "column": 39, + "endLine": 128, + "endColumn": 44, + "problem": "LimitedLiteralType", + "suggest": "", + "rule": "Literal types are restricted(arkts-limited-literal-types)", + "severity": "ERROR" + }, + { + "line": 132, + "column": 3, + "endLine": 132, + "endColumn": 11, + "problem": "InvalidIdentifier", + "suggest": "", + "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", + "severity": "ERROR" + }, + { + "line": 139, + "column": 3, + "endLine": 139, + "endColumn": 11, + "problem": "ExplicitFunctionType", + "suggest": "", + "rule": "The function type should be explicit (arkts-no-ts-like-function-call)", + "severity": "ERROR" + }, + { + "line": 150, + "column": 16, + "endLine": 150, + "endColumn": 21, + "problem": "LimitedReturnTypeInference", + "suggest": "", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "severity": "ERROR" + }, + { + "line": 151, + "column": 14, + "endLine": 151, + "endColumn": 22, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 154, + "column": 9, + "endLine": 154, + "endColumn": 31, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 160, + "column": 62, + "endLine": 160, + "endColumn": 66, + "problem": "ExplicitFunctionType", + "suggest": "", + "rule": "The function type should be explicit (arkts-no-ts-like-function-call)", + "severity": "ERROR" + }, + { + "line": 160, + "column": 67, + "endLine": 160, + "endColumn": 71, + "problem": "ExplicitFunctionType", + "suggest": "", + "rule": "The function type should be explicit (arkts-no-ts-like-function-call)", + "severity": "ERROR" + }, + { + "line": 166, + "column": 1, + "endLine": 166, + "endColumn": 3, + "problem": "ExplicitFunctionType", + "suggest": "", + "rule": "The function type should be explicit (arkts-no-ts-like-function-call)", + "severity": "ERROR" + }, + { + "line": 172, + "column": 1, + "endLine": 172, + "endColumn": 8, + "problem": "ExplicitFunctionType", + "suggest": "", + "rule": "The function type should be explicit (arkts-no-ts-like-function-call)", + "severity": "ERROR" + }, + { + "line": 175, + "column": 1, + "endLine": 175, + "endColumn": 8, + "problem": "ExplicitFunctionType", + "suggest": "", + "rule": "The function type should be explicit (arkts-no-ts-like-function-call)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/migrate/func_return_type.ts.migrate.json b/ets2panda/linter/test/main/explicit_function_type.ets.autofix.json similarity index 30% rename from ets2panda/linter/test/migrate/func_return_type.ts.migrate.json rename to ets2panda/linter/test/main/explicit_function_type.ets.autofix.json index 567dd757ee..5f69b7bd51 100644 --- a/ets2panda/linter/test/migrate/func_return_type.ts.migrate.json +++ b/ets2panda/linter/test/main/explicit_function_type.ets.autofix.json @@ -1,263 +1,300 @@ { + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], "result": [ { "line": 16, - "column": 10, + "column": 20, "endLine": 16, - "endColumn": 11, - "problem": "LimitedReturnTypeInference", - "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", - "severity": "ERROR" - }, - { - "line": 23, - "column": 10, - "endLine": 23, - "endColumn": 11, - "problem": "LimitedReturnTypeInference", - "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", - "severity": "ERROR" - }, - { - "line": 33, - "column": 10, - "endLine": 33, - "endColumn": 11, - "problem": "LimitedReturnTypeInference", - "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", - "severity": "ERROR" - }, - { - "line": 40, - "column": 10, - "endLine": 40, - "endColumn": 11, - "problem": "LimitedReturnTypeInference", - "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", - "severity": "ERROR" - }, - { - "line": 46, - "column": 10, - "endLine": 46, - "endColumn": 11, - "problem": "LimitedReturnTypeInference", + "endColumn": 33, + "problem": "FunctionExpression", + "autofix": [ + { + "start": 668, + "end": 681, + "replacementText": "() => { }" + } + ], "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", "severity": "ERROR" }, { - "line": 54, + "line": 18, "column": 10, - "endLine": 54, - "endColumn": 11, - "problem": "LimitedReturnTypeInference", + "endLine": 18, + "endColumn": 23, + "problem": "FunctionExpression", + "autofix": [ + { + "start": 760, + "end": 773, + "replacementText": "() => { }" + } + ], "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", "severity": "ERROR" }, { "line": 57, - "column": 10, + "column": 3, "endLine": 57, - "endColumn": 11, - "problem": "LimitedReturnTypeInference", + "endColumn": 5, + "problem": "ExplicitFunctionType", + "autofix": [ + { + "replacementText": "fn.unSafeCall", + "start": 1572, + "end": 1574 + } + ], "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "The function type should be explicit (arkts-no-ts-like-function-call)", "severity": "ERROR" }, { - "line": 57, - "column": 15, - "endLine": 57, - "endColumn": 18, - "problem": "AnyType", + "line": 70, + "column": 12, + "endLine": 70, + "endColumn": 20, + "problem": "ClassAsObjectError", "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", "severity": "ERROR" }, { - "line": 62, - "column": 12, - "endLine": 64, - "endColumn": 4, - "problem": "FunctionExpression", + "line": 79, + "column": 11, + "endLine": 79, + "endColumn": 19, + "problem": "ClassAsObjectError", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", "severity": "ERROR" }, { - "line": 65, - "column": 12, - "endLine": 67, - "endColumn": 4, - "problem": "FunctionExpression", + "line": 118, + "column": 16, + "endLine": 118, + "endColumn": 24, + "problem": "ClassAsObjectError", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", "severity": "ERROR" }, { - "line": 69, - "column": 12, - "endLine": 71, - "endColumn": 4, - "problem": "FunctionExpression", + "line": 121, + "column": 3, + "endLine": 121, + "endColumn": 10, + "problem": "TsOverload", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "Class TS overloading is not supported(arkts-no-ts-overload)", "severity": "ERROR" }, { - "line": 73, - "column": 12, - "endLine": 75, - "endColumn": 4, - "problem": "FunctionExpression", + "line": 122, + "column": 3, + "endLine": 122, + "endColumn": 35, + "problem": "TsOverload", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "Class TS overloading is not supported(arkts-no-ts-overload)", "severity": "ERROR" }, { - "line": 76, - "column": 12, - "endLine": 78, + "line": 123, + "column": 3, + "endLine": 125, "endColumn": 4, - "problem": "FunctionExpression", + "problem": "TsOverload", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "Class TS overloading is not supported(arkts-no-ts-overload)", "severity": "ERROR" }, { - "line": 80, - "column": 12, - "endLine": 82, - "endColumn": 4, - "problem": "FunctionExpression", + "line": 128, + "column": 31, + "endLine": 128, + "endColumn": 32, + "problem": "LimitedLiteralType", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "Literal types are restricted(arkts-limited-literal-types)", "severity": "ERROR" }, { - "line": 80, - "column": 12, - "endLine": 82, - "endColumn": 4, - "problem": "LimitedReturnTypeInference", + "line": 128, + "column": 33, + "endLine": 128, + "endColumn": 37, + "problem": "LimitedLiteralType", "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "Literal types are restricted(arkts-limited-literal-types)", "severity": "ERROR" }, { - "line": 86, - "column": 12, - "endLine": 88, - "endColumn": 4, - "problem": "LimitedReturnTypeInference", + "line": 128, + "column": 39, + "endLine": 128, + "endColumn": 44, + "problem": "LimitedLiteralType", "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "Literal types are restricted(arkts-limited-literal-types)", "severity": "ERROR" }, { - "line": 97, - "column": 12, - "endLine": 99, - "endColumn": 4, - "problem": "LimitedReturnTypeInference", + "line": 132, + "column": 3, + "endLine": 132, + "endColumn": 11, + "problem": "InvalidIdentifier", "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", "severity": "ERROR" }, { - "line": 104, - "column": 12, - "endLine": 106, - "endColumn": 4, - "problem": "LimitedReturnTypeInference", + "line": 139, + "column": 3, + "endLine": 139, + "endColumn": 11, + "problem": "ExplicitFunctionType", + "autofix": [ + { + "replacementText": "callback.unSafeCall", + "start": 2921, + "end": 2929 + } + ], "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "The function type should be explicit (arkts-no-ts-like-function-call)", "severity": "ERROR" }, { - "line": 110, - "column": 3, - "endLine": 110, - "endColumn": 4, + "line": 150, + "column": 16, + "endLine": 150, + "endColumn": 21, "problem": "LimitedReturnTypeInference", "suggest": "", "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", "severity": "ERROR" }, { - "line": 114, - "column": 3, - "endLine": 114, - "endColumn": 5, - "problem": "LimitedReturnTypeInference", + "line": 151, + "column": 14, + "endLine": 151, + "endColumn": 22, + "problem": "DynamicCtorCall", "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", "severity": "ERROR" }, { - "line": 122, - "column": 3, - "endLine": 122, - "endColumn": 5, - "problem": "LimitedReturnTypeInference", + "line": 154, + "column": 9, + "endLine": 154, + "endColumn": 31, + "problem": "AnyType", "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, { - "line": 126, - "column": 3, - "endLine": 126, - "endColumn": 5, - "problem": "LimitedReturnTypeInference", + "line": 160, + "column": 62, + "endLine": 160, + "endColumn": 66, + "problem": "ExplicitFunctionType", + "autofix": [ + { + "replacementText": "curr.unSafeCall", + "start": 3458, + "end": 3462 + } + ], "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "The function type should be explicit (arkts-no-ts-like-function-call)", "severity": "ERROR" }, { - "line": 131, - "column": 10, - "endLine": 131, - "endColumn": 30, - "problem": "LimitedReturnTypeInference", + "line": 160, + "column": 67, + "endLine": 160, + "endColumn": 71, + "problem": "ExplicitFunctionType", + "autofix": [ + { + "replacementText": "prev.unSafeCall", + "start": 3463, + "end": 3467 + } + ], "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "The function type should be explicit (arkts-no-ts-like-function-call)", "severity": "ERROR" }, { - "line": 135, - "column": 18, - "endLine": 135, - "endColumn": 40, - "problem": "LimitedReturnTypeInference", + "line": 166, + "column": 1, + "endLine": 166, + "endColumn": 3, + "problem": "ExplicitFunctionType", + "autofix": [ + { + "replacementText": "f1.unSafeCall", + "start": 3586, + "end": 3588 + } + ], "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "The function type should be explicit (arkts-no-ts-like-function-call)", "severity": "ERROR" }, { - "line": 139, - "column": 3, - "endLine": 139, - "endColumn": 10, - "problem": "LimitedReturnTypeInference", + "line": 172, + "column": 1, + "endLine": 172, + "endColumn": 8, + "problem": "ExplicitFunctionType", + "autofix": [ + { + "replacementText": "ab3.fn3.unSafeCall", + "start": 3656, + "end": 3663 + } + ], "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "The function type should be explicit (arkts-no-ts-like-function-call)", "severity": "ERROR" }, { - "line": 144, - "column": 3, - "endLine": 144, - "endColumn": 7, - "problem": "LimitedReturnTypeInference", + "line": 175, + "column": 1, + "endLine": 175, + "endColumn": 8, + "problem": "ExplicitFunctionType", + "autofix": [ + { + "replacementText": "fn29[1].unSafeCall", + "start": 3697, + "end": 3704 + } + ], "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "The function type should be explicit (arkts-no-ts-like-function-call)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/main/explicit_function_type.ets.migrate.ets b/ets2panda/linter/test/main/explicit_function_type.ets.migrate.ets new file mode 100644 index 0000000000..e5584d49c7 --- /dev/null +++ b/ets2panda/linter/test/main/explicit_function_type.ets.migrate.ets @@ -0,0 +1,175 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let f1: Function = () => {}; // NOT OK +let g1: Function = () => { }; // NOT OK +let h1: Function = new Function('return 42'); // NOT OK +let g2 = () => { }; // OK +let h2 = new Function('return 42'); // NOT OK +let j1 = () => {}; // OK +let f2 = (x: number) => x + 1; // OK + + +type F = () => R; +type F1 = (p: P) => R; +type F2 = (p1: P1, p2: P2) => R; + +let f3: F = () => {}; // OK +let g3: F = () => 42; // OK +let h3: F1 = (s: string) => s.length; // OK +let i: F2 = (n: number, s: string) => s.length > n; // OK + +export let add: (a: number, b: number) => number; // OK +export let add1: (a: string) => object; // OK + +interface C2 { + f2: Function // NOK +} + +class A3 { + func3: Function = () => {} // NOK +} + +class A4 extends A3 { + f4: Function = () => {} // NOK +} + +interface C5 { + a5; +} + +class D5 implements C5 { + a5: Function = () => {} // NOK +} + +function run6(fn: Function) { + fn.unSafeCall(); +} + +function getFunction8(): Function { + return () => {}; +} + +abstract class F17 { + abstract f17: Function; +} + +class H23 { + async foo1(): Promise { + return Function; + } +} + +class I24 { + constructor(par: Function, par1?: string) {} +} +class I24_1 extends I24 { + constructor() { + super(Function) + } +} + + +class I25 { + constructor(par: number, par1?: string) {} + + foo3(fn: Function) { + console.log("this is Arkts1") + } +} +class I25_1 extends I25 { + constructor() { + super(2) + } + + override foo3(fn: Function): void { + console.log("this is Arkts2") + } +} + +function foo30(par1: Function, par2: Function[], par3: Function) { + console.log("ArkTs foo30") +} + +function foo31(par1?: Function) { + console.log("ArkTs foo31") +} + +function push32(...items: Function[]) { + items.forEach(item => { + }); +} + +function foo33(par1: number, par2: boolean, par3: string, par4: [string, Array]) { + console.log("ArkTs foo33") +} + +let array34 = [Function, 1, 2, 3]; + +class L36 { + foo1(); + foo1(par:Function, par1:string); + foo1(par?:Function, par1?:string){ + console.log('arkts36') + } +} + +let tup38:[['arkts'|Function, 1|true, false], string[], Function] = [['arkts', 1, false], ['arkts1', 'arkts2'], tup38_1]; + +//枚举 +enum E39 { + Function, + BLUE = 1, + YELLOW +} + +//回调参数不明确 +function handleEvent41(callback: Function) { + callback.unSafeCall("event", Date.now()); +} + +let fn43: Function = (x: number) => x + 1; +function process43(input: number): Function { + if (typeof input === "string") return fn43; + if (typeof input === "number") return fn43; + return fn43; +} + +//as +async function fetch(url: string) { + return new Animal42(); +} +const fetchData44: Function = async (url: string) => { + const res = await fetch(url); + return res as Function; +}; + +//高阶函数 +function compose45(...fns: Function[]): Function { + return fns.reduce((prev, curr) => (...args: Function[]) => curr.unSafeCall(prev.unSafeCall(...args)) as Function); +} + +export let add: (a: number, b: number) => number; +export let add1: (a: string) => object; + +f1.unSafeCall(); + +class AB3 { + fn3: Function = () => {}; +} +let ab3 = new AB3(); +ab3.fn3.unSafeCall(); + +const fn29: Function[] = []; +fn29[1].unSafeCall(); \ No newline at end of file diff --git a/ets2panda/linter/test/main/explicit_function_type.ets.migrate.json b/ets2panda/linter/test/main/explicit_function_type.ets.migrate.json new file mode 100644 index 0000000000..8b449e6619 --- /dev/null +++ b/ets2panda/linter/test/main/explicit_function_type.ets.migrate.json @@ -0,0 +1,148 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 70, + "column": 12, + "endLine": 70, + "endColumn": 20, + "problem": "ClassAsObjectError", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "ERROR" + }, + { + "line": 79, + "column": 11, + "endLine": 79, + "endColumn": 19, + "problem": "ClassAsObjectError", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "ERROR" + }, + { + "line": 118, + "column": 16, + "endLine": 118, + "endColumn": 24, + "problem": "ClassAsObjectError", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "ERROR" + }, + { + "line": 121, + "column": 3, + "endLine": 121, + "endColumn": 10, + "problem": "TsOverload", + "suggest": "", + "rule": "Class TS overloading is not supported(arkts-no-ts-overload)", + "severity": "ERROR" + }, + { + "line": 122, + "column": 3, + "endLine": 122, + "endColumn": 35, + "problem": "TsOverload", + "suggest": "", + "rule": "Class TS overloading is not supported(arkts-no-ts-overload)", + "severity": "ERROR" + }, + { + "line": 123, + "column": 3, + "endLine": 125, + "endColumn": 4, + "problem": "TsOverload", + "suggest": "", + "rule": "Class TS overloading is not supported(arkts-no-ts-overload)", + "severity": "ERROR" + }, + { + "line": 128, + "column": 31, + "endLine": 128, + "endColumn": 32, + "problem": "LimitedLiteralType", + "suggest": "", + "rule": "Literal types are restricted(arkts-limited-literal-types)", + "severity": "ERROR" + }, + { + "line": 128, + "column": 33, + "endLine": 128, + "endColumn": 37, + "problem": "LimitedLiteralType", + "suggest": "", + "rule": "Literal types are restricted(arkts-limited-literal-types)", + "severity": "ERROR" + }, + { + "line": 128, + "column": 39, + "endLine": 128, + "endColumn": 44, + "problem": "LimitedLiteralType", + "suggest": "", + "rule": "Literal types are restricted(arkts-limited-literal-types)", + "severity": "ERROR" + }, + { + "line": 132, + "column": 3, + "endLine": 132, + "endColumn": 11, + "problem": "InvalidIdentifier", + "suggest": "", + "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", + "severity": "ERROR" + }, + { + "line": 150, + "column": 16, + "endLine": 150, + "endColumn": 21, + "problem": "LimitedReturnTypeInference", + "suggest": "", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "severity": "ERROR" + }, + { + "line": 151, + "column": 14, + "endLine": 151, + "endColumn": 22, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 154, + "column": 9, + "endLine": 154, + "endColumn": 31, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/exponent.ets.args.json b/ets2panda/linter/test/main/exponent.ets.args.json index c0636ac689..0476e60c0b 100644 --- a/ets2panda/linter/test/main/exponent.ets.args.json +++ b/ets2panda/linter/test/main/exponent.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "autofix": "--arkts-2", - "arkts2": "" + "arkts2": "", + "migrate": "--arkts-2" } } diff --git a/ets2panda/linter/test/main/exponent.ets.migrate.ets b/ets2panda/linter/test/main/exponent.ets.migrate.ets new file mode 100644 index 0000000000..056294b864 --- /dev/null +++ b/ets2panda/linter/test/main/exponent.ets.migrate.ets @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +let kk: number = Math.pow(6, 3); +console.log(kk); + +let k: number = Math.pow(5, 2); +console.log(k); + +k = Math.pow(k, 2); +console.log(k); + +k = Math.pow(-1, Infinity); +console.log(k); diff --git a/ets2panda/linter/test/main/exponent.ets.migrate.json b/ets2panda/linter/test/main/exponent.ets.migrate.json new file mode 100644 index 0000000000..daeb5bf97a --- /dev/null +++ b/ets2panda/linter/test/main/exponent.ets.migrate.json @@ -0,0 +1,58 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 18, + "endLine": 16, + "endColumn": 32, + "problem": "MathPow", + "suggest": "", + "rule": "function \"Math.pow()\" behavior for ArkTS differs from Typescript version (arkts-math-pow-standard-diff)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 17, + "endLine": 19, + "endColumn": 31, + "problem": "MathPow", + "suggest": "", + "rule": "function \"Math.pow()\" behavior for ArkTS differs from Typescript version (arkts-math-pow-standard-diff)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 5, + "endLine": 22, + "endColumn": 19, + "problem": "MathPow", + "suggest": "", + "rule": "function \"Math.pow()\" behavior for ArkTS differs from Typescript version (arkts-math-pow-standard-diff)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 5, + "endLine": 25, + "endColumn": 27, + "problem": "MathPow", + "suggest": "", + "rule": "function \"Math.pow()\" behavior for ArkTS differs from Typescript version (arkts-math-pow-standard-diff)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/extend_decorator_1.ets.args.json b/ets2panda/linter/test/main/extend_decorator_1.ets.args.json index 60cb1832f2..30973c00a2 100644 --- a/ets2panda/linter/test/main/extend_decorator_1.ets.args.json +++ b/ets2panda/linter/test/main/extend_decorator_1.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/extend_decorator_1.ets.migrate.ets b/ets2panda/linter/test/main/extend_decorator_1.ets.migrate.ets new file mode 100644 index 0000000000..829d53b38a --- /dev/null +++ b/ets2panda/linter/test/main/extend_decorator_1.ets.migrate.ets @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Component, Column, Text, ColumnAttribute, Color } from '@kit.ArkUI'; + +@Component +struct MyCard { + build() { + Column() { + Text('Card') + } + .cardStyle() + } +} + +const mycolor: string = "#ffffff" + +function cardStyle(this: ColumnAttribute): this { + this.backgroundColor("#ffff00"); + this.backgroundColor("#00ffff"); + this.backgroundColor("#ff00ff"); + this.backgroundColor(mycolor); + this.backgroundColor(Color.Red); + this.borderRadius(8); + this.padding(8); + this.backgroundImagePosition({ + x: 0, + y: 0 + }); + return this; +} + +function superCard(this: ColumnAttribute, padding: number): this { + this.cardStyle(); + this.padding(10); + return this; +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/extend_decorator_1.ets.migrate.json b/ets2panda/linter/test/main/extend_decorator_1.ets.migrate.json new file mode 100644 index 0000000000..be60c93486 --- /dev/null +++ b/ets2panda/linter/test/main/extend_decorator_1.ets.migrate.json @@ -0,0 +1,178 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 31, + "column": 5, + "endLine": 31, + "endColumn": 9, + "problem": "FunctionContainsThis", + "suggest": "", + "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 5, + "endLine": 32, + "endColumn": 9, + "problem": "FunctionContainsThis", + "suggest": "", + "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 5, + "endLine": 33, + "endColumn": 9, + "problem": "FunctionContainsThis", + "suggest": "", + "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 5, + "endLine": 34, + "endColumn": 9, + "problem": "FunctionContainsThis", + "suggest": "", + "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 5, + "endLine": 35, + "endColumn": 9, + "problem": "FunctionContainsThis", + "suggest": "", + "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", + "severity": "ERROR" + }, + { + "line": 36, + "column": 5, + "endLine": 36, + "endColumn": 9, + "problem": "FunctionContainsThis", + "suggest": "", + "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 5, + "endLine": 37, + "endColumn": 9, + "problem": "FunctionContainsThis", + "suggest": "", + "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 5, + "endLine": 38, + "endColumn": 9, + "problem": "FunctionContainsThis", + "suggest": "", + "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", + "severity": "ERROR" + }, + { + "line": 42, + "column": 12, + "endLine": 42, + "endColumn": 16, + "problem": "FunctionContainsThis", + "suggest": "", + "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 20, + "endLine": 30, + "endColumn": 24, + "problem": "InvalidIdentifier", + "suggest": "", + "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 44, + "endLine": 30, + "endColumn": 48, + "problem": "ThisType", + "suggest": "", + "rule": "Type notation using \"this\" is not supported (arkts-no-typing-with-this)", + "severity": "ERROR" + }, + { + "line": 46, + "column": 5, + "endLine": 46, + "endColumn": 9, + "problem": "FunctionContainsThis", + "suggest": "", + "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", + "severity": "ERROR" + }, + { + "line": 47, + "column": 5, + "endLine": 47, + "endColumn": 9, + "problem": "FunctionContainsThis", + "suggest": "", + "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", + "severity": "ERROR" + }, + { + "line": 48, + "column": 12, + "endLine": 48, + "endColumn": 16, + "problem": "FunctionContainsThis", + "suggest": "", + "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 20, + "endLine": 45, + "endColumn": 24, + "problem": "InvalidIdentifier", + "suggest": "", + "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 61, + "endLine": 45, + "endColumn": 65, + "problem": "ThisType", + "suggest": "", + "rule": "Type notation using \"this\" is not supported (arkts-no-typing-with-this)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/extend_decorator_2.ets.args.json b/ets2panda/linter/test/main/extend_decorator_2.ets.args.json index 60cb1832f2..30973c00a2 100644 --- a/ets2panda/linter/test/main/extend_decorator_2.ets.args.json +++ b/ets2panda/linter/test/main/extend_decorator_2.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/extend_decorator_2.ets.migrate.ets b/ets2panda/linter/test/main/extend_decorator_2.ets.migrate.ets new file mode 100644 index 0000000000..c53497da05 --- /dev/null +++ b/ets2panda/linter/test/main/extend_decorator_2.ets.migrate.ets @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Component, Column, Text, ColumnAttribute, Color } from '@kit.ArkUI'; + +@Component +struct MyCard { + build() { + Column() { + Text('Card') + } + .cardStyle() + } +} + +const mycolor: string = "#ffffff" + +function cardStyle(this: ColumnAttribute): this { + this.backgroundColor("#ffff00"); + this.backgroundColor("#00ffff"); + this.backgroundColor("#ff00ff"); + this.backgroundColor(mycolor); + this.backgroundColor(Color.Red); + this.borderRadius(8); + this.padding(8); + this.backgroundImagePosition({ + x: 0, + y: 0 + }); + return this; +} + +function superCard(this: ColumnAttribute, padding: number): this { + .cardStyle() + .padding(10) +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/extend_decorator_2.ets.migrate.json b/ets2panda/linter/test/main/extend_decorator_2.ets.migrate.json new file mode 100644 index 0000000000..0f332deca6 --- /dev/null +++ b/ets2panda/linter/test/main/extend_decorator_2.ets.migrate.json @@ -0,0 +1,148 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 31, + "column": 3, + "endLine": 31, + "endColumn": 7, + "problem": "FunctionContainsThis", + "suggest": "", + "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 3, + "endLine": 32, + "endColumn": 7, + "problem": "FunctionContainsThis", + "suggest": "", + "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 3, + "endLine": 33, + "endColumn": 7, + "problem": "FunctionContainsThis", + "suggest": "", + "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 3, + "endLine": 34, + "endColumn": 7, + "problem": "FunctionContainsThis", + "suggest": "", + "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 3, + "endLine": 35, + "endColumn": 7, + "problem": "FunctionContainsThis", + "suggest": "", + "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", + "severity": "ERROR" + }, + { + "line": 36, + "column": 3, + "endLine": 36, + "endColumn": 7, + "problem": "FunctionContainsThis", + "suggest": "", + "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 3, + "endLine": 37, + "endColumn": 7, + "problem": "FunctionContainsThis", + "suggest": "", + "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 3, + "endLine": 38, + "endColumn": 7, + "problem": "FunctionContainsThis", + "suggest": "", + "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", + "severity": "ERROR" + }, + { + "line": 42, + "column": 10, + "endLine": 42, + "endColumn": 14, + "problem": "FunctionContainsThis", + "suggest": "", + "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 20, + "endLine": 30, + "endColumn": 24, + "problem": "InvalidIdentifier", + "suggest": "", + "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 44, + "endLine": 30, + "endColumn": 48, + "problem": "ThisType", + "suggest": "", + "rule": "Type notation using \"this\" is not supported (arkts-no-typing-with-this)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 20, + "endLine": 45, + "endColumn": 24, + "problem": "InvalidIdentifier", + "suggest": "", + "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 61, + "endLine": 45, + "endColumn": 65, + "problem": "ThisType", + "suggest": "", + "rule": "Type notation using \"this\" is not supported (arkts-no-typing-with-this)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/extends_expression.ets b/ets2panda/linter/test/main/extends_expression.ets index d95b96aee4..fde6f5729d 100755 --- a/ets2panda/linter/test/main/extends_expression.ets +++ b/ets2panda/linter/test/main/extends_expression.ets @@ -12,6 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +'use static' + class A { v: number = 0 } diff --git a/ets2panda/linter/test/main/extends_expression.ets.arkts2.json b/ets2panda/linter/test/main/extends_expression.ets.arkts2.json index 1c73b16814..d157d2e206 100755 --- a/ets2panda/linter/test/main/extends_expression.ets.arkts2.json +++ b/ets2panda/linter/test/main/extends_expression.ets.arkts2.json @@ -13,116 +13,116 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "result": [ - { - "line": 19, - "column": 9, - "endLine": 19, - "endColumn": 10, - "problem": "ClassAsObjectError", - "suggest": "", - "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", - "severity": "ERROR" - }, - { - "line": 21, - "column": 17, - "endLine": 21, - "endColumn": 18, - "problem": "ExtendsExpression", - "suggest": "", - "rule": "Extends or implements expression are not supported(arkts-no-extends-expression)", - "severity": "ERROR" - }, - { - "line": 29, - "column": 37, - "endLine": 29, - "endColumn": 44, - "problem": "InterfaceExtendsClass", - "suggest": "", - "rule": "Interfaces cannot extend classes (arkts-extends-only-class)", - "severity": "ERROR" - }, - { - "line": 45, - "column": 5, - "endLine": 45, - "endColumn": 10, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 56, - "column": 22, - "endLine": 56, - "endColumn": 23, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 56, - "column": 24, - "endLine": 56, - "endColumn": 32, - "problem": "ConstructorType", - "suggest": "", - "rule": "Use \"class\" instead of a type with constructor signature (arkts-no-ctor-signatures-type)", - "severity": "ERROR" - }, - { - "line": 59, - "column": 10, - "endLine": 59, - "endColumn": 22, - "problem": "LimitedReturnTypeInference", - "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", - "severity": "ERROR" - }, - { - "line": 71, - "column": 12, - "endLine": 71, - "endColumn": 13, - "problem": "ClassAsObjectError", - "suggest": "", - "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", - "severity": "ERROR" - }, - { - "line": 73, - "column": 12, - "endLine": 73, - "endColumn": 13, - "problem": "ClassAsObjectError", - "suggest": "", - "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", - "severity": "ERROR" - }, - { - "line": 77, - "column": 20, - "endLine": 77, - "endColumn": 39, - "problem": "ExtendsExpression", - "suggest": "", - "rule": "Extends or implements expression are not supported(arkts-no-extends-expression)", - "severity": "ERROR" - }, - { - "line": 83, - "column": 21, - "endLine": 83, - "endColumn": 39, - "problem": "ExtendsExpression", - "suggest": "", - "rule": "Extends or implements expression are not supported(arkts-no-extends-expression)", - "severity": "ERROR" - } - ] + "result": [ + { + "line": 21, + "column": 9, + "endLine": 21, + "endColumn": 10, + "problem": "ClassAsObjectError", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 17, + "endLine": 23, + "endColumn": 18, + "problem": "ExtendsExpression", + "suggest": "", + "rule": "Extends or implements expression are not supported(arkts-no-extends-expression)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 37, + "endLine": 31, + "endColumn": 44, + "problem": "InterfaceExtendsClass", + "suggest": "", + "rule": "Interfaces cannot extend classes (arkts-extends-only-class)", + "severity": "ERROR" + }, + { + "line": 47, + "column": 5, + "endLine": 47, + "endColumn": 10, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 58, + "column": 22, + "endLine": 58, + "endColumn": 23, + "problem": "ObjectTypeLiteral", + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 58, + "column": 24, + "endLine": 58, + "endColumn": 32, + "problem": "ConstructorType", + "suggest": "", + "rule": "Use \"class\" instead of a type with constructor signature (arkts-no-ctor-signatures-type)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 10, + "endLine": 61, + "endColumn": 22, + "problem": "LimitedReturnTypeInference", + "suggest": "", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 12, + "endLine": 73, + "endColumn": 13, + "problem": "ClassAsObjectError", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "ERROR" + }, + { + "line": 75, + "column": 12, + "endLine": 75, + "endColumn": 13, + "problem": "ClassAsObjectError", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "ERROR" + }, + { + "line": 79, + "column": 20, + "endLine": 79, + "endColumn": 39, + "problem": "ExtendsExpression", + "suggest": "", + "rule": "Extends or implements expression are not supported(arkts-no-extends-expression)", + "severity": "ERROR" + }, + { + "line": 85, + "column": 21, + "endLine": 85, + "endColumn": 39, + "problem": "ExtendsExpression", + "suggest": "", + "rule": "Extends or implements expression are not supported(arkts-no-extends-expression)", + "severity": "ERROR" + } + ] } diff --git a/ets2panda/linter/test/main/extends_expression.ets.json b/ets2panda/linter/test/main/extends_expression.ets.json index d8afa3d8c8..390e52b781 100644 --- a/ets2panda/linter/test/main/extends_expression.ets.json +++ b/ets2panda/linter/test/main/extends_expression.ets.json @@ -13,76 +13,76 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "result": [ - { - "line": 19, - "column": 9, - "endLine": 19, - "endColumn": 10, - "problem": "ClassAsObject", - "suggest": "", - "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", - "severity": "WARNING" - }, - { - "line": 29, - "column": 37, - "endLine": 29, - "endColumn": 44, - "problem": "InterfaceExtendsClass", - "suggest": "", - "rule": "Interfaces cannot extend classes (arkts-extends-only-class)", - "severity": "ERROR" - }, - { - "line": 45, - "column": 5, - "endLine": 45, - "endColumn": 10, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 56, - "column": 22, - "endLine": 56, - "endColumn": 23, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 56, - "column": 24, - "endLine": 56, - "endColumn": 32, - "problem": "ConstructorType", - "suggest": "", - "rule": "Use \"class\" instead of a type with constructor signature (arkts-no-ctor-signatures-type)", - "severity": "ERROR" - }, - { - "line": 71, - "column": 12, - "endLine": 71, - "endColumn": 13, - "problem": "ClassAsObject", - "suggest": "", - "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", - "severity": "WARNING" - }, - { - "line": 73, - "column": 12, - "endLine": 73, - "endColumn": 13, - "problem": "ClassAsObject", - "suggest": "", - "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", - "severity": "WARNING" - } - ] -} \ No newline at end of file + "result": [ + { + "line": 21, + "column": 9, + "endLine": 21, + "endColumn": 10, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 31, + "column": 37, + "endLine": 31, + "endColumn": 44, + "problem": "InterfaceExtendsClass", + "suggest": "", + "rule": "Interfaces cannot extend classes (arkts-extends-only-class)", + "severity": "ERROR" + }, + { + "line": 47, + "column": 5, + "endLine": 47, + "endColumn": 10, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 58, + "column": 22, + "endLine": 58, + "endColumn": 23, + "problem": "ObjectTypeLiteral", + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 58, + "column": 24, + "endLine": 58, + "endColumn": 32, + "problem": "ConstructorType", + "suggest": "", + "rule": "Use \"class\" instead of a type with constructor signature (arkts-no-ctor-signatures-type)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 12, + "endLine": 73, + "endColumn": 13, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 75, + "column": 12, + "endLine": 75, + "endColumn": 13, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + } + ] +} diff --git a/ets2panda/linter/test/main/func_inferred_type_args.ets b/ets2panda/linter/test/main/func_inferred_type_args.ets index 91bf75c577..f5bcd5b762 100644 --- a/ets2panda/linter/test/main/func_inferred_type_args.ets +++ b/ets2panda/linter/test/main/func_inferred_type_args.ets @@ -14,7 +14,17 @@ */ import { bad_func } from "./dynamic_lib" - +import { Deque } from '@kit.ArkTS'; +import ArrayList from '@ohos.util.ArrayList'; +import Deque from '@ohos.util.Deque'; +import HashMap from '@ohos.util.HashMap'; +import HashSet from '@ohos.util.HashSet'; +import LinkedList from '@ohos.util.LinkedList'; +import PlainArray from '@ohos.util.PlainArray'; +import Queue from '@ohos.util.Queue'; +import TreeMap from '@ohos.util.TreeMap'; +import TreeSet from '@ohos.util.TreeSet'; +import { LinkedList } from '@kit.ArkTS'; function choose(x: T, y: T): T { return Math.random() < 0.5 ? x : y } @@ -89,3 +99,36 @@ const stringBox1: Box1 = new Box1(); // NOK const stringBox2: Box1 = new Box1(); // OK const stringBox3: Box1 = new Box1(); // OK const stringBox4 = new Box1(); // NOK + +let de: Deque = new Deque(); //error +function newDeque():Deque{ + return new Deque(); //error +} +class D{ + dd: Deque; + constructor(){ + new Deque(); //error + } + + initDD(){ + dd = new Deque(); + } +} + +class Base{} +class NewClass extends Base{} +export let obj = new NewClass(); +class NewClass2 extends Base{} +export let obj2 = new NewClass2(); + +let test_arrayList_e: ArrayList = new ArrayList(); // +let test_deque_e: Deque = new Deque(); // +let test_hashMap_e: HashMap = new HashMap(); // +let test_hashSet_e: HashSet = new HashSet(); // +let test_linkedList_e: LinkedList = new LinkedList(); // +let test_plainArray_e: PlainArray = new PlainArray(); // +let test_queue_e: Queue = new Queue(); // +let test_treeMap_e: TreeMap = new TreeMap(); // +let test_treeSet_e: TreeSet = new TreeSet(); // +let test_treeSet_set_e: TreeSet> = new TreeSet(); +let listenerList: LinkedList = new LinkedList(); \ No newline at end of file diff --git a/ets2panda/linter/test/main/func_inferred_type_args.ets.arkts2.json b/ets2panda/linter/test/main/func_inferred_type_args.ets.arkts2.json index ac441596b1..3d6311cc42 100755 --- a/ets2panda/linter/test/main/func_inferred_type_args.ets.arkts2.json +++ b/ets2panda/linter/test/main/func_inferred_type_args.ets.arkts2.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2023-2025 Huawei Device Co., Ltd.", + "Copyright (c) 2023-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -15,9 +15,9 @@ ], "result": [ { - "line": 21, + "line": 31, "column": 5, - "endLine": 21, + "endLine": 31, "endColumn": 23, "problem": "NumericSemantics", "suggest": "", @@ -25,9 +25,9 @@ "severity": "ERROR" }, { - "line": 26, + "line": 36, "column": 5, - "endLine": 26, + "endLine": 36, "endColumn": 16, "problem": "UnknownType", "suggest": "", @@ -35,9 +35,9 @@ "severity": "ERROR" }, { - "line": 26, + "line": 36, "column": 9, - "endLine": 26, + "endLine": 36, "endColumn": 16, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -45,9 +45,9 @@ "severity": "ERROR" }, { - "line": 28, + "line": 38, "column": 1, - "endLine": 30, + "endLine": 40, "endColumn": 2, "problem": "NumericSemantics", "suggest": "", @@ -55,9 +55,9 @@ "severity": "ERROR" }, { - "line": 28, + "line": 38, "column": 21, - "endLine": 28, + "endLine": 38, "endColumn": 24, "problem": "AnyType", "suggest": "", @@ -65,9 +65,9 @@ "severity": "ERROR" }, { - "line": 31, + "line": 41, "column": 1, - "endLine": 31, + "endLine": 41, "endColumn": 6, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -75,9 +75,9 @@ "severity": "ERROR" }, { - "line": 38, + "line": 48, "column": 1, - "endLine": 38, + "endLine": 48, "endColumn": 6, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -85,9 +85,9 @@ "severity": "ERROR" }, { - "line": 42, + "line": 52, "column": 5, - "endLine": 42, + "endLine": 52, "endColumn": 14, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -95,9 +95,9 @@ "severity": "ERROR" }, { - "line": 43, + "line": 53, "column": 1, - "endLine": 43, + "endLine": 53, "endColumn": 31, "problem": "NumericSemantics", "suggest": "", @@ -105,9 +105,9 @@ "severity": "ERROR" }, { - "line": 46, + "line": 56, "column": 8, - "endLine": 46, + "endLine": 56, "endColumn": 11, "problem": "AnyType", "suggest": "", @@ -115,9 +115,9 @@ "severity": "ERROR" }, { - "line": 47, + "line": 57, "column": 16, - "endLine": 47, + "endLine": 57, "endColumn": 19, "problem": "AnyType", "suggest": "", @@ -125,9 +125,9 @@ "severity": "ERROR" }, { - "line": 49, + "line": 59, "column": 8, - "endLine": 49, + "endLine": 59, "endColumn": 9, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -135,9 +135,9 @@ "severity": "ERROR" }, { - "line": 51, + "line": 61, "column": 5, - "endLine": 51, + "endLine": 61, "endColumn": 20, "problem": "UnknownType", "suggest": "", @@ -145,9 +145,9 @@ "severity": "ERROR" }, { - "line": 51, + "line": 61, "column": 11, - "endLine": 51, + "endLine": 61, "endColumn": 20, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -155,9 +155,9 @@ "severity": "ERROR" }, { - "line": 53, + "line": 63, "column": 3, - "endLine": 53, + "endLine": 63, "endColumn": 22, "problem": "TsOverload", "suggest": "", @@ -165,9 +165,9 @@ "severity": "ERROR" }, { - "line": 54, + "line": 64, "column": 3, - "endLine": 54, + "endLine": 64, "endColumn": 19, "problem": "TsOverload", "suggest": "", @@ -175,9 +175,9 @@ "severity": "ERROR" }, { - "line": 56, + "line": 66, "column": 5, - "endLine": 56, + "endLine": 66, "endColumn": 16, "problem": "UnknownType", "suggest": "", @@ -185,9 +185,9 @@ "severity": "ERROR" }, { - "line": 56, + "line": 66, "column": 9, - "endLine": 56, + "endLine": 66, "endColumn": 16, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -195,9 +195,9 @@ "severity": "ERROR" }, { - "line": 58, + "line": 68, "column": 5, - "endLine": 58, + "endLine": 68, "endColumn": 17, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -205,9 +205,9 @@ "severity": "ERROR" }, { - "line": 58, + "line": 68, "column": 11, - "endLine": 58, + "endLine": 68, "endColumn": 16, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -215,9 +215,9 @@ "severity": "ERROR" }, { - "line": 59, + "line": 69, "column": 5, - "endLine": 59, + "endLine": 69, "endColumn": 15, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -225,9 +225,9 @@ "severity": "ERROR" }, { - "line": 60, + "line": 70, "column": 5, - "endLine": 60, + "endLine": 70, "endColumn": 26, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -235,9 +235,9 @@ "severity": "ERROR" }, { - "line": 60, + "line": 70, "column": 19, - "endLine": 60, + "endLine": 70, "endColumn": 22, "problem": "AnyType", "suggest": "", @@ -245,9 +245,9 @@ "severity": "ERROR" }, { - "line": 62, + "line": 72, "column": 10, - "endLine": 62, + "endLine": 72, "endColumn": 11, "problem": "ObjectTypeLiteral", "suggest": "", @@ -255,9 +255,9 @@ "severity": "ERROR" }, { - "line": 69, + "line": 79, "column": 11, - "endLine": 69, + "endLine": 79, "endColumn": 14, "problem": "AnyType", "suggest": "", @@ -265,9 +265,9 @@ "severity": "ERROR" }, { - "line": 79, + "line": 89, "column": 5, - "endLine": 79, + "endLine": 89, "endColumn": 23, "problem": "AnyType", "suggest": "", @@ -275,9 +275,9 @@ "severity": "ERROR" }, { - "line": 79, + "line": 89, "column": 12, - "endLine": 79, + "endLine": 89, "endColumn": 23, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -285,9 +285,9 @@ "severity": "ERROR" }, { - "line": 80, + "line": 90, "column": 5, - "endLine": 80, + "endLine": 90, "endColumn": 21, "problem": "AnyType", "suggest": "", @@ -295,9 +295,9 @@ "severity": "ERROR" }, { - "line": 80, + "line": 90, "column": 5, - "endLine": 80, + "endLine": 90, "endColumn": 21, "problem": "AnyType", "suggest": "", @@ -305,9 +305,9 @@ "severity": "ERROR" }, { - "line": 80, + "line": 90, "column": 12, - "endLine": 80, + "endLine": 90, "endColumn": 21, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -315,9 +315,9 @@ "severity": "ERROR" }, { - "line": 81, + "line": 91, "column": 5, - "endLine": 81, + "endLine": 91, "endColumn": 39, "problem": "AnyType", "suggest": "", @@ -325,9 +325,9 @@ "severity": "ERROR" }, { - "line": 81, + "line": 91, "column": 24, - "endLine": 81, + "endLine": 91, "endColumn": 37, "problem": "DynamicCtorCall", "suggest": "", @@ -335,9 +335,9 @@ "severity": "ERROR" }, { - "line": 81, + "line": 91, "column": 20, - "endLine": 81, + "endLine": 91, "endColumn": 39, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -345,9 +345,9 @@ "severity": "ERROR" }, { - "line": 82, + "line": 92, "column": 5, - "endLine": 82, + "endLine": 92, "endColumn": 52, "problem": "UnknownType", "suggest": "", @@ -355,9 +355,9 @@ "severity": "ERROR" }, { - "line": 82, + "line": 92, "column": 16, - "endLine": 82, + "endLine": 92, "endColumn": 52, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -365,9 +365,9 @@ "severity": "ERROR" }, { - "line": 83, + "line": 93, "column": 5, - "endLine": 83, + "endLine": 93, "endColumn": 29, "problem": "AnyType", "suggest": "", @@ -375,9 +375,9 @@ "severity": "ERROR" }, { - "line": 83, + "line": 93, "column": 16, - "endLine": 83, + "endLine": 93, "endColumn": 29, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -385,9 +385,9 @@ "severity": "ERROR" }, { - "line": 84, + "line": 94, "column": 16, - "endLine": 84, + "endLine": 94, "endColumn": 29, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -395,9 +395,9 @@ "severity": "ERROR" }, { - "line": 88, + "line": 98, "column": 34, - "endLine": 88, + "endLine": 98, "endColumn": 44, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -405,9 +405,9 @@ "severity": "ERROR" }, { - "line": 91, + "line": 101, "column": 7, - "endLine": 91, + "endLine": 101, "endColumn": 30, "problem": "UnknownType", "suggest": "", @@ -415,9 +415,9 @@ "severity": "ERROR" }, { - "line": 91, + "line": 101, "column": 20, - "endLine": 91, + "endLine": 101, "endColumn": 30, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -425,9 +425,299 @@ "severity": "ERROR" }, { - "line": 63, + "line": 103, + "column": 21, + "endLine": 103, + "endColumn": 26, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 103, + "column": 17, + "endLine": 103, + "endColumn": 28, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 105, + "column": 14, + "endLine": 105, + "endColumn": 19, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 105, + "column": 10, + "endLine": 105, + "endColumn": 21, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 110, + "column": 9, + "endLine": 110, + "endColumn": 14, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 110, + "column": 5, + "endLine": 110, + "endColumn": 16, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 114, + "column": 14, + "endLine": 114, + "endColumn": 19, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 124, + "column": 47, + "endLine": 124, + "endColumn": 56, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 124, + "column": 43, + "endLine": 124, + "endColumn": 58, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 125, + "column": 39, + "endLine": 125, + "endColumn": 44, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 125, + "column": 35, + "endLine": 125, + "endColumn": 46, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 126, + "column": 51, + "endLine": 126, + "endColumn": 58, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 126, + "column": 47, + "endLine": 126, + "endColumn": 60, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 127, + "column": 43, + "endLine": 127, + "endColumn": 50, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 127, + "column": 39, + "endLine": 127, + "endColumn": 52, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 128, + "column": 49, + "endLine": 128, + "endColumn": 59, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 128, + "column": 45, + "endLine": 128, + "endColumn": 61, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 129, + "column": 49, + "endLine": 129, + "endColumn": 59, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 129, + "column": 45, + "endLine": 129, + "endColumn": 61, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 130, + "column": 39, + "endLine": 130, + "endColumn": 44, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 130, + "column": 35, + "endLine": 130, + "endColumn": 46, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 131, + "column": 51, + "endLine": 131, + "endColumn": 58, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 131, + "column": 47, + "endLine": 131, + "endColumn": 60, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 132, + "column": 43, + "endLine": 132, + "endColumn": 50, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 132, + "column": 39, + "endLine": 132, + "endColumn": 52, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 133, + "column": 56, + "endLine": 133, + "endColumn": 63, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 133, + "column": 52, + "endLine": 133, + "endColumn": 65, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 134, + "column": 44, + "endLine": 134, + "endColumn": 54, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 134, + "column": 40, + "endLine": 134, + "endColumn": 56, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 73, "column": 1, - "endLine": 63, + "endLine": 73, "endColumn": 2, "problem": "StrictDiagnostic", "suggest": "Variable 'd' is used before being assigned.", diff --git a/ets2panda/linter/test/main/func_inferred_type_args.ets.json b/ets2panda/linter/test/main/func_inferred_type_args.ets.json index bd681a3a67..2d86c954b2 100644 --- a/ets2panda/linter/test/main/func_inferred_type_args.ets.json +++ b/ets2panda/linter/test/main/func_inferred_type_args.ets.json @@ -1,278 +1,278 @@ { - "copyright": [ - "Copyright (c) 2023-2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "result": [ - { - "line": 26, - "column": 5, - "endLine": 26, - "endColumn": 16, - "problem": "UnknownType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 26, - "column": 9, - "endLine": 26, - "endColumn": 16, - "problem": "GenericCallNoTypeArgs", - "suggest": "", - "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", - "severity": "ERROR" - }, - { - "line": 28, - "column": 21, - "endLine": 28, - "endColumn": 24, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 31, - "column": 1, - "endLine": 31, - "endColumn": 6, - "problem": "GenericCallNoTypeArgs", - "suggest": "", - "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", - "severity": "ERROR" - }, - { - "line": 38, - "column": 1, - "endLine": 38, - "endColumn": 6, - "problem": "GenericCallNoTypeArgs", - "suggest": "", - "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", - "severity": "ERROR" - }, - { - "line": 46, - "column": 8, - "endLine": 46, - "endColumn": 11, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 47, - "column": 16, - "endLine": 47, - "endColumn": 19, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 49, - "column": 8, - "endLine": 49, - "endColumn": 9, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 51, - "column": 5, - "endLine": 51, - "endColumn": 20, - "problem": "UnknownType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 51, - "column": 11, - "endLine": 51, - "endColumn": 20, - "problem": "GenericCallNoTypeArgs", - "suggest": "", - "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", - "severity": "ERROR" - }, - { - "line": 56, - "column": 5, - "endLine": 56, - "endColumn": 16, - "problem": "UnknownType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 56, - "column": 9, - "endLine": 56, - "endColumn": 16, - "problem": "GenericCallNoTypeArgs", - "suggest": "", - "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", - "severity": "ERROR" - }, - { - "line": 58, - "column": 11, - "endLine": 58, - "endColumn": 16, - "problem": "GenericCallNoTypeArgs", - "suggest": "", - "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", - "severity": "ERROR" - }, - { - "line": 60, - "column": 19, - "endLine": 60, - "endColumn": 22, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 62, - "column": 10, - "endLine": 62, - "endColumn": 11, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 69, - "column": 11, - "endLine": 69, - "endColumn": 14, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 79, - "column": 5, - "endLine": 79, - "endColumn": 23, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 80, - "column": 5, - "endLine": 80, - "endColumn": 21, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 80, - "column": 5, - "endLine": 80, - "endColumn": 21, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 81, - "column": 5, - "endLine": 81, - "endColumn": 39, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 82, - "column": 5, - "endLine": 82, - "endColumn": 52, - "problem": "UnknownType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 82, - "column": 16, - "endLine": 82, - "endColumn": 52, - "problem": "GenericCallNoTypeArgs", - "suggest": "", - "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", - "severity": "ERROR" - }, - { - "line": 83, - "column": 5, - "endLine": 83, - "endColumn": 29, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 91, - "column": 7, - "endLine": 91, - "endColumn": 30, - "problem": "UnknownType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 91, - "column": 20, - "endLine": 91, - "endColumn": 30, - "problem": "GenericCallNoTypeArgs", - "suggest": "", - "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", - "severity": "ERROR" - }, - { - "line": 63, - "column": 1, - "endLine": 63, - "endColumn": 2, - "problem": "StrictDiagnostic", - "suggest": "Variable 'd' is used before being assigned.", - "rule": "Variable 'd' is used before being assigned.", - "severity": "ERROR" - } - ] -} + "copyright": [ + "Copyright (c) 2023-2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 36, + "column": 5, + "endLine": 36, + "endColumn": 16, + "problem": "UnknownType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 36, + "column": 9, + "endLine": 36, + "endColumn": 16, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 21, + "endLine": 38, + "endColumn": 24, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 1, + "endLine": 41, + "endColumn": 6, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 48, + "column": 1, + "endLine": 48, + "endColumn": 6, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 56, + "column": 8, + "endLine": 56, + "endColumn": 11, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 57, + "column": 16, + "endLine": 57, + "endColumn": 19, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 59, + "column": 8, + "endLine": 59, + "endColumn": 9, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 5, + "endLine": 61, + "endColumn": 20, + "problem": "UnknownType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 11, + "endLine": 61, + "endColumn": 20, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 66, + "column": 5, + "endLine": 66, + "endColumn": 16, + "problem": "UnknownType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 66, + "column": 9, + "endLine": 66, + "endColumn": 16, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 68, + "column": 11, + "endLine": 68, + "endColumn": 16, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 70, + "column": 19, + "endLine": 70, + "endColumn": 22, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 10, + "endLine": 72, + "endColumn": 11, + "problem": "ObjectTypeLiteral", + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 79, + "column": 11, + "endLine": 79, + "endColumn": 14, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 89, + "column": 5, + "endLine": 89, + "endColumn": 23, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 90, + "column": 5, + "endLine": 90, + "endColumn": 21, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 90, + "column": 5, + "endLine": 90, + "endColumn": 21, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 91, + "column": 5, + "endLine": 91, + "endColumn": 39, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 92, + "column": 5, + "endLine": 92, + "endColumn": 52, + "problem": "UnknownType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 92, + "column": 16, + "endLine": 92, + "endColumn": 52, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 93, + "column": 5, + "endLine": 93, + "endColumn": 29, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 101, + "column": 7, + "endLine": 101, + "endColumn": 30, + "problem": "UnknownType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 101, + "column": 20, + "endLine": 101, + "endColumn": 30, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 1, + "endLine": 73, + "endColumn": 2, + "problem": "StrictDiagnostic", + "suggest": "Variable 'd' is used before being assigned.", + "rule": "Variable 'd' is used before being assigned.", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/func_inferred_type_args_2.ets b/ets2panda/linter/test/main/func_inferred_type_args_2.ets new file mode 100644 index 0000000000..636e016aea --- /dev/null +++ b/ets2panda/linter/test/main/func_inferred_type_args_2.ets @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +const irreparableArr = new Array(); +let repairableArr: Array = new Array(); +repairableArr = new Array(); + +const irreparableMap = new Map(); +const repairableMap: Map = new Map(); +repairableMap = new Map(); + +class MyClass { + public irreparableMap = new Map(); + public repairableSet: Set = new Map(); + public repairableMap: Map string[]> = new Map(); + static repairableStaticMap: Map string[]> = new Map(); + constructor() {} +} + +const irreparableA = new MyClass(); +const irreparableB = new MyClass(); +const repairableC: MyClass = new MyClass(); +repairableC.irreparableMap = new Map(); +repairableC.repairableSet = new Set(); +repairableC.repairableMap = new Map(); +MyClass.repairableStaticMap = new Map(); + +const promise: Promise = new Promise(()=> {return ''}); + +function testA(): Map { + return new Map(); +} + +async function testB(): Promise> { + return new Map(); +} + +function testC(): Map { + return new Set(); +} + +async function testD(): Promise> { + return new Set(); +} + +class MyClassB { + testA(): Map { + return new Map(); + } + + async testB(): Promise> { + return new Map(); + } + + testC(): Map { + return new Set(); + } + + async testD(): Promise> { + return new Set(); + } +} diff --git a/ets2panda/linter/test/main/func_inferred_type_args_2.ets.args.json b/ets2panda/linter/test/main/func_inferred_type_args_2.ets.args.json new file mode 100644 index 0000000000..30973c00a2 --- /dev/null +++ b/ets2panda/linter/test/main/func_inferred_type_args_2.ets.args.json @@ -0,0 +1,21 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2", + "migrate": "--arkts-2" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/func_inferred_type_args_2.ets.arkts2.json b/ets2panda/linter/test/main/func_inferred_type_args_2.ets.arkts2.json new file mode 100644 index 0000000000..8332379fa7 --- /dev/null +++ b/ets2panda/linter/test/main/func_inferred_type_args_2.ets.arkts2.json @@ -0,0 +1,378 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 7, + "endLine": 16, + "endColumn": 35, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 16, + "column": 24, + "endLine": 16, + "endColumn": 35, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 36, + "endLine": 17, + "endColumn": 47, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 17, + "endLine": 18, + "endColumn": 28, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 7, + "endLine": 20, + "endColumn": 33, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 7, + "endLine": 20, + "endColumn": 33, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 24, + "endLine": 20, + "endColumn": 33, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 44, + "endLine": 21, + "endColumn": 53, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 17, + "endLine": 22, + "endColumn": 26, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 3, + "endLine": 25, + "endColumn": 37, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 3, + "endLine": 25, + "endColumn": 37, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 27, + "endLine": 25, + "endColumn": 36, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 10, + "endLine": 26, + "endColumn": 23, + "problem": "StructuralIdentity", + "suggest": "", + "rule": "Structural typing is not supported (arkts-no-structural-typing)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 39, + "endLine": 26, + "endColumn": 48, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 55, + "endLine": 27, + "endColumn": 64, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 61, + "endLine": 28, + "endColumn": 70, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 7, + "endLine": 32, + "endColumn": 35, + "problem": "UnknownType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 22, + "endLine": 32, + "endColumn": 35, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 38, + "endLine": 34, + "endColumn": 51, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 30, + "endLine": 35, + "endColumn": 39, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 36, + "column": 29, + "endLine": 36, + "endColumn": 38, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 29, + "endLine": 37, + "endColumn": 38, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 31, + "endLine": 38, + "endColumn": 40, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 40, + "column": 34, + "endLine": 40, + "endColumn": 63, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 43, + "column": 10, + "endLine": 43, + "endColumn": 19, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 47, + "column": 10, + "endLine": 47, + "endColumn": 19, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 51, + "column": 10, + "endLine": 51, + "endColumn": 19, + "problem": "StructuralIdentity", + "suggest": "", + "rule": "Structural typing is not supported (arkts-no-structural-typing)", + "severity": "ERROR" + }, + { + "line": 51, + "column": 10, + "endLine": 51, + "endColumn": 19, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 55, + "column": 10, + "endLine": 55, + "endColumn": 19, + "problem": "StructuralIdentity", + "suggest": "", + "rule": "Structural typing is not supported (arkts-no-structural-typing)", + "severity": "ERROR" + }, + { + "line": 55, + "column": 10, + "endLine": 55, + "endColumn": 19, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 60, + "column": 12, + "endLine": 60, + "endColumn": 21, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 64, + "column": 12, + "endLine": 64, + "endColumn": 21, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 68, + "column": 12, + "endLine": 68, + "endColumn": 21, + "problem": "StructuralIdentity", + "suggest": "", + "rule": "Structural typing is not supported (arkts-no-structural-typing)", + "severity": "ERROR" + }, + { + "line": 68, + "column": 12, + "endLine": 68, + "endColumn": 21, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 12, + "endLine": 72, + "endColumn": 21, + "problem": "StructuralIdentity", + "suggest": "", + "rule": "Structural typing is not supported (arkts-no-structural-typing)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 12, + "endLine": 72, + "endColumn": 21, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/func_inferred_type_args_2.ets.autofix.json b/ets2panda/linter/test/main/func_inferred_type_args_2.ets.autofix.json new file mode 100644 index 0000000000..773fea5ff8 --- /dev/null +++ b/ets2panda/linter/test/main/func_inferred_type_args_2.ets.autofix.json @@ -0,0 +1,483 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 7, + "endLine": 16, + "endColumn": 35, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 16, + "column": 24, + "endLine": 16, + "endColumn": 35, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 36, + "endLine": 17, + "endColumn": 47, + "problem": "GenericCallNoTypeArgs", + "autofix": [ + { + "start": 676, + "end": 687, + "replacementText": "new Array()" + } + ], + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 17, + "endLine": 18, + "endColumn": 28, + "problem": "GenericCallNoTypeArgs", + "autofix": [ + { + "start": 705, + "end": 716, + "replacementText": "new Array()" + } + ], + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 7, + "endLine": 20, + "endColumn": 33, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 7, + "endLine": 20, + "endColumn": 33, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 24, + "endLine": 20, + "endColumn": 33, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 44, + "endLine": 21, + "endColumn": 53, + "problem": "GenericCallNoTypeArgs", + "autofix": [ + { + "start": 796, + "end": 805, + "replacementText": "new Map()" + } + ], + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 17, + "endLine": 22, + "endColumn": 26, + "problem": "GenericCallNoTypeArgs", + "autofix": [ + { + "start": 823, + "end": 832, + "replacementText": "new Map()" + } + ], + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 3, + "endLine": 25, + "endColumn": 37, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 3, + "endLine": 25, + "endColumn": 37, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 27, + "endLine": 25, + "endColumn": 36, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 10, + "endLine": 26, + "endColumn": 23, + "problem": "StructuralIdentity", + "suggest": "", + "rule": "Structural typing is not supported (arkts-no-structural-typing)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 39, + "endLine": 26, + "endColumn": 48, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 55, + "endLine": 27, + "endColumn": 64, + "problem": "GenericCallNoTypeArgs", + "autofix": [ + { + "start": 994, + "end": 1003, + "replacementText": "new Map string[]>()" + } + ], + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 61, + "endLine": 28, + "endColumn": 70, + "problem": "GenericCallNoTypeArgs", + "autofix": [ + { + "start": 1065, + "end": 1074, + "replacementText": "new Map string[]>()" + } + ], + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 7, + "endLine": 32, + "endColumn": 35, + "problem": "UnknownType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 22, + "endLine": 32, + "endColumn": 35, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 38, + "endLine": 34, + "endColumn": 51, + "problem": "GenericCallNoTypeArgs", + "autofix": [ + { + "start": 1215, + "end": 1228, + "replacementText": "new MyClass()" + } + ], + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 30, + "endLine": 35, + "endColumn": 39, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 36, + "column": 29, + "endLine": 36, + "endColumn": 38, + "problem": "GenericCallNoTypeArgs", + "autofix": [ + { + "start": 1298, + "end": 1307, + "replacementText": "new Set()" + } + ], + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 29, + "endLine": 37, + "endColumn": 38, + "problem": "GenericCallNoTypeArgs", + "autofix": [ + { + "start": 1337, + "end": 1346, + "replacementText": "new Map string[]>()" + } + ], + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 31, + "endLine": 38, + "endColumn": 40, + "problem": "GenericCallNoTypeArgs", + "autofix": [ + { + "start": 1378, + "end": 1387, + "replacementText": "new Map string[]>()" + } + ], + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 40, + "column": 34, + "endLine": 40, + "endColumn": 63, + "problem": "GenericCallNoTypeArgs", + "autofix": [ + { + "start": 1423, + "end": 1452, + "replacementText": "new Promise(() => { return ''; })" + } + ], + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 43, + "column": 10, + "endLine": 43, + "endColumn": 19, + "problem": "GenericCallNoTypeArgs", + "autofix": [ + { + "start": 1504, + "end": 1513, + "replacementText": "new Map()" + } + ], + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 47, + "column": 10, + "endLine": 47, + "endColumn": 19, + "problem": "GenericCallNoTypeArgs", + "autofix": [ + { + "start": 1582, + "end": 1591, + "replacementText": "new Map()" + } + ], + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 51, + "column": 10, + "endLine": 51, + "endColumn": 19, + "problem": "StructuralIdentity", + "suggest": "", + "rule": "Structural typing is not supported (arkts-no-structural-typing)", + "severity": "ERROR" + }, + { + "line": 51, + "column": 10, + "endLine": 51, + "endColumn": 19, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 55, + "column": 10, + "endLine": 55, + "endColumn": 19, + "problem": "StructuralIdentity", + "suggest": "", + "rule": "Structural typing is not supported (arkts-no-structural-typing)", + "severity": "ERROR" + }, + { + "line": 55, + "column": 10, + "endLine": 55, + "endColumn": 19, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 60, + "column": 12, + "endLine": 60, + "endColumn": 21, + "problem": "GenericCallNoTypeArgs", + "autofix": [ + { + "start": 1798, + "end": 1807, + "replacementText": "new Map()" + } + ], + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 64, + "column": 12, + "endLine": 64, + "endColumn": 21, + "problem": "GenericCallNoTypeArgs", + "autofix": [ + { + "start": 1873, + "end": 1882, + "replacementText": "new Map()" + } + ], + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 68, + "column": 12, + "endLine": 68, + "endColumn": 21, + "problem": "StructuralIdentity", + "suggest": "", + "rule": "Structural typing is not supported (arkts-no-structural-typing)", + "severity": "ERROR" + }, + { + "line": 68, + "column": 12, + "endLine": 68, + "endColumn": 21, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 12, + "endLine": 72, + "endColumn": 21, + "problem": "StructuralIdentity", + "suggest": "", + "rule": "Structural typing is not supported (arkts-no-structural-typing)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 12, + "endLine": 72, + "endColumn": 21, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/func_inferred_type_args_2.ets.json b/ets2panda/linter/test/main/func_inferred_type_args_2.ets.json new file mode 100644 index 0000000000..1f00081d43 --- /dev/null +++ b/ets2panda/linter/test/main/func_inferred_type_args_2.ets.json @@ -0,0 +1,128 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 7, + "endLine": 16, + "endColumn": 35, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 7, + "endLine": 20, + "endColumn": 33, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 7, + "endLine": 20, + "endColumn": 33, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 3, + "endLine": 25, + "endColumn": 37, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 3, + "endLine": 25, + "endColumn": 37, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 7, + "endLine": 32, + "endColumn": 35, + "problem": "UnknownType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 22, + "endLine": 32, + "endColumn": 35, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 51, + "column": 10, + "endLine": 51, + "endColumn": 19, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 55, + "column": 10, + "endLine": 55, + "endColumn": 19, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 68, + "column": 12, + "endLine": 68, + "endColumn": 21, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 12, + "endLine": 72, + "endColumn": 21, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/func_inferred_type_args_2.ets.migrate.ets b/ets2panda/linter/test/main/func_inferred_type_args_2.ets.migrate.ets new file mode 100644 index 0000000000..01a5d89f97 --- /dev/null +++ b/ets2panda/linter/test/main/func_inferred_type_args_2.ets.migrate.ets @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +const irreparableArr = new Array(); +let repairableArr: Array = new Array(); +repairableArr = new Array(); + +const irreparableMap = new Map(); +const repairableMap: Map = new Map(); +repairableMap = new Map(); + +class MyClass { + public irreparableMap = new Map(); + public repairableSet: Set = new Map(); + public repairableMap: Map string[]> = new Map string[]>(); + static repairableStaticMap: Map string[]> = new Map string[]>(); + constructor() {} +} + +const irreparableA = new MyClass(); +const irreparableB = new MyClass(); +const repairableC: MyClass = new MyClass(); +repairableC.irreparableMap = new Map(); +repairableC.repairableSet = new Set(); +repairableC.repairableMap = new Map string[]>(); +MyClass.repairableStaticMap = new Map string[]>(); + +const promise: Promise = new Promise(() => { return ''; }); + +function testA(): Map { + return new Map(); +} + +async function testB(): Promise> { + return new Map(); +} + +function testC(): Map { + return new Set(); +} + +async function testD(): Promise> { + return new Set(); +} + +class MyClassB { + testA(): Map { + return new Map(); + } + + async testB(): Promise> { + return new Map(); + } + + testC(): Map { + return new Set(); + } + + async testD(): Promise> { + return new Set(); + } +} diff --git a/ets2panda/linter/test/main/func_inferred_type_args_2.ets.migrate.json b/ets2panda/linter/test/main/func_inferred_type_args_2.ets.migrate.json new file mode 100644 index 0000000000..a3d92d0d96 --- /dev/null +++ b/ets2panda/linter/test/main/func_inferred_type_args_2.ets.migrate.json @@ -0,0 +1,228 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 7, + "endLine": 16, + "endColumn": 35, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 16, + "column": 24, + "endLine": 16, + "endColumn": 35, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 7, + "endLine": 20, + "endColumn": 33, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 7, + "endLine": 20, + "endColumn": 33, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 24, + "endLine": 20, + "endColumn": 33, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 3, + "endLine": 25, + "endColumn": 37, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 3, + "endLine": 25, + "endColumn": 37, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 27, + "endLine": 25, + "endColumn": 36, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 10, + "endLine": 26, + "endColumn": 23, + "problem": "StructuralIdentity", + "suggest": "", + "rule": "Structural typing is not supported (arkts-no-structural-typing)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 39, + "endLine": 26, + "endColumn": 48, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 7, + "endLine": 32, + "endColumn": 35, + "problem": "UnknownType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 22, + "endLine": 32, + "endColumn": 35, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 30, + "endLine": 35, + "endColumn": 39, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 51, + "column": 10, + "endLine": 51, + "endColumn": 19, + "problem": "StructuralIdentity", + "suggest": "", + "rule": "Structural typing is not supported (arkts-no-structural-typing)", + "severity": "ERROR" + }, + { + "line": 51, + "column": 10, + "endLine": 51, + "endColumn": 19, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 55, + "column": 10, + "endLine": 55, + "endColumn": 19, + "problem": "StructuralIdentity", + "suggest": "", + "rule": "Structural typing is not supported (arkts-no-structural-typing)", + "severity": "ERROR" + }, + { + "line": 55, + "column": 10, + "endLine": 55, + "endColumn": 19, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 68, + "column": 12, + "endLine": 68, + "endColumn": 21, + "problem": "StructuralIdentity", + "suggest": "", + "rule": "Structural typing is not supported (arkts-no-structural-typing)", + "severity": "ERROR" + }, + { + "line": 68, + "column": 12, + "endLine": 68, + "endColumn": 21, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 12, + "endLine": 72, + "endColumn": 21, + "problem": "StructuralIdentity", + "suggest": "", + "rule": "Structural typing is not supported (arkts-no-structural-typing)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 12, + "endLine": 72, + "endColumn": 21, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/func_return_type.ets.args.json b/ets2panda/linter/test/main/func_return_type.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/main/func_return_type.ets.args.json +++ b/ets2panda/linter/test/main/func_return_type.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/migrate/func_return_type.sts b/ets2panda/linter/test/main/func_return_type.ets.migrate.ets similarity index 77% rename from ets2panda/linter/test/migrate/func_return_type.sts rename to ets2panda/linter/test/main/func_return_type.ets.migrate.ets index c2167e6373..cbcf3e1fb8 100644 --- a/ets2panda/linter/test/migrate/func_return_type.sts +++ b/ets2panda/linter/test/main/func_return_type.ets.migrate.ets @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,14 +13,14 @@ * limitations under the License. */ -function q(x: number) { // Need fix +function q(x: number): number { // Need fix return w(x) } function w(x: number) { - return x; + return x; } -function e(x: string) { // Need fix +function e(x: string): string { // Need fix return r(x) } function r(x: string) { @@ -30,7 +30,7 @@ function t(x: string): string { return x; } -function y() { // Need fix +function y(): number[] { // Need fix return u(); } function u() { @@ -59,23 +59,23 @@ function z(a: any) { // Not fixable } function functionExpressions() { - let f1 = function (c: C) { // Need fix + let f1 = (c: C): C => { return f2(c); - }; - let f2 = function (c: C) { +}; + let f2 = (c: C) => { return new C(); - }; - - let f3 = function (x: number, y: number) { +}; + + let f3 = (x: number, y: number) => { return x + y; - }; +}; - let f4 = function () { // Need fix + let f4 = (): Map => { return f5(); - }; - let f5 = function () { +}; + let f5 = () => { return new Map(); - }; +}; let f6 = function () { // Not fixable return z(0); @@ -83,20 +83,20 @@ function functionExpressions() { } function lambdas() { - let l1 = (t: T) => { // Need fix + let l1 = (t: T): T => { return l2(t); - }; +}; let l2 = (t: T) => { return t; }; - + let l3 = (x: number, y: number) => { return x + y; }; - let l4 = () => { // Need fix + let l4 = (): (x: number) => string => { return l5(); - }; +}; let l5 = () => { return (x: number) => x.toString(); }; @@ -107,19 +107,19 @@ function lambdas() { } class C { - m(x: number) { // Need fix + m(x: number): number { // Need fix return q(x) } - - m2(x: number) { // Need fix + + m2(x: number): number { // Need fix return this.m(x) } m3(x: number) { return 10; } - - m4() { // Need fix + + m4(): number { // Need fix return this.m2(20); } @@ -128,7 +128,7 @@ class C { } } -function no_space_before_body(x: number){ // Need fix +function no_space_before_body(x: number): number{ // Need fix return w(x) } diff --git a/ets2panda/linter/test/interop/no_js_await.ets.arkts2.json b/ets2panda/linter/test/main/func_return_type.ets.migrate.json old mode 100755 new mode 100644 similarity index 66% rename from ets2panda/linter/test/interop/no_js_await.ets.arkts2.json rename to ets2panda/linter/test/main/func_return_type.ets.migrate.json index 7b4e605344..4d8789634f --- a/ets2panda/linter/test/interop/no_js_await.ets.arkts2.json +++ b/ets2panda/linter/test/main/func_return_type.ets.migrate.json @@ -15,79 +15,69 @@ ], "result": [ { - "line": 17, - "column": 1, - "endLine": 17, - "endColumn": 80, - "problem": "ImportAfterStatement", - "suggest": "", - "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", - "severity": "ERROR" - }, - { - "line": 20, - "column": 16, - "endLine": 20, - "endColumn": 28, + "line": 40, + "column": 10, + "endLine": 40, + "endColumn": 11, "problem": "LimitedReturnTypeInference", "suggest": "", "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", "severity": "ERROR" }, { - "line": 25, - "column": 16, - "endLine": 25, - "endColumn": 33, + "line": 46, + "column": 10, + "endLine": 46, + "endColumn": 11, "problem": "LimitedReturnTypeInference", "suggest": "", "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", "severity": "ERROR" }, { - "line": 29, - "column": 16, - "endLine": 29, - "endColumn": 31, + "line": 54, + "column": 10, + "endLine": 54, + "endColumn": 11, "problem": "LimitedReturnTypeInference", "suggest": "", "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", "severity": "ERROR" }, { - "line": 34, - "column": 16, - "endLine": 34, - "endColumn": 30, + "line": 57, + "column": 10, + "endLine": 57, + "endColumn": 11, "problem": "LimitedReturnTypeInference", "suggest": "", "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", "severity": "ERROR" }, { - "line": 38, - "column": 16, - "endLine": 38, - "endColumn": 32, - "problem": "LimitedReturnTypeInference", + "line": 57, + "column": 15, + "endLine": 57, + "endColumn": 18, + "problem": "AnyType", "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, { - "line": 44, - "column": 9, - "endLine": 44, - "endColumn": 20, - "problem": "LimitedReturnTypeInference", + "line": 80, + "column": 12, + "endLine": 82, + "endColumn": 4, + "problem": "FunctionExpression", "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", "severity": "ERROR" }, { - "line": 48, - "column": 13, - "endLine": 50, + "line": 80, + "column": 12, + "endLine": 82, "endColumn": 4, "problem": "LimitedReturnTypeInference", "suggest": "", @@ -95,53 +85,53 @@ "severity": "ERROR" }, { - "line": 54, - "column": 20, - "endLine": 54, - "endColumn": 21, - "problem": "ObjectLiteralNoContextType", + "line": 104, + "column": 12, + "endLine": 106, + "endColumn": 4, + "problem": "LimitedReturnTypeInference", "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", "severity": "ERROR" }, { - "line": 55, + "line": 126, "column": 3, - "endLine": 57, - "endColumn": 4, - "problem": "ObjectLiteralProperty", + "endLine": 126, + "endColumn": 5, + "problem": "LimitedReturnTypeInference", "suggest": "", - "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", "severity": "ERROR" }, { - "line": 55, - "column": 9, - "endLine": 55, - "endColumn": 18, + "line": 135, + "column": 18, + "endLine": 135, + "endColumn": 40, "problem": "LimitedReturnTypeInference", "suggest": "", "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", "severity": "ERROR" }, { - "line": 59, - "column": 17, - "endLine": 61, - "endColumn": 4, + "line": 139, + "column": 3, + "endLine": 139, + "endColumn": 10, "problem": "LimitedReturnTypeInference", "suggest": "", "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", "severity": "ERROR" }, { - "line": 65, - "column": 2, - "endLine": 67, - "endColumn": 2, - "problem": "FunctionExpression", + "line": 144, + "column": 3, + "endLine": 144, + "endColumn": 7, + "problem": "LimitedReturnTypeInference", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/main/function_expression.ets.args.json b/ets2panda/linter/test/main/function_expression.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/main/function_expression.ets.args.json +++ b/ets2panda/linter/test/main/function_expression.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/migrate/function_expression.sts b/ets2panda/linter/test/main/function_expression.ets.migrate.ets similarity index 42% rename from ets2panda/linter/test/migrate/function_expression.sts rename to ets2panda/linter/test/main/function_expression.ets.migrate.ets index 0806c249b8..5e0cd324c2 100644 --- a/ets2panda/linter/test/migrate/function_expression.sts +++ b/ets2panda/linter/test/main/function_expression.ets.migrate.ets @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,36 +13,36 @@ * limitations under the License. */ -const empty = function () {}; +const empty = () => { }; -const multiply = function (x: number, y): number { - return x * y; +const multiply = (x: number, y): number => { + return x * y; }; function createFunc(): () => number { - return function () { + return () => { return 100; - }; +}; } -const foobar = (function () { - return 'get result immediately'; +const foobar = (() => { + return 'get result immediately'; })(); -(function () { - console.log('foo!'); +(() => { + console.log('foo!'); })(); -void (function () { - console.log('bar!'); +void (() => { + console.log('bar!'); })(); const array = [1, 2, 3, 4, 5, 6]; -const double = array.map(function (e) { - return e * 2; +const double = array.map((e) => { + return e * 2; }); -const even = array.filter(function (x) { - return x % 2 === 0; +const even = array.filter((x) => { + return x % 2 === 0; }); const retTypeInfer = function (p: any) { @@ -53,12 +53,12 @@ const generator = function * () { yield 1; }; -const generic = function (t: T, e: E) { - return t; +const generic = (t: T, e: E) => { + return t; }; -const asyncFun = async function() { - console.log('baz!'); +const asyncFun = async () => { + console.log('baz!'); }; const factorial = function f(n: number): number { @@ -68,46 +68,46 @@ const factorial = function f(n: number): number { class C { m() {} } -const noRecursiveCall = function f(p: () => number): void { // Doesn't have recursive call, should be autofixable - let a = factorial(3); - let b = p(); - let c = new C() - c.m(); +const noRecursiveCall = (p: () => number): void => { + let a = factorial(3); + let b = p(); + let c = new C(); + c.m(); }; -let iife = function() { - console.log('called immediately'); -}(); +let iife = (() => { + console.log('called immediately'); +})(); -let indexAccess = function() { - console.log('index access'); -}[0]; +let indexAccess = (() => { + console.log('index access'); +})[0]; -void function() { - console.log('void'); -}; +void (() => { + console.log('void'); +}); -async function awaitFun() { - await function() { +async function awaitFun() { + await (() => { console.log('async'); - }; +}); } -let typeofFunc = typeof function() { - console.log('typeof'); -} +let typeofFunc = typeof (() => { + console.log('typeof'); +}) class BindFuncExpr { foo() { - let bar = function(p: boolean) { - console.log('Function.bind(this)'); - }.bind(this); + let bar = ((p: boolean) => { + console.log('Function.bind(this)'); +}).bind(this); } } -let callback = function() { console.log('callback'); } -callback = callback || function() { console.log('expr || function(){}'); }; +let callback = () => { console.log('callback'); } +callback = callback || (() => { console.log('expr || function(){}'); }); let ternaryExpr = !!callback - ? function() { console.log('ternary 1'); } || 2 - : 3 && function() { console.log('ternary 2'); }; \ No newline at end of file + ? (() => { console.log('ternary 1'); }) || 2 + : 3 && (() => { console.log('ternary 2'); }); \ No newline at end of file diff --git a/ets2panda/linter/test/migrate/void_operator.ts.json b/ets2panda/linter/test/main/function_expression.ets.migrate.json similarity index 46% rename from ets2panda/linter/test/migrate/void_operator.ts.json rename to ets2panda/linter/test/main/function_expression.ets.migrate.json index 4903dda820..71e6ea8002 100644 --- a/ets2panda/linter/test/migrate/void_operator.ts.json +++ b/ets2panda/linter/test/main/function_expression.ets.migrate.json @@ -15,19 +15,19 @@ ], "result": [ { - "line": 22, - "column": 6, - "endLine": 22, - "endColumn": 7, - "problem": "ObjectLiteralNoContextType", + "line": 18, + "column": 30, + "endLine": 18, + "endColumn": 31, + "problem": "AnyType", "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, { - "line": 36, - "column": 6, - "endLine": 38, + "line": 48, + "column": 22, + "endLine": 50, "endColumn": 2, "problem": "FunctionExpression", "suggest": "", @@ -35,19 +35,29 @@ "severity": "ERROR" }, { - "line": 40, - "column": 6, - "endLine": 42, + "line": 48, + "column": 22, + "endLine": 50, "endColumn": 2, - "problem": "FunctionExpression", + "problem": "LimitedReturnTypeInference", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "severity": "ERROR" + }, + { + "line": 48, + "column": 35, + "endLine": 48, + "endColumn": 38, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, { - "line": 44, - "column": 7, - "endLine": 46, + "line": 52, + "column": 19, + "endLine": 54, "endColumn": 2, "problem": "FunctionExpression", "suggest": "", @@ -55,64 +65,74 @@ "severity": "ERROR" }, { - "line": 48, - "column": 6, - "endLine": 48, - "endColumn": 11, - "problem": "ClassExpression", + "line": 52, + "column": 19, + "endLine": 54, + "endColumn": 2, + "problem": "GeneratorFunction", "suggest": "", - "rule": "Class literals are not supported (arkts-no-class-literals)", + "rule": "Generator functions are not supported (arkts-no-generators)", "severity": "ERROR" }, { - "line": 50, - "column": 7, - "endLine": 50, - "endColumn": 12, - "problem": "ClassExpression", + "line": 53, + "column": 3, + "endLine": 53, + "endColumn": 10, + "problem": "YieldExpression", "suggest": "", - "rule": "Class literals are not supported (arkts-no-class-literals)", + "rule": "Generator functions are not supported (arkts-no-generators)", "severity": "ERROR" }, { - "line": 61, - "column": 8, - "endLine": 63, - "endColumn": 4, + "line": 64, + "column": 19, + "endLine": 66, + "endColumn": 2, "problem": "FunctionExpression", "suggest": "", "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", "severity": "ERROR" }, { - "line": 65, - "column": 8, - "endLine": 67, - "endColumn": 4, - "problem": "FunctionExpression", + "line": 82, + "column": 5, + "endLine": 84, + "endColumn": 6, + "problem": "AnyType", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, { - "line": 69, - "column": 8, - "endLine": 69, - "endColumn": 13, - "problem": "ClassExpression", + "line": 82, + "column": 19, + "endLine": 84, + "endColumn": 6, + "problem": "PropertyAccessByIndex", "suggest": "", - "rule": "Class literals are not supported (arkts-no-class-literals)", + "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", "severity": "ERROR" }, { - "line": 71, - "column": 8, - "endLine": 71, - "endColumn": 13, - "problem": "ClassExpression", + "line": 102, + "column": 9, + "endLine": 104, + "endColumn": 14, + "problem": "AnyType", "suggest": "", - "rule": "Class literals are not supported (arkts-no-class-literals)", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" + }, + { + "line": 104, + "column": 4, + "endLine": 104, + "endColumn": 14, + "problem": "FunctionBind", + "suggest": "", + "rule": "'Function.bind' is not supported (arkts-no-func-bind)", + "severity": "WARNING" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/function_object_methods.ets.arkts2.json b/ets2panda/linter/test/main/function_object_methods.ets.arkts2.json index b434010361..adb91f9c46 100644 --- a/ets2panda/linter/test/main/function_object_methods.ets.arkts2.json +++ b/ets2panda/linter/test/main/function_object_methods.ets.arkts2.json @@ -14,26 +14,6 @@ "limitations under the License." ], "result": [ - { - "line": 19, - "column": 16, - "endLine": 19, - "endColumn": 24, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, - { - "line": 20, - "column": 14, - "endLine": 20, - "endColumn": 22, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, { "line": 29, "column": 5, @@ -134,16 +114,6 @@ "rule": "'Function.bind' is not supported (arkts-no-func-bind)", "severity": "ERROR" }, - { - "line": 75, - "column": 15, - "endLine": 75, - "endColumn": 23, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, { "line": 75, "column": 48, @@ -155,13 +125,13 @@ "severity": "ERROR" }, { - "line": 78, - "column": 15, - "endLine": 78, - "endColumn": 23, + "line": 76, + "column": 9, + "endLine": 76, + "endColumn": 13, "problem": "ExplicitFunctionType", "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", + "rule": "The function type should be explicit (arkts-no-ts-like-function-call)", "severity": "ERROR" }, { @@ -174,6 +144,16 @@ "rule": "'Function.bind' is not supported (arkts-no-func-bind)", "severity": "ERROR" }, + { + "line": 79, + "column": 9, + "endLine": 79, + "endColumn": 13, + "problem": "ExplicitFunctionType", + "suggest": "", + "rule": "The function type should be explicit (arkts-no-ts-like-function-call)", + "severity": "ERROR" + }, { "line": 81, "column": 31, @@ -244,16 +224,6 @@ "rule": "'Function.bind' is not supported (arkts-no-func-bind)", "severity": "ERROR" }, - { - "line": 101, - "column": 14, - "endLine": 101, - "endColumn": 22, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, { "line": 101, "column": 42, @@ -265,13 +235,13 @@ "severity": "ERROR" }, { - "line": 104, - "column": 14, - "endLine": 104, - "endColumn": 22, + "line": 102, + "column": 3, + "endLine": 102, + "endColumn": 6, "problem": "ExplicitFunctionType", "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", + "rule": "The function type should be explicit (arkts-no-ts-like-function-call)", "severity": "ERROR" }, { @@ -284,6 +254,16 @@ "rule": "'Function.bind' is not supported (arkts-no-func-bind)", "severity": "ERROR" }, + { + "line": 105, + "column": 3, + "endLine": 105, + "endColumn": 6, + "problem": "ExplicitFunctionType", + "suggest": "", + "rule": "The function type should be explicit (arkts-no-ts-like-function-call)", + "severity": "ERROR" + }, { "line": 107, "column": 20, diff --git a/ets2panda/linter/test/main/global_this.ets.args.json b/ets2panda/linter/test/main/global_this.ets.args.json index db044a3dff..a89d885810 100644 --- a/ets2panda/linter/test/main/global_this.ets.args.json +++ b/ets2panda/linter/test/main/global_this.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } diff --git a/ets2panda/linter/test/main/global_this.ets.migrate.ets b/ets2panda/linter/test/main/global_this.ets.migrate.ets new file mode 100644 index 0000000000..d1fb5d519f --- /dev/null +++ b/ets2panda/linter/test/main/global_this.ets.migrate.ets @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +const pi: number = 3.1416; + +function circleArea(r: number): number { + foo(globalThis); + + return specialAutofixLib.globalThis.get("pi") * r * r; +} + +function foo(x: any): void { + console.log(x.pi); +} + +specialAutofixLib.globalThis.set("abc", 200); + +const value = specialAutofixLib.globalThis.get("obj").prop; + +delete specialAutofixLib.globalThis.get("property"); + +globalThisprop = 100; + +specialAutofixLib.globalThis.get("pi"); + +specialAutofixLib.globalThis.set("pi",3.1416); + +specialAutofixLib.globalThis; + diff --git a/ets2panda/linter/test/main/global_this.ets.migrate.json b/ets2panda/linter/test/main/global_this.ets.migrate.json new file mode 100644 index 0000000000..cdc3cef837 --- /dev/null +++ b/ets2panda/linter/test/main/global_this.ets.migrate.json @@ -0,0 +1,58 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 19, + "column": 7, + "endLine": 19, + "endColumn": 17, + "problem": "GlobalThisError", + "suggest": "", + "rule": "\"globalThis\" is not supported (arkts-no-globalthis)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 17, + "endLine": 24, + "endColumn": 20, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 7, + "endLine": 30, + "endColumn": 59, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 1, + "endLine": 32, + "endColumn": 7, + "problem": "DeleteOperator", + "suggest": "", + "rule": "\"delete\" operator is not supported (arkts-no-delete)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/index_negative.ets.arkts2.json b/ets2panda/linter/test/main/index_negative.ets.arkts2.json index 8c2d2b6a35..f74d810960 100755 --- a/ets2panda/linter/test/main/index_negative.ets.arkts2.json +++ b/ets2panda/linter/test/main/index_negative.ets.arkts2.json @@ -64,6 +64,16 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 21, + "column": 10, + "endLine": 21, + "endColumn": 12, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, { "line": 22, "column": 10, @@ -124,6 +134,16 @@ "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", "severity": "ERROR" }, + { + "line": 40, + "column": 5, + "endLine": 40, + "endColumn": 13, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, { "line": 42, "column": 1, @@ -134,6 +154,26 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 42, + "column": 5, + "endLine": 42, + "endColumn": 6, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 5, + "endLine": 44, + "endColumn": 8, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, { "line": 45, "column": 5, @@ -144,6 +184,26 @@ "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", "severity": "ERROR" }, + { + "line": 47, + "column": 5, + "endLine": 47, + "endColumn": 10, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 48, + "column": 5, + "endLine": 48, + "endColumn": 13, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, { "line": 50, "column": 1, @@ -154,6 +214,16 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 50, + "column": 5, + "endLine": 50, + "endColumn": 9, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, { "line": 52, "column": 1, @@ -164,6 +234,26 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 52, + "column": 5, + "endLine": 52, + "endColumn": 14, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 53, + "column": 5, + "endLine": 53, + "endColumn": 6, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, { "line": 54, "column": 1, @@ -174,6 +264,26 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 54, + "column": 5, + "endLine": 54, + "endColumn": 7, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 56, + "column": 6, + "endLine": 56, + "endColumn": 30, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, { "line": 57, "column": 1, @@ -194,6 +304,26 @@ "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", "severity": "ERROR" }, + { + "line": 58, + "column": 5, + "endLine": 58, + "endColumn": 6, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 59, + "column": 5, + "endLine": 59, + "endColumn": 7, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, { "line": 60, "column": 1, @@ -204,6 +334,16 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 60, + "column": 5, + "endLine": 60, + "endColumn": 16, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, { "line": 61, "column": 1, @@ -234,6 +374,16 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 63, + "column": 6, + "endLine": 63, + "endColumn": 30, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, { "line": 65, "column": 1, @@ -244,6 +394,16 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 65, + "column": 5, + "endLine": 65, + "endColumn": 7, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, { "line": 66, "column": 1, @@ -254,6 +414,16 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 66, + "column": 5, + "endLine": 66, + "endColumn": 9, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, { "line": 68, "column": 1, @@ -264,6 +434,36 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 68, + "column": 5, + "endLine": 68, + "endColumn": 30, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 69, + "column": 5, + "endLine": 69, + "endColumn": 6, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 70, + "column": 5, + "endLine": 70, + "endColumn": 7, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, { "line": 71, "column": 7, @@ -274,6 +474,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 72, + "column": 5, + "endLine": 72, + "endColumn": 30, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, { "line": 73, "column": 1, @@ -284,6 +494,16 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 73, + "column": 5, + "endLine": 73, + "endColumn": 6, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, { "line": 74, "column": 7, @@ -324,16 +544,6 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, - { - "line": 77, - "column": 12, - "endLine": 77, - "endColumn": 16, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, { "line": 78, "column": 7, @@ -354,6 +564,26 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 80, + "column": 5, + "endLine": 80, + "endColumn": 7, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 81, + "column": 5, + "endLine": 81, + "endColumn": 7, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, { "line": 82, "column": 1, @@ -364,6 +594,16 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 82, + "column": 5, + "endLine": 82, + "endColumn": 7, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, { "line": 83, "column": 1, @@ -374,6 +614,26 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 83, + "column": 5, + "endLine": 83, + "endColumn": 7, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 84, + "column": 5, + "endLine": 84, + "endColumn": 7, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, { "line": 85, "column": 1, @@ -384,6 +644,16 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 85, + "column": 5, + "endLine": 85, + "endColumn": 7, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, { "line": 86, "column": 7, @@ -404,6 +674,16 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 87, + "column": 5, + "endLine": 87, + "endColumn": 7, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, { "line": 88, "column": 5, @@ -424,6 +704,16 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 89, + "column": 5, + "endLine": 89, + "endColumn": 7, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, { "line": 90, "column": 1, @@ -484,6 +774,16 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 92, + "column": 5, + "endLine": 92, + "endColumn": 9, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, { "line": 96, "column": 11, @@ -494,6 +794,16 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 97, + "column": 15, + "endLine": 97, + "endColumn": 24, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, { "line": 98, "column": 7, @@ -514,6 +824,16 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 99, + "column": 5, + "endLine": 99, + "endColumn": 14, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, { "line": 100, "column": 1, @@ -523,6 +843,16 @@ "suggest": "", "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" + }, + { + "line": 100, + "column": 5, + "endLine": 100, + "endColumn": 8, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" } ] -} \ No newline at end of file +} diff --git a/ets2panda/linter/test/main/interface_import_1.ets.args.json b/ets2panda/linter/test/main/interface_import_1.ets.args.json index f6c6b88ccf..631484dfeb 100644 --- a/ets2panda/linter/test/main/interface_import_1.ets.args.json +++ b/ets2panda/linter/test/main/interface_import_1.ets.args.json @@ -15,7 +15,8 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/interface_import_1.ets.arkts2.json b/ets2panda/linter/test/main/interface_import_1.ets.arkts2.json index 745ac0fec0..87714d54f8 100644 --- a/ets2panda/linter/test/main/interface_import_1.ets.arkts2.json +++ b/ets2panda/linter/test/main/interface_import_1.ets.arkts2.json @@ -14,16 +14,6 @@ "limitations under the License." ], "result": [ - { - "line": 22, - "column": 3, - "endLine": 22, - "endColumn": 38, - "problem": "DataObservation", - "suggest": "", - "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", - "severity": "ERROR" - }, { "line": 60, "column": 1, diff --git a/ets2panda/linter/test/main/interface_import_1.ets.autofix.json b/ets2panda/linter/test/main/interface_import_1.ets.autofix.json index cebc9338ef..513f949766 100644 --- a/ets2panda/linter/test/main/interface_import_1.ets.autofix.json +++ b/ets2panda/linter/test/main/interface_import_1.ets.autofix.json @@ -14,23 +14,6 @@ "limitations under the License." ], "result": [ - { - "line": 22, - "column": 3, - "endLine": 22, - "endColumn": 38, - "problem": "DataObservation", - "autofix": [ - { - "start": 1409, - "end": 1409, - "replacementText": "@Observed\n" - } - ], - "suggest": "", - "rule": "Data observation needs to add \"@Observed\" (arkui-data-observation)", - "severity": "ERROR" - }, { "line": 60, "column": 1, @@ -92,7 +75,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Observed, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, State, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" } ], "suggest": "", @@ -109,7 +92,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Observed, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, State, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" } ], "suggest": "", @@ -126,7 +109,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Observed, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, State, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" } ], "suggest": "", @@ -143,7 +126,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Observed, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, State, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" } ], "suggest": "", @@ -160,7 +143,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Observed, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, State, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" } ], "suggest": "", @@ -177,7 +160,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Observed, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, State, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" } ], "suggest": "", @@ -194,7 +177,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Observed, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, State, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" } ], "suggest": "", @@ -211,7 +194,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Observed, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, State, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" } ], "suggest": "", @@ -228,7 +211,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Observed, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, State, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" } ], "suggest": "", @@ -245,7 +228,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Observed, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, State, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" } ], "suggest": "", @@ -262,7 +245,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Observed, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, State, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" } ], "suggest": "", @@ -279,7 +262,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Observed, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, State, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" } ], "suggest": "", @@ -296,7 +279,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Observed, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, State, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" } ], "suggest": "", @@ -313,7 +296,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Observed, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, State, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" } ], "suggest": "", @@ -330,7 +313,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Observed, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, State, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';" } ], "suggest": "", diff --git a/ets2panda/linter/test/main/data_observation_1.ets b/ets2panda/linter/test/main/interface_import_1.ets.migrate.ets similarity index 37% rename from ets2panda/linter/test/main/data_observation_1.ets rename to ets2panda/linter/test/main/interface_import_1.ets.migrate.ets index 3ccdd38f94..231baa7371 100644 --- a/ets2panda/linter/test/main/data_observation_1.ets +++ b/ets2panda/linter/test/main/interface_import_1.ets.migrate.ets @@ -13,70 +13,81 @@ * limitations under the License. */ -class MyClassA {} - -class MyClassB { - name: string = '' -} +import { Entry, Component, State, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI'; -class MyClassC1 {} +import { Slider } from '@kit.ArkUI'; -class MyClassC2 extends MyClassC1 {} +@Entry +@Component +struct Test { + @State num: number = 0 + @State a: MyClassA = new MyClassA() -class MyClassC3 extends MyClassC2 {} + build() { + Column() { + Button('按钮') + .backgroundColor('#ffffff') + Circle() { + + } -class MyClassD extends MyClassC3 {} + MyComponent1() { -class MyClassC4 extends MyClassD {} + } -interface IntfA {} + Text("Test") + }.width("100%") + } +} -class MyClassE implements IntfA {} +enum Color { + Green +} -@Observed -class MyClassF {} +function Circle() { -class MyClassG {} +} -class MyClassH {} +@Component +struct MyComponent1 { + @State count: number = 0; -class MyClassI {} + build() { + Row() { + Slider(){} + } + } +} -@Observed -class MyClassJ extends MyClassI {} +function cardStyle(this: TextAttribute): this { + this.backgroundColor(Color.Green); + return this; +} -@Observed -class MyClassK extends MyClassJ {} +@AnimatableExtend +function animatableWidth(this: ColumnAttribute, width: number): this { + this.width(width); + return this; +} -@Entry @Component -struct Test { - @State data1: number = 0 - @State data2: MyClassA = new MyClassA() - @State data3: MyClassB = { name: "jack" } - @State data4: MyClassC2 = new MyClassD() - @State data5: IntfA = new MyClassE() - @Prop data6: MyClassE = new MyClassE() - @Prop data7: MyClassF = new MyClassF() - @Prop data8: MyClassG | MyClassH | number = 0 - @Prop data9: MyClassJ = new MyClassK() - @Provide selectedDate: Date = new Date('2021-08-08') - @StorageLink('PropB') storageLink: MyClassA = new MyClassA() - @LocalStorageLink('LinkB') localStorageLink: MyClassB = new MyClassB() - @StorageProp('test') test1: MyClassC2 = new MyClassC3() - @LocalStorageProp('test') test2: MyClassD = new MyClassD() +struct MyComponent2 { + @State value: number = 0; build() { - + Row() { + Slider({ + value: $$(this.value) + }) + } } } -@Component -struct MyComponent { - @Link data2: MyClassA - @Consume selectedDate: Date +class MyClassA {} - build() { +function processImageFit(imageFit: ImageFit): void { +} + +function Calendar() { - } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/interface_import_1.ets.migrate.json b/ets2panda/linter/test/main/interface_import_1.ets.migrate.json new file mode 100644 index 0000000000..400a3c7033 --- /dev/null +++ b/ets2panda/linter/test/main/interface_import_1.ets.migrate.json @@ -0,0 +1,98 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 63, + "column": 5, + "endLine": 63, + "endColumn": 9, + "problem": "FunctionContainsThis", + "suggest": "", + "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", + "severity": "ERROR" + }, + { + "line": 64, + "column": 12, + "endLine": 64, + "endColumn": 16, + "problem": "FunctionContainsThis", + "suggest": "", + "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", + "severity": "ERROR" + }, + { + "line": 62, + "column": 20, + "endLine": 62, + "endColumn": 24, + "problem": "InvalidIdentifier", + "suggest": "", + "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", + "severity": "ERROR" + }, + { + "line": 62, + "column": 42, + "endLine": 62, + "endColumn": 46, + "problem": "ThisType", + "suggest": "", + "rule": "Type notation using \"this\" is not supported (arkts-no-typing-with-this)", + "severity": "ERROR" + }, + { + "line": 69, + "column": 5, + "endLine": 69, + "endColumn": 9, + "problem": "FunctionContainsThis", + "suggest": "", + "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", + "severity": "ERROR" + }, + { + "line": 70, + "column": 12, + "endLine": 70, + "endColumn": 16, + "problem": "FunctionContainsThis", + "suggest": "", + "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", + "severity": "ERROR" + }, + { + "line": 68, + "column": 26, + "endLine": 68, + "endColumn": 30, + "problem": "InvalidIdentifier", + "suggest": "", + "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", + "severity": "ERROR" + }, + { + "line": 68, + "column": 65, + "endLine": 68, + "endColumn": 69, + "problem": "ThisType", + "suggest": "", + "rule": "Type notation using \"this\" is not supported (arkts-no-typing-with-this)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/interface_import_2.ets b/ets2panda/linter/test/main/interface_import_2.ets index 49eea0d570..231baa7371 100644 --- a/ets2panda/linter/test/main/interface_import_2.ets +++ b/ets2panda/linter/test/main/interface_import_2.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import { Entry, Component, State, Observed, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI'; +import { Entry, Component, State, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI'; import { Slider } from '@kit.ArkUI'; @@ -83,7 +83,6 @@ struct MyComponent2 { } } -@Observed class MyClassA {} function processImageFit(imageFit: ImageFit): void { diff --git a/ets2panda/linter/test/main/interface_import_2.ets.args.json b/ets2panda/linter/test/main/interface_import_2.ets.args.json index f6c6b88ccf..631484dfeb 100644 --- a/ets2panda/linter/test/main/interface_import_2.ets.args.json +++ b/ets2panda/linter/test/main/interface_import_2.ets.args.json @@ -15,7 +15,8 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/interface_import_2.ets.migrate.ets b/ets2panda/linter/test/main/interface_import_2.ets.migrate.ets new file mode 100644 index 0000000000..231baa7371 --- /dev/null +++ b/ets2panda/linter/test/main/interface_import_2.ets.migrate.ets @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, State, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI'; + +import { Slider } from '@kit.ArkUI'; + +@Entry +@Component +struct Test { + @State num: number = 0 + @State a: MyClassA = new MyClassA() + + build() { + Column() { + Button('按钮') + .backgroundColor('#ffffff') + Circle() { + + } + + MyComponent1() { + + } + + Text("Test") + }.width("100%") + } +} + +enum Color { + Green +} + +function Circle() { + +} + +@Component +struct MyComponent1 { + @State count: number = 0; + + build() { + Row() { + Slider(){} + } + } +} + +function cardStyle(this: TextAttribute): this { + this.backgroundColor(Color.Green); + return this; +} + +@AnimatableExtend +function animatableWidth(this: ColumnAttribute, width: number): this { + this.width(width); + return this; +} + +@Component +struct MyComponent2 { + @State value: number = 0; + + build() { + Row() { + Slider({ + value: $$(this.value) + }) + } + } +} + +class MyClassA {} + +function processImageFit(imageFit: ImageFit): void { +} + +function Calendar() { + +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/interface_import_2.ets.migrate.json b/ets2panda/linter/test/main/interface_import_2.ets.migrate.json new file mode 100644 index 0000000000..400a3c7033 --- /dev/null +++ b/ets2panda/linter/test/main/interface_import_2.ets.migrate.json @@ -0,0 +1,98 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 63, + "column": 5, + "endLine": 63, + "endColumn": 9, + "problem": "FunctionContainsThis", + "suggest": "", + "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", + "severity": "ERROR" + }, + { + "line": 64, + "column": 12, + "endLine": 64, + "endColumn": 16, + "problem": "FunctionContainsThis", + "suggest": "", + "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", + "severity": "ERROR" + }, + { + "line": 62, + "column": 20, + "endLine": 62, + "endColumn": 24, + "problem": "InvalidIdentifier", + "suggest": "", + "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", + "severity": "ERROR" + }, + { + "line": 62, + "column": 42, + "endLine": 62, + "endColumn": 46, + "problem": "ThisType", + "suggest": "", + "rule": "Type notation using \"this\" is not supported (arkts-no-typing-with-this)", + "severity": "ERROR" + }, + { + "line": 69, + "column": 5, + "endLine": 69, + "endColumn": 9, + "problem": "FunctionContainsThis", + "suggest": "", + "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", + "severity": "ERROR" + }, + { + "line": 70, + "column": 12, + "endLine": 70, + "endColumn": 16, + "problem": "FunctionContainsThis", + "suggest": "", + "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", + "severity": "ERROR" + }, + { + "line": 68, + "column": 26, + "endLine": 68, + "endColumn": 30, + "problem": "InvalidIdentifier", + "suggest": "", + "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", + "severity": "ERROR" + }, + { + "line": 68, + "column": 65, + "endLine": 68, + "endColumn": 69, + "problem": "ThisType", + "suggest": "", + "rule": "Type notation using \"this\" is not supported (arkts-no-typing-with-this)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/invalid_identifier.ets.arkts2.json b/ets2panda/linter/test/main/invalid_identifier.ets.arkts2.json index 9704178b5e..39bd99fe34 100644 --- a/ets2panda/linter/test/main/invalid_identifier.ets.arkts2.json +++ b/ets2panda/linter/test/main/invalid_identifier.ets.arkts2.json @@ -81,7 +81,7 @@ "endColumn": 13, "problem": "SwitchExpression", "suggest": "", - "rule": "The switch expression type must be of type number,string or enum (arkts-switch-expr)", + "rule": "The switch expression type must be of type char, byte, short, int, long, string or enum (arkts-switch-expr)", "severity": "ERROR" }, { diff --git a/ets2panda/linter/test/main/lazy_import.ets b/ets2panda/linter/test/main/lazy_import.ets index baea8b80e4..a40b832b4f 100755 --- a/ets2panda/linter/test/main/lazy_import.ets +++ b/ets2panda/linter/test/main/lazy_import.ets @@ -14,3 +14,6 @@ */ import lazy { m } from 'module' + +import lazy { a, b } from 'module1' +import { c } from 'module2' diff --git a/ets2panda/linter/test/main/lazy_import.ets.args.json b/ets2panda/linter/test/main/lazy_import.ets.args.json index 948b846fe0..aaabef1e0a 100755 --- a/ets2panda/linter/test/main/lazy_import.ets.args.json +++ b/ets2panda/linter/test/main/lazy_import.ets.args.json @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "arkts2": "" + "arkts2": "", + "autofix": "--arkts-2" } } diff --git a/ets2panda/linter/test/main/lazy_import.ets.arkts2.json b/ets2panda/linter/test/main/lazy_import.ets.arkts2.json index a55c1929ec..bd0dee6544 100755 --- a/ets2panda/linter/test/main/lazy_import.ets.arkts2.json +++ b/ets2panda/linter/test/main/lazy_import.ets.arkts2.json @@ -23,6 +23,16 @@ "suggest": "", "rule": "Lazy import is not supported(arkts-no-lazy-import)", "severity": "ERROR" + }, + { + "line": 18, + "column": 8, + "endLine": 18, + "endColumn": 12, + "problem": "ImportLazyIdentifier", + "suggest": "", + "rule": "Lazy import is not supported(arkts-no-lazy-import)", + "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/lazy_import.ets.autofix.json b/ets2panda/linter/test/main/lazy_import.ets.autofix.json new file mode 100644 index 0000000000..765ce394d8 --- /dev/null +++ b/ets2panda/linter/test/main/lazy_import.ets.autofix.json @@ -0,0 +1,52 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 8, + "endLine": 16, + "endColumn": 12, + "problem": "ImportLazyIdentifier", + "autofix": [ + { + "start": 612, + "end": 622, + "replacementText": "{ m }" + } + ], + "suggest": "", + "rule": "Lazy import is not supported(arkts-no-lazy-import)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 8, + "endLine": 18, + "endColumn": 12, + "problem": "ImportLazyIdentifier", + "autofix": [ + { + "start": 645, + "end": 658, + "replacementText": "{ a, b }" + } + ], + "suggest": "", + "rule": "Lazy import is not supported(arkts-no-lazy-import)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/limit_void_type.ets b/ets2panda/linter/test/main/limit_void_type.ets index 603154118f..d6ae5d427f 100644 --- a/ets2panda/linter/test/main/limit_void_type.ets +++ b/ets2panda/linter/test/main/limit_void_type.ets @@ -189,3 +189,17 @@ class C { return; } } + +function foo(): void {} +function bar(): void {} + +let aa = '1'; +let bb = aa === '1' ? foo() : bar(); // Error + +aa === '1' ? foo() : bar(); // No error +let dd; +dd = aa === '1' ? foo() : bar(); // Error +interface testB{ + u:void; // Error + fooIf():void; +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/limit_void_type.ets.arkts2.json b/ets2panda/linter/test/main/limit_void_type.ets.arkts2.json index b72341140b..3555b90375 100644 --- a/ets2panda/linter/test/main/limit_void_type.ets.arkts2.json +++ b/ets2panda/linter/test/main/limit_void_type.ets.arkts2.json @@ -965,13 +965,63 @@ "severity": "ERROR" }, { - "line": 177, - "column": 8, - "endLine": 177, - "endColumn": 16, - "problem": "ExplicitFunctionType", + "line": 197, + "column": 23, + "endLine": 197, + "endColumn": 28, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 197, + "column": 31, + "endLine": 197, + "endColumn": 36, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 200, + "column": 5, + "endLine": 200, + "endColumn": 7, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 201, + "column": 19, + "endLine": 201, + "endColumn": 24, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 201, + "column": 27, + "endLine": 201, + "endColumn": 32, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 203, + "column": 5, + "endLine": 203, + "endColumn": 9, + "problem": "LimitedVoidType", "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/main/limit_void_type.ets.json b/ets2panda/linter/test/main/limit_void_type.ets.json index f095579e86..c23430e5d2 100644 --- a/ets2panda/linter/test/main/limit_void_type.ets.json +++ b/ets2panda/linter/test/main/limit_void_type.ets.json @@ -183,6 +183,16 @@ "suggest": "", "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", "severity": "WARNING" + }, + { + "line": 200, + "column": 5, + "endLine": 200, + "endColumn": 7, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/limited_literal_type.ets b/ets2panda/linter/test/main/limited_literal_type.ets index eeb8ea8275..d44a76204c 100644 --- a/ets2panda/linter/test/main/limited_literal_type.ets +++ b/ets2panda/linter/test/main/limited_literal_type.ets @@ -34,3 +34,18 @@ class A{ } let x: number; let persons : Record; + +let s = "123"; +let c1 = s.length as number & 1; +let c2 = s.length & 1 + +function foo(p: 1) {} // CTE + +let arr: 1[]; // CTE + +let a = 1 as 1; // CTE + +let c1 = s.length as (number & 1); // error +let tup: [['arkts' | boolean, 1 | true, false], string[], number] = [['arkts', 1, false], ['arkts1', 'arkts2'], 1.5]; +let a : 1| boolean = 1; +let b : [1] = [1] \ No newline at end of file diff --git a/ets2panda/linter/test/main/limited_literal_type.ets.arkts2.json b/ets2panda/linter/test/main/limited_literal_type.ets.arkts2.json index 3675178087..08bcd5b26c 100644 --- a/ets2panda/linter/test/main/limited_literal_type.ets.arkts2.json +++ b/ets2panda/linter/test/main/limited_literal_type.ets.arkts2.json @@ -53,6 +53,166 @@ "suggest": "", "rule": "Literal types are restricted(arkts-limited-literal-types)", "severity": "ERROR" + }, + { + "line": 39, + "column": 5, + "endLine": 39, + "endColumn": 32, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 22, + "endLine": 39, + "endColumn": 32, + "problem": "IntersectionType", + "suggest": "", + "rule": "Use inheritance instead of intersection types (arkts-no-intersection-types)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 31, + "endLine": 39, + "endColumn": 32, + "problem": "LimitedLiteralType", + "suggest": "", + "rule": "Literal types are restricted(arkts-limited-literal-types)", + "severity": "ERROR" + }, + { + "line": 40, + "column": 5, + "endLine": 40, + "endColumn": 22, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 42, + "column": 17, + "endLine": 42, + "endColumn": 18, + "problem": "LimitedLiteralType", + "suggest": "", + "rule": "Literal types are restricted(arkts-limited-literal-types)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 10, + "endLine": 44, + "endColumn": 11, + "problem": "LimitedLiteralType", + "suggest": "", + "rule": "Literal types are restricted(arkts-limited-literal-types)", + "severity": "ERROR" + }, + { + "line": 46, + "column": 5, + "endLine": 46, + "endColumn": 15, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 46, + "column": 14, + "endLine": 46, + "endColumn": 15, + "problem": "LimitedLiteralType", + "suggest": "", + "rule": "Literal types are restricted(arkts-limited-literal-types)", + "severity": "ERROR" + }, + { + "line": 48, + "column": 5, + "endLine": 48, + "endColumn": 34, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 48, + "column": 23, + "endLine": 48, + "endColumn": 33, + "problem": "IntersectionType", + "suggest": "", + "rule": "Use inheritance instead of intersection types (arkts-no-intersection-types)", + "severity": "ERROR" + }, + { + "line": 48, + "column": 32, + "endLine": 48, + "endColumn": 33, + "problem": "LimitedLiteralType", + "suggest": "", + "rule": "Literal types are restricted(arkts-limited-literal-types)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 31, + "endLine": 49, + "endColumn": 32, + "problem": "LimitedLiteralType", + "suggest": "", + "rule": "Literal types are restricted(arkts-limited-literal-types)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 35, + "endLine": 49, + "endColumn": 39, + "problem": "LimitedLiteralType", + "suggest": "", + "rule": "Literal types are restricted(arkts-limited-literal-types)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 41, + "endLine": 49, + "endColumn": 46, + "problem": "LimitedLiteralType", + "suggest": "", + "rule": "Literal types are restricted(arkts-limited-literal-types)", + "severity": "ERROR" + }, + { + "line": 50, + "column": 9, + "endLine": 50, + "endColumn": 10, + "problem": "LimitedLiteralType", + "suggest": "", + "rule": "Literal types are restricted(arkts-limited-literal-types)", + "severity": "ERROR" + }, + { + "line": 51, + "column": 10, + "endLine": 51, + "endColumn": 11, + "problem": "LimitedLiteralType", + "suggest": "", + "rule": "Literal types are restricted(arkts-limited-literal-types)", + "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/limited_literal_type.ets.json b/ets2panda/linter/test/main/limited_literal_type.ets.json index ca88f857e9..cc9bfbefca 100644 --- a/ets2panda/linter/test/main/limited_literal_type.ets.json +++ b/ets2panda/linter/test/main/limited_literal_type.ets.json @@ -13,5 +13,26 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "result": [] + "result": [ + { + "line": 39, + "column": 22, + "endLine": 39, + "endColumn": 32, + "problem": "IntersectionType", + "suggest": "", + "rule": "Use inheritance instead of intersection types (arkts-no-intersection-types)", + "severity": "ERROR" + }, + { + "line": 48, + "column": 23, + "endLine": 48, + "endColumn": 33, + "problem": "IntersectionType", + "suggest": "", + "rule": "Use inheritance instead of intersection types (arkts-no-intersection-types)", + "severity": "ERROR" + } + ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/limited_stdlib_api.ets.arkts2.json b/ets2panda/linter/test/main/limited_stdlib_api.ets.arkts2.json index 2c05e0ccbc..115d052092 100644 --- a/ets2panda/linter/test/main/limited_stdlib_api.ets.arkts2.json +++ b/ets2panda/linter/test/main/limited_stdlib_api.ets.arkts2.json @@ -85,14 +85,14 @@ "severity": "ERROR" }, { - "line": 34, - "column": 19, - "endLine": 34, - "endColumn": 27, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" + "line": 34, + "column": 19, + "endLine": 34, + "endColumn": 32, + "problem": "ExplicitFunctionType", + "suggest": "", + "rule": "The function type should be explicit (arkts-no-ts-like-function-call)", + "severity": "ERROR" }, { "line": 56, @@ -304,6 +304,16 @@ "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", "severity": "ERROR" }, + { + "line": 77, + "column": 13, + "endLine": 77, + "endColumn": 39, + "problem": "BuiltinGetOwnPropertyNames", + "suggest": "", + "rule": "Using \"Object.getOwnPropertyNames\" is not allowed in this API (arkts-builtin-object-getOwnPropertyNames))", + "severity": "ERROR" + }, { "line": 85, "column": 9, diff --git a/ets2panda/linter/test/main/literals_as_prop_names.ets.args.json b/ets2panda/linter/test/main/literals_as_prop_names.ets.args.json index 4e9dc628f7..ff8738ddc9 100644 --- a/ets2panda/linter/test/main/literals_as_prop_names.ets.args.json +++ b/ets2panda/linter/test/main/literals_as_prop_names.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } diff --git a/ets2panda/linter/test/main/literals_as_prop_names.ets.arkts2.json b/ets2panda/linter/test/main/literals_as_prop_names.ets.arkts2.json index bc8e2bf232..9d889b27b6 100755 --- a/ets2panda/linter/test/main/literals_as_prop_names.ets.arkts2.json +++ b/ets2panda/linter/test/main/literals_as_prop_names.ets.arkts2.json @@ -49,9 +49,9 @@ "column": 3, "endLine": 32, "endColumn": 4, - "problem": "ObjectLiteralProperty", + "problem": "LiteralAsPropertyName", "suggest": "", - "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, { @@ -59,16 +59,6 @@ "column": 3, "endLine": 33, "endColumn": 8, - "problem": "ObjectLiteralProperty", - "suggest": "", - "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", - "severity": "ERROR" - }, - { - "line": 32, - "column": 3, - "endLine": 32, - "endColumn": 4, "problem": "LiteralAsPropertyName", "suggest": "", "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", @@ -119,19 +109,9 @@ "column": 10, "endLine": 57, "endColumn": 16, - "problem": "ObjectLiteralProperty", - "suggest": "", - "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", - "severity": "ERROR" - }, - { - "line": 57, - "column": 22, - "endLine": 57, - "endColumn": 23, - "problem": "ObjectLiteralProperty", + "problem": "LiteralAsPropertyName", "suggest": "", - "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, { @@ -209,9 +189,9 @@ "column": 3, "endLine": 80, "endColumn": 4, - "problem": "ObjectLiteralProperty", + "problem": "LiteralAsPropertyName", "suggest": "", - "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, { @@ -219,31 +199,11 @@ "column": 3, "endLine": 81, "endColumn": 8, - "problem": "ObjectLiteralProperty", - "suggest": "", - "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", - "severity": "ERROR" - }, - { - "line": 80, - "column": 3, - "endLine": 80, - "endColumn": 4, "problem": "LiteralAsPropertyName", "suggest": "", "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, - { - "line": 84, - "column": 36, - "endLine": 84, - "endColumn": 37, - "problem": "ObjectLiteralProperty", - "suggest": "", - "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", - "severity": "ERROR" - }, { "line": 84, "column": 36, diff --git a/ets2panda/linter/test/main/literals_as_prop_names.ets.autofix.json b/ets2panda/linter/test/main/literals_as_prop_names.ets.autofix.json index 0b1642d1da..69a6d4d352 100644 --- a/ets2panda/linter/test/main/literals_as_prop_names.ets.autofix.json +++ b/ets2panda/linter/test/main/literals_as_prop_names.ets.autofix.json @@ -90,26 +90,6 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, - { - "line": 32, - "column": 3, - "endLine": 32, - "endColumn": 4, - "problem": "ObjectLiteralProperty", - "suggest": "", - "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", - "severity": "ERROR" - }, - { - "line": 33, - "column": 3, - "endLine": 33, - "endColumn": 8, - "problem": "ObjectLiteralProperty", - "suggest": "", - "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", - "severity": "ERROR" - }, { "line": 32, "column": 3, @@ -137,6 +117,33 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, + { + "line": 33, + "column": 3, + "endLine": 33, + "endColumn": 8, + "problem": "LiteralAsPropertyName", + "autofix": [ + { + "replacementText": "Two", + "start": 849, + "end": 854 + }, + { + "replacementText": "Two", + "start": 940, + "end": 945 + }, + { + "replacementText": "litAsPropName.Two", + "start": 1032, + "end": 1052 + } + ], + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, { "line": 36, "column": 13, @@ -214,18 +221,6 @@ "endLine": 57, "endColumn": 10, "problem": "ObjectLiteralNoContextType", - "autofix": [ - { - "start": 1416, - "end": 1416, - "replacementText": "interface GeneratedObjectLiteralInterface_1 {\n \"name\": number;\n 2: number;\n}\n" - }, - { - "start": 1421, - "end": 1421, - "replacementText": ": GeneratedObjectLiteralInterface_1" - } - ], "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" @@ -235,19 +230,9 @@ "column": 10, "endLine": 57, "endColumn": 16, - "problem": "ObjectLiteralProperty", - "suggest": "", - "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", - "severity": "ERROR" - }, - { - "line": 57, - "column": 22, - "endLine": 57, - "endColumn": 23, - "problem": "ObjectLiteralProperty", + "problem": "LiteralAsPropertyName", "suggest": "", - "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, { @@ -290,12 +275,12 @@ { "start": 1556, "end": 1556, - "replacementText": "interface GeneratedObjectLiteralInterface_2 {\n name: number;\n _2: number;\n}\n" + "replacementText": "interface GeneratedObjectLiteralInterface_1 {\n name: number;\n _2: number;\n}\n" }, { "start": 1565, "end": 1565, - "replacementText": ": GeneratedObjectLiteralInterface_2" + "replacementText": ": GeneratedObjectLiteralInterface_1" } ], "suggest": "", @@ -356,26 +341,6 @@ "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", "severity": "ERROR" }, - { - "line": 80, - "column": 3, - "endLine": 80, - "endColumn": 4, - "problem": "ObjectLiteralProperty", - "suggest": "", - "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", - "severity": "ERROR" - }, - { - "line": 81, - "column": 3, - "endLine": 81, - "endColumn": 8, - "problem": "ObjectLiteralProperty", - "suggest": "", - "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", - "severity": "ERROR" - }, { "line": 80, "column": 3, @@ -399,13 +364,25 @@ "severity": "ERROR" }, { - "line": 84, - "column": 36, - "endLine": 84, - "endColumn": 37, - "problem": "ObjectLiteralProperty", + "line": 81, + "column": 3, + "endLine": 81, + "endColumn": 8, + "problem": "LiteralAsPropertyName", + "autofix": [ + { + "replacementText": "__2", + "start": 1739, + "end": 1744 + }, + { + "replacementText": "__2", + "start": 1824, + "end": 1829 + } + ], "suggest": "", - "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, { diff --git a/ets2panda/linter/test/migrate/literals_as_prop_names.sts b/ets2panda/linter/test/main/literals_as_prop_names.ets.migrate.ets similarity index 58% rename from ets2panda/linter/test/migrate/literals_as_prop_names.sts rename to ets2panda/linter/test/main/literals_as_prop_names.ets.migrate.ets index 7d4da7fcdd..322bb59464 100644 --- a/ets2panda/linter/test/migrate/literals_as_prop_names.sts +++ b/ets2panda/linter/test/main/literals_as_prop_names.ets.migrate.ets @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,23 +13,31 @@ * limitations under the License. */ +import { Component, State } from '@kit.ArkUI'; + import { ExportLitAsPropName } from './ignore_files/good'; +enum LiteralAsPropertyNameEnum { + One = "one", + PrivateTwo = "_2", + Two = "Two" +} + class LiteralAsPropertyName { public one: string = "1111111111"; - private 2: string; - 'Two': number; + private __2: string; + Two: number; } const litAsPropName: LiteralAsPropertyName = { one: "1", - 2: 'two', - 'Two': 2, + __2: 'two', + Two: 2, }; -console.log(litAsPropName["one"]); -console.log(litAsPropName[2]); -console.log(litAsPropName["Two"]); +console.log(litAsPropName.one); +console.log(litAsPropName.__2); +console.log(litAsPropName.Two); class LiteralAsPropertyName_fix { public one: string = "1111111111"; @@ -58,7 +66,11 @@ class X_class { public _2: number; } -let x_fix = {name: 20, _2: 20}; +interface GeneratedObjectLiteralInterface_1 { + name: number; + _2: number; +} +let x_fix: GeneratedObjectLiteralInterface_1 = {name: 20, _2: 20}; console.log("Fixed x object literal:"); console.log(x_fix.name); @@ -66,13 +78,50 @@ console.log(x_fix._2); interface litAsPropNameIface { one: string; - 2: string; - '__2': number; + ___2: string; + __2: number; } const int: litAsPropNameIface = { one: '12321', - 2: 'weqwewq', - '__2': 123 + ___2: 'weqwewq', + __2: 123 }; const imp: ExportLitAsPropName = { 1: 234 }; + +LiteralAsPropertyNameEnum['One'] + +LiteralAsPropertyNameEnum.PrivateTwo; + +{ + const enum Direction { + __empty = 1, + } +} + +const enum Direction16 { + ___x5c = 1, + __x5c = 1, +} + +const enum Direction17 { + ___x5c = 1, + __x5c = 1, +} +let case17: number = Direction17.___x5c +let case172: number = Direction17.__x5c + +const enum Direction11 { +__x21x21 = 1, +} +const enum Direction23 { +aaa = 1, +} +// ArkUI +@Component +struct Index { +@State message: string = 'Hello World'; +private case11 = Direction11.__x21x21 +build() { +} +} \ No newline at end of file diff --git a/ets2panda/linter/test/migrate/literals_as_prop_names.ts.json b/ets2panda/linter/test/main/literals_as_prop_names.ets.migrate.json similarity index 60% rename from ets2panda/linter/test/migrate/literals_as_prop_names.ts.json rename to ets2panda/linter/test/main/literals_as_prop_names.ets.migrate.json index 5a6fd813fa..f58bbbb8ee 100644 --- a/ets2panda/linter/test/migrate/literals_as_prop_names.ts.json +++ b/ets2panda/linter/test/main/literals_as_prop_names.ets.migrate.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2023-2024 Huawei Device Co., Ltd.", + "Copyright (c) 2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -15,69 +15,29 @@ ], "result": [ { - "line": 20, - "column": 11, - "endLine": 20, - "endColumn": 12, - "problem": "LiteralAsPropertyName", + "line": 59, + "column": 9, + "endLine": 59, + "endColumn": 10, + "problem": "ObjectLiteralNoContextType", "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 26, - "column": 3, - "endLine": 26, - "endColumn": 4, + "line": 59, + "column": 10, + "endLine": 59, + "endColumn": 16, "problem": "LiteralAsPropertyName", "suggest": "", "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, { - "line": 30, - "column": 13, - "endLine": 30, - "endColumn": 33, - "problem": "PropertyAccessByIndex", - "suggest": "", - "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", - "severity": "ERROR" - }, - { - "line": 31, - "column": 13, - "endLine": 31, - "endColumn": 29, - "problem": "PropertyAccessByIndex", - "suggest": "", - "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", - "severity": "ERROR" - }, - { - "line": 32, - "column": 13, - "endLine": 32, - "endColumn": 33, - "problem": "PropertyAccessByIndex", - "suggest": "", - "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", - "severity": "ERROR" - }, - { - "line": 51, - "column": 9, - "endLine": 51, - "endColumn": 10, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 51, + "line": 59, "column": 22, - "endLine": 51, + "endLine": 59, "endColumn": 23, "problem": "LiteralAsPropertyName", "suggest": "", @@ -85,9 +45,9 @@ "severity": "ERROR" }, { - "line": 53, + "line": 61, "column": 13, - "endLine": 53, + "endLine": 61, "endColumn": 22, "problem": "PropertyAccessByIndex", "suggest": "", @@ -95,9 +55,9 @@ "severity": "ERROR" }, { - "line": 54, + "line": 62, "column": 13, - "endLine": 54, + "endLine": 62, "endColumn": 17, "problem": "PropertyAccessByIndex", "suggest": "", @@ -105,49 +65,49 @@ "severity": "ERROR" }, { - "line": 61, - "column": 13, - "endLine": 61, - "endColumn": 14, - "problem": "ObjectLiteralNoContextType", + "line": 84, + "column": 7, + "endLine": 84, + "endColumn": 10, + "problem": "InvalidIdentifier", "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", "severity": "ERROR" }, { - "line": 69, - "column": 3, - "endLine": 69, - "endColumn": 4, + "line": 90, + "column": 36, + "endLine": 90, + "endColumn": 37, "problem": "LiteralAsPropertyName", "suggest": "", "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, { - "line": 74, - "column": 3, - "endLine": 74, - "endColumn": 4, - "problem": "LiteralAsPropertyName", - "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "line": 28, + "column": 11, + "endLine": 28, + "endColumn": 14, + "problem": "StrictDiagnostic", + "suggest": "Property '__2' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property '__2' has no initializer and is not definitely assigned in the constructor.", "severity": "ERROR" }, { - "line": 78, - "column": 36, - "endLine": 78, - "endColumn": 37, - "problem": "LiteralAsPropertyName", - "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "line": 29, + "column": 3, + "endLine": 29, + "endColumn": 6, + "problem": "StrictDiagnostic", + "suggest": "Property 'Two' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'Two' has no initializer and is not definitely assigned in the constructor.", "severity": "ERROR" }, { - "line": 36, + "line": 44, "column": 11, - "endLine": 36, + "endLine": 44, "endColumn": 13, "problem": "StrictDiagnostic", "suggest": "Property '_2' has no initializer and is not definitely assigned in the constructor.", @@ -155,9 +115,9 @@ "severity": "ERROR" }, { - "line": 37, + "line": 45, "column": 3, - "endLine": 37, + "endLine": 45, "endColumn": 6, "problem": "StrictDiagnostic", "suggest": "Property 'Two' has no initializer and is not definitely assigned in the constructor.", @@ -165,9 +125,9 @@ "severity": "ERROR" }, { - "line": 57, + "line": 65, "column": 12, - "endLine": 57, + "endLine": 65, "endColumn": 16, "problem": "StrictDiagnostic", "suggest": "Property 'name' has no initializer and is not definitely assigned in the constructor.", @@ -175,9 +135,9 @@ "severity": "ERROR" }, { - "line": 58, + "line": 66, "column": 12, - "endLine": 58, + "endLine": 66, "endColumn": 14, "problem": "StrictDiagnostic", "suggest": "Property '_2' has no initializer and is not definitely assigned in the constructor.", diff --git a/ets2panda/linter/test/main/localBuilder_1.ets b/ets2panda/linter/test/main/localBuilder_1.ets new file mode 100644 index 0000000000..cdf32f53d6 --- /dev/null +++ b/ets2panda/linter/test/main/localBuilder_1.ets @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@Entry +@Component +struct Parent { + @State label: string = 'Hello'; + + @LocalBuilder + citeLocalBuilder(paramA1: string) { + Row() { + Text(`UseStateVarByValue: ${paramA1}`) + } + } + + build() { + Column() { + this.citeLocalBuilder(this.label) + } + } +} diff --git a/ets2panda/linter/test/main/data_observation_2.ets.args.json b/ets2panda/linter/test/main/localBuilder_1.ets.args.json similarity index 92% rename from ets2panda/linter/test/main/data_observation_2.ets.args.json rename to ets2panda/linter/test/main/localBuilder_1.ets.args.json index 5efbceacdc..e7a5dbc614 100644 --- a/ets2panda/linter/test/main/data_observation_2.ets.args.json +++ b/ets2panda/linter/test/main/localBuilder_1.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/interop/ts_decorator.ets.arkts2.json b/ets2panda/linter/test/main/localBuilder_1.ets.arkts2.json similarity index 51% rename from ets2panda/linter/test/interop/ts_decorator.ets.arkts2.json rename to ets2panda/linter/test/main/localBuilder_1.ets.arkts2.json index 5c199b0805..d25d1a3cb3 100644 --- a/ets2panda/linter/test/interop/ts_decorator.ets.arkts2.json +++ b/ets2panda/linter/test/main/localBuilder_1.ets.arkts2.json @@ -15,70 +15,70 @@ ], "result": [ { - "line": 19, - "column": 1, - "endLine": 19, - "endColumn": 18, - "problem": "InteropNoDecorators", + "line": 21, + "column": 3, + "endLine": 21, + "endColumn": 16, + "problem": "LocalBuilderDecoratorNotSupported", "suggest": "", - "rule": "Typescript class decorators are not allowed (arkts-interop-no-decorators)", + "rule": "\"@LocalBuilder\" Decorator is not supported (arkui-no-localbuilder-decorator)", "severity": "ERROR" }, { - "line": 19, - "column": 1, - "endLine": 19, - "endColumn": 18, - "problem": "DecoratorsNotSupported", + "line": 16, + "column": 2, + "endLine": 16, + "endColumn": 7, + "problem": "UIInterfaceImport", "suggest": "", - "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 25, - "column": 1, - "endLine": 25, - "endColumn": 13, - "problem": "DecoratorsNotSupported", + "line": 17, + "column": 2, + "endLine": 17, + "endColumn": 11, + "problem": "UIInterfaceImport", "suggest": "", - "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 28, - "column": 1, - "endLine": 28, - "endColumn": 19, - "problem": "InteropNoDecorators", + "line": 19, + "column": 4, + "endLine": 19, + "endColumn": 9, + "problem": "UIInterfaceImport", "suggest": "", - "rule": "Typescript class decorators are not allowed (arkts-interop-no-decorators)", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 28, - "column": 1, - "endLine": 28, - "endColumn": 19, - "problem": "DecoratorsNotSupported", + "line": 23, + "column": 5, + "endLine": 23, + "endColumn": 8, + "problem": "UIInterfaceImport", "suggest": "", - "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 32, - "column": 3, - "endLine": 32, - "endColumn": 21, - "problem": "DecoratorsNotSupported", + "line": 24, + "column": 7, + "endLine": 24, + "endColumn": 11, + "problem": "UIInterfaceImport", "suggest": "", - "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 22, - "column": 2, - "endLine": 22, - "endColumn": 7, + "line": 29, + "column": 5, + "endLine": 29, + "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", diff --git a/ets2panda/linter/test/main/localBuilder_1.ets.autofix.json b/ets2panda/linter/test/main/localBuilder_1.ets.autofix.json new file mode 100644 index 0000000000..03374a941a --- /dev/null +++ b/ets2panda/linter/test/main/localBuilder_1.ets.autofix.json @@ -0,0 +1,137 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 21, + "column": 3, + "endLine": 21, + "endColumn": 16, + "problem": "LocalBuilderDecoratorNotSupported", + "autofix": [ + { + "start": 676, + "end": 689, + "replacementText": "@Builder" + } + ], + "suggest": "", + "rule": "\"@LocalBuilder\" Decorator is not supported (arkui-no-localbuilder-decorator)", + "severity": "ERROR" + }, + { + "line": 16, + "column": 2, + "endLine": 16, + "endColumn": 7, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, State, Row, Text, Column } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 2, + "endLine": 17, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, State, Row, Text, Column } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 4, + "endLine": 19, + "endColumn": 9, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, State, Row, Text, Column } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 5, + "endLine": 23, + "endColumn": 8, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, State, Row, Text, Column } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 7, + "endLine": 24, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, State, Row, Text, Column } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 5, + "endLine": 29, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, State, Row, Text, Column } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/localBuilder_1.ets.json b/ets2panda/linter/test/main/localBuilder_1.ets.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/localBuilder_1.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/localBuilder_1.ets.migrate.ets b/ets2panda/linter/test/main/localBuilder_1.ets.migrate.ets new file mode 100644 index 0000000000..d9a2b55ebe --- /dev/null +++ b/ets2panda/linter/test/main/localBuilder_1.ets.migrate.ets @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Builder } from '@kit.ArkUI'; + +import { Entry, Component, State, Row, Text, Column } from '@kit.ArkUI'; + +@Entry +@Component +struct Parent { + @State label: string = 'Hello'; + + @Builder + citeLocalBuilder(paramA1: string) { + Row() { + Text(`UseStateVarByValue: ${paramA1}`) + } + } + + build() { + Column() { + this.citeLocalBuilder(this.label) + } + } +} diff --git a/ets2panda/linter/test/main/localBuilder_1.ets.migrate.json b/ets2panda/linter/test/main/localBuilder_1.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/localBuilder_1.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/localBuilder_2.ets b/ets2panda/linter/test/main/localBuilder_2.ets new file mode 100644 index 0000000000..d9a2b55ebe --- /dev/null +++ b/ets2panda/linter/test/main/localBuilder_2.ets @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Builder } from '@kit.ArkUI'; + +import { Entry, Component, State, Row, Text, Column } from '@kit.ArkUI'; + +@Entry +@Component +struct Parent { + @State label: string = 'Hello'; + + @Builder + citeLocalBuilder(paramA1: string) { + Row() { + Text(`UseStateVarByValue: ${paramA1}`) + } + } + + build() { + Column() { + this.citeLocalBuilder(this.label) + } + } +} diff --git a/ets2panda/linter/test/main/localBuilder_2.ets.args.json b/ets2panda/linter/test/main/localBuilder_2.ets.args.json new file mode 100644 index 0000000000..e7a5dbc614 --- /dev/null +++ b/ets2panda/linter/test/main/localBuilder_2.ets.args.json @@ -0,0 +1,21 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2", + "migrate": "--arkts-2" + } + } \ No newline at end of file diff --git a/ets2panda/linter/test/main/localBuilder_2.ets.arkts2.json b/ets2panda/linter/test/main/localBuilder_2.ets.arkts2.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/localBuilder_2.ets.arkts2.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/localBuilder_2.ets.autofix.json b/ets2panda/linter/test/main/localBuilder_2.ets.autofix.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/localBuilder_2.ets.autofix.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/localBuilder_2.ets.json b/ets2panda/linter/test/main/localBuilder_2.ets.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/localBuilder_2.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/localBuilder_2.ets.migrate.ets b/ets2panda/linter/test/main/localBuilder_2.ets.migrate.ets new file mode 100644 index 0000000000..d9a2b55ebe --- /dev/null +++ b/ets2panda/linter/test/main/localBuilder_2.ets.migrate.ets @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Builder } from '@kit.ArkUI'; + +import { Entry, Component, State, Row, Text, Column } from '@kit.ArkUI'; + +@Entry +@Component +struct Parent { + @State label: string = 'Hello'; + + @Builder + citeLocalBuilder(paramA1: string) { + Row() { + Text(`UseStateVarByValue: ${paramA1}`) + } + } + + build() { + Column() { + this.citeLocalBuilder(this.label) + } + } +} diff --git a/ets2panda/linter/test/main/localBuilder_2.ets.migrate.json b/ets2panda/linter/test/main/localBuilder_2.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/localBuilder_2.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/make_observed_1.ets b/ets2panda/linter/test/main/make_observed_1.ets new file mode 100644 index 0000000000..f85d77d996 --- /dev/null +++ b/ets2panda/linter/test/main/make_observed_1.ets @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { UIUtils } from '@kit.ArkUI'; + +class Info { + id: number = 0; + constructor(id: number) { + this.id = id; + } +} + +@Entry +@ComponentV2 +struct Index { + @Local message: Info = UIUtils.makeObserved(new Info(20)); + build() { + Column() { + Button(`change id`).onClick(() => { + this.message.id++; + }) + Button(`change Info ${this.message.id}`).onClick(() => { + this.message = new Info(30); + }) + Button(`change Info ${this.message.id}`).onClick(() => { + this.message = UIUtils.makeObserved(new Info(30)); + }) + } + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/make_observed_1.ets.args.json b/ets2panda/linter/test/main/make_observed_1.ets.args.json new file mode 100644 index 0000000000..d8d3390ad9 --- /dev/null +++ b/ets2panda/linter/test/main/make_observed_1.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/api_path_changed.ets.arkts2.json b/ets2panda/linter/test/main/make_observed_1.ets.arkts2.json similarity index 59% rename from ets2panda/linter/test/sdkwhite/api_path_changed.ets.arkts2.json rename to ets2panda/linter/test/main/make_observed_1.ets.arkts2.json index cec30e7f8b..25479ad946 100644 --- a/ets2panda/linter/test/sdkwhite/api_path_changed.ets.arkts2.json +++ b/ets2panda/linter/test/main/make_observed_1.ets.arkts2.json @@ -15,49 +15,29 @@ ], "result": [ { - "line": 19, - "column": 19, - "endLine": 19, - "endColumn": 28, - "problem": "ApiPathChanged", + "line": 28, + "column": 26, + "endLine": 28, + "endColumn": 46, + "problem": "MakeObservedIsNotSupported", "suggest": "", - "rule": "API path have changed - please update your imports accordingly (arkts-sdk-no-decl-with-duplicate-name)", + "rule": "The makeObserved function is not supported (arkui-no-makeobserved-function)", "severity": "ERROR" }, { - "line": 19, - "column": 35, - "endLine": 19, + "line": 38, + "column": 24, + "endLine": 38, "endColumn": 44, - "problem": "ApiPathChanged", + "problem": "MakeObservedIsNotSupported", "suggest": "", - "rule": "API path have changed - please update your imports accordingly (arkts-sdk-no-decl-with-duplicate-name)", + "rule": "The makeObserved function is not supported (arkui-no-makeobserved-function)", "severity": "ERROR" }, { - "line": 19, - "column": 35, - "endLine": 19, - "endColumn": 44, - "problem": "DynamicCtorCall", - "suggest": "", - "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", - "severity": "ERROR" - }, - { - "line": 20, - "column": 19, - "endLine": 20, - "endColumn": 28, - "problem": "ApiPathChanged", - "suggest": "", - "rule": "API path have changed - please update your imports accordingly (arkts-sdk-no-decl-with-duplicate-name)", - "severity": "ERROR" - }, - { - "line": 16, + "line": 25, "column": 2, - "endLine": 16, + "endLine": 25, "endColumn": 7, "problem": "UIInterfaceImport", "suggest": "", @@ -65,60 +45,60 @@ "severity": "ERROR" }, { - "line": 17, + "line": 26, "column": 2, - "endLine": 17, - "endColumn": 11, + "endLine": 26, + "endColumn": 13, "problem": "UIInterfaceImport", "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 19, - "column": 19, - "endLine": 19, - "endColumn": 28, + "line": 28, + "column": 4, + "endLine": 28, + "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 19, - "column": 35, - "endLine": 19, - "endColumn": 44, + "line": 30, + "column": 5, + "endLine": 30, + "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 19, - "column": 57, - "endLine": 19, - "endColumn": 62, + "line": 31, + "column": 7, + "endLine": 31, + "endColumn": 13, "problem": "UIInterfaceImport", "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 20, - "column": 19, - "endLine": 20, - "endColumn": 28, + "line": 34, + "column": 7, + "endLine": 34, + "endColumn": 13, "problem": "UIInterfaceImport", "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 22, - "column": 5, - "endLine": 22, - "endColumn": 9, + "line": 37, + "column": 7, + "endLine": 37, + "endColumn": 13, "problem": "UIInterfaceImport", "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", diff --git a/ets2panda/linter/test/main/make_observed_1.ets.json b/ets2panda/linter/test/main/make_observed_1.ets.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/make_observed_1.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/make_observed_2.ets b/ets2panda/linter/test/main/make_observed_2.ets new file mode 100644 index 0000000000..f6f99b903f --- /dev/null +++ b/ets2panda/linter/test/main/make_observed_2.ets @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { UIUtils as utils } from '@ohos.arkui.StateManagement'; + +class Info { + id: number = 0; + constructor(id: number) { + this.id = id; + } +} + +@Entry +@ComponentV2 +struct Index { + @Local message: Info = utils.makeObserved(new Info(20)); + build() { + Column() { + Button(`change id`).onClick(() => { + this.message.id++; + }) + Button(`change Info ${this.message.id}`).onClick(() => { + this.message = new Info(30); + }) + Button(`change Info ${this.message.id}`).onClick(() => { + this.message = utils.makeObserved(new Info(30)); + }) + } + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/make_observed_2.ets.args.json b/ets2panda/linter/test/main/make_observed_2.ets.args.json new file mode 100644 index 0000000000..d8d3390ad9 --- /dev/null +++ b/ets2panda/linter/test/main/make_observed_2.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/make_observed_2.ets.arkts2.json b/ets2panda/linter/test/main/make_observed_2.ets.arkts2.json new file mode 100644 index 0000000000..9637e0d4ec --- /dev/null +++ b/ets2panda/linter/test/main/make_observed_2.ets.arkts2.json @@ -0,0 +1,108 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 28, + "column": 26, + "endLine": 28, + "endColumn": 44, + "problem": "MakeObservedIsNotSupported", + "suggest": "", + "rule": "The makeObserved function is not supported (arkui-no-makeobserved-function)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 24, + "endLine": 38, + "endColumn": 42, + "problem": "MakeObservedIsNotSupported", + "suggest": "", + "rule": "The makeObserved function is not supported (arkui-no-makeobserved-function)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 2, + "endLine": 25, + "endColumn": 7, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 2, + "endLine": 26, + "endColumn": 13, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 4, + "endLine": 28, + "endColumn": 9, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 5, + "endLine": 30, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 7, + "endLine": 31, + "endColumn": 13, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 7, + "endLine": 34, + "endColumn": 13, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 7, + "endLine": 37, + "endColumn": 13, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/make_observed_2.ets.json b/ets2panda/linter/test/main/make_observed_2.ets.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/make_observed_2.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/make_observed_3.ets b/ets2panda/linter/test/main/make_observed_3.ets new file mode 100644 index 0000000000..1c9c6dcc19 --- /dev/null +++ b/ets2panda/linter/test/main/make_observed_3.ets @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { UIUtils } from './utils'; + +class Info { + id: number = 0; + constructor(id: number) { + this.id = id; + } +} + +@Entry +@ComponentV2 +struct Index { + @Local message: Info = UIUtils.makeObserved(new Info(20)); + build() { + Column() { + Button(`change id`).onClick(() => { + this.message.id++; + }) + Button(`change Info ${this.message.id}`).onClick(() => { + this.message = new Info(30); + }) + Button(`change Info1 ${this.message.id}`).onClick(() => { + this.message = UIUtils.makeObserved(new Info(30)); + }) + Button(`change Info1 ${this.message.id}`).onClick(() => { + this.message = makeObserved(new Info(30)); + }) + } + } +} + +function makeObserved(source: T): T { + return source; +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/make_observed_3.ets.args.json b/ets2panda/linter/test/main/make_observed_3.ets.args.json new file mode 100644 index 0000000000..d8d3390ad9 --- /dev/null +++ b/ets2panda/linter/test/main/make_observed_3.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/make_observed_3.ets.arkts2.json b/ets2panda/linter/test/main/make_observed_3.ets.arkts2.json new file mode 100644 index 0000000000..19d2b241e6 --- /dev/null +++ b/ets2panda/linter/test/main/make_observed_3.ets.arkts2.json @@ -0,0 +1,98 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 25, + "column": 2, + "endLine": 25, + "endColumn": 7, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 2, + "endLine": 26, + "endColumn": 13, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 4, + "endLine": 28, + "endColumn": 9, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 5, + "endLine": 30, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 7, + "endLine": 31, + "endColumn": 13, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 7, + "endLine": 34, + "endColumn": 13, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 7, + "endLine": 37, + "endColumn": 13, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 40, + "column": 7, + "endLine": 40, + "endColumn": 13, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/make_observed_3.ets.json b/ets2panda/linter/test/main/make_observed_3.ets.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/make_observed_3.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/method_inheritance.ets b/ets2panda/linter/test/main/method_inheritance.ets new file mode 100644 index 0000000000..ff1895fc91 --- /dev/null +++ b/ets2panda/linter/test/main/method_inheritance.ets @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +abstract class Y { + abstract getDataByName(name: string | number, albumUri: string): Promise; +} + +class X extends Y { + async getDataByName(name: string, albumUri: string): Promise { + return; + } +} + +abstract class B { + abstract getDataByName(name: string | number, albumUri: string): Promise | Promise; +} + +class A extends B { + async getDataByName(name: string | number | boolean, albumUri: string): Promise { //Legal + return undefined; + } +} + +abstract class W { + abstract getDataByName(name: string | number, albumUri: string): Promise; +} + +class Q extends W { + async getDataByName(name: string | number, albumUri: string | number): Promise { + return; + }; +} + +abstract class BaseClass3 { + abstract compute(value: string): string; +} + +class IncorrectWiderReturn extends BaseClass3 { + compute(value: string): string | number { + return value.length > 5 ? value : 0; + } +} + +abstract class BaseClass4 { + abstract setValues(x: string | number, y: boolean | number): void; +} + +class IncorrectMultipleParamMismatch extends BaseClass4 { + setValues(x: string, y: boolean): void { + console.log(x, y); + } +} + +abstract class BaseClass5 { + abstract transform(data: number | string): number; +} + +class IncorrectBothMismatch extends BaseClass5 { + transform(data: number): number | string { + return data > 10 ? data : "too small"; + } +} + +//legal +abstract class BaseClass { + abstract getData(a: string | number): string | number; +} + +class CorrectWiderParam extends BaseClass { + getData(a: string | number | boolean): string | number { + return typeof a === 'boolean' ? 0 : a; + } +} + +class CorrectNarrowerReturn extends BaseClass { + getData(a: string | number): string { + return typeof a === 'number' ? a.toString() : a; + } +} + +class CorrectBothWiderParamNarrowReturn extends BaseClass { + getData(a: string | number | boolean): string { + return String(a); + } +} + + diff --git a/ets2panda/linter/test/main/method_inheritance.ets.args.json b/ets2panda/linter/test/main/method_inheritance.ets.args.json new file mode 100644 index 0000000000..d8d3390ad9 --- /dev/null +++ b/ets2panda/linter/test/main/method_inheritance.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/method_inheritance.ets.arkts2.json b/ets2panda/linter/test/main/method_inheritance.ets.arkts2.json new file mode 100644 index 0000000000..4a6d9d7c64 --- /dev/null +++ b/ets2panda/linter/test/main/method_inheritance.ets.arkts2.json @@ -0,0 +1,98 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 21, + "column": 25, + "endLine": 21, + "endColumn": 37, + "problem": "MethodInheritRule", + "suggest": "", + "rule": "Overridden method parameters and return types must respect type inheritance principles (arkts-method-inherit-rule)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 58, + "endLine": 21, + "endColumn": 76, + "problem": "MethodInheritRule", + "suggest": "", + "rule": "Overridden method parameters and return types must respect type inheritance principles (arkts-method-inherit-rule)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 76, + "endLine": 41, + "endColumn": 94, + "problem": "MethodInheritRule", + "suggest": "", + "rule": "Overridden method parameters and return types must respect type inheritance principles (arkts-method-inherit-rule)", + "severity": "ERROR" + }, + { + "line": 51, + "column": 29, + "endLine": 51, + "endColumn": 44, + "problem": "MethodInheritRule", + "suggest": "", + "rule": "Overridden method parameters and return types must respect type inheritance principles (arkts-method-inherit-rule)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 15, + "endLine": 61, + "endColumn": 24, + "problem": "MethodInheritRule", + "suggest": "", + "rule": "Overridden method parameters and return types must respect type inheritance principles (arkts-method-inherit-rule)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 26, + "endLine": 61, + "endColumn": 36, + "problem": "MethodInheritRule", + "suggest": "", + "rule": "Overridden method parameters and return types must respect type inheritance principles (arkts-method-inherit-rule)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 15, + "endLine": 71, + "endColumn": 27, + "problem": "MethodInheritRule", + "suggest": "", + "rule": "Overridden method parameters and return types must respect type inheritance principles (arkts-method-inherit-rule)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 30, + "endLine": 71, + "endColumn": 45, + "problem": "MethodInheritRule", + "suggest": "", + "rule": "Overridden method parameters and return types must respect type inheritance principles (arkts-method-inherit-rule)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/method_inheritance.ets.json b/ets2panda/linter/test/main/method_inheritance.ets.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/method_inheritance.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/method_overriding.ets b/ets2panda/linter/test/main/method_overriding.ets index f4f2e72de9..d2c2684927 100755 --- a/ets2panda/linter/test/main/method_overriding.ets +++ b/ets2panda/linter/test/main/method_overriding.ets @@ -54,3 +54,11 @@ interface Person8 { interface Person8_1 extends Person8 { fun: () => void } + +interface Person9 { + fun: () => void +} + +interface Person9_1 extends Person9 { + fun():void +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/method_overriding.ets.arkts2.json b/ets2panda/linter/test/main/method_overriding.ets.arkts2.json index 6353ca54f2..4d9808c7f7 100755 --- a/ets2panda/linter/test/main/method_overriding.ets.arkts2.json +++ b/ets2panda/linter/test/main/method_overriding.ets.arkts2.json @@ -21,7 +21,7 @@ "endColumn": 10, "problem": "MethodOverridingField", "suggest": "", - "rule": "Method cant't override filed in interface implemented (arkts-no-method-overriding-field)", + "rule": "Method can't override filed in interface implemented (arkts-no-method-overriding-field)", "severity": "ERROR" }, { @@ -31,7 +31,7 @@ "endColumn": 12, "problem": "MethodOverridingField", "suggest": "", - "rule": "Method cant't override filed in interface implemented (arkts-no-method-overriding-field)", + "rule": "Method can't override filed in interface implemented (arkts-no-method-overriding-field)", "severity": "ERROR" }, { @@ -41,7 +41,7 @@ "endColumn": 31, "problem": "MethodOverridingField", "suggest": "", - "rule": "Method cant't override filed in interface implemented (arkts-no-method-overriding-field)", + "rule": "Method can't override filed in interface implemented (arkts-no-method-overriding-field)", "severity": "ERROR" }, { @@ -51,7 +51,7 @@ "endColumn": 30, "problem": "MethodOverridingField", "suggest": "", - "rule": "Method cant't override filed in interface implemented (arkts-no-method-overriding-field)", + "rule": "Method can't override filed in interface implemented (arkts-no-method-overriding-field)", "severity": "ERROR" }, { @@ -61,7 +61,7 @@ "endColumn": 13, "problem": "MethodOverridingField", "suggest": "", - "rule": "Method cant't override filed in interface implemented (arkts-no-method-overriding-field)", + "rule": "Method can't override filed in interface implemented (arkts-no-method-overriding-field)", "severity": "ERROR" }, { @@ -71,8 +71,18 @@ "endColumn": 18, "problem": "MethodOverridingField", "suggest": "", - "rule": "Method cant't override filed in interface implemented (arkts-no-method-overriding-field)", + "rule": "Method can't override filed in interface implemented (arkts-no-method-overriding-field)", "severity": "ERROR" - } + }, + { + "line": 63, + "column": 3, + "endLine": 63, + "endColumn": 13, + "problem": "MethodOverridingField", + "suggest": "", + "rule": "Method can't override filed in interface implemented (arkts-no-method-overriding-field)", + "severity": "ERROR" + } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/no_enum_prop_as_type.ets b/ets2panda/linter/test/main/no_enum_prop_as_type.ets new file mode 100644 index 0000000000..531ba32806 --- /dev/null +++ b/ets2panda/linter/test/main/no_enum_prop_as_type.ets @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +enum A { E = 'A' } +function foo(a: A.E) {} // ERROR + +let b: A.E = ''; \ No newline at end of file diff --git a/ets2panda/linter/test/main/no_enum_prop_as_type.ets.args.json b/ets2panda/linter/test/main/no_enum_prop_as_type.ets.args.json new file mode 100644 index 0000000000..d8d3390ad9 --- /dev/null +++ b/ets2panda/linter/test/main/no_enum_prop_as_type.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/no_enum_prop_as_type.ets.arkts2.json b/ets2panda/linter/test/main/no_enum_prop_as_type.ets.arkts2.json new file mode 100644 index 0000000000..5974b15145 --- /dev/null +++ b/ets2panda/linter/test/main/no_enum_prop_as_type.ets.arkts2.json @@ -0,0 +1,38 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 17, + "endLine": 18, + "endColumn": 20, + "problem": "NoEnumPropAsType", + "suggest": "", + "rule": "Enum prop as type are not supported (arkts-no-enum-prop-as-type)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 8, + "endLine": 20, + "endColumn": 11, + "problem": "NoEnumPropAsType", + "suggest": "", + "rule": "Enum prop as type are not supported (arkts-no-enum-prop-as-type)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/no_enum_prop_as_type.ets.json b/ets2panda/linter/test/main/no_enum_prop_as_type.ets.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/no_enum_prop_as_type.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/no_import_concurrency.ets b/ets2panda/linter/test/main/no_import_concurrency.ets index 3414485f76..d6f173602a 100644 --- a/ets2panda/linter/test/main/no_import_concurrency.ets +++ b/ets2panda/linter/test/main/no_import_concurrency.ets @@ -14,9 +14,13 @@ */ -import { taskpool }from '@kit.ArkTS'; +import { foo, util, taskpool as tpp } from '@ohos.taskpool'; import { anyClass } from '@kit.ArkTS'; //legal -import process from '@ohos.process'; +import foo2, { fooClass } from '@ohos.taskpool'; //legal +import taskpool, { ArkTSUtils as Atu, roo } from '@kit.ArkTS'; +import koo, { ArkTSUtils as Ark, process as pr } from '@kit.ArkTS'; +import doo, { ArkTSUtils as Ats, too } from '@kit.ArkTS'; import fooke from '@ohos.process'; //legal -import { fooClass } from '@ohos.process'; //legal -import { ArkTSUtils } from '@kit.ArkTS' \ No newline at end of file +import { process as ps } from '@ohos.process'; +import process from '@ohos.process'; +import ArkTSUtils, { taskpool as tsk, process as prs } from '@kit.ArkTS'; \ No newline at end of file diff --git a/ets2panda/linter/test/main/no_import_concurrency.ets.args.json b/ets2panda/linter/test/main/no_import_concurrency.ets.args.json index d8d3390ad9..ef3938e967 100644 --- a/ets2panda/linter/test/main/no_import_concurrency.ets.args.json +++ b/ets2panda/linter/test/main/no_import_concurrency.ets.args.json @@ -14,6 +14,8 @@ "limitations under the License." ], "mode": { - "arkts2": "" + "arkts2": "", + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/no_import_concurrency.ets.arkts2.json b/ets2panda/linter/test/main/no_import_concurrency.ets.arkts2.json index 66ab81cc70..7d90da6369 100644 --- a/ets2panda/linter/test/main/no_import_concurrency.ets.arkts2.json +++ b/ets2panda/linter/test/main/no_import_concurrency.ets.arkts2.json @@ -16,29 +16,89 @@ "result": [ { "line": 17, - "column": 1, + "column": 21, "endLine": 17, - "endColumn": 38, + "endColumn": 36, "problem": "LimitedStdLibNoImportConcurrency", "suggest": "", "rule": "Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)", "severity": "ERROR" }, { - "line": 19, - "column": 1, - "endLine": 19, + "line": 20, + "column": 8, + "endLine": 20, + "endColumn": 16, + "problem": "LimitedStdLibNoImportConcurrency", + "suggest": "", + "rule": "Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 20, + "endLine": 20, "endColumn": 37, "problem": "LimitedStdLibNoImportConcurrency", "suggest": "", "rule": "Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)", "severity": "ERROR" }, + { + "line": 21, + "column": 15, + "endLine": 21, + "endColumn": 32, + "problem": "LimitedStdLibNoImportConcurrency", + "suggest": "", + "rule": "Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 34, + "endLine": 21, + "endColumn": 47, + "problem": "LimitedStdLibNoImportConcurrency", + "suggest": "", + "rule": "Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)", + "severity": "ERROR" + }, { "line": 22, - "column": 1, + "column": 15, "endLine": 22, - "endColumn": 40, + "endColumn": 32, + "problem": "LimitedStdLibNoImportConcurrency", + "suggest": "", + "rule": "Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 1, + "endLine": 24, + "endColumn": 47, + "problem": "LimitedStdLibNoImportConcurrency", + "suggest": "", + "rule": "Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 1, + "endLine": 25, + "endColumn": 37, + "problem": "LimitedStdLibNoImportConcurrency", + "suggest": "", + "rule": "Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 1, + "endLine": 26, + "endColumn": 74, "problem": "LimitedStdLibNoImportConcurrency", "suggest": "", "rule": "Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)", diff --git a/ets2panda/linter/test/main/no_import_concurrency.ets.autofix.json b/ets2panda/linter/test/main/no_import_concurrency.ets.autofix.json new file mode 100644 index 0000000000..2a756c0a4e --- /dev/null +++ b/ets2panda/linter/test/main/no_import_concurrency.ets.autofix.json @@ -0,0 +1,171 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 21, + "endLine": 17, + "endColumn": 36, + "problem": "LimitedStdLibNoImportConcurrency", + "autofix": [ + { + "start": 629, + "end": 646, + "replacementText": "" + } + ], + "suggest": "", + "rule": "Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 8, + "endLine": 20, + "endColumn": 16, + "problem": "LimitedStdLibNoImportConcurrency", + "autofix": [ + { + "start": 783, + "end": 793, + "replacementText": "" + } + ], + "suggest": "", + "rule": "Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 20, + "endLine": 20, + "endColumn": 37, + "problem": "LimitedStdLibNoImportConcurrency", + "autofix": [ + { + "start": 795, + "end": 814, + "replacementText": "" + } + ], + "suggest": "", + "rule": "Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 15, + "endLine": 21, + "endColumn": 32, + "problem": "LimitedStdLibNoImportConcurrency", + "autofix": [ + { + "start": 853, + "end": 872, + "replacementText": "" + } + ], + "suggest": "", + "rule": "Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 34, + "endLine": 21, + "endColumn": 47, + "problem": "LimitedStdLibNoImportConcurrency", + "autofix": [ + { + "start": 870, + "end": 885, + "replacementText": "" + } + ], + "suggest": "", + "rule": "Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 15, + "endLine": 22, + "endColumn": 32, + "problem": "LimitedStdLibNoImportConcurrency", + "autofix": [ + { + "start": 921, + "end": 940, + "replacementText": "" + } + ], + "suggest": "", + "rule": "Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 1, + "endLine": 24, + "endColumn": 47, + "problem": "LimitedStdLibNoImportConcurrency", + "autofix": [ + { + "start": 1008, + "end": 1054, + "replacementText": "" + } + ], + "suggest": "", + "rule": "Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 1, + "endLine": 25, + "endColumn": 37, + "problem": "LimitedStdLibNoImportConcurrency", + "autofix": [ + { + "start": 1055, + "end": 1091, + "replacementText": "" + } + ], + "suggest": "", + "rule": "Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 1, + "endLine": 26, + "endColumn": 74, + "problem": "LimitedStdLibNoImportConcurrency", + "autofix": [ + { + "start": 1092, + "end": 1165, + "replacementText": "" + } + ], + "suggest": "", + "rule": "Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/no_import_concurrency.ets.migrate.ets b/ets2panda/linter/test/main/no_import_concurrency.ets.migrate.ets new file mode 100644 index 0000000000..a7dc1cccd1 --- /dev/null +++ b/ets2panda/linter/test/main/no_import_concurrency.ets.migrate.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +import { foo, util } from '@ohos.taskpool'; +import { anyClass } from '@kit.ArkTS'; //legal +import foo2, { fooClass } from '@ohos.taskpool'; //legal +import { roo } from '@kit.ArkTS'; +import koo from '@kit.ArkTS'; +import doo, { too } from '@kit.ArkTS'; +import fooke from '@ohos.process'; //legal + + diff --git a/ets2panda/linter/test/main/no_import_concurrency.ets.migrate.json b/ets2panda/linter/test/main/no_import_concurrency.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/no_import_concurrency.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/no_sparse_array.ets b/ets2panda/linter/test/main/no_sparse_array.ets new file mode 100644 index 0000000000..3298c36c92 --- /dev/null +++ b/ets2panda/linter/test/main/no_sparse_array.ets @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +let a = [1, , , 3]; +let b = []; \ No newline at end of file diff --git a/ets2panda/linter/test/main/no_sparse_array.ets.args.json b/ets2panda/linter/test/main/no_sparse_array.ets.args.json new file mode 100644 index 0000000000..ddcd120faf --- /dev/null +++ b/ets2panda/linter/test/main/no_sparse_array.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } + } + \ No newline at end of file diff --git a/ets2panda/linter/test/main/no_sparse_array.ets.arkts2.json b/ets2panda/linter/test/main/no_sparse_array.ets.arkts2.json new file mode 100644 index 0000000000..e6e4296523 --- /dev/null +++ b/ets2panda/linter/test/main/no_sparse_array.ets.arkts2.json @@ -0,0 +1,38 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 12, + "endLine": 16, + "endColumn": 12, + "problem": "NosparseArray", + "suggest": "", + "rule": "Sparse array are not supported (arkts-no-sparse-array)", + "severity": "ERROR" + }, + { + "line": 16, + "column": 14, + "endLine": 16, + "endColumn": 14, + "problem": "NosparseArray", + "suggest": "", + "rule": "Sparse array are not supported (arkts-no-sparse-array)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/no_sparse_array.ets.json b/ets2panda/linter/test/main/no_sparse_array.ets.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/no_sparse_array.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/no_ts_like_smart_type.ets b/ets2panda/linter/test/main/no_ts_like_smart_type.ets new file mode 100755 index 0000000000..01a023bc1f --- /dev/null +++ b/ets2panda/linter/test/main/no_ts_like_smart_type.ets @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// static +class AA1 { + public static instance : number | string; + getInstance(): number { + if (AA1.instance instanceof string) { + return 0; + } + return AA1.instance; // Error + } +} + +class AA2 { + public instance : number | string; + getInstance(): number { + if (this.instance instanceof string) { + return 0; + } + return this.instance; // Error + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/no_ts_like_smart_type.ets.args.json b/ets2panda/linter/test/main/no_ts_like_smart_type.ets.args.json new file mode 100755 index 0000000000..aac366be5e --- /dev/null +++ b/ets2panda/linter/test/main/no_ts_like_smart_type.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} diff --git a/ets2panda/linter/test/main/no_ts_like_smart_type.ets.arkts2.json b/ets2panda/linter/test/main/no_ts_like_smart_type.ets.arkts2.json new file mode 100755 index 0000000000..ac0ca437fc --- /dev/null +++ b/ets2panda/linter/test/main/no_ts_like_smart_type.ets.arkts2.json @@ -0,0 +1,58 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 22, + "column": 9, + "endLine": 22, + "endColumn": 29, + "problem": "NoTsLikeSmartType", + "suggest": "", + "rule": "Smart type differences (arkts-no-ts-like-smart-type)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 5, + "endLine": 17, + "endColumn": 46, + "problem": "ClassstaticInitialization", + "suggest": "", + "rule": "The static property has no initializer (arkts-class-static-initialization)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 9, + "endLine": 32, + "endColumn": 30, + "problem": "NoTsLikeSmartType", + "suggest": "", + "rule": "Smart type differences (arkts-no-ts-like-smart-type)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 12, + "endLine": 27, + "endColumn": 20, + "problem": "StrictDiagnostic", + "suggest": "Property 'instance' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'instance' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/no_ts_like_smart_type.ets.json b/ets2panda/linter/test/main/no_ts_like_smart_type.ets.json new file mode 100755 index 0000000000..b9d40bdd28 --- /dev/null +++ b/ets2panda/linter/test/main/no_ts_like_smart_type.ets.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 27, + "column": 12, + "endLine": 27, + "endColumn": 20, + "problem": "StrictDiagnostic", + "suggest": "Property 'instance' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'instance' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/no_tuples_arrays.ets b/ets2panda/linter/test/main/no_tuples_arrays.ets index feddaf52a0..93ab572c51 100644 --- a/ets2panda/linter/test/main/no_tuples_arrays.ets +++ b/ets2panda/linter/test/main/no_tuples_arrays.ets @@ -72,4 +72,19 @@ let gg: (boolean | number | boolean)[] = new A().ee() let ff = new A().ff() let hh: (boolean | number | boolean)[] =ff let mm: (boolean | number | boolean)[] = a.gg(); -let test: (boolean | string | A)[] = this.test3() \ No newline at end of file +let test: (boolean | string | A)[] = this.test3() + +let tuple14: [number, boolean] = [3.14, true] +let array13: (number|boolean)[] = tuple as (number|boolean)[] //error +let array14: (number|boolean)[] = tuple14 as (number|boolean)[] //error +let array15: (number|boolean)[] = array as (number|boolean)[] +let array16: (boolean | number | boolean)[] = a.gg() as (boolean | number | boolean)[] //error +let tuple15: [string, number, boolean] = this.test2() as [string, number, boolean] +let tuple16: [number, number, boolean] = array as [number, number, boolean] +let tuple17: [number, string, boolean] = ['s', 3.14, true] as [number, string, boolean] +const array17 = Array.from({ length: 5 }, (_, index) => index % 2 === 0 ? index : index % 3 === 0); +let tuple19: [number, boolean] = array17 as [number, boolean] //error +const originalArray: [number] = [1, 2, 3, 4, 5]; +const array18 = originalArray.map((value) => value % 2 === 0 ? true : value * 2); +let tuple20: [number, boolean] = array18 as [number, boolean] //error +let array20: (number)[] = originalArray as (number)[] //error \ No newline at end of file diff --git a/ets2panda/linter/test/main/no_tuples_arrays.ets.arkts2.json b/ets2panda/linter/test/main/no_tuples_arrays.ets.arkts2.json index 38136a1694..b86a5ddb80 100644 --- a/ets2panda/linter/test/main/no_tuples_arrays.ets.arkts2.json +++ b/ets2panda/linter/test/main/no_tuples_arrays.ets.arkts2.json @@ -34,6 +34,16 @@ "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", "severity": "ERROR" }, + { + "line": 25, + "column": 13, + "endLine": 25, + "endColumn": 59, + "problem": "ArrayTypeImmutable", + "suggest": "", + "rule": "Array types follow the principle of invariance (arkts-array-type-immutable)", + "severity": "ERROR" + }, { "line": 39, "column": 13, @@ -44,6 +54,16 @@ "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", "severity": "ERROR" }, + { + "line": 39, + "column": 13, + "endLine": 39, + "endColumn": 62, + "problem": "ArrayTypeImmutable", + "suggest": "", + "rule": "Array types follow the principle of invariance (arkts-array-type-immutable)", + "severity": "ERROR" + }, { "line": 65, "column": 7, @@ -54,6 +74,16 @@ "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", "severity": "ERROR" }, + { + "line": 65, + "column": 7, + "endLine": 65, + "endColumn": 42, + "problem": "ArrayTypeImmutable", + "suggest": "", + "rule": "Array types follow the principle of invariance (arkts-array-type-immutable)", + "severity": "ERROR" + }, { "line": 67, "column": 7, @@ -64,6 +94,16 @@ "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", "severity": "ERROR" }, + { + "line": 67, + "column": 7, + "endLine": 67, + "endColumn": 53, + "problem": "ArrayTypeImmutable", + "suggest": "", + "rule": "Array types follow the principle of invariance (arkts-array-type-immutable)", + "severity": "ERROR" + }, { "line": 68, "column": 7, @@ -74,6 +114,16 @@ "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", "severity": "ERROR" }, + { + "line": 68, + "column": 7, + "endLine": 68, + "endColumn": 53, + "problem": "ArrayTypeImmutable", + "suggest": "", + "rule": "Array types follow the principle of invariance (arkts-array-type-immutable)", + "severity": "ERROR" + }, { "line": 70, "column": 5, @@ -84,6 +134,16 @@ "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", "severity": "ERROR" }, + { + "line": 70, + "column": 5, + "endLine": 70, + "endColumn": 53, + "problem": "ArrayTypeImmutable", + "suggest": "", + "rule": "Array types follow the principle of invariance (arkts-array-type-immutable)", + "severity": "ERROR" + }, { "line": 73, "column": 5, @@ -94,6 +154,16 @@ "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", "severity": "ERROR" }, + { + "line": 73, + "column": 5, + "endLine": 73, + "endColumn": 43, + "problem": "ArrayTypeImmutable", + "suggest": "", + "rule": "Array types follow the principle of invariance (arkts-array-type-immutable)", + "severity": "ERROR" + }, { "line": 74, "column": 5, @@ -104,11 +174,121 @@ "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", "severity": "ERROR" }, + { + "line": 74, + "column": 5, + "endLine": 74, + "endColumn": 48, + "problem": "ArrayTypeImmutable", + "suggest": "", + "rule": "Array types follow the principle of invariance (arkts-array-type-immutable)", + "severity": "ERROR" + }, + { + "line": 75, + "column": 5, + "endLine": 75, + "endColumn": 50, + "problem": "NoTuplesArrays", + "suggest": "", + "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", + "severity": "ERROR" + }, { "line": 75, "column": 5, "endLine": 75, "endColumn": 50, + "problem": "ArrayTypeImmutable", + "suggest": "", + "rule": "Array types follow the principle of invariance (arkts-array-type-immutable)", + "severity": "ERROR" + }, + { + "line": 78, + "column": 35, + "endLine": 78, + "endColumn": 62, + "problem": "NoTuplesArrays", + "suggest": "", + "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", + "severity": "ERROR" + }, + { + "line": 79, + "column": 35, + "endLine": 79, + "endColumn": 64, + "problem": "NoTuplesArrays", + "suggest": "", + "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", + "severity": "ERROR" + }, + { + "line": 81, + "column": 47, + "endLine": 81, + "endColumn": 87, + "problem": "NoTuplesArrays", + "suggest": "", + "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", + "severity": "ERROR" + }, + { + "line": 83, + "column": 42, + "endLine": 83, + "endColumn": 76, + "problem": "NoTuplesArrays", + "suggest": "", + "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", + "severity": "ERROR" + }, + { + "line": 85, + "column": 17, + "endLine": 85, + "endColumn": 99, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 85, + "column": 44, + "endLine": 85, + "endColumn": 45, + "problem": "UnknownType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 86, + "column": 34, + "endLine": 86, + "endColumn": 62, + "problem": "NoTuplesArrays", + "suggest": "", + "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", + "severity": "ERROR" + }, + { + "line": 89, + "column": 34, + "endLine": 89, + "endColumn": 62, + "problem": "NoTuplesArrays", + "suggest": "", + "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", + "severity": "ERROR" + }, + { + "line": 90, + "column": 27, + "endLine": 90, + "endColumn": 54, "problem": "NoTuplesArrays", "suggest": "", "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", diff --git a/ets2panda/linter/test/main/no_tuples_arrays.ets.json b/ets2panda/linter/test/main/no_tuples_arrays.ets.json index ca88f857e9..f08af47672 100644 --- a/ets2panda/linter/test/main/no_tuples_arrays.ets.json +++ b/ets2panda/linter/test/main/no_tuples_arrays.ets.json @@ -13,5 +13,26 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "result": [] + "result": [ + { + "line": 85, + "column": 17, + "endLine": 85, + "endColumn": 99, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 85, + "column": 44, + "endLine": 85, + "endColumn": 45, + "problem": "UnknownType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + } + ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/nondecimal-bigint.ets b/ets2panda/linter/test/main/nondecimal-bigint.ets new file mode 100755 index 0000000000..6ba019d0e5 --- /dev/null +++ b/ets2panda/linter/test/main/nondecimal-bigint.ets @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +let a1: bigint = 0xBAD3n +let a2: bigint = 0o777n +let a3: bigint = 0b101n +let a3: bigint = 123n diff --git a/ets2panda/linter/test/main/nondecimal-bigint.ets.args.json b/ets2panda/linter/test/main/nondecimal-bigint.ets.args.json new file mode 100755 index 0000000000..d8d3390ad9 --- /dev/null +++ b/ets2panda/linter/test/main/nondecimal-bigint.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/nondecimal-bigint.ets.arkts2.json b/ets2panda/linter/test/main/nondecimal-bigint.ets.arkts2.json new file mode 100755 index 0000000000..e23fd1b155 --- /dev/null +++ b/ets2panda/linter/test/main/nondecimal-bigint.ets.arkts2.json @@ -0,0 +1,48 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 18, + "endLine": 16, + "endColumn": 25, + "problem": "NondecimalBigint", + "suggest": "", + "rule": "Non-decimal BigInt literals (0x/0o/0b) are not supported. Use decimal format instead (arkts-only-support-decimal-bigint-literal)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 18, + "endLine": 17, + "endColumn": 24, + "problem": "NondecimalBigint", + "suggest": "", + "rule": "Non-decimal BigInt literals (0x/0o/0b) are not supported. Use decimal format instead (arkts-only-support-decimal-bigint-literal)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 18, + "endLine": 18, + "endColumn": 24, + "problem": "NondecimalBigint", + "suggest": "", + "rule": "Non-decimal BigInt literals (0x/0o/0b) are not supported. Use decimal format instead (arkts-only-support-decimal-bigint-literal)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/nondecimal-bigint.ets.json b/ets2panda/linter/test/main/nondecimal-bigint.ets.json new file mode 100755 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/nondecimal-bigint.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/api_path_changed.ets b/ets2panda/linter/test/main/numeric_bigint_compare.ets similarity index 78% rename from ets2panda/linter/test/sdkwhite/api_path_changed.ets rename to ets2panda/linter/test/main/numeric_bigint_compare.ets index 5f3d51d879..74f1bf97da 100755 --- a/ets2panda/linter/test/sdkwhite/api_path_changed.ets +++ b/ets2panda/linter/test/main/numeric_bigint_compare.ets @@ -13,12 +13,22 @@ * limitations under the License. */ -@Entry -@Component -struct Index { - fontStyleAttr1: TextStyle = new TextStyle({fontColor: Color.Blue}); - fontStyleAttr2: TextStyle; - build() { - Text(); - } -} \ No newline at end of file +let n1:number = 123; +let n2:bigint = 456n; + +n1 <= n2 +n1 == n2 +n1 >= n2 + +n1 != n2 +n1 !== n2 +n1 === n2 +n1 > n2 +n1 < n2 + +n1 = n2 +n1 + n2 +n1 - n2 +n1 * n2 +n1 / n2 +n1 % n2 \ No newline at end of file diff --git a/ets2panda/linter/test/main/data_observation_1.ets.args.json b/ets2panda/linter/test/main/numeric_bigint_compare.ets.args.json old mode 100644 new mode 100755 similarity index 93% rename from ets2panda/linter/test/main/data_observation_1.ets.args.json rename to ets2panda/linter/test/main/numeric_bigint_compare.ets.args.json index 5efbceacdc..b9d72da174 --- a/ets2panda/linter/test/main/data_observation_1.ets.args.json +++ b/ets2panda/linter/test/main/numeric_bigint_compare.ets.args.json @@ -1,20 +1,19 @@ -{ - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "mode": { - "arkts2": "", - "autofix": "--arkts-2" - } +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/numeric_bigint_compare.ets.arkts2.json b/ets2panda/linter/test/main/numeric_bigint_compare.ets.arkts2.json new file mode 100755 index 0000000000..30d46ababf --- /dev/null +++ b/ets2panda/linter/test/main/numeric_bigint_compare.ets.arkts2.json @@ -0,0 +1,98 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 9, + "problem": "NumericBigintCompare", + "suggest": "", + "rule": "Not supporting comparison between number type and bigint type (arkts-numeric-bigint-compare)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 9, + "problem": "NumericBigintCompare", + "suggest": "", + "rule": "Not supporting comparison between number type and bigint type (arkts-numeric-bigint-compare)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 9, + "problem": "NumericBigintCompare", + "suggest": "", + "rule": "Not supporting comparison between number type and bigint type (arkts-numeric-bigint-compare)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 1, + "endLine": 23, + "endColumn": 9, + "problem": "NumericBigintCompare", + "suggest": "", + "rule": "Not supporting comparison between number type and bigint type (arkts-numeric-bigint-compare)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 1, + "endLine": 24, + "endColumn": 10, + "problem": "NumericBigintCompare", + "suggest": "", + "rule": "Not supporting comparison between number type and bigint type (arkts-numeric-bigint-compare)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 1, + "endLine": 25, + "endColumn": 10, + "problem": "NumericBigintCompare", + "suggest": "", + "rule": "Not supporting comparison between number type and bigint type (arkts-numeric-bigint-compare)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 1, + "endLine": 26, + "endColumn": 8, + "problem": "NumericBigintCompare", + "suggest": "", + "rule": "Not supporting comparison between number type and bigint type (arkts-numeric-bigint-compare)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 1, + "endLine": 27, + "endColumn": 8, + "problem": "NumericBigintCompare", + "suggest": "", + "rule": "Not supporting comparison between number type and bigint type (arkts-numeric-bigint-compare)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/numeric_bigint_compare.ets.json b/ets2panda/linter/test/main/numeric_bigint_compare.ets.json new file mode 100755 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/numeric_bigint_compare.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/numeric_semantics.ets b/ets2panda/linter/test/main/numeric_semantics.ets index 34a471161c..e09d8b47cf 100755 --- a/ets2panda/linter/test/main/numeric_semantics.ets +++ b/ets2panda/linter/test/main/numeric_semantics.ets @@ -140,4 +140,66 @@ export class G{ readonly a5 = 4; } -const fingerprintPositionY = AppStorage.get(FingerprintConstants.COORDINATE_Y_OF_FINGERPRINT_UD_SCREEN_IN_PX) ?? 0; \ No newline at end of file +const fingerprintPositionY = AppStorage.get(FingerprintConstants.COORDINATE_Y_OF_FINGERPRINT_UD_SCREEN_IN_PX) ?? 0; + +private doCloseFolderBackgroundAnimation(): void { + openFolderLayout.getGridSwiperLayout().bgHeight = openFolderLayout.getBackgroundLayout().closedHeight; + openFolderLayout.getGridSwiperLayout().bgWidth = openFolderLayout.getBackgroundLayout().closedWidth; + + let pos = [-1, -1]; + pos = folderLayoutUtil.getFolderComponentCenterPosition(FolderData.getInstance().getOpenedFolder()); + let editModeTranslateY = this.getEditModeTranslateY(pos); + if (pos.length > 1) { + let translateXForScreenSplit: number = AppStorage.get('translateXForScreenSplit') ?? 0 as number; + let screenWidth: number = AppStorage.get('screenWidth') as number; + let screenHeight: number = AppStorage.get('screenHeight') as number; + if (screenWidth > screenHeight) { + log.showInfo('doCloseFolderBackgroundAnimation screenWidth: ' + screenWidth + ', height: ' + screenHeight); + screenWidth = screenHeight; + } + openFolderLayout.getGridSwiperLayout().bgTranslateX = pos[0] - screenWidth / 2 + translateXForScreenSplit; + openFolderLayout.getGridSwiperLayout().bgTranslateY = pos[1] + editModeTranslateY - + openFolderLayout.getBackgroundLayout().closedHeight * 0.5 - openFolderLayout.getBackgroundLayout().openedMargin; + } +} + +let f = 0.0; +let b5: number = 0; +f = b5; // OK + +let e = 0.0; +let g1: number = 0; + +e += g1; // OK +e -= g1; // OK +e *= g1; // OK +e /= g1; // OK +e <<= g1; // OK +e >>= g1; // OK +e &= g1; // OK +e = e & 3; // OK +e = e | 3; // OK +let arr1 = [1,2,3] +e += arr1[0]; // OK + +let a = 0.0; +a = fun1(); +a = fun2()!; + +function fun1():number{ + return 1; +} + +function fun2():number|undefined{ + return 1; +} + +import { ArrayList } from "@kit.ArkTS"; + +let arr = new ArrayList() +for (let i:number = 0; i < 100; i++) { + arr.add(i) +} +let cancelIds:ArrayList = arr.subArrayList(6, 86) +let a: Array = Array.from(cancelIds) +let arr1: Array = Array.from(new ArrayList()) \ No newline at end of file diff --git a/ets2panda/linter/test/main/numeric_semantics.ets.args.json b/ets2panda/linter/test/main/numeric_semantics.ets.args.json index 40bac500e3..b023016d6b 100755 --- a/ets2panda/linter/test/main/numeric_semantics.ets.args.json +++ b/ets2panda/linter/test/main/numeric_semantics.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/numeric_semantics.ets.arkts2.json b/ets2panda/linter/test/main/numeric_semantics.ets.arkts2.json index 60878c95bd..1c60c7069a 100755 --- a/ets2panda/linter/test/main/numeric_semantics.ets.arkts2.json +++ b/ets2panda/linter/test/main/numeric_semantics.ets.arkts2.json @@ -24,66 +24,6 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, - { - "line": 21, - "column": 1, - "endLine": 21, - "endColumn": 8, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 24, - "column": 1, - "endLine": 24, - "endColumn": 9, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 28, - "column": 13, - "endLine": 28, - "endColumn": 18, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 30, - "column": 13, - "endLine": 30, - "endColumn": 18, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 34, - "column": 1, - "endLine": 34, - "endColumn": 6, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 35, - "column": 1, - "endLine": 35, - "endColumn": 7, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, { "line": 39, "column": 5, @@ -94,26 +34,6 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, - { - "line": 40, - "column": 1, - "endLine": 40, - "endColumn": 6, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 41, - "column": 1, - "endLine": 41, - "endColumn": 7, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, { "line": 45, "column": 5, @@ -124,16 +44,6 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, - { - "line": 49, - "column": 13, - "endLine": 49, - "endColumn": 18, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, { "line": 51, "column": 5, @@ -464,6 +374,216 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 145, + "column": 45, + "endLine": 145, + "endColumn": 49, + "problem": "VoidOperator", + "suggest": "", + "rule": "\"void\" operator is not supported (arkts-no-void-operator)", + "severity": "ERROR" + }, + { + "line": 145, + "column": 50, + "endLine": 145, + "endColumn": 51, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 146, + "column": 5, + "endLine": 146, + "endColumn": 21, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 147, + "column": 5, + "endLine": 147, + "endColumn": 21, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 149, + "column": 5, + "endLine": 149, + "endColumn": 8, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 149, + "column": 9, + "endLine": 149, + "endColumn": 23, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 150, + "column": 5, + "endLine": 150, + "endColumn": 104, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 151, + "column": 5, + "endLine": 151, + "endColumn": 8, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 151, + "column": 9, + "endLine": 151, + "endColumn": 61, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 152, + "column": 5, + "endLine": 152, + "endColumn": 12, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 152, + "column": 5, + "endLine": 152, + "endColumn": 7, + "problem": "LimitedReturnTypeInference", + "suggest": "", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "severity": "ERROR" + }, + { + "line": 152, + "column": 5, + "endLine": 152, + "endColumn": 7, + "problem": "InvalidIdentifier", + "suggest": "", + "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", + "severity": "ERROR" + }, + { + "line": 152, + "column": 9, + "endLine": 152, + "endColumn": 12, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 166, + "column": 5, + "endLine": 166, + "endColumn": 12, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 170, + "column": 5, + "endLine": 170, + "endColumn": 12, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 182, + "column": 5, + "endLine": 182, + "endColumn": 19, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 185, + "column": 5, + "endLine": 185, + "endColumn": 12, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 197, + "column": 1, + "endLine": 197, + "endColumn": 40, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 199, + "column": 5, + "endLine": 199, + "endColumn": 34, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 199, + "column": 15, + "endLine": 199, + "endColumn": 24, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 205, + "column": 42, + "endLine": 205, + "endColumn": 51, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, { "line": 117, "column": 2, @@ -523,6 +643,36 @@ "suggest": "", "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" + }, + { + "line": 153, + "column": 46, + "endLine": 153, + "endColumn": 56, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 154, + "column": 33, + "endLine": 154, + "endColumn": 43, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 155, + "column": 34, + "endLine": 155, + "endColumn": 44, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/numeric_semantics.ets.autofix.json b/ets2panda/linter/test/main/numeric_semantics.ets.autofix.json index 8344ba36aa..ea3285da99 100644 --- a/ets2panda/linter/test/main/numeric_semantics.ets.autofix.json +++ b/ets2panda/linter/test/main/numeric_semantics.ets.autofix.json @@ -24,73 +24,17 @@ { "start": 744, "end": 749, - "replacementText": "a: number = 1" + "replacementText": "a: number = 1", + "line": 18, + "column": 5, + "endLine": 18, + "endColumn": 10 } ], "suggest": "", "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, - { - "line": 21, - "column": 1, - "endLine": 21, - "endColumn": 8, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 24, - "column": 1, - "endLine": 24, - "endColumn": 9, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 28, - "column": 13, - "endLine": 28, - "endColumn": 18, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 30, - "column": 13, - "endLine": 30, - "endColumn": 18, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 34, - "column": 1, - "endLine": 34, - "endColumn": 6, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 35, - "column": 1, - "endLine": 35, - "endColumn": 7, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, { "line": 39, "column": 5, @@ -101,33 +45,17 @@ { "start": 1377, "end": 1384, - "replacementText": "c: number = 1.5" + "replacementText": "c: number = 1.5", + "line": 39, + "column": 5, + "endLine": 39, + "endColumn": 12 } ], "suggest": "", "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, - { - "line": 40, - "column": 1, - "endLine": 40, - "endColumn": 6, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 41, - "column": 1, - "endLine": 41, - "endColumn": 7, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, { "line": 45, "column": 5, @@ -138,23 +66,17 @@ { "start": 1561, "end": 1566, - "replacementText": "d: number = 2" + "replacementText": "d: number = 2", + "line": 45, + "column": 5, + "endLine": 45, + "endColumn": 10 } ], "suggest": "", "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, - { - "line": 49, - "column": 13, - "endLine": 49, - "endColumn": 18, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, { "line": 51, "column": 5, @@ -165,7 +87,11 @@ { "start": 1712, "end": 1717, - "replacementText": "n: number = 2" + "replacementText": "n: number = 2", + "line": 51, + "column": 5, + "endLine": 51, + "endColumn": 10 } ], "suggest": "", @@ -182,7 +108,11 @@ { "start": 1747, "end": 1760, - "replacementText": "g: number[] = [1, 2, 3]" + "replacementText": "g: number[] = [1, 2, 3]", + "line": 55, + "column": 5, + "endLine": 55, + "endColumn": 18 } ], "suggest": "", @@ -209,7 +139,11 @@ { "start": 1786, "end": 1799, - "replacementText": "t8: number = Infinity" + "replacementText": "t8: number = Infinity", + "line": 59, + "column": 5, + "endLine": 59, + "endColumn": 18 } ], "suggest": "", @@ -226,7 +160,11 @@ { "start": 1807, "end": 1821, - "replacementText": "t9: number = -Infinity" + "replacementText": "t9: number = -Infinity", + "line": 61, + "column": 5, + "endLine": 61, + "endColumn": 19 } ], "suggest": "", @@ -243,7 +181,11 @@ { "start": 1830, "end": 1839, - "replacementText": "t10: number = NaN" + "replacementText": "t10: number = NaN", + "line": 63, + "column": 5, + "endLine": 63, + "endColumn": 14 } ], "suggest": "", @@ -260,7 +202,11 @@ { "start": 1848, "end": 1870, - "replacementText": "t11: number = Number.MAX_VALUE" + "replacementText": "t11: number = Number.MAX_VALUE", + "line": 65, + "column": 5, + "endLine": 65, + "endColumn": 27 } ], "suggest": "", @@ -277,7 +223,11 @@ { "start": 1879, "end": 1901, - "replacementText": "t12: number = Number.MIN_VALUE" + "replacementText": "t12: number = Number.MIN_VALUE", + "line": 67, + "column": 5, + "endLine": 67, + "endColumn": 27 } ], "suggest": "", @@ -294,7 +244,11 @@ { "start": 1959, "end": 1965, - "replacementText": "o2: number = o" + "replacementText": "o2: number = o", + "line": 73, + "column": 5, + "endLine": 73, + "endColumn": 11 } ], "suggest": "", @@ -311,7 +265,11 @@ { "start": 1975, "end": 1982, - "replacementText": "o3: number = oo" + "replacementText": "o3: number = oo", + "line": 75, + "column": 5, + "endLine": 75, + "endColumn": 12 } ], "suggest": "", @@ -328,7 +286,11 @@ { "start": 2001, "end": 2007, - "replacementText": "a: number = 1;" + "replacementText": "a: number = 1;", + "line": 78, + "column": 4, + "endLine": 78, + "endColumn": 10 } ], "suggest": "", @@ -345,7 +307,11 @@ { "start": 2043, "end": 2052, - "replacementText": "t2: number = +123" + "replacementText": "t2: number = +123", + "line": 83, + "column": 5, + "endLine": 83, + "endColumn": 14 } ], "suggest": "", @@ -362,7 +328,11 @@ { "start": 2061, "end": 2070, - "replacementText": "t3: number = -234" + "replacementText": "t3: number = -234", + "line": 85, + "column": 5, + "endLine": 85, + "endColumn": 14 } ], "suggest": "", @@ -379,7 +349,11 @@ { "start": 2079, "end": 2100, - "replacementText": "num: number = Math.floor(4.8)" + "replacementText": "num: number = Math.floor(4.8)", + "line": 87, + "column": 5, + "endLine": 87, + "endColumn": 26 } ], "suggest": "", @@ -396,7 +370,11 @@ { "start": 2124, "end": 2146, - "replacementText": "value: number = parseInt(\"42\")" + "replacementText": "value: number = parseInt(\"42\")", + "line": 89, + "column": 5, + "endLine": 89, + "endColumn": 27 } ], "suggest": "", @@ -413,7 +391,11 @@ { "start": 2188, "end": 2193, - "replacementText": "x: number = 2" + "replacementText": "x: number = 2", + "line": 92, + "column": 1, + "endLine": 94, + "endColumn": 2 } ], "suggest": "", @@ -430,7 +412,11 @@ { "start": 2195, "end": 2200, - "replacementText": "y: number = 3" + "replacementText": "y: number = 3", + "line": 92, + "column": 1, + "endLine": 94, + "endColumn": 2 } ], "suggest": "", @@ -447,7 +433,11 @@ { "start": 2201, "end": 2201, - "replacementText": ": number" + "replacementText": ": number", + "line": 92, + "column": 1, + "endLine": 94, + "endColumn": 2 } ], "suggest": "", @@ -464,7 +454,11 @@ { "start": 2264, "end": 2264, - "replacementText": ": number" + "replacementText": ": number", + "line": 96, + "column": 1, + "endLine": 98, + "endColumn": 2 } ], "suggest": "", @@ -481,7 +475,11 @@ { "start": 2347, "end": 2359, - "replacementText": "identity(42)" + "replacementText": "identity(42)", + "line": 103, + "column": 1, + "endLine": 103, + "endColumn": 13 } ], "suggest": "", @@ -498,7 +496,11 @@ { "start": 2368, "end": 2386, - "replacementText": "an_array: number[] = [1, 2, 3]" + "replacementText": "an_array: number[] = [1, 2, 3]", + "line": 105, + "column": 5, + "endLine": 105, + "endColumn": 23 } ], "suggest": "", @@ -515,7 +517,11 @@ { "start": 2394, "end": 2408, - "replacementText": "g: number = an_array[]" + "replacementText": "g: number = an_array[]", + "line": 107, + "column": 5, + "endLine": 107, + "endColumn": 19 } ], "suggest": "", @@ -542,7 +548,11 @@ { "start": 2418, "end": 2423, - "replacementText": "a: number = 1" + "replacementText": "a: number = 1", + "line": 109, + "column": 7, + "endLine": 109, + "endColumn": 12 } ], "suggest": "", @@ -559,7 +569,11 @@ { "start": 2493, "end": 2506, - "replacementText": "test: number = Test.A" + "replacementText": "test: number = Test.A", + "line": 115, + "column": 7, + "endLine": 115, + "endColumn": 20 } ], "suggest": "", @@ -576,7 +590,11 @@ { "start": 2593, "end": 2609, - "replacementText": "readonly c1: number = 1;" + "replacementText": "readonly c1: number = 1;", + "line": 121, + "column": 3, + "endLine": 121, + "endColumn": 19 } ], "suggest": "", @@ -593,7 +611,11 @@ { "start": 2620, "end": 2638, - "replacementText": "readonly c4: number = 1.7;" + "replacementText": "readonly c4: number = 1.7;", + "line": 122, + "column": 3, + "endLine": 122, + "endColumn": 21 } ], "suggest": "", @@ -610,7 +632,11 @@ { "start": 2651, "end": 2671, - "replacementText": "readonly c5: number = 0x123;" + "replacementText": "readonly c5: number = 0x123;", + "line": 123, + "column": 3, + "endLine": 123, + "endColumn": 23 } ], "suggest": "", @@ -627,7 +653,11 @@ { "start": 2683, "end": 2703, - "replacementText": "readonly c6: number = 0o123;" + "replacementText": "readonly c6: number = 0o123;", + "line": 124, + "column": 3, + "endLine": 124, + "endColumn": 23 } ], "suggest": "", @@ -644,7 +674,11 @@ { "start": 2713, "end": 2733, - "replacementText": "readonly c7: number = 0b101;" + "replacementText": "readonly c7: number = 0b101;", + "line": 125, + "column": 3, + "endLine": 125, + "endColumn": 23 } ], "suggest": "", @@ -661,7 +695,11 @@ { "start": 2743, "end": 2764, - "replacementText": "readonly c8: number[] = [1, 2, 3];" + "replacementText": "readonly c8: number[] = [1, 2, 3];", + "line": 126, + "column": 3, + "endLine": 126, + "endColumn": 24 } ], "suggest": "", @@ -678,7 +716,11 @@ { "start": 2893, "end": 2899, - "replacementText": "c1: number = 1" + "replacementText": "c1: number = 1", + "line": 137, + "column": 7, + "endLine": 137, + "endColumn": 13 } ], "suggest": "", @@ -695,7 +737,11 @@ { "start": 2923, "end": 2939, - "replacementText": "readonly a5: number = 4;" + "replacementText": "readonly a5: number = 4;", + "line": 140, + "column": 3, + "endLine": 140, + "endColumn": 19 } ], "suggest": "", @@ -722,13 +768,359 @@ { "replacementText": "fingerprintPositionY: number = AppStorage.get(FingerprintConstants.COORDINATE_Y_OF_FINGERPRINT_UD_SCREEN_IN_PX) ?? 0", "start": 2952, - "end": 3068 + "end": 3068, + "line": 143, + "column": 30, + "endLine": 143, + "endColumn": 118 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 145, + "column": 45, + "endLine": 145, + "endColumn": 49, + "problem": "VoidOperator", + "autofix": [ + { + "start": 3117, + "end": 3558, + "replacementText": "(() => {\r\n ({\r\n openFolderLayout, : .getGridSwiperLayout().bgHeight = openFolderLayout.getBackgroundLayout().closedHeight,\r\n openFolderLayout, : .getGridSwiperLayout().bgWidth = openFolderLayout.getBackgroundLayout().closedWidth,\r\n let, pos = [-1, -1],\r\n pos = folderLayoutUtil.getFolderComponentCenterPosition(FolderData.getInstance().getOpenedFolder()),\r\n let, editModeTranslateY = this.getEditModeTranslateY(pos),\r\n if(pos) { }, : .length > 1\r\n });\r\n return undefined;\r\n})()", + "line": 145, + "column": 45, + "endLine": 145, + "endColumn": 49 + } + ], + "suggest": "", + "rule": "\"void\" operator is not supported (arkts-no-void-operator)", + "severity": "ERROR" + }, + { + "line": 145, + "column": 50, + "endLine": 145, + "endColumn": 51, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 146, + "column": 5, + "endLine": 146, + "endColumn": 21, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 3129, + "end": 3145, + "replacementText": "openFolderLayout: openFolderLayout", + "line": 146, + "column": 5, + "endLine": 146, + "endColumn": 21 + } + ], + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 147, + "column": 5, + "endLine": 147, + "endColumn": 21, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 3237, + "end": 3253, + "replacementText": "openFolderLayout: openFolderLayout", + "line": 147, + "column": 5, + "endLine": 147, + "endColumn": 21 + } + ], + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 149, + "column": 5, + "endLine": 149, + "endColumn": 8, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 3345, + "end": 3348, + "replacementText": "let: let", + "line": 149, + "column": 5, + "endLine": 149, + "endColumn": 8 + } + ], + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 149, + "column": 9, + "endLine": 149, + "endColumn": 23, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 3349, + "end": 3363, + "replacementText": "pos: pos", + "line": 149, + "column": 9, + "endLine": 149, + "endColumn": 23 + } + ], + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 150, + "column": 5, + "endLine": 150, + "endColumn": 104, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 3370, + "end": 3469, + "replacementText": "pos: pos", + "line": 150, + "column": 5, + "endLine": 150, + "endColumn": 104 + } + ], + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 151, + "column": 5, + "endLine": 151, + "endColumn": 8, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 3476, + "end": 3479, + "replacementText": "let: let", + "line": 151, + "column": 5, + "endLine": 151, + "endColumn": 8 + } + ], + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 151, + "column": 9, + "endLine": 151, + "endColumn": 61, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 3480, + "end": 3532, + "replacementText": "editModeTranslateY: editModeTranslateY", + "line": 151, + "column": 9, + "endLine": 151, + "endColumn": 61 + } + ], + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 152, + "column": 5, + "endLine": 152, + "endColumn": 12, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 152, + "column": 5, + "endLine": 152, + "endColumn": 7, + "problem": "LimitedReturnTypeInference", + "suggest": "", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "severity": "ERROR" + }, + { + "line": 152, + "column": 5, + "endLine": 152, + "endColumn": 7, + "problem": "InvalidIdentifier", + "suggest": "", + "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", + "severity": "ERROR" + }, + { + "line": 152, + "column": 9, + "endLine": 152, + "endColumn": 12, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 166, + "column": 5, + "endLine": 166, + "endColumn": 12, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 4388, + "end": 4395, + "replacementText": "f: number = 0.0", + "line": 166, + "column": 5, + "endLine": 166, + "endColumn": 12 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 170, + "column": 5, + "endLine": 170, + "endColumn": 12, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 4440, + "end": 4447, + "replacementText": "e: number = 0.0", + "line": 170, + "column": 5, + "endLine": 170, + "endColumn": 12 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 182, + "column": 5, + "endLine": 182, + "endColumn": 19, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 4627, + "end": 4641, + "replacementText": "arr1: number[] = [1, 2, 3]", + "line": 182, + "column": 5, + "endLine": 182, + "endColumn": 19 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 185, + "column": 5, + "endLine": 185, + "endColumn": 12, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 4670, + "end": 4677, + "replacementText": "a: number = 0.0", + "line": 185, + "column": 5, + "endLine": 185, + "endColumn": 12 } ], "suggest": "", "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 197, + "column": 1, + "endLine": 197, + "endColumn": 40, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 199, + "column": 5, + "endLine": 199, + "endColumn": 34, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 199, + "column": 15, + "endLine": 199, + "endColumn": 24, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 205, + "column": 42, + "endLine": 205, + "endColumn": 51, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, { "line": 117, "column": 2, @@ -739,7 +1131,11 @@ { "start": 738, "end": 738, - "replacementText": "\n\nimport { Entry, Component, State, RelativeContainer, Text, AppStorage } from '@kit.ArkUI';\n" + "replacementText": "\r\n\r\nimport { Entry, Component, State, RelativeContainer, Text, AppStorage } from '@kit.ArkUI';\r\n", + "line": 155, + "column": 34, + "endLine": 155, + "endColumn": 44 } ], "suggest": "", @@ -756,7 +1152,11 @@ { "start": 738, "end": 738, - "replacementText": "\n\nimport { Entry, Component, State, RelativeContainer, Text, AppStorage } from '@kit.ArkUI';\n" + "replacementText": "\r\n\r\nimport { Entry, Component, State, RelativeContainer, Text, AppStorage } from '@kit.ArkUI';\r\n", + "line": 155, + "column": 34, + "endLine": 155, + "endColumn": 44 } ], "suggest": "", @@ -773,7 +1173,11 @@ { "start": 738, "end": 738, - "replacementText": "\n\nimport { Entry, Component, State, RelativeContainer, Text, AppStorage } from '@kit.ArkUI';\n" + "replacementText": "\r\n\r\nimport { Entry, Component, State, RelativeContainer, Text, AppStorage } from '@kit.ArkUI';\r\n", + "line": 155, + "column": 34, + "endLine": 155, + "endColumn": 44 } ], "suggest": "", @@ -790,7 +1194,11 @@ { "start": 738, "end": 738, - "replacementText": "\n\nimport { Entry, Component, State, RelativeContainer, Text, AppStorage } from '@kit.ArkUI';\n" + "replacementText": "\r\n\r\nimport { Entry, Component, State, RelativeContainer, Text, AppStorage } from '@kit.ArkUI';\r\n", + "line": 155, + "column": 34, + "endLine": 155, + "endColumn": 44 } ], "suggest": "", @@ -807,7 +1215,11 @@ { "start": 738, "end": 738, - "replacementText": "\n\nimport { Entry, Component, State, RelativeContainer, Text, AppStorage } from '@kit.ArkUI';\n" + "replacementText": "\r\n\r\nimport { Entry, Component, State, RelativeContainer, Text, AppStorage } from '@kit.ArkUI';\r\n", + "line": 155, + "column": 34, + "endLine": 155, + "endColumn": 44 } ], "suggest": "", @@ -824,7 +1236,74 @@ { "start": 738, "end": 738, - "replacementText": "\n\nimport { Entry, Component, State, RelativeContainer, Text, AppStorage } from '@kit.ArkUI';\n" + "replacementText": "\r\n\r\nimport { Entry, Component, State, RelativeContainer, Text, AppStorage } from '@kit.ArkUI';\r\n", + "line": 155, + "column": 34, + "endLine": 155, + "endColumn": 44 + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 153, + "column": 46, + "endLine": 153, + "endColumn": 56, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 738, + "end": 738, + "replacementText": "\r\n\r\nimport { Entry, Component, State, RelativeContainer, Text, AppStorage } from '@kit.ArkUI';\r\n", + "line": 155, + "column": 34, + "endLine": 155, + "endColumn": 44 + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 154, + "column": 33, + "endLine": 154, + "endColumn": 43, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 738, + "end": 738, + "replacementText": "\r\n\r\nimport { Entry, Component, State, RelativeContainer, Text, AppStorage } from '@kit.ArkUI';\r\n", + "line": 155, + "column": 34, + "endLine": 155, + "endColumn": 44 + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 155, + "column": 34, + "endLine": 155, + "endColumn": 44, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 738, + "end": 738, + "replacementText": "\r\n\r\nimport { Entry, Component, State, RelativeContainer, Text, AppStorage } from '@kit.ArkUI';\r\n", + "line": 155, + "column": 34, + "endLine": 155, + "endColumn": 44 } ], "suggest": "", diff --git a/ets2panda/linter/test/main/numeric_semantics.ets.json b/ets2panda/linter/test/main/numeric_semantics.ets.json index 95cc38ecce..47737941ad 100755 --- a/ets2panda/linter/test/main/numeric_semantics.ets.json +++ b/ets2panda/linter/test/main/numeric_semantics.ets.json @@ -1,38 +1,88 @@ -{ - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "result": [ - { - "line": 57, - "column": 5, - "endLine": 57, - "endColumn": 15, - "problem": "DefiniteAssignment", - "suggest": "", - "rule": "Definite assignment assertions are not supported (arkts-no-definite-assignment)", - "severity": "WARNING" - }, - { - "line": 143, - "column": 7, - "endLine": 143, - "endColumn": 123, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - } - ] +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 57, + "column": 5, + "endLine": 57, + "endColumn": 15, + "problem": "DefiniteAssignment", + "suggest": "", + "rule": "Definite assignment assertions are not supported (arkts-no-definite-assignment)", + "severity": "WARNING" + }, + { + "line": 143, + "column": 7, + "endLine": 143, + "endColumn": 123, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 145, + "column": 50, + "endLine": 145, + "endColumn": 51, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 152, + "column": 5, + "endLine": 152, + "endColumn": 7, + "problem": "LimitedReturnTypeInference", + "suggest": "", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "severity": "ERROR" + }, + { + "line": 152, + "column": 9, + "endLine": 152, + "endColumn": 12, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 197, + "column": 1, + "endLine": 197, + "endColumn": 40, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 199, + "column": 5, + "endLine": 199, + "endColumn": 34, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + } + ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/numeric_semantics.ets.migrate.ets b/ets2panda/linter/test/main/numeric_semantics.ets.migrate.ets new file mode 100644 index 0000000000..9afe1bb1ba --- /dev/null +++ b/ets2panda/linter/test/main/numeric_semantics.ets.migrate.ets @@ -0,0 +1,211 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// TypeScript: treats 'n' as having type number +// ArkTS: treats 'n' as having type int to reach max code performance + +import { Entry, Component, State, RelativeContainer, Text, AppStorage } from '@kit.ArkUI'; + +let a: number = 1; + +a = 1; // OK +a = 1.5; // CTE in ArkTS: Type 'double' can't be assigned to type 'int' + +a += 1; // OK +a += 1.5; // ArkTS: Result is integer value + +console.log(a + 1); // OK +console.log(a - 0.5); // OK +console.log(a / 2); // ArkTS: integer division is used, result is integer value +console.log(a / 2.5); // OK +console.log(2 / a); // ArkTS: integer division is used, result is integer value +console.log(2.5 / a); // OK + +let b: number = 1; +a = b; // CTE in ArkTS: Type 'double' can't be assigned to type 'int' +a += b; // ArkTS: Result is integer value +console.log(a + b); // OK +console.log(a / b); // OK + +let c: number = 1.5; +a = c; // CTE in ArkTS: Type 'double' can't be assigned to type 'int' +a += c; // ArkTS: Result is integer value +console.log(a + c); // OK +console.log(a / c); // OK + +let d: number = 2; +a = d; // OK +a += d; // OK +console.log(a + d); // OK +console.log(a / d); // ArkTS: integer division is used, result is integer value + +let n: number = 2; + +let f: number = 1 + +let g: number[] = [1, 2, 3] + +let x!: number + +let t8: number = Infinity + +let t9: number = -Infinity; + +let t10: number = NaN; + +let t11: number = Number.MAX_VALUE; + +let t12: number = Number.MIN_VALUE; + +let o:number = 123; + +const oo:number = 123; + +let o2: number = o; + +let o3: number = oo; + +class A{ + a: number = 1; + constructor() { + } +} + +let t2: number = +123; + +let t3: number = -234; + +let num: number = Math.floor(4.8); // num 可能是 int + +let value: number = parseInt("42"); // value 可能是 int + + +function multiply(x: number = 2, y: number = 3): number { + return x * y; +} + +function divide(x: number, y: number): number { + return x / y; +} + +function identity(value: T): T { + return value; +} +identity(42); + +let an_array: number[] = [1, 2, 3] + +let g: number = an_array[] + +const a: number = 1 + +enum Test { + A = 1, // 显式赋值为 1 + B = 2 // 显式赋值为 2 +} +const test: number = Test.A; + +@Entry +@Component +struct Index2 { + @State message: string = 'Hello World'; + readonly c1: number = 1; // int + readonly c4: number = 1.7; // float + readonly c5: number = 0x123; // 16进制 + readonly c6: number = 0o123; //8进制 + readonly c7: number = 0b101; //2进制 + readonly c8: number[] = [1, 2, 3]; + +build() { + RelativeContainer() { + Text(this.message) + .onClick(() => { + }) + } + } +} + +const c1: number = 1; + +export class G{ + readonly a5: number = 4; +} + +const fingerprintPositionY: number = AppStorage.get(FingerprintConstants.COORDINATE_Y_OF_FINGERPRINT_UD_SCREEN_IN_PX) ?? 0; + +private doCloseFolderBackgroundAnimation(): (() => { + ({ + openFolderLayout: openFolderLayout, : .getGridSwiperLayout().bgHeight = openFolderLayout.getBackgroundLayout().closedHeight, + openFolderLayout: openFolderLayout, : .getGridSwiperLayout().bgWidth = openFolderLayout.getBackgroundLayout().closedWidth, + let: let, pos: pos, + pos: pos, + let: let, editModeTranslateY: editModeTranslateY, + if(pos) { }, : .length > 1 + }); + return undefined; +})() { + let translateXForScreenSplit: number = AppStorage.get('translateXForScreenSplit') ?? 0 as number; + let screenWidth: number = AppStorage.get('screenWidth') as number; + let screenHeight: number = AppStorage.get('screenHeight') as number; + if (screenWidth > screenHeight) { + log.showInfo('doCloseFolderBackgroundAnimation screenWidth: ' + screenWidth + ', height: ' + screenHeight); + screenWidth = screenHeight; + } + openFolderLayout.getGridSwiperLayout().bgTranslateX = pos[0] - screenWidth / 2 + translateXForScreenSplit; + openFolderLayout.getGridSwiperLayout().bgTranslateY = pos[1] + editModeTranslateY - + openFolderLayout.getBackgroundLayout().closedHeight * 0.5 - openFolderLayout.getBackgroundLayout().openedMargin; + } +} + +let f: number = 0.0; +let b5: number = 0; +f = b5; // OK + +let e: number = 0.0; +let g1: number = 0; + +e += g1; // OK +e -= g1; // OK +e *= g1; // OK +e /= g1; // OK +e <<= g1; // OK +e >>= g1; // OK +e &= g1; // OK +e = e & 3; // OK +e = e | 3; // OK +let arr1: number[] = [1, 2, 3] +e += arr1[0]; // OK + +let a: number = 0.0; +a = fun1(); +a = fun2()!; + +function fun1():number{ + return 1; +} + +function fun2():number|undefined{ + return 1; +} + +import { ArrayList } from "@kit.ArkTS"; + +let arr = new ArrayList() +for (let i:number = 0; i < 100; i++) { + arr.add(i) +} +let cancelIds:ArrayList = arr.subArrayList(6, 86) +let a: Array = Array.from(cancelIds) +let arr1: Array = Array.from(new ArrayList()) \ No newline at end of file diff --git a/ets2panda/linter/test/main/numeric_semantics.ets.migrate.json b/ets2panda/linter/test/main/numeric_semantics.ets.migrate.json new file mode 100644 index 0000000000..c86c2373e1 --- /dev/null +++ b/ets2panda/linter/test/main/numeric_semantics.ets.migrate.json @@ -0,0 +1,118 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 60, + "column": 5, + "endLine": 60, + "endColumn": 15, + "problem": "DefiniteAssignmentError", + "suggest": "", + "rule": "Definite assignment assertions are not supported (arkts-no-definite-assignment)", + "severity": "ERROR" + }, + { + "line": 110, + "column": 26, + "endLine": 110, + "endColumn": 26, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 149, + "column": 6, + "endLine": 149, + "endColumn": 7, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 155, + "column": 9, + "endLine": 155, + "endColumn": 20, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 155, + "column": 9, + "endLine": 155, + "endColumn": 11, + "problem": "InvalidIdentifier", + "suggest": "", + "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", + "severity": "ERROR" + }, + { + "line": 155, + "column": 12, + "endLine": 155, + "endColumn": 15, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 203, + "column": 1, + "endLine": 203, + "endColumn": 40, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 205, + "column": 5, + "endLine": 205, + "endColumn": 34, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 205, + "column": 15, + "endLine": 205, + "endColumn": 24, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 211, + "column": 42, + "endLine": 211, + "endColumn": 51, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/object_literals.ets.args.json b/ets2panda/linter/test/main/object_literals.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/main/object_literals.ets.args.json +++ b/ets2panda/linter/test/main/object_literals.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/main/object_literals.ets.migrate.ets b/ets2panda/linter/test/main/object_literals.ets.migrate.ets new file mode 100644 index 0000000000..7ae3763807 --- /dev/null +++ b/ets2panda/linter/test/main/object_literals.ets.migrate.ets @@ -0,0 +1,293 @@ +/* + * Copyright (c) 2023-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import {ohFunction1, ohFunction2, OhosI} from './oh_modules/ohos_lib' +interface I { + a: number; + b: string; +} + +class C { + a: number; + b: string; +} + +interface GeneratedTypeLiteralInterface_1 { + x: number; + y: string; +} +class C2 { + q: GeneratedTypeLiteralInterface_1; + w: any; + e: I; + r: C; +} + +interface GeneratedObjectLiteralInterface_1 { + a: number; + b: string; +} +interface GeneratedTypeLiteralInterface_2 { + a: number; + b: string; +} +function localVariable(): void { + // Declaration + let a1: GeneratedObjectLiteralInterface_1 = { a: 1, b: 'a' }; // NOT OK + let a2: any = { a: 2, b: 'b' }; // OK - ASSIGNMENT TO ANY + let a3: GeneratedTypeLiteralInterface_2 = { a: 30, b: 'c' }; // NOT OK + let a4: I = { a: 4, b: 'd' }; // OK + let a5: C = { a: 5, b: 'e' }; // OK + let a6: C2 = { + // OK + q: { x: 6, y: 'f' }, // NOT OK + w: { a: 7, b: 'g' }, // OK - ASSIGNMENT TO ANY + e: { a: 8, b: 'h' }, // OK + r: { a: 9, b: 'i' }, // OK + }; + + // Assignment + a1 = { a: 11, b: 'a' }; // NOT OK + a2 = { a: 12, b: 'b' }; // OK - ASSIGNMENT TO ANY + a3 = { a: 13, b: 'c' }; // NOT OK + a4 = { a: 14, b: 'd' }; // OK + a5 = { a: 15, b: 'e' }; // OK + a6 = { + // OK + q: { x: 16, y: 'f' }, // NOT OK + w: { a: 17, b: 'g' }, // OK - ASSIGNMENT TO ANY + e: { a: 18, b: 'h' }, // OK + r: { a: 19, b: 'i' }, // OK + }; +} + +interface GeneratedObjectLiteralInterface_2 { + a: number; + b: string; +} +interface GeneratedTypeLiteralInterface_3 { + a: number; + b: string; +} +function defaultParamValue(): void { + function foo(x: GeneratedObjectLiteralInterface_2 = { a: 21, b: 'a' }) { + console.log(x.a, x.b); + } // NOT OK + function foo2(x: any = { a: 22, b: 'b' }) { + console.log(x.a, x.b); + } // NOT OK + function foo3(x: GeneratedTypeLiteralInterface_3 = { a: 23, b: 'c' }) { + console.log(x.a, x.b); + } // NOT OK + function foo4(x: I = { a: 24, b: 'd' }) { + console.log(x.a, x.b); + } // OK + function foo5(x: C = { a: 25, b: 'e' }) { + console.log(x.a, x.b); + } // OK + + // Function call + foo({ a: 21, b: 'a' }); // NOT OK + foo2({ a: 22, b: 'b' }); // OK - ASSIGNMENT TO ANY + foo3({ a: 23, b: 'c' }); // NOT OK + foo4({ a: 24, b: 'd' }); // OK + foo5({ a: 25, b: 'e' }); // OK +} + +interface GeneratedObjectLiteralInterface_3 { + a: number; + b: string; +} +interface GeneratedTypeLiteralInterface_4 { + a: number; + b: string; +} +interface GeneratedTypeLiteralInterface_5 { + a: number; + b: string; +} +function returnFromFunction(): void { + function bar() { + return ({ a: 31, b: 'a' } as GeneratedObjectLiteralInterface_3); + } // NOT OK + let bar2: () => any = (): any => { + return { a: 32, b: 'b' }; +}; // OK - ASSIGNMENT TO ANY + let bar3: () => GeneratedTypeLiteralInterface_4 = (): GeneratedTypeLiteralInterface_5 => { + return { a: 33, b: 'c' }; +}; // NOT OK + let bar4: () => I = (): I => { + return { a: 34, b: 'd' }; +}; // OK + let bar5: () => C = (): C => { + return { a: 35, b: 'e' }; +}; // OK +} + +interface GeneratedObjectLiteralInterface_4 { + a: number; + b: string; +} +interface GeneratedObjectLiteralInterface_5 { + a: number; + b: string; +} +interface GeneratedTypeLiteralInterface_6 { + a: number; + b: string; +} +function ternaryOperator(): void { + // In ternary operator + const condition = true; + const a1 = condition ? ({ a: 41, b: 'a' } as GeneratedObjectLiteralInterface_4) : ({ a: 42, b: 'b' } as GeneratedObjectLiteralInterface_5); // NOT OK + const a2: any = condition ? { a: 43, b: 'c' } : { a: 44, b: 'd' }; // OK - ASSIGNMENT TO ANY + const a3: GeneratedTypeLiteralInterface_6 = condition + ? { a: 45, b: 'e' } + : { a: 46, b: 'f' }; // NOT OK + const a4: I = condition ? { a: 47, b: 'g' } : { a: 48, b: 'h' }; // OK + const a5: C = condition ? { a: 49, b: 'i' } : { a: 50, b: 'j' }; // OK +} + +interface GeneratedObjectLiteralInterface_6 { + a: number; + b: string; +} +interface GeneratedObjectLiteralInterface_7 { + a: number; + b: string; +} +interface GeneratedTypeLiteralInterface_7 { + a: number; + b: string; +} +function arrayLiteral(): void { + const arr1 = [ + ({ a: 51, b: 'a' } as GeneratedObjectLiteralInterface_6), + ({ a: 52, b: 'b' } as GeneratedObjectLiteralInterface_7), + ]; // NOT OK + const arr2: any[] = [ + { a: 53, b: 'c' }, + { a: 54, b: 'd' }, + ]; // OK - ASSIGNMENT TO ANY + const arr3: GeneratedTypeLiteralInterface_7[] = [ + { a: 55, b: 'e' }, + { a: 56, b: 'f' }, + ]; // NOT OK + const arr4: I[] = [ + { a: 57, b: 'g' }, + { a: 58, b: 'h' }, + ]; // OK + const arr5: C[] = [ + { a: 59, b: 'i' }, + { a: 60, b: 'j' }, + ]; // OK +} + +enum E { + OK, + NO_OK, +} +interface I1 { + v: E | number +} + +interface I2 { + v: E +} + +let i1: I1 = {v:E.OK} +let i2: I2 = {v:E.NO_OK} + +function g1(a: E) { + let ii1: I1 = {v:a} + let ii2: I2 = {v:a} +} + +function g(): boolean { + return true; +} +interface CondI { + a: number; +} +let a1: CondI = { + a: g() ? 0 : 1, +}; +let b1: CondI = { + a: (g() ? 0 : 1) as number, +}; +let c1 = g() ? 0 : 1; +let d1: CondI = { + a: c1, +}; +let e1: CondI = { +a: 0|1|2|3 +} +let f1: 0|1|2|3 = 3 +let ff : CondI = { + a: f1 +} + +let dict = new Map(); +dict.set('1', 123) + +interface III { + param?: string | number | boolean +} + +let test1: III = { param: dict.get('1') } as III +let test2: III = { param: dict.get('1')! } as III +let test3: III = { param: dict.get('1') as number } as III +let test4: III = { param: dict.get('1') as (number | string) } as III +export interface Style { +} +export class SwitchMenuStyle implements Style { +} +export class ProfileOneLineSwitchMenuStyle extends SwitchMenuStyle { +} +export class ProfileSwitchMenuStyle extends SwitchMenuStyle { +} +export let hfpProfileSwitchMenuStyle = new ProfileSwitchMenuStyle(); +export let hfpProfileOneLineSwitchMenuStyle = new ProfileOneLineSwitchMenuStyle(); + +export interface SettingsBaseMenuData { + style?: Style; +} + +function test(isDisConnected:boolean){ + let a={style: isDisConnected ? hfpProfileOneLineSwitchMenuStyle: hfpProfileSwitchMenuStyle} as SettingsBaseMenuData +} + +interface PPP { + x: number + y: number | undefined + z?: number +} + +let p1: PPP = {x: 10, y: 10} +let p2: PPP = {x: 10, y: undefined} +let p3: PPP = {x: 10, y: undefined, z: undefined} +let p4: PPP = {x: 10, y: undefined, z: 10} +let p5: PPP = {x: 10, y: 10, z: 10} +const cp1: PPP = {x: 10, y: 10} +const cp2: PPP = {x: 10, y: undefined} +const cp3: PPP = {x: 10, y: undefined, z: undefined} +const cp4: PPP = {x: 10, y: undefined, z: 10} +const cp5: PPP = {x: 10, y: 10, z: 10} + +const oi: OhosI = { f: 1 }; + +ohFunction1({d: oi}) +ohFunction1({d: {f: 1}}) +ohFunction2({d: oi}) +ohFunction2({d: {f: 1}}) diff --git a/ets2panda/linter/test/main/object_literals.ets.migrate.json b/ets2panda/linter/test/main/object_literals.ets.migrate.json new file mode 100644 index 0000000000..a227223d64 --- /dev/null +++ b/ets2panda/linter/test/main/object_literals.ets.migrate.json @@ -0,0 +1,198 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 32, + "column": 6, + "endLine": 32, + "endColumn": 9, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 48, + "column": 11, + "endLine": 48, + "endColumn": 14, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 84, + "column": 3, + "endLine": 84, + "endColumn": 11, + "problem": "LocalFunction", + "suggest": "", + "rule": "Nested functions are not supported (arkts-no-nested-funcs)", + "severity": "ERROR" + }, + { + "line": 87, + "column": 3, + "endLine": 87, + "endColumn": 11, + "problem": "LocalFunction", + "suggest": "", + "rule": "Nested functions are not supported (arkts-no-nested-funcs)", + "severity": "ERROR" + }, + { + "line": 87, + "column": 20, + "endLine": 87, + "endColumn": 23, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 90, + "column": 3, + "endLine": 90, + "endColumn": 11, + "problem": "LocalFunction", + "suggest": "", + "rule": "Nested functions are not supported (arkts-no-nested-funcs)", + "severity": "ERROR" + }, + { + "line": 93, + "column": 3, + "endLine": 93, + "endColumn": 11, + "problem": "LocalFunction", + "suggest": "", + "rule": "Nested functions are not supported (arkts-no-nested-funcs)", + "severity": "ERROR" + }, + { + "line": 96, + "column": 3, + "endLine": 96, + "endColumn": 11, + "problem": "LocalFunction", + "suggest": "", + "rule": "Nested functions are not supported (arkts-no-nested-funcs)", + "severity": "ERROR" + }, + { + "line": 121, + "column": 3, + "endLine": 121, + "endColumn": 11, + "problem": "LocalFunction", + "suggest": "", + "rule": "Nested functions are not supported (arkts-no-nested-funcs)", + "severity": "ERROR" + }, + { + "line": 124, + "column": 19, + "endLine": 124, + "endColumn": 22, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 124, + "column": 29, + "endLine": 124, + "endColumn": 32, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 154, + "column": 13, + "endLine": 154, + "endColumn": 16, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 179, + "column": 15, + "endLine": 179, + "endColumn": 18, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 3, + "endLine": 22, + "endColumn": 4, + "problem": "StrictDiagnostic", + "suggest": "Property 'a' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'a' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 23, + "column": 3, + "endLine": 23, + "endColumn": 4, + "problem": "StrictDiagnostic", + "suggest": "Property 'b' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'b' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 31, + "column": 3, + "endLine": 31, + "endColumn": 4, + "problem": "StrictDiagnostic", + "suggest": "Property 'q' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'q' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 33, + "column": 3, + "endLine": 33, + "endColumn": 4, + "problem": "StrictDiagnostic", + "suggest": "Property 'e' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'e' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 34, + "column": 3, + "endLine": 34, + "endColumn": 4, + "problem": "StrictDiagnostic", + "suggest": "Property 'r' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'r' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/object_literals_2.ets.args.json b/ets2panda/linter/test/main/object_literals_2.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/main/object_literals_2.ets.args.json +++ b/ets2panda/linter/test/main/object_literals_2.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/main/object_literals_2.ets.migrate.ets b/ets2panda/linter/test/main/object_literals_2.ets.migrate.ets new file mode 100644 index 0000000000..1b08cb786e --- /dev/null +++ b/ets2panda/linter/test/main/object_literals_2.ets.migrate.ets @@ -0,0 +1,289 @@ +/* + * Copyright (c) 2023-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +interface GeneratedObjectLiteralInterface_1 { + n: number; + s: string; +} +let obj: GeneratedObjectLiteralInterface_1 = {n: 42, s: 'foo'} // OK in TypeScript, CTE in ArkTS: unknown type of obj. + +class C { + n: number = 0; + s: string = ""; +} + +let c1: C = {n: 42, s: 'foo'} // Declaration + initialization: type of the literla is inferred from the type of c1. + +let c2: C; +c2 = {n: 42, s: 'foo'}; // Initialization after declaration: type of the literal is inferred from the type of c2. + +let c3: Object = {n: 42, s: 'foo'} as C as Object; // Type of the literal is inferred from the 'as' cast. +console.log(c3 instanceof C); // NB! Output is true in ArkTS, but is false in TS. + +function foo(c: C) { + console.log('foo is called'); +} + +foo({n: 42, s: 'foo'}); // Parsing as an argument: type of the literal is inferred from the type of parameter 'c' + +function bar(): C { + return {n: 42, s: 'foo'}; // Returning from function: type of the literal is inferred from the bar's return type. +} + +let cc: C[] = [{n: 1, s: '1'}, {n: 2, s: '2'}]; // Type of the literal is inferred from the type of the array. + +class D { + b: boolean = false; + c: C = {n: 0, s: ""}; +} + +let d: D = { + b: true, + c: { // Initialization of a field with a literal: type of the literal is inferred from the definition of class D. + n: 42, + s: 'foo' + } +} + +// Restrictions of classes that can be initialized with literal +// Default initializable class. +class C1 { + n: number = 0; + s?: string; +} + +let c4: C1 = {n: 42}; // OK in TS, OK in ArkTS, c.s is null + +class C2 { + s: string; + constructor(s: string) { + this.s = "s = " + s; + } +} + +let c5: C2 = {s: 'foo'} // OK in TS, CTE in ArkTS + +// All class fields are accessible at the point of initialization. +class C3 { + private n: number = 0; + public s: string = ''; +} + +// CTE in TypeScript, CTE in ArkTS // let c6: C3 = {n: 42, s: 'foo'}, + +class C4 { + readonly n: number = 0; + readonly s: string = ''; +} + +let c7: C4 = {n: 42, s: 'foo'}; // OK in TS, CTE in ArkTS + +// Class is non-abstract +abstract class A {} +let a: A = {}; // OK in TS, CTE in ArkTS + +// Class declares no methods, apart from optionally declared constructors and setters. +class C5 { + n: number = 0; + s: string = ''; + f() { + console.log('C5.f is called'); + } +} + +let c8: C5 = {n: 42, s: 'foo', f: () => {}} // OK in TS, CTE in ArkTS + +// NB! If a class has getters/setters the semantics of initialization differs: +class C6 { + n: number = 0; + _s: string = ''; + get s(): string { return this._s; } + set s(s: string) { this._s = s; } +} + +let c9: C6 = {n: 42, _s: 'foo', s: 'bar'} +console.log(c9.s); // TS: 'bar', ArkTS: 'bar' +console.log(c9._s); // TS: 'foo', ArkTS: 'bar' + +// Extra fields are not allowed (eventually it means that it's not possible to assign literals to Object / object): +class C7 { + n: number = 0; + s: string = ''; +} +// TS: CTE, ArtTS: CTE // let c10: C7 = {n: 42, s: '', extra: true}, +let o1: Object = {s: '', n: 42} // OK in TS, CTE in ArkTS: no fields 'n' and 's' in Object +let o2: object = {n: 42, s: ''} // OK in TS, CTE in ArkTS: no fields 'n' and 's' in object + +// If initialized class is inherited from another class, the base class must also be literal-initializable, +// and initialization should happen from the 'glattened' literal: +class Base { + n: number = 0; +} + +class Derived extends Base { + s: string = ''; +} + +let d2: Derived = {n: 42, s: ''}; + +// Interface should not declare methods, only properties are allowed. +interface I { + n: number; + s: string; + f(): void; +} + +let i: I = {n: 42, s: '', f: () => {console.log('I.f is called')}} // OK in TypeScript, CTE in ArkTS + +// Interface properties of reference types must be default-initializable: +interface I2 { + n: number; + s: string; // Assuming that 'string' is an alias for 'String', and there is String() constructor (what is true). +} + +let i2: I2 = {n: 42, s: ''}; + +interface CompilerOptions { + strict?: boolean; + sourcePath?: string; + targetPath?: string; +} + +const options: CompilerOptions = { // OK, as 'targetPath' field is optional + strict: true, + sourcePath: './src', +}; + +// Function parameter with union type. +function funcWithUnionParam(x: C | number): void { } +funcWithUnionParam({ n: 1, s: '2' }) // OK, union type is supported + +// issue 13022: property with union type +class UnionProperty { + a: number | string = 123; + b?: boolean | number; +} +let u: UnionProperty = { a: 1 }; // OK, union type is supported +u = { a: '2' }; // OK, union type is supported +u = { a: 3, b: true }; // OK, union type is supported + +// issue 13022: optional property +class OptionalProp { + a?: number; +} +let o: OptionalProp = {}; +o = {a: 1}; // OK + +class OptionalProp2 { + a?: number; + b: string; +} +function optProp(a: OptionalProp2) {} +optProp({b: ''}); // OK +optProp({a: 0, b: '1'}); // OK + +// Property with inheritance +class E1 { + x: number; + y: Base; +} +let e1 : E1 = { + x: 1, + y: new Derived() +} + +// Property with inheritance through generic type parameter +class E2 { + x: number; + y: T; +} +let e2 : E2 = { + x: 1, + y: new Derived() +} + +// Type alias chain to interface +interface ITypeAlias { a: number; b: T } +type ITA = ITypeAlias; +type ITA2 = ITA; +let ti: ITA2 = { // OK, 'ITA2' is an alias to interface 'ITypeAlias' + a: 12, + b: '34' +} + +// Type alias chain to class +class CTypeAlias { + a: number; + b: T; +} +type CTA = CTypeAlias; +type CTA2 = CTA; +let tc: CTA2 = { // OK, 'CTA' is an alias to class 'CTypeAlias' + a: 4, + b: '4' +} + +// issue 13114: Const enum value converted to string/number type. +const enum ATTRIBUTE { + ROW = 'Row', + COLUMN = 'Column', + COLUMN_REVERSE = 'ColumnReverse', +}; +const enum GROUP { + MAIN_DIRECTION = 'MAIN_DIRECTION', +}; +enum Orientation { + Horizontal, + Vertical +} +class ContainerModuleItem { + groupName: string = ''; + attributeList: string[] = []; + attribute: ATTRIBUTE = ATTRIBUTE.COLUMN; + orientation: number = 0; +} +const FLEX_MODULE: ContainerModuleItem[] = [ + { + groupName: GROUP.MAIN_DIRECTION, + attributeList: [ATTRIBUTE.COLUMN, ATTRIBUTE.ROW, ATTRIBUTE.COLUMN_REVERSE], + attribute: ATTRIBUTE.ROW, + orientation: Orientation.Horizontal + } +]; + +interface I3 {} + +class CCl implements I3 {} + +class CCl2 extends CCl implements I3 {} + +interface I4 { + a: I3; + b: I3; + c: CCl; + d: CCl2; +} + +class DCl { + constructor(a: I4) {} +} + +let c: I4 = {a: new CCl(), b: new CCl2(), c: new CCl2(), d: new CCl2()} + +new DCl({a: new CCl(), b: new CCl2(), c: new CCl2(), d: new CCl2()}) + +let oo1: Object = {} + +let oo2: Object = {a: 12} diff --git a/ets2panda/linter/test/main/object_literals_2.ets.migrate.json b/ets2panda/linter/test/main/object_literals_2.ets.migrate.json new file mode 100644 index 0000000000..9d29201f6c --- /dev/null +++ b/ets2panda/linter/test/main/object_literals_2.ets.migrate.json @@ -0,0 +1,178 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 76, + "column": 14, + "endLine": 76, + "endColumn": 15, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 91, + "column": 14, + "endLine": 91, + "endColumn": 15, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 95, + "column": 12, + "endLine": 95, + "endColumn": 13, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 106, + "column": 14, + "endLine": 106, + "endColumn": 15, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 126, + "column": 18, + "endLine": 126, + "endColumn": 19, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 127, + "column": 18, + "endLine": 127, + "endColumn": 19, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 148, + "column": 12, + "endLine": 148, + "endColumn": 13, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 287, + "column": 19, + "endLine": 287, + "endColumn": 20, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 289, + "column": 19, + "endLine": 289, + "endColumn": 20, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 191, + "column": 5, + "endLine": 191, + "endColumn": 6, + "problem": "StrictDiagnostic", + "suggest": "Property 'b' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'b' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 199, + "column": 3, + "endLine": 199, + "endColumn": 4, + "problem": "StrictDiagnostic", + "suggest": "Property 'x' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'x' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 200, + "column": 3, + "endLine": 200, + "endColumn": 4, + "problem": "StrictDiagnostic", + "suggest": "Property 'y' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'y' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 209, + "column": 3, + "endLine": 209, + "endColumn": 4, + "problem": "StrictDiagnostic", + "suggest": "Property 'x' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'x' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 210, + "column": 3, + "endLine": 210, + "endColumn": 4, + "problem": "StrictDiagnostic", + "suggest": "Property 'y' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'y' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 228, + "column": 5, + "endLine": 228, + "endColumn": 6, + "problem": "StrictDiagnostic", + "suggest": "Property 'a' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'a' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 229, + "column": 5, + "endLine": 229, + "endColumn": 6, + "problem": "StrictDiagnostic", + "suggest": "Property 'b' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'b' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/object_literals_3.ets.args.json b/ets2panda/linter/test/main/object_literals_3.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/main/object_literals_3.ets.args.json +++ b/ets2panda/linter/test/main/object_literals_3.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/main/object_literals_3.ets.migrate.ets b/ets2panda/linter/test/main/object_literals_3.ets.migrate.ets new file mode 100644 index 0000000000..bce9e88fa1 --- /dev/null +++ b/ets2panda/linter/test/main/object_literals_3.ets.migrate.ets @@ -0,0 +1,277 @@ +/* + * Copyright (c) 2023-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +interface GeneratedObjectLiteralInterface_1 { +} +const test1: GeneratedObjectLiteralInterface_1 = {} + +interface GeneratedObjectLiteralInterface_2 { + hello: string; +} +const test2: GeneratedObjectLiteralInterface_2 = { hello: "world" }; + +interface GeneratedTypeLiteralInterface_1 { +} +let test3:GeneratedTypeLiteralInterface_1 = {}; + +interface GeneratedObjectLiteralInterface_3 { + field: string; + field1: string; + field2: string; + field3: string; + field4: string; + field5: string; + field6: string; +} +const test4: GeneratedObjectLiteralInterface_3 = { + field: "world", + field1: "hello2", + field2: "hello3", + field3: "hello4", + field4: "hello5", + field5: "hello6", + field6: "hello7", + }; + +interface GeneratedObjectLiteralInterface_4 { + field: number; + field1: number; + field2: number; + field3: number; + field4: number; + field5: number; + field6: number; +} +const test5: GeneratedObjectLiteralInterface_4 = { + field: 1, + field1: 2, + field2: 3, + field3: 4, + field4: 5, + field5: 6, + field6: 7, + }; + +interface GeneratedObjectLiteralInterface_5 { + field: string; + field1: number; + field2: string; + field3: number; + field4: string; + field5: number; + field6: string; + field7: boolean; + field8: boolean; +} +const test6: GeneratedObjectLiteralInterface_5 = { + field: "world", + field1: 2, + field2: "hello3", + field3: 4, + field4: "hello5", + field5: 6, + field6: "hello7", + field7: true, + field8: false + }; + +interface test7 { + field: "world", + field1: "hello2", + field2: "hello3", + field3: "hello4", + field4: "hello5", + field5: "hello6", + field6: "hello7" + }; + +interface test8 { + field: 1, + field1: 2, + field2: 3, + field3: 4, + field4: 5, + field5: 6, + field6: 7, + }; + +interface test9 { + field: "world", + field1: 2, + field2: "hello3", + field3: 4, + field4: "hello5", + field5: 6, + field6: "hello7", + field7: true, + field8: false + }; + +const test10:object = { + field: "world", + field1: "hello2", + field2: "hello3", + field3: "hello4", + field4: "hello5", + field5: "hello6", + field6: "hello7", + }; + +const test11:object = { + field: 1, + field1: 2, + field2: 3, + field3: 4, + field4: 5, + field5: 6, + field6: 7, + }; + +const test12:object = { + field: "world", + field1: 2, + field2: "hello3", + field3: 4, + field4: "hello5", + field5: 6, + field6: "hello7", + field7: true, + field8: false + }; + +const test13:object = { + field: "world", + field1: "hello2", + field2: "hello3", + field3: "hello4", + field4: "hello5", + field5: "hello6", + field6: "hello7", + }; + +const test14:object = { + field: 1, + field1: 2, + field2: 3, + field3: 4, + field4: 5, + field5: 6, + field6: 7, + }; + +const test15:object = { + field: "world", + field1: 2, + field2: "hello3", + field3: 4, + field4: "hello5", + field5: 6, + field6: "hello7", + field7: true, + field8: false + }; + +interface GeneratedTypeLiteralInterface_2 { + field: String; + field1: String; + field2: String; + field3: String; + field4: String; + field5: String; + field6: String; +} +let test16:GeneratedTypeLiteralInterface_2 = { + field: "world", + field1: "hello2", + field2: "hello3", + field3: "hello4", + field4: "hello5", + field5: "hello6", + field6: "hello7", + }; + +interface GeneratedTypeLiteralInterface_3 { + field: number; + field1: number; + field2: number; + field3: number; + field4: number; + field5: number; + field6: number; +} +let test17:GeneratedTypeLiteralInterface_3 = { + field: 1, + field1: 2, + field2: 3, + field3: 4, + field4: 5, + field5: 6, + field6: 7, + }; + +interface GeneratedTypeLiteralInterface_4 { + field: String; + field1: number; + field2: String; + field3: number; + field4: String; + field5: number; + field6: String; + field7: boolean; + field8: boolean; +} +let test18:GeneratedTypeLiteralInterface_4 = { + field: "world", + field1: 2, + field2: "hello3", + field3: 4, + field4: "hello5", + field5: 6, + field6: "hello7", + field7: true, + field8: false + }; + +const test19:Record = { + "field": "world", + "field1": "hello2", + "field2": "hello3", + "field3": "hello4", + "field4": "hello5", + "field5": "hello6", + "field6": "hello7", + }; + +const test20:Record = { + "field": 1, + "field1": 2, + "field2": 3, + "field3": 4, + "field4": 5, + "field5": 6, + "field6": 7, + }; + +const test21:Record = { + "field": "world", + "field1": 2, + "field2": "hello3", + "field3": 4, + "field4": "hello5", + "field5": 6, + "field6": "hello7", + "field7": true, + "field8": false + }; \ No newline at end of file diff --git a/ets2panda/linter/test/main/object_literals_3.ets.migrate.json b/ets2panda/linter/test/main/object_literals_3.ets.migrate.json new file mode 100644 index 0000000000..69a3046345 --- /dev/null +++ b/ets2panda/linter/test/main/object_literals_3.ets.migrate.json @@ -0,0 +1,78 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 122, + "column": 23, + "endLine": 122, + "endColumn": 24, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 132, + "column": 23, + "endLine": 132, + "endColumn": 24, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 142, + "column": 23, + "endLine": 142, + "endColumn": 24, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 154, + "column": 23, + "endLine": 154, + "endColumn": 24, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 164, + "column": 23, + "endLine": 164, + "endColumn": 24, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 174, + "column": 23, + "endLine": 174, + "endColumn": 24, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/object_literals_4.ets.args.json b/ets2panda/linter/test/main/object_literals_4.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/main/object_literals_4.ets.args.json +++ b/ets2panda/linter/test/main/object_literals_4.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/main/object_literals_4.ets.migrate.ets b/ets2panda/linter/test/main/object_literals_4.ets.migrate.ets new file mode 100644 index 0000000000..19e21b00c1 --- /dev/null +++ b/ets2panda/linter/test/main/object_literals_4.ets.migrate.ets @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2023-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +type T = () => void + +class A { + foo?: T + bar?: Function +} + +let a: A = { + foo: () => { + console.log("Hello") + }, + bar: () => { + console.log("Hello") + } +} + +//====================== +class Resource{} + +class ContainerModuleItem { + groupName: string = ""; + moduleName: Resource | null = null; + atributeList: string[] = []; +} + +const FLEX_MODULE: ContainerModuleItem[] = [{ + groupName: GROUP.MAIN_DIRECTION, + moduleName: "ASF", + atributeList: [ATTRIBUTE.COLUMN, ATTRIBUTE.ROW, ATTRIBUTE.COLUMN_REVERSE], +}] + +const enum ATTRIBUTE { + ROW = 'Row', + COLUMN = 'Column', + COLUMN_REVERSE = 'ColumnReverse' +} + +const enum GROUP { + MAIN_DIRECTION = 'MAIN_DIRECTION' +} + +//==================================== + +class C { + s: string = "" + n: number = 0 + l: () => void = () => {} +} + +let c : C = { + s: "foo", + n: 42, + l: () => { + console.log("Hi") + } +} + +c.l() \ No newline at end of file diff --git a/ets2panda/linter/test/main/object_literals_4.ets.migrate.json b/ets2panda/linter/test/main/object_literals_4.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/object_literals_4.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/object_literals_autofixes.ets b/ets2panda/linter/test/main/object_literals_autofixes.ets index 87814c7da5..9bc2be4e2f 100644 --- a/ets2panda/linter/test/main/object_literals_autofixes.ets +++ b/ets2panda/linter/test/main/object_literals_autofixes.ets @@ -102,7 +102,7 @@ function bar(): void { let d = {g: 7, d: foo({q:1,w:2}.q + {q:3,w:4}.w)}; } -const o9 = { 1: '1', '2': 2 }; +const o9 = { 1: '1', '2': 2 }; // Not fixable, property name is string/numeric literal const o10 = { [3]: 3 }; // Not fixable, computed property value const o11 = { [o2.hello]: 'world' }; // Not fixable, computed property value @@ -110,9 +110,9 @@ const anyVal: any = 1; const o12 = { a: anyVal }; // Not fixable, type of property 'a' is not supported let val = 1; -const o13 = { val }; // Not fixable, property is not 'key:value' pair +const o13 = { val }; // Fixable const o14 = { ...o1 }; // Not fixable, property is not 'key:value' pair -const o15 = { m() {} }; // Not fixable, property is not 'key:value' pair +const o15 = { m() {} }; // Fixable const o16 = { // Not fixable, property 'c' is initialized with non-fixable nested object literal, and thus will always have unsupported type (object type literal) a: 1, diff --git a/ets2panda/linter/test/main/object_literals_autofixes.ets.args.json b/ets2panda/linter/test/main/object_literals_autofixes.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/main/object_literals_autofixes.ets.args.json +++ b/ets2panda/linter/test/main/object_literals_autofixes.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/main/object_literals_autofixes.ets.autofix.json b/ets2panda/linter/test/main/object_literals_autofixes.ets.autofix.json index e139fc2d4a..5f107cd9ac 100644 --- a/ets2panda/linter/test/main/object_literals_autofixes.ets.autofix.json +++ b/ets2panda/linter/test/main/object_literals_autofixes.ets.autofix.json @@ -738,18 +738,6 @@ "endLine": 105, "endColumn": 13, "problem": "ObjectLiteralNoContextType", - "autofix": [ - { - "start": 2600, - "end": 2600, - "replacementText": "interface GeneratedObjectLiteralInterface_37 {\n 1: string;\n '2': number;\n}\n" - }, - { - "start": 2608, - "end": 2608, - "replacementText": ": GeneratedObjectLiteralInterface_37" - } - ], "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" @@ -860,6 +848,18 @@ "endLine": 115, "endColumn": 14, "problem": "ObjectLiteralNoContextType", + "autofix": [ + { + "start": 3051, + "end": 3051, + "replacementText": "class GeneratedObjectLiteralClass_1 {\n m() { }\n}\n\n" + }, + { + "start": 3063, + "end": 3073, + "replacementText": "new GeneratedObjectLiteralClass_1()" + } + ], "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" @@ -922,8 +922,8 @@ "problem": "ObjectTypeLiteral", "autofix": [ { - "start": 3779, - "end": 3819, + "start": 3759, + "end": 3799, "replacementText": "interface LocalType {\n a: number;\n b: string;\n}" } ], @@ -999,18 +999,18 @@ "problem": "ObjectLiteralNoContextType", "autofix": [ { - "start": 4301, - "end": 4302, + "start": 4281, + "end": 4282, "replacementText": "\"a\"" }, { - "start": 4311, - "end": 4312, + "start": 4291, + "end": 4292, "replacementText": "\"b\"" }, { - "start": 4321, - "end": 4322, + "start": 4301, + "end": 4302, "replacementText": "\"c\"" } ], @@ -1036,18 +1036,18 @@ "problem": "ObjectLiteralNoContextType", "autofix": [ { - "start": 4376, - "end": 4379, + "start": 4356, + "end": 4359, "replacementText": "\"foo\"" }, { - "start": 4388, - "end": 4391, + "start": 4368, + "end": 4371, "replacementText": "\"bar\"" }, { - "start": 4430, - "end": 4433, + "start": 4410, + "end": 4413, "replacementText": "\"baz\"" } ], @@ -1103,13 +1103,13 @@ "problem": "ObjectLiteralNoContextType", "autofix": [ { - "start": 4721, - "end": 4724, + "start": 4701, + "end": 4704, "replacementText": "\"key\"" }, { - "start": 4739, - "end": 4746, + "start": 4719, + "end": 4726, "replacementText": "\"message\"" } ], diff --git a/ets2panda/linter/test/migrate/object_literals_autofixes.sts b/ets2panda/linter/test/main/object_literals_autofixes.ets.migrate.ets similarity index 40% rename from ets2panda/linter/test/migrate/object_literals_autofixes.sts rename to ets2panda/linter/test/main/object_literals_autofixes.ets.migrate.ets index 48d3fe6aa3..7022a9431a 100644 --- a/ets2panda/linter/test/migrate/object_literals_autofixes.sts +++ b/ets2panda/linter/test/main/object_literals_autofixes.ets.migrate.ets @@ -20,7 +20,7 @@ import { GeneratedObjectLiteralInterface_8, foo as GeneratedObjectLiteralInterface_9 } from 'x'; -interface GeneratedObjectLiteralInterface_11 {} +interface GeneratedObjectLiteralInterface_11 {} class GeneratedObjectLiteralInterface_12 {} function GeneratedObjectLiteralInterface_15() {} @@ -30,10 +30,27 @@ function foo(x): number { return 1; } -const o1 = {}; -const o2 = { hello: "world" }; -const o3! = {a: 1, b: 2}; -const o4 = { +interface GeneratedObjectLiteralInterface_1 { +} +const o1: GeneratedObjectLiteralInterface_1 = {}; +interface GeneratedObjectLiteralInterface_2 { + hello: string; +} +const o2: GeneratedObjectLiteralInterface_2 = { hello: "world" }; +interface GeneratedObjectLiteralInterface_3 { + a: number; + b: number; +} +const o3!: GeneratedObjectLiteralInterface_3 = {a: 1, b: 2}; +interface GeneratedObjectLiteralInterface_5 { + field: string; + field1: number; + field2: string; + field3: number; + field4: boolean; + field5: boolean; +} +const o4: GeneratedObjectLiteralInterface_5 = { field: "hello", field1: 2, field2: "world", @@ -43,66 +60,184 @@ const o4 = { }; // Properties with various types. Nested object literals -const o5 = { +interface GeneratedObjectLiteralInterface_6 { +} +interface GeneratedObjectLiteralInterface_10 { + a: number; + b: string; +} +interface GeneratedObjectLiteralInterface_13 { + q: number; + w: number; +} +interface GeneratedObjectLiteralInterface_25 { + a: number; + b: string; + c: boolean; + d: C; + e: GeneratedObjectLiteralInterface_6; + f: GeneratedObjectLiteralInterface_10; + g: GeneratedObjectLiteralInterface_13; +} +const o5: GeneratedObjectLiteralInterface_25 = { a: 1, b: '2', c: true, d: new C(), - e: {}, - f: { a: 1, b: '2' }, - g: { - q: 10, - w: 20 - }, + e: ({} as GeneratedObjectLiteralInterface_6), + f: ({ a: 1, b: '2' } as GeneratedObjectLiteralInterface_10), + g: ({ q: 10, + w: 20 } as GeneratedObjectLiteralInterface_13), }; -const o6 = { +interface GeneratedObjectLiteralInterface_14 { + q: number; + w: number; +} +interface GeneratedObjectLiteralInterface_16 { + q: number; + w: number; +} +interface GeneratedObjectLiteralInterface_21 { + a: number; + b: string; + c: GeneratedObjectLiteralInterface_14; + d: boolean; + e: GeneratedObjectLiteralInterface_16; +} +const o6: GeneratedObjectLiteralInterface_21 = { a: 1, b: '2', - c: { q: 10, w: 20 }, + c: ({ q: 10, w: 20 } as GeneratedObjectLiteralInterface_14), d: true, - e: { q: 30, w: 40 } + e: ({ q: 30, w: 40 } as GeneratedObjectLiteralInterface_16) }; // Object literals inside another expression -const o7 = { a:1, b:2 }.a + { a:3, b:4 }.b; -const o8 = { - a: 1, +interface GeneratedObjectLiteralInterface_17 { + a: number; + b: number; +} +interface GeneratedObjectLiteralInterface_18 { + a: number; + b: number; +} +const o7 = ({ a: 1, b: 2 } as GeneratedObjectLiteralInterface_17).a + ({ a: 3, b: 4 } as GeneratedObjectLiteralInterface_18).b; +interface GeneratedObjectLiteralInterface_19 { + x: number; + y: number; +} +interface GeneratedObjectLiteralInterface_20 { + a: number; + b: number; + c: GeneratedObjectLiteralInterface_19; + d: number; +} +interface GeneratedObjectLiteralInterface_23 { + q: number; + w: number; +} +interface GeneratedObjectLiteralInterface_27 { + q: number; + w: number; +} +const o8: GeneratedObjectLiteralInterface_20 = { + a: 1, b: 2, - c: ({x:1, y:2}), - d: foo({q:1, w:2}.q + {q:3, w:4}.w) + c: ({ x: 1, y: 2 } as GeneratedObjectLiteralInterface_19), + d: foo(({ q: 1, w: 2 } as GeneratedObjectLiteralInterface_23).q + ({ q: 3, w: 4 } as GeneratedObjectLiteralInterface_27).w) }; // Object literals inside class declaration +interface GeneratedObjectLiteralInterface_22 { + a: number; + b: number; +} +interface GeneratedObjectLiteralInterface_24 { + a: number; + b: number; +} +interface GeneratedObjectLiteralInterface_26 { + a: number; + b: number; +} +interface GeneratedObjectLiteralInterface_28 { + c: number; + d: number; +} +interface GeneratedObjectLiteralInterface_29 { + e: number; +} +interface GeneratedObjectLiteralInterface_32 { + f: number; + g: number; +} +interface GeneratedObjectLiteralInterface_34 { + a: number; + b: number; +} +interface GeneratedObjectLiteralInterface_36 { + c: number; + d: number; + e: number; +} class D { - f1 = {a: 1, b: 2}; - f2? = {a: 1, b: 2}; - f3! = {a: 1, b: 2}; - f4 = ({c: 3, d: 4}); - f5 = {e: 5}.e + {f: 6, g: 7}.f; + f1: GeneratedObjectLiteralInterface_22 = {a: 1, b: 2}; + f2?: GeneratedObjectLiteralInterface_24 = {a: 1, b: 2}; + f3!: GeneratedObjectLiteralInterface_26 = {a: 1, b: 2}; + f4 = ({ c: 3, d: 4 } as GeneratedObjectLiteralInterface_28); + f5 = ({ e: 5 } as GeneratedObjectLiteralInterface_29).e + ({ f: 6, g: 7 } as GeneratedObjectLiteralInterface_32).f; m() { - let x = {a:1, b:2}; - let y = {c:1, d:2, e:3}; + let x: GeneratedObjectLiteralInterface_34 = {a:1, b:2}; + let y: GeneratedObjectLiteralInterface_36 = {c:1, d:2, e:3}; } } // Object literals as function parameter initializer -function funInit(p = { a: 1, b: 2 }) {} +interface GeneratedObjectLiteralInterface_30 { + a: number; + b: number; +} +function funInit(p: GeneratedObjectLiteralInterface_30 = { a: 1, b: 2 }) {} function funInit2({a, b} = { a: 3, b: 4 }) {} // Not fixable, as in case of destructuring parameters, the contextual type of expression is implied by the binding pattern // Object literals inside function declaration +interface GeneratedObjectLiteralInterface_31 { + a: number; + b: number; +} +interface GeneratedObjectLiteralInterface_33 { + c: number; + d: number; +} +interface GeneratedObjectLiteralInterface_35 { + e: number; + f: number; +} +interface GeneratedObjectLiteralInterface_37 { + g: number; + d: number; +} +interface GeneratedObjectLiteralInterface_38 { + q: number; + w: number; +} +interface GeneratedObjectLiteralInterface_39 { + q: number; + w: number; +} function bar(): void { - let a = {a: 1, b: 2}; - let b = {c: 3, d: 4}; + let a: GeneratedObjectLiteralInterface_31 = {a: 1, b: 2}; + let b: GeneratedObjectLiteralInterface_33 = {c: 3, d: 4}; if (a.b > b.c) { - let c = {e: 5, f: 6}; + let c: GeneratedObjectLiteralInterface_35 = {e: 5, f: 6}; } - let d = {g: 7, d: foo({q:1,w:2}.q + {q:3,w:4}.w)}; + let d: GeneratedObjectLiteralInterface_37 = {g: 7, d: foo(({ q: 1, w: 2 } as GeneratedObjectLiteralInterface_38).q + ({ q: 3, w: 4 } as GeneratedObjectLiteralInterface_39).w)}; } -const o9 = { 1: '1', '2': 2 }; +const o9 = { 1: '1', '2': 2 }; // Not fixable, property name is string/numeric literal const o10 = { [3]: 3 }; // Not fixable, computed property value const o11 = { [o2.hello]: 'world' }; // Not fixable, computed property value @@ -110,9 +245,13 @@ const anyVal: any = 1; const o12 = { a: anyVal }; // Not fixable, type of property 'a' is not supported let val = 1; -const o13 = { val }; // Not fixable, property is not 'key:value' pair +const o13 = { val }; // Fixable const o14 = { ...o1 }; // Not fixable, property is not 'key:value' pair -const o15 = { m() {} }; // Not fixable, property is not 'key:value' pair +class GeneratedObjectLiteralClass_1 { + m() { } +} + +const o15 = new GeneratedObjectLiteralClass_1(); // Fixable const o16 = { // Not fixable, property 'c' is initialized with non-fixable nested object literal, and thus will always have unsupported type (object type literal) a: 1, @@ -130,30 +269,33 @@ function captureFromLocalScope(t: T): void { let v1 = {a: 1, b: '2', c: t}; // Not fixable, `c` references local type parameter `T` let v2 = {a: 1, b: '2', c: new X()}; // Not fixable, `c` references local type parameter `T` let v3 = {a: 1, b: '2', c: new Y>()}; // Not fixable, `c` references local type parameter `T` - - type LocalType = {a: number, b: string}; + + interface LocalType { + a: number; + b: string; +} let localTypeVar: LocalType = {a:1, b:'2'}; let v4 = { x: localTypeVar }; // Non-fixable, `x` references type `LocalType` declared in local scope - + class LocalClass {x: number = 1}; let v5 = { y: new LocalClass() }; // Non-fixable, `y` references type `LocalClass` declared in local scope - + let v6 = { z: LocalClass }; // Non-fixable, `z` references type `LocalClass` declared in local scope } // Record object literals let rec1: Record = { - a: 1, - b: 2, - c: 3 + "a": 1, + "b": 2, + "c": 3 } let rec2: Record = { - foo: 1, - bar: 2, + "foo": 1, + "bar": 2, 10: 'foo', 20: 'bar', - baz: 3, + "baz": 3, 'daz': 4 } @@ -169,7 +311,7 @@ interface NullableRecord { } let rec4: NullableRecord = { params: { - key: '1', - message: '2' + "key": '1', + "message": '2' } }; \ No newline at end of file diff --git a/ets2panda/linter/test/migrate/object_literals_autofixes.ts.json b/ets2panda/linter/test/main/object_literals_autofixes.ets.migrate.json similarity index 37% rename from ets2panda/linter/test/migrate/object_literals_autofixes.ts.json rename to ets2panda/linter/test/main/object_literals_autofixes.ets.migrate.json index ff838327c3..e69f8c2850 100644 --- a/ets2panda/linter/test/migrate/object_literals_autofixes.ts.json +++ b/ets2panda/linter/test/main/object_literals_autofixes.ets.migrate.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -25,289 +25,29 @@ "severity": "ERROR" }, { - "line": 33, - "column": 12, - "endLine": 33, - "endColumn": 13, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 34, - "column": 12, - "endLine": 34, - "endColumn": 13, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 35, + "line": 44, "column": 7, - "endLine": 35, - "endColumn": 25, + "endLine": 44, + "endColumn": 60, "problem": "DefiniteAssignment", "suggest": "", "rule": "Definite assignment assertions are not supported (arkts-no-definite-assignment)", "severity": "WARNING" }, { - "line": 35, - "column": 13, - "endLine": 35, - "endColumn": 14, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 36, - "column": 12, - "endLine": 36, - "endColumn": 13, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 46, - "column": 12, - "endLine": 46, - "endColumn": 13, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 51, - "column": 8, - "endLine": 51, - "endColumn": 9, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 52, - "column": 8, - "endLine": 52, - "endColumn": 9, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 53, - "column": 8, - "endLine": 53, - "endColumn": 9, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 58, - "column": 12, - "endLine": 58, - "endColumn": 13, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 61, - "column": 8, - "endLine": 61, - "endColumn": 9, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 63, - "column": 8, - "endLine": 63, - "endColumn": 9, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 67, - "column": 12, - "endLine": 67, - "endColumn": 13, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 67, - "column": 29, - "endLine": 67, - "endColumn": 30, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 68, - "column": 12, - "endLine": 68, - "endColumn": 13, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 71, - "column": 9, - "endLine": 71, - "endColumn": 10, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 72, - "column": 12, - "endLine": 72, - "endColumn": 13, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 72, - "column": 27, - "endLine": 72, - "endColumn": 28, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 77, - "column": 10, - "endLine": 77, - "endColumn": 11, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 78, - "column": 11, - "endLine": 78, - "endColumn": 12, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 79, + "line": 186, "column": 5, - "endLine": 79, - "endColumn": 24, + "endLine": 186, + "endColumn": 60, "problem": "DefiniteAssignment", "suggest": "", "rule": "Definite assignment assertions are not supported (arkts-no-definite-assignment)", "severity": "WARNING" }, { - "line": 79, - "column": 11, - "endLine": 79, - "endColumn": 12, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 80, - "column": 11, - "endLine": 80, - "endColumn": 12, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 81, - "column": 10, - "endLine": 81, - "endColumn": 11, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 81, - "column": 21, - "endLine": 81, - "endColumn": 22, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 84, - "column": 17, - "endLine": 84, - "endColumn": 18, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 85, - "column": 17, - "endLine": 85, - "endColumn": 18, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 90, - "column": 22, - "endLine": 90, - "endColumn": 23, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 91, + "line": 202, "column": 19, - "endLine": 91, + "endLine": 202, "endColumn": 42, "problem": "DestructuringParameter", "suggest": "", @@ -315,9 +55,9 @@ "severity": "ERROR" }, { - "line": 91, + "line": 202, "column": 28, - "endLine": 91, + "endLine": 202, "endColumn": 29, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -325,69 +65,9 @@ "severity": "ERROR" }, { - "line": 95, - "column": 13, - "endLine": 95, - "endColumn": 14, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 96, - "column": 13, - "endLine": 96, - "endColumn": 14, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 99, - "column": 17, - "endLine": 99, - "endColumn": 18, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 102, - "column": 13, - "endLine": 102, - "endColumn": 14, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 102, - "column": 27, - "endLine": 102, - "endColumn": 28, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 102, - "column": 41, - "endLine": 102, - "endColumn": 42, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 105, + "line": 240, "column": 12, - "endLine": 105, + "endLine": 240, "endColumn": 13, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -395,9 +75,9 @@ "severity": "ERROR" }, { - "line": 105, + "line": 240, "column": 14, - "endLine": 105, + "endLine": 240, "endColumn": 15, "problem": "LiteralAsPropertyName", "suggest": "", @@ -405,9 +85,9 @@ "severity": "ERROR" }, { - "line": 106, + "line": 241, "column": 13, - "endLine": 106, + "endLine": 241, "endColumn": 14, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -415,9 +95,9 @@ "severity": "ERROR" }, { - "line": 106, + "line": 241, "column": 15, - "endLine": 106, + "endLine": 241, "endColumn": 18, "problem": "ComputedPropertyName", "suggest": "", @@ -425,9 +105,9 @@ "severity": "ERROR" }, { - "line": 107, + "line": 242, "column": 13, - "endLine": 107, + "endLine": 242, "endColumn": 14, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -435,9 +115,9 @@ "severity": "ERROR" }, { - "line": 107, + "line": 242, "column": 15, - "endLine": 107, + "endLine": 242, "endColumn": 25, "problem": "ComputedPropertyName", "suggest": "", @@ -445,9 +125,9 @@ "severity": "ERROR" }, { - "line": 109, + "line": 244, "column": 15, - "endLine": 109, + "endLine": 244, "endColumn": 18, "problem": "AnyType", "suggest": "", @@ -455,9 +135,9 @@ "severity": "ERROR" }, { - "line": 110, + "line": 245, "column": 13, - "endLine": 110, + "endLine": 245, "endColumn": 14, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -465,9 +145,9 @@ "severity": "ERROR" }, { - "line": 113, + "line": 248, "column": 13, - "endLine": 113, + "endLine": 248, "endColumn": 14, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -475,9 +155,9 @@ "severity": "ERROR" }, { - "line": 114, + "line": 249, "column": 13, - "endLine": 114, + "endLine": 249, "endColumn": 14, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -485,9 +165,9 @@ "severity": "ERROR" }, { - "line": 114, + "line": 249, "column": 15, - "endLine": 114, + "endLine": 249, "endColumn": 20, "problem": "SpreadOperator", "suggest": "", @@ -495,9 +175,9 @@ "severity": "ERROR" }, { - "line": 115, + "line": 256, "column": 13, - "endLine": 115, + "endLine": 256, "endColumn": 14, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -505,19 +185,9 @@ "severity": "ERROR" }, { - "line": 117, - "column": 13, - "endLine": 117, - "endColumn": 14, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 120, + "line": 259, "column": 8, - "endLine": 120, + "endLine": 259, "endColumn": 9, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -525,9 +195,9 @@ "severity": "ERROR" }, { - "line": 130, + "line": 269, "column": 14, - "endLine": 130, + "endLine": 269, "endColumn": 15, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -535,9 +205,9 @@ "severity": "ERROR" }, { - "line": 131, + "line": 270, "column": 14, - "endLine": 131, + "endLine": 270, "endColumn": 15, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -545,9 +215,9 @@ "severity": "ERROR" }, { - "line": 132, + "line": 271, "column": 14, - "endLine": 132, + "endLine": 271, "endColumn": 15, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -555,29 +225,9 @@ "severity": "ERROR" }, { - "line": 134, - "column": 22, - "endLine": 134, - "endColumn": 23, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 135, - "column": 35, - "endLine": 135, - "endColumn": 36, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 136, + "line": 278, "column": 14, - "endLine": 136, + "endLine": 278, "endColumn": 15, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -585,9 +235,9 @@ "severity": "ERROR" }, { - "line": 139, + "line": 281, "column": 14, - "endLine": 139, + "endLine": 281, "endColumn": 15, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -595,9 +245,9 @@ "severity": "ERROR" }, { - "line": 141, + "line": 283, "column": 14, - "endLine": 141, + "endLine": 283, "endColumn": 15, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -605,9 +255,9 @@ "severity": "ERROR" }, { - "line": 141, + "line": 283, "column": 19, - "endLine": 141, + "endLine": 283, "endColumn": 29, "problem": "ClassAsObject", "suggest": "", @@ -615,9 +265,9 @@ "severity": "WARNING" }, { - "line": 145, + "line": 287, "column": 26, - "endLine": 145, + "endLine": 287, "endColumn": 29, "problem": "AnyType", "suggest": "", @@ -625,19 +275,9 @@ "severity": "ERROR" }, { - "line": 145, - "column": 33, - "endLine": 145, - "endColumn": 34, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 151, + "line": 293, "column": 35, - "endLine": 151, + "endLine": 293, "endColumn": 38, "problem": "AnyType", "suggest": "", @@ -645,19 +285,9 @@ "severity": "ERROR" }, { - "line": 151, - "column": 42, - "endLine": 151, - "endColumn": 43, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 160, + "line": 302, "column": 35, - "endLine": 160, + "endLine": 302, "endColumn": 38, "problem": "AnyType", "suggest": "", @@ -665,9 +295,9 @@ "severity": "ERROR" }, { - "line": 160, + "line": 302, "column": 42, - "endLine": 160, + "endLine": 302, "endColumn": 43, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -675,34 +305,14 @@ "severity": "ERROR" }, { - "line": 164, + "line": 306, "column": 5, - "endLine": 164, + "endLine": 306, "endColumn": 10, "problem": "ComputedPropertyName", "suggest": "", "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" - }, - { - "line": 170, - "column": 28, - "endLine": 170, - "endColumn": 29, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 171, - "column": 13, - "endLine": 171, - "endColumn": 14, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/object_literals_prop_func_type.ets.args.json b/ets2panda/linter/test/main/object_literals_prop_func_type.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/main/object_literals_prop_func_type.ets.args.json +++ b/ets2panda/linter/test/main/object_literals_prop_func_type.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/main/object_literals_prop_func_type.ets.migrate.ets b/ets2panda/linter/test/main/object_literals_prop_func_type.ets.migrate.ets new file mode 100644 index 0000000000..d1901e50e0 --- /dev/null +++ b/ets2panda/linter/test/main/object_literals_prop_func_type.ets.migrate.ets @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2023-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +type F = () => void; +interface FuncInterface { + (x: number): string + f?: number; +} + +class A { + a: F; + b: Function; + c: () => void; + d: FuncInterface; +} + +let a: A = { + a: () => { console.log('Hello'); }, + b: () => { console.log('Bye'); }, + c: () => { console.log('Apple'); }, + d: (x: number) => x.toString(), +} + +let q: F = () => {}; +let w: Function = (x: number) => x * x; +let e = () => { console.log('Orange'); }; +let r: FuncInterface = (x: number) => x.toString(); + +a = { + a: q, + b: w, + c: e, + d: r, +} + +// #14569 - initialize field with 'Function' object +class B { + f: Function = () => {}; +} +let b: B = { + f: Function +}; \ No newline at end of file diff --git a/ets2panda/linter/test/main/object_literals_prop_func_type.ets.migrate.json b/ets2panda/linter/test/main/object_literals_prop_func_type.ets.migrate.json new file mode 100644 index 0000000000..8c06a808b0 --- /dev/null +++ b/ets2panda/linter/test/main/object_literals_prop_func_type.ets.migrate.json @@ -0,0 +1,78 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 3, + "endLine": 18, + "endColumn": 22, + "problem": "CallSignature", + "suggest": "", + "rule": "Use \"class\" instead of a type with call signature (arkts-no-call-signatures)", + "severity": "ERROR" + }, + { + "line": 53, + "column": 6, + "endLine": 53, + "endColumn": 14, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 23, + "column": 3, + "endLine": 23, + "endColumn": 4, + "problem": "StrictDiagnostic", + "suggest": "Property 'a' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'a' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 24, + "column": 3, + "endLine": 24, + "endColumn": 4, + "problem": "StrictDiagnostic", + "suggest": "Property 'b' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'b' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 25, + "column": 3, + "endLine": 25, + "endColumn": 4, + "problem": "StrictDiagnostic", + "suggest": "Property 'c' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'c' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 26, + "column": 3, + "endLine": 26, + "endColumn": 4, + "problem": "StrictDiagnostic", + "suggest": "Property 'd' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'd' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/object_literals_properties.ets b/ets2panda/linter/test/main/object_literals_properties.ets index e695679833..da4dacf6b6 100644 --- a/ets2panda/linter/test/main/object_literals_properties.ets +++ b/ets2panda/linter/test/main/object_literals_properties.ets @@ -13,32 +13,233 @@ * limitations under the License. */ -class MyClass { - a: string = "" - b: number = 0 -} +// Untyped object literals +let method = { + m() { console.log(1); } // Error, fixable +}; + +let getMethod = { + get property() { return 2; } // Error, fixable +}; + +let setMethod = { + set property(value: number) { // Error, fixable + console.log(value); + } +}; + +let x = 1, y = '2', z = true; + +let shorthand = { + x, // Error, fixable + y, // Error, fixable + z // Error, fixable +}; + +let spread = { + ...shorthand // Error, not fixable +}; -let c: MyClass = {a: "a", b: 3} +let mixed = { // Fixable + a: "foo", + b: 42, + c: [1, 2, 3], + x, // Error + y, // Error -let b: MyClass = { - a: "Alice", - "c", // Error - c, // Error - b: "num", - method() { // Error + method() { // Error console.log(42) }, + + get property() { // Error + return 0; + }, + + set property(value: number) { // Error + if (value < 0) { + throw new Error('Bad value'); + } + } +}; + +let x2 = 1, y2 = 2, z2 = 3; +let mixedBad = { // Not fixable + a: 1, + b: 2, + x2, // Error, fixable + y2, // Error, fixable + z2, // Error, fixable + m() {}, + ...shorthand // Error, not fixable } -let o: MyClass = { - a: "foo", - b: 42, - c: {}, - 1: "number literal property", // Error - "foo:bar": "string literal property", // Error +// Typed object literals +interface I { + m(): void; +} +let i: I = { + m() { // Fixable + console.log(100); + } +}; + +class C { + m(): void { + console.log(200); + } +} +let c: C = { + m(): void { // Fixable + console.log(300); + } +}; + +function foo(c: C) {} +foo({ + m() { console.log(300); } // Fixable +}); - get property() {}, // Error - set property(value) {}, // Error +class C2 { + x2 = 10; + y2 = 20; + z2 = 30; + + m() {} +} +let c2: C2 = { + x2, // Fixable + y2, // Fixable + z2, // Fixable + m() { console.log(1); } // Fixable +}; - [expression]: "computed property", // Error +let c22: C2 = { + x2, // Fixable + y2, // Fixable + z2, // Fixable + m() { console.log(1); }, // Not fixable, object has spread property + ...shorthand // Not fixable }; + +class C3 { + x2 = 10; + y2 = 20; + z2 = 30; + + m() {} + + constructor(a: number) {} +} +let c3: C3 = { + x2, // Fixable + y2, // Fixable + z2, // Fixable + m() { console.log(1); } // Not fixable, class type has constructor with parameters +}; + +function capturesFromLocalScope() { + let a = 1, b = 2; + let captureLocalVal = { + m() { // Not fixable, captures local values 'a' and 'b' + console.log(a, b); + } + }; + + let captureLocalVal2: C = { + m(): void { // Not fixable, captures local values 'a' and 'b' + console.log(a, b); + } + }; + + type LocalType = {a: number, b: string}; + let localTypeVar: LocalType = { a: 1, b: '2' }; + let captureLocalType = { + m() { // Not fixable, captures value of type `LocalType` declared in local scope + console.log(localTypeVar); + } + }; + let captureLocalType2 = { + m(x: LocalType) { // Not fixable, `x` references type `LocalType` declared in local scope + console.log(x); + } + }; + + class LocalClass { x: number = 1 }; + let captureLocalType3 = { + m() { // Not fixable, references type `LocalClass` declared in local scope + console.log(new LocalClass()); + } + }; +} + +// Method overriding field +class C4 { + a: number = 0; + b() {}; +} +let c4: C4 = { // Not fixable, overrides class method with property of functional type + a: 1, + b: () => {} +}; + +class C5 { + a: number = 0; + b: () => void; +} +let c5: C5 = { // Not fixable, overrides class property with method + a: 1, + b() {} +}; + +interface I2 { + a: number; + b(): void; +} +let i2: I2 = { // Not fixable, implements method as functional-type property + a: 1, + b: () => {} +}; + +interface I3 { + a: number; + b: () => void; +} +let ii: I3 = { // Not fixable, implements functional-type property as a method + a: 1, + b() {} +}; + +// Inheritance +class Base { + constructor() {} +} +class Derived extends Base { + m() {} +} +let b: Derived = { // Fixable + m() { console.log(2); } +}; + +class Base2 { + constructor(a: number) {} +} +class Derived2 extends Base2 { + m() {} +} +let b2: Derived2 = { // Not fixable, derived class inherits a constructor with parameters from base class + m() { console.log(2); } +}; + +class Base3 { + constructor(a: number) {} +} +class Derived3 extends Base3 { + m() {} + + constructor() { + super(1); + } +} +let b3: Derived3 = { // Fixable + m() { console.log(2); } +}; \ No newline at end of file diff --git a/ets2panda/linter/test/main/object_literals_properties.ets.args.json b/ets2panda/linter/test/main/object_literals_properties.ets.args.json index 720715a55c..f9fc1047e8 100644 --- a/ets2panda/linter/test/main/object_literals_properties.ets.args.json +++ b/ets2panda/linter/test/main/object_literals_properties.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2023-2024 Huawei Device Co., Ltd.", + "Copyright (c) 2023-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,8 @@ "limitations under the License." ], "mode": { - "arkts2": "" + "arkts2": "", + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } diff --git a/ets2panda/linter/test/main/object_literals_properties.ets.arkts2.json b/ets2panda/linter/test/main/object_literals_properties.ets.arkts2.json index d22a345648..8f19012800 100644 --- a/ets2panda/linter/test/main/object_literals_properties.ets.arkts2.json +++ b/ets2panda/linter/test/main/object_literals_properties.ets.arkts2.json @@ -15,59 +15,89 @@ ], "result": [ { - "line": 23, - "column": 18, - "endLine": 23, - "endColumn": 19, + "line": 17, + "column": 14, + "endLine": 17, + "endColumn": 15, "problem": "ObjectLiteralNoContextType", "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 25, + "line": 18, "column": 3, - "endLine": 25, - "endColumn": 6, + "endLine": 18, + "endColumn": 26, "problem": "ObjectLiteralProperty", "suggest": "", "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 26, + "line": 21, + "column": 17, + "endLine": 21, + "endColumn": 18, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 22, "column": 3, - "endLine": 26, - "endColumn": 4, + "endLine": 22, + "endColumn": 31, "problem": "ObjectLiteralProperty", "suggest": "", "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 28, + "line": 25, + "column": 17, + "endLine": 25, + "endColumn": 18, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 26, "column": 3, - "endLine": 30, + "endLine": 28, "endColumn": 4, "problem": "ObjectLiteralProperty", "suggest": "", "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, + { + "line": 31, + "column": 5, + "endLine": 31, + "endColumn": 10, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { "line": 33, - "column": 18, + "column": 17, "endLine": 33, - "endColumn": 19, + "endColumn": 18, "problem": "ObjectLiteralNoContextType", "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 37, + "line": 34, "column": 3, - "endLine": 37, + "endLine": 34, "endColumn": 4, "problem": "ObjectLiteralProperty", "suggest": "", @@ -75,39 +105,199 @@ "severity": "ERROR" }, { - "line": 38, + "line": 35, "column": 3, - "endLine": 38, - "endColumn": 12, + "endLine": 35, + "endColumn": 4, "problem": "ObjectLiteralProperty", "suggest": "", "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, + { + "line": 36, + "column": 3, + "endLine": 36, + "endColumn": 4, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 14, + "endLine": 39, + "endColumn": 15, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, { "line": 40, "column": 3, "endLine": 40, - "endColumn": 20, + "endColumn": 15, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 40, + "column": 3, + "endLine": 40, + "endColumn": 15, + "problem": "SpreadOperator", + "suggest": "", + "rule": "It is possible to spread only arrays or classes derived from arrays into the rest parameter or array literals (arkts-no-spread)", + "severity": "ERROR" + }, + { + "line": 43, + "column": 13, + "endLine": 43, + "endColumn": 14, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 47, + "column": 3, + "endLine": 47, + "endColumn": 4, "problem": "ObjectLiteralProperty", "suggest": "", "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 41, + "line": 48, "column": 3, - "endLine": 41, - "endColumn": 25, + "endLine": 48, + "endColumn": 4, "problem": "ObjectLiteralProperty", "suggest": "", "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 43, + "line": 50, "column": 3, - "endLine": 43, + "endLine": 52, + "endColumn": 4, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 54, + "column": 3, + "endLine": 56, + "endColumn": 4, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 58, + "column": 3, + "endLine": 62, + "endColumn": 4, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 65, + "column": 5, + "endLine": 65, + "endColumn": 11, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 65, + "column": 13, + "endLine": 65, + "endColumn": 19, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 65, + "column": 21, + "endLine": 65, + "endColumn": 27, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 66, + "column": 16, + "endLine": 66, + "endColumn": 17, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 69, + "column": 3, + "endLine": 69, + "endColumn": 5, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 70, + "column": 3, + "endLine": 70, + "endColumn": 5, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 3, + "endLine": 71, + "endColumn": 5, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 3, + "endLine": 72, + "endColumn": 9, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 3, + "endLine": 73, "endColumn": 15, "problem": "ObjectLiteralProperty", "suggest": "", @@ -115,33 +305,553 @@ "severity": "ERROR" }, { - "line": 36, - "column": 6, - "endLine": 36, - "endColumn": 7, + "line": 73, + "column": 3, + "endLine": 73, + "endColumn": 15, + "problem": "SpreadOperator", + "suggest": "", + "rule": "It is possible to spread only arrays or classes derived from arrays into the rest parameter or array literals (arkts-no-spread)", + "severity": "ERROR" + }, + { + "line": 80, + "column": 12, + "endLine": 80, + "endColumn": 13, "problem": "ObjectLiteralNoContextType", "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 37, + "line": 81, "column": 3, - "endLine": 37, + "endLine": 83, "endColumn": 4, - "problem": "LiteralAsPropertyName", + "problem": "ObjectLiteralProperty", "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 43, + "line": 91, + "column": 12, + "endLine": 91, + "endColumn": 13, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 92, "column": 3, - "endLine": 43, + "endLine": 94, + "endColumn": 4, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 98, + "column": 5, + "endLine": 98, + "endColumn": 6, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 99, + "column": 3, + "endLine": 99, + "endColumn": 28, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 103, + "column": 3, + "endLine": 103, + "endColumn": 11, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 104, + "column": 3, + "endLine": 104, + "endColumn": 11, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 105, + "column": 3, + "endLine": 105, + "endColumn": 11, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 109, + "column": 14, + "endLine": 109, + "endColumn": 15, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 110, + "column": 3, + "endLine": 110, + "endColumn": 5, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 111, + "column": 3, + "endLine": 111, + "endColumn": 5, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 112, + "column": 3, + "endLine": 112, + "endColumn": 5, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 113, + "column": 3, + "endLine": 113, + "endColumn": 26, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 116, + "column": 15, + "endLine": 116, + "endColumn": 16, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 117, + "column": 3, + "endLine": 117, + "endColumn": 5, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 118, + "column": 3, + "endLine": 118, + "endColumn": 5, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 119, + "column": 3, + "endLine": 119, + "endColumn": 5, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 120, + "column": 3, + "endLine": 120, + "endColumn": 26, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 121, + "column": 3, + "endLine": 121, + "endColumn": 15, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 121, + "column": 3, + "endLine": 121, + "endColumn": 15, + "problem": "SpreadOperator", + "suggest": "", + "rule": "It is possible to spread only arrays or classes derived from arrays into the rest parameter or array literals (arkts-no-spread)", + "severity": "ERROR" + }, + { + "line": 125, + "column": 3, + "endLine": 125, + "endColumn": 11, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 126, + "column": 3, + "endLine": 126, + "endColumn": 11, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 127, + "column": 3, + "endLine": 127, + "endColumn": 11, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 133, + "column": 14, + "endLine": 133, + "endColumn": 15, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 134, + "column": 3, + "endLine": 134, + "endColumn": 5, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 135, + "column": 3, + "endLine": 135, + "endColumn": 5, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 136, + "column": 3, + "endLine": 136, + "endColumn": 5, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 137, + "column": 3, + "endLine": 137, + "endColumn": 26, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 141, + "column": 7, + "endLine": 141, + "endColumn": 12, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 141, + "column": 14, + "endLine": 141, + "endColumn": 19, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 142, + "column": 25, + "endLine": 142, + "endColumn": 26, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 143, + "column": 5, + "endLine": 145, + "endColumn": 6, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 148, + "column": 29, + "endLine": 148, + "endColumn": 30, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 149, + "column": 5, + "endLine": 151, + "endColumn": 6, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 154, + "column": 20, + "endLine": 154, + "endColumn": 21, + "problem": "ObjectTypeLiteral", + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 155, + "column": 33, + "endLine": 155, + "endColumn": 34, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 156, + "column": 26, + "endLine": 156, + "endColumn": 27, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 157, + "column": 5, + "endLine": 159, + "endColumn": 6, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 161, + "column": 27, + "endLine": 161, + "endColumn": 28, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 162, + "column": 5, + "endLine": 164, + "endColumn": 6, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 168, + "column": 27, + "endLine": 168, + "endColumn": 28, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 169, + "column": 5, + "endLine": 171, + "endColumn": 6, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 180, + "column": 14, + "endLine": 180, + "endColumn": 15, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 191, + "column": 3, + "endLine": 191, + "endColumn": 9, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 198, + "column": 14, + "endLine": 198, "endColumn": 15, - "problem": "ComputedPropertyName", + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 209, + "column": 3, + "endLine": 209, + "endColumn": 9, + "problem": "ObjectLiteralProperty", "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 219, + "column": 18, + "endLine": 219, + "endColumn": 19, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 220, + "column": 3, + "endLine": 220, + "endColumn": 26, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 229, + "column": 20, + "endLine": 229, + "endColumn": 21, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 230, + "column": 3, + "endLine": 230, + "endColumn": 26, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 243, + "column": 20, + "endLine": 243, + "endColumn": 21, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 244, + "column": 3, + "endLine": 244, + "endColumn": 26, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 187, + "column": 3, + "endLine": 187, + "endColumn": 4, + "problem": "StrictDiagnostic", + "suggest": "Property 'b' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'b' has no initializer and is not definitely assigned in the constructor.", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/migrate/object_literals_autofixes.ts.migrate.json b/ets2panda/linter/test/main/object_literals_properties.ets.autofix.json similarity index 30% rename from ets2panda/linter/test/migrate/object_literals_autofixes.ts.migrate.json rename to ets2panda/linter/test/main/object_literals_properties.ets.autofix.json index 8757f86ed2..de865a4411 100644 --- a/ets2panda/linter/test/migrate/object_literals_autofixes.ts.migrate.json +++ b/ets2panda/linter/test/main/object_literals_properties.ets.autofix.json @@ -1,519 +1,827 @@ { + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], "result": [ { - "line": 29, + "line": 17, "column": 14, - "endLine": 29, + "endLine": 17, "endColumn": 15, - "problem": "AnyType", + "problem": "ObjectLiteralNoContextType", + "autofix": [ + { + "start": 637, + "end": 637, + "replacementText": "class GeneratedObjectLiteralClass_1 {\n m() { console.log(1); } // Error, fixable\n}\n\n" + }, + { + "start": 650, + "end": 697, + "replacementText": "new GeneratedObjectLiteralClass_1()" + } + ], "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 33, - "column": 12, - "endLine": 33, - "endColumn": 13, - "problem": "ObjectLiteralNoContextType", + "line": 18, + "column": 3, + "endLine": 18, + "endColumn": 26, + "problem": "ObjectLiteralProperty", "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 34, - "column": 12, - "endLine": 34, - "endColumn": 13, + "line": 21, + "column": 17, + "endLine": 21, + "endColumn": 18, "problem": "ObjectLiteralNoContextType", + "autofix": [ + { + "start": 700, + "end": 700, + "replacementText": "class GeneratedObjectLiteralClass_2 {\n get property() { return 2; } // Error, fixable\n}\n\n" + }, + { + "start": 716, + "end": 768, + "replacementText": "new GeneratedObjectLiteralClass_2()" + } + ], "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 35, - "column": 7, - "endLine": 35, - "endColumn": 25, - "problem": "DefiniteAssignment", + "line": 22, + "column": 3, + "endLine": 22, + "endColumn": 31, + "problem": "ObjectLiteralProperty", "suggest": "", - "rule": "Definite assignment assertions are not supported (arkts-no-definite-assignment)", - "severity": "WARNING" + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" }, { - "line": 35, - "column": 13, - "endLine": 35, - "endColumn": 14, + "line": 25, + "column": 17, + "endLine": 25, + "endColumn": 18, "problem": "ObjectLiteralNoContextType", + "autofix": [ + { + "start": 771, + "end": 771, + "replacementText": "class GeneratedObjectLiteralClass_3 {\n set property(value: number) {\n console.log(value);\n }\n}\n\n" + }, + { + "start": 787, + "end": 868, + "replacementText": "new GeneratedObjectLiteralClass_3()" + } + ], "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 36, - "column": 12, - "endLine": 36, - "endColumn": 13, - "problem": "ObjectLiteralNoContextType", + "line": 26, + "column": 3, + "endLine": 28, + "endColumn": 4, + "problem": "ObjectLiteralProperty", "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 46, - "column": 12, - "endLine": 46, - "endColumn": 13, - "problem": "ObjectLiteralNoContextType", + "line": 31, + "column": 5, + "endLine": 31, + "endColumn": 10, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 875, + "end": 880, + "replacementText": "x: number = 1" + } + ], "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { - "line": 51, - "column": 8, - "endLine": 51, - "endColumn": 9, + "line": 33, + "column": 17, + "endLine": 33, + "endColumn": 18, "problem": "ObjectLiteralNoContextType", "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 52, - "column": 8, - "endLine": 52, - "endColumn": 9, - "problem": "ObjectLiteralNoContextType", + "line": 34, + "column": 3, + "endLine": 34, + "endColumn": 4, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 922, + "end": 923, + "replacementText": "x: x" + } + ], "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 53, - "column": 8, - "endLine": 53, - "endColumn": 9, - "problem": "ObjectLiteralNoContextType", + "line": 35, + "column": 3, + "endLine": 35, + "endColumn": 4, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 945, + "end": 946, + "replacementText": "y: y" + } + ], "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 58, - "column": 12, - "endLine": 58, - "endColumn": 13, - "problem": "ObjectLiteralNoContextType", + "line": 36, + "column": 3, + "endLine": 36, + "endColumn": 4, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 968, + "end": 969, + "replacementText": "z: z" + } + ], "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 61, - "column": 8, - "endLine": 61, - "endColumn": 9, + "line": 39, + "column": 14, + "endLine": 39, + "endColumn": 15, "problem": "ObjectLiteralNoContextType", "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 63, - "column": 8, - "endLine": 63, - "endColumn": 9, - "problem": "ObjectLiteralNoContextType", + "line": 40, + "column": 3, + "endLine": 40, + "endColumn": 15, + "problem": "ObjectLiteralProperty", "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 67, - "column": 12, - "endLine": 67, - "endColumn": 13, - "problem": "ObjectLiteralNoContextType", + "line": 40, + "column": 3, + "endLine": 40, + "endColumn": 15, + "problem": "SpreadOperator", "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "It is possible to spread only arrays or classes derived from arrays into the rest parameter or array literals (arkts-no-spread)", "severity": "ERROR" }, { - "line": 67, - "column": 29, - "endLine": 67, - "endColumn": 30, + "line": 43, + "column": 13, + "endLine": 43, + "endColumn": 14, "problem": "ObjectLiteralNoContextType", + "autofix": [ + { + "start": 1048, + "end": 1048, + "replacementText": "class GeneratedObjectLiteralClass_4 {\n a: string;\n b: number;\n c: number[];\n x: number;\n y: string;\n constructor(init: GeneratedObjectLiteralInitInterface_4) {\n this.a = init.a;\n this.b = init.b;\n this.c = init.c;\n this.x = init.x;\n this.y = init.y;\n }\n method() {\n console.log(42);\n }\n get property() {\n return 0;\n }\n set property(value: number) {\n if (value < 0) {\n throw new Error('Bad value');\n }\n }\n}\n\ninterface GeneratedObjectLiteralInitInterface_4 {\n a: string;\n b: number;\n c: number[];\n x: number;\n y: string;\n}\n\n" + }, + { + "start": 1060, + "end": 1344, + "replacementText": "new GeneratedObjectLiteralClass_4({\n a: \"foo\",\n b: 42,\n c: [1, 2, 3],\n x: x,\n y: y\n})" + } + ], "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 68, - "column": 12, - "endLine": 68, - "endColumn": 13, - "problem": "ObjectLiteralNoContextType", + "line": 47, + "column": 3, + "endLine": 47, + "endColumn": 4, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 1112, + "end": 1113, + "replacementText": "x: x" + } + ], "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 71, - "column": 9, - "endLine": 71, - "endColumn": 10, - "problem": "ObjectLiteralNoContextType", + "line": 48, + "column": 3, + "endLine": 48, + "endColumn": 4, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 1126, + "end": 1127, + "replacementText": "y: y" + } + ], "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 72, - "column": 12, - "endLine": 72, - "endColumn": 13, - "problem": "ObjectLiteralNoContextType", + "line": 50, + "column": 3, + "endLine": 52, + "endColumn": 4, + "problem": "ObjectLiteralProperty", "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 72, - "column": 27, - "endLine": 72, - "endColumn": 28, - "problem": "ObjectLiteralNoContextType", + "line": 54, + "column": 3, + "endLine": 56, + "endColumn": 4, + "problem": "ObjectLiteralProperty", "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 77, - "column": 10, - "endLine": 77, - "endColumn": 11, - "problem": "ObjectLiteralNoContextType", + "line": 58, + "column": 3, + "endLine": 62, + "endColumn": 4, + "problem": "ObjectLiteralProperty", "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 78, - "column": 11, - "endLine": 78, - "endColumn": 12, - "problem": "ObjectLiteralNoContextType", + "line": 65, + "column": 5, + "endLine": 65, + "endColumn": 11, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1351, + "end": 1357, + "replacementText": "x2: number = 1" + } + ], "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { - "line": 79, - "column": 5, - "endLine": 79, - "endColumn": 24, - "problem": "DefiniteAssignment", + "line": 65, + "column": 13, + "endLine": 65, + "endColumn": 19, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1359, + "end": 1365, + "replacementText": "y2: number = 2" + } + ], "suggest": "", - "rule": "Definite assignment assertions are not supported (arkts-no-definite-assignment)", - "severity": "WARNING" + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" }, { - "line": 79, - "column": 11, - "endLine": 79, - "endColumn": 12, - "problem": "ObjectLiteralNoContextType", + "line": 65, + "column": 21, + "endLine": 65, + "endColumn": 27, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1367, + "end": 1373, + "replacementText": "z2: number = 3" + } + ], "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { - "line": 80, - "column": 11, - "endLine": 80, - "endColumn": 12, + "line": 66, + "column": 16, + "endLine": 66, + "endColumn": 17, "problem": "ObjectLiteralNoContextType", "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 81, - "column": 10, - "endLine": 81, - "endColumn": 11, - "problem": "ObjectLiteralNoContextType", + "line": 69, + "column": 3, + "endLine": 69, + "endColumn": 5, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 1425, + "end": 1427, + "replacementText": "x2: x2" + } + ], "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 81, - "column": 21, - "endLine": 81, - "endColumn": 22, - "problem": "ObjectLiteralNoContextType", + "line": 70, + "column": 3, + "endLine": 70, + "endColumn": 5, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 1449, + "end": 1451, + "replacementText": "y2: y2" + } + ], "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 84, - "column": 17, - "endLine": 84, - "endColumn": 18, - "problem": "ObjectLiteralNoContextType", + "line": 71, + "column": 3, + "endLine": 71, + "endColumn": 5, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 1473, + "end": 1475, + "replacementText": "z2: z2" + } + ], "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 85, - "column": 17, - "endLine": 85, - "endColumn": 18, - "problem": "ObjectLiteralNoContextType", + "line": 72, + "column": 3, + "endLine": 72, + "endColumn": 9, + "problem": "ObjectLiteralProperty", "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 90, - "column": 22, - "endLine": 90, - "endColumn": 23, - "problem": "ObjectLiteralNoContextType", + "line": 73, + "column": 3, + "endLine": 73, + "endColumn": 15, + "problem": "ObjectLiteralProperty", "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 91, - "column": 19, - "endLine": 91, - "endColumn": 42, - "problem": "DestructuringParameter", + "line": 73, + "column": 3, + "endLine": 73, + "endColumn": 15, + "problem": "SpreadOperator", "suggest": "", - "rule": "Destructuring parameter declarations are not supported (arkts-no-destruct-params)", + "rule": "It is possible to spread only arrays or classes derived from arrays into the rest parameter or array literals (arkts-no-spread)", "severity": "ERROR" }, { - "line": 91, - "column": 28, - "endLine": 91, - "endColumn": 29, + "line": 80, + "column": 12, + "endLine": 80, + "endColumn": 13, "problem": "ObjectLiteralNoContextType", "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 95, - "column": 13, - "endLine": 95, - "endColumn": 14, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "line": 81, + "column": 3, + "endLine": 83, + "endColumn": 4, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 1599, + "end": 1599, + "replacementText": "class GeneratedObjectLiteralClass_5 implements I {\n m() {\n console.log(100);\n }\n}\n\n" + }, + { + "start": 1610, + "end": 1658, + "replacementText": "new GeneratedObjectLiteralClass_5()" + } + ], + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 96, - "column": 13, - "endLine": 96, - "endColumn": 14, + "line": 91, + "column": 12, + "endLine": 91, + "endColumn": 13, "problem": "ObjectLiteralNoContextType", "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 99, - "column": 17, - "endLine": 99, - "endColumn": 18, - "problem": "ObjectLiteralNoContextType", + "line": 92, + "column": 3, + "endLine": 94, + "endColumn": 4, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 1713, + "end": 1713, + "replacementText": "class GeneratedObjectLiteralClass_6 extends C {\n m(): void {\n console.log(300);\n }\n}\n\n" + }, + { + "start": 1724, + "end": 1778, + "replacementText": "new GeneratedObjectLiteralClass_6()" + } + ], "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 102, - "column": 13, - "endLine": 102, - "endColumn": 14, + "line": 98, + "column": 5, + "endLine": 98, + "endColumn": 6, "problem": "ObjectLiteralNoContextType", "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 102, - "column": 27, - "endLine": 102, + "line": 99, + "column": 3, + "endLine": 99, "endColumn": 28, - "problem": "ObjectLiteralNoContextType", + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 1803, + "end": 1803, + "replacementText": "class GeneratedObjectLiteralClass_7 extends C {\n m() { console.log(300); } // Fixable\n}\n\n" + }, + { + "start": 1807, + "end": 1849, + "replacementText": "new GeneratedObjectLiteralClass_7()" + } + ], + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 103, + "column": 3, + "endLine": 103, + "endColumn": 11, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1866, + "end": 1874, + "replacementText": "x2: number = 10;" + } + ], "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { - "line": 102, - "column": 41, - "endLine": 102, - "endColumn": 42, - "problem": "ObjectLiteralNoContextType", + "line": 104, + "column": 3, + "endLine": 104, + "endColumn": 11, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1877, + "end": 1885, + "replacementText": "y2: number = 20;" + } + ], "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { "line": 105, - "column": 12, + "column": 3, "endLine": 105, - "endColumn": 13, - "problem": "ObjectLiteralNoContextType", + "endColumn": 11, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1888, + "end": 1896, + "replacementText": "z2: number = 30;" + } + ], "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { - "line": 105, + "line": 109, "column": 14, - "endLine": 105, + "endLine": 109, "endColumn": 15, - "problem": "LiteralAsPropertyName", + "problem": "ObjectLiteralNoContextType", "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 106, - "column": 13, - "endLine": 106, - "endColumn": 14, - "problem": "ObjectLiteralNoContextType", + "line": 110, + "column": 3, + "endLine": 110, + "endColumn": 5, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 1926, + "end": 1928, + "replacementText": "x2: x2" + } + ], "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 106, - "column": 15, - "endLine": 106, - "endColumn": 18, - "problem": "ComputedPropertyName", + "line": 111, + "column": 3, + "endLine": 111, + "endColumn": 5, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 1943, + "end": 1945, + "replacementText": "y2: y2" + } + ], "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 107, - "column": 13, - "endLine": 107, - "endColumn": 14, + "line": 112, + "column": 3, + "endLine": 112, + "endColumn": 5, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 1960, + "end": 1962, + "replacementText": "z2: z2" + } + ], + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 113, + "column": 3, + "endLine": 113, + "endColumn": 26, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 1909, + "end": 1909, + "replacementText": "class GeneratedObjectLiteralClass_8 extends C2 {\n x2: number;\n y2: number;\n z2: number;\n constructor(init: GeneratedObjectLiteralInitInterface_8) {\n super();\n this.x2 = init.x2;\n this.y2 = init.y2;\n this.z2 = init.z2;\n }\n m() { console.log(1); } // Fixable\n}\n\ninterface GeneratedObjectLiteralInitInterface_8 {\n x2: number;\n y2: number;\n z2: number;\n}\n\n" + }, + { + "start": 1922, + "end": 2013, + "replacementText": "new GeneratedObjectLiteralClass_8({\n x2: x2,\n y2: y2,\n z2: z2\n})" + } + ], + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 116, + "column": 15, + "endLine": 116, + "endColumn": 16, "problem": "ObjectLiteralNoContextType", "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 107, - "column": 15, - "endLine": 107, - "endColumn": 25, - "problem": "ComputedPropertyName", + "line": 117, + "column": 3, + "endLine": 117, + "endColumn": 5, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 2034, + "end": 2036, + "replacementText": "x2: x2" + } + ], "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 109, - "column": 15, - "endLine": 109, - "endColumn": 18, - "problem": "AnyType", + "line": 118, + "column": 3, + "endLine": 118, + "endColumn": 5, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 2051, + "end": 2053, + "replacementText": "y2: y2" + } + ], "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 110, - "column": 13, - "endLine": 110, - "endColumn": 14, - "problem": "ObjectLiteralNoContextType", + "line": 119, + "column": 3, + "endLine": 119, + "endColumn": 5, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 2068, + "end": 2070, + "replacementText": "z2: z2" + } + ], "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 113, - "column": 13, - "endLine": 113, - "endColumn": 14, - "problem": "ObjectLiteralNoContextType", + "line": 120, + "column": 3, + "endLine": 120, + "endColumn": 26, + "problem": "ObjectLiteralProperty", "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 114, - "column": 13, - "endLine": 114, - "endColumn": 14, - "problem": "ObjectLiteralNoContextType", + "line": 121, + "column": 3, + "endLine": 121, + "endColumn": 15, + "problem": "ObjectLiteralProperty", "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 114, - "column": 15, - "endLine": 114, - "endColumn": 20, + "line": 121, + "column": 3, + "endLine": 121, + "endColumn": 15, "problem": "SpreadOperator", "suggest": "", "rule": "It is possible to spread only arrays or classes derived from arrays into the rest parameter or array literals (arkts-no-spread)", "severity": "ERROR" }, { - "line": 115, - "column": 13, - "endLine": 115, - "endColumn": 14, - "problem": "ObjectLiteralNoContextType", + "line": 125, + "column": 3, + "endLine": 125, + "endColumn": 11, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2200, + "end": 2208, + "replacementText": "x2: number = 10;" + } + ], "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { - "line": 117, - "column": 13, - "endLine": 117, - "endColumn": 14, - "problem": "ObjectLiteralNoContextType", + "line": 126, + "column": 3, + "endLine": 126, + "endColumn": 11, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2211, + "end": 2219, + "replacementText": "y2: number = 20;" + } + ], "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { - "line": 120, - "column": 8, - "endLine": 120, - "endColumn": 9, - "problem": "ObjectLiteralNoContextType", + "line": 127, + "column": 3, + "endLine": 127, + "endColumn": 11, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2222, + "end": 2230, + "replacementText": "z2: number = 30;" + } + ], "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { - "line": 130, + "line": 133, "column": 14, - "endLine": 130, + "endLine": 133, "endColumn": 15, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -521,174 +829,360 @@ "severity": "ERROR" }, { - "line": 131, + "line": 134, + "column": 3, + "endLine": 134, + "endColumn": 5, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 2289, + "end": 2291, + "replacementText": "x2: x2" + } + ], + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 135, + "column": 3, + "endLine": 135, + "endColumn": 5, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 2306, + "end": 2308, + "replacementText": "y2: y2" + } + ], + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 136, + "column": 3, + "endLine": 136, + "endColumn": 5, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 2323, + "end": 2325, + "replacementText": "z2: z2" + } + ], + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 137, + "column": 3, + "endLine": 137, + "endColumn": 26, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 141, + "column": 7, + "endLine": 141, + "endColumn": 12, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2469, + "end": 2474, + "replacementText": "a: number = 1" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 141, "column": 14, - "endLine": 131, - "endColumn": 15, + "endLine": 141, + "endColumn": 19, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2476, + "end": 2481, + "replacementText": "b: number = 2" + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 142, + "column": 25, + "endLine": 142, + "endColumn": 26, "problem": "ObjectLiteralNoContextType", "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 132, - "column": 14, - "endLine": 132, - "endColumn": 15, + "line": 143, + "column": 5, + "endLine": 145, + "endColumn": 6, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 148, + "column": 29, + "endLine": 148, + "endColumn": 30, "problem": "ObjectLiteralNoContextType", "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 134, - "column": 22, - "endLine": 134, - "endColumn": 23, + "line": 149, + "column": 5, + "endLine": 151, + "endColumn": 6, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 154, + "column": 20, + "endLine": 154, + "endColumn": 21, "problem": "ObjectTypeLiteral", + "autofix": [ + { + "start": 2741, + "end": 2781, + "replacementText": "interface LocalType {\n a: number;\n b: string;\n}" + } + ], "suggest": "", "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", "severity": "ERROR" }, { - "line": 135, - "column": 35, - "endLine": 135, - "endColumn": 36, + "line": 155, + "column": 33, + "endLine": 155, + "endColumn": 34, "problem": "ObjectLiteralNoContextType", "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 136, - "column": 14, - "endLine": 136, - "endColumn": 15, + "line": 156, + "column": 26, + "endLine": 156, + "endColumn": 27, "problem": "ObjectLiteralNoContextType", "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 139, - "column": 14, - "endLine": 139, - "endColumn": 15, - "problem": "ObjectLiteralNoContextType", + "line": 157, + "column": 5, + "endLine": 159, + "endColumn": 6, + "problem": "ObjectLiteralProperty", "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 141, - "column": 14, - "endLine": 141, - "endColumn": 15, + "line": 161, + "column": 27, + "endLine": 161, + "endColumn": 28, "problem": "ObjectLiteralNoContextType", "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 141, - "column": 19, - "endLine": 141, - "endColumn": 29, - "problem": "ClassAsObject", + "line": 162, + "column": 5, + "endLine": 164, + "endColumn": 6, + "problem": "ObjectLiteralProperty", "suggest": "", - "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", - "severity": "WARNING" + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" }, { - "line": 145, - "column": 26, - "endLine": 145, - "endColumn": 29, - "problem": "AnyType", + "line": 168, + "column": 27, + "endLine": 168, + "endColumn": 28, + "problem": "ObjectLiteralNoContextType", "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 145, - "column": 33, - "endLine": 145, - "endColumn": 34, + "line": 169, + "column": 5, + "endLine": 171, + "endColumn": 6, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 180, + "column": 14, + "endLine": 180, + "endColumn": 15, "problem": "ObjectLiteralNoContextType", "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 151, - "column": 35, - "endLine": 151, - "endColumn": 38, - "problem": "AnyType", + "line": 191, + "column": 3, + "endLine": 191, + "endColumn": 9, + "problem": "ObjectLiteralProperty", "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 151, - "column": 42, - "endLine": 151, - "endColumn": 43, + "line": 198, + "column": 14, + "endLine": 198, + "endColumn": 15, "problem": "ObjectLiteralNoContextType", "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 160, - "column": 35, - "endLine": 160, - "endColumn": 38, - "problem": "AnyType", + "line": 209, + "column": 3, + "endLine": 209, + "endColumn": 9, + "problem": "ObjectLiteralProperty", "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 160, - "column": 42, - "endLine": 160, - "endColumn": 43, + "line": 219, + "column": 18, + "endLine": 219, + "endColumn": 19, "problem": "ObjectLiteralNoContextType", "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 164, - "column": 5, - "endLine": 164, - "endColumn": 10, - "problem": "ComputedPropertyName", + "line": 220, + "column": 3, + "endLine": 220, + "endColumn": 26, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 4038, + "end": 4038, + "replacementText": "class GeneratedObjectLiteralClass_9 extends Derived {\n m() { console.log(2); }\n}\n\n" + }, + { + "start": 4055, + "end": 4095, + "replacementText": "new GeneratedObjectLiteralClass_9()" + } + ], "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", "severity": "ERROR" }, { - "line": 170, - "column": 28, - "endLine": 170, - "endColumn": 29, + "line": 229, + "column": 20, + "endLine": 229, + "endColumn": 21, "problem": "ObjectLiteralNoContextType", "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 171, - "column": 13, - "endLine": 171, - "endColumn": 14, + "line": 230, + "column": 3, + "endLine": 230, + "endColumn": 26, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 243, + "column": 20, + "endLine": 243, + "endColumn": 21, "problem": "ObjectLiteralNoContextType", "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" + }, + { + "line": 244, + "column": 3, + "endLine": 244, + "endColumn": 26, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 4443, + "end": 4443, + "replacementText": "class GeneratedObjectLiteralClass_10 extends Derived3 {\n m() { console.log(2); }\n}\n\n" + }, + { + "start": 4462, + "end": 4502, + "replacementText": "new GeneratedObjectLiteralClass_10()" + } + ], + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 187, + "column": 3, + "endLine": 187, + "endColumn": 4, + "problem": "StrictDiagnostic", + "suggest": "Property 'b' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'b' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/object_literals_properties.ets.json b/ets2panda/linter/test/main/object_literals_properties.ets.json index f49a2e6be9..c8d9bf18dc 100644 --- a/ets2panda/linter/test/main/object_literals_properties.ets.json +++ b/ets2panda/linter/test/main/object_literals_properties.ets.json @@ -15,10 +15,30 @@ ], "result": [ { - "line": 23, - "column": 18, - "endLine": 23, - "endColumn": 19, + "line": 17, + "column": 14, + "endLine": 17, + "endColumn": 15, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 17, + "endLine": 21, + "endColumn": 18, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 17, + "endLine": 25, + "endColumn": 18, "problem": "ObjectLiteralNoContextType", "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", @@ -26,42 +46,262 @@ }, { "line": 33, - "column": 18, + "column": 17, "endLine": 33, - "endColumn": 19, + "endColumn": 18, "problem": "ObjectLiteralNoContextType", "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 36, - "column": 6, - "endLine": 36, - "endColumn": 7, + "line": 39, + "column": 14, + "endLine": 39, + "endColumn": 15, "problem": "ObjectLiteralNoContextType", "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 37, + "line": 40, "column": 3, - "endLine": 37, - "endColumn": 4, - "problem": "LiteralAsPropertyName", + "endLine": 40, + "endColumn": 15, + "problem": "SpreadOperator", "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "rule": "It is possible to spread only arrays or classes derived from arrays into the rest parameter or array literals (arkts-no-spread)", "severity": "ERROR" }, { "line": 43, - "column": 3, + "column": 13, "endLine": 43, + "endColumn": 14, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 66, + "column": 16, + "endLine": 66, + "endColumn": 17, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 3, + "endLine": 73, "endColumn": 15, - "problem": "ComputedPropertyName", + "problem": "SpreadOperator", + "suggest": "", + "rule": "It is possible to spread only arrays or classes derived from arrays into the rest parameter or array literals (arkts-no-spread)", + "severity": "ERROR" + }, + { + "line": 80, + "column": 12, + "endLine": 80, + "endColumn": 13, + "problem": "ObjectLiteralNoContextType", "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 91, + "column": 12, + "endLine": 91, + "endColumn": 13, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 98, + "column": 5, + "endLine": 98, + "endColumn": 6, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 109, + "column": 14, + "endLine": 109, + "endColumn": 15, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 116, + "column": 15, + "endLine": 116, + "endColumn": 16, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 121, + "column": 3, + "endLine": 121, + "endColumn": 15, + "problem": "SpreadOperator", + "suggest": "", + "rule": "It is possible to spread only arrays or classes derived from arrays into the rest parameter or array literals (arkts-no-spread)", + "severity": "ERROR" + }, + { + "line": 133, + "column": 14, + "endLine": 133, + "endColumn": 15, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 142, + "column": 25, + "endLine": 142, + "endColumn": 26, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 148, + "column": 29, + "endLine": 148, + "endColumn": 30, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 154, + "column": 20, + "endLine": 154, + "endColumn": 21, + "problem": "ObjectTypeLiteral", + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 155, + "column": 33, + "endLine": 155, + "endColumn": 34, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 156, + "column": 26, + "endLine": 156, + "endColumn": 27, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 161, + "column": 27, + "endLine": 161, + "endColumn": 28, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 168, + "column": 27, + "endLine": 168, + "endColumn": 28, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 180, + "column": 14, + "endLine": 180, + "endColumn": 15, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 198, + "column": 14, + "endLine": 198, + "endColumn": 15, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 219, + "column": 18, + "endLine": 219, + "endColumn": 19, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 229, + "column": 20, + "endLine": 229, + "endColumn": 21, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 243, + "column": 20, + "endLine": 243, + "endColumn": 21, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 187, + "column": 3, + "endLine": 187, + "endColumn": 4, + "problem": "StrictDiagnostic", + "suggest": "Property 'b' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'b' has no initializer and is not definitely assigned in the constructor.", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/main/object_literals_properties.ets.migrate.ets b/ets2panda/linter/test/main/object_literals_properties.ets.migrate.ets new file mode 100644 index 0000000000..1bbf9dbf43 --- /dev/null +++ b/ets2panda/linter/test/main/object_literals_properties.ets.migrate.ets @@ -0,0 +1,307 @@ +/* + * Copyright (c) 2023-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Untyped object literals +class GeneratedObjectLiteralClass_1 { + m() { console.log(1); } // Error, fixable +} + +let method = new GeneratedObjectLiteralClass_1(); + +class GeneratedObjectLiteralClass_2 { + get property() { return 2; } // Error, fixable +} + +let getMethod = new GeneratedObjectLiteralClass_2(); + +class GeneratedObjectLiteralClass_3 { + set property(value: number) { + console.log(value); + } +} + +let setMethod = new GeneratedObjectLiteralClass_3(); + +let x: number = 1, y = '2', z = true; + +interface GeneratedObjectLiteralInterface_1 { + x: number; + y: string; + z: boolean; +} +let shorthand: GeneratedObjectLiteralInterface_1 = { + x: x, // Error, fixable + y: y, // Error, fixable + z: z // Error, fixable +}; + +let spread = { + ...shorthand // Error, not fixable +}; + +class GeneratedObjectLiteralClass_4 { + a: string; + b: number; + c: number[]; + x: number; + y: string; + constructor(init: GeneratedObjectLiteralInitInterface_4) { + this.a = init.a; + this.b = init.b; + this.c = init.c; + this.x = init.x; + this.y = init.y; + } + method() { + console.log(42); + } + get property() { + return 0; + } + set property(value: number) { + if (value < 0) { + throw new Error('Bad value'); + } + } +} + +interface GeneratedObjectLiteralInitInterface_4 { + a: string; + b: number; + c: number[]; + x: number; + y: string; +} + +let mixed = new GeneratedObjectLiteralClass_4({ + a: "foo", + b: 42, + c: [1, 2, 3], + x: x, + y: y +}); + +let x2: number = 1, y2: number = 2, z2: number = 3; +let mixedBad = { // Not fixable + a: 1, + b: 2, + x2: x2, // Error, fixable + y2: y2, // Error, fixable + z2: z2, // Error, fixable + m() {}, + ...shorthand // Error, not fixable +} + +// Typed object literals +interface I { + m(): void; +} +class GeneratedObjectLiteralClass_5 implements I { + m() { + console.log(100); + } +} + +let i: I = new GeneratedObjectLiteralClass_5(); + +class C { + m(): void { + console.log(200); + } +} +class GeneratedObjectLiteralClass_6 extends C { + m(): void { + console.log(300); + } +} + +let c: C = new GeneratedObjectLiteralClass_6(); + +function foo(c: C) {} +class GeneratedObjectLiteralClass_7 extends C { + m() { console.log(300); } // Fixable +} + +foo(new GeneratedObjectLiteralClass_7()); + +class C2 { + x2: number = 10; + y2: number = 20; + z2: number = 30; + + m() {} +} +class GeneratedObjectLiteralClass_8 extends C2 { + x2: number; + y2: number; + z2: number; + constructor(init: GeneratedObjectLiteralInitInterface_1) { + super(); + this.x2 = init.x2; + this.y2 = init.y2; + this.z2 = init.z2; + } + m() { console.log(1); } // Fixable +} + +interface GeneratedObjectLiteralInitInterface_1 { + x2: number; + y2: number; + z2: number; +} + +let c2: C2 = new GeneratedObjectLiteralClass_8({ + x2: x2, + y2: y2, + z2: z2 +}); + +let c22: C2 = { + x2: x2, // Fixable + y2: y2, // Fixable + z2: z2, // Fixable + m() { console.log(1); }, // Not fixable, object has spread property + ...shorthand // Not fixable +}; + +class C3 { + x2: number = 10; + y2: number = 20; + z2: number = 30; + + m() {} + + constructor(a: number) {} +} +let c3: C3 = { + x2: x2, // Fixable + y2: y2, // Fixable + z2: z2, // Fixable + m() { console.log(1); } // Not fixable, class type has constructor with parameters +}; + +function capturesFromLocalScope() { + let a: number = 1, b: number = 2; + let captureLocalVal = { + m() { // Not fixable, captures local values 'a' and 'b' + console.log(a, b); + } + }; + + let captureLocalVal2: C = { + m(): void { // Not fixable, captures local values 'a' and 'b' + console.log(a, b); + } + }; + + interface LocalType { + a: number; + b: string; +} + let localTypeVar: LocalType = { a: 1, b: '2' }; + let captureLocalType = { + m() { // Not fixable, captures value of type `LocalType` declared in local scope + console.log(localTypeVar); + } + }; + let captureLocalType2 = { + m(x: LocalType) { // Not fixable, `x` references type `LocalType` declared in local scope + console.log(x); + } + }; + + class LocalClass { x: number = 1 }; + let captureLocalType3 = { + m() { // Not fixable, references type `LocalClass` declared in local scope + console.log(new LocalClass()); + } + }; +} + +// Method overriding field +class C4 { + a: number = 0; + b() {}; +} +let c4: C4 = { // Not fixable, overrides class method with property of functional type + a: 1, + b: () => {} +}; + +class C5 { + a: number = 0; + b: () => void; +} +let c5: C5 = { // Not fixable, overrides class property with method + a: 1, + b() {} +}; + +interface I2 { + a: number; + b(): void; +} +let i2: I2 = { // Not fixable, implements method as functional-type property + a: 1, + b: () => {} +}; + +interface I3 { + a: number; + b: () => void; +} +let ii: I3 = { // Not fixable, implements functional-type property as a method + a: 1, + b() {} +}; + +// Inheritance +class Base { + constructor() {} +} +class Derived extends Base { + m() {} +} +class GeneratedObjectLiteralClass_9 extends Derived { + m() { console.log(2); } +} + +let b: Derived = new GeneratedObjectLiteralClass_9(); + +class Base2 { + constructor(a: number) {} +} +class Derived2 extends Base2 { + m() {} +} +let b2: Derived2 = { // Not fixable, derived class inherits a constructor with parameters from base class + m() { console.log(2); } +}; + +class Base3 { + constructor(a: number) {} +} +class Derived3 extends Base3 { + m() {} + + constructor() { + super(1); + } +} +class GeneratedObjectLiteralClass_10 extends Derived3 { + m() { console.log(2); } +} + +let b3: Derived3 = new GeneratedObjectLiteralClass_10(); \ No newline at end of file diff --git a/ets2panda/linter/test/main/object_literals_properties.ets.migrate.json b/ets2panda/linter/test/main/object_literals_properties.ets.migrate.json new file mode 100644 index 0000000000..05c3a0ea0a --- /dev/null +++ b/ets2panda/linter/test/main/object_literals_properties.ets.migrate.json @@ -0,0 +1,318 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 50, + "column": 14, + "endLine": 50, + "endColumn": 15, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 51, + "column": 3, + "endLine": 51, + "endColumn": 15, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 51, + "column": 3, + "endLine": 51, + "endColumn": 15, + "problem": "SpreadOperator", + "suggest": "", + "rule": "It is possible to spread only arrays or classes derived from arrays into the rest parameter or array literals (arkts-no-spread)", + "severity": "ERROR" + }, + { + "line": 97, + "column": 16, + "endLine": 97, + "endColumn": 17, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 103, + "column": 3, + "endLine": 103, + "endColumn": 9, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 104, + "column": 3, + "endLine": 104, + "endColumn": 15, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 104, + "column": 3, + "endLine": 104, + "endColumn": 15, + "problem": "SpreadOperator", + "suggest": "", + "rule": "It is possible to spread only arrays or classes derived from arrays into the rest parameter or array literals (arkts-no-spread)", + "severity": "ERROR" + }, + { + "line": 171, + "column": 15, + "endLine": 171, + "endColumn": 16, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 175, + "column": 3, + "endLine": 175, + "endColumn": 26, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 176, + "column": 3, + "endLine": 176, + "endColumn": 15, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 176, + "column": 3, + "endLine": 176, + "endColumn": 15, + "problem": "SpreadOperator", + "suggest": "", + "rule": "It is possible to spread only arrays or classes derived from arrays into the rest parameter or array literals (arkts-no-spread)", + "severity": "ERROR" + }, + { + "line": 188, + "column": 14, + "endLine": 188, + "endColumn": 15, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 192, + "column": 3, + "endLine": 192, + "endColumn": 26, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 197, + "column": 25, + "endLine": 197, + "endColumn": 26, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 198, + "column": 5, + "endLine": 200, + "endColumn": 6, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 203, + "column": 29, + "endLine": 203, + "endColumn": 30, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 204, + "column": 5, + "endLine": 206, + "endColumn": 6, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 214, + "column": 26, + "endLine": 214, + "endColumn": 27, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 215, + "column": 5, + "endLine": 217, + "endColumn": 6, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 219, + "column": 27, + "endLine": 219, + "endColumn": 28, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 220, + "column": 5, + "endLine": 222, + "endColumn": 6, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 226, + "column": 27, + "endLine": 226, + "endColumn": 28, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 227, + "column": 5, + "endLine": 229, + "endColumn": 6, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 238, + "column": 14, + "endLine": 238, + "endColumn": 15, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 249, + "column": 3, + "endLine": 249, + "endColumn": 9, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 256, + "column": 14, + "endLine": 256, + "endColumn": 15, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 267, + "column": 3, + "endLine": 267, + "endColumn": 9, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 289, + "column": 20, + "endLine": 289, + "endColumn": 21, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 290, + "column": 3, + "endLine": 290, + "endColumn": 26, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 245, + "column": 3, + "endLine": 245, + "endColumn": 4, + "problem": "StrictDiagnostic", + "suggest": "Property 'b' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'b' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/object_spread.ets.args.json b/ets2panda/linter/test/main/object_spread.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/main/object_spread.ets.args.json +++ b/ets2panda/linter/test/main/object_spread.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/main/object_spread.ets.migrate.ets b/ets2panda/linter/test/main/object_spread.ets.migrate.ets new file mode 100644 index 0000000000..0925345ec7 --- /dev/null +++ b/ets2panda/linter/test/main/object_spread.ets.migrate.ets @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2023-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +interface GeneratedObjectLiteralInterface_1 { + x: number; + y: number; +} +const pt2D: GeneratedObjectLiteralInterface_1 = { x: 1, y: 2 }; + +console.log(pt2D); + +const pt3D = { ...pt2D, z: 3 }; + +console.log(pt3D); diff --git a/ets2panda/linter/test/main/object_spread.ets.migrate.json b/ets2panda/linter/test/main/object_spread.ets.migrate.json new file mode 100644 index 0000000000..b1bad3882f --- /dev/null +++ b/ets2panda/linter/test/main/object_spread.ets.migrate.json @@ -0,0 +1,38 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 24, + "column": 14, + "endLine": 24, + "endColumn": 15, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 16, + "endLine": 24, + "endColumn": 23, + "problem": "SpreadOperator", + "suggest": "", + "rule": "It is possible to spread only arrays or classes derived from arrays into the rest parameter or array literals (arkts-no-spread)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/oh_modules/@arkts.collections.d.ets b/ets2panda/linter/test/main/oh_modules/@arkts.collections.d.ets new file mode 100644 index 0000000000..f54a1fd4d6 --- /dev/null +++ b/ets2panda/linter/test/main/oh_modules/@arkts.collections.d.ets @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export namespace collections { + export class Array implements ConcatArray { + constructor(); + } + + export class Map { + constructor(entries?: readonly (readonly [K, V])[] | null); + } + + export interface ConcatArray { + + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/oh_modules/@arkts.utils.d.ets b/ets2panda/linter/test/main/oh_modules/@arkts.utils.d.ets new file mode 100644 index 0000000000..df91841374 --- /dev/null +++ b/ets2panda/linter/test/main/oh_modules/@arkts.utils.d.ets @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export namespace utils { + namespace ASON { + function stringify(value: Object | null | undefined): string; + } +} + +export default utils; \ No newline at end of file diff --git a/ets2panda/linter/test/main/oh_modules/@kit.ArkTS.d.ets b/ets2panda/linter/test/main/oh_modules/@kit.ArkTS.d.ets new file mode 100644 index 0000000000..dd994ead62 --- /dev/null +++ b/ets2panda/linter/test/main/oh_modules/@kit.ArkTS.d.ets @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { worker } from '../oh_modules/@ohos.worker'; +export { collections } from '../oh_modules/@arkts.collections'; +export { utils } from '../oh_modules/@arkts.utils'; +export { taskpool } from '../oh_modules/@ohos.taskpool'; \ No newline at end of file diff --git a/ets2panda/linter/test/interop/oh_modules/reflect_export_safe.ets b/ets2panda/linter/test/main/oh_modules/@ohos.taskpool.d.ets similarity index 80% rename from ets2panda/linter/test/interop/oh_modules/reflect_export_safe.ets rename to ets2panda/linter/test/main/oh_modules/@ohos.taskpool.d.ets index 64ac6ea76a..f727b78f7a 100644 --- a/ets2panda/linter/test/interop/oh_modules/reflect_export_safe.ets +++ b/ets2panda/linter/test/main/oh_modules/@ohos.taskpool.d.ets @@ -13,8 +13,6 @@ * limitations under the License. */ -export function safeVersion(prx: Object) { - Reflect.get(prx, 'a') // 'hello' - Reflect.set(prx, 'a', 'world') // true - Reflect.ownKeys(prx) // ['a'] +export namespace taskpool { + export const isConcurrent: () => boolean; } \ No newline at end of file diff --git a/ets2panda/linter/test/main/oh_modules/@ohos.worker.d.ets b/ets2panda/linter/test/main/oh_modules/@ohos.worker.d.ets new file mode 100644 index 0000000000..74748df41d --- /dev/null +++ b/ets2panda/linter/test/main/oh_modules/@ohos.worker.d.ets @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export namespace worker { + export class ThreadWorker { + constructor(scriptURL: string, options?: WorkerOptions); + postMessage(message: any, transfer?: Transferable[]): void; + terminate(): void; + on(type: string, listener: (data: any) => void): void; + } + + export interface WorkerOptions { + type?: "classic" | "module"; + name?: string; + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/parameter_properties.ets.args.json b/ets2panda/linter/test/main/parameter_properties.ets.args.json index 4e9dc628f7..571ee6bb76 100644 --- a/ets2panda/linter/test/main/parameter_properties.ets.args.json +++ b/ets2panda/linter/test/main/parameter_properties.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } diff --git a/ets2panda/linter/test/main/parameter_properties.ets.migrate.ets b/ets2panda/linter/test/main/parameter_properties.ets.migrate.ets new file mode 100644 index 0000000000..6a79a113c4 --- /dev/null +++ b/ets2panda/linter/test/main/parameter_properties.ets.migrate.ets @@ -0,0 +1,147 @@ +/* + * Copyright (c) 2023-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class A { + public readonly x: number; +protected y: number; +private z: number; +constructor( + x: number, + y: number, + z: number + ) { + this.x = x; + this.y = y; + this.z = z; +} + + foo(): void { + console.log(this.x + this.y + this.z); + } +} + +const a = new A(1, 2, 3); +console.log(a.x); + +class B { + public f: number = 10; + + public w: string; +private readonly r: number[]; +constructor(q: number, w = 'default', e: boolean, r: number[] = [1, 2, 3]) { + this.w = w; + this.r = r; + console.log(q, this.w, e, this.r, this.f); +} +} + +const b = new B(1, '2', true, []); +console.log(b.w); + +class C { + constructor(public a: any) {} // not fixable +} + +interface GeneratedTypeLiteralInterface_1 { + x: string; +} +class D { + public a: number; +private b: GeneratedTypeLiteralInterface_1; +constructor(a: number, b: GeneratedTypeLiteralInterface_1) { + this.a = a; + this.b = b; +} // not fixable +} + +class E { + b: number = 0; + c: number = 0; + + readonly a: number; +constructor(a: number) { + this.a = a; +} +} + +class F extends E { + readonly aa: number; +b: number; +public c: number; +constructor( + aa: number, + b: number, + c: number + ){ + super(aa); + this.aa = aa; + this.b = b; + this.c = c; +} +} + +class F2 extends E { + readonly aa: number; +constructor(aa: number) { + let f2: number = 1; + console.log('before super() call'); + super(aa); + this.aa = aa; +} +} + +class F3 extends E { + readonly aa: number; +constructor(aa: number) { + super(aa); + this.aa = aa; + let f3: number = 1; + console.log('after super() call'); +} +} + +class F4 extends E { + readonly aa: number; +constructor(aa: number) { + let f4: number = 1; + console.log('before super() call'); + super(aa); + this.aa = aa; + console.log('after super() call'); + let f5: number = 1; +} +} + +class G { + constructor(a?: number) {} +} + +class G1 { + public a?: number; +public b: number; +constructor(a?: number, b: number) { + this.a = a; + this.b = b; +} +} + +class G2 { + public a?: number; +public b?: number; +constructor(a?: number, b?: number) { + this.a = a; + this.b = b; +} +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/parameter_properties.ets.migrate.json b/ets2panda/linter/test/main/parameter_properties.ets.migrate.json new file mode 100644 index 0000000000..03cac9f4e4 --- /dev/null +++ b/ets2panda/linter/test/main/parameter_properties.ets.migrate.json @@ -0,0 +1,38 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 54, + "column": 15, + "endLine": 54, + "endColumn": 21, + "problem": "ParameterProperties", + "suggest": "", + "rule": "Declaring fields in \"constructor\" is not supported (arkts-no-ctor-prop-decls)", + "severity": "ERROR" + }, + { + "line": 54, + "column": 25, + "endLine": 54, + "endColumn": 28, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/private_identifiers.ets.args.json b/ets2panda/linter/test/main/private_identifiers.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/main/private_identifiers.ets.args.json +++ b/ets2panda/linter/test/main/private_identifiers.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/main/private_identifiers.ets.migrate.ets b/ets2panda/linter/test/main/private_identifiers.ets.migrate.ets new file mode 100644 index 0000000000..001beccf21 --- /dev/null +++ b/ets2panda/linter/test/main/private_identifiers.ets.migrate.ets @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class C { + private p: number; + + p2: number; + #p2: string; // not fixable + + private q?: string; + private e!: string; + private static s = 0; + private readonly r = 20; + private static readonly sr = 0; + private static readonly srq?: string; + + private m(x: number): void { } + + m2(x: number): void {} + #m2(x: number): void {} // not fixable + + m3: boolean; + #m3(x: number): void {} // not fixable + + private get g1(): number { return 10; } + private set s1(x: number) { } + + private static get g2(): number { return 10; } + private static set s2(x: number) { } + + test() { + console.log(this.p + this.#p2 + this.q + this.e + C.s + this.r + C.sr + C.srq); // '#p2' is not fixable + this.m(10); + this.#m2(20); // not fixable + this.#m3(30); // not fixable + let x = this.g1; + this.s1 = x; + let y = C.g2; + C.s2 = y; + } +} + +class D extends C { + private a: string; + #p: number; // not fixable + + #m(): string { return 'foo'; } // not fixable + + private bar(): string { return 'baz'; } + + test() { + console.log(this.#p + this.a); // '#p' is not fixable + let x = this.#m(); // not fixable + let y = this.bar(); + } +} + +class E { + private a: number; + #b: string; // not fixable + + public b: number; +constructor(b: number) { + this.b = b; +} +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/private_identifiers.ets.migrate.json b/ets2panda/linter/test/main/private_identifiers.ets.migrate.json new file mode 100644 index 0000000000..4b6bcee720 --- /dev/null +++ b/ets2panda/linter/test/main/private_identifiers.ets.migrate.json @@ -0,0 +1,318 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 19, + "column": 3, + "endLine": 19, + "endColumn": 5, + "problem": "DeclWithDuplicateName", + "suggest": "", + "rule": "Use unique names for types and namespaces. (arkts-unique-names)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 3, + "endLine": 20, + "endColumn": 6, + "problem": "DeclWithDuplicateName", + "suggest": "", + "rule": "Use unique names for types and namespaces. (arkts-unique-names)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 3, + "endLine": 31, + "endColumn": 5, + "problem": "DeclWithDuplicateName", + "suggest": "", + "rule": "Use unique names for types and namespaces. (arkts-unique-names)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 3, + "endLine": 32, + "endColumn": 6, + "problem": "DeclWithDuplicateName", + "suggest": "", + "rule": "Use unique names for types and namespaces. (arkts-unique-names)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 3, + "endLine": 34, + "endColumn": 5, + "problem": "DeclWithDuplicateName", + "suggest": "", + "rule": "Use unique names for types and namespaces. (arkts-unique-names)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 3, + "endLine": 35, + "endColumn": 6, + "problem": "DeclWithDuplicateName", + "suggest": "", + "rule": "Use unique names for types and namespaces. (arkts-unique-names)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 3, + "endLine": 20, + "endColumn": 6, + "problem": "PrivateIdentifier", + "suggest": "", + "rule": "Private \"#\" identifiers are not supported (arkts-no-private-identifiers)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 3, + "endLine": 23, + "endColumn": 22, + "problem": "DefiniteAssignment", + "suggest": "", + "rule": "Definite assignment assertions are not supported (arkts-no-definite-assignment)", + "severity": "WARNING" + }, + { + "line": 32, + "column": 3, + "endLine": 32, + "endColumn": 6, + "problem": "PrivateIdentifier", + "suggest": "", + "rule": "Private \"#\" identifiers are not supported (arkts-no-private-identifiers)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 3, + "endLine": 35, + "endColumn": 6, + "problem": "PrivateIdentifier", + "suggest": "", + "rule": "Private \"#\" identifiers are not supported (arkts-no-private-identifiers)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 31, + "endLine": 44, + "endColumn": 34, + "problem": "PrivateIdentifier", + "suggest": "", + "rule": "Private \"#\" identifiers are not supported (arkts-no-private-identifiers)", + "severity": "ERROR" + }, + { + "line": 46, + "column": 10, + "endLine": 46, + "endColumn": 13, + "problem": "PrivateIdentifier", + "suggest": "", + "rule": "Private \"#\" identifiers are not supported (arkts-no-private-identifiers)", + "severity": "ERROR" + }, + { + "line": 47, + "column": 10, + "endLine": 47, + "endColumn": 13, + "problem": "PrivateIdentifier", + "suggest": "", + "rule": "Private \"#\" identifiers are not supported (arkts-no-private-identifiers)", + "severity": "ERROR" + }, + { + "line": 57, + "column": 3, + "endLine": 57, + "endColumn": 5, + "problem": "DeclWithDuplicateName", + "suggest": "", + "rule": "Use unique names for types and namespaces. (arkts-unique-names)", + "severity": "ERROR" + }, + { + "line": 59, + "column": 3, + "endLine": 59, + "endColumn": 5, + "problem": "DeclWithDuplicateName", + "suggest": "", + "rule": "Use unique names for types and namespaces. (arkts-unique-names)", + "severity": "ERROR" + }, + { + "line": 57, + "column": 3, + "endLine": 57, + "endColumn": 5, + "problem": "PrivateIdentifier", + "suggest": "", + "rule": "Private \"#\" identifiers are not supported (arkts-no-private-identifiers)", + "severity": "ERROR" + }, + { + "line": 59, + "column": 3, + "endLine": 59, + "endColumn": 5, + "problem": "PrivateIdentifier", + "suggest": "", + "rule": "Private \"#\" identifiers are not supported (arkts-no-private-identifiers)", + "severity": "ERROR" + }, + { + "line": 64, + "column": 22, + "endLine": 64, + "endColumn": 24, + "problem": "PrivateIdentifier", + "suggest": "", + "rule": "Private \"#\" identifiers are not supported (arkts-no-private-identifiers)", + "severity": "ERROR" + }, + { + "line": 65, + "column": 18, + "endLine": 65, + "endColumn": 20, + "problem": "PrivateIdentifier", + "suggest": "", + "rule": "Private \"#\" identifiers are not supported (arkts-no-private-identifiers)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 3, + "endLine": 72, + "endColumn": 5, + "problem": "DeclWithDuplicateName", + "suggest": "", + "rule": "Use unique names for types and namespaces. (arkts-unique-names)", + "severity": "ERROR" + }, + { + "line": 74, + "column": 10, + "endLine": 74, + "endColumn": 11, + "problem": "DeclWithDuplicateName", + "suggest": "", + "rule": "Use unique names for types and namespaces. (arkts-unique-names)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 3, + "endLine": 72, + "endColumn": 5, + "problem": "PrivateIdentifier", + "suggest": "", + "rule": "Private \"#\" identifiers are not supported (arkts-no-private-identifiers)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 11, + "endLine": 17, + "endColumn": 12, + "problem": "StrictDiagnostic", + "suggest": "Property 'p' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'p' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 19, + "column": 3, + "endLine": 19, + "endColumn": 5, + "problem": "StrictDiagnostic", + "suggest": "Property 'p2' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'p2' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 20, + "column": 3, + "endLine": 20, + "endColumn": 6, + "problem": "StrictDiagnostic", + "suggest": "Property '#p2' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property '#p2' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 34, + "column": 3, + "endLine": 34, + "endColumn": 5, + "problem": "StrictDiagnostic", + "suggest": "Property 'm3' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'm3' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 56, + "column": 11, + "endLine": 56, + "endColumn": 12, + "problem": "StrictDiagnostic", + "suggest": "Property 'a' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'a' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 57, + "column": 3, + "endLine": 57, + "endColumn": 5, + "problem": "StrictDiagnostic", + "suggest": "Property '#p' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property '#p' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 71, + "column": 11, + "endLine": 71, + "endColumn": 12, + "problem": "StrictDiagnostic", + "suggest": "Property 'a' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'a' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 72, + "column": 3, + "endLine": 72, + "endColumn": 5, + "problem": "StrictDiagnostic", + "suggest": "Property '#b' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property '#b' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets b/ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets new file mode 100644 index 0000000000..7f83645b5e --- /dev/null +++ b/ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class User { + name: string = "" + age: number = 0 +} + +@Entry +@Component +struct FatherComponent { + @Prop user1: User = new User() + @StorageLink("user2") user2: User = new User() + @LocalStorageLink("user3") user3: User = new User() + + build() { + } +} + +@Component +struct ChildComponent { + @StorageProp("user2") user2: User = new User() + @LocalStorageProp("user3") user3: User = new User() + + build() { + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets.args.json b/ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets.args.json new file mode 100644 index 0000000000..4acc088d1d --- /dev/null +++ b/ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets.arkts2.json b/ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets.arkts2.json new file mode 100644 index 0000000000..eda4a3c782 --- /dev/null +++ b/ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets.arkts2.json @@ -0,0 +1,128 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 24, + "column": 3, + "endLine": 24, + "endColumn": 33, + "problem": "PropDecoratorsAndInterfacesAreNotSupported", + "suggest": "", + "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 3, + "endLine": 34, + "endColumn": 49, + "problem": "PropDecoratorsAndInterfacesAreNotSupported", + "suggest": "", + "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 3, + "endLine": 35, + "endColumn": 54, + "problem": "PropDecoratorsAndInterfacesAreNotSupported", + "suggest": "", + "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 2, + "endLine": 21, + "endColumn": 7, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 2, + "endLine": 22, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 4, + "endLine": 24, + "endColumn": 8, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 4, + "endLine": 25, + "endColumn": 15, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 4, + "endLine": 26, + "endColumn": 20, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 2, + "endLine": 32, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 4, + "endLine": 34, + "endColumn": 15, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 4, + "endLine": 35, + "endColumn": 20, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets.json b/ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets b/ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets new file mode 100644 index 0000000000..f218bde1db --- /dev/null +++ b/ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class MyClassA { + +} + +let para: Record = { 'PropA': 47 } +let storage: LocalStorage = new LocalStorage(para) +let prop1 = storage.prop('PropA') +let prop2 = storage.prop('PropA') +let prop3 = storage.prop('PropA') +let prop4: SubscribedAbstractProperty = storage.prop('PropA') +let prop5: SubscribedAbstractProperty = storage.prop('PropA') +let prop6: SubscribedAbstractProperty = storage.prop('PropA') + +AppStorage.SetOrCreate('PropB', 46) +let prop7 = AppStorage.prop('PropB') +let prop8 = AppStorage.prop('PropB') +let prop9 = AppStorage.prop('PropB') +let prop10: SubscribedAbstractProperty = AppStorage.prop('PropB') +let prop11: SubscribedAbstractProperty = AppStorage.prop('PropB') +let prop12: SubscribedAbstractProperty = AppStorage.prop('PropB') + +@Entry +@Component +struct MyComponent { + + aboutToAppear(): void { + let storage = LocalStorage.getShared() + let prop1 = storage.prop('PropA') + let prop2: SubscribedAbstractProperty = storage.prop('PropA') + } + + build() { + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets.args.json b/ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets.args.json new file mode 100644 index 0000000000..4acc088d1d --- /dev/null +++ b/ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets.arkts2.json b/ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets.arkts2.json new file mode 100644 index 0000000000..a34c537148 --- /dev/null +++ b/ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets.arkts2.json @@ -0,0 +1,448 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 21, + "column": 33, + "endLine": 21, + "endColumn": 45, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 5, + "endLine": 22, + "endColumn": 42, + "problem": "PropDecoratorsAndInterfacesAreNotSupported", + "suggest": "", + "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 5, + "endLine": 22, + "endColumn": 42, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 5, + "endLine": 23, + "endColumn": 44, + "problem": "PropDecoratorsAndInterfacesAreNotSupported", + "suggest": "", + "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 5, + "endLine": 23, + "endColumn": 44, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 5, + "endLine": 24, + "endColumn": 53, + "problem": "PropDecoratorsAndInterfacesAreNotSupported", + "suggest": "", + "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 5, + "endLine": 24, + "endColumn": 53, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 5, + "endLine": 25, + "endColumn": 70, + "problem": "PropDecoratorsAndInterfacesAreNotSupported", + "suggest": "", + "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 5, + "endLine": 26, + "endColumn": 72, + "problem": "PropDecoratorsAndInterfacesAreNotSupported", + "suggest": "", + "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 5, + "endLine": 27, + "endColumn": 81, + "problem": "PropDecoratorsAndInterfacesAreNotSupported", + "suggest": "", + "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 5, + "endLine": 30, + "endColumn": 45, + "problem": "PropDecoratorsAndInterfacesAreNotSupported", + "suggest": "", + "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 5, + "endLine": 30, + "endColumn": 45, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 13, + "endLine": 30, + "endColumn": 45, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 5, + "endLine": 31, + "endColumn": 47, + "problem": "PropDecoratorsAndInterfacesAreNotSupported", + "suggest": "", + "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 5, + "endLine": 31, + "endColumn": 47, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 5, + "endLine": 32, + "endColumn": 56, + "problem": "PropDecoratorsAndInterfacesAreNotSupported", + "suggest": "", + "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 5, + "endLine": 32, + "endColumn": 56, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 5, + "endLine": 33, + "endColumn": 74, + "problem": "PropDecoratorsAndInterfacesAreNotSupported", + "suggest": "", + "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 5, + "endLine": 34, + "endColumn": 76, + "problem": "PropDecoratorsAndInterfacesAreNotSupported", + "suggest": "", + "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 5, + "endLine": 35, + "endColumn": 85, + "problem": "PropDecoratorsAndInterfacesAreNotSupported", + "suggest": "", + "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", + "severity": "ERROR" + }, + { + "line": 42, + "column": 13, + "endLine": 42, + "endColumn": 47, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 43, + "column": 13, + "endLine": 43, + "endColumn": 52, + "problem": "PropDecoratorsAndInterfacesAreNotSupported", + "suggest": "", + "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", + "severity": "ERROR" + }, + { + "line": 43, + "column": 13, + "endLine": 43, + "endColumn": 52, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 13, + "endLine": 44, + "endColumn": 80, + "problem": "PropDecoratorsAndInterfacesAreNotSupported", + "suggest": "", + "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 14, + "endLine": 21, + "endColumn": 26, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 33, + "endLine": 21, + "endColumn": 45, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 12, + "endLine": 25, + "endColumn": 38, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 12, + "endLine": 26, + "endColumn": 38, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 12, + "endLine": 27, + "endColumn": 38, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 1, + "endLine": 29, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 13, + "endLine": 30, + "endColumn": 23, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 13, + "endLine": 31, + "endColumn": 23, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 13, + "endLine": 32, + "endColumn": 23, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 13, + "endLine": 33, + "endColumn": 39, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 50, + "endLine": 33, + "endColumn": 60, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 13, + "endLine": 34, + "endColumn": 39, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 52, + "endLine": 34, + "endColumn": 62, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 13, + "endLine": 35, + "endColumn": 39, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 61, + "endLine": 35, + "endColumn": 71, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 2, + "endLine": 37, + "endColumn": 7, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 2, + "endLine": 38, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 42, + "column": 23, + "endLine": 42, + "endColumn": 35, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 20, + "endLine": 44, + "endColumn": 46, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets.json b/ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets.json new file mode 100644 index 0000000000..897276b6eb --- /dev/null +++ b/ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets.json @@ -0,0 +1,98 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 22, + "column": 5, + "endLine": 22, + "endColumn": 42, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 5, + "endLine": 23, + "endColumn": 44, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 5, + "endLine": 24, + "endColumn": 53, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 5, + "endLine": 30, + "endColumn": 45, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 5, + "endLine": 31, + "endColumn": 47, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 5, + "endLine": 32, + "endColumn": 56, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 42, + "column": 13, + "endLine": 42, + "endColumn": 47, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 43, + "column": 13, + "endLine": 43, + "endColumn": 52, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets b/ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets new file mode 100644 index 0000000000..5a75d8e00d --- /dev/null +++ b/ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */1q + +class MyClassA { + +} + +class MyClassB { + +} + +function getClass1 { + let a = new MyClassA() + + if (1 > 0) { + return new MyClassB() + } else { + return a + } +} + +function getClass2 { + if (1 > 0) { + return 1 + } else { + return new MyClassA() + } +} + +let para: Record = { 'PropA': 47 } +let storage: LocalStorage = new LocalStorage(para) +let prop1 = storage.setAndProp('PropA', getClass1()) +let prop2 = storage.setAndProp('PropA', getClass2()) +let prop3 = storage.setAndProp('PropA', {name: "jack", age: 2}) +let prop4 = storage.setAndProp('PropA', 1 > 0 ? 1 : getClass1()) +let prop5 = storage.setAndProp('PropA', 1 > 0 ? {name: "jack"} : "test") +let prop6 = storage.setAndProp('PropA', new MyClassA()) +let prop7 = storage.setAndProp('PropA', 1) +let prop8 = storage.setAndProp('PropA', "test") +let prop9 = storage.setAndProp('PropA', true) + +@Entry +@Component +struct MyComponent { + build() { + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets.args.json b/ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets.args.json new file mode 100644 index 0000000000..4acc088d1d --- /dev/null +++ b/ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets.arkts2.json b/ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets.arkts2.json new file mode 100644 index 0000000000..aae50874a9 --- /dev/null +++ b/ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets.arkts2.json @@ -0,0 +1,248 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 43, + "column": 33, + "endLine": 43, + "endColumn": 45, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 5, + "endLine": 44, + "endColumn": 53, + "problem": "PropDecoratorsAndInterfacesAreNotSupported", + "suggest": "", + "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 5, + "endLine": 44, + "endColumn": 53, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 5, + "endLine": 45, + "endColumn": 53, + "problem": "PropDecoratorsAndInterfacesAreNotSupported", + "suggest": "", + "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 5, + "endLine": 45, + "endColumn": 53, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 46, + "column": 5, + "endLine": 46, + "endColumn": 64, + "problem": "PropDecoratorsAndInterfacesAreNotSupported", + "suggest": "", + "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", + "severity": "ERROR" + }, + { + "line": 46, + "column": 5, + "endLine": 46, + "endColumn": 64, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 47, + "column": 5, + "endLine": 47, + "endColumn": 65, + "problem": "PropDecoratorsAndInterfacesAreNotSupported", + "suggest": "", + "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", + "severity": "ERROR" + }, + { + "line": 47, + "column": 5, + "endLine": 47, + "endColumn": 65, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 48, + "column": 5, + "endLine": 48, + "endColumn": 73, + "problem": "PropDecoratorsAndInterfacesAreNotSupported", + "suggest": "", + "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", + "severity": "ERROR" + }, + { + "line": 48, + "column": 5, + "endLine": 48, + "endColumn": 73, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 5, + "endLine": 49, + "endColumn": 56, + "problem": "PropDecoratorsAndInterfacesAreNotSupported", + "suggest": "", + "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 5, + "endLine": 49, + "endColumn": 56, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 50, + "column": 5, + "endLine": 50, + "endColumn": 43, + "problem": "PropDecoratorsAndInterfacesAreNotSupported", + "suggest": "", + "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", + "severity": "ERROR" + }, + { + "line": 50, + "column": 5, + "endLine": 50, + "endColumn": 43, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 51, + "column": 5, + "endLine": 51, + "endColumn": 48, + "problem": "PropDecoratorsAndInterfacesAreNotSupported", + "suggest": "", + "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", + "severity": "ERROR" + }, + { + "line": 51, + "column": 5, + "endLine": 51, + "endColumn": 48, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 52, + "column": 5, + "endLine": 52, + "endColumn": 46, + "problem": "PropDecoratorsAndInterfacesAreNotSupported", + "suggest": "", + "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", + "severity": "ERROR" + }, + { + "line": 52, + "column": 5, + "endLine": 52, + "endColumn": 46, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 43, + "column": 14, + "endLine": 43, + "endColumn": 26, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 43, + "column": 33, + "endLine": 43, + "endColumn": 45, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 54, + "column": 2, + "endLine": 54, + "endColumn": 7, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 55, + "column": 2, + "endLine": 55, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets.json b/ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets.json new file mode 100644 index 0000000000..de7a4258a1 --- /dev/null +++ b/ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets.json @@ -0,0 +1,108 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 44, + "column": 5, + "endLine": 44, + "endColumn": 53, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 5, + "endLine": 45, + "endColumn": 53, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 46, + "column": 5, + "endLine": 46, + "endColumn": 64, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 47, + "column": 5, + "endLine": 47, + "endColumn": 65, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 48, + "column": 5, + "endLine": 48, + "endColumn": 73, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 5, + "endLine": 49, + "endColumn": 56, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 50, + "column": 5, + "endLine": 50, + "endColumn": 43, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 51, + "column": 5, + "endLine": 51, + "endColumn": 48, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 52, + "column": 5, + "endLine": 52, + "endColumn": 46, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_name_from_value.ets b/ets2panda/linter/test/main/prop_name_from_value.ets new file mode 100644 index 0000000000..bdfdc1a80d --- /dev/null +++ b/ets2panda/linter/test/main/prop_name_from_value.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +enum TEST { + A, + B, + C +} +const arr = ['a', 'b', 'c']; + +const val = TEST[1]; +const value: number = TEST.A; //legal +const arrVal = arr[1]; //legal \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_name_from_value.ets.args.json b/ets2panda/linter/test/main/prop_name_from_value.ets.args.json new file mode 100644 index 0000000000..66fb88f859 --- /dev/null +++ b/ets2panda/linter/test/main/prop_name_from_value.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} diff --git a/ets2panda/linter/test/migrate/class_static_block.ts.json b/ets2panda/linter/test/main/prop_name_from_value.ets.arkts2.json similarity index 73% rename from ets2panda/linter/test/migrate/class_static_block.ts.json rename to ets2panda/linter/test/main/prop_name_from_value.ets.arkts2.json index 487f1000c4..4218268d31 100644 --- a/ets2panda/linter/test/migrate/class_static_block.ts.json +++ b/ets2panda/linter/test/main/prop_name_from_value.ets.arkts2.json @@ -1,10 +1,12 @@ { "copyright": [ - "Copyright (c) 2022-2024 Huawei Device Co., Ltd.", + "Copyright (c) 2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", + "", "http://www.apache.org/licenses/LICENSE-2.0", + "", "Unless required by applicable law or agreed to in writing, software", "distributed under the License is distributed on an 'AS IS' BASIS,", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", @@ -14,12 +16,12 @@ "result": [ { "line": 23, - "column": 3, + "column": 13, "endLine": 23, - "endColumn": 9, - "problem": "MultipleStaticBlocks", + "endColumn": 20, + "problem": "UnsupportPropNameFromValue", "suggest": "", - "rule": "Only one static block is supported (arkts-no-multiple-static-blocks)", + "rule": "Enum cannot get member name by member value (arkts-unsupport-prop-name-from-value)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/main/prop_name_from_value.ets.json b/ets2panda/linter/test/main/prop_name_from_value.ets.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/prop_name_from_value.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/property_access_by_index.ets.args.json b/ets2panda/linter/test/main/property_access_by_index.ets.args.json index a830284339..7341e330fa 100644 --- a/ets2panda/linter/test/main/property_access_by_index.ets.args.json +++ b/ets2panda/linter/test/main/property_access_by_index.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -15,6 +15,7 @@ ], "mode": { "autofix": "", - "arkts2": "" + "arkts2": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/main/property_access_by_index.ets.arkts2.json b/ets2panda/linter/test/main/property_access_by_index.ets.arkts2.json index 7fd2c9eac2..ea96b93ba8 100644 --- a/ets2panda/linter/test/main/property_access_by_index.ets.arkts2.json +++ b/ets2panda/linter/test/main/property_access_by_index.ets.arkts2.json @@ -14,6 +14,16 @@ "limitations under the License." ], "result": [ + { + "line": 16, + "column": 10, + "endLine": 16, + "endColumn": 21, + "problem": "NoNeedStdLibSendableContainer", + "suggest": "", + "rule": "Sendable containers are not supported (arkts-no-need-stdlib-sendable-containers)", + "severity": "ERROR" + }, { "line": 22, "column": 3, @@ -134,6 +144,16 @@ "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", "severity": "ERROR" }, + { + "line": 107, + "column": 24, + "endLine": 107, + "endColumn": 39, + "problem": "BuiltinSymbolIterator", + "suggest": "", + "rule": "Using \"Symbol.iterator\" is not allowed in this API (arkts-builtin-symbol-iterator)", + "severity": "ERROR" + }, { "line": 108, "column": 5, @@ -174,6 +194,16 @@ "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", "severity": "ERROR" }, + { + "line": 117, + "column": 20, + "endLine": 117, + "endColumn": 35, + "problem": "BuiltinSymbolIterator", + "suggest": "", + "rule": "Using \"Symbol.iterator\" is not allowed in this API (arkts-builtin-symbol-iterator)", + "severity": "ERROR" + }, { "line": 118, "column": 5, @@ -204,6 +234,16 @@ "rule": "Avoid using union types (arkts-common-union-member-access)", "severity": "ERROR" }, + { + "line": 139, + "column": 12, + "endLine": 139, + "endColumn": 31, + "problem": "CreatingPrimitiveTypes", + "suggest": "", + "rule": "ArkTS creating primitive types is not supported (arkts-primitive-type-normalization)", + "severity": "ERROR" + }, { "line": 159, "column": 3, @@ -245,13 +285,13 @@ "severity": "ERROR" }, { - "line": 176, - "column": 1, - "endLine": 176, - "endColumn": 10, - "problem": "LimitedStdLibApi", + "line": 177, + "column": 23, + "endLine": 177, + "endColumn": 34, + "problem": "NoNeedStdLibSendableContainer", "suggest": "", - "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", + "rule": "Sendable containers are not supported (arkts-no-need-stdlib-sendable-containers)", "severity": "ERROR" }, { @@ -265,4 +305,4 @@ "severity": "ERROR" } ] -} \ No newline at end of file +} diff --git a/ets2panda/linter/test/main/property_access_by_index.ets.migrate.ets b/ets2panda/linter/test/main/property_access_by_index.ets.migrate.ets new file mode 100644 index 0000000000..a19d015480 --- /dev/null +++ b/ets2panda/linter/test/main/property_access_by_index.ets.migrate.ets @@ -0,0 +1,184 @@ +/* + * Copyright (c) 2023-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import {OhosInterface} from './oh_modules/ohos_lib'; +import { collections } from './@arkts.collections'; +// #14071 +class A { + v: string = ''; +} +function SetProperty(oldObj: T, str: string, obj: Object): void { + oldObj[str] = obj; // Should report error +} +function GetProperty(oldObj: T, str: string): U { + return oldObj[str]; // Should report error +} +function test() { + let a: A = { v: 'abc' }; + SetProperty(a, 'u', 'def'); + return GetProperty(a, 'v') + GetProperty(a, 'u'); +} + +let ar1 = [1, 2, 3, 4]; +let ar2 = [1, '2', 3, 4]; +let ar3: number[] = []; + +ar1[2]; +ar2[2]; +ar3[2]; + +const r0 = [1, 2, 3][1]; +let r1 = [1, 2, 3, 4][0] +let r2 = [1, '2', 3, 4][0] + +function fobject1(o: object) { + o['j'] +} + +function fobject2(o: Object) { + o['k'] +} + +let array1 = [0,1] +let array2 = [1,2,3,4,5] +let array3: number[] = [1,2,3,4,5] +let array4: Array = [1,2,3,4,5] +let array5 = new Array(10) +let array6 = new Int8Array(10) +let array7 = new Uint8Array(10) +let array8 = new Uint8ClampedArray(10) +let array9 = new Int16Array(10) +let array10 = new Uint16Array(10) +let array11 = new Int32Array(10) +let array12 = new Uint32Array(10) +let array13 = new Float32Array(10) +let array14 = new Float64Array(10) +let array15 = new BigInt64Array(10) +let array16 = new BigUint64Array(10) + +array1[0]; +array2[0]; +array3[0]; +array4[0]; +array5[0]; +array6[0]; +array7[0]; +array8[0]; +array9[0]; +array10[0]; +array11[0]; +array12[0]; +array13[0]; +array14[0]; +array15[0]; +array16[0]; + +function fff1(r: Record) { + r['bob'] +} + +enum CCCCCCCCC { + KATE, + BOB, + ROB, +} + +CCCCCCCCC['KATE'] +CCCCCCCCC['BOB'] +CCCCCCCCC['ROB'] + +CCCCCCCCC[CCCCCCCCC.KATE] +CCCCCCCCC[CCCCCCCCC.BOB] +CCCCCCCCC[CCCCCCCCC.ROB] + +let arr32 = new Float32Array([1,2,3]) + +let iter_arr32 = arr32[Symbol.iterator]() +let tmp_arr32 = iter_arr32.next().value; +while (!!tmp_arr32) { + console.log(tmp_arr32[0]) + + tmp_arr32 = iter_arr32.next().value +} + +let arr = new Array() +arr = ['a','f','g'] +let iter_arr = arr[Symbol.iterator]() +let tmp_arr = iter_arr.next().value; +while (!!tmp_arr) { + console.log(tmp_arr[0]) + tmp_arr = iter_arr.next().value +} + +// #14415 +class ArrayContainer { + numbers: number[] = []; +} +class NullableArray { + container: ArrayContainer | null = null; + + print() { + console.log(this.container?.numbers[0]); + } +} + +let str1 = 'sssss' +let str2 = "aaaaa" +let str3 = `sssss` +let str4 = new String('sssss') +let str5 = str1 +let str6 = str2 + +str1[1] +str2[1] +str3[1] +str4[1] +str5[1] +str6[1] + +class AString extends String {} +let str7 = new AString('dwdd') +str7[1] + +type IndexableUnion = string[] | (number | string)[] | Uint8Array; +type NonIndexableUnion = string[] | number[] | Uint8Array | number; + +function indexUnion(iu: IndexableUnion, niu: NonIndexableUnion) { + iu[0]; + niu[0]; +} + +function testLibraryUnnamedType(a: OhosInterface) { + a['kek']; +} + +class MMap extends Map {} + +let mmap1 = new Map(); +let mmap2 = new Map(); +let mmap3 = new MMap(); + +mmap1[1]; +mmap2['222']; +mmap3["kkr"]; + +@Sendable +class MyClass extends collections.BitVector { + constructor() { + super(0); + for (let i = 0; i < this.length; i++) { + this[i] = 1; + } + } +} diff --git a/ets2panda/linter/test/main/property_access_by_index.ts.arkts2.json b/ets2panda/linter/test/main/property_access_by_index.ets.migrate.json similarity index 68% rename from ets2panda/linter/test/main/property_access_by_index.ts.arkts2.json rename to ets2panda/linter/test/main/property_access_by_index.ets.migrate.json index 610499fd9a..e700885404 100644 --- a/ets2panda/linter/test/main/property_access_by_index.ts.arkts2.json +++ b/ets2panda/linter/test/main/property_access_by_index.ets.migrate.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -34,16 +34,6 @@ "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", "severity": "ERROR" }, - { - "line": 46, - "column": 3, - "endLine": 46, - "endColumn": 9, - "problem": "PropertyAccessByIndex", - "suggest": "", - "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", - "severity": "ERROR" - }, { "line": 50, "column": 3, @@ -93,36 +83,6 @@ "suggest": "", "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", "severity": "ERROR" - }, - { - "line": 172, - "column": 1, - "endLine": 172, - "endColumn": 9, - "problem": "PropertyAccessByIndex", - "suggest": "", - "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", - "severity": "ERROR" - }, - { - "line": 173, - "column": 1, - "endLine": 173, - "endColumn": 13, - "problem": "PropertyAccessByIndex", - "suggest": "", - "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", - "severity": "ERROR" - }, - { - "line": 174, - "column": 1, - "endLine": 174, - "endColumn": 13, - "problem": "PropertyAccessByIndex", - "suggest": "", - "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", - "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/property_decl_on_function.ets.arkts2.json b/ets2panda/linter/test/main/property_decl_on_function.ets.arkts2.json index f7836beb52..4f28f1e680 100644 --- a/ets2panda/linter/test/main/property_decl_on_function.ets.arkts2.json +++ b/ets2panda/linter/test/main/property_decl_on_function.ets.arkts2.json @@ -184,16 +184,6 @@ "rule": "Declaring properties on functions is not supported (arkts-no-func-props)", "severity": "ERROR" }, - { - "line": 48, - "column": 16, - "endLine": 48, - "endColumn": 24, - "problem": "ExplicitFunctionType", - "suggest": "", - "rule": "The function type should be explicit (arkts-no-ts-like-function)", - "severity": "ERROR" - }, { "line": 52, "column": 13, diff --git a/ets2panda/linter/test/main/provide_annotation_1.ets b/ets2panda/linter/test/main/provide_annotation_1.ets index 6eebfb8e65..6ef3ea6756 100644 --- a/ets2panda/linter/test/main/provide_annotation_1.ets +++ b/ets2panda/linter/test/main/provide_annotation_1.ets @@ -1,44 +1,44 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -@Component -struct Index { - @Provide - value: number; - build() { - Column() { - } - } -} - -@Component -struct Index { - @Provide("value") - value: number; - build() { - Column() { - } - } -} - -@Component -struct Index { - @Provide({allowOverride: "value"}) - value: number; - build() { - Column() { - } - } +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@Component +struct Index { + @Provide + value: number; + build() { + Column() { + } + } +} + +@Component +struct Index { + @Provide("value") + value: number; + build() { + Column() { + } + } +} + +@Component +struct Index { + @Provide({allowOverride: "value"}) + value: number; + build() { + Column() { + } + } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/provide_annotation_1.ets.args.json b/ets2panda/linter/test/main/provide_annotation_1.ets.args.json index 40bac500e3..b023016d6b 100644 --- a/ets2panda/linter/test/main/provide_annotation_1.ets.args.json +++ b/ets2panda/linter/test/main/provide_annotation_1.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/provide_annotation_1.ets.autofix.json b/ets2panda/linter/test/main/provide_annotation_1.ets.autofix.json index 73e8de4b45..499fa5b296 100644 --- a/ets2panda/linter/test/main/provide_annotation_1.ets.autofix.json +++ b/ets2panda/linter/test/main/provide_annotation_1.ets.autofix.json @@ -22,8 +22,8 @@ "problem": "ProvideAnnotation", "autofix": [ { - "start": 754, - "end": 771, + "start": 727, + "end": 744, "replacementText": "@Provide({ alias: \"value\" })" } ], @@ -39,8 +39,8 @@ "problem": "ProvideAnnotation", "autofix": [ { - "start": 867, - "end": 901, + "start": 830, + "end": 864, "replacementText": "@Provide({ alias: \"value\", allowOverride: true })" } ], @@ -56,8 +56,8 @@ "problem": "UIInterfaceImport", "autofix": [ { - "start": 616, - "end": 616, + "start": 603, + "end": 603, "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" } ], @@ -73,8 +73,8 @@ "problem": "UIInterfaceImport", "autofix": [ { - "start": 616, - "end": 616, + "start": 603, + "end": 603, "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" } ], @@ -90,8 +90,8 @@ "problem": "UIInterfaceImport", "autofix": [ { - "start": 616, - "end": 616, + "start": 603, + "end": 603, "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" } ], @@ -107,8 +107,8 @@ "problem": "UIInterfaceImport", "autofix": [ { - "start": 616, - "end": 616, + "start": 603, + "end": 603, "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" } ], @@ -124,8 +124,8 @@ "problem": "UIInterfaceImport", "autofix": [ { - "start": 616, - "end": 616, + "start": 603, + "end": 603, "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" } ], @@ -141,8 +141,8 @@ "problem": "UIInterfaceImport", "autofix": [ { - "start": 616, - "end": 616, + "start": 603, + "end": 603, "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" } ], @@ -158,8 +158,8 @@ "problem": "UIInterfaceImport", "autofix": [ { - "start": 616, - "end": 616, + "start": 603, + "end": 603, "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" } ], @@ -175,8 +175,8 @@ "problem": "UIInterfaceImport", "autofix": [ { - "start": 616, - "end": 616, + "start": 603, + "end": 603, "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" } ], @@ -192,8 +192,8 @@ "problem": "UIInterfaceImport", "autofix": [ { - "start": 616, - "end": 616, + "start": 603, + "end": 603, "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" } ], diff --git a/ets2panda/linter/test/main/provide_annotation_1.ets.migrate.ets b/ets2panda/linter/test/main/provide_annotation_1.ets.migrate.ets new file mode 100644 index 0000000000..ba3e787752 --- /dev/null +++ b/ets2panda/linter/test/main/provide_annotation_1.ets.migrate.ets @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Component, Provide, Column } from '@kit.ArkUI'; + +@Component +struct Index { + @Provide + value: number; + build() { + Column() { + } + } +} + +@Component +struct Index { + @Provide({ alias: "value" }) + value: number; + build() { + Column() { + } + } +} + +@Component +struct Index { + @Provide({ alias: "value", allowOverride: true }) + value: number; + build() { + Column() { + } + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/provide_annotation_1.ets.migrate.json b/ets2panda/linter/test/main/provide_annotation_1.ets.migrate.json new file mode 100644 index 0000000000..2817e72894 --- /dev/null +++ b/ets2panda/linter/test/main/provide_annotation_1.ets.migrate.json @@ -0,0 +1,48 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 21, + "column": 3, + "endLine": 21, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 31, + "column": 3, + "endLine": 31, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 41, + "column": 3, + "endLine": 41, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/provide_annotation_2.ets b/ets2panda/linter/test/main/provide_annotation_2.ets index a3d3e3bb35..bddf1e72c0 100644 --- a/ets2panda/linter/test/main/provide_annotation_2.ets +++ b/ets2panda/linter/test/main/provide_annotation_2.ets @@ -1,44 +1,44 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -@Component -struct Index { - @Provide - value: number; - build() { - Column() { - } - } -} - -@Component -struct Index { - @Provide({ alias: "value" }) - value: number; - build() { - Column() { - } - } -} - -@Component -struct Index { - @Provide({ alias: "value", allowOverride: true }) - value: number; - build() { - Column() { - } - } +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@Component +struct Index { + @Provide + value: number; + build() { + Column() { + } + } +} + +@Component +struct Index { + @Provide({ alias: "value" }) + value: number; + build() { + Column() { + } + } +} + +@Component +struct Index { + @Provide({ alias: "value", allowOverride: true }) + value: number; + build() { + Column() { + } + } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/provide_annotation_2.ets.args.json b/ets2panda/linter/test/main/provide_annotation_2.ets.args.json index 40bac500e3..b023016d6b 100644 --- a/ets2panda/linter/test/main/provide_annotation_2.ets.args.json +++ b/ets2panda/linter/test/main/provide_annotation_2.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/provide_annotation_2.ets.autofix.json b/ets2panda/linter/test/main/provide_annotation_2.ets.autofix.json index 4db8f1e8f2..f828839e12 100644 --- a/ets2panda/linter/test/main/provide_annotation_2.ets.autofix.json +++ b/ets2panda/linter/test/main/provide_annotation_2.ets.autofix.json @@ -22,8 +22,8 @@ "problem": "UIInterfaceImport", "autofix": [ { - "start": 616, - "end": 616, + "start": 603, + "end": 603, "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" } ], @@ -39,8 +39,8 @@ "problem": "UIInterfaceImport", "autofix": [ { - "start": 616, - "end": 616, + "start": 603, + "end": 603, "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" } ], @@ -56,8 +56,8 @@ "problem": "UIInterfaceImport", "autofix": [ { - "start": 616, - "end": 616, + "start": 603, + "end": 603, "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" } ], @@ -73,8 +73,8 @@ "problem": "UIInterfaceImport", "autofix": [ { - "start": 616, - "end": 616, + "start": 603, + "end": 603, "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" } ], @@ -90,8 +90,8 @@ "problem": "UIInterfaceImport", "autofix": [ { - "start": 616, - "end": 616, + "start": 603, + "end": 603, "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" } ], @@ -107,8 +107,8 @@ "problem": "UIInterfaceImport", "autofix": [ { - "start": 616, - "end": 616, + "start": 603, + "end": 603, "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" } ], @@ -124,8 +124,8 @@ "problem": "UIInterfaceImport", "autofix": [ { - "start": 616, - "end": 616, + "start": 603, + "end": 603, "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" } ], @@ -141,8 +141,8 @@ "problem": "UIInterfaceImport", "autofix": [ { - "start": 616, - "end": 616, + "start": 603, + "end": 603, "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" } ], @@ -158,8 +158,8 @@ "problem": "UIInterfaceImport", "autofix": [ { - "start": 616, - "end": 616, + "start": 603, + "end": 603, "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" } ], diff --git a/ets2panda/linter/test/main/provide_annotation_2.ets.migrate.ets b/ets2panda/linter/test/main/provide_annotation_2.ets.migrate.ets new file mode 100644 index 0000000000..ba3e787752 --- /dev/null +++ b/ets2panda/linter/test/main/provide_annotation_2.ets.migrate.ets @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Component, Provide, Column } from '@kit.ArkUI'; + +@Component +struct Index { + @Provide + value: number; + build() { + Column() { + } + } +} + +@Component +struct Index { + @Provide({ alias: "value" }) + value: number; + build() { + Column() { + } + } +} + +@Component +struct Index { + @Provide({ alias: "value", allowOverride: true }) + value: number; + build() { + Column() { + } + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/provide_annotation_2.ets.migrate.json b/ets2panda/linter/test/main/provide_annotation_2.ets.migrate.json new file mode 100644 index 0000000000..2817e72894 --- /dev/null +++ b/ets2panda/linter/test/main/provide_annotation_2.ets.migrate.json @@ -0,0 +1,48 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 21, + "column": 3, + "endLine": 21, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 31, + "column": 3, + "endLine": 31, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 41, + "column": 3, + "endLine": 41, + "endColumn": 8, + "problem": "StrictDiagnostic", + "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'value' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/runtime_array_bound.ets b/ets2panda/linter/test/main/runtime_array_bound.ets new file mode 100644 index 0000000000..435c6ac0e6 --- /dev/null +++ b/ets2panda/linter/test/main/runtime_array_bound.ets @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +'use static' + +const arr: int[] = [1, 2, 3, 4]; + +for (let i = 0; i < arr.length; i++) { + arr[i]; //legal +} + +for (let i = 0; i < 100; i++) { + console.log(i); //legal +} + +const arr2: int[] = [1, 2, 3, 4]; +for (let i = 0; i < 100; i++) { + arr2[10] //should report +} + +const arr3: int[] = [1, 2, 3, 4]; +for (let i = 0; i < arr3.length; i++) { + arr3[10] //should report +} + +const arr4: int[] = [1, 2, 3, 4]; +let x: int = 3; +for (let i = 0; i < arr4.length; i++) { + arr4[x]; //should report +} + +const arr5: int[] = [1, 2, 3, 4]; +for (let i = 0; i < 10; i++) { + arr5[i]; //should report +} + + +const arr6: int[] = [1, 2, 3, 4]; +if (arr6.length > 10) { + arr6[10] +} + +const arr7: int[] = [1, 2, 3, 4]; +if (arr7.length > 10) { + return; +} + +arr7[10] + +const arr8: int[] = [1, 2, 3, 4]; +const index: int = 9; +if (arr8.length > 10 && index > 0) { + return; +} + +arr8[index]; + +const arr9: int[] = [1, 2, 3, 4]; +if (arr9.length > 10 && index > 0) { + arr9[index]; +} + +const arr10: int[] = [1, 2, 3, 4]; +if (index > 0) { + arr10[index]; +} + +const arr10: int[] = [1, 2, 3, 4]; +let newIndex = 10; +if (arr10.length > newIndex) { + return; +} + +newIndex = 22; + +arr10[newIndex]; + + + diff --git a/ets2panda/linter/test/main/runtime_array_bound.ets.args.json b/ets2panda/linter/test/main/runtime_array_bound.ets.args.json new file mode 100644 index 0000000000..8a4be28991 --- /dev/null +++ b/ets2panda/linter/test/main/runtime_array_bound.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "migrate": "--arkts-2" + } +} diff --git a/ets2panda/linter/test/main/runtime_array_bound.ets.arkts2.json b/ets2panda/linter/test/main/runtime_array_bound.ets.arkts2.json new file mode 100644 index 0000000000..134de695ab --- /dev/null +++ b/ets2panda/linter/test/main/runtime_array_bound.ets.arkts2.json @@ -0,0 +1,168 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 19, + "column": 10, + "endLine": 19, + "endColumn": 15, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 10, + "endLine": 23, + "endColumn": 15, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 5, + "endLine": 29, + "endColumn": 13, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 10, + "endLine": 28, + "endColumn": 15, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 5, + "endLine": 34, + "endColumn": 13, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 10, + "endLine": 33, + "endColumn": 15, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 40, + "column": 5, + "endLine": 40, + "endColumn": 12, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 10, + "endLine": 39, + "endColumn": 15, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 5, + "endLine": 45, + "endColumn": 12, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 10, + "endLine": 44, + "endColumn": 15, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 67, + "column": 1, + "endLine": 67, + "endColumn": 12, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 5, + "endLine": 71, + "endColumn": 16, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 76, + "column": 5, + "endLine": 76, + "endColumn": 17, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 80, + "column": 5, + "endLine": 80, + "endColumn": 18, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 87, + "column": 1, + "endLine": 87, + "endColumn": 16, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/main/runtime_array_bound.ets.json b/ets2panda/linter/test/main/runtime_array_bound.ets.json new file mode 100644 index 0000000000..bd1b7140ca --- /dev/null +++ b/ets2panda/linter/test/main/runtime_array_bound.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} diff --git a/ets2panda/linter/test/main/runtime_array_bound.ets.migrate.ets b/ets2panda/linter/test/main/runtime_array_bound.ets.migrate.ets new file mode 100644 index 0000000000..261214843c --- /dev/null +++ b/ets2panda/linter/test/main/runtime_array_bound.ets.migrate.ets @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +'use static' + +const arr: int[] = [1, 2, 3, 4]; + +for (let i: number = 0; i < arr.length; i++) { + arr[i]; //legal +} + +for (let i: number = 0; i < 100; i++) { + console.log(i); //legal +} + +const arr2: int[] = [1, 2, 3, 4]; +for (let i: number = 0; i < 100; i++) { + arr2[10] //should report +} + +const arr3: int[] = [1, 2, 3, 4]; +for (let i: number = 0; i < arr3.length; i++) { + arr3[10] //should report +} + +const arr4: int[] = [1, 2, 3, 4]; +let x: int = 3; +for (let i: number = 0; i < arr4.length; i++) { + arr4[x]; //should report +} + +const arr5: int[] = [1, 2, 3, 4]; +for (let i: number = 0; i < 10; i++) { + arr5[i]; //should report +} + + +const arr6: int[] = [1, 2, 3, 4]; +if (arr6.length > 10) { + arr6[10] +} + +const arr7: int[] = [1, 2, 3, 4]; +if (arr7.length > 10) { + return; +} + +arr7[10] + +const arr8: int[] = [1, 2, 3, 4]; +const index: int = 9; +if (arr8.length > 10 && index > 0) { + return; +} + +arr8[index]; + +const arr9: int[] = [1, 2, 3, 4]; +if (arr9.length > 10 && index > 0) { + arr9[index]; +} + +const arr10: int[] = [1, 2, 3, 4]; +if (index > 0) { + arr10[index]; +} + +const arr10: int[] = [1, 2, 3, 4]; +let newIndex: number = 10; +if (arr10.length > newIndex) { + return; +} + +newIndex = 22; + +arr10[newIndex]; + + + diff --git a/ets2panda/linter/test/main/runtime_array_bound.ets.migrate.json b/ets2panda/linter/test/main/runtime_array_bound.ets.migrate.json new file mode 100644 index 0000000000..d472b1c6cc --- /dev/null +++ b/ets2panda/linter/test/main/runtime_array_bound.ets.migrate.json @@ -0,0 +1,98 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 29, + "column": 5, + "endLine": 29, + "endColumn": 13, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 5, + "endLine": 34, + "endColumn": 13, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 40, + "column": 5, + "endLine": 40, + "endColumn": 12, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 5, + "endLine": 45, + "endColumn": 12, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 67, + "column": 1, + "endLine": 67, + "endColumn": 12, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 5, + "endLine": 71, + "endColumn": 16, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 76, + "column": 5, + "endLine": 76, + "endColumn": 17, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 87, + "column": 1, + "endLine": 87, + "endColumn": 16, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/main/sendable_class_inheritance.ets.args.json b/ets2panda/linter/test/main/sendable_class_inheritance.ets.args.json index 4ce1a4c45c..12b3ca8dec 100644 --- a/ets2panda/linter/test/main/sendable_class_inheritance.ets.args.json +++ b/ets2panda/linter/test/main/sendable_class_inheritance.ets.args.json @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/main/sendable_class_inheritance.ets.migrate.ets b/ets2panda/linter/test/main/sendable_class_inheritance.ets.migrate.ets new file mode 100644 index 0000000000..34b7339258 --- /dev/null +++ b/ets2panda/linter/test/main/sendable_class_inheritance.ets.migrate.ets @@ -0,0 +1,190 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + sendableClassA, + sendableVar, + nonSendableClassB, + nonSendableVar, + sendableInterface, + nonSendableInterface, + lang, +} from './@arkts.lang'; + +// sendable class +@Sendable +class localSendableClassA {} + +// sendable class var +let localSendableVar = localSendableClassA + + +// non-sendable class +class localNonSendableClassB {} + +// non-sendable class var +let localNonSendableVar = localNonSendableClassB + +// sendable interface +interface localSendableInterface extends lang.ISendable {} + +// non-sendable interface +interface localNonSendableInterface {} + +// sendable interface type alias +type localSendableInterfaceAlias = localSendableInterface + +// non-sendable interface type alias +type localNonSendableInterfaceAlias = localNonSendableInterface + +// left: sendable class + +// class + class + +// case1: extends import var +// == case1.1: extends sendable +@Sendable +class sendableClass1 extends sendableVar {} // ERROR + +// == case1.2: extends non-sendable +@Sendable +class sendableClass2 extends nonSendableVar {} // ERROR + +// case2: extends local var +// == case2.1: extends sendable +@Sendable +class sendableClass3 extends localSendableVar {} // ERROR + +// == case2.2: extends non-sendable +@Sendable +class sendableClass4 extends localNonSendableVar {} // ERROR + +// case3: extends import class +// == case3.1: extends sendable +@Sendable +class sendableClass5 extends sendableClassA {} // OK + +// == case3.2: extends non-sendable +@Sendable +class sendableClass6 extends nonSendableClassB {} // ERROR + +// case4: extends local class +// == case4.1: extends sendable +@Sendable +class sendableClass7 extends localSendableClassA {} // OK + +// == case4.2: extends non-sendable +@Sendable +class sendableClass8 extends localNonSendableClassB {} // ERROR + +// class + interface + +// case1: implements local interface +// == case1.1: implements sendable +@Sendable +class sendableClass9 implements localSendableInterface {} // OK + +// == case1.2: implements non-sendable +@Sendable +class sendableClass10 implements localNonSendableInterface {} // OK + +// case2: implements import interface +// == case2.1: implements sendable +@Sendable +class sendableClass11 implements sendableInterface {} // OK + +// == case2.2: implements non-sendable +@Sendable +class sendableClass12 implements nonSendableInterface {} // OK + +// case3: implements type alias +// == case3.1: implements sendable +@Sendable +class sendableClass13 implements localSendableInterfaceAlias {} // OK + +// == case3.2: implements non-sendable +@Sendable +class sendableClass14 implements localNonSendableInterfaceAlias {} // OK + +// left: non sendable class + +// case1: extends import var +// == case1.1: extends sendable +class sendableClass15 extends sendableVar {} // ERROR + +// == case1.2: extends non-sendable +class sendableClass16 extends nonSendableVar {} // OK + +// case2: extends local var +// == case2.1: extends sendable +class sendableClass17 extends localSendableVar {} // ERROR + +// == case2.2: extends non-sendable +class sendableClass18 extends localNonSendableVar {} // OK + +// case3: extends import class +// == case3.1: extends sendable +@Sendable +class sendableClass19 extends sendableClassA {} // ERROR + +// == case3.2: extends non-sendable +class sendableClass20 extends nonSendableClassB {} // OK + +// case4: extends local class +// == case4.1: extends sendable +@Sendable +class sendableClass21 extends localSendableClassA {} // ERROR + +// == case4.2: extends non-sendable +class sendableClass22 extends localNonSendableClassB {} // OK + +// class + interface + +// case1: implements local interface +// == case1.1: implements sendable +@Sendable +class sendableClass23 implements localSendableInterface {} // ERROR + +// == case1.2: implements non-sendable +class sendableClass24 implements localNonSendableInterface {} // OK + +// case2: implements import interface +// == case2.1: implements sendable +@Sendable +class sendableClass25 implements sendableInterface {} // ERROR + +// == case2.2: implements non-sendable +class sendableClass26 implements nonSendableInterface {} // OK + +// case3: implements type alias +// == case4.1: implements sendable +@Sendable +class sendableClass27 implements localSendableInterfaceAlias {} // ERROR + +// == case4.2: implements non-sendable +class sendableClass28 implements localNonSendableInterfaceAlias {} // OK + +// ISendable created by developer is not a sendable interface + +interface ISendable {} + +interface fakeSendableInterface extends ISendable {} + +// fake sendable interface type alias +type fakeSendableInterfaceAlias = fakeSendableInterface + +class sendableClass29 implements fakeSendableInterface {} // OK + +class sendableClass30 implements fakeSendableInterfaceAlias {} // OK \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/ConstructorFuncs.ets.json b/ets2panda/linter/test/main/sendable_class_inheritance.ets.migrate.json similarity index 43% rename from ets2panda/linter/test/sdkwhite/ConstructorFuncs.ets.json rename to ets2panda/linter/test/main/sendable_class_inheritance.ets.migrate.json index d16c4619db..1b1edbb0f9 100644 --- a/ets2panda/linter/test/sdkwhite/ConstructorFuncs.ets.json +++ b/ets2panda/linter/test/main/sendable_class_inheritance.ets.migrate.json @@ -15,94 +15,104 @@ ], "result": [ { - "line": 62, + "line": 31, "column": 24, - "endLine": 62, - "endColumn": 35, - "problem": "ConstructorFuncs", + "endLine": 31, + "endColumn": 43, + "problem": "ClassAsObject", "suggest": "", - "rule": "Constructor function type is not supported (arkts-no-ctor-signatures-funcs)", - "severity": "ERROR" + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + }, + { + "line": 38, + "column": 27, + "endLine": 38, + "endColumn": 49, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" }, { - "line": 64, - "column": 28, - "endLine": 64, - "endColumn": 39, - "problem": "ConstructorFuncs", + "line": 59, + "column": 30, + "endLine": 59, + "endColumn": 41, + "problem": "SendableClassInheritance", "suggest": "", - "rule": "Constructor function type is not supported (arkts-no-ctor-signatures-funcs)", + "rule": "The inheritance for \"Sendable\" classes is limited (arkts-sendable-class-inheritance)", "severity": "ERROR" }, { - "line": 74, - "column": 12, - "endLine": 74, - "endColumn": 13, - "problem": "ObjectLiteralNoContextType", + "line": 63, + "column": 30, + "endLine": 63, + "endColumn": 44, + "problem": "SendableClassInheritance", "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "The inheritance for \"Sendable\" classes is limited (arkts-sendable-class-inheritance)", "severity": "ERROR" }, { - "line": 74, - "column": 13, - "endLine": 74, - "endColumn": 22, - "problem": "SpreadOperator", + "line": 68, + "column": 30, + "endLine": 68, + "endColumn": 46, + "problem": "SendableClassInheritance", "suggest": "", - "rule": "It is possible to spread only arrays or classes derived from arrays into the rest parameter or array literals (arkts-no-spread)", + "rule": "The inheritance for \"Sendable\" classes is limited (arkts-sendable-class-inheritance)", "severity": "ERROR" }, { - "line": 82, - "column": 12, - "endLine": 82, - "endColumn": 32, - "problem": "ArrayLiteralNoContextType", + "line": 72, + "column": 30, + "endLine": 72, + "endColumn": 49, + "problem": "SendableClassInheritance", "suggest": "", - "rule": "Array literals must contain elements of only inferrable types (arkts-no-noninferrable-arr-literals)", + "rule": "The inheritance for \"Sendable\" classes is limited (arkts-sendable-class-inheritance)", "severity": "ERROR" }, { - "line": 82, - "column": 13, - "endLine": 82, - "endColumn": 14, - "problem": "ObjectLiteralNoContextType", + "line": 81, + "column": 30, + "endLine": 81, + "endColumn": 47, + "problem": "SendableClassInheritance", "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "The inheritance for \"Sendable\" classes is limited (arkts-sendable-class-inheritance)", "severity": "ERROR" }, { - "line": 82, - "column": 14, - "endLine": 82, - "endColumn": 23, - "problem": "SpreadOperator", + "line": 90, + "column": 30, + "endLine": 90, + "endColumn": 52, + "problem": "SendableClassInheritance", "suggest": "", - "rule": "It is possible to spread only arrays or classes derived from arrays into the rest parameter or array literals (arkts-no-spread)", + "rule": "The inheritance for \"Sendable\" classes is limited (arkts-sendable-class-inheritance)", "severity": "ERROR" }, { - "line": 89, - "column": 37, - "endLine": 89, - "endColumn": 41, - "problem": "ClassAsObject", + "line": 125, + "column": 31, + "endLine": 125, + "endColumn": 42, + "problem": "SendableClassInheritance", "suggest": "", - "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", - "severity": "WARNING" + "rule": "The inheritance for \"Sendable\" classes is limited (arkts-sendable-class-inheritance)", + "severity": "ERROR" }, { - "line": 104, - "column": 42, - "endLine": 104, - "endColumn": 49, - "problem": "ClassAsObject", + "line": 132, + "column": 31, + "endLine": 132, + "endColumn": 47, + "problem": "SendableClassInheritance", "suggest": "", - "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", - "severity": "WARNING" + "rule": "The inheritance for \"Sendable\" classes is limited (arkts-sendable-class-inheritance)", + "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/sendable_class_inheritance_2.ets.args.json b/ets2panda/linter/test/main/sendable_class_inheritance_2.ets.args.json index 4ce1a4c45c..12b3ca8dec 100644 --- a/ets2panda/linter/test/main/sendable_class_inheritance_2.ets.args.json +++ b/ets2panda/linter/test/main/sendable_class_inheritance_2.ets.args.json @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/main/sendable_class_inheritance_2.ets.migrate.ets b/ets2panda/linter/test/main/sendable_class_inheritance_2.ets.migrate.ets new file mode 100644 index 0000000000..42ff9e372c --- /dev/null +++ b/ets2panda/linter/test/main/sendable_class_inheritance_2.ets.migrate.ets @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { lang } from './@arkts.lang'; + +@Sendable +class GoodA implements lang.ISendable {} + +@Sendable +class BadA implements lang.ISendable {} // Fixable + +interface B extends lang.ISendable {} + +@Sendable +class GoodB implements B {} + +@Sendable +class BadB implements B {} // Fixable + +@Sendable +class C {} + +@Sendable +class GoodC extends C {} + +@Sendable +class BadC extends C {} // Fixable + +@Sendable +class BadC2 extends C implements lang.ISendable {} // Fixable + +class D {} + +@Sendable +class BadD extends D {} // Not fixable + +class GoodD extends D {} \ No newline at end of file diff --git a/ets2panda/linter/test/main/sendable_class_inheritance_2.ets.migrate.json b/ets2panda/linter/test/main/sendable_class_inheritance_2.ets.migrate.json new file mode 100644 index 0000000000..6cc01d31bc --- /dev/null +++ b/ets2panda/linter/test/main/sendable_class_inheritance_2.ets.migrate.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 47, + "column": 20, + "endLine": 47, + "endColumn": 21, + "problem": "SendableClassInheritance", + "suggest": "", + "rule": "The inheritance for \"Sendable\" classes is limited (arkts-sendable-class-inheritance)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/sendable_decorator_arkts2.ets b/ets2panda/linter/test/main/sendable_decorator_arkts2.ets index 604e2aadb3..ad7642039b 100644 --- a/ets2panda/linter/test/main/sendable_decorator_arkts2.ets +++ b/ets2panda/linter/test/main/sendable_decorator_arkts2.ets @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +'use static' @Sendable // ERROR class SendableClass { diff --git a/ets2panda/linter/test/main/sendable_decorator_arkts2.ets.args.json b/ets2panda/linter/test/main/sendable_decorator_arkts2.ets.args.json index 4e9dc628f7..571ee6bb76 100644 --- a/ets2panda/linter/test/main/sendable_decorator_arkts2.ets.args.json +++ b/ets2panda/linter/test/main/sendable_decorator_arkts2.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } diff --git a/ets2panda/linter/test/main/sendable_decorator_arkts2.ets.arkts2.json b/ets2panda/linter/test/main/sendable_decorator_arkts2.ets.arkts2.json index 9a72d0f98a..84cf5f2ee3 100644 --- a/ets2panda/linter/test/main/sendable_decorator_arkts2.ets.arkts2.json +++ b/ets2panda/linter/test/main/sendable_decorator_arkts2.ets.arkts2.json @@ -1,28 +1,14 @@ { - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], "result": [ { - "line": 16, + "line": 17, "column": 1, - "endLine": 16, + "endLine": 17, "endColumn": 10, - "problem": "LimitedStdLibApi", + "problem": "LimitedStdLibNoSendableDecorator", "suggest": "", - "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", + "rule": "Usage of standard library is restricted(arkts-limited-stdlib-no-sendable-decorator)", "severity": "ERROR" } ] -} +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/sendable_decorator_arkts2.ets.autofix.json b/ets2panda/linter/test/main/sendable_decorator_arkts2.ets.autofix.json index 4c8d17a17a..713f44e680 100644 --- a/ets2panda/linter/test/main/sendable_decorator_arkts2.ets.autofix.json +++ b/ets2panda/linter/test/main/sendable_decorator_arkts2.ets.autofix.json @@ -15,20 +15,20 @@ ], "result": [ { - "line": 16, + "line": 17, "column": 1, - "endLine": 16, + "endLine": 17, "endColumn": 10, - "problem": "LimitedStdLibApi", + "problem": "LimitedStdLibNoSendableDecorator", "autofix": [ { - "start": 610, - "end": 619, + "start": 623, + "end": 632, "replacementText": "" } ], "suggest": "", - "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", + "rule": "Usage of standard library is restricted(arkts-limited-stdlib-no-sendable-decorator)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/main/sendable_decorator_arkts2.ets.migrate.ets b/ets2panda/linter/test/main/sendable_decorator_arkts2.ets.migrate.ets new file mode 100644 index 0000000000..32a1cd22fa --- /dev/null +++ b/ets2panda/linter/test/main/sendable_decorator_arkts2.ets.migrate.ets @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +'use static' + + // ERROR +class SendableClass { +} diff --git a/ets2panda/linter/test/main/sendable_decorator_arkts2.ets.migrate.json b/ets2panda/linter/test/main/sendable_decorator_arkts2.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/sendable_decorator_arkts2.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/sendable_decorator_limited.ets.args.json b/ets2panda/linter/test/main/sendable_decorator_limited.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/main/sendable_decorator_limited.ets.args.json +++ b/ets2panda/linter/test/main/sendable_decorator_limited.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/main/sendable_decorator_limited.ets.migrate.ets b/ets2panda/linter/test/main/sendable_decorator_limited.ets.migrate.ets new file mode 100644 index 0000000000..7b27a36af2 --- /dev/null +++ b/ets2panda/linter/test/main/sendable_decorator_limited.ets.migrate.ets @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@Sendable // OK +class SendableClass { +} + +@Sendable // OK +function sendableFunction(): void { +}; + +@Sendable // OK +type SendableType = () => void; + + // ERROR +struct SendableStruct { +}; + + +class NormalClass { + // ERROR + name: string = 'name'; + + // ERROR + handle() { + + }; + + handle2( param: string) { // ERROR + + } + + // ERROR + get age(): number { + return 1; + } + + // ERROR + set age(value: number) { + } +} diff --git a/ets2panda/linter/test/main/sendable_decorator_limited.ets.migrate.json b/ets2panda/linter/test/main/sendable_decorator_limited.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/sendable_decorator_limited.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/sendable_explicit_field_type.ets.args.json b/ets2panda/linter/test/main/sendable_explicit_field_type.ets.args.json index 4ce1a4c45c..12b3ca8dec 100644 --- a/ets2panda/linter/test/main/sendable_explicit_field_type.ets.args.json +++ b/ets2panda/linter/test/main/sendable_explicit_field_type.ets.args.json @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/main/sendable_explicit_field_type.ets.autofix.json b/ets2panda/linter/test/main/sendable_explicit_field_type.ets.autofix.json index ca304dd6c5..4431346a56 100644 --- a/ets2panda/linter/test/main/sendable_explicit_field_type.ets.autofix.json +++ b/ets2panda/linter/test/main/sendable_explicit_field_type.ets.autofix.json @@ -542,9 +542,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 3320, - "end": 3447, - "replacementText": "// Error, Field in sendable class must have type annotation (arkts-sendable-explicit-field-type)\nbooleanProp4: boolean = true;" + "start": 3439, + "end": 3439, + "replacementText": ": boolean" } ], "suggest": "", @@ -559,9 +559,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 3447, - "end": 3469, - "replacementText": "numberProp4: number = 42;" + "start": 3463, + "end": 3463, + "replacementText": ": number" } ], "suggest": "", @@ -576,9 +576,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 3469, - "end": 3496, - "replacementText": "stringProp4: string = \"Hello\";" + "start": 3485, + "end": 3485, + "replacementText": ": string" } ], "suggest": "", @@ -593,9 +593,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 3496, - "end": 3524, - "replacementText": "arrayProp4: number[] = [1, 2, 3];" + "start": 3511, + "end": 3511, + "replacementText": ": number[]" } ], "suggest": "", @@ -610,9 +610,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 3524, - "end": 3560, - "replacementText": "tupleProp4: (string | number)[] = [\"typescript\", 4];" + "start": 3539, + "end": 3539, + "replacementText": ": (string | number)[]" } ], "suggest": "", @@ -627,9 +627,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 3560, - "end": 3589, - "replacementText": "enumProp4: Color = Color.Green;" + "start": 3574, + "end": 3574, + "replacementText": ": Color" } ], "suggest": "", @@ -676,9 +676,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 3622, - "end": 3649, - "replacementText": "voidProp4: undefined = undefined;" + "start": 3636, + "end": 3636, + "replacementText": ": undefined" } ], "suggest": "", @@ -693,9 +693,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 3649, - "end": 3671, - "replacementText": "nullProp4: null = null;" + "start": 3663, + "end": 3663, + "replacementText": ": null" } ], "suggest": "", @@ -710,9 +710,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 3671, - "end": 3703, - "replacementText": "undefinedProp4: undefined = undefined;" + "start": 3690, + "end": 3690, + "replacementText": ": undefined" } ], "suggest": "", @@ -759,9 +759,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 3748, - "end": 3790, - "replacementText": "sendableClass4: SendableClass = new SendableClass();" + "start": 3767, + "end": 3767, + "replacementText": ": SendableClass" } ], "suggest": "", @@ -776,9 +776,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 3790, - "end": 3836, - "replacementText": "noSendableClass4: NoSendableClass = new NoSendableClass();" + "start": 3811, + "end": 3811, + "replacementText": ": NoSendableClass" } ], "suggest": "", @@ -793,9 +793,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 3836, - "end": 3964, - "replacementText": "// Error, Field in sendable class must have type annotation (arkts-sendable-explicit-field-type)\nbooleanProp5?: boolean | undefined = true;" + "start": 3956, + "end": 3956, + "replacementText": ": boolean | undefined" } ], "suggest": "", @@ -810,9 +810,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 3964, - "end": 3987, - "replacementText": "numberProp5?: number | undefined = 42;" + "start": 3981, + "end": 3981, + "replacementText": ": number | undefined" } ], "suggest": "", @@ -827,9 +827,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 3987, - "end": 4015, - "replacementText": "stringProp5?: string | undefined = \"Hello\";" + "start": 4004, + "end": 4004, + "replacementText": ": string | undefined" } ], "suggest": "", @@ -844,9 +844,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 4015, - "end": 4044, - "replacementText": "arrayProp5?: number[] | undefined = [1, 2, 3];" + "start": 4031, + "end": 4031, + "replacementText": ": number[] | undefined" } ], "suggest": "", @@ -861,9 +861,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 4044, - "end": 4081, - "replacementText": "tupleProp5?: (string | number)[] | undefined = [\"typescript\", 4];" + "start": 4060, + "end": 4060, + "replacementText": ": (string | number)[] | undefined" } ], "suggest": "", @@ -878,9 +878,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 4081, - "end": 4111, - "replacementText": "enumProp5?: Color | undefined = Color.Green;" + "start": 4096, + "end": 4096, + "replacementText": ": Color | undefined" } ], "suggest": "", @@ -927,9 +927,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 4145, - "end": 4173, - "replacementText": "voidProp5?: undefined = undefined;" + "start": 4160, + "end": 4160, + "replacementText": ": undefined" } ], "suggest": "", @@ -944,9 +944,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 4173, - "end": 4196, - "replacementText": "nullProp5?: null | undefined = null;" + "start": 4188, + "end": 4188, + "replacementText": ": null | undefined" } ], "suggest": "", @@ -961,9 +961,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 4196, - "end": 4229, - "replacementText": "undefinedProp5?: undefined = undefined;" + "start": 4216, + "end": 4216, + "replacementText": ": undefined" } ], "suggest": "", @@ -1010,9 +1010,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 4275, - "end": 4318, - "replacementText": "sendableClass5?: SendableClass | undefined = new SendableClass();" + "start": 4295, + "end": 4295, + "replacementText": ": SendableClass | undefined" } ], "suggest": "", @@ -1027,9 +1027,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 4318, - "end": 4365, - "replacementText": "noSendableClass5?: NoSendableClass | undefined = new NoSendableClass();" + "start": 4340, + "end": 4340, + "replacementText": ": NoSendableClass | undefined" } ], "suggest": "", @@ -1044,9 +1044,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 4365, - "end": 4502, - "replacementText": "// Error, Field in sendable class must have type annotation (arkts-sendable-explicit-field-type)\npublic optBooleanProp6: boolean = true;" + "start": 4494, + "end": 4494, + "replacementText": ": boolean" } ], "suggest": "", @@ -1061,9 +1061,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 4502, - "end": 4534, - "replacementText": "public optNumberProp6: number = 42;" + "start": 4528, + "end": 4528, + "replacementText": ": number" } ], "suggest": "", @@ -1078,9 +1078,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 4534, - "end": 4571, - "replacementText": "public optStringProp6: string = \"Hello\";" + "start": 4560, + "end": 4560, + "replacementText": ": string" } ], "suggest": "", @@ -1095,9 +1095,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 4571, - "end": 4609, - "replacementText": "public optArrayProp6: number[] = [1, 2, 3];" + "start": 4596, + "end": 4596, + "replacementText": ": number[]" } ], "suggest": "", @@ -1112,9 +1112,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 4609, - "end": 4655, - "replacementText": "public optTupleProp6: (string | number)[] = [\"typescript\", 4];" + "start": 4634, + "end": 4634, + "replacementText": ": (string | number)[]" } ], "suggest": "", @@ -1129,9 +1129,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 4655, - "end": 4694, - "replacementText": "public optEnumProp6: Color = Color.Green;" + "start": 4679, + "end": 4679, + "replacementText": ": Color" } ], "suggest": "", @@ -1178,9 +1178,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 4737, - "end": 4774, - "replacementText": "public optVoidProp6: undefined = undefined;" + "start": 4761, + "end": 4761, + "replacementText": ": undefined" } ], "suggest": "", @@ -1195,9 +1195,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 4774, - "end": 4806, - "replacementText": "public optNullProp6: null = null;" + "start": 4798, + "end": 4798, + "replacementText": ": null" } ], "suggest": "", @@ -1212,9 +1212,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 4806, - "end": 4848, - "replacementText": "public optUndefinedProp6: undefined = undefined;" + "start": 4835, + "end": 4835, + "replacementText": ": undefined" } ], "suggest": "", @@ -1261,9 +1261,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 4903, - "end": 4955, - "replacementText": "public optSendableClass6: SendableClass = new SendableClass();" + "start": 4932, + "end": 4932, + "replacementText": ": SendableClass" } ], "suggest": "", @@ -1278,9 +1278,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 4955, - "end": 5011, - "replacementText": "public optNoSendableClass6: NoSendableClass = new NoSendableClass();" + "start": 4986, + "end": 4986, + "replacementText": ": NoSendableClass" } ], "suggest": "", @@ -1295,9 +1295,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 5011, - "end": 5150, - "replacementText": "// Error, Field in sendable class must have type annotation (arkts-sendable-explicit-field-type)\nreadonly optBooleanProp7: true = true;" + "start": 5142, + "end": 5142, + "replacementText": ": true" } ], "suggest": "", @@ -1312,9 +1312,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 5150, - "end": 5184, - "replacementText": "readonly optNumberProp7: 42 = 42;" + "start": 5178, + "end": 5178, + "replacementText": ": 42" } ], "suggest": "", @@ -1329,9 +1329,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 5184, - "end": 5223, - "replacementText": "readonly optStringProp7: \"Hello\" = \"Hello\";" + "start": 5212, + "end": 5212, + "replacementText": ": \"Hello\"" } ], "suggest": "", @@ -1346,9 +1346,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 5223, - "end": 5263, - "replacementText": "readonly optArrayProp7: number[] = [1, 2, 3];" + "start": 5250, + "end": 5250, + "replacementText": ": number[]" } ], "suggest": "", @@ -1363,9 +1363,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 5263, - "end": 5311, - "replacementText": "readonly optTupleProp7: (string | number)[] = [\"typescript\", 4];" + "start": 5290, + "end": 5290, + "replacementText": ": (string | number)[]" } ], "suggest": "", @@ -1380,9 +1380,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 5311, - "end": 5352, - "replacementText": "readonly optEnumProp7: Color.Green = Color.Green;" + "start": 5337, + "end": 5337, + "replacementText": ": Color.Green" } ], "suggest": "", @@ -1429,9 +1429,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 5397, - "end": 5436, - "replacementText": "readonly optVoidProp7: undefined = undefined;" + "start": 5423, + "end": 5423, + "replacementText": ": undefined" } ], "suggest": "", @@ -1446,9 +1446,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 5436, - "end": 5470, - "replacementText": "readonly optNullProp7: null = null;" + "start": 5462, + "end": 5462, + "replacementText": ": null" } ], "suggest": "", @@ -1463,9 +1463,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 5470, - "end": 5514, - "replacementText": "readonly optUndefinedProp7: undefined = undefined;" + "start": 5501, + "end": 5501, + "replacementText": ": undefined" } ], "suggest": "", @@ -1512,9 +1512,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 5571, - "end": 5625, - "replacementText": "readonly optSendableClass7: SendableClass = new SendableClass();" + "start": 5602, + "end": 5602, + "replacementText": ": SendableClass" } ], "suggest": "", @@ -1529,9 +1529,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 5625, - "end": 5683, - "replacementText": "readonly optNoSendableClass7: NoSendableClass = new NoSendableClass();" + "start": 5658, + "end": 5658, + "replacementText": ": NoSendableClass" } ], "suggest": "", @@ -2066,9 +2066,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 8256, - "end": 8383, - "replacementText": "// Error, Field in sendable class must have type annotation (arkts-sendable-explicit-field-type)\nbooleanProp4: boolean = true;" + "start": 8375, + "end": 8375, + "replacementText": ": boolean" } ], "suggest": "", @@ -2083,9 +2083,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 8383, - "end": 8405, - "replacementText": "numberProp4: number = 42;" + "start": 8399, + "end": 8399, + "replacementText": ": number" } ], "suggest": "", @@ -2100,9 +2100,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 8405, - "end": 8432, - "replacementText": "stringProp4: string = \"Hello\";" + "start": 8421, + "end": 8421, + "replacementText": ": string" } ], "suggest": "", @@ -2117,9 +2117,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 8432, - "end": 8460, - "replacementText": "arrayProp4: number[] = [1, 2, 3];" + "start": 8447, + "end": 8447, + "replacementText": ": number[]" } ], "suggest": "", @@ -2134,9 +2134,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 8460, - "end": 8496, - "replacementText": "tupleProp4: (string | number)[] = [\"typescript\", 4];" + "start": 8475, + "end": 8475, + "replacementText": ": (string | number)[]" } ], "suggest": "", @@ -2151,9 +2151,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 8496, - "end": 8525, - "replacementText": "enumProp4: Color = Color.Green;" + "start": 8510, + "end": 8510, + "replacementText": ": Color" } ], "suggest": "", @@ -2200,9 +2200,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 8558, - "end": 8585, - "replacementText": "voidProp4: undefined = undefined;" + "start": 8572, + "end": 8572, + "replacementText": ": undefined" } ], "suggest": "", @@ -2217,9 +2217,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 8585, - "end": 8607, - "replacementText": "nullProp4: null = null;" + "start": 8599, + "end": 8599, + "replacementText": ": null" } ], "suggest": "", @@ -2234,9 +2234,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 8607, - "end": 8639, - "replacementText": "undefinedProp4: undefined = undefined;" + "start": 8626, + "end": 8626, + "replacementText": ": undefined" } ], "suggest": "", @@ -2283,9 +2283,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 8684, - "end": 8726, - "replacementText": "sendableClass4: SendableClass = new SendableClass();" + "start": 8703, + "end": 8703, + "replacementText": ": SendableClass" } ], "suggest": "", @@ -2300,9 +2300,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 8726, - "end": 8772, - "replacementText": "noSendableClass4: NoSendableClass = new NoSendableClass();" + "start": 8747, + "end": 8747, + "replacementText": ": NoSendableClass" } ], "suggest": "", @@ -2317,9 +2317,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 8772, - "end": 8900, - "replacementText": "// Error, Field in sendable class must have type annotation (arkts-sendable-explicit-field-type)\nbooleanProp5?: boolean | undefined = true;" + "start": 8892, + "end": 8892, + "replacementText": ": boolean | undefined" } ], "suggest": "", @@ -2334,9 +2334,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 8900, - "end": 8923, - "replacementText": "numberProp5?: number | undefined = 42;" + "start": 8917, + "end": 8917, + "replacementText": ": number | undefined" } ], "suggest": "", @@ -2351,9 +2351,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 8923, - "end": 8951, - "replacementText": "stringProp5?: string | undefined = \"Hello\";" + "start": 8940, + "end": 8940, + "replacementText": ": string | undefined" } ], "suggest": "", @@ -2368,9 +2368,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 8951, - "end": 8980, - "replacementText": "arrayProp5?: number[] | undefined = [1, 2, 3];" + "start": 8967, + "end": 8967, + "replacementText": ": number[] | undefined" } ], "suggest": "", @@ -2385,9 +2385,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 8980, - "end": 9017, - "replacementText": "tupleProp5?: (string | number)[] | undefined = [\"typescript\", 4];" + "start": 8996, + "end": 8996, + "replacementText": ": (string | number)[] | undefined" } ], "suggest": "", @@ -2402,9 +2402,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 9017, - "end": 9047, - "replacementText": "enumProp5?: Color | undefined = Color.Green;" + "start": 9032, + "end": 9032, + "replacementText": ": Color | undefined" } ], "suggest": "", @@ -2451,9 +2451,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 9081, - "end": 9109, - "replacementText": "voidProp5?: undefined = undefined;" + "start": 9096, + "end": 9096, + "replacementText": ": undefined" } ], "suggest": "", @@ -2468,9 +2468,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 9109, - "end": 9132, - "replacementText": "nullProp5?: null | undefined = null;" + "start": 9124, + "end": 9124, + "replacementText": ": null | undefined" } ], "suggest": "", @@ -2485,9 +2485,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 9132, - "end": 9165, - "replacementText": "undefinedProp5?: undefined = undefined;" + "start": 9152, + "end": 9152, + "replacementText": ": undefined" } ], "suggest": "", @@ -2534,9 +2534,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 9211, - "end": 9254, - "replacementText": "sendableClass5?: SendableClass | undefined = new SendableClass();" + "start": 9231, + "end": 9231, + "replacementText": ": SendableClass | undefined" } ], "suggest": "", @@ -2551,9 +2551,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 9254, - "end": 9301, - "replacementText": "noSendableClass5?: NoSendableClass | undefined = new NoSendableClass();" + "start": 9276, + "end": 9276, + "replacementText": ": NoSendableClass | undefined" } ], "suggest": "", @@ -2568,9 +2568,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 9301, - "end": 9438, - "replacementText": "// Error, Field in sendable class must have type annotation (arkts-sendable-explicit-field-type)\npublic optBooleanProp6: boolean = true;" + "start": 9430, + "end": 9430, + "replacementText": ": boolean" } ], "suggest": "", @@ -2585,9 +2585,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 9438, - "end": 9470, - "replacementText": "public optNumberProp6: number = 42;" + "start": 9464, + "end": 9464, + "replacementText": ": number" } ], "suggest": "", @@ -2602,9 +2602,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 9470, - "end": 9507, - "replacementText": "public optStringProp6: string = \"Hello\";" + "start": 9496, + "end": 9496, + "replacementText": ": string" } ], "suggest": "", @@ -2619,9 +2619,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 9507, - "end": 9545, - "replacementText": "public optArrayProp6: number[] = [1, 2, 3];" + "start": 9532, + "end": 9532, + "replacementText": ": number[]" } ], "suggest": "", @@ -2636,9 +2636,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 9545, - "end": 9591, - "replacementText": "public optTupleProp6: (string | number)[] = [\"typescript\", 4];" + "start": 9570, + "end": 9570, + "replacementText": ": (string | number)[]" } ], "suggest": "", @@ -2653,9 +2653,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 9591, - "end": 9630, - "replacementText": "public optEnumProp6: Color = Color.Green;" + "start": 9615, + "end": 9615, + "replacementText": ": Color" } ], "suggest": "", @@ -2702,9 +2702,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 9673, - "end": 9710, - "replacementText": "public optVoidProp6: undefined = undefined;" + "start": 9697, + "end": 9697, + "replacementText": ": undefined" } ], "suggest": "", @@ -2719,9 +2719,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 9710, - "end": 9742, - "replacementText": "public optNullProp6: null = null;" + "start": 9734, + "end": 9734, + "replacementText": ": null" } ], "suggest": "", @@ -2736,9 +2736,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 9742, - "end": 9784, - "replacementText": "public optUndefinedProp6: undefined = undefined;" + "start": 9771, + "end": 9771, + "replacementText": ": undefined" } ], "suggest": "", @@ -2785,9 +2785,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 9839, - "end": 9891, - "replacementText": "public optSendableClass6: SendableClass = new SendableClass();" + "start": 9868, + "end": 9868, + "replacementText": ": SendableClass" } ], "suggest": "", @@ -2802,9 +2802,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 9891, - "end": 9947, - "replacementText": "public optNoSendableClass6: NoSendableClass = new NoSendableClass();" + "start": 9922, + "end": 9922, + "replacementText": ": NoSendableClass" } ], "suggest": "", @@ -2819,9 +2819,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 9947, - "end": 10086, - "replacementText": "// Error, Field in sendable class must have type annotation (arkts-sendable-explicit-field-type)\nreadonly optBooleanProp7: true = true;" + "start": 10078, + "end": 10078, + "replacementText": ": true" } ], "suggest": "", @@ -2836,9 +2836,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 10086, - "end": 10120, - "replacementText": "readonly optNumberProp7: 42 = 42;" + "start": 10114, + "end": 10114, + "replacementText": ": 42" } ], "suggest": "", @@ -2853,9 +2853,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 10120, - "end": 10159, - "replacementText": "readonly optStringProp7: \"Hello\" = \"Hello\";" + "start": 10148, + "end": 10148, + "replacementText": ": \"Hello\"" } ], "suggest": "", @@ -2870,9 +2870,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 10159, - "end": 10199, - "replacementText": "readonly optArrayProp7: number[] = [1, 2, 3];" + "start": 10186, + "end": 10186, + "replacementText": ": number[]" } ], "suggest": "", @@ -2887,9 +2887,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 10199, - "end": 10247, - "replacementText": "readonly optTupleProp7: (string | number)[] = [\"typescript\", 4];" + "start": 10226, + "end": 10226, + "replacementText": ": (string | number)[]" } ], "suggest": "", @@ -2904,9 +2904,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 10247, - "end": 10288, - "replacementText": "readonly optEnumProp7: Color.Green = Color.Green;" + "start": 10273, + "end": 10273, + "replacementText": ": Color.Green" } ], "suggest": "", @@ -2953,9 +2953,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 10333, - "end": 10372, - "replacementText": "readonly optVoidProp7: undefined = undefined;" + "start": 10359, + "end": 10359, + "replacementText": ": undefined" } ], "suggest": "", @@ -2970,9 +2970,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 10372, - "end": 10406, - "replacementText": "readonly optNullProp7: null = null;" + "start": 10398, + "end": 10398, + "replacementText": ": null" } ], "suggest": "", @@ -2987,9 +2987,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 10406, - "end": 10450, - "replacementText": "readonly optUndefinedProp7: undefined = undefined;" + "start": 10437, + "end": 10437, + "replacementText": ": undefined" } ], "suggest": "", @@ -3036,9 +3036,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 10507, - "end": 10561, - "replacementText": "readonly optSendableClass7: SendableClass = new SendableClass();" + "start": 10538, + "end": 10538, + "replacementText": ": SendableClass" } ], "suggest": "", @@ -3053,9 +3053,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 10561, - "end": 10619, - "replacementText": "readonly optNoSendableClass7: NoSendableClass = new NoSendableClass();" + "start": 10594, + "end": 10594, + "replacementText": ": NoSendableClass" } ], "suggest": "", @@ -3590,9 +3590,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 13165, - "end": 13292, - "replacementText": "// Error, Field in sendable class must have type annotation (arkts-sendable-explicit-field-type)\nbooleanProp4: boolean = true;" + "start": 13284, + "end": 13284, + "replacementText": ": boolean" } ], "suggest": "", @@ -3607,9 +3607,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 13292, - "end": 13314, - "replacementText": "numberProp4: number = 42;" + "start": 13308, + "end": 13308, + "replacementText": ": number" } ], "suggest": "", @@ -3624,9 +3624,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 13314, - "end": 13341, - "replacementText": "stringProp4: string = \"Hello\";" + "start": 13330, + "end": 13330, + "replacementText": ": string" } ], "suggest": "", @@ -3641,9 +3641,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 13341, - "end": 13369, - "replacementText": "arrayProp4: number[] = [1, 2, 3];" + "start": 13356, + "end": 13356, + "replacementText": ": number[]" } ], "suggest": "", @@ -3658,9 +3658,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 13369, - "end": 13405, - "replacementText": "tupleProp4: (string | number)[] = [\"typescript\", 4];" + "start": 13384, + "end": 13384, + "replacementText": ": (string | number)[]" } ], "suggest": "", @@ -3675,9 +3675,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 13405, - "end": 13434, - "replacementText": "enumProp4: Color = Color.Green;" + "start": 13419, + "end": 13419, + "replacementText": ": Color" } ], "suggest": "", @@ -3724,9 +3724,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 13467, - "end": 13494, - "replacementText": "voidProp4: undefined = undefined;" + "start": 13481, + "end": 13481, + "replacementText": ": undefined" } ], "suggest": "", @@ -3741,9 +3741,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 13494, - "end": 13516, - "replacementText": "nullProp4: null = null;" + "start": 13508, + "end": 13508, + "replacementText": ": null" } ], "suggest": "", @@ -3758,9 +3758,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 13516, - "end": 13548, - "replacementText": "undefinedProp4: undefined = undefined;" + "start": 13535, + "end": 13535, + "replacementText": ": undefined" } ], "suggest": "", @@ -3807,9 +3807,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 13593, - "end": 13635, - "replacementText": "sendableClass4: SendableClass = new SendableClass();" + "start": 13612, + "end": 13612, + "replacementText": ": SendableClass" } ], "suggest": "", @@ -3824,9 +3824,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 13635, - "end": 13681, - "replacementText": "noSendableClass4: NoSendableClass = new NoSendableClass();" + "start": 13656, + "end": 13656, + "replacementText": ": NoSendableClass" } ], "suggest": "", @@ -3841,9 +3841,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 13681, - "end": 13809, - "replacementText": "// Error, Field in sendable class must have type annotation (arkts-sendable-explicit-field-type)\nbooleanProp5?: boolean | undefined = true;" + "start": 13801, + "end": 13801, + "replacementText": ": boolean | undefined" } ], "suggest": "", @@ -3858,9 +3858,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 13809, - "end": 13832, - "replacementText": "numberProp5?: number | undefined = 42;" + "start": 13826, + "end": 13826, + "replacementText": ": number | undefined" } ], "suggest": "", @@ -3875,9 +3875,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 13832, - "end": 13860, - "replacementText": "stringProp5?: string | undefined = \"Hello\";" + "start": 13849, + "end": 13849, + "replacementText": ": string | undefined" } ], "suggest": "", @@ -3892,9 +3892,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 13860, - "end": 13889, - "replacementText": "arrayProp5?: number[] | undefined = [1, 2, 3];" + "start": 13876, + "end": 13876, + "replacementText": ": number[] | undefined" } ], "suggest": "", @@ -3909,9 +3909,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 13889, - "end": 13926, - "replacementText": "tupleProp5?: (string | number)[] | undefined = [\"typescript\", 4];" + "start": 13905, + "end": 13905, + "replacementText": ": (string | number)[] | undefined" } ], "suggest": "", @@ -3926,9 +3926,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 13926, - "end": 13956, - "replacementText": "enumProp5?: Color | undefined = Color.Green;" + "start": 13941, + "end": 13941, + "replacementText": ": Color | undefined" } ], "suggest": "", @@ -3975,9 +3975,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 13990, - "end": 14018, - "replacementText": "voidProp5?: undefined = undefined;" + "start": 14005, + "end": 14005, + "replacementText": ": undefined" } ], "suggest": "", @@ -3992,9 +3992,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 14018, - "end": 14041, - "replacementText": "nullProp5?: null | undefined = null;" + "start": 14033, + "end": 14033, + "replacementText": ": null | undefined" } ], "suggest": "", @@ -4009,9 +4009,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 14041, - "end": 14074, - "replacementText": "undefinedProp5?: undefined = undefined;" + "start": 14061, + "end": 14061, + "replacementText": ": undefined" } ], "suggest": "", @@ -4058,9 +4058,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 14120, - "end": 14163, - "replacementText": "sendableClass5?: SendableClass | undefined = new SendableClass();" + "start": 14140, + "end": 14140, + "replacementText": ": SendableClass | undefined" } ], "suggest": "", @@ -4075,9 +4075,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 14163, - "end": 14210, - "replacementText": "noSendableClass5?: NoSendableClass | undefined = new NoSendableClass();" + "start": 14185, + "end": 14185, + "replacementText": ": NoSendableClass | undefined" } ], "suggest": "", @@ -4092,9 +4092,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 14210, - "end": 14347, - "replacementText": "// Error, Field in sendable class must have type annotation (arkts-sendable-explicit-field-type)\npublic optBooleanProp6: boolean = true;" + "start": 14339, + "end": 14339, + "replacementText": ": boolean" } ], "suggest": "", @@ -4109,9 +4109,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 14347, - "end": 14379, - "replacementText": "public optNumberProp6: number = 42;" + "start": 14373, + "end": 14373, + "replacementText": ": number" } ], "suggest": "", @@ -4126,9 +4126,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 14379, - "end": 14416, - "replacementText": "public optStringProp6: string = \"Hello\";" + "start": 14405, + "end": 14405, + "replacementText": ": string" } ], "suggest": "", @@ -4143,9 +4143,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 14416, - "end": 14454, - "replacementText": "public optArrayProp6: number[] = [1, 2, 3];" + "start": 14441, + "end": 14441, + "replacementText": ": number[]" } ], "suggest": "", @@ -4160,9 +4160,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 14454, - "end": 14500, - "replacementText": "public optTupleProp6: (string | number)[] = [\"typescript\", 4];" + "start": 14479, + "end": 14479, + "replacementText": ": (string | number)[]" } ], "suggest": "", @@ -4177,9 +4177,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 14500, - "end": 14539, - "replacementText": "public optEnumProp6: Color = Color.Green;" + "start": 14524, + "end": 14524, + "replacementText": ": Color" } ], "suggest": "", @@ -4226,9 +4226,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 14582, - "end": 14619, - "replacementText": "public optVoidProp6: undefined = undefined;" + "start": 14606, + "end": 14606, + "replacementText": ": undefined" } ], "suggest": "", @@ -4243,9 +4243,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 14619, - "end": 14651, - "replacementText": "public optNullProp6: null = null;" + "start": 14643, + "end": 14643, + "replacementText": ": null" } ], "suggest": "", @@ -4260,9 +4260,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 14651, - "end": 14693, - "replacementText": "public optUndefinedProp6: undefined = undefined;" + "start": 14680, + "end": 14680, + "replacementText": ": undefined" } ], "suggest": "", @@ -4309,9 +4309,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 14748, - "end": 14800, - "replacementText": "public optSendableClass6: SendableClass = new SendableClass();" + "start": 14777, + "end": 14777, + "replacementText": ": SendableClass" } ], "suggest": "", @@ -4326,9 +4326,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 14800, - "end": 14856, - "replacementText": "public optNoSendableClass6: NoSendableClass = new NoSendableClass();" + "start": 14831, + "end": 14831, + "replacementText": ": NoSendableClass" } ], "suggest": "", @@ -4343,9 +4343,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 14856, - "end": 14995, - "replacementText": "// Error, Field in sendable class must have type annotation (arkts-sendable-explicit-field-type)\nreadonly optBooleanProp7: true = true;" + "start": 14987, + "end": 14987, + "replacementText": ": true" } ], "suggest": "", @@ -4360,9 +4360,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 14995, - "end": 15029, - "replacementText": "readonly optNumberProp7: 42 = 42;" + "start": 15023, + "end": 15023, + "replacementText": ": 42" } ], "suggest": "", @@ -4377,9 +4377,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 15029, - "end": 15068, - "replacementText": "readonly optStringProp7: \"Hello\" = \"Hello\";" + "start": 15057, + "end": 15057, + "replacementText": ": \"Hello\"" } ], "suggest": "", @@ -4394,9 +4394,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 15068, - "end": 15108, - "replacementText": "readonly optArrayProp7: number[] = [1, 2, 3];" + "start": 15095, + "end": 15095, + "replacementText": ": number[]" } ], "suggest": "", @@ -4411,9 +4411,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 15108, - "end": 15156, - "replacementText": "readonly optTupleProp7: (string | number)[] = [\"typescript\", 4];" + "start": 15135, + "end": 15135, + "replacementText": ": (string | number)[]" } ], "suggest": "", @@ -4428,9 +4428,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 15156, - "end": 15197, - "replacementText": "readonly optEnumProp7: Color.Green = Color.Green;" + "start": 15182, + "end": 15182, + "replacementText": ": Color.Green" } ], "suggest": "", @@ -4477,9 +4477,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 15242, - "end": 15281, - "replacementText": "readonly optVoidProp7: undefined = undefined;" + "start": 15268, + "end": 15268, + "replacementText": ": undefined" } ], "suggest": "", @@ -4494,9 +4494,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 15281, - "end": 15315, - "replacementText": "readonly optNullProp7: null = null;" + "start": 15307, + "end": 15307, + "replacementText": ": null" } ], "suggest": "", @@ -4511,9 +4511,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 15315, - "end": 15359, - "replacementText": "readonly optUndefinedProp7: undefined = undefined;" + "start": 15346, + "end": 15346, + "replacementText": ": undefined" } ], "suggest": "", @@ -4560,9 +4560,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 15416, - "end": 15470, - "replacementText": "readonly optSendableClass7: SendableClass = new SendableClass();" + "start": 15447, + "end": 15447, + "replacementText": ": SendableClass" } ], "suggest": "", @@ -4577,9 +4577,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 15470, - "end": 15528, - "replacementText": "readonly optNoSendableClass7: NoSendableClass = new NoSendableClass();" + "start": 15503, + "end": 15503, + "replacementText": ": NoSendableClass" } ], "suggest": "", diff --git a/ets2panda/linter/test/main/sendable_explicit_field_type.ets.migrate.ets b/ets2panda/linter/test/main/sendable_explicit_field_type.ets.migrate.ets new file mode 100644 index 0000000000..8bcbd30881 --- /dev/null +++ b/ets2panda/linter/test/main/sendable_explicit_field_type.ets.migrate.ets @@ -0,0 +1,659 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +declare namespace lang { + interface ISendable {} +} + +enum Color {Red, Green, Blue} + +@Sendable +class SendableClass { + public a: number = 1; +} + +class NoSendableClass { + public b: number = 1; +} + +interface GeneratedObjectLiteralInterface_1 { + key: string; +} +interface GeneratedObjectLiteralInterface_2 { + name: string; + age: number; +} +interface GeneratedObjectLiteralInterface_3 { + key: string; +} +interface GeneratedObjectLiteralInterface_4 { + name: string; + age: number; +} +interface GeneratedObjectLiteralInterface_5 { + key: string; +} +interface GeneratedObjectLiteralInterface_6 { + name: string; + age: number; +} +interface GeneratedObjectLiteralInterface_7 { + key: string; +} +interface GeneratedObjectLiteralInterface_8 { + name: string; + age: number; +} +@Sendable +class A { + booleanProp: boolean = true; + numberProp: number = 42; + stringProp: string = "Hello"; + arrayProp: number[] = [1, 2, 3]; + tupleProp: [string, number] = ["typescript", 4]; + enumProp: Color = Color.Green; + anyProp: any = { key: "value" }; + voidProp: void = undefined; + nullProp: null = null; + undefinedProp: undefined = undefined; + objectProp: object = { name: "John", age: 30 }; + sendableClass: SendableClass = new SendableClass(); + noSendableClass: NoSendableClass = new NoSendableClass(); + + optBooleanProp1?: boolean = true; + optNumberProp1?: number = 42; + optStringProp1?: string = "Hello"; + optArrayProp1?: number[] = [1, 2, 3]; + optTupleProp1?: [string, number] = ["typescript", 4]; + optEnumProp1?: Color = Color.Green; + optAnyProp1?: any = { key: "value" }; + optVoidProp1?: void = undefined; + optNullProp1?: null = null; + optUndefinedProp1?: undefined = undefined; + optObjectProp1?: object = { name: "John", age: 30 }; + optSendableClass1?: SendableClass = new SendableClass(); + optNoSendableClass1?: NoSendableClass = new NoSendableClass(); + + public optBooleanProp2: boolean = true; + public optNumberProp2: number = 42; + public optStringProp2: string = "Hello"; + public optArrayProp2: number[] = [1, 2, 3]; + public optTupleProp2: [string, number] = ["typescript", 4]; + public optEnumProp2: Color = Color.Green; + public optAnyProp2: any = { key: "value" }; + public optVoidProp2: void = undefined; + public optNullProp2: null = null; + public optUndefinedProp2: undefined = undefined; + public optObjectProp2: object = { name: "John", age: 30 }; + public optSendableClass2: SendableClass = new SendableClass(); + public optNoSendableClass2: NoSendableClass = new NoSendableClass(); + + readonly optBooleanProp3: boolean = true; + readonly optNumberProp3: number = 42; + readonly optStringProp3: string = "Hello"; + readonly optArrayProp3: number[] = [1, 2, 3]; + readonly optTupleProp3: [string, number] = ["typescript", 4]; + readonly optEnumProp3: Color = Color.Green; + readonly optAnyProp3: any = { key: "value" }; + readonly optVoidProp3: void = undefined; + readonly optNullProp3: null = null; + readonly optUndefinedProp3: undefined = undefined; + readonly optObjectProp3: object = { name: "John", age: 30 }; + readonly optSendableClass3: SendableClass = new SendableClass(); + readonly optNoSendableClass3: NoSendableClass = new NoSendableClass(); + + // Error, Field in sendable class must have type annotation (arkts-sendable-explicit-field-type) + booleanProp4: boolean = true; + numberProp4: number = 42; + stringProp4: string = "Hello"; + arrayProp4: number[] = [1, 2, 3]; + tupleProp4: (string | number)[] = ["typescript", 4]; + enumProp4: Color = Color.Green; + anyProp4: GeneratedObjectLiteralInterface_1 = { key: "value" }; + voidProp4: undefined = undefined; + nullProp4: null = null; + undefinedProp4: undefined = undefined; + objectProp4: GeneratedObjectLiteralInterface_2 = { name: "John", age: 30 }; + sendableClass4: SendableClass = new SendableClass(); + noSendableClass4: NoSendableClass = new NoSendableClass(); + + // Error, Field in sendable class must have type annotation (arkts-sendable-explicit-field-type) + booleanProp5?: boolean | undefined = true; + numberProp5?: number | undefined = 42; + stringProp5?: string | undefined = "Hello"; + arrayProp5?: number[] | undefined = [1, 2, 3]; + tupleProp5?: (string | number)[] | undefined = ["typescript", 4]; + enumProp5?: Color | undefined = Color.Green; + anyProp5?: GeneratedObjectLiteralInterface_3 = { key: "value" }; + voidProp5?: undefined = undefined; + nullProp5?: null | undefined = null; + undefinedProp5?: undefined = undefined; + objectProp5?: GeneratedObjectLiteralInterface_4 = { name: "John", age: 30 }; + sendableClass5?: SendableClass | undefined = new SendableClass(); + noSendableClass5?: NoSendableClass | undefined = new NoSendableClass(); + + // Error, Field in sendable class must have type annotation (arkts-sendable-explicit-field-type) + public optBooleanProp6: boolean = true; + public optNumberProp6: number = 42; + public optStringProp6: string = "Hello"; + public optArrayProp6: number[] = [1, 2, 3]; + public optTupleProp6: (string | number)[] = ["typescript", 4]; + public optEnumProp6: Color = Color.Green; + public optAnyProp6: GeneratedObjectLiteralInterface_5 = { key: "value" }; + public optVoidProp6: undefined = undefined; + public optNullProp6: null = null; + public optUndefinedProp6: undefined = undefined; + public optObjectProp6: GeneratedObjectLiteralInterface_6 = { name: "John", age: 30 }; + public optSendableClass6: SendableClass = new SendableClass(); + public optNoSendableClass6: NoSendableClass = new NoSendableClass(); + + // Error, Field in sendable class must have type annotation (arkts-sendable-explicit-field-type) + readonly optBooleanProp7: true = true; + readonly optNumberProp7: 42 = 42; + readonly optStringProp7: "Hello" = "Hello"; + readonly optArrayProp7: number[] = [1, 2, 3]; + readonly optTupleProp7: (string | number)[] = ["typescript", 4]; + readonly optEnumProp7: Color.Green = Color.Green; + readonly optAnyProp7: GeneratedObjectLiteralInterface_7 = { key: "value" }; + readonly optVoidProp7: undefined = undefined; + readonly optNullProp7: null = null; + readonly optUndefinedProp7: undefined = undefined; + readonly optObjectProp7: GeneratedObjectLiteralInterface_8 = { name: "John", age: 30 }; + readonly optSendableClass7: SendableClass = new SendableClass(); + readonly optNoSendableClass7: NoSendableClass = new NoSendableClass(); +} + +interface GeneratedObjectLiteralInterface_9 { + key: string; +} +interface GeneratedObjectLiteralInterface_10 { + name: string; + age: number; +} +interface GeneratedObjectLiteralInterface_11 { + key: string; +} +interface GeneratedObjectLiteralInterface_12 { + name: string; + age: number; +} +interface GeneratedObjectLiteralInterface_13 { + key: string; +} +interface GeneratedObjectLiteralInterface_14 { + name: string; + age: number; +} +interface GeneratedObjectLiteralInterface_15 { + key: string; +} +interface GeneratedObjectLiteralInterface_16 { + name: string; + age: number; +} +@Sendable +class A1 extends A { + constructor() { + super(); + } + booleanProp: boolean = true; + numberProp: number = 42; + stringProp: string = "Hello"; + arrayProp: number[] = [1, 2, 3]; + tupleProp: [string, number] = ["typescript", 4]; + enumProp: Color = Color.Green; + anyProp: any = { key: "value" }; + voidProp: void = undefined; + nullProp: null = null; + undefinedProp: undefined = undefined; + objectProp: object = { name: "John", age: 30 }; + sendableClass: SendableClass = new SendableClass(); + noSendableClass: NoSendableClass = new NoSendableClass(); + + optBooleanProp1?: boolean = true; + optNumberProp1?: number = 42; + optStringProp1?: string = "Hello"; + optArrayProp1?: number[] = [1, 2, 3]; + optTupleProp1?: [string, number] = ["typescript", 4]; + optEnumProp1?: Color = Color.Green; + optAnyProp1?: any = { key: "value" }; + optVoidProp1?: void = undefined; + optNullProp1?: null = null; + optUndefinedProp1?: undefined = undefined; + optObjectProp1?: object = { name: "John", age: 30 }; + optSendableClass1?: SendableClass = new SendableClass(); + optNoSendableClass1?: NoSendableClass = new NoSendableClass(); + + public optBooleanProp2: boolean = true; + public optNumberProp2: number = 42; + public optStringProp2: string = "Hello"; + public optArrayProp2: number[] = [1, 2, 3]; + public optTupleProp2: [string, number] = ["typescript", 4]; + public optEnumProp2: Color = Color.Green; + public optAnyProp2: any = { key: "value" }; + public optVoidProp2: void = undefined; + public optNullProp2: null = null; + public optUndefinedProp2: undefined = undefined; + public optObjectProp2: object = { name: "John", age: 30 }; + public optSendableClass2: SendableClass = new SendableClass(); + public optNoSendableClass2: NoSendableClass = new NoSendableClass(); + + readonly optBooleanProp3: boolean = true; + readonly optNumberProp3: number = 42; + readonly optStringProp3: string = "Hello"; + readonly optArrayProp3: number[] = [1, 2, 3]; + readonly optTupleProp3: [string, number] = ["typescript", 4]; + readonly optEnumProp3: Color = Color.Green; + readonly optAnyProp3: any = { key: "value" }; + readonly optVoidProp3: void = undefined; + readonly optNullProp3: null = null; + readonly optUndefinedProp3: undefined = undefined; + readonly optObjectProp3: object = { name: "John", age: 30 }; + readonly optSendableClass3: SendableClass = new SendableClass(); + readonly optNoSendableClass3: NoSendableClass = new NoSendableClass(); + + // Error, Field in sendable class must have type annotation (arkts-sendable-explicit-field-type) + booleanProp4: boolean = true; + numberProp4: number = 42; + stringProp4: string = "Hello"; + arrayProp4: number[] = [1, 2, 3]; + tupleProp4: (string | number)[] = ["typescript", 4]; + enumProp4: Color = Color.Green; + anyProp4: GeneratedObjectLiteralInterface_9 = { key: "value" }; + voidProp4: undefined = undefined; + nullProp4: null = null; + undefinedProp4: undefined = undefined; + objectProp4: GeneratedObjectLiteralInterface_10 = { name: "John", age: 30 }; + sendableClass4: SendableClass = new SendableClass(); + noSendableClass4: NoSendableClass = new NoSendableClass(); + + // Error, Field in sendable class must have type annotation (arkts-sendable-explicit-field-type) + booleanProp5?: boolean | undefined = true; + numberProp5?: number | undefined = 42; + stringProp5?: string | undefined = "Hello"; + arrayProp5?: number[] | undefined = [1, 2, 3]; + tupleProp5?: (string | number)[] | undefined = ["typescript", 4]; + enumProp5?: Color | undefined = Color.Green; + anyProp5?: GeneratedObjectLiteralInterface_11 = { key: "value" }; + voidProp5?: undefined = undefined; + nullProp5?: null | undefined = null; + undefinedProp5?: undefined = undefined; + objectProp5?: GeneratedObjectLiteralInterface_12 = { name: "John", age: 30 }; + sendableClass5?: SendableClass | undefined = new SendableClass(); + noSendableClass5?: NoSendableClass | undefined = new NoSendableClass(); + + // Error, Field in sendable class must have type annotation (arkts-sendable-explicit-field-type) + public optBooleanProp6: boolean = true; + public optNumberProp6: number = 42; + public optStringProp6: string = "Hello"; + public optArrayProp6: number[] = [1, 2, 3]; + public optTupleProp6: (string | number)[] = ["typescript", 4]; + public optEnumProp6: Color = Color.Green; + public optAnyProp6: GeneratedObjectLiteralInterface_13 = { key: "value" }; + public optVoidProp6: undefined = undefined; + public optNullProp6: null = null; + public optUndefinedProp6: undefined = undefined; + public optObjectProp6: GeneratedObjectLiteralInterface_14 = { name: "John", age: 30 }; + public optSendableClass6: SendableClass = new SendableClass(); + public optNoSendableClass6: NoSendableClass = new NoSendableClass(); + + // Error, Field in sendable class must have type annotation (arkts-sendable-explicit-field-type) + readonly optBooleanProp7: true = true; + readonly optNumberProp7: 42 = 42; + readonly optStringProp7: "Hello" = "Hello"; + readonly optArrayProp7: number[] = [1, 2, 3]; + readonly optTupleProp7: (string | number)[] = ["typescript", 4]; + readonly optEnumProp7: Color.Green = Color.Green; + readonly optAnyProp7: GeneratedObjectLiteralInterface_15 = { key: "value" }; + readonly optVoidProp7: undefined = undefined; + readonly optNullProp7: null = null; + readonly optUndefinedProp7: undefined = undefined; + readonly optObjectProp7: GeneratedObjectLiteralInterface_16 = { name: "John", age: 30 }; + readonly optSendableClass7: SendableClass = new SendableClass(); + readonly optNoSendableClass7: NoSendableClass = new NoSendableClass(); +} + +interface GeneratedObjectLiteralInterface_17 { + key: string; +} +interface GeneratedObjectLiteralInterface_18 { + name: string; + age: number; +} +interface GeneratedObjectLiteralInterface_19 { + key: string; +} +interface GeneratedObjectLiteralInterface_20 { + name: string; + age: number; +} +interface GeneratedObjectLiteralInterface_21 { + key: string; +} +interface GeneratedObjectLiteralInterface_22 { + name: string; + age: number; +} +interface GeneratedObjectLiteralInterface_23 { + key: string; +} +interface GeneratedObjectLiteralInterface_24 { + name: string; + age: number; +} +@Sendable +class A2 implements lang.ISendable { + booleanProp: boolean = true; + numberProp: number = 42; + stringProp: string = "Hello"; + arrayProp: number[] = [1, 2, 3]; + tupleProp: [string, number] = ["typescript", 4]; + enumProp: Color = Color.Green; + anyProp: any = { key: "value" }; + voidProp: void = undefined; + nullProp: null = null; + undefinedProp: undefined = undefined; + objectProp: object = { name: "John", age: 30 }; + sendableClass: SendableClass = new SendableClass(); + noSendableClass: NoSendableClass = new NoSendableClass(); + + optBooleanProp1?: boolean = true; + optNumberProp1?: number = 42; + optStringProp1?: string = "Hello"; + optArrayProp1?: number[] = [1, 2, 3]; + optTupleProp1?: [string, number] = ["typescript", 4]; + optEnumProp1?: Color = Color.Green; + optAnyProp1?: any = { key: "value" }; + optVoidProp1?: void = undefined; + optNullProp1?: null = null; + optUndefinedProp1?: undefined = undefined; + optObjectProp1?: object = { name: "John", age: 30 }; + optSendableClass1?: SendableClass = new SendableClass(); + optNoSendableClass1?: NoSendableClass = new NoSendableClass(); + + public optBooleanProp2: boolean = true; + public optNumberProp2: number = 42; + public optStringProp2: string = "Hello"; + public optArrayProp2: number[] = [1, 2, 3]; + public optTupleProp2: [string, number] = ["typescript", 4]; + public optEnumProp2: Color = Color.Green; + public optAnyProp2: any = { key: "value" }; + public optVoidProp2: void = undefined; + public optNullProp2: null = null; + public optUndefinedProp2: undefined = undefined; + public optObjectProp2: object = { name: "John", age: 30 }; + public optSendableClass2: SendableClass = new SendableClass(); + public optNoSendableClass2: NoSendableClass = new NoSendableClass(); + + readonly optBooleanProp3: boolean = true; + readonly optNumberProp3: number = 42; + readonly optStringProp3: string = "Hello"; + readonly optArrayProp3: number[] = [1, 2, 3]; + readonly optTupleProp3: [string, number] = ["typescript", 4]; + readonly optEnumProp3: Color = Color.Green; + readonly optAnyProp3: any = { key: "value" }; + readonly optVoidProp3: void = undefined; + readonly optNullProp3: null = null; + readonly optUndefinedProp3: undefined = undefined; + readonly optObjectProp3: object = { name: "John", age: 30 }; + readonly optSendableClass3: SendableClass = new SendableClass(); + readonly optNoSendableClass3: NoSendableClass = new NoSendableClass(); + + // Error, Field in sendable class must have type annotation (arkts-sendable-explicit-field-type) + booleanProp4: boolean = true; + numberProp4: number = 42; + stringProp4: string = "Hello"; + arrayProp4: number[] = [1, 2, 3]; + tupleProp4: (string | number)[] = ["typescript", 4]; + enumProp4: Color = Color.Green; + anyProp4: GeneratedObjectLiteralInterface_17 = { key: "value" }; + voidProp4: undefined = undefined; + nullProp4: null = null; + undefinedProp4: undefined = undefined; + objectProp4: GeneratedObjectLiteralInterface_18 = { name: "John", age: 30 }; + sendableClass4: SendableClass = new SendableClass(); + noSendableClass4: NoSendableClass = new NoSendableClass(); + + // Error, Field in sendable class must have type annotation (arkts-sendable-explicit-field-type) + booleanProp5?: boolean | undefined = true; + numberProp5?: number | undefined = 42; + stringProp5?: string | undefined = "Hello"; + arrayProp5?: number[] | undefined = [1, 2, 3]; + tupleProp5?: (string | number)[] | undefined = ["typescript", 4]; + enumProp5?: Color | undefined = Color.Green; + anyProp5?: GeneratedObjectLiteralInterface_19 = { key: "value" }; + voidProp5?: undefined = undefined; + nullProp5?: null | undefined = null; + undefinedProp5?: undefined = undefined; + objectProp5?: GeneratedObjectLiteralInterface_20 = { name: "John", age: 30 }; + sendableClass5?: SendableClass | undefined = new SendableClass(); + noSendableClass5?: NoSendableClass | undefined = new NoSendableClass(); + + // Error, Field in sendable class must have type annotation (arkts-sendable-explicit-field-type) + public optBooleanProp6: boolean = true; + public optNumberProp6: number = 42; + public optStringProp6: string = "Hello"; + public optArrayProp6: number[] = [1, 2, 3]; + public optTupleProp6: (string | number)[] = ["typescript", 4]; + public optEnumProp6: Color = Color.Green; + public optAnyProp6: GeneratedObjectLiteralInterface_21 = { key: "value" }; + public optVoidProp6: undefined = undefined; + public optNullProp6: null = null; + public optUndefinedProp6: undefined = undefined; + public optObjectProp6: GeneratedObjectLiteralInterface_22 = { name: "John", age: 30 }; + public optSendableClass6: SendableClass = new SendableClass(); + public optNoSendableClass6: NoSendableClass = new NoSendableClass(); + + // Error, Field in sendable class must have type annotation (arkts-sendable-explicit-field-type) + readonly optBooleanProp7: true = true; + readonly optNumberProp7: 42 = 42; + readonly optStringProp7: "Hello" = "Hello"; + readonly optArrayProp7: number[] = [1, 2, 3]; + readonly optTupleProp7: (string | number)[] = ["typescript", 4]; + readonly optEnumProp7: Color.Green = Color.Green; + readonly optAnyProp7: GeneratedObjectLiteralInterface_23 = { key: "value" }; + readonly optVoidProp7: undefined = undefined; + readonly optNullProp7: null = null; + readonly optUndefinedProp7: undefined = undefined; + readonly optObjectProp7: GeneratedObjectLiteralInterface_24 = { name: "John", age: 30 }; + readonly optSendableClass7: SendableClass = new SendableClass(); + readonly optNoSendableClass7: NoSendableClass = new NoSendableClass(); +} + +interface GeneratedObjectLiteralInterface_25 { + key: string; +} +interface GeneratedObjectLiteralInterface_26 { + name: string; + age: number; +} +interface GeneratedObjectLiteralInterface_27 { + key: string; +} +interface GeneratedObjectLiteralInterface_28 { + name: string; + age: number; +} +interface GeneratedObjectLiteralInterface_29 { + key: string; +} +interface GeneratedObjectLiteralInterface_30 { + name: string; + age: number; +} +interface GeneratedObjectLiteralInterface_31 { + key: string; +} +interface GeneratedObjectLiteralInterface_32 { + name: string; + age: number; +} +class A3 { + booleanProp: boolean = true; + numberProp: number = 42; + stringProp: string = "Hello"; + arrayProp: number[] = [1, 2, 3]; + tupleProp: [string, number] = ["typescript", 4]; + enumProp: Color = Color.Green; + anyProp: any = { key: "value" }; + voidProp: void = undefined; + nullProp: null = null; + undefinedProp: undefined = undefined; + objectProp: object = { name: "John", age: 30 }; + sendableClass: SendableClass = new SendableClass(); + noSendableClass: NoSendableClass = new NoSendableClass(); + + optBooleanProp1?: boolean = true; + optNumberProp1?: number = 42; + optStringProp1?: string = "Hello"; + optArrayProp1?: number[] = [1, 2, 3]; + optTupleProp1?: [string, number] = ["typescript", 4]; + optEnumProp1?: Color = Color.Green; + optAnyProp1?: any = { key: "value" }; + optVoidProp1?: void = undefined; + optNullProp1?: null = null; + optUndefinedProp1?: undefined = undefined; + optObjectProp1?: object = { name: "John", age: 30 }; + optSendableClass1?: SendableClass = new SendableClass(); + optNoSendableClass1?: NoSendableClass = new NoSendableClass(); + + public optBooleanProp2: boolean = true; + public optNumberProp2: number = 42; + public optStringProp2: string = "Hello"; + public optArrayProp2: number[] = [1, 2, 3]; + public optTupleProp2: [string, number] = ["typescript", 4]; + public optEnumProp2: Color = Color.Green; + public optAnyProp2: any = { key: "value" }; + public optVoidProp2: void = undefined; + public optNullProp2: null = null; + public optUndefinedProp2: undefined = undefined; + public optObjectProp2: object = { name: "John", age: 30 }; + public optSendableClass2: SendableClass = new SendableClass(); + public optNoSendableClass2: NoSendableClass = new NoSendableClass(); + + readonly optBooleanProp3: boolean = true; + readonly optNumberProp3: number = 42; + readonly optStringProp3: string = "Hello"; + readonly optArrayProp3: number[] = [1, 2, 3]; + readonly optTupleProp3: [string, number] = ["typescript", 4]; + readonly optEnumProp3: Color = Color.Green; + readonly optAnyProp3: any = { key: "value" }; + readonly optVoidProp3: void = undefined; + readonly optNullProp3: null = null; + readonly optUndefinedProp3: undefined = undefined; + readonly optObjectProp3: object = { name: "John", age: 30 }; + readonly optSendableClass3: SendableClass = new SendableClass(); + readonly optNoSendableClass3: NoSendableClass = new NoSendableClass(); + + booleanProp4 = true; + numberProp4 = 42; + stringProp4 = "Hello"; + arrayProp4 = [1, 2, 3]; + tupleProp4 = ["typescript", 4]; + enumProp4 = Color.Green; + anyProp4: GeneratedObjectLiteralInterface_25 = { key: "value" }; + voidProp4 = undefined; + nullProp4 = null; + undefinedProp4 = undefined; + objectProp4: GeneratedObjectLiteralInterface_26 = { name: "John", age: 30 }; + sendableClass4 = new SendableClass(); + noSendableClass4 = new NoSendableClass(); + + booleanProp5? = true; + numberProp5? = 42; + stringProp5? = "Hello"; + arrayProp5? = [1, 2, 3]; + tupleProp5? = ["typescript", 4]; + enumProp5? = Color.Green; + anyProp5?: GeneratedObjectLiteralInterface_27 = { key: "value" }; + voidProp5? = undefined; + nullProp5? = null; + undefinedProp5? = undefined; + objectProp5?: GeneratedObjectLiteralInterface_28 = { name: "John", age: 30 }; + sendableClass5? = new SendableClass(); + noSendableClass5? = new NoSendableClass(); + + public optBooleanProp6 = true; + public optNumberProp6 = 42; + public optStringProp6 = "Hello"; + public optArrayProp6 = [1, 2, 3]; + public optTupleProp6 = ["typescript", 4]; + public optEnumProp6 = Color.Green; + public optAnyProp6: GeneratedObjectLiteralInterface_29 = { key: "value" }; + public optVoidProp6 = undefined; + public optNullProp6 = null; + public optUndefinedProp6 = undefined; + public optObjectProp6: GeneratedObjectLiteralInterface_30 = { name: "John", age: 30 }; + public optSendableClass6 = new SendableClass(); + public optNoSendableClass6 = new NoSendableClass(); + + readonly optBooleanProp7 = true; + readonly optNumberProp7 = 42; + readonly optStringProp7 = "Hello"; + readonly optArrayProp7 = [1, 2, 3]; + readonly optTupleProp7 = ["typescript", 4]; + readonly optEnumProp7 = Color.Green; + readonly optAnyProp7: GeneratedObjectLiteralInterface_31 = { key: "value" }; + readonly optVoidProp7 = undefined; + readonly optNullProp7 = null; + readonly optUndefinedProp7 = undefined; + readonly optObjectProp7: GeneratedObjectLiteralInterface_32 = { name: "John", age: 30 }; + readonly optSendableClass7 = new SendableClass(); + readonly optNoSendableClass7 = new NoSendableClass(); +} + +interface I extends lang.ISendable { + booleanProp: boolean; + numberProp: number; + stringProp: string; + arrayProp: number[]; + tupleProp: [string, number]; + enumProp: Color; + anyProp: any; + voidProp: void; + nullProp: null; + undefinedProp: undefined; + objectProp: object; + sendableClass: SendableClass; + noSendableClass: NoSendableClass; + + optBooleanProp1?: boolean; + optNumberProp1?: number; + optStringProp1?: string; + optArrayProp1?: number[]; + optTupleProp1?: [string, number]; + optEnumProp1?: Color; + optAnyProp1?: any; + optVoidProp1?: void; + optNullProp1?: null; + optUndefinedProp1?: undefined; + optObjectProp1?: object; + optSendableClass1?: SendableClass; + optNoSendableClass1?: NoSendableClass; + + readonly optBooleanProp3: boolean; + readonly optNumberProp3: number; + readonly optStringProp3: string; + readonly optArrayProp3: number[]; + readonly optTupleProp3: [string, number]; + readonly optEnumProp3: Color; + readonly optAnyProp3: any; + readonly optVoidProp3: void; + readonly optNullProp3: null; + readonly optUndefinedProp3: undefined; + readonly optObjectProp3: object; + readonly optSendableClass3: SendableClass; + readonly optNoSendableClass3: NoSendableClass; +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/sendable_explicit_field_type.ets.migrate.json b/ets2panda/linter/test/main/sendable_explicit_field_type.ets.migrate.json new file mode 100644 index 0000000000..b8c6d94da9 --- /dev/null +++ b/ets2panda/linter/test/main/sendable_explicit_field_type.ets.migrate.json @@ -0,0 +1,2498 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 66, + "column": 23, + "endLine": 66, + "endColumn": 28, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 44, + "endLine": 73, + "endColumn": 59, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 80, + "column": 28, + "endLine": 80, + "endColumn": 33, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 87, + "column": 49, + "endLine": 87, + "endColumn": 64, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 94, + "column": 34, + "endLine": 94, + "endColumn": 39, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 101, + "column": 55, + "endLine": 101, + "endColumn": 70, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 108, + "column": 36, + "endLine": 108, + "endColumn": 41, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 115, + "column": 57, + "endLine": 115, + "endColumn": 72, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 123, + "column": 24, + "endLine": 123, + "endColumn": 29, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 130, + "column": 45, + "endLine": 130, + "endColumn": 60, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 138, + "column": 37, + "endLine": 138, + "endColumn": 42, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 145, + "column": 58, + "endLine": 145, + "endColumn": 73, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 153, + "column": 34, + "endLine": 153, + "endColumn": 39, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 160, + "column": 55, + "endLine": 160, + "endColumn": 70, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 168, + "column": 42, + "endLine": 168, + "endColumn": 47, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 175, + "column": 57, + "endLine": 175, + "endColumn": 72, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 64, + "column": 5, + "endLine": 64, + "endColumn": 37, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 65, + "column": 5, + "endLine": 65, + "endColumn": 53, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 66, + "column": 5, + "endLine": 66, + "endColumn": 35, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 67, + "column": 5, + "endLine": 67, + "endColumn": 37, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 67, + "column": 14, + "endLine": 67, + "endColumn": 17, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 68, + "column": 5, + "endLine": 68, + "endColumn": 32, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 5, + "endLine": 71, + "endColumn": 52, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 26, + "endLine": 71, + "endColumn": 27, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 5, + "endLine": 73, + "endColumn": 62, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 78, + "column": 5, + "endLine": 78, + "endColumn": 42, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 79, + "column": 5, + "endLine": 79, + "endColumn": 58, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 80, + "column": 5, + "endLine": 80, + "endColumn": 40, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 81, + "column": 5, + "endLine": 81, + "endColumn": 42, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 81, + "column": 19, + "endLine": 81, + "endColumn": 22, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 82, + "column": 5, + "endLine": 82, + "endColumn": 37, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 85, + "column": 5, + "endLine": 85, + "endColumn": 57, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 85, + "column": 31, + "endLine": 85, + "endColumn": 32, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 87, + "column": 5, + "endLine": 87, + "endColumn": 67, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 92, + "column": 5, + "endLine": 92, + "endColumn": 48, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 93, + "column": 5, + "endLine": 93, + "endColumn": 64, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 94, + "column": 5, + "endLine": 94, + "endColumn": 46, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 95, + "column": 5, + "endLine": 95, + "endColumn": 48, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 95, + "column": 25, + "endLine": 95, + "endColumn": 28, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 96, + "column": 5, + "endLine": 96, + "endColumn": 43, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 99, + "column": 5, + "endLine": 99, + "endColumn": 63, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 99, + "column": 37, + "endLine": 99, + "endColumn": 38, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 101, + "column": 5, + "endLine": 101, + "endColumn": 73, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 106, + "column": 5, + "endLine": 106, + "endColumn": 50, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 107, + "column": 5, + "endLine": 107, + "endColumn": 66, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 108, + "column": 5, + "endLine": 108, + "endColumn": 48, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 109, + "column": 5, + "endLine": 109, + "endColumn": 50, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 109, + "column": 27, + "endLine": 109, + "endColumn": 30, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 110, + "column": 5, + "endLine": 110, + "endColumn": 45, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 113, + "column": 5, + "endLine": 113, + "endColumn": 65, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 113, + "column": 39, + "endLine": 113, + "endColumn": 40, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 115, + "column": 5, + "endLine": 115, + "endColumn": 75, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 121, + "column": 5, + "endLine": 121, + "endColumn": 38, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 122, + "column": 5, + "endLine": 122, + "endColumn": 57, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 123, + "column": 5, + "endLine": 123, + "endColumn": 36, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 124, + "column": 5, + "endLine": 124, + "endColumn": 68, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 128, + "column": 5, + "endLine": 128, + "endColumn": 80, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 130, + "column": 5, + "endLine": 130, + "endColumn": 63, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 136, + "column": 5, + "endLine": 136, + "endColumn": 51, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 137, + "column": 5, + "endLine": 137, + "endColumn": 70, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 138, + "column": 5, + "endLine": 138, + "endColumn": 49, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 139, + "column": 5, + "endLine": 139, + "endColumn": 69, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 143, + "column": 5, + "endLine": 143, + "endColumn": 81, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 145, + "column": 5, + "endLine": 145, + "endColumn": 76, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 151, + "column": 5, + "endLine": 151, + "endColumn": 48, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 152, + "column": 5, + "endLine": 152, + "endColumn": 67, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 153, + "column": 5, + "endLine": 153, + "endColumn": 46, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 154, + "column": 5, + "endLine": 154, + "endColumn": 78, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 158, + "column": 5, + "endLine": 158, + "endColumn": 90, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 160, + "column": 5, + "endLine": 160, + "endColumn": 73, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 163, + "column": 5, + "endLine": 163, + "endColumn": 43, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 164, + "column": 5, + "endLine": 164, + "endColumn": 38, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 165, + "column": 5, + "endLine": 165, + "endColumn": 48, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 166, + "column": 5, + "endLine": 166, + "endColumn": 50, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 167, + "column": 5, + "endLine": 167, + "endColumn": 69, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 168, + "column": 5, + "endLine": 168, + "endColumn": 54, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 169, + "column": 5, + "endLine": 169, + "endColumn": 80, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 173, + "column": 5, + "endLine": 173, + "endColumn": 92, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 175, + "column": 5, + "endLine": 175, + "endColumn": 75, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 216, + "column": 23, + "endLine": 216, + "endColumn": 28, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 223, + "column": 44, + "endLine": 223, + "endColumn": 59, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 230, + "column": 28, + "endLine": 230, + "endColumn": 33, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 237, + "column": 49, + "endLine": 237, + "endColumn": 64, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 244, + "column": 34, + "endLine": 244, + "endColumn": 39, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 251, + "column": 55, + "endLine": 251, + "endColumn": 70, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 258, + "column": 36, + "endLine": 258, + "endColumn": 41, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 265, + "column": 57, + "endLine": 265, + "endColumn": 72, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 273, + "column": 24, + "endLine": 273, + "endColumn": 29, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 280, + "column": 45, + "endLine": 280, + "endColumn": 60, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 288, + "column": 37, + "endLine": 288, + "endColumn": 42, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 295, + "column": 58, + "endLine": 295, + "endColumn": 73, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 303, + "column": 34, + "endLine": 303, + "endColumn": 39, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 310, + "column": 55, + "endLine": 310, + "endColumn": 70, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 318, + "column": 42, + "endLine": 318, + "endColumn": 47, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 325, + "column": 57, + "endLine": 325, + "endColumn": 72, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 214, + "column": 5, + "endLine": 214, + "endColumn": 37, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 215, + "column": 5, + "endLine": 215, + "endColumn": 53, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 216, + "column": 5, + "endLine": 216, + "endColumn": 35, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 217, + "column": 5, + "endLine": 217, + "endColumn": 37, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 217, + "column": 14, + "endLine": 217, + "endColumn": 17, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 218, + "column": 5, + "endLine": 218, + "endColumn": 32, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 221, + "column": 5, + "endLine": 221, + "endColumn": 52, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 221, + "column": 26, + "endLine": 221, + "endColumn": 27, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 223, + "column": 5, + "endLine": 223, + "endColumn": 62, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 228, + "column": 5, + "endLine": 228, + "endColumn": 42, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 229, + "column": 5, + "endLine": 229, + "endColumn": 58, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 230, + "column": 5, + "endLine": 230, + "endColumn": 40, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 231, + "column": 5, + "endLine": 231, + "endColumn": 42, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 231, + "column": 19, + "endLine": 231, + "endColumn": 22, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 232, + "column": 5, + "endLine": 232, + "endColumn": 37, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 235, + "column": 5, + "endLine": 235, + "endColumn": 57, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 235, + "column": 31, + "endLine": 235, + "endColumn": 32, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 237, + "column": 5, + "endLine": 237, + "endColumn": 67, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 242, + "column": 5, + "endLine": 242, + "endColumn": 48, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 243, + "column": 5, + "endLine": 243, + "endColumn": 64, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 244, + "column": 5, + "endLine": 244, + "endColumn": 46, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 245, + "column": 5, + "endLine": 245, + "endColumn": 48, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 245, + "column": 25, + "endLine": 245, + "endColumn": 28, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 246, + "column": 5, + "endLine": 246, + "endColumn": 43, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 249, + "column": 5, + "endLine": 249, + "endColumn": 63, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 249, + "column": 37, + "endLine": 249, + "endColumn": 38, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 251, + "column": 5, + "endLine": 251, + "endColumn": 73, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 256, + "column": 5, + "endLine": 256, + "endColumn": 50, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 257, + "column": 5, + "endLine": 257, + "endColumn": 66, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 258, + "column": 5, + "endLine": 258, + "endColumn": 48, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 259, + "column": 5, + "endLine": 259, + "endColumn": 50, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 259, + "column": 27, + "endLine": 259, + "endColumn": 30, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 260, + "column": 5, + "endLine": 260, + "endColumn": 45, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 263, + "column": 5, + "endLine": 263, + "endColumn": 65, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 263, + "column": 39, + "endLine": 263, + "endColumn": 40, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 265, + "column": 5, + "endLine": 265, + "endColumn": 75, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 271, + "column": 5, + "endLine": 271, + "endColumn": 38, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 272, + "column": 5, + "endLine": 272, + "endColumn": 57, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 273, + "column": 5, + "endLine": 273, + "endColumn": 36, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 274, + "column": 5, + "endLine": 274, + "endColumn": 68, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 278, + "column": 5, + "endLine": 278, + "endColumn": 81, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 280, + "column": 5, + "endLine": 280, + "endColumn": 63, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 286, + "column": 5, + "endLine": 286, + "endColumn": 51, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 287, + "column": 5, + "endLine": 287, + "endColumn": 70, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 288, + "column": 5, + "endLine": 288, + "endColumn": 49, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 289, + "column": 5, + "endLine": 289, + "endColumn": 70, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 293, + "column": 5, + "endLine": 293, + "endColumn": 82, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 295, + "column": 5, + "endLine": 295, + "endColumn": 76, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 301, + "column": 5, + "endLine": 301, + "endColumn": 48, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 302, + "column": 5, + "endLine": 302, + "endColumn": 67, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 303, + "column": 5, + "endLine": 303, + "endColumn": 46, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 304, + "column": 5, + "endLine": 304, + "endColumn": 79, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 308, + "column": 5, + "endLine": 308, + "endColumn": 91, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 310, + "column": 5, + "endLine": 310, + "endColumn": 73, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 313, + "column": 5, + "endLine": 313, + "endColumn": 43, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 314, + "column": 5, + "endLine": 314, + "endColumn": 38, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 315, + "column": 5, + "endLine": 315, + "endColumn": 48, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 316, + "column": 5, + "endLine": 316, + "endColumn": 50, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 317, + "column": 5, + "endLine": 317, + "endColumn": 69, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 318, + "column": 5, + "endLine": 318, + "endColumn": 54, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 319, + "column": 5, + "endLine": 319, + "endColumn": 81, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 323, + "column": 5, + "endLine": 323, + "endColumn": 93, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 325, + "column": 5, + "endLine": 325, + "endColumn": 75, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 363, + "column": 23, + "endLine": 363, + "endColumn": 28, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 370, + "column": 44, + "endLine": 370, + "endColumn": 59, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 377, + "column": 28, + "endLine": 377, + "endColumn": 33, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 384, + "column": 49, + "endLine": 384, + "endColumn": 64, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 391, + "column": 34, + "endLine": 391, + "endColumn": 39, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 398, + "column": 55, + "endLine": 398, + "endColumn": 70, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 405, + "column": 36, + "endLine": 405, + "endColumn": 41, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 412, + "column": 57, + "endLine": 412, + "endColumn": 72, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 420, + "column": 24, + "endLine": 420, + "endColumn": 29, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 427, + "column": 45, + "endLine": 427, + "endColumn": 60, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 435, + "column": 37, + "endLine": 435, + "endColumn": 42, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 442, + "column": 58, + "endLine": 442, + "endColumn": 73, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 450, + "column": 34, + "endLine": 450, + "endColumn": 39, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 457, + "column": 55, + "endLine": 457, + "endColumn": 70, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 465, + "column": 42, + "endLine": 465, + "endColumn": 47, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 472, + "column": 57, + "endLine": 472, + "endColumn": 72, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 361, + "column": 5, + "endLine": 361, + "endColumn": 37, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 362, + "column": 5, + "endLine": 362, + "endColumn": 53, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 363, + "column": 5, + "endLine": 363, + "endColumn": 35, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 364, + "column": 5, + "endLine": 364, + "endColumn": 37, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 364, + "column": 14, + "endLine": 364, + "endColumn": 17, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 365, + "column": 5, + "endLine": 365, + "endColumn": 32, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 368, + "column": 5, + "endLine": 368, + "endColumn": 52, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 368, + "column": 26, + "endLine": 368, + "endColumn": 27, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 370, + "column": 5, + "endLine": 370, + "endColumn": 62, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 375, + "column": 5, + "endLine": 375, + "endColumn": 42, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 376, + "column": 5, + "endLine": 376, + "endColumn": 58, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 377, + "column": 5, + "endLine": 377, + "endColumn": 40, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 378, + "column": 5, + "endLine": 378, + "endColumn": 42, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 378, + "column": 19, + "endLine": 378, + "endColumn": 22, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 379, + "column": 5, + "endLine": 379, + "endColumn": 37, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 382, + "column": 5, + "endLine": 382, + "endColumn": 57, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 382, + "column": 31, + "endLine": 382, + "endColumn": 32, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 384, + "column": 5, + "endLine": 384, + "endColumn": 67, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 389, + "column": 5, + "endLine": 389, + "endColumn": 48, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 390, + "column": 5, + "endLine": 390, + "endColumn": 64, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 391, + "column": 5, + "endLine": 391, + "endColumn": 46, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 392, + "column": 5, + "endLine": 392, + "endColumn": 48, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 392, + "column": 25, + "endLine": 392, + "endColumn": 28, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 393, + "column": 5, + "endLine": 393, + "endColumn": 43, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 396, + "column": 5, + "endLine": 396, + "endColumn": 63, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 396, + "column": 37, + "endLine": 396, + "endColumn": 38, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 398, + "column": 5, + "endLine": 398, + "endColumn": 73, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 403, + "column": 5, + "endLine": 403, + "endColumn": 50, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 404, + "column": 5, + "endLine": 404, + "endColumn": 66, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 405, + "column": 5, + "endLine": 405, + "endColumn": 48, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 406, + "column": 5, + "endLine": 406, + "endColumn": 50, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 406, + "column": 27, + "endLine": 406, + "endColumn": 30, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 407, + "column": 5, + "endLine": 407, + "endColumn": 45, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 410, + "column": 5, + "endLine": 410, + "endColumn": 65, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 410, + "column": 39, + "endLine": 410, + "endColumn": 40, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 412, + "column": 5, + "endLine": 412, + "endColumn": 75, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 418, + "column": 5, + "endLine": 418, + "endColumn": 38, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 419, + "column": 5, + "endLine": 419, + "endColumn": 57, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 420, + "column": 5, + "endLine": 420, + "endColumn": 36, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 421, + "column": 5, + "endLine": 421, + "endColumn": 69, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 425, + "column": 5, + "endLine": 425, + "endColumn": 81, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 427, + "column": 5, + "endLine": 427, + "endColumn": 63, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 433, + "column": 5, + "endLine": 433, + "endColumn": 51, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 434, + "column": 5, + "endLine": 434, + "endColumn": 70, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 435, + "column": 5, + "endLine": 435, + "endColumn": 49, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 436, + "column": 5, + "endLine": 436, + "endColumn": 70, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 440, + "column": 5, + "endLine": 440, + "endColumn": 82, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 442, + "column": 5, + "endLine": 442, + "endColumn": 76, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 448, + "column": 5, + "endLine": 448, + "endColumn": 48, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 449, + "column": 5, + "endLine": 449, + "endColumn": 67, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 450, + "column": 5, + "endLine": 450, + "endColumn": 46, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 451, + "column": 5, + "endLine": 451, + "endColumn": 79, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 455, + "column": 5, + "endLine": 455, + "endColumn": 91, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 457, + "column": 5, + "endLine": 457, + "endColumn": 73, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 460, + "column": 5, + "endLine": 460, + "endColumn": 43, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 461, + "column": 5, + "endLine": 461, + "endColumn": 38, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 462, + "column": 5, + "endLine": 462, + "endColumn": 48, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 463, + "column": 5, + "endLine": 463, + "endColumn": 50, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 464, + "column": 5, + "endLine": 464, + "endColumn": 69, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 465, + "column": 5, + "endLine": 465, + "endColumn": 54, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 466, + "column": 5, + "endLine": 466, + "endColumn": 81, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 470, + "column": 5, + "endLine": 470, + "endColumn": 93, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 472, + "column": 5, + "endLine": 472, + "endColumn": 75, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 510, + "column": 14, + "endLine": 510, + "endColumn": 17, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 514, + "column": 26, + "endLine": 514, + "endColumn": 27, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 524, + "column": 19, + "endLine": 524, + "endColumn": 22, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 528, + "column": 31, + "endLine": 528, + "endColumn": 32, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 538, + "column": 25, + "endLine": 538, + "endColumn": 28, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 542, + "column": 37, + "endLine": 542, + "endColumn": 38, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 552, + "column": 27, + "endLine": 552, + "endColumn": 30, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 556, + "column": 39, + "endLine": 556, + "endColumn": 40, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 624, + "column": 14, + "endLine": 624, + "endColumn": 17, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 638, + "column": 19, + "endLine": 638, + "endColumn": 22, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 652, + "column": 27, + "endLine": 652, + "endColumn": 30, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/sendable_explicit_field_type_2.ets.args.json b/ets2panda/linter/test/main/sendable_explicit_field_type_2.ets.args.json index 4ce1a4c45c..12b3ca8dec 100644 --- a/ets2panda/linter/test/main/sendable_explicit_field_type_2.ets.args.json +++ b/ets2panda/linter/test/main/sendable_explicit_field_type_2.ets.args.json @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/main/sendable_explicit_field_type_2.ets.autofix.json b/ets2panda/linter/test/main/sendable_explicit_field_type_2.ets.autofix.json index 4debe78577..210cf70cd2 100644 --- a/ets2panda/linter/test/main/sendable_explicit_field_type_2.ets.autofix.json +++ b/ets2panda/linter/test/main/sendable_explicit_field_type_2.ets.autofix.json @@ -22,9 +22,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 647, - "end": 673, - "replacementText": "// fixable\na: number = 0;" + "start": 668, + "end": 668, + "replacementText": ": number" } ], "suggest": "", @@ -39,9 +39,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 673, - "end": 693, - "replacementText": "static b: string = ' ';" + "start": 686, + "end": 686, + "replacementText": ": string" } ], "suggest": "", @@ -56,9 +56,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 693, - "end": 720, - "replacementText": "private c: undefined = undefined;" + "start": 707, + "end": 707, + "replacementText": ": undefined" } ], "suggest": "", @@ -73,9 +73,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 720, - "end": 751, - "replacementText": "public static d: A = new A();" + "start": 740, + "end": 740, + "replacementText": ": A" } ], "suggest": "", @@ -90,9 +90,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 751, - "end": 764, - "replacementText": "e?: number | undefined = 10;" + "start": 758, + "end": 758, + "replacementText": ": number | undefined" } ], "suggest": "", @@ -107,9 +107,9 @@ "problem": "SendableExplicitFieldType", "autofix": [ { - "start": 764, - "end": 783, - "replacementText": "f: number[] = [1, 2, 3];" + "start": 770, + "end": 770, + "replacementText": ": number[]" } ], "suggest": "", diff --git a/ets2panda/linter/test/migrate/parameter_properties.sts b/ets2panda/linter/test/main/sendable_explicit_field_type_2.ets.migrate.ets similarity index 52% rename from ets2panda/linter/test/migrate/parameter_properties.sts rename to ets2panda/linter/test/main/sendable_explicit_field_type_2.ets.migrate.ets index d6878228fd..75be1fcd77 100644 --- a/ets2panda/linter/test/migrate/parameter_properties.sts +++ b/ets2panda/linter/test/main/sendable_explicit_field_type_2.ets.migrate.ets @@ -13,36 +13,35 @@ * limitations under the License. */ +@Sendable class A { - constructor( - public readonly x: number, - protected y: number, - private z: number - ) {} - - foo(): void { - console.log(this.x + this.y + this.z); - } } -const a = new A(1, 2, 3); -console.log(a.x); - -class B { - public f: number = 10; - - constructor(q: number, public w = 'default', e: boolean, private readonly r: number[] = [1, 2, 3]) { - console.log(q, this.w, e, this.r, this.f); - } +interface GeneratedObjectLiteralInterface_1 { + e1: number; + e2: string; } - -const b = new B(1, '2', true, []); -console.log(b.w); - -class C { - constructor(public a: any) {} // not fixable +@Sendable +class B { + // fixable + a: number = 0; + static b: string = ' '; + private c: undefined = undefined; + public static d: A = new A(); + e?: number | undefined = 10; + f: number[] = [1, 2, 3]; + + // not fixable + bad; + + ehelper1: number = 4; + ehelper2: string = 'abc'; + public bad3: GeneratedObjectLiteralInterface_1 = { + e1: this.ehelper1, + e2: this.ehelper2 + }; + + constructor(x: boolean) { + this.bad = x; + } } - -class D { - constructor(public a: number, private b: {x: string}) {} // not fixable -} \ No newline at end of file diff --git a/ets2panda/linter/test/main/sendable_explicit_field_type_2.ets.migrate.json b/ets2panda/linter/test/main/sendable_explicit_field_type_2.ets.migrate.json new file mode 100644 index 0000000000..ab1db740e7 --- /dev/null +++ b/ets2panda/linter/test/main/sendable_explicit_field_type_2.ets.migrate.json @@ -0,0 +1,58 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 32, + "column": 5, + "endLine": 32, + "endColumn": 29, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 5, + "endLine": 35, + "endColumn": 9, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 5, + "endLine": 35, + "endColumn": 9, + "problem": "SendableExplicitFieldType", + "suggest": "", + "rule": "Field in sendable class must have type annotation (arkts-sendable-explicit-field-type)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 5, + "endLine": 42, + "endColumn": 7, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/sendable_function.ets.args.json b/ets2panda/linter/test/main/sendable_function.ets.args.json index 4ce1a4c45c..12b3ca8dec 100644 --- a/ets2panda/linter/test/main/sendable_function.ets.args.json +++ b/ets2panda/linter/test/main/sendable_function.ets.args.json @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/main/sendable_function.ets.migrate.ets b/ets2panda/linter/test/main/sendable_function.ets.migrate.ets new file mode 100644 index 0000000000..2c4a30f42d --- /dev/null +++ b/ets2panda/linter/test/main/sendable_function.ets.migrate.ets @@ -0,0 +1,230 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { D_Sft, D_Nft } from './sendable_function_dependencie'; +import { + D_sf, Dv_sf, D_nf, Dv_nf, Dv_Sft, Dv_Nft, D_Sc, D_Nc, + D_sf as AS_D_sf, Dv_sf as AS_Dv_sf, D_nf as AS_D_nf, Dv_nf as AS_Dv_nf, + D_Sft as AS_D_Sft, Dv_Sft as AS_Dv_Sft, D_Nft as AS_D_Nft, Dv_Nft as AS_Dv_Nft, + D_Sc as AS_D_Sc, D_Nc as AS_D_Nc +} from './sendable_function_dependencie'; + +// -------------------- check sendable-function declaration -------------------- // +@Sendable +function sf():void {} // OK +@Sendable +function stf(p:T):T { + return p; +} // OK +@Sendable +@Other // ERROR +function sf2():void {} + + +// check overloading +@Sendable +function sf3():void; // OK +@Sendable +function sf3():void; + +@Sendable +function sf3():void {} + +@Sendable +function sf4():void; +@Sendable +function sf4():void; // ERROR +@Sendable +function sf4():void {} + +@Sendable +function sf5():void; + +@Sendable +@Other // ERROR +function sf5():void; + +@Sendable +function sf5():void {} + +function nf():void {} + +// -------------------- check sendable-typealias declaration -------------------- // +@Sendable +type Sft = () => void; // OK +@Sendable +type Sft2 = () => void; // OK +@Sendable +type Sft3 = (p:T) => T; // OK +@Sendable +@Other // ERROR +type Sft4 = () => void; +@Sendable +type Sft5 = number; // ERROR +@Sendable +type Sft6 = Sft; // ERROR +type Sft7 = () => void; + +@Sendable +type Sft8 = Sft4; // ERROR + +type Nft = ()=>void; + +// -------------------- check sendable-function closure -------------------- // +@Sendable +class Sc {} +class Nc {} + +@Sendable +class SendableClassClosure { + constructor() { + const a1:Sft = sf; // OK + const a2:Nft = nf; // ERROR + const a3:Sc = new Sc(); // OK + const a4:Nc = new Nc(); // ERROR + + const b1:D_Sft = D_sf; // OK + const b2:D_Nft = D_nf; // OK + const b3:D_Sc = new D_Sc(); // OK + const b4:D_Nc = new D_Nc(); // OK + } + + @nf + handle() {} +} + +@Sendable +@nf +function SendableFunctionClosure() { + const a1:Sft = sf; // OK + const a2:Nft = nf; // ERROR + const a3:Sc = new Sc(); // OK + const a4:Nc = new Nc(); // ERROR + const b1:D_Sft = D_sf; // OK + const b2:D_Nft = D_nf; // OK + const b3:D_Sc = new D_Sc(); // OK + const b4:D_Nc = new D_Nc(); // OK +} + +namespace ns { + @Sendable + function sf():void; + @Sendable + function sf():void {} +} + + + +// -------------------- check sendable-typealias is sendaboe-data-type -------------------- // + + +// check property +@Sendable +class Sc2 { + p1: Sft = sf; // OK + p2: D_Nft = sf; // ERROR +} +// check genericity +new Sc2(); +new Sc2(); // ERROR + +// -------------------- check sendable-function cannot operation property --------------------// +sf.prop = 1; // ERROR +D_nf.prop = 1; // OK +D_sf.prop = 1; // ERROR +AS_D_sf.prop = 1;// ERROR + +// -------------------- check sendable-function assignment --------------------// + +@Sendable +function stf1(p:T):T {return p;}; +function ntf1(p:T):T {return p}; +// +const of1 = ()=>{}; +// +@Sendable +type Stft1 = (p:T)=>T; +@Sendable +type Stft2 = ()=>void; +// +type Nft1 = ()=>void; +type Nft2 = ()=>number; +type Ntft1 = (p:T)=>T; +type Ntft2 = ()=>void; +// +type U_Sft1 = Sft | D_Sft; +type U_Sft2 = Sft | Stft1; +type U_Nft1 = Nft1 | Nft2; +type U_Nft2 = Nft1 | Ntft1; +type U_ft1 = Sft | Nft1; +type U_ft2 = Sft | Stft1| Nft1 | Ntft1; +// +type TU_Sft1 = Sft | D_Sft; +type TU_Sft2 = Sft | Stft1 | Stft1 ; +type TU_Nft1 = Nft1 | Nft2; +type TU_Nft2 = Nft1 | Ntft1| Ntft2; +type TU_ft1 = Sft | Stft1 | Nft1 | Ntft1; +// +type DU_Sft1 = U_Sft1 | U_Sft2; +type DU_Sft2 = DU_Sft1 | TU_Sft1; +type DU_Sft3 = DU_Sft2 | TU_Sft2; +type DU_Nft = DU_Sft3 | TU_Nft2; +// normal +const a1: Sft = sf; // OK +const a2: Sft = nf; // ERROR +const a3: Sft = of1; // ERROR +const a4: Nft1 = nf; // OK +const a5: Sft = a1; // OK +const a6: Sft = a4; // ERROR +// generic +const b1: Stft1 = stf1; // OK +const b2: Stft1 = ntf1; // ERROR +const b3: Ntft1 = ntf1; // OK +const b4: Stft1 = b1; // OK +const b5: Stft1 = b3; // ERROR +// unite +const f1: U_ft1 = sf; // OK +const f2: U_ft2 = stf1; // OK +const f3: U_ft1 = nf; // ERROR +const f4: U_ft2 = ntf1; // ERROR +const d1: U_Sft1 = sf; // OK +const d2: U_Sft1 = nf; // ERROR +const d3: U_Sft1 = of1; // ERROR +const d4: U_Nft1 = sf; // OK +const d5: U_Nft1 = nf; // OK +const d6: U_Nft1 = of1; // OK +const d7: U_Sft1 = d1; // OK +const d18: U_Sft1 = d4; // ERROR +const d9: U_Sft1 = f1; // ERROR +// const d10: U_Sft1 = f2; // ERROR +const e1: U_Sft2 = stf1; // OK +const e2: U_Sft2 = ntf1; // ERROR +const e3: U_Nft2 = ntf1; // OK +const e4: U_Sft2 = e1; // OK +const e5: U_Sft2 = e3; // ERROR +const e6: U_Sft2 = f1; // ERROR +const e7: U_Sft2 = f2; // ERROR +// unite & generic +const g1: TU_ft1 = sf; // OK +const g2: TU_ft1 = stf1; // OK +const g3: TU_ft1 = nf; // ERROR +const h1: TU_Sft1 = sf; // OK +const h2: TU_Sft1 = nf; // ERROR +const h3: TU_Sft1 = of1; // ERROR +const h4: TU_Nft1 = nf; // OK +const h5: TU_Sft1 = h1; // OK +const h6: TU_Sft1 = h4; // ERROR +const h7: TU_Sft2 = stf1; // OK +const h8: TU_Sft2 = ntf1; // ERROR diff --git a/ets2panda/linter/test/main/sendable_function.ets.migrate.json b/ets2panda/linter/test/main/sendable_function.ets.migrate.json new file mode 100644 index 0000000000..4055118574 --- /dev/null +++ b/ets2panda/linter/test/main/sendable_function.ets.migrate.json @@ -0,0 +1,388 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 32, + "column": 1, + "endLine": 32, + "endColumn": 7, + "problem": "SendableFunctionDecorator", + "suggest": "", + "rule": "Only \"@Sendable\" decorator can be used on \"Sendable\" function (arkts-sendable-function-decorator)", + "severity": "ERROR" + }, + { + "line": 56, + "column": 1, + "endLine": 56, + "endColumn": 7, + "problem": "SendableFunctionDecorator", + "suggest": "", + "rule": "Only \"@Sendable\" decorator can be used on \"Sendable\" function (arkts-sendable-function-decorator)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 1, + "endLine": 72, + "endColumn": 7, + "problem": "SendableTypeAliasDecorator", + "suggest": "", + "rule": "Only \"@Sendable\" decorator can be used on \"Sendable\" typeAlias (arkts-sendable-typealias-decorator)", + "severity": "ERROR" + }, + { + "line": 75, + "column": 13, + "endLine": 75, + "endColumn": 19, + "problem": "SendableTypeAliasDeclaration", + "suggest": "", + "rule": "Only \"FunctionType\" can declare \"Sendable\" typeAlias (arkts-sendable-typeAlias-declaration)", + "severity": "ERROR" + }, + { + "line": 77, + "column": 13, + "endLine": 77, + "endColumn": 16, + "problem": "SendableTypeAliasDeclaration", + "suggest": "", + "rule": "Only \"FunctionType\" can declare \"Sendable\" typeAlias (arkts-sendable-typeAlias-declaration)", + "severity": "ERROR" + }, + { + "line": 81, + "column": 13, + "endLine": 81, + "endColumn": 17, + "problem": "SendableTypeAliasDeclaration", + "suggest": "", + "rule": "Only \"FunctionType\" can declare \"Sendable\" typeAlias (arkts-sendable-typeAlias-declaration)", + "severity": "ERROR" + }, + { + "line": 94, + "column": 20, + "endLine": 94, + "endColumn": 22, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 96, + "column": 23, + "endLine": 96, + "endColumn": 25, + "problem": "SendableCapturedVars", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" class (arkts-sendable-imported-variables)", + "severity": "ERROR" + }, + { + "line": 104, + "column": 3, + "endLine": 104, + "endColumn": 6, + "problem": "SendableClassDecorator", + "suggest": "", + "rule": "Only \"@Sendable\" decorator can be used on \"Sendable\" class (arkts-sendable-class-decorator)", + "severity": "ERROR" + }, + { + "line": 109, + "column": 1, + "endLine": 109, + "endColumn": 4, + "problem": "SendableFunctionDecorator", + "suggest": "", + "rule": "Only \"@Sendable\" decorator can be used on \"Sendable\" function (arkts-sendable-function-decorator)", + "severity": "ERROR" + }, + { + "line": 112, + "column": 18, + "endLine": 112, + "endColumn": 20, + "problem": "SendableFunctionImportedVariables", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" function (arkts-sendable-function-imported-variables)", + "severity": "ERROR" + }, + { + "line": 114, + "column": 21, + "endLine": 114, + "endColumn": 23, + "problem": "SendableFunctionImportedVariables", + "suggest": "", + "rule": "Only imported variables can be captured by \"Sendable\" function (arkts-sendable-function-imported-variables)", + "severity": "ERROR" + }, + { + "line": 137, + "column": 3, + "endLine": 137, + "endColumn": 18, + "problem": "SendablePropType", + "suggest": "", + "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (arkts-sendable-prop-types)", + "severity": "ERROR" + }, + { + "line": 141, + "column": 9, + "endLine": 141, + "endColumn": 14, + "problem": "SendableGenericTypes", + "suggest": "", + "rule": "Type arguments of generic \"Sendable\" type must be a \"Sendable\" data type (arkts-sendable-generic-types)", + "severity": "ERROR" + }, + { + "line": 144, + "column": 1, + "endLine": 144, + "endColumn": 8, + "problem": "SendableFunctionProperty", + "suggest": "", + "rule": "The property of \"Sendable\" function is limited (arkts-sendable-function-property)", + "severity": "ERROR" + }, + { + "line": 146, + "column": 1, + "endLine": 146, + "endColumn": 10, + "problem": "SendableFunctionProperty", + "suggest": "", + "rule": "The property of \"Sendable\" function is limited (arkts-sendable-function-property)", + "severity": "ERROR" + }, + { + "line": 147, + "column": 1, + "endLine": 147, + "endColumn": 13, + "problem": "SendableFunctionProperty", + "suggest": "", + "rule": "The property of \"Sendable\" function is limited (arkts-sendable-function-property)", + "severity": "ERROR" + }, + { + "line": 186, + "column": 7, + "endLine": 186, + "endColumn": 19, + "problem": "SendableFunctionAssignment", + "suggest": "", + "rule": "Only \"Sendable\" function or \"Sendable\" typeAlias object can be assigned to \"Sendable\" typeAlias (arkts-sendable-function-assignment)", + "severity": "ERROR" + }, + { + "line": 187, + "column": 7, + "endLine": 187, + "endColumn": 20, + "problem": "SendableFunctionAssignment", + "suggest": "", + "rule": "Only \"Sendable\" function or \"Sendable\" typeAlias object can be assigned to \"Sendable\" typeAlias (arkts-sendable-function-assignment)", + "severity": "ERROR" + }, + { + "line": 190, + "column": 7, + "endLine": 190, + "endColumn": 19, + "problem": "SendableFunctionAssignment", + "suggest": "", + "rule": "Only \"Sendable\" function or \"Sendable\" typeAlias object can be assigned to \"Sendable\" typeAlias (arkts-sendable-function-assignment)", + "severity": "ERROR" + }, + { + "line": 193, + "column": 7, + "endLine": 193, + "endColumn": 23, + "problem": "SendableFunctionAssignment", + "suggest": "", + "rule": "Only \"Sendable\" function or \"Sendable\" typeAlias object can be assigned to \"Sendable\" typeAlias (arkts-sendable-function-assignment)", + "severity": "ERROR" + }, + { + "line": 196, + "column": 7, + "endLine": 196, + "endColumn": 21, + "problem": "SendableFunctionAssignment", + "suggest": "", + "rule": "Only \"Sendable\" function or \"Sendable\" typeAlias object can be assigned to \"Sendable\" typeAlias (arkts-sendable-function-assignment)", + "severity": "ERROR" + }, + { + "line": 200, + "column": 7, + "endLine": 200, + "endColumn": 21, + "problem": "SendableFunctionAssignment", + "suggest": "", + "rule": "Only \"Sendable\" function or \"Sendable\" typeAlias object can be assigned to \"Sendable\" typeAlias (arkts-sendable-function-assignment)", + "severity": "ERROR" + }, + { + "line": 201, + "column": 7, + "endLine": 201, + "endColumn": 23, + "problem": "SendableFunctionAssignment", + "suggest": "", + "rule": "Only \"Sendable\" function or \"Sendable\" typeAlias object can be assigned to \"Sendable\" typeAlias (arkts-sendable-function-assignment)", + "severity": "ERROR" + }, + { + "line": 203, + "column": 7, + "endLine": 203, + "endColumn": 22, + "problem": "SendableFunctionAssignment", + "suggest": "", + "rule": "Only \"Sendable\" function or \"Sendable\" typeAlias object can be assigned to \"Sendable\" typeAlias (arkts-sendable-function-assignment)", + "severity": "ERROR" + }, + { + "line": 204, + "column": 7, + "endLine": 204, + "endColumn": 23, + "problem": "SendableFunctionAssignment", + "suggest": "", + "rule": "Only \"Sendable\" function or \"Sendable\" typeAlias object can be assigned to \"Sendable\" typeAlias (arkts-sendable-function-assignment)", + "severity": "ERROR" + }, + { + "line": 209, + "column": 7, + "endLine": 209, + "endColumn": 23, + "problem": "SendableFunctionAssignment", + "suggest": "", + "rule": "Only \"Sendable\" function or \"Sendable\" typeAlias object can be assigned to \"Sendable\" typeAlias (arkts-sendable-function-assignment)", + "severity": "ERROR" + }, + { + "line": 210, + "column": 7, + "endLine": 210, + "endColumn": 22, + "problem": "SendableFunctionAssignment", + "suggest": "", + "rule": "Only \"Sendable\" function or \"Sendable\" typeAlias object can be assigned to \"Sendable\" typeAlias (arkts-sendable-function-assignment)", + "severity": "ERROR" + }, + { + "line": 213, + "column": 7, + "endLine": 213, + "endColumn": 24, + "problem": "SendableFunctionAssignment", + "suggest": "", + "rule": "Only \"Sendable\" function or \"Sendable\" typeAlias object can be assigned to \"Sendable\" typeAlias (arkts-sendable-function-assignment)", + "severity": "ERROR" + }, + { + "line": 216, + "column": 7, + "endLine": 216, + "endColumn": 22, + "problem": "SendableFunctionAssignment", + "suggest": "", + "rule": "Only \"Sendable\" function or \"Sendable\" typeAlias object can be assigned to \"Sendable\" typeAlias (arkts-sendable-function-assignment)", + "severity": "ERROR" + }, + { + "line": 217, + "column": 7, + "endLine": 217, + "endColumn": 22, + "problem": "SendableFunctionAssignment", + "suggest": "", + "rule": "Only \"Sendable\" function or \"Sendable\" typeAlias object can be assigned to \"Sendable\" typeAlias (arkts-sendable-function-assignment)", + "severity": "ERROR" + }, + { + "line": 218, + "column": 7, + "endLine": 218, + "endColumn": 22, + "problem": "SendableFunctionAssignment", + "suggest": "", + "rule": "Only \"Sendable\" function or \"Sendable\" typeAlias object can be assigned to \"Sendable\" typeAlias (arkts-sendable-function-assignment)", + "severity": "ERROR" + }, + { + "line": 222, + "column": 7, + "endLine": 222, + "endColumn": 30, + "problem": "SendableFunctionAssignment", + "suggest": "", + "rule": "Only \"Sendable\" function or \"Sendable\" typeAlias object can be assigned to \"Sendable\" typeAlias (arkts-sendable-function-assignment)", + "severity": "ERROR" + }, + { + "line": 224, + "column": 7, + "endLine": 224, + "endColumn": 31, + "problem": "SendableFunctionAssignment", + "suggest": "", + "rule": "Only \"Sendable\" function or \"Sendable\" typeAlias object can be assigned to \"Sendable\" typeAlias (arkts-sendable-function-assignment)", + "severity": "ERROR" + }, + { + "line": 225, + "column": 7, + "endLine": 225, + "endColumn": 32, + "problem": "SendableFunctionAssignment", + "suggest": "", + "rule": "Only \"Sendable\" function or \"Sendable\" typeAlias object can be assigned to \"Sendable\" typeAlias (arkts-sendable-function-assignment)", + "severity": "ERROR" + }, + { + "line": 228, + "column": 7, + "endLine": 228, + "endColumn": 31, + "problem": "SendableFunctionAssignment", + "suggest": "", + "rule": "Only \"Sendable\" function or \"Sendable\" typeAlias object can be assigned to \"Sendable\" typeAlias (arkts-sendable-function-assignment)", + "severity": "ERROR" + }, + { + "line": 230, + "column": 7, + "endLine": 230, + "endColumn": 33, + "problem": "SendableFunctionAssignment", + "suggest": "", + "rule": "Only \"Sendable\" function or \"Sendable\" typeAlias object can be assigned to \"Sendable\" typeAlias (arkts-sendable-function-assignment)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/sendable_function_2.ets.args.json b/ets2panda/linter/test/main/sendable_function_2.ets.args.json index 4ce1a4c45c..12b3ca8dec 100644 --- a/ets2panda/linter/test/main/sendable_function_2.ets.args.json +++ b/ets2panda/linter/test/main/sendable_function_2.ets.args.json @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/main/sendable_function_2.ets.migrate.ets b/ets2panda/linter/test/main/sendable_function_2.ets.migrate.ets new file mode 100644 index 0000000000..db2a902510 --- /dev/null +++ b/ets2panda/linter/test/main/sendable_function_2.ets.migrate.ets @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@Sendable +function foo(name: string): void; +@Sendable +function foo(age: number): void; // Fixable +@Sendable +function foo(...args: Object[]): void {} // Fixable + +@Sendable +function bar(name: string): void; // Fixable +@Sendable +function bar(age: number): void; // Fixable +@Sendable +function bar(...args: Object[]): void {} diff --git a/ets2panda/linter/test/main/sendable_function_2.ets.migrate.json b/ets2panda/linter/test/main/sendable_function_2.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/sendable_function_2.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/static_class.ets b/ets2panda/linter/test/main/static_class.ets new file mode 100644 index 0000000000..3316c3afad --- /dev/null +++ b/ets2panda/linter/test/main/static_class.ets @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +'use static' + +class A { + static { + console.log("Shouldn't be here"); + } +} diff --git a/ets2panda/linter/test/main/static_class.ets.args.json b/ets2panda/linter/test/main/static_class.ets.args.json new file mode 100644 index 0000000000..8a4be28991 --- /dev/null +++ b/ets2panda/linter/test/main/static_class.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "migrate": "--arkts-2" + } +} diff --git a/ets2panda/linter/test/main/static_class.ets.arkts2.json b/ets2panda/linter/test/main/static_class.ets.arkts2.json new file mode 100644 index 0000000000..614cb2e9da --- /dev/null +++ b/ets2panda/linter/test/main/static_class.ets.arkts2.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 5, + "endLine": 20, + "endColumn": 6, + "problem": "NoStaticOnClass", + "suggest": "", + "rule": "Class cannot have static codeblocks. (arkts-class-lazy-import)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/main/static_class.ets.json b/ets2panda/linter/test/main/static_class.ets.json new file mode 100644 index 0000000000..bd1b7140ca --- /dev/null +++ b/ets2panda/linter/test/main/static_class.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} diff --git a/ets2panda/linter/test/main/static_class.ets.migrate.ets b/ets2panda/linter/test/main/static_class.ets.migrate.ets new file mode 100644 index 0000000000..3316c3afad --- /dev/null +++ b/ets2panda/linter/test/main/static_class.ets.migrate.ets @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +'use static' + +class A { + static { + console.log("Shouldn't be here"); + } +} diff --git a/ets2panda/linter/test/main/static_class.ets.migrate.json b/ets2panda/linter/test/main/static_class.ets.migrate.json new file mode 100644 index 0000000000..614cb2e9da --- /dev/null +++ b/ets2panda/linter/test/main/static_class.ets.migrate.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 5, + "endLine": 20, + "endColumn": 6, + "problem": "NoStaticOnClass", + "suggest": "", + "rule": "Class cannot have static codeblocks. (arkts-class-lazy-import)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/main/structural_identity.ets.arkts2.json b/ets2panda/linter/test/main/structural_identity.ets.arkts2.json index 2546e534df..a3b9b0c1a1 100644 --- a/ets2panda/linter/test/main/structural_identity.ets.arkts2.json +++ b/ets2panda/linter/test/main/structural_identity.ets.arkts2.json @@ -974,26 +974,6 @@ "rule": "Structural typing is not supported (arkts-no-structural-typing)", "severity": "ERROR" }, - { - "line": 480, - "column": 1, - "endLine": 480, - "endColumn": 10, - "problem": "LimitedStdLibApi", - "suggest": "", - "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", - "severity": "ERROR" - }, - { - "line": 485, - "column": 1, - "endLine": 485, - "endColumn": 10, - "problem": "LimitedStdLibApi", - "suggest": "", - "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", - "severity": "ERROR" - }, { "line": 502, "column": 7, @@ -1344,16 +1324,6 @@ "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, - { - "line": 622, - "column": 50, - "endLine": 622, - "endColumn": 58, - "problem": "StructuralIdentity", - "suggest": "", - "rule": "Structural typing is not supported (arkts-no-structural-typing)", - "severity": "ERROR" - }, { "line": 626, "column": 5, @@ -1575,4 +1545,4 @@ "severity": "ERROR" } ] -} \ No newline at end of file +} diff --git a/ets2panda/linter/test/main/styles_decorator_anon_1.ets.args.json b/ets2panda/linter/test/main/styles_decorator_anon_1.ets.args.json index 5cdfe96f7a..df6e67a5c9 100644 --- a/ets2panda/linter/test/main/styles_decorator_anon_1.ets.args.json +++ b/ets2panda/linter/test/main/styles_decorator_anon_1.ets.args.json @@ -1,20 +1,21 @@ { - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "mode": { - "arkts2": "", - "autofix": "--arkts-2" - } + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2", + "migrate": "--arkts-2" + } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_anon_1.ets.arkts2.json b/ets2panda/linter/test/main/styles_decorator_anon_1.ets.arkts2.json index ff8b6e8a6e..1bf55e2d4c 100644 --- a/ets2panda/linter/test/main/styles_decorator_anon_1.ets.arkts2.json +++ b/ets2panda/linter/test/main/styles_decorator_anon_1.ets.arkts2.json @@ -16,9 +16,9 @@ "result": [ { "line": 27, - "column": 6, + "column": 18, "endLine": 40, - "endColumn": 7, + "endColumn": 6, "problem": "StylesDecoratorNotSupported", "suggest": "", "rule": "\"@Styles\" decorator is not supported (arkui-no-styles-decorator)", diff --git a/ets2panda/linter/test/main/styles_decorator_anon_1.ets.autofix.json b/ets2panda/linter/test/main/styles_decorator_anon_1.ets.autofix.json index bbf6e8f769..d6ed03103f 100644 --- a/ets2panda/linter/test/main/styles_decorator_anon_1.ets.autofix.json +++ b/ets2panda/linter/test/main/styles_decorator_anon_1.ets.autofix.json @@ -16,9 +16,9 @@ "result": [ { "line": 27, - "column": 6, + "column": 18, "endLine": 40, - "endColumn": 7, + "endColumn": 6, "problem": "StylesDecoratorNotSupported", "autofix": [ { diff --git a/ets2panda/linter/test/main/styles_decorator_anon_1.ets.migrate.ets b/ets2panda/linter/test/main/styles_decorator_anon_1.ets.migrate.ets new file mode 100644 index 0000000000..26b949ad37 --- /dev/null +++ b/ets2panda/linter/test/main/styles_decorator_anon_1.ets.migrate.ets @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, BuilderParam, Require, Button, CommonMethod, Color } from '@kit.ArkUI'; + +@Entry +@Component +struct TestStateStyle { + @BuilderParam + @Require + content: () => void; + + build() { + Button() { + this.content + } + .stateStyles({ + normal: (instance: CommonMethod): void => { + instance.backgroundColor("#00ffff"); + instance.borderWidth(8); + }, + pressed: (instance: CommonMethod): void => { + instance.backgroundColor(Color.Red); + instance.backgroundImagePosition({ + x: 0, + y: 0 + }); + instance.backgroundColor("#ffff00"); + } + }) + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_anon_1.ets.migrate.json b/ets2panda/linter/test/main/styles_decorator_anon_1.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/styles_decorator_anon_1.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_anon_2.ets.args.json b/ets2panda/linter/test/main/styles_decorator_anon_2.ets.args.json index 5cdfe96f7a..ee0734c0fc 100644 --- a/ets2panda/linter/test/main/styles_decorator_anon_2.ets.args.json +++ b/ets2panda/linter/test/main/styles_decorator_anon_2.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_anon_2.ets.migrate.ets b/ets2panda/linter/test/main/styles_decorator_anon_2.ets.migrate.ets new file mode 100644 index 0000000000..a0888e5b74 --- /dev/null +++ b/ets2panda/linter/test/main/styles_decorator_anon_2.ets.migrate.ets @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entry, Component, BuilderParam, Require, Button, CommonMethod, Color } from '@kit.ArkUI'; + +@Entry +@Component +struct TestStateStyle { + @BuilderParam + @Require + content: () => void; + + build() { + Button() { + this.content + } + .stateStyles({ + normal: (instance: CommonMethod): void => { + instance.backgroundColor("#00ffff"); + instance.borderWidth(8); + }, + pressed: (instance: CommonMethod): void => { + instance.backgroundColor(Color.Red); + instance.backgroundImagePosition({ + x: 0, + y: 0 + }); + instance.backgroundColor("#ffff00"); + } + }) + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_anon_2.ets.migrate.json b/ets2panda/linter/test/main/styles_decorator_anon_2.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/styles_decorator_anon_2.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_global_1.ets b/ets2panda/linter/test/main/styles_decorator_global_1.ets index e7ebe0041b..0c7853382e 100644 --- a/ets2panda/linter/test/main/styles_decorator_global_1.ets +++ b/ets2panda/linter/test/main/styles_decorator_global_1.ets @@ -32,9 +32,10 @@ function cardStyle1() struct MyCard1 { build() { Column() { - + Text("TestStyles").cardStyle1() } .cardStyle1() + .backgroundColor(Color.Red) } } diff --git a/ets2panda/linter/test/main/styles_decorator_global_1.ets.args.json b/ets2panda/linter/test/main/styles_decorator_global_1.ets.args.json index 5cdfe96f7a..ee0734c0fc 100644 --- a/ets2panda/linter/test/main/styles_decorator_global_1.ets.args.json +++ b/ets2panda/linter/test/main/styles_decorator_global_1.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_global_1.ets.arkts2.json b/ets2panda/linter/test/main/styles_decorator_global_1.ets.arkts2.json index 58303d7e15..775283b08e 100644 --- a/ets2panda/linter/test/main/styles_decorator_global_1.ets.arkts2.json +++ b/ets2panda/linter/test/main/styles_decorator_global_1.ets.arkts2.json @@ -25,9 +25,9 @@ "severity": "ERROR" }, { - "line": 41, + "line": 42, "column": 1, - "endLine": 44, + "endLine": 45, "endColumn": 2, "problem": "StylesDecoratorNotSupported", "suggest": "", @@ -35,9 +35,9 @@ "severity": "ERROR" }, { - "line": 46, + "line": 47, "column": 1, - "endLine": 49, + "endLine": 50, "endColumn": 2, "problem": "StylesDecoratorNotSupported", "suggest": "", @@ -75,9 +75,29 @@ "severity": "ERROR" }, { - "line": 51, + "line": 35, + "column": 13, + "endLine": 35, + "endColumn": 17, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 26, + "endLine": 38, + "endColumn": 31, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 52, "column": 2, - "endLine": 51, + "endLine": 52, "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", @@ -85,9 +105,9 @@ "severity": "ERROR" }, { - "line": 53, + "line": 54, "column": 6, - "endLine": 53, + "endLine": 54, "endColumn": 18, "problem": "UIInterfaceImport", "suggest": "", @@ -95,9 +115,9 @@ "severity": "ERROR" }, { - "line": 54, + "line": 55, "column": 6, - "endLine": 54, + "endLine": 55, "endColumn": 13, "problem": "UIInterfaceImport", "suggest": "", @@ -105,9 +125,9 @@ "severity": "ERROR" }, { - "line": 58, + "line": 59, "column": 9, - "endLine": 58, + "endLine": 59, "endColumn": 15, "problem": "UIInterfaceImport", "suggest": "", diff --git a/ets2panda/linter/test/main/styles_decorator_global_1.ets.autofix.json b/ets2panda/linter/test/main/styles_decorator_global_1.ets.autofix.json index e385b5de17..e7bb004c03 100644 --- a/ets2panda/linter/test/main/styles_decorator_global_1.ets.autofix.json +++ b/ets2panda/linter/test/main/styles_decorator_global_1.ets.autofix.json @@ -27,8 +27,13 @@ "replacementText": "function cardStyle1(instance: CommonMethod): void {\n instance.backgroundColor(mycolor);\n instance.borderColor(Color.Red);\n instance.borderRadius(8);\n instance.padding(8);\n instance.backgroundImagePosition({\n x: 0,\n y: 0\n });\n}" }, { - "start": 918, - "end": 930, + "start": 929, + "end": 941, + "replacementText": "applyStyles(cardStyle1)" + }, + { + "start": 961, + "end": 973, "replacementText": "applyStyles(cardStyle1)" } ], @@ -37,15 +42,15 @@ "severity": "ERROR" }, { - "line": 41, + "line": 42, "column": 1, - "endLine": 44, + "endLine": 45, "endColumn": 2, "problem": "StylesDecoratorNotSupported", "autofix": [ { - "start": 940, - "end": 1007, + "start": 1019, + "end": 1086, "replacementText": "function NormalStyles(instance: CommonMethod): void {\n instance.backgroundColor(\"#ffffff\");\n}" } ], @@ -54,15 +59,15 @@ "severity": "ERROR" }, { - "line": 46, + "line": 47, "column": 1, - "endLine": 49, + "endLine": 50, "endColumn": 2, "problem": "StylesDecoratorNotSupported", "autofix": [ { - "start": 1009, - "end": 1077, + "start": 1088, + "end": 1156, "replacementText": "function PressedStyles(instance: CommonMethod): void {\n instance.backgroundColor(\"#ffffff\");\n}" } ], @@ -80,7 +85,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Component, Column, BuilderParam, Require, Button } from '@kit.ArkUI';" + "replacementText": "\n\nimport { CommonMethod, Color, Component, Column, Text, BuilderParam, Require, Button } from '@kit.ArkUI';" } ], "suggest": "", @@ -97,7 +102,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Component, Column, BuilderParam, Require, Button } from '@kit.ArkUI';" + "replacementText": "\n\nimport { CommonMethod, Color, Component, Column, Text, BuilderParam, Require, Button } from '@kit.ArkUI';" } ], "suggest": "", @@ -114,7 +119,24 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Component, Column, BuilderParam, Require, Button } from '@kit.ArkUI';" + "replacementText": "\n\nimport { CommonMethod, Color, Component, Column, Text, BuilderParam, Require, Button } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 13, + "endLine": 35, + "endColumn": 17, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { CommonMethod, Color, Component, Column, Text, BuilderParam, Require, Button } from '@kit.ArkUI';" } ], "suggest": "", @@ -122,16 +144,33 @@ "severity": "ERROR" }, { - "line": 51, + "line": 38, + "column": 26, + "endLine": 38, + "endColumn": 31, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { CommonMethod, Color, Component, Column, Text, BuilderParam, Require, Button } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 52, "column": 2, - "endLine": 51, + "endLine": 52, "endColumn": 11, "problem": "UIInterfaceImport", "autofix": [ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Component, Column, BuilderParam, Require, Button } from '@kit.ArkUI';" + "replacementText": "\n\nimport { CommonMethod, Color, Component, Column, Text, BuilderParam, Require, Button } from '@kit.ArkUI';" } ], "suggest": "", @@ -139,16 +178,16 @@ "severity": "ERROR" }, { - "line": 53, + "line": 54, "column": 6, - "endLine": 53, + "endLine": 54, "endColumn": 18, "problem": "UIInterfaceImport", "autofix": [ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Component, Column, BuilderParam, Require, Button } from '@kit.ArkUI';" + "replacementText": "\n\nimport { CommonMethod, Color, Component, Column, Text, BuilderParam, Require, Button } from '@kit.ArkUI';" } ], "suggest": "", @@ -156,16 +195,16 @@ "severity": "ERROR" }, { - "line": 54, + "line": 55, "column": 6, - "endLine": 54, + "endLine": 55, "endColumn": 13, "problem": "UIInterfaceImport", "autofix": [ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Component, Column, BuilderParam, Require, Button } from '@kit.ArkUI';" + "replacementText": "\n\nimport { CommonMethod, Color, Component, Column, Text, BuilderParam, Require, Button } from '@kit.ArkUI';" } ], "suggest": "", @@ -173,16 +212,16 @@ "severity": "ERROR" }, { - "line": 58, + "line": 59, "column": 9, - "endLine": 58, + "endLine": 59, "endColumn": 15, "problem": "UIInterfaceImport", "autofix": [ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Component, Column, BuilderParam, Require, Button } from '@kit.ArkUI';" + "replacementText": "\n\nimport { CommonMethod, Color, Component, Column, Text, BuilderParam, Require, Button } from '@kit.ArkUI';" } ], "suggest": "", diff --git a/ets2panda/linter/test/main/styles_decorator_global_1.ets.migrate.ets b/ets2panda/linter/test/main/styles_decorator_global_1.ets.migrate.ets new file mode 100644 index 0000000000..fd272fd000 --- /dev/null +++ b/ets2panda/linter/test/main/styles_decorator_global_1.ets.migrate.ets @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { CommonMethod, Color, Component, Column, Text, BuilderParam, Require, Button } from '@kit.ArkUI'; + +const mycolor: string = "#ffff00" + +function cardStyle1(instance: CommonMethod): void { + instance.backgroundColor(mycolor); + instance.borderColor(Color.Red); + instance.borderRadius(8); + instance.padding(8); + instance.backgroundImagePosition({ + x: 0, + y: 0 + }); +} + +@Component +struct MyCard1 { + build() { + Column() { + Text("TestStyles").applyStyles(cardStyle1) + } + .applyStyles(cardStyle1) + .backgroundColor(Color.Red) + } +} + +function NormalStyles(instance: CommonMethod): void { + instance.backgroundColor("#ffffff"); +} + +function PressedStyles(instance: CommonMethod): void { + instance.backgroundColor("#ffffff"); +} + +@Component +struct MyButton { + @BuilderParam + @Require + content: () => void; + + build() { + Button() { + this.content() + } + .stateStyles({ + normal: NormalStyles, + pressed: PressedStyles + }) + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_global_1.ets.migrate.json b/ets2panda/linter/test/main/styles_decorator_global_1.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/styles_decorator_global_1.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_global_2.ets b/ets2panda/linter/test/main/styles_decorator_global_2.ets index a3f4363eb4..fd272fd000 100644 --- a/ets2panda/linter/test/main/styles_decorator_global_2.ets +++ b/ets2panda/linter/test/main/styles_decorator_global_2.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import { CommonMethod, Color, Component, Column, BuilderParam, Require, Button } from '@kit.ArkUI'; +import { CommonMethod, Color, Component, Column, Text, BuilderParam, Require, Button } from '@kit.ArkUI'; const mycolor: string = "#ffff00" @@ -32,9 +32,10 @@ function cardStyle1(instance: CommonMethod): void { struct MyCard1 { build() { Column() { - + Text("TestStyles").applyStyles(cardStyle1) } - applyStyles.cardStyle1() + .applyStyles(cardStyle1) + .backgroundColor(Color.Red) } } diff --git a/ets2panda/linter/test/main/styles_decorator_global_2.ets.args.json b/ets2panda/linter/test/main/styles_decorator_global_2.ets.args.json index 5cdfe96f7a..ee0734c0fc 100644 --- a/ets2panda/linter/test/main/styles_decorator_global_2.ets.args.json +++ b/ets2panda/linter/test/main/styles_decorator_global_2.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_global_2.ets.migrate.ets b/ets2panda/linter/test/main/styles_decorator_global_2.ets.migrate.ets new file mode 100644 index 0000000000..fd272fd000 --- /dev/null +++ b/ets2panda/linter/test/main/styles_decorator_global_2.ets.migrate.ets @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { CommonMethod, Color, Component, Column, Text, BuilderParam, Require, Button } from '@kit.ArkUI'; + +const mycolor: string = "#ffff00" + +function cardStyle1(instance: CommonMethod): void { + instance.backgroundColor(mycolor); + instance.borderColor(Color.Red); + instance.borderRadius(8); + instance.padding(8); + instance.backgroundImagePosition({ + x: 0, + y: 0 + }); +} + +@Component +struct MyCard1 { + build() { + Column() { + Text("TestStyles").applyStyles(cardStyle1) + } + .applyStyles(cardStyle1) + .backgroundColor(Color.Red) + } +} + +function NormalStyles(instance: CommonMethod): void { + instance.backgroundColor("#ffffff"); +} + +function PressedStyles(instance: CommonMethod): void { + instance.backgroundColor("#ffffff"); +} + +@Component +struct MyButton { + @BuilderParam + @Require + content: () => void; + + build() { + Button() { + this.content() + } + .stateStyles({ + normal: NormalStyles, + pressed: PressedStyles + }) + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_global_2.ets.migrate.json b/ets2panda/linter/test/main/styles_decorator_global_2.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/styles_decorator_global_2.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_mix_1.ets b/ets2panda/linter/test/main/styles_decorator_mix_1.ets new file mode 100644 index 0000000000..040d2154f7 --- /dev/null +++ b/ets2panda/linter/test/main/styles_decorator_mix_1.ets @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@Styles +function NormalStyles() { + .backgroundColor(Color.Blue) +} + +@Entry +@Component +struct MyButton1 { + @BuilderParam + @Require + content: () => void; + + @Styles + PressedStyles() { + .backgroundColor(Color.Green) + } + + build() { + Button("MyButton1") { + this.content + } + .stateStyles({ + pressed: this.PressedStyles, + selected: { + .backgroundColor(Color.Red) + }, + normal: NormalStyles + }) + } +} + +@Component +struct MyButton2 { + @BuilderParam + @Require + content: () => void; + + build() { + Button("MyButton2") { + this.content + } + .stateStyles({ + selected: { + .backgroundColor(Color.Red) + }, + normal: NormalStyles, + }) + } +} + +@Component +struct MyButton3 { + + build() { + Button("MyButton3") + .stateStyles({ + normal: NormalStyles, + selected: { + .backgroundColor(Color.Red) + } + }) + } +} + +@Component +struct MyButton4 { + + build() { + Button("MyButton4") + .stateStyles({ + selected: { + .backgroundColor(Color.Red) + }, + normal: NormalStyles + }) + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_mix_1.ets.args.json b/ets2panda/linter/test/main/styles_decorator_mix_1.ets.args.json new file mode 100644 index 0000000000..ee0734c0fc --- /dev/null +++ b/ets2panda/linter/test/main/styles_decorator_mix_1.ets.args.json @@ -0,0 +1,21 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2", + "migrate": "--arkts-2" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/migrate/func_return_type.ts.json b/ets2panda/linter/test/main/styles_decorator_mix_1.ets.arkts2.json similarity index 33% rename from ets2panda/linter/test/migrate/func_return_type.ts.json rename to ets2panda/linter/test/main/styles_decorator_mix_1.ets.arkts2.json index 00be5f244b..b0c53b4c8e 100644 --- a/ets2panda/linter/test/migrate/func_return_type.ts.json +++ b/ets2panda/linter/test/main/styles_decorator_mix_1.ets.arkts2.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2023-2024 Huawei Device Co., Ltd.", + "Copyright (c) 2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -16,262 +16,252 @@ "result": [ { "line": 16, - "column": 10, - "endLine": 16, - "endColumn": 11, - "problem": "LimitedReturnTypeInference", - "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", - "severity": "ERROR" - }, - { - "line": 23, - "column": 10, - "endLine": 23, - "endColumn": 11, - "problem": "LimitedReturnTypeInference", + "column": 1, + "endLine": 19, + "endColumn": 2, + "problem": "StylesDecoratorNotSupported", "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "\"@Styles\" decorator is not supported (arkui-no-styles-decorator)", "severity": "ERROR" }, { - "line": 33, - "column": 10, - "endLine": 33, - "endColumn": 11, - "problem": "LimitedReturnTypeInference", + "line": 28, + "column": 3, + "endLine": 31, + "endColumn": 4, + "problem": "StylesDecoratorNotSupported", "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "\"@Styles\" decorator is not supported (arkui-no-styles-decorator)", "severity": "ERROR" }, { - "line": 40, - "column": 10, - "endLine": 40, - "endColumn": 11, - "problem": "LimitedReturnTypeInference", + "line": 37, + "column": 18, + "endLine": 43, + "endColumn": 6, + "problem": "StylesDecoratorNotSupported", "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "\"@Styles\" decorator is not supported (arkui-no-styles-decorator)", "severity": "ERROR" }, { - "line": 46, - "column": 10, - "endLine": 46, - "endColumn": 11, - "problem": "LimitedReturnTypeInference", + "line": 57, + "column": 18, + "endLine": 62, + "endColumn": 6, + "problem": "StylesDecoratorNotSupported", "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "\"@Styles\" decorator is not supported (arkui-no-styles-decorator)", "severity": "ERROR" }, { - "line": 54, - "column": 10, - "endLine": 54, - "endColumn": 11, - "problem": "LimitedReturnTypeInference", + "line": 71, + "column": 20, + "endLine": 76, + "endColumn": 8, + "problem": "StylesDecoratorNotSupported", "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "\"@Styles\" decorator is not supported (arkui-no-styles-decorator)", "severity": "ERROR" }, { - "line": 57, - "column": 10, - "endLine": 57, - "endColumn": 11, - "problem": "LimitedReturnTypeInference", + "line": 85, + "column": 20, + "endLine": 90, + "endColumn": 8, + "problem": "StylesDecoratorNotSupported", "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "\"@Styles\" decorator is not supported (arkui-no-styles-decorator)", "severity": "ERROR" }, { - "line": 57, - "column": 15, - "endLine": 57, - "endColumn": 18, - "problem": "AnyType", + "line": 18, + "column": 22, + "endLine": 18, + "endColumn": 27, + "problem": "UIInterfaceImport", "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 62, - "column": 12, - "endLine": 64, - "endColumn": 4, - "problem": "FunctionExpression", + "line": 21, + "column": 2, + "endLine": 21, + "endColumn": 7, + "problem": "UIInterfaceImport", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 65, - "column": 12, - "endLine": 67, - "endColumn": 4, - "problem": "FunctionExpression", + "line": 22, + "column": 2, + "endLine": 22, + "endColumn": 11, + "problem": "UIInterfaceImport", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 69, - "column": 12, - "endLine": 71, - "endColumn": 4, - "problem": "FunctionExpression", + "line": 24, + "column": 4, + "endLine": 24, + "endColumn": 16, + "problem": "UIInterfaceImport", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 73, - "column": 12, - "endLine": 75, - "endColumn": 4, - "problem": "FunctionExpression", + "line": 25, + "column": 4, + "endLine": 25, + "endColumn": 11, + "problem": "UIInterfaceImport", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 76, - "column": 12, - "endLine": 78, - "endColumn": 4, - "problem": "FunctionExpression", + "line": 30, + "column": 22, + "endLine": 30, + "endColumn": 27, + "problem": "UIInterfaceImport", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 80, - "column": 12, - "endLine": 82, - "endColumn": 4, - "problem": "FunctionExpression", + "line": 34, + "column": 5, + "endLine": 34, + "endColumn": 11, + "problem": "UIInterfaceImport", "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 80, - "column": 12, - "endLine": 82, - "endColumn": 4, - "problem": "LimitedReturnTypeInference", + "line": 40, + "column": 26, + "endLine": 40, + "endColumn": 31, + "problem": "UIInterfaceImport", "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 86, - "column": 12, - "endLine": 88, - "endColumn": 4, - "problem": "LimitedReturnTypeInference", + "line": 47, + "column": 2, + "endLine": 47, + "endColumn": 11, + "problem": "UIInterfaceImport", "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 97, - "column": 12, - "endLine": 99, - "endColumn": 4, - "problem": "LimitedReturnTypeInference", + "line": 49, + "column": 4, + "endLine": 49, + "endColumn": 16, + "problem": "UIInterfaceImport", "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 104, - "column": 12, - "endLine": 106, - "endColumn": 4, - "problem": "LimitedReturnTypeInference", + "line": 50, + "column": 4, + "endLine": 50, + "endColumn": 11, + "problem": "UIInterfaceImport", "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 110, - "column": 3, - "endLine": 110, - "endColumn": 4, - "problem": "LimitedReturnTypeInference", + "line": 54, + "column": 5, + "endLine": 54, + "endColumn": 11, + "problem": "UIInterfaceImport", "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 114, - "column": 3, - "endLine": 114, - "endColumn": 5, - "problem": "LimitedReturnTypeInference", + "line": 59, + "column": 26, + "endLine": 59, + "endColumn": 31, + "problem": "UIInterfaceImport", "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 122, - "column": 3, - "endLine": 122, - "endColumn": 5, - "problem": "LimitedReturnTypeInference", + "line": 66, + "column": 2, + "endLine": 66, + "endColumn": 11, + "problem": "UIInterfaceImport", "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 126, - "column": 3, - "endLine": 126, - "endColumn": 5, - "problem": "LimitedReturnTypeInference", + "line": 70, + "column": 5, + "endLine": 70, + "endColumn": 11, + "problem": "UIInterfaceImport", "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 131, - "column": 10, - "endLine": 131, - "endColumn": 30, - "problem": "LimitedReturnTypeInference", + "line": 74, + "column": 28, + "endLine": 74, + "endColumn": 33, + "problem": "UIInterfaceImport", "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 135, - "column": 18, - "endLine": 135, - "endColumn": 40, - "problem": "LimitedReturnTypeInference", + "line": 80, + "column": 2, + "endLine": 80, + "endColumn": 11, + "problem": "UIInterfaceImport", "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 139, - "column": 3, - "endLine": 139, - "endColumn": 10, - "problem": "LimitedReturnTypeInference", + "line": 84, + "column": 5, + "endLine": 84, + "endColumn": 11, + "problem": "UIInterfaceImport", "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 144, - "column": 3, - "endLine": 144, - "endColumn": 7, - "problem": "LimitedReturnTypeInference", + "line": 87, + "column": 28, + "endLine": 87, + "endColumn": 33, + "problem": "UIInterfaceImport", "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/main/styles_decorator_mix_1.ets.autofix.json b/ets2panda/linter/test/main/styles_decorator_mix_1.ets.autofix.json new file mode 100644 index 0000000000..a84810a9e7 --- /dev/null +++ b/ets2panda/linter/test/main/styles_decorator_mix_1.ets.autofix.json @@ -0,0 +1,443 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 1, + "endLine": 19, + "endColumn": 2, + "problem": "StylesDecoratorNotSupported", + "autofix": [ + { + "start": 605, + "end": 673, + "replacementText": "function NormalStyles(instance: CommonMethod): void {\n instance.backgroundColor(Color.Blue);\n}" + } + ], + "suggest": "", + "rule": "\"@Styles\" decorator is not supported (arkui-no-styles-decorator)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 3, + "endLine": 31, + "endColumn": 4, + "problem": "StylesDecoratorNotSupported", + "autofix": [ + { + "start": 765, + "end": 830, + "replacementText": "PressedStyles = (instance: CommonMethod): void => {\n instance.backgroundColor(Color.Green);\n };" + } + ], + "suggest": "", + "rule": "\"@Styles\" decorator is not supported (arkui-no-styles-decorator)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 18, + "endLine": 43, + "endColumn": 6, + "problem": "StylesDecoratorNotSupported", + "autofix": [ + { + "start": 912, + "end": 1044, + "replacementText": "{\n pressed: this.PressedStyles,\n selected: (instance: CommonMethod): void => {\n instance.backgroundColor(Color.Red);\n },\n normal: NormalStyles\n }" + } + ], + "suggest": "", + "rule": "\"@Styles\" decorator is not supported (arkui-no-styles-decorator)", + "severity": "ERROR" + }, + { + "line": 57, + "column": 18, + "endLine": 62, + "endColumn": 6, + "problem": "StylesDecoratorNotSupported", + "autofix": [ + { + "start": 1214, + "end": 1312, + "replacementText": "{\n selected: (instance: CommonMethod): void => {\n instance.backgroundColor(Color.Red);\n },\n normal: NormalStyles\n }" + } + ], + "suggest": "", + "rule": "\"@Styles\" decorator is not supported (arkui-no-styles-decorator)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 20, + "endLine": 76, + "endColumn": 8, + "problem": "StylesDecoratorNotSupported", + "autofix": [ + { + "start": 1407, + "end": 1514, + "replacementText": "{\n normal: NormalStyles,\n selected: (instance: CommonMethod): void => {\n instance.backgroundColor(Color.Red);\n }\n }" + } + ], + "suggest": "", + "rule": "\"@Styles\" decorator is not supported (arkui-no-styles-decorator)", + "severity": "ERROR" + }, + { + "line": 85, + "column": 20, + "endLine": 90, + "endColumn": 8, + "problem": "StylesDecoratorNotSupported", + "autofix": [ + { + "start": 1609, + "end": 1716, + "replacementText": "{\n selected: (instance: CommonMethod): void => {\n instance.backgroundColor(Color.Red);\n },\n normal: NormalStyles\n }" + } + ], + "suggest": "", + "rule": "\"@Styles\" decorator is not supported (arkui-no-styles-decorator)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 22, + "endLine": 18, + "endColumn": 27, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 2, + "endLine": 21, + "endColumn": 7, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 2, + "endLine": 22, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 4, + "endLine": 24, + "endColumn": 16, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 4, + "endLine": 25, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 22, + "endLine": 30, + "endColumn": 27, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 5, + "endLine": 34, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 40, + "column": 26, + "endLine": 40, + "endColumn": 31, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 47, + "column": 2, + "endLine": 47, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 4, + "endLine": 49, + "endColumn": 16, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 50, + "column": 4, + "endLine": 50, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 54, + "column": 5, + "endLine": 54, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 59, + "column": 26, + "endLine": 59, + "endColumn": 31, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 66, + "column": 2, + "endLine": 66, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 70, + "column": 5, + "endLine": 70, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 74, + "column": 28, + "endLine": 74, + "endColumn": 33, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 80, + "column": 2, + "endLine": 80, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 84, + "column": 5, + "endLine": 84, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 87, + "column": 28, + "endLine": 87, + "endColumn": 33, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_mix_1.ets.json b/ets2panda/linter/test/main/styles_decorator_mix_1.ets.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/styles_decorator_mix_1.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/data_observation_2.ets b/ets2panda/linter/test/main/styles_decorator_mix_1.ets.migrate.ets similarity index 31% rename from ets2panda/linter/test/main/data_observation_2.ets rename to ets2panda/linter/test/main/styles_decorator_mix_1.ets.migrate.ets index 7a91607067..4e9c2b35e0 100644 --- a/ets2panda/linter/test/main/data_observation_2.ets +++ b/ets2panda/linter/test/main/styles_decorator_mix_1.ets.migrate.ets @@ -13,82 +13,80 @@ * limitations under the License. */ -import { Observed, Entry, Component, State, Prop, Provide, StorageLink, LocalStorageLink, StorageProp, LocalStorageProp, Link, Consume } from '@kit.ArkUI'; +import { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI'; -@Observed -class MyClassA {} - -@Observed -class MyClassB { - name: string = '' +function NormalStyles(instance: CommonMethod): void { + instance.backgroundColor(Color.Blue); } -@Observed -class MyClassC1 {} - -@Observed -class MyClassC2 extends MyClassC1 {} - -@Observed -class MyClassC3 extends MyClassC2 {} - -@Observed -class MyClassD extends MyClassC3 {} - -class MyClassC4 extends MyClassD {} - -interface IntfA {} - -@Observed -class MyClassE implements IntfA {} - -@Observed -class MyClassF {} - -@Observed -class MyClassG {} +@Entry +@Component +struct MyButton1 { + @BuilderParam + @Require + content: () => void; -@Observed -class MyClassH {} + PressedStyles = (instance: CommonMethod): void => { + instance.backgroundColor(Color.Green); + }; -@Observed -class MyClassI {} + build() { + Button("MyButton1") { + this.content + } + .stateStyles({ + pressed: this.PressedStyles, + selected: (instance: CommonMethod): void => { + instance.backgroundColor(Color.Red); + }, + normal: NormalStyles + }) + } +} -@Observed -class MyClassJ extends MyClassI {} +@Component +struct MyButton2 { + @BuilderParam + @Require + content: () => void; -@Observed -class MyClassK extends MyClassJ {} + build() { + Button("MyButton2") { + this.content + } + .stateStyles({ + selected: (instance: CommonMethod): void => { + instance.backgroundColor(Color.Red); + }, + normal: NormalStyles + }) + } +} -@Entry @Component -struct Test { - @State data1: number = 0 - @State data2: MyClassA = new MyClassA() - @State data3: MyClassB = { name: "jack" } - @State data4: MyClassC2 = new MyClassD() - @State data5: IntfA = new MyClassE() - @Prop data6: MyClassE = new MyClassE() - @Prop data7: MyClassF = new MyClassF() - @Prop data8: MyClassG | MyClassH | number = 0 - @Prop data9: MyClassJ = new MyClassK() - @Provide selectedDate: Date = new Date('2021-08-08') - @StorageLink('PropB') storageLink: MyClassA = new MyClassA() - @LocalStorageLink('LinkB') localStorageLink: MyClassB = new MyClassB() - @StorageProp('test') test1: MyClassC2 = new MyClassC3() - @LocalStorageProp('test') test2: MyClassD = new MyClassD() +struct MyButton3 { build() { - + Button("MyButton3") + .stateStyles({ + normal: NormalStyles, + selected: (instance: CommonMethod): void => { + instance.backgroundColor(Color.Red); + } + }) } } @Component -struct MyComponent { - @Link data2: MyClassA - @Consume selectedDate: Date +struct MyButton4 { build() { - + Button("MyButton4") + .stateStyles({ + selected: (instance: CommonMethod): void => { + instance.backgroundColor(Color.Red); + }, + normal: NormalStyles + }) } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_mix_1.ets.migrate.json b/ets2panda/linter/test/main/styles_decorator_mix_1.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/styles_decorator_mix_1.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_mix_2.ets b/ets2panda/linter/test/main/styles_decorator_mix_2.ets new file mode 100644 index 0000000000..4e9c2b35e0 --- /dev/null +++ b/ets2panda/linter/test/main/styles_decorator_mix_2.ets @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI'; + +function NormalStyles(instance: CommonMethod): void { + instance.backgroundColor(Color.Blue); +} + +@Entry +@Component +struct MyButton1 { + @BuilderParam + @Require + content: () => void; + + PressedStyles = (instance: CommonMethod): void => { + instance.backgroundColor(Color.Green); + }; + + build() { + Button("MyButton1") { + this.content + } + .stateStyles({ + pressed: this.PressedStyles, + selected: (instance: CommonMethod): void => { + instance.backgroundColor(Color.Red); + }, + normal: NormalStyles + }) + } +} + +@Component +struct MyButton2 { + @BuilderParam + @Require + content: () => void; + + build() { + Button("MyButton2") { + this.content + } + .stateStyles({ + selected: (instance: CommonMethod): void => { + instance.backgroundColor(Color.Red); + }, + normal: NormalStyles + }) + } +} + +@Component +struct MyButton3 { + + build() { + Button("MyButton3") + .stateStyles({ + normal: NormalStyles, + selected: (instance: CommonMethod): void => { + instance.backgroundColor(Color.Red); + } + }) + } +} + +@Component +struct MyButton4 { + + build() { + Button("MyButton4") + .stateStyles({ + selected: (instance: CommonMethod): void => { + instance.backgroundColor(Color.Red); + }, + normal: NormalStyles + }) + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_mix_2.ets.args.json b/ets2panda/linter/test/main/styles_decorator_mix_2.ets.args.json new file mode 100644 index 0000000000..ee0734c0fc --- /dev/null +++ b/ets2panda/linter/test/main/styles_decorator_mix_2.ets.args.json @@ -0,0 +1,21 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2", + "migrate": "--arkts-2" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_mix_2.ets.arkts2.json b/ets2panda/linter/test/main/styles_decorator_mix_2.ets.arkts2.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/styles_decorator_mix_2.ets.arkts2.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_mix_2.ets.autofix.json b/ets2panda/linter/test/main/styles_decorator_mix_2.ets.autofix.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/styles_decorator_mix_2.ets.autofix.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_mix_2.ets.json b/ets2panda/linter/test/main/styles_decorator_mix_2.ets.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/styles_decorator_mix_2.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_mix_2.ets.migrate.ets b/ets2panda/linter/test/main/styles_decorator_mix_2.ets.migrate.ets new file mode 100644 index 0000000000..4e9c2b35e0 --- /dev/null +++ b/ets2panda/linter/test/main/styles_decorator_mix_2.ets.migrate.ets @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI'; + +function NormalStyles(instance: CommonMethod): void { + instance.backgroundColor(Color.Blue); +} + +@Entry +@Component +struct MyButton1 { + @BuilderParam + @Require + content: () => void; + + PressedStyles = (instance: CommonMethod): void => { + instance.backgroundColor(Color.Green); + }; + + build() { + Button("MyButton1") { + this.content + } + .stateStyles({ + pressed: this.PressedStyles, + selected: (instance: CommonMethod): void => { + instance.backgroundColor(Color.Red); + }, + normal: NormalStyles + }) + } +} + +@Component +struct MyButton2 { + @BuilderParam + @Require + content: () => void; + + build() { + Button("MyButton2") { + this.content + } + .stateStyles({ + selected: (instance: CommonMethod): void => { + instance.backgroundColor(Color.Red); + }, + normal: NormalStyles + }) + } +} + +@Component +struct MyButton3 { + + build() { + Button("MyButton3") + .stateStyles({ + normal: NormalStyles, + selected: (instance: CommonMethod): void => { + instance.backgroundColor(Color.Red); + } + }) + } +} + +@Component +struct MyButton4 { + + build() { + Button("MyButton4") + .stateStyles({ + selected: (instance: CommonMethod): void => { + instance.backgroundColor(Color.Red); + }, + normal: NormalStyles + }) + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_mix_2.ets.migrate.json b/ets2panda/linter/test/main/styles_decorator_mix_2.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/styles_decorator_mix_2.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_struct_1.ets b/ets2panda/linter/test/main/styles_decorator_struct_1.ets index f757e64088..d6be553734 100644 --- a/ets2panda/linter/test/main/styles_decorator_struct_1.ets +++ b/ets2panda/linter/test/main/styles_decorator_struct_1.ets @@ -23,9 +23,10 @@ struct MyCard1 { build() { Column() { - Text('Card') + Text('Card').cardStyle1() } .cardStyle1() + .backgroundColor(Color.Red) } } @@ -50,9 +51,10 @@ struct MyCard2 { build() { Column() { - Text('Card') + Text('Card').cardStyle2() } .cardStyle2() + .backgroundColor(Color.Red) } } @@ -77,8 +79,8 @@ struct MyButton { this.content } .stateStyles({ - normal: this.NormalStyles(), - pressed: this.PressedStyles() + normal: this.NormalStyles, + pressed: this.PressedStyles }) } } diff --git a/ets2panda/linter/test/main/styles_decorator_struct_1.ets.args.json b/ets2panda/linter/test/main/styles_decorator_struct_1.ets.args.json index 5cdfe96f7a..ee0734c0fc 100644 --- a/ets2panda/linter/test/main/styles_decorator_struct_1.ets.args.json +++ b/ets2panda/linter/test/main/styles_decorator_struct_1.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_struct_1.ets.arkts2.json b/ets2panda/linter/test/main/styles_decorator_struct_1.ets.arkts2.json index a134245793..7c09951b77 100644 --- a/ets2panda/linter/test/main/styles_decorator_struct_1.ets.arkts2.json +++ b/ets2panda/linter/test/main/styles_decorator_struct_1.ets.arkts2.json @@ -25,9 +25,9 @@ "severity": "ERROR" }, { - "line": 34, + "line": 35, "column": 3, - "endLine": 41, + "endLine": 42, "endColumn": 4, "problem": "StylesDecoratorNotSupported", "suggest": "", @@ -35,9 +35,9 @@ "severity": "ERROR" }, { - "line": 65, + "line": 67, "column": 3, - "endLine": 68, + "endLine": 70, "endColumn": 4, "problem": "StylesDecoratorNotSupported", "suggest": "", @@ -45,9 +45,9 @@ "severity": "ERROR" }, { - "line": 70, + "line": 72, "column": 3, - "endLine": 73, + "endLine": 75, "endColumn": 4, "problem": "StylesDecoratorNotSupported", "suggest": "", @@ -55,29 +55,9 @@ "severity": "ERROR" }, { - "line": 80, - "column": 15, - "endLine": 80, - "endColumn": 34, - "problem": "LimitedVoidType", - "suggest": "", - "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", - "severity": "ERROR" - }, - { - "line": 81, - "column": 16, - "endLine": 81, - "endColumn": 36, - "problem": "LimitedVoidType", - "suggest": "", - "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", - "severity": "ERROR" - }, - { - "line": 103, + "line": 105, "column": 3, - "endLine": 116, + "endLine": 118, "endColumn": 4, "problem": "StylesDecoratorNotSupported", "suggest": "", @@ -85,9 +65,9 @@ "severity": "ERROR" }, { - "line": 106, + "line": 108, "column": 18, - "endLine": 114, + "endLine": 116, "endColumn": 6, "problem": "LimitedReturnTypeInference", "suggest": "", @@ -125,9 +105,19 @@ "severity": "ERROR" }, { - "line": 32, + "line": 29, + "column": 22, + "endLine": 29, + "endColumn": 27, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 33, "column": 2, - "endLine": 32, + "endLine": 33, "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", @@ -135,9 +125,9 @@ "severity": "ERROR" }, { - "line": 43, + "line": 44, "column": 23, - "endLine": 43, + "endLine": 44, "endColumn": 28, "problem": "UIInterfaceImport", "suggest": "", @@ -145,9 +135,9 @@ "severity": "ERROR" }, { - "line": 44, + "line": 45, "column": 12, - "endLine": 44, + "endLine": 45, "endColumn": 17, "problem": "UIInterfaceImport", "suggest": "", @@ -155,9 +145,9 @@ "severity": "ERROR" }, { - "line": 52, + "line": 53, "column": 5, - "endLine": 52, + "endLine": 53, "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", @@ -165,9 +155,9 @@ "severity": "ERROR" }, { - "line": 53, + "line": 54, "column": 7, - "endLine": 53, + "endLine": 54, "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", @@ -175,9 +165,19 @@ "severity": "ERROR" }, { - "line": 59, + "line": 57, + "column": 22, + "endLine": 57, + "endColumn": 27, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 61, "column": 2, - "endLine": 59, + "endLine": 61, "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", @@ -185,9 +185,9 @@ "severity": "ERROR" }, { - "line": 61, + "line": 63, "column": 4, - "endLine": 61, + "endLine": 63, "endColumn": 16, "problem": "UIInterfaceImport", "suggest": "", @@ -195,9 +195,9 @@ "severity": "ERROR" }, { - "line": 62, + "line": 64, "column": 4, - "endLine": 62, + "endLine": 64, "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", @@ -205,9 +205,9 @@ "severity": "ERROR" }, { - "line": 67, + "line": 69, "column": 22, - "endLine": 67, + "endLine": 69, "endColumn": 27, "problem": "UIInterfaceImport", "suggest": "", @@ -215,9 +215,9 @@ "severity": "ERROR" }, { - "line": 72, + "line": 74, "column": 22, - "endLine": 72, + "endLine": 74, "endColumn": 27, "problem": "UIInterfaceImport", "suggest": "", @@ -225,9 +225,9 @@ "severity": "ERROR" }, { - "line": 76, + "line": 78, "column": 5, - "endLine": 76, + "endLine": 78, "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", @@ -235,9 +235,9 @@ "severity": "ERROR" }, { - "line": 97, + "line": 99, "column": 2, - "endLine": 97, + "endLine": 99, "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", @@ -245,9 +245,9 @@ "severity": "ERROR" }, { - "line": 101, + "line": 103, "column": 24, - "endLine": 101, + "endLine": 103, "endColumn": 37, "problem": "UIInterfaceImport", "suggest": "", diff --git a/ets2panda/linter/test/main/styles_decorator_struct_1.ets.autofix.json b/ets2panda/linter/test/main/styles_decorator_struct_1.ets.autofix.json index 778dc5b85f..aeedca2d7d 100644 --- a/ets2panda/linter/test/main/styles_decorator_struct_1.ets.autofix.json +++ b/ets2panda/linter/test/main/styles_decorator_struct_1.ets.autofix.json @@ -27,8 +27,13 @@ "replacementText": "cardStyle1 = (instance: CommonMethod): void => {\n instance.backgroundColor('#ffffff');\n instance.borderRadius(8);\n };" }, { - "start": 775, - "end": 787, + "start": 764, + "end": 776, + "replacementText": "applyStyles(this.cardStyle1)" + }, + { + "start": 788, + "end": 800, "replacementText": "applyStyles(this.cardStyle1)" } ], @@ -37,20 +42,25 @@ "severity": "ERROR" }, { - "line": 34, + "line": 35, "column": 3, - "endLine": 41, + "endLine": 42, "endColumn": 4, "problem": "StylesDecoratorNotSupported", "autofix": [ { - "start": 825, - "end": 965, + "start": 870, + "end": 1010, "replacementText": "cardStyle2 = (instance: CommonMethod): void => {\n instance.border({\n color: this.getColor(),\n width: this.getWidth()\n });\n instance.backgroundColor('#ffffff');\n };" }, { - "start": 1134, - "end": 1146, + "start": 1168, + "end": 1180, + "replacementText": "applyStyles(this.cardStyle2)" + }, + { + "start": 1192, + "end": 1204, "replacementText": "applyStyles(this.cardStyle2)" } ], @@ -59,15 +69,15 @@ "severity": "ERROR" }, { - "line": 65, + "line": 67, "column": 3, - "endLine": 68, + "endLine": 70, "endColumn": 4, "problem": "StylesDecoratorNotSupported", "autofix": [ { - "start": 1236, - "end": 1298, + "start": 1326, + "end": 1388, "replacementText": "NormalStyles = (instance: CommonMethod): void => {\n instance.backgroundColor(Color.Red);\n };" } ], @@ -76,15 +86,15 @@ "severity": "ERROR" }, { - "line": 70, + "line": 72, "column": 3, - "endLine": 73, + "endLine": 75, "endColumn": 4, "problem": "StylesDecoratorNotSupported", "autofix": [ { - "start": 1302, - "end": 1367, + "start": 1392, + "end": 1457, "replacementText": "PressedStyles = (instance: CommonMethod): void => {\n instance.backgroundColor(Color.Green);\n };" } ], @@ -93,35 +103,15 @@ "severity": "ERROR" }, { - "line": 80, - "column": 15, - "endLine": 80, - "endColumn": 34, - "problem": "LimitedVoidType", - "suggest": "", - "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", - "severity": "ERROR" - }, - { - "line": 81, - "column": 16, - "endLine": 81, - "endColumn": 36, - "problem": "LimitedVoidType", - "suggest": "", - "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", - "severity": "ERROR" - }, - { - "line": 103, + "line": 105, "column": 3, - "endLine": 116, + "endLine": 118, "endColumn": 4, "problem": "StylesDecoratorNotSupported", "autofix": [ { - "start": 1867, - "end": 2363, + "start": 1953, + "end": 2449, "replacementText": "imageStyle = (instance: CommonMethod): void => {\n instance.draggable(this.isShowLongPressMenu() && this.isPC());\n instance.onDragStart(() => {\n console.info(TAG, 'onDragStart');\n this.touchVibrate(VibrateType.DRAG);\n if (this.mediaItem?.path) {\n this.previewUri =\n this.getPreviewUri(this.mediaItem?.path, this.mediaItem?.getDateModified?.(), false, true);\n }\n return this.DragBuilder;\n });\n instance.accessibilityText(this.isOpenTouchGuide ? this.getImageItemGridAccessibilityText() : '');\n };" } ], @@ -130,9 +120,9 @@ "severity": "ERROR" }, { - "line": 106, + "line": 108, "column": 18, - "endLine": 114, + "endLine": 116, "endColumn": 6, "problem": "LimitedReturnTypeInference", "suggest": "", @@ -191,9 +181,26 @@ "severity": "ERROR" }, { - "line": 32, + "line": 29, + "column": 22, + "endLine": 29, + "endColumn": 27, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 33, "column": 2, - "endLine": 32, + "endLine": 33, "endColumn": 11, "problem": "UIInterfaceImport", "autofix": [ @@ -208,9 +215,9 @@ "severity": "ERROR" }, { - "line": 43, + "line": 44, "column": 23, - "endLine": 43, + "endLine": 44, "endColumn": 28, "problem": "UIInterfaceImport", "autofix": [ @@ -225,9 +232,9 @@ "severity": "ERROR" }, { - "line": 44, + "line": 45, "column": 12, - "endLine": 44, + "endLine": 45, "endColumn": 17, "problem": "UIInterfaceImport", "autofix": [ @@ -242,9 +249,9 @@ "severity": "ERROR" }, { - "line": 52, + "line": 53, "column": 5, - "endLine": 52, + "endLine": 53, "endColumn": 11, "problem": "UIInterfaceImport", "autofix": [ @@ -259,9 +266,9 @@ "severity": "ERROR" }, { - "line": 53, + "line": 54, "column": 7, - "endLine": 53, + "endLine": 54, "endColumn": 11, "problem": "UIInterfaceImport", "autofix": [ @@ -276,9 +283,26 @@ "severity": "ERROR" }, { - "line": 59, + "line": 57, + "column": 22, + "endLine": 57, + "endColumn": 27, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';" + } + ], + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 61, "column": 2, - "endLine": 59, + "endLine": 61, "endColumn": 11, "problem": "UIInterfaceImport", "autofix": [ @@ -293,9 +317,9 @@ "severity": "ERROR" }, { - "line": 61, + "line": 63, "column": 4, - "endLine": 61, + "endLine": 63, "endColumn": 16, "problem": "UIInterfaceImport", "autofix": [ @@ -310,9 +334,9 @@ "severity": "ERROR" }, { - "line": 62, + "line": 64, "column": 4, - "endLine": 62, + "endLine": 64, "endColumn": 11, "problem": "UIInterfaceImport", "autofix": [ @@ -327,9 +351,9 @@ "severity": "ERROR" }, { - "line": 67, + "line": 69, "column": 22, - "endLine": 67, + "endLine": 69, "endColumn": 27, "problem": "UIInterfaceImport", "autofix": [ @@ -344,9 +368,9 @@ "severity": "ERROR" }, { - "line": 72, + "line": 74, "column": 22, - "endLine": 72, + "endLine": 74, "endColumn": 27, "problem": "UIInterfaceImport", "autofix": [ @@ -361,9 +385,9 @@ "severity": "ERROR" }, { - "line": 76, + "line": 78, "column": 5, - "endLine": 76, + "endLine": 78, "endColumn": 11, "problem": "UIInterfaceImport", "autofix": [ @@ -378,9 +402,9 @@ "severity": "ERROR" }, { - "line": 97, + "line": 99, "column": 2, - "endLine": 97, + "endLine": 99, "endColumn": 11, "problem": "UIInterfaceImport", "autofix": [ @@ -395,9 +419,9 @@ "severity": "ERROR" }, { - "line": 101, + "line": 103, "column": 24, - "endLine": 101, + "endLine": 103, "endColumn": 37, "problem": "UIInterfaceImport", "autofix": [ diff --git a/ets2panda/linter/test/main/styles_decorator_struct_1.ets.json b/ets2panda/linter/test/main/styles_decorator_struct_1.ets.json index 3b43bc06e5..967418d911 100644 --- a/ets2panda/linter/test/main/styles_decorator_struct_1.ets.json +++ b/ets2panda/linter/test/main/styles_decorator_struct_1.ets.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 106, + "line": 108, "column": 18, - "endLine": 114, + "endLine": 116, "endColumn": 6, "problem": "LimitedReturnTypeInference", "suggest": "", diff --git a/ets2panda/linter/test/main/styles_decorator_struct_1.ets.migrate.ets b/ets2panda/linter/test/main/styles_decorator_struct_1.ets.migrate.ets new file mode 100644 index 0000000000..31fb825cee --- /dev/null +++ b/ets2panda/linter/test/main/styles_decorator_struct_1.ets.migrate.ets @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI'; + +@Component +struct MyCard1 { + cardStyle1 = (instance: CommonMethod): void => { + instance.backgroundColor('#ffffff'); + instance.borderRadius(8); + }; + + build() { + Column() { + Text('Card').applyStyles(this.cardStyle1) + } + .applyStyles(this.cardStyle1) + .backgroundColor(Color.Red) + } +} + +@Component +struct MyCard2 { + cardStyle2 = (instance: CommonMethod): void => { + instance.border({ + color: this.getColor(), + width: this.getWidth() + }); + instance.backgroundColor('#ffffff'); + }; + + private getColor(): Color { + return Color.Red + } + + private getWidth(): number { + return 10 + } + + build() { + Column() { + Text('Card').applyStyles(this.cardStyle2) + } + .applyStyles(this.cardStyle2) + .backgroundColor(Color.Red) + } +} + +@Component +struct MyButton { + @BuilderParam + @Require + content: () => void; + + NormalStyles = (instance: CommonMethod): void => { + instance.backgroundColor(Color.Red); + }; + + PressedStyles = (instance: CommonMethod): void => { + instance.backgroundColor(Color.Green); + }; + + build() { + Button() { + this.content + } + .stateStyles({ + normal: this.NormalStyles, + pressed: this.PressedStyles + }) + } +} + +const TAG: string = 'common_ImageTest'; + +class MediaItem { + public path: string = ''; + public uri: string = ''; + + public getDateModified(): string { + return '' + } +} + +@Component +struct imageTest { + private mediaItem: MediaItem | undefined; + private previewUri: string | undefined; + private DragBuilder: CustomBuilder | undefined; + + imageStyle = (instance: CommonMethod): void => { + instance.draggable(this.isShowLongPressMenu() && this.isPC()); + instance.onDragStart(() => { + console.info(TAG, 'onDragStart'); + this.touchVibrate(VibrateType.DRAG); + if (this.mediaItem?.path) { + this.previewUri = + this.getPreviewUri(this.mediaItem?.path, this.mediaItem?.getDateModified?.(), false, true); + } + return this.DragBuilder; + }); + instance.accessibilityText(this.isOpenTouchGuide ? this.getImageItemGridAccessibilityText() : ''); + }; + + private isShowLongPressMenu(): boolean { + return true; + } + + private isPC(): boolean { + return true; + } + + private touchVibrate(type: VibrateType): void { + + } + + private isOpenTouchGuide: boolean = true; + + private getImageItemGridAccessibilityText(): string { + return '' + } + + private getPreviewUri(path: string, date: string, isOk: boolean, ready: boolean): string { + return '' + } + + build() { + + } +} + +enum VibrateType { + DRAG +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_struct_1.ets.migrate.json b/ets2panda/linter/test/main/styles_decorator_struct_1.ets.migrate.json new file mode 100644 index 0000000000..0e17a7dad5 --- /dev/null +++ b/ets2panda/linter/test/main/styles_decorator_struct_1.ets.migrate.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 105, + "column": 26, + "endLine": 113, + "endColumn": 6, + "problem": "LimitedReturnTypeInference", + "suggest": "", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_struct_2.ets b/ets2panda/linter/test/main/styles_decorator_struct_2.ets index 82fe4ba1fe..31fb825cee 100644 --- a/ets2panda/linter/test/main/styles_decorator_struct_2.ets +++ b/ets2panda/linter/test/main/styles_decorator_struct_2.ets @@ -24,9 +24,10 @@ struct MyCard1 { build() { Column() { - Text('Card') + Text('Card').applyStyles(this.cardStyle1) } - applyStyles.cardStyle1() + .applyStyles(this.cardStyle1) + .backgroundColor(Color.Red) } } @@ -34,9 +35,10 @@ struct MyCard1 { struct MyCard2 { cardStyle2 = (instance: CommonMethod): void => { instance.border({ - color: this.getColor(), - width: this.getWidth() + color: this.getColor(), + width: this.getWidth() }); + instance.backgroundColor('#ffffff'); }; private getColor(): Color { @@ -49,9 +51,10 @@ struct MyCard2 { build() { Column() { - Text('Card') + Text('Card').applyStyles(this.cardStyle2) } - .cardStyle2() + .applyStyles(this.cardStyle2) + .backgroundColor(Color.Red) } } @@ -63,19 +66,19 @@ struct MyButton { NormalStyles = (instance: CommonMethod): void => { instance.backgroundColor(Color.Red); - } + }; PressedStyles = (instance: CommonMethod): void => { instance.backgroundColor(Color.Green); - } + }; build() { Button() { this.content } .stateStyles({ - normal: this.NormalStyles(), - pressed: this.PressedStyles() + normal: this.NormalStyles, + pressed: this.PressedStyles }) } } @@ -100,13 +103,13 @@ struct imageTest { imageStyle = (instance: CommonMethod): void => { instance.draggable(this.isShowLongPressMenu() && this.isPC()); instance.onDragStart(() => { - console.info(TAG, 'onDragStart'); - this.touchVibrate(VibrateType.DRAG); - if (this.mediaItem?.path) { - this.previewUri = - this.getPreviewUri(this.mediaItem?.path, this.mediaItem?.getDateModified?.(), false, true); - } - return this.DragBuilder; + console.info(TAG, 'onDragStart'); + this.touchVibrate(VibrateType.DRAG); + if (this.mediaItem?.path) { + this.previewUri = + this.getPreviewUri(this.mediaItem?.path, this.mediaItem?.getDateModified?.(), false, true); + } + return this.DragBuilder; }); instance.accessibilityText(this.isOpenTouchGuide ? this.getImageItemGridAccessibilityText() : ''); }; diff --git a/ets2panda/linter/test/main/styles_decorator_struct_2.ets.args.json b/ets2panda/linter/test/main/styles_decorator_struct_2.ets.args.json index 5cdfe96f7a..ee0734c0fc 100644 --- a/ets2panda/linter/test/main/styles_decorator_struct_2.ets.args.json +++ b/ets2panda/linter/test/main/styles_decorator_struct_2.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_struct_2.ets.arkts2.json b/ets2panda/linter/test/main/styles_decorator_struct_2.ets.arkts2.json index 13eb52986b..0e17a7dad5 100644 --- a/ets2panda/linter/test/main/styles_decorator_struct_2.ets.arkts2.json +++ b/ets2panda/linter/test/main/styles_decorator_struct_2.ets.arkts2.json @@ -15,29 +15,9 @@ ], "result": [ { - "line": 77, - "column": 15, - "endLine": 77, - "endColumn": 34, - "problem": "LimitedVoidType", - "suggest": "", - "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", - "severity": "ERROR" - }, - { - "line": 78, - "column": 16, - "endLine": 78, - "endColumn": 36, - "problem": "LimitedVoidType", - "suggest": "", - "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", - "severity": "ERROR" - }, - { - "line": 102, + "line": 105, "column": 26, - "endLine": 110, + "endLine": 113, "endColumn": 6, "problem": "LimitedReturnTypeInference", "suggest": "", diff --git a/ets2panda/linter/test/main/styles_decorator_struct_2.ets.autofix.json b/ets2panda/linter/test/main/styles_decorator_struct_2.ets.autofix.json index 13eb52986b..0e17a7dad5 100644 --- a/ets2panda/linter/test/main/styles_decorator_struct_2.ets.autofix.json +++ b/ets2panda/linter/test/main/styles_decorator_struct_2.ets.autofix.json @@ -15,29 +15,9 @@ ], "result": [ { - "line": 77, - "column": 15, - "endLine": 77, - "endColumn": 34, - "problem": "LimitedVoidType", - "suggest": "", - "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", - "severity": "ERROR" - }, - { - "line": 78, - "column": 16, - "endLine": 78, - "endColumn": 36, - "problem": "LimitedVoidType", - "suggest": "", - "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", - "severity": "ERROR" - }, - { - "line": 102, + "line": 105, "column": 26, - "endLine": 110, + "endLine": 113, "endColumn": 6, "problem": "LimitedReturnTypeInference", "suggest": "", diff --git a/ets2panda/linter/test/main/styles_decorator_struct_2.ets.json b/ets2panda/linter/test/main/styles_decorator_struct_2.ets.json index ce898503c6..0e17a7dad5 100644 --- a/ets2panda/linter/test/main/styles_decorator_struct_2.ets.json +++ b/ets2panda/linter/test/main/styles_decorator_struct_2.ets.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 102, + "line": 105, "column": 26, - "endLine": 110, + "endLine": 113, "endColumn": 6, "problem": "LimitedReturnTypeInference", "suggest": "", diff --git a/ets2panda/linter/test/main/styles_decorator_struct_2.ets.migrate.ets b/ets2panda/linter/test/main/styles_decorator_struct_2.ets.migrate.ets new file mode 100644 index 0000000000..31fb825cee --- /dev/null +++ b/ets2panda/linter/test/main/styles_decorator_struct_2.ets.migrate.ets @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI'; + +@Component +struct MyCard1 { + cardStyle1 = (instance: CommonMethod): void => { + instance.backgroundColor('#ffffff'); + instance.borderRadius(8); + }; + + build() { + Column() { + Text('Card').applyStyles(this.cardStyle1) + } + .applyStyles(this.cardStyle1) + .backgroundColor(Color.Red) + } +} + +@Component +struct MyCard2 { + cardStyle2 = (instance: CommonMethod): void => { + instance.border({ + color: this.getColor(), + width: this.getWidth() + }); + instance.backgroundColor('#ffffff'); + }; + + private getColor(): Color { + return Color.Red + } + + private getWidth(): number { + return 10 + } + + build() { + Column() { + Text('Card').applyStyles(this.cardStyle2) + } + .applyStyles(this.cardStyle2) + .backgroundColor(Color.Red) + } +} + +@Component +struct MyButton { + @BuilderParam + @Require + content: () => void; + + NormalStyles = (instance: CommonMethod): void => { + instance.backgroundColor(Color.Red); + }; + + PressedStyles = (instance: CommonMethod): void => { + instance.backgroundColor(Color.Green); + }; + + build() { + Button() { + this.content + } + .stateStyles({ + normal: this.NormalStyles, + pressed: this.PressedStyles + }) + } +} + +const TAG: string = 'common_ImageTest'; + +class MediaItem { + public path: string = ''; + public uri: string = ''; + + public getDateModified(): string { + return '' + } +} + +@Component +struct imageTest { + private mediaItem: MediaItem | undefined; + private previewUri: string | undefined; + private DragBuilder: CustomBuilder | undefined; + + imageStyle = (instance: CommonMethod): void => { + instance.draggable(this.isShowLongPressMenu() && this.isPC()); + instance.onDragStart(() => { + console.info(TAG, 'onDragStart'); + this.touchVibrate(VibrateType.DRAG); + if (this.mediaItem?.path) { + this.previewUri = + this.getPreviewUri(this.mediaItem?.path, this.mediaItem?.getDateModified?.(), false, true); + } + return this.DragBuilder; + }); + instance.accessibilityText(this.isOpenTouchGuide ? this.getImageItemGridAccessibilityText() : ''); + }; + + private isShowLongPressMenu(): boolean { + return true; + } + + private isPC(): boolean { + return true; + } + + private touchVibrate(type: VibrateType): void { + + } + + private isOpenTouchGuide: boolean = true; + + private getImageItemGridAccessibilityText(): string { + return '' + } + + private getPreviewUri(path: string, date: string, isOk: boolean, ready: boolean): string { + return '' + } + + build() { + + } +} + +enum VibrateType { + DRAG +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_struct_2.ets.migrate.json b/ets2panda/linter/test/main/styles_decorator_struct_2.ets.migrate.json new file mode 100644 index 0000000000..0e17a7dad5 --- /dev/null +++ b/ets2panda/linter/test/main/styles_decorator_struct_2.ets.migrate.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 105, + "column": 26, + "endLine": 113, + "endColumn": 6, + "problem": "LimitedReturnTypeInference", + "suggest": "", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/ts_decorator.ets b/ets2panda/linter/test/main/subclass_super_call.ets similarity index 64% rename from ets2panda/linter/test/interop/ts_decorator.ets rename to ets2panda/linter/test/main/subclass_super_call.ets index 8ce1c11817..d275725c9c 100644 --- a/ets2panda/linter/test/interop/ts_decorator.ets +++ b/ets2panda/linter/test/main/subclass_super_call.ets @@ -12,23 +12,28 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +'use static' -import {MyClassDecorator, MyClassDecorator2} from "./oh_modules/ts_decorator" -import { MyDecorator } from "./oh_modules/ets_decorator"; - -@MyClassDecorator -class K {} +class A { + constructor(a: number) { + } +} -@Entry //legal -class X {} +class B { + constructor() { + } +} -@MyDecorator //legal -class Y {} +class C extends A {} // ERROR -@MyClassDecorator2 -class Z {} +class D extends A { // ERROR super is not called + constructor(a: number) {} +} -class Example { - @MyClassDecorator2 //legal - doSomething() {} +class E extends A { // NO ERROR constructor is called + constructor(a: number) { + super(a); + } } + +class F extends B {} // NO ERROR diff --git a/ets2panda/linter/test/sdkwhite/OptionalMethod1.ets.args.json b/ets2panda/linter/test/main/subclass_super_call.ets.args.json similarity index 100% rename from ets2panda/linter/test/sdkwhite/OptionalMethod1.ets.args.json rename to ets2panda/linter/test/main/subclass_super_call.ets.args.json diff --git a/ets2panda/linter/test/main/subclass_super_call.ets.arkts2.json b/ets2panda/linter/test/main/subclass_super_call.ets.arkts2.json new file mode 100644 index 0000000000..289a83337b --- /dev/null +++ b/ets2panda/linter/test/main/subclass_super_call.ets.arkts2.json @@ -0,0 +1,38 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 27, + "column": 9, + "endLine": 27, + "endColumn": 18, + "problem": "MissingSuperCall", + "suggest": "", + "rule": "The subclass constructor must call the parent class's parametered constructor (arkts-subclass-must-call-super-constructor-with-args)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 9, + "endLine": 29, + "endColumn": 18, + "problem": "MissingSuperCall", + "suggest": "", + "rule": "The subclass constructor must call the parent class's parametered constructor (arkts-subclass-must-call-super-constructor-with-args)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/main/subclass_super_call.ets.json b/ets2panda/linter/test/main/subclass_super_call.ets.json new file mode 100644 index 0000000000..dd03fcf544 --- /dev/null +++ b/ets2panda/linter/test/main/subclass_super_call.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} diff --git a/ets2panda/linter/test/main/swicth_expr.ets b/ets2panda/linter/test/main/swicth_expr.ets index 6cb0b9550e..bdef6cc461 100755 --- a/ets2panda/linter/test/main/swicth_expr.ets +++ b/ets2panda/linter/test/main/swicth_expr.ets @@ -31,7 +31,7 @@ switch (objValue) { break; default: console.log("Non-matching object"); - +} let arrayValue = [1, 2, 3]; @@ -220,4 +220,162 @@ switch (str11) { break case "world": console.log("Default Case") +} + +let isnum1: string | number = 1; +switch (isnum1) { + case 1.1: + console.log('It's num'); + break; + default: + console.log('F'); +} +// 整型 5.2fail +type sw1 = number + +function FunSw4(): sw1 { + return 1 +} + +switch (FunSw4()) { + case 1: + console.log('A'); + break; + default: + console.log('F'); +} + +// 浮点 5.2fail +type sw2 = number | string + +function FunSw5(): sw2 { + return 1.11 +} + +switch (FunSw5()) { + case 1.11: + console.log('A'); + break; + default: + console.log('F'); +} + +let number7 = Math.floor(1.5); +switch (number7) { + case Math.floor(1.5): + console.log("Case 1"); + break; + default: + console.log("Default case"); +} +switch (85 + 5.5) { + case 90.5: + console.log('A'); + break; + default: + console.log('F'); +} +const add = (a: number, b: number): number => a + b; +const result1 = add(10, 5); +switch (result1) { + case 15: + console.log('A'); + break; + case 14: + console.log('B'); + break; + default: + console.log('F'); +} +function FunSw2(): number { + return 1.1 +} + +switch (FunSw2()) { + case 1.1: + console.log('A'); + break; + default: + console.log('F'); +} + +// 正无穷 +let number4 = Infinity; +switch (number4) { + case Infinity: + console.log("Case 1"); + break; + default: + console.log("Default case"); +} + +// 负无穷 +let number5 = -Infinity; +switch (number5) { + case -Infinity: + console.log("Case 1"); + break; + default: + console.log("Default case"); +} + +// NaN +let number6 = NaN; +switch (number6) { + case NaN: + console.log("Case 1"); + break; + default: + console.log("Default case"); +} +// 1.0 +let num111 = 1.0; +switch (num111) { + case 1.0: + console.log('One'); + break; + case 2.0: + console.log('Other number'); +} + +// let声明整型,case浮点 +let number33: number = 1; +switch (number33) { + case 1.1: + console.log("Case 1"); + break; + case 2: + console.log("Case 2"); + break; + case 3: + console.log("Case 3"); + break; + default: + console.log("Default case"); +} + +// const声明,整型number,有类型 +const num11: number = 2; +switch (num11) { + case 1: { + console.log('One'); + break; + } + case 2: { + console.log('Two'); + break; + } +} + +// let声明,整型number,有类型 +let num00: number = 2; +switch (num00) { + case 1: { + console.log('One'); + break; + } + case 2: { + console.log('Two'); + break; + } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/swicth_expr.ets.arkts2.json b/ets2panda/linter/test/main/swicth_expr.ets.arkts2.json index 641b2b4be7..bd61cc7b00 100755 --- a/ets2panda/linter/test/main/swicth_expr.ets.arkts2.json +++ b/ets2panda/linter/test/main/swicth_expr.ets.arkts2.json @@ -13,196 +13,446 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "result": [ - { - "line": 17, - "column": 9, - "endLine": 17, - "endColumn": 15, - "problem": "SwitchExpression", - "suggest": "", - "rule": "The switch expression type must be of type number,string or enum (arkts-switch-expr)", - "severity": "ERROR" - }, - { - "line": 26, - "column": 16, - "endLine": 26, - "endColumn": 17, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 28, - "column": 9, - "endLine": 28, - "endColumn": 17, - "problem": "SwitchExpression", - "suggest": "", - "rule": "The switch expression type must be of type number,string or enum (arkts-switch-expr)", - "severity": "ERROR" - }, - { - "line": 29, - "column": 8, - "endLine": 29, - "endColumn": 9, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 36, - "column": 5, - "endLine": 36, - "endColumn": 27, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 38, - "column": 9, - "endLine": 38, - "endColumn": 19, - "problem": "SwitchExpression", - "suggest": "", - "rule": "The switch expression type must be of type number,string or enum (arkts-switch-expr)", - "severity": "ERROR" - }, - { - "line": 56, - "column": 7, - "endLine": 56, - "endColumn": 18, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 70, - "column": 7, - "endLine": 70, - "endColumn": 20, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 80, - "column": 7, - "endLine": 80, - "endColumn": 21, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 81, - "column": 9, - "endLine": 81, - "endColumn": 16, - "problem": "SwitchExpression", - "suggest": "", - "rule": "The switch expression type must be of type number,string or enum (arkts-switch-expr)", - "severity": "ERROR" - }, - { - "line": 90, - "column": 7, - "endLine": 90, - "endColumn": 27, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 91, - "column": 9, - "endLine": 91, - "endColumn": 16, - "problem": "SwitchExpression", - "suggest": "", - "rule": "The switch expression type must be of type number,string or enum (arkts-switch-expr)", - "severity": "ERROR" - }, - { - "line": 100, - "column": 7, - "endLine": 100, - "endColumn": 33, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 101, - "column": 9, - "endLine": 101, - "endColumn": 16, - "problem": "SwitchExpression", - "suggest": "", - "rule": "The switch expression type must be of type number,string or enum (arkts-switch-expr)", - "severity": "ERROR" - }, - { - "line": 139, - "column": 1, - "endLine": 139, - "endColumn": 9, - "problem": "LocalFunction", - "suggest": "", - "rule": "Nested functions are not supported (arkts-no-nested-funcs)", - "severity": "ERROR" - }, - { - "line": 163, - "column": 5, - "endLine": 163, - "endColumn": 13, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 187, - "column": 5, - "endLine": 187, - "endColumn": 13, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 197, - "column": 5, - "endLine": 197, - "endColumn": 17, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 206, - "column": 7, - "endLine": 206, - "endColumn": 22, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - } - ] + "result": [ + { + "line": 17, + "column": 9, + "endLine": 17, + "endColumn": 15, + "problem": "SwitchExpression", + "suggest": "", + "rule": "The switch expression type must be of type char, byte, short, int, long, string or enum (arkts-switch-expr)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 16, + "endLine": 26, + "endColumn": 17, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 9, + "endLine": 28, + "endColumn": 17, + "problem": "SwitchExpression", + "suggest": "", + "rule": "The switch expression type must be of type char, byte, short, int, long, string or enum (arkts-switch-expr)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 8, + "endLine": 29, + "endColumn": 9, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 36, + "column": 5, + "endLine": 36, + "endColumn": 27, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 9, + "endLine": 38, + "endColumn": 19, + "problem": "SwitchExpression", + "suggest": "", + "rule": "The switch expression type must be of type char, byte, short, int, long, string or enum (arkts-switch-expr)", + "severity": "ERROR" + }, + { + "line": 56, + "column": 7, + "endLine": 56, + "endColumn": 18, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 70, + "column": 7, + "endLine": 70, + "endColumn": 20, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 80, + "column": 7, + "endLine": 80, + "endColumn": 21, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 81, + "column": 9, + "endLine": 81, + "endColumn": 16, + "problem": "SwitchExpression", + "suggest": "", + "rule": "The switch expression type must be of type char, byte, short, int, long, string or enum (arkts-switch-expr)", + "severity": "ERROR" + }, + { + "line": 90, + "column": 7, + "endLine": 90, + "endColumn": 27, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 91, + "column": 9, + "endLine": 91, + "endColumn": 16, + "problem": "SwitchExpression", + "suggest": "", + "rule": "The switch expression type must be of type char, byte, short, int, long, string or enum (arkts-switch-expr)", + "severity": "ERROR" + }, + { + "line": 100, + "column": 7, + "endLine": 100, + "endColumn": 33, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 101, + "column": 9, + "endLine": 101, + "endColumn": 16, + "problem": "SwitchExpression", + "suggest": "", + "rule": "The switch expression type must be of type char, byte, short, int, long, string or enum (arkts-switch-expr)", + "severity": "ERROR" + }, + { + "line": 112, + "column": 9, + "endLine": 112, + "endColumn": 12, + "problem": "SwitchExpression", + "suggest": "", + "rule": "The switch expression type must be of type char, byte, short, int, long, string or enum (arkts-switch-expr)", + "severity": "ERROR" + }, + { + "line": 140, + "column": 11, + "endLine": 140, + "endColumn": 19, + "problem": "SwitchExpression", + "suggest": "", + "rule": "The switch expression type must be of type char, byte, short, int, long, string or enum (arkts-switch-expr)", + "severity": "ERROR" + }, + { + "line": 152, + "column": 9, + "endLine": 152, + "endColumn": 14, + "problem": "SwitchExpression", + "suggest": "", + "rule": "The switch expression type must be of type char, byte, short, int, long, string or enum (arkts-switch-expr)", + "severity": "ERROR" + }, + { + "line": 163, + "column": 5, + "endLine": 163, + "endColumn": 13, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 176, + "column": 9, + "endLine": 176, + "endColumn": 14, + "problem": "SwitchExpression", + "suggest": "", + "rule": "The switch expression type must be of type char, byte, short, int, long, string or enum (arkts-switch-expr)", + "severity": "ERROR" + }, + { + "line": 187, + "column": 5, + "endLine": 187, + "endColumn": 13, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 197, + "column": 5, + "endLine": 197, + "endColumn": 17, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 198, + "column": 9, + "endLine": 198, + "endColumn": 15, + "problem": "SwitchExpression", + "suggest": "", + "rule": "The switch expression type must be of type char, byte, short, int, long, string or enum (arkts-switch-expr)", + "severity": "ERROR" + }, + { + "line": 206, + "column": 7, + "endLine": 206, + "endColumn": 22, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 216, + "column": 13, + "endLine": 216, + "endColumn": 32, + "problem": "CreatingPrimitiveTypes", + "suggest": "", + "rule": "ArkTS creating primitive types is not supported (arkts-primitive-type-normalization)", + "severity": "ERROR" + }, + { + "line": 226, + "column": 9, + "endLine": 226, + "endColumn": 15, + "problem": "SwitchExpression", + "suggest": "", + "rule": "The switch expression type must be of type char, byte, short, int, long, string or enum (arkts-switch-expr)", + "severity": "ERROR" + }, + { + "line": 240, + "column": 9, + "endLine": 240, + "endColumn": 17, + "problem": "SwitchExpression", + "suggest": "", + "rule": "The switch expression type must be of type char, byte, short, int, long, string or enum (arkts-switch-expr)", + "severity": "ERROR" + }, + { + "line": 255, + "column": 9, + "endLine": 255, + "endColumn": 17, + "problem": "SwitchExpression", + "suggest": "", + "rule": "The switch expression type must be of type char, byte, short, int, long, string or enum (arkts-switch-expr)", + "severity": "ERROR" + }, + { + "line": 263, + "column": 5, + "endLine": 263, + "endColumn": 30, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 264, + "column": 9, + "endLine": 264, + "endColumn": 16, + "problem": "SwitchExpression", + "suggest": "", + "rule": "The switch expression type must be of type char, byte, short, int, long, string or enum (arkts-switch-expr)", + "severity": "ERROR" + }, + { + "line": 271, + "column": 9, + "endLine": 271, + "endColumn": 17, + "problem": "SwitchExpression", + "suggest": "", + "rule": "The switch expression type must be of type char, byte, short, int, long, string or enum (arkts-switch-expr)", + "severity": "ERROR" + }, + { + "line": 279, + "column": 7, + "endLine": 279, + "endColumn": 27, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 280, + "column": 9, + "endLine": 280, + "endColumn": 16, + "problem": "SwitchExpression", + "suggest": "", + "rule": "The switch expression type must be of type char, byte, short, int, long, string or enum (arkts-switch-expr)", + "severity": "ERROR" + }, + { + "line": 294, + "column": 9, + "endLine": 294, + "endColumn": 17, + "problem": "SwitchExpression", + "suggest": "", + "rule": "The switch expression type must be of type char, byte, short, int, long, string or enum (arkts-switch-expr)", + "severity": "ERROR" + }, + { + "line": 303, + "column": 5, + "endLine": 303, + "endColumn": 23, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 304, + "column": 9, + "endLine": 304, + "endColumn": 16, + "problem": "SwitchExpression", + "suggest": "", + "rule": "The switch expression type must be of type char, byte, short, int, long, string or enum (arkts-switch-expr)", + "severity": "ERROR" + }, + { + "line": 313, + "column": 5, + "endLine": 313, + "endColumn": 24, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 314, + "column": 9, + "endLine": 314, + "endColumn": 16, + "problem": "SwitchExpression", + "suggest": "", + "rule": "The switch expression type must be of type char, byte, short, int, long, string or enum (arkts-switch-expr)", + "severity": "ERROR" + }, + { + "line": 323, + "column": 5, + "endLine": 323, + "endColumn": 18, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 324, + "column": 9, + "endLine": 324, + "endColumn": 16, + "problem": "SwitchExpression", + "suggest": "", + "rule": "The switch expression type must be of type char, byte, short, int, long, string or enum (arkts-switch-expr)", + "severity": "ERROR" + }, + { + "line": 332, + "column": 5, + "endLine": 332, + "endColumn": 17, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 333, + "column": 9, + "endLine": 333, + "endColumn": 15, + "problem": "SwitchExpression", + "suggest": "", + "rule": "The switch expression type must be of type char, byte, short, int, long, string or enum (arkts-switch-expr)", + "severity": "ERROR" + }, + { + "line": 343, + "column": 9, + "endLine": 343, + "endColumn": 17, + "problem": "SwitchExpression", + "suggest": "", + "rule": "The switch expression type must be of type char, byte, short, int, long, string or enum (arkts-switch-expr)", + "severity": "ERROR" + }, + { + "line": 359, + "column": 9, + "endLine": 359, + "endColumn": 14, + "problem": "SwitchExpression", + "suggest": "", + "rule": "The switch expression type must be of type char, byte, short, int, long, string or enum (arkts-switch-expr)", + "severity": "ERROR" + }, + { + "line": 372, + "column": 9, + "endLine": 372, + "endColumn": 14, + "problem": "SwitchExpression", + "suggest": "", + "rule": "The switch expression type must be of type char, byte, short, int, long, string or enum (arkts-switch-expr)", + "severity": "ERROR" + } +] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/swicth_expr.ets.json b/ets2panda/linter/test/main/swicth_expr.ets.json index f4aef68661..9dda12ea9c 100755 --- a/ets2panda/linter/test/main/swicth_expr.ets.json +++ b/ets2panda/linter/test/main/swicth_expr.ets.json @@ -15,33 +15,23 @@ ], "result": [ { - "line": 26, - "column": 16, - "endLine": 26, - "endColumn": 17, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 29, - "column": 8, - "endLine": 29, - "endColumn": 9, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" + "line": 26, + "column": 16, + "endLine": 26, + "endColumn": 17, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" }, { - "line": 139, - "column": 1, - "endLine": 139, + "line": 29, + "column": 8, + "endLine": 29, "endColumn": 9, - "problem": "LocalFunction", + "problem": "ObjectLiteralNoContextType", "suggest": "", - "rule": "Nested functions are not supported (arkts-no-nested-funcs)", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/main/taskpool_deprecated_usages.ets b/ets2panda/linter/test/main/taskpool_deprecated_usages.ets new file mode 100644 index 0000000000..05ec4e2f14 --- /dev/null +++ b/ets2panda/linter/test/main/taskpool_deprecated_usages.ets @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +'use static' + +let baseInstance1: BaseClass = new BaseClass(); +let array1 = new Array(); +array1.push(baseInstance1); +let task1 = new taskpool.Task(testFunc, array1, 10); +task1.setCloneList(array1); +task1.setTransferList(array1); diff --git a/ets2panda/linter/test/migrate/class_static_block.ts.args.json b/ets2panda/linter/test/main/taskpool_deprecated_usages.ets.args.json similarity index 90% rename from ets2panda/linter/test/migrate/class_static_block.ts.args.json rename to ets2panda/linter/test/main/taskpool_deprecated_usages.ets.args.json index 66b623df60..3ef4496a81 100644 --- a/ets2panda/linter/test/migrate/class_static_block.ts.args.json +++ b/ets2panda/linter/test/main/taskpool_deprecated_usages.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,6 @@ "limitations under the License." ], "mode": { - "migrate": "" + "arkts2": "" } } diff --git a/ets2panda/linter/test/main/taskpool_deprecated_usages.ets.arkts2.json b/ets2panda/linter/test/main/taskpool_deprecated_usages.ets.arkts2.json new file mode 100644 index 0000000000..f2b6fbc104 --- /dev/null +++ b/ets2panda/linter/test/main/taskpool_deprecated_usages.ets.arkts2.json @@ -0,0 +1,68 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 36, + "endLine": 17, + "endColumn": 45, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 5, + "endLine": 20, + "endColumn": 52, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 17, + "endLine": 20, + "endColumn": 30, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 28, + "problem": "SetCloneListDeprecated", + "suggest": "", + "rule": "The taskpool setCloneList interface is deleted from ArkTS1.2 (arkts-limited-stdlib-no-setCloneList)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 1, + "endLine": 22, + "endColumn": 31, + "problem": "SetTransferListDeprecated", + "suggest": "", + "rule": "The taskpool setTransferList interface is deleted from ArkTS1.2 (arkts-limited-stdlib-no-setTransferList)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/main/taskpool_deprecated_usages.ets.json b/ets2panda/linter/test/main/taskpool_deprecated_usages.ets.json new file mode 100644 index 0000000000..1c17b59df7 --- /dev/null +++ b/ets2panda/linter/test/main/taskpool_deprecated_usages.ets.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 20, + "column": 5, + "endLine": 20, + "endColumn": 52, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/main/ts-like-catch-type.ets b/ets2panda/linter/test/main/ts-like-catch-type.ets new file mode 100644 index 0000000000..76d4be8122 --- /dev/null +++ b/ets2panda/linter/test/main/ts-like-catch-type.ets @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +function test() { + try { + let a: number = 1; + } catch (e) { + console.log('catch') + } +} + +function test2() { + try { + let a: number = 1; + } catch (e: any) { + console.log('catch') + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/ts-like-catch-type.ets.args.json b/ets2panda/linter/test/main/ts-like-catch-type.ets.args.json new file mode 100644 index 0000000000..e2b903f0aa --- /dev/null +++ b/ets2panda/linter/test/main/ts-like-catch-type.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } + } \ No newline at end of file diff --git a/ets2panda/linter/test/main/ts-like-catch-type.ets.arkts2.json b/ets2panda/linter/test/main/ts-like-catch-type.ets.arkts2.json new file mode 100644 index 0000000000..c42a190874 --- /dev/null +++ b/ets2panda/linter/test/main/ts-like-catch-type.ets.arkts2.json @@ -0,0 +1,58 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 19, + "column": 5, + "endLine": 21, + "endColumn": 4, + "problem": "TsLikeCatchType", + "suggest": "", + "rule": "TS catch type are not supported (arkts-no-ts-like-catch-type)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 12, + "endLine": 27, + "endColumn": 18, + "problem": "CatchWithUnsupportedType", + "suggest": "", + "rule": "Type annotation in catch clause is not supported (arkts-no-types-in-catch)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 5, + "endLine": 29, + "endColumn": 4, + "problem": "TsLikeCatchType", + "suggest": "", + "rule": "TS catch type are not supported (arkts-no-ts-like-catch-type)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 15, + "endLine": 27, + "endColumn": 18, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/ts-like-catch-type.ets.json b/ets2panda/linter/test/main/ts-like-catch-type.ets.json new file mode 100644 index 0000000000..bd65f7efbe --- /dev/null +++ b/ets2panda/linter/test/main/ts-like-catch-type.ets.json @@ -0,0 +1,38 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 27, + "column": 12, + "endLine": 27, + "endColumn": 18, + "problem": "CatchWithUnsupportedType", + "suggest": "", + "rule": "Type annotation in catch clause is not supported (arkts-no-types-in-catch)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 15, + "endLine": 27, + "endColumn": 18, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/type_literals.ets.args.json b/ets2panda/linter/test/main/type_literals.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/main/type_literals.ets.args.json +++ b/ets2panda/linter/test/main/type_literals.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/migrate/type_literals.sts b/ets2panda/linter/test/main/type_literals.ets.migrate.ets similarity index 34% rename from ets2panda/linter/test/migrate/type_literals.sts rename to ets2panda/linter/test/main/type_literals.ets.migrate.ets index b3ec3eea0f..a8a0de8970 100644 --- a/ets2panda/linter/test/migrate/type_literals.sts +++ b/ets2panda/linter/test/main/type_literals.ets.migrate.ets @@ -13,36 +13,83 @@ * limitations under the License. */ -type Type1 = {}; -type Type2 = {a: number; b: string;}; -type Type3 = {a: number, b: number,}[]; -type Type4 = Type1 | {a: number, b: string} | {c: number, d: string}; -type Type5 = {a: T, b: K, c: number}; -type Type6 = { - a: number - b: string - c: { - x: number - y: string - z: Type1 - } -}; -export type Type7 = {a: number}; - -let var1: {} = {}; -let var2: {a: number, b: string} = {a:1, b:'2'}; -let var3: {a: number, b: number,}[]; -let var4: Type1 | {a: number, b: string} | {c: number, d: string}; -let var5 = var1 as {a: number, b: string}; -let var6: { - a: number - b: string - c: { - x: number - y: string - z: Type2 - } -} = { +interface Type1 { +} +interface Type2 { + a: number; + b: string; +} +interface GeneratedTypeLiteralInterface_1 { + a: number; + b: number; +} +type Type3 = GeneratedTypeLiteralInterface_1[]; +interface GeneratedTypeLiteralInterface_2 { + a: number; + b: string; +} +interface GeneratedTypeLiteralInterface_3 { + c: number; + d: string; +} +type Type4 = Type1 | GeneratedTypeLiteralInterface_2 | GeneratedTypeLiteralInterface_3; +interface Type5 { + a: T; + b: K; + c: number; +} +interface GeneratedTypeLiteralInterface_4 { + x: number; + y: string; + z: Type1; +} +interface Type6 { + a: number; + b: string; + c: GeneratedTypeLiteralInterface_4; +} +export interface Type7 { + a: number; +} + +interface GeneratedTypeLiteralInterface_5 { +} +let var1: GeneratedTypeLiteralInterface_5 = {}; +interface GeneratedTypeLiteralInterface_6 { + a: number; + b: string; +} +let var2: GeneratedTypeLiteralInterface_6 = {a:1, b:'2'}; +interface GeneratedTypeLiteralInterface_7 { + a: number; + b: number; +} +let var3: GeneratedTypeLiteralInterface_7[]; +interface GeneratedTypeLiteralInterface_8 { + a: number; + b: string; +} +interface GeneratedTypeLiteralInterface_9 { + c: number; + d: string; +} +let var4: Type1 | GeneratedTypeLiteralInterface_8 | GeneratedTypeLiteralInterface_9; +interface GeneratedTypeLiteralInterface_10 { + a: number; + b: string; +} +let var5 = var1 as GeneratedTypeLiteralInterface_10; +interface GeneratedTypeLiteralInterface_12 { + x: number; + y: string; + z: Type2; +} +interface GeneratedTypeLiteralInterface_11 { + a: number; + b: string; + c: GeneratedTypeLiteralInterface_12; +} +let var6: GeneratedTypeLiteralInterface_11 = { a: 1, b: '2', c: { @@ -55,67 +102,100 @@ let var6: { } }; -function f(p: {x: number, y: string}): {z: boolean} { +interface GeneratedTypeLiteralInterface_13 { + x: number; + y: string; +} +interface GeneratedTypeLiteralInterface_14 { + z: boolean; +} +function f(p: GeneratedTypeLiteralInterface_13): GeneratedTypeLiteralInterface_14 { return {z: true}; } +interface GeneratedTypeLiteralInterface_15 { + a: number; + b: string; +} +interface GeneratedTypeLiteralInterface_16 { + c: number; + d: string; +} +interface GeneratedTypeLiteralInterface_17 { + e: boolean; +} class C { - f: {a: number, b: string} = {a: 1, b:'2'}; + f: GeneratedTypeLiteralInterface_15 = {a: 1, b:'2'}; - m(p: {c: number, d: string}): {e: boolean} { + m(p: GeneratedTypeLiteralInterface_16): GeneratedTypeLiteralInterface_17 { return {e: true}; } } // Generic types class GC {} -class GC2 extends GC<{ x: 10 }> {} -const gc: GC<{ y: string }> = new GC<{ y: '20' }>(); +interface GeneratedTypeLiteralInterface_18 { + x: 10; +} +class GC2 extends GC {} +interface GeneratedTypeLiteralInterface_19 { + y: string; +} +interface GeneratedTypeLiteralInterface_20 { + y: '20'; +} +const gc: GC = new GC(); -type GType = GC; +interface GeneratedTypeLiteralInterface_21 { + z: number; +} +type GType = GC; function g(t: T): number { return 10; } -g<{ z: boolean }>({ z: true }); - -type TypeMembers = { - a: number; - 'b': string; - 3: boolean; - ['x']: number; - - m: (p: string) => number; - n(p: number): void; - get val(): number; - set val(p: number); - - (p: number): string; - new (p: string): C; - [key: string]: unknown; +interface GeneratedTypeLiteralInterface_22 { + z: boolean; +} +g({ z: true }); + +interface TypeMembers { + a: number; + 'b': string; + __3: boolean; + ['x']: number; + m: (p: string) => number; + n(p: number): void; + get val(): number; + set val(p: number); + (p: number): string; + new (p: string): C; + [key: string]: unknown; } -let typeMembers: { - a: number; - 'b': string; - 3: boolean; - ['x']: number; - - m: (p: string) => number; - n(p: number): void; - get val(): number; - set val(p: number); - - (p: number): string; - new (p: string): C; - [key: string]: unknown; -}; +interface GeneratedTypeLiteralInterface_23 { + a: number; + 'b': string; + __3: boolean; + ['x']: number; + m: (p: string) => number; + n(p: number): void; + get val(): number; + set val(p: number); + (p: number): string; + new (p: string): C; + [key: string]: unknown; +} +let typeMembers: GeneratedTypeLiteralInterface_23; // Capture type from enclosing local scope export function captureFromLocalScope(t: T): {ret: T} { // Non-fixable, type captures type parameter from enclosing declaration let v1: {local: T}; // Non-fixable, type captures type parameter from enclosing declaration - type LocalType = {a: number, b: string}; + interface LocalType { + a: number; + b: string; +} let v2: { x: LocalType } = {x: {a: 1, b: '2'}}; // Non-fixable, type captures another type declared in local scope type LocalType2 = ({k: K}); // Non-fixable, type captures type parameter from enclosing declaration diff --git a/ets2panda/linter/test/migrate/types.ts.migrate.json b/ets2panda/linter/test/main/type_literals.ets.migrate.json similarity index 31% rename from ets2panda/linter/test/migrate/types.ts.migrate.json rename to ets2panda/linter/test/main/type_literals.ets.migrate.json index 58dcba3064..f132876e48 100644 --- a/ets2panda/linter/test/migrate/types.ts.migrate.json +++ b/ets2panda/linter/test/main/type_literals.ets.migrate.json @@ -1,454 +1,238 @@ { + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], "result": [ { - "line": 17, - "column": 15, - "endLine": 17, - "endColumn": 18, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 18, - "column": 15, - "endLine": 18, - "endColumn": 21, - "problem": "SymbolType", - "suggest": "", - "rule": "\"Symbol()\" API is not supported (arkts-no-symbol)", - "severity": "ERROR" - }, - { - "line": 19, - "column": 20, - "endLine": 19, - "endColumn": 27, - "problem": "UnknownType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 26, - "column": 18, - "endLine": 26, - "endColumn": 19, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 32, - "column": 16, - "endLine": 32, - "endColumn": 17, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 34, - "column": 15, - "endLine": 34, + "line": 171, + "column": 5, + "endLine": 171, "endColumn": 25, - "problem": "IndexedAccessType", - "suggest": "", - "rule": "Indexed access types are not supported (arkts-no-aliases-by-index)", - "severity": "ERROR" - }, - { - "line": 36, - "column": 24, - "endLine": 36, - "endColumn": 31, - "problem": "UnknownType", + "problem": "CallSignature", "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "rule": "Use \"class\" instead of a type with call signature (arkts-no-call-signatures)", "severity": "ERROR" }, { - "line": 37, - "column": 20, - "endLine": 37, - "endColumn": 23, - "problem": "AnyType", + "line": 172, + "column": 5, + "endLine": 172, + "endColumn": 24, + "problem": "ConstructorIface", "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "rule": "Construct signatures are not supported in interfaces (arkts-no-ctor-signatures-iface)", "severity": "ERROR" }, { - "line": 43, - "column": 3, - "endLine": 43, - "endColumn": 11, - "problem": "LocalFunction", + "line": 173, + "column": 5, + "endLine": 173, + "endColumn": 28, + "problem": "IndexMember", "suggest": "", - "rule": "Nested functions are not supported (arkts-no-nested-funcs)", + "rule": "Indexed signatures are not supported (arkts-no-indexed-signatures)", "severity": "ERROR" }, { - "line": 43, - "column": 24, - "endLine": 43, + "line": 173, + "column": 20, + "endLine": 173, "endColumn": 27, - "problem": "AnyType", + "problem": "UnknownType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, { - "line": 43, - "column": 30, - "endLine": 43, - "endColumn": 41, - "problem": "IsOperator", - "suggest": "", - "rule": "Type guarding is supported with \"instanceof\" and \"as\" (arkts-no-is)", - "severity": "ERROR" - }, - { - "line": 54, - "column": 26, - "endLine": 54, - "endColumn": 27, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 56, - "column": 3, - "endLine": 56, - "endColumn": 4, - "problem": "LiteralAsPropertyName", - "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", - "severity": "ERROR" - }, - { - "line": 57, - "column": 3, - "endLine": 57, - "endColumn": 6, - "problem": "ComputedPropertyName", - "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", - "severity": "ERROR" - }, - { - "line": 58, - "column": 3, - "endLine": 58, - "endColumn": 6, - "problem": "ComputedPropertyName", - "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", - "severity": "ERROR" - }, - { - "line": 62, - "column": 3, - "endLine": 62, - "endColumn": 4, - "problem": "LiteralAsPropertyName", - "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", - "severity": "ERROR" - }, - { - "line": 67, - "column": 3, - "endLine": 67, - "endColumn": 4, - "problem": "LiteralAsPropertyName", + "line": 185, + "column": 5, + "endLine": 185, + "endColumn": 25, + "problem": "CallSignature", "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "rule": "Use \"class\" instead of a type with call signature (arkts-no-call-signatures)", "severity": "ERROR" }, { - "line": 71, - "column": 19, - "endLine": 71, - "endColumn": 20, - "problem": "ObjectTypeLiteral", + "line": 186, + "column": 5, + "endLine": 186, + "endColumn": 24, + "problem": "ConstructorIface", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Construct signatures are not supported in interfaces (arkts-no-ctor-signatures-iface)", "severity": "ERROR" }, { - "line": 72, - "column": 3, - "endLine": 72, - "endColumn": 26, + "line": 187, + "column": 5, + "endLine": 187, + "endColumn": 28, "problem": "IndexMember", "suggest": "", "rule": "Indexed signatures are not supported (arkts-no-indexed-signatures)", "severity": "ERROR" }, { - "line": 72, - "column": 18, - "endLine": 72, - "endColumn": 25, + "line": 187, + "column": 20, + "endLine": 187, + "endColumn": 27, "problem": "UnknownType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, { - "line": 76, - "column": 32, - "endLine": 76, - "endColumn": 35, - "problem": "AnyType", + "line": 192, + "column": 49, + "endLine": 192, + "endColumn": 50, + "problem": "ObjectTypeLiteral", "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", "severity": "ERROR" }, { - "line": 77, + "line": 193, "column": 11, - "endLine": 77, - "endColumn": 13, - "problem": "InOperator", - "suggest": "", - "rule": "\"in\" operator is not supported (arkts-no-in)", - "severity": "ERROR" - }, - { - "line": 78, - "column": 5, - "endLine": 78, - "endColumn": 14, - "problem": "PropertyAccessByIndex", - "suggest": "", - "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", - "severity": "ERROR" - }, - { - "line": 92, - "column": 22, - "endLine": 92, - "endColumn": 29, - "problem": "IntersectionType", + "endLine": 193, + "endColumn": 12, + "problem": "ObjectTypeLiteral", "suggest": "", - "rule": "Use inheritance instead of intersection types (arkts-no-intersection-types)", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", "severity": "ERROR" }, { - "line": 94, - "column": 28, - "endLine": 94, - "endColumn": 29, + "line": 199, + "column": 11, + "endLine": 199, + "endColumn": 12, "problem": "ObjectTypeLiteral", "suggest": "", "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", "severity": "ERROR" }, { - "line": 96, - "column": 3, - "endLine": 96, - "endColumn": 30, - "problem": "CallSignature", + "line": 199, + "column": 30, + "endLine": 199, + "endColumn": 31, + "problem": "ObjectLiteralNoContextType", "suggest": "", - "rule": "Use \"class\" instead of a type with call signature (arkts-no-call-signatures)", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 111, - "column": 19, - "endLine": 111, - "endColumn": 20, + "line": 201, + "column": 25, + "endLine": 201, + "endColumn": 26, "problem": "ObjectTypeLiteral", "suggest": "", "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", "severity": "ERROR" }, { - "line": 112, - "column": 12, - "endLine": 112, - "endColumn": 13, + "line": 204, + "column": 11, + "endLine": 204, + "endColumn": 12, "problem": "ObjectTypeLiteral", "suggest": "", "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", "severity": "ERROR" }, { - "line": 112, - "column": 35, - "endLine": 112, - "endColumn": 36, - "problem": "ObjectTypeLiteral", + "line": 204, + "column": 12, + "endLine": 204, + "endColumn": 17, + "problem": "ComputedPropertyName", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, { - "line": 116, - "column": 9, - "endLine": 116, - "endColumn": 10, + "line": 207, + "column": 11, + "endLine": 207, + "endColumn": 12, "problem": "ObjectTypeLiteral", "suggest": "", "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", "severity": "ERROR" }, { - "line": 116, - "column": 25, - "endLine": 116, - "endColumn": 26, + "line": 207, + "column": 31, + "endLine": 207, + "endColumn": 32, "problem": "ObjectLiteralNoContextType", "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 119, - "column": 9, - "endLine": 119, - "endColumn": 21, - "problem": "AnyType", + "line": 209, + "column": 11, + "endLine": 209, + "endColumn": 12, + "problem": "ObjectTypeLiteral", "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", "severity": "ERROR" }, { - "line": 119, - "column": 15, - "endLine": 119, - "endColumn": 21, - "problem": "TypeAssertion", + "line": 209, + "column": 17, + "endLine": 209, + "endColumn": 23, + "problem": "TypeQuery", "suggest": "", - "rule": "Only \"as T\" syntax is supported for type casts (arkts-as-casts)", + "rule": "\"typeof\" operator is allowed only in expression contexts (arkts-no-type-query)", "severity": "ERROR" }, { - "line": 119, - "column": 16, - "endLine": 119, - "endColumn": 19, - "problem": "AnyType", + "line": 211, + "column": 11, + "endLine": 211, + "endColumn": 12, + "problem": "ObjectTypeLiteral", "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", "severity": "ERROR" }, { - "line": 120, - "column": 20, - "endLine": 120, - "endColumn": 77, - "problem": "TypeAssertion", + "line": 211, + "column": 17, + "endLine": 211, + "endColumn": 23, + "problem": "TypeQuery", "suggest": "", - "rule": "Only \"as T\" syntax is supported for type casts (arkts-as-casts)", + "rule": "\"typeof\" operator is allowed only in expression contexts (arkts-no-type-query)", "severity": "ERROR" }, { - "line": 124, - "column": 13, - "endLine": 124, - "endColumn": 14, + "line": 213, + "column": 10, + "endLine": 213, + "endColumn": 11, "problem": "ObjectLiteralNoContextType", "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" - }, - { - "line": 125, - "column": 3, - "endLine": 125, - "endColumn": 9, - "problem": "PropertyAccessByIndex", - "suggest": "", - "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", - "severity": "ERROR" - }, - { - "line": 126, - "column": 15, - "endLine": 126, - "endColumn": 21, - "problem": "PropertyAccessByIndex", - "suggest": "", - "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", - "severity": "ERROR" - }, - { - "line": 128, - "column": 12, - "endLine": 128, - "endColumn": 15, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 138, - "column": 3, - "endLine": 138, - "endColumn": 11, - "problem": "LocalFunction", - "suggest": "", - "rule": "Nested functions are not supported (arkts-no-nested-funcs)", - "severity": "ERROR" - }, - { - "line": 157, - "column": 5, - "endLine": 157, - "endColumn": 23, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 106, - "column": 3, - "endLine": 106, - "endColumn": 6, - "problem": "StrictDiagnostic", - "suggest": "Property 'val' has no initializer and is not definitely assigned in the constructor.", - "rule": "Property 'val' has no initializer and is not definitely assigned in the constructor.", - "severity": "ERROR" - }, - { - "line": 148, - "column": 3, - "endLine": 148, - "endColumn": 4, - "problem": "StrictDiagnostic", - "suggest": "Type 'undefined' is not assignable to type 'string'.", - "rule": "Type 'undefined' is not assignable to type 'string'.", - "severity": "ERROR" - }, - { - "line": 149, - "column": 18, - "endLine": 149, - "endColumn": 27, - "problem": "StrictDiagnostic", - "suggest": "Argument of type 'undefined' is not assignable to parameter of type 'string'.", - "rule": "Argument of type 'undefined' is not assignable to parameter of type 'string'.", - "severity": "ERROR" - }, - { - "line": 150, - "column": 17, - "endLine": 150, - "endColumn": 26, - "problem": "StrictDiagnostic", - "suggest": "Argument of type 'undefined' is not assignable to parameter of type 'number'.", - "rule": "Argument of type 'undefined' is not assignable to parameter of type 'number'.", - "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/types.ets.args.json b/ets2panda/linter/test/main/types.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/main/types.ets.args.json +++ b/ets2panda/linter/test/main/types.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/migrate/types.sts b/ets2panda/linter/test/main/types.ets.migrate.ets similarity index 67% rename from ets2panda/linter/test/migrate/types.sts rename to ets2panda/linter/test/main/types.ets.migrate.ets index 3e6cffadf2..07bcd20369 100644 --- a/ets2panda/linter/test/migrate/types.sts +++ b/ets2panda/linter/test/main/types.ets.migrate.ets @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,6 +13,11 @@ * limitations under the License. */ +interface GeneratedObjectLiteralInterface_1 { + name: string; + idx: number; + handler: string; +} export function animations() { let anyvar: any = undefined; let symvar: symbol; @@ -23,13 +28,16 @@ export function animations() { const flag = false; - const status = { name: 'A', idx: 0, handler: 'foo' }; + const status: GeneratedObjectLiteralInterface_1 = { name: 'A', idx: 0, handler: 'foo' }; type Person = [string, number]; const user: Person = ['John', 32]; const age = user[1]; - type Point = { x: number; y: number }; + interface Point { + x: number; + y: number; +} type P = keyof Point; type AxeX = Point['x']; type P_NULL = P | null; @@ -40,9 +48,9 @@ export function animations() { const typeU = typeof user; - function isNumber(x: any): x is number { + let isNumber: (x: any) => x is number = (x: any): x is number => { return typeof x === 'number'; - } +}; const regex = /go*d/; @@ -51,26 +59,26 @@ export function animations() { const c = 'c'; const d = 10; -type ComputedPropertyT = { - a: string; // String-like name - 5: string; // Number-like name - [c]: string; // String-like name - [d]: string; // Number-like name -}; +interface ComputedPropertyT { + a: string; // String-like name + __5: string; // Number-like name + [c]: string; // String-like name + [d]: string; // Number-like name +} class LiteralAsPropertyName { - 2: string; + __2: string; 'Two': number; } const litAsPropName: LiteralAsPropertyName = { - 2: 'two', + __2: 'two', 'Two': 2, }; -type Dictionary = { - [key: string]: unknown; -}; +interface Dictionary { + [key: string]: unknown; +} let dict: Dictionary; function bar(key: string, val: any) { @@ -91,10 +99,10 @@ interface I2 { type IntersectionT = I1 & I2; -type DescribableFunction = { - description: string; - (someArg: number): boolean; -}; +interface DescribableFunction { + description: string; + (someArg: number): boolean; +} function callFunctionObject(fn: DescribableFunction) { console.log(fn.description + ' returned ' + fn(5)); } @@ -108,20 +116,36 @@ class G { return this.val; } } -class H extends G<{ x: 2 }> {} -const g: G<{ y: string }> = new G<{ y: 'constant' }>(); +interface GeneratedTypeLiteralInterface_1 { + x: 2; +} +class H extends G {} +interface GeneratedTypeLiteralInterface_2 { + y: string; +} +interface GeneratedTypeLiteralInterface_3 { + y: 'constant'; +} +const g: G = new G(); function generic(t: T): number { return 10; } -generic<{ z: boolean }>({ z: true }); +interface GeneratedTypeLiteralInterface_4 { + z: boolean; +} +generic({ z: true }); function typeAssertions(): void { - const num = 1; - const myCanvas = document.getElementById('main_canvas'); + const num = 1 as any; + const myCanvas = document.getElementById('main_canvas') as HTMLCanvasElement; } +interface GeneratedObjectLiteralInterface_2 { + a: number; + b: string; +} function dynamicProperties(): void { - const x = { a: 5, b: 'text' }; + const x: GeneratedObjectLiteralInterface_2 = { a: 5, b: 'text' }; x['c'] = 100200; console.log(x['c']); @@ -135,9 +159,9 @@ function genericArrayType(): void { const y: Array = new Array(1, 2, 3); const z: number[] = [1, 2, 3]; - function arrayFunc(array: Array): Array { + let arrayFunc: (array: Array) => Array = (array: Array): Array => { return array.map((x) => x.toString()); - } +}; } class C { diff --git a/ets2panda/linter/test/migrate/types.ts.json b/ets2panda/linter/test/main/types.ets.migrate.json similarity index 51% rename from ets2panda/linter/test/migrate/types.ts.json rename to ets2panda/linter/test/main/types.ets.migrate.json index 69500549d0..9235d4235c 100644 --- a/ets2panda/linter/test/migrate/types.ts.json +++ b/ets2panda/linter/test/main/types.ets.migrate.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2022-2024 Huawei Device Co., Ltd.", + "Copyright (c) 2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -15,9 +15,9 @@ ], "result": [ { - "line": 17, + "line": 22, "column": 15, - "endLine": 17, + "endLine": 22, "endColumn": 18, "problem": "AnyType", "suggest": "", @@ -25,9 +25,9 @@ "severity": "ERROR" }, { - "line": 18, + "line": 23, "column": 15, - "endLine": 18, + "endLine": 23, "endColumn": 21, "problem": "SymbolType", "suggest": "", @@ -35,9 +35,9 @@ "severity": "ERROR" }, { - "line": 19, + "line": 24, "column": 20, - "endLine": 19, + "endLine": 24, "endColumn": 27, "problem": "UnknownType", "suggest": "", @@ -45,29 +45,9 @@ "severity": "ERROR" }, { - "line": 26, - "column": 18, - "endLine": 26, - "endColumn": 19, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 32, - "column": 16, - "endLine": 32, - "endColumn": 17, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 34, + "line": 42, "column": 15, - "endLine": 34, + "endLine": 42, "endColumn": 25, "problem": "IndexedAccessType", "suggest": "", @@ -75,9 +55,9 @@ "severity": "ERROR" }, { - "line": 36, + "line": 44, "column": 24, - "endLine": 36, + "endLine": 44, "endColumn": 31, "problem": "UnknownType", "suggest": "", @@ -85,9 +65,9 @@ "severity": "ERROR" }, { - "line": 37, + "line": 45, "column": 20, - "endLine": 37, + "endLine": 45, "endColumn": 23, "problem": "AnyType", "suggest": "", @@ -95,129 +75,89 @@ "severity": "ERROR" }, { - "line": 43, - "column": 3, - "endLine": 43, - "endColumn": 11, - "problem": "LocalFunction", - "suggest": "", - "rule": "Nested functions are not supported (arkts-no-nested-funcs)", - "severity": "ERROR" - }, - { - "line": 43, - "column": 24, - "endLine": 43, - "endColumn": 27, + "line": 51, + "column": 21, + "endLine": 51, + "endColumn": 24, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, { - "line": 43, - "column": 30, - "endLine": 43, - "endColumn": 41, + "line": 51, + "column": 29, + "endLine": 51, + "endColumn": 40, "problem": "IsOperator", "suggest": "", "rule": "Type guarding is supported with \"instanceof\" and \"as\" (arkts-no-is)", "severity": "ERROR" }, { - "line": 54, - "column": 26, - "endLine": 54, - "endColumn": 27, - "problem": "ObjectTypeLiteral", + "line": 51, + "column": 47, + "endLine": 51, + "endColumn": 50, + "problem": "AnyType", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, { - "line": 56, - "column": 3, - "endLine": 56, - "endColumn": 4, - "problem": "LiteralAsPropertyName", + "line": 51, + "column": 53, + "endLine": 51, + "endColumn": 64, + "problem": "IsOperator", "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "rule": "Type guarding is supported with \"instanceof\" and \"as\" (arkts-no-is)", "severity": "ERROR" }, { - "line": 57, - "column": 3, - "endLine": 57, - "endColumn": 6, + "line": 65, + "column": 5, + "endLine": 65, + "endColumn": 8, "problem": "ComputedPropertyName", "suggest": "", "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, { - "line": 58, - "column": 3, - "endLine": 58, - "endColumn": 6, + "line": 66, + "column": 5, + "endLine": 66, + "endColumn": 8, "problem": "ComputedPropertyName", "suggest": "", "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, { - "line": 62, - "column": 3, - "endLine": 62, - "endColumn": 4, - "problem": "LiteralAsPropertyName", - "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", - "severity": "ERROR" - }, - { - "line": 67, - "column": 3, - "endLine": 67, - "endColumn": 4, - "problem": "LiteralAsPropertyName", - "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", - "severity": "ERROR" - }, - { - "line": 71, - "column": 19, - "endLine": 71, - "endColumn": 20, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 72, - "column": 3, - "endLine": 72, - "endColumn": 26, + "line": 80, + "column": 5, + "endLine": 80, + "endColumn": 28, "problem": "IndexMember", "suggest": "", "rule": "Indexed signatures are not supported (arkts-no-indexed-signatures)", "severity": "ERROR" }, { - "line": 72, - "column": 18, - "endLine": 72, - "endColumn": 25, + "line": 80, + "column": 20, + "endLine": 80, + "endColumn": 27, "problem": "UnknownType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, { - "line": 76, + "line": 84, "column": 32, - "endLine": 76, + "endLine": 84, "endColumn": 35, "problem": "AnyType", "suggest": "", @@ -225,9 +165,9 @@ "severity": "ERROR" }, { - "line": 77, + "line": 85, "column": 11, - "endLine": 77, + "endLine": 85, "endColumn": 13, "problem": "InOperator", "suggest": "", @@ -235,9 +175,9 @@ "severity": "ERROR" }, { - "line": 78, + "line": 86, "column": 5, - "endLine": 78, + "endLine": 86, "endColumn": 14, "problem": "PropertyAccessByIndex", "suggest": "", @@ -245,9 +185,9 @@ "severity": "ERROR" }, { - "line": 92, + "line": 100, "column": 22, - "endLine": 92, + "endLine": 100, "endColumn": 29, "problem": "IntersectionType", "suggest": "", @@ -255,129 +195,39 @@ "severity": "ERROR" }, { - "line": 94, - "column": 28, - "endLine": 94, - "endColumn": 29, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 96, - "column": 3, - "endLine": 96, - "endColumn": 30, + "line": 104, + "column": 5, + "endLine": 104, + "endColumn": 32, "problem": "CallSignature", "suggest": "", "rule": "Use \"class\" instead of a type with call signature (arkts-no-call-signatures)", "severity": "ERROR" }, { - "line": 111, - "column": 19, - "endLine": 111, - "endColumn": 20, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 112, - "column": 12, - "endLine": 112, - "endColumn": 13, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 112, - "column": 35, - "endLine": 112, - "endColumn": 36, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 116, + "line": 139, "column": 9, - "endLine": 116, - "endColumn": 10, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 116, - "column": 25, - "endLine": 116, - "endColumn": 26, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 119, - "column": 9, - "endLine": 119, - "endColumn": 21, + "endLine": 139, + "endColumn": 23, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, { - "line": 119, - "column": 15, - "endLine": 119, - "endColumn": 21, - "problem": "TypeAssertion", - "suggest": "", - "rule": "Only \"as T\" syntax is supported for type casts (arkts-as-casts)", - "severity": "ERROR" - }, - { - "line": 119, - "column": 16, - "endLine": 119, - "endColumn": 19, + "line": 139, + "column": 20, + "endLine": 139, + "endColumn": 23, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, { - "line": 120, - "column": 20, - "endLine": 120, - "endColumn": 77, - "problem": "TypeAssertion", - "suggest": "", - "rule": "Only \"as T\" syntax is supported for type casts (arkts-as-casts)", - "severity": "ERROR" - }, - { - "line": 124, - "column": 13, - "endLine": 124, - "endColumn": 14, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 125, + "line": 149, "column": 3, - "endLine": 125, + "endLine": 149, "endColumn": 9, "problem": "PropertyAccessByIndex", "suggest": "", @@ -385,9 +235,9 @@ "severity": "ERROR" }, { - "line": 126, + "line": 150, "column": 15, - "endLine": 126, + "endLine": 150, "endColumn": 21, "problem": "PropertyAccessByIndex", "suggest": "", @@ -395,9 +245,9 @@ "severity": "ERROR" }, { - "line": 128, + "line": 152, "column": 12, - "endLine": 128, + "endLine": 152, "endColumn": 15, "problem": "AnyType", "suggest": "", @@ -405,19 +255,9 @@ "severity": "ERROR" }, { - "line": 138, - "column": 3, - "endLine": 138, - "endColumn": 11, - "problem": "LocalFunction", - "suggest": "", - "rule": "Nested functions are not supported (arkts-no-nested-funcs)", - "severity": "ERROR" - }, - { - "line": 157, + "line": 181, "column": 5, - "endLine": 157, + "endLine": 181, "endColumn": 23, "problem": "AnyType", "suggest": "", @@ -425,9 +265,19 @@ "severity": "ERROR" }, { - "line": 106, + "line": 70, "column": 3, - "endLine": 106, + "endLine": 70, + "endColumn": 6, + "problem": "StrictDiagnostic", + "suggest": "Property '__2' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property '__2' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 114, + "column": 3, + "endLine": 114, "endColumn": 6, "problem": "StrictDiagnostic", "suggest": "Property 'val' has no initializer and is not definitely assigned in the constructor.", @@ -435,9 +285,9 @@ "severity": "ERROR" }, { - "line": 148, + "line": 172, "column": 3, - "endLine": 148, + "endLine": 172, "endColumn": 4, "problem": "StrictDiagnostic", "suggest": "Type 'undefined' is not assignable to type 'string'.", @@ -445,9 +295,9 @@ "severity": "ERROR" }, { - "line": 149, + "line": 173, "column": 18, - "endLine": 149, + "endLine": 173, "endColumn": 27, "problem": "StrictDiagnostic", "suggest": "Argument of type 'undefined' is not assignable to parameter of type 'string'.", @@ -455,9 +305,9 @@ "severity": "ERROR" }, { - "line": 150, + "line": 174, "column": 17, - "endLine": 150, + "endLine": 174, "endColumn": 26, "problem": "StrictDiagnostic", "suggest": "Argument of type 'undefined' is not assignable to parameter of type 'number'.", diff --git a/ets2panda/linter/test/main/void_operator.ets.args.json b/ets2panda/linter/test/main/void_operator.ets.args.json index aaabef1e0a..8186a08902 100644 --- a/ets2panda/linter/test/main/void_operator.ets.args.json +++ b/ets2panda/linter/test/main/void_operator.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } diff --git a/ets2panda/linter/test/main/void_operator.ets.migrate.ets b/ets2panda/linter/test/main/void_operator.ets.migrate.ets new file mode 100644 index 0000000000..2a81c570d5 --- /dev/null +++ b/ets2panda/linter/test/main/void_operator.ets.migrate.ets @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +(() => { + 0; + return undefined; +})(); + +(() => { + 'hello'; + return undefined; +})(); + +(() => { + (1 + 2); + return undefined; +})(); + +interface GeneratedObjectLiteralInterface_1 { + a: number; + b: number; +} +(() => { + ({ a: 1, b: 2 } as GeneratedObjectLiteralInterface_1); + return undefined; +})(); + +(() => { + [1, 2, 3]; + return undefined; +})(); + +(() => { + console.log('expression evaluated'); + return undefined; +})(); + +const undefined_value = (() => { + 1; + return undefined; +})(); + +const undefined_value2: undefined = (() => { + 2; + return undefined; +})(); + +const undefined_value3: number | undefined = (() => { + 3; + return undefined; +})(); + +(() => { + (() => { + 1; + return undefined; +})(); + return undefined; +})(); + +(() => { + (() => { + console.log('foo'); +}); + return undefined; +})(); + +(() => { + (() => { + console.log("bar!"); +})(); + return undefined; +})(); + +(() => { + (() => { + console.log('baz!'); +})(); + return undefined; +})(); + +(() => { + (class { + }); + return undefined; +})(); + +(() => { + (class { + }); + return undefined; +})(); + +(() => { + (() => { }); + return undefined; +})(); + +function foo() { + let a: number = 1; + (() => { + a++; + return undefined; +})(); + + let b: number[] = [1, 2, 3]; + (() => { + console.log(b.filter(x => x % 2 !== 0)); + return undefined; +})(); + + (() => { + (() => { + console.log('foo'); +}); + return undefined; +})(); + + (() => { + (() => { + console.log('foo'); +}); + return undefined; +})(); + + (() => { + (class { + }); + return undefined; +})(); + + (() => { + (class localClass { + }); + return undefined; +})(); +} diff --git a/ets2panda/linter/test/main/void_operator.ets.migrate.json b/ets2panda/linter/test/main/void_operator.ets.migrate.json new file mode 100644 index 0000000000..12de68ea37 --- /dev/null +++ b/ets2panda/linter/test/main/void_operator.ets.migrate.json @@ -0,0 +1,58 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 95, + "column": 6, + "endLine": 95, + "endColumn": 11, + "problem": "ClassExpression", + "suggest": "", + "rule": "Class literals are not supported (arkts-no-class-literals)", + "severity": "ERROR" + }, + { + "line": 101, + "column": 6, + "endLine": 101, + "endColumn": 11, + "problem": "ClassExpression", + "suggest": "", + "rule": "Class literals are not supported (arkts-no-class-literals)", + "severity": "ERROR" + }, + { + "line": 139, + "column": 6, + "endLine": 139, + "endColumn": 11, + "problem": "ClassExpression", + "suggest": "", + "rule": "Class literals are not supported (arkts-no-class-literals)", + "severity": "ERROR" + }, + { + "line": 145, + "column": 6, + "endLine": 145, + "endColumn": 11, + "problem": "ClassExpression", + "suggest": "", + "rule": "Class literals are not supported (arkts-no-class-literals)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/worker_module.ets b/ets2panda/linter/test/main/worker_module.ets index 5eb608bafe..dc6f082a9f 100644 --- a/ets2panda/linter/test/main/worker_module.ets +++ b/ets2panda/linter/test/main/worker_module.ets @@ -13,12 +13,28 @@ * limitations under the License. */ -import { worker, MessageEvents } from '@kit.ArkTS'; +import { worker } from './oh_modules/@ohos.worker'; -import { process } from '@kit.ArkTS'; //legal +import { worker as workerAlias } from './oh_modules/@ohos.worker'; -import { worker as workerAlias } from '@ohos.worker'; - -import { worker as kitWorker } from '@kit.ArkTS'; +import { worker as kitWorker } from './oh_modules/@kit.ArkTS'; import { worker as definedWorker } from 'user_defined_worker'; //legal + +export { worker } from './oh_modules/@ohos.worker'; + +function testWorkerUsage() { + + const worker1: worker.ThreadWorker = new worker.ThreadWorker('script.js'); + + const worker2 = new workerAlias.ThreadWorker('script.js'); + + const worker3 = new kitWorker.ThreadWorker('script.js'); + + let worker4: workerAlias.ThreadWorker('script.js'); + + const worker5: workerAlias.ThreadWorker = new workerAlias.ThreadWorker('script.js'); + + let worker6: definedWorker.ThreadWorker('script.js'); // legal + +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/worker_module.ets.arkts2.json b/ets2panda/linter/test/main/worker_module.ets.arkts2.json index 9dea915ba6..535d022afd 100644 --- a/ets2panda/linter/test/main/worker_module.ets.arkts2.json +++ b/ets2panda/linter/test/main/worker_module.ets.arkts2.json @@ -16,32 +16,132 @@ "result": [ { "line": 16, - "column": 1, + "column": 10, "endLine": 16, - "endColumn": 52, - "problem": "LimitedStdLibApi", + "endColumn": 16, + "problem": "NoNeedStdlibWorker", "suggest": "", - "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", + "rule": "Worker are not supported(arkts-no-need-stdlib-worker)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 10, + "endLine": 18, + "endColumn": 16, + "problem": "NoNeedStdlibWorker", + "suggest": "", + "rule": "Worker are not supported(arkts-no-need-stdlib-worker)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 20, + "endLine": 18, + "endColumn": 31, + "problem": "NoNeedStdlibWorker", + "suggest": "", + "rule": "Worker are not supported(arkts-no-need-stdlib-worker)", "severity": "ERROR" }, { "line": 20, - "column": 1, + "column": 10, "endLine": 20, - "endColumn": 54, - "problem": "LimitedStdLibApi", + "endColumn": 16, + "problem": "NoNeedStdlibWorker", + "suggest": "", + "rule": "Worker are not supported(arkts-no-need-stdlib-worker)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 20, + "endLine": 20, + "endColumn": 29, + "problem": "NoNeedStdlibWorker", + "suggest": "", + "rule": "Worker are not supported(arkts-no-need-stdlib-worker)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 10, + "endLine": 24, + "endColumn": 16, + "problem": "NoNeedStdlibWorker", + "suggest": "", + "rule": "Worker are not supported(arkts-no-need-stdlib-worker)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 18, + "endLine": 28, + "endColumn": 24, + "problem": "NoNeedStdlibWorker", "suggest": "", - "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", + "rule": "Worker are not supported(arkts-no-need-stdlib-worker)", "severity": "ERROR" }, { - "line": 22, - "column": 1, - "endLine": 22, + "line": 28, + "column": 44, + "endLine": 28, "endColumn": 50, - "problem": "LimitedStdLibApi", + "problem": "NoNeedStdlibWorker", + "suggest": "", + "rule": "Worker are not supported(arkts-no-need-stdlib-worker)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 23, + "endLine": 30, + "endColumn": 34, + "problem": "NoNeedStdlibWorker", + "suggest": "", + "rule": "Worker are not supported(arkts-no-need-stdlib-worker)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 23, + "endLine": 32, + "endColumn": 32, + "problem": "NoNeedStdlibWorker", + "suggest": "", + "rule": "Worker are not supported(arkts-no-need-stdlib-worker)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 16, + "endLine": 34, + "endColumn": 27, + "problem": "NoNeedStdlibWorker", + "suggest": "", + "rule": "Worker are not supported(arkts-no-need-stdlib-worker)", + "severity": "ERROR" + }, + { + "line": 36, + "column": 18, + "endLine": 36, + "endColumn": 29, + "problem": "NoNeedStdlibWorker", + "suggest": "", + "rule": "Worker are not supported(arkts-no-need-stdlib-worker)", + "severity": "ERROR" + }, + { + "line": 36, + "column": 49, + "endLine": 36, + "endColumn": 60, + "problem": "NoNeedStdlibWorker", "suggest": "", - "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", + "rule": "Worker are not supported(arkts-no-need-stdlib-worker)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/migrate/class_static_block.ts.migrate.json b/ets2panda/linter/test/migrate/class_static_block.ts.migrate.json deleted file mode 100644 index ed0f91dab0..0000000000 --- a/ets2panda/linter/test/migrate/class_static_block.ts.migrate.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "result": [ - { - "line": 23, - "column": 3, - "endLine": 23, - "endColumn": 9, - "problem": "MultipleStaticBlocks", - "suggest": "", - "rule": "Only one static block is supported (arkts-no-multiple-static-blocks)", - "severity": "ERROR" - } - ] -} \ No newline at end of file diff --git a/ets2panda/linter/test/migrate/destructuring_assignments.ts.migrate.json b/ets2panda/linter/test/migrate/destructuring_assignments.ts.migrate.json deleted file mode 100644 index 05a9b858c9..0000000000 --- a/ets2panda/linter/test/migrate/destructuring_assignments.ts.migrate.json +++ /dev/null @@ -1,624 +0,0 @@ -{ - "result": [ - { - "line": 18, - "column": 5, - "endLine": 18, - "endColumn": 9, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 18, - "column": 11, - "endLine": 18, - "endColumn": 16, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 19, - "column": 2, - "endLine": 19, - "endColumn": 44, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 19, - "column": 16, - "endLine": 19, - "endColumn": 17, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 20, - "column": 2, - "endLine": 20, - "endColumn": 18, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 20, - "column": 16, - "endLine": 20, - "endColumn": 17, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 21, - "column": 2, - "endLine": 21, - "endColumn": 33, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 21, - "column": 7, - "endLine": 21, - "endColumn": 14, - "problem": "SpreadOperator", - "suggest": "", - "rule": "It is possible to spread only arrays or classes derived from arrays into the rest parameter or array literals (arkts-no-spread)", - "severity": "ERROR" - }, - { - "line": 22, - "column": 2, - "endLine": 22, - "endColumn": 56, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 22, - "column": 26, - "endLine": 22, - "endColumn": 27, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 22, - "column": 37, - "endLine": 22, - "endColumn": 38, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 23, - "column": 2, - "endLine": 23, - "endColumn": 56, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 23, - "column": 12, - "endLine": 23, - "endColumn": 19, - "problem": "SpreadOperator", - "suggest": "", - "rule": "It is possible to spread only arrays or classes derived from arrays into the rest parameter or array literals (arkts-no-spread)", - "severity": "ERROR" - }, - { - "line": 23, - "column": 26, - "endLine": 23, - "endColumn": 27, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 26, - "column": 10, - "endLine": 26, - "endColumn": 11, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 28, - "column": 2, - "endLine": 28, - "endColumn": 24, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 31, - "column": 1, - "endLine": 31, - "endColumn": 25, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 32, - "column": 1, - "endLine": 32, - "endColumn": 15, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 33, - "column": 1, - "endLine": 33, - "endColumn": 58, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 34, - "column": 1, - "endLine": 34, - "endColumn": 16, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 35, - "column": 1, - "endLine": 35, - "endColumn": 39, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 35, - "column": 8, - "endLine": 35, - "endColumn": 15, - "problem": "SpreadOperator", - "suggest": "", - "rule": "It is possible to spread only arrays or classes derived from arrays into the rest parameter or array literals (arkts-no-spread)", - "severity": "ERROR" - }, - { - "line": 36, - "column": 1, - "endLine": 36, - "endColumn": 42, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 37, - "column": 1, - "endLine": 37, - "endColumn": 46, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 37, - "column": 12, - "endLine": 37, - "endColumn": 19, - "problem": "SpreadOperator", - "suggest": "", - "rule": "It is possible to spread only arrays or classes derived from arrays into the rest parameter or array literals (arkts-no-spread)", - "severity": "ERROR" - }, - { - "line": 40, - "column": 1, - "endLine": 40, - "endColumn": 17, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 41, - "column": 1, - "endLine": 41, - "endColumn": 21, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 41, - "column": 5, - "endLine": 41, - "endColumn": 12, - "problem": "SpreadOperator", - "suggest": "", - "rule": "It is possible to spread only arrays or classes derived from arrays into the rest parameter or array literals (arkts-no-spread)", - "severity": "ERROR" - }, - { - "line": 44, - "column": 1, - "endLine": 44, - "endColumn": 20, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 47, - "column": 1, - "endLine": 47, - "endColumn": 16, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 50, - "column": 1, - "endLine": 50, - "endColumn": 23, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 53, - "column": 30, - "endLine": 53, - "endColumn": 31, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 53, - "column": 45, - "endLine": 53, - "endColumn": 46, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 54, - "column": 1, - "endLine": 54, - "endColumn": 51, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 54, - "column": 29, - "endLine": 54, - "endColumn": 50, - "problem": "ArrayLiteralNoContextType", - "suggest": "", - "rule": "Array literals must contain elements of only inferrable types (arkts-no-noninferrable-arr-literals)", - "severity": "ERROR" - }, - { - "line": 54, - "column": 30, - "endLine": 54, - "endColumn": 31, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 54, - "column": 41, - "endLine": 54, - "endColumn": 42, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 55, - "column": 1, - "endLine": 55, - "endColumn": 42, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 55, - "column": 18, - "endLine": 55, - "endColumn": 22, - "problem": "SpreadOperator", - "suggest": "", - "rule": "It is possible to spread only arrays or classes derived from arrays into the rest parameter or array literals (arkts-no-spread)", - "severity": "ERROR" - }, - { - "line": 56, - "column": 1, - "endLine": 56, - "endColumn": 38, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 56, - "column": 8, - "endLine": 56, - "endColumn": 19, - "problem": "SpreadOperator", - "suggest": "", - "rule": "It is possible to spread only arrays or classes derived from arrays into the rest parameter or array literals (arkts-no-spread)", - "severity": "ERROR" - }, - { - "line": 56, - "column": 23, - "endLine": 56, - "endColumn": 38, - "problem": "ArrayLiteralNoContextType", - "suggest": "", - "rule": "Array literals must contain elements of only inferrable types (arkts-no-noninferrable-arr-literals)", - "severity": "ERROR" - }, - { - "line": 56, - "column": 30, - "endLine": 56, - "endColumn": 31, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 58, - "column": 2, - "endLine": 58, - "endColumn": 41, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 58, - "column": 22, - "endLine": 58, - "endColumn": 23, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 59, - "column": 2, - "endLine": 65, - "endColumn": 44, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 65, - "column": 5, - "endLine": 65, - "endColumn": 6, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 65, - "column": 17, - "endLine": 65, - "endColumn": 18, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 68, - "column": 2, - "endLine": 68, - "endColumn": 48, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 68, - "column": 20, - "endLine": 68, - "endColumn": 21, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 69, - "column": 2, - "endLine": 69, - "endColumn": 60, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 69, - "column": 30, - "endLine": 69, - "endColumn": 31, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 69, - "column": 41, - "endLine": 69, - "endColumn": 42, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 70, - "column": 2, - "endLine": 70, - "endColumn": 45, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 70, - "column": 26, - "endLine": 70, - "endColumn": 27, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 71, - "column": 2, - "endLine": 77, - "endColumn": 44, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 77, - "column": 5, - "endLine": 77, - "endColumn": 6, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 77, - "column": 17, - "endLine": 77, - "endColumn": 18, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 87, - "column": 2, - "endLine": 87, - "endColumn": 23, - "problem": "DestructuringAssignment", - "suggest": "", - "rule": "Destructuring assignment is not supported (arkts-no-destruct-assignment)", - "severity": "ERROR" - }, - { - "line": 32, - "column": 2, - "endLine": 32, - "endColumn": 3, - "problem": "StrictDiagnostic", - "suggest": "Type 'undefined' is not assignable to type 'number'.", - "rule": "Type 'undefined' is not assignable to type 'number'.", - "severity": "ERROR" - }, - { - "line": 32, - "column": 5, - "endLine": 32, - "endColumn": 6, - "problem": "StrictDiagnostic", - "suggest": "Type 'undefined' is not assignable to type 'number'.", - "rule": "Type 'undefined' is not assignable to type 'number'.", - "severity": "ERROR" - }, - { - "line": 32, - "column": 8, - "endLine": 32, - "endColumn": 9, - "problem": "StrictDiagnostic", - "suggest": "Type 'undefined' is not assignable to type 'number'.", - "rule": "Type 'undefined' is not assignable to type 'number'.", - "severity": "ERROR" - } - ] -} \ No newline at end of file diff --git a/ets2panda/linter/test/migrate/destructuring_declarations.ts.migrate.json b/ets2panda/linter/test/migrate/destructuring_declarations.ts.migrate.json deleted file mode 100644 index 0729d4936c..0000000000 --- a/ets2panda/linter/test/migrate/destructuring_declarations.ts.migrate.json +++ /dev/null @@ -1,494 +0,0 @@ -{ - "result": [ - { - "line": 17, - "column": 5, - "endLine": 17, - "endColumn": 47, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 17, - "column": 19, - "endLine": 17, - "endColumn": 20, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 18, - "column": 5, - "endLine": 18, - "endColumn": 40, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 18, - "column": 24, - "endLine": 18, - "endColumn": 25, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 19, - "column": 5, - "endLine": 19, - "endColumn": 68, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 19, - "column": 34, - "endLine": 19, - "endColumn": 35, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 19, - "column": 47, - "endLine": 19, - "endColumn": 48, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 20, - "column": 5, - "endLine": 20, - "endColumn": 66, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 20, - "column": 32, - "endLine": 20, - "endColumn": 33, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 20, - "column": 45, - "endLine": 20, - "endColumn": 46, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 22, - "column": 5, - "endLine": 22, - "endColumn": 21, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 22, - "column": 19, - "endLine": 22, - "endColumn": 20, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 25, - "column": 10, - "endLine": 25, - "endColumn": 11, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 27, - "column": 5, - "endLine": 27, - "endColumn": 29, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 30, - "column": 7, - "endLine": 30, - "endColumn": 34, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 31, - "column": 7, - "endLine": 31, - "endColumn": 48, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 32, - "column": 7, - "endLine": 32, - "endColumn": 52, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 33, - "column": 7, - "endLine": 33, - "endColumn": 56, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 35, - "column": 7, - "endLine": 35, - "endColumn": 64, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 36, - "column": 7, - "endLine": 36, - "endColumn": 85, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 39, - "column": 5, - "endLine": 39, - "endColumn": 25, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 40, - "column": 5, - "endLine": 40, - "endColumn": 29, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 43, - "column": 5, - "endLine": 43, - "endColumn": 28, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 46, - "column": 5, - "endLine": 46, - "endColumn": 26, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 49, - "column": 5, - "endLine": 49, - "endColumn": 35, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 52, - "column": 5, - "endLine": 52, - "endColumn": 67, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 52, - "column": 41, - "endLine": 52, - "endColumn": 66, - "problem": "ArrayLiteralNoContextType", - "suggest": "", - "rule": "Array literals must contain elements of only inferrable types (arkts-no-noninferrable-arr-literals)", - "severity": "ERROR" - }, - { - "line": 52, - "column": 55, - "endLine": 52, - "endColumn": 56, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 53, - "column": 5, - "endLine": 53, - "endColumn": 60, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 53, - "column": 43, - "endLine": 53, - "endColumn": 60, - "problem": "ArrayLiteralNoContextType", - "suggest": "", - "rule": "Array literals must contain elements of only inferrable types (arkts-no-noninferrable-arr-literals)", - "severity": "ERROR" - }, - { - "line": 53, - "column": 50, - "endLine": 53, - "endColumn": 51, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 54, - "column": 7, - "endLine": 54, - "endColumn": 45, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 56, - "column": 5, - "endLine": 56, - "endColumn": 55, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 56, - "column": 32, - "endLine": 56, - "endColumn": 33, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 57, - "column": 5, - "endLine": 63, - "endColumn": 52, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 63, - "column": 5, - "endLine": 63, - "endColumn": 6, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 63, - "column": 21, - "endLine": 63, - "endColumn": 22, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 66, - "column": 5, - "endLine": 66, - "endColumn": 51, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 66, - "column": 23, - "endLine": 66, - "endColumn": 24, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 67, - "column": 5, - "endLine": 67, - "endColumn": 73, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 67, - "column": 39, - "endLine": 67, - "endColumn": 40, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 67, - "column": 52, - "endLine": 67, - "endColumn": 53, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 68, - "column": 5, - "endLine": 68, - "endColumn": 33, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 69, - "column": 5, - "endLine": 69, - "endColumn": 60, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 69, - "column": 37, - "endLine": 69, - "endColumn": 38, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 70, - "column": 5, - "endLine": 76, - "endColumn": 52, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - }, - { - "line": 76, - "column": 5, - "endLine": 76, - "endColumn": 6, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 76, - "column": 21, - "endLine": 76, - "endColumn": 22, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 85, - "column": 5, - "endLine": 85, - "endColumn": 26, - "problem": "DestructuringDeclaration", - "suggest": "", - "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", - "severity": "ERROR" - } - ] -} \ No newline at end of file diff --git a/ets2panda/linter/test/migrate/function_expression.ts.args.json b/ets2panda/linter/test/migrate/function_expression.ts.args.json deleted file mode 100644 index 66b623df60..0000000000 --- a/ets2panda/linter/test/migrate/function_expression.ts.args.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "mode": { - "migrate": "" - } -} diff --git a/ets2panda/linter/test/migrate/function_expression.ts.migrate.json b/ets2panda/linter/test/migrate/function_expression.ts.migrate.json deleted file mode 100644 index 7d294016f9..0000000000 --- a/ets2panda/linter/test/migrate/function_expression.ts.migrate.json +++ /dev/null @@ -1,334 +0,0 @@ -{ - "result": [ - { - "line": 16, - "column": 15, - "endLine": 16, - "endColumn": 29, - "problem": "FunctionExpression", - "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", - "severity": "ERROR" - }, - { - "line": 18, - "column": 18, - "endLine": 20, - "endColumn": 2, - "problem": "FunctionExpression", - "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", - "severity": "ERROR" - }, - { - "line": 18, - "column": 39, - "endLine": 18, - "endColumn": 40, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 23, - "column": 10, - "endLine": 25, - "endColumn": 4, - "problem": "FunctionExpression", - "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", - "severity": "ERROR" - }, - { - "line": 28, - "column": 17, - "endLine": 30, - "endColumn": 2, - "problem": "FunctionExpression", - "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", - "severity": "ERROR" - }, - { - "line": 32, - "column": 2, - "endLine": 34, - "endColumn": 2, - "problem": "FunctionExpression", - "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", - "severity": "ERROR" - }, - { - "line": 36, - "column": 7, - "endLine": 38, - "endColumn": 2, - "problem": "FunctionExpression", - "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", - "severity": "ERROR" - }, - { - "line": 41, - "column": 26, - "endLine": 43, - "endColumn": 2, - "problem": "FunctionExpression", - "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", - "severity": "ERROR" - }, - { - "line": 44, - "column": 27, - "endLine": 46, - "endColumn": 2, - "problem": "FunctionExpression", - "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", - "severity": "ERROR" - }, - { - "line": 48, - "column": 22, - "endLine": 50, - "endColumn": 2, - "problem": "FunctionExpression", - "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", - "severity": "ERROR" - }, - { - "line": 48, - "column": 22, - "endLine": 50, - "endColumn": 2, - "problem": "LimitedReturnTypeInference", - "suggest": "", - "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", - "severity": "ERROR" - }, - { - "line": 48, - "column": 35, - "endLine": 48, - "endColumn": 38, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 52, - "column": 19, - "endLine": 54, - "endColumn": 2, - "problem": "FunctionExpression", - "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", - "severity": "ERROR" - }, - { - "line": 52, - "column": 19, - "endLine": 54, - "endColumn": 2, - "problem": "GeneratorFunction", - "suggest": "", - "rule": "Generator functions are not supported (arkts-no-generators)", - "severity": "ERROR" - }, - { - "line": 53, - "column": 3, - "endLine": 53, - "endColumn": 10, - "problem": "YieldExpression", - "suggest": "", - "rule": "Generator functions are not supported (arkts-no-generators)", - "severity": "ERROR" - }, - { - "line": 56, - "column": 17, - "endLine": 58, - "endColumn": 2, - "problem": "FunctionExpression", - "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", - "severity": "ERROR" - }, - { - "line": 60, - "column": 18, - "endLine": 62, - "endColumn": 2, - "problem": "FunctionExpression", - "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", - "severity": "ERROR" - }, - { - "line": 64, - "column": 19, - "endLine": 66, - "endColumn": 2, - "problem": "FunctionExpression", - "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", - "severity": "ERROR" - }, - { - "line": 71, - "column": 25, - "endLine": 76, - "endColumn": 2, - "problem": "FunctionExpression", - "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", - "severity": "ERROR" - }, - { - "line": 78, - "column": 12, - "endLine": 80, - "endColumn": 2, - "problem": "FunctionExpression", - "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", - "severity": "ERROR" - }, - { - "line": 82, - "column": 5, - "endLine": 84, - "endColumn": 5, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 82, - "column": 19, - "endLine": 84, - "endColumn": 5, - "problem": "PropertyAccessByIndex", - "suggest": "", - "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", - "severity": "ERROR" - }, - { - "line": 82, - "column": 19, - "endLine": 84, - "endColumn": 2, - "problem": "FunctionExpression", - "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", - "severity": "ERROR" - }, - { - "line": 86, - "column": 6, - "endLine": 88, - "endColumn": 2, - "problem": "FunctionExpression", - "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", - "severity": "ERROR" - }, - { - "line": 91, - "column": 9, - "endLine": 93, - "endColumn": 4, - "problem": "FunctionExpression", - "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", - "severity": "ERROR" - }, - { - "line": 96, - "column": 25, - "endLine": 98, - "endColumn": 2, - "problem": "FunctionExpression", - "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", - "severity": "ERROR" - }, - { - "line": 102, - "column": 9, - "endLine": 104, - "endColumn": 17, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 104, - "column": 7, - "endLine": 104, - "endColumn": 17, - "problem": "FunctionBind", - "suggest": "", - "rule": "'Function.bind' is not supported (arkts-no-func-bind)", - "severity": "WARNING" - }, - { - "line": 102, - "column": 15, - "endLine": 104, - "endColumn": 6, - "problem": "FunctionExpression", - "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", - "severity": "ERROR" - }, - { - "line": 108, - "column": 16, - "endLine": 108, - "endColumn": 55, - "problem": "FunctionExpression", - "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", - "severity": "ERROR" - }, - { - "line": 109, - "column": 24, - "endLine": 109, - "endColumn": 75, - "problem": "FunctionExpression", - "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", - "severity": "ERROR" - }, - { - "line": 112, - "column": 5, - "endLine": 112, - "endColumn": 45, - "problem": "FunctionExpression", - "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", - "severity": "ERROR" - }, - { - "line": 113, - "column": 10, - "endLine": 113, - "endColumn": 50, - "problem": "FunctionExpression", - "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", - "severity": "ERROR" - } - ] -} \ No newline at end of file diff --git a/ets2panda/linter/test/migrate/literals_as_prop_names.ts.args.json b/ets2panda/linter/test/migrate/literals_as_prop_names.ts.args.json deleted file mode 100644 index 66b623df60..0000000000 --- a/ets2panda/linter/test/migrate/literals_as_prop_names.ts.args.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "mode": { - "migrate": "" - } -} diff --git a/ets2panda/linter/test/migrate/object_literals_autofixes.ts.args.json b/ets2panda/linter/test/migrate/object_literals_autofixes.ts.args.json deleted file mode 100644 index 66b623df60..0000000000 --- a/ets2panda/linter/test/migrate/object_literals_autofixes.ts.args.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "mode": { - "migrate": "" - } -} diff --git a/ets2panda/linter/test/migrate/parameter_properties.ts.args.json b/ets2panda/linter/test/migrate/parameter_properties.ts.args.json deleted file mode 100644 index 66b623df60..0000000000 --- a/ets2panda/linter/test/migrate/parameter_properties.ts.args.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "mode": { - "migrate": "" - } -} diff --git a/ets2panda/linter/test/migrate/parameter_properties.ts.migrate.json b/ets2panda/linter/test/migrate/parameter_properties.ts.migrate.json deleted file mode 100644 index ea6dab7c47..0000000000 --- a/ets2panda/linter/test/migrate/parameter_properties.ts.migrate.json +++ /dev/null @@ -1,104 +0,0 @@ -{ - "result": [ - { - "line": 18, - "column": 5, - "endLine": 18, - "endColumn": 11, - "problem": "ParameterProperties", - "suggest": "", - "rule": "Declaring fields in \"constructor\" is not supported (arkts-no-ctor-prop-decls)", - "severity": "ERROR" - }, - { - "line": 19, - "column": 5, - "endLine": 19, - "endColumn": 14, - "problem": "ParameterProperties", - "suggest": "", - "rule": "Declaring fields in \"constructor\" is not supported (arkts-no-ctor-prop-decls)", - "severity": "ERROR" - }, - { - "line": 20, - "column": 5, - "endLine": 20, - "endColumn": 12, - "problem": "ParameterProperties", - "suggest": "", - "rule": "Declaring fields in \"constructor\" is not supported (arkts-no-ctor-prop-decls)", - "severity": "ERROR" - }, - { - "line": 34, - "column": 26, - "endLine": 34, - "endColumn": 32, - "problem": "ParameterProperties", - "suggest": "", - "rule": "Declaring fields in \"constructor\" is not supported (arkts-no-ctor-prop-decls)", - "severity": "ERROR" - }, - { - "line": 34, - "column": 60, - "endLine": 34, - "endColumn": 67, - "problem": "ParameterProperties", - "suggest": "", - "rule": "Declaring fields in \"constructor\" is not supported (arkts-no-ctor-prop-decls)", - "severity": "ERROR" - }, - { - "line": 43, - "column": 15, - "endLine": 43, - "endColumn": 21, - "problem": "ParameterProperties", - "suggest": "", - "rule": "Declaring fields in \"constructor\" is not supported (arkts-no-ctor-prop-decls)", - "severity": "ERROR" - }, - { - "line": 43, - "column": 25, - "endLine": 43, - "endColumn": 28, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 47, - "column": 15, - "endLine": 47, - "endColumn": 21, - "problem": "ParameterProperties", - "suggest": "", - "rule": "Declaring fields in \"constructor\" is not supported (arkts-no-ctor-prop-decls)", - "severity": "ERROR" - }, - { - "line": 47, - "column": 33, - "endLine": 47, - "endColumn": 40, - "problem": "ParameterProperties", - "suggest": "", - "rule": "Declaring fields in \"constructor\" is not supported (arkts-no-ctor-prop-decls)", - "severity": "ERROR" - }, - { - "line": 47, - "column": 44, - "endLine": 47, - "endColumn": 45, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - } - ] -} \ No newline at end of file diff --git a/ets2panda/linter/test/migrate/type_literals.ts.args.json b/ets2panda/linter/test/migrate/type_literals.ts.args.json deleted file mode 100644 index 66b623df60..0000000000 --- a/ets2panda/linter/test/migrate/type_literals.ts.args.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "mode": { - "migrate": "" - } -} diff --git a/ets2panda/linter/test/migrate/type_literals.ts.migrate.json b/ets2panda/linter/test/migrate/type_literals.ts.migrate.json deleted file mode 100644 index bae2bb2104..0000000000 --- a/ets2panda/linter/test/migrate/type_literals.ts.migrate.json +++ /dev/null @@ -1,644 +0,0 @@ -{ - "result": [ - { - "line": 16, - "column": 14, - "endLine": 16, - "endColumn": 15, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 17, - "column": 14, - "endLine": 17, - "endColumn": 15, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 18, - "column": 14, - "endLine": 18, - "endColumn": 15, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 19, - "column": 22, - "endLine": 19, - "endColumn": 23, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 19, - "column": 47, - "endLine": 19, - "endColumn": 48, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 20, - "column": 20, - "endLine": 20, - "endColumn": 21, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 21, - "column": 14, - "endLine": 21, - "endColumn": 15, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 24, - "column": 6, - "endLine": 24, - "endColumn": 7, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 30, - "column": 21, - "endLine": 30, - "endColumn": 22, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 32, - "column": 11, - "endLine": 32, - "endColumn": 12, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 32, - "column": 16, - "endLine": 32, - "endColumn": 17, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 33, - "column": 11, - "endLine": 33, - "endColumn": 12, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 33, - "column": 36, - "endLine": 33, - "endColumn": 37, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 34, - "column": 11, - "endLine": 34, - "endColumn": 12, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 35, - "column": 19, - "endLine": 35, - "endColumn": 20, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 35, - "column": 44, - "endLine": 35, - "endColumn": 45, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 36, - "column": 20, - "endLine": 36, - "endColumn": 21, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 37, - "column": 11, - "endLine": 37, - "endColumn": 12, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 40, - "column": 6, - "endLine": 40, - "endColumn": 7, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 45, - "column": 5, - "endLine": 45, - "endColumn": 6, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 48, - "column": 6, - "endLine": 48, - "endColumn": 7, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 51, - "column": 8, - "endLine": 51, - "endColumn": 9, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 58, - "column": 15, - "endLine": 58, - "endColumn": 16, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 58, - "column": 40, - "endLine": 58, - "endColumn": 41, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 59, - "column": 10, - "endLine": 59, - "endColumn": 11, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 63, - "column": 6, - "endLine": 63, - "endColumn": 7, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 63, - "column": 31, - "endLine": 63, - "endColumn": 32, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 65, - "column": 8, - "endLine": 65, - "endColumn": 9, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 65, - "column": 33, - "endLine": 65, - "endColumn": 34, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 66, - "column": 12, - "endLine": 66, - "endColumn": 13, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 72, - "column": 22, - "endLine": 72, - "endColumn": 23, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 73, - "column": 14, - "endLine": 73, - "endColumn": 15, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 73, - "column": 38, - "endLine": 73, - "endColumn": 39, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 75, - "column": 16, - "endLine": 75, - "endColumn": 17, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 80, - "column": 3, - "endLine": 80, - "endColumn": 4, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 80, - "column": 19, - "endLine": 80, - "endColumn": 20, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 82, - "column": 20, - "endLine": 82, - "endColumn": 21, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 85, - "column": 3, - "endLine": 85, - "endColumn": 4, - "problem": "LiteralAsPropertyName", - "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", - "severity": "ERROR" - }, - { - "line": 93, - "column": 3, - "endLine": 93, - "endColumn": 23, - "problem": "CallSignature", - "suggest": "", - "rule": "Use \"class\" instead of a type with call signature (arkts-no-call-signatures)", - "severity": "ERROR" - }, - { - "line": 94, - "column": 3, - "endLine": 94, - "endColumn": 22, - "problem": "ConstructorType", - "suggest": "", - "rule": "Use \"class\" instead of a type with constructor signature (arkts-no-ctor-signatures-type)", - "severity": "ERROR" - }, - { - "line": 95, - "column": 3, - "endLine": 95, - "endColumn": 26, - "problem": "IndexMember", - "suggest": "", - "rule": "Indexed signatures are not supported (arkts-no-indexed-signatures)", - "severity": "ERROR" - }, - { - "line": 95, - "column": 18, - "endLine": 95, - "endColumn": 25, - "problem": "UnknownType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 98, - "column": 18, - "endLine": 98, - "endColumn": 19, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 101, - "column": 3, - "endLine": 101, - "endColumn": 4, - "problem": "LiteralAsPropertyName", - "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", - "severity": "ERROR" - }, - { - "line": 109, - "column": 3, - "endLine": 109, - "endColumn": 23, - "problem": "CallSignature", - "suggest": "", - "rule": "Use \"class\" instead of a type with call signature (arkts-no-call-signatures)", - "severity": "ERROR" - }, - { - "line": 110, - "column": 3, - "endLine": 110, - "endColumn": 22, - "problem": "ConstructorType", - "suggest": "", - "rule": "Use \"class\" instead of a type with constructor signature (arkts-no-ctor-signatures-type)", - "severity": "ERROR" - }, - { - "line": 111, - "column": 3, - "endLine": 111, - "endColumn": 26, - "problem": "IndexMember", - "suggest": "", - "rule": "Indexed signatures are not supported (arkts-no-indexed-signatures)", - "severity": "ERROR" - }, - { - "line": 111, - "column": 18, - "endLine": 111, - "endColumn": 25, - "problem": "UnknownType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 115, - "column": 49, - "endLine": 115, - "endColumn": 50, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 116, - "column": 11, - "endLine": 116, - "endColumn": 12, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 118, - "column": 20, - "endLine": 118, - "endColumn": 21, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 119, - "column": 11, - "endLine": 119, - "endColumn": 12, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 119, - "column": 30, - "endLine": 119, - "endColumn": 31, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 119, - "column": 34, - "endLine": 119, - "endColumn": 35, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 121, - "column": 25, - "endLine": 121, - "endColumn": 26, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 124, - "column": 11, - "endLine": 124, - "endColumn": 12, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 124, - "column": 12, - "endLine": 124, - "endColumn": 17, - "problem": "ComputedPropertyName", - "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", - "severity": "ERROR" - }, - { - "line": 127, - "column": 11, - "endLine": 127, - "endColumn": 12, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 127, - "column": 31, - "endLine": 127, - "endColumn": 32, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 129, - "column": 11, - "endLine": 129, - "endColumn": 12, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 129, - "column": 17, - "endLine": 129, - "endColumn": 23, - "problem": "TypeQuery", - "suggest": "", - "rule": "\"typeof\" operator is allowed only in expression contexts (arkts-no-type-query)", - "severity": "ERROR" - }, - { - "line": 131, - "column": 11, - "endLine": 131, - "endColumn": 12, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 131, - "column": 17, - "endLine": 131, - "endColumn": 23, - "problem": "TypeQuery", - "suggest": "", - "rule": "\"typeof\" operator is allowed only in expression contexts (arkts-no-type-query)", - "severity": "ERROR" - }, - { - "line": 133, - "column": 10, - "endLine": 133, - "endColumn": 11, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - } - ] -} \ No newline at end of file diff --git a/ets2panda/linter/test/migrate/types.ts.args.json b/ets2panda/linter/test/migrate/types.ts.args.json deleted file mode 100644 index 66b623df60..0000000000 --- a/ets2panda/linter/test/migrate/types.ts.args.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "mode": { - "migrate": "" - } -} diff --git a/ets2panda/linter/test/migrate/void_operator.ts.migrate.json b/ets2panda/linter/test/migrate/void_operator.ts.migrate.json deleted file mode 100644 index e1644e2d8d..0000000000 --- a/ets2panda/linter/test/migrate/void_operator.ts.migrate.json +++ /dev/null @@ -1,104 +0,0 @@ -{ - "result": [ - { - "line": 22, - "column": 6, - "endLine": 22, - "endColumn": 7, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", - "severity": "ERROR" - }, - { - "line": 36, - "column": 6, - "endLine": 38, - "endColumn": 2, - "problem": "FunctionExpression", - "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", - "severity": "ERROR" - }, - { - "line": 40, - "column": 6, - "endLine": 42, - "endColumn": 2, - "problem": "FunctionExpression", - "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", - "severity": "ERROR" - }, - { - "line": 44, - "column": 7, - "endLine": 46, - "endColumn": 2, - "problem": "FunctionExpression", - "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", - "severity": "ERROR" - }, - { - "line": 48, - "column": 6, - "endLine": 48, - "endColumn": 11, - "problem": "ClassExpression", - "suggest": "", - "rule": "Class literals are not supported (arkts-no-class-literals)", - "severity": "ERROR" - }, - { - "line": 50, - "column": 7, - "endLine": 50, - "endColumn": 12, - "problem": "ClassExpression", - "suggest": "", - "rule": "Class literals are not supported (arkts-no-class-literals)", - "severity": "ERROR" - }, - { - "line": 61, - "column": 8, - "endLine": 63, - "endColumn": 4, - "problem": "FunctionExpression", - "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", - "severity": "ERROR" - }, - { - "line": 65, - "column": 8, - "endLine": 67, - "endColumn": 4, - "problem": "FunctionExpression", - "suggest": "", - "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", - "severity": "ERROR" - }, - { - "line": 69, - "column": 8, - "endLine": 69, - "endColumn": 13, - "problem": "ClassExpression", - "suggest": "", - "rule": "Class literals are not supported (arkts-no-class-literals)", - "severity": "ERROR" - }, - { - "line": 71, - "column": 8, - "endLine": 71, - "endColumn": 13, - "problem": "ClassExpression", - "suggest": "", - "rule": "Class literals are not supported (arkts-no-class-literals)", - "severity": "ERROR" - } - ] -} \ No newline at end of file diff --git a/ets2panda/linter/test/migration/mixed_problems.ets b/ets2panda/linter/test/migration/mixed_problems.ets new file mode 100644 index 0000000000..617d37acf6 --- /dev/null +++ b/ets2panda/linter/test/migration/mixed_problems.ets @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// destructuring declaration + untyped object literal +let { a, b } = { a: 1, b: 2 }; + +// destructuring declaration + untyped object literal + type literal +let { a2, b2 } = { + a2: 1, + b2: { + c2: 1, + d2: '2' + } as { c2: number, d2: string } +}; + +// untyped object literal + 'in' operator +console.log('a' in { a: 1, b: 2 }); + +// untyped object literal + var declaration + literal as property name + function expression +var fun = function() { + var o = { + 'a': 1, + 'b': 2 + }; + + var o2 = { + 'c': 3, + 'd': 4, + 5: { + x1: 10, + x2: 20 + } + }; +}; + +// private identifier + definite assignment +class A { + #a!: number; +} + +// type assertion + as 'const' +const t = 'hello'; \ No newline at end of file diff --git a/ets2panda/linter/test/migration/mixed_problems.ets.args.json b/ets2panda/linter/test/migration/mixed_problems.ets.args.json new file mode 100644 index 0000000000..65eb728b5d --- /dev/null +++ b/ets2panda/linter/test/migration/mixed_problems.ets.args.json @@ -0,0 +1,20 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "autofix": "", + "migrate": "" + } +} diff --git a/ets2panda/linter/test/migration/mixed_problems.ets.autofix.json b/ets2panda/linter/test/migration/mixed_problems.ets.autofix.json new file mode 100644 index 0000000000..57f25df2f3 --- /dev/null +++ b/ets2panda/linter/test/migration/mixed_problems.ets.autofix.json @@ -0,0 +1,303 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 5, + "endLine": 17, + "endColumn": 30, + "problem": "DestructuringDeclaration", + "autofix": [ + { + "replacementText": "GeneratedDestructObj_1", + "start": 663, + "end": 671 + }, + { + "replacementText": "\nlet a = GeneratedDestructObj_1.a;\nlet b = GeneratedDestructObj_1.b;\n", + "start": 689, + "end": 689 + } + ], + "suggest": "", + "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 16, + "endLine": 17, + "endColumn": 17, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 5, + "endLine": 26, + "endColumn": 2, + "problem": "DestructuringDeclaration", + "autofix": [ + { + "replacementText": "GeneratedDestructObj_2", + "start": 764, + "end": 774 + }, + { + "replacementText": "\nlet a2 = GeneratedDestructObj_2.a2;\nlet b2 = GeneratedDestructObj_2.b2;\n", + "start": 869, + "end": 869 + } + ], + "suggest": "", + "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 18, + "endLine": 20, + "endColumn": 19, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 9, + "endLine": 22, + "endColumn": 10, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 10, + "endLine": 25, + "endColumn": 11, + "problem": "ObjectTypeLiteral", + "autofix": [ + { + "start": 760, + "end": 760, + "replacementText": "interface GeneratedTypeLiteralInterface_1 {\n c2: number;\n d2: string;\n}\n" + }, + { + "start": 840, + "end": 866, + "replacementText": "GeneratedTypeLiteralInterface_1" + } + ], + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 17, + "endLine": 29, + "endColumn": 19, + "problem": "InOperator", + "suggest": "", + "rule": "\"in\" operator is not supported (arkts-no-in)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 20, + "endLine": 29, + "endColumn": 21, + "problem": "ObjectLiteralNoContextType", + "autofix": [ + { + "start": 913, + "end": 913, + "replacementText": "interface GeneratedObjectLiteralInterface_1 {\n a: number;\n b: number;\n}\n" + }, + { + "start": 932, + "end": 946, + "replacementText": "({ a: 1, b: 2 } as GeneratedObjectLiteralInterface_1)" + } + ], + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 1, + "endLine": 32, + "endColumn": 4, + "problem": "VarDeclaration", + "autofix": [ + { + "start": 1043, + "end": 1238, + "replacementText": "let fun = function () {\n var o = {\n 'a': 1,\n 'b': 2\n };\n var o2 = {\n 'c': 3,\n 'd': 4,\n 5: {\n x1: 10,\n x2: 20\n }\n };\n}" + } + ], + "suggest": "", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 11, + "endLine": 46, + "endColumn": 2, + "problem": "FunctionExpression", + "autofix": [ + { + "start": 1053, + "end": 1238, + "replacementText": "() => {\n var o = {\n 'a': 1,\n 'b': 2\n };\n var o2 = {\n 'c': 3,\n 'd': 4,\n 5: {\n x1: 10,\n x2: 20\n }\n };\n}" + } + ], + "suggest": "", + "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 5, + "endLine": 33, + "endColumn": 8, + "problem": "VarDeclaration", + "autofix": [ + { + "start": 1071, + "end": 1117, + "replacementText": "let o = {\n 'a': 1,\n 'b': 2\n}" + } + ], + "suggest": "", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 13, + "endLine": 33, + "endColumn": 14, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 5, + "endLine": 38, + "endColumn": 8, + "problem": "VarDeclaration", + "autofix": [ + { + "start": 1124, + "end": 1235, + "replacementText": "let o2 = {\n 'c': 3,\n 'd': 4,\n 5: {\n x1: 10,\n x2: 20\n }\n}" + } + ], + "suggest": "", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 14, + "endLine": 38, + "endColumn": 15, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 9, + "endLine": 41, + "endColumn": 10, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 12, + "endLine": 41, + "endColumn": 13, + "problem": "ObjectLiteralNoContextType", + "autofix": [ + { + "start": 1043, + "end": 1043, + "replacementText": "interface GeneratedObjectLiteralInterface_2 {\n x1: number;\n x2: number;\n}\n" + }, + { + "start": 1178, + "end": 1228, + "replacementText": "({ x1: 10,\n x2: 20 } as GeneratedObjectLiteralInterface_2)" + } + ], + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 50, + "column": 5, + "endLine": 50, + "endColumn": 17, + "problem": "DefiniteAssignment", + "suggest": "", + "rule": "Definite assignment assertions are not supported (arkts-no-definite-assignment)", + "severity": "WARNING" + }, + { + "line": 50, + "column": 5, + "endLine": 50, + "endColumn": 7, + "problem": "PrivateIdentifier", + "autofix": [ + { + "start": 1299, + "end": 1311, + "replacementText": "private a!: number;" + } + ], + "suggest": "", + "rule": "Private \"#\" identifiers are not supported (arkts-no-private-identifiers)", + "severity": "ERROR" + }, + { + "line": 54, + "column": 27, + "endLine": 54, + "endColumn": 18, + "problem": "ConstAssertion", + "suggest": "", + "rule": "\"as const\" assertions are not supported (arkts-no-as-const)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/migration/mixed_problems.ets.json b/ets2panda/linter/test/migration/mixed_problems.ets.json new file mode 100644 index 0000000000..dbb09ef3dc --- /dev/null +++ b/ets2panda/linter/test/migration/mixed_problems.ets.json @@ -0,0 +1,208 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 5, + "endLine": 17, + "endColumn": 30, + "problem": "DestructuringDeclaration", + "suggest": "", + "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 16, + "endLine": 17, + "endColumn": 17, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 5, + "endLine": 26, + "endColumn": 2, + "problem": "DestructuringDeclaration", + "suggest": "", + "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 18, + "endLine": 20, + "endColumn": 19, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 9, + "endLine": 22, + "endColumn": 10, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 10, + "endLine": 25, + "endColumn": 11, + "problem": "ObjectTypeLiteral", + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 17, + "endLine": 29, + "endColumn": 19, + "problem": "InOperator", + "suggest": "", + "rule": "\"in\" operator is not supported (arkts-no-in)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 20, + "endLine": 29, + "endColumn": 21, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 1, + "endLine": 32, + "endColumn": 4, + "problem": "VarDeclaration", + "suggest": "", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 11, + "endLine": 46, + "endColumn": 2, + "problem": "FunctionExpression", + "suggest": "", + "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 5, + "endLine": 33, + "endColumn": 8, + "problem": "VarDeclaration", + "suggest": "", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 13, + "endLine": 33, + "endColumn": 14, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 5, + "endLine": 38, + "endColumn": 8, + "problem": "VarDeclaration", + "suggest": "", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 14, + "endLine": 38, + "endColumn": 15, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 9, + "endLine": 41, + "endColumn": 10, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 12, + "endLine": 41, + "endColumn": 13, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 50, + "column": 5, + "endLine": 50, + "endColumn": 17, + "problem": "DefiniteAssignment", + "suggest": "", + "rule": "Definite assignment assertions are not supported (arkts-no-definite-assignment)", + "severity": "WARNING" + }, + { + "line": 50, + "column": 5, + "endLine": 50, + "endColumn": 7, + "problem": "PrivateIdentifier", + "suggest": "", + "rule": "Private \"#\" identifiers are not supported (arkts-no-private-identifiers)", + "severity": "ERROR" + }, + { + "line": 54, + "column": 27, + "endLine": 54, + "endColumn": 18, + "problem": "ConstAssertion", + "suggest": "", + "rule": "\"as const\" assertions are not supported (arkts-no-as-const)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/migration/mixed_problems.ets.migrate.ets b/ets2panda/linter/test/migration/mixed_problems.ets.migrate.ets new file mode 100644 index 0000000000..1ffb82d2eb --- /dev/null +++ b/ets2panda/linter/test/migration/mixed_problems.ets.migrate.ets @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// destructuring declaration + untyped object literal +interface GeneratedObjectLiteralInterface_2 { + a: number; + b: number; +} +let GeneratedDestructObj_1: GeneratedObjectLiteralInterface_2 = { a: 1, b: 2 }; +let a = GeneratedDestructObj_1.a; +let b = GeneratedDestructObj_1.b; + + +// destructuring declaration + untyped object literal + type literal +interface GeneratedTypeLiteralInterface_1 { + c2: number; + d2: string; +} +interface GeneratedObjectLiteralInterface_3 { + a2: number; + b2: GeneratedTypeLiteralInterface_1; +} +let GeneratedDestructObj_2: GeneratedObjectLiteralInterface_3 = { + a2: 1, + b2: { + c2: 1, + d2: '2' + } as GeneratedTypeLiteralInterface_1 +}; +let a2 = GeneratedDestructObj_2.a2; +let b2 = GeneratedDestructObj_2.b2; + + +// untyped object literal + 'in' operator +interface GeneratedObjectLiteralInterface_1 { + a: number; + b: number; +} +console.log('a' in ({ a: 1, b: 2 } as GeneratedObjectLiteralInterface_1)); + +// untyped object literal + var declaration + literal as property name + function expression +interface GeneratedObjectLiteralInterface_4 { + x1: number; + x2: number; +} +let fun = () => { + let o = { + 'a': 1, + 'b': 2 +}; + let o2 = { + 'c': 3, + 'd': 4, + 5: ({ x1: 10, + x2: 20 } as GeneratedObjectLiteralInterface_4) +}; +}; + +// private identifier + definite assignment +class A { + private a!: number; +} + +// type assertion + as 'const' +const t = 'hello'; \ No newline at end of file diff --git a/ets2panda/linter/test/migration/mixed_problems.ets.migrate.json b/ets2panda/linter/test/migration/mixed_problems.ets.migrate.json new file mode 100644 index 0000000000..bfb7a82f08 --- /dev/null +++ b/ets2panda/linter/test/migration/mixed_problems.ets.migrate.json @@ -0,0 +1,78 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 51, + "column": 17, + "endLine": 51, + "endColumn": 19, + "problem": "InOperator", + "suggest": "", + "rule": "\"in\" operator is not supported (arkts-no-in)", + "severity": "ERROR" + }, + { + "line": 59, + "column": 13, + "endLine": 59, + "endColumn": 14, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 63, + "column": 14, + "endLine": 63, + "endColumn": 15, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 66, + "column": 5, + "endLine": 66, + "endColumn": 6, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 5, + "endLine": 73, + "endColumn": 24, + "problem": "DefiniteAssignment", + "suggest": "", + "rule": "Definite assignment assertions are not supported (arkts-no-definite-assignment)", + "severity": "WARNING" + }, + { + "line": 77, + "column": 27, + "endLine": 77, + "endColumn": 18, + "problem": "ConstAssertion", + "suggest": "", + "rule": "\"as const\" assertions are not supported (arkts-no-as-const)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/ohmurl/ohmurl_import.ets.args.json b/ets2panda/linter/test/ohmurl/ohmurl_import.ets.args.json index db044a3dff..a89d885810 100644 --- a/ets2panda/linter/test/ohmurl/ohmurl_import.ets.args.json +++ b/ets2panda/linter/test/ohmurl/ohmurl_import.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } diff --git a/ets2panda/linter/test/ohmurl/ohmurl_import.ets.migrate.ets b/ets2panda/linter/test/ohmurl/ohmurl_import.ets.migrate.ets new file mode 100644 index 0000000000..1d67bf9461 --- /dev/null +++ b/ets2panda/linter/test/ohmurl/ohmurl_import.ets.migrate.ets @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + import { MainPage } from 'library/src/main/ets/components/MainPage' // Should fail on ArkTS 1.2 + import { Something1 } from "library/src/main/ets/components/Something1" // Valid + import { Something2 } from 'entry/src/main/ets/components/Something2' // Should Fail + import { Valid } from "normal/path/to/import/MainPage" // Valid + import { RelativeImport } from "../components/MainPage" // Valid + import { Something } from 'entry/src/main/ets/pages/test1' //should fail + import { SomethingElse } from 'entry/src/main/ets/pages/testing'; //should fail + import { Test } from 'module/src/main/ets/random/test'; //should fail diff --git a/ets2panda/linter/test/ohmurl/ohmurl_import.ets.migrate.json b/ets2panda/linter/test/ohmurl/ohmurl_import.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/ohmurl/ohmurl_import.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/rules/rule1.ets.args.json b/ets2panda/linter/test/rules/rule1.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/rules/rule1.ets.args.json +++ b/ets2panda/linter/test/rules/rule1.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/rules/rule1.ets.autofix.json b/ets2panda/linter/test/rules/rule1.ets.autofix.json index 7a9e068c21..4418693726 100644 --- a/ets2panda/linter/test/rules/rule1.ets.autofix.json +++ b/ets2panda/linter/test/rules/rule1.ets.autofix.json @@ -37,18 +37,6 @@ "endLine": 16, "endColumn": 10, "problem": "ObjectLiteralNoContextType", - "autofix": [ - { - "start": 610, - "end": 610, - "replacementText": "interface GeneratedObjectLiteralInterface_1 {\n \"name\": number;\n 2: number;\n}\n" - }, - { - "start": 615, - "end": 615, - "replacementText": ": GeneratedObjectLiteralInterface_1" - } - ], "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" @@ -93,12 +81,12 @@ { "start": 719, "end": 719, - "replacementText": "interface GeneratedObjectLiteralInterface_2 {\n name: number;\n}\n" + "replacementText": "interface GeneratedObjectLiteralInterface_1 {\n name: number;\n}\n" }, { "start": 724, "end": 724, - "replacementText": ": GeneratedObjectLiteralInterface_2" + "replacementText": ": GeneratedObjectLiteralInterface_1" } ], "suggest": "", diff --git a/ets2panda/linter/test/rules/rule1.ets.migrate.ets b/ets2panda/linter/test/rules/rule1.ets.migrate.ets new file mode 100644 index 0000000000..e78c2703ba --- /dev/null +++ b/ets2panda/linter/test/rules/rule1.ets.migrate.ets @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2023-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +let x = { "name": 1, 2: 3 } + +console.log(x["name"]) +console.log(x[2]) + +class X { + public name: number = 0 +} +interface GeneratedObjectLiteralInterface_1 { + name: number; +} +let y: GeneratedObjectLiteralInterface_1 = {name: 1} +console.log(x.name) + +let z = [1, 2, 3] +console.log(y[2]) + +enum S1 { + s1 = "qwqwq", +} + +enum S2 { + s2 = 123, +} + +interface A1 { + [S1.s1]: string; +} + +interface A2 { + [S2.s2]: string; +} + +const a1: A1 = { + [S1.s1]: "fld1", +}; + +const a2: A2 = { + [S2.s2]: "fld2", +}; + +S1["s1"]; +S2["s2"]; diff --git a/ets2panda/linter/test/rules/rule1.ets.migrate.json b/ets2panda/linter/test/rules/rule1.ets.migrate.json new file mode 100644 index 0000000000..a6b59e880c --- /dev/null +++ b/ets2panda/linter/test/rules/rule1.ets.migrate.json @@ -0,0 +1,88 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 9, + "endLine": 16, + "endColumn": 10, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 16, + "column": 22, + "endLine": 16, + "endColumn": 23, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 13, + "endLine": 18, + "endColumn": 22, + "problem": "PropertyAccessByIndex", + "suggest": "", + "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 13, + "endLine": 19, + "endColumn": 17, + "problem": "PropertyAccessByIndex", + "suggest": "", + "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 13, + "endLine": 31, + "endColumn": 17, + "problem": "PropertyAccessByIndex", + "suggest": "", + "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", + "severity": "ERROR" + }, + { + "line": 46, + "column": 3, + "endLine": 46, + "endColumn": 10, + "problem": "ComputedPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 54, + "column": 3, + "endLine": 54, + "endColumn": 10, + "problem": "ComputedPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/rules/rule113.ets.args.json b/ets2panda/linter/test/rules/rule113.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/rules/rule113.ets.args.json +++ b/ets2panda/linter/test/rules/rule113.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/rules/rule113.ets.migrate.ets b/ets2panda/linter/test/rules/rule113.ets.migrate.ets new file mode 100644 index 0000000000..67b6f18276 --- /dev/null +++ b/ets2panda/linter/test/rules/rule113.ets.migrate.ets @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2023-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +// fixable +enum Color { + RED, + GREEN, + YELLOW = 2, + BLACK = 3, + BLUE +} + + +// ------ + +// not fixable +enum C { + A = 1 +} + +const x = 6 +let y = C.A + +enum C{ + B = x +} +// ------ + +// not fixable +const d = 6 + +enum D { + A = 1 +} + +enum D{ + B = d +} +// ------ + +// fixable +enum Str { + A = 1, + B = "abc", + C = 2, + D, + E = "qwerty" +} + + +// ------ + +enum Empty { +} + + diff --git a/ets2panda/linter/test/rules/rule113.ets.migrate.json b/ets2panda/linter/test/rules/rule113.ets.migrate.json new file mode 100644 index 0000000000..93a274b257 --- /dev/null +++ b/ets2panda/linter/test/rules/rule113.ets.migrate.json @@ -0,0 +1,78 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 30, + "column": 1, + "endLine": 32, + "endColumn": 2, + "problem": "EnumMerging", + "suggest": "", + "rule": "\"enum\" declaration merging is not supported (arkts-no-enum-merging)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 1, + "endLine": 39, + "endColumn": 2, + "problem": "EnumMerging", + "suggest": "", + "rule": "\"enum\" declaration merging is not supported (arkts-no-enum-merging)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 1, + "endLine": 47, + "endColumn": 2, + "problem": "EnumMerging", + "suggest": "", + "rule": "\"enum\" declaration merging is not supported (arkts-no-enum-merging)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 1, + "endLine": 51, + "endColumn": 2, + "problem": "EnumMerging", + "suggest": "", + "rule": "\"enum\" declaration merging is not supported (arkts-no-enum-merging)", + "severity": "ERROR" + }, + { + "line": 57, + "column": 5, + "endLine": 57, + "endColumn": 14, + "problem": "EnumMemberNonConstInit", + "suggest": "", + "rule": "Enumeration members can be initialized only with compile time expressions of the same type (arkts-no-enum-mixed-types)", + "severity": "ERROR" + }, + { + "line": 60, + "column": 5, + "endLine": 60, + "endColumn": 17, + "problem": "EnumMemberNonConstInit", + "suggest": "", + "rule": "Enumeration members can be initialized only with compile time expressions of the same type (arkts-no-enum-mixed-types)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/rules/rule140.ets.args.json b/ets2panda/linter/test/rules/rule140.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/rules/rule140.ets.args.json +++ b/ets2panda/linter/test/rules/rule140.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/rules/rule140.ets.migrate.ets b/ets2panda/linter/test/rules/rule140.ets.migrate.ets new file mode 100644 index 0000000000..eee3cc75c5 --- /dev/null +++ b/ets2panda/linter/test/rules/rule140.ets.migrate.ets @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2023-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +const person = { + firstName: "aa", + fullName: function (): string { + return this.firstName + } +} +interface GeneratedObjectLiteralInterface_1 { + firstName: string; +} +const person1: GeneratedObjectLiteralInterface_1 = { + firstName: "Mary" +} +// This will log "Mary": +const boundFullName = person.fullName.bind(person1) +console.log(boundFullName()) \ No newline at end of file diff --git a/ets2panda/linter/test/rules/rule140.ets.migrate.json b/ets2panda/linter/test/rules/rule140.ets.migrate.json new file mode 100644 index 0000000000..c2f9a120a5 --- /dev/null +++ b/ets2panda/linter/test/rules/rule140.ets.migrate.json @@ -0,0 +1,68 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 16, + "column": 16, + "endLine": 16, + "endColumn": 17, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 15, + "endLine": 20, + "endColumn": 6, + "problem": "FunctionExpression", + "suggest": "", + "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 16, + "endLine": 19, + "endColumn": 20, + "problem": "FunctionContainsThis", + "suggest": "", + "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 7, + "endLine": 29, + "endColumn": 52, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 39, + "endLine": 29, + "endColumn": 52, + "problem": "FunctionBind", + "suggest": "", + "rule": "'Function.bind' is not supported (arkts-no-func-bind)", + "severity": "WARNING" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/rules/rule16.ets.args.json b/ets2panda/linter/test/rules/rule16.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/rules/rule16.ets.args.json +++ b/ets2panda/linter/test/rules/rule16.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/rules/rule16.ets.migrate.ets b/ets2panda/linter/test/rules/rule16.ets.migrate.ets new file mode 100644 index 0000000000..7b8bdd8a50 --- /dev/null +++ b/ets2panda/linter/test/rules/rule16.ets.migrate.ets @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2023-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class C { + static s: string + + static { + C.s = "aa"; + C.s = C.s + "bb"; +} + +} + +class D { + static s: string + + static { + D.s = "aa" + D.s = D.s + "bb" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/rules/rule16.ets.migrate.json b/ets2panda/linter/test/rules/rule16.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/rules/rule16.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/rules/rule25.ets.args.json b/ets2panda/linter/test/rules/rule25.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/rules/rule25.ets.args.json +++ b/ets2panda/linter/test/rules/rule25.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/rules/rule25.ets.migrate.ets b/ets2panda/linter/test/rules/rule25.ets.migrate.ets new file mode 100644 index 0000000000..51395c45d2 --- /dev/null +++ b/ets2panda/linter/test/rules/rule25.ets.migrate.ets @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class Person { + protected ssn: string; +private firstName: string; +private lastName: string; +constructor( + ssn: string, + firstName: string, + lastName: string + ) { + this.ssn = ssn; + this.firstName = firstName; + this.lastName = lastName; + this.ssn = ssn; + this.firstName = firstName; + this.lastName = lastName; +} + + getFullName(): string { + return this.firstName + " " + this.lastName + } +} + +class Person2{ + protected ssn: string + private firstName: string + private lastName: string + + constructor(ssn: string, firstName: string, lastName: string) { + this.ssn = ssn + this.firstName = firstName + this.lastName = lastName + } + + getFullName(): string { + return this.firstName + " " + this.lastName + } +} + +class A { + constructor(readonly a: A) { + this.a = a; + } +} + \ No newline at end of file diff --git a/ets2panda/linter/test/rules/rule25.ets.migrate.json b/ets2panda/linter/test/rules/rule25.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/rules/rule25.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/rules/rule29.ets.args.json b/ets2panda/linter/test/rules/rule29.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/rules/rule29.ets.args.json +++ b/ets2panda/linter/test/rules/rule29.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/rules/rule29.ets.migrate.ets b/ets2panda/linter/test/rules/rule29.ets.migrate.ets new file mode 100644 index 0000000000..284d21dac7 --- /dev/null +++ b/ets2panda/linter/test/rules/rule29.ets.migrate.ets @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class Point {x: number = 0; y: number = 0} +let p: Point = {x: 1, y: 2} +let x = p.x + +class Point2 {x: number = 0; y: number = 0} +let p2: Point2 = {x: 1, y: 2} +let x2 = p.x \ No newline at end of file diff --git a/ets2panda/linter/test/rules/rule29.ets.migrate.json b/ets2panda/linter/test/rules/rule29.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/rules/rule29.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/rules/rule3.ets.args.json b/ets2panda/linter/test/rules/rule3.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/rules/rule3.ets.args.json +++ b/ets2panda/linter/test/rules/rule3.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/rules/rule3.ets.migrate.ets b/ets2panda/linter/test/rules/rule3.ets.migrate.ets new file mode 100644 index 0000000000..d67266f181 --- /dev/null +++ b/ets2panda/linter/test/rules/rule3.ets.migrate.ets @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +class C { + private foo: number = 42; +} + +class X { + private foo: number = 42 +} + +class D { + private a: number = 1; + private b: number = 2; + + foo(): number { + return this.a + this.b + } + + bar(): number { + return this.a + this.b - this.a - this.b + } +} diff --git a/ets2panda/linter/test/rules/rule3.ets.migrate.json b/ets2panda/linter/test/rules/rule3.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/rules/rule3.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/rules/rule37.ets b/ets2panda/linter/test/rules/rule37.ets index 4839a90823..a1d8a329ac 100644 --- a/ets2panda/linter/test/rules/rule37.ets +++ b/ets2panda/linter/test/rules/rule37.ets @@ -64,4 +64,12 @@ let regex12: RegExp = RegExp("ab*c") - let regex13: RegExp = RegExp("ab*c","i") \ No newline at end of file + let regex13: RegExp = RegExp("ab*c","i") + + let a27: RegExp = RegExp('dawfgr'+'12345') + + let a25: RegExp = RegExp('.∗?(?:(?:元宵|三八|妇女|母亲|父亲|七夕|重阳|情人|儿童|六一'+'|愚人|复活|青年|护士|建军|教师|建党|万圣|感恩|秘书|七一|五四|八一|腊八|光棍|植树|中元)节|除夕|大年三十|大年30|七夕'+'|平安夜|六一|七一|五四|八一|三八|腊八|双十一|双十二).∗'); + + let regex20: RegExp = RegExp('dawfgr'.concat('12345')) + + let a28: RegExp = RegExp('dawfgr'+'12345' + '789') diff --git a/ets2panda/linter/test/rules/rule37.ets.args.json b/ets2panda/linter/test/rules/rule37.ets.args.json index 60cb1832f2..30973c00a2 100644 --- a/ets2panda/linter/test/rules/rule37.ets.args.json +++ b/ets2panda/linter/test/rules/rule37.ets.args.json @@ -15,6 +15,7 @@ ], "mode": { "arkts2": "", - "autofix": "--arkts-2" + "autofix": "--arkts-2", + "migrate": "--arkts-2" } } \ No newline at end of file diff --git a/ets2panda/linter/test/rules/rule37.ets.arkts2.json b/ets2panda/linter/test/rules/rule37.ets.arkts2.json index ffad898af9..e07b57d6df 100644 --- a/ets2panda/linter/test/rules/rule37.ets.arkts2.json +++ b/ets2panda/linter/test/rules/rule37.ets.arkts2.json @@ -143,6 +143,46 @@ "suggest": "", "rule": "RegExp literals are not supported (arkts-no-regexp-literals)", "severity": "ERROR" + }, + { + "line": 69, + "column": 20, + "endLine": 69, + "endColumn": 44, + "problem": "RegularExpressionLiteral", + "suggest": "", + "rule": "RegExp literals are not supported (arkts-no-regexp-literals)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 20, + "endLine": 71, + "endColumn": 176, + "problem": "RegularExpressionLiteral", + "suggest": "", + "rule": "RegExp literals are not supported (arkts-no-regexp-literals)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 24, + "endLine": 73, + "endColumn": 56, + "problem": "RegularExpressionLiteral", + "suggest": "", + "rule": "RegExp literals are not supported (arkts-no-regexp-literals)", + "severity": "ERROR" + }, + { + "line": 75, + "column": 21, + "endLine": 75, + "endColumn": 53, + "problem": "RegularExpressionLiteral", + "suggest": "", + "rule": "RegExp literals are not supported (arkts-no-regexp-literals)", + "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/rules/rule37.ets.autofix.json b/ets2panda/linter/test/rules/rule37.ets.autofix.json index bd396f0bda..3cad91ca09 100644 --- a/ets2panda/linter/test/rules/rule37.ets.autofix.json +++ b/ets2panda/linter/test/rules/rule37.ets.autofix.json @@ -234,6 +234,74 @@ "suggest": "", "rule": "RegExp literals are not supported (arkts-no-regexp-literals)", "severity": "ERROR" + }, + { + "line": 69, + "column": 20, + "endLine": 69, + "endColumn": 44, + "problem": "RegularExpressionLiteral", + "autofix": [ + { + "start": 1968, + "end": 1992, + "replacementText": "new RegExp('dawfgr' + '12345')" + } + ], + "suggest": "", + "rule": "RegExp literals are not supported (arkts-no-regexp-literals)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 20, + "endLine": 71, + "endColumn": 176, + "problem": "RegularExpressionLiteral", + "autofix": [ + { + "start": 2013, + "end": 2169, + "replacementText": "new RegExp('.∗?(?:(?:元宵|三八|妇女|母亲|父亲|七夕|重阳|情人|儿童|六一' + '|愚人|复活|青年|护士|建军|教师|建党|万圣|感恩|秘书|七一|五四|八一|腊八|光棍|植树|中元)节|除夕|大年三十|大年30|七夕' + '|平安夜|六一|七一|五四|八一|三八|腊八|双十一|双十二).∗')" + } + ], + "suggest": "", + "rule": "RegExp literals are not supported (arkts-no-regexp-literals)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 24, + "endLine": 73, + "endColumn": 56, + "problem": "RegularExpressionLiteral", + "autofix": [ + { + "start": 2195, + "end": 2227, + "replacementText": "new RegExp('dawfgr'.concat('12345'))" + } + ], + "suggest": "", + "rule": "RegExp literals are not supported (arkts-no-regexp-literals)", + "severity": "ERROR" + }, + { + "line": 75, + "column": 21, + "endLine": 75, + "endColumn": 53, + "problem": "RegularExpressionLiteral", + "autofix": [ + { + "start": 2250, + "end": 2282, + "replacementText": "new RegExp('dawfgr' + '12345' + '789')" + } + ], + "suggest": "", + "rule": "RegExp literals are not supported (arkts-no-regexp-literals)", + "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/rules/rule37.ets.migrate.ets b/ets2panda/linter/test/rules/rule37.ets.migrate.ets new file mode 100644 index 0000000000..6cd09a1b8b --- /dev/null +++ b/ets2panda/linter/test/rules/rule37.ets.migrate.ets @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2023-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + let regex: RegExp = new RegExp("bc*d"); + + let regex2: RegExp = new RegExp("bc*d"); + + const regex3 = new RegExp("^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*(\\.[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*)*$"); + const regex4: RegExp = new RegExp('^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*(\.[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*)*$'); + + let regex5: RegExp = new RegExp("bc*d", "ig"); + + let regex6: RegExp = new RegExp("bc*d", "ig"); + + let regex7: RegExp = new RegExp(new RegExp("bc*d", "i"), "g"); + + let regex8: RegExp = new RegExp(new RegExp("bc*d", "i"), "g"); + + let regex9: RegExp = new RegExp("a\\\\"); + + let regex10: RegExp = new RegExp("a\\\\"); + + class A { + static readonly classregex0: RegExp = new RegExp("bc*d") + + static readonly classregex2 = new RegExp("^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*(\\.[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*)*$"); + + classregex3: RegExp = new RegExp("bc*d"); + + static staticMethodOne() { + let regex = new RegExp("bc*d") + } + + static staticMethodTwo() { + let regex: RegExp = new RegExp("/bc*d/"); + } + + methodOne() { + let regex = new RegExp("bc*d") + } + + methodTwo() { + let regex: RegExp = new RegExp("/bc*d/"); + } + + methodRet(): RegExp { + return new RegExp("^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*(\\.[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*)*$"); + } + } + + const regexLambda = () => new RegExp("^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*(\\.[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*)*$"); + + let regex12: RegExp = new RegExp("ab*c") + + let regex13: RegExp = new RegExp("ab*c", "i") + + let a27: RegExp = new RegExp('dawfgr' + '12345') + + let a25: RegExp = new RegExp('.∗?(?:(?:元宵|三八|妇女|母亲|父亲|七夕|重阳|情人|儿童|六一' + '|愚人|复活|青年|护士|建军|教师|建党|万圣|感恩|秘书|七一|五四|八一|腊八|光棍|植树|中元)节|除夕|大年三十|大年30|七夕' + '|平安夜|六一|七一|五四|八一|三八|腊八|双十一|双十二).∗'); + + let regex20: RegExp = new RegExp('dawfgr'.concat('12345')) + + let a28: RegExp = new RegExp('dawfgr' + '12345' + '789') diff --git a/ets2panda/linter/test/rules/rule37.ets.migrate.json b/ets2panda/linter/test/rules/rule37.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/rules/rule37.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/rules/rule38.ets.args.json b/ets2panda/linter/test/rules/rule38.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/rules/rule38.ets.args.json +++ b/ets2panda/linter/test/rules/rule38.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/rules/rule38.ets.migrate.ets b/ets2panda/linter/test/rules/rule38.ets.migrate.ets new file mode 100644 index 0000000000..59cb4761aa --- /dev/null +++ b/ets2panda/linter/test/rules/rule38.ets.migrate.ets @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2023-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +interface GeneratedObjectLiteralInterface_1 { + n: number; + s: string; +} +let o1: GeneratedObjectLiteralInterface_1 = {n: 42, s: "foo"} +let o2: Object = {n: 42, s: "foo"} +let o3: object = {n: 42, s: "foo"} + +let oo: Object[] = [{n: 1, s: "1"}, {n: 2, s: "2"}] + +class C2 { + s: string + constructor(s: string) { + this.s = "s =" + s + } +} +let o4: C2 = {s: "foo"} + +class C3 { + readonly n: number = 0 + readonly s: string = "" +} +let o5: C3 = {n: 42, s: "foo"} + +abstract class A {} +let o6: A = {} + +class C4 { + n: number = 0 + s: string = "" + f() { + console.log("Hello") + } +} +let o7: C4 = {n: 42, s: "foo", f : () => {}} + +class Point { + x: number = 0 + y: number = 0 +} +function id_x_y(o: Point): Point { + return o +} + +// Structural typing is used to deduce that p is Point: +interface GeneratedObjectLiteralInterface_2 { + x: number; + y: number; +} +let p: GeneratedObjectLiteralInterface_2 = {x: 5, y: 10} +id_x_y(p) + +// A literal can be contextually (i.e., implicitly) typed as Point: +id_x_y({x: 5, y: 10}) \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/ComputedPropertyName.ets.json b/ets2panda/linter/test/rules/rule38.ets.migrate.json similarity index 56% rename from ets2panda/linter/test/sdkwhite/ComputedPropertyName.ets.json rename to ets2panda/linter/test/rules/rule38.ets.migrate.json index 4d9df55e45..c7161779da 100644 --- a/ets2panda/linter/test/sdkwhite/ComputedPropertyName.ets.json +++ b/ets2panda/linter/test/rules/rule38.ets.migrate.json @@ -15,103 +15,103 @@ ], "result": [ { - "line": 17, - "column": 3, - "endLine": 17, - "endColumn": 4, - "problem": "LiteralAsPropertyName", + "line": 21, + "column": 18, + "endLine": 21, + "endColumn": 19, + "problem": "ObjectLiteralNoContextType", "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 17, - "column": 6, - "endLine": 17, - "endColumn": 7, + "line": 22, + "column": 18, + "endLine": 22, + "endColumn": 19, "problem": "ObjectLiteralNoContextType", "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 20, - "column": 3, - "endLine": 20, - "endColumn": 4, - "problem": "LiteralAsPropertyName", + "line": 24, + "column": 20, + "endLine": 24, + "endColumn": 52, + "problem": "ArrayLiteralNoContextType", "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "rule": "Array literals must contain elements of only inferrable types (arkts-no-noninferrable-arr-literals)", "severity": "ERROR" }, { - "line": 20, - "column": 6, - "endLine": 20, - "endColumn": 7, + "line": 24, + "column": 21, + "endLine": 24, + "endColumn": 22, "problem": "ObjectLiteralNoContextType", "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 23, - "column": 3, - "endLine": 23, - "endColumn": 4, - "problem": "LiteralAsPropertyName", + "line": 24, + "column": 37, + "endLine": 24, + "endColumn": 38, + "problem": "ObjectLiteralNoContextType", "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 23, - "column": 6, - "endLine": 23, - "endColumn": 7, + "line": 32, + "column": 14, + "endLine": 32, + "endColumn": 15, "problem": "ObjectLiteralNoContextType", "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 26, - "column": 3, - "endLine": 26, - "endColumn": 4, - "problem": "LiteralAsPropertyName", + "line": 38, + "column": 14, + "endLine": 38, + "endColumn": 15, + "problem": "ObjectLiteralNoContextType", "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 26, - "column": 6, - "endLine": 26, - "endColumn": 7, + "line": 41, + "column": 13, + "endLine": 41, + "endColumn": 14, "problem": "ObjectLiteralNoContextType", "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 29, - "column": 3, - "endLine": 29, - "endColumn": 4, - "problem": "LiteralAsPropertyName", + "line": 50, + "column": 14, + "endLine": 50, + "endColumn": 15, + "problem": "ObjectLiteralNoContextType", "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 29, - "column": 6, - "endLine": 29, - "endColumn": 7, - "problem": "ObjectLiteralNoContextType", + "line": 66, + "column": 8, + "endLine": 66, + "endColumn": 9, + "problem": "StructuralIdentity", "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Structural typing is not supported (arkts-no-structural-typing)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/rules/rule40.ets.args.json b/ets2panda/linter/test/rules/rule40.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/rules/rule40.ets.args.json +++ b/ets2panda/linter/test/rules/rule40.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/rules/rule40.ets.migrate.ets b/ets2panda/linter/test/rules/rule40.ets.migrate.ets new file mode 100644 index 0000000000..b981110453 --- /dev/null +++ b/ets2panda/linter/test/rules/rule40.ets.migrate.ets @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2023-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +interface GeneratedTypeLiteralInterface_1 { + x: number; + y: number; +} +let o: GeneratedTypeLiteralInterface_1 = { + x: 2, + y: 3 +} + +interface GeneratedTypeLiteralInterface_2 { + x: number; + y: number; +} +type S = Set + +class C { + x: number = 0 + y: number = 0 +} + +let c: C = {x: 2, y: 3} + +type t = Set \ No newline at end of file diff --git a/ets2panda/linter/test/rules/rule40.ets.migrate.json b/ets2panda/linter/test/rules/rule40.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/rules/rule40.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/rules/rule46.ets.args.json b/ets2panda/linter/test/rules/rule46.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/rules/rule46.ets.args.json +++ b/ets2panda/linter/test/rules/rule46.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/rules/rule46.ets.migrate.ets b/ets2panda/linter/test/rules/rule46.ets.migrate.ets new file mode 100644 index 0000000000..d05a578739 --- /dev/null +++ b/ets2panda/linter/test/rules/rule46.ets.migrate.ets @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2023-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +let f = (s: string) => { + console.log(s); +} + +let foo = (s: string) => { + console.log(s) +} \ No newline at end of file diff --git a/ets2panda/linter/test/rules/rule46.ets.migrate.json b/ets2panda/linter/test/rules/rule46.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/rules/rule46.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/rules/rule5.ets.args.json b/ets2panda/linter/test/rules/rule5.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/rules/rule5.ets.args.json +++ b/ets2panda/linter/test/rules/rule5.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/rules/rule5.ets.migrate.ets b/ets2panda/linter/test/rules/rule5.ets.migrate.ets new file mode 100644 index 0000000000..4be90ab719 --- /dev/null +++ b/ets2panda/linter/test/rules/rule5.ets.migrate.ets @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// fixable +let bar1 = 1; +let foo1 = bar1; + +let bar2 = 1; +let most2 = 1; +let foo2 = bar2, toast2 = most2; + +let bar3 = 1; +let most3 = 1; +let foo3 = bar3; let toast3 = most3; + +let b4 = []; +for (let a4 of b4) { console.log(a4); } + +let b5 = []; +for (let a5 in b5) { console.log(a5); } + +let b6 = []; +for (let a6 of b6) { let c6 = 1; console.log(c6); } + +let list7 = []; +for (let i7 = 0; i7 < list7.length; ++i7) { foo(i7) } + +var {a8, b8 = a8} = {} // not fixable + +let a9 = b9; var b9 = 1 + +let foo10 = 1 + +declare let foo11 = 2; + +// not fixable +var fx12 = function (i12 = 0) { if (i12 < 5) { return fx12(i12 + 1); } console.log(i12); }; fx12(); + +var foo13 = () => { foo13(); }; + +var foo14 = () => foo14(); + +// fixable +let bar15 = foo15; var foo15 = () => { foo15(); }; + +let bar16 = () => { foo16(); }; var foo16 = () => { }; + +// not fixable +for (var i17 = 0, i17 = 0; false;); + +var i18 = 0; for (var i18 = 1; false;); console.log(i18); + +var a19, b19, c19; var a19; + +let b20 = 1; +var a20; if (b20) { var a20; } + +let foo21 = 1; +if (foo21) { var a21, b21, c21; } a21; + +for (var i22 = 0; i22 < 10; ++i22) {} i22; + +let obj23 = []; +for (var a23 in obj23) {} a23; + +let list24 = []; +for (var a24 of list24) {} a24; + +let a25 = 1; +switch (a25) { case 0: var b25 = 1 } + +let b26 = []; +let arr26 = []; +for (var a26 of b26) { arr26.push(() => a26); } + +let b27 = []; +for (let a27 of b27) { var c27; console.log(c27); c27 = 'hello'; } + +var a28 = a28 + +var {a29 = a29} = {} + +var {a30 = b30, b30} = {} + +var a31 = b31, b31 = 1 + +function foo32() { a32 } var a32 = 1; foo32() + +let foo33 = 1; +if (foo33) var bar33 = 1; + +// var foo34 = 1 + +// { var foo35 = 1 } + +if (true) { var foo36 = 1 } + +function foo37() { var let; } + +// how to test it, let keyword should stay let keyword +// function foo38() { var { let } = {}; } + +var foo39 = (() => { foo39(); })(); + +let bar40 = (a) => { }; +var foo40 = bar40(() => { foo40(); }); + +var bar41 = foo41, foo41 = () => { foo41(); }; + +var { foo42 = foo42 } = () => { foo42(); }; + +var { bar43 = foo43, foo43 } = () => { foo43(); }; diff --git a/ets2panda/linter/test/migrate/type_literals.ts.json b/ets2panda/linter/test/rules/rule5.ets.migrate.json similarity index 38% rename from ets2panda/linter/test/migrate/type_literals.ts.json rename to ets2panda/linter/test/rules/rule5.ets.migrate.json index 45191b82e3..d5974e4a39 100644 --- a/ets2panda/linter/test/migrate/type_literals.ts.json +++ b/ets2panda/linter/test/rules/rule5.ets.migrate.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -15,643 +15,673 @@ ], "result": [ { - "line": 16, - "column": 14, - "endLine": 16, + "line": 32, + "column": 13, + "endLine": 32, "endColumn": 15, - "problem": "ObjectTypeLiteral", + "problem": "ForInStatement", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "\"for .. in\" is not supported (arkts-no-for-in)", "severity": "ERROR" }, { - "line": 17, - "column": 14, - "endLine": 17, - "endColumn": 15, - "problem": "ObjectTypeLiteral", + "line": 40, + "column": 1, + "endLine": 40, + "endColumn": 4, + "problem": "VarDeclaration", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", "severity": "ERROR" }, { - "line": 18, - "column": 14, - "endLine": 18, - "endColumn": 15, - "problem": "ObjectTypeLiteral", + "line": 40, + "column": 5, + "endLine": 40, + "endColumn": 23, + "problem": "DestructuringDeclaration", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", "severity": "ERROR" }, { - "line": 19, - "column": 22, - "endLine": 19, - "endColumn": 23, - "problem": "ObjectTypeLiteral", + "line": 40, + "column": 21, + "endLine": 40, + "endColumn": 22, + "problem": "ObjectLiteralNoContextType", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 19, - "column": 47, - "endLine": 19, - "endColumn": 48, - "problem": "ObjectTypeLiteral", + "line": 42, + "column": 14, + "endLine": 42, + "endColumn": 17, + "problem": "VarDeclaration", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", "severity": "ERROR" }, { - "line": 20, - "column": 20, - "endLine": 20, - "endColumn": 21, - "problem": "ObjectTypeLiteral", + "line": 49, + "column": 1, + "endLine": 49, + "endColumn": 4, + "problem": "VarDeclaration", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", "severity": "ERROR" }, { - "line": 21, - "column": 14, - "endLine": 21, - "endColumn": 15, - "problem": "ObjectTypeLiteral", + "line": 49, + "column": 12, + "endLine": 49, + "endColumn": 91, + "problem": "FunctionExpression", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", "severity": "ERROR" }, { - "line": 24, - "column": 6, - "endLine": 24, - "endColumn": 7, - "problem": "ObjectTypeLiteral", + "line": 49, + "column": 12, + "endLine": 49, + "endColumn": 91, + "problem": "LimitedReturnTypeInference", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", "severity": "ERROR" }, { - "line": 30, - "column": 21, - "endLine": 30, - "endColumn": 22, - "problem": "ObjectTypeLiteral", + "line": 51, + "column": 1, + "endLine": 51, + "endColumn": 4, + "problem": "VarDeclaration", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", "severity": "ERROR" }, { - "line": 32, - "column": 11, - "endLine": 32, - "endColumn": 12, - "problem": "ObjectTypeLiteral", + "line": 53, + "column": 1, + "endLine": 53, + "endColumn": 4, + "problem": "VarDeclaration", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", "severity": "ERROR" }, { - "line": 32, - "column": 16, - "endLine": 32, - "endColumn": 17, - "problem": "ObjectLiteralNoContextType", + "line": 53, + "column": 13, + "endLine": 53, + "endColumn": 26, + "problem": "LimitedReturnTypeInference", "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", "severity": "ERROR" }, { - "line": 33, - "column": 11, - "endLine": 33, - "endColumn": 12, - "problem": "ObjectTypeLiteral", + "line": 56, + "column": 20, + "endLine": 56, + "endColumn": 23, + "problem": "VarDeclaration", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", "severity": "ERROR" }, { - "line": 33, - "column": 36, - "endLine": 33, - "endColumn": 37, - "problem": "ObjectLiteralNoContextType", + "line": 58, + "column": 33, + "endLine": 58, + "endColumn": 36, + "problem": "VarDeclaration", "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", "severity": "ERROR" }, { - "line": 34, - "column": 11, - "endLine": 34, - "endColumn": 12, - "problem": "ObjectTypeLiteral", + "line": 61, + "column": 6, + "endLine": 61, + "endColumn": 9, + "problem": "VarDeclaration", + "suggest": "", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", + "severity": "ERROR" + }, + { + "line": 63, + "column": 1, + "endLine": 63, + "endColumn": 4, + "problem": "VarDeclaration", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", "severity": "ERROR" }, { - "line": 35, + "line": 63, "column": 19, - "endLine": 35, - "endColumn": 20, - "problem": "ObjectTypeLiteral", + "endLine": 63, + "endColumn": 22, + "problem": "VarDeclaration", + "suggest": "", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", + "severity": "ERROR" + }, + { + "line": 65, + "column": 1, + "endLine": 65, + "endColumn": 4, + "problem": "VarDeclaration", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", "severity": "ERROR" }, { - "line": 35, - "column": 44, - "endLine": 35, - "endColumn": 45, - "problem": "ObjectTypeLiteral", + "line": 65, + "column": 5, + "endLine": 65, + "endColumn": 8, + "problem": "AnyType", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, { - "line": 36, + "line": 65, + "column": 10, + "endLine": 65, + "endColumn": 13, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 65, + "column": 15, + "endLine": 65, + "endColumn": 18, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 65, "column": 20, - "endLine": 36, - "endColumn": 21, - "problem": "ObjectTypeLiteral", + "endLine": 65, + "endColumn": 23, + "problem": "VarDeclaration", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", "severity": "ERROR" }, { - "line": 37, - "column": 11, - "endLine": 37, - "endColumn": 12, - "problem": "ObjectTypeLiteral", + "line": 65, + "column": 24, + "endLine": 65, + "endColumn": 27, + "problem": "AnyType", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, { - "line": 40, - "column": 6, - "endLine": 40, - "endColumn": 7, - "problem": "ObjectTypeLiteral", + "line": 68, + "column": 1, + "endLine": 68, + "endColumn": 4, + "problem": "VarDeclaration", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", "severity": "ERROR" }, { - "line": 45, + "line": 68, "column": 5, - "endLine": 45, - "endColumn": 6, - "problem": "ObjectLiteralNoContextType", + "endLine": 68, + "endColumn": 8, + "problem": "AnyType", "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, { - "line": 48, - "column": 6, - "endLine": 48, - "endColumn": 7, - "problem": "ObjectLiteralNoContextType", + "line": 68, + "column": 21, + "endLine": 68, + "endColumn": 24, + "problem": "VarDeclaration", "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", "severity": "ERROR" }, { - "line": 51, - "column": 8, - "endLine": 51, - "endColumn": 9, - "problem": "ObjectLiteralNoContextType", + "line": 68, + "column": 25, + "endLine": 68, + "endColumn": 28, + "problem": "AnyType", "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, { - "line": 58, - "column": 15, - "endLine": 58, - "endColumn": 16, - "problem": "ObjectTypeLiteral", + "line": 71, + "column": 14, + "endLine": 71, + "endColumn": 17, + "problem": "VarDeclaration", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", "severity": "ERROR" }, { - "line": 58, - "column": 40, - "endLine": 58, - "endColumn": 41, - "problem": "ObjectTypeLiteral", + "line": 71, + "column": 18, + "endLine": 71, + "endColumn": 21, + "problem": "AnyType", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, { - "line": 59, - "column": 10, - "endLine": 59, - "endColumn": 11, - "problem": "ObjectLiteralNoContextType", + "line": 71, + "column": 23, + "endLine": 71, + "endColumn": 26, + "problem": "AnyType", "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, { - "line": 63, - "column": 6, - "endLine": 63, - "endColumn": 7, - "problem": "ObjectTypeLiteral", + "line": 71, + "column": 28, + "endLine": 71, + "endColumn": 31, + "problem": "AnyType", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, { - "line": 63, - "column": 31, - "endLine": 63, - "endColumn": 32, - "problem": "ObjectLiteralNoContextType", + "line": 73, + "column": 6, + "endLine": 73, + "endColumn": 9, + "problem": "VarDeclaration", "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", "severity": "ERROR" }, { - "line": 65, - "column": 8, - "endLine": 65, - "endColumn": 9, - "problem": "ObjectTypeLiteral", + "line": 76, + "column": 14, + "endLine": 76, + "endColumn": 16, + "problem": "ForInStatement", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "\"for .. in\" is not supported (arkts-no-for-in)", "severity": "ERROR" }, { - "line": 65, - "column": 33, - "endLine": 65, - "endColumn": 34, - "problem": "ObjectTypeLiteral", + "line": 76, + "column": 6, + "endLine": 76, + "endColumn": 9, + "problem": "VarDeclaration", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", "severity": "ERROR" }, { - "line": 66, - "column": 12, - "endLine": 66, - "endColumn": 13, - "problem": "ObjectLiteralNoContextType", + "line": 79, + "column": 6, + "endLine": 79, + "endColumn": 9, + "problem": "VarDeclaration", "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", "severity": "ERROR" }, { - "line": 72, - "column": 22, - "endLine": 72, - "endColumn": 23, - "problem": "ObjectTypeLiteral", + "line": 82, + "column": 24, + "endLine": 82, + "endColumn": 27, + "problem": "VarDeclaration", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", "severity": "ERROR" }, { - "line": 73, - "column": 14, - "endLine": 73, - "endColumn": 15, - "problem": "ObjectTypeLiteral", + "line": 86, + "column": 6, + "endLine": 86, + "endColumn": 9, + "problem": "VarDeclaration", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", "severity": "ERROR" }, { - "line": 73, - "column": 38, - "endLine": 73, - "endColumn": 39, - "problem": "ObjectTypeLiteral", + "line": 89, + "column": 24, + "endLine": 89, + "endColumn": 27, + "problem": "VarDeclaration", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", "severity": "ERROR" }, { - "line": 75, - "column": 16, - "endLine": 75, - "endColumn": 17, - "problem": "ObjectTypeLiteral", + "line": 89, + "column": 28, + "endLine": 89, + "endColumn": 31, + "problem": "AnyType", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, { - "line": 80, - "column": 3, - "endLine": 80, + "line": 91, + "column": 1, + "endLine": 91, "endColumn": 4, - "problem": "ObjectTypeLiteral", + "problem": "VarDeclaration", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", "severity": "ERROR" }, { - "line": 80, - "column": 19, - "endLine": 80, - "endColumn": 20, - "problem": "ObjectLiteralNoContextType", + "line": 91, + "column": 5, + "endLine": 91, + "endColumn": 14, + "problem": "AnyType", "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, { - "line": 82, - "column": 20, - "endLine": 82, - "endColumn": 21, - "problem": "ObjectTypeLiteral", + "line": 93, + "column": 1, + "endLine": 93, + "endColumn": 4, + "problem": "VarDeclaration", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", "severity": "ERROR" }, { - "line": 85, - "column": 3, - "endLine": 85, - "endColumn": 4, - "problem": "LiteralAsPropertyName", + "line": 93, + "column": 5, + "endLine": 93, + "endColumn": 21, + "problem": "DestructuringDeclaration", "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", "severity": "ERROR" }, { "line": 93, - "column": 3, + "column": 19, "endLine": 93, - "endColumn": 23, - "problem": "CallSignature", + "endColumn": 20, + "problem": "ObjectLiteralNoContextType", "suggest": "", - "rule": "Use \"class\" instead of a type with call signature (arkts-no-call-signatures)", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 94, - "column": 3, - "endLine": 94, - "endColumn": 22, - "problem": "ConstructorType", + "line": 95, + "column": 1, + "endLine": 95, + "endColumn": 4, + "problem": "VarDeclaration", "suggest": "", - "rule": "Use \"class\" instead of a type with constructor signature (arkts-no-ctor-signatures-type)", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", "severity": "ERROR" }, { "line": 95, - "column": 3, + "column": 5, "endLine": 95, "endColumn": 26, - "problem": "IndexMember", + "problem": "DestructuringDeclaration", "suggest": "", - "rule": "Indexed signatures are not supported (arkts-no-indexed-signatures)", + "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", "severity": "ERROR" }, { "line": 95, - "column": 18, + "column": 24, "endLine": 95, "endColumn": 25, - "problem": "UnknownType", + "problem": "ObjectLiteralNoContextType", "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, { - "line": 98, - "column": 18, - "endLine": 98, - "endColumn": 19, - "problem": "ObjectTypeLiteral", + "line": 97, + "column": 1, + "endLine": 97, + "endColumn": 4, + "problem": "VarDeclaration", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", "severity": "ERROR" }, { - "line": 101, - "column": 3, - "endLine": 101, - "endColumn": 4, - "problem": "LiteralAsPropertyName", + "line": 99, + "column": 26, + "endLine": 99, + "endColumn": 29, + "problem": "VarDeclaration", "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", "severity": "ERROR" }, { - "line": 109, - "column": 3, - "endLine": 109, - "endColumn": 23, - "problem": "CallSignature", + "line": 102, + "column": 12, + "endLine": 102, + "endColumn": 15, + "problem": "VarDeclaration", "suggest": "", - "rule": "Use \"class\" instead of a type with call signature (arkts-no-call-signatures)", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", "severity": "ERROR" }, { - "line": 110, - "column": 3, - "endLine": 110, - "endColumn": 22, - "problem": "ConstructorType", + "line": 108, + "column": 13, + "endLine": 108, + "endColumn": 16, + "problem": "VarDeclaration", "suggest": "", - "rule": "Use \"class\" instead of a type with constructor signature (arkts-no-ctor-signatures-type)", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", "severity": "ERROR" }, { - "line": 111, - "column": 3, - "endLine": 111, - "endColumn": 26, - "problem": "IndexMember", + "line": 110, + "column": 20, + "endLine": 110, + "endColumn": 23, + "problem": "VarDeclaration", "suggest": "", - "rule": "Indexed signatures are not supported (arkts-no-indexed-signatures)", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", "severity": "ERROR" }, { - "line": 111, - "column": 18, - "endLine": 111, - "endColumn": 25, - "problem": "UnknownType", + "line": 110, + "column": 24, + "endLine": 110, + "endColumn": 27, + "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, { "line": 115, - "column": 49, + "column": 1, "endLine": 115, - "endColumn": 50, - "problem": "ObjectTypeLiteral", + "endColumn": 4, + "problem": "VarDeclaration", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", "severity": "ERROR" }, { - "line": 116, - "column": 11, - "endLine": 116, - "endColumn": 12, - "problem": "ObjectTypeLiteral", + "line": 117, + "column": 14, + "endLine": 117, + "endColumn": 15, + "problem": "AnyType", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, { "line": 118, - "column": 20, + "column": 1, "endLine": 118, - "endColumn": 21, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 119, - "column": 11, - "endLine": 119, - "endColumn": 12, - "problem": "ObjectTypeLiteral", + "endColumn": 4, + "problem": "VarDeclaration", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", "severity": "ERROR" }, { - "line": 119, - "column": 30, - "endLine": 119, - "endColumn": 31, - "problem": "ObjectLiteralNoContextType", + "line": 120, + "column": 1, + "endLine": 120, + "endColumn": 4, + "problem": "VarDeclaration", "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", "severity": "ERROR" }, { - "line": 119, - "column": 34, - "endLine": 119, - "endColumn": 35, - "problem": "ObjectLiteralNoContextType", + "line": 122, + "column": 1, + "endLine": 122, + "endColumn": 4, + "problem": "VarDeclaration", "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", "severity": "ERROR" }, { - "line": 121, - "column": 25, - "endLine": 121, - "endColumn": 26, - "problem": "ObjectTypeLiteral", + "line": 122, + "column": 5, + "endLine": 122, + "endColumn": 43, + "problem": "DestructuringDeclaration", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", "severity": "ERROR" }, { "line": 124, - "column": 11, + "column": 1, "endLine": 124, - "endColumn": 12, - "problem": "ObjectTypeLiteral", + "endColumn": 4, + "problem": "VarDeclaration", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Use \"let\" instead of \"var\" (arkts-no-var)", "severity": "ERROR" }, { "line": 124, - "column": 12, + "column": 5, "endLine": 124, - "endColumn": 17, - "problem": "ComputedPropertyName", + "endColumn": 50, + "problem": "DestructuringDeclaration", "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", "severity": "ERROR" }, { - "line": 127, - "column": 11, - "endLine": 127, + "line": 42, + "column": 10, + "endLine": 42, "endColumn": 12, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "problem": "StrictDiagnostic", + "suggest": "Variable 'b9' is used before being assigned.", + "rule": "Variable 'b9' is used before being assigned.", "severity": "ERROR" }, { - "line": 127, - "column": 31, - "endLine": 127, - "endColumn": 32, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "line": 56, + "column": 13, + "endLine": 56, + "endColumn": 18, + "problem": "StrictDiagnostic", + "suggest": "Variable 'foo15' is used before being assigned.", + "rule": "Variable 'foo15' is used before being assigned.", "severity": "ERROR" }, { - "line": 129, - "column": 11, - "endLine": 129, - "endColumn": 12, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "line": 76, + "column": 27, + "endLine": 76, + "endColumn": 30, + "problem": "StrictDiagnostic", + "suggest": "Variable 'a23' is used before being assigned.", + "rule": "Variable 'a23' is used before being assigned.", "severity": "ERROR" }, { - "line": 129, - "column": 17, - "endLine": 129, - "endColumn": 23, - "problem": "TypeQuery", - "suggest": "", - "rule": "\"typeof\" operator is allowed only in expression contexts (arkts-no-type-query)", + "line": 79, + "column": 28, + "endLine": 79, + "endColumn": 31, + "problem": "StrictDiagnostic", + "suggest": "Variable 'a24' is used before being assigned.", + "rule": "Variable 'a24' is used before being assigned.", "severity": "ERROR" }, { - "line": 131, - "column": 11, - "endLine": 131, - "endColumn": 12, - "problem": "ObjectTypeLiteral", - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "line": 86, + "column": 35, + "endLine": 86, + "endColumn": 44, + "problem": "StrictDiagnostic", + "suggest": "Argument of type '() => never' is not assignable to parameter of type 'never'.", + "rule": "Argument of type '() => never' is not assignable to parameter of type 'never'.", "severity": "ERROR" }, { - "line": 131, - "column": 17, - "endLine": 131, - "endColumn": 23, - "problem": "TypeQuery", - "suggest": "", - "rule": "\"typeof\" operator is allowed only in expression contexts (arkts-no-type-query)", + "line": 97, + "column": 11, + "endLine": 97, + "endColumn": 14, + "problem": "StrictDiagnostic", + "suggest": "Variable 'b31' is used before being assigned.", + "rule": "Variable 'b31' is used before being assigned.", "severity": "ERROR" }, { - "line": 133, - "column": 10, - "endLine": 133, - "endColumn": 11, - "problem": "ObjectLiteralNoContextType", - "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "line": 120, + "column": 13, + "endLine": 120, + "endColumn": 18, + "problem": "StrictDiagnostic", + "suggest": "Variable 'foo41' is used before being assigned.", + "rule": "Variable 'foo41' is used before being assigned.", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/rules/rule53.ets.args.json b/ets2panda/linter/test/rules/rule53.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/rules/rule53.ets.args.json +++ b/ets2panda/linter/test/rules/rule53.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/rules/rule53.ets.migrate.ets b/ets2panda/linter/test/rules/rule53.ets.migrate.ets new file mode 100644 index 0000000000..616623d387 --- /dev/null +++ b/ets2panda/linter/test/rules/rule53.ets.migrate.ets @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2023-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class Shape {} +class Circle extends Shape {x: number = 5} +class Square extends Shape {y: string = "a"} + +function createShape(): Shape { + return new Circle() +} + +let c1 = createShape() as Circle + +let c2 = createShape() as Circle + +// No report is provided during compilation +// nor during runtime if cast is wrong: +let c3 = createShape() as Square +console.log(c3.y) // undefined + +// Important corner case for casting primitives to the boxed counterparts: +// The left operand is not properly boxed here in in runtime +// because "as" has no runtime effect in TypeScript +let e1 = (5.0 as Number) instanceof Number // false + +// Number object is created and instanceof works as expected: +let e2 = (new Number(5.0)) instanceof Number // true \ No newline at end of file diff --git a/ets2panda/linter/test/rules/rule53.ets.migrate.json b/ets2panda/linter/test/rules/rule53.ets.migrate.json new file mode 100644 index 0000000000..e1ec7aa8a9 --- /dev/null +++ b/ets2panda/linter/test/rules/rule53.ets.migrate.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 36, + "column": 11, + "endLine": 36, + "endColumn": 24, + "problem": "TypeAssertion", + "suggest": "", + "rule": "Only \"as T\" syntax is supported for type casts (arkts-as-casts)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/rules/rule71.ets.args.json b/ets2panda/linter/test/rules/rule71.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/rules/rule71.ets.args.json +++ b/ets2panda/linter/test/rules/rule71.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/rules/rule71.ets.migrate.ets b/ets2panda/linter/test/rules/rule71.ets.migrate.ets new file mode 100644 index 0000000000..e7b82ded6d --- /dev/null +++ b/ets2panda/linter/test/rules/rule71.ets.migrate.ets @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2023-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +for (let i = 0, j = 0; i < 10; ++i, j += 2) { + console.log(i) + console.log(j) +} + +let x = 0 + +// Error, no autofix +x = (++x, x++) + +// No error +for (let i = 0, j = 0; i < 10; ++i, j += 2) { + console.log(i) + console.log(j) +} + +let x2 = 0 +++x2 +x2 = x2++ + +let c = () => 33; + +// Error, no autofix +const a = (1, b = 2, c()); + +// Error, no autofix +const r = (c(), b, 1) + +class Test { + // Error, no autofix + static readonly sr = (1, c(), 2); + + // Error, no autofix + field1 = (1, 2, c()); + + method() { + // Error, no autofix + this.field1 = (c(), sr, 1); + } +} + +// Error, autofix +x++; + x--; + +// Error, autofix +x++; + x--; + ++x; + --x; + x; + +// Error, no autofix +if (x++, x === 1) { + // Error, autofix + x++; + x--; + ++x; + --x; + x; +} + +// Error, autofix +x++ + x--; + ++x; + --x; + +// Error, autofix +++x; + x-- + x++; + --x; + +// Error, autofix +++x; + --x; + x-- + x++; + +// Error, autofix +x === x; + --x; + x === x; + x++; + x === x; + +// Error, autofix +x instanceof number; + --x; + x instanceof number; + x++; + x instanceof number; + +// Error, autofix +x in x; + --x; + x in x; + x++; + x in x; diff --git a/ets2panda/linter/test/rules/rule71.ets.migrate.json b/ets2panda/linter/test/rules/rule71.ets.migrate.json new file mode 100644 index 0000000000..b3add27cb1 --- /dev/null +++ b/ets2panda/linter/test/rules/rule71.ets.migrate.json @@ -0,0 +1,148 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 24, + "column": 6, + "endLine": 24, + "endColumn": 14, + "problem": "CommaOperator", + "suggest": "", + "rule": "The comma operator \",\" is supported only in \"for\" loops (arkts-no-comma-outside-loops)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 12, + "endLine": 39, + "endColumn": 25, + "problem": "CommaOperator", + "suggest": "", + "rule": "The comma operator \",\" is supported only in \"for\" loops (arkts-no-comma-outside-loops)", + "severity": "ERROR" + }, + { + "line": 42, + "column": 12, + "endLine": 42, + "endColumn": 21, + "problem": "CommaOperator", + "suggest": "", + "rule": "The comma operator \",\" is supported only in \"for\" loops (arkts-no-comma-outside-loops)", + "severity": "ERROR" + }, + { + "line": 46, + "column": 27, + "endLine": 46, + "endColumn": 36, + "problem": "CommaOperator", + "suggest": "", + "rule": "The comma operator \",\" is supported only in \"for\" loops (arkts-no-comma-outside-loops)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 15, + "endLine": 49, + "endColumn": 24, + "problem": "CommaOperator", + "suggest": "", + "rule": "The comma operator \",\" is supported only in \"for\" loops (arkts-no-comma-outside-loops)", + "severity": "ERROR" + }, + { + "line": 53, + "column": 24, + "endLine": 53, + "endColumn": 34, + "problem": "CommaOperator", + "suggest": "", + "rule": "The comma operator \",\" is supported only in \"for\" loops (arkts-no-comma-outside-loops)", + "severity": "ERROR" + }, + { + "line": 69, + "column": 5, + "endLine": 69, + "endColumn": 17, + "problem": "CommaOperator", + "suggest": "", + "rule": "The comma operator \",\" is supported only in \"for\" loops (arkts-no-comma-outside-loops)", + "severity": "ERROR" + }, + { + "line": 101, + "column": 3, + "endLine": 101, + "endColumn": 13, + "problem": "InstanceofUnsupported", + "suggest": "", + "rule": "\"instanceof\" operator is partially supported (arkts-instanceof-ref-types)", + "severity": "ERROR" + }, + { + "line": 103, + "column": 4, + "endLine": 103, + "endColumn": 14, + "problem": "InstanceofUnsupported", + "suggest": "", + "rule": "\"instanceof\" operator is partially supported (arkts-instanceof-ref-types)", + "severity": "ERROR" + }, + { + "line": 105, + "column": 4, + "endLine": 105, + "endColumn": 14, + "problem": "InstanceofUnsupported", + "suggest": "", + "rule": "\"instanceof\" operator is partially supported (arkts-instanceof-ref-types)", + "severity": "ERROR" + }, + { + "line": 108, + "column": 3, + "endLine": 108, + "endColumn": 5, + "problem": "InOperator", + "suggest": "", + "rule": "\"in\" operator is not supported (arkts-no-in)", + "severity": "ERROR" + }, + { + "line": 110, + "column": 4, + "endLine": 110, + "endColumn": 6, + "problem": "InOperator", + "suggest": "", + "rule": "\"in\" operator is not supported (arkts-no-in)", + "severity": "ERROR" + }, + { + "line": 112, + "column": 4, + "endLine": 112, + "endColumn": 6, + "problem": "InOperator", + "suggest": "", + "rule": "\"in\" operator is not supported (arkts-no-in)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/rules/rule79.ets.args.json b/ets2panda/linter/test/rules/rule79.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/rules/rule79.ets.args.json +++ b/ets2panda/linter/test/rules/rule79.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/rules/rule79.ets.migrate.ets b/ets2panda/linter/test/rules/rule79.ets.migrate.ets new file mode 100644 index 0000000000..e31b555a88 --- /dev/null +++ b/ets2panda/linter/test/rules/rule79.ets.migrate.ets @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +try { + // some code +} +catch (a) { + // handle error +} + + +try { + // some code +} +catch (a) { + // handle error +} \ No newline at end of file diff --git a/ets2panda/linter/test/rules/rule79.ets.migrate.json b/ets2panda/linter/test/rules/rule79.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/rules/rule79.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/rules/rule90.ets.args.json b/ets2panda/linter/test/rules/rule90.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/rules/rule90.ets.args.json +++ b/ets2panda/linter/test/rules/rule90.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/rules/rule90.ets.migrate.ets b/ets2panda/linter/test/rules/rule90.ets.migrate.ets new file mode 100644 index 0000000000..3e97208530 --- /dev/null +++ b/ets2panda/linter/test/rules/rule90.ets.migrate.ets @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2023-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + // Compile-time error with noImplicitAny + function f(x: number) { + if (x <= 0) { + return x + } + return g(x) + } + + // Compile-time error with noImplicitAny + function g(x: number) { + return f(x - 1) + } + + function doOperation(x: number, y: number) { + return x + y + } + + console.log(f(10)) + console.log(doOperation(2, 3)) + + function f1(x: number) : number { + if (x <= 0) { + return x + } + return g1(x) + } + + function g1(x: number) { + return f1(x - 1) + } + + function doOperation1(x: number, y: number) { + return x + y + } + + console.log(f1(10)) + console.log(doOperation1(2, 3)) diff --git a/ets2panda/linter/test/rules/rule90.ets.migrate.json b/ets2panda/linter/test/rules/rule90.ets.migrate.json new file mode 100644 index 0000000000..0ca7cc2093 --- /dev/null +++ b/ets2panda/linter/test/rules/rule90.ets.migrate.json @@ -0,0 +1,38 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 14, + "endLine": 17, + "endColumn": 15, + "problem": "LimitedReturnTypeInference", + "suggest": "", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 14, + "endLine": 25, + "endColumn": 15, + "problem": "LimitedReturnTypeInference", + "suggest": "", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/rules/rule90_1.ets.args.json b/ets2panda/linter/test/rules/rule90_1.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/rules/rule90_1.ets.args.json +++ b/ets2panda/linter/test/rules/rule90_1.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/rules/rule90_1.ets.migrate.ets b/ets2panda/linter/test/rules/rule90_1.ets.migrate.ets new file mode 100644 index 0000000000..a4dc9107fc --- /dev/null +++ b/ets2panda/linter/test/rules/rule90_1.ets.migrate.ets @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2023-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + function f(x: number) { + return 0; + } + + function f1(): number { + return 0; + } + diff --git a/ets2panda/linter/test/rules/rule90_1.ets.migrate.json b/ets2panda/linter/test/rules/rule90_1.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/rules/rule90_1.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/rules/rule90_2.ets.args.json b/ets2panda/linter/test/rules/rule90_2.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/rules/rule90_2.ets.args.json +++ b/ets2panda/linter/test/rules/rule90_2.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/rules/rule90_2.ets.migrate.ets b/ets2panda/linter/test/rules/rule90_2.ets.migrate.ets new file mode 100644 index 0000000000..d25831ff19 --- /dev/null +++ b/ets2panda/linter/test/rules/rule90_2.ets.migrate.ets @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2023-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + class A { + public foo: number = 0; + } + + function f() { + return new A; + } + + function f1(): A{ + return new A; + } diff --git a/ets2panda/linter/test/rules/rule90_2.ets.migrate.json b/ets2panda/linter/test/rules/rule90_2.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/rules/rule90_2.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/rules/rule90_3.ets.args.json b/ets2panda/linter/test/rules/rule90_3.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/rules/rule90_3.ets.args.json +++ b/ets2panda/linter/test/rules/rule90_3.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/rules/rule90_3.ets.migrate.ets b/ets2panda/linter/test/rules/rule90_3.ets.migrate.ets new file mode 100644 index 0000000000..168ead9c1e --- /dev/null +++ b/ets2panda/linter/test/rules/rule90_3.ets.migrate.ets @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class A { + public foo: number = 0; + + public bar_no_return_def() { + return 0 + } + + public bar_with_return_def() : number { + return 0 + } +} + +function f(): number { + let a = new A(); + return a.bar_no_return_def(); +} + +function f2() { + let a = new A(); + return a.bar_with_return_def(); +} + +function f3(): number{ + let a = new A(); + return a.bar_no_return_def(); +} + +function f2(): number{ + let a = new A(); + return a.bar_with_return_def(); +} diff --git a/ets2panda/linter/test/rules/rule90_3.ets.migrate.json b/ets2panda/linter/test/rules/rule90_3.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/rules/rule90_3.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/rules/rule90_4.ets.args.json b/ets2panda/linter/test/rules/rule90_4.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/rules/rule90_4.ets.args.json +++ b/ets2panda/linter/test/rules/rule90_4.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/rules/rule90_4.ets.migrate.ets b/ets2panda/linter/test/rules/rule90_4.ets.migrate.ets new file mode 100644 index 0000000000..cc5ebb1c60 --- /dev/null +++ b/ets2panda/linter/test/rules/rule90_4.ets.migrate.ets @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class A { + public foo: number = 0; + + public bar_no_return_def() { + return this.bar_with_return_def(); + } + + public bar_with_return_def() : number { + return (2 + 2) + } +} + +class B { + public foo: number = 0; + + public bar_no_return_def() { + return (2 + 2) + } + + public bar_with_return_def() : number { + return this.bar_with_return_def(); + } +} + diff --git a/ets2panda/linter/test/rules/rule90_4.ets.migrate.json b/ets2panda/linter/test/rules/rule90_4.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/rules/rule90_4.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/rules/rule90_5.ets.args.json b/ets2panda/linter/test/rules/rule90_5.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/rules/rule90_5.ets.args.json +++ b/ets2panda/linter/test/rules/rule90_5.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/rules/rule90_5.ets.migrate.ets b/ets2panda/linter/test/rules/rule90_5.ets.migrate.ets new file mode 100644 index 0000000000..3c3ac9d3bc --- /dev/null +++ b/ets2panda/linter/test/rules/rule90_5.ets.migrate.ets @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2023-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class Data1 { + public foo: number = 0; +} + +class Data2 extends Data1{ + public foo: number = 0; + +} + + +function dataFactory1() : Data1 { + return new Data2(); +} + +function dataFactory2() : Data2 { + return new Data1(); +} diff --git a/ets2panda/linter/test/rules/rule90_5.ets.migrate.json b/ets2panda/linter/test/rules/rule90_5.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/rules/rule90_5.ets.migrate.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/rules/rule92.ets.args.json b/ets2panda/linter/test/rules/rule92.ets.args.json index 5a7e115070..410c5c189e 100644 --- a/ets2panda/linter/test/rules/rule92.ets.args.json +++ b/ets2panda/linter/test/rules/rule92.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,7 @@ "limitations under the License." ], "mode": { - "autofix": "" + "autofix": "", + "migrate": "" } } diff --git a/ets2panda/linter/test/rules/rule92.ets.migrate.ets b/ets2panda/linter/test/rules/rule92.ets.migrate.ets new file mode 100644 index 0000000000..b50118770b --- /dev/null +++ b/ets2panda/linter/test/rules/rule92.ets.migrate.ets @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2023-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Fixable + +function addNum(a: number, b: number): void { + let logToConsole: (message: String) => void = (message: String): void => { + console.log(message); +}; + + let result = a + b + + logToConsole("result is " + result) +} + + +function addNum2(a: number, b: number): void { + // Use lambda instead of a nested function: + let logToConsole: (message: string) => void = (message: string): void => { + console.log(message) + } + + let result = a + b + + logToConsole("result is " + result) +} + + +function NestedOne(a: number, b: number): void { + let NestedTwo: (message: String) => void = (message: String): void => { + let NestedThree: (message: String) => void = (message: String): void => { + console.log("NestedThree"); +}; +}; +} + + +function NestedOne1(a: number, b: number): void { + let NestedTwo: (message: String) => void = (message: String): void => { + console.log("NestedTwo"); +}; + + let NestedTooToo: (message: String) => void = (message: String): void => { + console.log("NestedTooToo"); +}; +} + +function NestedOne2(a: number, b: number): void { + let NestedTwo: (message: String) => void = (message: String): void => { + let NestedThree: (message: String) => void = (message: String): void => { + console.log("NestedThree"); +}; + let NestedThreeToo: (message: String) => void = (message: String): void => { + console.log("NestedThreeToo"); +}; +}; +} + +// Not fixable +function decoratorFoo(): void { + @decorator + function decorated(): void { + } + + function* generatorFunction() { + return 3; + } + + function thisFoo() { + return this.what; + } + + notFixable(); + + function notFixable(): void { + } +} + diff --git a/ets2panda/linter/test/rules/rule92.ets.migrate.json b/ets2panda/linter/test/rules/rule92.ets.migrate.json new file mode 100644 index 0000000000..4c5918f4ba --- /dev/null +++ b/ets2panda/linter/test/rules/rule92.ets.migrate.json @@ -0,0 +1,88 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 73, + "column": 5, + "endLine": 73, + "endColumn": 13, + "problem": "LocalFunction", + "suggest": "", + "rule": "Nested functions are not supported (arkts-no-nested-funcs)", + "severity": "ERROR" + }, + { + "line": 77, + "column": 5, + "endLine": 77, + "endColumn": 13, + "problem": "LocalFunction", + "suggest": "", + "rule": "Nested functions are not supported (arkts-no-nested-funcs)", + "severity": "ERROR" + }, + { + "line": 77, + "column": 5, + "endLine": 79, + "endColumn": 6, + "problem": "GeneratorFunction", + "suggest": "", + "rule": "Generator functions are not supported (arkts-no-generators)", + "severity": "ERROR" + }, + { + "line": 81, + "column": 14, + "endLine": 81, + "endColumn": 21, + "problem": "LimitedReturnTypeInference", + "suggest": "", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "severity": "ERROR" + }, + { + "line": 82, + "column": 16, + "endLine": 82, + "endColumn": 20, + "problem": "FunctionContainsThis", + "suggest": "", + "rule": "Using \"this\" inside stand-alone functions is not supported (arkts-no-standalone-this)", + "severity": "ERROR" + }, + { + "line": 81, + "column": 5, + "endLine": 81, + "endColumn": 13, + "problem": "LocalFunction", + "suggest": "", + "rule": "Nested functions are not supported (arkts-no-nested-funcs)", + "severity": "ERROR" + }, + { + "line": 87, + "column": 5, + "endLine": 87, + "endColumn": 13, + "problem": "LocalFunction", + "suggest": "", + "rule": "Nested functions are not supported (arkts-no-nested-funcs)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/ConstructorFuncs.ets b/ets2panda/linter/test/sdkwhite/ConstructorFuncs.ets deleted file mode 100644 index 81cb6eeb8b..0000000000 --- a/ets2panda/linter/test/sdkwhite/ConstructorFuncs.ets +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// 1. First, define the DatabaseObject base class and several entity classes - -// Base database object interface -interface DatabaseObject { - id: number; - save(): Promise; -} - -// User entity class -class User implements DatabaseObject { - id: number; - username: string; - email: string; - - constructor() { - this.id = 0; - this.username = ''; - this.email = ''; - } - - async save(): Promise { - console.log(`Saving user ${this.username}`); - // Actual saving logic... - } -} - -// Product entity class -class Product implements DatabaseObject { - id: number; - name: string; - price: number; - - constructor() { - this.id = 0; - this.name = ''; - this.price = 0; - } - - async save(): Promise { - console.log(`Saving product ${this.name}`); - // Actual saving logic... - } -} - -// 2. Implement the DatabaseQuery class -class DatabaseQuery { - private entityClass: new () => T; - - constructor(entityClass: new () => T) { - this.entityClass = entityClass; - } - - // Example query method - async findById(id: number): Promise { - const entity = new this.entityClass(); - // Simulate database query - console.log(`Querying ${entity.constructor.name} with id ${id}`); - // Actual query logic... - return {...entity, id}; // Return simulated data - } - - // Another example query method - async findAll(): Promise { - const entity = new this.entityClass(); - console.log(`Querying all ${entity.constructor.name} records`); - // Actual query logic... - return [{...entity, id: 1}]; // Return simulated data - } -} - -// 3. Usage example - -// Create a user query instance -const userQuery = new DatabaseQuery(User); // Error occurs - -// Use the query methods -(async () => { - const user = await userQuery.findById(1); - if (user) { - console.log(`Found user: ${user.username}`); - user.username = "newUsername"; - await user.save(); - } - - const allUsers = await userQuery.findAll(); - console.log(`Found ${allUsers.length} users`); - - // Create a product query instance - const productQuery = new DatabaseQuery(Product); // Error occurs - const product = await productQuery.findById(5); - if (product) { - console.log(`Found product: ${product.name} ($${product.price})`); - } -})(); \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/InterfaceExtendsClass.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/InterfaceExtendsClass.ets.arkts2.json deleted file mode 100644 index 5e75d5b3e7..0000000000 --- a/ets2panda/linter/test/sdkwhite/InterfaceExtendsClass.ets.arkts2.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "result": [ - - ] -} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/constructor_types_deprecated_sdk.ets.args.json b/ets2panda/linter/test/sdkwhite/LimitedVoidType3.ets.args.json old mode 100755 new mode 100644 similarity index 100% rename from ets2panda/linter/test/sdkwhite/constructor_types_deprecated_sdk.ets.args.json rename to ets2panda/linter/test/sdkwhite/LimitedVoidType3.ets.args.json diff --git a/ets2panda/linter/test/sdkwhite/LimitedVoidType3.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/LimitedVoidType3.ets.arkts2.json index 5e75d5b3e7..5d0e2d9cb6 100644 --- a/ets2panda/linter/test/sdkwhite/LimitedVoidType3.ets.arkts2.json +++ b/ets2panda/linter/test/sdkwhite/LimitedVoidType3.ets.arkts2.json @@ -14,6 +14,105 @@ "limitations under the License." ], "result": [ - + { + "line": 18, + "column": 3, + "endLine": 20, + "endColumn": 4, + "problem": "LimitedVoidTypeFromSdk", + "suggest": "", + "rule": "Type \"void\" has no instances.(sdk-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 3, + "endLine": 20, + "endColumn": 4, + "problem": "LimitedVoidTypeFromSdk", + "suggest": "", + "rule": "Type \"void\" has no instances.(sdk-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 48, + "endLine": 18, + "endColumn": 52, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 26, + "endLine": 24, + "endColumn": 50, + "problem": "LimitedVoidTypeFromSdk", + "suggest": "", + "rule": "Type \"void\" has no instances.(sdk-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 54, + "endLine": 24, + "endColumn": 66, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 44, + "endLine": 30, + "endColumn": 48, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 9, + "endLine": 32, + "endColumn": 10, + "problem": "OptionalMethod", + "suggest": "", + "rule": "Optional methods are not supported (arkts-optional-methods)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 43, + "endLine": 32, + "endColumn": 47, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 28, + "endLine": 37, + "endColumn": 32, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 26, + "endLine": 41, + "endColumn": 30, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/LiteralAsPropertyName2.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/LiteralAsPropertyName2.ets.arkts2.json deleted file mode 100644 index 5e75d5b3e7..0000000000 --- a/ets2panda/linter/test/sdkwhite/LiteralAsPropertyName2.ets.arkts2.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "result": [ - - ] -} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/SendablePropType.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/SendablePropType.ets.arkts2.json deleted file mode 100644 index 5e75d5b3e7..0000000000 --- a/ets2panda/linter/test/sdkwhite/SendablePropType.ets.arkts2.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "result": [ - - ] -} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/decl_with_duplicate_name_sdk.ets b/ets2panda/linter/test/sdkwhite/decl_with_duplicate_name_sdk.ets new file mode 100755 index 0000000000..4584cafa7b --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/decl_with_duplicate_name_sdk.ets @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +'use static' + +import { TextStyle } from './sdk/declarations/styled_string' +import { HyperlinkAttribute, HyperlinkInterface } from './sdk/declarations/hyperlink' + +@Entry +@Component +struct Index { + fontStyleAttr1: TextStyle = new TextStyle({fontColor: Color.Blue}); // Error(2) + fontStyleAttr2: TextStyle; // Error + + @State styleList: Array = new Array(); // Error + aboutToAppear() { + for (let i = 15; i < 50; i++) + this.styleList.push(new TextStyle({})); // Error + } + + build() { + List() { + ForEach(this.styleList, (item: TextStyle) => { // Error + ListItem() { + Text("Hello World") + .fontSize(item.fontSize) + } + }) + } + } +} + +class TextStyleDemo2 extends TextStyle { // Error + constructor() { + super(); + } +} + +let hyperlinkAttr1: HyperlinkAttribute = HyperlinkInterface; +let hyperlinkAttr2: HyperlinkAttribute = HyperlinkInterface.color(''); +class HyperlinkTest { + prop1: HyperlinkAttribute = HyperlinkInterface; + prop2: HyperlinkAttribute = HyperlinkInterface.color(''); +} +let hyperlinkAttr3: HyperlinkAttribute; +hyperlinkAttr3 = HyperlinkInterface; +function func(x = HyperlinkInterface) { + +} diff --git a/ets2panda/linter/test/migrate/destructuring_declarations.ts.args.json b/ets2panda/linter/test/sdkwhite/decl_with_duplicate_name_sdk.ets.args.json old mode 100644 new mode 100755 similarity index 90% rename from ets2panda/linter/test/migrate/destructuring_declarations.ts.args.json rename to ets2panda/linter/test/sdkwhite/decl_with_duplicate_name_sdk.ets.args.json index 66b623df60..3ef4496a81 --- a/ets2panda/linter/test/migrate/destructuring_declarations.ts.args.json +++ b/ets2panda/linter/test/sdkwhite/decl_with_duplicate_name_sdk.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,6 @@ "limitations under the License." ], "mode": { - "migrate": "" + "arkts2": "" } } diff --git a/ets2panda/linter/test/sdkwhite/decl_with_duplicate_name_sdk.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/decl_with_duplicate_name_sdk.ets.arkts2.json new file mode 100644 index 0000000000..307e9a28a6 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/decl_with_duplicate_name_sdk.ets.arkts2.json @@ -0,0 +1,278 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 61, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 86, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 19, + "endLine": 23, + "endColumn": 28, + "problem": "DuplicateDeclNameFromSdk", + "suggest": "", + "rule": "API path have changed - please update your imports accordingly (sdk-no-decl-with-duplicate-name)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 35, + "endLine": 23, + "endColumn": 44, + "problem": "DuplicateDeclNameFromSdk", + "suggest": "", + "rule": "API path have changed - please update your imports accordingly (sdk-no-decl-with-duplicate-name)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 19, + "endLine": 24, + "endColumn": 28, + "problem": "DuplicateDeclNameFromSdk", + "suggest": "", + "rule": "API path have changed - please update your imports accordingly (sdk-no-decl-with-duplicate-name)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 27, + "endLine": 26, + "endColumn": 36, + "problem": "DuplicateDeclNameFromSdk", + "suggest": "", + "rule": "API path have changed - please update your imports accordingly (sdk-no-decl-with-duplicate-name)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 40, + "endLine": 26, + "endColumn": 51, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 14, + "endLine": 28, + "endColumn": 20, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 31, + "endLine": 29, + "endColumn": 40, + "problem": "DuplicateDeclNameFromSdk", + "suggest": "", + "rule": "API path have changed - please update your imports accordingly (sdk-no-decl-with-duplicate-name)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 38, + "endLine": 34, + "endColumn": 47, + "problem": "DuplicateDeclNameFromSdk", + "suggest": "", + "rule": "API path have changed - please update your imports accordingly (sdk-no-decl-with-duplicate-name)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 30, + "endLine": 44, + "endColumn": 39, + "problem": "DuplicateDeclNameFromSdk", + "suggest": "", + "rule": "API path have changed - please update your imports accordingly (sdk-no-decl-with-duplicate-name)", + "severity": "ERROR" + }, + { + "line": 50, + "column": 42, + "endLine": 50, + "endColumn": 60, + "problem": "DuplicateDeclNameFromSdk", + "suggest": "", + "rule": "API path have changed - please update your imports accordingly (sdk-no-decl-with-duplicate-name)", + "severity": "ERROR" + }, + { + "line": 51, + "column": 42, + "endLine": 51, + "endColumn": 60, + "problem": "DuplicateDeclNameFromSdk", + "suggest": "", + "rule": "API path have changed - please update your imports accordingly (sdk-no-decl-with-duplicate-name)", + "severity": "ERROR" + }, + { + "line": 53, + "column": 31, + "endLine": 53, + "endColumn": 49, + "problem": "DuplicateDeclNameFromSdk", + "suggest": "", + "rule": "API path have changed - please update your imports accordingly (sdk-no-decl-with-duplicate-name)", + "severity": "ERROR" + }, + { + "line": 54, + "column": 31, + "endLine": 54, + "endColumn": 49, + "problem": "DuplicateDeclNameFromSdk", + "suggest": "", + "rule": "API path have changed - please update your imports accordingly (sdk-no-decl-with-duplicate-name)", + "severity": "ERROR" + }, + { + "line": 57, + "column": 18, + "endLine": 57, + "endColumn": 36, + "problem": "DuplicateDeclNameFromSdk", + "suggest": "", + "rule": "API path have changed - please update your imports accordingly (sdk-no-decl-with-duplicate-name)", + "severity": "ERROR" + }, + { + "line": 58, + "column": 19, + "endLine": 58, + "endColumn": 37, + "problem": "DuplicateDeclNameFromSdk", + "suggest": "", + "rule": "API path have changed - please update your imports accordingly (sdk-no-decl-with-duplicate-name)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 2, + "endLine": 20, + "endColumn": 7, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 2, + "endLine": 21, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 57, + "endLine": 23, + "endColumn": 62, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 4, + "endLine": 26, + "endColumn": 9, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 5, + "endLine": 33, + "endColumn": 9, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 7, + "endLine": 34, + "endColumn": 14, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 9, + "endLine": 35, + "endColumn": 17, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 36, + "column": 11, + "endLine": 36, + "endColumn": 15, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 3, + "endLine": 24, + "endColumn": 17, + "problem": "StrictDiagnostic", + "suggest": "Property 'fontStyleAttr2' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'fontStyleAttr2' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/decl_with_duplicate_name_sdk.ets.json b/ets2panda/linter/test/sdkwhite/decl_with_duplicate_name_sdk.ets.json new file mode 100755 index 0000000000..489a1474b5 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/decl_with_duplicate_name_sdk.ets.json @@ -0,0 +1,48 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 61, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 86, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 3, + "endLine": 24, + "endColumn": 17, + "problem": "StrictDiagnostic", + "suggest": "Property 'fontStyleAttr2' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'fontStyleAttr2' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/limit_void_type_sdk.ets b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk.ets index 82bf1e5c60..a2886cecbb 100644 --- a/ets2panda/linter/test/sdkwhite/limit_void_type_sdk.ets +++ b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk.ets @@ -13,10 +13,32 @@ * limitations under the License. */ -import {IDataSourcePrefetching} from '@ohos.arkui.Prefetcher' +import { IDataSourcePrefetching } from '@kit.ArkUI'; +import DataSource from './limit_void_type_sdk2'; +import { prefetchTest as preTest } from './limit_void_type_sdk2'; +import { res } from './limit_void_type_sdk2'; +import { LocalDataSource } from './LimitedVoidType3'; +class DS implements IDataSourcePrefetching { + cancel(index: number): void | Promise { //report error + throw new Error('Method not implemented.'); + } -class C implements IDataSourcePrefetching { - prefetch(index: number): void | Promise { + totalCount(): number { + throw new Error('Method not implemented.'); + } + + getData(index: number): number { + throw new Error('Method not implemented.'); + } + + registerDataChangeListener(): void { + throw new Error('Method not implemented.'); + } + + unregisterDataChangeListener(): void { + throw new Error('Method not implemented.'); + } + prefetch(index: number): void | Promise { //report error } @@ -24,3 +46,35 @@ class C implements IDataSourcePrefetching { } } +const ds = new DataSource(); +let num:number=ds.totalCount(); +function testDataSource(){ + console.log(`${num}=num`); + ds.cancel(66); //report error +} +function testPrefetch() { + preTest(); +} + +function testCancel(){ + return res; +} + +class localDemo{ + dataSource:DS|undefined=undefined; + constructor() { + this.dataSource = new DS(); + } + test(){ + this.dataSource?.getData(111); + this.dataSource?.registerDataChangeListener(); + this.dataSource?.unregisterDataChangeListener(); + this.dataSource?.cancel(111); //report error + } +} +function localTest(){ + return ds.cancel(222); //report error +} +const lds = new LocalDataSource(); +lds.prefetch(999); +lds.cancel(222); diff --git a/ets2panda/linter/test/sdkwhite/limit_void_type_sdk.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk.ets.arkts2.json index f65500d7d1..3651742628 100644 --- a/ets2panda/linter/test/sdkwhite/limit_void_type_sdk.ets.arkts2.json +++ b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk.ets.arkts2.json @@ -15,19 +15,49 @@ ], "result": [ { - "line": 19, + "line": 41, "column": 3, - "endLine": 21, + "endLine": 43, "endColumn": 4, "problem": "LimitedVoidTypeFromSdk", "suggest": "", - "rule": "Type \"void\" has no instances.(arkts-sdk-limited-void-type)", + "rule": "Type \"void\" has no instances.(sdk-limited-void-type)", "severity": "ERROR" }, { - "line": 19, + "line": 22, + "column": 3, + "endLine": 24, + "endColumn": 4, + "problem": "OptionalMethodFromSdk", + "suggest": "", + "rule": "API no longer supports optional methods (sdk-optional-methods)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 3, + "endLine": 24, + "endColumn": 4, + "problem": "LimitedVoidTypeFromSdk", + "suggest": "", + "rule": "Type \"void\" has no instances.(sdk-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 26, + "endLine": 22, + "endColumn": 30, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 41, "column": 28, - "endLine": 19, + "endLine": 41, "endColumn": 32, "problem": "LimitedVoidType", "suggest": "", @@ -35,14 +65,64 @@ "severity": "ERROR" }, { - "line": 23, + "line": 45, "column": 29, - "endLine": 23, + "endLine": 45, "endColumn": 33, "problem": "LimitedVoidType", "suggest": "", "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", "severity": "ERROR" + }, + { + "line": 53, + "column": 3, + "endLine": 53, + "endColumn": 12, + "problem": "LimitedVoidTypeFromSdk", + "suggest": "", + "rule": "Type \"void\" has no instances.(sdk-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 5, + "endLine": 72, + "endColumn": 28, + "problem": "LimitedVoidTypeFromSdk", + "suggest": "", + "rule": "Type \"void\" has no instances.(sdk-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 76, + "column": 10, + "endLine": 76, + "endColumn": 19, + "problem": "LimitedVoidTypeFromSdk", + "suggest": "", + "rule": "Type \"void\" has no instances.(sdk-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 78, + "column": 7, + "endLine": 78, + "endColumn": 34, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 78, + "column": 17, + "endLine": 78, + "endColumn": 32, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/limit_void_type_sdk.ets.json b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk.ets.json index 5e75d5b3e7..e25d43a057 100644 --- a/ets2panda/linter/test/sdkwhite/limit_void_type_sdk.ets.json +++ b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk.ets.json @@ -14,6 +14,15 @@ "limitations under the License." ], "result": [ - + { + "line": 78, + "column": 7, + "endLine": 78, + "endColumn": 34, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/limit_void_type_sdk2.ets b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk2.ets index e768ba911c..4592f1a479 100644 --- a/ets2panda/linter/test/sdkwhite/limit_void_type_sdk2.ets +++ b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk2.ets @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +import { IDataSourcePrefetching } from '@kit.ArkUI'; import { rcp } from '@kit.RemoteCommunicationKit'; class LI implements rcp.WriteFile { write(buffer: ArrayBuffer): Promise { @@ -22,4 +22,40 @@ class LI implements rcp.WriteFile { const sp:rcp.IncomingDataCallback = (incomingData) => { console.log(''); -} \ No newline at end of file +} +export default class MyDataSource implements IDataSourcePrefetching { + constructor() {} + prefetch(index: number): void | Promise { //report error + throw new Error('MyDataSource Method not implemented.'); + } + + cancel(index: number): void | Promise { //report error + throw new Error('MyDataSource Method not implemented.'); + } + + totalCount(): number { + throw new Error('MyDataSource Method not implemented.'); + } + + getData(index: number): number { + throw new Error('MyDataSource Method not implemented.'); + } + + registerDataChangeListener(listener?: DataChangeListener): void { + throw new Error('MyDataSource Method not implemented.'); + } + + unregisterDataChangeListener(listener?: DataChangeListener): void { + throw new Error('MyDataSource Method not implemented.'); + } +} +const ds = new MyDataSource(); +export function prefetchTest(){ + return new MyDataSource().prefetch(666); //report error +} +function prefetchTest2(){ + return ds.prefetch(666); //report error +} + +export const res = new MyDataSource().cancel(222); //report error +export const res2 = ds.cancel(222); //report error \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/limit_void_type_sdk2.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk2.ets.arkts2.json index bd91b2508b..2a4a3080f0 100644 --- a/ets2panda/linter/test/sdkwhite/limit_void_type_sdk2.ets.arkts2.json +++ b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk2.ets.arkts2.json @@ -21,7 +21,17 @@ "endColumn": 4, "problem": "LimitedVoidTypeFromSdk", "suggest": "", - "rule": "Type \"void\" has no instances.(arkts-sdk-limited-void-type)", + "rule": "Type \"void\" has no instances.(sdk-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 3, + "endLine": 20, + "endColumn": 4, + "problem": "LimitedVoidTypeFromSdk", + "suggest": "", + "rule": "Type \"void\" has no instances.(sdk-limited-void-type)", "severity": "ERROR" }, { @@ -41,7 +51,7 @@ "endColumn": 34, "problem": "LimitedVoidTypeFromSdk", "suggest": "", - "rule": "Type \"void\" has no instances.(arkts-sdk-limited-void-type)", + "rule": "Type \"void\" has no instances.(sdk-limited-void-type)", "severity": "ERROR" }, { @@ -53,6 +63,116 @@ "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" + }, + { + "line": 28, + "column": 3, + "endLine": 30, + "endColumn": 4, + "problem": "LimitedVoidTypeFromSdk", + "suggest": "", + "rule": "Type \"void\" has no instances.(sdk-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 3, + "endLine": 34, + "endColumn": 4, + "problem": "OptionalMethodFromSdk", + "suggest": "", + "rule": "API no longer supports optional methods (sdk-optional-methods)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 3, + "endLine": 34, + "endColumn": 4, + "problem": "LimitedVoidTypeFromSdk", + "suggest": "", + "rule": "Type \"void\" has no instances.(sdk-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 28, + "endLine": 28, + "endColumn": 32, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 26, + "endLine": 32, + "endColumn": 30, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 54, + "column": 10, + "endLine": 54, + "endColumn": 37, + "problem": "LimitedVoidTypeFromSdk", + "suggest": "", + "rule": "Type \"void\" has no instances.(sdk-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 57, + "column": 10, + "endLine": 57, + "endColumn": 21, + "problem": "LimitedVoidTypeFromSdk", + "suggest": "", + "rule": "Type \"void\" has no instances.(sdk-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 60, + "column": 20, + "endLine": 60, + "endColumn": 45, + "problem": "LimitedVoidTypeFromSdk", + "suggest": "", + "rule": "Type \"void\" has no instances.(sdk-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 21, + "endLine": 61, + "endColumn": 30, + "problem": "LimitedVoidTypeFromSdk", + "suggest": "", + "rule": "Type \"void\" has no instances.(sdk-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 41, + "endLine": 44, + "endColumn": 59, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 48, + "column": 43, + "endLine": 48, + "endColumn": 61, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/LimitedVoidType3.ets b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk3.ets similarity index 65% rename from ets2panda/linter/test/sdkwhite/LimitedVoidType3.ets rename to ets2panda/linter/test/sdkwhite/limit_void_type_sdk3.ets index e3c4c6107c..e05617b2ff 100644 --- a/ets2panda/linter/test/sdkwhite/LimitedVoidType3.ets +++ b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk3.ets @@ -24,4 +24,21 @@ class LI implements rcp.WriteFile{ const simpleDataHandler: rcp.IncomingDataCallback = (incomingData) => { console.log(`Received ${incomingData.byteLength} bytes of data`); // Error -}; \ No newline at end of file +}; + +interface IDataSourcePrefetching { + prefetch(index: number): Promise | void; + + cancel?(index: number): Promise | void; +} +export class LocalDataSource implements IDataSourcePrefetching { + constructor() {} + + prefetch(index: number): void | Promise { + throw new Error("LocalDataSource Method not implemented."); + } + + cancel(index: number): void | Promise { + throw new Error("LocalDataSource Method not implemented."); + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/migrate/void_operator.ts.args.json b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk3.ets.args.json similarity index 97% rename from ets2panda/linter/test/migrate/void_operator.ts.args.json rename to ets2panda/linter/test/sdkwhite/limit_void_type_sdk3.ets.args.json index 18bd09a666..948b846fe0 100644 --- a/ets2panda/linter/test/migrate/void_operator.ts.args.json +++ b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk3.ets.args.json @@ -14,6 +14,6 @@ "limitations under the License." ], "mode": { - "migrate": "" + "arkts2": "" } } diff --git a/ets2panda/linter/test/migrate/parameter_properties.ts.json b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk3.ets.arkts2.json similarity index 43% rename from ets2panda/linter/test/migrate/parameter_properties.ts.json rename to ets2panda/linter/test/sdkwhite/limit_void_type_sdk3.ets.arkts2.json index 52dc9cb7b7..5d0e2d9cb6 100644 --- a/ets2panda/linter/test/migrate/parameter_properties.ts.json +++ b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk3.ets.arkts2.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2023-2024 Huawei Device Co., Ltd.", + "Copyright (c) 2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -16,102 +16,102 @@ "result": [ { "line": 18, - "column": 5, - "endLine": 18, - "endColumn": 11, - "problem": "ParameterProperties", + "column": 3, + "endLine": 20, + "endColumn": 4, + "problem": "LimitedVoidTypeFromSdk", "suggest": "", - "rule": "Declaring fields in \"constructor\" is not supported (arkts-no-ctor-prop-decls)", + "rule": "Type \"void\" has no instances.(sdk-limited-void-type)", "severity": "ERROR" }, { - "line": 19, - "column": 5, - "endLine": 19, - "endColumn": 14, - "problem": "ParameterProperties", + "line": 18, + "column": 3, + "endLine": 20, + "endColumn": 4, + "problem": "LimitedVoidTypeFromSdk", "suggest": "", - "rule": "Declaring fields in \"constructor\" is not supported (arkts-no-ctor-prop-decls)", + "rule": "Type \"void\" has no instances.(sdk-limited-void-type)", "severity": "ERROR" }, { - "line": 20, - "column": 5, - "endLine": 20, - "endColumn": 12, - "problem": "ParameterProperties", + "line": 18, + "column": 48, + "endLine": 18, + "endColumn": 52, + "problem": "LimitedVoidType", "suggest": "", - "rule": "Declaring fields in \"constructor\" is not supported (arkts-no-ctor-prop-decls)", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", "severity": "ERROR" }, { - "line": 34, + "line": 24, "column": 26, - "endLine": 34, - "endColumn": 32, - "problem": "ParameterProperties", + "endLine": 24, + "endColumn": 50, + "problem": "LimitedVoidTypeFromSdk", "suggest": "", - "rule": "Declaring fields in \"constructor\" is not supported (arkts-no-ctor-prop-decls)", + "rule": "Type \"void\" has no instances.(sdk-limited-void-type)", "severity": "ERROR" }, { - "line": 34, - "column": 60, - "endLine": 34, - "endColumn": 67, - "problem": "ParameterProperties", + "line": 24, + "column": 54, + "endLine": 24, + "endColumn": 66, + "problem": "AnyType", "suggest": "", - "rule": "Declaring fields in \"constructor\" is not supported (arkts-no-ctor-prop-decls)", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, { - "line": 43, - "column": 15, - "endLine": 43, - "endColumn": 21, - "problem": "ParameterProperties", + "line": 30, + "column": 44, + "endLine": 30, + "endColumn": 48, + "problem": "LimitedVoidType", "suggest": "", - "rule": "Declaring fields in \"constructor\" is not supported (arkts-no-ctor-prop-decls)", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", "severity": "ERROR" }, { - "line": 43, - "column": 25, - "endLine": 43, - "endColumn": 28, - "problem": "AnyType", + "line": 32, + "column": 9, + "endLine": 32, + "endColumn": 10, + "problem": "OptionalMethod", "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "rule": "Optional methods are not supported (arkts-optional-methods)", "severity": "ERROR" }, { - "line": 47, - "column": 15, - "endLine": 47, - "endColumn": 21, - "problem": "ParameterProperties", + "line": 32, + "column": 43, + "endLine": 32, + "endColumn": 47, + "problem": "LimitedVoidType", "suggest": "", - "rule": "Declaring fields in \"constructor\" is not supported (arkts-no-ctor-prop-decls)", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", "severity": "ERROR" }, { - "line": 47, - "column": 33, - "endLine": 47, - "endColumn": 40, - "problem": "ParameterProperties", + "line": 37, + "column": 28, + "endLine": 37, + "endColumn": 32, + "problem": "LimitedVoidType", "suggest": "", - "rule": "Declaring fields in \"constructor\" is not supported (arkts-no-ctor-prop-decls)", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", "severity": "ERROR" }, { - "line": 47, - "column": 44, - "endLine": 47, - "endColumn": 45, - "problem": "ObjectTypeLiteral", + "line": 41, + "column": 26, + "endLine": 41, + "endColumn": 30, + "problem": "LimitedVoidType", "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/sdkwhite/LimitedVoidType3.ets.json b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk3.ets.json similarity index 100% rename from ets2panda/linter/test/sdkwhite/LimitedVoidType3.ets.json rename to ets2panda/linter/test/sdkwhite/limit_void_type_sdk3.ets.json diff --git a/ets2panda/linter/test/sdkwhite/LiteralAsPropertyName2.ets b/ets2panda/linter/test/sdkwhite/literal_as_property_name_sdk.ets similarity index 97% rename from ets2panda/linter/test/sdkwhite/LiteralAsPropertyName2.ets rename to ets2panda/linter/test/sdkwhite/literal_as_property_name_sdk.ets index 3afff7ad6d..299f58ac32 100644 --- a/ets2panda/linter/test/sdkwhite/LiteralAsPropertyName2.ets +++ b/ets2panda/linter/test/sdkwhite/literal_as_property_name_sdk.ets @@ -26,5 +26,4 @@ function createHeaders(authToken?: string): rcp.RequestHeaders { 'cache-control': 'no-cache', // Error 'user-agent': 'MyApp/2.0' // Error }; -} - +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/literal_as_property_name_sdk.ets.args.json b/ets2panda/linter/test/sdkwhite/literal_as_property_name_sdk.ets.args.json new file mode 100644 index 0000000000..948b846fe0 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/literal_as_property_name_sdk.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} diff --git a/ets2panda/linter/test/migrate/literals_as_prop_names.ts.migrate.json b/ets2panda/linter/test/sdkwhite/literal_as_property_name_sdk.ets.arkts2.json similarity index 36% rename from ets2panda/linter/test/migrate/literals_as_prop_names.ts.migrate.json rename to ets2panda/linter/test/sdkwhite/literal_as_property_name_sdk.ets.arkts2.json index 3d8279213f..aafa0c6dae 100644 --- a/ets2panda/linter/test/migrate/literals_as_prop_names.ts.migrate.json +++ b/ets2panda/linter/test/sdkwhite/literal_as_property_name_sdk.ets.arkts2.json @@ -1,174 +1,138 @@ { + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], "result": [ { - "line": 20, - "column": 11, - "endLine": 20, - "endColumn": 12, - "problem": "LiteralAsPropertyName", + "line": 18, + "column": 3, + "endLine": 18, + "endColumn": 35, + "problem": "QuotedHyphenPropsDeprecated", "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", "severity": "ERROR" }, { - "line": 26, + "line": 18, "column": 3, - "endLine": 26, - "endColumn": 4, + "endLine": 18, + "endColumn": 18, "problem": "LiteralAsPropertyName", "suggest": "", "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, { - "line": 30, - "column": 13, - "endLine": 30, - "endColumn": 33, - "problem": "PropertyAccessByIndex", - "suggest": "", - "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", - "severity": "ERROR" - }, - { - "line": 31, - "column": 13, - "endLine": 31, - "endColumn": 29, - "problem": "PropertyAccessByIndex", + "line": 19, + "column": 3, + "endLine": 19, + "endColumn": 37, + "problem": "QuotedHyphenPropsDeprecated", "suggest": "", - "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", "severity": "ERROR" }, { - "line": 32, - "column": 13, - "endLine": 32, - "endColumn": 33, - "problem": "PropertyAccessByIndex", + "line": 19, + "column": 3, + "endLine": 19, + "endColumn": 17, + "problem": "LiteralAsPropertyName", "suggest": "", - "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, { - "line": 51, - "column": 9, - "endLine": 51, - "endColumn": 10, - "problem": "ObjectLiteralNoContextType", + "line": 24, + "column": 5, + "endLine": 24, + "endColumn": 67, + "problem": "QuotedHyphenPropsDeprecated", "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", "severity": "ERROR" }, { - "line": 51, - "column": 22, - "endLine": 51, - "endColumn": 23, + "line": 24, + "column": 5, + "endLine": 24, + "endColumn": 20, "problem": "LiteralAsPropertyName", "suggest": "", "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, { - "line": 53, - "column": 13, - "endLine": 53, - "endColumn": 22, - "problem": "PropertyAccessByIndex", + "line": 25, + "column": 5, + "endLine": 25, + "endColumn": 33, + "problem": "QuotedHyphenPropsDeprecated", "suggest": "", - "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", "severity": "ERROR" }, { - "line": 54, - "column": 13, - "endLine": 54, - "endColumn": 17, - "problem": "PropertyAccessByIndex", + "line": 25, + "column": 5, + "endLine": 25, + "endColumn": 13, + "problem": "LiteralAsPropertyName", "suggest": "", - "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, { - "line": 61, - "column": 13, - "endLine": 61, - "endColumn": 14, - "problem": "ObjectLiteralNoContextType", + "line": 26, + "column": 5, + "endLine": 26, + "endColumn": 32, + "problem": "QuotedHyphenPropsDeprecated", "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", "severity": "ERROR" }, { - "line": 69, - "column": 3, - "endLine": 69, - "endColumn": 4, + "line": 26, + "column": 5, + "endLine": 26, + "endColumn": 20, "problem": "LiteralAsPropertyName", "suggest": "", "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, { - "line": 74, - "column": 3, - "endLine": 74, - "endColumn": 4, - "problem": "LiteralAsPropertyName", + "line": 27, + "column": 5, + "endLine": 27, + "endColumn": 30, + "problem": "QuotedHyphenPropsDeprecated", "suggest": "", - "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", "severity": "ERROR" }, { - "line": 78, - "column": 36, - "endLine": 78, - "endColumn": 37, + "line": 27, + "column": 5, + "endLine": 27, + "endColumn": 17, "problem": "LiteralAsPropertyName", "suggest": "", "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" - }, - { - "line": 36, - "column": 11, - "endLine": 36, - "endColumn": 13, - "problem": "StrictDiagnostic", - "suggest": "Property '_2' has no initializer and is not definitely assigned in the constructor.", - "rule": "Property '_2' has no initializer and is not definitely assigned in the constructor.", - "severity": "ERROR" - }, - { - "line": 37, - "column": 3, - "endLine": 37, - "endColumn": 6, - "problem": "StrictDiagnostic", - "suggest": "Property 'Two' has no initializer and is not definitely assigned in the constructor.", - "rule": "Property 'Two' has no initializer and is not definitely assigned in the constructor.", - "severity": "ERROR" - }, - { - "line": 57, - "column": 12, - "endLine": 57, - "endColumn": 16, - "problem": "StrictDiagnostic", - "suggest": "Property 'name' has no initializer and is not definitely assigned in the constructor.", - "rule": "Property 'name' has no initializer and is not definitely assigned in the constructor.", - "severity": "ERROR" - }, - { - "line": 58, - "column": 12, - "endLine": 58, - "endColumn": 14, - "problem": "StrictDiagnostic", - "suggest": "Property '_2' has no initializer and is not definitely assigned in the constructor.", - "rule": "Property '_2' has no initializer and is not definitely assigned in the constructor.", - "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/literal_as_property_name_sdk.ets.json b/ets2panda/linter/test/sdkwhite/literal_as_property_name_sdk.ets.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/literal_as_property_name_sdk.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk.ets b/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk.ets old mode 100755 new mode 100644 index 10ed3b18e1..af08caf952 --- a/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk.ets +++ b/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk.ets @@ -1,31 +1,200 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import {rcp} from '@kit.RemoteCommunicationKit'; -// case1 -const basicHeaders: rcp.RequestHeaders = { - 'authorization': 'Bearer abc123', // error - 'content-type': 'application/json' // error -} - -// case2 -function createHeaders(): rcp.RequestHeaders { - return { - 'authorization': '', // error - 'accept': 'application/json', // error - 'cache-control': 'no-cache', // error - 'user-agent': 'MyApp/2.0' // error - }; -} \ No newline at end of file +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { rcp } from '@kit.RemoteCommunicationKit'; +import { externalRequestHeaders,externalRequestHeadersInterface } from './quoted_hyphen_props_deprecated_sdk2'; +import { externalResponseHeaders,externalResponseHeadersInterface } from './quoted_hyphen_props_deprecated_sdk2'; +export interface internalRequestHeaders { + rcpHeaders: rcp.RequestHeaders; + additionalHeaders: T; +} +interface AdditionalHeaders { + customHeader: string; +} +type CustomRequestHeaders = internalRequestHeaders; +const cusRequestHeaders: CustomRequestHeaders = { + rcpHeaders: { + 'content-type': 'application/json', // Error + range: 'bytes=0-1023' // Error + }, + additionalHeaders: { + customHeader: 'custom value' + } +}; +const basicHeaders: rcp.RequestHeaders = { + 'authorization': 'Bearer abc123', // Error + 'content-type': 'application/json' // Error +}; +basicHeaders.cookie =''; // Error +function createHeaders(cookie:string,authToken?: string): rcp.RequestHeaders { + return { + 'authorization': authToken ? `Bearer ${authToken}` : undefined, // Error + 'accept': 'application/json', // Error + 'cache-control': 'no-cache', // Error + 'user-agent': 'MyApp/2.0' // Error + }; +} +createHeaders(basicHeaders.cookie); // Error +function getRange(){ + return basicHeaders.range; // Error +} + +export type localRequestHeaders = rcp.RequestHeaders; +let localHeaders:localRequestHeaders = { + 'accept-charset': 'UTF-8', // Error + 'accept-encoding': 'gzip, deflate', // Error + 'accept-language': 'en-US,en;q=0.9', // Error + 'cookie': 'session_id=123456', // Error + 'range': 'bytes=0-1023', // Error + 'upgrade': 'websocket', // Error + 'content-type':'application/json' // Error +} +let externalHeaders:externalRequestHeaders = { + cookie: 'session_id=123456', // Error + range: 'bytes=0-1023', // Error + 'content-type':'application/json' // Error +} +const setRequestHeaders1 = (headers: externalRequestHeaders) => { + headers.authorization =''; // Error +} +class RemoteTest{ + setCookie(cookie:string){ + cookie = 'cookie' + } + createHeaders(cookie:string,authToken?: string): rcp.RequestHeaders { + return { + authorization: authToken ? `Bearer ${authToken}` : undefined, // Error + accept: 'application/json', // Error + "cache-control": 'no-cache', + "user-agent": 'MyApp/2.0', + upgrade:'web', // Error + range:'' // Error + }; + } + constructor() { + createHeaders(basicHeaders.authorization!); // Error + } +} +const exRequestHeadersInterface: externalRequestHeadersInterface = { + authorization: 'Bearer token', //Error + customHeader1: 'value1' +}; +function processHeaders(headers: externalRequestHeadersInterface) { + console.log(headers.authorization); //Error + console.log(headers.customHeader1); +} +function createExHeaders(): externalRequestHeadersInterface { + return { + authorization: 'Bearer token', //Error + customHeader1: 'value1' + }; +} +typeof exRequestHeadersInterface.authorization; //Error +console.log('accept='+exRequestHeadersInterface.accept) //Error +function printHeaders(exheaders: externalRequestHeadersInterface) { + console.log(exheaders.authorization); //Error +} +const headersArray: externalRequestHeadersInterface[] = [ + { + authorization: 'application/json', //Error + customHeader1: 'header1Value1' + }, + { + 'cookie': 'sss', //Error + customHeader1: 'header1Value2' + } +]; +interface RequestConfig { + headers: externalRequestHeadersInterface; + url: string; + method: 'GET' | 'POST'; +} + +const config: RequestConfig = { + headers: { + 'authorization': 'application/json', //Error + customHeader1: 'configHeaderValue' + }, + url: 'https://example.com/api', + method: 'GET' +}; +export const headers:string[]=[ + 'authorization', + 'accept', + 'cache-control', + 'user-agent', + 'accept-charset', + 'accept-encoding', + 'accept-language', + 'cookie', + 'range', + 'upgrade', + 'content-type' +] + +//ResponseHeader part +let externalResponseHeader:externalResponseHeaders = { + 'accept-ranges':'', // Error + 'allow': '', // Error + 'cache-control': '', // Error + 'content-encoding': '' // Error +} +const setResponseHeaders = (headers: externalResponseHeaders) => { + headers.expires =''; // Error +} + +const exResponseHeadersInterface: externalResponseHeadersInterface = { + "www-authenticate": 'Bearer token', + customHeader2: 'value1' +}; +function processResponseHeaders(responseHeaders: externalResponseHeadersInterface) { + console.log(responseHeaders.date); // Error + console.log(responseHeaders.customHeader2); +} +function createExResponseHeaders(): externalResponseHeadersInterface { + return { + date: '2025', //Error + customHeader2: 'value1' + }; +} +typeof exResponseHeadersInterface.authorization; //Error +console.log('accept='+exResponseHeadersInterface.accept) //Error +function printResponseHeaders(exHeaders: externalResponseHeadersInterface) { + console.log(exHeaders.etag); //Error +} +const responseHeadersArray: externalResponseHeadersInterface[] = [ + { + "cache-control": 'application/json', + customHeader2: 'header1Value1' + }, + { + 'server': 'sss', //Error + customHeader2: 'header1Value2' + } +]; +interface ResponseConfig { + headers: externalResponseHeadersInterface; + url: string; + method: 'GET' | 'POST'; +} + +const config2: ResponseConfig = { + headers: { + 'content-encoding': 'application/json', //Error + customHeader2: 'configHeaderValue' + }, + url: 'https://example.com/api', + method: 'GET' +}; \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk.ets.args.json b/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk.ets.args.json old mode 100755 new mode 100644 index 3ef4496a81..1b80aa9e73 --- a/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk.ets.args.json +++ b/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk.ets.args.json @@ -1,19 +1,19 @@ { - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "mode": { - "arkts2": "" - } -} + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } + } \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk.ets.arkts2.json old mode 100755 new mode 100644 index 381a73c1da..3a348d3c83 --- a/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk.ets.arkts2.json +++ b/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk.ets.arkts2.json @@ -15,123 +15,653 @@ ], "result": [ { - "line": 19, - "column": 3, - "endLine": 19, - "endColumn": 18, + "line": 29, + "column": 5, + "endLine": 29, + "endColumn": 39, "problem": "QuotedHyphenPropsDeprecated", "suggest": "", "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", "severity": "ERROR" }, { - "line": 20, + "line": 29, + "column": 5, + "endLine": 29, + "endColumn": 19, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 37, "column": 3, - "endLine": 20, - "endColumn": 17, + "endLine": 37, + "endColumn": 35, "problem": "QuotedHyphenPropsDeprecated", "suggest": "", "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", "severity": "ERROR" }, { - "line": 19, + "line": 37, "column": 3, - "endLine": 19, + "endLine": 37, "endColumn": 18, - "problem": "ObjectLiteralProperty", + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 3, + "endLine": 38, + "endColumn": 37, + "problem": "QuotedHyphenPropsDeprecated", "suggest": "", - "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", "severity": "ERROR" }, { - "line": 20, + "line": 38, "column": 3, - "endLine": 20, + "endLine": 38, "endColumn": 17, - "problem": "ObjectLiteralProperty", + "problem": "LiteralAsPropertyName", "suggest": "", - "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, { - "line": 26, + "line": 43, "column": 5, - "endLine": 26, + "endLine": 43, + "endColumn": 67, + "problem": "QuotedHyphenPropsDeprecated", + "suggest": "", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", + "severity": "ERROR" + }, + { + "line": 43, + "column": 5, + "endLine": 43, "endColumn": 20, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 5, + "endLine": 44, + "endColumn": 33, "problem": "QuotedHyphenPropsDeprecated", "suggest": "", "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", "severity": "ERROR" }, { - "line": 27, + "line": 44, "column": 5, - "endLine": 27, + "endLine": 44, "endColumn": 13, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 5, + "endLine": 45, + "endColumn": 32, "problem": "QuotedHyphenPropsDeprecated", "suggest": "", "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", "severity": "ERROR" }, { - "line": 28, + "line": 45, "column": 5, - "endLine": 28, + "endLine": 45, "endColumn": 20, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 46, + "column": 5, + "endLine": 46, + "endColumn": 30, "problem": "QuotedHyphenPropsDeprecated", "suggest": "", "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", "severity": "ERROR" }, { - "line": 29, + "line": 46, "column": 5, - "endLine": 29, + "endLine": 46, + "endColumn": 17, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 50, + "column": 10, + "endLine": 50, + "endColumn": 18, + "problem": "LimitedReturnTypeInference", + "suggest": "", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "severity": "ERROR" + }, + { + "line": 56, + "column": 3, + "endLine": 56, + "endColumn": 28, + "problem": "QuotedHyphenPropsDeprecated", + "suggest": "", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", + "severity": "ERROR" + }, + { + "line": 56, + "column": 3, + "endLine": 56, + "endColumn": 19, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 57, + "column": 3, + "endLine": 57, + "endColumn": 37, + "problem": "QuotedHyphenPropsDeprecated", + "suggest": "", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", + "severity": "ERROR" + }, + { + "line": 57, + "column": 3, + "endLine": 57, + "endColumn": 20, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 58, + "column": 3, + "endLine": 58, + "endColumn": 38, + "problem": "QuotedHyphenPropsDeprecated", + "suggest": "", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", + "severity": "ERROR" + }, + { + "line": 58, + "column": 3, + "endLine": 58, + "endColumn": 20, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 59, + "column": 3, + "endLine": 59, + "endColumn": 32, + "problem": "QuotedHyphenPropsDeprecated", + "suggest": "", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", + "severity": "ERROR" + }, + { + "line": 59, + "column": 3, + "endLine": 59, + "endColumn": 11, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 60, + "column": 3, + "endLine": 60, + "endColumn": 26, + "problem": "QuotedHyphenPropsDeprecated", + "suggest": "", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", + "severity": "ERROR" + }, + { + "line": 60, + "column": 3, + "endLine": 60, + "endColumn": 10, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 3, + "endLine": 61, + "endColumn": 25, + "problem": "QuotedHyphenPropsDeprecated", + "suggest": "", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 3, + "endLine": 61, + "endColumn": 12, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 62, + "column": 3, + "endLine": 62, + "endColumn": 36, + "problem": "QuotedHyphenPropsDeprecated", + "suggest": "", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", + "severity": "ERROR" + }, + { + "line": 62, + "column": 3, + "endLine": 62, "endColumn": 17, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 67, + "column": 3, + "endLine": 67, + "endColumn": 36, "problem": "QuotedHyphenPropsDeprecated", "suggest": "", "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", "severity": "ERROR" }, { - "line": 26, + "line": 67, + "column": 3, + "endLine": 67, + "endColumn": 17, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 80, + "column": 7, + "endLine": 80, + "endColumn": 22, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 81, + "column": 7, + "endLine": 81, + "endColumn": 19, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 90, + "column": 68, + "endLine": 90, + "endColumn": 69, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 99, + "column": 10, + "endLine": 99, + "endColumn": 11, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 109, + "column": 57, + "endLine": 118, + "endColumn": 2, + "problem": "ArrayLiteralNoContextType", + "suggest": "", + "rule": "Array literals must contain elements of only inferrable types (arkts-no-noninferrable-arr-literals)", + "severity": "ERROR" + }, + { + "line": 110, + "column": 3, + "endLine": 110, + "endColumn": 4, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 114, + "column": 3, + "endLine": 114, + "endColumn": 4, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 115, "column": 5, - "endLine": 26, + "endLine": 115, "endColumn": 20, - "problem": "ObjectLiteralProperty", + "problem": "QuotedHyphenPropsDeprecated", "suggest": "", - "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", "severity": "ERROR" }, { - "line": 27, + "line": 115, "column": 5, - "endLine": 27, + "endLine": 115, "endColumn": 13, - "problem": "ObjectLiteralProperty", + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 125, + "column": 31, + "endLine": 125, + "endColumn": 32, + "problem": "ObjectLiteralNoContextType", "suggest": "", - "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 126, + "column": 12, + "endLine": 126, + "endColumn": 13, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 127, + "column": 5, + "endLine": 127, + "endColumn": 40, + "problem": "QuotedHyphenPropsDeprecated", + "suggest": "", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", "severity": "ERROR" }, { - "line": 28, + "line": 127, "column": 5, - "endLine": 28, + "endLine": 127, "endColumn": 20, - "problem": "ObjectLiteralProperty", + "problem": "LiteralAsPropertyName", "suggest": "", - "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, { - "line": 29, + "line": 149, + "column": 3, + "endLine": 149, + "endColumn": 21, + "problem": "QuotedHyphenPropsDeprecated", + "suggest": "", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", + "severity": "ERROR" + }, + { + "line": 149, + "column": 3, + "endLine": 149, + "endColumn": 18, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 150, + "column": 3, + "endLine": 150, + "endColumn": 14, + "problem": "QuotedHyphenPropsDeprecated", + "suggest": "", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", + "severity": "ERROR" + }, + { + "line": 150, + "column": 3, + "endLine": 150, + "endColumn": 10, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 151, + "column": 3, + "endLine": 151, + "endColumn": 22, + "problem": "QuotedHyphenPropsDeprecated", + "suggest": "", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", + "severity": "ERROR" + }, + { + "line": 151, + "column": 3, + "endLine": 151, + "endColumn": 18, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 152, + "column": 3, + "endLine": 152, + "endColumn": 25, + "problem": "QuotedHyphenPropsDeprecated", + "suggest": "", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", + "severity": "ERROR" + }, + { + "line": 152, + "column": 3, + "endLine": 152, + "endColumn": 21, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 158, + "column": 70, + "endLine": 158, + "endColumn": 71, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 159, + "column": 3, + "endLine": 159, + "endColumn": 21, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 167, + "column": 10, + "endLine": 167, + "endColumn": 11, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 177, + "column": 66, + "endLine": 186, + "endColumn": 2, + "problem": "ArrayLiteralNoContextType", + "suggest": "", + "rule": "Array literals must contain elements of only inferrable types (arkts-no-noninferrable-arr-literals)", + "severity": "ERROR" + }, + { + "line": 178, + "column": 3, + "endLine": 178, + "endColumn": 4, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 179, "column": 5, - "endLine": 29, - "endColumn": 17, - "problem": "ObjectLiteralProperty", + "endLine": 179, + "endColumn": 20, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 182, + "column": 3, + "endLine": 182, + "endColumn": 4, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 183, + "column": 5, + "endLine": 183, + "endColumn": 20, + "problem": "QuotedHyphenPropsDeprecated", + "suggest": "", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", + "severity": "ERROR" + }, + { + "line": 183, + "column": 5, + "endLine": 183, + "endColumn": 13, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 193, + "column": 33, + "endLine": 193, + "endColumn": 34, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 194, + "column": 12, + "endLine": 194, + "endColumn": 13, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 195, + "column": 5, + "endLine": 195, + "endColumn": 43, + "problem": "QuotedHyphenPropsDeprecated", + "suggest": "", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", + "severity": "ERROR" + }, + { + "line": 195, + "column": 5, + "endLine": 195, + "endColumn": 23, + "problem": "LiteralAsPropertyName", "suggest": "", - "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk.ets.json b/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk.ets.json index ca88f857e9..eaeaa76976 100755 --- a/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk.ets.json +++ b/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk.ets.json @@ -13,5 +13,156 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "result": [] + "result": [ + { + "line": 50, + "column": 10, + "endLine": 50, + "endColumn": 18, + "problem": "LimitedReturnTypeInference", + "suggest": "", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "severity": "ERROR" + }, + { + "line": 90, + "column": 68, + "endLine": 90, + "endColumn": 69, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 99, + "column": 10, + "endLine": 99, + "endColumn": 11, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 109, + "column": 57, + "endLine": 118, + "endColumn": 2, + "problem": "ArrayLiteralNoContextType", + "suggest": "", + "rule": "Array literals must contain elements of only inferrable types (arkts-no-noninferrable-arr-literals)", + "severity": "ERROR" + }, + { + "line": 110, + "column": 3, + "endLine": 110, + "endColumn": 4, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 114, + "column": 3, + "endLine": 114, + "endColumn": 4, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 125, + "column": 31, + "endLine": 125, + "endColumn": 32, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 126, + "column": 12, + "endLine": 126, + "endColumn": 13, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 158, + "column": 70, + "endLine": 158, + "endColumn": 71, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 167, + "column": 10, + "endLine": 167, + "endColumn": 11, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 177, + "column": 66, + "endLine": 186, + "endColumn": 2, + "problem": "ArrayLiteralNoContextType", + "suggest": "", + "rule": "Array literals must contain elements of only inferrable types (arkts-no-noninferrable-arr-literals)", + "severity": "ERROR" + }, + { + "line": 178, + "column": 3, + "endLine": 178, + "endColumn": 4, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 182, + "column": 3, + "endLine": 182, + "endColumn": 4, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 193, + "column": 33, + "endLine": 193, + "endColumn": 34, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 194, + "column": 12, + "endLine": 194, + "endColumn": 13, + "problem": "ObjectLiteralNoContextType", + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + } + ] } \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk2.ets b/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk2.ets new file mode 100755 index 0000000000..18c729ed2e --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk2.ets @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { rcp } from "@kit.RemoteCommunicationKit"; +export type externalRequestHeaders = rcp.RequestHeaders; +export type externalResponseHeaders = rcp.ResponseHeaders; +export interface externalRequestHeadersInterface extends rcp.RequestHeaders { + customHeader1: string; +} +export interface externalResponseHeadersInterface extends rcp.ResponseHeaders { + customHeader2: string; +} +export const headers:string[]=[ + 'accept-ranges', + 'allow', + 'cache-control', + 'content-encoding', + 'content-range', + 'content-type', + 'date', + 'etag', + 'expires', + 'location', + 'retry-after', + 'set-cookie', + 'server', + 'www-authenticate', +] + +export default function getCookie():string{ + return headers[7]; +} +export const generateRange = () => 'range'; +export let localUpgrade:string = 'upgrade'; +export let localRange:string = generateRange(); +export class Header{ + acceptLanguage = headers[6]; + cookie = 'cookie'; + getUpgrade(){ + return localUpgrade; + } +} + +export interface internalResponseHeaders { + rcpHeaders: rcp.ResponseHeaders; + additionalHeaders: T; +} +interface AdditionalHeaders { + customHeader: string; +} +type CustomResponseHeaders = internalResponseHeaders; +const cusRequestHeaders: CustomResponseHeaders = { + rcpHeaders: { + 'content-range': 'json', // Error + server: 'bytes=0-1023' // Error + }, + additionalHeaders: { + customHeader: 'custom value' + } +}; +const basicHeaders: rcp.ResponseHeaders = { + "set-cookie": 'Bearer abc123', + 'retry-after': 'application/json' // Error +}; +basicHeaders.allow =''; // Error +function createHeaders(cookie:string,authToken?: string): rcp.ResponseHeaders { + return { + server: undefined, + expires: 'application/json', + 'accept-ranges': 'no-cache', // Error + 'www-authenticate': 'MyApp/2.0' // Error + }; +} +createHeaders(basicHeaders.date!); // Error +function getRange(){ + return basicHeaders?.["content-range"]; // Error +} + +export type localResponseHeaders = rcp.ResponseHeaders; +let localHeaders:localResponseHeaders = { + 'content-encoding': 'UTF-8', // Error + 'content-range': 'gzip, deflate', // Error + 'location': 'en-US,en;q=0.9', // Error + 'set-cookie': 'session_id=123456', // Error + 'accept-ranges': 'bytes=0-1023', // Error + 'www-authenticate': 'websocket', // Error + 'content-type':'application/json' // Error +} +class RemoteTest{ + setCookie(cookie:string){ + cookie = 'cookie' + } + createHeaders(cookie:string,authToken?: string): rcp.ResponseHeaders { + return { + 'accept-ranges': undefined, // Error + 'content-encoding': 'application/json', // Error + date: '2025', // Error + "cache-control": 'no', + allow:'web', // Error + 'www-authenticate':'' // Error + }; + } + constructor() { + createHeaders(basicHeaders.date!); // Error + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/migrate/func_return_type.ts.args.json b/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk2.ets.args.json old mode 100644 new mode 100755 similarity index 90% rename from ets2panda/linter/test/migrate/func_return_type.ts.args.json rename to ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk2.ets.args.json index 66b623df60..3ef4496a81 --- a/ets2panda/linter/test/migrate/func_return_type.ts.args.json +++ b/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk2.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,6 @@ "limitations under the License." ], "mode": { - "migrate": "" + "arkts2": "" } } diff --git a/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk2.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk2.ets.arkts2.json new file mode 100755 index 0000000000..f2d125c578 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk2.ets.arkts2.json @@ -0,0 +1,328 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 65, + "column": 5, + "endLine": 65, + "endColumn": 28, + "problem": "QuotedHyphenPropsDeprecated", + "suggest": "", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", + "severity": "ERROR" + }, + { + "line": 65, + "column": 5, + "endLine": 65, + "endColumn": 20, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 3, + "endLine": 73, + "endColumn": 15, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 74, + "column": 3, + "endLine": 74, + "endColumn": 36, + "problem": "QuotedHyphenPropsDeprecated", + "suggest": "", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", + "severity": "ERROR" + }, + { + "line": 74, + "column": 3, + "endLine": 74, + "endColumn": 16, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 81, + "column": 5, + "endLine": 81, + "endColumn": 32, + "problem": "QuotedHyphenPropsDeprecated", + "suggest": "", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", + "severity": "ERROR" + }, + { + "line": 81, + "column": 5, + "endLine": 81, + "endColumn": 20, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 82, + "column": 5, + "endLine": 82, + "endColumn": 36, + "problem": "QuotedHyphenPropsDeprecated", + "suggest": "", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", + "severity": "ERROR" + }, + { + "line": 82, + "column": 5, + "endLine": 82, + "endColumn": 23, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 86, + "column": 10, + "endLine": 86, + "endColumn": 18, + "problem": "LimitedReturnTypeInference", + "suggest": "", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "severity": "ERROR" + }, + { + "line": 92, + "column": 3, + "endLine": 92, + "endColumn": 30, + "problem": "QuotedHyphenPropsDeprecated", + "suggest": "", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", + "severity": "ERROR" + }, + { + "line": 92, + "column": 3, + "endLine": 92, + "endColumn": 21, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 93, + "column": 3, + "endLine": 93, + "endColumn": 35, + "problem": "QuotedHyphenPropsDeprecated", + "suggest": "", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", + "severity": "ERROR" + }, + { + "line": 93, + "column": 3, + "endLine": 93, + "endColumn": 18, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 94, + "column": 3, + "endLine": 94, + "endColumn": 31, + "problem": "QuotedHyphenPropsDeprecated", + "suggest": "", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", + "severity": "ERROR" + }, + { + "line": 94, + "column": 3, + "endLine": 94, + "endColumn": 13, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 95, + "column": 3, + "endLine": 95, + "endColumn": 36, + "problem": "QuotedHyphenPropsDeprecated", + "suggest": "", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", + "severity": "ERROR" + }, + { + "line": 95, + "column": 3, + "endLine": 95, + "endColumn": 15, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 96, + "column": 3, + "endLine": 96, + "endColumn": 34, + "problem": "QuotedHyphenPropsDeprecated", + "suggest": "", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", + "severity": "ERROR" + }, + { + "line": 96, + "column": 3, + "endLine": 96, + "endColumn": 18, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 97, + "column": 3, + "endLine": 97, + "endColumn": 34, + "problem": "QuotedHyphenPropsDeprecated", + "suggest": "", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", + "severity": "ERROR" + }, + { + "line": 97, + "column": 3, + "endLine": 97, + "endColumn": 21, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 98, + "column": 3, + "endLine": 98, + "endColumn": 36, + "problem": "QuotedHyphenPropsDeprecated", + "suggest": "", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", + "severity": "ERROR" + }, + { + "line": 98, + "column": 3, + "endLine": 98, + "endColumn": 17, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 106, + "column": 7, + "endLine": 106, + "endColumn": 34, + "problem": "QuotedHyphenPropsDeprecated", + "suggest": "", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", + "severity": "ERROR" + }, + { + "line": 106, + "column": 7, + "endLine": 106, + "endColumn": 22, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 107, + "column": 7, + "endLine": 107, + "endColumn": 45, + "problem": "QuotedHyphenPropsDeprecated", + "suggest": "", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", + "severity": "ERROR" + }, + { + "line": 107, + "column": 7, + "endLine": 107, + "endColumn": 25, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 109, + "column": 7, + "endLine": 109, + "endColumn": 22, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 111, + "column": 7, + "endLine": 111, + "endColumn": 28, + "problem": "QuotedHyphenPropsDeprecated", + "suggest": "", + "rule": "Object property names must be valid identifiers.Single-quoted and hyphenated properties are not supported. (sdk-no-literal-as-property-name)", + "severity": "ERROR" + }, + { + "line": 111, + "column": 7, + "endLine": 111, + "endColumn": 25, + "problem": "LiteralAsPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk2.ets.json b/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk2.ets.json new file mode 100755 index 0000000000..fe966ab865 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk2.ets.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 86, + "column": 10, + "endLine": 86, + "endColumn": 18, + "problem": "LimitedReturnTypeInference", + "suggest": "", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/return_new_interface.ets b/ets2panda/linter/test/sdkwhite/return_new_interface.ets new file mode 100644 index 0000000000..3bbb797d6d --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/return_new_interface.ets @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +'use static' + +interface CircleInterface { + config: any; +} + +interface RectInterface { + config: any; +} + +function makeCI(c: CircleInterface) { + return new c({}); // ERROR: using `new` with interface +} + +function makeRe(r: RectInterface) { + return new r({}); // ERROR +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/return_new_interface.ets.args.json b/ets2panda/linter/test/sdkwhite/return_new_interface.ets.args.json new file mode 100644 index 0000000000..bc4d2071da --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/return_new_interface.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} diff --git a/ets2panda/linter/test/sdkwhite/return_new_interface.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/return_new_interface.ets.arkts2.json new file mode 100644 index 0000000000..92f597960e --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/return_new_interface.ets.arkts2.json @@ -0,0 +1,98 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 11, + "endLine": 18, + "endColumn": 14, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 11, + "endLine": 22, + "endColumn": 14, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 10, + "endLine": 25, + "endColumn": 16, + "problem": "LimitedReturnTypeInference", + "suggest": "", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 14, + "endLine": 26, + "endColumn": 15, + "problem": "ConstructorIface", + "suggest": "", + "rule": "Construct signatures are not supported in interfaces (arkts-no-ctor-signatures-iface)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 14, + "endLine": 26, + "endColumn": 15, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 10, + "endLine": 29, + "endColumn": 16, + "problem": "LimitedReturnTypeInference", + "suggest": "", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 14, + "endLine": 30, + "endColumn": 15, + "problem": "ConstructorIface", + "suggest": "", + "rule": "Construct signatures are not supported in interfaces (arkts-no-ctor-signatures-iface)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 14, + "endLine": 30, + "endColumn": 15, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/return_new_interface.ets.json b/ets2panda/linter/test/sdkwhite/return_new_interface.ets.json new file mode 100644 index 0000000000..4cc659e3fd --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/return_new_interface.ets.json @@ -0,0 +1,58 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 18, + "column": 11, + "endLine": 18, + "endColumn": 14, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 11, + "endLine": 22, + "endColumn": 14, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 10, + "endLine": 25, + "endColumn": 16, + "problem": "LimitedReturnTypeInference", + "suggest": "", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 10, + "endLine": 29, + "endColumn": 16, + "problem": "LimitedReturnTypeInference", + "suggest": "", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/sdk/declarations/alert_dialog.d.ts b/ets2panda/linter/test/sdkwhite/sdk/declarations/alert_dialog.d.ts new file mode 100644 index 0000000000..1093278402 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/sdk/declarations/alert_dialog.d.ts @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export declare interface TextStyle { + wordBreak?: WordBreak; +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/sdk/declarations/hyperlink.d.ts b/ets2panda/linter/test/sdkwhite/sdk/declarations/hyperlink.d.ts new file mode 100644 index 0000000000..aaf5150b5e --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/sdk/declarations/hyperlink.d.ts @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export declare class HyperlinkAttribute { + color(value: Color | number | string | Resource): HyperlinkAttribute; +} +export declare const HyperlinkInterface: HyperlinkAttribute; \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/sdk/declarations/styled_string.d.ts b/ets2panda/linter/test/sdkwhite/sdk/declarations/styled_string.d.ts new file mode 100644 index 0000000000..fbdd125c2f --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/sdk/declarations/styled_string.d.ts @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export declare class TextStyle { + constructor(value?: TextStyleInterface); + readonly fontColor?: ResourceColor; + readonly fontFamily?: string; + readonly fontSize?: number; + readonly fontWeight?: number; + readonly fontStyle?: FontStyle; +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/constructor_types_deprecated_sdk.ets b/ets2panda/linter/test/sdkwhite/sdk_constructor_funcs.ets similarity index 100% rename from ets2panda/linter/test/sdkwhite/constructor_types_deprecated_sdk.ets rename to ets2panda/linter/test/sdkwhite/sdk_constructor_funcs.ets diff --git a/ets2panda/linter/test/sdkwhite/sdk_constructor_funcs.ets.args.json b/ets2panda/linter/test/sdkwhite/sdk_constructor_funcs.ets.args.json new file mode 100755 index 0000000000..9c3d973432 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/sdk_constructor_funcs.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/constructor_types_deprecated_sdk.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/sdk_constructor_funcs.ets.arkts2.json similarity index 100% rename from ets2panda/linter/test/sdkwhite/constructor_types_deprecated_sdk.ets.arkts2.json rename to ets2panda/linter/test/sdkwhite/sdk_constructor_funcs.ets.arkts2.json diff --git a/ets2panda/linter/test/sdkwhite/sdk_constructor_funcs.ets.json b/ets2panda/linter/test/sdkwhite/sdk_constructor_funcs.ets.json new file mode 100755 index 0000000000..9f305c86d7 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/sdk_constructor_funcs.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} diff --git a/ets2panda/linter/test/sdkwhite/ConstructorIface4.ets b/ets2panda/linter/test/sdkwhite/sdk_ctor_signatures_iface.ets similarity index 100% rename from ets2panda/linter/test/sdkwhite/ConstructorIface4.ets rename to ets2panda/linter/test/sdkwhite/sdk_ctor_signatures_iface.ets diff --git a/ets2panda/linter/test/migrate/destructuring_assignments.ts.args.json b/ets2panda/linter/test/sdkwhite/sdk_ctor_signatures_iface.ets.args.json similarity index 90% rename from ets2panda/linter/test/migrate/destructuring_assignments.ts.args.json rename to ets2panda/linter/test/sdkwhite/sdk_ctor_signatures_iface.ets.args.json index 66b623df60..3ef4496a81 100644 --- a/ets2panda/linter/test/migrate/destructuring_assignments.ts.args.json +++ b/ets2panda/linter/test/sdkwhite/sdk_ctor_signatures_iface.ets.args.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -14,6 +14,6 @@ "limitations under the License." ], "mode": { - "migrate": "" + "arkts2": "" } } diff --git a/ets2panda/linter/test/sdkwhite/ConstructorIface4.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/sdk_ctor_signatures_iface.ets.arkts2.json similarity index 100% rename from ets2panda/linter/test/sdkwhite/ConstructorIface4.ets.arkts2.json rename to ets2panda/linter/test/sdkwhite/sdk_ctor_signatures_iface.ets.arkts2.json diff --git a/ets2panda/linter/test/sdkwhite/sdk_ctor_signatures_iface.ets.json b/ets2panda/linter/test/sdkwhite/sdk_ctor_signatures_iface.ets.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/sdk_ctor_signatures_iface.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/OptionalMethod1.ets b/ets2panda/linter/test/sdkwhite/sdk_optional_methods.ets similarity index 50% rename from ets2panda/linter/test/sdkwhite/OptionalMethod1.ets rename to ets2panda/linter/test/sdkwhite/sdk_optional_methods.ets index 128f882768..c7a1a79f36 100644 --- a/ets2panda/linter/test/sdkwhite/OptionalMethod1.ets +++ b/ets2panda/linter/test/sdkwhite/sdk_optional_methods.ets @@ -14,6 +14,7 @@ */ import { webview } from '@kit.ArkWeb'; +import { AbilityLifecycleCallback, UIAbility } from '@kit.AbilityKit'; class OptionalMethod implements webview.NativeMediaPlayerBridge { updateRect(x: number, y: number, width: number, height: number): void { @@ -65,4 +66,47 @@ class OptionalMethod implements webview.NativeMediaPlayerBridge { } } +class MyAbilityLifecycleCallback extends AbilityLifecycleCallback { + // 用例1: 重写为必选方法 预期报错 用例结果--Error 未识别 + onWillNewWant(ability: UIAbility) { + console.log('AbilityLifecycleCallback onWillNewWant.'); + } + + // 用例2: 重写为可选方法 预期报错 用例结果--Pass + onAbilityWillCreate?(ability: UIAbility) { + console.log('AbilityLifecycleCallback onAbilityWillCreate.'); + } + + // 用例3:使用必选属性重写父类方法 预期无报错 用例结果--Pass + onAbilityWillForeground: (ability: UIAbility) => void = + (ability: UIAbility) => { + console.log('AbilityLifecycleCallback onAbilityWillForeground'); + } + // 用例4:使用可选属性重写父类方法 预期无报错 用例结果--Pass + onAbilityWillBackground?: (ability: UIAbility) => void = + (ability: UIAbility) => { + console.log('AbilityLifecycleCallback onAbilityWillBackground'); + } +} + +// 用例5 类型断言 预期无报错 用例结果--Pass +const callback: AbilityLifecycleCallback = { + onAbilityWillForeground: (ability: UIAbility): void => { + console.log('AbilityLifecycleCallback onAbilityWillForeground'); + } +} as AbilityLifecycleCallback; + +// 用例6 泛型类拓展 +class GenericHandler extends AbilityLifecycleCallback { + // 预期报错 用例结果--Error 未识别 + onAbilityWillCreate(ability: T): void { /*...*/ } + // 预期无报错 用例结果--Pass + onAbilityWillForeground: (ability: T) => void = + (ability: T) => { + console.log('AbilityLifecycleCallback onAbilityWillForeground'); + } +} + +// 接口不能继承类;不能使用交叉类型扩展;不能声明合并 + diff --git a/ets2panda/linter/test/sdkwhite/sdk_optional_methods.ets.args.json b/ets2panda/linter/test/sdkwhite/sdk_optional_methods.ets.args.json new file mode 100644 index 0000000000..948b846fe0 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/sdk_optional_methods.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} diff --git a/ets2panda/linter/test/sdkwhite/OptionalMethod1.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/sdk_optional_methods.ets.arkts2.json similarity index 54% rename from ets2panda/linter/test/sdkwhite/OptionalMethod1.ets.arkts2.json rename to ets2panda/linter/test/sdkwhite/sdk_optional_methods.ets.arkts2.json index d7b0f6777b..bd2e0891ba 100644 --- a/ets2panda/linter/test/sdkwhite/OptionalMethod1.ets.arkts2.json +++ b/ets2panda/linter/test/sdkwhite/sdk_optional_methods.ets.arkts2.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 59, + "line": 60, "column": 3, - "endLine": 61, + "endLine": 62, "endColumn": 4, "problem": "OptionalMethodFromSdk", "suggest": "", @@ -25,9 +25,9 @@ "severity": "ERROR" }, { - "line": 63, + "line": 64, "column": 3, - "endLine": 65, + "endLine": 66, "endColumn": 4, "problem": "OptionalMethodFromSdk", "suggest": "", @@ -35,9 +35,9 @@ "severity": "ERROR" }, { - "line": 59, + "line": 60, "column": 15, - "endLine": 59, + "endLine": 60, "endColumn": 16, "problem": "OptionalMethod", "suggest": "", @@ -45,14 +45,54 @@ "severity": "ERROR" }, { - "line": 63, + "line": 64, "column": 16, - "endLine": 63, + "endLine": 64, "endColumn": 17, "problem": "OptionalMethod", "suggest": "", "rule": "Optional methods are not supported (arkts-optional-methods)", "severity": "ERROR" + }, + { + "line": 76, + "column": 3, + "endLine": 78, + "endColumn": 4, + "problem": "OptionalMethodFromSdk", + "suggest": "", + "rule": "API no longer supports optional methods (sdk-optional-methods)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 3, + "endLine": 73, + "endColumn": 4, + "problem": "OptionalMethodFromSdk", + "suggest": "", + "rule": "API no longer supports optional methods (sdk-optional-methods)", + "severity": "ERROR" + }, + { + "line": 76, + "column": 22, + "endLine": 76, + "endColumn": 23, + "problem": "OptionalMethod", + "suggest": "", + "rule": "Optional methods are not supported (arkts-optional-methods)", + "severity": "ERROR" + }, + { + "line": 102, + "column": 3, + "endLine": 102, + "endColumn": 52, + "problem": "OptionalMethodFromSdk", + "suggest": "", + "rule": "API no longer supports optional methods (sdk-optional-methods)", + "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/sdk_optional_methods.ets.json b/ets2panda/linter/test/sdkwhite/sdk_optional_methods.ets.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/sdk_optional_methods.ets.json @@ -0,0 +1,17 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/IndexedAccessType.ets b/ets2panda/linter/test/sdkwhite/sdk_props_by_index.ets similarity index 100% rename from ets2panda/linter/test/sdkwhite/IndexedAccessType.ets rename to ets2panda/linter/test/sdkwhite/sdk_props_by_index.ets diff --git a/ets2panda/linter/test/sdkwhite/sdk_props_by_index.ets.args.json b/ets2panda/linter/test/sdkwhite/sdk_props_by_index.ets.args.json new file mode 100644 index 0000000000..948b846fe0 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/sdk_props_by_index.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} diff --git a/ets2panda/linter/test/sdkwhite/IndexedAccessType.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/sdk_props_by_index.ets.arkts2.json similarity index 100% rename from ets2panda/linter/test/sdkwhite/IndexedAccessType.ets.arkts2.json rename to ets2panda/linter/test/sdkwhite/sdk_props_by_index.ets.arkts2.json diff --git a/ets2panda/linter/test/sdkwhite/IndexedAccessType.ets.json b/ets2panda/linter/test/sdkwhite/sdk_props_by_index.ets.json similarity index 100% rename from ets2panda/linter/test/sdkwhite/IndexedAccessType.ets.json rename to ets2panda/linter/test/sdkwhite/sdk_props_by_index.ets.json diff --git a/ets2panda/linter/test/sdkwhite/sdk_type_query.ets b/ets2panda/linter/test/sdkwhite/sdk_type_query.ets index e975f42d4d..a8d6e79d57 100755 --- a/ets2panda/linter/test/sdkwhite/sdk_type_query.ets +++ b/ets2panda/linter/test/sdkwhite/sdk_type_query.ets @@ -13,10 +13,43 @@ * limitations under the License. */ -import {worker} from '@kit.ArkTS'; +import {worker} from '@kit.ArkTS'; // sdk-type-query report in real env +// // test1 +import sendablePhotoAccessHelper from '@ohos.file.sendablePhotoAccessHelper' // 报错 PASS + +// test2 +import mySendablePhotoAccessHelper from '@ohos.file.sendablePhotoAccessHelper' // 报错 PASS + +import { dataSharePredicates } from '@kit.ArkData'; +import { photoAccessHelper } from '@kit.MediaLibraryKit'; +import spHelper from '@ohos.file.sendablePhotoAccessHelper'; // Error-sendable不再支持 worker.parentPort.self; const self = worker.parentPort.self; -console.log(worker.parentPort.self) \ No newline at end of file +console.log(worker.parentPort.self) + +const parentPort = worker.parentPort; +parentPort.self.name; +parentPort.self.clearTimeout; + +const workerport = worker.workerPort; +workerport.self.name; +workerport.self.clearTimeout; + +let sHelper = spHelper.getPhotoAccessHelper(globalThis.abilityContext); +let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); +let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: predicates +}; +// Array +export const sharedPhotoAssetList = sHelper.getSharedPhotoAssets(fetchOptions); +sharedPhotoAssetList.forEach((asset, index) => { + let pt = asset.position // Error-position:PositionType不再可用-未识别 + let ps = asset.subtype // Error-subtype:PhotoSubtype不再可用-未识别 + let aa = asset.movingPhotoEffectMode // Error-movingPhotoEffectMode:MovingPhotoEffectMode 不再可用-未识别 + let bb = asset.dynamicRangeType // Error-dynamicRangeType:DynamicRangeType 不再可用-未识别 + let cc = asset.thumbnailVisible // Error-thumbnailVisible:ThumbnailVisibility 不再可用-未识别 +}); \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/sdk_type_query.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/sdk_type_query.ets.arkts2.json index d13b1aa522..67a42975bf 100755 --- a/ets2panda/linter/test/sdkwhite/sdk_type_query.ets.arkts2.json +++ b/ets2panda/linter/test/sdkwhite/sdk_type_query.ets.arkts2.json @@ -15,29 +15,49 @@ ], "result": [ { - "line": 16, - "column": 1, - "endLine": 16, - "endColumn": 35, - "problem": "LimitedStdLibApi", + "line": 18, + "column": 39, + "endLine": 18, + "endColumn": 77, + "problem": "SdkTypeQuery", "suggest": "", - "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", + "rule": "Using typeof as a type is not allowed in this API (sdk-type-query)", "severity": "ERROR" }, { - "line": 18, + "line": 21, + "column": 41, + "endLine": 21, + "endColumn": 79, + "problem": "SdkTypeQuery", + "suggest": "", + "rule": "Using typeof as a type is not allowed in this API (sdk-type-query)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 22, + "endLine": 25, + "endColumn": 60, + "problem": "SdkTypeQuery", + "suggest": "", + "rule": "Using typeof as a type is not allowed in this API (sdk-type-query)", + "severity": "ERROR" + }, + { + "line": 27, "column": 19, - "endLine": 18, + "endLine": 27, "endColumn": 23, "problem": "SdkTypeQuery", "suggest": "", - "rule": "Using typeof as a type is not allowed in this API (arkts-sdk-Type-Query)", + "rule": "Using typeof as a type is not allowed in this API (sdk-type-query)", "severity": "ERROR" }, { - "line": 20, + "line": 29, "column": 7, - "endLine": 20, + "endLine": 29, "endColumn": 36, "problem": "AnyType", "suggest": "", @@ -45,23 +65,243 @@ "severity": "ERROR" }, { - "line": 20, + "line": 29, "column": 32, - "endLine": 20, + "endLine": 29, "endColumn": 36, "problem": "SdkTypeQuery", "suggest": "", - "rule": "Using typeof as a type is not allowed in this API (arkts-sdk-Type-Query)", + "rule": "Using typeof as a type is not allowed in this API (sdk-type-query)", "severity": "ERROR" }, { - "line": 22, + "line": 31, "column": 31, - "endLine": 22, + "endLine": 31, "endColumn": 35, "problem": "SdkTypeQuery", "suggest": "", - "rule": "Using typeof as a type is not allowed in this API (arkts-sdk-Type-Query)", + "rule": "Using typeof as a type is not allowed in this API (sdk-type-query)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 7, + "endLine": 33, + "endColumn": 37, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 17, + "endLine": 34, + "endColumn": 21, + "problem": "SdkTypeQuery", + "suggest": "", + "rule": "Using typeof as a type is not allowed in this API (sdk-type-query)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 17, + "endLine": 35, + "endColumn": 29, + "problem": "SdkTypeQuery", + "suggest": "", + "rule": "Using typeof as a type is not allowed in this API (sdk-type-query)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 7, + "endLine": 37, + "endColumn": 37, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 17, + "endLine": 38, + "endColumn": 21, + "problem": "SdkTypeQuery", + "suggest": "", + "rule": "Using typeof as a type is not allowed in this API (sdk-type-query)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 17, + "endLine": 39, + "endColumn": 29, + "problem": "SdkTypeQuery", + "suggest": "", + "rule": "Using typeof as a type is not allowed in this API (sdk-type-query)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 5, + "endLine": 41, + "endColumn": 71, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 45, + "endLine": 41, + "endColumn": 70, + "problem": "GlobalThisError", + "suggest": "", + "rule": "\"globalThis\" is not supported (arkts-no-globalthis)", + "severity": "ERROR" + }, + { + "line": 42, + "column": 63, + "endLine": 42, + "endColumn": 102, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 48, + "column": 14, + "endLine": 48, + "endColumn": 79, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 31, + "endLine": 49, + "endColumn": 36, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 38, + "endLine": 49, + "endColumn": 43, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 50, + "column": 7, + "endLine": 50, + "endColumn": 26, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 50, + "column": 18, + "endLine": 50, + "endColumn": 26, + "problem": "SdkTypeQuery", + "suggest": "", + "rule": "Using typeof as a type is not allowed in this API (sdk-type-query)", + "severity": "ERROR" + }, + { + "line": 51, + "column": 7, + "endLine": 51, + "endColumn": 25, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 51, + "column": 18, + "endLine": 51, + "endColumn": 25, + "problem": "SdkTypeQuery", + "suggest": "", + "rule": "Using typeof as a type is not allowed in this API (sdk-type-query)", + "severity": "ERROR" + }, + { + "line": 52, + "column": 7, + "endLine": 52, + "endColumn": 39, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 52, + "column": 18, + "endLine": 52, + "endColumn": 39, + "problem": "SdkTypeQuery", + "suggest": "", + "rule": "Using typeof as a type is not allowed in this API (sdk-type-query)", + "severity": "ERROR" + }, + { + "line": 53, + "column": 7, + "endLine": 53, + "endColumn": 34, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 53, + "column": 18, + "endLine": 53, + "endColumn": 34, + "problem": "SdkTypeQuery", + "suggest": "", + "rule": "Using typeof as a type is not allowed in this API (sdk-type-query)", + "severity": "ERROR" + }, + { + "line": 54, + "column": 7, + "endLine": 54, + "endColumn": 34, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 54, + "column": 18, + "endLine": 54, + "endColumn": 34, + "problem": "SdkTypeQuery", + "suggest": "", + "rule": "Using typeof as a type is not allowed in this API (sdk-type-query)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/sdkwhite/sdk_type_query.ets.json b/ets2panda/linter/test/sdkwhite/sdk_type_query.ets.json index 41b84cda9d..0ab8ef5d47 100755 --- a/ets2panda/linter/test/sdkwhite/sdk_type_query.ets.json +++ b/ets2panda/linter/test/sdkwhite/sdk_type_query.ets.json @@ -15,14 +15,164 @@ ], "result": [ { - "line": 20, - "column": 7, - "endLine": 20, - "endColumn": 36, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" + "line": 18, + "column": 39, + "endLine": 18, + "endColumn": 77, + "problem": "SdkTypeQuery", + "suggest": "", + "rule": "Using typeof as a type is not allowed in this API (sdk-type-query)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 41, + "endLine": 21, + "endColumn": 79, + "problem": "SdkTypeQuery", + "suggest": "", + "rule": "Using typeof as a type is not allowed in this API (sdk-type-query)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 22, + "endLine": 25, + "endColumn": 60, + "problem": "SdkTypeQuery", + "suggest": "", + "rule": "Using typeof as a type is not allowed in this API (sdk-type-query)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 7, + "endLine": 29, + "endColumn": 36, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 7, + "endLine": 33, + "endColumn": 37, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 7, + "endLine": 37, + "endColumn": 37, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 5, + "endLine": 41, + "endColumn": 71, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 45, + "endLine": 41, + "endColumn": 55, + "problem": "GlobalThis", + "suggest": "", + "rule": "\"globalThis\" is not supported (arkts-no-globalthis)", + "severity": "WARNING" + }, + { + "line": 48, + "column": 14, + "endLine": 48, + "endColumn": 79, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 31, + "endLine": 49, + "endColumn": 36, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 38, + "endLine": 49, + "endColumn": 43, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 50, + "column": 7, + "endLine": 50, + "endColumn": 26, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 51, + "column": 7, + "endLine": 51, + "endColumn": 25, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 52, + "column": 7, + "endLine": 52, + "endColumn": 39, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 53, + "column": 7, + "endLine": 53, + "endColumn": 34, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 54, + "column": 7, + "endLine": 54, + "endColumn": 34, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" } - ] + ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/sendable_class_interface_property_sdk.ets b/ets2panda/linter/test/sdkwhite/sendable_class_interface_property_sdk.ets similarity index 92% rename from ets2panda/linter/test/main/sendable_class_interface_property_sdk.ets rename to ets2panda/linter/test/sdkwhite/sendable_class_interface_property_sdk.ets index 3b39666b33..6b0535ba89 100644 --- a/ets2panda/linter/test/main/sendable_class_interface_property_sdk.ets +++ b/ets2panda/linter/test/sdkwhite/sendable_class_interface_property_sdk.ets @@ -13,5 +13,6 @@ * limitations under the License. */ +// they both is not in sdkwhitelist after updated sdkwhitelist. import { SharedPhotoAsset } from '@ohos.file.sendablePhotoAccessHelper'; import { SharedPhotoAsset } from '@ohos.file.photoAccessHelper'; diff --git a/ets2panda/linter/test/sdkwhite/sendable_class_interface_property_sdk.ets.args.json b/ets2panda/linter/test/sdkwhite/sendable_class_interface_property_sdk.ets.args.json new file mode 100644 index 0000000000..d8d3390ad9 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/sendable_class_interface_property_sdk.ets.args.json @@ -0,0 +1,19 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "mode": { + "arkts2": "" + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/sendable_class_interface_property_sdk.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/sendable_class_interface_property_sdk.ets.arkts2.json similarity index 74% rename from ets2panda/linter/test/main/sendable_class_interface_property_sdk.ets.arkts2.json rename to ets2panda/linter/test/sdkwhite/sendable_class_interface_property_sdk.ets.arkts2.json index 824e83e4a1..c65d038d23 100644 --- a/ets2panda/linter/test/main/sendable_class_interface_property_sdk.ets.arkts2.json +++ b/ets2panda/linter/test/sdkwhite/sendable_class_interface_property_sdk.ets.arkts2.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 2024 Huawei Device Co., Ltd.", + "Copyright (c) 2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", "You may obtain a copy of the License at", @@ -15,13 +15,13 @@ ], "result": [ { - "line": 16, + "line": 17, "column": 34, - "endLine": 16, + "endLine": 17, "endColumn": 72, - "problem": "SendablePropTypeFromSdk", + "problem": "SdkTypeQuery", "suggest": "", - "rule": "Properties in \"Sendable\" classes and interfaces must have a Sendable data type (sdk-no-sendable-prop-types)", + "rule": "Using typeof as a type is not allowed in this API (sdk-type-query)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/sdkwhite/sendable_class_interface_property_sdk.ets.json b/ets2panda/linter/test/sdkwhite/sendable_class_interface_property_sdk.ets.json new file mode 100644 index 0000000000..eecd9ba0f4 --- /dev/null +++ b/ets2panda/linter/test/sdkwhite/sendable_class_interface_property_sdk.ets.json @@ -0,0 +1,28 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 17, + "column": 34, + "endLine": 17, + "endColumn": 72, + "problem": "SdkTypeQuery", + "suggest": "", + "rule": "Using typeof as a type is not allowed in this API (sdk-type-query)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/webpack.config.js b/ets2panda/linter/webpack.config.js index f8269189a8..15ee37c29b 100644 --- a/ets2panda/linter/webpack.config.js +++ b/ets2panda/linter/webpack.config.js @@ -25,5 +25,10 @@ module.exports = { }, output: { filename: 'tslinter.js' - } + }, + resolve: { + alias: { + json5: require.resolve('json5/dist/index.js'), + } + } }; -- Gitee From 3f119207ff2318d8fd6ddf1ca1e381448ac30518 Mon Sep 17 00:00:00 2001 From: zhangkai366 Date: Sat, 17 May 2025 15:10:09 +0800 Subject: [PATCH 213/268] Modify the duplicated code snippet Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC8HP4 Test: grammar&ut Signed-off-by: zhangkai366 Change-Id: I73b8537365335417ac3baaa02096da527356962d --- .../advanced_type/intersection_types.ts | 37 ++++++++++--------- .../grammar/advanced_type/predefined_types.ts | 16 ++++---- .../predefined_types_expected.txt | 37 +++++++++++++++++++ ...umericLiteralsWithTrailingDecimalPoints.ts | 32 ++++++++-------- ...ralsWithTrailingDecimalPoints_expected.txt | 2 +- ...WithTrailingDecimalPoints_expected_map.txt | 2 +- .../interface_class_method.ts | 22 +++++------ .../grammar/module_validation/name_space.ts | 36 +++++++++--------- 8 files changed, 110 insertions(+), 74 deletions(-) create mode 100644 arkguard/test/grammar/advanced_type/predefined_types_expected.txt diff --git a/arkguard/test/grammar/advanced_type/intersection_types.ts b/arkguard/test/grammar/advanced_type/intersection_types.ts index 182de6165a..6d4457b850 100644 --- a/arkguard/test/grammar/advanced_type/intersection_types.ts +++ b/arkguard/test/grammar/advanced_type/intersection_types.ts @@ -15,35 +15,36 @@ import assert = require('assert'); -function extend(first: T, second: U): T & U { - let result = {}; - for (let id in first) { - (result)[id] = (first)[id]; +function mergeObjects(primary: T, secondary: U): T & U { + const merged = {} as T & U; + + for (const prop in primary) { + merged[prop] = primary[prop] as any; } - for (let id in second) { - if (!result.hasOwnProperty(id)) { - (result)[id] = (second)[id]; + + for (const prop in secondary) { + if (!Object.prototype.hasOwnProperty.call(merged, prop)) { + merged[prop] = secondary[prop] as any; } } - return result; + return merged; } -class Person { - constructor(public name: string) { - } +class Human { + constructor(public username: string) {} } -interface Loggable { - log(): void; +interface LoggingCapability { + writeLog(): void; } -class ConsoleLogger implements Loggable { - log(): void { +class TerminalLogger implements LoggingCapability { + writeLog(): void { console.log('Jim'); } } -const jim = extend(new Person('Jim'), new ConsoleLogger()); -const n = jim.name; +const user = mergeObjects(new Human('Jim'), new TerminalLogger()); +const currentUser = user.username; -assert(n === 'Jim', 'success'); +assert(currentUser === 'Jim', 'success'); diff --git a/arkguard/test/grammar/advanced_type/predefined_types.ts b/arkguard/test/grammar/advanced_type/predefined_types.ts index 22d55829e5..d12d9d5aca 100644 --- a/arkguard/test/grammar/advanced_type/predefined_types.ts +++ b/arkguard/test/grammar/advanced_type/predefined_types.ts @@ -13,8 +13,6 @@ * limitations under the License. */ -import assert = require('assert'); - type T00 = Exclude<'a' | 'b' | 'c' | 'd', 'a' | 'c' | 'f'>; // 'b' | 'd' type T01 = Extract<'a' | 'b' | 'c' | 'd', 'a' | 'c' | 'f'>; // 'a' | 'c' @@ -33,13 +31,13 @@ class C { y = 0; } -type T10 = ReturnType<() => string>; // string -type T11 = ReturnType<(s: string) => void>; // void -type T12 = ReturnType<(() => T)>; // {} -type T13 = ReturnType<(() => T)>; // number[] -type T14 = ReturnType; // { a: number, b: string } -type T15 = ReturnType; // any -type T16 = ReturnType; // any +type ResultString = ReturnType<() => string>; // string +type ResultVoid = ReturnType<(s: string) => void>; // void +type ResultGeneric = ReturnType<(() => T)>; // {} +type ResultConstrained = ReturnType<(() => T)>; // number[] +type ResultInstance = ReturnType; // { a: number, b: string } +type ResultAny = ReturnType; // any +type ResultNever = ReturnType; // any type T20 = InstanceType; // C type T21 = InstanceType; // any diff --git a/arkguard/test/grammar/advanced_type/predefined_types_expected.txt b/arkguard/test/grammar/advanced_type/predefined_types_expected.txt new file mode 100644 index 0000000000..b22f02196e --- /dev/null +++ b/arkguard/test/grammar/advanced_type/predefined_types_expected.txt @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the 'License'); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an 'AS IS' BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +type l1 = Exclude<'a' | 'b' | 'c' | 'd', 'a' | 'c' | 'f'>; // 'b' | 'd' +type m1 = Extract<'a' | 'b' | 'c' | 'd', 'a' | 'c' | 'f'>; // 'a' | 'c' +type n1 = Exclude void), Function>; // string | number +type o1 = Extract void), Function>; // () => void +type q1 = NonNullable; // string | number +type s1 = NonNullable<(() => string) | string[] | null | undefined>; // (() => string) | string[] +function j1(g2: string): any { + return { a: 1, b: g2 }; +} +class t1 { + x = 0; + y = 0; +} +type u1 = ReturnType<() => string>; // string +type v1 = ReturnType<(s: string) => void>; // void +type w1 = ReturnType<(() => T)>; // {} +type z1 = ReturnType<(() => T)>; // number[] +type a2 = ReturnType; // { a: number, b: string } +type b2 = ReturnType; // any +type c2 = ReturnType; // any +type d2 = InstanceType; // C +type e2 = InstanceType; // any +type f2 = InstanceType; // any diff --git a/arkguard/test/grammar/compact/numericLiteralsWithTrailingDecimalPoints.ts b/arkguard/test/grammar/compact/numericLiteralsWithTrailingDecimalPoints.ts index ff33413147..4b9cb71089 100644 --- a/arkguard/test/grammar/compact/numericLiteralsWithTrailingDecimalPoints.ts +++ b/arkguard/test/grammar/compact/numericLiteralsWithTrailingDecimalPoints.ts @@ -18,33 +18,33 @@ 1. + 2.0 + 3.; var i: number = 1; -var test1 = i.toString(); -var test3 = 3 .toString(); -var test4 = 3 .toString(); -var test5 = 3 .toString(); -var test6 = 3.['toString'](); -var test7 = 3 +var compactTest1 = i.toString(); +var compactTest3 = 3 .toString(); +var compactTest4 = 3 .toString(); +var compactTest5 = 3 .toString(); +var compactTest6 = 3.['toString'](); +var compactTest7 = 3 .toString(); -var test8 = new Number(4).toString(); -var test9 = 3. + 3.; -var test10 = 0 /* comment */.toString(); -var test11 = 3. /* comment */.toString(); -var test12 = 3 +var compactTest8 = new Number(4).toString(); +var compactTest9 = 3. + 3.; +var compactTest10 = 0 /* comment */.toString(); +var compactTest11 = 3. /* comment */.toString(); +var compactTest12 = 3 /* comment */ .toString(); var test122 = 3 /* comment */.toString(); var test1222 = 3 .toString(); -var test13 = 3. +var compactTest13 = 3. /* comment */.toString(); -var test14 = 3 +var compactTest14 = 3 // comment .toString(); -var test15 = 3. +var compactTest15 = 3. // comment .toString(); -var test16 = 3 // comment time +var compactTest16 = 3 // comment time .toString(); -var test17 = 3. // comment time again +var compactTest17 = 3. // comment time again .toString(); \ No newline at end of file diff --git a/arkguard/test/grammar/compact/numericLiteralsWithTrailingDecimalPoints_expected.txt b/arkguard/test/grammar/compact/numericLiteralsWithTrailingDecimalPoints_expected.txt index c00d3215e5..91796cd9c1 100644 --- a/arkguard/test/grammar/compact/numericLiteralsWithTrailingDecimalPoints_expected.txt +++ b/arkguard/test/grammar/compact/numericLiteralsWithTrailingDecimalPoints_expected.txt @@ -1 +1 @@ -1..toString();1.0.toString();1. + 2.0 + 3.;var i: number = 1;var test1 = i.toString();var test3 = 3..toString();var test4 = 3..toString();var test5 = 3..toString();var test6 = 3.['toString']();var test7 = 3 .toString();var test8 = new Number(4).toString();var test9 = 3. + 3.;var test10 = 0 .toString();var test11 = 3. .toString();var test12 = 3 .toString();var test122 = 3 .toString();var test1222 = 3 .toString();var test13 = 3. .toString();var test14 = 3 .toString();var test15 = 3. .toString();var test16 = 3 .toString();var test17 = 3. .toString(); \ No newline at end of file +1..toString();1.0.toString();1. + 2.0 + 3.;var i: number = 1;var compactTest1 = i.toString();var compactTest3 = 3..toString();var compactTest4 = 3..toString();var compactTest5 = 3..toString();var compactTest6 = 3.['toString']();var compactTest7 = 3 .toString();var compactTest8 = new Number(4).toString();var compactTest9 = 3. + 3.;var compactTest10 = 0 .toString();var compactTest11 = 3. .toString();var compactTest12 = 3 .toString();var test122 = 3 .toString();var test1222 = 3 .toString();var compactTest13 = 3. .toString();var compactTest14 = 3 .toString();var compactTest15 = 3. .toString();var compactTest16 = 3 .toString();var compactTest17 = 3. .toString(); \ No newline at end of file diff --git a/arkguard/test/grammar/compact/numericLiteralsWithTrailingDecimalPoints_expected_map.txt b/arkguard/test/grammar/compact/numericLiteralsWithTrailingDecimalPoints_expected_map.txt index 4e7f94de3f..69efdc4f7c 100644 --- a/arkguard/test/grammar/compact/numericLiteralsWithTrailingDecimalPoints_expected_map.txt +++ b/arkguard/test/grammar/compact/numericLiteralsWithTrailingDecimalPoints_expected_map.txt @@ -6,5 +6,5 @@ "test/grammar/compact/numericLiteralsWithTrailingDecimalPoints.ts" ], "names": [], - "mappings": "AAeA,EAAE,CAAC,QAAQ,EAAE,CACb,GAAG,CAAC,QAAQ,EAAE,CACd,EAAE,GAAG,GAAG,GAAG,EAAE,CAEb,IAAI,CAAC,EAAE,MAAM,GAAG,CAAC,CACjB,IAAI,KAAK,GAAG,CAAC,CAAC,QAAQ,EAAE,CACxB,IAAI,KAAK,GAAG,CAAC,EAAE,QAAQ,EAAE,CACzB,IAAI,KAAK,GAAG,CAAC,EAAK,QAAQ,EAAE,CAC5B,IAAI,KAAK,GAAG,CAAC,EAAE,QAAQ,EAAE,CACzB,IAAI,KAAK,GAAG,EAAE,CAAC,UAAU,CAAC,EAAE,CAC5B,IAAI,KAAK,GAAG,CAAC,EACV,QAAQ,EAAE,CACb,IAAI,KAAK,GAAG,IAAI,MAAM,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE,CACpC,IAAI,KAAK,GAAG,EAAE,GAAG,EAAE,CACnB,IAAI,MAAM,GAAG,CAAC,CAAc,CAAC,QAAQ,EAAE,CACvC,IAAI,MAAM,GAAG,EAAE,CAAc,CAAC,QAAQ,EAAE,CACxC,IAAI,MAAM,GAAG,CAAC,CACC,EAAE,QAAQ,EAAE,CAC3B,IAAI,OAAO,GAAG,CAAC,CACF,EAAC,QAAQ,EAAE,CACxB,IAAI,QAAQ,GAAG,CAAC,EAEb,QAAQ,EAAE,CACb,IAAI,MAAM,GAAG,EAAE,CACA,EAAC,QAAQ,EAAE,CAC1B,IAAI,MAAM,GAAG,CAAC,CACF,CACT,QAAQ,EAAE,CACb,IAAI,MAAM,GAAG,EAAE,CACH,CACT,QAAQ,EAAE,CACb,IAAI,MAAM,GAAG,CAAC,CAAiB,CAC5B,QAAQ,EAAE,CACb,IAAI,MAAM,GAAG,EAAE,CAAsB,CAClC,QAAQ,EAAE,CAAC" + "mappings": "AAeA,EAAE,CAAC,QAAQ,EAAE,CACb,GAAG,CAAC,QAAQ,EAAE,CACd,EAAE,GAAG,GAAG,GAAG,EAAE,CAEb,IAAI,CAAC,EAAE,MAAM,GAAG,CAAC,CACjB,IAAI,YAAY,GAAG,CAAC,CAAC,QAAQ,EAAE,CAC/B,IAAI,YAAY,GAAG,CAAC,EAAE,QAAQ,EAAE,CAChC,IAAI,YAAY,GAAG,CAAC,EAAK,QAAQ,EAAE,CACnC,IAAI,YAAY,GAAG,CAAC,EAAE,QAAQ,EAAE,CAChC,IAAI,YAAY,GAAG,EAAE,CAAC,UAAU,CAAC,EAAE,CACnC,IAAI,YAAY,GAAG,CAAC,EACjB,QAAQ,EAAE,CACb,IAAI,YAAY,GAAG,IAAI,MAAM,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE,CAC3C,IAAI,YAAY,GAAG,EAAE,GAAG,EAAE,CAC1B,IAAI,aAAa,GAAG,CAAC,CAAc,CAAC,QAAQ,EAAE,CAC9C,IAAI,aAAa,GAAG,EAAE,CAAc,CAAC,QAAQ,EAAE,CAC/C,IAAI,aAAa,GAAG,CAAC,CACN,EAAE,QAAQ,EAAE,CAC3B,IAAI,OAAO,GAAG,CAAC,CACF,EAAC,QAAQ,EAAE,CACxB,IAAI,QAAQ,GAAG,CAAC,EAEb,QAAQ,EAAE,CACb,IAAI,aAAa,GAAG,EAAE,CACP,EAAC,QAAQ,EAAE,CAC1B,IAAI,aAAa,GAAG,CAAC,CACT,CACT,QAAQ,EAAE,CACb,IAAI,aAAa,GAAG,EAAE,CACV,CACT,QAAQ,EAAE,CACb,IAAI,aAAa,GAAG,CAAC,CAAiB,CACnC,QAAQ,EAAE,CACb,IAAI,aAAa,GAAG,EAAE,CAAsB,CACzC,QAAQ,EAAE,CAAC" } \ No newline at end of file diff --git a/arkguard/test/grammar/interface_validation/interface_class_method.ts b/arkguard/test/grammar/interface_validation/interface_class_method.ts index f9bea5f4f4..1636c31168 100644 --- a/arkguard/test/grammar/interface_validation/interface_class_method.ts +++ b/arkguard/test/grammar/interface_validation/interface_class_method.ts @@ -15,27 +15,27 @@ import assert = require('assert'); -interface ClockInterface { - currentTime: Date; +interface TimepieceInterface { + currentDateTime: Date; - setTime(d: Date); + updateTime(newTime: Date); } -class Clock implements ClockInterface { - currentTime: Date; +class WallClock implements TimepieceInterface { + currentDateTime: Date; - setTime(d: Date) { - this.currentTime = d; + updateTime(newTime: Date) { + this.currentDateTime = newTime; } - constructor(h: number, m: number) { + constructor(hour: number, minute: number) { } } -let nowClock = new Clock(3, 20); +let nowClock = new WallClock(3, 20); let now = Date.prototype; -nowClock.setTime(now); +nowClock.updateTime(now); -assert(nowClock.currentTime === now, 'success'); \ No newline at end of file +assert(nowClock.currentDateTime === now, 'success'); \ No newline at end of file diff --git a/arkguard/test/grammar/module_validation/name_space.ts b/arkguard/test/grammar/module_validation/name_space.ts index bc9379802a..582fb79513 100644 --- a/arkguard/test/grammar/module_validation/name_space.ts +++ b/arkguard/test/grammar/module_validation/name_space.ts @@ -15,33 +15,33 @@ import assert = require('assert'); -interface StringValidator { - isAcceptable(s: string): boolean; +interface TextValidationRule { + isValid(text: string): boolean; } -let lettersRegexp = /^[A-Za-z]+$/; -let numberRegexp = /^[0-9]+$/; +const alphabeticPattern = /^[A-Za-z]+$/; +const numericPattern = /^[0-9]+$/; -class LettersOnlyValidator implements StringValidator { - isAcceptable(s: string) { - return lettersRegexp.test(s); +class AlphabeticalValidator implements TextValidationRule { + isValid(text: string) { + return alphabeticPattern.test(text); } } -class ZipCodeValidator implements StringValidator { - isAcceptable(s: string) { - return s.length === 5 && numberRegexp.test(s); +class PostalCodeValidator implements TextValidationRule { + isValid(text: string) { + return text.length === 5 && numericPattern.test(text); } } -// Some samples to try -let strings = ["Hello", "98052", "101"]; +// Test cases +const testInputs = ["Hello", "98052", "101"]; -// Validators to use -let validators: { [s: string]: StringValidator; } = {}; -validators["ZIP code"] = new ZipCodeValidator(); -validators["Letters only"] = new LettersOnlyValidator(); +// Validation registry +const validationRules: { [ruleName: string]: TextValidationRule } = {}; +validationRules["Postal Code"] = new PostalCodeValidator(); +validationRules["Alphabetical"] = new AlphabeticalValidator(); -assert(validators["Letters only"].isAcceptable(strings[0]), 'success'); -assert(validators["ZIP code"].isAcceptable(strings[1]), 'success'); +assert(validationRules["Alphabetical"].isValid(testInputs[0]), 'success'); +assert(validationRules["Postal Code"].isValid(testInputs[1]), 'success'); -- Gitee From 7f0bba7111f1c3b076d6748929737b6586fd087d Mon Sep 17 00:00:00 2001 From: kaanfurkancakiroglu Date: Thu, 24 Apr 2025 20:12:31 +0300 Subject: [PATCH 214/268] Title:[fuzzing][autoreport][es2panda] crash Issue: IC3RFJ Test: Build Signed-off-by: kaanfurkancakiroglu --- ets2panda/parser/ETSparserClasses.cpp | 4 ++++ ets2panda/parser/ETSparserExpressions.cpp | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/ets2panda/parser/ETSparserClasses.cpp b/ets2panda/parser/ETSparserClasses.cpp index cc020083e0..70df433251 100644 --- a/ets2panda/parser/ETSparserClasses.cpp +++ b/ets2panda/parser/ETSparserClasses.cpp @@ -430,6 +430,10 @@ ir::ModifierFlags ETSParser::ParseClassMethodModifiers(bool seenStatic) ir::TypeNode *ETSParser::ConvertToOptionalUnionType(ir::TypeNode *typeAnno) { + if (typeAnno == nullptr) { + return nullptr; + } + // NOLINTNEXTLINE(clang-analyzer-core.CallAndMessage) if (!typeAnno->IsETSUnionType()) { ArenaVector types(Allocator()->Adapter()); diff --git a/ets2panda/parser/ETSparserExpressions.cpp b/ets2panda/parser/ETSparserExpressions.cpp index aec40b4e82..594c038963 100644 --- a/ets2panda/parser/ETSparserExpressions.cpp +++ b/ets2panda/parser/ETSparserExpressions.cpp @@ -52,11 +52,11 @@ ir::Expression *ETSParser::ParseLaunchExpression(ExpressionParseFlags flags) static std::string GetArgumentsSourceView(lexer::Lexer *lexer, const util::StringView::Iterator &lexerPos) { std::string value = lexer->SourceView(lexerPos.Index(), lexer->Save().Iterator().Index()).Mutf8(); - while (value.back() == ' ') { + while (!value.empty() && value.back() == ' ') { value.pop_back(); } - if (value.back() == ')' || value.back() == ',') { + if (!value.empty() && (value.back() == ')' || value.back() == ',')) { value.pop_back(); } -- Gitee From c792e5d57cc2f90422d3c91ede4490ce4066eb61 Mon Sep 17 00:00:00 2001 From: shixiaowei4 Date: Tue, 27 May 2025 10:56:23 +0800 Subject: [PATCH 215/268] Fix warnings Issue: https://gitee.com/openharmony/arkcompiler_runtime_core/issues/ICAQF2 Signed-off-by: shixiaowei4 Change-Id: I98e0c8c71b894d95af7f4c2a44bb1a2b2dbf2029 --- es2panda/test/runner.py | 1 - 1 file changed, 1 deletion(-) diff --git a/es2panda/test/runner.py b/es2panda/test/runner.py index c4de73a4e9..19a86178e5 100755 --- a/es2panda/test/runner.py +++ b/es2panda/test/runner.py @@ -974,7 +974,6 @@ class CompilerProjectTest(Test): mod_files_info.append(abc_line) final_file_info_f.writelines(abc_line) - def gen_files_info(self, runner): # After collect_record_mapping, self.file_record_mapping stores {'source file name' : 'source file record name'} self.collect_record_mapping() -- Gitee From 96b3cf82fff0f9982cdadceae5c5099d9d4321ea Mon Sep 17 00:00:00 2001 From: cllvly Date: Wed, 28 May 2025 19:17:54 +0800 Subject: [PATCH 216/268] Update Kfl 0528 Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICB8V5 Signed-off-by: chenlong --- test/workload/ignored-third_lib_js-fastverify-arm64-jit.txt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/test/workload/ignored-third_lib_js-fastverify-arm64-jit.txt b/test/workload/ignored-third_lib_js-fastverify-arm64-jit.txt index 5a1ff03c90..7de5bd7250 100644 --- a/test/workload/ignored-third_lib_js-fastverify-arm64-jit.txt +++ b/test/workload/ignored-third_lib_js-fastverify-arm64-jit.txt @@ -9,3 +9,6 @@ hamcrest_test #19247 jsDiff_test + +#23235 +pdfview_test -- Gitee From f6d3aef6e0a9aae7dc3ba99ba4a8ad09ddc5825b Mon Sep 17 00:00:00 2001 From: lihao Date: Sat, 17 May 2025 16:54:03 +0800 Subject: [PATCH 217/268] Generate declaration files parallel Issue: https://gitee.com/openharmony/arkcompiler_runtime_core/issues/ICB973 Signed-off-by: lihao --- .../build_system/src/build/base_mode.ts | 31 ++++- .../build_system/src/build/build_mode.ts | 2 +- .../build_system/src/build/compile_worker.ts | 6 +- .../build_system/src/build/declgen_worker.ts | 126 ++++++++++++++++++ ets2panda/driver/build_system/src/entry.ts | 2 +- 5 files changed, 160 insertions(+), 7 deletions(-) create mode 100644 ets2panda/driver/build_system/src/build/declgen_worker.ts diff --git a/ets2panda/driver/build_system/src/build/base_mode.ts b/ets2panda/driver/build_system/src/build/base_mode.ts index 20ab3bd4bf..bbb32e5332 100644 --- a/ets2panda/driver/build_system/src/build/base_mode.ts +++ b/ets2panda/driver/build_system/src/build/base_mode.ts @@ -491,6 +491,31 @@ export abstract class BaseMode { } } + public async generateDeclarationParallell(): Promise { + this.generateModuleInfos(); + this.generateArkTSConfigForModules(); + + if (!cluster.isPrimary) { + return; + } + + try { + this.setupCluster(cluster, { + clearExitListeners: true, + execPath: path.resolve(__dirname, 'declgen_worker.js'), + }); + await this.dispatchTasks(); + this.logger.printInfo('All declaration generation tasks complete.'); + } catch (error) { + this.logger.printError(LogDataFactory.newInstance( + ErrorCode.BUILDSYSTEM_DECLGEN_FAIL, + 'Generate declaration files failed.' + )); + } finally { + this.terminateAllWorkers(); + } + } + private async dispatchTasks(): Promise { const numCPUs = os.cpus().length; const taskQueue = Array.from(this.compileFiles.values()); @@ -512,12 +537,14 @@ export abstract class BaseMode { const serializableConfig = this.getSerializableConfig(); const workerExitPromises: Promise[] = []; + const moduleInfosArray = Array.from(this.moduleInfos.entries()); + for (let i = 0; i < maxWorkers; i++) { const taskChunk = taskQueue.slice(i * chunkSize, (i + 1) * chunkSize); const worker = cluster.fork(); this.setupWorkerMessageHandler(worker); - worker.send({ taskList: taskChunk, buildConfig: serializableConfig }); + worker.send({ taskList: taskChunk, buildConfig: serializableConfig, moduleInfos: moduleInfosArray}); const exitPromise = new Promise((resolve, reject) => { worker.on('exit', (status) => status === 0 ? resolve() : reject()); @@ -547,7 +574,6 @@ export abstract class BaseMode { }); } - private getSerializableConfig(): Object { const ignoreList = [ 'compileFiles', @@ -566,6 +592,7 @@ export abstract class BaseMode { }); return JSON.parse(jsonStr); } + setupCluster(cluster: Cluster, options: SetupClusterOptions): void { const { clearExitListeners, diff --git a/ets2panda/driver/build_system/src/build/build_mode.ts b/ets2panda/driver/build_system/src/build/build_mode.ts index 4c797a308a..59bdb759ab 100644 --- a/ets2panda/driver/build_system/src/build/build_mode.ts +++ b/ets2panda/driver/build_system/src/build/build_mode.ts @@ -22,7 +22,7 @@ export class BuildMode extends BaseMode { } public async generateDeclaration(): Promise { - super.generateDeclaration(); + await super.generateDeclarationParallell(); } public async run(): Promise { diff --git a/ets2panda/driver/build_system/src/build/compile_worker.ts b/ets2panda/driver/build_system/src/build/compile_worker.ts index 4c69a0c8a4..38a1fcdb59 100644 --- a/ets2panda/driver/build_system/src/build/compile_worker.ts +++ b/ets2panda/driver/build_system/src/build/compile_worker.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -import { CompileFileInfo } from '../types'; +import { CompileFileInfo, ModuleInfo } from '../types'; import * as fs from 'fs'; import * as path from 'path'; import { ensurePathExists } from '../utils'; @@ -32,15 +32,15 @@ import { } from '../logger'; import { ErrorCode } from '../error_code'; - process.on('message', (message: { taskList: CompileFileInfo[]; buildConfig: BuildConfig; + moduleInfos: Array<[string, ModuleInfo]>; }) => { if (!process.send) { throw new Error('process.send is undefined. This worker must be run as a forked process.'); } - const { taskList, buildConfig } = message; + const { taskList, buildConfig, moduleInfos } = message; const isDebug = buildConfig.buildMode === BUILD_MODE.DEBUG; Logger.getInstance(buildConfig); diff --git a/ets2panda/driver/build_system/src/build/declgen_worker.ts b/ets2panda/driver/build_system/src/build/declgen_worker.ts new file mode 100644 index 0000000000..2d25e9704d --- /dev/null +++ b/ets2panda/driver/build_system/src/build/declgen_worker.ts @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { CompileFileInfo, ModuleInfo } from '../types'; +import { BuildConfig } from '../types'; +import { LogData, LogDataFactory, Logger } from '../logger'; +import { ErrorCode } from '../error_code'; +import * as fs from 'fs'; +import * as path from 'path'; +import { changeFileExtension, ensurePathExists } from '../utils'; +import { + DECL_ETS_SUFFIX, + TS_SUFFIX, + KOALA_WRAPPER_PATH_FROM_SDK +} from '../pre_define'; +import { PluginDriver, PluginHook } from '../plugins/plugins_driver'; + +process.on('message', (message: { + taskList: CompileFileInfo[]; + buildConfig: BuildConfig; + moduleInfos: Array<[string, ModuleInfo]>; +}) => { + if (!process.send) { + throw new Error('process.send is undefined. This worker must be run as a forked process.'); + } + const { taskList, buildConfig, moduleInfos } = message; + const moduleInfosMap = new Map(moduleInfos); + + const logger = Logger.getInstance(buildConfig); + const pluginDriver = PluginDriver.getInstance(); + pluginDriver.initPlugins(buildConfig); + + const koalaWrapperPath = path.resolve(buildConfig.buildSdkPath, KOALA_WRAPPER_PATH_FROM_SDK); + let { arkts, arktsGlobal } = require(koalaWrapperPath); + + for (const fileInfo of taskList) { + let errorStatus = false; + try { + const source = fs.readFileSync(fileInfo.filePath, 'utf8'); + let moduleInfo = moduleInfosMap.get(fileInfo.packageName)!; + let filePathFromModuleRoot: string = path.relative(moduleInfo.moduleRootPath, fileInfo.filePath); + let declEtsOutputPath: string = path.join( + moduleInfo.declgenV1OutPath as string, + moduleInfo.packageName, + filePathFromModuleRoot + ); + declEtsOutputPath = changeFileExtension(declEtsOutputPath, DECL_ETS_SUFFIX); + let etsOutputPath: string = path.join( + moduleInfo.declgenBridgeCodePath as string, + moduleInfo.packageName, + filePathFromModuleRoot + ); + etsOutputPath = changeFileExtension(etsOutputPath, TS_SUFFIX); + + ensurePathExists(declEtsOutputPath); + ensurePathExists(etsOutputPath); + + arktsGlobal.filePath = fileInfo.filePath; + arktsGlobal.config = arkts.Config.create([ + '_', + '--extension', + 'ets', + '--arktsconfig', + fileInfo.arktsConfigFile, + fileInfo.filePath + ]).peer; + arktsGlobal.compilerContext = arkts.Context.createFromString(source); + pluginDriver.getPluginContext().setArkTSProgram(arktsGlobal.compilerContext.program); + + arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, true); + + let ast = arkts.EtsScript.fromContext(); + pluginDriver.getPluginContext().setArkTSAst(ast); + pluginDriver.runPluginHook(PluginHook.PARSED); + + arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, true); + + ast = arkts.EtsScript.fromContext(); + pluginDriver.getPluginContext().setArkTSAst(ast); + pluginDriver.runPluginHook(PluginHook.CHECKED); + + arkts.generateTsDeclarationsFromContext( + declEtsOutputPath, + etsOutputPath, + false + ); // Generate 1.0 declaration files & 1.0 glue code + logger.printInfo('declaration files generated'); + + process.send({ success: true, filePath: fileInfo.filePath }); + } catch (error) { + errorStatus = true; + if (error instanceof Error) { + const logData: LogData = LogDataFactory.newInstance( + ErrorCode.BUILDSYSTEM_DECLGEN_FAIL, + 'Generate declaration files failed in worker.', + error.message + ); + logger.printError(logData); + } + process.send({ + success: false, + filePath: fileInfo.filePath, + error: 'Generate declaration files failed in worker.' + }); + } finally { + if (!errorStatus) { + // when error occur,wrapper will destroy context. + arktsGlobal.es2panda._DestroyContext(arktsGlobal.compilerContext.peer); + } + arkts.destroyConfig(arktsGlobal.config); + } + } + process.exit(0); +}); \ No newline at end of file diff --git a/ets2panda/driver/build_system/src/entry.ts b/ets2panda/driver/build_system/src/entry.ts index 5d70b509d0..6f0a52f9bb 100644 --- a/ets2panda/driver/build_system/src/entry.ts +++ b/ets2panda/driver/build_system/src/entry.ts @@ -30,7 +30,7 @@ export async function build(projectConfig: BuildConfig): Promise { if (projectConfig.enableDeclgenEts2Ts === true) { let buildMode: BuildMode = new BuildMode(buildConfig); - buildMode.generateDeclaration(); + await buildMode.generateDeclaration(); } else if (projectConfig.buildType === BUILD_TYPE_BUILD) { let buildMode: BuildMode = new BuildMode(buildConfig); await buildMode.run(); -- Gitee From 66036492e3488cd9bd8ad02316ad2fda5ebc3f89 Mon Sep 17 00:00:00 2001 From: zengzengran Date: Tue, 6 May 2025 21:18:08 +0800 Subject: [PATCH 218/268] Allowed ?? expression use identifier Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC3A69 Description: Allow Nulllish-Coalescing Expression use identifier, Check whether the identifier is PossibleTDZ or function Tested-by: ninja tests (passed) ets_testrunner (passed) Signed-off-by: zengzengran # --- ets2panda/checker/ets/validateHelpers.cpp | 11 +++ .../test/runtime/ets/function_assignable.ets | 68 +++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 ets2panda/test/runtime/ets/function_assignable.ets diff --git a/ets2panda/checker/ets/validateHelpers.cpp b/ets2panda/checker/ets/validateHelpers.cpp index 593e04c1e2..ed71d79e95 100644 --- a/ets2panda/checker/ets/validateHelpers.cpp +++ b/ets2panda/checker/ets/validateHelpers.cpp @@ -125,8 +125,10 @@ void ETSChecker::ValidateAssignmentIdentifier(ir::Identifier *const ident, Type bool ETSChecker::ValidateBinaryExpressionIdentifier(ir::Identifier *const ident, Type *const type) { + auto const resolved = ident->Variable(); const auto *const binaryExpr = ident->Parent()->AsBinaryExpression(); bool isFinished = false; + if (binaryExpr->OperatorType() == lexer::TokenType::KEYW_INSTANCEOF && binaryExpr->Left() == ident) { if (!IsReferenceType(type)) { std::ignore = @@ -134,6 +136,15 @@ bool ETSChecker::ValidateBinaryExpressionIdentifier(ir::Identifier *const ident, } isFinished = true; } + + if (binaryExpr->OperatorType() == lexer::TokenType::PUNCTUATOR_NULLISH_COALESCING || + binaryExpr->OperatorType() == lexer::TokenType::PUNCTUATOR_LOGICAL_OR || + binaryExpr->OperatorType() == lexer::TokenType::PUNCTUATOR_LOGICAL_AND) { + if ((resolved != nullptr) && (!resolved->Declaration()->PossibleTDZ() && !type->IsETSFunctionType())) { + WrongContextErrorClassifyByType(ident); + } + isFinished = true; + } return isFinished; } diff --git a/ets2panda/test/runtime/ets/function_assignable.ets b/ets2panda/test/runtime/ets/function_assignable.ets new file mode 100644 index 0000000000..80a1638485 --- /dev/null +++ b/ets2panda/test/runtime/ets/function_assignable.ets @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +function ccc(): string { + return "function ccc" +} + +let foo: () => string = () => { return "lambda foo" } + +interface AAAOp { + aa?: () => string +} + +class A { + _aa?: () => string + get aa(): () => string { + return this._aa!; + } + set aa(value: () => string) { + this._aa = value; + } + _init1(it?: AAAOp) { + this._aa = it?.aa ?? ccc; + } + _init2(it?: AAAOp) { + this.aa = it?.aa ?? ccc; + } + _init3() { + this._aa = foo ?? ccc; + } + _init4() { + this.aa = ccc ?? foo; + } + _init5(it?: AAAOp) { + this._aa = it == undefined ? ccc:it.aa; + } + _init6(it?: AAAOp) { + this._aa = it?.aa || ccc; + } +} + +function main(){ + let a = new A(); + a._init1() + assertEQ(a.aa(),"function ccc") + a._init2() + assertEQ(a.aa(),"function ccc") + a._init3() + assertEQ(a.aa(),"lambda foo") + a._init4() + assertEQ(a.aa(),"function ccc") + a._init5() + assertEQ(a.aa(),"function ccc") + a._init6() + assertEQ(a.aa(),"function ccc") +} -- Gitee From c4b428402c8fc94799d8d7d8595a39b163e1789f Mon Sep 17 00:00:00 2001 From: liu-yaxue Date: Wed, 28 May 2025 20:17:40 +0800 Subject: [PATCH 219/268] func_as_param test complete Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICB96W Signed-off-by: liu-yaxue --- .../test/ast/compiler/ets/func_as_param.ets | 67 ++++++++++++++++++- 1 file changed, 66 insertions(+), 1 deletion(-) diff --git a/ets2panda/test/ast/compiler/ets/func_as_param.ets b/ets2panda/test/ast/compiler/ets/func_as_param.ets index e78a161c81..7d03377605 100644 --- a/ets2panda/test/ast/compiler/ets/func_as_param.ets +++ b/ets2panda/test/ast/compiler/ets/func_as_param.ets @@ -16,7 +16,7 @@ function getFuncWithArgsZero(func: (() => void) | (() => Promise)) { return new Promise(async (resolve: (value: PromiseLike) => void) => { await (func as () => Promise)(); - const funcStr = (func as object).toString() + const funcStr = Type.of(func as object).getLiteral() const argsCount = getFunctionArgumentsCount(funcStr) const isAsync = checkIsAsyncFunction(funcStr) resolve(Promise.resolve()); @@ -47,4 +47,69 @@ function checkIsAsyncFunction(funcStr: string): boolean { } } +async function testAsyncGetFuncWithArgsZeroSafe() { + let success = false; + try { + await getFuncWithArgsZero( async () => {}); + success = true; + } catch (e) { + success = false; + } + assertEQ(success, true, "getFuncWithArgsZero with async should not throw"); +} + +function testGetFuncWithArgsZeroSafe() { + let success = false; + try { + getFuncWithArgsZero(() => {}); + success = true; + } catch (e) { + success = false; + } + assertEQ(success, true, "getFuncWithArgsZero should not throw"); +} + +function main(): void { + const func1 = (a: number, b: number): number => { + return a + b; + }; + + const func2 = async (): Promise => {}; + + const func3 = (): number => { + return 42; + }; + + const func4 = async (x: number, y: number, z: number): Promise => {}; + + const funcStr1: string = Type.of(func1 as object).getLiteral(); + const funcStr2: string = Type.of(func2 as object).getLiteral(); + const funcStr3: string = Type.of(func3 as object).getLiteral(); + const funcStr4: string = Type.of(func4 as object).getLiteral(); + + // Test getLiteral() + assertEQ(funcStr1, "(1: std.core.Double, 2: std.core.Double): std.core.Double", "func1 literal check"); + assertEQ(funcStr2, "(): std.core.Promise", "func2 literal check"); + assertEQ(funcStr3, "(): std.core.Double", "func3 literal check"); + assertEQ(funcStr4, "(1: std.core.Double, 2: std.core.Double, 3: std.core.Double): std.core.Promise", "func4 literal check"); + + // Test getFunctionArgumentsCount + assertEQ(getFunctionArgumentsCount(funcStr1), 2, "func1 should have 2 arguments"); + assertEQ(getFunctionArgumentsCount(funcStr2), 0, "func2 should have 0 arguments"); + assertEQ(getFunctionArgumentsCount(funcStr3), 0, "func3 should have 0 arguments"); + assertEQ(getFunctionArgumentsCount(funcStr4), 3, "func4 should have 3 arguments"); + + // Test checkIsAsyncFunction + assertEQ(checkIsAsyncFunction(funcStr1), false, "func1 should not be async"); + assertEQ(checkIsAsyncFunction(funcStr2), true, "func2 should be async"); + assertEQ(checkIsAsyncFunction(funcStr3), false, "func3 should not be async"); + assertEQ(checkIsAsyncFunction(funcStr4), true, "func4 should be async"); + + // execute getFuncWithArgsZero with async + testAsyncGetFuncWithArgsZeroSafe() + + // execute getFuncWithArgsZero with sync + testGetFuncWithArgsZeroSafe() +} + -- Gitee From f706f0735d09b24985fdb5c7318e829475b54466 Mon Sep 17 00:00:00 2001 From: eraycinar Date: Wed, 28 May 2025 07:48:13 +0300 Subject: [PATCH 220/268] [Bug] To much of expected errors Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICA5Y8 Signed-off-by: eraycinar --- .../ast/parser/ets/too_many_expression.ets | 1516 +++++++++++------ ets2panda/util/diagnostic/fatal.yaml | 4 - ets2panda/util/diagnostic/syntax.yaml | 4 + ets2panda/util/recursiveGuard.h | 2 +- 4 files changed, 1045 insertions(+), 481 deletions(-) diff --git a/ets2panda/test/ast/parser/ets/too_many_expression.ets b/ets2panda/test/ast/parser/ets/too_many_expression.ets index e46f538c79..6b51d78542 100644 --- a/ets2panda/test/ast/parser/ets/too_many_expression.ets +++ b/ets2panda/test/ast/parser/ets/too_many_expression.ets @@ -1,478 +1,1042 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ -/new Uint8Array[let [-9] = ([((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= . 7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .$7 = + >>> 0O5.25657e9)]((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= .7 = + >>> 0O5.25657e9)][((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((({Symbol: [ceil(h: b= . +(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( -/* @@? 16:1 Error SyntaxError: Unexpected token '/'. */ -/* @@? 16:1 Error TypeError: Bad operand type, the types of the operands must be numeric type. */ -/* @@? 16:17 Error SyntaxError: Unexpected token 'let'. */ -/* @@? 16:17 Error SyntaxError: Expected ']', got 'let'. */ -/* @@? 16:17 Error SyntaxError: Unexpected token 'let'. */ -/* @@? 16:22 Error SyntaxError: Identifier expected, got '['. */ -/* @@? 16:23 Error SyntaxError: Variable must be initialized or it's type must be declared. */ -/* @@? 16:23 Error SyntaxError: Unexpected token '9'. */ -/* @@? 16:24 Error SyntaxError: Unexpected token ']'. */ -/* @@? 16:26 Error SyntaxError: Unexpected token '='. */ -/* @@? 16:28 Error SyntaxError: Unexpected token '<'. */ -/* @@? 16:29 Error TypeError: Unresolved reference missing */ -/* @@? 16:37 Error SyntaxError: Unexpected token ']'. */ -/* @@? 16:37 Error TypeError: Bad operand type, the types of the operands must be numeric, same enumeration, or boolean type. */ -/* @@? 16:42 Error SyntaxError: Unexpected token '<'. */ -/* @@? 16:51 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 16:56 Error TypeError: need to specify target type for class composite */ -/* @@? 16:189 Error SyntaxError: Unexpected token. */ -/* @@? 16:189 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 16:189 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 16:191 Error SyntaxError: Invalid shorthand property initializer. */ -/* @@? 16:194 Error SyntaxError: Unexpected token '.'. */ -/* @@? 16:196 Error SyntaxError: Identifier expected, got 'number literal'. */ -/* @@? 16:202 Error SyntaxError: Unexpected token '>>>'. */ -/* @@? 16:209 Error SyntaxError: Unexpected token. */ -/* @@? 16:217 Error SyntaxError: Unexpected token. */ -/* @@? 16:218 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 16:353 Error SyntaxError: Unexpected token. */ -/* @@? 16:353 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 16:353 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 16:355 Error SyntaxError: Invalid shorthand property initializer. */ -/* @@? 16:361 Error SyntaxError: Invalid left-hand side in assignment expression. */ -/* @@? 16:365 Error SyntaxError: Unexpected token '>>>'. */ -/* @@? 16:372 Error SyntaxError: Unexpected token. */ -/* @@? 16:380 Error SyntaxError: Unexpected token. */ -/* @@? 16:381 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 16:516 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 16:516 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 16:516 Error SyntaxError: Unexpected token. */ -/* @@? 16:518 Error SyntaxError: Invalid shorthand property initializer. */ -/* @@? 16:524 Error SyntaxError: Invalid left-hand side in assignment expression. */ -/* @@? 16:528 Error SyntaxError: Unexpected token '>>>'. */ -/* @@? 16:535 Error SyntaxError: Unexpected token. */ -/* @@? 16:543 Error SyntaxError: Unexpected token. */ -/* @@? 16:544 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 16:679 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 16:679 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 16:679 Error SyntaxError: Unexpected token. */ -/* @@? 16:681 Error SyntaxError: Invalid shorthand property initializer. */ -/* @@? 16:687 Error SyntaxError: Invalid left-hand side in assignment expression. */ -/* @@? 16:691 Error SyntaxError: Unexpected token '>>>'. */ -/* @@? 16:698 Error SyntaxError: Unexpected token. */ -/* @@? 16:706 Error SyntaxError: Unexpected token. */ -/* @@? 16:707 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 16:842 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 16:842 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 16:842 Error SyntaxError: Unexpected token. */ -/* @@? 16:844 Error SyntaxError: Invalid shorthand property initializer. */ -/* @@? 16:850 Error SyntaxError: Invalid left-hand side in assignment expression. */ -/* @@? 16:854 Error SyntaxError: Unexpected token '>>>'. */ -/* @@? 16:861 Error SyntaxError: Unexpected token. */ -/* @@? 16:869 Error SyntaxError: Unexpected token. */ -/* @@? 16:870 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 16:1005 Error SyntaxError: Unexpected token. */ -/* @@? 16:1005 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 16:1005 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 16:1007 Error SyntaxError: Invalid shorthand property initializer. */ -/* @@? 16:1013 Error SyntaxError: Invalid left-hand side in assignment expression. */ -/* @@? 16:1017 Error SyntaxError: Unexpected token '>>>'. */ -/* @@? 16:1024 Error SyntaxError: Unexpected token. */ -/* @@? 16:1032 Error SyntaxError: Unexpected token. */ -/* @@? 16:1033 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 16:1168 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 16:1168 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 16:1168 Error SyntaxError: Unexpected token. */ -/* @@? 16:1170 Error SyntaxError: Invalid shorthand property initializer. */ -/* @@? 16:1176 Error SyntaxError: Invalid left-hand side in assignment expression. */ -/* @@? 16:1180 Error SyntaxError: Unexpected token '>>>'. */ -/* @@? 16:1187 Error SyntaxError: Unexpected token. */ -/* @@? 16:1195 Error SyntaxError: Unexpected token. */ -/* @@? 16:1196 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 16:1331 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 16:1331 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 16:1331 Error SyntaxError: Unexpected token. */ -/* @@? 16:1333 Error SyntaxError: Invalid shorthand property initializer. */ -/* @@? 16:1339 Error SyntaxError: Invalid left-hand side in assignment expression. */ -/* @@? 16:1343 Error SyntaxError: Unexpected token '>>>'. */ -/* @@? 16:1350 Error SyntaxError: Unexpected token. */ -/* @@? 16:1358 Error SyntaxError: Unexpected token. */ -/* @@? 16:1359 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 16:1494 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 16:1494 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 16:1494 Error SyntaxError: Unexpected token. */ -/* @@? 16:1496 Error SyntaxError: Invalid shorthand property initializer. */ -/* @@? 16:1502 Error SyntaxError: Invalid left-hand side in assignment expression. */ -/* @@? 16:1506 Error SyntaxError: Unexpected token '>>>'. */ -/* @@? 16:1513 Error SyntaxError: Unexpected token. */ -/* @@? 16:1521 Error SyntaxError: Unexpected token. */ -/* @@? 16:1522 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 16:1657 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 16:1657 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 16:1657 Error SyntaxError: Unexpected token. */ -/* @@? 16:1659 Error SyntaxError: Invalid shorthand property initializer. */ -/* @@? 16:1665 Error SyntaxError: Invalid left-hand side in assignment expression. */ -/* @@? 16:1669 Error SyntaxError: Unexpected token '>>>'. */ -/* @@? 16:1676 Error SyntaxError: Unexpected token. */ -/* @@? 16:1684 Error SyntaxError: Unexpected token. */ -/* @@? 16:1685 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 16:1820 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 16:1820 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 16:1820 Error SyntaxError: Unexpected token. */ -/* @@? 16:1822 Error SyntaxError: Invalid shorthand property initializer. */ -/* @@? 16:1828 Error SyntaxError: Invalid left-hand side in assignment expression. */ -/* @@? 16:1832 Error SyntaxError: Unexpected token '>>>'. */ -/* @@? 16:1839 Error SyntaxError: Unexpected token. */ -/* @@? 16:1847 Error SyntaxError: Unexpected token. */ -/* @@? 16:1848 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 16:1983 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 16:1983 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 16:1983 Error SyntaxError: Unexpected token. */ -/* @@? 16:1985 Error SyntaxError: Invalid shorthand property initializer. */ -/* @@? 16:1991 Error SyntaxError: Invalid left-hand side in assignment expression. */ -/* @@? 16:1995 Error SyntaxError: Unexpected token '>>>'. */ -/* @@? 16:2002 Error SyntaxError: Unexpected token. */ -/* @@? 16:2010 Error SyntaxError: Unexpected token. */ -/* @@? 16:2011 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 16:2146 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 16:2146 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 16:2146 Error SyntaxError: Unexpected token. */ -/* @@? 16:2148 Error SyntaxError: Invalid shorthand property initializer. */ -/* @@? 16:2154 Error SyntaxError: Invalid left-hand side in assignment expression. */ -/* @@? 16:2158 Error SyntaxError: Unexpected token '>>>'. */ -/* @@? 16:2165 Error SyntaxError: Unexpected token. */ -/* @@? 16:2173 Error SyntaxError: Unexpected token. */ -/* @@? 16:2174 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 16:2309 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 16:2309 Error SyntaxError: Unexpected token. */ -/* @@? 16:2309 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 16:2311 Error SyntaxError: Invalid shorthand property initializer. */ -/* @@? 16:2317 Error SyntaxError: Invalid left-hand side in assignment expression. */ -/* @@? 16:2321 Error SyntaxError: Unexpected token '>>>'. */ -/* @@? 16:2328 Error SyntaxError: Unexpected token. */ -/* @@? 16:2336 Error SyntaxError: Unexpected token. */ -/* @@? 16:2337 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 16:2472 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 16:2472 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 16:2472 Error SyntaxError: Unexpected token. */ -/* @@? 16:2474 Error SyntaxError: Invalid shorthand property initializer. */ -/* @@? 16:2480 Error SyntaxError: Invalid left-hand side in assignment expression. */ -/* @@? 16:2484 Error SyntaxError: Unexpected token '>>>'. */ -/* @@? 16:2491 Error SyntaxError: Unexpected token. */ -/* @@? 16:2499 Error SyntaxError: Unexpected token. */ -/* @@? 16:2500 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 16:2635 Error SyntaxError: Unexpected token. */ -/* @@? 16:2635 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 16:2635 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 16:2637 Error SyntaxError: Invalid shorthand property initializer. */ -/* @@? 16:2643 Error SyntaxError: Invalid left-hand side in assignment expression. */ -/* @@? 16:2647 Error SyntaxError: Unexpected token '>>>'. */ -/* @@? 16:2654 Error SyntaxError: Unexpected token. */ -/* @@? 16:2662 Error SyntaxError: Unexpected token. */ -/* @@? 16:2663 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 16:2798 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 16:2798 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 16:2798 Error SyntaxError: Unexpected token. */ -/* @@? 16:2800 Error SyntaxError: Invalid shorthand property initializer. */ -/* @@? 16:2806 Error SyntaxError: Invalid left-hand side in assignment expression. */ -/* @@? 16:2810 Error SyntaxError: Unexpected token '>>>'. */ -/* @@? 16:2817 Error SyntaxError: Unexpected token. */ -/* @@? 16:2825 Error SyntaxError: Unexpected token. */ -/* @@? 16:2826 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 16:2961 Error SyntaxError: Unexpected token. */ -/* @@? 16:2961 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 16:2961 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 16:2963 Error SyntaxError: Invalid shorthand property initializer. */ -/* @@? 16:2969 Error SyntaxError: Invalid left-hand side in assignment expression. */ -/* @@? 16:2973 Error SyntaxError: Unexpected token '>>>'. */ -/* @@? 16:2980 Error SyntaxError: Unexpected token. */ -/* @@? 16:2988 Error SyntaxError: Unexpected token. */ -/* @@? 16:2989 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 16:3124 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 16:3124 Error SyntaxError: Unexpected token. */ -/* @@? 16:3124 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 16:3126 Error SyntaxError: Invalid shorthand property initializer. */ -/* @@? 16:3132 Error SyntaxError: Invalid left-hand side in assignment expression. */ -/* @@? 16:3136 Error SyntaxError: Unexpected token '>>>'. */ -/* @@? 16:3143 Error SyntaxError: Unexpected token. */ -/* @@? 16:3151 Error SyntaxError: Unexpected token. */ -/* @@? 16:3152 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 16:3287 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 16:3287 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 16:3287 Error SyntaxError: Unexpected token. */ -/* @@? 16:3289 Error SyntaxError: Invalid shorthand property initializer. */ -/* @@? 16:3295 Error SyntaxError: Invalid left-hand side in assignment expression. */ -/* @@? 16:3299 Error SyntaxError: Unexpected token '>>>'. */ -/* @@? 16:3306 Error SyntaxError: Unexpected token. */ -/* @@? 16:3314 Error SyntaxError: Unexpected token. */ -/* @@? 16:3315 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 16:3450 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 16:3450 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 16:3450 Error SyntaxError: Unexpected token. */ -/* @@? 16:3452 Error SyntaxError: Invalid shorthand property initializer. */ -/* @@? 16:3458 Error SyntaxError: Invalid left-hand side in assignment expression. */ -/* @@? 16:3462 Error SyntaxError: Unexpected token '>>>'. */ -/* @@? 16:3469 Error SyntaxError: Unexpected token. */ -/* @@? 16:3477 Error SyntaxError: Unexpected token. */ -/* @@? 16:3478 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 16:3613 Error SyntaxError: Unexpected token. */ -/* @@? 16:3613 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 16:3613 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 16:3615 Error SyntaxError: Invalid shorthand property initializer. */ -/* @@? 16:3621 Error SyntaxError: Invalid left-hand side in assignment expression. */ -/* @@? 16:3625 Error SyntaxError: Unexpected token '>>>'. */ -/* @@? 16:3632 Error SyntaxError: Unexpected token. */ -/* @@? 16:3640 Error SyntaxError: Unexpected token. */ -/* @@? 16:3641 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 16:3776 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 16:3776 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 16:3776 Error SyntaxError: Unexpected token. */ -/* @@? 16:3778 Error SyntaxError: Invalid shorthand property initializer. */ -/* @@? 16:3784 Error SyntaxError: Invalid left-hand side in assignment expression. */ -/* @@? 16:3788 Error SyntaxError: Unexpected token '>>>'. */ -/* @@? 16:3795 Error SyntaxError: Unexpected token. */ -/* @@? 16:3803 Error SyntaxError: Unexpected token. */ -/* @@? 16:3804 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 16:3939 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 16:3939 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 16:3939 Error SyntaxError: Unexpected token. */ -/* @@? 16:3941 Error SyntaxError: Invalid shorthand property initializer. */ -/* @@? 16:3947 Error SyntaxError: Invalid left-hand side in assignment expression. */ -/* @@? 16:3951 Error SyntaxError: Unexpected token '>>>'. */ -/* @@? 16:3958 Error SyntaxError: Unexpected token. */ -/* @@? 16:3966 Error SyntaxError: Unexpected token. */ -/* @@? 16:3967 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 16:4102 Error SyntaxError: Unexpected token. */ -/* @@? 16:4102 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 16:4102 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 16:4104 Error SyntaxError: Invalid shorthand property initializer. */ -/* @@? 16:4110 Error SyntaxError: Invalid left-hand side in assignment expression. */ -/* @@? 16:4114 Error SyntaxError: Unexpected token '>>>'. */ -/* @@? 16:4121 Error SyntaxError: Unexpected token. */ -/* @@? 16:4129 Error SyntaxError: Unexpected token. */ -/* @@? 16:4130 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 16:4265 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 16:4265 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 16:4265 Error SyntaxError: Unexpected token. */ -/* @@? 16:4267 Error SyntaxError: Invalid shorthand property initializer. */ -/* @@? 16:4273 Error SyntaxError: Invalid left-hand side in assignment expression. */ -/* @@? 16:4277 Error SyntaxError: Unexpected token '>>>'. */ -/* @@? 16:4284 Error SyntaxError: Unexpected token. */ -/* @@? 16:4292 Error SyntaxError: Unexpected token. */ -/* @@? 16:4293 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 16:4428 Error SyntaxError: Unexpected token. */ -/* @@? 16:4428 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 16:4428 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 16:4430 Error SyntaxError: Invalid shorthand property initializer. */ -/* @@? 16:4436 Error SyntaxError: Invalid left-hand side in assignment expression. */ -/* @@? 16:4440 Error SyntaxError: Unexpected token '>>>'. */ -/* @@? 16:4447 Error SyntaxError: Unexpected token. */ -/* @@? 16:4455 Error SyntaxError: Unexpected token. */ -/* @@? 16:4456 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 16:4591 Error SyntaxError: Unexpected token. */ -/* @@? 16:4591 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 16:4591 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 16:4593 Error SyntaxError: Invalid shorthand property initializer. */ -/* @@? 16:4599 Error SyntaxError: Invalid left-hand side in assignment expression. */ -/* @@? 16:4603 Error SyntaxError: Unexpected token '>>>'. */ -/* @@? 16:4610 Error SyntaxError: Unexpected token. */ -/* @@? 16:4618 Error SyntaxError: Unexpected token. */ -/* @@? 16:4619 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 16:4754 Error SyntaxError: Unexpected token. */ -/* @@? 16:4754 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 16:4754 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 16:4756 Error SyntaxError: Invalid shorthand property initializer. */ -/* @@? 16:4762 Error SyntaxError: Invalid left-hand side in assignment expression. */ -/* @@? 16:4766 Error SyntaxError: Unexpected token '>>>'. */ -/* @@? 16:4773 Error SyntaxError: Unexpected token. */ -/* @@? 16:4781 Error SyntaxError: Unexpected token. */ -/* @@? 16:4782 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 16:4917 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 16:4917 Error SyntaxError: Unexpected token. */ -/* @@? 16:4917 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 16:4919 Error SyntaxError: Invalid shorthand property initializer. */ -/* @@? 16:4925 Error SyntaxError: Invalid left-hand side in assignment expression. */ -/* @@? 16:4929 Error SyntaxError: Unexpected token '>>>'. */ -/* @@? 16:4936 Error SyntaxError: Unexpected token. */ -/* @@? 16:4944 Error SyntaxError: Unexpected token. */ -/* @@? 16:4945 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 16:5080 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 16:5080 Error SyntaxError: Unexpected token. */ -/* @@? 16:5080 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 16:5082 Error SyntaxError: Invalid shorthand property initializer. */ -/* @@? 16:5088 Error SyntaxError: Invalid left-hand side in assignment expression. */ -/* @@? 16:5092 Error SyntaxError: Unexpected token '>>>'. */ -/* @@? 16:5099 Error SyntaxError: Unexpected token. */ -/* @@? 16:5107 Error SyntaxError: Unexpected token. */ -/* @@? 16:5108 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 16:5243 Error SyntaxError: Unexpected token. */ -/* @@? 16:5243 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 16:5243 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 16:5245 Error SyntaxError: Invalid shorthand property initializer. */ -/* @@? 16:5251 Error SyntaxError: Invalid left-hand side in assignment expression. */ -/* @@? 16:5255 Error SyntaxError: Unexpected token '>>>'. */ -/* @@? 16:5262 Error SyntaxError: Unexpected token. */ -/* @@? 16:5270 Error SyntaxError: Unexpected token. */ -/* @@? 16:5271 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 16:5406 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 16:5406 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 16:5406 Error SyntaxError: Unexpected token. */ -/* @@? 16:5408 Error SyntaxError: Invalid shorthand property initializer. */ -/* @@? 16:5414 Error SyntaxError: Invalid left-hand side in assignment expression. */ -/* @@? 16:5418 Error SyntaxError: Unexpected token '>>>'. */ -/* @@? 16:5425 Error SyntaxError: Unexpected token. */ -/* @@? 16:5433 Error SyntaxError: Unexpected token. */ -/* @@? 16:5434 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 16:5569 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 16:5569 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 16:5569 Error SyntaxError: Unexpected token. */ -/* @@? 16:5571 Error SyntaxError: Invalid shorthand property initializer. */ -/* @@? 16:5577 Error SyntaxError: Invalid left-hand side in assignment expression. */ -/* @@? 16:5581 Error SyntaxError: Unexpected token '>>>'. */ -/* @@? 16:5588 Error SyntaxError: Unexpected token. */ -/* @@? 16:5596 Error SyntaxError: Unexpected token. */ -/* @@? 16:5597 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 16:5732 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 16:5732 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 16:5732 Error SyntaxError: Unexpected token. */ -/* @@? 16:5734 Error SyntaxError: Invalid shorthand property initializer. */ -/* @@? 16:5740 Error SyntaxError: Invalid left-hand side in assignment expression. */ -/* @@? 16:5744 Error SyntaxError: Unexpected token '>>>'. */ -/* @@? 16:5751 Error SyntaxError: Unexpected token. */ -/* @@? 16:5759 Error SyntaxError: Unexpected token. */ -/* @@? 16:5760 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ',' or ']'. */ -/* @@? 479:1 Error SyntaxError: Unexpected token. */ -/* @@? 479:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 16:1025 Error SyntaxError: Maximum allowed nesting level exceeded. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ +/* @@? 1043:1 Error SyntaxError: Unexpected token, expected ')'. */ diff --git a/ets2panda/util/diagnostic/fatal.yaml b/ets2panda/util/diagnostic/fatal.yaml index c8e64913cc..0bc08c8af6 100644 --- a/ets2panda/util/diagnostic/fatal.yaml +++ b/ets2panda/util/diagnostic/fatal.yaml @@ -111,7 +111,3 @@ fatal: - name: MISSING_OUTPUT_FILE id: 25 message: "Output file path must be specified." - -- name: DEEP_NESTING - id: 26 - message: "Maximum allowed nesting level exceeded." diff --git a/ets2panda/util/diagnostic/syntax.yaml b/ets2panda/util/diagnostic/syntax.yaml index 60d0b0da2e..465347e084 100644 --- a/ets2panda/util/diagnostic/syntax.yaml +++ b/ets2panda/util/diagnostic/syntax.yaml @@ -1191,3 +1191,7 @@ syntax: - name: PREDEFINED_TYPE_AS_IDENTIFIER id: 295 message: "{} is a predefined type, cannot be used as an identifier" + +- name: DEEP_NESTING + id: 306 + message: "Maximum allowed nesting level exceeded." diff --git a/ets2panda/util/recursiveGuard.h b/ets2panda/util/recursiveGuard.h index ad89f5a8e5..34b57989b1 100644 --- a/ets2panda/util/recursiveGuard.h +++ b/ets2panda/util/recursiveGuard.h @@ -18,7 +18,7 @@ namespace ark::es2panda::parser { -constexpr unsigned int MAX_RECURSION_DEPTH = 4096; +constexpr unsigned int MAX_RECURSION_DEPTH = 1024; struct RecursiveContext { unsigned depth = 0; -- Gitee From 0cb874cdc1e194f3b9237584d0a78a73f42f04e6 Mon Sep 17 00:00:00 2001 From: Khil Sergey Date: Sun, 1 Jun 2025 09:59:44 +0300 Subject: [PATCH 221/268] Update build reviewers Issue:https://gitee.com/openharmony/arkcompiler_runtime_core/issues/ICBV0G Signed-off-by: Khil Sergey --- ets2panda/REVIEWERS | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/ets2panda/REVIEWERS b/ets2panda/REVIEWERS index 1a3d942328..622f8ed652 100644 --- a/ets2panda/REVIEWERS +++ b/ets2panda/REVIEWERS @@ -38,20 +38,20 @@ /ets2panda/checker/ETSAnalyzer.cpp ^akmaevaleksey @Ekkoruse ^igelhaus ^Prof1983 /ets2panda/checker/ETSAnalyzerHelpers.* @lirismankarina ^igelhaus ^Prof1983 /ets2panda/compiler/ @xuxjeeee @gogabr ^igelhaus ^Prof1983 ^zelentsovdmitry -/ets2panda/declgen_ets2ts/ @dreamdoomwalker ^trubachevilya ^ivagin ^hufeng20 ^igelhaus ^Prof1983 -/ets2panda/driver/ ^trubachevilya @dreamdoomwalker @chenqy930 @hufeng20 ^igelhaus ^Prof1983 +/ets2panda/declgen_ets2ts/ @dreamdoomwalker ^trubachevilya ^ivagin ^hufeng20 ^igelhaus ^Prof1983 @zenghang11 +/ets2panda/driver/ @trubachevilya @dreamdoomwalker ^chenqy930 ^hufeng20 ^igelhaus ^Prof1983 @zenghang11 /ets2panda/ir/ @ziziziiziziz @gavin1012_hw ^igelhaus ^Prof1983 /ets2panda/linter/ @ragnvald @rosinskiyigor @eokolnov1 @liwentao_uiw ^utkugursel /ets2panda/parser/ @mkaskov ^igelhaus ^Prof1983 ^chernykhsergey ^zelentsovdmitry /ets2panda/scripts/*-build.sh @titovatatiana ^igelhaus ^Prof1983 /ets2panda/scripts/arkui* @titovatatiana ^igelhaus ^Prof1983 /ets2panda/test/ast @mbolshov ^igelhaus ^Prof1983 -/ets2panda/test/depanalyzer @trubachevilya ^igelhaus ^Prof1983 +/ets2panda/test/depanalyzer @trubachevilya @dreamdoomwalker ^igelhaus ^Prof1983 /ets2panda/test/srcdump @mbolshov ^igelhaus ^Prof1983 /ets2panda/test/test-lists @igelhaus ^Prof1983 /ets2panda/test/utils @mbolshov ^igelhaus ^Prof1983 /ets2panda/util/ @mkaskov @dkofanov ^igelhaus ^Prof1983 -/ets2panda/util/arktsconfig* @dreamdoomwalker ^trubachevilya ^igelhaus ^Prof1983 +/ets2panda/util/arktsconfig* @dreamdoomwalker @trubachevilya ^igelhaus ^Prof1983 /ets2panda/util/diagnostic* @chernykhsergey @mkaskov ^igelhaus ^Prof1983 /ets2panda/util/importPathManager* @dreamdoomwalker @trubachevilya ^igelhaus ^Prof1983 /ets2panda/util/plugin.* @yyang16 @mbolshov ^igelhaus ^Prof1983 @@ -76,9 +76,9 @@ /ets2panda/ir/statements/ @dkofanov @Ekkoruse ^akmaevaleksey ^igelhaus ^Prof1983 /ets2panda/ir/statements/annotation* @lirismankarina @xuxjeeee ^igelhaus ^Prof1983 /ets2panda/test/test-lists/astchecker @chernykhsergey ^igelhaus ^Prof1983 -/ets2panda/test/test-lists/declgenets2ts @dreamdoomwalker ^hufeng20 ^igelhaus ^Prof1983 +/ets2panda/test/test-lists/declgenets2ts @dreamdoomwalker ^hufeng20 ^igelhaus ^Prof1983 @zenghang11 /ets2panda/test/test-lists/parser @chernykhsergey ^igelhaus ^Prof1983 -/ets2panda/test/unit/arktsconfig-parser @trubachevilya ^igelhaus ^Prof1983 +/ets2panda/test/unit/arktsconfig-parser @trubachevilya @dreamdoomwalker ^igelhaus ^Prof1983 /ets2panda/test/unit/lsp @dreamdoomwalker @utkugursel ^igelhaus ^Prof1983 /ets2panda/test/unit/plugin* @mbolshov ^igelhaus ^Prof1983 /ets2panda/test/unit/public @mbolshov ^igelhaus ^Prof1983 -- Gitee From 8bbb5bad829d29652982a3dfb66c7d549a0a85bf Mon Sep 17 00:00:00 2001 From: zhangkai366 Date: Wed, 4 Jun 2025 14:36:02 +0800 Subject: [PATCH 222/268] Fixed the bug of obf performance dotting tool Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICCMP4 Test: grammar&ut Signed-off-by: zhangkai366 Change-Id: Ifc2fa25b7fde078a2b9d85666058f16165c0f1c6 --- arkguard/src/transformers/rename/RenameFileNameTransformer.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/arkguard/src/transformers/rename/RenameFileNameTransformer.ts b/arkguard/src/transformers/rename/RenameFileNameTransformer.ts index bab1c891c3..eab7543b3b 100644 --- a/arkguard/src/transformers/rename/RenameFileNameTransformer.ts +++ b/arkguard/src/transformers/rename/RenameFileNameTransformer.ts @@ -101,7 +101,6 @@ namespace secharmony { const tempReservedName: string[] = ['.', '..', '']; configReservedFileNameOrPath.map(fileNameOrPath => { if (!fileNameOrPath || fileNameOrPath.length === 0) { - endFilesEvent(EventList.FILENAME_OBFUSCATION_INITIALIZATION); return; } const directories = FileUtils.splitFilePath(fileNameOrPath); -- Gitee From 687d104eb6dfedee05364a84c4cb1d370d71083a Mon Sep 17 00:00:00 2001 From: xiaopeiyang Date: Thu, 5 Jun 2025 10:07:53 +0800 Subject: [PATCH 223/268] Modify Reviewer Issue:[Bug]: Modify arkguard reviewer https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICCP4E Signed-off-by: xiaopeiyang Change-Id: I01cc92d49c165dba9303e0ada6d3c56aa4cfa14f --- ets2panda/REVIEWERS | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ets2panda/REVIEWERS b/ets2panda/REVIEWERS index 622f8ed652..9e256602ff 100644 --- a/ets2panda/REVIEWERS +++ b/ets2panda/REVIEWERS @@ -14,7 +14,7 @@ * @gavin1012_hw @zhuoli72 .* @zhuoli72 @Prof1983 @igelhaus -/arkguard/ @huangyu76 +/arkguard/ @xiao-peiyang /es2panda/ @gavin1012_hw /ets2panda/ @igelhaus @Prof1983 /ets2panda/aot @dkofanov @gavin1012_hw ^igelhaus ^Prof1983 -- Gitee From 16fccf4a9123fd2b98834266879b578ee3d0dcf3 Mon Sep 17 00:00:00 2001 From: guanmingyue Date: Thu, 5 Jun 2025 12:33:35 +0800 Subject: [PATCH 224/268] Update kfl 0605 Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICCRW4 Signed-off-by: guanmingyue --- test/workload/ignored-third_lib_js-release-x64-jit.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/workload/ignored-third_lib_js-release-x64-jit.txt b/test/workload/ignored-third_lib_js-release-x64-jit.txt index 573a56debb..63994fd7dd 100644 --- a/test/workload/ignored-third_lib_js-release-x64-jit.txt +++ b/test/workload/ignored-third_lib_js-release-x64-jit.txt @@ -1 +1,3 @@ # Known failures list for third_lib_js - release-x64-jit +#19623 +rebound_test -- Gitee From cd6e1557c07a066bc6572349ca5d021e3d26eb20 Mon Sep 17 00:00:00 2001 From: zhangzezhong Date: Wed, 28 May 2025 20:40:28 +0800 Subject: [PATCH 225/268] Fix atlntent not output to obfusion.txt Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC66QA Signed-off-by: zhangzezhong --- arkguard/src/initialization/ConfigResolver.ts | 14 ++++++-- arkguard/src/utils/ProjectCollections.ts | 32 +++++++++++-------- .../initialization/ConfigResolver-hsp.spec.ts | 5 +++ .../ut/initialization/ConfigResolver.spec.ts | 1 + 4 files changed, 37 insertions(+), 15 deletions(-) diff --git a/arkguard/src/initialization/ConfigResolver.ts b/arkguard/src/initialization/ConfigResolver.ts index d0019caca2..23731403ef 100644 --- a/arkguard/src/initialization/ConfigResolver.ts +++ b/arkguard/src/initialization/ConfigResolver.ts @@ -301,8 +301,8 @@ export class ObConfigResolver { } } - // when atKeep is enabled, we can not emit here since we need to collect names marked with atKeep - if (!mergedConfigs.options.enableAtKeep) { + // when obfuscation is enabled, we need to emit consumerConfig files after collecting whitelist. + if (!enableObfuscation) { this.emitConsumerConfigFiles(); } return mergedConfigs; @@ -944,6 +944,7 @@ export class ObConfigResolver { selfConsumerConfig.mergeAllRules(dependencyConfigs); } this.addKeepConsumer(selfConsumerConfig, AtKeepCollections.keepAsConsumer); + this.addIntentCollections(selfConsumerConfig, AtIntentCollections); selfConsumerConfig.sortAndDeduplicate(); this.writeConsumerConfigFile(selfConsumerConfig, sourceObConfig.exportRulePath); } @@ -957,6 +958,15 @@ export class ObConfigResolver { }); } + private addIntentCollections(selfConsumerConfig: MergedConfig, intentCollections: KeepInfo): void { + intentCollections.propertyNames.forEach((propertyName) => { + selfConsumerConfig.reservedPropertyNames.push(propertyName); + }); + intentCollections.globalNames.forEach((globalName) =>{ + selfConsumerConfig.reservedGlobalNames.push(globalName); + }); + } + public genConsumerConfigFilesForTest( sourceObConfig: SourceObConfig, selfConsumerConfig: MergedConfig, diff --git a/arkguard/src/utils/ProjectCollections.ts b/arkguard/src/utils/ProjectCollections.ts index a8b583fe60..e218b8b247 100644 --- a/arkguard/src/utils/ProjectCollections.ts +++ b/arkguard/src/utils/ProjectCollections.ts @@ -140,7 +140,7 @@ export interface FileKeepInfo { exported: KeepInfo; // Exported names and properties. enumProperties: Set; // Enum properties. stringProperties: Set; // String properties. - arkUIKeepInfo: KeepInfo; // Collecting classes and members + arkUIKeepInfo?: KeepInfo; // Collecting classes and members } export interface FileReservedInfo { @@ -339,10 +339,12 @@ export class ProjectWhiteListManager { }, enumProperties: arrayToSet(parsed[key].fileKeepInfo.enumProperties), stringProperties: arrayToSet(parsed[key].fileKeepInfo.stringProperties), - arkUIKeepInfo: { - propertyNames: arrayToSet(parsed[key].fileKeepInfo.arkUIKeepInfo.propertyNames), - globalNames: arrayToSet(parsed[key].fileKeepInfo.arkUIKeepInfo.globalNames), - }, + arkUIKeepInfo: parsed[key].fileKeepInfo.arkUIKeepInfo + ? { + propertyNames: arrayToSet(parsed[key].fileKeepInfo.arkUIKeepInfo.propertyNames), + globalNames: arrayToSet(parsed[key].fileKeepInfo.arkUIKeepInfo.globalNames), + } + : undefined, }; const fileReservedInfo: FileReservedInfo = { @@ -383,10 +385,12 @@ export class ProjectWhiteListManager { }, enumProperties: setToArray(value.fileKeepInfo.enumProperties), stringProperties: setToArray(value.fileKeepInfo.stringProperties), - arkUIKeepInfo: { - propertyNames: setToArray(value.fileKeepInfo.arkUIKeepInfo.propertyNames), - globalNames: setToArray(value.fileKeepInfo.arkUIKeepInfo.globalNames), - }, + arkUIKeepInfo: value.fileKeepInfo.arkUIKeepInfo + ? { + propertyNames: setToArray(value.fileKeepInfo.arkUIKeepInfo.propertyNames), + globalNames: setToArray(value.fileKeepInfo.arkUIKeepInfo.globalNames), + } + : undefined, }, fileReservedInfo: { enumProperties: setToArray(value.fileReservedInfo.enumProperties), @@ -506,11 +510,11 @@ export class ProjectWhiteListManager { }); // Collect arkUIKeepInfo - fileWhiteList.fileKeepInfo.arkUIKeepInfo.globalNames.forEach((globalName) => { + fileWhiteList.fileKeepInfo.arkUIKeepInfo?.globalNames.forEach((globalName) => { projectKeepInfo.globalNames.add(globalName); AtIntentCollections.globalNames.add(globalName); }); - fileWhiteList.fileKeepInfo.arkUIKeepInfo.propertyNames.forEach((propertyName) => { + fileWhiteList.fileKeepInfo.arkUIKeepInfo?.propertyNames.forEach((propertyName) => { projectKeepInfo.propertyNames.add(propertyName); AtIntentCollections.propertyNames.add(propertyName); }); @@ -575,8 +579,10 @@ export class ProjectWhiteListManager { addToSet(UnobfuscationCollections.reservedExportName, fileWhiteList.fileKeepInfo.exported.globalNames); addToSet(UnobfuscationCollections.reservedExportNameAndProp, fileWhiteList.fileKeepInfo.exported.propertyNames); addToSet(UnobfuscationCollections.reservedStrProp, fileWhiteList.fileKeepInfo.stringProperties); - addToSet(AtIntentCollections.propertyNames, fileWhiteList.fileKeepInfo.arkUIKeepInfo.propertyNames); - addToSet(AtIntentCollections.globalNames, fileWhiteList.fileKeepInfo.arkUIKeepInfo.globalNames); + if (fileWhiteList.fileKeepInfo.arkUIKeepInfo) { + addToSet(AtIntentCollections.propertyNames, fileWhiteList.fileKeepInfo.arkUIKeepInfo.propertyNames); + addToSet(AtIntentCollections.globalNames, fileWhiteList.fileKeepInfo.arkUIKeepInfo.globalNames); + } addToSet(ApiExtractor.mConstructorPropertySet, fileWhiteList.fileReservedInfo.propertyParams); addToSet(ApiExtractor.mEnumMemberSet, fileWhiteList.fileReservedInfo.enumProperties); const decoratorMap = fileWhiteList.bytecodeObfuscateKeepInfo?.decoratorMap; diff --git a/arkguard/test/ut/initialization/ConfigResolver-hsp.spec.ts b/arkguard/test/ut/initialization/ConfigResolver-hsp.spec.ts index 93c20dfafa..37031bc400 100644 --- a/arkguard/test/ut/initialization/ConfigResolver-hsp.spec.ts +++ b/arkguard/test/ut/initialization/ConfigResolver-hsp.spec.ts @@ -259,6 +259,7 @@ describe('hsp support consumerFiles', () => { localHspConfig.dependencies.hars.push(remoteHarObfFile); const hspResolver = new ObConfigResolver({ obfuscationOptions: localHspConfig, compileHar: false, compileShared: true }, printObfLogger); hspResolver.resolveObfuscationConfigs(); + hspResolver.emitConsumerConfigFiles(); const hspObfuscationContent = fs.readFileSync(localHspConfig.exportRulePath, 'utf-8'); expect(hspObfuscationContent).not.to.include('-disable-obfuscation'); @@ -334,6 +335,7 @@ describe('hsp support consumerFiles', () => { localHarConfig.dependencies.hspLibraries?.push(localHspConfig.selfConfig); const localHarResolver = new ObConfigResolver({ obfuscationOptions: localHarConfig, compileHar: true, compileShared: false }, printObfLogger); localHarResolver.resolveObfuscationConfigs(); + localHarResolver.emitConsumerConfigFiles(); const localHarObfuscationContent = fs.readFileSync(localHarConfig.exportRulePath, 'utf-8'); @@ -412,6 +414,7 @@ describe('hsp support consumerFiles', () => { localHarConfig.dependencies.hsps?.push(remoteHspObfFile); const localHarResolver = new ObConfigResolver({ obfuscationOptions: localHarConfig, compileHar: true, compileShared: false }, printObfLogger); localHarResolver.resolveObfuscationConfigs(); + localHarResolver.emitConsumerConfigFiles(); const localHarObfuscationContent = fs.readFileSync(localHarConfig.exportRulePath, 'utf-8'); @@ -589,6 +592,8 @@ describe('hsp support consumerFiles', () => { localMainHspConfig.dependencies.hsps?.push(remoteHspObfFile); const localMainHspResolver = new ObConfigResolver({ obfuscationOptions: localMainHspConfig, compileHar: false, compileShared: true }, printObfLogger); localMainHspResolver.resolveObfuscationConfigs(); + localMainHspResolver.emitConsumerConfigFiles(); + const localMainHspObfuscationContent = fs.readFileSync(localMainHspConfig.exportRulePath, 'utf-8'); expect(localMainHspObfuscationContent).not.to.include('-enable-filename-obfuscation'); diff --git a/arkguard/test/ut/initialization/ConfigResolver.spec.ts b/arkguard/test/ut/initialization/ConfigResolver.spec.ts index aba1673894..26c25a6592 100644 --- a/arkguard/test/ut/initialization/ConfigResolver.spec.ts +++ b/arkguard/test/ut/initialization/ConfigResolver.spec.ts @@ -2253,6 +2253,7 @@ describe('test for ConfigResolve', function() { AtKeepCollections.clear(); const obConfigResolver = new ObConfigResolver(projectConfig, printObfLogger); obConfigResolver.resolveObfuscationConfigs(); + obConfigResolver.emitConsumerConfigFiles(); const atKeepContent = fs.readFileSync(sourceObConfig.exportRulePath, 'utf-8'); expect(atKeepContent).to.include('-enable-property-obfuscation'); expect(atKeepContent).to.include('-keep-global-name'); -- Gitee From 6b4220cf600c4a55dbf7e92d94fa4d2228a227b6 Mon Sep 17 00:00:00 2001 From: liyue Date: Fri, 6 Jun 2025 15:31:51 +0800 Subject: [PATCH 226/268] CallThis instruction bound to property node Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICD6FK Signed-off-by: liyue Change-Id: I6acff199a777ceb5b684b74dffc886c6d854a666 --- es2panda/ir/expressions/callExpression.cpp | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/es2panda/ir/expressions/callExpression.cpp b/es2panda/ir/expressions/callExpression.cpp index 96085be9ab..cc1963c9c7 100644 --- a/es2panda/ir/expressions/callExpression.cpp +++ b/es2panda/ir/expressions/callExpression.cpp @@ -180,7 +180,11 @@ void CallExpression::Compile(compiler::PandaGen *pg) const realCallee->Compile(pg); } - pg->StoreAccumulator(this, callee); + if (realCallee->IsMemberExpression()) { + pg->StoreAccumulator(realCallee->AsMemberExpression()->Property(), callee); + } else { + pg->StoreAccumulator(this, callee); + } pg->GetOptionalChain()->CheckNullish(optional_, callee); if (containsSpread) { @@ -202,6 +206,16 @@ void CallExpression::Compile(compiler::PandaGen *pg) const } if (hasThis) { + /* + * To obtain more accurate line number information in the MemberExpression scenario, + * bind CallThis to the property node instead of the entire callee. + * especially for cases involving async stack tracing. + */ + if (realCallee->IsMemberExpression()) { + pg->CallThis(realCallee->AsMemberExpression()->Property(), callee, + static_cast(arguments_.size() + 1)); + return; + } pg->CallThis(this, callee, static_cast(arguments_.size() + 1)); return; } -- Gitee From 5f1efd093a2b804127909023fa95974117166889 Mon Sep 17 00:00:00 2001 From: xuxinjie4 Date: Sat, 7 Jun 2025 14:10:26 +0800 Subject: [PATCH 227/268] Change linter branch Signed-off-by: xuxinjie4 --- .../linter/scripts/install-ohos-typescript-and-homecheck.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ets2panda/linter/scripts/install-ohos-typescript-and-homecheck.mjs b/ets2panda/linter/scripts/install-ohos-typescript-and-homecheck.mjs index 5fc2c55baa..d4271589fe 100644 --- a/ets2panda/linter/scripts/install-ohos-typescript-and-homecheck.mjs +++ b/ets2panda/linter/scripts/install-ohos-typescript-and-homecheck.mjs @@ -90,7 +90,7 @@ function getTypescript(detectedOS) { fs.mkdirSync(third_party); } - let branch = process.env.TYPESCRIPT_BRANCH ?? 'OpenHarmony_feature_20250328' + let branch = process.env.TYPESCRIPT_BRANCH ?? 'master' if (detectedOS === 'Linux' || detectedOS === 'macOS') { let timeToWait = 5000 -- Gitee From a1d9f921025578171916a69d14e214b8c4bad1b5 Mon Sep 17 00:00:00 2001 From: cllvly Date: Fri, 6 Jun 2025 16:53:10 +0800 Subject: [PATCH 228/268] Add UT with cmc-gc Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICD2FX Signed-off-by: chenlong --- ...ignored-app_workload-cmc-gc-fastverify-qemu-int.txt | 4 ++++ .../ignored-jsperf-cmc-gc-release-qemu-int.txt | 5 +++++ ...gnored-third_lib_js-cmc-gc-fastverify-arm64-int.txt | 10 ++++++++++ ...ored-weekly_workload-cmc-gc-fastverify-qemu-int.txt | 8 ++++++++ test262/ignored-test262-cmc-gc-fastverify-qemu-int.txt | 4 ++++ 5 files changed, 31 insertions(+) create mode 100644 test/workload/ignored-app_workload-cmc-gc-fastverify-qemu-int.txt create mode 100644 test/workload/ignored-jsperf-cmc-gc-release-qemu-int.txt create mode 100644 test/workload/ignored-third_lib_js-cmc-gc-fastverify-arm64-int.txt create mode 100644 test/workload/ignored-weekly_workload-cmc-gc-fastverify-qemu-int.txt create mode 100644 test262/ignored-test262-cmc-gc-fastverify-qemu-int.txt diff --git a/test/workload/ignored-app_workload-cmc-gc-fastverify-qemu-int.txt b/test/workload/ignored-app_workload-cmc-gc-fastverify-qemu-int.txt new file mode 100644 index 0000000000..1ca281cb46 --- /dev/null +++ b/test/workload/ignored-app_workload-cmc-gc-fastverify-qemu-int.txt @@ -0,0 +1,4 @@ +# Known failures list for app_workload-cmc-gc-fastverify-qemu-int + +#26315 +shimo diff --git a/test/workload/ignored-jsperf-cmc-gc-release-qemu-int.txt b/test/workload/ignored-jsperf-cmc-gc-release-qemu-int.txt new file mode 100644 index 0000000000..4086047402 --- /dev/null +++ b/test/workload/ignored-jsperf-cmc-gc-release-qemu-int.txt @@ -0,0 +1,5 @@ +# Known failures list for jsperf - cmc-gc-release-qemu-int + +#26315 +Math_abs +TypedArray_toString diff --git a/test/workload/ignored-third_lib_js-cmc-gc-fastverify-arm64-int.txt b/test/workload/ignored-third_lib_js-cmc-gc-fastverify-arm64-int.txt new file mode 100644 index 0000000000..691283e3cb --- /dev/null +++ b/test/workload/ignored-third_lib_js-cmc-gc-fastverify-arm64-int.txt @@ -0,0 +1,10 @@ +# Known failures list for third_lib_js-cmc-gc-fastverify-arm64-int + +#26315 +jBox2d_test +jsDiff_test +crypto-js_test +brotli_test +memory-cache_test +mathjs_test +lodash_test \ No newline at end of file diff --git a/test/workload/ignored-weekly_workload-cmc-gc-fastverify-qemu-int.txt b/test/workload/ignored-weekly_workload-cmc-gc-fastverify-qemu-int.txt new file mode 100644 index 0000000000..d736b82390 --- /dev/null +++ b/test/workload/ignored-weekly_workload-cmc-gc-fastverify-qemu-int.txt @@ -0,0 +1,8 @@ +# Known failures list for weekly workload - cmc-gc-fastverify-qemu-int + +#26315 +fastarepeat +float-mm +typescript-compiler +wsl +json-parse-inspector diff --git a/test262/ignored-test262-cmc-gc-fastverify-qemu-int.txt b/test262/ignored-test262-cmc-gc-fastverify-qemu-int.txt new file mode 100644 index 0000000000..5e1d0f139b --- /dev/null +++ b/test262/ignored-test262-cmc-gc-fastverify-qemu-int.txt @@ -0,0 +1,4 @@ +# Known failure list for test262 - cmc-gc-fastverify-qemu-int + +#26315 +test262/data/test_es2021/intl402/supportedLocalesOf-unicode-extensions-ignored.js -- Gitee From 6aea05c7d3e34c53173774a5bd06dab36de20421 Mon Sep 17 00:00:00 2001 From: groshevmaksim Date: Mon, 9 Jun 2025 10:51:14 +0300 Subject: [PATCH 229/268] Change of reviewers list Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICDRIL Signed-off-by: groshevmaksim Change-Id: I0781a9b3e62677478cdf7d051b638dde2b9e13e3 --- ets2panda/REVIEWERS | 2 -- 1 file changed, 2 deletions(-) diff --git a/ets2panda/REVIEWERS b/ets2panda/REVIEWERS index 9e256602ff..fb870eeee4 100644 --- a/ets2panda/REVIEWERS +++ b/ets2panda/REVIEWERS @@ -58,7 +58,6 @@ /ets2panda/varbinder/ @lirismankarina @akmaevaleksey ^Ekkoruse ^zelentsovdmitry ^igelhaus ^Prof1983 /test/workload/ignored*.txt @shirunova_viktoria @kuchkovairina @gavin1012_hw @zhuheng27 /ets2panda/checker/ets/ @lirismankarina ^igelhaus ^Prof1983 -/ets2panda/checker/ets/dynamic.cpp @lirismankarina ^vpukhov ^igelhaus ^Prof1983 /ets2panda/checker/ets/function.cpp @gogabr ^vpukhov ^igelhaus ^Prof1983 /ets2panda/checker/ets/helpers.cpp @xuxjeeee @zelentsovdmitry ^igelhaus ^Prof1983 /ets2panda/checker/ets/object.cpp @xuxjeeee @zelentsovdmitry ^vpukhov ^igelhaus ^Prof1983 @@ -84,7 +83,6 @@ /ets2panda/test/unit/public @mbolshov ^igelhaus ^Prof1983 /ets2panda/checker/types/ets/Nullish.* ^vpukhov @gogabr ^igelhaus ^Prof1983 /ets2panda/checker/types/ets/etsA* @xuxjeeee ^gogabr ^igelhaus ^Prof1983 -/ets2panda/checker/types/ets/etsDynamicType.* ^vpukhov @gogabr ^igelhaus ^Prof1983 /ets2panda/checker/types/ets/etsE* @ziziziiziziz ^zelentsovdmitry ^igelhaus ^Prof1983 /ets2panda/checker/types/ets/etsFunctionType.* ^vpukhov @gogabr ^igelhaus ^Prof1983 /ets2panda/checker/types/ets/etsN* @ziziziiziziz ^zelentsovdmitry ^igelhaus ^Prof1983 -- Gitee From 9c87bc735a8d0df26f56cf0ae43d8cd36252e00c Mon Sep 17 00:00:00 2001 From: cllvly Date: Tue, 10 Jun 2025 09:37:31 +0800 Subject: [PATCH 230/268] Update Kfl 0609 Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICDV7C Signed-off-by: chenlong --- test/workload/ignored-third_lib_js-release-x64-jit.txt | 3 +++ test262/ignored-test262-cmc-gc-fastverify-qemu-int.txt | 1 + test262/ignored-test262-other-cmc-gc-fastverify-x64-int.txt | 4 ++++ 3 files changed, 8 insertions(+) create mode 100644 test262/ignored-test262-other-cmc-gc-fastverify-x64-int.txt diff --git a/test/workload/ignored-third_lib_js-release-x64-jit.txt b/test/workload/ignored-third_lib_js-release-x64-jit.txt index 63994fd7dd..8e46369b43 100644 --- a/test/workload/ignored-third_lib_js-release-x64-jit.txt +++ b/test/workload/ignored-third_lib_js-release-x64-jit.txt @@ -1,3 +1,6 @@ # Known failures list for third_lib_js - release-x64-jit #19623 rebound_test + +#23235 +pdfview_test diff --git a/test262/ignored-test262-cmc-gc-fastverify-qemu-int.txt b/test262/ignored-test262-cmc-gc-fastverify-qemu-int.txt index 5e1d0f139b..436f9331f2 100644 --- a/test262/ignored-test262-cmc-gc-fastverify-qemu-int.txt +++ b/test262/ignored-test262-cmc-gc-fastverify-qemu-int.txt @@ -2,3 +2,4 @@ #26315 test262/data/test_es2021/intl402/supportedLocalesOf-unicode-extensions-ignored.js +test262/data/test_es2021/intl402/supportedLocalesOf-consistent-with-resolvedOptions.js diff --git a/test262/ignored-test262-other-cmc-gc-fastverify-x64-int.txt b/test262/ignored-test262-other-cmc-gc-fastverify-x64-int.txt new file mode 100644 index 0000000000..6c816946ae --- /dev/null +++ b/test262/ignored-test262-other-cmc-gc-fastverify-x64-int.txt @@ -0,0 +1,4 @@ +# Known failure list for test262 -other -cmc-gc-fastverify-x64-int + +#25907 +test262/data/other_tests/built-ins/RegExp/property-escapes/generated/Script_Extensions_-Pau_Cin_Hau.js \ No newline at end of file -- Gitee From 9df64334a55e5456364cf8debbf69781f691fadb Mon Sep 17 00:00:00 2001 From: fanglou Date: Tue, 10 Jun 2025 10:25:56 +0800 Subject: [PATCH 231/268] fix homecheck timeout Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICDW36 Signed-off-by: fanglou Change-Id: I65353295231373c192520df9ef9a647cf68b1a9d --- ets2panda/linter/build_linter.py | 4 -- ets2panda/linter/src/cli/LinterCLI.ts | 18 +----- ets2panda/linter/src/lib/HomeCheck.ts | 84 --------------------------- 3 files changed, 1 insertion(+), 105 deletions(-) diff --git a/ets2panda/linter/build_linter.py b/ets2panda/linter/build_linter.py index cfc970134c..54bd9ce36a 100755 --- a/ets2panda/linter/build_linter.py +++ b/ets2panda/linter/build_linter.py @@ -265,15 +265,11 @@ def parse_args(): def main(): options = parse_args() - backup_package_files(options.source_path) - install_homecheck(options, 5, 3) install_typescript(options) node_modules_path = os.path.join(options.source_path, "node_modules") extract(options.typescript, node_modules_path, "typescript") build(options) copy_output(options) - clean_env(options.source_path) - if __name__ == '__main__': sys.exit(main()) diff --git a/ets2panda/linter/src/cli/LinterCLI.ts b/ets2panda/linter/src/cli/LinterCLI.ts index b5e9817221..b97aacc924 100644 --- a/ets2panda/linter/src/cli/LinterCLI.ts +++ b/ets2panda/linter/src/cli/LinterCLI.ts @@ -25,8 +25,6 @@ import { parseCommandLine } from './CommandLineParser'; import { compileLintOptions, getEtsLoaderPath } from '../lib/ts-compiler/Compiler'; import { logStatistics } from '../lib/statistics/StatisticsLogger'; import { arkts2Rules } from '../lib/utils/consts/ArkTS2Rules'; -import { MigrationTool } from 'homecheck'; -import { getHomeCheckConfigInfo, transferIssues2ProblemInfo } from '../lib/HomeCheck'; export function run(): void { const commandLineArgs = process.argv.slice(2); @@ -55,21 +53,7 @@ async function runIdeInteractiveMode(cmdOptions: CommandLineOptions): Promise(); const mergedProblems = new Map(); - - if (cmdOptions.homecheck === true) { - const { ruleConfigInfo, projectConfigInfo } = getHomeCheckConfigInfo(cmdOptions); - const migrationTool = new MigrationTool(ruleConfigInfo, projectConfigInfo); - await migrationTool.buildCheckEntry(); - const result = await migrationTool.start(); - - homeCheckResult = transferIssues2ProblemInfo(result); - for (const [filePath, problems] of homeCheckResult) { - if (!mergedProblems.has(filePath)) { - mergedProblems.set(filePath, []); - } - mergedProblems.get(filePath)!.push(...problems); - } - } + const result = lint(compileOptions, getEtsLoaderPath(compileOptions), homeCheckResult); for (const [filePath, problems] of result.problemsInfos) { diff --git a/ets2panda/linter/src/lib/HomeCheck.ts b/ets2panda/linter/src/lib/HomeCheck.ts index cbbdd29885..a60106beda 100644 --- a/ets2panda/linter/src/lib/HomeCheck.ts +++ b/ets2panda/linter/src/lib/HomeCheck.ts @@ -12,87 +12,3 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -import * as path from 'node:path'; -import type { FileIssues, RuleFix } from 'homecheck'; -import type { CommandLineOptions } from './CommandLineOptions'; -import type { ProblemInfo } from './ProblemInfo'; -import { FaultID } from './Problems'; - -interface RuleConfigInfo { - ruleSet: string[]; -} - -interface ProjectConfigInfo { - projectName: string | undefined; - projectPath: string | undefined; - logPath: string; - arkCheckPath: string; - ohosSdkPath: string; - hmsSdkPath: string; - reportDir: string; - languageTags: Map; - fileOrFolderToCheck: string[]; -} - -export function getHomeCheckConfigInfo(cmdOptions: CommandLineOptions): { - ruleConfigInfo: RuleConfigInfo; - projectConfigInfo: ProjectConfigInfo; -} { - const languageTags = new Map(); - const inputFiles = cmdOptions.inputFiles; - const ruleConfigInfo = { - ruleSet: ['plugin:@migration/all'], - files: ['**/*.ets', '**/*.ts', '**/*.js'] - }; - const projectConfigInfo = { - projectName: cmdOptions.arktsWholeProjectPath, - projectPath: cmdOptions.arktsWholeProjectPath, - logPath: './HomeCheck.log', - arkCheckPath: './node_modules/homecheck', - ohosSdkPath: cmdOptions.sdkDefaultApiPath ? cmdOptions.sdkDefaultApiPath : '', - hmsSdkPath: cmdOptions.sdkExternalApiPath ? cmdOptions.sdkExternalApiPath[0] : '', - reportDir: './', - languageTags: languageTags, - fileOrFolderToCheck: inputFiles - }; - return { ruleConfigInfo, projectConfigInfo }; -} - -export function transferIssues2ProblemInfo(fileIssuesArray: FileIssues[]): Map { - const result = new Map(); - fileIssuesArray.forEach((fileIssues) => { - fileIssues.issues.forEach((issueReport) => { - const defect = issueReport.defect; - const problemInfo: ProblemInfo = { - line: defect.reportLine, - column: defect.reportColumn, - endLine: defect.reportLine, - endColumn: defect.reportColumn, - start: 0, - end: 0, - type: '', - severity: defect.severity, - faultId: FaultID.LAST_ID, - problem: defect.problem, - suggest: '', - rule: defect.description, - ruleTag: -1, - autofixable: defect.fixable - }; - if (problemInfo.autofixable) { - const fix = issueReport.fix as RuleFix; - const replacementText = fix.text; - const start = fix.range[0]; - const end = fix.range[1]; - problemInfo.autofix = [{ replacementText, start, end }]; - problemInfo.autofixTitle = defect.ruleId; - } - const filePath = path.normalize(defect.mergeKey.split('%')[0]); - const problems = result.get(filePath) || []; - problems.push(problemInfo); - result.set(filePath, problems); - }); - }); - return result; -} -- Gitee From 2a788c3c4d5d77cf08b47b094837c860b27e2543 Mon Sep 17 00:00:00 2001 From: guanmingyue Date: Tue, 10 Jun 2025 20:39:47 +0800 Subject: [PATCH 232/268] Update kfl 0610 Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICE4EX Signed-off-by: guanmingyue --- .../ignored-third_lib_js-cmc-gc-fastverify-arm64-int.txt | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/test/workload/ignored-third_lib_js-cmc-gc-fastverify-arm64-int.txt b/test/workload/ignored-third_lib_js-cmc-gc-fastverify-arm64-int.txt index 691283e3cb..6653de140e 100644 --- a/test/workload/ignored-third_lib_js-cmc-gc-fastverify-arm64-int.txt +++ b/test/workload/ignored-third_lib_js-cmc-gc-fastverify-arm64-int.txt @@ -7,4 +7,10 @@ crypto-js_test brotli_test memory-cache_test mathjs_test -lodash_test \ No newline at end of file +lodash_test + +#24985 +qrcodegen_test + +#18745 +json-stringify-inspector -- Gitee From 843aed67089abf146d3bdb6e39ea19611e72957e Mon Sep 17 00:00:00 2001 From: quiet-thought Date: Wed, 11 Jun 2025 17:23:45 +0800 Subject: [PATCH 233/268] Add multi-context option for test Issue: https://gitee.com/openharmony/arkcompiler_ets_runtime/issues/ICCX81 Signed-off-by: quiet-thought Change-Id: I798eb807941f20bb95fa8a6c90cbe68f0299a03f --- test262/run_sunspider.py | 11 ++++++++++- test262/run_test262.py | 9 +++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/test262/run_sunspider.py b/test262/run_sunspider.py index 60c7e6f7a1..1e6310d80c 100755 --- a/test262/run_sunspider.py +++ b/test262/run_sunspider.py @@ -114,6 +114,8 @@ def parse_args(): help="Use abc2prog to generate abc, aot or pgo is not supported yet under this option") parser.add_argument('--disable-force-gc', action='store_true', help="Run test262 with close force-gc") + parser.add_argument('--multi-context', action='store_true', + help="Run test262 with multi context") parser.add_argument('--enable-arkguard', action='store_true', required=False, help="enable arkguard for 262 tests") @@ -141,6 +143,7 @@ class ArkProgram(): self.run_pgo = False self.enable_litecg = False self.disable_force_gc = False + self.multi_context = False self.run_jit = False self.run_baseline_jit = False self.ark_aot_tool = ARK_AOT_TOOL @@ -181,6 +184,9 @@ class ArkProgram(): if self.args.disable_force_gc: self.disable_force_gc = self.args.disable_force_gc + if self.args.multi_context: + self.multi_context = self.args.multi_context + if self.args.run_jit: self.run_jit = self.args.run_jit @@ -694,7 +700,10 @@ class ArkProgram(): asm_arg1 = "--enable-force-gc=true" if unforce_gc or self.disable_force_gc: asm_arg1 = "--enable-force-gc=false" - cmd_args = [self.ark_tool, icu_path, asm_arg1, + asm_arg2 = "--multi-context=false" + if self.multi_context: + asm_arg2 = "--multi-context=true" + cmd_args = [self.ark_tool, icu_path, asm_arg1, asm_arg2, f'{file_name_pre}.abc'] record_name = os.path.splitext(os.path.split(self.js_file)[1])[0] diff --git a/test262/run_test262.py b/test262/run_test262.py index 3a5e196373..484f63aa8c 100755 --- a/test262/run_test262.py +++ b/test262/run_test262.py @@ -157,6 +157,8 @@ def parse_args(): help="stub file") parser.add_argument('--disable-force-gc', action='store_true', help="Run test262 with close force-gc") + parser.add_argument('--multi-context', action='store_true', + help="Run test262 with multi context") parser.add_argument('--enable-arkguard', action='store_true', help="enable arkguard for 262 tests") @@ -758,6 +760,10 @@ def get_disable_force_gc(host_args, args): return host_args +def get_multi_context(args, host_args): + host_args += f"--multi-context " + + return host_args def get_host_args_of_stub_file(args, host_args): host_args += f"--stub-file={args.stub_file} " @@ -830,6 +836,9 @@ def get_host_args(args, host_type): if args.disable_force_gc: host_args = get_disable_force_gc(host_args, args) + if args.multi_context: + host_args = get_multi_context(args, host_args) + return host_args -- Gitee From 565e9034010c44c483ac5aea1ed3fc9ba1101125 Mon Sep 17 00:00:00 2001 From: cllvly Date: Thu, 12 Jun 2025 17:07:20 +0800 Subject: [PATCH 234/268] Update Kfl 0612 Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICEQBH Signed-off-by: chenlong --- .../ignored-weekly_workload-fastverify-qemu-aot-litecg.txt | 3 +++ test262/ignored-test262-other-cmc-gc-fastverify-x64-int.txt | 5 ++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/test/workload/ignored-weekly_workload-fastverify-qemu-aot-litecg.txt b/test/workload/ignored-weekly_workload-fastverify-qemu-aot-litecg.txt index 25fdaeede1..fb31da2b18 100644 --- a/test/workload/ignored-weekly_workload-fastverify-qemu-aot-litecg.txt +++ b/test/workload/ignored-weekly_workload-fastverify-qemu-aot-litecg.txt @@ -1,2 +1,5 @@ #19216 wsl + +#24985 +mandreel diff --git a/test262/ignored-test262-other-cmc-gc-fastverify-x64-int.txt b/test262/ignored-test262-other-cmc-gc-fastverify-x64-int.txt index 6c816946ae..7559623466 100644 --- a/test262/ignored-test262-other-cmc-gc-fastverify-x64-int.txt +++ b/test262/ignored-test262-other-cmc-gc-fastverify-x64-int.txt @@ -1,4 +1,7 @@ # Known failure list for test262 -other -cmc-gc-fastverify-x64-int #25907 -test262/data/other_tests/built-ins/RegExp/property-escapes/generated/Script_Extensions_-Pau_Cin_Hau.js \ No newline at end of file +test262/data/other_tests/built-ins/RegExp/property-escapes/generated/Script_Extensions_-Pau_Cin_Hau.js + +#26536 +test262/data/other_tests/language/statements/class/elements/after-same-line-static-async-gen-rs-private-method-alt.js \ No newline at end of file -- Gitee From 55f01a6bfc1c3ccff534e0bd29240c7a75c10276 Mon Sep 17 00:00:00 2001 From: hanlong Date: Tue, 17 Jun 2025 16:03:05 +0800 Subject: [PATCH 235/268] Update KFL 0617 Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICFSVP?from=project-issue Signed-off-by: hanlong --- .../ignored-weekly_workload-cmc-gc-fastverify-qemu-int.txt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/test/workload/ignored-weekly_workload-cmc-gc-fastverify-qemu-int.txt b/test/workload/ignored-weekly_workload-cmc-gc-fastverify-qemu-int.txt index d736b82390..09c6ed869d 100644 --- a/test/workload/ignored-weekly_workload-cmc-gc-fastverify-qemu-int.txt +++ b/test/workload/ignored-weekly_workload-cmc-gc-fastverify-qemu-int.txt @@ -6,3 +6,6 @@ float-mm typescript-compiler wsl json-parse-inspector + +#18740 +splay -- Gitee From 547b8f5babb3cebf3730ba2e3e5e0254be89e2a8 Mon Sep 17 00:00:00 2001 From: oh_ci Date: Thu, 19 Jun 2025 12:13:46 +0000 Subject: [PATCH 236/268] update .gitee/PULL_REQUEST_TEMPLATE.zh-CN.md. Signed-off-by: oh_ci --- .gitee/PULL_REQUEST_TEMPLATE.zh-CN.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md index f3d6c5e20a..7062489582 100644 --- a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md +++ b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md @@ -83,3 +83,7 @@ - [ ] 不涉及 **Email:** chenqiuyao@huawei.com + +### L0新增用例自检结果 +- [ ] 是,有新增L0用例,且完成自检 +- [ ] 否 -- Gitee From cfd1bd56f3e851a48766620a05f38b80cdf5a728 Mon Sep 17 00:00:00 2001 From: qianyong325 Date: Thu, 19 Jun 2025 15:59:26 +0800 Subject: [PATCH 237/268] =?UTF-8?q?external=5Fdeps=20=3D=20["ets=5Ffronten?= =?UTF-8?q?d:es2panda=E9=AA=8C=E8=AF=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICGDM6 Signed-off-by: qianyong325 --- es2panda/es2abc_config.gni | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/es2panda/es2abc_config.gni b/es2panda/es2abc_config.gni index 7f9c8c833a..7ca725e011 100644 --- a/es2panda/es2abc_config.gni +++ b/es2panda/es2abc_config.gni @@ -125,7 +125,15 @@ template("es2abc_gen_newest_abc") { script = "${es2abc_root}/scripts/generate_js_bytecode.py" deps = extra_dependencies - deps += es2abc_build_deps + if (host_toolchain == toolchain_mac) { + external_deps = ["ets_frontend:es2panda($toolchain_mac)"] + } else if (host_toolchain == toolchain_win) { + external_deps = ["ets_frontend:es2panda(${host_toolchain})"] + } else if (ark_standalone_build) { + deps += es2abc_build_deps + } else { + external_deps = ["ets_frontend:es2panda($toolchain_linux)"] + } args = [ "--src-js", -- Gitee From 1f15b2d8258c6dd9686bb63c6aacf4e859ee68ef Mon Sep 17 00:00:00 2001 From: liyue Date: Tue, 3 Jun 2025 15:25:59 +0800 Subject: [PATCH 238/268] Add API version compatibility test to checklist Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICC78U Signed-off-by: liyue Change-Id: I3b7619d1094a211aa4a4bc857052126050c930b0 --- .gitee/PULL_REQUEST_TEMPLATE.en.md | 74 +++++++++++++++++++++++++++ .gitee/PULL_REQUEST_TEMPLATE.zh-CN.md | 8 ++- 2 files changed, 81 insertions(+), 1 deletion(-) diff --git a/.gitee/PULL_REQUEST_TEMPLATE.en.md b/.gitee/PULL_REQUEST_TEMPLATE.en.md index 3758df1abd..e8d76c6d8c 100644 --- a/.gitee/PULL_REQUEST_TEMPLATE.en.md +++ b/.gitee/PULL_REQUEST_TEMPLATE.en.md @@ -12,3 +12,77 @@ _Please add detailed description_ ninja all tests ``` **All required pre-merge tests passed. Results are available in the internal CI.** + +#### Functional Testing (Mandatory unless the change only involves text) [wiki](https://gitee.com/openharmony/arkcompiler_ets_frontend/wikis/%E4%BB%A3%E7%A0%81%E6%8F%90%E4%BA%A4%E8%A6%81%E6%B1%82%E5%8F%8A%E6%B5%8B%E8%AF%95%E9%AA%8C%E8%AF%81%E6%B5%81%E7%A8%8B) +1. es2abc Test Cases (Debug Mode) +- [ ] Passed +- [ ] Not applicable, no need to verify + +2. Verifier Testing +- [ ] Passed +- [ ] Not applicable, no need to verify + +3. 64-bit RK Compilation +- [ ] Passed +- [ ] Not applicable, no need to verify + +4. Compile macOS SDK +- [ ] Passed +- [ ] Not applicable, no need to verify + +#### Obfuscation Testing (Mandatory if ArkGuard-related changes are involved) [wiki](https://gitee.com/openharmony/arkcompiler_ets_frontend/wikis/%E6%B7%B7%E6%B7%86%E6%B5%8B%E8%AF%95%E9%AA%8C%E8%AF%81%E6%B5%81%E7%A8%8B?sort_id=11451209) +1. Unit Tests +- [ ] Passed +- [ ] Not applicable, no need to verify + +2. Compiler Test Suite +- [ ] Passed +- [ ] Not applicable, no need to verify + +3. TSC Extra Test Suite +- [ ] Passed +- [ ] Not applicable, no need to verify + +4. Test262 Test Suite +- [ ] Passed +- [ ] Not applicable, no need to verify + +5. Benchmark Tests +- [ ] Passed +- [ ] Not applicable, no need to verify + +6. Automated Application Test Suite +- [ ] Passed +- [ ] Not applicable, no need to verify + +7. Global Variable Check — Were any global variables created? If so, were they cleared? +- [ ] Global variables created and cleared +- [ ] Global variables created but not cleared +- [ ] No global variables created + +#### Compatibility Testing (for instruction generation or file format changes) +1. Minor Version Compatibility Test +- [ ] Version number added +- [ ] Passed +- [ ] Not applicable, no need to verify + +2. Major Version Compatibility Test +- [ ] Passed +- [ ] Not applicable, no need to verify + +3. es2abc Version Compatibility Test +**Note: If the PR involves changes to version control test cases, you must also check its impact on other branches and confirm whether updates are needed in those branches.** +- [ ] Affected — Changes impact API/bytecode version and need to be synced to other branches +- [ ] Affected — Changes impact API/bytecode version but do not need to be synced to other branches +- [ ] Not affected — Changes do not involve API/bytecode version + +#### Performance Testing (e.g., new syntax checking scenarios) +- [ ] Passed +- [ ] Not applicable, no need to verify + +#### Command/abc format modification self-check, please contact the email below, synchronize to the relevant field +**Important: For modifications involving the abc2program, libpandafile and isa directories in the runtime_core repository, you must provide a compiled hap package for the helloworld project to the corresponding domain and contact the email address below.** +- [ ] Involved, already synchronized +- [ ] Not involved + +**Email:** wutao185@huawei.com \ No newline at end of file diff --git a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md index 7062489582..46d19c97b4 100644 --- a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md +++ b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md @@ -73,6 +73,12 @@ - [ ] 已通过 - [ ] 不涉及,无需验证 +3. es2abc版本兼容性测试 +**说明:如PR涉及版本控制用例的变更,需同步检查修改对其他分支的影响,并确认是否要同步受影响的分支** + - [ ] 涉及,变更影响 API/字节码 版本, 需同步修改到其他分支 + - [ ] 涉及,变更影响 API/字节码 版本, 无需同步到其他分支 + - [ ] 不涉及,变更不涉及 API/字节码 版本 + #### 性能测试 (新增语法检查等场景) - [ ] 已通过 - [ ] 不涉及,无需验证 @@ -82,7 +88,7 @@ - [ ] 涉及,已同步 - [ ] 不涉及 -**Email:** chenqiuyao@huawei.com +**Email:** wutao185@huawei.com ### L0新增用例自检结果 - [ ] 是,有新增L0用例,且完成自检 -- Gitee From de1e3ccd38d449cbecdeb5d17ebe8bd83ca884e6 Mon Sep 17 00:00:00 2001 From: lijunru Date: Wed, 18 Jun 2025 15:11:35 +0800 Subject: [PATCH 239/268] Adapt ohos independent build Issue: https://gitee.com/openharmony/arkcompiler_runtime_core/issues/ICFKLT Signed-off-by: lijunru --- bundle.json | 13 +++---- es2panda/BUILD.gn | 82 ++++++++++++++++++++++++++++++--------- es2panda/util/helpers.cpp | 9 ++--- ets2panda/BUILD.gn | 13 ++++++- ets2panda/aot/BUILD.gn | 4 ++ merge_abc/BUILD.gn | 40 +++++++++++++++---- 6 files changed, 120 insertions(+), 41 deletions(-) diff --git a/bundle.json b/bundle.json index aaab390cf3..bf8ba46efb 100644 --- a/bundle.json +++ b/bundle.json @@ -1,5 +1,5 @@ { - "name": "@arkcompiller/ets_frontend", + "name": "@ohos/ets_frontend", "description": "支持应用TS/JS语言代码的编译,行为符合ArkUI框架需要的Strict模式的ES2015标准", "version": "3.1", "license": "Apache License 2.0", @@ -22,12 +22,11 @@ "runtime_core", "zlib", "bounds_checking_function", - "protobuf" + "protobuf", + "icu", + "abseil-cpp" ], - "third_party": [ - "json", - "icu" - ] + "third_party": [] }, "build": { "sub_component": [ @@ -46,4 +45,4 @@ ] } } -} +} \ No newline at end of file diff --git a/es2panda/BUILD.gn b/es2panda/BUILD.gn index d7f663a2bb..56f0a55564 100644 --- a/es2panda/BUILD.gn +++ b/es2panda/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Copyright (c) 2021-2025 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -293,14 +293,18 @@ config("es2abc_config_src") { config("es2abc_config_common") { configs = [ "$ark_root:ark_config", - "$sdk_libc_secshared_config", "$ark_root/libpandafile:arkfile_public_config", "$ark_root/libpandabase:arkbase_public_config", "$ark_root/assembler:arkassembler_public_config", "$ark_root/abc2program:abc2program_public_config", - "$ark_third_party_root/json:nlohmann_json_config", ":es2abc_config_src", ] + if (defined(is_arkui_x) && is_arkui_x) { + configs += [ + "$sdk_libc_secshared_config", + "$ark_third_party_root/json:nlohmann_json_config", + ] + } if (enable_bytecode_optimizer) { defines = [ "ENABLE_BYTECODE_OPT" ] @@ -343,7 +347,11 @@ action_foreach("gen_keywords_headers") { # generate headers for es2panda compiler isa_gen = "${ark_root}/isa/gen.rb" -isa_gen_data = "$root_gen_dir/isa/isa.yaml" +if (defined(ohos_indep_compiler_enable) && ohos_indep_compiler_enable) { + isa_gen_data = "$root_build_dir/gen/isa/isa.yaml" +} else { + isa_gen_data = "$root_gen_dir/isa/isa.yaml" +} isa_gen_require = "${ark_root}/isa/isapi.rb" action_foreach("gen_isa_headers") { deps = [ "//arkcompiler/runtime_core/isa:isa_combine" ] @@ -361,11 +369,13 @@ action_foreach("gen_isa_headers") { outputs = [ "${generated_header_dir}/{{source_name_part}}" ] script = "scripts/gen_isa.sh" - inputs = [ - "${isa_gen}", - "${isa_gen_data}", - "${isa_gen_require}", - ] + if (defined(ohos_indep_compiler_enable) && !ohos_indep_compiler_enable) { + inputs = [ + "${isa_gen}", + "${isa_gen_data}", + "${isa_gen_require}", + ] + } args = [ "-g", rebase_path("${isa_gen}"), @@ -394,21 +404,25 @@ ohos_static_library("es2panda_lib") { "../merge_abc:panda_assembly_proto_public_config", ] - include_dirs = [ - "${target_out_dir}", - "//third_party/icu/icu4c/source/common", - "//third_party/icu/icu4c/source/i18n", - "//third_party/icu/icu4c/source", - ] + include_dirs = [ "${target_out_dir}" ] deps = [ ":gen_isa_headers", ":gen_keywords_headers", - "$ark_third_party_root/icu/icu4c:static_icuuc", "../merge_abc:panda_assembly_proto_static", ] + external_deps = [ sdk_libc_secshared_dep ] + if (ark_standalone_build || (defined(is_arkui_x) && is_arkui_x)) { + deps += [ "$ark_third_party_root/icu/icu4c:static_icuuc" ] + include_dirs += [ + "//third_party/icu/icu4c/source/common", + "//third_party/icu/icu4c/source/i18n", + "//third_party/icu/icu4c/source", + ] + } else { + external_deps += [ "icu:static_icuuc" ] + } - external_deps = [] if (!is_arkui_x) { external_deps += [ "json:nlohmann_json_static", @@ -451,7 +465,14 @@ ohos_static_library("es2panda_lib") { "-Wno-c++20-designator", "-Wno-implicit-fallthrough", ] - + if (defined(ohos_indep_compiler_enable) && ohos_indep_compiler_enable) { + external_deps += [ "runtime_core:libarkassembler_static" ] + if (enable_hilog) { + external_deps += [ "hilog:libhilog" ] + } + cflags += [ "-I" + rebase_path( + "$root_build_dir/gen/arkcompiler/runtime_core/compiler/generated") ] + } part_name = "ets_frontend" subsystem_name = "arkcompiler" } @@ -481,7 +502,30 @@ ohos_executable("es2panda") { "//arkcompiler/ets_frontend/merge_abc:panda_assembly_proto_static", ] - external_deps = [ "zlib:libz" ] + external_deps = [ + "json:nlohmann_json_static", + "zlib:libz", + sdk_libc_secshared_dep, + ] + + if (defined(ohos_indep_compiler_enable) && ohos_indep_compiler_enable) { + external_deps += [ + "abseil-cpp:absl_base_static", + "icu:shared_icuuc", + "runtime_core:libarkassembler_static", + ] + if (enable_hilog) { + external_deps += [ "hilog:libhilog" ] + } + cflags = [ + "-Wno-constant-conversion", + "-I" + rebase_path( + "$root_build_dir/gen/arkcompiler/runtime_core/bytecode_optimizer"), + "-I" + rebase_path( + "$root_build_dir/gen/arkcompiler/runtime_core/compiler/generated"), + ] + } + if (ark_standalone_build) { external_deps += [ "protobuf:protobuf_lite_static", diff --git a/es2panda/util/helpers.cpp b/es2panda/util/helpers.cpp index 30f0a4bc1c..02a0df64f1 100644 --- a/es2panda/util/helpers.cpp +++ b/es2panda/util/helpers.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -677,10 +677,9 @@ static std::string GetTempOutputName(const std::string &inputFile) void Helpers::AnalysisProgram(panda::pandasm::Program *prog, const std::string &inputFile) { +#ifdef PANDA_WITH_BYTECODE_OPTIMIZER std::map stat; std::map *statp = &stat; - -#ifdef PANDA_WITH_BYTECODE_OPTIMIZER auto tempOutput = GetTempOutputName(inputFile); bool exists = false; auto mapsp = &panda::bytecodeopt::BytecodeAnalysisResults::GetOrCreateBytecodeMaps(tempOutput, exists); @@ -701,11 +700,11 @@ void Helpers::AnalysisProgram(panda::pandasm::Program *prog, const std::string & void Helpers::OptimizeProgram(panda::pandasm::Program *prog, const std::string &inputFile) { - std::map stat; - std::map *statp = &stat; auto tempOutput = GetTempOutputName(inputFile); #ifdef PANDA_WITH_BYTECODE_OPTIMIZER + std::map stat; + std::map *statp = &stat; const uint32_t COMPONENT_MASK = panda::Logger::Component::ASSEMBLER | panda::Logger::Component::BYTECODE_OPTIMIZER | panda::Logger::Component::COMPILER; diff --git a/ets2panda/BUILD.gn b/ets2panda/BUILD.gn index 7542df6a82..a7d027eff5 100644 --- a/ets2panda/BUILD.gn +++ b/ets2panda/BUILD.gn @@ -1142,8 +1142,6 @@ ohos_source_set("libes2panda_frontend_static") { ":gen_es2panda_lexer_token_inl", ":isa_gen_es2panda_formats_h", ":isa_gen_es2panda_isa_h", - "$ark_third_party_root/icu/icu4c:static_icui18n", - "$ark_third_party_root/icu/icu4c:static_icuuc", ] external_deps = [ "runtime_core:libarktsassembler_package", @@ -1152,6 +1150,17 @@ ohos_source_set("libes2panda_frontend_static") { "runtime_core:libarktsfile_package", sdk_libc_secshared_dep, ] + if (ark_standalone_build || ark_static_standalone_build) { + deps += [ + "$ark_third_party_root/icu/icu4c:static_icui18n", + "$ark_third_party_root/icu/icu4c:static_icuuc", + ] + } else { + external_deps += [ + "icu:static_icui18n", + "icu:static_icuuc", + ] + } part_name = "ets_frontend" subsystem_name = "arkcompiler" } diff --git a/ets2panda/aot/BUILD.gn b/ets2panda/aot/BUILD.gn index 2a76c53b3d..0a8d75cffd 100644 --- a/ets2panda/aot/BUILD.gn +++ b/ets2panda/aot/BUILD.gn @@ -60,6 +60,10 @@ ohos_executable("ets2panda") { sdk_libc_secshared_dep, ] + if (defined(ohos_indep_compiler_enable) && ohos_indep_compiler_enable) { + external_deps += [ "icu:shared_icuuc" ] + } + libs = platform_libs ldflags = platform_ldflags if (is_linux) { diff --git a/merge_abc/BUILD.gn b/merge_abc/BUILD.gn index 54bdb3148c..a20f2b5607 100644 --- a/merge_abc/BUILD.gn +++ b/merge_abc/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. +# Copyright (c) 2022-2025 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -52,7 +52,6 @@ config("panda_assembly_proto_public_config") { } assembly_proto_configs = [ - sdk_libc_secshared_config, "$ark_root:ark_config", ":panda_assembly_proto_public_config", "$ark_root/assembler:arkassembler_public_config", @@ -60,6 +59,10 @@ assembly_proto_configs = [ "$ark_root/libpandafile:arkfile_public_config", ] +if (defined(is_arkui_x) && is_arkui_x) { + assembly_proto_configs += [ sdk_libc_secshared_config ] +} + proto_file_defines = [ # add your proto file here "annotation", @@ -91,7 +94,8 @@ foreach(proto_file, proto_file_defines) { protoc_binary_out_path = "${THIRDPARTY_PROTOBUF_SUBSYS_NAME}/${THIRDPARTY_PROTOBUF_PART_NAME}" -if (!ark_standalone_build) { +if (!ark_standalone_build && defined(ohos_indep_compiler_enable) && + !ohos_indep_compiler_enable) { if (default_toolchain == current_toolchain) { #if target build host_out_path = "/" + get_label_info(host_toolchain, "name") @@ -102,6 +106,10 @@ if (!ark_standalone_build) { host_protoc_path = root_out_dir + host_out_path + "/" + protoc_binary_out_path + "/protoc" +} else if (defined(ohos_indep_compiler_enable) && ohos_indep_compiler_enable) { + not_needed([ "protoc_binary_out_path" ]) + host_protoc_path = rebase_path( + "//binarys/third_party/protobuf/innerapis/protoc/clang_x64/libs/protoc") } else { host_protoc_path = get_label_info( @@ -110,7 +118,11 @@ if (!ark_standalone_build) { } action("arkcompiler_generate_proto") { - deps = [ "$ark_third_party_root/protobuf:protoc($host_toolchain)" ] + if (ark_standalone_build) { + deps = [ "$ark_third_party_root/protobuf:protoc($host_toolchain)" ] + } else { + external_deps = [ "protobuf:protoc($host_toolchain)" ] + } args = [] sources = [] outputs = proto_generated_header + proto_generated_source @@ -149,6 +161,7 @@ ohos_source_set("assembly_proto_static") { "runtime_core:libarkassembler_frontend_static", "runtime_core:libarkbase_frontend_static", "runtime_core:libarkfile_frontend_static", + sdk_libc_secshared_dep, ] } else { deps += [ @@ -160,6 +173,16 @@ ohos_source_set("assembly_proto_static") { ] } + if (defined(ohos_indep_compiler_enable) && ohos_indep_compiler_enable) { + external_deps += [ + "abseil-cpp:absl_base_static", + "runtime_core:libarkassembler_static", + ] + if (enable_hilog) { + external_deps += [ "hilog:libhilog" ] + } + } + sources = proto_generated_header + proto_generated_source + protobuf_snapshot_generator_sources public_configs = assembly_proto_configs @@ -196,7 +219,6 @@ ohos_executable("merge_abc") { include_dirs = [ "./src" ] configs = [ - sdk_libc_secshared_config, "$ark_root:ark_config", ":panda_assembly_proto_public_config", "$ark_root/assembler:arkassembler_public_config", @@ -207,12 +229,14 @@ ohos_executable("merge_abc") { deps = [ ":panda_assembly_proto_static", - "$ark_third_party_root/icu/icu4c:static_icuuc", "../es2panda:es2panda_lib", ] - + external_deps = [ + "icu:static_icuuc", + sdk_libc_secshared_dep, + ] if (!is_arkui_x) { - external_deps = [ "runtime_core:libarkziparchive_frontend_static" ] + external_deps += [ "runtime_core:libarkziparchive_frontend_static" ] } else { deps += [ "$ark_root/libziparchive:libarkziparchive_frontend_static" ] } -- Gitee From 5ea72e703a655aef0a5a87d9247d46711d3a08e3 Mon Sep 17 00:00:00 2001 From: qianyong325 Date: Mon, 16 Jun 2025 17:47:45 +0800 Subject: [PATCH 240/268] ets_frontend access control alarm modification Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICFJPC Signed-off-by: qianyong325 --- .../ast_verifier/invariants/arithmeticOperationValid.cpp | 2 +- ets2panda/ast_verifier/invariants/arithmeticOperationValid.h | 2 +- ets2panda/ast_verifier/invariants/checkAbstractMethod.h | 2 +- ets2panda/ast_verifier/invariants/checkConstProperties.h | 2 +- ets2panda/ast_verifier/invariants/checkScopeDeclaration.h | 2 +- ets2panda/ast_verifier/invariants/checkStructDeclaration.h | 2 +- ets2panda/ast_verifier/invariants/everyChildHasValidParent.h | 2 +- ets2panda/ast_verifier/invariants/everyChildInParentRange.h | 2 +- .../ast_verifier/invariants/forLoopCorrectlyInitialized.h | 2 +- ets2panda/ast_verifier/invariants/getterSetterValidation.h | 2 +- ets2panda/ast_verifier/invariants/identifierHasVariable.h | 2 +- ets2panda/ast_verifier/invariants/importExportAccessValid.cpp | 2 +- ets2panda/ast_verifier/invariants/importExportAccessValid.h | 2 +- ets2panda/ast_verifier/invariants/modifierAccessValid.cpp | 2 +- ets2panda/ast_verifier/invariants/modifierAccessValid.h | 2 +- ets2panda/ast_verifier/invariants/nodeHasParent.h | 2 +- ets2panda/ast_verifier/invariants/nodeHasSourceRange.h | 2 +- ets2panda/ast_verifier/invariants/nodeHasType.cpp | 2 +- ets2panda/ast_verifier/invariants/nodeHasType.h | 2 +- .../ast_verifier/invariants/referenceTypeAnnotationIsNull.h | 2 +- .../ast_verifier/invariants/sequenceExpressionHasLastType.h | 2 +- .../ast_verifier/invariants/variableHasEnclosingScope.cpp | 2 +- ets2panda/ast_verifier/invariants/variableHasEnclosingScope.h | 2 +- ets2panda/ast_verifier/invariants/variableHasScope.cpp | 2 +- ets2panda/ast_verifier/invariants/variableHasScope.h | 2 +- .../ast_verifier/invariants/variableNameIdentifierNameSame.h | 2 +- ets2panda/compiler/lowering/ets/localClassLowering.cpp | 2 +- ets2panda/lexer/regexp/regexp.h | 4 ++-- .../test/unit/plugin_ut/plugin_ut_binary_expression_api.cpp | 2 +- .../plugin_ut/plugin_ut_new_array_instance_expression_api.cpp | 2 +- ets2panda/test/unit/plugin_ut/plugin_ut_variables_api.cpp | 2 +- 31 files changed, 32 insertions(+), 32 deletions(-) diff --git a/ets2panda/ast_verifier/invariants/arithmeticOperationValid.cpp b/ets2panda/ast_verifier/invariants/arithmeticOperationValid.cpp index bb77859aed..bf6ab12646 100644 --- a/ets2panda/ast_verifier/invariants/arithmeticOperationValid.cpp +++ b/ets2panda/ast_verifier/invariants/arithmeticOperationValid.cpp @@ -19,7 +19,7 @@ #include "ir/ts/tsInterfaceDeclaration.h" #include "ir/ts/tsEnumDeclaration.h" #include "ir/ts/tsInterfaceBody.h" -#include "../helpers.h" +#include "ast_verifier/helpers.h" namespace ark::es2panda::compiler::ast_verifier { diff --git a/ets2panda/ast_verifier/invariants/arithmeticOperationValid.h b/ets2panda/ast_verifier/invariants/arithmeticOperationValid.h index 1afed1ea7f..ba478d93ec 100644 --- a/ets2panda/ast_verifier/invariants/arithmeticOperationValid.h +++ b/ets2panda/ast_verifier/invariants/arithmeticOperationValid.h @@ -16,7 +16,7 @@ #ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_ARITHMETICOPERATIONVALID_H #define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_ARITHMETICOPERATIONVALID_H -#include "../invariantBase.h" +#include "ast_verifier/invariantBase.h" namespace ark::es2panda::compiler::ast_verifier { diff --git a/ets2panda/ast_verifier/invariants/checkAbstractMethod.h b/ets2panda/ast_verifier/invariants/checkAbstractMethod.h index d2534f5483..174a685564 100644 --- a/ets2panda/ast_verifier/invariants/checkAbstractMethod.h +++ b/ets2panda/ast_verifier/invariants/checkAbstractMethod.h @@ -16,7 +16,7 @@ #ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_CHECKABSTRACTMETHOD_H #define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_CHECKABSTRACTMETHOD_H -#include "../invariantBase.h" +#include "ast_verifier/invariantBase.h" namespace ark::es2panda::compiler::ast_verifier { diff --git a/ets2panda/ast_verifier/invariants/checkConstProperties.h b/ets2panda/ast_verifier/invariants/checkConstProperties.h index 379e446e7a..a4a042b121 100644 --- a/ets2panda/ast_verifier/invariants/checkConstProperties.h +++ b/ets2panda/ast_verifier/invariants/checkConstProperties.h @@ -16,7 +16,7 @@ #ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_CHECKCONSTPROPERTIES_H #define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_CHECKCONSTPROPERTIES_H -#include "../invariantBase.h" +#include "ast_verifier/invariantBase.h" namespace ark::es2panda::compiler::ast_verifier { diff --git a/ets2panda/ast_verifier/invariants/checkScopeDeclaration.h b/ets2panda/ast_verifier/invariants/checkScopeDeclaration.h index f7766ab0b8..1137ee9848 100644 --- a/ets2panda/ast_verifier/invariants/checkScopeDeclaration.h +++ b/ets2panda/ast_verifier/invariants/checkScopeDeclaration.h @@ -16,7 +16,7 @@ #ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_CHECKSCOPEDECLARATION_H #define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_CHECKSCOPEDECLARATION_H -#include "../invariantBase.h" +#include "ast_verifier/invariantBase.h" namespace ark::es2panda::compiler::ast_verifier { diff --git a/ets2panda/ast_verifier/invariants/checkStructDeclaration.h b/ets2panda/ast_verifier/invariants/checkStructDeclaration.h index 931279a83c..aa6d9ffe53 100644 --- a/ets2panda/ast_verifier/invariants/checkStructDeclaration.h +++ b/ets2panda/ast_verifier/invariants/checkStructDeclaration.h @@ -16,7 +16,7 @@ #ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_CHECKSTRUCTDECLARATION_H #define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_CHECKSTRUCTDECLARATION_H -#include "../invariantBase.h" +#include "ast_verifier/invariantBase.h" namespace ark::es2panda::compiler::ast_verifier { diff --git a/ets2panda/ast_verifier/invariants/everyChildHasValidParent.h b/ets2panda/ast_verifier/invariants/everyChildHasValidParent.h index d18220f781..a2a3070c25 100644 --- a/ets2panda/ast_verifier/invariants/everyChildHasValidParent.h +++ b/ets2panda/ast_verifier/invariants/everyChildHasValidParent.h @@ -16,7 +16,7 @@ #ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_EVERYCHILDHASVALIDPARENT_H #define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_EVERYCHILDHASVALIDPARENT_H -#include "../invariantBase.h" +#include "ast_verifier/invariantBase.h" namespace ark::es2panda::compiler::ast_verifier { diff --git a/ets2panda/ast_verifier/invariants/everyChildInParentRange.h b/ets2panda/ast_verifier/invariants/everyChildInParentRange.h index c3406de3e0..fa25a46544 100644 --- a/ets2panda/ast_verifier/invariants/everyChildInParentRange.h +++ b/ets2panda/ast_verifier/invariants/everyChildInParentRange.h @@ -16,7 +16,7 @@ #ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_EVERYCHILDINPARENTRANGE_H #define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_EVERYCHILDINPARENTRANGE_H -#include "../invariantBase.h" +#include "ast_verifier/invariantBase.h" namespace ark::es2panda::compiler::ast_verifier { diff --git a/ets2panda/ast_verifier/invariants/forLoopCorrectlyInitialized.h b/ets2panda/ast_verifier/invariants/forLoopCorrectlyInitialized.h index 15c3e45451..ea2fa365dd 100644 --- a/ets2panda/ast_verifier/invariants/forLoopCorrectlyInitialized.h +++ b/ets2panda/ast_verifier/invariants/forLoopCorrectlyInitialized.h @@ -16,7 +16,7 @@ #ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_FORLOOPCORRECTLYINITIALIZED_H #define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_FORLOOPCORRECTLYINITIALIZED_H -#include "../invariantBase.h" +#include "ast_verifier/invariantBase.h" namespace ark::es2panda::compiler::ast_verifier { diff --git a/ets2panda/ast_verifier/invariants/getterSetterValidation.h b/ets2panda/ast_verifier/invariants/getterSetterValidation.h index 4f4b1d4aed..9d6bd4f221 100644 --- a/ets2panda/ast_verifier/invariants/getterSetterValidation.h +++ b/ets2panda/ast_verifier/invariants/getterSetterValidation.h @@ -16,7 +16,7 @@ #ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_GETTERSETTERVALIDATION_H #define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_GETTERSETTERVALIDATION_H -#include "../invariantBase.h" +#include "ast_verifier/invariantBase.h" namespace ark::es2panda::compiler::ast_verifier { diff --git a/ets2panda/ast_verifier/invariants/identifierHasVariable.h b/ets2panda/ast_verifier/invariants/identifierHasVariable.h index 8fc17ff9bb..72f9d27190 100644 --- a/ets2panda/ast_verifier/invariants/identifierHasVariable.h +++ b/ets2panda/ast_verifier/invariants/identifierHasVariable.h @@ -16,7 +16,7 @@ #ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_IDENTIFIERHASVARIABLE_H #define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_IDENTIFIERHASVARIABLE_H -#include "../invariantBase.h" +#include "ast_verifier/invariantBase.h" #include "ir/expressions/identifier.h" diff --git a/ets2panda/ast_verifier/invariants/importExportAccessValid.cpp b/ets2panda/ast_verifier/invariants/importExportAccessValid.cpp index 10a85bbdc0..035796aacc 100644 --- a/ets2panda/ast_verifier/invariants/importExportAccessValid.cpp +++ b/ets2panda/ast_verifier/invariants/importExportAccessValid.cpp @@ -14,7 +14,7 @@ */ #include "importExportAccessValid.h" -#include "../helpers.h" +#include "ast_verifier/helpers.h" #include "ir/expressions/callExpression.h" #include "checker/types/ets/etsObjectType.h" #include "ir/module/importSpecifier.h" diff --git a/ets2panda/ast_verifier/invariants/importExportAccessValid.h b/ets2panda/ast_verifier/invariants/importExportAccessValid.h index 7977ee3a56..1eaf3cb642 100644 --- a/ets2panda/ast_verifier/invariants/importExportAccessValid.h +++ b/ets2panda/ast_verifier/invariants/importExportAccessValid.h @@ -16,7 +16,7 @@ #ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_IMPORTEXPORTACCESSVALID_H #define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_IMPORTEXPORTACCESSVALID_H -#include "../invariantBase.h" +#include "ast_verifier/invariantBase.h" namespace ark::es2panda::compiler::ast_verifier { diff --git a/ets2panda/ast_verifier/invariants/modifierAccessValid.cpp b/ets2panda/ast_verifier/invariants/modifierAccessValid.cpp index 58ce2de70a..7f8875f7a9 100644 --- a/ets2panda/ast_verifier/invariants/modifierAccessValid.cpp +++ b/ets2panda/ast_verifier/invariants/modifierAccessValid.cpp @@ -14,7 +14,7 @@ */ #include "modifierAccessValid.h" -#include "../helpers.h" +#include "ast_verifier/helpers.h" #include "varbinder/variableFlags.h" #include "ir/expressions/memberExpression.h" #include "ir/expressions/callExpression.h" diff --git a/ets2panda/ast_verifier/invariants/modifierAccessValid.h b/ets2panda/ast_verifier/invariants/modifierAccessValid.h index a5fe690286..5889a24cb7 100644 --- a/ets2panda/ast_verifier/invariants/modifierAccessValid.h +++ b/ets2panda/ast_verifier/invariants/modifierAccessValid.h @@ -16,7 +16,7 @@ #ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_MODIFIERACCESSVALID_H #define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_MODIFIERACCESSVALID_H -#include "../invariantBase.h" +#include "ast_verifier/invariantBase.h" namespace ark::es2panda::compiler::ast_verifier { diff --git a/ets2panda/ast_verifier/invariants/nodeHasParent.h b/ets2panda/ast_verifier/invariants/nodeHasParent.h index c3f583c8d9..f5a77f9a3e 100644 --- a/ets2panda/ast_verifier/invariants/nodeHasParent.h +++ b/ets2panda/ast_verifier/invariants/nodeHasParent.h @@ -16,7 +16,7 @@ #ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_NODEHASPARENT_H #define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_NODEHASPARENT_H -#include "../invariantBase.h" +#include "ast_verifier/invariantBase.h" namespace ark::es2panda::compiler::ast_verifier { diff --git a/ets2panda/ast_verifier/invariants/nodeHasSourceRange.h b/ets2panda/ast_verifier/invariants/nodeHasSourceRange.h index fed802ecb7..a797369d03 100644 --- a/ets2panda/ast_verifier/invariants/nodeHasSourceRange.h +++ b/ets2panda/ast_verifier/invariants/nodeHasSourceRange.h @@ -16,7 +16,7 @@ #ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_NODEHASSOURCERANGE_H #define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_NODEHASSOURCERANGE_H -#include "../invariantBase.h" +#include "ast_verifier/invariantBase.h" namespace ark::es2panda::compiler::ast_verifier { diff --git a/ets2panda/ast_verifier/invariants/nodeHasType.cpp b/ets2panda/ast_verifier/invariants/nodeHasType.cpp index 4cfa95f5ca..4a57eda031 100644 --- a/ets2panda/ast_verifier/invariants/nodeHasType.cpp +++ b/ets2panda/ast_verifier/invariants/nodeHasType.cpp @@ -13,7 +13,7 @@ * limitations under the License. */ -#include "../helpers.h" +#include "ast_verifier/helpers.h" #include "nodeHasType.h" #include "ir/base/classDefinition.h" #include "ir/base/methodDefinition.h" diff --git a/ets2panda/ast_verifier/invariants/nodeHasType.h b/ets2panda/ast_verifier/invariants/nodeHasType.h index 81769166cf..12e7eaf4e6 100644 --- a/ets2panda/ast_verifier/invariants/nodeHasType.h +++ b/ets2panda/ast_verifier/invariants/nodeHasType.h @@ -16,7 +16,7 @@ #ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_NODEHASTYPE_H #define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_NODEHASTYPE_H -#include "../invariantBase.h" +#include "ast_verifier/invariantBase.h" #include "checker/types/type.h" namespace ark::es2panda::compiler::ast_verifier { diff --git a/ets2panda/ast_verifier/invariants/referenceTypeAnnotationIsNull.h b/ets2panda/ast_verifier/invariants/referenceTypeAnnotationIsNull.h index e0e7bcaf36..562cc47cb1 100644 --- a/ets2panda/ast_verifier/invariants/referenceTypeAnnotationIsNull.h +++ b/ets2panda/ast_verifier/invariants/referenceTypeAnnotationIsNull.h @@ -16,7 +16,7 @@ #ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_REFERENCETYPEANNOTATIONISNULL_H #define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_REFERENCETYPEANNOTATIONISNULL_H -#include "../invariantBase.h" +#include "ast_verifier/invariantBase.h" namespace ark::es2panda::compiler::ast_verifier { diff --git a/ets2panda/ast_verifier/invariants/sequenceExpressionHasLastType.h b/ets2panda/ast_verifier/invariants/sequenceExpressionHasLastType.h index c39f505072..7b4f0760cb 100644 --- a/ets2panda/ast_verifier/invariants/sequenceExpressionHasLastType.h +++ b/ets2panda/ast_verifier/invariants/sequenceExpressionHasLastType.h @@ -16,7 +16,7 @@ #ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_SEQUENCEEXPRESSIONHASLASTTYPE_H #define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_SEQUENCEEXPRESSIONHASLASTTYPE_H -#include "../invariantBase.h" +#include "ast_verifier/invariantBase.h" namespace ark::es2panda::compiler::ast_verifier { diff --git a/ets2panda/ast_verifier/invariants/variableHasEnclosingScope.cpp b/ets2panda/ast_verifier/invariants/variableHasEnclosingScope.cpp index 1aa6f1abf0..08ae83ddcb 100644 --- a/ets2panda/ast_verifier/invariants/variableHasEnclosingScope.cpp +++ b/ets2panda/ast_verifier/invariants/variableHasEnclosingScope.cpp @@ -15,7 +15,7 @@ #include "variableHasEnclosingScope.h" #include "variableHasScope.h" -#include "../helpers.h" +#include "ast_verifier/helpers.h" namespace ark::es2panda::compiler::ast_verifier { diff --git a/ets2panda/ast_verifier/invariants/variableHasEnclosingScope.h b/ets2panda/ast_verifier/invariants/variableHasEnclosingScope.h index 5d0cf63698..fa75e280f0 100644 --- a/ets2panda/ast_verifier/invariants/variableHasEnclosingScope.h +++ b/ets2panda/ast_verifier/invariants/variableHasEnclosingScope.h @@ -16,7 +16,7 @@ #ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_VARIABLEHASENCLOSINGSCOPE_H #define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_VARIABLEHASENCLOSINGSCOPE_H -#include "../invariantBase.h" +#include "ast_verifier/invariantBase.h" namespace ark::es2panda::compiler::ast_verifier { diff --git a/ets2panda/ast_verifier/invariants/variableHasScope.cpp b/ets2panda/ast_verifier/invariants/variableHasScope.cpp index 0e072bf384..9b18ba8289 100644 --- a/ets2panda/ast_verifier/invariants/variableHasScope.cpp +++ b/ets2panda/ast_verifier/invariants/variableHasScope.cpp @@ -13,7 +13,7 @@ * limitations under the License. */ -#include "../helpers.h" +#include "ast_verifier/helpers.h" #include "variableHasScope.h" #include "ir/base/scriptFunction.h" #include "ir/ts/tsEnumDeclaration.h" diff --git a/ets2panda/ast_verifier/invariants/variableHasScope.h b/ets2panda/ast_verifier/invariants/variableHasScope.h index 41d067774e..a6c7741c94 100644 --- a/ets2panda/ast_verifier/invariants/variableHasScope.h +++ b/ets2panda/ast_verifier/invariants/variableHasScope.h @@ -16,7 +16,7 @@ #ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_VARIABLEHASSCOPE_H #define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_VARIABLEHASSCOPE_H -#include "../invariantBase.h" +#include "ast_verifier/invariantBase.h" #include "varbinder/varbinder.h" diff --git a/ets2panda/ast_verifier/invariants/variableNameIdentifierNameSame.h b/ets2panda/ast_verifier/invariants/variableNameIdentifierNameSame.h index 5eb9e85e21..211c166828 100644 --- a/ets2panda/ast_verifier/invariants/variableNameIdentifierNameSame.h +++ b/ets2panda/ast_verifier/invariants/variableNameIdentifierNameSame.h @@ -16,7 +16,7 @@ #ifndef ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_VARIABLENAMEIDENTIFIERNAMESAME_H #define ES2PANDA_COMPILER_CORE_AST_VERIFIER_INVARIANTS_VARIABLENAMEIDENTIFIERNAMESAME_H -#include "../invariantBase.h" +#include "ast_verifier/invariantBase.h" namespace ark::es2panda::compiler::ast_verifier { diff --git a/ets2panda/compiler/lowering/ets/localClassLowering.cpp b/ets2panda/compiler/lowering/ets/localClassLowering.cpp index 5153b0be11..7b1de4c561 100644 --- a/ets2panda/compiler/lowering/ets/localClassLowering.cpp +++ b/ets2panda/compiler/lowering/ets/localClassLowering.cpp @@ -16,7 +16,7 @@ #include "localClassLowering.h" #include "checker/ETSchecker.h" -#include "../util.h" +#include "compiler/lowering/util.h" namespace ark::es2panda::compiler { diff --git a/ets2panda/lexer/regexp/regexp.h b/ets2panda/lexer/regexp/regexp.h index 445659c557..42c11f4f10 100644 --- a/ets2panda/lexer/regexp/regexp.h +++ b/ets2panda/lexer/regexp/regexp.h @@ -1,5 +1,5 @@ /** - * Copyright (c) 2021-2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -19,7 +19,7 @@ #include "util/enumbitops.h" #include "util/ustring.h" -#include "../../parser/parserImpl.h" +#include "parser/parserImpl.h" #include diff --git a/ets2panda/test/unit/plugin_ut/plugin_ut_binary_expression_api.cpp b/ets2panda/test/unit/plugin_ut/plugin_ut_binary_expression_api.cpp index 42e150fa9f..ac6bcbb874 100644 --- a/ets2panda/test/unit/plugin_ut/plugin_ut_binary_expression_api.cpp +++ b/ets2panda/test/unit/plugin_ut/plugin_ut_binary_expression_api.cpp @@ -19,7 +19,7 @@ #include #include #include -#include "../plugin/util.h" +#include "test/unit/plugin/util.h" #include "public/es2panda_lib.h" // NOLINTBEGIN diff --git a/ets2panda/test/unit/plugin_ut/plugin_ut_new_array_instance_expression_api.cpp b/ets2panda/test/unit/plugin_ut/plugin_ut_new_array_instance_expression_api.cpp index 14c55feb30..2b1a73020d 100644 --- a/ets2panda/test/unit/plugin_ut/plugin_ut_new_array_instance_expression_api.cpp +++ b/ets2panda/test/unit/plugin_ut/plugin_ut_new_array_instance_expression_api.cpp @@ -19,7 +19,7 @@ #include #include #include -#include "../plugin/util.h" +#include "test/unit/plugin/util.h" #include "public/es2panda_lib.h" // NOLINTBEGIN diff --git a/ets2panda/test/unit/plugin_ut/plugin_ut_variables_api.cpp b/ets2panda/test/unit/plugin_ut/plugin_ut_variables_api.cpp index b9752c7f48..d96ab188a3 100644 --- a/ets2panda/test/unit/plugin_ut/plugin_ut_variables_api.cpp +++ b/ets2panda/test/unit/plugin_ut/plugin_ut_variables_api.cpp @@ -20,7 +20,7 @@ #include #include #include -#include "../plugin/util.h" +#include "test/unit/plugin/util.h" #include "public/es2panda_lib.h" // NOLINTBEGIN -- Gitee From a1b75bebaa093353d3365c8d4613d1e54bd56533 Mon Sep 17 00:00:00 2001 From: qianyong325 Date: Sat, 21 Jun 2025 15:45:46 +0800 Subject: [PATCH 241/268] =?UTF-8?q?=E7=8B=AC=E7=AB=8B=E7=BC=96=E8=AF=91?= =?UTF-8?q?=E5=91=8A=E8=AD=A6=E6=B6=88=E9=99=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICGTYF Signed-off-by: qianyong325 --- es2panda/es2abc_config.gni | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/es2panda/es2abc_config.gni b/es2panda/es2abc_config.gni index 7ca725e011..9427086588 100644 --- a/es2panda/es2abc_config.gni +++ b/es2panda/es2abc_config.gni @@ -64,7 +64,17 @@ template("es2abc_gen_abc") { script = "${es2abc_root}/scripts/generate_js_bytecode.py" deps = extra_dependencies - deps += es2abc_build_deps + if (ark_standalone_build || is_arkui_x) { + deps += es2abc_build_deps + } else { + if (host_toolchain == toolchain_mac) { + external_deps = ["ets_frontend:es2panda($toolchain_mac)"] + } else if (host_toolchain == toolchain_win) { + external_deps = ["ets_frontend:es2panda(${host_toolchain})"] + } else { + external_deps = ["ets_frontend:es2panda($toolchain_linux)"] + } + } args = [ "--src-js", -- Gitee From 431dcf0379f59ceb9bfc39b8a2a7d87de88be6c5 Mon Sep 17 00:00:00 2001 From: daizihan Date: Thu, 22 May 2025 09:51:53 +0800 Subject: [PATCH 242/268] Fix reexport bug with relative path Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC9KUQ?from=project-issue Signed-off-by: daizihan --- ets2panda/parser/ETSparser.cpp | 2 +- .../test/ast/parser/ets/re_export/export_5.ets | 18 ++++++++++++++++++ .../test/ast/parser/ets/re_export/export_6.ets | 18 ++++++++++++++++++ .../ast/parser/ets/re_export/re_export_16.ets | 16 ++++++++++++++++ .../srcdumper/srcdumper-ets-ignored.txt | 3 +++ 5 files changed, 56 insertions(+), 1 deletion(-) create mode 100644 ets2panda/test/ast/parser/ets/re_export/export_5.ets create mode 100644 ets2panda/test/ast/parser/ets/re_export/export_6.ets create mode 100644 ets2panda/test/ast/parser/ets/re_export/re_export_16.ets diff --git a/ets2panda/parser/ETSparser.cpp b/ets2panda/parser/ETSparser.cpp index 9aa2bcd87f..5364fc13da 100644 --- a/ets2panda/parser/ETSparser.cpp +++ b/ets2panda/parser/ETSparser.cpp @@ -996,7 +996,7 @@ ir::Statement *ETSParser::ParseExport(lexer::SourcePosition startLoc, ir::Modifi // re-export directive auto *reExportDeclaration = ParseImportPathBuildImport(std::move(specifiers), true, startLoc, ir::ImportKinds::ALL); auto reExport = AllocNode(reExportDeclaration, std::vector(), - GetProgram()->SourceFilePath(), Allocator()); + GetProgram()->AbsoluteName(), Allocator()); reExport->AddModifier(modifiers); return reExport; } diff --git a/ets2panda/test/ast/parser/ets/re_export/export_5.ets b/ets2panda/test/ast/parser/ets/re_export/export_5.ets new file mode 100644 index 0000000000..745a950975 --- /dev/null +++ b/ets2panda/test/ast/parser/ets/re_export/export_5.ets @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {test2} from './re_export_16' + +export class test1 {} diff --git a/ets2panda/test/ast/parser/ets/re_export/export_6.ets b/ets2panda/test/ast/parser/ets/re_export/export_6.ets new file mode 100644 index 0000000000..1628fe5be5 --- /dev/null +++ b/ets2panda/test/ast/parser/ets/re_export/export_6.ets @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {test1} from './export_5' + +export class test2 {} diff --git a/ets2panda/test/ast/parser/ets/re_export/re_export_16.ets b/ets2panda/test/ast/parser/ets/re_export/re_export_16.ets new file mode 100644 index 0000000000..e98c8fe230 --- /dev/null +++ b/ets2panda/test/ast/parser/ets/re_export/re_export_16.ets @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export {test2} from './export_6' \ No newline at end of file diff --git a/ets2panda/test/test-lists/srcdumper/srcdumper-ets-ignored.txt b/ets2panda/test/test-lists/srcdumper/srcdumper-ets-ignored.txt index c44899c0eb..c63c252969 100644 --- a/ets2panda/test/test-lists/srcdumper/srcdumper-ets-ignored.txt +++ b/ets2panda/test/test-lists/srcdumper/srcdumper-ets-ignored.txt @@ -17,6 +17,9 @@ ast/parser/ets/import_tests/export_and_import_class.ets ast/parser/ets/import_tests/export_and_import_top_level.ets ast/parser/ets/re_export/import_11.ets ast/parser/ets/re_export/import_12.ets +ast/parser/ets/re_export/export_5.ets +ast/parser/ets/re_export/export_6.ets +ast/parser/ets/re_export/re_export_16.ets ast/parser/ets/re_export/re_export_11.ets ast/parser/ets/re_export/re_export_12.ets ast/parser/ets/re_export/re_export_5.ets -- Gitee From 7bf5cbfac9935d8bd06d82969f81733e58bd651b Mon Sep 17 00:00:00 2001 From: 18157154025 Date: Mon, 23 Jun 2025 17:24:13 +0800 Subject: [PATCH 243/268] Frontend unshielded use cases Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICHUPM?from=project-issue Signed-off-by: 18157154025 Change-Id: I806547e8a454e9ee3ec471caada7c62b3047b9b7 --- .../ignored-app_workload-cmc-gc-fastverify-qemu-int.txt | 1 - test/workload/ignored-jsperf-cmc-gc-release-qemu-int.txt | 2 -- .../ignored-third_lib_js-cmc-gc-fastverify-arm64-int.txt | 7 ++----- .../ignored-weekly_workload-cmc-gc-fastverify-qemu-int.txt | 3 +-- 4 files changed, 3 insertions(+), 10 deletions(-) diff --git a/test/workload/ignored-app_workload-cmc-gc-fastverify-qemu-int.txt b/test/workload/ignored-app_workload-cmc-gc-fastverify-qemu-int.txt index 1ca281cb46..9994f0e3a4 100644 --- a/test/workload/ignored-app_workload-cmc-gc-fastverify-qemu-int.txt +++ b/test/workload/ignored-app_workload-cmc-gc-fastverify-qemu-int.txt @@ -1,4 +1,3 @@ # Known failures list for app_workload-cmc-gc-fastverify-qemu-int #26315 -shimo diff --git a/test/workload/ignored-jsperf-cmc-gc-release-qemu-int.txt b/test/workload/ignored-jsperf-cmc-gc-release-qemu-int.txt index 4086047402..1886f6b8cb 100644 --- a/test/workload/ignored-jsperf-cmc-gc-release-qemu-int.txt +++ b/test/workload/ignored-jsperf-cmc-gc-release-qemu-int.txt @@ -1,5 +1,3 @@ # Known failures list for jsperf - cmc-gc-release-qemu-int #26315 -Math_abs -TypedArray_toString diff --git a/test/workload/ignored-third_lib_js-cmc-gc-fastverify-arm64-int.txt b/test/workload/ignored-third_lib_js-cmc-gc-fastverify-arm64-int.txt index 6653de140e..659263de78 100644 --- a/test/workload/ignored-third_lib_js-cmc-gc-fastverify-arm64-int.txt +++ b/test/workload/ignored-third_lib_js-cmc-gc-fastverify-arm64-int.txt @@ -4,13 +4,10 @@ jBox2d_test jsDiff_test crypto-js_test -brotli_test memory-cache_test -mathjs_test -lodash_test #24985 -qrcodegen_test + #18745 -json-stringify-inspector + diff --git a/test/workload/ignored-weekly_workload-cmc-gc-fastverify-qemu-int.txt b/test/workload/ignored-weekly_workload-cmc-gc-fastverify-qemu-int.txt index 09c6ed869d..89d7ef91d9 100644 --- a/test/workload/ignored-weekly_workload-cmc-gc-fastverify-qemu-int.txt +++ b/test/workload/ignored-weekly_workload-cmc-gc-fastverify-qemu-int.txt @@ -1,11 +1,10 @@ # Known failures list for weekly workload - cmc-gc-fastverify-qemu-int #26315 -fastarepeat +json-parse-inspector float-mm typescript-compiler wsl -json-parse-inspector #18740 splay -- Gitee From 9edd42e1945ae2c83fadb138b4d2a19d82a0d0bc Mon Sep 17 00:00:00 2001 From: zhangkai366 Date: Thu, 26 Jun 2025 17:06:54 +0800 Subject: [PATCH 244/268] Fixed the bug of obfuscation increments Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICI26Z Test: grammar&ut Signed-off-by: zhangkai366 --- arkguard/src/transformers/rename/RenameIdentifierTransformer.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/arkguard/src/transformers/rename/RenameIdentifierTransformer.ts b/arkguard/src/transformers/rename/RenameIdentifierTransformer.ts index a0df5ff66a..f27fda5560 100644 --- a/arkguard/src/transformers/rename/RenameIdentifierTransformer.ts +++ b/arkguard/src/transformers/rename/RenameIdentifierTransformer.ts @@ -875,7 +875,6 @@ namespace secharmony { tmpReservedProps.forEach(item => { PropCollections.reservedProperties.add(item); }); - PropCollections.globalMangledNamesInCache = new Set(PropCollections.historyMangledTable?.values()); addToSet(PropCollections.reservedProperties, AtKeepCollections.keepSymbol.propertyNames); addToSet(PropCollections.reservedProperties, AtKeepCollections.keepAsConsumer.propertyNames); addToSet(PropCollections.reservedProperties, AtIntentCollections.propertyNames); @@ -893,6 +892,7 @@ namespace secharmony { UnobfuscationCollections.reservedSdkApiForProp.add(element); }); } + PropCollections.globalMangledNamesInCache = new Set(PropCollections.historyMangledTable?.values()); LocalVariableCollections.reservedConfig = new Set(profile?.mReservedNames ?? []); profile?.mReservedToplevelNames?.forEach(item => PropCollections.reservedProperties.add(item)); addToSet(PropCollections.reservedProperties, AtKeepCollections.keepSymbol.globalNames); -- Gitee From 2e30d89eccbb4c00e19795edcf25e503c19f53e5 Mon Sep 17 00:00:00 2001 From: oh_ci Date: Fri, 27 Jun 2025 09:37:05 +0000 Subject: [PATCH 245/268] update .gitee/PULL_REQUEST_TEMPLATE.zh-CN.md. Signed-off-by: oh_ci --- .gitee/PULL_REQUEST_TEMPLATE.zh-CN.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md index 46d19c97b4..b2eed2595f 100644 --- a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md +++ b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md @@ -90,6 +90,6 @@ **Email:** wutao185@huawei.com -### L0新增用例自检结果 -- [ ] 是,有新增L0用例,且完成自检 -- [ ] 否 +### 是否已执行L0用例 +- [ ] 已验证 +- [ ] 不涉及。如不涉及,请写明理由 -- Gitee From 0f3b11bf80508a321e887830d3b4ade5e0cf8668 Mon Sep 17 00:00:00 2001 From: xingshunxiang Date: Mon, 23 Jun 2025 15:29:46 +0800 Subject: [PATCH 246/268] Fix several bugs from fuzzing case Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICHJSW?from=project-issue Description: some crash bugs from fuzzer Reason: 1. in case1, {@@} will invoke the ETSFormattedParse, if the insertNode is empty, it will return BrokenType and Throw logError, BrokenType will cause nullptr segV in EnumCheck, since it have no tsType, so subsitute it with BrokenExpression, it will has typeError as tsType. 2. in case2, some poccessing of boolean had been lost, now add it. // case2 cannot reproduce on master, related change were dropped 3. in case3, parser goes into TypedParser and return an unsupported astnode, so override the related function to return the correct astnode 4. in case4, invalid namespace inside blockstatement cannot be transfered to classDefinition, so cause SegV in the later lowering Tests: ninja tests passed tests/tests-u-runner/runner.sh --ets-cts --show-progress --build-dir x64.release --processes=all passed tests/tests-u-runner/runner.sh --ets-func-tests --show-progress --build-dir x64.release --processes=all passed tests/tests-u-runner/runner.sh --astchecker --show-progress --build-dir x64.release --processes=all passed tests/tests-u-runner/runner.sh --ets-runtime --show-progress --build-dir x64.release --processes=all passed tests/tests-u-runner/runner.sh --parser --no-js --show-progress --build-dir x64.release --processes=all passed Signed-off-by: xingshunxiang --- .../ets/topLevelStmts/globalClassHandler.cpp | 4 --- .../ets/topLevelStmts/globalClassHandler.h | 2 +- ets2panda/parser/ETSFormattedParser.cpp | 2 +- ets2panda/parser/ETSparser.h | 2 +- ets2panda/parser/ETSparserNamespaces.cpp | 6 ++--- ets2panda/parser/TypedParser.cpp | 7 ++++- ets2panda/parser/TypedParser.h | 1 + .../ast/compiler/ets/binary_operator_neg.ets | 21 +++++++++++++++ .../compiler/ets/classproperty_init_neg.ets | 18 +++++++++++++ .../compiler/ets/invalid_namespace_neg.ets | 26 +++++++++++++++++++ .../compiler/ets/invalid_namespace_neg2.ets | 22 ++++++++++++++++ 11 files changed, 100 insertions(+), 11 deletions(-) create mode 100644 ets2panda/test/ast/compiler/ets/binary_operator_neg.ets create mode 100644 ets2panda/test/ast/compiler/ets/classproperty_init_neg.ets create mode 100644 ets2panda/test/ast/compiler/ets/invalid_namespace_neg.ets create mode 100644 ets2panda/test/ast/compiler/ets/invalid_namespace_neg2.ets diff --git a/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.cpp b/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.cpp index 4e7c4e9e71..89453793d7 100644 --- a/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.cpp +++ b/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.cpp @@ -262,7 +262,6 @@ void GlobalClassHandler::SetupGlobalClass(const ArenaVector & globalClass->SetGlobalInitialized(); CollectProgramGlobalClasses(globalProgram, namespaces); - CollectExportedClasses(globalClass, globalProgram->Ast()->Statements()); // NOTE(vpukhov): stdlib checks are to be removed - do not extend the existing logic @@ -396,9 +395,6 @@ ArenaVector GlobalClassHandler::FormInitMethodStatements(parser for (const auto &[p, ps] : initStatements) { statements.insert(statements.end(), ps.begin(), ps.end()); } - for (auto st : statements) { - st->SetParent(nullptr); - } return statements; } diff --git a/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.h b/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.h index f4b14745c5..6b2691f467 100644 --- a/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.h +++ b/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.h @@ -65,8 +65,8 @@ private: ir::ClassStaticBlock *CreateStaticBlock(ir::ClassDefinition *classDef); ir::MethodDefinition *CreateGlobalMethod(const std::string_view name, ArenaVector &&statements, const parser::Program *program); - void AddInitCallFromStaticBlock(ir::ClassDefinition *globalClass, ir::MethodDefinition *initMethod); + void AddInitCallFromStaticBlock(ir::ClassDefinition *globalClass, ir::MethodDefinition *initMethod); ArenaVector FormInitMethodStatements(parser::Program *program, const ModuleDependencies *moduleDependencies, ArenaVector &&initStatements); diff --git a/ets2panda/parser/ETSFormattedParser.cpp b/ets2panda/parser/ETSFormattedParser.cpp index 519b5aa2f4..24cfaaa237 100644 --- a/ets2panda/parser/ETSFormattedParser.cpp +++ b/ets2panda/parser/ETSFormattedParser.cpp @@ -71,7 +71,7 @@ ir::Expression *ETSParser::ParseExpressionFormatPlaceholder() LogUnexpectedToken(lexer::TokenType::PUNCTUATOR_FORMAT); const auto &rangeToken = Lexer()->GetToken().Loc(); Lexer()->NextToken(); - return AllocBrokenType(rangeToken); + return AllocBrokenExpression(rangeToken); } ParserImpl::NodeFormatType nodeFormat = GetFormatPlaceholderType(); diff --git a/ets2panda/parser/ETSparser.h b/ets2panda/parser/ETSparser.h index 7721a8ffa6..a288b7150e 100644 --- a/ets2panda/parser/ETSparser.h +++ b/ets2panda/parser/ETSparser.h @@ -499,7 +499,7 @@ private: ir::ModifierFlags flags = ir::ModifierFlags::NONE) override; bool CheckInNamespaceContextIsExported(); ir::ETSModule *ParseNamespaceStatement(ir::ModifierFlags memberModifiers); - ir::ETSModule *ParseNamespace(ir::ModifierFlags flags); + ir::Statement *ParseNamespace(ir::ModifierFlags flags) override; ir::ETSModule *ParseNamespaceImp(ir::ModifierFlags flags); using NamespaceBody = std::tuple, lexer::SourceRange>; NamespaceBody ParseNamespaceBody(ir::ClassDefinitionModifiers modifiers, ir::ModifierFlags flags); diff --git a/ets2panda/parser/ETSparserNamespaces.cpp b/ets2panda/parser/ETSparserNamespaces.cpp index af0e4d1045..47f37b6f42 100644 --- a/ets2panda/parser/ETSparserNamespaces.cpp +++ b/ets2panda/parser/ETSparserNamespaces.cpp @@ -41,7 +41,7 @@ ir::ETSModule *ETSParser::ParseNamespaceStatement(ir::ModifierFlags memberModifi GetContext().Status() |= ParserStatus::IN_NAMESPACE; IncrementNamespaceNestedRank(); - ir::ETSModule *result = ParseNamespace(modifiers); + auto *result = ParseNamespace(modifiers); DecrementNamespaceNestedRank(); if (GetNamespaceNestedRank() == 0) { @@ -50,10 +50,10 @@ ir::ETSModule *ETSParser::ParseNamespaceStatement(ir::ModifierFlags memberModifi if ((memberModifiers & ir::ModifierFlags::DECLARE) != 0) { GetContext().Status() &= ~ParserStatus::IN_AMBIENT_CONTEXT; } - return result; + return result->AsETSModule(); } -ir::ETSModule *ETSParser::ParseNamespace(ir::ModifierFlags flags) +ir::Statement *ETSParser::ParseNamespace(ir::ModifierFlags flags) { if ((GetContext().Status() & ParserStatus::IN_NAMESPACE) == 0) { LogError(diagnostic::NAMESPACE_ONLY_TOP_OR_IN_NAMESPACE); diff --git a/ets2panda/parser/TypedParser.cpp b/ets2panda/parser/TypedParser.cpp index 30c4b499d6..9f8273a82a 100644 --- a/ets2panda/parser/TypedParser.cpp +++ b/ets2panda/parser/TypedParser.cpp @@ -162,7 +162,7 @@ ir::Statement *TypedParser::ParsePotentialExpressionStatement(StatementParsingFl } case lexer::TokenType::KEYW_NAMESPACE: { if (((GetContext().Status() & ParserStatus::IN_AMBIENT_CONTEXT) != 0U) || IsNamespaceDecl()) { - return ParseModuleDeclaration(); + return ParseNamespace(ir::ModifierFlags::NONE); } [[fallthrough]]; } @@ -217,6 +217,11 @@ ir::Statement *TypedParser::ParseModuleDeclaration([[maybe_unused]] StatementPar return ParseModuleOrNamespaceDeclaration(startLoc); } +ir::Statement *TypedParser::ParseNamespace([[maybe_unused]] ir::ModifierFlags flags) +{ + return ParseModuleDeclaration(); +} + ir::ArrowFunctionExpression *TypedParser::ParseGenericArrowFunction() { ArrowFunctionContext arrowFunctionContext(this, false); diff --git a/ets2panda/parser/TypedParser.h b/ets2panda/parser/TypedParser.h index 8101ab7123..bb1379b9e5 100644 --- a/ets2panda/parser/TypedParser.h +++ b/ets2panda/parser/TypedParser.h @@ -87,6 +87,7 @@ protected: // NOLINTNEXTLINE(google-default-arguments) ir::Statement *ParseModuleDeclaration(StatementParsingFlags flags = StatementParsingFlags::NONE) override; + virtual ir::Statement *ParseNamespace(ir::ModifierFlags flags); virtual void CheckIfTypeParameterNameIsReserved() {}; virtual ArenaVector ParseInterfaceExtendsClause(); virtual ir::Statement *ParseDeclareAndDecorators(StatementParsingFlags flags); diff --git a/ets2panda/test/ast/compiler/ets/binary_operator_neg.ets b/ets2panda/test/ast/compiler/ets/binary_operator_neg.ets new file mode 100644 index 0000000000..ee4c76c29c --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/binary_operator_neg.ets @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* @@ label1 */@@/@ + +/* @@@ label1 Error SyntaxError: Unexpected token '@@'. */ +/* @@? 21:93 Error SyntaxError: Identifier expected, got 'eos'. */ +/* @@? 21:93 Error SyntaxError: Unexpected token 'eos'. */ +/* @@? 21:93 Error SyntaxError: Annotations are not allowed on this type of declaration. */ \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/classproperty_init_neg.ets b/ets2panda/test/ast/compiler/ets/classproperty_init_neg.ets new file mode 100644 index 0000000000..65fa3f5ea6 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/classproperty_init_neg.ets @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class A {b5 : boolean = /* @@ label1 */7;} + +/* @@@ label1 Error TypeError: Type 'int' cannot be assigned to type 'boolean' */ \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/invalid_namespace_neg.ets b/ets2panda/test/ast/compiler/ets/invalid_namespace_neg.ets new file mode 100644 index 0000000000..3a3ae02f86 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/invalid_namespace_neg.ets @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +namespace C{ + { + let y: number = + /* @@ label1 */} + + namespace C { + let xsx = 1 + } +} + +/* @@@ label1 Error SyntaxError: Unexpected token '}'. */ diff --git a/ets2panda/test/ast/compiler/ets/invalid_namespace_neg2.ets b/ets2panda/test/ast/compiler/ets/invalid_namespace_neg2.ets new file mode 100644 index 0000000000..c7941e4248 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/invalid_namespace_neg2.ets @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + /* @@ label1 */namespace C { + let my:number = 1 + } +} + +/* @@@ label1 Error SyntaxError: Namespace is allowed only at the top level or inside a namespace. */ -- Gitee From ec0432141a587fc3f0faa1ba3e703b208ec7beea Mon Sep 17 00:00:00 2001 From: liyue Date: Fri, 20 Jun 2025 11:48:10 +0800 Subject: [PATCH 247/268] Fix error on macOS when convert extremely values Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICGKJO Signed-off-by: liyue Change-Id: I6e423aaab5f9fa30f1a358aa72b439f250c416f6 --- es2panda/lexer/lexer.cpp | 25 ++- .../test/compiler/js/json-parser-expected.txt | 49 +++++ es2panda/test/compiler/js/json-parser.js | 207 ++++++++++++++++++ .../test-ts-extremely-number-1-expected.txt | 38 ++++ .../compiler/test-ts-extremely-number-1.ts | 80 +++++++ .../test-ts-extremely-number-2-expected.txt | 18 ++ .../compiler/test-ts-extremely-number-2.ts | 35 +++ 7 files changed, 446 insertions(+), 6 deletions(-) create mode 100644 es2panda/test/compiler/js/json-parser-expected.txt create mode 100644 es2panda/test/compiler/js/json-parser.js create mode 100644 es2panda/test/compiler/ts/cases/compiler/test-ts-extremely-number-1-expected.txt create mode 100644 es2panda/test/compiler/ts/cases/compiler/test-ts-extremely-number-1.ts create mode 100644 es2panda/test/compiler/ts/cases/compiler/test-ts-extremely-number-2-expected.txt create mode 100644 es2panda/test/compiler/ts/cases/compiler/test-ts-extremely-number-2.ts diff --git a/es2panda/lexer/lexer.cpp b/es2panda/lexer/lexer.cpp index 11f965aed9..b5e4726b1e 100644 --- a/es2panda/lexer/lexer.cpp +++ b/es2panda/lexer/lexer.cpp @@ -372,14 +372,27 @@ void Lexer::ConvertNumber(size_t exponentSignPos) GetToken().src_ = sv; } - try { - GetToken().number_ = static_cast(std::stold(utf8, nullptr)); - } catch (const std::invalid_argument &) { + errno = 0; + char *endptr = nullptr; + double value = std::strtod(utf8.c_str(), &endptr); + + if (endptr == utf8.c_str()) { ThrowError("Invalid number"); - } catch (const std::out_of_range &) { - // TODO(frobert): look for a more elegant solution to this - GetToken().number_ = std::numeric_limits::infinity(); + return; } + + /* + * Extreme value handling: + * If the number exceeds Number.MAX_VALUE (~1.7976931348623157e+308), treat it as Infinity / -Infinity + * If the number is smaller than Number.MIN_VALUE (5e-324), it may be rounded to 0.0 or Number.MIN_VALUE, + * depending on platform behavior. + */ + if (errno == ERANGE && std::abs(value) > std::numeric_limits::max()) { + value = (value > 0.0 ? std::numeric_limits::infinity() + : -std::numeric_limits::infinity()); + } + + GetToken().number_ = value; } void Lexer::ScanNumber(bool allowNumericSeparator, bool allowBigInt) { diff --git a/es2panda/test/compiler/js/json-parser-expected.txt b/es2panda/test/compiler/js/json-parser-expected.txt new file mode 100644 index 0000000000..09daa6cc4f --- /dev/null +++ b/es2panda/test/compiler/js/json-parser-expected.txt @@ -0,0 +1,49 @@ +1,2,3 1,2,3 +1 1 + +https://www.a.com https://www.a.com +https://www.b.com https://www.b.com +https://www.c.com https://www.c.com +[object Object] [object Object] +Infinity Infinity +-Infinity -Infinity +123 123 +SyntaxError SyntaxError +56320 56320 +{"a":"{\"width\": 18}"} {"a":"{\"width\": 18}"} +{"a":"{\"name\": \"张三\"}"} {"a":"{\"name\": \"张三\"}"} +{"1\u0000":"name"} {"1\u0000":"name"} +0 0 +-Infinity -Infinity +JSON.parse with backslash JSON.parse with backslash +"" "" +Uf Uf +啕晦 啕晦 +"" "" +Uf Uf +啕晦 啕晦 +SyntaxError SyntaxError +SyntaxError SyntaxError +SyntaxError SyntaxError +10 10 +hello hello +true true +14 14 +24 24 +29 29 +36 36 +46 46 +1.79e+308 1.79e+308 +Infinity Infinity +Infinity Infinity +2.225e-308 2.225e-308 +2.225e-309 2.225e-309 +3e-320 3e-320 +5e-324 5e-324 +0 0 +0 0 +2.225e-308 +2.225e-309 +3e-320 +5e-324 +SyntaxError SyntaxError diff --git a/es2panda/test/compiler/js/json-parser.js b/es2panda/test/compiler/js/json-parser.js new file mode 100644 index 0000000000..bb7a92d40a --- /dev/null +++ b/es2panda/test/compiler/js/json-parser.js @@ -0,0 +1,207 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +let json = JSON.parse("[ 1, 2, 3]"); +print(json,[1,2,3]); +let json2 = JSON.parse("[ 1 ]"); +print(json2,[1]); +let json3 = JSON.parse("[ ]"); +print(json3,[]); +let data = { + "11111111" : "https://www.a.com", + "22222222" : "https://www.b.com", + "00000000" : "https://www.c.com" +} +let strData = JSON.stringify(data); +let res = JSON.parse(strData); +print(res["11111111"],'https://www.a.com'); +print(res["22222222"],'https://www.b.com'); +print(res["00000000"],'https://www.c.com'); + +var a = `{"code": 0, "msg": "ok"}` +function reviver(k, v) { return v; } +var o = JSON.parse(a, reviver); +print(o.toString(),'[object Object]'); + +let strData2 = "1.7976971348623157e+308"; +let res2 = JSON.parse(strData2); +print(res2,Infinity); + +let strData3 = "-1.7976971348623157e+308"; +let res3 = JSON.parse(strData3); +print(res3,-Infinity); + +let strData4 = "123"; +let res4 = JSON.parse(strData4); +print(res4,123); + +try { + JSON.parse(`{"object": 42, "test":{}`) +} catch (error) { + print(error.name,'SyntaxError') + +} + +let strData5 = "\"\\uDC00\""; +let res5 = JSON.parse(strData5); +print(res5.codePointAt(0),56320) + +let strData6 = '{"a": "{\\"width\\": 18}"}' +print(JSON.stringify(JSON.parse(strData6)),'{"a":"{\\"width\\": 18}"}') + +let strData7 = '{"a": "{\\"name\\": \\"张三\\"}"}' +print(JSON.stringify(JSON.parse(strData7)),'{"a":"{\\"name\\": \\"张三\\"}"}') + +let strData8 = '{"1\\u0000":"name"}' +print(JSON.stringify(JSON.parse(strData8)),'{"1\\u0000":"name"}') + +print(JSON.parse('123.456e-789'),0); +print(1 / JSON.parse('-0'),-Infinity); + +var string = "JSON.parse with backslash"; +print(string,"JSON.parse with backslash"); +print(JSON.parse('"\\"\\""'),'""'); // utf8 -> utf8 +print(JSON.parse('"\\u0055\\u0066"'),'Uf'); // utf8 -> utf8 +print(JSON.parse('"\\u5555\\u6666"'),'啕晦'); // utf8 -> utf16 +print(JSON.parse('["\\"\\"","中文"]')[0],'""'); // utf16 -> utf8 +print(JSON.parse('["\\u0055\\u0066","中文"]')[0],'Uf'); // utf16 -> utf8 +print(JSON.parse('["\\u5555\\u6666","中文"]')[0],'啕晦'); // utf16 -> utf16 + +const strData9 = `{"k1":"hello","k2":3}`; +const strErr = strData9.substring(0, strData9.length - 2); +try { + JSON.parse(strErr); +} catch (err) { + print(err.name,'SyntaxError'); +} + +const strData10 = `{"k1":"hello","k2": 3}`; +const strErr2 = strData10.substring(0, strData10.length - 2); +try { + JSON.parse(strErr2); +} catch (err) { + print(err.name,'SyntaxError'); +} + +const strData11 = `{"k1":"hello","k2":311111}`; +const strErr3 = strData11.substring(0, strData11.length - 2); +try { + JSON.parse(strErr3); +} catch (err) { + print(err.name,'SyntaxError'); +} + +let jsonSingleStr = `{ + "a": 10, + "b": "hello", + "c": true, + "d": null, + "e": 5, + "f": 6, + "g": 7, + "h": 8, + "i": 9, + "j": 10, + "k": 11, + "l": 12, + "m": 13, + "n": 14, + "o": 15, + "p": 16, + "q": 17, + "r": 18, + "s": 19, + "t": 20, + "u": 21, + "v": 22, + "w": 23, + "x": 24, + "y": 25, + "z": 26, + "A": 27, + "B": 28, + "C": 29, + "D": 30, + "E": 31, + "F": 32, + "G": 33, + "H": 34, + "I": 35, + "J": 36, + "K": 37, + "L": 38, + "M": 39, + "N": 40, + "O": 41, + "P": 42, + "Q": 43, + "R": 44, + "S": 45, + "T": 46, + "U": 47, + "V": 48, + "W": 49, + "X": 50, + "Y": 51, + "Z": 52 +}`; + +let parsedObj = JSON.parse(jsonSingleStr); +print(parsedObj.a, 10); +print(parsedObj.b, 'hello'); +print(parsedObj.c, true); +print(parsedObj.n, 14); +print(parsedObj.x, 24); +print(parsedObj.C, 29); +print(parsedObj.J, 36); +print(parsedObj.T, 46); + +let numStr = `{ + "numberval1": 1.79e+308, + "numberval2": 1.7976931348623158e+309, + "numberval3": 5e+320, + "numberval4": 2.225e-308, + "numberval5": 2.225e-309, + "numberval6": 3e-320, + "numberval7": 5e-324, + "numberval8": 5e-325, + "numberval9": 7e-350 +}`; +let numParsedObj = JSON.parse(numStr); +print(numParsedObj.numberval1, 1.79e+308);// DBL_MAX +print(numParsedObj.numberval2, Infinity);// greater than DBL_MAX, expect Infinity +print(numParsedObj.numberval3, Infinity);// greater than DBL_MAX, expect Infinity +print(numParsedObj.numberval4, 2.225e-308);// DBL_MIN +print(numParsedObj.numberval5, 2.225e-309);// less than DBL_MIN +print(numParsedObj.numberval6, 3e-320);// less than DBL_MIN +print(numParsedObj.numberval7, 5e-324);// Number.MIN_VALUE +print(numParsedObj.numberval8, 0);// less than Number.MIN_VALUE, expect 0 +print(numParsedObj.numberval9, 0);// less than Number.MIN_VALUE, expect 0 + +print(2.225e-308); // 2.225e-308 +print(2.225e-309); // 2.225e-309 +print(3e-320); // 3e-320 +print(5e-324); // 5e-324 + +{ + let err = {}; + try { + JSON.parse(`{"object哈哈": 42, "test":{}`) + } catch (error) { + err = error; + } + print(err.name, 'SyntaxError'); +} \ No newline at end of file diff --git a/es2panda/test/compiler/ts/cases/compiler/test-ts-extremely-number-1-expected.txt b/es2panda/test/compiler/ts/cases/compiler/test-ts-extremely-number-1-expected.txt new file mode 100644 index 0000000000..4fd6ce6872 --- /dev/null +++ b/es2panda/test/compiler/ts/cases/compiler/test-ts-extremely-number-1-expected.txt @@ -0,0 +1,38 @@ +1.79e+308 +Infinity +Infinity +2.225e-308 +2.225e-309 +3e-320 +5e-324 +0 +0 +-1.79e+308 +-Infinity +-Infinity +-2.225e-308 +-2.225e-309 +-3e-320 +-5e-324 +0 +0 +false +false +true +true +true +true +true +true +true +true +true +true +true +true +true +true +true +true +true +true diff --git a/es2panda/test/compiler/ts/cases/compiler/test-ts-extremely-number-1.ts b/es2panda/test/compiler/ts/cases/compiler/test-ts-extremely-number-1.ts new file mode 100644 index 0000000000..6f765b6206 --- /dev/null +++ b/es2panda/test/compiler/ts/cases/compiler/test-ts-extremely-number-1.ts @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +let numStr = `{ + "numberval1": 1.79e+308, + "numberval2": 1.7976931348623158e+309, + "numberval3": 5e+320, + "numberval4": 2.225e-308, + "numberval5": 2.225e-309, + "numberval6": 3e-320, + "numberval7": 5e-324, + "numberval8": 5e-325, + "numberval9": 7e-350, + "numberval10": -1.79e+308, + "numberval11": -1.7976931348623158e+309, + "numberval12": -5e+320, + "numberval13": -2.225e-308, + "numberval14": -2.225e-309, + "numberval15": -3e-320, + "numberval16": -5e-324, + "numberval17": -5e-325, + "numberval18": -7e-350 +}`; + +let numParsedObj = JSON.parse(numStr); +print(numParsedObj.numberval1);// DBL_MAX, 1.79e+308 +print(numParsedObj.numberval2);// greater than DBL_MAX, expect Infinity +print(numParsedObj.numberval3);// greater than DBL_MAX, expect Infinity +print(numParsedObj.numberval4);// DBL_MIN, 2.225e-308 +print(numParsedObj.numberval5);// less than DBL_MIN, 2.225e-309 +print(numParsedObj.numberval6);// less than DBL_MIN, 3e-320 +print(numParsedObj.numberval7);// Number.MIN_VALUE, 5e-324 +print(numParsedObj.numberval8);// less than Number.MIN_VALUE, expect 0 +print(numParsedObj.numberval9);// less than Number.MIN_VALUE, expect 0 + +print(numParsedObj.numberval10); // -1.79e+308 +print(numParsedObj.numberval11); // -Infinity +print(numParsedObj.numberval12); // -Infinity +print(numParsedObj.numberval13); // -2.225e-308 +print(numParsedObj.numberval14); // -2.225e-309 +print(numParsedObj.numberval15); // -3e-320 +print(numParsedObj.numberval16); // -5e-324 +print(numParsedObj.numberval17); // -0 +print(numParsedObj.numberval18); // -0 + +print(Object.is(numParsedObj.numberval2, numParsedObj.numberval11)) // false +print(Object.is(numParsedObj.numberval18, numParsedObj.numberval9)) // false + +print(Object.is(numParsedObj.numberval1, 1.79e+308)); // true +print(Object.is(numParsedObj.numberval2, Infinity)); // true +print(Object.is(numParsedObj.numberval3, Infinity)); // true +print(Object.is(numParsedObj.numberval4, 2.225e-308)); // true +print(Object.is(numParsedObj.numberval5, 2.225e-309)); // true +print(Object.is(numParsedObj.numberval6, 3e-320)); // true +print(Object.is(numParsedObj.numberval7, Number.MIN_VALUE)); // true +print(Object.is(numParsedObj.numberval8, 0)); // true +print(Object.is(numParsedObj.numberval9, 0)); // true + +print(Object.is(numParsedObj.numberval10, -1.79e+308)); // true +print(Object.is(numParsedObj.numberval11, -Infinity)); // true +print(Object.is(numParsedObj.numberval12, -Infinity)); // true +print(Object.is(numParsedObj.numberval13, -2.225e-308)); // true +print(Object.is(numParsedObj.numberval14, -2.225e-309)); // true +print(Object.is(numParsedObj.numberval15, -3e-320)); // true +print(Object.is(numParsedObj.numberval16, -5e-324)); // true +print(Object.is(numParsedObj.numberval17, -0)); // true, distinguishes from 0 +print(Object.is(numParsedObj.numberval18, -0)); // true \ No newline at end of file diff --git a/es2panda/test/compiler/ts/cases/compiler/test-ts-extremely-number-2-expected.txt b/es2panda/test/compiler/ts/cases/compiler/test-ts-extremely-number-2-expected.txt new file mode 100644 index 0000000000..9ee55078c1 --- /dev/null +++ b/es2panda/test/compiler/ts/cases/compiler/test-ts-extremely-number-2-expected.txt @@ -0,0 +1,18 @@ +1.79e+308 +Infinity +Infinity +2.225e-308 +2.225e-309 +3e-320 +5e-324 +0 +0 +-1.79e+308 +-Infinity +-Infinity +-2.225e-308 +-2.225e-309 +-3e-320 +-5e-324 +0 +0 diff --git a/es2panda/test/compiler/ts/cases/compiler/test-ts-extremely-number-2.ts b/es2panda/test/compiler/ts/cases/compiler/test-ts-extremely-number-2.ts new file mode 100644 index 0000000000..bfa7afc80d --- /dev/null +++ b/es2panda/test/compiler/ts/cases/compiler/test-ts-extremely-number-2.ts @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +print(1.79e+308); +print(1.7976931348623158e+309); +print(5e+320); +print(2.225e-308); +print(2.225e-309); +print(3e-320); +print(5e-324); +print(5e-325); +print(7e-350); + +print(-1.79e+308); +print(-1.7976931348623158e+309); +print(-5e+320); +print(-2.225e-308); +print(-2.225e-309); +print(-3e-320); +print(-5e-324); +print(-5e-325); +print(-7e-350); \ No newline at end of file -- Gitee From 255ff1a8c92c98b31b7c911a2ef031ba160163cf Mon Sep 17 00:00:00 2001 From: xingshunxiang Date: Tue, 10 Jun 2025 14:36:32 +0800 Subject: [PATCH 248/268] Fix several bugs in fuzzing case Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICII3T?from=project-issue Description: 1. several sigsegV, see fuzzingtest0 - funzzingtest2; 2. a memory leak while handle unterminated string, see fuzzingtest3 Reason: 1. several sigsegV, see fuzzingtest0 - funzzingtest2; 2. a memory leak while handle unterminated string, see fuzzingtest3 Tests: ninja tests passed tests/tests-u-runner/runner.sh --ets-cts --show-progress --build-dir x64.release --processes=all passed tests/tests-u-runner/runner.sh --ets-func-tests --show-progress --build-dir x64.release --processes=all passed tests/tests-u-runner/runner.sh --astchecker --show-progress --build-dir x64.release --processes=all passed tests/tests-u-runner/runner.sh --ets-runtime --show-progress --build-dir x64.release --processes=all passed tests/tests-u-runner/runner.sh --parser --no-js --show-progress --build-dir x64.release --processes=all passed Signed-off-by: xingshunxiang --- ets2panda/checker/ets/arithmetic.cpp | 4 +++ ets2panda/lexer/lexer.h | 7 ++-- ets2panda/parser/TypedParser.cpp | 3 ++ ets2panda/parser/statementParser.cpp | 4 +++ .../test/ast/compiler/ets/fuzzingtest0.ets | 25 +++++++++++++ .../test/ast/compiler/ets/fuzzingtest1.ets | 22 ++++++++++++ .../test/ast/compiler/ets/fuzzingtest2.ets | 20 +++++++++++ .../test/ast/compiler/ets/fuzzingtest3.ets | 24 +++++++++++++ .../ast/parser/ets/unexpected_token_56.ets | 36 +++++++++---------- 9 files changed, 123 insertions(+), 22 deletions(-) create mode 100644 ets2panda/test/ast/compiler/ets/fuzzingtest0.ets create mode 100644 ets2panda/test/ast/compiler/ets/fuzzingtest1.ets create mode 100644 ets2panda/test/ast/compiler/ets/fuzzingtest2.ets create mode 100644 ets2panda/test/ast/compiler/ets/fuzzingtest3.ets diff --git a/ets2panda/checker/ets/arithmetic.cpp b/ets2panda/checker/ets/arithmetic.cpp index f1172e016d..3459f33a10 100644 --- a/ets2panda/checker/ets/arithmetic.cpp +++ b/ets2panda/checker/ets/arithmetic.cpp @@ -836,6 +836,10 @@ Type *ETSChecker::CheckBinaryOperatorNullishCoalescing(ir::Expression *left, ir: return leftType; } leftType = GetNonNullishType(leftType); + if (leftType->IsTypeError()) { + ES2PANDA_ASSERT(IsAnyError()); + return GlobalTypeError(); + } auto *rightType = MaybeBoxExpression(right); if (IsTypeIdenticalTo(leftType, rightType)) { diff --git a/ets2panda/lexer/lexer.h b/ets2panda/lexer/lexer.h index ed61b733e7..e12e89870d 100644 --- a/ets2panda/lexer/lexer.h +++ b/ets2panda/lexer/lexer.h @@ -406,13 +406,14 @@ void Lexer::ScanString() PrepareStringTokenHelper(); const auto startPos = Iterator().Index(); auto escapeEnd = startPos; - bool validEscape = true; + bool isFinalizedStr = true; do { const char32_t cp = Iterator().Peek(); switch (cp) { case util::StringView::Iterator::INVALID_CP: { LogError(diagnostic::UNTERMINATED_STRING); + isFinalizedStr = false; break; } case LEX_CHAR_CR: @@ -425,7 +426,7 @@ void Lexer::ScanString() continue; } case LEX_CHAR_BACKSLASH: { - validEscape &= HandleBackslashHelper(&str, &escapeEnd); + isFinalizedStr &= HandleBackslashHelper(&str, &escapeEnd); continue; } case LEX_CHAR_BACK_TICK: @@ -448,7 +449,7 @@ void Lexer::ScanString() } } - FinalizeTokenHelper(&str, startPos, escapeEnd, validEscape); + FinalizeTokenHelper(&str, startPos, escapeEnd, isFinalizedStr); break; } while (true); diff --git a/ets2panda/parser/TypedParser.cpp b/ets2panda/parser/TypedParser.cpp index 30c4b499d6..0ac467dd2c 100644 --- a/ets2panda/parser/TypedParser.cpp +++ b/ets2panda/parser/TypedParser.cpp @@ -1237,6 +1237,9 @@ ir::Expression *TypedParser::ParseQualifiedReference(ir::Expression *typeName, E propName = AllocNode(Lexer()->GetToken().Ident(), Allocator()); } + if (propName == nullptr) { + return AllocBrokenExpression(Lexer()->GetToken().Loc()); + } propName->SetRange(Lexer()->GetToken().Loc()); typeName = AllocNode(typeName, propName, Allocator()); diff --git a/ets2panda/parser/statementParser.cpp b/ets2panda/parser/statementParser.cpp index d3fcb64454..9cfb10992b 100644 --- a/ets2panda/parser/statementParser.cpp +++ b/ets2panda/parser/statementParser.cpp @@ -837,12 +837,16 @@ std::tuple if (condExpr->Alternate()->IsBinaryExpression() && condExpr->Alternate()->AsBinaryExpression()->OperatorType() == lexer::TokenType::KEYW_IN) { LogError(diagnostic::INVALID_LEFT_FOR_IN); + rightNode = AllocBrokenExpression(Lexer()->GetToken().Loc()); + updateNode = AllocBrokenExpression(Lexer()->GetToken().Loc()); // CC-OFFNXT(G.FMT.03-CPP) project code style return {ForStatementKind::IN, initNode, rightNode, updateNode}; } } if (lexer_->GetToken().Type() == lexer::TokenType::PUNCTUATOR_RIGHT_PARENTHESIS) { + rightNode = AllocBrokenExpression(Lexer()->GetToken().Loc()); + updateNode = AllocBrokenExpression(Lexer()->GetToken().Loc()); LogError(diagnostic::INVALID_LEFT_FOR_IN_OF); return {ForStatementKind::UPDATE, initNode, rightNode, updateNode}; } diff --git a/ets2panda/test/ast/compiler/ets/fuzzingtest0.ets b/ets2panda/test/ast/compiler/ets/fuzzingtest0.ets new file mode 100644 index 0000000000..2a395eb89b --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/fuzzingtest0.ets @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// the test case is from fuzzer. +let callback = () => {for /* @@ label1 */aa !== /* @@ label2 */arr[idx]/* @@ label3 */) + +/* @@@ label1 Error SyntaxError: Expected '(', got 'identification literal'. */ +/* @@@ label1 Error TypeError: Unresolved reference aa */ +/* @@@ label2 Error TypeError: Unresolved reference arr */ +/* @@@ label2 Error TypeError: Indexed access is not supported for such expression type. */ +/* @@@ label3 Error SyntaxError: Invalid left-hand side in 'For[In/Of]Statement'. */ +/* @@? 26:1 Error SyntaxError: Unexpected token 'eos'. */ +/* @@? 26:1 Error SyntaxError: Expected '}', got 'eos'. */ diff --git a/ets2panda/test/ast/compiler/ets/fuzzingtest1.ets b/ets2panda/test/ast/compiler/ets/fuzzingtest1.ets new file mode 100644 index 0000000000..32a58853e9 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/fuzzingtest1.ets @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// the test case is from fuzzer. +/* @@ label */fuzzz./* @@ label2 */@@/* @@ label3 */@@ + +/* @@@ label Error TypeError: Unresolved reference fuzzz */ +/* @@@ label2 Error SyntaxError: There is no any node to insert at the placeholder position. */ +/* @@@ label2 Error SyntaxError: Identifier expected, got '@@'. */ +/* @@@ label3 Error SyntaxError: Unexpected token '@@'. */ \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/fuzzingtest2.ets b/ets2panda/test/ast/compiler/ets/fuzzingtest2.ets new file mode 100644 index 0000000000..eff6fa17ba --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/fuzzingtest2.ets @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// the test case is from fuzzer. +/* @@ label */i ??/* @@ label2 */@@ + +/* @@@ label Error TypeError: Unresolved reference i */ +/* @@@ label2 Error SyntaxError: Unexpected token '@@'. */ diff --git a/ets2panda/test/ast/compiler/ets/fuzzingtest3.ets b/ets2panda/test/ast/compiler/ets/fuzzingtest3.ets new file mode 100644 index 0000000000..f3b80f5acc --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/fuzzingtest3.ets @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// the test case is from fuzzer. +/* @@? 24:1 Error TypeError: Unresolved reference abcdefghijklmnopqrstuvwxyzABC */ +/* @@? 24:30 Error SyntaxError: Unexpected token '`'. */ +/* @@? 24:30 Error SyntaxError: Unexpected token, expected '`'. */ +/* @@? 24:31 Error SyntaxError: Unterminated string. */ +/* @@? 24:31 Error SyntaxError: Unexpected token, expected '${' or '`' */ +/* @@? 24:31 Error SyntaxError: Unexpected token, expected '`'. */ + +abcdefghijklmnopqrstuvwxyzABC`DEF\n� \ No newline at end of file diff --git a/ets2panda/test/ast/parser/ets/unexpected_token_56.ets b/ets2panda/test/ast/parser/ets/unexpected_token_56.ets index ad0043f46c..95e865545d 100644 --- a/ets2panda/test/ast/parser/ets/unexpected_token_56.ets +++ b/ets2panda/test/ast/parser/ets/unexpected_token_56.ets @@ -13,24 +13,22 @@ * limitations under the License. */ -for await (/* @@ label1 */;/* @@ label2 */;i < count/* @@ label3 */; ++i/* @@ label */) { - result = result + p[i]!.awaitResolution() * a[i]; +for await (/* @@ label1 */;/* @@ label2 */;/* @@ label3 */i < /* @@ label4 */count/* @@ label5 */; ++i/* @@ label6 */) { + /* @@ label8 */result = result + /* @@ label9 */p[i]!.awaitResolution() * /* @@ label10 */a[i]; } -for (let i? : Number = 1;;) { break; } +for (let i?: Number = 1;;) { break; } -/* @@? 16:27 Error SyntaxError: Unexpected token ';'. */ -/* @@? 16:43 Error SyntaxError: Unexpected token ';'. */ -/* @@? 16:44 Error TypeError: Unresolved reference i */ -/* @@? 16:48 Error TypeError: Function name 'count' used in the wrong context */ -/* @@? 16:44 Error TypeError: Bad operand type, the types of the operands must be numeric, same enumeration, or boolean type. */ -/* @@? 16:68 Error SyntaxError: Expected ')', got ';'. */ -/* @@? 16:87 Error SyntaxError: Unexpected token ')'. */ -/* @@? 16:87 Error SyntaxError: Unexpected token ')'. */ -/* @@? 16:87 Error SyntaxError: Unexpected token ')'. */ -/* @@? 16:87 Error SyntaxError: Unexpected token ')'. */ -/* @@? 16:87 Error SyntaxError: Unexpected token ')'. */ -/* @@? 17:5 Error TypeError: Unresolved reference result */ -/* @@? 17:23 Error TypeError: Unresolved reference p */ -/* @@? 17:23 Error TypeError: Indexed access is not supported for such expression type. */ -/* @@? 17:49 Error TypeError: Unresolved reference a */ -/* @@? 17:49 Error TypeError: Indexed access is not supported for such expression type. */ +/* @@@ label1 Error SyntaxError: Unexpected token ';'. */ +/* @@@ label2 Error SyntaxError: Unexpected token ';'. */ +/* @@@ label3 Error TypeError: Unresolved reference i */ +/* @@@ label3 Error TypeError: Bad operand type, the types of the operands must be numeric, same enumeration, or boolean type. */ +/* @@@ label4 Error TypeError: Function name 'count' used in the wrong context */ +/* @@@ label5 Error SyntaxError: Expected ')', got ';'. */ +/* @@@ label6 Error SyntaxError: Unexpected token ')'. */ +/* @@@ label6 Error SyntaxError: Unexpected token ')'. */ +/* @@@ label6 Error SyntaxError: Unexpected token ')'. */ +/* @@@ label8 Error TypeError: Unresolved reference result */ +/* @@@ label9 Error TypeError: Unresolved reference p */ +/* @@@ label9 Error TypeError: Indexed access is not supported for such expression type. */ +/* @@@ label10 Error TypeError: Unresolved reference a */ +/* @@@ label10 Error TypeError: Indexed access is not supported for such expression type. */ -- Gitee From 61aa3148046761f476341273dca029486c0be375 Mon Sep 17 00:00:00 2001 From: xingshunxiang Date: Wed, 25 Jun 2025 21:03:25 +0800 Subject: [PATCH 249/268] Fix bugs from fuzzer Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICIGQ4?from=project-issue Description: some bugs from fuzzer Reason: 1. in case1, when ParseAnnotation property, the while loop dose not check the EOS token, when so cause the endless loop. 2. in case2, when handle -2147483648 / -1, the int32 overflow cause the crash, now fix it Tests: ninja tests passed tests/tests-u-runner/runner.sh --ets-cts --show-progress --build-dir x64.release --processes=all passed tests/tests-u-runner/runner.sh --ets-func-tests --show-progress --build-dir x64.release --processes=all passed tests/tests-u-runner/runner.sh --astchecker --show-progress --build-dir x64.release --processes=all passed tests/tests-u-runner/runner.sh --ets-runtime --show-progress --build-dir x64.release --processes=all passed tests/tests-u-runner/runner.sh --parser --no-js --show-progress --build-dir x64.release --processes=all passed Signed-off-by: xingshunxiang --- ets2panda/checker/ets/arithmetic.h | 9 +++++++++ ets2panda/parser/ETSparserAnnotations.cpp | 3 ++- .../ast/compiler/ets/parser_annotation_n.ets | 19 +++++++++++++++++++ ets2panda/test/runtime/ets/MaxBoundInt.ets | 17 +++++++++++++++++ 4 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 ets2panda/test/ast/compiler/ets/parser_annotation_n.ets create mode 100644 ets2panda/test/runtime/ets/MaxBoundInt.ets diff --git a/ets2panda/checker/ets/arithmetic.h b/ets2panda/checker/ets/arithmetic.h index 9e08b1e46e..0f6782c00b 100644 --- a/ets2panda/checker/ets/arithmetic.h +++ b/ets2panda/checker/ets/arithmetic.h @@ -108,6 +108,10 @@ Type *ETSChecker::PerformArithmeticOperationOnTypes(Type *left, Type *right, lex UType rightValue = GetOperand(right); auto result = leftValue; auto isForbiddenZeroDivision = [&rightValue]() { return std::is_integral::value && rightValue == 0; }; + auto isIntegralDivideResOverflow = [&rightValue, &leftValue]() { + // Note: Handle corner cases + return std::is_integral_v && leftValue == std::numeric_limits::min() && rightValue == -1; + }; switch (operationType) { case lexer::TokenType::PUNCTUATOR_PLUS: @@ -125,6 +129,11 @@ Type *ETSChecker::PerformArithmeticOperationOnTypes(Type *left, Type *right, lex if (isForbiddenZeroDivision()) { return nullptr; } + + if (isIntegralDivideResOverflow()) { + return Allocator()->New(std::numeric_limits::min()); + } + result = leftValue / rightValue; break; } diff --git a/ets2panda/parser/ETSparserAnnotations.cpp b/ets2panda/parser/ETSparserAnnotations.cpp index f95b1bb943..f09bc2591f 100644 --- a/ets2panda/parser/ETSparserAnnotations.cpp +++ b/ets2panda/parser/ETSparserAnnotations.cpp @@ -114,7 +114,8 @@ ArenaVector ETSParser::ParseAnnotationProperties(ir::ModifierFlag Lexer()->NextToken(lexer::NextTokenFlags::KEYWORD_TO_IDENT); ArenaVector properties(Allocator()->Adapter()); - while (Lexer()->GetToken().Type() != lexer::TokenType::PUNCTUATOR_RIGHT_BRACE) { + while (Lexer()->GetToken().Type() != lexer::TokenType::PUNCTUATOR_RIGHT_BRACE && + Lexer()->GetToken().Type() != lexer::TokenType::EOS) { if ((memberModifiers & ir::ModifierFlags::ANNOTATION_DECLARATION) != 0U && Lexer()->GetToken().Type() == lexer::TokenType::PUNCTUATOR_SEMI_COLON) { Lexer()->NextToken(); // eat ';' diff --git a/ets2panda/test/ast/compiler/ets/parser_annotation_n.ets b/ets2panda/test/ast/compiler/ets/parser_annotation_n.ets new file mode 100644 index 0000000000..2a6fd1d170 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/parser_annotation_n.ets @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@interface /* @@ label1 */� + +/* @@@ label1 Error SyntaxError: Unexpected token, expected an identifier. */ +/* @@? 20:1 Error SyntaxError: Expected '{', got 'eos'. */ diff --git a/ets2panda/test/runtime/ets/MaxBoundInt.ets b/ets2panda/test/runtime/ets/MaxBoundInt.ets new file mode 100644 index 0000000000..ca9b91de4b --- /dev/null +++ b/ets2panda/test/runtime/ets/MaxBoundInt.ets @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +assertEQ(-2147483648 / -1, -2147483648) +assertEQ(-9223372036854775808 / -1, -9223372036854775808) -- Gitee From 0b2f72fefee5181fbbdd738bf852403690c46417 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A5=88=E6=84=BF?= Date: Fri, 4 Jul 2025 14:47:41 +0800 Subject: [PATCH 250/268] Fixed the alarm for independent compilation Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICJZK2 Signed-off-by: chenlong --- ets2panda/BUILD.gn | 56 +++++++++++++++++++++++++++++++----------- ets2panda/aot/BUILD.gn | 30 +++++++++++++++++----- 2 files changed, 66 insertions(+), 20 deletions(-) diff --git a/ets2panda/BUILD.gn b/ets2panda/BUILD.gn index a7d027eff5..3ebfa38385 100644 --- a/ets2panda/BUILD.gn +++ b/ets2panda/BUILD.gn @@ -23,12 +23,14 @@ config("libes2panda_public_config") { include_dirs = [ "$target_gen_dir", "$target_gen_dir/include", - "$target_gen_dir/generated", "//third_party/icu/icu4c/source/common", "//third_party/icu/icu4c/source/i18n", "//third_party/icu/icu4c/source", "$ark_es2panda_root", ] + if (ark_standalone_build || ark_static_standalone_build) { + include_dirs += [ "$target_gen_dir/generated" ] + } } libes2panda_sources = [ @@ -1095,25 +1097,35 @@ config("libes2panda_config") { ] } +if (ark_standalone_build || ark_static_standalone_build) { + libes2panda_configs += [ + "$ark_root/assembler:arkassembler_public_config", + "$ark_root/libpandabase:arkbase_public_config", + "$ark_root/libpandafile:arkfile_public_config", + ] +} + libes2panda_configs = [ - "$ark_root/assembler:arkassembler_public_config", "$ark_root:ark_config", ":libes2panda_public_config", ":libes2panda_config", - "$ark_root/libpandabase:arkbase_public_config", - "$ark_root/libpandafile:arkfile_public_config", ] +if (ark_standalone_build || ark_static_standalone_build) { + libes2panda_public_configs += [ + "$ark_root/assembler:arkassembler_public_config", + "$ark_root/libpandabase:arkbase_public_config", + "$ark_root/libpandafile:arkfile_public_config", + "$ark_root/bytecode_optimizer:bytecodeopt_public_config", + "$ark_root/runtime:arkruntime_public_config", + "$ark_root/compiler:arkcompiler_public_config", + ] +} + libes2panda_public_configs = [ - "$ark_root/assembler:arkassembler_public_config", "$ark_root:ark_config", ":libes2panda_public_config", ":libes2panda_config", - "$ark_root/libpandabase:arkbase_public_config", - "$ark_root/libpandafile:arkfile_public_config", - "$ark_root/bytecode_optimizer:bytecodeopt_public_config", - "$ark_root/compiler:arkcompiler_public_config", - "$ark_root/runtime:arkruntime_public_config", ] ohos_shared_library("libes2panda") { @@ -1159,6 +1171,10 @@ ohos_source_set("libes2panda_frontend_static") { external_deps += [ "icu:static_icui18n", "icu:static_icuuc", + "runtime_core:assembler_headers", + "runtime_core:libpandabase_headers", + "runtime_core:libpandafile_headers", + "runtime_core:runtime_gen_headers", ] } part_name = "ets_frontend" @@ -1198,10 +1214,6 @@ ohos_source_set("libes2panda_public_frontend_static") { deps = [ ":libes2panda_frontend_static" ] - if (ark_standalone_build || ark_static_standalone_build) { - deps += [ "$ark_root/bytecode_optimizer:libarktsbytecodeopt_package" ] - } - if (target_os != "win" && target_os != "mingw" && target_os != "winuwp") { deps += [ ":generate_ets2panda_info" ] defines = [ "ES2PANDA_COMPILE_BY_GN" ] @@ -1211,6 +1223,22 @@ ohos_source_set("libes2panda_public_frontend_static") { "runtime_core:libarktsbytecodeopt_package", sdk_libc_secshared_dep, ] + + if (ark_standalone_build || ark_static_standalone_build) { + deps += [ "$ark_root/bytecode_optimizer:libarktsbytecodeopt_package" ] + } else { + external_deps += [ + "runtime_core:assembler_headers", + "runtime_core:runtime_gen_headers", + "runtime_core:libpandabase_headers", + "runtime_core:libpandafile_headers", + "runtime_core:bytecode_optimizer_headers", + "runtime_core:runtime_headers", + "runtime_core:compiler_headers", + "runtime_core:verification_headers", + ] + } + part_name = "ets_frontend" subsystem_name = "arkcompiler" } diff --git a/ets2panda/aot/BUILD.gn b/ets2panda/aot/BUILD.gn index 0a8d75cffd..742f3affcb 100644 --- a/ets2panda/aot/BUILD.gn +++ b/ets2panda/aot/BUILD.gn @@ -29,15 +29,20 @@ ohos_executable("ets2panda") { configs = [ "$ark_root:ark_config", - "$ark_root/assembler:arkassembler_public_config", "$ark_es2panda_root:libes2panda_public_config", - "$ark_root/libpandafile:arkfile_public_config", - "$ark_root/libpandabase:arkbase_public_config", - "$ark_root/bytecode_optimizer:bytecodeopt_public_config", - "$ark_root/compiler:arkcompiler_public_config", - "$ark_root/runtime:arkruntime_public_config", ] + if (ark_standalone_build || ark_static_standalone_build) { + configs += [ + "$ark_root/assembler:arkassembler_public_config", + "$ark_root/libpandafile:arkfile_public_config", + "$ark_root/libpandabase:arkbase_public_config", + "$ark_root/bytecode_optimizer:bytecodeopt_public_config", + "$ark_root/runtime:arkruntime_public_config", + "$ark_root/compiler:arkcompiler_public_config", + ] + } + deps = [ "$ark_es2panda_root:libes2panda_frontend_static", "$ark_es2panda_root:libes2panda_public_frontend_static", @@ -60,6 +65,19 @@ ohos_executable("ets2panda") { sdk_libc_secshared_dep, ] + if (!(ark_standalone_build || ark_static_standalone_build)) { + external_deps += [ + "runtime_core:assembler_headers", + "runtime_core:bytecode_optimizer_headers", + "runtime_core:libpandabase_headers", + "runtime_core:libpandafile_headers", + "runtime_core:runtime_gen_headers", + "runtime_core:runtime_headers", + "runtime_core:compiler_headers", + "runtime_core:verification_headers", + ] + } + if (defined(ohos_indep_compiler_enable) && ohos_indep_compiler_enable) { external_deps += [ "icu:shared_icuuc" ] } -- Gitee From 698b06ca482d923c961d4b7ed3ab36b0f5d2af79 Mon Sep 17 00:00:00 2001 From: lijunru Date: Wed, 25 Jun 2025 18:08:29 +0800 Subject: [PATCH 251/268] Fix ohos independent build error Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICHSZV Change-id: i4f367000f535c8cd0c4e366c964adc017d0b8aa6 Signed-off-by: lijunru --- ets2panda/BUILD.gn | 25 +++++++++++++++---- ets2panda/aot/BUILD.gn | 25 ++++++++++++++----- ets2panda/bindings/BUILD.gn | 18 +++++++++++-- ets2panda/declgen_ets2ts/BUILD.gn | 20 ++++++++++++--- ets2panda/driver/dependency_analyzer/BUILD.gn | 22 +++++++++++----- ets2panda/lsp/BUILD.gn | 19 +++++++++++--- 6 files changed, 103 insertions(+), 26 deletions(-) diff --git a/ets2panda/BUILD.gn b/ets2panda/BUILD.gn index 3ebfa38385..509012251f 100644 --- a/ets2panda/BUILD.gn +++ b/ets2panda/BUILD.gn @@ -11,7 +11,13 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/runtime_core/static_core/ark_config.gni") +if ((defined(ark_standalone_build) && ark_standalone_build) || + (defined(ark_static_standalone_build) && ark_static_standalone_build)) { + import("//arkcompiler/runtime_core/static_core/ark_config.gni") +} else { + import( + "//build/config/components/runtime_core/static_core/ark_common_config.gni") +} if (ark_standalone_build) { import("$build_root/ark.gni") @@ -1097,6 +1103,17 @@ config("libes2panda_config") { ] } +if ((defined(ark_standalone_build) && ark_standalone_build) || + (defined(ark_static_standalone_build) && ark_static_standalone_build)) { + libes2panda_configs = [ "$ark_root:ark_config" ] + libes2panda_public_configs = [ "$ark_root:ark_config" ] +} else { + libes2panda_configs = + [ "//build/config/components/runtime_core/static_core:ark_common_config" ] + libes2panda_public_configs = + [ "//build/config/components/runtime_core/static_core:ark_common_config" ] +} + if (ark_standalone_build || ark_static_standalone_build) { libes2panda_configs += [ "$ark_root/assembler:arkassembler_public_config", @@ -1105,8 +1122,7 @@ if (ark_standalone_build || ark_static_standalone_build) { ] } -libes2panda_configs = [ - "$ark_root:ark_config", +libes2panda_configs += [ ":libes2panda_public_config", ":libes2panda_config", ] @@ -1122,8 +1138,7 @@ if (ark_standalone_build || ark_static_standalone_build) { ] } -libes2panda_public_configs = [ - "$ark_root:ark_config", +libes2panda_public_configs += [ ":libes2panda_public_config", ":libes2panda_config", ] diff --git a/ets2panda/aot/BUILD.gn b/ets2panda/aot/BUILD.gn index 742f3affcb..7a45e1c675 100644 --- a/ets2panda/aot/BUILD.gn +++ b/ets2panda/aot/BUILD.gn @@ -11,7 +11,13 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/runtime_core/static_core/ark_config.gni") +if ((defined(ark_standalone_build) && ark_standalone_build) || + (defined(ark_static_standalone_build) && ark_static_standalone_build)) { + import("//arkcompiler/runtime_core/static_core/ark_config.gni") +} else { + import( + "//build/config/components/runtime_core/static_core/ark_common_config.gni") +} if (ark_standalone_build) { import("$build_root/ark.gni") @@ -26,11 +32,14 @@ ohos_executable("ets2panda") { "$target_gen_dir", "$target_gen_dir/include", ] - - configs = [ - "$ark_root:ark_config", - "$ark_es2panda_root:libes2panda_public_config", - ] + if ((defined(ark_standalone_build) && ark_standalone_build) || + (defined(ark_static_standalone_build) && ark_static_standalone_build)) { + configs = [ "$ark_root:ark_config" ] + } else { + configs = [ + "//build/config/components/runtime_core/static_core:ark_common_config", + ] + } if (ark_standalone_build || ark_static_standalone_build) { configs += [ @@ -43,6 +52,10 @@ ohos_executable("ets2panda") { ] } + configs += [ + "$ark_es2panda_root:libes2panda_public_config" + ] + deps = [ "$ark_es2panda_root:libes2panda_frontend_static", "$ark_es2panda_root:libes2panda_public_frontend_static", diff --git a/ets2panda/bindings/BUILD.gn b/ets2panda/bindings/BUILD.gn index e6dbc5c5f4..4a86840448 100644 --- a/ets2panda/bindings/BUILD.gn +++ b/ets2panda/bindings/BUILD.gn @@ -11,7 +11,14 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/runtime_core/static_core/ark_config.gni") +if ((defined(ark_standalone_build) && ark_standalone_build) || + (defined(ark_static_standalone_build) && ark_static_standalone_build)) { + import("//arkcompiler/runtime_core/static_core/ark_config.gni") +} else { + import( + "//build/config/components/runtime_core/static_core/ark_common_config.gni") +} + if (ark_standalone_build) { import("$build_root/ark.gni") } else { @@ -27,9 +34,16 @@ shared_library("ts_bindings") { "./native/src/convertors-napi.cpp", "./native/src/lsp.cpp", ] + if ((defined(ark_standalone_build) && ark_standalone_build) || + (defined(ark_static_standalone_build) && ark_static_standalone_build)) { + configs += [ "$ark_root:ark_config" ] + } else { + configs += [ + "//build/config/components/runtime_core/static_core:ark_common_config", + ] + } configs += [ "$ark_root/assembler:arkassembler_public_config", - "$ark_root:ark_config", "../:libes2panda_public_config", "../:libes2panda_config", "$ark_root/libpandabase:arkbase_public_config", diff --git a/ets2panda/declgen_ets2ts/BUILD.gn b/ets2panda/declgen_ets2ts/BUILD.gn index 165a35a81f..7b6d95b385 100644 --- a/ets2panda/declgen_ets2ts/BUILD.gn +++ b/ets2panda/declgen_ets2ts/BUILD.gn @@ -11,8 +11,14 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/runtime_core/static_core/ark_config.gni") import("//build/ohos.gni") +if ((defined(ark_standalone_build) && ark_standalone_build) || + (defined(ark_static_standalone_build) && ark_static_standalone_build)) { + import("//arkcompiler/runtime_core/static_core/ark_config.gni") +} else { + import( + "//build/config/components/runtime_core/static_core/ark_common_config.gni") +} ohos_executable("declgen_ets2ts") { sources = [ @@ -21,9 +27,15 @@ ohos_executable("declgen_ets2ts") { ] include_dirs = [ "$target_gen_dir" ] - - configs = [ - "$ark_root:ark_config", + if ((defined(ark_standalone_build) && ark_standalone_build) || + (defined(ark_static_standalone_build) && ark_static_standalone_build)) { + configs = [ "$ark_root:ark_config" ] + } else { + configs = [ + "//build/config/components/runtime_core/static_core:ark_common_config", + ] + } + configs += [ "$ark_es2panda_root:libes2panda_public_config", "$ark_root/assembler:arkassembler_public_config", "$ark_root/libpandafile:arkfile_public_config", diff --git a/ets2panda/driver/dependency_analyzer/BUILD.gn b/ets2panda/driver/dependency_analyzer/BUILD.gn index 8fc5e7492f..11142fd797 100644 --- a/ets2panda/driver/dependency_analyzer/BUILD.gn +++ b/ets2panda/driver/dependency_analyzer/BUILD.gn @@ -11,8 +11,14 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/runtime_core/static_core/ark_config.gni") import("//build/ohos.gni") +if ((defined(ark_standalone_build) && ark_standalone_build) || + (defined(ark_static_standalone_build) && ark_static_standalone_build)) { + import("//arkcompiler/runtime_core/static_core/ark_config.gni") +} else { + import( + "//build/config/components/runtime_core/static_core/ark_common_config.gni") +} ohos_executable("dependency_analyzer") { sources = [ @@ -21,11 +27,15 @@ ohos_executable("dependency_analyzer") { ] include_dirs = [ "$target_gen_dir" ] - - configs = [ - "$ark_root:ark_config", - "$ark_es2panda_root:libes2panda_public_config", - ] + if ((defined(ark_standalone_build) && ark_standalone_build) || + (defined(ark_static_standalone_build) && ark_static_standalone_build)) { + configs = [ "$ark_root:ark_config" ] + } else { + configs = [ + "//build/config/components/runtime_core/static_core:ark_common_config", + ] + } + configs += [ "$ark_es2panda_root:libes2panda_public_config" ] deps = [ "$ark_es2panda_root:libes2panda_frontend_static", diff --git a/ets2panda/lsp/BUILD.gn b/ets2panda/lsp/BUILD.gn index 08ec8fd1b9..b9082e4bc7 100644 --- a/ets2panda/lsp/BUILD.gn +++ b/ets2panda/lsp/BUILD.gn @@ -11,7 +11,13 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/runtime_core/static_core/ark_config.gni") +if ((defined(ark_standalone_build) && ark_standalone_build) || + (defined(ark_static_standalone_build) && ark_static_standalone_build)) { + import("//arkcompiler/runtime_core/static_core/ark_config.gni") +} else { + import( + "//build/config/components/runtime_core/static_core/ark_common_config.gni") +} if (ark_standalone_build) { import("$build_root/ark.gni") @@ -58,9 +64,16 @@ ohos_source_set("libes2panda_lsp_static") { "src/string_completions.cpp", "src/suggestion_diagnostics.cpp", ] - configs = [ + if ((defined(ark_standalone_build) && ark_standalone_build) || + (defined(ark_static_standalone_build) && ark_static_standalone_build)) { + configs = [ "$ark_root:ark_config" ] + } else { + configs = [ + "//build/config/components/runtime_core/static_core:ark_common_config", + ] + } + configs += [ "$ark_root/assembler:arkassembler_public_config", - "$ark_root:ark_config", "../:libes2panda_public_config", "../:libes2panda_config", "$ark_root/libpandabase:arkbase_public_config", -- Gitee From fd28daa32e573d4eaf64ac1e87a4375a551f61b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A5=88=E6=84=BF?= Date: Fri, 4 Jul 2025 14:47:41 +0800 Subject: [PATCH 252/268] Fixed the alarm for independent compilation Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICJZK2 Signed-off-by: chenlong --- ets2panda/BUILD.gn | 64 +++++++++++++++++++++++++++--------------- ets2panda/aot/BUILD.gn | 31 +++++++++++++++----- 2 files changed, 66 insertions(+), 29 deletions(-) diff --git a/ets2panda/BUILD.gn b/ets2panda/BUILD.gn index 5c1d967d82..6ce91a6479 100644 --- a/ets2panda/BUILD.gn +++ b/ets2panda/BUILD.gn @@ -23,12 +23,14 @@ config("libes2panda_public_config") { include_dirs = [ "$target_gen_dir", "$target_gen_dir/include", - "$target_gen_dir/generated", "//third_party/icu/icu4c/source/common", "//third_party/icu/icu4c/source/i18n", "//third_party/icu/icu4c/source", "$ark_es2panda_root", ] + if (ark_standalone_build || ark_static_standalone_build) { + include_dirs += [ "$target_gen_dir/generated" ] + } } action("check_build_system_consistency") { @@ -1131,26 +1133,35 @@ config("libes2panda_config") { ] } +if (ark_standalone_build || ark_static_standalone_build) { + libes2panda_configs += [ + "$ark_root/assembler:arkassembler_public_config", + "$ark_root/libpandabase:arkbase_public_config", + "$ark_root/libpandafile:arkfile_public_config", + ] +} + libes2panda_configs = [ - "$ark_root/assembler:arkassembler_public_config", "$ark_root:ark_config", ":libes2panda_public_config", ":libes2panda_config", - "$ark_root/libpandabase:arkbase_public_config", - "$ark_root/libpandafile:arkfile_public_config", - "$ark_root/abc2program:arkts_abc2program_public_config", ] +if (ark_standalone_build || ark_static_standalone_build) { + libes2panda_public_configs += [ + "$ark_root/assembler:arkassembler_public_config", + "$ark_root/libpandabase:arkbase_public_config", + "$ark_root/libpandafile:arkfile_public_config", + "$ark_root/bytecode_optimizer:bytecodeopt_public_config", + "$ark_root/runtime:arkruntime_public_config", + "$ark_root/compiler:arkcompiler_public_config", + ] +} + libes2panda_public_configs = [ - "$ark_root/assembler:arkassembler_public_config", "$ark_root:ark_config", ":libes2panda_public_config", ":libes2panda_config", - "$ark_root/libpandabase:arkbase_public_config", - "$ark_root/libpandafile:arkfile_public_config", - "$ark_root/bytecode_optimizer:bytecodeopt_public_config", - "$ark_root/compiler:arkcompiler_public_config", - "$ark_root/runtime:arkruntime_public_config", ] ohos_shared_library("libes2panda") { @@ -1198,6 +1209,10 @@ ohos_source_set("libes2panda_frontend_static") { external_deps += [ "icu:static_icui18n", "icu:static_icuuc", + "runtime_core:assembler_headers", + "runtime_core:libpandabase_headers", + "runtime_core:libpandafile_headers", + "runtime_core:runtime_gen_headers", ] } part_name = "ets_frontend" @@ -1237,17 +1252,6 @@ ohos_source_set("libes2panda_public_frontend_static") { deps = [ ":libes2panda_frontend_static" ] - if (ark_standalone_build || ark_static_standalone_build) { - deps += [ - "$ark_root/bytecode_optimizer:libarktsbytecodeopt_package", - "$ark_root/abc2program:libarktsabc2program_package", - "$ark_root/assembler:libarktsassembler", - "$ark_root/compiler:libarktscompiler", - "$ark_root/libpandabase:libarktsbase", - "$ark_root/libpandafile:libarktsfile", - ] - } - if (target_os != "win" && target_os != "mingw" && target_os != "winuwp") { deps += [ ":generate_ets2panda_info" ] defines = [ "ES2PANDA_COMPILE_BY_GN" ] @@ -1258,6 +1262,22 @@ ohos_source_set("libes2panda_public_frontend_static") { "runtime_core:libarktsabc2program_package", sdk_libc_secshared_dep, ] + + if (ark_standalone_build || ark_static_standalone_build) { + deps += [ "$ark_root/bytecode_optimizer:libarktsbytecodeopt_package" ] + } else { + external_deps += [ + "runtime_core:assembler_headers", + "runtime_core:runtime_gen_headers", + "runtime_core:libpandabase_headers", + "runtime_core:libpandafile_headers", + "runtime_core:bytecode_optimizer_headers", + "runtime_core:runtime_headers", + "runtime_core:compiler_headers", + "runtime_core:verification_headers", + ] + } + part_name = "ets_frontend" subsystem_name = "arkcompiler" } diff --git a/ets2panda/aot/BUILD.gn b/ets2panda/aot/BUILD.gn index db0599ed82..b6d0d652af 100644 --- a/ets2panda/aot/BUILD.gn +++ b/ets2panda/aot/BUILD.gn @@ -29,16 +29,20 @@ ohos_executable("ets2panda") { configs = [ "$ark_root:ark_config", - "$ark_root/assembler:arkassembler_public_config", "$ark_es2panda_root:libes2panda_public_config", - "$ark_root/libpandafile:arkfile_public_config", - "$ark_root/libpandabase:arkbase_public_config", - "$ark_root/bytecode_optimizer:bytecodeopt_public_config", - "$ark_root/compiler:arkcompiler_public_config", - "$ark_root/runtime:arkruntime_public_config", - "$ark_root/abc2program:arkts_abc2program_public_config", ] + if (ark_standalone_build || ark_static_standalone_build) { + configs += [ + "$ark_root/assembler:arkassembler_public_config", + "$ark_root/libpandafile:arkfile_public_config", + "$ark_root/libpandabase:arkbase_public_config", + "$ark_root/bytecode_optimizer:bytecodeopt_public_config", + "$ark_root/runtime:arkruntime_public_config", + "$ark_root/compiler:arkcompiler_public_config", + ] + } + deps = [ "$ark_es2panda_root:libes2panda_frontend_static", "$ark_es2panda_root:libes2panda_public_frontend_static", @@ -62,6 +66,19 @@ ohos_executable("ets2panda") { sdk_libc_secshared_dep, ] + if (!(ark_standalone_build || ark_static_standalone_build)) { + external_deps += [ + "runtime_core:assembler_headers", + "runtime_core:bytecode_optimizer_headers", + "runtime_core:libpandabase_headers", + "runtime_core:libpandafile_headers", + "runtime_core:runtime_gen_headers", + "runtime_core:runtime_headers", + "runtime_core:compiler_headers", + "runtime_core:verification_headers", + ] + } + if (defined(ohos_indep_compiler_enable) && ohos_indep_compiler_enable) { external_deps += [ "icu:shared_icuuc" ] } -- Gitee From 84af1b7361fffb6122c3c49c1eea89594b2a1149 Mon Sep 17 00:00:00 2001 From: lijunru Date: Wed, 25 Jun 2025 18:08:29 +0800 Subject: [PATCH 253/268] Fix ohos independent build error Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICHSZV Change-id: i4f367000f535c8cd0c4e366c964adc017d0b8aa6 Signed-off-by: lijunru --- ets2panda/BUILD.gn | 25 +++++++++++++---- ets2panda/aot/BUILD.gn | 25 +++++++++++++---- ets2panda/bindings/BUILD.gn | 18 ++++++++++-- ets2panda/declgen_ets2ts/BUILD.gn | 20 ++++++++++--- ets2panda/driver/dependency_analyzer/BUILD.gn | 28 +++++++++++-------- ets2panda/lsp/BUILD.gn | 19 +++++++++++-- 6 files changed, 104 insertions(+), 31 deletions(-) diff --git a/ets2panda/BUILD.gn b/ets2panda/BUILD.gn index 6ce91a6479..bf9285760d 100644 --- a/ets2panda/BUILD.gn +++ b/ets2panda/BUILD.gn @@ -11,7 +11,13 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/runtime_core/static_core/ark_config.gni") +if ((defined(ark_standalone_build) && ark_standalone_build) || + (defined(ark_static_standalone_build) && ark_static_standalone_build)) { + import("//arkcompiler/runtime_core/static_core/ark_config.gni") +} else { + import( + "//build/config/components/runtime_core/static_core/ark_common_config.gni") +} if (ark_standalone_build) { import("$build_root/ark.gni") @@ -1133,6 +1139,17 @@ config("libes2panda_config") { ] } +if ((defined(ark_standalone_build) && ark_standalone_build) || + (defined(ark_static_standalone_build) && ark_static_standalone_build)) { + libes2panda_configs = [ "$ark_root:ark_config" ] + libes2panda_public_configs = [ "$ark_root:ark_config" ] +} else { + libes2panda_configs = + [ "//build/config/components/runtime_core/static_core:ark_common_config" ] + libes2panda_public_configs = + [ "//build/config/components/runtime_core/static_core:ark_common_config" ] +} + if (ark_standalone_build || ark_static_standalone_build) { libes2panda_configs += [ "$ark_root/assembler:arkassembler_public_config", @@ -1141,8 +1158,7 @@ if (ark_standalone_build || ark_static_standalone_build) { ] } -libes2panda_configs = [ - "$ark_root:ark_config", +libes2panda_configs += [ ":libes2panda_public_config", ":libes2panda_config", ] @@ -1158,8 +1174,7 @@ if (ark_standalone_build || ark_static_standalone_build) { ] } -libes2panda_public_configs = [ - "$ark_root:ark_config", +libes2panda_public_configs += [ ":libes2panda_public_config", ":libes2panda_config", ] diff --git a/ets2panda/aot/BUILD.gn b/ets2panda/aot/BUILD.gn index b6d0d652af..a3a533b320 100644 --- a/ets2panda/aot/BUILD.gn +++ b/ets2panda/aot/BUILD.gn @@ -11,7 +11,13 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/runtime_core/static_core/ark_config.gni") +if ((defined(ark_standalone_build) && ark_standalone_build) || + (defined(ark_static_standalone_build) && ark_static_standalone_build)) { + import("//arkcompiler/runtime_core/static_core/ark_config.gni") +} else { + import( + "//build/config/components/runtime_core/static_core/ark_common_config.gni") +} if (ark_standalone_build) { import("$build_root/ark.gni") @@ -26,11 +32,14 @@ ohos_executable("ets2panda") { "$target_gen_dir", "$target_gen_dir/include", ] - - configs = [ - "$ark_root:ark_config", - "$ark_es2panda_root:libes2panda_public_config", - ] + if ((defined(ark_standalone_build) && ark_standalone_build) || + (defined(ark_static_standalone_build) && ark_static_standalone_build)) { + configs = [ "$ark_root:ark_config" ] + } else { + configs = [ + "//build/config/components/runtime_core/static_core:ark_common_config", + ] + } if (ark_standalone_build || ark_static_standalone_build) { configs += [ @@ -43,6 +52,10 @@ ohos_executable("ets2panda") { ] } + configs += [ + "$ark_es2panda_root:libes2panda_public_config" + ] + deps = [ "$ark_es2panda_root:libes2panda_frontend_static", "$ark_es2panda_root:libes2panda_public_frontend_static", diff --git a/ets2panda/bindings/BUILD.gn b/ets2panda/bindings/BUILD.gn index 0e6be72fd9..a6f48462ab 100644 --- a/ets2panda/bindings/BUILD.gn +++ b/ets2panda/bindings/BUILD.gn @@ -11,7 +11,14 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/runtime_core/static_core/ark_config.gni") +if ((defined(ark_standalone_build) && ark_standalone_build) || + (defined(ark_static_standalone_build) && ark_static_standalone_build)) { + import("//arkcompiler/runtime_core/static_core/ark_config.gni") +} else { + import( + "//build/config/components/runtime_core/static_core/ark_common_config.gni") +} + if (ark_standalone_build) { import("$build_root/ark.gni") } else { @@ -26,9 +33,16 @@ shared_library("ts_bindings") { "./native/src/convertors-napi.cpp", "./native/src/lsp.cpp", ] + if ((defined(ark_standalone_build) && ark_standalone_build) || + (defined(ark_static_standalone_build) && ark_static_standalone_build)) { + configs += [ "$ark_root:ark_config" ] + } else { + configs += [ + "//build/config/components/runtime_core/static_core:ark_common_config", + ] + } configs += [ "$ark_root/assembler:arkassembler_public_config", - "$ark_root:ark_config", "../:libes2panda_public_config", "../:libes2panda_config", "$ark_root/libpandabase:arkbase_public_config", diff --git a/ets2panda/declgen_ets2ts/BUILD.gn b/ets2panda/declgen_ets2ts/BUILD.gn index 8de1df605d..8cc3dabeef 100644 --- a/ets2panda/declgen_ets2ts/BUILD.gn +++ b/ets2panda/declgen_ets2ts/BUILD.gn @@ -11,8 +11,14 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/runtime_core/static_core/ark_config.gni") import("//build/ohos.gni") +if ((defined(ark_standalone_build) && ark_standalone_build) || + (defined(ark_static_standalone_build) && ark_static_standalone_build)) { + import("//arkcompiler/runtime_core/static_core/ark_config.gni") +} else { + import( + "//build/config/components/runtime_core/static_core/ark_common_config.gni") +} ohos_executable("declgen_ets2ts") { sources = [ @@ -22,9 +28,15 @@ ohos_executable("declgen_ets2ts") { ] include_dirs = [ "$target_gen_dir" ] - - configs = [ - "$ark_root:ark_config", + if ((defined(ark_standalone_build) && ark_standalone_build) || + (defined(ark_static_standalone_build) && ark_static_standalone_build)) { + configs = [ "$ark_root:ark_config" ] + } else { + configs = [ + "//build/config/components/runtime_core/static_core:ark_common_config", + ] + } + configs += [ "$ark_es2panda_root:libes2panda_public_config", "$ark_root/assembler:arkassembler_public_config", "$ark_root/libpandafile:arkfile_public_config", diff --git a/ets2panda/driver/dependency_analyzer/BUILD.gn b/ets2panda/driver/dependency_analyzer/BUILD.gn index 7adcfb1a6f..7e8e3448ac 100644 --- a/ets2panda/driver/dependency_analyzer/BUILD.gn +++ b/ets2panda/driver/dependency_analyzer/BUILD.gn @@ -11,8 +11,14 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/runtime_core/static_core/ark_config.gni") import("//build/ohos.gni") +if ((defined(ark_standalone_build) && ark_standalone_build) || + (defined(ark_static_standalone_build) && ark_static_standalone_build)) { + import("//arkcompiler/runtime_core/static_core/ark_config.gni") +} else { + import( + "//build/config/components/runtime_core/static_core/ark_common_config.gni") +} ohos_executable("dependency_analyzer") { sources = [ @@ -20,16 +26,16 @@ ohos_executable("dependency_analyzer") { "main.cpp", ] - configs = [ - "$ark_root:ark_config", - "$ark_root/assembler:arkassembler_public_config", - "$ark_es2panda_root:libes2panda_public_config", - "$ark_root/libpandafile:arkfile_public_config", - "$ark_root/libpandabase:arkbase_public_config", - "$ark_root/bytecode_optimizer:bytecodeopt_public_config", - "$ark_root/compiler:arkcompiler_public_config", - "$ark_root/runtime:arkruntime_public_config", - ] + include_dirs = [ "$target_gen_dir" ] + if ((defined(ark_standalone_build) && ark_standalone_build) || + (defined(ark_static_standalone_build) && ark_static_standalone_build)) { + configs = [ "$ark_root:ark_config" ] + } else { + configs = [ + "//build/config/components/runtime_core/static_core:ark_common_config", + ] + } + configs += [ "$ark_es2panda_root:libes2panda_public_config" ] deps = [ "$ark_es2panda_root:libes2panda_frontend_static", diff --git a/ets2panda/lsp/BUILD.gn b/ets2panda/lsp/BUILD.gn index fd60354d62..ab1423c222 100644 --- a/ets2panda/lsp/BUILD.gn +++ b/ets2panda/lsp/BUILD.gn @@ -11,7 +11,13 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/runtime_core/static_core/ark_config.gni") +if ((defined(ark_standalone_build) && ark_standalone_build) || + (defined(ark_static_standalone_build) && ark_static_standalone_build)) { + import("//arkcompiler/runtime_core/static_core/ark_config.gni") +} else { + import( + "//build/config/components/runtime_core/static_core/ark_common_config.gni") +} if (ark_standalone_build) { import("$build_root/ark.gni") @@ -100,9 +106,16 @@ ohos_source_set("libes2panda_lsp_static") { "src/todo_comments.cpp", "src/types.cpp", ] - configs = [ + if ((defined(ark_standalone_build) && ark_standalone_build) || + (defined(ark_static_standalone_build) && ark_static_standalone_build)) { + configs = [ "$ark_root:ark_config" ] + } else { + configs = [ + "//build/config/components/runtime_core/static_core:ark_common_config", + ] + } + configs += [ "$ark_root/assembler:arkassembler_public_config", - "$ark_root:ark_config", "../:libes2panda_public_config", "../:libes2panda_config", "$ark_root/libpandabase:arkbase_public_config", -- Gitee From 4b11e749a88c69819fb05897cc33d9396c0e647d Mon Sep 17 00:00:00 2001 From: tengtengh Date: Mon, 7 Jul 2025 17:23:38 +0800 Subject: [PATCH 254/268] Merge 0328 into 0702 Signed-off-by: tengtengh --- ets2panda/BUILD.gn | 10 +++++++++- ets2panda/checker/types/ets/etsTupleType.h | 5 ----- ets2panda/declgen_ets2ts/declgenEts2Ts.h | 1 - .../scripts/install-ohos-typescript-and-homecheck.mjs | 2 +- ets2panda/lsp/src/completions.cpp | 3 +++ ets2panda/varbinder/ETSBinder.cpp | 5 ----- ets2panda/varbinder/ETSBinder.h | 4 ++++ ets2panda/varbinder/varbinder.cpp | 5 ----- 8 files changed, 17 insertions(+), 18 deletions(-) diff --git a/ets2panda/BUILD.gn b/ets2panda/BUILD.gn index bf9285760d..b02fb5319a 100644 --- a/ets2panda/BUILD.gn +++ b/ets2panda/BUILD.gn @@ -1161,6 +1161,7 @@ if (ark_standalone_build || ark_static_standalone_build) { libes2panda_configs += [ ":libes2panda_public_config", ":libes2panda_config", + "$ark_root/abc2program:arkts_abc2program_public_config", ] if (ark_standalone_build || ark_static_standalone_build) { @@ -1279,7 +1280,14 @@ ohos_source_set("libes2panda_public_frontend_static") { ] if (ark_standalone_build || ark_static_standalone_build) { - deps += [ "$ark_root/bytecode_optimizer:libarktsbytecodeopt_package" ] + deps += [ + "$ark_root/bytecode_optimizer:libarktsbytecodeopt_package", + "$ark_root/abc2program:libarktsabc2program_package", + "$ark_root/assembler:libarktsassembler", + "$ark_root/compiler:libarktscompiler", + "$ark_root/libpandabase:libarktsbase", + "$ark_root/libpandafile:libarktsfile", + ] } else { external_deps += [ "runtime_core:assembler_headers", diff --git a/ets2panda/checker/types/ets/etsTupleType.h b/ets2panda/checker/types/ets/etsTupleType.h index 3660276686..2a326dedf9 100644 --- a/ets2panda/checker/types/ets/etsTupleType.h +++ b/ets2panda/checker/types/ets/etsTupleType.h @@ -48,11 +48,6 @@ public: return wrapperType_; } - [[nodiscard]] ETSObjectType *GetWrapperType() const - { - return wrapperType_; - } - [[nodiscard]] Type *GetTypeAtIndex(TupleSizeType index) const; void ToString(std::stringstream &ss, bool precise) const override; diff --git a/ets2panda/declgen_ets2ts/declgenEts2Ts.h b/ets2panda/declgen_ets2ts/declgenEts2Ts.h index 48013c18b2..850722c6f0 100644 --- a/ets2panda/declgen_ets2ts/declgenEts2Ts.h +++ b/ets2panda/declgen_ets2ts/declgenEts2Ts.h @@ -322,4 +322,3 @@ private: } // namespace ark::es2panda::declgen_ets2ts #endif // ES2PANDA_DECLGEN_ETS2TS_H - diff --git a/ets2panda/linter/scripts/install-ohos-typescript-and-homecheck.mjs b/ets2panda/linter/scripts/install-ohos-typescript-and-homecheck.mjs index 5fc2c55baa..d4271589fe 100644 --- a/ets2panda/linter/scripts/install-ohos-typescript-and-homecheck.mjs +++ b/ets2panda/linter/scripts/install-ohos-typescript-and-homecheck.mjs @@ -90,7 +90,7 @@ function getTypescript(detectedOS) { fs.mkdirSync(third_party); } - let branch = process.env.TYPESCRIPT_BRANCH ?? 'OpenHarmony_feature_20250328' + let branch = process.env.TYPESCRIPT_BRANCH ?? 'master' if (detectedOS === 'Linux' || detectedOS === 'macOS') { let timeToWait = 5000 diff --git a/ets2panda/lsp/src/completions.cpp b/ets2panda/lsp/src/completions.cpp index 6c752c52fb..8b1961ff2f 100644 --- a/ets2panda/lsp/src/completions.cpp +++ b/ets2panda/lsp/src/completions.cpp @@ -460,9 +460,12 @@ std::vector GetCompletionFromTSInterfaceDeclaration(ir::TSInter auto extendCom = extendInterf->IsTSInterfaceDeclaration() ? GetCompletionFromTSInterfaceDeclaration(extendInterf->AsTSInterfaceDeclaration(), triggerWord) + : completions; + extendCompletions.insert(extendCompletions.end(), extendCom.begin(), extendCom.end()); } } auto qualifiedBodies = FilterFromInterfaceBody(bodies, triggerWord); + auto res = GetEntriesForTSInterfaceDeclaration(qualifiedBodies); res.insert(res.end(), extendCompletions.begin(), extendCompletions.end()); return res; } diff --git a/ets2panda/varbinder/ETSBinder.cpp b/ets2panda/varbinder/ETSBinder.cpp index 588f2f26c7..ce4d9475a3 100644 --- a/ets2panda/varbinder/ETSBinder.cpp +++ b/ets2panda/varbinder/ETSBinder.cpp @@ -1559,9 +1559,4 @@ bool ETSBinder::IsGlobalIdentifier([[maybe_unused]] const util::StringView &str) return false; } -bool ETSBinder::IsGlobalIdentifier([[maybe_unused]] const util::StringView &str) const -{ - return false; -} - } // namespace ark::es2panda::varbinder diff --git a/ets2panda/varbinder/ETSBinder.h b/ets2panda/varbinder/ETSBinder.h index a2d434c27d..001a02cb10 100644 --- a/ets2panda/varbinder/ETSBinder.h +++ b/ets2panda/varbinder/ETSBinder.h @@ -199,11 +199,15 @@ public: void ThrowError(const lexer::SourcePosition &pos, const diagnostic::DiagnosticKind &kind) const { + ThrowError(pos, kind, util::DiagnosticMessageParams {}); + } + void ThrowError(const lexer::SourcePosition &pos, const diagnostic::DiagnosticKind &kind, const util::DiagnosticMessageParams ¶ms) const override; bool IsGlobalIdentifier(const util::StringView &str) const override; void SetDefaultImports(ArenaVector defaultImports) noexcept { + defaultImports_ = std::move(defaultImports); } void AddDynamicImport(ir::ETSImportDeclaration *import); diff --git a/ets2panda/varbinder/varbinder.cpp b/ets2panda/varbinder/varbinder.cpp index cce4d6e6fe..fc48436145 100644 --- a/ets2panda/varbinder/varbinder.cpp +++ b/ets2panda/varbinder/varbinder.cpp @@ -94,11 +94,6 @@ bool VarBinder::IsGlobalIdentifier(const util::StringView &str) const return util::Helpers::IsGlobalIdentifier(str); } -bool VarBinder::IsGlobalIdentifier(const util::StringView &str) const -{ - return util::Helpers::IsGlobalIdentifier(str); -} - void VarBinder::IdentifierAnalysis() { ES2PANDA_ASSERT(program_->Ast()); -- Gitee From cfb9d4a327234db57e3842264f25c35a36b1c4c9 Mon Sep 17 00:00:00 2001 From: xudan16 Date: Tue, 8 Jul 2025 17:35:50 +0800 Subject: [PATCH 255/268] homecheck add try catch Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICKU8I Signed-off-by: xudan16 --- .../linter/homecheck/src/model/File2Check.ts | 8 +++-- .../homecheck/src/model/Project2Check.ts | 12 ++++--- .../homecheck/src/utils/common/Disable.ts | 35 +++++++++++-------- .../homecheck/src/utils/common/FileUtils.ts | 16 +++++---- 4 files changed, 45 insertions(+), 26 deletions(-) diff --git a/ets2panda/linter/homecheck/src/model/File2Check.ts b/ets2panda/linter/homecheck/src/model/File2Check.ts index ecfc86270a..f34f7e1420 100644 --- a/ets2panda/linter/homecheck/src/model/File2Check.ts +++ b/ets2panda/linter/homecheck/src/model/File2Check.ts @@ -105,8 +105,12 @@ export class File2Check { } public async checkDisable(): Promise { - const fileLineList = await FileUtils.readLinesFromFile(this.arkFile.getFilePath()); - this.issues = await filterDisableIssue(fileLineList, this.issues, this.arkFile.getFilePath()); + try { + const fileLineList = await FileUtils.readLinesFromFile(this.arkFile.getFilePath()); + this.issues = await filterDisableIssue(fileLineList, this.issues, this.arkFile.getFilePath()); + } catch (e) { + logger.error(e); + } } public async run(): Promise { diff --git a/ets2panda/linter/homecheck/src/model/Project2Check.ts b/ets2panda/linter/homecheck/src/model/Project2Check.ts index 3e9c1bf9ed..43d57723ef 100644 --- a/ets2panda/linter/homecheck/src/model/Project2Check.ts +++ b/ets2panda/linter/homecheck/src/model/Project2Check.ts @@ -167,10 +167,14 @@ export class Project2Check { if (!fs.existsSync(filePath)) { continue; } - const fileLineList = await FileUtils.readLinesFromFile(filePath); - const filtedResult = await filterDisableIssue(fileLineList, [issue], filePath); - if (filtedResult.length > 0) { - filtedIssues = filtedIssues.concat(filtedResult[0]); + try { + const fileLineList = await FileUtils.readLinesFromFile(filePath); + const filtedResult = await filterDisableIssue(fileLineList, [issue], filePath); + if (filtedResult.length > 0) { + filtedIssues = filtedIssues.concat(filtedResult[0]); + } + } catch (e) { + logger.error(e); } } this.issues = filtedIssues; diff --git a/ets2panda/linter/homecheck/src/utils/common/Disable.ts b/ets2panda/linter/homecheck/src/utils/common/Disable.ts index e8f86a2618..a33205ff20 100644 --- a/ets2panda/linter/homecheck/src/utils/common/Disable.ts +++ b/ets2panda/linter/homecheck/src/utils/common/Disable.ts @@ -17,6 +17,9 @@ import * as fs from 'fs'; import path from 'path'; import { IssueReport } from '../../model/Defects'; import { FileUtils } from '../../Index'; +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'Disable'); export const DisableText = { FILE_DISABLE_TEXT: '\/* homecheck-disable *\/', @@ -25,23 +28,27 @@ export const DisableText = { export async function filterDisableIssue(lineList: string[], issues: IssueReport[], filePath: string): Promise { let filtedIssues: IssueReport[] = []; - for (const issue of issues) { - // @migration/arkui-data-observation规则的自动修复是在定义处,存在跨文件场景 - const actualFilePath = path.normalize(issue.defect.mergeKey.split('%')[0]); - if (path.normalize(actualFilePath) !== path.normalize(filePath)) { - if (!fs.existsSync(actualFilePath)) { + try { + for (const issue of issues) { + // @migration/arkui-data-observation规则的自动修复是在定义处,存在跨文件场景 + const actualFilePath = path.normalize(issue.defect.mergeKey.split('%')[0]); + if (path.normalize(actualFilePath) !== path.normalize(filePath)) { + if (!fs.existsSync(actualFilePath)) { + continue; + } + lineList = await FileUtils.readLinesFromFile(actualFilePath); + } + // 有些特殊规则允许返回行列号为0 + if (issue.defect.reportLine < 0 || issue.defect.reportLine - 1 > lineList.length) { continue; } - lineList = await FileUtils.readLinesFromFile(actualFilePath); - } - // 有些特殊规则允许返回行列号为0 - if (issue.defect.reportLine < 0 || issue.defect.reportLine - 1 > lineList.length) { - continue; - } - const text = lineList[issue.defect.reportLine - 2]; - if (!isDisableIssue(text, issue.defect.ruleId)) { - filtedIssues.push(issue); + const text = lineList[issue.defect.reportLine - 2]; + if (!isDisableIssue(text, issue.defect.ruleId)) { + filtedIssues.push(issue); + } } + } catch (e) { + logger.error(e); } return filtedIssues; } diff --git a/ets2panda/linter/homecheck/src/utils/common/FileUtils.ts b/ets2panda/linter/homecheck/src/utils/common/FileUtils.ts index f17425f284..a69df56e6a 100644 --- a/ets2panda/linter/homecheck/src/utils/common/FileUtils.ts +++ b/ets2panda/linter/homecheck/src/utils/common/FileUtils.ts @@ -67,12 +67,16 @@ export class FileUtils { let result: string[] = []; for (const filePath of fileList) { if (!ignoreGlob?.matchGlob(filePath) && fileGlob.matchGlob(filePath)) { - // 读取file文件内容首行,若为屏蔽行则跳过 - const firstLineText = await this.readLinesFromFile(filePath, 1); - if (firstLineText.includes(DisableText.FILE_DISABLE_TEXT)) { - continue; + try { + // 读取file文件内容首行,若为屏蔽行则跳过 + const firstLineText = await this.readLinesFromFile(filePath, 1); + if (firstLineText.includes(DisableText.FILE_DISABLE_TEXT)) { + continue; + } + result.push(filePath); + } catch (e) { + logger.error(e); } - result.push(filePath); } } return result; @@ -310,4 +314,4 @@ export class FileUtils { export enum WriteFileMode { OVERWRITE, APPEND -} +} \ No newline at end of file -- Gitee From 2b1886dacb2b7c92bf9bb82e3cc0197cfbc6e6a9 Mon Sep 17 00:00:00 2001 From: tengtengh Date: Tue, 8 Jul 2025 20:30:23 +0800 Subject: [PATCH 256/268] Merge 0328 to 0702 modified: ets2panda/BUILD.gn modified: ets2panda/declgen_ets2ts/declgenEts2Ts.cpp Signed-off-by: tengtengh --- ets2panda/BUILD.gn | 25 +++++++++++----------- ets2panda/declgen_ets2ts/declgenEts2Ts.cpp | 1 - 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/ets2panda/BUILD.gn b/ets2panda/BUILD.gn index b02fb5319a..c0857f4c8d 100644 --- a/ets2panda/BUILD.gn +++ b/ets2panda/BUILD.gn @@ -224,8 +224,8 @@ libes2panda_sources = [ "compiler/lowering/ets/cfgBuilderPhase.cpp", "compiler/lowering/ets/constantExpressionLowering.cpp", "compiler/lowering/ets/convertPrimitiveCastMethodCall.cpp", - "compiler/lowering/ets/declareOverloadLowering.cpp", "compiler/lowering/ets/declGenPhase.cpp", + "compiler/lowering/ets/declareOverloadLowering.cpp", "compiler/lowering/ets/defaultParametersInConstructorLowering.cpp", "compiler/lowering/ets/defaultParametersLowering.cpp", "compiler/lowering/ets/dynamicImport.cpp", @@ -1065,7 +1065,7 @@ ES2PANDA_API_GENERATED = [ "$LIBGEN_DIR/gen/headers/util/importPathManager.yaml", "$LIBGEN_DIR/gen/headers/util/path.yaml", "$LIBGEN_DIR/gen/headers/util/arktsconfig.yaml", - "$LIBGEN_DIR/gen/headers/util/options.yaml" + "$LIBGEN_DIR/gen/headers/util/options.yaml", ] ES2PANDA_API = [ @@ -1155,13 +1155,13 @@ if (ark_standalone_build || ark_static_standalone_build) { "$ark_root/assembler:arkassembler_public_config", "$ark_root/libpandabase:arkbase_public_config", "$ark_root/libpandafile:arkfile_public_config", + "$ark_root/abc2program:arkts_abc2program_public_config", ] } libes2panda_configs += [ ":libes2panda_public_config", ":libes2panda_config", - "$ark_root/abc2program:arkts_abc2program_public_config", ] if (ark_standalone_build || ark_static_standalone_build) { @@ -1209,11 +1209,11 @@ ohos_source_set("libes2panda_frontend_static") { ":isa_gen_es2panda_isa_h", ] external_deps = [ + "runtime_core:libarktsabc2program_package", "runtime_core:libarktsassembler_package", "runtime_core:libarktsbase_package", "runtime_core:libarktscompiler_package", "runtime_core:libarktsfile_package", - "runtime_core:libarktsabc2program_package", sdk_libc_secshared_dep, ] if (ark_standalone_build || ark_static_standalone_build) { @@ -1225,6 +1225,7 @@ ohos_source_set("libes2panda_frontend_static") { external_deps += [ "icu:static_icui18n", "icu:static_icuuc", + "runtime_core:arkts_abc2program_public_headers", "runtime_core:assembler_headers", "runtime_core:libpandabase_headers", "runtime_core:libpandafile_headers", @@ -1274,16 +1275,16 @@ ohos_source_set("libes2panda_public_frontend_static") { } external_deps = [ - "runtime_core:libarktsbytecodeopt_package", "runtime_core:libarktsabc2program_package", + "runtime_core:libarktsbytecodeopt_package", sdk_libc_secshared_dep, ] if (ark_standalone_build || ark_static_standalone_build) { deps += [ - "$ark_root/bytecode_optimizer:libarktsbytecodeopt_package", "$ark_root/abc2program:libarktsabc2program_package", "$ark_root/assembler:libarktsassembler", + "$ark_root/bytecode_optimizer:libarktsbytecodeopt_package", "$ark_root/compiler:libarktscompiler", "$ark_root/libpandabase:libarktsbase", "$ark_root/libpandafile:libarktsfile", @@ -1291,16 +1292,16 @@ ohos_source_set("libes2panda_public_frontend_static") { } else { external_deps += [ "runtime_core:assembler_headers", - "runtime_core:runtime_gen_headers", + "runtime_core:bytecode_optimizer_headers", + "runtime_core:compiler_headers", "runtime_core:libpandabase_headers", "runtime_core:libpandafile_headers", - "runtime_core:bytecode_optimizer_headers", + "runtime_core:runtime_gen_headers", "runtime_core:runtime_headers", - "runtime_core:compiler_headers", "runtime_core:verification_headers", ] } - + part_name = "ets_frontend" subsystem_name = "arkcompiler" } @@ -1388,10 +1389,10 @@ template("panda_code_fix_gen") { destination = invoker.destination api = api_list if (defined(invoker.requires)) { - requires = invoker.requires + requires = invoker.requires } if (defined(invoker.extra_dependencies)) { - extra_dependencies = invoker.extra_dependencies + extra_dependencies = invoker.extra_dependencies } } } diff --git a/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp b/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp index 675ac1ed1c..7b37223644 100644 --- a/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp +++ b/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp @@ -2247,4 +2247,3 @@ bool GenerateTsDeclarations(checker::ETSChecker *checker, const ark::es2panda::p return true; } } // namespace ark::es2panda::declgen_ets2ts - -- Gitee From e2b7e6bd258696237176a348d10f7128a9cde322 Mon Sep 17 00:00:00 2001 From: tengtengh Date: Wed, 9 Jul 2025 10:34:01 +0800 Subject: [PATCH 257/268] Merge 0328 into 0702 Signed-off-by: tengtengh --- ets2panda/driver/dependency_analyzer/BUILD.gn | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ets2panda/driver/dependency_analyzer/BUILD.gn b/ets2panda/driver/dependency_analyzer/BUILD.gn index 7e8e3448ac..96449c6f58 100644 --- a/ets2panda/driver/dependency_analyzer/BUILD.gn +++ b/ets2panda/driver/dependency_analyzer/BUILD.gn @@ -51,11 +51,14 @@ ohos_executable("dependency_analyzer") { } external_deps = [ + "runtime_core:assembler_headers", "runtime_core:libarktsassembler_package", "runtime_core:libarktsbase_package", "runtime_core:libarktsbytecodeopt_package", "runtime_core:libarktscompiler_package", "runtime_core:libarktsfile_package", + "runtime_core:libpandabase_headers", + "runtime_core:libpandafile_headers", sdk_libc_secshared_dep, ] -- Gitee From 23766b9e68df931136bd5abd8302ea9b18ab4fb5 Mon Sep 17 00:00:00 2001 From: tengtengh Date: Wed, 9 Jul 2025 15:45:29 +0800 Subject: [PATCH 258/268] Merge 0328 to 0702 : bindings Signed-off-by: tengtengh --- .../bindings/src/Es2pandaNativeModule.ts | 498 ------------------ ets2panda/bindings/src/InteropNativeModule.ts | 90 ---- ets2panda/bindings/src/InteropTypes.ts | 38 -- ets2panda/bindings/src/arktsConfigGenerate.ts | 58 -- ets2panda/bindings/src/arrays.ts | 171 ------ ets2panda/bindings/src/build/buildMode.ts | 188 ------- ets2panda/bindings/src/buildConfigGenerate.ts | 230 -------- ets2panda/bindings/src/driver_helper.ts | 123 ----- ets2panda/bindings/src/global.ts | 108 ---- ets2panda/bindings/src/lspNode.ts | 400 -------------- ets2panda/bindings/src/lsp_helper.ts | 355 ------------- ets2panda/bindings/src/strings.ts | 210 -------- ets2panda/bindings/src/types.ts | 198 ------- 13 files changed, 2667 deletions(-) delete mode 100644 ets2panda/bindings/src/Es2pandaNativeModule.ts delete mode 100644 ets2panda/bindings/src/InteropNativeModule.ts delete mode 100644 ets2panda/bindings/src/InteropTypes.ts delete mode 100644 ets2panda/bindings/src/arktsConfigGenerate.ts delete mode 100644 ets2panda/bindings/src/arrays.ts delete mode 100644 ets2panda/bindings/src/build/buildMode.ts delete mode 100644 ets2panda/bindings/src/buildConfigGenerate.ts delete mode 100644 ets2panda/bindings/src/driver_helper.ts delete mode 100644 ets2panda/bindings/src/global.ts delete mode 100644 ets2panda/bindings/src/lspNode.ts delete mode 100644 ets2panda/bindings/src/lsp_helper.ts delete mode 100644 ets2panda/bindings/src/strings.ts delete mode 100644 ets2panda/bindings/src/types.ts diff --git a/ets2panda/bindings/src/Es2pandaNativeModule.ts b/ets2panda/bindings/src/Es2pandaNativeModule.ts deleted file mode 100644 index 643cb0b3d4..0000000000 --- a/ets2panda/bindings/src/Es2pandaNativeModule.ts +++ /dev/null @@ -1,498 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as fs from 'fs'; -import * as path from 'path'; -import { KNativePointer as KPtr, KInt, KBoolean, KNativePointer, KDouble, KUInt, KStringPtr } from './InteropTypes'; -import { Es2pandaNativeModule as GeneratedEs2pandaNativeModule } from './generated/Es2pandaNativeModule'; -import { loadNativeModuleLibrary, registerNativeModuleLibraryName } from './loadLibraries'; -import { throwError } from './utils'; - -export type KPtrArray = BigUint64Array; - -export class Es2pandaNativeModule { - _ClassDefinitionSuper(context: KPtr, node: KPtr): KPtr { - throw new Error('Not implemented'); - } - _CreateTSInterfaceDeclaration( - _context: KPtr, - _extends: KPtrArray, - _extendsLen: KInt, - _id: KPtr, - _typeParams: KPtr, - _body: KPtr, - _isStatic: KBoolean, - _isExternal: KBoolean - ): KPtr { - throw new Error('Not implemented'); - } - - _ContextState(context: KPtr): KInt { - throw new Error('Not implemented'); - } - _ContextErrorMessage(context: KPtr): KPtr { - throw new Error('Not implemented'); - } - - _AstNodeDumpModifiers(context: KPtr, node: KPtr): KPtr { - throw new Error('Not implemented'); - } - _CreateAstDumper(context: KPtr, node: KPtr, source: String): KPtr { - throw new Error('Not implemented'); - } - - _CreateConfig(argc: number, argv: string[] | Uint8Array, pandaLibPath: KStringPtr): KPtr { - throw new Error('Not implemented'); - } - _DestroyConfig(config: KPtr): void { - throw new Error('Not implemented'); - } - _CreateContextFromString(config: KPtr, source: String, filename: String): KPtr { - throw new Error('Not implemented'); - } - _GenerateTsDeclarationsFromContext( - config: KPtr, - outputDeclEts: String, - outputEts: String, - exportAll: KBoolean - ): KPtr { - throw new Error('Not implemented'); - } - _CreateContextFromFile(config: KPtr, filename: String): KPtr { - throw new Error('Not implemented'); - } - _DestroyContext(context: KPtr): void { - throw new Error('Not implemented'); - } - _ProceedToState(context: KPtr, state: number): void { - throw new Error('Not implemented'); - } - _ContextProgram(context: KPtr): KPtr { - throw new Error('Not implemented'); - } - _ProgramAst(program: KPtr): KPtr { - throw new Error('Not implemented'); - } - _CheckerStartChecker(context: KPtr): KBoolean { - throw new Error('Not implemented'); - } - - _IsProgram(context: KPtr, node: KPtr): KBoolean { - throw new Error('Not implemented'); - } - _AstNodeDumpJsonConst(context: KPtr, node: KPtr): KPtr { - throw new Error('Not implemented'); - } - _AstNodeDumpEtsSrcConst(context: KPtr, node: KPtr): KPtr { - throw new Error('Not implemented'); - } - _AstNodeUpdateChildren(context: KPtr, node: KPtr): void { - throw new Error('Not implemented'); - } - _AstNodeUpdateAll(context: KPtr, node: KPtr): void { - throw new Error('Not implemented'); - } - _AstNodeSetOriginalNode(context: KPtr, ast: KPtr, originalNode: KPtr): void { - throw new Error('Not implemented'); - } - _AstNodeOriginalNodeConst(context: KPtr, ast: KPtr): KPtr { - throw new Error('Not implemented'); - } - - _VarBinderSetProgram(context: KPtr): void { - throw new Error('Not implemented'); - } - _VarBinderSetContext(context: KPtr): void { - throw new Error('Not implemented'); - } - - _getCurrentTokenValue(context: KNativePointer, position: KInt): KPtr { - throw new Error('Not implemented'); - } - - _getSemanticDiagnostics(context: KNativePointer): KPtr { - throw new Error('Not implemented'); - } - - _getSyntacticDiagnostics(context: KNativePointer): KPtr { - throw new Error('Not implemented'); - } - - _getDiags(ptr: KNativePointer): KPtr { - throw new Error('Not implemented'); - } - - _getDiagMsg(ptr: KNativePointer): KPtr { - throw new Error('Not implemented'); - } - - _getDiagSource(ptr: KNativePointer): KPtr { - throw new Error('Not implemented'); - } - - _getDefinitionAtPosition(context: KNativePointer, position: KInt): KPtr { - throw new Error('Not implemented'); - } - - _getFileNameFromDef(ptr: KNativePointer): KPtr { - throw new Error('Not implemented'); - } - - _getStartFromDef(ptr: KPtr): KInt { - throw new Error('Not implemented'); - } - - _getLengthFromDef(ptr: KPtr): KInt { - throw new Error('Not implemented'); - } - - _getDiagRange(ptr: KPtr): KPtr { - throw new Error('Not implemented'); - } - - _getRangeEnd(ptr: KPtr): KPtr { - throw new Error('Not implemented'); - } - - _getRangeStart(ptr: KPtr): KPtr { - throw new Error('Not implemented'); - } - _getPosLine(ptr: KPtr): KInt { - throw new Error('Not implemented'); - } - - _getPosChar(ptr: KPtr): KInt { - throw new Error('Not implemented'); - } - - _getDiagSeverity(ptr: KPtr): KInt { - throw new Error('Not implemented'); - } - - _getDiagCode(ptr: KPtr): KPtr { - throw new Error('Not implemented'); - } - - _getDiagCodeDescription(ptr: KPtr): KPtr { - throw new Error('Not implemented'); - } - - _getCodeDescriptionHref(ptr: KPtr): KPtr { - throw new Error('Not implemented'); - } - - _getDiagTags(ptr: KPtr): KPtr { - throw new Error('Not implemented'); - } - - _getDiagData(ptr: KPtr): KPtr { - throw new Error('Not implemented'); - } - - _getDiagRelatedInfo(ptr: KPtr): KPtr { - throw new Error('Not implemented'); - } - - _getRelatedInfoMsg(ptr: KPtr): KPtr { - throw new Error('Not implemented'); - } - - _getRelatedInfoLoc(ptr: KPtr): KPtr { - throw new Error('Not implemented'); - } - - _getLocUri(ptr: KPtr): KPtr { - throw new Error('Not implemented'); - } - - _getLocRange(ptr: KPtr): KPtr { - throw new Error('Not implemented'); - } - - _getImplementationAtPosition(context: KNativePointer, position: KInt): KPtr { - throw new Error('Not implemented'); - } - - _getReferenceStart(ptr: KPtr): KInt { - throw new Error('Not implemented'); - } - - _getReferenceLength(ptr: KPtr): KInt { - throw new Error('Not implemented'); - } - - _getReferenceFileName(ptr: KNativePointer): KPtr { - throw new Error('Not implemented'); - } - - _getReferencesFromRefs(ptr: KNativePointer): KPtr[] { - throw new Error('Not implemented'); - } - - _getReferenceInfos(ptr: KNativePointer): KPtr { - throw new Error('Not implemented'); - } - - _getDeclInfo(context: KNativePointer, position: KInt): KPtr { - throw new Error('Not implemented'); - } - - _getDeclInfoFileText(declInfo: KNativePointer): KPtr { - throw new Error('Not implemented'); - } - - _getDeclInfoFileName(declInfo: KNativePointer): KPtr { - throw new Error('Not implemented'); - } - - _getReferencesAtPosition(context: KNativePointer, declInfo: KNativePointer): KPtr { - throw new Error('Not implemented'); - } - - _isPackageModule(context: KNativePointer): boolean { - throw new Error('Not implemented'); - } - - _getFileReferences(filename: String, context: KNativePointer, isPackageModule: boolean): KPtr { - throw new Error('Not implemented'); - } - - _getSpanOfEnclosingComment(filename: String, position: KInt): KPtr { - throw new Error('Not implemented'); - } - - _getSuggestionDiagnostics(context: KNativePointer): KPtr { - throw new Error('Not implemented'); - } - - _getQuickInfoAtPosition(filename: String, context: KNativePointer, position: KInt): KPtr { - throw new Error('Not implemented'); - } - - _getDisplayPartsText(ptr: KNativePointer): KPtr { - throw new Error('Not implemented'); - } - - _getDisplayPartsKind(ptr: KNativePointer): KPtr { - throw new Error('Not implemented'); - } - - _getQuickInfoKind(ptr: KNativePointer): KPtr { - throw new Error('Not implemented'); - } - - _getQuickInfoKindModifier(ptr: KNativePointer): KPtr { - throw new Error('Not implemented'); - } - - _getQuickInfoFileName(ptr: KNativePointer): KPtr { - throw new Error('Not implemented'); - } - - _getSymbolDisplayPart(ptr: KNativePointer): KPtr { - throw new Error('Not implemented'); - } - - _getTextSpanStart(ptr: KNativePointer): KInt { - throw new Error('Not implemented'); - } - - _getTextSpanLength(ptr: KNativePointer): KInt { - throw new Error('Not implemented'); - } - - _getTextSpan(ptr: KNativePointer): KPtr { - throw new Error('Not implemented'); - } - - _getHighlightTextSpan(ptr: KNativePointer): KPtr { - throw new Error('Not implemented'); - } - - _getHighlightContextSpan(ptr: KNativePointer): KPtr { - throw new Error('Not implemented'); - } - - _getHighlightFileName(ptr: KNativePointer): KPtr { - throw new Error('Not implemented'); - } - - _getHighlightIsInString(ptr: KNativePointer): boolean { - throw new Error('Not implemented'); - } - - _getHighlightKind(ptr: KPtr): KInt { - throw new Error('Not implemented'); - } - - _getHighlightSpanFromHighlights(ptr: KNativePointer): KPtr { - throw new Error('Not implemented'); - } - - _getDocumentHighlightsFromRef(ptr: KNativePointer): KPtr { - throw new Error('Not implemented'); - } - - _getDocumentHighlights(context: KNativePointer, position: KInt): KPtr { - throw new Error('Not implemented'); - } - - _getCompletionAtPosition(context: KNativePointer, position: KInt): KPtr { - throw new Error('Not implemented'); - } - - _getFileNameFromEntryData(ptr: KNativePointer): KPtr { - throw new Error('Not implemented'); - } - - _getNamedExportFromEntryData(ptr: KNativePointer): KPtr { - throw new Error('Not implemented'); - } - - _getImportDeclarationFromEntryData(ptr: KNativePointer): KPtr { - throw new Error('Not implemented'); - } - - _getStatusFromEntryData(ptr: KPtr): KInt { - throw new Error('Not implemented'); - } - - _getNameFromEntry(ptr: KNativePointer): KPtr { - throw new Error('Not implemented'); - } - - _getSortTextFromEntry(ptr: KNativePointer): KPtr { - throw new Error('Not implemented'); - } - - _getInsertTextFromEntry(ptr: KNativePointer): KPtr { - throw new Error('Not implemented'); - } - - _getKindFromEntry(ptr: KPtr): KInt { - throw new Error('Not implemented'); - } - - _getDataFromEntry(ptr: KNativePointer): KPtr { - throw new Error('Not implemented'); - } - - _getEntriesFromCompletionInfo(ptr: KNativePointer): KPtr { - throw new Error('Not implemented'); - } - - _getUriFromLocation(ptr: KNativePointer): KPtr { - throw new Error('Not implemented'); - } - - _getStartFromLocation(ptr: KNativePointer): KInt { - throw new Error('Not implemented'); - } - - _getEndFromLocation(ptr: KNativePointer): KInt { - throw new Error('Not implemented'); - } - - _getIsDefinitionFromLocation(ptr: KNativePointer): boolean { - throw new Error('Not implemented'); - } - - _getIsImportFromLocation(ptr: KNativePointer): boolean { - throw new Error('Not implemented'); - } - - _getAccessKindFromLocation(ptr: KPtr): KInt { - throw new Error('Not implemented'); - } - - _getLocationFromList(ptr: KNativePointer): KPtr { - throw new Error('Not implemented'); - } - - _getLine(ptr: KNativePointer): KInt { - throw new Error('Not implemented'); - } - - _getChar(ptr: KNativePointer): KInt { - throw new Error('Not implemented'); - } - - _toLineColumnOffset(context: KNativePointer, position: KInt): KPtr { - throw new Error('Not implemented'); - } -} - -export function initEs2panda(): Es2pandaNativeModule { - let libPath = process.env.BINDINGS_PATH; - if (libPath === undefined) { - libPath = path.resolve(__dirname, '../ts_bindings.node'); - } else { - libPath = path.join(libPath, 'ts_bindings.node'); - } - if (!fs.existsSync(libPath)) { - throwError(`Cannot find lib path ${libPath}`); - } - registerNativeModuleLibraryName('NativeModule', libPath); - const instance = new Es2pandaNativeModule(); - loadNativeModuleLibrary('NativeModule', instance); - return instance; -} - -export function initGeneratedEs2panda(): GeneratedEs2pandaNativeModule { - let libPath = process.env.BINDINGS_PATH; - if (libPath === undefined) { - libPath = path.resolve(__dirname, '../ts_bindings.node'); - } else { - libPath = path.join(libPath, 'ts_bindings.node'); - } - if (!fs.existsSync(libPath)) { - throwError(`Cannot find lib path ${libPath}`); - } - registerNativeModuleLibraryName('NativeModule', libPath); - const instance = new GeneratedEs2pandaNativeModule(); - loadNativeModuleLibrary('NativeModule', instance); - return instance; -} - -export function initPublicEs2panda(): Es2pandaNativeModule { - let libPath = process.env.BINDINGS_PATH; - if (libPath === undefined) { - libPath = path.resolve(__dirname, '../public.node'); - } else { - libPath = path.join(libPath, 'public.node'); - } - if (!fs.existsSync(libPath)) { - throwError(`Cannot find lib path ${libPath}`); - } - registerNativeModuleLibraryName('NativeModule', libPath); - const instance = new Es2pandaNativeModule(); - loadNativeModuleLibrary('NativeModule', instance); - return instance; -} - -export function initPublicGeneratedEs2panda(): GeneratedEs2pandaNativeModule { - let libPath = process.env.BINDINGS_PATH; - if (libPath === undefined) { - libPath = path.resolve(__dirname, '../public.node'); - } else { - libPath = path.join(libPath, 'public.node'); - } - if (!fs.existsSync(libPath)) { - throwError(`Cannot find lib path ${libPath}`); - } - registerNativeModuleLibraryName('NativeModule', libPath); - const instance = new GeneratedEs2pandaNativeModule(); - loadNativeModuleLibrary('NativeModule', instance); - return instance; -} diff --git a/ets2panda/bindings/src/InteropNativeModule.ts b/ets2panda/bindings/src/InteropNativeModule.ts deleted file mode 100644 index 35eac9b806..0000000000 --- a/ets2panda/bindings/src/InteropNativeModule.ts +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as fs from 'fs'; -import * as path from 'path'; -import { KNativePointer as KPtr, KInt, KUInt } from './InteropTypes'; -import { loadNativeModuleLibrary, registerNativeModuleLibraryName } from './loadLibraries'; -import { throwError } from './utils'; - -export class InteropNativeModule { - _StringLength(ptr: KPtr): KInt { - throw new Error('Not implemented'); - } - - _StringData(ptr: KPtr, buffer: KPtr, length: KInt): void { - throw new Error('Not implemented'); - } - - _GetStringFinalizer(): KPtr { - throw new Error('Not implemented'); - } - - _InvokeFinalizer(ptr: KPtr, finalizer: KPtr): void { - throw new Error('Not implemented'); - } - - _GetPtrVectorSize(ptr: KPtr): KInt { - throw new Error('Not implemented'); - } - - _GetPtrVectorElement(ptr: KPtr, index: KInt): KPtr { - throw new Error('Not implemented'); - } - - _getTypeOfVariant(ptr: KPtr): KInt { - throw new Error('Not implemented'); - } - - _getIntFromVariant(ptr: KPtr): KInt { - throw new Error('Not implemented'); - } - - _getStringFromVariant(ptr: KPtr): KPtr { - throw new Error('Not implemented'); - } -} - -export function initInterop(): InteropNativeModule { - let libPath = process.env.BINDINGS_PATH; - if (libPath === undefined) { - libPath = path.resolve(__dirname, '../ts_bindings.node'); - } else { - libPath = path.join(libPath, 'ts_bindings.node'); - } - if (!fs.existsSync(libPath)) { - throwError(`Cannot find lib path ${libPath}`); - } - registerNativeModuleLibraryName('InteropNativeModule', libPath); - const instance = new InteropNativeModule(); - loadNativeModuleLibrary('InteropNativeModule', instance); - return instance; -} - -export function initPublicInterop(): InteropNativeModule { - let libPath = process.env.BINDINGS_PATH; - if (libPath === undefined) { - libPath = path.resolve(__dirname, '../public.node'); - } else { - libPath = path.join(libPath, 'public.node'); - } - if (!fs.existsSync(libPath)) { - throwError(`Cannot find lib path ${libPath}`); - } - registerNativeModuleLibraryName('InteropNativeModule', libPath); - const instance = new InteropNativeModule(); - loadNativeModuleLibrary('InteropNativeModule', instance); - return instance; -} diff --git a/ets2panda/bindings/src/InteropTypes.ts b/ets2panda/bindings/src/InteropTypes.ts deleted file mode 100644 index 4a3a3d8678..0000000000 --- a/ets2panda/bindings/src/InteropTypes.ts +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -export const nullptr: int | bigint = BigInt(0); -export type int = number; -export type int32 = int; -export type int64 = int; -export type float = number; -export type float32 = float; -export type float64 = float; - -export type KStringPtr = int32 | string | null; -export type KStringArrayPtr = int32 | Uint8Array | null; -export type KInt32ArrayPtr = int32 | Int32Array | null; -export type KFloat32ArrayPtr = int32 | Float32Array | null; -export type KUint8ArrayPtr = int32 | Uint8Array | null; -export type KInt = int32; -export type KUInt = int32; -export type KLong = int64; -export type KFloat = float32; -export type KDouble = float64; -export type KBoolean = int32; -export type KPointer = Uint8Array | number | bigint; -export type pointer = KPointer; -export type KNativePointer = KPointer; -export type KNativePointerArray = BigUint64Array; diff --git a/ets2panda/bindings/src/arktsConfigGenerate.ts b/ets2panda/bindings/src/arktsConfigGenerate.ts deleted file mode 100644 index 56f00052ed..0000000000 --- a/ets2panda/bindings/src/arktsConfigGenerate.ts +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { BuildMode } from './build/buildMode'; -import { BuildConfig } from './types'; -import { ModuleDescriptor, generateBuildConfigs } from './buildConfigGenerate'; -import { PANDA_SDK_PATH_FROM_SDK } from './preDefine'; - -import * as fs from 'fs'; -import * as path from 'path'; -import { PluginDriver } from './ui_plugins_driver'; - -function processBuildConfig(projectConfig: BuildConfig): BuildConfig { - let buildConfig: BuildConfig = { ...projectConfig }; - let buildSdkPath: string = buildConfig.buildSdkPath as string; - buildConfig.pandaSdkPath = buildConfig.pandaSdkPath ?? path.resolve(buildSdkPath, PANDA_SDK_PATH_FROM_SDK); - PluginDriver.getInstance().initPlugins(buildConfig); - return buildConfig; -} - -export function generateArkTsConfigByModules( - buildSdkPath: string, - projectRoot: string, - modules?: ModuleDescriptor[] -): void { - const allBuildConfig = generateBuildConfigs(buildSdkPath, projectRoot, modules); - let compileFileInfos: Record = {}; - const cacheDir = path.join(projectRoot, '.idea', '.deveco'); - const compileFileInfosPath = path.join(cacheDir, 'lsp_compileFileInfos.json'); - Object.keys(allBuildConfig).forEach((moduleName) => { - const moduleConfig = allBuildConfig[moduleName] as BuildConfig; - const processedConfig = processBuildConfig(moduleConfig); - - const buildMode = new BuildMode(processedConfig); - buildMode.generateArkTSConfig(compileFileInfos); - }); - try { - const jsonCompileFileInfos = JSON.stringify(compileFileInfos, null, 2); - if (!fs.existsSync(cacheDir)) { - fs.mkdirSync(cacheDir, { recursive: true }); - } - fs.writeFileSync(compileFileInfosPath, jsonCompileFileInfos, 'utf-8'); - } catch (err) { - console.error(`Failed to write compileFileInfos to ${compileFileInfosPath} with error: ${err}`); - } -} diff --git a/ets2panda/bindings/src/arrays.ts b/ets2panda/bindings/src/arrays.ts deleted file mode 100644 index d0fe749945..0000000000 --- a/ets2panda/bindings/src/arrays.ts +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { KPointer, int32 } from './InteropTypes'; -import { Wrapper } from './mainWrapper'; -import { CustomTextDecoder, CustomTextEncoder } from './strings'; -import { throwError } from './utils'; - -const encoder = new CustomTextEncoder(); -const decoder = new CustomTextDecoder(); - -export function decodeToString(array: Uint8Array): string { - return decoder.decode(array); -} - -export function encodeToData(string: string): Uint8Array { - return encoder.encode(string, false); -} - -export function withString(data: string, exec: Exec): R { - return exec(data); -} - -export function withStringArray(strings: Array | undefined): Uint8Array { - if (strings === undefined || strings.length === 0) { - throwError('Error in strings array'); - } - - let array = encoder.encodeArray(strings); - return array; -} - -function withArray(data: C | undefined, exec: ExecWithLength): R { - return exec(data ?? null, data?.length ?? 0); -} - -export function withPtrArray( - data: BigUint64Array, - access: Access, - exec: ExecWithLength -): R { - return exec(data ?? null, data?.length ?? 0); // TODO rethink -} - -export function toPtrArray(data: Array | undefined): BigUint64Array { - if (data === undefined || data.length === 0) { - return new BigUint64Array(0); - } - const array = new BigUint64Array(data.length); - for (let i = 0; i < data.length; i++) { - let item = data[i]; - array[i] = item !== undefined ? (item.ptr as bigint) : nullptr; - } - return array; -} - -export function fromPtrArray(array: PtrArray, factory: (ptr: KPointer) => T): Array { - if (array.length === 0) { - return new Array(0); - } - const result = new Array(array.length); - for (let i = 0; i < array.length; i++) { - let ptr = array[i]; - if (ptr === nullptr) { - result[i] = undefined; - } else { - result[i] = factory(ptr); - } - } - return result; -} - -export function withUint8Array( - data: Uint8Array | undefined, - access: Access, - exec: ExecWithLength -): T { - return withArray(data, exec); -} -export function withInt8Array( - data: Int8Array | undefined, - access: Access, - exec: ExecWithLength -): T { - return withArray(data, exec); -} -export function withUint16Array( - data: Uint16Array | undefined, - access: Access, - exec: ExecWithLength -): T { - return withArray(data, exec); -} -export function withInt16Array( - data: Int16Array | undefined, - access: Access, - exec: ExecWithLength -): T { - return withArray(data, exec); -} -export function withUint32Array( - data: Uint32Array | undefined, - access: Access, - exec: ExecWithLength -): T { - return withArray(data, exec); -} -export function withInt32Array( - data: Int32Array | undefined, - access: Access, - exec: ExecWithLength -): T { - return withArray(data, exec); -} -export function withFloat32Array( - data: Float32Array | undefined, - access: Access, - exec: ExecWithLength -): T { - return withArray(data, exec); -} -export function withFloat64Array( - data: Float64Array | undefined, - access: Access, - exec: ExecWithLength -): T { - return withArray(data, exec); -} -export function wasmHeap(): ArrayBuffer { - throw new Error('Unused'); -} - -export enum Access { - READ = 1, // 1 << 0, - WRITE = 2, // 1 << 1, - READWRITE = 3 // READ | WRITE -} -export function isRead(access: Access): boolean { - return !!(access & Access.READ); -} -export function isWrite(access: Access): boolean { - return !!(access & Access.WRITE); -} - -export type Exec = (pointer: P) => R; -export type ExecWithLength = (pointer: P, length: int32) => R; - -export type TypedArray = - | Uint8Array - | Int8Array - | Uint16Array - | Int16Array - | Uint32Array - | Int32Array - | Float32Array - | Float64Array; - -export const nullptr: bigint = BigInt(0); -export type PtrArray = Uint32Array | BigUint64Array; diff --git a/ets2panda/bindings/src/build/buildMode.ts b/ets2panda/bindings/src/build/buildMode.ts deleted file mode 100644 index d1be834b99..0000000000 --- a/ets2panda/bindings/src/build/buildMode.ts +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; - -import { ABC_SUFFIX, ARKTSCONFIG_JSON_FILE, LANGUAGE_VERSION } from '../preDefine'; -import { changeFileExtension } from '../utils'; -import { BuildConfig, DependentModuleConfig, ModuleInfo, CompileFileInfo } from '../types'; -import { ArkTSConfigGenerator } from './generateArkTSConfig'; - -export class BuildMode { - buildConfig: BuildConfig; - entryFiles: Set; - compileFiles: Map; - cacheDir: string; - pandaSdkPath: string; - buildSdkPath: string; - packageName: string; - sourceRoots: string[]; - moduleRootPath: string; - moduleType: string; - dependentModuleList: DependentModuleConfig[]; - moduleInfos: Map; - declgenV1OutPath: string | undefined; - declgenBridgeCodePath: string | undefined; - hasMainModule: boolean; - - constructor(buildConfig: BuildConfig) { - this.buildConfig = buildConfig; - this.entryFiles = new Set(buildConfig.compileFiles as string[]); - this.cacheDir = buildConfig.cachePath as string; - this.pandaSdkPath = buildConfig.pandaSdkPath as string; - this.buildSdkPath = buildConfig.buildSdkPath as string; - this.packageName = buildConfig.packageName as string; - this.sourceRoots = buildConfig.sourceRoots as string[]; - this.moduleRootPath = buildConfig.moduleRootPath as string; - this.moduleType = buildConfig.moduleType as string; - this.dependentModuleList = buildConfig.dependentModuleList; - this.hasMainModule = buildConfig.hasMainModule; - - this.declgenV1OutPath = buildConfig.declgenV1OutPath as string | undefined; - this.declgenBridgeCodePath = buildConfig.declgenBridgeCodePath as string | undefined; - - this.moduleInfos = new Map(); - this.compileFiles = new Map(); - } - - private getDependentModules(moduleInfo: ModuleInfo): Map[] { - let dynamicDepModules: Map = new Map(); - let staticDepModules: Map = new Map(); - - if (moduleInfo.isMainModule) { - this.moduleInfos.forEach((module: ModuleInfo, packageName: string) => { - if (module.isMainModule) { - return; - } - module.language === LANGUAGE_VERSION.ARKTS_1_2 - ? staticDepModules.set(packageName, module) - : dynamicDepModules.set(packageName, module); - }); - return [dynamicDepModules, staticDepModules]; - } - - if (moduleInfo.dependencies) { - moduleInfo.dependencies.forEach((packageName: string) => { - let depModuleInfo: ModuleInfo | undefined = this.moduleInfos.get(packageName); - if (!depModuleInfo) { - console.error(`Module ${packageName} not found in moduleInfos`); - } else { - depModuleInfo.language === LANGUAGE_VERSION.ARKTS_1_2 - ? staticDepModules.set(packageName, depModuleInfo) - : dynamicDepModules.set(packageName, depModuleInfo); - } - }); - } - return [dynamicDepModules, staticDepModules]; - } - - private generateArkTSConfigForModules(compileFileInfos: Record): void { - let generator = ArkTSConfigGenerator.getGenerator(this.buildConfig, this.moduleInfos); - this.moduleInfos.forEach((moduleInfo: ModuleInfo, moduleRootPath: string) => { - for (const fileInfo of moduleInfo.compileFileInfos) { - compileFileInfos[fileInfo.filePath] = fileInfo.arktsConfigFile; - } - generator.writeArkTSConfigFile(moduleInfo); - }); - } - - private collectDepModuleInfos(): void { - this.moduleInfos.forEach((moduleInfo) => { - let [dynamicDepModules, staticDepModules] = this.getDependentModules(moduleInfo); - moduleInfo.dynamicDepModuleInfos = dynamicDepModules; - moduleInfo.staticDepModuleInfos = staticDepModules; - }); - } - - private collectModuleInfos(): void { - if (this.hasMainModule && (!this.packageName || !this.moduleRootPath || !this.sourceRoots)) { - console.error('Main module info from hvigor is not correct.'); - } - let mainModuleInfo: ModuleInfo = { - isMainModule: this.hasMainModule, - packageName: this.packageName, - moduleRootPath: this.moduleRootPath, - moduleType: this.moduleType, - sourceRoots: this.sourceRoots, - entryFile: '', - arktsConfigFile: path.resolve(this.cacheDir, this.packageName, ARKTSCONFIG_JSON_FILE), - dynamicDepModuleInfos: new Map(), - staticDepModuleInfos: new Map(), - compileFileInfos: [], - declgenV1OutPath: this.declgenV1OutPath, - declgenBridgeCodePath: this.declgenBridgeCodePath - }; - this.moduleInfos.set(this.packageName, mainModuleInfo); - this.dependentModuleList.forEach((module: DependentModuleConfig) => { - if (!module.packageName || !module.modulePath || !module.sourceRoots || !module.entryFile) { - console.error('Dependent module info from hvigor is not correct.'); - } - let moduleInfo: ModuleInfo = { - isMainModule: false, - packageName: module.packageName, - moduleRootPath: module.modulePath, - moduleType: module.moduleType, - sourceRoots: module.sourceRoots, - entryFile: module.entryFile, - arktsConfigFile: path.resolve(this.cacheDir, module.packageName, ARKTSCONFIG_JSON_FILE), - compileFileInfos: [], - dynamicDepModuleInfos: new Map(), - staticDepModuleInfos: new Map(), - declgenV1OutPath: undefined, - declgenBridgeCodePath: undefined, - language: module.language, - declFilesPath: module.declFilesPath, - dependencies: module.dependencies - }; - this.moduleInfos.set(module.packageName, moduleInfo); - }); - this.collectDepModuleInfos(); - } - - private collectCompileFiles(): void { - this.entryFiles.forEach((file: string) => { - for (const [packageName, moduleInfo] of this.moduleInfos) { - if (!file.startsWith(moduleInfo.moduleRootPath)) { - continue; - } - let filePathFromModuleRoot: string = path.relative(moduleInfo.moduleRootPath, file); - let filePathInCache: string = path.join(this.cacheDir, moduleInfo.packageName, filePathFromModuleRoot); - let abcFilePath: string = path.resolve(changeFileExtension(filePathInCache, ABC_SUFFIX)); - - let fileInfo: CompileFileInfo = { - filePath: file, - dependentFiles: [], - abcFilePath: abcFilePath, - arktsConfigFile: moduleInfo.arktsConfigFile, - packageName: moduleInfo.packageName - }; - moduleInfo.compileFileInfos.push(fileInfo); - this.compileFiles.set(file, fileInfo); - return; - } - console.error('File does not belong to any module in moduleInfos.'); - }); - } - - public generateModuleInfos(): void { - this.collectModuleInfos(); - this.collectCompileFiles(); - } - - public async generateArkTSConfig(compileFileInfos: Record): Promise { - this.generateModuleInfos(); - this.generateArkTSConfigForModules(compileFileInfos); - } -} diff --git a/ets2panda/bindings/src/buildConfigGenerate.ts b/ets2panda/bindings/src/buildConfigGenerate.ts deleted file mode 100644 index 4d1b1c34d1..0000000000 --- a/ets2panda/bindings/src/buildConfigGenerate.ts +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as fs from 'fs'; -import * as path from 'path'; -import * as JSON5 from 'json5'; -import { BuildConfig } from './types'; - -export interface ModuleDescriptor { - arktsversion: string; - name: string; - moduleType: string; - srcPath: string; -} - -interface Json5Object { - module?: { - type?: string; - }; - modules?: Array<{ - name: string; - srcPath: string; - arktsversion?: string; - }>; - dependencies?: { - [packageName: string]: string; - }; -} - -function removeTrailingCommas(jsonString: string): string { - return jsonString.replace(/,\s*([}\]])/g, '$1'); -} - -function parseJson5(filePath: string): Json5Object { - try { - const rawContent = fs.readFileSync(filePath, 'utf8'); - const cleanedContent = removeTrailingCommas(rawContent); - return JSON5.parse(cleanedContent) as Json5Object; - } catch (error) { - console.error(`Error parsing ${filePath}:`, error); - return {} as Json5Object; - } -} - -function getModuleTypeFromConfig(modulePath: string): string { - const moduleConfigPath = path.join(modulePath, 'src/main/module.json5'); - if (fs.existsSync(moduleConfigPath)) { - try { - const moduleData = parseJson5(moduleConfigPath); - return moduleData.module?.type || 'har'; - } catch (error) { - console.error(`Error parsing ${moduleConfigPath}:`, error); - } - } - return 'har'; -} - -function getModulesFromBuildProfile(buildProfilePath: string): ModuleDescriptor[] { - if (!fs.existsSync(buildProfilePath)) { - console.error('Error: build-profile.json5 not found'); - process.exit(1); - } - - const buildProfile = parseJson5(buildProfilePath); - const modules = buildProfile.modules || []; - - return modules.map((module: { name: string; srcPath: string; arktsversion?: string }) => { - const moduleSrcPath = path.resolve(path.dirname(buildProfilePath), module.srcPath); - const arktsversion = module.arktsversion || '1.1'; - return { - name: module.name, - moduleType: getModuleTypeFromConfig(moduleSrcPath), - srcPath: moduleSrcPath, - arktsversion - }; - }); -} - -function getEtsFiles(modulePath: string): string[] { - const files: string[] = []; - - const shouldSkipDirectory = (relativePath: string): boolean => { - const testDir1 = `src${path.sep}test`; - const testDir2 = `src${path.sep}ohosTest`; - return relativePath.startsWith(testDir1) || relativePath.startsWith(testDir2); - }; - - const processEntry = (dir: string, entry: fs.Dirent): void => { - const fullPath = path.join(dir, entry.name); - const relativePath = path.relative(modulePath, fullPath); - - if (entry.isDirectory()) { - if (shouldSkipDirectory(relativePath)) { - return; - } - traverseDir(fullPath); - return; - } - - if (entry.isFile() && entry.name.endsWith('.ets')) { - files.push(fullPath); - } - }; - - const traverseDir = (dir: string): void => { - if (!fs.existsSync(dir)) { - return; - } - - const entries = fs.readdirSync(dir, { withFileTypes: true }); - entries.forEach((entry) => processEntry(dir, entry)); - }; - - traverseDir(modulePath); - return files; -} - -function getModuleDependencies(modulePath: string, visited = new Set()): string[] { - if (visited.has(modulePath)) { - return []; - } - visited.add(modulePath); - - const extractDependencies = (): string[] => { - const packageFilePath = path.join(modulePath, 'oh-package.json5'); - if (!fs.existsSync(packageFilePath)) { - return []; - } - - try { - const packageData = parseJson5(packageFilePath); - return Object.entries(packageData.dependencies || {}) - .map(([_, depPath]) => (depPath as string).replace('file:', '')) - .map((depPath) => path.resolve(modulePath, depPath)); - } catch (error) { - console.error(`Error parsing ${packageFilePath}:`, error); - return []; - } - }; - - const resolveNestedDependencies = (deps: string[]): string[] => { - return deps.flatMap((depPath) => - visited.has(depPath) ? [] : [depPath, ...getModuleDependencies(depPath, visited)] - ); - }; - - const dependencies = extractDependencies(); - const nestedDependencies = resolveNestedDependencies(dependencies); - return Array.from(new Set([...dependencies, ...nestedDependencies])); -} - -export function generateBuildConfigs( - buildSdkPath: string, - projectRoot: string, - modules?: ModuleDescriptor[] -): Record { - const allBuildConfigs: Record = {}; - - if (!modules) { - const buildProfilePath = path.join(projectRoot, 'build-profile.json5'); - modules = getModulesFromBuildProfile(buildProfilePath); - } - - const definedModules = modules; - const cacheDir = path.join(projectRoot, '.idea', '.deveco'); - - for (const module of definedModules) { - const modulePath = module.srcPath; - const compileFiles = new Set(getEtsFiles(modulePath)); - - // Get recursive dependencies - const dependencies = getModuleDependencies(modulePath); - for (const depPath of dependencies) { - getEtsFiles(depPath).forEach((file) => compileFiles.add(file)); - } - - allBuildConfigs[module.name] = { - plugins: { - 'ui-plugins': path.join(buildSdkPath, 'build-tools', 'ui-plugins', 'lib', 'ui-plugins', 'index'), - 'memo-plugin': path.join(buildSdkPath, 'build-tools', 'ui-plugins', 'lib', 'memo-plugins', 'index') - }, - arkts: {}, - arktsGlobal: {}, - compileFiles: Array.from(compileFiles), - packageName: module.name, - moduleType: module.moduleType, - buildType: 'build', - buildMode: 'Debug', - moduleRootPath: modulePath, - sourceRoots: ['./'], - hasMainModule: true, - loaderOutPath: path.join(modulePath, 'build', 'default', 'cache'), - cachePath: cacheDir, - buildSdkPath: buildSdkPath, - enableDeclgenEts2Ts: false, - declgenDtsOutPath: path.join(modulePath, 'build', 'default', 'cache'), - declgenTsOutPath: path.join(modulePath, 'build', 'default', 'cache'), - dependentModuleList: dependencies.map((dep) => { - const depModule = definedModules.find((m) => m.srcPath === dep); - return { - packageName: path.basename(dep), - moduleName: path.basename(dep), - moduleType: depModule ? depModule.moduleType : 'har', - modulePath: dep, - sourceRoots: ['./'], - entryFile: 'index.ets', - language: depModule ? depModule.arktsversion : '1.1' - }; - }) - }; - } - const outputPath = path.join(cacheDir, 'lsp_build_config.json'); - if (!fs.existsSync(cacheDir)) { - fs.mkdirSync(cacheDir, { recursive: true }); - } - fs.writeFileSync(outputPath, JSON.stringify(allBuildConfigs, null, 4)); - return allBuildConfigs; -} diff --git a/ets2panda/bindings/src/driver_helper.ts b/ets2panda/bindings/src/driver_helper.ts deleted file mode 100644 index 29f82f3d01..0000000000 --- a/ets2panda/bindings/src/driver_helper.ts +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Context, Config } from './types'; -import { global } from './global'; -import { throwError } from './utils'; -import { Es2pandaContextState } from './generated/Es2pandaEnums'; -import { withStringResult } from './Platform'; -import { KBoolean, KNativePointer, KPointer } from './InteropTypes'; - -export class DriverHelper { - constructor(filePath: string, cmd: string[]) { - this._filePath = filePath; - global.filePath = this._filePath; - this._cfg = Config.create(cmd, filePath); - } - private _ctx: Context | undefined; - private _cfg: Config; - private _filePath: string; - - public createCtx(source: string): KPointer { - this._ctx = Context.createFromString(source); - return this._ctx.peer; - } - - public toString(): string { - return `DriverHelper (filepath = ${this._filePath}, config = ${this._cfg}, context = ${this._ctx})`; - } - - public proceedToState(state: Es2pandaContextState): void { - if (this._ctx === undefined) { - throwError('Trying to proceed to state while cts is undefined'); - } - if (state <= global.es2panda._ContextState(this._ctx.peer)) { - return; - } - - try { - global.es2panda._ProceedToState(this._ctx.peer, state); - if (global.es2panda._ContextState(this._ctx.peer) === Es2pandaContextState.ES2PANDA_STATE_ERROR) { - const errMsg = withStringResult(global.es2panda._ContextErrorMessage(this._ctx.peer)); - if (errMsg === undefined) { - throwError(`Couldn't get context error msg`); - } else { - throwError('Failed proceed to: ' + Es2pandaContextState[state] + '\n' + errMsg); - } - } - } catch (e) { - global.es2panda._DestroyContext(this._ctx.peer); - throw e; - } - } - - public finalize(): void { - if (this._cfg === undefined) { - throwError('Call finalize before initialized config'); - } - if (this._ctx === undefined) { - throwError('Call finalize before initialized context'); - } - global.es2panda._DestroyContext(this._ctx.peer); - global.es2panda._DestroyConfig(this._cfg.peer); - this._ctx = undefined; - global.destroyCfg(); - } - - public generateTsDecl(declOutPath: string, etsOutPath: string, exportAll: boolean): void { - let exportAll_: KBoolean = exportAll ? 1 : 0; - global.es2panda._GenerateTsDeclarationsFromContext(this._cfg.peer, declOutPath, etsOutPath, exportAll_); - } -} - -export class LspDriverHelper { - public createCfg(cmd: string[], filePath: string, pandaLibPath: string): Config { - return Config.create(cmd, filePath, pandaLibPath, true); - } - - public createCtx(source: string, filePath: string, cfg: Config): KNativePointer { - return Context.lspCreateFromString(source, filePath, cfg); - } - - public proceedToState(ctx: KNativePointer, state: Es2pandaContextState): void { - if (ctx === undefined) { - throwError('Trying to proceed to state while cts is undefined'); - } - if (state <= global.es2pandaPublic._ContextState(ctx)) { - return; - } - - try { - global.es2pandaPublic._ProceedToState(ctx, state); - } catch (e) { - global.es2pandaPublic._DestroyContext(ctx); - throw e; - } - } - - public destroyContext(ctx: KNativePointer): void { - if (ctx === undefined) { - return; - } - global.es2pandaPublic._DestroyContext(ctx); - } - - public destroyConfig(cfg: Config): void { - if (cfg === undefined) { - return; - } - global.es2pandaPublic._DestroyConfig(cfg.peer); - } -} diff --git a/ets2panda/bindings/src/global.ts b/ets2panda/bindings/src/global.ts deleted file mode 100644 index 2c99dce5ca..0000000000 --- a/ets2panda/bindings/src/global.ts +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { throwError } from './utils'; -import { KNativePointer } from './InteropTypes'; -import { - initEs2panda, - Es2pandaNativeModule, - initGeneratedEs2panda, - initPublicEs2panda, - initPublicGeneratedEs2panda -} from './Es2pandaNativeModule'; -import { Es2pandaNativeModule as GeneratedEs2pandaNativeModule } from './generated/Es2pandaNativeModule'; -import { initInterop, InteropNativeModule, initPublicInterop } from './InteropNativeModule'; -import { Context } from './types'; - -// CC-OFFNXT(G.NAM.01) project code style -export class global { - public static filePath: string = './examples/input/main.ets'; - - private static _config?: KNativePointer; - public static set config(config: KNativePointer) { - if (global._config !== undefined) { - throwError('Global.config already initialized'); - } - global._config = config; - } - - public static get config(): KNativePointer { - return global._config ?? throwError('Global.config not initialized'); - } - - public static destroyCfg(): void { - global._config = undefined; - } - - public static configIsInitialized(): boolean { - return global._config !== undefined; - } - - private static _context?: KNativePointer; - public static set context(context: KNativePointer) { - global._context = context; - } - public static get context(): KNativePointer { - return global._context ?? throwError('Global.context not initialized'); - } - - private static _es2panda: Es2pandaNativeModule | undefined = undefined; - private static _es2pandaPublic: Es2pandaNativeModule | undefined = undefined; - public static get es2panda(): Es2pandaNativeModule { - if (this._es2panda === undefined) { - this._es2panda = initEs2panda(); - } - return this._es2panda; - } - - public static get es2pandaPublic(): Es2pandaNativeModule { - if (this._es2pandaPublic === undefined) { - this._es2pandaPublic = initPublicEs2panda(); - } - return this._es2pandaPublic; - } - - private static _generatedEs2panda: GeneratedEs2pandaNativeModule | undefined = undefined; - private static _generatedEs2pandaPublic: GeneratedEs2pandaNativeModule | undefined = undefined; - public static get generatedEs2panda(): GeneratedEs2pandaNativeModule { - if (this._generatedEs2panda === undefined) { - this._generatedEs2panda = initGeneratedEs2panda(); - } - return this._generatedEs2panda; - } - - public static get generatedEs2pandaPublic(): GeneratedEs2pandaNativeModule { - if (this._generatedEs2pandaPublic === undefined) { - this._generatedEs2pandaPublic = initPublicGeneratedEs2panda(); - } - return this._generatedEs2pandaPublic; - } - - private static _interop: InteropNativeModule | undefined = undefined; - private static _interopPublic: InteropNativeModule | undefined = undefined; - public static get interop(): InteropNativeModule { - if (this._interop === undefined) { - this._interop = initInterop(); - } - return this._interop; - } - - public static get interopPublic(): InteropNativeModule { - if (this._interopPublic === undefined) { - this._interopPublic = initPublicInterop(); - } - return this._interopPublic; - } -} diff --git a/ets2panda/bindings/src/lspNode.ts b/ets2panda/bindings/src/lspNode.ts deleted file mode 100644 index 7bb465f526..0000000000 --- a/ets2panda/bindings/src/lspNode.ts +++ /dev/null @@ -1,400 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { KBoolean, KInt, KNativePointer, KUInt } from './InteropTypes'; -import { unpackString, VariantTypes } from './private'; -import { throwError } from './utils'; -import { isNullPtr } from './Wrapper'; -import { global } from './global'; -import { NativePtrDecoder } from './Platform'; - -export abstract class LspNode { - readonly peer: KNativePointer; - - protected constructor(peer: KNativePointer) { - if (isNullPtr(peer)) { - throwError('nullptr from peer in lspnode constuctor'); - } - this.peer = peer; - } -} - -export class LspPosition extends LspNode { - readonly line: number; - readonly character: number; - constructor(peer: KNativePointer) { - super(peer); - this.line = global.es2panda._getPosLine(peer); - this.character = global.es2panda._getPosChar(peer); - } -} - -export class LspRange extends LspNode { - readonly start: LspPosition; - readonly end: LspPosition; - constructor(peer: KNativePointer) { - super(peer); - this.start = new LspPosition(global.es2panda._getRangeStart(peer)); - this.end = new LspPosition(global.es2panda._getRangeEnd(peer)); - } -} - -export enum LspDiagSeverity { - Error = 1, - Warning = 2, - Information = 3, - Hint = 4 -} - -export enum LspDiagTag { - Unnecessary = 1, - Deprecated = 2 -} - -export class LspLocation extends LspNode { - constructor(peer: KNativePointer) { - super(peer); - this.uri = unpackString(global.es2panda._getLocUri(peer)); - this.range = new LspRange(global.es2panda._getLocRange(peer)); - } - readonly uri: string; - readonly range: LspRange; -} - -export class LspRelatedInfo extends LspNode { - constructor(peer: KNativePointer) { - super(peer); - this.message = unpackString(global.es2panda._getRelatedInfoMsg(peer)); - this.location = new LspLocation(global.es2panda._getRelatedInfoLoc(peer)); - } - readonly message: string; - readonly location: LspLocation; -} - -export class LspCodeDescription extends LspNode { - constructor(peer: KNativePointer) { - super(peer); - this.href = unpackString(global.es2panda._getCodeDescriptionHref(peer)); - } - readonly href: string; -} - -export class LspDiagnosticNode extends LspNode { - constructor(peer: KNativePointer) { - super(peer); - this.message = unpackString(global.es2panda._getDiagMsg(peer)); - this.source = unpackString(global.es2panda._getDiagSource(peer)); - this.range = new LspRange(global.es2panda._getDiagRange(peer)); - this.tags = new NativePtrDecoder() - .decode(global.es2panda._getDiagTags(peer)) - .map((elPeer: KNativePointer) => elPeer as KInt); - this.relatedInfo = new NativePtrDecoder() - .decode(global.es2panda._getDiagRelatedInfo(peer)) - .map((elPeer: KNativePointer) => new LspRelatedInfo(elPeer)); - let codeVarPtr = global.es2panda._getDiagCode(peer); - if (global.interop._getTypeOfVariant(codeVarPtr) === VariantTypes.VARIANT_INT) { - this.code = global.interop._getIntFromVariant(codeVarPtr); - } else { - this.code = unpackString(global.interop._getStringFromVariant(codeVarPtr)); - } - let dataPtr = global.es2panda._getDiagData(peer); - if (global.interop._getTypeOfVariant(dataPtr) === VariantTypes.VARIANT_INT) { - this.data = global.interop._getIntFromVariant(dataPtr); - } else { - this.data = unpackString(global.interop._getStringFromVariant(dataPtr)); - } - this.severity = global.es2panda._getDiagSeverity(peer); - this.codeDescription = new LspCodeDescription(global.es2panda._getDiagCodeDescription(peer)); - } - readonly source: String; - readonly message: String; - readonly range: LspRange; - readonly codeDescription: LspCodeDescription; - readonly severity: LspDiagSeverity; - readonly tags: LspDiagTag[]; - readonly relatedInfo: LspRelatedInfo[]; - readonly code: number | String; - readonly data: number | string; -} - -export class LspDiagsNode extends LspNode { - constructor(peer: KNativePointer) { - super(peer); - this.diagnostics = new NativePtrDecoder() - .decode(global.es2panda._getDiags(this.peer)) - .map((elPeer: KNativePointer) => { - return new LspDiagnosticNode(elPeer); - }); - } - readonly diagnostics: LspDiagnosticNode[]; -} - -export class LspDefinitionData extends LspNode { - constructor(peer: KNativePointer) { - super(peer); - this.fileName = unpackString(global.es2panda._getFileNameFromDef(peer)); - this.start = global.es2panda._getStartFromDef(peer); - this.length = global.es2panda._getLengthFromDef(peer); - } - readonly fileName: String; - readonly start: KInt; - readonly length: KInt; -} - -export class LspReferenceData extends LspNode { - constructor(peer: KNativePointer) { - super(peer); - this.fileName = unpackString(global.es2panda._getReferenceFileName(peer)); - this.start = global.es2panda._getReferenceStart(peer); - this.length = global.es2panda._getReferenceLength(peer); - } - readonly fileName: String; - readonly start: KInt; - readonly length: KInt; -} - -export class LspDeclInfo extends LspNode { - constructor(peer: KNativePointer) { - super(peer); - this.fileName = unpackString(global.es2panda._getDeclInfoFileName(peer)); - this.fileText = unpackString(global.es2panda._getDeclInfoFileText(peer)); - } - readonly fileName: String; - readonly fileText: String; -} - -export class LspReferences extends LspNode { - constructor(peer: KNativePointer) { - super(peer); - this.referenceInfos = new NativePtrDecoder() - .decode(global.es2panda._getReferenceInfos(this.peer)) - .map((elPeer: KNativePointer) => { - return new LspReferenceData(elPeer); - }); - } - readonly referenceInfos: LspReferenceData[]; -} - -export class LspTextSpan extends LspNode { - constructor(peer: KNativePointer) { - super(peer); - this.start = global.es2panda._getTextSpanStart(peer); - this.length = global.es2panda._getTextSpanLength(peer); - } - readonly start: KInt; - readonly length: KInt; -} - -export class LspSymbolDisplayPart extends LspNode { - constructor(peer: KNativePointer) { - super(peer); - this.text = unpackString(global.es2panda._getDisplayPartsText(peer)); - this.kind = unpackString(global.es2panda._getDisplayPartsKind(peer)); - } - readonly text: String; - readonly kind: String; -} - -export class LspQuickInfo extends LspNode { - constructor(peer: KNativePointer) { - super(peer); - this.kind = unpackString(global.es2panda._getQuickInfoKind(peer)); - this.kindModifier = unpackString(global.es2panda._getQuickInfoKindModifier(peer)); - this.textSpan = new LspTextSpan(global.es2panda._getTextSpan(peer)); - this.fileName = unpackString(global.es2panda._getQuickInfoFileName(peer)); - this.displayParts = new NativePtrDecoder() - .decode(global.es2panda._getSymbolDisplayPart(peer)) - .map((elPeer: KNativePointer) => { - return new LspSymbolDisplayPart(elPeer); - }); - } - readonly kind: String; - readonly kindModifier: String; - readonly textSpan: LspTextSpan; - readonly fileName: String; - readonly displayParts: LspSymbolDisplayPart[]; -} - -export enum LspHighlightSpanKind { - NONE, - DEFINITION, - REFERENCE, - WRITTEN_REFERENCE -} - -export class LspHighlightSpan extends LspNode { - constructor(peer: KNativePointer) { - super(peer); - this.fileName = unpackString(global.es2panda._getHighlightFileName(peer)); - this.textSpan = new LspTextSpan(global.es2panda._getHighlightTextSpan(peer)); - this.contextSpan = new LspTextSpan(global.es2panda._getHighlightContextSpan(peer)); - this.kind = global.es2panda._getHighlightKind(peer); - } - readonly fileName: String; - readonly textSpan: LspTextSpan; - readonly contextSpan: LspTextSpan; - readonly kind: LspHighlightSpanKind; -} - -export class LspDocumentHighlights extends LspNode { - constructor(peer: KNativePointer) { - super(peer); - this.fileName = unpackString(global.es2panda._getQuickInfoKind(peer)); - this.highlightSpans = new NativePtrDecoder() - .decode(global.es2panda._getHighlightSpanFromHighlights(peer)) - .map((elPeer: KNativePointer) => { - return new LspHighlightSpan(elPeer); - }); - } - readonly fileName: String; - readonly highlightSpans: LspHighlightSpan[]; -} - -export class LspDocumentHighlightsReferences extends LspNode { - constructor(peer: KNativePointer) { - super(peer); - this.documentHighlights = new NativePtrDecoder() - .decode(global.es2panda._getDocumentHighlightsFromRef(peer)) - .map((elPeer: KNativePointer) => { - return new LspDocumentHighlights(elPeer); - }); - } - readonly documentHighlights: LspDocumentHighlights[]; -} - -export enum LspCompletionEntryKind { - TEXT = 1, - METHOD = 2, - FUNCTION = 3, - CONSTRUCTOR = 4, - FIELD = 5, - VARIABLE = 6, - CLASS = 7, - INTERFACE = 8, - MODULE = 9, - PROPERTY = 10, - UNIT = 11, - VALUE = 12, - ENUM = 13, - KEYWORD = 14, - SNIPPET = 15, - COLOR = 16, - FILE = 17, - REFERENCE = 18, - FOLDER = 19, - ENUM_MEMBER = 20, - CONSTANT = 21, - STRUCT = 22, - EVENT = 23, - OPERATOR = 24, - TYPE_PARAMETER = 25 -} - -export enum ResolutionStatus { - RESOLVED, - UNRESOLVED -} - -export class LspCompletionEntryData extends LspNode { - constructor(peer: KNativePointer) { - super(peer); - this.fileName = unpackString(global.es2panda._getFileNameFromEntryData(peer)); - this.namedExport = unpackString(global.es2panda._getNamedExportFromEntryData(peer)); - this.importDeclaration = unpackString(global.es2panda._getImportDeclarationFromEntryData(peer)); - this.status = global.es2panda._getStatusFromEntryData(peer); - } - readonly fileName: String; - readonly namedExport: String; - readonly importDeclaration: String; - readonly status: ResolutionStatus; -} - -export class LspCompletionEntry extends LspNode { - constructor(peer: KNativePointer) { - super(peer); - this.name = unpackString(global.es2panda._getNameFromEntry(peer)); - this.sortText = unpackString(global.es2panda._getSortTextFromEntry(peer)); - this.insertText = unpackString(global.es2panda._getInsertTextFromEntry(peer)); - this.kind = global.es2panda._getKindFromEntry(peer); - this.data = this.getCompletionEntryData(peer); - } - readonly name: String; - readonly sortText: String; - readonly insertText: String; - readonly kind: LspCompletionEntryKind; - readonly data: LspCompletionEntryData | null; - private getCompletionEntryData(peer: KNativePointer): LspCompletionEntryData | null { - const dataPtr = global.es2panda._getDataFromEntry(peer); - if (dataPtr) { - return new LspCompletionEntryData(dataPtr); - } else { - return null; - } - } -} - -export class LspCompletionInfo extends LspNode { - constructor(peer: KNativePointer) { - super(peer); - this.entries = new NativePtrDecoder() - .decode(global.es2panda._getEntriesFromCompletionInfo(peer)) - .map((elPeer: KNativePointer) => { - return new LspCompletionEntry(elPeer); - }); - } - readonly entries: LspCompletionEntry[]; -} - -export enum AccessKind { - READ, - WRITE, - READWRITE -} - -export class LspReferenceLocation extends LspNode { - constructor(peer: KNativePointer) { - super(peer); - this.uri = unpackString(global.es2panda._getUriFromLocation(peer)); - this.start = global.es2panda._getStartFromLocation(peer); - this.end = global.es2panda._getEndFromLocation(peer); - this.accessKind = global.es2panda._getAccessKindFromLocation(peer); - } - readonly uri: String; - readonly start: KInt; - readonly end: KInt; - readonly accessKind: AccessKind; -} - -export class LspReferenceLocationList extends LspNode { - constructor(peer: KNativePointer) { - super(peer); - this.entries = new NativePtrDecoder() - .decode(global.es2panda._getLocationFromList(peer)) - .map((elPeer: KNativePointer) => { - return new LspReferenceLocation(elPeer); - }); - } - readonly entries: LspReferenceLocation[]; -} - -export class LspLineAndCharacter extends LspNode { - readonly line: number; - readonly character: number; - constructor(peer: KNativePointer) { - super(peer); - this.line = global.es2panda._getLine(peer); - this.character = global.es2panda._getChar(peer); - } -} diff --git a/ets2panda/bindings/src/lsp_helper.ts b/ets2panda/bindings/src/lsp_helper.ts deleted file mode 100644 index 48bbf71c16..0000000000 --- a/ets2panda/bindings/src/lsp_helper.ts +++ /dev/null @@ -1,355 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { LspDriverHelper } from './driver_helper'; -import { global } from './global'; -import { - LspDefinitionData, - LspDiagsNode, - LspReferences, - LspQuickInfo, - LspDocumentHighlightsReferences, - LspCompletionInfo, - LspReferenceLocationList, - LspLineAndCharacter, - LspReferenceData -} from './lspNode'; -import { unpackString } from './private'; -import { Es2pandaContextState } from './generated/Es2pandaEnums'; -import { BuildConfig } from './types'; -import { PluginDriver, PluginHook } from './ui_plugins_driver'; -import { ModuleDescriptor } from './buildConfigGenerate'; -import { generateArkTsConfigByModules } from './arktsConfigGenerate'; - -import * as fs from 'fs'; -import * as path from 'path'; - -function initBuildEnv(): void { - const currentPath: string | undefined = process.env.PATH; - let pandaLibPath: string = path.resolve(__dirname, '../../ets2panda/lib'); - process.env.PATH = `${currentPath}${path.delimiter}${pandaLibPath}`; -} - -export class Lsp { - private pandaLibPath: string; - private projectPath: string; - private fileNameToArktsconfig: Record; // Map - private moduleToBuildConfig: Record; // Map - private getFileContent: (filePath: string) => string; - - constructor(projectPath: string, getContentCallback?: (filePath: string) => string) { - initBuildEnv(); - this.pandaLibPath = path.resolve(__dirname, '../../ets2panda/lib'); - this.projectPath = projectPath; - let compileFileInfoPath = path.join(projectPath, '.idea', '.deveco', 'lsp_compileFileInfos.json'); - this.fileNameToArktsconfig = JSON.parse(fs.readFileSync(compileFileInfoPath, 'utf-8')); - let buildConfigPath = path.join(projectPath, '.idea', '.deveco', 'lsp_build_config.json'); - this.moduleToBuildConfig = JSON.parse(fs.readFileSync(buildConfigPath, 'utf-8')); - this.getFileContent = getContentCallback || ((path: string): string => fs.readFileSync(path, 'utf8')); - } - - updateConfig(buildSdkPath: string, modules?: ModuleDescriptor[]): void { - generateArkTsConfigByModules(buildSdkPath, this.projectPath, modules); - let compileFileInfoPath = path.join(this.projectPath, '.idea', '.deveco', 'lsp_compileFileInfos.json'); - this.fileNameToArktsconfig = JSON.parse(fs.readFileSync(compileFileInfoPath, 'utf-8')); - let buildConfigPath = path.join(this.projectPath, '.idea', '.deveco', 'lsp_build_config.json'); - this.moduleToBuildConfig = JSON.parse(fs.readFileSync(buildConfigPath, 'utf-8')); - } - - getDefinitionAtPosition(filename: String, offset: number): LspDefinitionData { - let lspDriverHelper = new LspDriverHelper(); - let filePath = path.resolve(filename.valueOf()); - let arktsconfig = this.fileNameToArktsconfig[filePath]; - let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; - let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); - const source = this.getFileContent(filePath).replace(/\r\n/g, '\n'); - let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); - PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); - PluginDriver.getInstance().runPluginHook(PluginHook.PARSED); - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED); - let ptr = global.es2panda._getDefinitionAtPosition(localCtx, offset); - PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); - lspDriverHelper.destroyContext(localCtx); - lspDriverHelper.destroyConfig(localCfg); - return new LspDefinitionData(ptr); - } - - getSemanticDiagnostics(filename: String): LspDiagsNode { - let lspDriverHelper = new LspDriverHelper(); - let filePath = path.resolve(filename.valueOf()); - let arktsconfig = this.fileNameToArktsconfig[filePath]; - let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; - let pandaLibPath: string = path.resolve(__dirname, '../../ets2panda/lib'); - let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, pandaLibPath); - const source = this.getFileContent(filePath).replace(/\r\n/g, '\n'); - let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); - PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); - PluginDriver.getInstance().runPluginHook(PluginHook.PARSED); - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED); - let ptr = global.es2panda._getSemanticDiagnostics(localCtx); - PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); - lspDriverHelper.destroyContext(localCtx); - lspDriverHelper.destroyConfig(localCfg); - return new LspDiagsNode(ptr); - } - - getCurrentTokenValue(filename: String, offset: number): string { - let lspDriverHelper = new LspDriverHelper(); - let filePath = path.resolve(filename.valueOf()); - let arktsconfig = this.fileNameToArktsconfig[filePath]; - let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; - let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); - const source = this.getFileContent(filePath).replace(/\r\n/g, '\n'); - let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); - PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); - PluginDriver.getInstance().runPluginHook(PluginHook.PARSED); - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED); - let ptr = global.es2panda._getCurrentTokenValue(localCtx, offset); - PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); - lspDriverHelper.destroyContext(localCtx); - lspDriverHelper.destroyConfig(localCfg); - return unpackString(ptr); - } - - getImplementationAtPosition(filename: String, offset: number): LspDefinitionData { - let lspDriverHelper = new LspDriverHelper(); - let filePath = path.resolve(filename.valueOf()); - let arktsconfig = this.fileNameToArktsconfig[filePath]; - let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; - let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); - const source = this.getFileContent(filePath).replace(/\r\n/g, '\n'); - let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); - PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); - PluginDriver.getInstance().runPluginHook(PluginHook.PARSED); - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED); - let ptr = global.es2panda._getImplementationAtPosition(localCtx, offset); - PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); - lspDriverHelper.destroyContext(localCtx); - lspDriverHelper.destroyConfig(localCfg); - return new LspDefinitionData(ptr); - } - - getFileReferences(filename: String): LspReferenceData[] { - let lspDriverHelper = new LspDriverHelper(); - let searchFilePath = path.resolve(filename.valueOf()); - let arktsconfig = this.fileNameToArktsconfig[searchFilePath]; - let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; - let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, searchFilePath, this.pandaLibPath); - const source = this.getFileContent(searchFilePath).replace(/\r\n/g, '\n'); - let localCtx = lspDriverHelper.createCtx(source, searchFilePath, localCfg); - PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); - PluginDriver.getInstance().runPluginHook(PluginHook.PARSED); - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED); - let isPackageModule = global.es2panda._isPackageModule(localCtx); - PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); - lspDriverHelper.destroyContext(localCtx); - lspDriverHelper.destroyConfig(localCfg); - let result: LspReferenceData[] = []; - let moduleName = path.basename(path.dirname(arktsconfig)); - let buildConfig: BuildConfig = this.moduleToBuildConfig[moduleName]; - for (let i = 0; i < buildConfig.compileFiles.length; i++) { - let filePath = path.resolve(buildConfig.compileFiles[i]); - let arktsconfig = this.fileNameToArktsconfig[filePath]; - let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; - let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); - const source = fs.readFileSync(filePath, 'utf8').toString().replace(/\r\n/g, '\n'); - let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); - PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); - PluginDriver.getInstance().runPluginHook(PluginHook.PARSED); - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED); - let ptr = global.es2panda._getFileReferences(searchFilePath, localCtx, isPackageModule); - let refs = new LspReferences(ptr); - PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); - lspDriverHelper.destroyContext(localCtx); - lspDriverHelper.destroyConfig(localCfg); - for (let j = 0; j < refs.referenceInfos.length; j++) { - if (refs.referenceInfos[j].fileName !== '') { - result.push(refs.referenceInfos[j]); - } - } - } - return result; - } - - getReferencesAtPosition(filename: String, offset: number): LspReferenceData[] { - let lspDriverHelper = new LspDriverHelper(); - let filePath = path.resolve(filename.valueOf()); - let arktsconfig = this.fileNameToArktsconfig[filePath]; - let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; - let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); - const source = this.getFileContent(filePath).replace(/\r\n/g, '\n'); - let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); - PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); - PluginDriver.getInstance().runPluginHook(PluginHook.PARSED); - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED); - let declInfo = global.es2panda._getDeclInfo(localCtx, offset); - PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); - lspDriverHelper.destroyContext(localCtx); - lspDriverHelper.destroyConfig(localCfg); - let result: LspReferenceData[] = []; - let moduleName = path.basename(path.dirname(arktsconfig)); - let buildConfig: BuildConfig = this.moduleToBuildConfig[moduleName]; - for (let i = 0; i < buildConfig.compileFiles.length; i++) { - let filePath = path.resolve(buildConfig.compileFiles[i]); - let arktsconfig = this.fileNameToArktsconfig[filePath]; - let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; - let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); - const source = fs.readFileSync(filePath, 'utf8').toString().replace(/\r\n/g, '\n'); - let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); - PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); - PluginDriver.getInstance().runPluginHook(PluginHook.PARSED); - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED); - let ptr = global.es2panda._getReferencesAtPosition(localCtx, declInfo); - PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); - lspDriverHelper.destroyContext(localCtx); - lspDriverHelper.destroyConfig(localCfg); - let refs = new LspReferences(ptr); - result.push(...refs.referenceInfos); - } - return Array.from(new Set(result)); - } - - getSyntacticDiagnostics(filename: String): LspDiagsNode { - let lspDriverHelper = new LspDriverHelper(); - let filePath = path.resolve(filename.valueOf()); - let arktsconfig = this.fileNameToArktsconfig[filePath]; - let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; - let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); - const source = this.getFileContent(filePath).replace(/\r\n/g, '\n'); - let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); - PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); - PluginDriver.getInstance().runPluginHook(PluginHook.PARSED); - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED); - let ptr = global.es2panda._getSyntacticDiagnostics(localCtx); - PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); - lspDriverHelper.destroyContext(localCtx); - lspDriverHelper.destroyConfig(localCfg); - return new LspDiagsNode(ptr); - } - - getSuggestionDiagnostics(filename: String): LspDiagsNode { - let lspDriverHelper = new LspDriverHelper(); - let filePath = path.resolve(filename.valueOf()); - let arktsconfig = this.fileNameToArktsconfig[filePath]; - let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; - let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); - const source = this.getFileContent(filePath).replace(/\r\n/g, '\n'); - let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); - PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); - PluginDriver.getInstance().runPluginHook(PluginHook.PARSED); - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED); - let ptr = global.es2panda._getSuggestionDiagnostics(localCtx); - PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); - lspDriverHelper.destroyContext(localCtx); - lspDriverHelper.destroyConfig(localCfg); - return new LspDiagsNode(ptr); - } - - getQuickInfoAtPosition(filename: String, offset: number): LspQuickInfo { - let lspDriverHelper = new LspDriverHelper(); - let filePath = path.resolve(filename.valueOf()); - let arktsconfig = this.fileNameToArktsconfig[filePath]; - let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; - let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); - const source = this.getFileContent(filePath).replace(/\r\n/g, '\n'); - let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); - PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); - PluginDriver.getInstance().runPluginHook(PluginHook.PARSED); - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED); - let ptr = global.es2panda._getQuickInfoAtPosition(filename, localCtx, offset); - PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); - lspDriverHelper.destroyContext(localCtx); - lspDriverHelper.destroyConfig(localCfg); - return new LspQuickInfo(ptr); - } - - getDocumentHighlights(filename: String, offset: number): LspDocumentHighlightsReferences { - let lspDriverHelper = new LspDriverHelper(); - let filePath = path.resolve(filename.valueOf()); - let arktsconfig = this.fileNameToArktsconfig[filePath]; - let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; - let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); - const source = this.getFileContent(filePath).replace(/\r\n/g, '\n'); - let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); - PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); - PluginDriver.getInstance().runPluginHook(PluginHook.PARSED); - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED); - let ptr = global.es2panda._getDocumentHighlights(localCtx, offset); - PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); - lspDriverHelper.destroyContext(localCtx); - lspDriverHelper.destroyConfig(localCfg); - return new LspDocumentHighlightsReferences(ptr); - } - - getCompletionAtPosition(filename: String, offset: number): LspCompletionInfo { - let lspDriverHelper = new LspDriverHelper(); - let filePath = path.resolve(filename.valueOf()); - let arktsconfig = this.fileNameToArktsconfig[filePath]; - let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; - let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); - let source = this.getFileContent(filePath).replace(/\r\n/g, '\n'); - // This is a temporary solution to support "obj." with wildcard for better solution in internal issue. - if (source[offset - 1] === '.') { - const wildcard = '_WILDCARD'; - if (offset < source.length + 1) { - source = source.slice(0, offset) + wildcard + source.slice(offset); - } else { - source += wildcard; - } - offset += wildcard.length; - } - let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); - PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); - PluginDriver.getInstance().runPluginHook(PluginHook.PARSED); - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED); - let ptr = global.es2panda._getCompletionAtPosition(localCtx, offset); - PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); - lspDriverHelper.destroyContext(localCtx); - lspDriverHelper.destroyConfig(localCfg); - return new LspCompletionInfo(ptr); - } - - toLineColumnOffset(filename: String, offset: number): LspLineAndCharacter { - let lspDriverHelper = new LspDriverHelper(); - let filePath = path.resolve(filename.valueOf()); - let arktsconfig = this.fileNameToArktsconfig[filePath]; - let ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', arktsconfig]; - let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); - const source = this.getFileContent(filePath).replace(/\r\n/g, '\n'); - let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); - PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); - PluginDriver.getInstance().runPluginHook(PluginHook.PARSED); - lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED); - let ptr = global.es2panda._toLineColumnOffset(localCtx, offset); - PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); - lspDriverHelper.destroyContext(localCtx); - lspDriverHelper.destroyConfig(localCfg); - return new LspLineAndCharacter(ptr); - } -} diff --git a/ets2panda/bindings/src/strings.ts b/ets2panda/bindings/src/strings.ts deleted file mode 100644 index ff72c1626e..0000000000 --- a/ets2panda/bindings/src/strings.ts +++ /dev/null @@ -1,210 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { int32 } from './InteropTypes'; - -interface SystemTextEncoder { - encode(input?: string): Uint8Array; - encodeInto(src: string, dest: Uint8Array): void; -} - -interface WithStreamOption { - stream?: boolean | undefined; -} - -interface SystemTextDecoder { - decode(input?: ArrayBuffer | null | Uint8Array, options?: WithStreamOption): string; -} - -export class CustomTextEncoder { - static readonly HeaderLen: int32 = Int32Array.BYTES_PER_ELEMENT; - - constructor( - encoder: SystemTextEncoder | undefined = typeof TextEncoder !== 'undefined' ? new TextEncoder() : undefined - ) { - this.encoder = encoder; - } - - private readonly encoder: SystemTextEncoder | undefined; - - public static stringLength(input: string): int32 { - let length = 0; - for (let i = 0; i < input.length; i++) { - length++; - let cp = input.codePointAt(i)!; - if (cp >= 0x10000) { - i++; - } - } - return length; - } - - encodedLength(input: string): int32 { - let length = 0; - for (let i = 0; i < input.length; i++) { - let cp = input.codePointAt(i)!; - if (cp < 0x80) { - length += 1; - } else if (cp < 0x800) { - length += 2; - } else if (cp < 0x10000) { - length += 3; - } else { - length += 4; - i++; - } - } - return length; - } - - private addLength(array: Uint8Array, offset: int32, len: int32): void { - array[offset] = len & 0xff; - array[offset + 1] = (len >> 8) & 0xff; - array[offset + 2] = (len >> 16) & 0xff; - array[offset + 3] = (len >> 24) & 0xff; - } - - static getHeaderLength(array: Uint8Array, offset: int32 = 0): int32 { - return array[offset] | (array[offset + 1] << 8) | (array[offset + 2] << 16) | (array[offset + 3] << 24); - } - - // Produces array of bytes with encoded string headed by 4 bytes (little endian) size information: - // [s0][s1][s2][s3] [c_0] ... [c_size-1] - encode(input: string | undefined, addLength: boolean = true): Uint8Array { - let headerLen = addLength ? CustomTextEncoder.HeaderLen : 0; - let result: Uint8Array; - if (!input) { - result = new Uint8Array(headerLen); - } else if (this.encoder !== undefined) { - result = this.encoder!.encode('s'.repeat(headerLen) + input); - } else { - let length = this.encodedLength(input); - result = new Uint8Array(length + headerLen); - this.encodeInto(input, result, headerLen); - } - if (addLength) { - this.addLength(result, 0, result.length - headerLen); - } - return result; - } - - // Produces encoded array of strings with size information. - encodeArray(strings: Array): Uint8Array { - let totalBytes = CustomTextEncoder.HeaderLen; - let lengths = new Int32Array(strings.length); - for (let i = 0; i < lengths.length; i++) { - let len = this.encodedLength(strings[i]); - lengths[i] = len; - totalBytes += len + CustomTextEncoder.HeaderLen; - } - let array = new Uint8Array(totalBytes); - let position = 0; - this.addLength(array, position, lengths.length); - position += CustomTextEncoder.HeaderLen; - for (let i = 0; i < lengths.length; i++) { - this.addLength(array, position, lengths[i]); - position += CustomTextEncoder.HeaderLen; - this.encodeInto(strings[i], array, position); - position += lengths[i]; - } - return array; - } - - encodeInto(input: string, result: Uint8Array, position: int32): Uint8Array { - if (this.encoder !== undefined) { - this.encoder!.encodeInto(input, result.subarray(position, result.length)); - return result; - } - let index = position; - for (let stringPosition = 0; stringPosition < input.length; stringPosition++) { - let cp = input.codePointAt(stringPosition)!; - if (cp < 0x80) { - result[index++] = cp | 0; - } else if (cp < 0x800) { - result[index++] = (cp >> 6) | 0xc0; - result[index++] = (cp & 0x3f) | 0x80; - } else if (cp < 0x10000) { - result[index++] = (cp >> 12) | 0xe0; - result[index++] = ((cp >> 6) & 0x3f) | 0x80; - result[index++] = (cp & 0x3f) | 0x80; - } else { - result[index++] = (cp >> 18) | 0xf0; - result[index++] = ((cp >> 12) & 0x3f) | 0x80; - result[index++] = ((cp >> 6) & 0x3f) | 0x80; - result[index++] = (cp & 0x3f) | 0x80; - stringPosition++; - } - } - result[index] = 0; - return result; - } -} - -export class CustomTextDecoder { - static cpArrayMaxSize = 128; - constructor( - decoder: SystemTextDecoder | TextDecoder | undefined = typeof TextDecoder !== 'undefined' - ? new TextDecoder() - : undefined - ) { - this.decoder = decoder; - } - - private readonly decoder: SystemTextDecoder | TextDecoder | undefined; - - decode(input: Uint8Array): string { - if (this.decoder !== undefined) { - return this.decoder!.decode(input); - } - const cpSize = Math.min(CustomTextDecoder.cpArrayMaxSize, input.length); - let codePoints = new Int32Array(cpSize); - let cpIndex = 0; - let index = 0; - let result = ''; - while (index < input.length) { - let elem = input[index]; - let lead = elem & 0xff; - let count = 0; - let value = 0; - if (lead < 0x80) { - count = 1; - value = elem; - } else if (lead >> 5 === 0x6) { - value = ((elem << 6) & 0x7ff) + (input[index + 1] & 0x3f); - count = 2; - } else if (lead >> 4 === 0xe) { - value = ((elem << 12) & 0xffff) + ((input[index + 1] << 6) & 0xfff) + (input[index + 2] & 0x3f); - count = 3; - } else if (lead >> 3 === 0x1e) { - value = - ((elem << 18) & 0x1fffff) + - ((input[index + 1] << 12) & 0x3ffff) + - ((input[index + 2] << 6) & 0xfff) + - (input[index + 3] & 0x3f); - count = 4; - } - codePoints[cpIndex++] = value; - if (cpIndex === cpSize) { - cpIndex = 0; - result += String.fromCodePoint(...codePoints); - } - index += count; - } - if (cpIndex > 0) { - result += String.fromCodePoint(...codePoints.slice(0, cpIndex)); - } - return result; - } -} diff --git a/ets2panda/bindings/src/types.ts b/ets2panda/bindings/src/types.ts deleted file mode 100644 index 2a34d968b7..0000000000 --- a/ets2panda/bindings/src/types.ts +++ /dev/null @@ -1,198 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { KNativePointer as KPtr } from './InteropTypes'; -import { global } from './global'; -import { throwError } from './utils'; -import { passString, passStringArray, unpackString } from './private'; -import { isNullPtr } from './Wrapper'; - -export const arrayOfNullptr = new BigUint64Array([BigInt(0)]); - -export abstract class ArktsObject { - protected constructor(peer: KPtr) { - this.peer = peer; - } - - readonly peer: KPtr; -} - -export abstract class Node extends ArktsObject { - protected constructor(peer: KPtr) { - if (isNullPtr(peer)) { - throw new Error('trying to create new Node on NULLPTR'); - } - super(peer); - } - - public get originalPeer(): KPtr { - return global.es2panda._AstNodeOriginalNodeConst(global.context, this.peer); - } - - public set originalPeer(peer: KPtr) { - global.es2panda._AstNodeSetOriginalNode(global.context, this.peer, peer); - } - - protected dumpMessage(): string { - return ``; - } - - public dumpJson(): string { - return unpackString(global.es2panda._AstNodeDumpJsonConst(global.context, this.peer)); - } - - public dumpSrc(): string { - return unpackString(global.es2panda._AstNodeDumpEtsSrcConst(global.context, this.peer)); - } -} - -export class Config extends ArktsObject { - readonly path: string; - constructor(peer: KPtr, fpath: string) { - super(peer); - // TODO: wait for getter from api - this.path = fpath; - } - - public toString(): string { - return `Config (peer = ${this.peer}, path = ${this.path})`; - } - - static create(input: string[], fpath: string, pandaLibPath: string = '', isEditingMode: boolean = false): Config { - if (isEditingMode) { - let cfg = global.es2pandaPublic._CreateConfig(input.length, passStringArray(input), pandaLibPath); - return new Config(cfg, fpath); - } - if (!global.configIsInitialized()) { - let cfg = global.es2panda._CreateConfig(input.length, passStringArray(input), pandaLibPath); - global.config = cfg; - return new Config(cfg, fpath); - } else { - return new Config(global.config, fpath); - } - } -} - -export class Context extends ArktsObject { - constructor(peer: KPtr) { - super(peer); - } - - public toString(): string { - return `Context (peer = ${this.peer})`; - } - - static createFromString(source: string): Context { - if (!global.configIsInitialized()) { - throwError(`Config not initialized`); - } - return new Context( - global.es2panda._CreateContextFromString(global.config, passString(source), passString(global.filePath)) - ); - } - - static lspCreateFromString(source: string, filePath: string, cfg: Config): KPtr { - if (cfg === undefined) { - throwError(`Config not initialized`); - } - return global.es2pandaPublic._CreateContextFromString(cfg.peer, passString(source), passString(filePath)); - } -} - -// ProjectConfig begins -export interface PluginsConfig { - [pluginName: string]: string; -} - -export interface BuildBaseConfig { - buildType: 'build' | 'preview' | 'hotreload' | 'coldreload'; - buildMode: 'Debug' | 'Release'; - hasMainModule: boolean; - arkts: object; - arktsGlobal: object; -} - -export interface ModuleConfig { - packageName: string; - moduleType: string; - moduleRootPath: string; - sourceRoots: string[]; -} - -export interface PathConfig { - loaderOutPath: string; - declgenDtsOutPath: string; - declgenTsOutPath: string; - cachePath: string; - buildSdkPath: string; - pandaSdkPath?: string; // path to panda sdk lib/bin, for local test - pandaStdlibPath?: string; // path to panda sdk stdlib, for local test - abcLinkerPath?: string; -} - -export interface DeclgenConfig { - enableDeclgenEts2Ts: boolean; - declgenV1OutPath?: string; - declgenBridgeCodePath?: string; -} - -export interface LoggerConfig { - getHvigorConsoleLogger?: Function; -} - -export interface DependentModuleConfig { - packageName: string; - moduleName: string; - moduleType: string; - modulePath: string; - sourceRoots: string[]; - entryFile: string; - language: string; - declFilesPath?: string; - dependencies?: string[]; -} - -export interface BuildConfig extends BuildBaseConfig, DeclgenConfig, LoggerConfig, ModuleConfig, PathConfig { - plugins: PluginsConfig; - compileFiles: string[]; - dependentModuleList: DependentModuleConfig[]; -} -// ProjectConfig ends - -export interface CompileFileInfo { - filePath: string; - dependentFiles: string[]; - abcFilePath: string; - arktsConfigFile: string; - packageName: string; -} - -export interface ModuleInfo { - isMainModule: boolean; - packageName: string; - moduleRootPath: string; - moduleType: string; - sourceRoots: string[]; - entryFile: string; - arktsConfigFile: string; - compileFileInfos: CompileFileInfo[]; - declgenV1OutPath: string | undefined; - declgenBridgeCodePath: string | undefined; - dependencies?: string[]; - staticDepModuleInfos: Map; - dynamicDepModuleInfos: Map; - language?: string; - declFilesPath?: string; -} -- Gitee From 87a3aa4bec74fe773639017758f6863c7c3126bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A5=88=E6=84=BF?= Date: Mon, 7 Jul 2025 15:13:23 +0800 Subject: [PATCH 259/268] Remove third-party header dependencies MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICLBUO Signed-off-by: chenlong --- ets2panda/BUILD.gn | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/ets2panda/BUILD.gn b/ets2panda/BUILD.gn index c0857f4c8d..58a6dd05fc 100644 --- a/ets2panda/BUILD.gn +++ b/ets2panda/BUILD.gn @@ -29,13 +29,15 @@ config("libes2panda_public_config") { include_dirs = [ "$target_gen_dir", "$target_gen_dir/include", - "//third_party/icu/icu4c/source/common", - "//third_party/icu/icu4c/source/i18n", - "//third_party/icu/icu4c/source", "$ark_es2panda_root", ] if (ark_standalone_build || ark_static_standalone_build) { - include_dirs += [ "$target_gen_dir/generated" ] + include_dirs += [ + "$target_gen_dir/generated", + "//third_party/icu/icu4c/source/common", + "//third_party/icu/icu4c/source/i18n", + "//third_party/icu/icu4c/source", + ] } } -- Gitee From ff59146f47756ed75844f377f7c536bfb14c332c Mon Sep 17 00:00:00 2001 From: tengtengh Date: Thu, 10 Jul 2025 15:31:41 +0800 Subject: [PATCH 260/268] Merge 0328 to 0702 : lsp file include Signed-off-by: tengtengh --- ets2panda/lsp/src/services/text_change/change_tracker.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/ets2panda/lsp/src/services/text_change/change_tracker.cpp b/ets2panda/lsp/src/services/text_change/change_tracker.cpp index fd86706d03..477add0b18 100644 --- a/ets2panda/lsp/src/services/text_change/change_tracker.cpp +++ b/ets2panda/lsp/src/services/text_change/change_tracker.cpp @@ -18,7 +18,6 @@ #include #include #include -#include "util.h" #include #include -- Gitee From 5ff15e9ca8984c24946dec998e630616d1741ed1 Mon Sep 17 00:00:00 2001 From: zhongmingwei Date: Fri, 23 May 2025 11:05:15 +0800 Subject: [PATCH 261/268] Es2abc support static interface Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICAOLR Description: es2abc support static interface Change-Id: I1157db3b20125a270f05c08ba45adaa08f775f35 Signed-off-by: zhongmingwei --- es2panda/parser/parserImpl.cpp | 1 + es2panda/parser/program/program.cpp | 2 ++ es2panda/util/helpers.h | 1 + 3 files changed, 4 insertions(+) diff --git a/es2panda/parser/parserImpl.cpp b/es2panda/parser/parserImpl.cpp index d92e9c42d2..0dab3b7005 100644 --- a/es2panda/parser/parserImpl.cpp +++ b/es2panda/parser/parserImpl.cpp @@ -120,6 +120,7 @@ Program ParserImpl::Parse(const SourceFile &sourceFile, const CompilerOptions &o if (util::Helpers::IsSupportAnnotationVersion(program_.TargetApiVersion())) { program_.SetEnableAnnotations(options.enableAnnotations); } + program_.SetEnableEtsImplements(options.enableEtsImplements); program_.SetShared(sourceFile.isSharedModule); program_.SetModuleRecordFieldName(options.moduleRecordFieldName); program_.SetSourceLang(sourceFile.sourceLang); diff --git a/es2panda/parser/program/program.cpp b/es2panda/parser/program/program.cpp index ed6e6ca1be..992292ea00 100644 --- a/es2panda/parser/program/program.cpp +++ b/es2panda/parser/program/program.cpp @@ -49,6 +49,7 @@ Program::Program(Program &&other) useDefineSemantic_(other.useDefineSemantic_), isShared_(other.isShared_), enableAnnotations_(other.enableAnnotations_), + enableEtsImplements_(other.enableEtsImplements_), targetApiSubVersion_(other.targetApiSubVersion_), moduleRecordFieldName_(other.moduleRecordFieldName_), sourceLang_(other.sourceLang_) @@ -80,6 +81,7 @@ Program &Program::operator=(Program &&other) useDefineSemantic_ = other.useDefineSemantic_; isShared_ = other.isShared_; enableAnnotations_ = other.enableAnnotations_; + enableEtsImplements_ = other.enableEtsImplements_; targetApiSubVersion_ = other.targetApiSubVersion_; moduleRecordFieldName_ = other.moduleRecordFieldName_; sourceLang_ = other.sourceLang_; diff --git a/es2panda/util/helpers.h b/es2panda/util/helpers.h index 92e122a509..d2a0614fab 100644 --- a/es2panda/util/helpers.h +++ b/es2panda/util/helpers.h @@ -190,6 +190,7 @@ public: static bool IsSupportLazyImportVersion(int apiVersion, std::string subApiVersion); static bool IsEnableExpectedPropertyCountApiVersion(int apiVersion); static bool IsSupportAnnotationVersion(int apiVersion); + static bool IsSupportEtsImplementsVersion(int apiVersion); static const uint32_t MAX_DOUBLE_DIGIT = 310; static const uint32_t MAX_DOUBLE_PRECISION_DIGIT = 17; -- Gitee From da69c462af5fe61d2fb3a35c7652e1a3961d4d36 Mon Sep 17 00:00:00 2001 From: tengtengh Date: Fri, 11 Jul 2025 16:06:53 +0800 Subject: [PATCH 262/268] cover linter/test with 0328 Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICLSLO Signed-off-by: tengtengh --- ..._support_property_descriptor.ets.args.json | 2 +- ...ncurrent_decorator_arkts2.ets.migrate.json | 2 +- .../interop/increases_decreases_js_obj_js.js | 1 - .../interop_export_js_rules.ets.autofix.json | 88 -- .../interop_export_js_rules.ets.migrate.ets | 27 - .../interop_export_js_rules.ets.migrate.json | 58 -- .../static_dynamic_import.ets.args.json | 19 - .../interop/test_files/dummy_arkts1_file.ets | 16 - .../test/interop/test_files/dummy_js_file.js | 16 - .../test/interop/test_files/dummy_ts_file.ts | 16 - .../test/main/class_static_init.ets.args.json | 3 +- .../main/class_static_init.ets.arkts2.json | 20 - .../main/class_static_init.ets.autofix.json | 876 ------------------ .../main/debugger_statememt.ets.migrate.ets | 22 - .../main/debugger_statememt.ets.migrate.json | 17 - .../test/main/double_excla_binding_3.ets | 2 +- .../test/main/global_this.ets.migrate.ets | 41 - .../test/main/global_this.ets.migrate.json | 58 -- .../main/prop_decorator_and_interfaces_1.ets | 39 - ...p_decorator_and_interfaces_1.ets.args.json | 19 - ...decorator_and_interfaces_1.ets.arkts2.json | 128 --- .../prop_decorator_and_interfaces_1.ets.json | 17 - .../main/prop_decorator_and_interfaces_2.ets | 49 - ...p_decorator_and_interfaces_2.ets.args.json | 19 - ...decorator_and_interfaces_2.ets.arkts2.json | 448 --------- .../prop_decorator_and_interfaces_2.ets.json | 98 -- .../main/prop_decorator_and_interfaces_3.ets | 59 -- ...p_decorator_and_interfaces_3.ets.args.json | 19 - ...decorator_and_interfaces_3.ets.arkts2.json | 248 ----- .../prop_decorator_and_interfaces_3.ets.json | 108 --- .../linter/test/main/prop_name_from_value.ets | 25 - .../main/prop_name_from_value.ets.args.json | 19 - .../main/prop_name_from_value.ets.arkts2.json | 28 - .../test/main/prop_name_from_value.ets.json | 17 - 34 files changed, 4 insertions(+), 2620 deletions(-) mode change 100755 => 100644 ets2panda/linter/test/builtin/builtin_not_support_property_descriptor.ets.args.json mode change 100755 => 100644 ets2panda/linter/test/concurrent/concurrent_decorator_arkts2.ets.migrate.json delete mode 100644 ets2panda/linter/test/interop/interop_export_js_rules.ets.autofix.json delete mode 100644 ets2panda/linter/test/interop/interop_export_js_rules.ets.migrate.ets delete mode 100644 ets2panda/linter/test/interop/interop_export_js_rules.ets.migrate.json delete mode 100644 ets2panda/linter/test/interop/static_dynamic_import.ets.args.json delete mode 100644 ets2panda/linter/test/interop/test_files/dummy_arkts1_file.ets delete mode 100644 ets2panda/linter/test/interop/test_files/dummy_js_file.js delete mode 100644 ets2panda/linter/test/interop/test_files/dummy_ts_file.ts delete mode 100644 ets2panda/linter/test/main/class_static_init.ets.autofix.json delete mode 100644 ets2panda/linter/test/main/debugger_statememt.ets.migrate.ets delete mode 100644 ets2panda/linter/test/main/debugger_statememt.ets.migrate.json delete mode 100644 ets2panda/linter/test/main/global_this.ets.migrate.ets delete mode 100644 ets2panda/linter/test/main/global_this.ets.migrate.json delete mode 100644 ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets delete mode 100644 ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets.args.json delete mode 100644 ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets.arkts2.json delete mode 100644 ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets.json delete mode 100644 ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets delete mode 100644 ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets.args.json delete mode 100644 ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets.arkts2.json delete mode 100644 ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets.json delete mode 100644 ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets delete mode 100644 ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets.args.json delete mode 100644 ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets.arkts2.json delete mode 100644 ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets.json delete mode 100644 ets2panda/linter/test/main/prop_name_from_value.ets delete mode 100644 ets2panda/linter/test/main/prop_name_from_value.ets.args.json delete mode 100644 ets2panda/linter/test/main/prop_name_from_value.ets.arkts2.json delete mode 100644 ets2panda/linter/test/main/prop_name_from_value.ets.json diff --git a/ets2panda/linter/test/builtin/builtin_not_support_property_descriptor.ets.args.json b/ets2panda/linter/test/builtin/builtin_not_support_property_descriptor.ets.args.json old mode 100755 new mode 100644 index b214d57430..1b80aa9e73 --- a/ets2panda/linter/test/builtin/builtin_not_support_property_descriptor.ets.args.json +++ b/ets2panda/linter/test/builtin/builtin_not_support_property_descriptor.ets.args.json @@ -16,4 +16,4 @@ "mode": { "arkts2": "" } - } + } \ No newline at end of file diff --git a/ets2panda/linter/test/concurrent/concurrent_decorator_arkts2.ets.migrate.json b/ets2panda/linter/test/concurrent/concurrent_decorator_arkts2.ets.migrate.json old mode 100755 new mode 100644 index 7e6581bf3a..1dde4c017f --- a/ets2panda/linter/test/concurrent/concurrent_decorator_arkts2.ets.migrate.json +++ b/ets2panda/linter/test/concurrent/concurrent_decorator_arkts2.ets.migrate.json @@ -25,4 +25,4 @@ "severity": "ERROR" } ] -} \ No newline at end of file +} diff --git a/ets2panda/linter/test/interop/increases_decreases_js_obj_js.js b/ets2panda/linter/test/interop/increases_decreases_js_obj_js.js index 2519dec804..88eed7f647 100755 --- a/ets2panda/linter/test/interop/increases_decreases_js_obj_js.js +++ b/ets2panda/linter/test/interop/increases_decreases_js_obj_js.js @@ -12,6 +12,5 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use static' export let foo = {num: 0} diff --git a/ets2panda/linter/test/interop/interop_export_js_rules.ets.autofix.json b/ets2panda/linter/test/interop/interop_export_js_rules.ets.autofix.json deleted file mode 100644 index 58c2313941..0000000000 --- a/ets2panda/linter/test/interop/interop_export_js_rules.ets.autofix.json +++ /dev/null @@ -1,88 +0,0 @@ -{ - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "result": [ - { - "line": 17, - "column": 1, - "endLine": 17, - "endColumn": 51, - "problem": "ImportAfterStatement", - "suggest": "", - "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", - "severity": "ERROR" - }, - { - "line": 17, - "column": 1, - "endLine": 17, - "endColumn": 51, - "problem": "InterOpImportJs", - "autofix": [ - { - "start": 618, - "end": 668, - "replacementText": "", - "line": 17, - "column": 1, - "endLine": 17, - "endColumn": 51 - }, - { - "start": 668, - "end": 668, - "replacementText": "let GeneratedImportVar_1 = ESObject.load('./interop_import_js_rules_js');\nlet ff1 = GeneratedImportVar_1.getPropertyByName('ff1');\n", - "line": 17, - "column": 1, - "endLine": 17, - "endColumn": 51 - } - ], - "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", - "severity": "ERROR" - }, - { - "line": 19, - "column": 1, - "endLine": 19, - "endColumn": 13, - "problem": "InteropJsObjectExport", - "suggest": "", - "rule": "Direct export of interop JS objects is not supported (arkts-interop-js2s-export-js)", - "severity": "ERROR" - }, - { - "line": 21, - "column": 1, - "endLine": 21, - "endColumn": 51, - "problem": "InteropJsObjectExport", - "suggest": "", - "rule": "Direct export of interop JS objects is not supported (arkts-interop-js2s-export-js)", - "severity": "ERROR" - }, - { - "line": 23, - "column": 1, - "endLine": 23, - "endColumn": 57, - "problem": "InteropArkTs1ObjectExport", - "suggest": "", - "rule": "Direct export of interop ArkTS1.0 objects is not supported (arkts-interop-d2s-export-entity)", - "severity": "ERROR" - } - ] -} diff --git a/ets2panda/linter/test/interop/interop_export_js_rules.ets.migrate.ets b/ets2panda/linter/test/interop/interop_export_js_rules.ets.migrate.ets deleted file mode 100644 index ad8d86948b..0000000000 --- a/ets2panda/linter/test/interop/interop_export_js_rules.ets.migrate.ets +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -'use static' - -let GeneratedImportVar_1 = ESObject.load('./interop_import_js_rules_js'); -let ff1 = GeneratedImportVar_1.getPropertyByName('ff1'); - - -export {ff1} // imported from js. Error is shown - -export { ff2 } from "./interop_import_js_rules_js" // ff2 is imported from js. Error is shown - -export { MyDecorator } from "./oh_modules/ets_decorator" // MyDecorator is imported from arkts1. Error is shown - -export { foo as bar } from "./oh_modules/reflect_export" // foo is imported from arkts1.2. No error. diff --git a/ets2panda/linter/test/interop/interop_export_js_rules.ets.migrate.json b/ets2panda/linter/test/interop/interop_export_js_rules.ets.migrate.json deleted file mode 100644 index 1291e15d5e..0000000000 --- a/ets2panda/linter/test/interop/interop_export_js_rules.ets.migrate.json +++ /dev/null @@ -1,58 +0,0 @@ -{ - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "result": [ - { - "line": 17, - "column": 5, - "endLine": 17, - "endColumn": 73, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 18, - "column": 5, - "endLine": 18, - "endColumn": 56, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 23, - "column": 1, - "endLine": 23, - "endColumn": 51, - "problem": "InteropJsObjectExport", - "suggest": "", - "rule": "Direct export of interop JS objects is not supported (arkts-interop-js2s-export-js)", - "severity": "ERROR" - }, - { - "line": 25, - "column": 1, - "endLine": 25, - "endColumn": 57, - "problem": "InteropArkTs1ObjectExport", - "suggest": "", - "rule": "Direct export of interop ArkTS1.0 objects is not supported (arkts-interop-d2s-export-entity)", - "severity": "ERROR" - } - ] -} diff --git a/ets2panda/linter/test/interop/static_dynamic_import.ets.args.json b/ets2panda/linter/test/interop/static_dynamic_import.ets.args.json deleted file mode 100644 index d8d3390ad9..0000000000 --- a/ets2panda/linter/test/interop/static_dynamic_import.ets.args.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "mode": { - "arkts2": "" - } -} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/test_files/dummy_arkts1_file.ets b/ets2panda/linter/test/interop/test_files/dummy_arkts1_file.ets deleted file mode 100644 index 5aad017834..0000000000 --- a/ets2panda/linter/test/interop/test_files/dummy_arkts1_file.ets +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -export module arkts {} diff --git a/ets2panda/linter/test/interop/test_files/dummy_js_file.js b/ets2panda/linter/test/interop/test_files/dummy_js_file.js deleted file mode 100644 index fa09fbb12c..0000000000 --- a/ets2panda/linter/test/interop/test_files/dummy_js_file.js +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -export {} diff --git a/ets2panda/linter/test/interop/test_files/dummy_ts_file.ts b/ets2panda/linter/test/interop/test_files/dummy_ts_file.ts deleted file mode 100644 index e2f4a0e44b..0000000000 --- a/ets2panda/linter/test/interop/test_files/dummy_ts_file.ts +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -export module tsModule {} diff --git a/ets2panda/linter/test/main/class_static_init.ets.args.json b/ets2panda/linter/test/main/class_static_init.ets.args.json index 4e9dc628f7..3ef4496a81 100755 --- a/ets2panda/linter/test/main/class_static_init.ets.args.json +++ b/ets2panda/linter/test/main/class_static_init.ets.args.json @@ -14,7 +14,6 @@ "limitations under the License." ], "mode": { - "arkts2": "", - "autofix": "--arkts-2" + "arkts2": "" } } diff --git a/ets2panda/linter/test/main/class_static_init.ets.arkts2.json b/ets2panda/linter/test/main/class_static_init.ets.arkts2.json index a14cdf2ce5..da2a0d8e4b 100644 --- a/ets2panda/linter/test/main/class_static_init.ets.arkts2.json +++ b/ets2panda/linter/test/main/class_static_init.ets.arkts2.json @@ -544,26 +544,6 @@ "rule": "Property 'id' has no initializer and is not definitely assigned in the constructor.", "severity": "ERROR" }, - { - "line": 148, - "column": 3, - "endLine": 148, - "endColumn": 7, - "problem": "StrictDiagnostic", - "suggest": "Property 'name' has no initializer and is not definitely assigned in the constructor.", - "rule": "Property 'name' has no initializer and is not definitely assigned in the constructor.", - "severity": "ERROR" - }, - { - "line": 147, - "column": 3, - "endLine": 147, - "endColumn": 5, - "problem": "StrictDiagnostic", - "suggest": "Property 'id' has no initializer and is not definitely assigned in the constructor.", - "rule": "Property 'id' has no initializer and is not definitely assigned in the constructor.", - "severity": "ERROR" - }, { "line": 148, "column": 3, diff --git a/ets2panda/linter/test/main/class_static_init.ets.autofix.json b/ets2panda/linter/test/main/class_static_init.ets.autofix.json deleted file mode 100644 index 2be737a16e..0000000000 --- a/ets2panda/linter/test/main/class_static_init.ets.autofix.json +++ /dev/null @@ -1,876 +0,0 @@ -{ - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "result": [ - { - "line": 21, - "column": 3, - "endLine": 21, - "endColumn": 14, - "problem": "ClassstaticInitialization", - "autofix": [ - { - "start": 641, - "end": 652, - "replacementText": "static a: A | undefined = undefined;" - } - ], - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 25, - "column": 3, - "endLine": 25, - "endColumn": 14, - "problem": "ClassstaticInitialization", - "autofix": [ - { - "start": 668, - "end": 679, - "replacementText": "static g: G | undefined = undefined;" - } - ], - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 32, - "column": 3, - "endLine": 32, - "endColumn": 15, - "problem": "ClassstaticInitialization", - "autofix": [ - { - "start": 753, - "end": 765, - "replacementText": "static g: G | undefined = undefined;" - } - ], - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 36, - "column": 3, - "endLine": 36, - "endColumn": 14, - "problem": "ClassstaticInitialization", - "autofix": [ - { - "start": 781, - "end": 792, - "replacementText": "static a: A | undefined = undefined;" - } - ], - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 46, - "column": 3, - "endLine": 46, - "endColumn": 29, - "problem": "ClassstaticInitialization", - "autofix": [ - { - "start": 933, - "end": 959, - "replacementText": "public static abc: string = \"\";" - } - ], - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 59, - "column": 3, - "endLine": 59, - "endColumn": 16, - "problem": "ClassstaticInitialization", - "autofix": [ - { - "start": 1088, - "end": 1101, - "replacementText": "static b: BB | undefined = undefined;" - } - ], - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 67, - "column": 3, - "endLine": 67, - "endColumn": 35, - "problem": "ClassstaticInitialization", - "autofix": [ - { - "start": 1156, - "end": 1188, - "replacementText": "static config: {\n theme: string;\n} = {\n theme: \"\"\n };" - } - ], - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 67, - "column": 18, - "endLine": 67, - "endColumn": 19, - "problem": "ObjectTypeLiteral", - "autofix": [ - { - "start": 1143, - "end": 1143, - "replacementText": "interface GeneratedTypeLiteralInterface_1 {\n theme: string;\n}\n" - }, - { - "start": 1171, - "end": 1187, - "replacementText": "GeneratedTypeLiteralInterface_1" - } - ], - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 71, - "column": 3, - "endLine": 71, - "endColumn": 23, - "problem": "ClassstaticInitialization", - "autofix": [ - { - "start": 1205, - "end": 1225, - "replacementText": "static name: string = \"\";" - } - ], - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 79, - "column": 3, - "endLine": 79, - "endColumn": 38, - "problem": "ClassstaticInitialization", - "autofix": [ - { - "start": 1314, - "end": 1349, - "replacementText": "static uninitializedString: string = \"\";" - } - ], - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 86, - "column": 3, - "endLine": 86, - "endColumn": 45, - "problem": "ClassstaticInitialization", - "autofix": [ - { - "start": 1467, - "end": 1509, - "replacementText": "static uninitializedStringArray: string[] = [];" - } - ], - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 87, - "column": 3, - "endLine": 87, - "endColumn": 45, - "problem": "ClassstaticInitialization", - "autofix": [ - { - "start": 1512, - "end": 1554, - "replacementText": "static uninitializedNumberArray: number[] = [];" - } - ], - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 88, - "column": 3, - "endLine": 88, - "endColumn": 53, - "problem": "ClassstaticInitialization", - "autofix": [ - { - "start": 1557, - "end": 1607, - "replacementText": "static uninitializedObjectArray: {\n id: number;\n }[] = [];" - } - ], - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 88, - "column": 36, - "endLine": 88, - "endColumn": 37, - "problem": "ObjectTypeLiteral", - "autofix": [ - { - "start": 1446, - "end": 1446, - "replacementText": "interface GeneratedTypeLiteralInterface_2 {\n id: number;\n}\n" - }, - { - "start": 1590, - "end": 1604, - "replacementText": "GeneratedTypeLiteralInterface_2" - } - ], - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 89, - "column": 3, - "endLine": 89, - "endColumn": 55, - "problem": "ClassstaticInitialization", - "autofix": [ - { - "start": 1610, - "end": 1662, - "replacementText": "static uninitializedUnionArray: (string | number)[] = [];" - } - ], - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 94, - "column": 3, - "endLine": 94, - "endColumn": 67, - "problem": "ClassstaticInitialization", - "autofix": [ - { - "start": 1704, - "end": 1768, - "replacementText": "static uninitializedSimpleObject: {\n name: string;\n age: number;\n} = {\n name: \"\"\n };" - } - ], - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 94, - "column": 37, - "endLine": 94, - "endColumn": 38, - "problem": "ObjectTypeLiteral", - "autofix": [ - { - "start": 1682, - "end": 1682, - "replacementText": "interface GeneratedTypeLiteralInterface_3 {\n name: string;\n age: number;\n}\n" - }, - { - "start": 1738, - "end": 1767, - "replacementText": "GeneratedTypeLiteralInterface_3" - } - ], - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 95, - "column": 3, - "endLine": 101, - "endColumn": 5, - "problem": "ClassstaticInitialization", - "autofix": [ - { - "start": 1771, - "end": 1895, - "replacementText": "static uninitializedNestedObject: {\n id: number;\n metadata: {\n createdAt: Date;\n tags: string[];\n };\n} = {\n metadata: {\n createdAt: new Date(),\n tags: []\n }\n };" - } - ], - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 95, - "column": 37, - "endLine": 95, - "endColumn": 38, - "problem": "ObjectTypeLiteral", - "autofix": [ - { - "start": 1682, - "end": 1682, - "replacementText": "interface GeneratedTypeLiteralInterface_4 {\n id: number;\n metadata: {\n createdAt: Date;\n tags: string[];\n };\n}\n" - }, - { - "start": 1805, - "end": 1894, - "replacementText": "GeneratedTypeLiteralInterface_4" - } - ], - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 97, - "column": 15, - "endLine": 97, - "endColumn": 16, - "problem": "ObjectTypeLiteral", - "autofix": [ - { - "start": 1682, - "end": 1682, - "replacementText": "interface GeneratedTypeLiteralInterface_5 {\n createdAt: Date;\n tags: string[];\n}\n" - }, - { - "start": 1837, - "end": 1889, - "replacementText": "GeneratedTypeLiteralInterface_5" - } - ], - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 106, - "column": 3, - "endLine": 106, - "endColumn": 34, - "problem": "ClassstaticInitialization", - "autofix": [ - { - "start": 1948, - "end": 1979, - "replacementText": "static uninitializedDate: Date = new Date();" - } - ], - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 107, - "column": 3, - "endLine": 107, - "endColumn": 48, - "problem": "ClassstaticInitialization", - "autofix": [ - { - "start": 1982, - "end": 2027, - "replacementText": "static uninitializedMap: Map = new Map();" - } - ], - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 108, - "column": 3, - "endLine": 108, - "endColumn": 40, - "problem": "ClassstaticInitialization", - "autofix": [ - { - "start": 2030, - "end": 2067, - "replacementText": "static uninitializedSet: Set = new Set();" - } - ], - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 109, - "column": 3, - "endLine": 109, - "endColumn": 46, - "problem": "ClassstaticInitialization", - "autofix": [ - { - "start": 2070, - "end": 2113, - "replacementText": "static uninitializedPromise: Promise = undefined;" - } - ], - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 114, - "column": 3, - "endLine": 114, - "endColumn": 46, - "problem": "ClassstaticInitialization", - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 115, - "column": 3, - "endLine": 115, - "endColumn": 72, - "problem": "ClassstaticInitialization", - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 115, - "column": 37, - "endLine": 115, - "endColumn": 71, - "problem": "IntersectionType", - "suggest": "", - "rule": "Use inheritance instead of intersection types (arkts-no-intersection-types)", - "severity": "ERROR" - }, - { - "line": 115, - "column": 37, - "endLine": 115, - "endColumn": 38, - "problem": "ObjectTypeLiteral", - "autofix": [ - { - "start": 2149, - "end": 2149, - "replacementText": "interface GeneratedTypeLiteralInterface_6 {\n name: string;\n}\n" - }, - { - "start": 2253, - "end": 2269, - "replacementText": "GeneratedTypeLiteralInterface_6" - } - ], - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 115, - "column": 56, - "endLine": 115, - "endColumn": 57, - "problem": "ObjectTypeLiteral", - "autofix": [ - { - "start": 2149, - "end": 2149, - "replacementText": "interface GeneratedTypeLiteralInterface_7 {\n age: number;\n}\n" - }, - { - "start": 2272, - "end": 2287, - "replacementText": "GeneratedTypeLiteralInterface_7" - } - ], - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 116, - "column": 3, - "endLine": 116, - "endColumn": 57, - "problem": "ClassstaticInitialization", - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 128, - "column": 3, - "endLine": 128, - "endColumn": 41, - "problem": "ClassstaticInitialization", - "autofix": [ - { - "start": 2567, - "end": 2605, - "replacementText": "static uninitializedGenericArray: T[] = [];" - } - ], - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 129, - "column": 3, - "endLine": 129, - "endColumn": 39, - "problem": "ClassstaticInitialization", - "autofix": [ - { - "start": 2608, - "end": 2644, - "replacementText": "static uninitializedGenericValue: T | undefined = undefined;" - } - ], - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 134, - "column": 3, - "endLine": 134, - "endColumn": 44, - "problem": "ClassstaticInitialization", - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 135, - "column": 3, - "endLine": 135, - "endColumn": 60, - "problem": "ClassstaticInitialization", - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 140, - "column": 3, - "endLine": 140, - "endColumn": 91, - "problem": "ClassstaticInitialization", - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 140, - "column": 43, - "endLine": 140, - "endColumn": 44, - "problem": "ObjectTypeLiteral", - "autofix": [ - { - "start": 2821, - "end": 2821, - "replacementText": "interface GeneratedTypeLiteralInterface_8 {\n id: number;\n data: Map>;\n}\n" - }, - { - "start": 2884, - "end": 2930, - "replacementText": "GeneratedTypeLiteralInterface_8" - } - ], - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 141, - "column": 3, - "endLine": 141, - "endColumn": 65, - "problem": "ClassstaticInitialization", - "autofix": [ - { - "start": 2935, - "end": 2997, - "replacementText": "static uninitializedRecord: Record | undefined = undefined;" - } - ], - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 141, - "column": 46, - "endLine": 141, - "endColumn": 47, - "problem": "ObjectTypeLiteral", - "autofix": [ - { - "start": 2821, - "end": 2821, - "replacementText": "interface GeneratedTypeLiteralInterface_9 {\n value: number;\n}\n" - }, - { - "start": 2978, - "end": 2995, - "replacementText": "GeneratedTypeLiteralInterface_9" - } - ], - "suggest": "", - "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", - "severity": "ERROR" - }, - { - "line": 142, - "column": 3, - "endLine": 142, - "endColumn": 57, - "problem": "ClassstaticInitialization", - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 152, - "column": 3, - "endLine": 152, - "endColumn": 34, - "problem": "ClassstaticInitialization", - "autofix": [ - { - "start": 3153, - "end": 3184, - "replacementText": "static uninitializedUser: User | undefined = undefined;" - } - ], - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 153, - "column": 3, - "endLine": 153, - "endColumn": 37, - "problem": "ClassstaticInitialization", - "autofix": [ - { - "start": 3187, - "end": 3221, - "replacementText": "static uninitializedUsers: User[] = [];" - } - ], - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 163, - "column": 3, - "endLine": 163, - "endColumn": 38, - "problem": "ClassstaticInitialization", - "autofix": [ - { - "start": 3297, - "end": 3332, - "replacementText": "static uninitializedStatus: Status | undefined = undefined;" - } - ], - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 164, - "column": 3, - "endLine": 164, - "endColumn": 45, - "problem": "ClassstaticInitialization", - "autofix": [ - { - "start": 3335, - "end": 3377, - "replacementText": "static uninitializedStatusArray: Status[] = [];" - } - ], - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 169, - "column": 3, - "endLine": 169, - "endColumn": 36, - "problem": "ClassstaticInitialization", - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 170, - "column": 3, - "endLine": 170, - "endColumn": 40, - "problem": "ClassstaticInitialization", - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 170, - "column": 32, - "endLine": 170, - "endColumn": 39, - "problem": "UnknownType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 171, - "column": 3, - "endLine": 171, - "endColumn": 32, - "problem": "ClassstaticInitialization", - "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", - "severity": "ERROR" - }, - { - "line": 171, - "column": 28, - "endLine": 171, - "endColumn": 31, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 42, - "column": 2, - "endLine": 42, - "endColumn": 7, - "problem": "UIInterfaceImport", - "autofix": [ - { - "start": 603, - "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Text } from '@kit.ArkUI';" - } - ], - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 43, - "column": 2, - "endLine": 43, - "endColumn": 11, - "problem": "UIInterfaceImport", - "autofix": [ - { - "start": 603, - "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Text } from '@kit.ArkUI';" - } - ], - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 45, - "column": 4, - "endLine": 45, - "endColumn": 9, - "problem": "UIInterfaceImport", - "autofix": [ - { - "start": 603, - "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Text } from '@kit.ArkUI';" - } - ], - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 49, - "column": 7, - "endLine": 49, - "endColumn": 11, - "problem": "UIInterfaceImport", - "autofix": [ - { - "start": 603, - "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Text } from '@kit.ArkUI';" - } - ], - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 147, - "column": 3, - "endLine": 147, - "endColumn": 5, - "problem": "StrictDiagnostic", - "suggest": "Property 'id' has no initializer and is not definitely assigned in the constructor.", - "rule": "Property 'id' has no initializer and is not definitely assigned in the constructor.", - "severity": "ERROR" - }, - { - "line": 148, - "column": 3, - "endLine": 148, - "endColumn": 7, - "problem": "StrictDiagnostic", - "suggest": "Property 'name' has no initializer and is not definitely assigned in the constructor.", - "rule": "Property 'name' has no initializer and is not definitely assigned in the constructor.", - "severity": "ERROR" - } - ] -} \ No newline at end of file diff --git a/ets2panda/linter/test/main/debugger_statememt.ets.migrate.ets b/ets2panda/linter/test/main/debugger_statememt.ets.migrate.ets deleted file mode 100644 index 04eeeb8969..0000000000 --- a/ets2panda/linter/test/main/debugger_statememt.ets.migrate.ets +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -specialAutofixLib.debugger(); - -function a() { - specialAutofixLib.debugger(); -} - -console.log('debugger'); \ No newline at end of file diff --git a/ets2panda/linter/test/main/debugger_statememt.ets.migrate.json b/ets2panda/linter/test/main/debugger_statememt.ets.migrate.json deleted file mode 100644 index ca88f857e9..0000000000 --- a/ets2panda/linter/test/main/debugger_statememt.ets.migrate.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "result": [] -} \ No newline at end of file diff --git a/ets2panda/linter/test/main/double_excla_binding_3.ets b/ets2panda/linter/test/main/double_excla_binding_3.ets index 4eff7d72ca..8c9dcc1e87 100644 --- a/ets2panda/linter/test/main/double_excla_binding_3.ets +++ b/ets2panda/linter/test/main/double_excla_binding_3.ets @@ -29,4 +29,4 @@ struct MyComponent { Text(this.user!!!.name) } } -} +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/global_this.ets.migrate.ets b/ets2panda/linter/test/main/global_this.ets.migrate.ets deleted file mode 100644 index d1fb5d519f..0000000000 --- a/ets2panda/linter/test/main/global_this.ets.migrate.ets +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2022-2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -const pi: number = 3.1416; - -function circleArea(r: number): number { - foo(globalThis); - - return specialAutofixLib.globalThis.get("pi") * r * r; -} - -function foo(x: any): void { - console.log(x.pi); -} - -specialAutofixLib.globalThis.set("abc", 200); - -const value = specialAutofixLib.globalThis.get("obj").prop; - -delete specialAutofixLib.globalThis.get("property"); - -globalThisprop = 100; - -specialAutofixLib.globalThis.get("pi"); - -specialAutofixLib.globalThis.set("pi",3.1416); - -specialAutofixLib.globalThis; - diff --git a/ets2panda/linter/test/main/global_this.ets.migrate.json b/ets2panda/linter/test/main/global_this.ets.migrate.json deleted file mode 100644 index cdc3cef837..0000000000 --- a/ets2panda/linter/test/main/global_this.ets.migrate.json +++ /dev/null @@ -1,58 +0,0 @@ -{ - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "result": [ - { - "line": 19, - "column": 7, - "endLine": 19, - "endColumn": 17, - "problem": "GlobalThisError", - "suggest": "", - "rule": "\"globalThis\" is not supported (arkts-no-globalthis)", - "severity": "ERROR" - }, - { - "line": 24, - "column": 17, - "endLine": 24, - "endColumn": 20, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 30, - "column": 7, - "endLine": 30, - "endColumn": 59, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 32, - "column": 1, - "endLine": 32, - "endColumn": 7, - "problem": "DeleteOperator", - "suggest": "", - "rule": "\"delete\" operator is not supported (arkts-no-delete)", - "severity": "ERROR" - } - ] -} \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets b/ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets deleted file mode 100644 index 7f83645b5e..0000000000 --- a/ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -class User { - name: string = "" - age: number = 0 -} - -@Entry -@Component -struct FatherComponent { - @Prop user1: User = new User() - @StorageLink("user2") user2: User = new User() - @LocalStorageLink("user3") user3: User = new User() - - build() { - } -} - -@Component -struct ChildComponent { - @StorageProp("user2") user2: User = new User() - @LocalStorageProp("user3") user3: User = new User() - - build() { - } -} \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets.args.json b/ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets.args.json deleted file mode 100644 index 4acc088d1d..0000000000 --- a/ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets.args.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "mode": { - "arkts2": "" - } -} \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets.arkts2.json b/ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets.arkts2.json deleted file mode 100644 index eda4a3c782..0000000000 --- a/ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets.arkts2.json +++ /dev/null @@ -1,128 +0,0 @@ -{ - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "result": [ - { - "line": 24, - "column": 3, - "endLine": 24, - "endColumn": 33, - "problem": "PropDecoratorsAndInterfacesAreNotSupported", - "suggest": "", - "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", - "severity": "ERROR" - }, - { - "line": 34, - "column": 3, - "endLine": 34, - "endColumn": 49, - "problem": "PropDecoratorsAndInterfacesAreNotSupported", - "suggest": "", - "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", - "severity": "ERROR" - }, - { - "line": 35, - "column": 3, - "endLine": 35, - "endColumn": 54, - "problem": "PropDecoratorsAndInterfacesAreNotSupported", - "suggest": "", - "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", - "severity": "ERROR" - }, - { - "line": 21, - "column": 2, - "endLine": 21, - "endColumn": 7, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 22, - "column": 2, - "endLine": 22, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 24, - "column": 4, - "endLine": 24, - "endColumn": 8, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 25, - "column": 4, - "endLine": 25, - "endColumn": 15, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 26, - "column": 4, - "endLine": 26, - "endColumn": 20, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 32, - "column": 2, - "endLine": 32, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 34, - "column": 4, - "endLine": 34, - "endColumn": 15, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 35, - "column": 4, - "endLine": 35, - "endColumn": 20, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - } - ] -} \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets.json b/ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets.json deleted file mode 100644 index ca88f857e9..0000000000 --- a/ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "result": [] -} \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets b/ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets deleted file mode 100644 index f218bde1db..0000000000 --- a/ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -class MyClassA { - -} - -let para: Record = { 'PropA': 47 } -let storage: LocalStorage = new LocalStorage(para) -let prop1 = storage.prop('PropA') -let prop2 = storage.prop('PropA') -let prop3 = storage.prop('PropA') -let prop4: SubscribedAbstractProperty = storage.prop('PropA') -let prop5: SubscribedAbstractProperty = storage.prop('PropA') -let prop6: SubscribedAbstractProperty = storage.prop('PropA') - -AppStorage.SetOrCreate('PropB', 46) -let prop7 = AppStorage.prop('PropB') -let prop8 = AppStorage.prop('PropB') -let prop9 = AppStorage.prop('PropB') -let prop10: SubscribedAbstractProperty = AppStorage.prop('PropB') -let prop11: SubscribedAbstractProperty = AppStorage.prop('PropB') -let prop12: SubscribedAbstractProperty = AppStorage.prop('PropB') - -@Entry -@Component -struct MyComponent { - - aboutToAppear(): void { - let storage = LocalStorage.getShared() - let prop1 = storage.prop('PropA') - let prop2: SubscribedAbstractProperty = storage.prop('PropA') - } - - build() { - } -} \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets.args.json b/ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets.args.json deleted file mode 100644 index 4acc088d1d..0000000000 --- a/ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets.args.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "mode": { - "arkts2": "" - } -} \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets.arkts2.json b/ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets.arkts2.json deleted file mode 100644 index a34c537148..0000000000 --- a/ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets.arkts2.json +++ /dev/null @@ -1,448 +0,0 @@ -{ - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "result": [ - { - "line": 21, - "column": 33, - "endLine": 21, - "endColumn": 45, - "problem": "DynamicCtorCall", - "suggest": "", - "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", - "severity": "ERROR" - }, - { - "line": 22, - "column": 5, - "endLine": 22, - "endColumn": 42, - "problem": "PropDecoratorsAndInterfacesAreNotSupported", - "suggest": "", - "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", - "severity": "ERROR" - }, - { - "line": 22, - "column": 5, - "endLine": 22, - "endColumn": 42, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 23, - "column": 5, - "endLine": 23, - "endColumn": 44, - "problem": "PropDecoratorsAndInterfacesAreNotSupported", - "suggest": "", - "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", - "severity": "ERROR" - }, - { - "line": 23, - "column": 5, - "endLine": 23, - "endColumn": 44, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 24, - "column": 5, - "endLine": 24, - "endColumn": 53, - "problem": "PropDecoratorsAndInterfacesAreNotSupported", - "suggest": "", - "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", - "severity": "ERROR" - }, - { - "line": 24, - "column": 5, - "endLine": 24, - "endColumn": 53, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 25, - "column": 5, - "endLine": 25, - "endColumn": 70, - "problem": "PropDecoratorsAndInterfacesAreNotSupported", - "suggest": "", - "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", - "severity": "ERROR" - }, - { - "line": 26, - "column": 5, - "endLine": 26, - "endColumn": 72, - "problem": "PropDecoratorsAndInterfacesAreNotSupported", - "suggest": "", - "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", - "severity": "ERROR" - }, - { - "line": 27, - "column": 5, - "endLine": 27, - "endColumn": 81, - "problem": "PropDecoratorsAndInterfacesAreNotSupported", - "suggest": "", - "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", - "severity": "ERROR" - }, - { - "line": 30, - "column": 5, - "endLine": 30, - "endColumn": 45, - "problem": "PropDecoratorsAndInterfacesAreNotSupported", - "suggest": "", - "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", - "severity": "ERROR" - }, - { - "line": 30, - "column": 5, - "endLine": 30, - "endColumn": 45, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 30, - "column": 13, - "endLine": 30, - "endColumn": 45, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 31, - "column": 5, - "endLine": 31, - "endColumn": 47, - "problem": "PropDecoratorsAndInterfacesAreNotSupported", - "suggest": "", - "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", - "severity": "ERROR" - }, - { - "line": 31, - "column": 5, - "endLine": 31, - "endColumn": 47, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 32, - "column": 5, - "endLine": 32, - "endColumn": 56, - "problem": "PropDecoratorsAndInterfacesAreNotSupported", - "suggest": "", - "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", - "severity": "ERROR" - }, - { - "line": 32, - "column": 5, - "endLine": 32, - "endColumn": 56, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 33, - "column": 5, - "endLine": 33, - "endColumn": 74, - "problem": "PropDecoratorsAndInterfacesAreNotSupported", - "suggest": "", - "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", - "severity": "ERROR" - }, - { - "line": 34, - "column": 5, - "endLine": 34, - "endColumn": 76, - "problem": "PropDecoratorsAndInterfacesAreNotSupported", - "suggest": "", - "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", - "severity": "ERROR" - }, - { - "line": 35, - "column": 5, - "endLine": 35, - "endColumn": 85, - "problem": "PropDecoratorsAndInterfacesAreNotSupported", - "suggest": "", - "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", - "severity": "ERROR" - }, - { - "line": 42, - "column": 13, - "endLine": 42, - "endColumn": 47, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 43, - "column": 13, - "endLine": 43, - "endColumn": 52, - "problem": "PropDecoratorsAndInterfacesAreNotSupported", - "suggest": "", - "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", - "severity": "ERROR" - }, - { - "line": 43, - "column": 13, - "endLine": 43, - "endColumn": 52, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 44, - "column": 13, - "endLine": 44, - "endColumn": 80, - "problem": "PropDecoratorsAndInterfacesAreNotSupported", - "suggest": "", - "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", - "severity": "ERROR" - }, - { - "line": 21, - "column": 14, - "endLine": 21, - "endColumn": 26, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 21, - "column": 33, - "endLine": 21, - "endColumn": 45, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 25, - "column": 12, - "endLine": 25, - "endColumn": 38, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 26, - "column": 12, - "endLine": 26, - "endColumn": 38, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 27, - "column": 12, - "endLine": 27, - "endColumn": 38, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 29, - "column": 1, - "endLine": 29, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 30, - "column": 13, - "endLine": 30, - "endColumn": 23, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 31, - "column": 13, - "endLine": 31, - "endColumn": 23, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 32, - "column": 13, - "endLine": 32, - "endColumn": 23, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 33, - "column": 13, - "endLine": 33, - "endColumn": 39, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 33, - "column": 50, - "endLine": 33, - "endColumn": 60, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 34, - "column": 13, - "endLine": 34, - "endColumn": 39, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 34, - "column": 52, - "endLine": 34, - "endColumn": 62, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 35, - "column": 13, - "endLine": 35, - "endColumn": 39, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 35, - "column": 61, - "endLine": 35, - "endColumn": 71, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 37, - "column": 2, - "endLine": 37, - "endColumn": 7, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 38, - "column": 2, - "endLine": 38, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 42, - "column": 23, - "endLine": 42, - "endColumn": 35, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 44, - "column": 20, - "endLine": 44, - "endColumn": 46, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - } - ] -} \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets.json b/ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets.json deleted file mode 100644 index 897276b6eb..0000000000 --- a/ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets.json +++ /dev/null @@ -1,98 +0,0 @@ -{ - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "result": [ - { - "line": 22, - "column": 5, - "endLine": 22, - "endColumn": 42, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 23, - "column": 5, - "endLine": 23, - "endColumn": 44, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 24, - "column": 5, - "endLine": 24, - "endColumn": 53, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 30, - "column": 5, - "endLine": 30, - "endColumn": 45, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 31, - "column": 5, - "endLine": 31, - "endColumn": 47, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 32, - "column": 5, - "endLine": 32, - "endColumn": 56, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 42, - "column": 13, - "endLine": 42, - "endColumn": 47, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 43, - "column": 13, - "endLine": 43, - "endColumn": 52, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - } - ] -} \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets b/ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets deleted file mode 100644 index 5a75d8e00d..0000000000 --- a/ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */1q - -class MyClassA { - -} - -class MyClassB { - -} - -function getClass1 { - let a = new MyClassA() - - if (1 > 0) { - return new MyClassB() - } else { - return a - } -} - -function getClass2 { - if (1 > 0) { - return 1 - } else { - return new MyClassA() - } -} - -let para: Record = { 'PropA': 47 } -let storage: LocalStorage = new LocalStorage(para) -let prop1 = storage.setAndProp('PropA', getClass1()) -let prop2 = storage.setAndProp('PropA', getClass2()) -let prop3 = storage.setAndProp('PropA', {name: "jack", age: 2}) -let prop4 = storage.setAndProp('PropA', 1 > 0 ? 1 : getClass1()) -let prop5 = storage.setAndProp('PropA', 1 > 0 ? {name: "jack"} : "test") -let prop6 = storage.setAndProp('PropA', new MyClassA()) -let prop7 = storage.setAndProp('PropA', 1) -let prop8 = storage.setAndProp('PropA', "test") -let prop9 = storage.setAndProp('PropA', true) - -@Entry -@Component -struct MyComponent { - build() { - } -} \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets.args.json b/ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets.args.json deleted file mode 100644 index 4acc088d1d..0000000000 --- a/ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets.args.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "mode": { - "arkts2": "" - } -} \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets.arkts2.json b/ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets.arkts2.json deleted file mode 100644 index aae50874a9..0000000000 --- a/ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets.arkts2.json +++ /dev/null @@ -1,248 +0,0 @@ -{ - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "result": [ - { - "line": 43, - "column": 33, - "endLine": 43, - "endColumn": 45, - "problem": "DynamicCtorCall", - "suggest": "", - "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", - "severity": "ERROR" - }, - { - "line": 44, - "column": 5, - "endLine": 44, - "endColumn": 53, - "problem": "PropDecoratorsAndInterfacesAreNotSupported", - "suggest": "", - "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", - "severity": "ERROR" - }, - { - "line": 44, - "column": 5, - "endLine": 44, - "endColumn": 53, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 45, - "column": 5, - "endLine": 45, - "endColumn": 53, - "problem": "PropDecoratorsAndInterfacesAreNotSupported", - "suggest": "", - "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", - "severity": "ERROR" - }, - { - "line": 45, - "column": 5, - "endLine": 45, - "endColumn": 53, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 46, - "column": 5, - "endLine": 46, - "endColumn": 64, - "problem": "PropDecoratorsAndInterfacesAreNotSupported", - "suggest": "", - "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", - "severity": "ERROR" - }, - { - "line": 46, - "column": 5, - "endLine": 46, - "endColumn": 64, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 47, - "column": 5, - "endLine": 47, - "endColumn": 65, - "problem": "PropDecoratorsAndInterfacesAreNotSupported", - "suggest": "", - "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", - "severity": "ERROR" - }, - { - "line": 47, - "column": 5, - "endLine": 47, - "endColumn": 65, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 48, - "column": 5, - "endLine": 48, - "endColumn": 73, - "problem": "PropDecoratorsAndInterfacesAreNotSupported", - "suggest": "", - "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", - "severity": "ERROR" - }, - { - "line": 48, - "column": 5, - "endLine": 48, - "endColumn": 73, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 49, - "column": 5, - "endLine": 49, - "endColumn": 56, - "problem": "PropDecoratorsAndInterfacesAreNotSupported", - "suggest": "", - "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", - "severity": "ERROR" - }, - { - "line": 49, - "column": 5, - "endLine": 49, - "endColumn": 56, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 50, - "column": 5, - "endLine": 50, - "endColumn": 43, - "problem": "PropDecoratorsAndInterfacesAreNotSupported", - "suggest": "", - "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", - "severity": "ERROR" - }, - { - "line": 50, - "column": 5, - "endLine": 50, - "endColumn": 43, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 51, - "column": 5, - "endLine": 51, - "endColumn": 48, - "problem": "PropDecoratorsAndInterfacesAreNotSupported", - "suggest": "", - "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", - "severity": "ERROR" - }, - { - "line": 51, - "column": 5, - "endLine": 51, - "endColumn": 48, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 52, - "column": 5, - "endLine": 52, - "endColumn": 46, - "problem": "PropDecoratorsAndInterfacesAreNotSupported", - "suggest": "", - "rule": "The \"Prop\", \"StorageProp\", and \"LocalStorageProp\" decorators, as well as the \"prop\" and \"setAndProp\" interfaces, are not supported (arkui-no-specific-prop-decorators-and-interfaces)", - "severity": "ERROR" - }, - { - "line": 52, - "column": 5, - "endLine": 52, - "endColumn": 46, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 43, - "column": 14, - "endLine": 43, - "endColumn": 26, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 43, - "column": 33, - "endLine": 43, - "endColumn": 45, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 54, - "column": 2, - "endLine": 54, - "endColumn": 7, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - }, - { - "line": 55, - "column": 2, - "endLine": 55, - "endColumn": 11, - "problem": "UIInterfaceImport", - "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", - "severity": "ERROR" - } - ] -} \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets.json b/ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets.json deleted file mode 100644 index de7a4258a1..0000000000 --- a/ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets.json +++ /dev/null @@ -1,108 +0,0 @@ -{ - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "result": [ - { - "line": 44, - "column": 5, - "endLine": 44, - "endColumn": 53, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 45, - "column": 5, - "endLine": 45, - "endColumn": 53, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 46, - "column": 5, - "endLine": 46, - "endColumn": 64, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 47, - "column": 5, - "endLine": 47, - "endColumn": 65, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 48, - "column": 5, - "endLine": 48, - "endColumn": 73, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 49, - "column": 5, - "endLine": 49, - "endColumn": 56, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 50, - "column": 5, - "endLine": 50, - "endColumn": 43, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 51, - "column": 5, - "endLine": 51, - "endColumn": 48, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 52, - "column": 5, - "endLine": 52, - "endColumn": 46, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - } - ] -} \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_name_from_value.ets b/ets2panda/linter/test/main/prop_name_from_value.ets deleted file mode 100644 index bdfdc1a80d..0000000000 --- a/ets2panda/linter/test/main/prop_name_from_value.ets +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -enum TEST { - A, - B, - C -} -const arr = ['a', 'b', 'c']; - -const val = TEST[1]; -const value: number = TEST.A; //legal -const arrVal = arr[1]; //legal \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_name_from_value.ets.args.json b/ets2panda/linter/test/main/prop_name_from_value.ets.args.json deleted file mode 100644 index 66fb88f859..0000000000 --- a/ets2panda/linter/test/main/prop_name_from_value.ets.args.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "mode": { - "arkts2": "" - } -} diff --git a/ets2panda/linter/test/main/prop_name_from_value.ets.arkts2.json b/ets2panda/linter/test/main/prop_name_from_value.ets.arkts2.json deleted file mode 100644 index 4218268d31..0000000000 --- a/ets2panda/linter/test/main/prop_name_from_value.ets.arkts2.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "result": [ - { - "line": 23, - "column": 13, - "endLine": 23, - "endColumn": 20, - "problem": "UnsupportPropNameFromValue", - "suggest": "", - "rule": "Enum cannot get member name by member value (arkts-unsupport-prop-name-from-value)", - "severity": "ERROR" - } - ] -} \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_name_from_value.ets.json b/ets2panda/linter/test/main/prop_name_from_value.ets.json deleted file mode 100644 index ca88f857e9..0000000000 --- a/ets2panda/linter/test/main/prop_name_from_value.ets.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License." - ], - "result": [] -} \ No newline at end of file -- Gitee From 2c6d07aa92a5ed01aeb20c18a039b2b32bdd51b8 Mon Sep 17 00:00:00 2001 From: tengtengh Date: Fri, 11 Jul 2025 23:15:01 +0800 Subject: [PATCH 263/268] cover ets2panda/ir with 0328 Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICLSLO Signed-off-by: tengtengh --- ets2panda/ir/ets/etsNewArrayInstanceExpression.h | 16 ---------------- .../ets/etsNewMultiDimArrayInstanceExpression.h | 16 ---------------- 2 files changed, 32 deletions(-) diff --git a/ets2panda/ir/ets/etsNewArrayInstanceExpression.h b/ets2panda/ir/ets/etsNewArrayInstanceExpression.h index 4d5b374cbb..002a1cb1a6 100644 --- a/ets2panda/ir/ets/etsNewArrayInstanceExpression.h +++ b/ets2panda/ir/ets/etsNewArrayInstanceExpression.h @@ -75,21 +75,6 @@ public: return defaultConstructorSignature_; } - void SetPreferredType(checker::Type *preferredType) noexcept - { - preferredType_ = preferredType; - } - - [[nodiscard]] checker::Type *GetPreferredType() noexcept - { - return preferredType_; - } - - [[nodiscard]] checker::Type const *GetPreferredType() const noexcept - { - return preferredType_; - } - void SetDimension(ir::Expression *dimension) noexcept { dimension_ = dimension; @@ -134,7 +119,6 @@ private: ir::TypeNode *typeReference_; ir::Expression *dimension_; checker::Signature *defaultConstructorSignature_ {}; - checker::Type *preferredType_ {}; }; } // namespace ark::es2panda::ir diff --git a/ets2panda/ir/ets/etsNewMultiDimArrayInstanceExpression.h b/ets2panda/ir/ets/etsNewMultiDimArrayInstanceExpression.h index 0ea4253904..20d8be5d48 100644 --- a/ets2panda/ir/ets/etsNewMultiDimArrayInstanceExpression.h +++ b/ets2panda/ir/ets/etsNewMultiDimArrayInstanceExpression.h @@ -79,21 +79,6 @@ public: return signature_; } - [[nodiscard]] checker::Type *GetPreferredType() noexcept - { - return preferredType_; - } - - [[nodiscard]] checker::Type const *GetPreferredType() const noexcept - { - return preferredType_; - } - - void SetPreferredType(checker::Type *preferredType) noexcept - { - preferredType_ = preferredType; - } - void SetSignature(checker::Signature *signature) noexcept { signature_ = signature; @@ -131,7 +116,6 @@ private: ir::TypeNode *typeReference_; ArenaVector dimensions_; checker::Signature *signature_ {}; - checker::Type *preferredType_ {}; }; } // namespace ark::es2panda::ir -- Gitee From 5e573ae29e785ed1f40f2c2dcd27381089a4bf94 Mon Sep 17 00:00:00 2001 From: tengtengh Date: Sat, 12 Jul 2025 00:10:57 +0800 Subject: [PATCH 264/268] cover ets2panda/test with 0328 Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICLSLO Signed-off-by: tengtengh --- .../Readonly-with-ArrayType-test2.ets | 4 +- .../Readonly-with-ArrayType-test3.ets | 2 +- .../readonly-parameter-test2.ets | 2 +- .../ets/rethrowingCheck1-expected.txt | 787 ----- .../ets/rethrowingCheck4-expected.txt | 926 ------ .../rethrowingConstructorCheck3-expected.txt | 853 ------ .../ets/rethrowingFunctionCheck3-expected.txt | 754 ----- .../ets/rethrowingMethodCheck3-expected.txt | 1056 ------- .../throwInRethrowingFunction2-expected.txt | 662 ----- .../ets/throwInThrowingFunction-expected.txt | 480 --- .../throwingFunctionAsParameter1-expected.txt | 835 ------ .../ets/throwingFunctionCheck2-expected.txt | 809 ------ .../ets/throwingFunctionCheck3-expected.txt | 1154 -------- .../ets/throwingFunctionCheck6-expected.txt | 1180 -------- .../ets/throwingFunctionType1-expected.txt | 654 ----- .../constructorThrowsRethrows-expected.txt | 753 ----- .../ets/functionThrowsRethrows-expected.txt | 809 ------ .../ets/functionTypeThrows-expected.txt | 446 --- .../ets/lambdaThrowsRethrows-expected.txt | 974 ------- .../ets/methodThrowsRethrows-expected.txt | 838 ------ .../ets/method_override_throw_1-expected.txt | 2575 ----------------- .../parser/ets/rethrow-func-1-expected.txt | 1309 --------- .../throwsRethrowsAsVariables-expected.txt | 829 ------ .../trailing_lambda_with_throw-expected.txt | 817 ------ .../variable_throw_function_1-expected.txt | 1087 ------- .../test/runtime/ets/UnaryExpression.ets | 20 - .../use_plugin_to_test_export_table.cpp | 163 -- 27 files changed, 4 insertions(+), 20774 deletions(-) delete mode 100644 ets2panda/test/compiler/ets/rethrowingCheck1-expected.txt delete mode 100644 ets2panda/test/compiler/ets/rethrowingCheck4-expected.txt delete mode 100644 ets2panda/test/compiler/ets/rethrowingConstructorCheck3-expected.txt delete mode 100644 ets2panda/test/compiler/ets/rethrowingFunctionCheck3-expected.txt delete mode 100644 ets2panda/test/compiler/ets/rethrowingMethodCheck3-expected.txt delete mode 100644 ets2panda/test/compiler/ets/throwInRethrowingFunction2-expected.txt delete mode 100644 ets2panda/test/compiler/ets/throwInThrowingFunction-expected.txt delete mode 100644 ets2panda/test/compiler/ets/throwingFunctionAsParameter1-expected.txt delete mode 100644 ets2panda/test/compiler/ets/throwingFunctionCheck2-expected.txt delete mode 100644 ets2panda/test/compiler/ets/throwingFunctionCheck3-expected.txt delete mode 100644 ets2panda/test/compiler/ets/throwingFunctionCheck6-expected.txt delete mode 100644 ets2panda/test/compiler/ets/throwingFunctionType1-expected.txt delete mode 100644 ets2panda/test/parser/ets/constructorThrowsRethrows-expected.txt delete mode 100644 ets2panda/test/parser/ets/functionThrowsRethrows-expected.txt delete mode 100644 ets2panda/test/parser/ets/functionTypeThrows-expected.txt delete mode 100644 ets2panda/test/parser/ets/lambdaThrowsRethrows-expected.txt delete mode 100644 ets2panda/test/parser/ets/methodThrowsRethrows-expected.txt delete mode 100644 ets2panda/test/parser/ets/method_override_throw_1-expected.txt delete mode 100644 ets2panda/test/parser/ets/rethrow-func-1-expected.txt delete mode 100644 ets2panda/test/parser/ets/throwsRethrowsAsVariables-expected.txt delete mode 100644 ets2panda/test/parser/ets/trailing_lambda_tests/trailing_lambda_with_throw-expected.txt delete mode 100644 ets2panda/test/parser/ets/variable_throw_function_1-expected.txt delete mode 100644 ets2panda/test/unit/plugin/use_plugin_to_test_export_table.cpp diff --git a/ets2panda/test/ast/parser/ets/readonly-parameter-test/Readonly-with-ArrayType-test2.ets b/ets2panda/test/ast/parser/ets/readonly-parameter-test/Readonly-with-ArrayType-test2.ets index 7fbea40572..7656872082 100644 --- a/ets2panda/test/ast/parser/ets/readonly-parameter-test/Readonly-with-ArrayType-test2.ets +++ b/ets2panda/test/ast/parser/ets/readonly-parameter-test/Readonly-with-ArrayType-test2.ets @@ -19,5 +19,5 @@ function foo (p: [int, string]) { let x: Readonly<[int, string]> = [] /* @@ label */foo(/* @@ label1 */x) -/* @@@ label1 Error TypeError: Type 'readonly [int, String]' is not compatible with type '[int, String]' at index 1 */ -/* @@@ label Error TypeError: No matching call signature for foo(readonly [int, String]) */ +/* @@@ label1 Error TypeError: Type 'readonly [Int, String]' is not compatible with type '[Int, String]' at index 1 */ +/* @@@ label Error TypeError: No matching call signature for foo(readonly [Int, String]) */ diff --git a/ets2panda/test/ast/parser/ets/readonly-parameter-test/Readonly-with-ArrayType-test3.ets b/ets2panda/test/ast/parser/ets/readonly-parameter-test/Readonly-with-ArrayType-test3.ets index 0953054d47..1d321b90e4 100644 --- a/ets2panda/test/ast/parser/ets/readonly-parameter-test/Readonly-with-ArrayType-test3.ets +++ b/ets2panda/test/ast/parser/ets/readonly-parameter-test/Readonly-with-ArrayType-test3.ets @@ -17,4 +17,4 @@ function foo (x: Readonly<[int, string]>) { let y: [int, string] = /* @@ label */x } -/* @@@ label Error TypeError: Type 'readonly [int, String]' cannot be assigned to type '[int, String]' */ +/* @@@ label Error TypeError: Type 'readonly [Int, String]' cannot be assigned to type '[Int, String]' */ diff --git a/ets2panda/test/ast/parser/ets/readonly-parameter-test/readonly-parameter-test2.ets b/ets2panda/test/ast/parser/ets/readonly-parameter-test/readonly-parameter-test2.ets index fd6e6d8419..12e4c37fed 100644 --- a/ets2panda/test/ast/parser/ets/readonly-parameter-test/readonly-parameter-test2.ets +++ b/ets2panda/test/ast/parser/ets/readonly-parameter-test/readonly-parameter-test2.ets @@ -18,4 +18,4 @@ function foo (x: readonly [int, string]) { let y: [int, string] = /* @@ label */x } -/* @@@ label Error TypeError: Type 'readonly [int, String]' cannot be assigned to type '[int, String]' */ +/* @@@ label Error TypeError: Type 'readonly [Int, String]' cannot be assigned to type '[Int, String]' */ diff --git a/ets2panda/test/compiler/ets/rethrowingCheck1-expected.txt b/ets2panda/test/compiler/ets/rethrowingCheck1-expected.txt deleted file mode 100644 index c971b8965f..0000000000 --- a/ets2panda/test/compiler/ets/rethrowingCheck1-expected.txt +++ /dev/null @@ -1,787 +0,0 @@ -{ - "type": "Program", - "statements": [ - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "ETSGLOBAL", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrowingCheck1.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrowingCheck1.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrowingCheck1.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "foo", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 16, - "column": 13, - "program": "rethrowingCheck1.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "foo", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 16, - "column": 13, - "program": "rethrowingCheck1.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "ThrowStatement", - "argument": { - "type": "ETSNewClassInstanceExpression", - "typeReference": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "Exception", - "decorators": [], - "loc": { - "start": { - "line": 17, - "column": 15, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 17, - "column": 24, - "program": "rethrowingCheck1.ets" - } - } - }, - "loc": { - "start": { - "line": 17, - "column": 15, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 17, - "column": 25, - "program": "rethrowingCheck1.ets" - } - } - }, - "loc": { - "start": { - "line": 17, - "column": 15, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 17, - "column": 25, - "program": "rethrowingCheck1.ets" - } - } - }, - "arguments": [ - { - "type": "StringLiteral", - "value": "I am an exception", - "loc": { - "start": { - "line": 17, - "column": 25, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 17, - "column": 44, - "program": "rethrowingCheck1.ets" - } - } - } - ], - "loc": { - "start": { - "line": 17, - "column": 11, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 17, - "column": 46, - "program": "rethrowingCheck1.ets" - } - } - }, - "loc": { - "start": { - "line": 17, - "column": 5, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 17, - "column": 46, - "program": "rethrowingCheck1.ets" - } - } - } - ], - "loc": { - "start": { - "line": 16, - "column": 23, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 18, - "column": 2, - "program": "rethrowingCheck1.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 18, - "column": 2, - "program": "rethrowingCheck1.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 18, - "column": 2, - "program": "rethrowingCheck1.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 1, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 18, - "column": 2, - "program": "rethrowingCheck1.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "bar", - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 20, - "column": 13, - "program": "rethrowingCheck1.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "bar", - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 20, - "column": 13, - "program": "rethrowingCheck1.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "a", - "typeAnnotation": { - "type": "ETSFunctionType", - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 20, - "column": 23, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 20, - "column": 27, - "program": "rethrowingCheck1.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 20, - "column": 17, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 20, - "column": 27, - "program": "rethrowingCheck1.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 14, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 20, - "column": 27, - "program": "rethrowingCheck1.ets" - } - } - }, - "loc": { - "start": { - "line": 20, - "column": 14, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 20, - "column": 27, - "program": "rethrowingCheck1.ets" - } - } - } - ], - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "TryStatement", - "block": { - "type": "BlockStatement", - "statements": [ - { - "type": "ExpressionStatement", - "expression": { - "type": "CallExpression", - "callee": { - "type": "Identifier", - "name": "foo", - "decorators": [], - "loc": { - "start": { - "line": 22, - "column": 9, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 22, - "column": 12, - "program": "rethrowingCheck1.ets" - } - } - }, - "arguments": [], - "optional": false, - "loc": { - "start": { - "line": 22, - "column": 9, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 22, - "column": 14, - "program": "rethrowingCheck1.ets" - } - } - }, - "loc": { - "start": { - "line": 22, - "column": 9, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 22, - "column": 15, - "program": "rethrowingCheck1.ets" - } - } - } - ], - "loc": { - "start": { - "line": 21, - "column": 9, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 23, - "column": 6, - "program": "rethrowingCheck1.ets" - } - } - }, - "handler": [ - { - "type": "CatchClause", - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 23, - "column": 17, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 25, - "column": 6, - "program": "rethrowingCheck1.ets" - } - } - }, - "param": { - "type": "Identifier", - "name": "e", - "decorators": [], - "loc": { - "start": { - "line": 23, - "column": 14, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 23, - "column": 15, - "program": "rethrowingCheck1.ets" - } - } - }, - "loc": { - "start": { - "line": 23, - "column": 7, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 25, - "column": 6, - "program": "rethrowingCheck1.ets" - } - } - } - ], - "finalizer": null, - "loc": { - "start": { - "line": 21, - "column": 5, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 25, - "column": 6, - "program": "rethrowingCheck1.ets" - } - } - } - ], - "loc": { - "start": { - "line": 20, - "column": 45, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 26, - "column": 2, - "program": "rethrowingCheck1.ets" - } - } - }, - "throwMarker": "rethrows", - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 26, - "column": 2, - "program": "rethrowingCheck1.ets" - } - } - }, - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 26, - "column": 2, - "program": "rethrowingCheck1.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 1, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 26, - "column": 2, - "program": "rethrowingCheck1.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrowingCheck1.ets" - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrowingCheck1.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingCheck1.ets" - }, - "end": { - "line": 27, - "column": 1, - "program": "rethrowingCheck1.ets" - } - } -} diff --git a/ets2panda/test/compiler/ets/rethrowingCheck4-expected.txt b/ets2panda/test/compiler/ets/rethrowingCheck4-expected.txt deleted file mode 100644 index ffd83cec5b..0000000000 --- a/ets2panda/test/compiler/ets/rethrowingCheck4-expected.txt +++ /dev/null @@ -1,926 +0,0 @@ -{ - "type": "Program", - "statements": [ - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "ETSGLOBAL", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrowingCheck4.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrowingCheck4.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrowingCheck4.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "b", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 16, - "column": 11, - "program": "rethrowingCheck4.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "b", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 16, - "column": 11, - "program": "rethrowingCheck4.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "foo", - "typeAnnotation": { - "type": "ETSFunctionType", - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 16, - "column": 23, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 16, - "column": 27, - "program": "rethrowingCheck4.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 16, - "column": 17, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 16, - "column": 27, - "program": "rethrowingCheck4.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 12, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 16, - "column": 27, - "program": "rethrowingCheck4.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 12, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 16, - "column": 27, - "program": "rethrowingCheck4.ets" - } - } - } - ], - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "ExpressionStatement", - "expression": { - "type": "CallExpression", - "callee": { - "type": "Identifier", - "name": "foo", - "decorators": [], - "loc": { - "start": { - "line": 17, - "column": 5, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 17, - "column": 8, - "program": "rethrowingCheck4.ets" - } - } - }, - "arguments": [], - "optional": false, - "loc": { - "start": { - "line": 17, - "column": 5, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 17, - "column": 10, - "program": "rethrowingCheck4.ets" - } - } - }, - "loc": { - "start": { - "line": 17, - "column": 5, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 17, - "column": 11, - "program": "rethrowingCheck4.ets" - } - } - } - ], - "loc": { - "start": { - "line": 16, - "column": 45, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 18, - "column": 2, - "program": "rethrowingCheck4.ets" - } - } - }, - "throwMarker": "rethrows", - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 18, - "column": 2, - "program": "rethrowingCheck4.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 18, - "column": 2, - "program": "rethrowingCheck4.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 1, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 18, - "column": 2, - "program": "rethrowingCheck4.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "foo", - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 20, - "column": 13, - "program": "rethrowingCheck4.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "foo", - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 20, - "column": 13, - "program": "rethrowingCheck4.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "ThrowStatement", - "argument": { - "type": "ETSNewClassInstanceExpression", - "typeReference": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "Exception", - "decorators": [], - "loc": { - "start": { - "line": 21, - "column": 15, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 21, - "column": 24, - "program": "rethrowingCheck4.ets" - } - } - }, - "loc": { - "start": { - "line": 21, - "column": 15, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 21, - "column": 25, - "program": "rethrowingCheck4.ets" - } - } - }, - "loc": { - "start": { - "line": 21, - "column": 15, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 21, - "column": 25, - "program": "rethrowingCheck4.ets" - } - } - }, - "arguments": [ - { - "type": "StringLiteral", - "value": "I am an exception", - "loc": { - "start": { - "line": 21, - "column": 25, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 21, - "column": 44, - "program": "rethrowingCheck4.ets" - } - } - } - ], - "loc": { - "start": { - "line": 21, - "column": 11, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 21, - "column": 46, - "program": "rethrowingCheck4.ets" - } - } - }, - "loc": { - "start": { - "line": 21, - "column": 5, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 21, - "column": 46, - "program": "rethrowingCheck4.ets" - } - } - } - ], - "loc": { - "start": { - "line": 20, - "column": 23, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 22, - "column": 2, - "program": "rethrowingCheck4.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 22, - "column": 2, - "program": "rethrowingCheck4.ets" - } - } - }, - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 22, - "column": 2, - "program": "rethrowingCheck4.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 1, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 22, - "column": 2, - "program": "rethrowingCheck4.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "bar", - "decorators": [], - "loc": { - "start": { - "line": 24, - "column": 10, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 24, - "column": 13, - "program": "rethrowingCheck4.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "bar", - "decorators": [], - "loc": { - "start": { - "line": 24, - "column": 10, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 24, - "column": 13, - "program": "rethrowingCheck4.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "b", - "typeAnnotation": { - "type": "ETSFunctionType", - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 24, - "column": 23, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 24, - "column": 27, - "program": "rethrowingCheck4.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 24, - "column": 17, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 24, - "column": 27, - "program": "rethrowingCheck4.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 24, - "column": 14, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 24, - "column": 27, - "program": "rethrowingCheck4.ets" - } - } - }, - "loc": { - "start": { - "line": 24, - "column": 14, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 24, - "column": 27, - "program": "rethrowingCheck4.ets" - } - } - } - ], - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "ExpressionStatement", - "expression": { - "type": "CallExpression", - "callee": { - "type": "Identifier", - "name": "b", - "decorators": [], - "loc": { - "start": { - "line": 25, - "column": 5, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 25, - "column": 6, - "program": "rethrowingCheck4.ets" - } - } - }, - "arguments": [], - "optional": false, - "loc": { - "start": { - "line": 25, - "column": 5, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 25, - "column": 8, - "program": "rethrowingCheck4.ets" - } - } - }, - "loc": { - "start": { - "line": 25, - "column": 5, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 25, - "column": 9, - "program": "rethrowingCheck4.ets" - } - } - } - ], - "loc": { - "start": { - "line": 24, - "column": 45, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 26, - "column": 2, - "program": "rethrowingCheck4.ets" - } - } - }, - "throwMarker": "rethrows", - "loc": { - "start": { - "line": 24, - "column": 10, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 26, - "column": 2, - "program": "rethrowingCheck4.ets" - } - } - }, - "loc": { - "start": { - "line": 24, - "column": 10, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 26, - "column": 2, - "program": "rethrowingCheck4.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 24, - "column": 1, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 26, - "column": 2, - "program": "rethrowingCheck4.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrowingCheck4.ets" - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrowingCheck4.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingCheck4.ets" - }, - "end": { - "line": 27, - "column": 1, - "program": "rethrowingCheck4.ets" - } - } -} diff --git a/ets2panda/test/compiler/ets/rethrowingConstructorCheck3-expected.txt b/ets2panda/test/compiler/ets/rethrowingConstructorCheck3-expected.txt deleted file mode 100644 index 1a0939cc0c..0000000000 --- a/ets2panda/test/compiler/ets/rethrowingConstructorCheck3-expected.txt +++ /dev/null @@ -1,853 +0,0 @@ -{ - "type": "Program", - "statements": [ - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "TestClass", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 7, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 16, - "column": 16, - "program": "rethrowingConstructorCheck3.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "constructor", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "constructor", - "accessibility": "public", - "static": false, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "constructor", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "f", - "typeAnnotation": { - "type": "ETSFunctionType", - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 17, - "column": 24, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 17, - "column": 28, - "program": "rethrowingConstructorCheck3.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 17, - "column": 18, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 17, - "column": 28, - "program": "rethrowingConstructorCheck3.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 17, - "column": 15, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 17, - "column": 28, - "program": "rethrowingConstructorCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 17, - "column": 15, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 17, - "column": 28, - "program": "rethrowingConstructorCheck3.ets" - } - } - } - ], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 17, - "column": 46, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 17, - "column": 48, - "program": "rethrowingConstructorCheck3.ets" - } - } - }, - "throwMarker": "rethrows", - "loc": { - "start": { - "line": 17, - "column": 14, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 17, - "column": 48, - "program": "rethrowingConstructorCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 17, - "column": 14, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 17, - "column": 48, - "program": "rethrowingConstructorCheck3.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 17, - "column": 3, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 17, - "column": 48, - "program": "rethrowingConstructorCheck3.ets" - } - } - } - ], - "loc": { - "start": { - "line": 16, - "column": 17, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 20, - "column": 9, - "program": "rethrowingConstructorCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 1, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 20, - "column": 9, - "program": "rethrowingConstructorCheck3.ets" - } - } - }, - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "ETSGLOBAL", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrowingConstructorCheck3.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrowingConstructorCheck3.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "TestFunction", - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 20, - "column": 22, - "program": "rethrowingConstructorCheck3.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "TestFunction", - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 20, - "column": 22, - "program": "rethrowingConstructorCheck3.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 20, - "column": 26, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 20, - "column": 30, - "program": "rethrowingConstructorCheck3.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 20, - "column": 38, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 20, - "column": 40, - "program": "rethrowingConstructorCheck3.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 20, - "column": 40, - "program": "rethrowingConstructorCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 20, - "column": 40, - "program": "rethrowingConstructorCheck3.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 1, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 20, - "column": 40, - "program": "rethrowingConstructorCheck3.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 22, - "column": 10, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 22, - "column": 14, - "program": "rethrowingConstructorCheck3.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 22, - "column": 10, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 22, - "column": 14, - "program": "rethrowingConstructorCheck3.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 22, - "column": 18, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 22, - "column": 22, - "program": "rethrowingConstructorCheck3.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "TryStatement", - "block": { - "type": "BlockStatement", - "statements": [ - { - "type": "VariableDeclaration", - "declarations": [ - { - "type": "VariableDeclarator", - "id": { - "type": "Identifier", - "name": "a", - "decorators": [], - "loc": { - "start": { - "line": 24, - "column": 9, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 24, - "column": 10, - "program": "rethrowingConstructorCheck3.ets" - } - } - }, - "init": { - "type": "ETSNewClassInstanceExpression", - "typeReference": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "TestClass", - "decorators": [], - "loc": { - "start": { - "line": 24, - "column": 17, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 24, - "column": 26, - "program": "rethrowingConstructorCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 24, - "column": 17, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 24, - "column": 27, - "program": "rethrowingConstructorCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 24, - "column": 17, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 24, - "column": 27, - "program": "rethrowingConstructorCheck3.ets" - } - } - }, - "arguments": [ - { - "type": "Identifier", - "name": "TestFunction", - "decorators": [], - "loc": { - "start": { - "line": 24, - "column": 27, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 24, - "column": 39, - "program": "rethrowingConstructorCheck3.ets" - } - } - } - ], - "loc": { - "start": { - "line": 24, - "column": 13, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 24, - "column": 41, - "program": "rethrowingConstructorCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 24, - "column": 9, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 24, - "column": 41, - "program": "rethrowingConstructorCheck3.ets" - } - } - } - ], - "kind": "let", - "loc": { - "start": { - "line": 24, - "column": 5, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 24, - "column": 41, - "program": "rethrowingConstructorCheck3.ets" - } - } - } - ], - "loc": { - "start": { - "line": 23, - "column": 7, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 25, - "column": 4, - "program": "rethrowingConstructorCheck3.ets" - } - } - }, - "handler": [ - { - "type": "CatchClause", - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 25, - "column": 15, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 25, - "column": 17, - "program": "rethrowingConstructorCheck3.ets" - } - } - }, - "param": { - "type": "Identifier", - "name": "e", - "decorators": [], - "loc": { - "start": { - "line": 25, - "column": 12, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 25, - "column": 13, - "program": "rethrowingConstructorCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 25, - "column": 5, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 25, - "column": 17, - "program": "rethrowingConstructorCheck3.ets" - } - } - } - ], - "finalizer": null, - "loc": { - "start": { - "line": 23, - "column": 3, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 25, - "column": 17, - "program": "rethrowingConstructorCheck3.ets" - } - } - } - ], - "loc": { - "start": { - "line": 22, - "column": 23, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 26, - "column": 2, - "program": "rethrowingConstructorCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 22, - "column": 10, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 26, - "column": 2, - "program": "rethrowingConstructorCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 22, - "column": 10, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 26, - "column": 2, - "program": "rethrowingConstructorCheck3.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 22, - "column": 1, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 26, - "column": 2, - "program": "rethrowingConstructorCheck3.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrowingConstructorCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrowingConstructorCheck3.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingConstructorCheck3.ets" - }, - "end": { - "line": 27, - "column": 1, - "program": "rethrowingConstructorCheck3.ets" - } - } -} diff --git a/ets2panda/test/compiler/ets/rethrowingFunctionCheck3-expected.txt b/ets2panda/test/compiler/ets/rethrowingFunctionCheck3-expected.txt deleted file mode 100644 index 811fac12b9..0000000000 --- a/ets2panda/test/compiler/ets/rethrowingFunctionCheck3-expected.txt +++ /dev/null @@ -1,754 +0,0 @@ -{ - "type": "Program", - "statements": [ - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "ETSGLOBAL", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrowingFunctionCheck3.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrowingFunctionCheck3.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "TestFunction", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 16, - "column": 22, - "program": "rethrowingFunctionCheck3.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "TestFunction", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 16, - "column": 22, - "program": "rethrowingFunctionCheck3.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "f", - "typeAnnotation": { - "type": "ETSFunctionType", - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 16, - "column": 32, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 16, - "column": 36, - "program": "rethrowingFunctionCheck3.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 16, - "column": 26, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 16, - "column": 36, - "program": "rethrowingFunctionCheck3.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 23, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 16, - "column": 36, - "program": "rethrowingFunctionCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 23, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 16, - "column": 36, - "program": "rethrowingFunctionCheck3.ets" - } - } - } - ], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 16, - "column": 46, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 16, - "column": 50, - "program": "rethrowingFunctionCheck3.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 16, - "column": 60, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 16, - "column": 62, - "program": "rethrowingFunctionCheck3.ets" - } - } - }, - "throwMarker": "rethrows", - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 16, - "column": 62, - "program": "rethrowingFunctionCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 16, - "column": 62, - "program": "rethrowingFunctionCheck3.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 1, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 16, - "column": 62, - "program": "rethrowingFunctionCheck3.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "TestFunctionToo", - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 10, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 18, - "column": 25, - "program": "rethrowingFunctionCheck3.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "TestFunctionToo", - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 10, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 18, - "column": 25, - "program": "rethrowingFunctionCheck3.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 18, - "column": 29, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 18, - "column": 33, - "program": "rethrowingFunctionCheck3.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 18, - "column": 41, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 18, - "column": 43, - "program": "rethrowingFunctionCheck3.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 18, - "column": 10, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 18, - "column": 43, - "program": "rethrowingFunctionCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 18, - "column": 10, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 18, - "column": 43, - "program": "rethrowingFunctionCheck3.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 1, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 18, - "column": 43, - "program": "rethrowingFunctionCheck3.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 20, - "column": 14, - "program": "rethrowingFunctionCheck3.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 20, - "column": 14, - "program": "rethrowingFunctionCheck3.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 20, - "column": 18, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 20, - "column": 22, - "program": "rethrowingFunctionCheck3.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "TryStatement", - "block": { - "type": "BlockStatement", - "statements": [ - { - "type": "ExpressionStatement", - "expression": { - "type": "CallExpression", - "callee": { - "type": "Identifier", - "name": "TestFunction", - "decorators": [], - "loc": { - "start": { - "line": 22, - "column": 5, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 22, - "column": 17, - "program": "rethrowingFunctionCheck3.ets" - } - } - }, - "arguments": [ - { - "type": "Identifier", - "name": "TestFunctionToo", - "decorators": [], - "loc": { - "start": { - "line": 22, - "column": 18, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 22, - "column": 33, - "program": "rethrowingFunctionCheck3.ets" - } - } - } - ], - "optional": false, - "loc": { - "start": { - "line": 22, - "column": 5, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 22, - "column": 34, - "program": "rethrowingFunctionCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 22, - "column": 5, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 22, - "column": 35, - "program": "rethrowingFunctionCheck3.ets" - } - } - } - ], - "loc": { - "start": { - "line": 21, - "column": 7, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 23, - "column": 4, - "program": "rethrowingFunctionCheck3.ets" - } - } - }, - "handler": [ - { - "type": "CatchClause", - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 23, - "column": 15, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 23, - "column": 17, - "program": "rethrowingFunctionCheck3.ets" - } - } - }, - "param": { - "type": "Identifier", - "name": "e", - "decorators": [], - "loc": { - "start": { - "line": 23, - "column": 12, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 23, - "column": 13, - "program": "rethrowingFunctionCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 23, - "column": 5, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 23, - "column": 17, - "program": "rethrowingFunctionCheck3.ets" - } - } - } - ], - "finalizer": null, - "loc": { - "start": { - "line": 21, - "column": 3, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 23, - "column": 17, - "program": "rethrowingFunctionCheck3.ets" - } - } - } - ], - "loc": { - "start": { - "line": 20, - "column": 23, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 24, - "column": 2, - "program": "rethrowingFunctionCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 24, - "column": 2, - "program": "rethrowingFunctionCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 24, - "column": 2, - "program": "rethrowingFunctionCheck3.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 1, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 24, - "column": 2, - "program": "rethrowingFunctionCheck3.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrowingFunctionCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrowingFunctionCheck3.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingFunctionCheck3.ets" - }, - "end": { - "line": 25, - "column": 1, - "program": "rethrowingFunctionCheck3.ets" - } - } -} diff --git a/ets2panda/test/compiler/ets/rethrowingMethodCheck3-expected.txt b/ets2panda/test/compiler/ets/rethrowingMethodCheck3-expected.txt deleted file mode 100644 index 270f5b7066..0000000000 --- a/ets2panda/test/compiler/ets/rethrowingMethodCheck3-expected.txt +++ /dev/null @@ -1,1056 +0,0 @@ -{ - "type": "Program", - "statements": [ - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "TestClass", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 7, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 16, - "column": 16, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "testMethod", - "decorators": [], - "loc": { - "start": { - "line": 17, - "column": 3, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 17, - "column": 13, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": false, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "testMethod", - "decorators": [], - "loc": { - "start": { - "line": 17, - "column": 3, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 17, - "column": 13, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "f", - "typeAnnotation": { - "type": "ETSFunctionType", - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 17, - "column": 23, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 17, - "column": 27, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 17, - "column": 17, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 17, - "column": 27, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 17, - "column": 14, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 17, - "column": 27, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 17, - "column": 14, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 17, - "column": 27, - "program": "rethrowingMethodCheck3.ets" - } - } - } - ], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 17, - "column": 37, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 17, - "column": 41, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 17, - "column": 51, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 17, - "column": 53, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "throwMarker": "rethrows", - "loc": { - "start": { - "line": 17, - "column": 13, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 17, - "column": 53, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 17, - "column": 13, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 17, - "column": 53, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 17, - "column": 3, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 17, - "column": 53, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "constructor", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 18, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 16, - "column": 18, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "kind": "constructor", - "static": false, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "constructor", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 18, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 16, - "column": 18, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 16, - "column": 18, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 16, - "column": 18, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 18, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 16, - "column": 18, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 18, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 16, - "column": 18, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - } - ], - "loc": { - "start": { - "line": 16, - "column": 17, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 20, - "column": 9, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 1, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 20, - "column": 9, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "ETSGLOBAL", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "TestFunction", - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 20, - "column": 22, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "TestFunction", - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 20, - "column": 22, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 20, - "column": 26, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 20, - "column": 30, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 20, - "column": 38, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 20, - "column": 40, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 20, - "column": 40, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 20, - "column": 40, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 1, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 20, - "column": 40, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 22, - "column": 10, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 22, - "column": 14, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 22, - "column": 10, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 22, - "column": 14, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 22, - "column": 18, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 22, - "column": 22, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "VariableDeclaration", - "declarations": [ - { - "type": "VariableDeclarator", - "id": { - "type": "Identifier", - "name": "testClass", - "decorators": [], - "loc": { - "start": { - "line": 23, - "column": 7, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 23, - "column": 16, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "init": { - "type": "ETSNewClassInstanceExpression", - "typeReference": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "TestClass", - "decorators": [], - "loc": { - "start": { - "line": 23, - "column": 23, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 23, - "column": 32, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 23, - "column": 23, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 23, - "column": 33, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 23, - "column": 23, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 23, - "column": 33, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "arguments": [], - "loc": { - "start": { - "line": 23, - "column": 19, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 23, - "column": 35, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 23, - "column": 7, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 23, - "column": 35, - "program": "rethrowingMethodCheck3.ets" - } - } - } - ], - "kind": "let", - "loc": { - "start": { - "line": 23, - "column": 3, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 23, - "column": 35, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - { - "type": "TryStatement", - "block": { - "type": "BlockStatement", - "statements": [ - { - "type": "ExpressionStatement", - "expression": { - "type": "CallExpression", - "callee": { - "type": "MemberExpression", - "object": { - "type": "Identifier", - "name": "testClass", - "decorators": [], - "loc": { - "start": { - "line": 26, - "column": 5, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 26, - "column": 14, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "property": { - "type": "Identifier", - "name": "testMethod", - "decorators": [], - "loc": { - "start": { - "line": 26, - "column": 15, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 26, - "column": 25, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "computed": false, - "optional": false, - "loc": { - "start": { - "line": 26, - "column": 5, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 26, - "column": 25, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "arguments": [ - { - "type": "Identifier", - "name": "TestFunction", - "decorators": [], - "loc": { - "start": { - "line": 26, - "column": 26, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 26, - "column": 38, - "program": "rethrowingMethodCheck3.ets" - } - } - } - ], - "optional": false, - "loc": { - "start": { - "line": 26, - "column": 5, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 26, - "column": 39, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 26, - "column": 5, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 26, - "column": 40, - "program": "rethrowingMethodCheck3.ets" - } - } - } - ], - "loc": { - "start": { - "line": 25, - "column": 7, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 27, - "column": 4, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "handler": [ - { - "type": "CatchClause", - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 27, - "column": 15, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 27, - "column": 17, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "param": { - "type": "Identifier", - "name": "e", - "decorators": [], - "loc": { - "start": { - "line": 27, - "column": 12, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 27, - "column": 13, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 27, - "column": 5, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 27, - "column": 17, - "program": "rethrowingMethodCheck3.ets" - } - } - } - ], - "finalizer": null, - "loc": { - "start": { - "line": 25, - "column": 3, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 27, - "column": 17, - "program": "rethrowingMethodCheck3.ets" - } - } - } - ], - "loc": { - "start": { - "line": 22, - "column": 23, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 28, - "column": 2, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 22, - "column": 10, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 28, - "column": 2, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 22, - "column": 10, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 28, - "column": 2, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 22, - "column": 1, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 28, - "column": 2, - "program": "rethrowingMethodCheck3.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrowingMethodCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrowingMethodCheck3.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrowingMethodCheck3.ets" - }, - "end": { - "line": 29, - "column": 1, - "program": "rethrowingMethodCheck3.ets" - } - } -} diff --git a/ets2panda/test/compiler/ets/throwInRethrowingFunction2-expected.txt b/ets2panda/test/compiler/ets/throwInRethrowingFunction2-expected.txt deleted file mode 100644 index 0206339f32..0000000000 --- a/ets2panda/test/compiler/ets/throwInRethrowingFunction2-expected.txt +++ /dev/null @@ -1,662 +0,0 @@ -{ - "type": "Program", - "statements": [ - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "ETSGLOBAL", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwInRethrowingFunction2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwInRethrowingFunction2.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwInRethrowingFunction2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwInRethrowingFunction2.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwInRethrowingFunction2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwInRethrowingFunction2.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "RethrowingFunc", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "throwInRethrowingFunction2.ets" - }, - "end": { - "line": 16, - "column": 24, - "program": "throwInRethrowingFunction2.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "RethrowingFunc", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "throwInRethrowingFunction2.ets" - }, - "end": { - "line": 16, - "column": 24, - "program": "throwInRethrowingFunction2.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "f", - "typeAnnotation": { - "type": "ETSFunctionType", - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 16, - "column": 34, - "program": "throwInRethrowingFunction2.ets" - }, - "end": { - "line": 16, - "column": 38, - "program": "throwInRethrowingFunction2.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 16, - "column": 28, - "program": "throwInRethrowingFunction2.ets" - }, - "end": { - "line": 16, - "column": 38, - "program": "throwInRethrowingFunction2.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 25, - "program": "throwInRethrowingFunction2.ets" - }, - "end": { - "line": 16, - "column": 38, - "program": "throwInRethrowingFunction2.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 25, - "program": "throwInRethrowingFunction2.ets" - }, - "end": { - "line": 16, - "column": 38, - "program": "throwInRethrowingFunction2.ets" - } - } - } - ], - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "TryStatement", - "block": { - "type": "BlockStatement", - "statements": [ - { - "type": "ThrowStatement", - "argument": { - "type": "ETSNewClassInstanceExpression", - "typeReference": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "Exception", - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 15, - "program": "throwInRethrowingFunction2.ets" - }, - "end": { - "line": 18, - "column": 24, - "program": "throwInRethrowingFunction2.ets" - } - } - }, - "loc": { - "start": { - "line": 18, - "column": 15, - "program": "throwInRethrowingFunction2.ets" - }, - "end": { - "line": 18, - "column": 25, - "program": "throwInRethrowingFunction2.ets" - } - } - }, - "loc": { - "start": { - "line": 18, - "column": 15, - "program": "throwInRethrowingFunction2.ets" - }, - "end": { - "line": 18, - "column": 25, - "program": "throwInRethrowingFunction2.ets" - } - } - }, - "arguments": [], - "loc": { - "start": { - "line": 18, - "column": 11, - "program": "throwInRethrowingFunction2.ets" - }, - "end": { - "line": 18, - "column": 27, - "program": "throwInRethrowingFunction2.ets" - } - } - }, - "loc": { - "start": { - "line": 18, - "column": 5, - "program": "throwInRethrowingFunction2.ets" - }, - "end": { - "line": 18, - "column": 27, - "program": "throwInRethrowingFunction2.ets" - } - } - } - ], - "loc": { - "start": { - "line": 17, - "column": 7, - "program": "throwInRethrowingFunction2.ets" - }, - "end": { - "line": 19, - "column": 4, - "program": "throwInRethrowingFunction2.ets" - } - } - }, - "handler": [ - { - "type": "CatchClause", - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 19, - "column": 15, - "program": "throwInRethrowingFunction2.ets" - }, - "end": { - "line": 19, - "column": 17, - "program": "throwInRethrowingFunction2.ets" - } - } - }, - "param": { - "type": "Identifier", - "name": "e", - "decorators": [], - "loc": { - "start": { - "line": 19, - "column": 12, - "program": "throwInRethrowingFunction2.ets" - }, - "end": { - "line": 19, - "column": 13, - "program": "throwInRethrowingFunction2.ets" - } - } - }, - "loc": { - "start": { - "line": 19, - "column": 5, - "program": "throwInRethrowingFunction2.ets" - }, - "end": { - "line": 19, - "column": 17, - "program": "throwInRethrowingFunction2.ets" - } - } - } - ], - "finalizer": null, - "loc": { - "start": { - "line": 17, - "column": 3, - "program": "throwInRethrowingFunction2.ets" - }, - "end": { - "line": 19, - "column": 17, - "program": "throwInRethrowingFunction2.ets" - } - } - }, - { - "type": "ExpressionStatement", - "expression": { - "type": "CallExpression", - "callee": { - "type": "Identifier", - "name": "f", - "decorators": [], - "loc": { - "start": { - "line": 21, - "column": 3, - "program": "throwInRethrowingFunction2.ets" - }, - "end": { - "line": 21, - "column": 4, - "program": "throwInRethrowingFunction2.ets" - } - } - }, - "arguments": [], - "optional": false, - "loc": { - "start": { - "line": 21, - "column": 3, - "program": "throwInRethrowingFunction2.ets" - }, - "end": { - "line": 21, - "column": 6, - "program": "throwInRethrowingFunction2.ets" - } - } - }, - "loc": { - "start": { - "line": 21, - "column": 3, - "program": "throwInRethrowingFunction2.ets" - }, - "end": { - "line": 21, - "column": 7, - "program": "throwInRethrowingFunction2.ets" - } - } - } - ], - "loc": { - "start": { - "line": 16, - "column": 56, - "program": "throwInRethrowingFunction2.ets" - }, - "end": { - "line": 22, - "column": 2, - "program": "throwInRethrowingFunction2.ets" - } - } - }, - "throwMarker": "rethrows", - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "throwInRethrowingFunction2.ets" - }, - "end": { - "line": 22, - "column": 2, - "program": "throwInRethrowingFunction2.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "throwInRethrowingFunction2.ets" - }, - "end": { - "line": 22, - "column": 2, - "program": "throwInRethrowingFunction2.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 1, - "program": "throwInRethrowingFunction2.ets" - }, - "end": { - "line": 22, - "column": 2, - "program": "throwInRethrowingFunction2.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwInRethrowingFunction2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwInRethrowingFunction2.ets" - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwInRethrowingFunction2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwInRethrowingFunction2.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwInRethrowingFunction2.ets" - }, - "end": { - "line": 23, - "column": 1, - "program": "throwInRethrowingFunction2.ets" - } - } -} diff --git a/ets2panda/test/compiler/ets/throwInThrowingFunction-expected.txt b/ets2panda/test/compiler/ets/throwInThrowingFunction-expected.txt deleted file mode 100644 index a677bd13a0..0000000000 --- a/ets2panda/test/compiler/ets/throwInThrowingFunction-expected.txt +++ /dev/null @@ -1,480 +0,0 @@ -{ - "type": "Program", - "statements": [ - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "ETSGLOBAL", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwInThrowingFunction.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwInThrowingFunction.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwInThrowingFunction.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwInThrowingFunction.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwInThrowingFunction.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwInThrowingFunction.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "TestFunction", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "throwInThrowingFunction.ets" - }, - "end": { - "line": 16, - "column": 22, - "program": "throwInThrowingFunction.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "TestFunction", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "throwInThrowingFunction.ets" - }, - "end": { - "line": 16, - "column": 22, - "program": "throwInThrowingFunction.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 16, - "column": 26, - "program": "throwInThrowingFunction.ets" - }, - "end": { - "line": 16, - "column": 30, - "program": "throwInThrowingFunction.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "ThrowStatement", - "argument": { - "type": "ETSNewClassInstanceExpression", - "typeReference": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "Exception", - "decorators": [], - "loc": { - "start": { - "line": 17, - "column": 13, - "program": "throwInThrowingFunction.ets" - }, - "end": { - "line": 17, - "column": 22, - "program": "throwInThrowingFunction.ets" - } - } - }, - "loc": { - "start": { - "line": 17, - "column": 13, - "program": "throwInThrowingFunction.ets" - }, - "end": { - "line": 17, - "column": 23, - "program": "throwInThrowingFunction.ets" - } - } - }, - "loc": { - "start": { - "line": 17, - "column": 13, - "program": "throwInThrowingFunction.ets" - }, - "end": { - "line": 17, - "column": 23, - "program": "throwInThrowingFunction.ets" - } - } - }, - "arguments": [], - "loc": { - "start": { - "line": 17, - "column": 9, - "program": "throwInThrowingFunction.ets" - }, - "end": { - "line": 17, - "column": 25, - "program": "throwInThrowingFunction.ets" - } - } - }, - "loc": { - "start": { - "line": 17, - "column": 3, - "program": "throwInThrowingFunction.ets" - }, - "end": { - "line": 17, - "column": 25, - "program": "throwInThrowingFunction.ets" - } - } - } - ], - "loc": { - "start": { - "line": 16, - "column": 38, - "program": "throwInThrowingFunction.ets" - }, - "end": { - "line": 18, - "column": 2, - "program": "throwInThrowingFunction.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "throwInThrowingFunction.ets" - }, - "end": { - "line": 18, - "column": 2, - "program": "throwInThrowingFunction.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "throwInThrowingFunction.ets" - }, - "end": { - "line": 18, - "column": 2, - "program": "throwInThrowingFunction.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 1, - "program": "throwInThrowingFunction.ets" - }, - "end": { - "line": 18, - "column": 2, - "program": "throwInThrowingFunction.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwInThrowingFunction.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwInThrowingFunction.ets" - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwInThrowingFunction.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwInThrowingFunction.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwInThrowingFunction.ets" - }, - "end": { - "line": 19, - "column": 1, - "program": "throwInThrowingFunction.ets" - } - } -} diff --git a/ets2panda/test/compiler/ets/throwingFunctionAsParameter1-expected.txt b/ets2panda/test/compiler/ets/throwingFunctionAsParameter1-expected.txt deleted file mode 100644 index 1b05a374db..0000000000 --- a/ets2panda/test/compiler/ets/throwingFunctionAsParameter1-expected.txt +++ /dev/null @@ -1,835 +0,0 @@ -{ - "type": "Program", - "statements": [ - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "ETSGLOBAL", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwingFunctionAsParameter1.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwingFunctionAsParameter1.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwingFunctionAsParameter1.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "RethrowingFunc", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 16, - "column": 24, - "program": "throwingFunctionAsParameter1.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "RethrowingFunc", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 16, - "column": 24, - "program": "throwingFunctionAsParameter1.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "func", - "typeAnnotation": { - "type": "ETSFunctionType", - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 16, - "column": 37, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 16, - "column": 41, - "program": "throwingFunctionAsParameter1.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 16, - "column": 31, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 16, - "column": 41, - "program": "throwingFunctionAsParameter1.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 25, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 16, - "column": 41, - "program": "throwingFunctionAsParameter1.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 25, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 16, - "column": 41, - "program": "throwingFunctionAsParameter1.ets" - } - } - } - ], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 16, - "column": 51, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 16, - "column": 55, - "program": "throwingFunctionAsParameter1.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "ExpressionStatement", - "expression": { - "type": "CallExpression", - "callee": { - "type": "Identifier", - "name": "func", - "decorators": [], - "loc": { - "start": { - "line": 17, - "column": 3, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 17, - "column": 7, - "program": "throwingFunctionAsParameter1.ets" - } - } - }, - "arguments": [], - "optional": false, - "loc": { - "start": { - "line": 17, - "column": 3, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 17, - "column": 9, - "program": "throwingFunctionAsParameter1.ets" - } - } - }, - "loc": { - "start": { - "line": 17, - "column": 3, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 17, - "column": 10, - "program": "throwingFunctionAsParameter1.ets" - } - } - } - ], - "loc": { - "start": { - "line": 16, - "column": 65, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 18, - "column": 2, - "program": "throwingFunctionAsParameter1.ets" - } - } - }, - "throwMarker": "rethrows", - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 18, - "column": 2, - "program": "throwingFunctionAsParameter1.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 18, - "column": 2, - "program": "throwingFunctionAsParameter1.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 1, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 18, - "column": 2, - "program": "throwingFunctionAsParameter1.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "NonThrowingFunc", - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 20, - "column": 25, - "program": "throwingFunctionAsParameter1.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "NonThrowingFunc", - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 20, - "column": 25, - "program": "throwingFunctionAsParameter1.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "func", - "typeAnnotation": { - "type": "ETSFunctionType", - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 20, - "column": 38, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 20, - "column": 42, - "program": "throwingFunctionAsParameter1.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 20, - "column": 32, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 20, - "column": 42, - "program": "throwingFunctionAsParameter1.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 26, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 20, - "column": 42, - "program": "throwingFunctionAsParameter1.ets" - } - } - }, - "loc": { - "start": { - "line": 20, - "column": 26, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 20, - "column": 42, - "program": "throwingFunctionAsParameter1.ets" - } - } - } - ], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 20, - "column": 52, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 20, - "column": 56, - "program": "throwingFunctionAsParameter1.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "TryStatement", - "block": { - "type": "BlockStatement", - "statements": [ - { - "type": "ExpressionStatement", - "expression": { - "type": "CallExpression", - "callee": { - "type": "Identifier", - "name": "func", - "decorators": [], - "loc": { - "start": { - "line": 22, - "column": 5, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 22, - "column": 9, - "program": "throwingFunctionAsParameter1.ets" - } - } - }, - "arguments": [], - "optional": false, - "loc": { - "start": { - "line": 22, - "column": 5, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 22, - "column": 11, - "program": "throwingFunctionAsParameter1.ets" - } - } - }, - "loc": { - "start": { - "line": 22, - "column": 5, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 22, - "column": 12, - "program": "throwingFunctionAsParameter1.ets" - } - } - } - ], - "loc": { - "start": { - "line": 21, - "column": 7, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 23, - "column": 4, - "program": "throwingFunctionAsParameter1.ets" - } - } - }, - "handler": [ - { - "type": "CatchClause", - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 23, - "column": 15, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 23, - "column": 17, - "program": "throwingFunctionAsParameter1.ets" - } - } - }, - "param": { - "type": "Identifier", - "name": "e", - "decorators": [], - "loc": { - "start": { - "line": 23, - "column": 12, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 23, - "column": 13, - "program": "throwingFunctionAsParameter1.ets" - } - } - }, - "loc": { - "start": { - "line": 23, - "column": 5, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 23, - "column": 17, - "program": "throwingFunctionAsParameter1.ets" - } - } - } - ], - "finalizer": null, - "loc": { - "start": { - "line": 21, - "column": 3, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 23, - "column": 17, - "program": "throwingFunctionAsParameter1.ets" - } - } - } - ], - "loc": { - "start": { - "line": 20, - "column": 57, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 24, - "column": 2, - "program": "throwingFunctionAsParameter1.ets" - } - } - }, - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 24, - "column": 2, - "program": "throwingFunctionAsParameter1.ets" - } - } - }, - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 24, - "column": 2, - "program": "throwingFunctionAsParameter1.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 1, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 24, - "column": 2, - "program": "throwingFunctionAsParameter1.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwingFunctionAsParameter1.ets" - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwingFunctionAsParameter1.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionAsParameter1.ets" - }, - "end": { - "line": 25, - "column": 1, - "program": "throwingFunctionAsParameter1.ets" - } - } -} diff --git a/ets2panda/test/compiler/ets/throwingFunctionCheck2-expected.txt b/ets2panda/test/compiler/ets/throwingFunctionCheck2-expected.txt deleted file mode 100644 index cc12ad55a9..0000000000 --- a/ets2panda/test/compiler/ets/throwingFunctionCheck2-expected.txt +++ /dev/null @@ -1,809 +0,0 @@ -{ - "type": "Program", - "statements": [ - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "ETSGLOBAL", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck2.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck2.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "TestFunction", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 16, - "column": 22, - "program": "throwingFunctionCheck2.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "TestFunction", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 16, - "column": 22, - "program": "throwingFunctionCheck2.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 16, - "column": 26, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 16, - "column": 30, - "program": "throwingFunctionCheck2.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 16, - "column": 38, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 16, - "column": 40, - "program": "throwingFunctionCheck2.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 16, - "column": 40, - "program": "throwingFunctionCheck2.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 16, - "column": 40, - "program": "throwingFunctionCheck2.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 1, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 16, - "column": 40, - "program": "throwingFunctionCheck2.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 10, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 18, - "column": 14, - "program": "throwingFunctionCheck2.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 10, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 18, - "column": 14, - "program": "throwingFunctionCheck2.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 18, - "column": 18, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 18, - "column": 22, - "program": "throwingFunctionCheck2.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "TryStatement", - "block": { - "type": "BlockStatement", - "statements": [ - { - "type": "TryStatement", - "block": { - "type": "BlockStatement", - "statements": [ - { - "type": "TryStatement", - "block": { - "type": "BlockStatement", - "statements": [ - { - "type": "ExpressionStatement", - "expression": { - "type": "CallExpression", - "callee": { - "type": "Identifier", - "name": "TestFunction", - "decorators": [], - "loc": { - "start": { - "line": 22, - "column": 17, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 22, - "column": 29, - "program": "throwingFunctionCheck2.ets" - } - } - }, - "arguments": [], - "optional": false, - "loc": { - "start": { - "line": 22, - "column": 17, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 22, - "column": 31, - "program": "throwingFunctionCheck2.ets" - } - } - }, - "loc": { - "start": { - "line": 22, - "column": 17, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 22, - "column": 32, - "program": "throwingFunctionCheck2.ets" - } - } - } - ], - "loc": { - "start": { - "line": 21, - "column": 17, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 23, - "column": 14, - "program": "throwingFunctionCheck2.ets" - } - } - }, - "handler": [ - { - "type": "CatchClause", - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 23, - "column": 36, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 23, - "column": 38, - "program": "throwingFunctionCheck2.ets" - } - } - }, - "param": { - "type": "Identifier", - "name": "e", - "typeAnnotation": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "Exception", - "decorators": [], - "loc": { - "start": { - "line": 23, - "column": 25, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 23, - "column": 34, - "program": "throwingFunctionCheck2.ets" - } - } - }, - "loc": { - "start": { - "line": 23, - "column": 25, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 23, - "column": 35, - "program": "throwingFunctionCheck2.ets" - } - } - }, - "loc": { - "start": { - "line": 23, - "column": 25, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 23, - "column": 35, - "program": "throwingFunctionCheck2.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 23, - "column": 22, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 23, - "column": 23, - "program": "throwingFunctionCheck2.ets" - } - } - }, - "loc": { - "start": { - "line": 23, - "column": 15, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 23, - "column": 38, - "program": "throwingFunctionCheck2.ets" - } - } - } - ], - "finalizer": null, - "loc": { - "start": { - "line": 21, - "column": 13, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 23, - "column": 38, - "program": "throwingFunctionCheck2.ets" - } - } - } - ], - "loc": { - "start": { - "line": 20, - "column": 13, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 24, - "column": 10, - "program": "throwingFunctionCheck2.ets" - } - } - }, - "handler": [ - { - "type": "CatchClause", - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 24, - "column": 21, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 24, - "column": 23, - "program": "throwingFunctionCheck2.ets" - } - } - }, - "param": { - "type": "Identifier", - "name": "e", - "decorators": [], - "loc": { - "start": { - "line": 24, - "column": 18, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 24, - "column": 19, - "program": "throwingFunctionCheck2.ets" - } - } - }, - "loc": { - "start": { - "line": 24, - "column": 11, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 24, - "column": 23, - "program": "throwingFunctionCheck2.ets" - } - } - } - ], - "finalizer": null, - "loc": { - "start": { - "line": 20, - "column": 9, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 24, - "column": 23, - "program": "throwingFunctionCheck2.ets" - } - } - } - ], - "loc": { - "start": { - "line": 19, - "column": 9, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 25, - "column": 6, - "program": "throwingFunctionCheck2.ets" - } - } - }, - "handler": [ - { - "type": "CatchClause", - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 25, - "column": 28, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 25, - "column": 30, - "program": "throwingFunctionCheck2.ets" - } - } - }, - "param": { - "type": "Identifier", - "name": "e", - "typeAnnotation": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "Exception", - "decorators": [], - "loc": { - "start": { - "line": 25, - "column": 17, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 25, - "column": 26, - "program": "throwingFunctionCheck2.ets" - } - } - }, - "loc": { - "start": { - "line": 25, - "column": 17, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 25, - "column": 27, - "program": "throwingFunctionCheck2.ets" - } - } - }, - "loc": { - "start": { - "line": 25, - "column": 17, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 25, - "column": 27, - "program": "throwingFunctionCheck2.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 25, - "column": 14, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 25, - "column": 15, - "program": "throwingFunctionCheck2.ets" - } - } - }, - "loc": { - "start": { - "line": 25, - "column": 7, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 25, - "column": 30, - "program": "throwingFunctionCheck2.ets" - } - } - } - ], - "finalizer": null, - "loc": { - "start": { - "line": 19, - "column": 5, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 25, - "column": 30, - "program": "throwingFunctionCheck2.ets" - } - } - } - ], - "loc": { - "start": { - "line": 18, - "column": 23, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 26, - "column": 2, - "program": "throwingFunctionCheck2.ets" - } - } - }, - "loc": { - "start": { - "line": 18, - "column": 10, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 26, - "column": 2, - "program": "throwingFunctionCheck2.ets" - } - } - }, - "loc": { - "start": { - "line": 18, - "column": 10, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 26, - "column": 2, - "program": "throwingFunctionCheck2.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 1, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 26, - "column": 2, - "program": "throwingFunctionCheck2.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck2.ets" - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck2.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck2.ets" - }, - "end": { - "line": 27, - "column": 1, - "program": "throwingFunctionCheck2.ets" - } - } -} diff --git a/ets2panda/test/compiler/ets/throwingFunctionCheck3-expected.txt b/ets2panda/test/compiler/ets/throwingFunctionCheck3-expected.txt deleted file mode 100644 index d9f11899d8..0000000000 --- a/ets2panda/test/compiler/ets/throwingFunctionCheck3-expected.txt +++ /dev/null @@ -1,1154 +0,0 @@ -{ - "type": "Program", - "statements": [ - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "TestClass", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 7, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 16, - "column": 16, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "constructor", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "constructor", - "accessibility": "public", - "static": false, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "constructor", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 17, - "column": 26, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 17, - "column": 28, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 17, - "column": 16, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 17, - "column": 28, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 17, - "column": 16, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 17, - "column": 28, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 17, - "column": 5, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 17, - "column": 28, - "program": "throwingFunctionCheck3.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "TestMethod", - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 5, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 18, - "column": 15, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": false, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "TestMethod", - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 5, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 18, - "column": 15, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 18, - "column": 19, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 18, - "column": 23, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 18, - "column": 24, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 18, - "column": 26, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 18, - "column": 15, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 18, - "column": 26, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 18, - "column": 15, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 18, - "column": 26, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 5, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 18, - "column": 26, - "program": "throwingFunctionCheck3.ets" - } - } - } - ], - "loc": { - "start": { - "line": 16, - "column": 17, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 21, - "column": 9, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 1, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 21, - "column": 9, - "program": "throwingFunctionCheck3.ets" - } - } - }, - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "ETSGLOBAL", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck3.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "TestFunction", - "decorators": [], - "loc": { - "start": { - "line": 21, - "column": 10, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 21, - "column": 22, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "TestFunction", - "decorators": [], - "loc": { - "start": { - "line": 21, - "column": 10, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 21, - "column": 22, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 21, - "column": 26, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 21, - "column": 30, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "VariableDeclaration", - "declarations": [ - { - "type": "VariableDeclarator", - "id": { - "type": "Identifier", - "name": "a", - "decorators": [], - "loc": { - "start": { - "line": 22, - "column": 9, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 22, - "column": 10, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "init": { - "type": "ETSNewClassInstanceExpression", - "typeReference": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "TestClass", - "decorators": [], - "loc": { - "start": { - "line": 22, - "column": 17, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 22, - "column": 26, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 22, - "column": 17, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 22, - "column": 27, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 22, - "column": 17, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 22, - "column": 27, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "arguments": [], - "loc": { - "start": { - "line": 22, - "column": 13, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 22, - "column": 29, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 22, - "column": 9, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 22, - "column": 29, - "program": "throwingFunctionCheck3.ets" - } - } - } - ], - "kind": "let", - "loc": { - "start": { - "line": 22, - "column": 5, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 22, - "column": 29, - "program": "throwingFunctionCheck3.ets" - } - } - }, - { - "type": "TryStatement", - "block": { - "type": "BlockStatement", - "statements": [ - { - "type": "ExpressionStatement", - "expression": { - "type": "CallExpression", - "callee": { - "type": "MemberExpression", - "object": { - "type": "Identifier", - "name": "a", - "decorators": [], - "loc": { - "start": { - "line": 25, - "column": 9, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 25, - "column": 10, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "property": { - "type": "Identifier", - "name": "TestMethod", - "decorators": [], - "loc": { - "start": { - "line": 25, - "column": 11, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 25, - "column": 21, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "computed": false, - "optional": false, - "loc": { - "start": { - "line": 25, - "column": 9, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 25, - "column": 21, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "arguments": [], - "optional": false, - "loc": { - "start": { - "line": 25, - "column": 9, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 25, - "column": 23, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 25, - "column": 9, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 25, - "column": 24, - "program": "throwingFunctionCheck3.ets" - } - } - } - ], - "loc": { - "start": { - "line": 24, - "column": 9, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 26, - "column": 6, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "handler": [ - { - "type": "CatchClause", - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 26, - "column": 28, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 26, - "column": 30, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "param": { - "type": "Identifier", - "name": "e", - "typeAnnotation": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "Exception", - "decorators": [], - "loc": { - "start": { - "line": 26, - "column": 17, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 26, - "column": 26, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 26, - "column": 17, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 26, - "column": 27, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 26, - "column": 17, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 26, - "column": 27, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 26, - "column": 14, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 26, - "column": 15, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 26, - "column": 7, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 26, - "column": 30, - "program": "throwingFunctionCheck3.ets" - } - } - } - ], - "finalizer": null, - "loc": { - "start": { - "line": 24, - "column": 5, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 26, - "column": 30, - "program": "throwingFunctionCheck3.ets" - } - } - } - ], - "loc": { - "start": { - "line": 21, - "column": 38, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 27, - "column": 2, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 21, - "column": 10, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 27, - "column": 2, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 21, - "column": 10, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 27, - "column": 2, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 21, - "column": 1, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 27, - "column": 2, - "program": "throwingFunctionCheck3.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 29, - "column": 10, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 29, - "column": 14, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 29, - "column": 10, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 29, - "column": 14, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 29, - "column": 18, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 29, - "column": 22, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "TryStatement", - "block": { - "type": "BlockStatement", - "statements": [ - { - "type": "ExpressionStatement", - "expression": { - "type": "CallExpression", - "callee": { - "type": "Identifier", - "name": "TestFunction", - "decorators": [], - "loc": { - "start": { - "line": 31, - "column": 9, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 31, - "column": 21, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "arguments": [], - "optional": false, - "loc": { - "start": { - "line": 31, - "column": 9, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 31, - "column": 23, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 31, - "column": 9, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 31, - "column": 24, - "program": "throwingFunctionCheck3.ets" - } - } - } - ], - "loc": { - "start": { - "line": 30, - "column": 9, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 32, - "column": 6, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "handler": [ - { - "type": "CatchClause", - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 32, - "column": 17, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 32, - "column": 19, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "param": { - "type": "Identifier", - "name": "e", - "decorators": [], - "loc": { - "start": { - "line": 32, - "column": 14, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 32, - "column": 15, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 32, - "column": 7, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 32, - "column": 19, - "program": "throwingFunctionCheck3.ets" - } - } - } - ], - "finalizer": null, - "loc": { - "start": { - "line": 30, - "column": 5, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 32, - "column": 19, - "program": "throwingFunctionCheck3.ets" - } - } - } - ], - "loc": { - "start": { - "line": 29, - "column": 23, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 33, - "column": 2, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 29, - "column": 10, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 33, - "column": 2, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 29, - "column": 10, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 33, - "column": 2, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 29, - "column": 1, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 33, - "column": 2, - "program": "throwingFunctionCheck3.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck3.ets" - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck3.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck3.ets" - }, - "end": { - "line": 34, - "column": 1, - "program": "throwingFunctionCheck3.ets" - } - } -} diff --git a/ets2panda/test/compiler/ets/throwingFunctionCheck6-expected.txt b/ets2panda/test/compiler/ets/throwingFunctionCheck6-expected.txt deleted file mode 100644 index 767d95af48..0000000000 --- a/ets2panda/test/compiler/ets/throwingFunctionCheck6-expected.txt +++ /dev/null @@ -1,1180 +0,0 @@ -{ - "type": "Program", - "statements": [ - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "TestClass", - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 7, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 20, - "column": 16, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "testMethod", - "decorators": [], - "loc": { - "start": { - "line": 21, - "column": 3, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 21, - "column": 13, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": false, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "testMethod", - "decorators": [], - "loc": { - "start": { - "line": 21, - "column": 3, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 21, - "column": 13, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 21, - "column": 17, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 21, - "column": 21, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "ThrowStatement", - "argument": { - "type": "ETSNewClassInstanceExpression", - "typeReference": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "Exception", - "decorators": [], - "loc": { - "start": { - "line": 22, - "column": 15, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 22, - "column": 24, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "loc": { - "start": { - "line": 22, - "column": 15, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 22, - "column": 25, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "loc": { - "start": { - "line": 22, - "column": 15, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 22, - "column": 25, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "arguments": [], - "loc": { - "start": { - "line": 22, - "column": 11, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 22, - "column": 27, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "loc": { - "start": { - "line": 22, - "column": 5, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 22, - "column": 27, - "program": "throwingFunctionCheck6.ets" - } - } - } - ], - "loc": { - "start": { - "line": 21, - "column": 29, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 23, - "column": 4, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 21, - "column": 13, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 23, - "column": 4, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "loc": { - "start": { - "line": 21, - "column": 13, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 23, - "column": 4, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 21, - "column": 3, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 23, - "column": 4, - "program": "throwingFunctionCheck6.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "constructor", - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 18, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 20, - "column": 18, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "kind": "constructor", - "static": false, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "constructor", - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 18, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 20, - "column": 18, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 20, - "column": 18, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 20, - "column": 18, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "loc": { - "start": { - "line": 20, - "column": 18, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 20, - "column": 18, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "loc": { - "start": { - "line": 20, - "column": 18, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 20, - "column": 18, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - } - ], - "loc": { - "start": { - "line": 20, - "column": 17, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 26, - "column": 9, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "loc": { - "start": { - "line": 20, - "column": 1, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 26, - "column": 9, - "program": "throwingFunctionCheck6.ets" - } - } - }, - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "ETSGLOBAL", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck6.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "TestFunction", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 16, - "column": 22, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "TestFunction", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 16, - "column": 22, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 16, - "column": 26, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 16, - "column": 30, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "ThrowStatement", - "argument": { - "type": "ETSNewClassInstanceExpression", - "typeReference": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "Exception", - "decorators": [], - "loc": { - "start": { - "line": 17, - "column": 13, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 17, - "column": 22, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "loc": { - "start": { - "line": 17, - "column": 13, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 17, - "column": 23, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "loc": { - "start": { - "line": 17, - "column": 13, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 17, - "column": 23, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "arguments": [], - "loc": { - "start": { - "line": 17, - "column": 9, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 17, - "column": 25, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "loc": { - "start": { - "line": 17, - "column": 3, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 17, - "column": 25, - "program": "throwingFunctionCheck6.ets" - } - } - } - ], - "loc": { - "start": { - "line": 16, - "column": 38, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 18, - "column": 2, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 18, - "column": 2, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 18, - "column": 2, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 1, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 18, - "column": 2, - "program": "throwingFunctionCheck6.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 26, - "column": 10, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 26, - "column": 14, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 26, - "column": 10, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 26, - "column": 14, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 26, - "column": 18, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 26, - "column": 22, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "VariableDeclaration", - "declarations": [ - { - "type": "VariableDeclarator", - "id": { - "type": "Identifier", - "name": "testClass", - "decorators": [], - "loc": { - "start": { - "line": 27, - "column": 7, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 27, - "column": 16, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "init": { - "type": "ETSNewClassInstanceExpression", - "typeReference": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "TestClass", - "decorators": [], - "loc": { - "start": { - "line": 27, - "column": 23, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 27, - "column": 32, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "loc": { - "start": { - "line": 27, - "column": 23, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 27, - "column": 33, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "loc": { - "start": { - "line": 27, - "column": 23, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 27, - "column": 33, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "arguments": [], - "loc": { - "start": { - "line": 27, - "column": 19, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 27, - "column": 35, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "loc": { - "start": { - "line": 27, - "column": 7, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 27, - "column": 35, - "program": "throwingFunctionCheck6.ets" - } - } - } - ], - "kind": "let", - "loc": { - "start": { - "line": 27, - "column": 3, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 27, - "column": 35, - "program": "throwingFunctionCheck6.ets" - } - } - }, - { - "type": "TryStatement", - "block": { - "type": "BlockStatement", - "statements": [ - { - "type": "ExpressionStatement", - "expression": { - "type": "CallExpression", - "callee": { - "type": "Identifier", - "name": "TestFunction", - "decorators": [], - "loc": { - "start": { - "line": 30, - "column": 5, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 30, - "column": 17, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "arguments": [], - "optional": false, - "loc": { - "start": { - "line": 30, - "column": 5, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 30, - "column": 19, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "loc": { - "start": { - "line": 30, - "column": 5, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 30, - "column": 20, - "program": "throwingFunctionCheck6.ets" - } - } - }, - { - "type": "ExpressionStatement", - "expression": { - "type": "CallExpression", - "callee": { - "type": "MemberExpression", - "object": { - "type": "Identifier", - "name": "testClass", - "decorators": [], - "loc": { - "start": { - "line": 31, - "column": 5, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 31, - "column": 14, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "property": { - "type": "Identifier", - "name": "testMethod", - "decorators": [], - "loc": { - "start": { - "line": 31, - "column": 15, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 31, - "column": 25, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "computed": false, - "optional": false, - "loc": { - "start": { - "line": 31, - "column": 5, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 31, - "column": 25, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "arguments": [], - "optional": false, - "loc": { - "start": { - "line": 31, - "column": 5, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 31, - "column": 27, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "loc": { - "start": { - "line": 31, - "column": 5, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 31, - "column": 28, - "program": "throwingFunctionCheck6.ets" - } - } - } - ], - "loc": { - "start": { - "line": 29, - "column": 7, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 32, - "column": 4, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "handler": [ - { - "type": "CatchClause", - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 32, - "column": 15, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 32, - "column": 17, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "param": { - "type": "Identifier", - "name": "e", - "decorators": [], - "loc": { - "start": { - "line": 32, - "column": 12, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 32, - "column": 13, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "loc": { - "start": { - "line": 32, - "column": 5, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 32, - "column": 17, - "program": "throwingFunctionCheck6.ets" - } - } - } - ], - "finalizer": null, - "loc": { - "start": { - "line": 29, - "column": 3, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 32, - "column": 17, - "program": "throwingFunctionCheck6.ets" - } - } - } - ], - "loc": { - "start": { - "line": 26, - "column": 23, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 33, - "column": 2, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "loc": { - "start": { - "line": 26, - "column": 10, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 33, - "column": 2, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "loc": { - "start": { - "line": 26, - "column": 10, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 33, - "column": 2, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 26, - "column": 1, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 33, - "column": 2, - "program": "throwingFunctionCheck6.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck6.ets" - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck6.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionCheck6.ets" - }, - "end": { - "line": 34, - "column": 1, - "program": "throwingFunctionCheck6.ets" - } - } -} diff --git a/ets2panda/test/compiler/ets/throwingFunctionType1-expected.txt b/ets2panda/test/compiler/ets/throwingFunctionType1-expected.txt deleted file mode 100644 index 123a8379e0..0000000000 --- a/ets2panda/test/compiler/ets/throwingFunctionType1-expected.txt +++ /dev/null @@ -1,654 +0,0 @@ -{ - "type": "Program", - "statements": [ - { - "type": "TSTypeAliasDeclaration", - "id": { - "type": "Identifier", - "name": "func_type", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 6, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 16, - "column": 15, - "program": "throwingFunctionType1.ets" - } - } - }, - "typeAnnotation": { - "type": "ETSFunctionType", - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 16, - "column": 24, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 16, - "column": 28, - "program": "throwingFunctionType1.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 16, - "column": 18, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 16, - "column": 28, - "program": "throwingFunctionType1.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 1, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 16, - "column": 36, - "program": "throwingFunctionType1.ets" - } - } - }, - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "ETSGLOBAL", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwingFunctionType1.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwingFunctionType1.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 10, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 18, - "column": 14, - "program": "throwingFunctionType1.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 10, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 18, - "column": 14, - "program": "throwingFunctionType1.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 18, - "column": 18, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 18, - "column": 22, - "program": "throwingFunctionType1.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "VariableDeclaration", - "declarations": [ - { - "type": "VariableDeclarator", - "id": { - "type": "Identifier", - "name": "a", - "typeAnnotation": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "func_type", - "decorators": [], - "loc": { - "start": { - "line": 19, - "column": 10, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 19, - "column": 19, - "program": "throwingFunctionType1.ets" - } - } - }, - "loc": { - "start": { - "line": 19, - "column": 10, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 19, - "column": 21, - "program": "throwingFunctionType1.ets" - } - } - }, - "loc": { - "start": { - "line": 19, - "column": 10, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 19, - "column": 21, - "program": "throwingFunctionType1.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 19, - "column": 7, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 19, - "column": 8, - "program": "throwingFunctionType1.ets" - } - } - }, - "init": { - "type": "ArrowFunctionExpression", - "function": { - "type": "ScriptFunction", - "id": null, - "generator": false, - "async": false, - "expression": false, - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 19, - "column": 26, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 19, - "column": 30, - "program": "throwingFunctionType1.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 19, - "column": 34, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 19, - "column": 36, - "program": "throwingFunctionType1.ets" - } - } - }, - "loc": { - "start": { - "line": 19, - "column": 22, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 19, - "column": 36, - "program": "throwingFunctionType1.ets" - } - } - }, - "loc": { - "start": { - "line": 19, - "column": 22, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 19, - "column": 36, - "program": "throwingFunctionType1.ets" - } - } - }, - "loc": { - "start": { - "line": 19, - "column": 7, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 19, - "column": 36, - "program": "throwingFunctionType1.ets" - } - } - } - ], - "kind": "let", - "loc": { - "start": { - "line": 19, - "column": 3, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 19, - "column": 37, - "program": "throwingFunctionType1.ets" - } - } - }, - { - "type": "TryStatement", - "block": { - "type": "BlockStatement", - "statements": [ - { - "type": "ExpressionStatement", - "expression": { - "type": "CallExpression", - "callee": { - "type": "Identifier", - "name": "a", - "decorators": [], - "loc": { - "start": { - "line": 22, - "column": 5, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 22, - "column": 6, - "program": "throwingFunctionType1.ets" - } - } - }, - "arguments": [], - "optional": false, - "loc": { - "start": { - "line": 22, - "column": 5, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 22, - "column": 8, - "program": "throwingFunctionType1.ets" - } - } - }, - "loc": { - "start": { - "line": 22, - "column": 5, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 22, - "column": 9, - "program": "throwingFunctionType1.ets" - } - } - } - ], - "loc": { - "start": { - "line": 21, - "column": 7, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 23, - "column": 4, - "program": "throwingFunctionType1.ets" - } - } - }, - "handler": [ - { - "type": "CatchClause", - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 23, - "column": 15, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 23, - "column": 17, - "program": "throwingFunctionType1.ets" - } - } - }, - "param": { - "type": "Identifier", - "name": "e", - "decorators": [], - "loc": { - "start": { - "line": 23, - "column": 12, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 23, - "column": 13, - "program": "throwingFunctionType1.ets" - } - } - }, - "loc": { - "start": { - "line": 23, - "column": 5, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 23, - "column": 17, - "program": "throwingFunctionType1.ets" - } - } - } - ], - "finalizer": null, - "loc": { - "start": { - "line": 21, - "column": 3, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 23, - "column": 17, - "program": "throwingFunctionType1.ets" - } - } - } - ], - "loc": { - "start": { - "line": 18, - "column": 23, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 24, - "column": 2, - "program": "throwingFunctionType1.ets" - } - } - }, - "loc": { - "start": { - "line": 18, - "column": 10, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 24, - "column": 2, - "program": "throwingFunctionType1.ets" - } - } - }, - "loc": { - "start": { - "line": 18, - "column": 10, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 24, - "column": 2, - "program": "throwingFunctionType1.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 1, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 24, - "column": 2, - "program": "throwingFunctionType1.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwingFunctionType1.ets" - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwingFunctionType1.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwingFunctionType1.ets" - }, - "end": { - "line": 25, - "column": 1, - "program": "throwingFunctionType1.ets" - } - } -} diff --git a/ets2panda/test/parser/ets/constructorThrowsRethrows-expected.txt b/ets2panda/test/parser/ets/constructorThrowsRethrows-expected.txt deleted file mode 100644 index b4ef5220f5..0000000000 --- a/ets2panda/test/parser/ets/constructorThrowsRethrows-expected.txt +++ /dev/null @@ -1,753 +0,0 @@ -{ - "type": "Program", - "statements": [ - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "TestClass", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 7, - "program": "constructorThrowsRethrows.ets" - }, - "end": { - "line": 16, - "column": 16, - "program": "constructorThrowsRethrows.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "constructor", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "constructor", - "accessibility": "public", - "static": false, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "constructor", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 17, - "column": 24, - "program": "constructorThrowsRethrows.ets" - }, - "end": { - "line": 17, - "column": 26, - "program": "constructorThrowsRethrows.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 17, - "column": 14, - "program": "constructorThrowsRethrows.ets" - }, - "end": { - "line": 17, - "column": 26, - "program": "constructorThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 17, - "column": 14, - "program": "constructorThrowsRethrows.ets" - }, - "end": { - "line": 17, - "column": 26, - "program": "constructorThrowsRethrows.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 17, - "column": 3, - "program": "constructorThrowsRethrows.ets" - }, - "end": { - "line": 17, - "column": 26, - "program": "constructorThrowsRethrows.ets" - } - } - } - ], - "loc": { - "start": { - "line": 16, - "column": 17, - "program": "constructorThrowsRethrows.ets" - }, - "end": { - "line": 20, - "column": 6, - "program": "constructorThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 1, - "program": "constructorThrowsRethrows.ets" - }, - "end": { - "line": 20, - "column": 6, - "program": "constructorThrowsRethrows.ets" - } - } - }, - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "TestClassToo", - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 7, - "program": "constructorThrowsRethrows.ets" - }, - "end": { - "line": 20, - "column": 19, - "program": "constructorThrowsRethrows.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "constructor", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "constructor", - "accessibility": "public", - "static": false, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "constructor", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "param", - "typeAnnotation": { - "type": "ETSFunctionType", - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "c", - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 21, - "column": 26, - "program": "constructorThrowsRethrows.ets" - }, - "end": { - "line": 21, - "column": 29, - "program": "constructorThrowsRethrows.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 21, - "column": 23, - "program": "constructorThrowsRethrows.ets" - }, - "end": { - "line": 21, - "column": 29, - "program": "constructorThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 21, - "column": 23, - "program": "constructorThrowsRethrows.ets" - }, - "end": { - "line": 21, - "column": 29, - "program": "constructorThrowsRethrows.ets" - } - } - }, - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "b", - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 21, - "column": 34, - "program": "constructorThrowsRethrows.ets" - }, - "end": { - "line": 21, - "column": 37, - "program": "constructorThrowsRethrows.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 21, - "column": 31, - "program": "constructorThrowsRethrows.ets" - }, - "end": { - "line": 21, - "column": 37, - "program": "constructorThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 21, - "column": 31, - "program": "constructorThrowsRethrows.ets" - }, - "end": { - "line": 21, - "column": 37, - "program": "constructorThrowsRethrows.ets" - } - } - } - ], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 21, - "column": 42, - "program": "constructorThrowsRethrows.ets" - }, - "end": { - "line": 21, - "column": 46, - "program": "constructorThrowsRethrows.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 21, - "column": 22, - "program": "constructorThrowsRethrows.ets" - }, - "end": { - "line": 21, - "column": 46, - "program": "constructorThrowsRethrows.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 21, - "column": 15, - "program": "constructorThrowsRethrows.ets" - }, - "end": { - "line": 21, - "column": 46, - "program": "constructorThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 21, - "column": 15, - "program": "constructorThrowsRethrows.ets" - }, - "end": { - "line": 21, - "column": 46, - "program": "constructorThrowsRethrows.ets" - } - } - } - ], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 21, - "column": 64, - "program": "constructorThrowsRethrows.ets" - }, - "end": { - "line": 21, - "column": 66, - "program": "constructorThrowsRethrows.ets" - } - } - }, - "throwMarker": "rethrows", - "loc": { - "start": { - "line": 21, - "column": 14, - "program": "constructorThrowsRethrows.ets" - }, - "end": { - "line": 21, - "column": 66, - "program": "constructorThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 21, - "column": 14, - "program": "constructorThrowsRethrows.ets" - }, - "end": { - "line": 21, - "column": 66, - "program": "constructorThrowsRethrows.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 21, - "column": 3, - "program": "constructorThrowsRethrows.ets" - }, - "end": { - "line": 21, - "column": 66, - "program": "constructorThrowsRethrows.ets" - } - } - } - ], - "loc": { - "start": { - "line": 20, - "column": 20, - "program": "constructorThrowsRethrows.ets" - }, - "end": { - "line": 23, - "column": 1, - "program": "constructorThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 20, - "column": 1, - "program": "constructorThrowsRethrows.ets" - }, - "end": { - "line": 23, - "column": 1, - "program": "constructorThrowsRethrows.ets" - } - } - }, - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "ETSGLOBAL", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "constructorThrowsRethrows.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "constructorThrowsRethrows.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "constructorThrowsRethrows.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "constructorThrowsRethrows.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "constructorThrowsRethrows.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "constructorThrowsRethrows.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "constructorThrowsRethrows.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "constructorThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "constructorThrowsRethrows.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "constructorThrowsRethrows.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "constructorThrowsRethrows.ets" - }, - "end": { - "line": 23, - "column": 1, - "program": "constructorThrowsRethrows.ets" - } - } -} diff --git a/ets2panda/test/parser/ets/functionThrowsRethrows-expected.txt b/ets2panda/test/parser/ets/functionThrowsRethrows-expected.txt deleted file mode 100644 index 4d1c381ee1..0000000000 --- a/ets2panda/test/parser/ets/functionThrowsRethrows-expected.txt +++ /dev/null @@ -1,809 +0,0 @@ -{ - "type": "Program", - "statements": [ - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "ETSGLOBAL", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "functionThrowsRethrows.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "functionThrowsRethrows.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "functionThrowsRethrows.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "testFunction", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 16, - "column": 22, - "program": "functionThrowsRethrows.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "testFunction", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 16, - "column": 22, - "program": "functionThrowsRethrows.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 16, - "column": 26, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 16, - "column": 30, - "program": "functionThrowsRethrows.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "ThrowStatement", - "argument": { - "type": "ETSNewClassInstanceExpression", - "typeReference": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "Exception", - "decorators": [], - "loc": { - "start": { - "line": 17, - "column": 15, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 17, - "column": 24, - "program": "functionThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 17, - "column": 15, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 17, - "column": 25, - "program": "functionThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 17, - "column": 15, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 17, - "column": 25, - "program": "functionThrowsRethrows.ets" - } - } - }, - "arguments": [], - "loc": { - "start": { - "line": 17, - "column": 11, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 17, - "column": 27, - "program": "functionThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 17, - "column": 5, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 17, - "column": 27, - "program": "functionThrowsRethrows.ets" - } - } - } - ], - "loc": { - "start": { - "line": 16, - "column": 38, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 18, - "column": 2, - "program": "functionThrowsRethrows.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 18, - "column": 2, - "program": "functionThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 18, - "column": 2, - "program": "functionThrowsRethrows.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 1, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 18, - "column": 2, - "program": "functionThrowsRethrows.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "testFunctionToo", - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 20, - "column": 25, - "program": "functionThrowsRethrows.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "testFunctionToo", - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 20, - "column": 25, - "program": "functionThrowsRethrows.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "param", - "typeAnnotation": { - "type": "ETSFunctionType", - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "c", - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 20, - "column": 37, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 20, - "column": 40, - "program": "functionThrowsRethrows.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 34, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 20, - "column": 40, - "program": "functionThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 20, - "column": 34, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 20, - "column": 40, - "program": "functionThrowsRethrows.ets" - } - } - }, - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "b", - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 20, - "column": 45, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 20, - "column": 48, - "program": "functionThrowsRethrows.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 42, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 20, - "column": 48, - "program": "functionThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 20, - "column": 42, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 20, - "column": 48, - "program": "functionThrowsRethrows.ets" - } - } - } - ], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 20, - "column": 53, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 20, - "column": 57, - "program": "functionThrowsRethrows.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 20, - "column": 33, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 20, - "column": 57, - "program": "functionThrowsRethrows.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 26, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 20, - "column": 57, - "program": "functionThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 20, - "column": 26, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 20, - "column": 57, - "program": "functionThrowsRethrows.ets" - } - } - }, - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "p", - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 20, - "column": 69, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 20, - "column": 72, - "program": "functionThrowsRethrows.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 66, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 20, - "column": 72, - "program": "functionThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 20, - "column": 66, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 20, - "column": 72, - "program": "functionThrowsRethrows.ets" - } - } - } - ], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 20, - "column": 75, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 20, - "column": 79, - "program": "functionThrowsRethrows.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 20, - "column": 89, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 20, - "column": 91, - "program": "functionThrowsRethrows.ets" - } - } - }, - "throwMarker": "rethrows", - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 20, - "column": 91, - "program": "functionThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 20, - "column": 91, - "program": "functionThrowsRethrows.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 1, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 20, - "column": 91, - "program": "functionThrowsRethrows.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "functionThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "functionThrowsRethrows.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "functionThrowsRethrows.ets" - }, - "end": { - "line": 21, - "column": 1, - "program": "functionThrowsRethrows.ets" - } - } -} diff --git a/ets2panda/test/parser/ets/functionTypeThrows-expected.txt b/ets2panda/test/parser/ets/functionTypeThrows-expected.txt deleted file mode 100644 index 072678965d..0000000000 --- a/ets2panda/test/parser/ets/functionTypeThrows-expected.txt +++ /dev/null @@ -1,446 +0,0 @@ -{ - "type": "Program", - "statements": [ - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "ETSGLOBAL", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "functionTypeThrows.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "functionTypeThrows.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "functionTypeThrows.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "functionTypeThrows.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "functionTypeThrows.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "functionTypeThrows.ets" - } - } - }, - { - "type": "ClassProperty", - "key": { - "type": "Identifier", - "name": "a", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 5, - "program": "functionTypeThrows.ets" - }, - "end": { - "line": 16, - "column": 6, - "program": "functionTypeThrows.ets" - } - } - }, - "accessibility": "public", - "static": true, - "readonly": false, - "declare": false, - "optional": false, - "computed": false, - "typeAnnotation": { - "type": "ETSFunctionType", - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "c", - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 16, - "column": 12, - "program": "functionTypeThrows.ets" - }, - "end": { - "line": 16, - "column": 15, - "program": "functionTypeThrows.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 9, - "program": "functionTypeThrows.ets" - }, - "end": { - "line": 16, - "column": 15, - "program": "functionTypeThrows.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 9, - "program": "functionTypeThrows.ets" - }, - "end": { - "line": 16, - "column": 15, - "program": "functionTypeThrows.ets" - } - } - }, - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "b", - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 16, - "column": 20, - "program": "functionTypeThrows.ets" - }, - "end": { - "line": 16, - "column": 23, - "program": "functionTypeThrows.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 17, - "program": "functionTypeThrows.ets" - }, - "end": { - "line": 16, - "column": 23, - "program": "functionTypeThrows.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 17, - "program": "functionTypeThrows.ets" - }, - "end": { - "line": 16, - "column": 23, - "program": "functionTypeThrows.ets" - } - } - } - ], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 16, - "column": 28, - "program": "functionTypeThrows.ets" - }, - "end": { - "line": 16, - "column": 32, - "program": "functionTypeThrows.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 16, - "column": 8, - "program": "functionTypeThrows.ets" - }, - "end": { - "line": 16, - "column": 32, - "program": "functionTypeThrows.ets" - } - } - }, - "definite": false, - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 5, - "program": "functionTypeThrows.ets" - }, - "end": { - "line": 16, - "column": 6, - "program": "functionTypeThrows.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "functionTypeThrows.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "functionTypeThrows.ets" - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "functionTypeThrows.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "functionTypeThrows.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "functionTypeThrows.ets" - }, - "end": { - "line": 17, - "column": 1, - "program": "functionTypeThrows.ets" - } - } -} diff --git a/ets2panda/test/parser/ets/lambdaThrowsRethrows-expected.txt b/ets2panda/test/parser/ets/lambdaThrowsRethrows-expected.txt deleted file mode 100644 index dc195cfcfa..0000000000 --- a/ets2panda/test/parser/ets/lambdaThrowsRethrows-expected.txt +++ /dev/null @@ -1,974 +0,0 @@ -{ - "type": "Program", - "statements": [ - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "ETSGLOBAL", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "ExpressionStatement", - "expression": { - "type": "AssignmentExpression", - "operator": "=", - "left": { - "type": "Identifier", - "name": "lambda", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 5, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 16, - "column": 11, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - "right": { - "type": "ArrowFunctionExpression", - "function": { - "type": "ScriptFunction", - "id": null, - "generator": false, - "async": false, - "expression": false, - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 16, - "column": 37, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 16, - "column": 41, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 16, - "column": 52, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 16, - "column": 54, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 16, - "column": 33, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 16, - "column": 54, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 33, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 16, - "column": 54, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 5, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 16, - "column": 54, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 5, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 16, - "column": 54, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - { - "type": "ExpressionStatement", - "expression": { - "type": "AssignmentExpression", - "operator": "=", - "left": { - "type": "Identifier", - "name": "lambda2", - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 5, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 18, - "column": 12, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - "right": { - "type": "ArrowFunctionExpression", - "function": { - "type": "ScriptFunction", - "id": null, - "generator": false, - "async": false, - "expression": false, - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "param", - "typeAnnotation": { - "type": "ETSFunctionType", - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "c", - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 18, - "column": 84, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 18, - "column": 87, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 81, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 18, - "column": 87, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 18, - "column": 81, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 18, - "column": 87, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "b", - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 18, - "column": 92, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 18, - "column": 95, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 89, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 18, - "column": 95, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 18, - "column": 89, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 18, - "column": 95, - "program": "lambdaThrowsRethrows.ets" - } - } - } - ], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 18, - "column": 100, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 18, - "column": 104, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 18, - "column": 80, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 18, - "column": 104, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 73, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 18, - "column": 104, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 18, - "column": 73, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 18, - "column": 104, - "program": "lambdaThrowsRethrows.ets" - } - } - } - ], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 18, - "column": 114, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 18, - "column": 118, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 18, - "column": 131, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 18, - "column": 133, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - "throwMarker": "rethrows", - "loc": { - "start": { - "line": 18, - "column": 72, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 18, - "column": 133, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 18, - "column": 72, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 18, - "column": 133, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 18, - "column": 5, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 18, - "column": 133, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 18, - "column": 5, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 18, - "column": 133, - "program": "lambdaThrowsRethrows.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - { - "type": "ClassProperty", - "key": { - "type": "Identifier", - "name": "lambda", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 5, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 16, - "column": 11, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - "accessibility": "public", - "static": true, - "readonly": false, - "declare": false, - "optional": false, - "computed": false, - "typeAnnotation": { - "type": "ETSFunctionType", - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 16, - "column": 19, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 16, - "column": 23, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 16, - "column": 13, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 16, - "column": 23, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - "definite": false, - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 5, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 16, - "column": 54, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - { - "type": "ClassProperty", - "key": { - "type": "Identifier", - "name": "lambda2", - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 5, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 18, - "column": 12, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - "accessibility": "public", - "static": true, - "readonly": false, - "declare": false, - "optional": false, - "computed": false, - "typeAnnotation": { - "type": "ETSFunctionType", - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "param", - "typeAnnotation": { - "type": "ETSFunctionType", - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "c", - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 18, - "column": 26, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 18, - "column": 29, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 23, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 18, - "column": 29, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 18, - "column": 23, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 18, - "column": 29, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "b", - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 18, - "column": 34, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 18, - "column": 37, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 31, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 18, - "column": 37, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 18, - "column": 31, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 18, - "column": 37, - "program": "lambdaThrowsRethrows.ets" - } - } - } - ], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 18, - "column": 42, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 18, - "column": 46, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 18, - "column": 22, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 18, - "column": 46, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 15, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 18, - "column": 46, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 18, - "column": 15, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 18, - "column": 46, - "program": "lambdaThrowsRethrows.ets" - } - } - } - ], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 18, - "column": 58, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 18, - "column": 62, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 18, - "column": 14, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 18, - "column": 62, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - "definite": false, - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 5, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 18, - "column": 133, - "program": "lambdaThrowsRethrows.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambdaThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "lambdaThrowsRethrows.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "lambdaThrowsRethrows.ets" - }, - "end": { - "line": 19, - "column": 1, - "program": "lambdaThrowsRethrows.ets" - } - } -} diff --git a/ets2panda/test/parser/ets/methodThrowsRethrows-expected.txt b/ets2panda/test/parser/ets/methodThrowsRethrows-expected.txt deleted file mode 100644 index 093b36752f..0000000000 --- a/ets2panda/test/parser/ets/methodThrowsRethrows-expected.txt +++ /dev/null @@ -1,838 +0,0 @@ -{ - "type": "Program", - "statements": [ - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "TestClass", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 7, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 16, - "column": 16, - "program": "methodThrowsRethrows.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "testMethodThrows", - "decorators": [], - "loc": { - "start": { - "line": 17, - "column": 3, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 17, - "column": 19, - "program": "methodThrowsRethrows.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": false, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "testMethodThrows", - "decorators": [], - "loc": { - "start": { - "line": 17, - "column": 3, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 17, - "column": 19, - "program": "methodThrowsRethrows.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 17, - "column": 23, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 17, - "column": 27, - "program": "methodThrowsRethrows.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 17, - "column": 35, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 17, - "column": 37, - "program": "methodThrowsRethrows.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 17, - "column": 19, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 17, - "column": 37, - "program": "methodThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 17, - "column": 19, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 17, - "column": 37, - "program": "methodThrowsRethrows.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 17, - "column": 3, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 17, - "column": 37, - "program": "methodThrowsRethrows.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "testMethodRethrows", - "decorators": [], - "loc": { - "start": { - "line": 19, - "column": 3, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 19, - "column": 21, - "program": "methodThrowsRethrows.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": false, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "testMethodRethrows", - "decorators": [], - "loc": { - "start": { - "line": 19, - "column": 3, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 19, - "column": 21, - "program": "methodThrowsRethrows.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "param", - "typeAnnotation": { - "type": "ETSFunctionType", - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "c", - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 19, - "column": 33, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 19, - "column": 36, - "program": "methodThrowsRethrows.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 19, - "column": 30, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 19, - "column": 36, - "program": "methodThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 19, - "column": 30, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 19, - "column": 36, - "program": "methodThrowsRethrows.ets" - } - } - }, - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "b", - "typeAnnotation": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 19, - "column": 41, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 19, - "column": 44, - "program": "methodThrowsRethrows.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 19, - "column": 38, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 19, - "column": 44, - "program": "methodThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 19, - "column": 38, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 19, - "column": 44, - "program": "methodThrowsRethrows.ets" - } - } - } - ], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 19, - "column": 49, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 19, - "column": 53, - "program": "methodThrowsRethrows.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 19, - "column": 29, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 19, - "column": 53, - "program": "methodThrowsRethrows.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 19, - "column": 22, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 19, - "column": 53, - "program": "methodThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 19, - "column": 22, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 19, - "column": 53, - "program": "methodThrowsRethrows.ets" - } - } - } - ], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 19, - "column": 63, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 19, - "column": 67, - "program": "methodThrowsRethrows.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 19, - "column": 77, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 19, - "column": 79, - "program": "methodThrowsRethrows.ets" - } - } - }, - "throwMarker": "rethrows", - "loc": { - "start": { - "line": 19, - "column": 21, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 19, - "column": 79, - "program": "methodThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 19, - "column": 21, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 19, - "column": 79, - "program": "methodThrowsRethrows.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 19, - "column": 3, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 19, - "column": 79, - "program": "methodThrowsRethrows.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "constructor", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 18, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 16, - "column": 18, - "program": "methodThrowsRethrows.ets" - } - } - }, - "kind": "constructor", - "static": false, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "constructor", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 18, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 16, - "column": 18, - "program": "methodThrowsRethrows.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 16, - "column": 18, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 16, - "column": 18, - "program": "methodThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 18, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 16, - "column": 18, - "program": "methodThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 18, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 16, - "column": 18, - "program": "methodThrowsRethrows.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - } - ], - "loc": { - "start": { - "line": 16, - "column": 17, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 21, - "column": 1, - "program": "methodThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 1, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 21, - "column": 1, - "program": "methodThrowsRethrows.ets" - } - } - }, - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "ETSGLOBAL", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "methodThrowsRethrows.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "methodThrowsRethrows.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "methodThrowsRethrows.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "methodThrowsRethrows.ets" - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "methodThrowsRethrows.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "methodThrowsRethrows.ets" - }, - "end": { - "line": 21, - "column": 1, - "program": "methodThrowsRethrows.ets" - } - } -} diff --git a/ets2panda/test/parser/ets/method_override_throw_1-expected.txt b/ets2panda/test/parser/ets/method_override_throw_1-expected.txt deleted file mode 100644 index c04044c9c4..0000000000 --- a/ets2panda/test/parser/ets/method_override_throw_1-expected.txt +++ /dev/null @@ -1,2575 +0,0 @@ -{ - "type": "Program", - "statements": [ - { - "type": "TSInterfaceDeclaration", - "body": { - "type": "TSInterfaceBody", - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "foo1", - "decorators": [], - "loc": { - "start": { - "line": 17, - "column": 5, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 17, - "column": 9, - "program": "method_override_throw_1.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": false, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "foo1", - "decorators": [], - "loc": { - "start": { - "line": 17, - "column": 5, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 17, - "column": 9, - "program": "method_override_throw_1.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 17, - "column": 13, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 17, - "column": 17, - "program": "method_override_throw_1.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 17, - "column": 9, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 17, - "column": 17, - "program": "method_override_throw_1.ets" - } - } - }, - "loc": { - "start": { - "line": 17, - "column": 9, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 17, - "column": 17, - "program": "method_override_throw_1.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 17, - "column": 5, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 17, - "column": 25, - "program": "method_override_throw_1.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "foo2", - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 5, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 18, - "column": 9, - "program": "method_override_throw_1.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": false, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "foo2", - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 5, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 18, - "column": 9, - "program": "method_override_throw_1.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "param", - "typeAnnotation": { - "type": "ETSFunctionType", - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 18, - "column": 23, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 18, - "column": 27, - "program": "method_override_throw_1.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 18, - "column": 17, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 18, - "column": 27, - "program": "method_override_throw_1.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 10, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 18, - "column": 27, - "program": "method_override_throw_1.ets" - } - } - }, - "loc": { - "start": { - "line": 18, - "column": 10, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 18, - "column": 27, - "program": "method_override_throw_1.ets" - } - } - } - ], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 18, - "column": 37, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 18, - "column": 41, - "program": "method_override_throw_1.ets" - } - } - }, - "throwMarker": "rethrows", - "loc": { - "start": { - "line": 18, - "column": 9, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 18, - "column": 41, - "program": "method_override_throw_1.ets" - } - } - }, - "loc": { - "start": { - "line": 18, - "column": 9, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 18, - "column": 41, - "program": "method_override_throw_1.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 5, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 18, - "column": 51, - "program": "method_override_throw_1.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "foo3", - "decorators": [], - "loc": { - "start": { - "line": 19, - "column": 5, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 19, - "column": 9, - "program": "method_override_throw_1.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": false, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "foo3", - "decorators": [], - "loc": { - "start": { - "line": 19, - "column": 5, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 19, - "column": 9, - "program": "method_override_throw_1.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 19, - "column": 13, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 19, - "column": 17, - "program": "method_override_throw_1.ets" - } - } - }, - "loc": { - "start": { - "line": 19, - "column": 9, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 19, - "column": 17, - "program": "method_override_throw_1.ets" - } - } - }, - "loc": { - "start": { - "line": 19, - "column": 9, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 19, - "column": 17, - "program": "method_override_throw_1.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 19, - "column": 5, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 19, - "column": 18, - "program": "method_override_throw_1.ets" - } - } - } - ], - "loc": { - "start": { - "line": 16, - "column": 13, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 20, - "column": 2, - "program": "method_override_throw_1.ets" - } - } - }, - "id": { - "type": "Identifier", - "name": "A", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 11, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 16, - "column": 12, - "program": "method_override_throw_1.ets" - } - } - }, - "extends": [], - "loc": { - "start": { - "line": 16, - "column": 1, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 22, - "column": 6, - "program": "method_override_throw_1.ets" - } - } - }, - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "AClass", - "decorators": [], - "loc": { - "start": { - "line": 22, - "column": 7, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 22, - "column": 13, - "program": "method_override_throw_1.ets" - } - } - }, - "superClass": null, - "implements": [ - { - "type": "TSClassImplements", - "expression": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "A", - "decorators": [], - "loc": { - "start": { - "line": 22, - "column": 25, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 22, - "column": 26, - "program": "method_override_throw_1.ets" - } - } - }, - "loc": { - "start": { - "line": 22, - "column": 25, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 22, - "column": 28, - "program": "method_override_throw_1.ets" - } - } - }, - "loc": { - "start": { - "line": 22, - "column": 25, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 22, - "column": 28, - "program": "method_override_throw_1.ets" - } - } - }, - "loc": { - "start": { - "line": 22, - "column": 25, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 22, - "column": 28, - "program": "method_override_throw_1.ets" - } - } - } - ], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "foo1", - "decorators": [], - "loc": { - "start": { - "line": 23, - "column": 14, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 23, - "column": 18, - "program": "method_override_throw_1.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": false, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "foo1", - "decorators": [], - "loc": { - "start": { - "line": 23, - "column": 14, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 23, - "column": 18, - "program": "method_override_throw_1.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 23, - "column": 22, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 23, - "column": 26, - "program": "method_override_throw_1.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 23, - "column": 34, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 23, - "column": 36, - "program": "method_override_throw_1.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 23, - "column": 18, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 23, - "column": 36, - "program": "method_override_throw_1.ets" - } - } - }, - "loc": { - "start": { - "line": 23, - "column": 18, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 23, - "column": 36, - "program": "method_override_throw_1.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 23, - "column": 5, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 23, - "column": 36, - "program": "method_override_throw_1.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "foo2", - "decorators": [], - "loc": { - "start": { - "line": 24, - "column": 14, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 24, - "column": 18, - "program": "method_override_throw_1.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": false, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "foo2", - "decorators": [], - "loc": { - "start": { - "line": 24, - "column": 14, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 24, - "column": 18, - "program": "method_override_throw_1.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "param", - "typeAnnotation": { - "type": "ETSFunctionType", - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 24, - "column": 32, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 24, - "column": 36, - "program": "method_override_throw_1.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 24, - "column": 26, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 24, - "column": 36, - "program": "method_override_throw_1.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 24, - "column": 19, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 24, - "column": 36, - "program": "method_override_throw_1.ets" - } - } - }, - "loc": { - "start": { - "line": 24, - "column": 19, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 24, - "column": 36, - "program": "method_override_throw_1.ets" - } - } - } - ], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 24, - "column": 46, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 24, - "column": 50, - "program": "method_override_throw_1.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 24, - "column": 60, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 24, - "column": 62, - "program": "method_override_throw_1.ets" - } - } - }, - "throwMarker": "rethrows", - "loc": { - "start": { - "line": 24, - "column": 18, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 24, - "column": 62, - "program": "method_override_throw_1.ets" - } - } - }, - "loc": { - "start": { - "line": 24, - "column": 18, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 24, - "column": 62, - "program": "method_override_throw_1.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 24, - "column": 5, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 24, - "column": 62, - "program": "method_override_throw_1.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "foo3", - "decorators": [], - "loc": { - "start": { - "line": 25, - "column": 14, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 25, - "column": 18, - "program": "method_override_throw_1.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": false, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "foo3", - "decorators": [], - "loc": { - "start": { - "line": 25, - "column": 14, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 25, - "column": 18, - "program": "method_override_throw_1.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 25, - "column": 22, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 25, - "column": 26, - "program": "method_override_throw_1.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 25, - "column": 27, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 25, - "column": 29, - "program": "method_override_throw_1.ets" - } - } - }, - "loc": { - "start": { - "line": 25, - "column": 18, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 25, - "column": 29, - "program": "method_override_throw_1.ets" - } - } - }, - "loc": { - "start": { - "line": 25, - "column": 18, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 25, - "column": 29, - "program": "method_override_throw_1.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 25, - "column": 5, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 25, - "column": 29, - "program": "method_override_throw_1.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "constructor", - "decorators": [], - "loc": { - "start": { - "line": 22, - "column": 28, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 22, - "column": 28, - "program": "method_override_throw_1.ets" - } - } - }, - "kind": "constructor", - "static": false, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "constructor", - "decorators": [], - "loc": { - "start": { - "line": 22, - "column": 28, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 22, - "column": 28, - "program": "method_override_throw_1.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 22, - "column": 28, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 22, - "column": 28, - "program": "method_override_throw_1.ets" - } - } - }, - "loc": { - "start": { - "line": 22, - "column": 28, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 22, - "column": 28, - "program": "method_override_throw_1.ets" - } - } - }, - "loc": { - "start": { - "line": 22, - "column": 28, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 22, - "column": 28, - "program": "method_override_throw_1.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - } - ], - "loc": { - "start": { - "line": 22, - "column": 27, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 28, - "column": 6, - "program": "method_override_throw_1.ets" - } - } - }, - "loc": { - "start": { - "line": 22, - "column": 1, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 28, - "column": 6, - "program": "method_override_throw_1.ets" - } - } - }, - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "BClass", - "decorators": [], - "loc": { - "start": { - "line": 28, - "column": 7, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 28, - "column": 13, - "program": "method_override_throw_1.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "foo1", - "decorators": [], - "loc": { - "start": { - "line": 29, - "column": 5, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 29, - "column": 9, - "program": "method_override_throw_1.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": false, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "foo1", - "decorators": [], - "loc": { - "start": { - "line": 29, - "column": 5, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 29, - "column": 9, - "program": "method_override_throw_1.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 29, - "column": 13, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 29, - "column": 17, - "program": "method_override_throw_1.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 29, - "column": 25, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 29, - "column": 27, - "program": "method_override_throw_1.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 29, - "column": 9, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 29, - "column": 27, - "program": "method_override_throw_1.ets" - } - } - }, - "loc": { - "start": { - "line": 29, - "column": 9, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 29, - "column": 27, - "program": "method_override_throw_1.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 29, - "column": 5, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 29, - "column": 27, - "program": "method_override_throw_1.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "foo2", - "decorators": [], - "loc": { - "start": { - "line": 30, - "column": 5, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 30, - "column": 9, - "program": "method_override_throw_1.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": false, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "foo2", - "decorators": [], - "loc": { - "start": { - "line": 30, - "column": 5, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 30, - "column": 9, - "program": "method_override_throw_1.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "param", - "typeAnnotation": { - "type": "ETSFunctionType", - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 30, - "column": 23, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 30, - "column": 27, - "program": "method_override_throw_1.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 30, - "column": 17, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 30, - "column": 27, - "program": "method_override_throw_1.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 30, - "column": 10, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 30, - "column": 27, - "program": "method_override_throw_1.ets" - } - } - }, - "loc": { - "start": { - "line": 30, - "column": 10, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 30, - "column": 27, - "program": "method_override_throw_1.ets" - } - } - } - ], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 30, - "column": 37, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 30, - "column": 41, - "program": "method_override_throw_1.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 30, - "column": 51, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 30, - "column": 53, - "program": "method_override_throw_1.ets" - } - } - }, - "throwMarker": "rethrows", - "loc": { - "start": { - "line": 30, - "column": 9, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 30, - "column": 53, - "program": "method_override_throw_1.ets" - } - } - }, - "loc": { - "start": { - "line": 30, - "column": 9, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 30, - "column": 53, - "program": "method_override_throw_1.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 30, - "column": 5, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 30, - "column": 53, - "program": "method_override_throw_1.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "foo3", - "decorators": [], - "loc": { - "start": { - "line": 31, - "column": 5, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 31, - "column": 9, - "program": "method_override_throw_1.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": false, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "foo3", - "decorators": [], - "loc": { - "start": { - "line": 31, - "column": 5, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 31, - "column": 9, - "program": "method_override_throw_1.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 31, - "column": 13, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 31, - "column": 17, - "program": "method_override_throw_1.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 31, - "column": 18, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 31, - "column": 20, - "program": "method_override_throw_1.ets" - } - } - }, - "loc": { - "start": { - "line": 31, - "column": 9, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 31, - "column": 20, - "program": "method_override_throw_1.ets" - } - } - }, - "loc": { - "start": { - "line": 31, - "column": 9, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 31, - "column": 20, - "program": "method_override_throw_1.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 31, - "column": 5, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 31, - "column": 20, - "program": "method_override_throw_1.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "constructor", - "decorators": [], - "loc": { - "start": { - "line": 28, - "column": 15, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 28, - "column": 15, - "program": "method_override_throw_1.ets" - } - } - }, - "kind": "constructor", - "static": false, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "constructor", - "decorators": [], - "loc": { - "start": { - "line": 28, - "column": 15, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 28, - "column": 15, - "program": "method_override_throw_1.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 28, - "column": 15, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 28, - "column": 15, - "program": "method_override_throw_1.ets" - } - } - }, - "loc": { - "start": { - "line": 28, - "column": 15, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 28, - "column": 15, - "program": "method_override_throw_1.ets" - } - } - }, - "loc": { - "start": { - "line": 28, - "column": 15, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 28, - "column": 15, - "program": "method_override_throw_1.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - } - ], - "loc": { - "start": { - "line": 28, - "column": 14, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 34, - "column": 6, - "program": "method_override_throw_1.ets" - } - } - }, - "loc": { - "start": { - "line": 28, - "column": 1, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 34, - "column": 6, - "program": "method_override_throw_1.ets" - } - } - }, - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "CClass", - "decorators": [], - "loc": { - "start": { - "line": 34, - "column": 13, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 34, - "column": 19, - "program": "method_override_throw_1.ets" - } - } - }, - "superClass": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "BClass", - "decorators": [], - "loc": { - "start": { - "line": 34, - "column": 28, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 34, - "column": 34, - "program": "method_override_throw_1.ets" - } - } - }, - "loc": { - "start": { - "line": 34, - "column": 28, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 34, - "column": 36, - "program": "method_override_throw_1.ets" - } - } - }, - "loc": { - "start": { - "line": 34, - "column": 28, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 34, - "column": 36, - "program": "method_override_throw_1.ets" - } - } - }, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "foo1", - "decorators": [], - "loc": { - "start": { - "line": 35, - "column": 14, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 35, - "column": 18, - "program": "method_override_throw_1.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": false, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "foo1", - "decorators": [], - "loc": { - "start": { - "line": 35, - "column": 14, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 35, - "column": 18, - "program": "method_override_throw_1.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 35, - "column": 22, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 35, - "column": 26, - "program": "method_override_throw_1.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 35, - "column": 34, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 35, - "column": 36, - "program": "method_override_throw_1.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 35, - "column": 18, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 35, - "column": 36, - "program": "method_override_throw_1.ets" - } - } - }, - "loc": { - "start": { - "line": 35, - "column": 18, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 35, - "column": 36, - "program": "method_override_throw_1.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 35, - "column": 5, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 35, - "column": 36, - "program": "method_override_throw_1.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "foo2", - "decorators": [], - "loc": { - "start": { - "line": 36, - "column": 14, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 36, - "column": 18, - "program": "method_override_throw_1.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": false, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "foo2", - "decorators": [], - "loc": { - "start": { - "line": 36, - "column": 14, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 36, - "column": 18, - "program": "method_override_throw_1.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "param", - "typeAnnotation": { - "type": "ETSFunctionType", - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 36, - "column": 32, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 36, - "column": 36, - "program": "method_override_throw_1.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 36, - "column": 26, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 36, - "column": 36, - "program": "method_override_throw_1.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 36, - "column": 19, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 36, - "column": 36, - "program": "method_override_throw_1.ets" - } - } - }, - "loc": { - "start": { - "line": 36, - "column": 19, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 36, - "column": 36, - "program": "method_override_throw_1.ets" - } - } - } - ], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 36, - "column": 46, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 36, - "column": 50, - "program": "method_override_throw_1.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 36, - "column": 60, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 36, - "column": 62, - "program": "method_override_throw_1.ets" - } - } - }, - "throwMarker": "rethrows", - "loc": { - "start": { - "line": 36, - "column": 18, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 36, - "column": 62, - "program": "method_override_throw_1.ets" - } - } - }, - "loc": { - "start": { - "line": 36, - "column": 18, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 36, - "column": 62, - "program": "method_override_throw_1.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 36, - "column": 5, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 36, - "column": 62, - "program": "method_override_throw_1.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "foo3", - "decorators": [], - "loc": { - "start": { - "line": 37, - "column": 14, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 37, - "column": 18, - "program": "method_override_throw_1.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": false, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "foo3", - "decorators": [], - "loc": { - "start": { - "line": 37, - "column": 14, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 37, - "column": 18, - "program": "method_override_throw_1.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 37, - "column": 22, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 37, - "column": 26, - "program": "method_override_throw_1.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 37, - "column": 27, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 37, - "column": 29, - "program": "method_override_throw_1.ets" - } - } - }, - "loc": { - "start": { - "line": 37, - "column": 18, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 37, - "column": 29, - "program": "method_override_throw_1.ets" - } - } - }, - "loc": { - "start": { - "line": 37, - "column": 18, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 37, - "column": 29, - "program": "method_override_throw_1.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 37, - "column": 5, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 37, - "column": 29, - "program": "method_override_throw_1.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "constructor", - "decorators": [], - "loc": { - "start": { - "line": 34, - "column": 36, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 34, - "column": 36, - "program": "method_override_throw_1.ets" - } - } - }, - "kind": "constructor", - "static": false, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "constructor", - "decorators": [], - "loc": { - "start": { - "line": 34, - "column": 36, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 34, - "column": 36, - "program": "method_override_throw_1.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 34, - "column": 36, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 34, - "column": 36, - "program": "method_override_throw_1.ets" - } - } - }, - "loc": { - "start": { - "line": 34, - "column": 36, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 34, - "column": 36, - "program": "method_override_throw_1.ets" - } - } - }, - "loc": { - "start": { - "line": 34, - "column": 36, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 34, - "column": 36, - "program": "method_override_throw_1.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - } - ], - "loc": { - "start": { - "line": 34, - "column": 35, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 39, - "column": 1, - "program": "method_override_throw_1.ets" - } - } - }, - "loc": { - "start": { - "line": 34, - "column": 7, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 39, - "column": 1, - "program": "method_override_throw_1.ets" - } - } - }, - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "ETSGLOBAL", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "method_override_throw_1.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "method_override_throw_1.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "method_override_throw_1.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "method_override_throw_1.ets" - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "method_override_throw_1.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "method_override_throw_1.ets" - }, - "end": { - "line": 39, - "column": 1, - "program": "method_override_throw_1.ets" - } - } -} diff --git a/ets2panda/test/parser/ets/rethrow-func-1-expected.txt b/ets2panda/test/parser/ets/rethrow-func-1-expected.txt deleted file mode 100644 index 76388e85f7..0000000000 --- a/ets2panda/test/parser/ets/rethrow-func-1-expected.txt +++ /dev/null @@ -1,1309 +0,0 @@ -{ - "type": "Program", - "statements": [ - { - "type": "TSTypeAliasDeclaration", - "id": { - "type": "Identifier", - "name": "func_type", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 6, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 16, - "column": 15, - "program": "rethrow-func-1.ets" - } - } - }, - "typeAnnotation": { - "type": "ETSFunctionType", - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 16, - "column": 24, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 16, - "column": 28, - "program": "rethrow-func-1.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 16, - "column": 18, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 16, - "column": 28, - "program": "rethrow-func-1.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 1, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 16, - "column": 36, - "program": "rethrow-func-1.ets" - } - } - }, - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "ETSGLOBAL", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrow-func-1.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrow-func-1.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "RethrowingFunc", - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 10, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 18, - "column": 24, - "program": "rethrow-func-1.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "RethrowingFunc", - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 10, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 18, - "column": 24, - "program": "rethrow-func-1.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "f121f", - "typeAnnotation": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "func_type", - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 32, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 18, - "column": 41, - "program": "rethrow-func-1.ets" - } - } - }, - "loc": { - "start": { - "line": 18, - "column": 32, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 18, - "column": 42, - "program": "rethrow-func-1.ets" - } - } - }, - "loc": { - "start": { - "line": 18, - "column": 32, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 18, - "column": 42, - "program": "rethrow-func-1.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 25, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 18, - "column": 42, - "program": "rethrow-func-1.ets" - } - } - }, - "loc": { - "start": { - "line": 18, - "column": 25, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 18, - "column": 42, - "program": "rethrow-func-1.ets" - } - } - } - ], - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "ExpressionStatement", - "expression": { - "type": "CallExpression", - "callee": { - "type": "MemberExpression", - "object": { - "type": "Identifier", - "name": "console", - "decorators": [], - "loc": { - "start": { - "line": 19, - "column": 5, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 19, - "column": 12, - "program": "rethrow-func-1.ets" - } - } - }, - "property": { - "type": "Identifier", - "name": "println", - "decorators": [], - "loc": { - "start": { - "line": 19, - "column": 13, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 19, - "column": 20, - "program": "rethrow-func-1.ets" - } - } - }, - "computed": false, - "optional": false, - "loc": { - "start": { - "line": 19, - "column": 5, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 19, - "column": 20, - "program": "rethrow-func-1.ets" - } - } - }, - "arguments": [ - { - "type": "StringLiteral", - "value": "Hello in RethrowingFunc", - "loc": { - "start": { - "line": 19, - "column": 21, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 19, - "column": 46, - "program": "rethrow-func-1.ets" - } - } - } - ], - "optional": false, - "loc": { - "start": { - "line": 19, - "column": 5, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 19, - "column": 47, - "program": "rethrow-func-1.ets" - } - } - }, - "loc": { - "start": { - "line": 19, - "column": 5, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 19, - "column": 47, - "program": "rethrow-func-1.ets" - } - } - }, - { - "type": "ExpressionStatement", - "expression": { - "type": "CallExpression", - "callee": { - "type": "Identifier", - "name": "f121f", - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 5, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 20, - "column": 10, - "program": "rethrow-func-1.ets" - } - } - }, - "arguments": [], - "optional": false, - "loc": { - "start": { - "line": 20, - "column": 5, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 20, - "column": 12, - "program": "rethrow-func-1.ets" - } - } - }, - "loc": { - "start": { - "line": 20, - "column": 5, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 20, - "column": 12, - "program": "rethrow-func-1.ets" - } - } - } - ], - "loc": { - "start": { - "line": 18, - "column": 52, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 21, - "column": 2, - "program": "rethrow-func-1.ets" - } - } - }, - "throwMarker": "rethrows", - "loc": { - "start": { - "line": 18, - "column": 10, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 21, - "column": 2, - "program": "rethrow-func-1.ets" - } - } - }, - "loc": { - "start": { - "line": 18, - "column": 10, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 21, - "column": 2, - "program": "rethrow-func-1.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 1, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 21, - "column": 2, - "program": "rethrow-func-1.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 23, - "column": 10, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 23, - "column": 14, - "program": "rethrow-func-1.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 23, - "column": 10, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 23, - "column": 14, - "program": "rethrow-func-1.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 23, - "column": 18, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 23, - "column": 22, - "program": "rethrow-func-1.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "VariableDeclaration", - "declarations": [ - { - "type": "VariableDeclarator", - "id": { - "type": "Identifier", - "name": "my_var", - "typeAnnotation": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "func_type", - "decorators": [], - "loc": { - "start": { - "line": 24, - "column": 17, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 24, - "column": 26, - "program": "rethrow-func-1.ets" - } - } - }, - "loc": { - "start": { - "line": 24, - "column": 17, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 24, - "column": 28, - "program": "rethrow-func-1.ets" - } - } - }, - "loc": { - "start": { - "line": 24, - "column": 17, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 24, - "column": 28, - "program": "rethrow-func-1.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 24, - "column": 9, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 24, - "column": 15, - "program": "rethrow-func-1.ets" - } - } - }, - "init": { - "type": "ArrowFunctionExpression", - "function": { - "type": "ScriptFunction", - "id": null, - "generator": false, - "async": false, - "expression": false, - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 24, - "column": 33, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 24, - "column": 37, - "program": "rethrow-func-1.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "ExpressionStatement", - "expression": { - "type": "CallExpression", - "callee": { - "type": "MemberExpression", - "object": { - "type": "Identifier", - "name": "console", - "decorators": [], - "loc": { - "start": { - "line": 25, - "column": 9, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 25, - "column": 16, - "program": "rethrow-func-1.ets" - } - } - }, - "property": { - "type": "Identifier", - "name": "println", - "decorators": [], - "loc": { - "start": { - "line": 25, - "column": 17, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 25, - "column": 24, - "program": "rethrow-func-1.ets" - } - } - }, - "computed": false, - "optional": false, - "loc": { - "start": { - "line": 25, - "column": 9, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 25, - "column": 24, - "program": "rethrow-func-1.ets" - } - } - }, - "arguments": [ - { - "type": "StringLiteral", - "value": "Hello in my_var", - "loc": { - "start": { - "line": 25, - "column": 25, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 25, - "column": 42, - "program": "rethrow-func-1.ets" - } - } - } - ], - "optional": false, - "loc": { - "start": { - "line": 25, - "column": 9, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 25, - "column": 43, - "program": "rethrow-func-1.ets" - } - } - }, - "loc": { - "start": { - "line": 25, - "column": 9, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 25, - "column": 43, - "program": "rethrow-func-1.ets" - } - } - }, - { - "type": "VariableDeclaration", - "declarations": [ - { - "type": "VariableDeclarator", - "id": { - "type": "Identifier", - "name": "a", - "decorators": [], - "loc": { - "start": { - "line": 26, - "column": 13, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 26, - "column": 14, - "program": "rethrow-func-1.ets" - } - } - }, - "init": { - "type": "BinaryExpression", - "operator": "/", - "left": { - "type": "NumberLiteral", - "value": 1, - "loc": { - "start": { - "line": 26, - "column": 17, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 26, - "column": 18, - "program": "rethrow-func-1.ets" - } - } - }, - "right": { - "type": "NumberLiteral", - "value": 0, - "loc": { - "start": { - "line": 26, - "column": 21, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 26, - "column": 22, - "program": "rethrow-func-1.ets" - } - } - }, - "loc": { - "start": { - "line": 26, - "column": 17, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 26, - "column": 22, - "program": "rethrow-func-1.ets" - } - } - }, - "loc": { - "start": { - "line": 26, - "column": 13, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 26, - "column": 22, - "program": "rethrow-func-1.ets" - } - } - } - ], - "kind": "let", - "loc": { - "start": { - "line": 26, - "column": 9, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 26, - "column": 22, - "program": "rethrow-func-1.ets" - } - } - } - ], - "loc": { - "start": { - "line": 24, - "column": 41, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 27, - "column": 6, - "program": "rethrow-func-1.ets" - } - } - }, - "loc": { - "start": { - "line": 24, - "column": 29, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 27, - "column": 6, - "program": "rethrow-func-1.ets" - } - } - }, - "loc": { - "start": { - "line": 24, - "column": 29, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 27, - "column": 6, - "program": "rethrow-func-1.ets" - } - } - }, - "loc": { - "start": { - "line": 24, - "column": 9, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 27, - "column": 6, - "program": "rethrow-func-1.ets" - } - } - } - ], - "kind": "let", - "loc": { - "start": { - "line": 24, - "column": 5, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 27, - "column": 6, - "program": "rethrow-func-1.ets" - } - } - }, - { - "type": "TryStatement", - "block": { - "type": "BlockStatement", - "statements": [ - { - "type": "ExpressionStatement", - "expression": { - "type": "CallExpression", - "callee": { - "type": "Identifier", - "name": "RethrowingFunc", - "decorators": [], - "loc": { - "start": { - "line": 29, - "column": 9, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 29, - "column": 23, - "program": "rethrow-func-1.ets" - } - } - }, - "arguments": [ - { - "type": "Identifier", - "name": "my_var", - "decorators": [], - "loc": { - "start": { - "line": 29, - "column": 24, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 29, - "column": 30, - "program": "rethrow-func-1.ets" - } - } - } - ], - "optional": false, - "loc": { - "start": { - "line": 29, - "column": 9, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 29, - "column": 31, - "program": "rethrow-func-1.ets" - } - } - }, - "loc": { - "start": { - "line": 29, - "column": 9, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 29, - "column": 32, - "program": "rethrow-func-1.ets" - } - } - } - ], - "loc": { - "start": { - "line": 28, - "column": 9, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 30, - "column": 6, - "program": "rethrow-func-1.ets" - } - } - }, - "handler": [ - { - "type": "CatchClause", - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "ExpressionStatement", - "expression": { - "type": "CallExpression", - "callee": { - "type": "MemberExpression", - "object": { - "type": "Identifier", - "name": "console", - "decorators": [], - "loc": { - "start": { - "line": 31, - "column": 9, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 31, - "column": 16, - "program": "rethrow-func-1.ets" - } - } - }, - "property": { - "type": "Identifier", - "name": "println", - "decorators": [], - "loc": { - "start": { - "line": 31, - "column": 17, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 31, - "column": 24, - "program": "rethrow-func-1.ets" - } - } - }, - "computed": false, - "optional": false, - "loc": { - "start": { - "line": 31, - "column": 9, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 31, - "column": 24, - "program": "rethrow-func-1.ets" - } - } - }, - "arguments": [ - { - "type": "StringLiteral", - "value": "Hello in exception", - "loc": { - "start": { - "line": 31, - "column": 25, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 31, - "column": 45, - "program": "rethrow-func-1.ets" - } - } - } - ], - "optional": false, - "loc": { - "start": { - "line": 31, - "column": 9, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 31, - "column": 46, - "program": "rethrow-func-1.ets" - } - } - }, - "loc": { - "start": { - "line": 31, - "column": 9, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 31, - "column": 46, - "program": "rethrow-func-1.ets" - } - } - } - ], - "loc": { - "start": { - "line": 30, - "column": 17, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 32, - "column": 6, - "program": "rethrow-func-1.ets" - } - } - }, - "param": { - "type": "Identifier", - "name": "a", - "decorators": [], - "loc": { - "start": { - "line": 30, - "column": 14, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 30, - "column": 15, - "program": "rethrow-func-1.ets" - } - } - }, - "loc": { - "start": { - "line": 30, - "column": 7, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 32, - "column": 6, - "program": "rethrow-func-1.ets" - } - } - } - ], - "finalizer": null, - "loc": { - "start": { - "line": 28, - "column": 5, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 32, - "column": 6, - "program": "rethrow-func-1.ets" - } - } - } - ], - "loc": { - "start": { - "line": 23, - "column": 23, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 33, - "column": 2, - "program": "rethrow-func-1.ets" - } - } - }, - "loc": { - "start": { - "line": 23, - "column": 10, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 33, - "column": 2, - "program": "rethrow-func-1.ets" - } - } - }, - "loc": { - "start": { - "line": 23, - "column": 10, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 33, - "column": 2, - "program": "rethrow-func-1.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 23, - "column": 1, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 33, - "column": 2, - "program": "rethrow-func-1.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrow-func-1.ets" - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "rethrow-func-1.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "rethrow-func-1.ets" - }, - "end": { - "line": 34, - "column": 1, - "program": "rethrow-func-1.ets" - } - } -} diff --git a/ets2panda/test/parser/ets/throwsRethrowsAsVariables-expected.txt b/ets2panda/test/parser/ets/throwsRethrowsAsVariables-expected.txt deleted file mode 100644 index 3e02fd2143..0000000000 --- a/ets2panda/test/parser/ets/throwsRethrowsAsVariables-expected.txt +++ /dev/null @@ -1,829 +0,0 @@ -{ - "type": "Program", - "statements": [ - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "ETSGLOBAL", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwsRethrowsAsVariables.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwsRethrowsAsVariables.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "ExpressionStatement", - "expression": { - "type": "AssignmentExpression", - "operator": "=", - "left": { - "type": "Identifier", - "name": "throws", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 5, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 16, - "column": 11, - "program": "throwsRethrowsAsVariables.ets" - } - } - }, - "right": { - "type": "NumberLiteral", - "value": 1, - "loc": { - "start": { - "line": 16, - "column": 14, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 16, - "column": 15, - "program": "throwsRethrowsAsVariables.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 5, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 16, - "column": 15, - "program": "throwsRethrowsAsVariables.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 5, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 16, - "column": 15, - "program": "throwsRethrowsAsVariables.ets" - } - } - }, - { - "type": "ExpressionStatement", - "expression": { - "type": "AssignmentExpression", - "operator": "=", - "left": { - "type": "Identifier", - "name": "rethrows", - "decorators": [], - "loc": { - "start": { - "line": 17, - "column": 5, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 17, - "column": 13, - "program": "throwsRethrowsAsVariables.ets" - } - } - }, - "right": { - "type": "NumberLiteral", - "value": 2, - "loc": { - "start": { - "line": 17, - "column": 16, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 17, - "column": 17, - "program": "throwsRethrowsAsVariables.ets" - } - } - }, - "loc": { - "start": { - "line": 17, - "column": 5, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 17, - "column": 17, - "program": "throwsRethrowsAsVariables.ets" - } - } - }, - "loc": { - "start": { - "line": 17, - "column": 5, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 17, - "column": 17, - "program": "throwsRethrowsAsVariables.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwsRethrowsAsVariables.ets" - } - } - }, - { - "type": "ClassProperty", - "key": { - "type": "Identifier", - "name": "throws", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 5, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 16, - "column": 11, - "program": "throwsRethrowsAsVariables.ets" - } - } - }, - "value": { - "type": "NumberLiteral", - "value": 1, - "loc": { - "start": { - "line": 16, - "column": 14, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 16, - "column": 15, - "program": "throwsRethrowsAsVariables.ets" - } - } - }, - "accessibility": "public", - "static": true, - "readonly": false, - "declare": false, - "optional": false, - "computed": false, - "definite": false, - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 5, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 16, - "column": 15, - "program": "throwsRethrowsAsVariables.ets" - } - } - }, - { - "type": "ClassProperty", - "key": { - "type": "Identifier", - "name": "rethrows", - "decorators": [], - "loc": { - "start": { - "line": 17, - "column": 5, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 17, - "column": 13, - "program": "throwsRethrowsAsVariables.ets" - } - } - }, - "value": { - "type": "NumberLiteral", - "value": 2, - "loc": { - "start": { - "line": 17, - "column": 16, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 17, - "column": 17, - "program": "throwsRethrowsAsVariables.ets" - } - } - }, - "accessibility": "public", - "static": true, - "readonly": false, - "declare": false, - "optional": false, - "computed": false, - "definite": false, - "decorators": [], - "loc": { - "start": { - "line": 17, - "column": 5, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 17, - "column": 17, - "program": "throwsRethrowsAsVariables.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "testFunction", - "decorators": [], - "loc": { - "start": { - "line": 19, - "column": 10, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 19, - "column": 22, - "program": "throwsRethrowsAsVariables.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "testFunction", - "decorators": [], - "loc": { - "start": { - "line": 19, - "column": 10, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 19, - "column": 22, - "program": "throwsRethrowsAsVariables.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 19, - "column": 26, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 19, - "column": 30, - "program": "throwsRethrowsAsVariables.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 19, - "column": 38, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 19, - "column": 40, - "program": "throwsRethrowsAsVariables.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 19, - "column": 10, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 19, - "column": 40, - "program": "throwsRethrowsAsVariables.ets" - } - } - }, - "loc": { - "start": { - "line": 19, - "column": 10, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 19, - "column": 40, - "program": "throwsRethrowsAsVariables.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 19, - "column": 1, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 19, - "column": 40, - "program": "throwsRethrowsAsVariables.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "testFunction2", - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 20, - "column": 23, - "program": "throwsRethrowsAsVariables.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "testFunction2", - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 20, - "column": 23, - "program": "throwsRethrowsAsVariables.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "f", - "typeAnnotation": { - "type": "ETSFunctionType", - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 20, - "column": 33, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 20, - "column": 37, - "program": "throwsRethrowsAsVariables.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 20, - "column": 27, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 20, - "column": 37, - "program": "throwsRethrowsAsVariables.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 24, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 20, - "column": 37, - "program": "throwsRethrowsAsVariables.ets" - } - } - }, - "loc": { - "start": { - "line": 20, - "column": 24, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 20, - "column": 37, - "program": "throwsRethrowsAsVariables.ets" - } - } - } - ], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 20, - "column": 47, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 20, - "column": 51, - "program": "throwsRethrowsAsVariables.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 20, - "column": 61, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 20, - "column": 63, - "program": "throwsRethrowsAsVariables.ets" - } - } - }, - "throwMarker": "rethrows", - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 20, - "column": 63, - "program": "throwsRethrowsAsVariables.ets" - } - } - }, - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 20, - "column": 63, - "program": "throwsRethrowsAsVariables.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 1, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 20, - "column": 63, - "program": "throwsRethrowsAsVariables.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwsRethrowsAsVariables.ets" - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "throwsRethrowsAsVariables.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "throwsRethrowsAsVariables.ets" - }, - "end": { - "line": 21, - "column": 1, - "program": "throwsRethrowsAsVariables.ets" - } - } -} diff --git a/ets2panda/test/parser/ets/trailing_lambda_tests/trailing_lambda_with_throw-expected.txt b/ets2panda/test/parser/ets/trailing_lambda_tests/trailing_lambda_with_throw-expected.txt deleted file mode 100644 index edeeb7a594..0000000000 --- a/ets2panda/test/parser/ets/trailing_lambda_tests/trailing_lambda_with_throw-expected.txt +++ /dev/null @@ -1,817 +0,0 @@ -{ - "type": "Program", - "statements": [ - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "ETSGLOBAL", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "foo", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 16, - "column": 13, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "foo", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 16, - "column": 13, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "c", - "typeAnnotation": { - "type": "ETSFunctionType", - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 16, - "column": 21, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 16, - "column": 25, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 16, - "column": 17, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 16, - "column": 25, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 14, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 16, - "column": 25, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 14, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 16, - "column": 25, - "program": "trailing_lambda_with_throw.ets" - } - } - } - ], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 16, - "column": 34, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 17, - "column": 2, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 17, - "column": 2, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 17, - "column": 2, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 1, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 17, - "column": 2, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "foo2", - "decorators": [], - "loc": { - "start": { - "line": 19, - "column": 10, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 19, - "column": 14, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "foo2", - "decorators": [], - "loc": { - "start": { - "line": 19, - "column": 10, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 19, - "column": 14, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "c", - "typeAnnotation": { - "type": "ETSFunctionType", - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 19, - "column": 22, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 19, - "column": 26, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - "loc": { - "start": { - "line": 19, - "column": 18, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 19, - "column": 26, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 19, - "column": 15, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 19, - "column": 26, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - "loc": { - "start": { - "line": 19, - "column": 15, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 19, - "column": 26, - "program": "trailing_lambda_with_throw.ets" - } - } - } - ], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 19, - "column": 28, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 20, - "column": 2, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - "loc": { - "start": { - "line": 19, - "column": 10, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 20, - "column": 2, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - "loc": { - "start": { - "line": 19, - "column": 10, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 20, - "column": 2, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 19, - "column": 1, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 20, - "column": 2, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 22, - "column": 10, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 22, - "column": 14, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 22, - "column": 10, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 22, - "column": 14, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "ExpressionStatement", - "expression": { - "type": "CallExpression", - "callee": { - "type": "Identifier", - "name": "foo", - "decorators": [], - "loc": { - "start": { - "line": 23, - "column": 5, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 23, - "column": 8, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - "arguments": [], - "optional": false, - "loc": { - "start": { - "line": 23, - "column": 5, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 23, - "column": 10, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - "loc": { - "start": { - "line": 23, - "column": 5, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 23, - "column": 10, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - { - "type": "ExpressionStatement", - "expression": { - "type": "CallExpression", - "callee": { - "type": "Identifier", - "name": "foo", - "decorators": [], - "loc": { - "start": { - "line": 27, - "column": 5, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 27, - "column": 8, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - "arguments": [], - "optional": false, - "loc": { - "start": { - "line": 27, - "column": 5, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 27, - "column": 10, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - "loc": { - "start": { - "line": 27, - "column": 5, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 27, - "column": 10, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - { - "type": "ExpressionStatement", - "expression": { - "type": "CallExpression", - "callee": { - "type": "Identifier", - "name": "foo2", - "decorators": [], - "loc": { - "start": { - "line": 29, - "column": 5, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 29, - "column": 9, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - "arguments": [], - "optional": false, - "loc": { - "start": { - "line": 29, - "column": 5, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 29, - "column": 11, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - "loc": { - "start": { - "line": 29, - "column": 5, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 29, - "column": 11, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - { - "type": "ExpressionStatement", - "expression": { - "type": "CallExpression", - "callee": { - "type": "Identifier", - "name": "foo2", - "decorators": [], - "loc": { - "start": { - "line": 33, - "column": 5, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 33, - "column": 9, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - "arguments": [], - "optional": false, - "loc": { - "start": { - "line": 33, - "column": 5, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 33, - "column": 11, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - "loc": { - "start": { - "line": 33, - "column": 5, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 33, - "column": 11, - "program": "trailing_lambda_with_throw.ets" - } - } - } - ], - "loc": { - "start": { - "line": 22, - "column": 17, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 34, - "column": 2, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - "loc": { - "start": { - "line": 22, - "column": 10, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 34, - "column": 2, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - "loc": { - "start": { - "line": 22, - "column": 10, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 34, - "column": 2, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 22, - "column": 1, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 34, - "column": 2, - "program": "trailing_lambda_with_throw.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "trailing_lambda_with_throw.ets" - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "trailing_lambda_with_throw.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "trailing_lambda_with_throw.ets" - }, - "end": { - "line": 35, - "column": 1, - "program": "trailing_lambda_with_throw.ets" - } - } -} diff --git a/ets2panda/test/parser/ets/variable_throw_function_1-expected.txt b/ets2panda/test/parser/ets/variable_throw_function_1-expected.txt deleted file mode 100644 index 68ebafcd7a..0000000000 --- a/ets2panda/test/parser/ets/variable_throw_function_1-expected.txt +++ /dev/null @@ -1,1087 +0,0 @@ -{ - "type": "Program", - "statements": [ - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "ETSGLOBAL", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "variable_throw_function_1.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "_$init$_", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "variable_throw_function_1.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "foo", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 16, - "column": 13, - "program": "variable_throw_function_1.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "foo", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 16, - "column": 13, - "program": "variable_throw_function_1.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 16, - "column": 18, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 16, - "column": 22, - "program": "variable_throw_function_1.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 16, - "column": 23, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 16, - "column": 25, - "program": "variable_throw_function_1.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 16, - "column": 25, - "program": "variable_throw_function_1.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 16, - "column": 25, - "program": "variable_throw_function_1.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 1, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 16, - "column": 25, - "program": "variable_throw_function_1.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "bar", - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 10, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 18, - "column": 13, - "program": "variable_throw_function_1.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "bar", - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 10, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 18, - "column": 13, - "program": "variable_throw_function_1.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 18, - "column": 18, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 18, - "column": 22, - "program": "variable_throw_function_1.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 18, - "column": 30, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 18, - "column": 32, - "program": "variable_throw_function_1.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 18, - "column": 10, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 18, - "column": 32, - "program": "variable_throw_function_1.ets" - } - } - }, - "loc": { - "start": { - "line": 18, - "column": 10, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 18, - "column": 32, - "program": "variable_throw_function_1.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 1, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 18, - "column": 32, - "program": "variable_throw_function_1.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "baz", - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 20, - "column": 13, - "program": "variable_throw_function_1.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "baz", - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 20, - "column": 13, - "program": "variable_throw_function_1.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "e", - "typeAnnotation": { - "type": "ETSFunctionType", - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 20, - "column": 23, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 20, - "column": 27, - "program": "variable_throw_function_1.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 20, - "column": 17, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 20, - "column": 27, - "program": "variable_throw_function_1.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 14, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 20, - "column": 27, - "program": "variable_throw_function_1.ets" - } - } - }, - "loc": { - "start": { - "line": 20, - "column": 14, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 20, - "column": 27, - "program": "variable_throw_function_1.ets" - } - } - } - ], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 20, - "column": 38, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 20, - "column": 42, - "program": "variable_throw_function_1.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 20, - "column": 52, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 20, - "column": 54, - "program": "variable_throw_function_1.ets" - } - } - }, - "throwMarker": "rethrows", - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 20, - "column": 54, - "program": "variable_throw_function_1.ets" - } - } - }, - "loc": { - "start": { - "line": 20, - "column": 10, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 20, - "column": 54, - "program": "variable_throw_function_1.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 20, - "column": 1, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 20, - "column": 54, - "program": "variable_throw_function_1.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 22, - "column": 10, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 22, - "column": 14, - "program": "variable_throw_function_1.ets" - } - } - }, - "kind": "method", - "accessibility": "public", - "static": true, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 22, - "column": 10, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 22, - "column": 14, - "program": "variable_throw_function_1.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 22, - "column": 18, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 22, - "column": 22, - "program": "variable_throw_function_1.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "VariableDeclaration", - "declarations": [ - { - "type": "VariableDeclarator", - "id": { - "type": "Identifier", - "name": "throwing1", - "typeAnnotation": { - "type": "ETSFunctionType", - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 23, - "column": 26, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 23, - "column": 30, - "program": "variable_throw_function_1.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 23, - "column": 20, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 23, - "column": 30, - "program": "variable_throw_function_1.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 23, - "column": 9, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 23, - "column": 18, - "program": "variable_throw_function_1.ets" - } - } - }, - "init": { - "type": "Identifier", - "name": "foo", - "decorators": [], - "loc": { - "start": { - "line": 23, - "column": 40, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 23, - "column": 43, - "program": "variable_throw_function_1.ets" - } - } - }, - "loc": { - "start": { - "line": 23, - "column": 9, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 23, - "column": 43, - "program": "variable_throw_function_1.ets" - } - } - } - ], - "kind": "let", - "loc": { - "start": { - "line": 23, - "column": 5, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 23, - "column": 44, - "program": "variable_throw_function_1.ets" - } - } - }, - { - "type": "VariableDeclaration", - "declarations": [ - { - "type": "VariableDeclarator", - "id": { - "type": "Identifier", - "name": "throwing2", - "typeAnnotation": { - "type": "ETSFunctionType", - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 25, - "column": 26, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 25, - "column": 30, - "program": "variable_throw_function_1.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 25, - "column": 20, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 25, - "column": 30, - "program": "variable_throw_function_1.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 25, - "column": 9, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 25, - "column": 18, - "program": "variable_throw_function_1.ets" - } - } - }, - "init": { - "type": "Identifier", - "name": "bar", - "decorators": [], - "loc": { - "start": { - "line": 25, - "column": 40, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 25, - "column": 43, - "program": "variable_throw_function_1.ets" - } - } - }, - "loc": { - "start": { - "line": 25, - "column": 9, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 25, - "column": 43, - "program": "variable_throw_function_1.ets" - } - } - } - ], - "kind": "let", - "loc": { - "start": { - "line": 25, - "column": 5, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 25, - "column": 44, - "program": "variable_throw_function_1.ets" - } - } - }, - { - "type": "VariableDeclaration", - "declarations": [ - { - "type": "VariableDeclarator", - "id": { - "type": "Identifier", - "name": "throwing3", - "typeAnnotation": { - "type": "ETSFunctionType", - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "e", - "typeAnnotation": { - "type": "ETSFunctionType", - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 27, - "column": 30, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 27, - "column": 34, - "program": "variable_throw_function_1.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 27, - "column": 24, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 27, - "column": 34, - "program": "variable_throw_function_1.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 27, - "column": 21, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 27, - "column": 34, - "program": "variable_throw_function_1.ets" - } - } - }, - "loc": { - "start": { - "line": 27, - "column": 21, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 27, - "column": 34, - "program": "variable_throw_function_1.ets" - } - } - } - ], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 27, - "column": 46, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 27, - "column": 50, - "program": "variable_throw_function_1.ets" - } - } - }, - "throwMarker": "throws", - "loc": { - "start": { - "line": 27, - "column": 20, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 27, - "column": 50, - "program": "variable_throw_function_1.ets" - } - } - }, - "decorators": [], - "loc": { - "start": { - "line": 27, - "column": 9, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 27, - "column": 18, - "program": "variable_throw_function_1.ets" - } - } - }, - "init": { - "type": "Identifier", - "name": "baz", - "decorators": [], - "loc": { - "start": { - "line": 27, - "column": 60, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 27, - "column": 63, - "program": "variable_throw_function_1.ets" - } - } - }, - "loc": { - "start": { - "line": 27, - "column": 9, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 27, - "column": 63, - "program": "variable_throw_function_1.ets" - } - } - } - ], - "kind": "let", - "loc": { - "start": { - "line": 27, - "column": 5, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 27, - "column": 64, - "program": "variable_throw_function_1.ets" - } - } - } - ], - "loc": { - "start": { - "line": 22, - "column": 23, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 28, - "column": 2, - "program": "variable_throw_function_1.ets" - } - } - }, - "loc": { - "start": { - "line": 22, - "column": 10, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 28, - "column": 2, - "program": "variable_throw_function_1.ets" - } - } - }, - "loc": { - "start": { - "line": 22, - "column": 10, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 28, - "column": 2, - "program": "variable_throw_function_1.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 22, - "column": 1, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 28, - "column": 2, - "program": "variable_throw_function_1.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "variable_throw_function_1.ets" - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "variable_throw_function_1.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "variable_throw_function_1.ets" - }, - "end": { - "line": 29, - "column": 1, - "program": "variable_throw_function_1.ets" - } - } -} diff --git a/ets2panda/test/runtime/ets/UnaryExpression.ets b/ets2panda/test/runtime/ets/UnaryExpression.ets index b08df62db4..2502dbb53d 100644 --- a/ets2panda/test/runtime/ets/UnaryExpression.ets +++ b/ets2panda/test/runtime/ets/UnaryExpression.ets @@ -117,24 +117,4 @@ function main(): void { let f = + -1; arktest.assertEQ(f, -1); } - - { - let a = -(-1); - assertEQ(a, 1); - - let b = -(1); - assertEQ(b, -1); - - let c = - -1; - assertEQ(c, 1); - - let d = +(1); - assertEQ(d, 1); - - let e = +(-1); - assertEQ(e, -1); - - let f = + -1; - assertEQ(f, -1); - } } diff --git a/ets2panda/test/unit/plugin/use_plugin_to_test_export_table.cpp b/ets2panda/test/unit/plugin/use_plugin_to_test_export_table.cpp deleted file mode 100644 index 1bfb5a30ef..0000000000 --- a/ets2panda/test/unit/plugin/use_plugin_to_test_export_table.cpp +++ /dev/null @@ -1,163 +0,0 @@ -/** - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include "file.h" -#include "macros.h" -#include "os/file.h" -#include "public/es2panda_lib.h" -#include "util.h" -#include "parser/program/program.h" -#include "ir/statements/blockStatement.h" -#include "ir/astNode.h" -#include "ir/statements/classDeclaration.h" -#include "ir/base/classDefinition.h" -#include "ir/base/methodDefinition.h" -#include "public/public.h" -#include "util/options.h" -#include "abc2program/abc2program_driver.h" - -// NOLINTBEGIN - -static es2panda_Impl *impl = nullptr; - -namespace { -constexpr size_t CLASS_DEFINITION_INDEX = 1; -constexpr size_t METHOD_DEFINITION_INDEX = 0; -constexpr size_t METHOD_BODY_INDEX = 2; - -enum Const { - LITERAL_INDEX_0 = 0, - LITERAL_INDEX_1 = 1, - LITERAL_INDEX_2 = 2, - LITERAL_INDEX_3 = 3, - LITERAL_INDEX_4 = 4, - LITERAL_INDEX_5 = 5, - EXPECTED_VALUE_1 = 1, - EXPECTED_VALUE_2 = 2, -}; - -const std::string SOURCE_CODE = - " function foo():void {\n" - " }\n" - " class A{}\n"; - -const std::string EXPECTED_CLASS_DEFINITION = "class A {\n public constructor() {}\n \n}\n"; - -const std::string EXPECTED_METHOD_DEFINITION = "function foo(): void {}\n"; - -int CheckLiteralValues(ark::es2panda::public_lib::Context *ctx, const ark::pandasm::Program &prog) -{ - auto file = ark::panda_file::OpenPandaFile(ctx->config->options->GetOutput()); - if (!file) { - return TEST_ERROR_CODE; - } - - auto literalArrIt = prog.literalarrayTable.find("0"); - if (literalArrIt == prog.literalarrayTable.end()) { - return TEST_ERROR_CODE; - } - auto &literalArr = literalArrIt->second.literals; - if (EXPECTED_VALUE_2 != std::get(literalArr[LITERAL_INDEX_1].value) || - EXPECTED_VALUE_1 != std::get(literalArr[LITERAL_INDEX_4].value)) { - return TEST_ERROR_CODE; - } - - const auto offsetA = std::get(literalArr[LITERAL_INDEX_0].value); - const auto stringDataA = file->GetStringData(ark::panda_file::File::EntityId(offsetA)); - auto stringA = std::string(reinterpret_cast(stringDataA.data), stringDataA.utf16Length); - - const auto offsetFoo = std::get(literalArr[LITERAL_INDEX_3].value); - const auto stringDataFoo = file->GetStringData(ark::panda_file::File::EntityId(offsetFoo)); - auto stringFoo = std::string(reinterpret_cast(stringDataFoo.data), stringDataFoo.utf16Length); - - if (stringA != EXPECTED_CLASS_DEFINITION) { - return TEST_ERROR_CODE; - } - - if (stringFoo != EXPECTED_METHOD_DEFINITION) { - return TEST_ERROR_CODE; - } - - return 0; -} - -void ProcessProgram(ark::es2panda::parser::Program *programPtr) -{ - auto *classDef = programPtr->Ast()->Statements()[CLASS_DEFINITION_INDEX]->AsClassDeclaration()->Definition(); - programPtr->AddDeclGenExportNode(classDef->DumpEtsSrc(), classDef); - - auto *methodDef = programPtr->Ast() - ->Statements()[METHOD_DEFINITION_INDEX] - ->AsClassDeclaration() - ->Definition() - ->AsClassDefinition() - ->Body()[METHOD_BODY_INDEX] - ->AsMethodDefinition(); - programPtr->AddDeclGenExportNode(methodDef->DumpEtsSrc(), methodDef); -} -} // namespace - -int main(int argc, char **argv) -{ - if (argc < MIN_ARGC) { - return INVALID_ARGC_ERROR_CODE; - } - - if (GetImpl() == nullptr) { - return NULLPTR_IMPL_ERROR_CODE; - } - impl = GetImpl(); - const char **args = const_cast(&(argv[1])); - auto config = impl->CreateConfig(argc - 1, args); - auto config_ = reinterpret_cast(config); - const_cast(config_->options)->SetWithExportTable(true); - auto context = impl->CreateContextFromString(config, SOURCE_CODE.data(), argv[argc - 1]); - if (context == nullptr) { - return NULLPTR_CONTEXT_ERROR_CODE; - } - - impl->ProceedToState(context, ES2PANDA_STATE_PARSED); - CheckForErrors("PARSE", context); - - impl->ProceedToState(context, ES2PANDA_STATE_BOUND); - CheckForErrors("BOUND", context); - - impl->ProceedToState(context, ES2PANDA_STATE_CHECKED); - CheckForErrors("CHECKED", context); - - auto program = impl->ContextProgram(context); - auto programPtr = reinterpret_cast(program); - ProcessProgram(programPtr); - - impl->ProceedToState(context, ES2PANDA_STATE_LOWERED); - CheckForErrors("LOWERED", context); - - impl->ProceedToState(context, ES2PANDA_STATE_ASM_GENERATED); - CheckForErrors("ASM", context); - - impl->ProceedToState(context, ES2PANDA_STATE_BIN_GENERATED); - CheckForErrors("BIN", context); - - auto *ctx = reinterpret_cast(context); - auto abc2program = new ark::abc2program::Abc2ProgramDriver(); - abc2program->Compile("./use_plugin_to_test_export_table.abc"); - auto res = CheckLiteralValues(ctx, abc2program->GetProgram()); - impl->DestroyConfig(config); - return res; -} - -// NOLINTEND \ No newline at end of file -- Gitee From d595d6b75d9991fddb18e08146207aab6c99e1d0 Mon Sep 17 00:00:00 2001 From: tengtengh Date: Sat, 12 Jul 2025 16:08:54 +0800 Subject: [PATCH 265/268] code check ignore for linter Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICLSLO Signed-off-by: tengtengh --- codecheck_ignore.json | 2 ++ 1 file changed, 2 insertions(+) diff --git a/codecheck_ignore.json b/codecheck_ignore.json index e51d43f3b4..a30bb19d2b 100755 --- a/codecheck_ignore.json +++ b/codecheck_ignore.json @@ -14,7 +14,9 @@ "ets2panda/linter/arkanalyzer": "*", "ets2panda/linter/homecheck": "*", "ets2panda/linter/build_linter.py": "*", + "ets2panda/linter/src/cli/CommandLineParser.ts": "*", "ets2panda/linter/src/lib/TypeScriptLinter.ts": "*", + "ets2panda/linter/src/lib/autofixes/Autofixer.ts": "*", "ets2panda/linter/src/lib/autofixes/QuasiEditor.ts": "*", "ets2panda/linter/src/lib/statistics/scan/ProblemStatisticsCommonFunction.ts": "*", "ets2panda/linter/src/lib/utils/functions/ConfiguredRulesProcess.ts": "*", -- Gitee From ee678b10a887fc4b55190afd1659e66a919ae556 Mon Sep 17 00:00:00 2001 From: dongchao Date: Fri, 30 May 2025 10:27:56 +0800 Subject: [PATCH 266/268] Cancel detection of unused tools when enableDecl Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICLS2A Signed-off-by: dongchao Change-Id: Iafd28c3657b7882c726d64b2e790df4b036fc29f --- ets2panda/driver/build_system/src/build/base_mode.ts | 12 +++++------- .../driver/build_system/src/build/declgen_worker.ts | 11 ++++++----- .../build_system/src/init/process_build_config.ts | 4 ++-- ets2panda/driver/build_system/src/types.ts | 1 + 4 files changed, 14 insertions(+), 14 deletions(-) diff --git a/ets2panda/driver/build_system/src/build/base_mode.ts b/ets2panda/driver/build_system/src/build/base_mode.ts index 50369fc99e..4431ced34c 100644 --- a/ets2panda/driver/build_system/src/build/base_mode.ts +++ b/ets2panda/driver/build_system/src/build/base_mode.ts @@ -107,6 +107,7 @@ export abstract class BaseMode { public hasCleanWorker: boolean; public byteCodeHar: boolean; public es2pandaMode: number; + public skipDeclCheck: boolean; constructor(buildConfig: BuildConfig) { this.buildConfig = buildConfig; @@ -142,7 +143,8 @@ export abstract class BaseMode { this.isBuildConfigModified = buildConfig.isBuildConfigModified as boolean | undefined; this.hasCleanWorker = false; this.byteCodeHar = buildConfig.byteCodeHar as boolean; - this.es2pandaMode = buildConfig?.es2pandaMode ?? ES2PANDA_MODE.RUN; + this.es2pandaMode = buildConfig?.es2pandaMode ?? 0; + this.skipDeclCheck = buildConfig?.skipDeclCheck as boolean ?? true; } public declgen(fileInfo: CompileFileInfo): void { @@ -175,13 +177,13 @@ export abstract class BaseMode { arktsGlobal.compilerContext = arkts.Context.createFromString(source); PluginDriver.getInstance().getPluginContext().setArkTSProgram(arktsGlobal.compilerContext.program); - arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, arktsGlobal.compilerContext.peer, true); + arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, arktsGlobal.compilerContext.peer, this.skipDeclCheck); let ast = arkts.EtsScript.fromContext(); PluginDriver.getInstance().getPluginContext().setArkTSAst(ast); PluginDriver.getInstance().runPluginHook(PluginHook.PARSED); - arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, arktsGlobal.compilerContext.peer, true); + arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, arktsGlobal.compilerContext.peer, this.skipDeclCheck); ast = arkts.EtsScript.fromContext(); PluginDriver.getInstance().getPluginContext().setArkTSAst(ast); @@ -694,10 +696,6 @@ export abstract class BaseMode { protected collectCompileFiles(): void { this.entryFiles.forEach((file: string) => { - // Skip the declaration files when compiling abc - if (file.endsWith(DECL_ETS_SUFFIX)) { - return; - } for (const [packageName, moduleInfo] of this.moduleInfos) { const relativePath = path.relative(moduleInfo.moduleRootPath, file); if (relativePath.startsWith('..') || path.isAbsolute(relativePath)) { diff --git a/ets2panda/driver/build_system/src/build/declgen_worker.ts b/ets2panda/driver/build_system/src/build/declgen_worker.ts index 872eb49db1..5a32a7f000 100644 --- a/ets2panda/driver/build_system/src/build/declgen_worker.ts +++ b/ets2panda/driver/build_system/src/build/declgen_worker.ts @@ -18,7 +18,7 @@ import { BuildConfig } from '../types'; import { Logger } from '../logger'; import * as fs from 'fs'; import * as path from 'path'; -import { changeFileExtension, ensurePathExists } from '../utils'; +import { changeDeclgenFileExtension, ensurePathExists } from '../utils'; import { DECL_ETS_SUFFIX, TS_SUFFIX, @@ -56,13 +56,13 @@ process.on('message', (message: { moduleInfo.packageName, filePathFromModuleRoot ); - declEtsOutputPath = changeFileExtension(declEtsOutputPath, DECL_ETS_SUFFIX); + declEtsOutputPath = changeDeclgenFileExtension(declEtsOutputPath, DECL_ETS_SUFFIX); let etsOutputPath: string = path.join( moduleInfo.declgenBridgeCodePath as string, moduleInfo.packageName, filePathFromModuleRoot ); - etsOutputPath = changeFileExtension(etsOutputPath, TS_SUFFIX); + etsOutputPath = changeDeclgenFileExtension(etsOutputPath, TS_SUFFIX); ensurePathExists(declEtsOutputPath); ensurePathExists(etsOutputPath); @@ -78,14 +78,15 @@ process.on('message', (message: { ]).peer; arktsGlobal.compilerContext = arkts.Context.createFromString(source); pluginDriver.getPluginContext().setArkTSProgram(arktsGlobal.compilerContext.program); + const skipDeclCheck = buildConfig?.skipDeclCheck as boolean ?? true; - arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, arktsGlobal.compilerContext.peer, true); + arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, arktsGlobal.compilerContext.peer, skipDeclCheck); let ast = arkts.EtsScript.fromContext(); pluginDriver.getPluginContext().setArkTSAst(ast); pluginDriver.runPluginHook(PluginHook.PARSED); - arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, arktsGlobal.compilerContext.peer, true); + arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, arktsGlobal.compilerContext.peer, skipDeclCheck); ast = arkts.EtsScript.fromContext(); pluginDriver.getPluginContext().setArkTSAst(ast); diff --git a/ets2panda/driver/build_system/src/init/process_build_config.ts b/ets2panda/driver/build_system/src/init/process_build_config.ts index 9a98a3fd00..50aac6d47c 100644 --- a/ets2panda/driver/build_system/src/init/process_build_config.ts +++ b/ets2panda/driver/build_system/src/init/process_build_config.ts @@ -103,7 +103,7 @@ function initPlatformSpecificConfig(buildConfig: BuildConfig): void { buildConfig.dependencyAnalyzerPath = path.join(pandaSdkPath, 'bin', 'dependency_analyzer'); } - if (!fs.existsSync(buildConfig.abcLinkerPath as string)) { + if (!buildConfig.enableDeclgenEts2Ts && !fs.existsSync(buildConfig.abcLinkerPath as string)) { const logData: LogData = LogDataFactory.newInstance( ErrorCode.BUILDSYSTEM_ARK_LINK_NOT_FOUND_FAIL, 'Ark_link not found in path.', @@ -113,7 +113,7 @@ function initPlatformSpecificConfig(buildConfig: BuildConfig): void { logger.printError(logData); } - if (!buildConfig.frameworkMode && !fs.existsSync(buildConfig.dependencyAnalyzerPath as string)) { + if (!buildConfig.frameworkMode && !buildConfig.enableDeclgenEts2Ts && !fs.existsSync(buildConfig.dependencyAnalyzerPath as string)) { const logData: LogData = LogDataFactory.newInstance( ErrorCode.BUILDSYSTEM_Dependency_Analyzer_NOT_FOUND_FAIL, 'Dependency_analyzer not found in path.', diff --git a/ets2panda/driver/build_system/src/types.ts b/ets2panda/driver/build_system/src/types.ts index 6e69ccd0b1..80f3f76ab3 100644 --- a/ets2panda/driver/build_system/src/types.ts +++ b/ets2panda/driver/build_system/src/types.ts @@ -164,6 +164,7 @@ export interface DeclgenConfig { declgenV1OutPath?: string; declgenV2OutPath?: string; declgenBridgeCodePath?: string; + skipDeclCheck?: boolean; } export interface LoggerConfig { -- Gitee From 4b28b37f86596248323869dc24bd4623e61a6ea0 Mon Sep 17 00:00:00 2001 From: dongchao Date: Fri, 30 May 2025 10:27:56 +0800 Subject: [PATCH 267/268] Cancel detection of unused tools when enableDecl Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICLS27 Signed-off-by: dongchao Change-Id: Iafd28c3657b7882c726d64b2e790df4b036fc29f --- ets2panda/driver/build_system/src/build/base_mode.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ets2panda/driver/build_system/src/build/base_mode.ts b/ets2panda/driver/build_system/src/build/base_mode.ts index 4431ced34c..465492b1e7 100644 --- a/ets2panda/driver/build_system/src/build/base_mode.ts +++ b/ets2panda/driver/build_system/src/build/base_mode.ts @@ -143,7 +143,7 @@ export abstract class BaseMode { this.isBuildConfigModified = buildConfig.isBuildConfigModified as boolean | undefined; this.hasCleanWorker = false; this.byteCodeHar = buildConfig.byteCodeHar as boolean; - this.es2pandaMode = buildConfig?.es2pandaMode ?? 0; + this.es2pandaMode = buildConfig?.es2pandaMode ?? ES2PANDA_MODE.RUN; this.skipDeclCheck = buildConfig?.skipDeclCheck as boolean ?? true; } -- Gitee From 922b824f86466a4e643d87d18268b6d320419cd2 Mon Sep 17 00:00:00 2001 From: Kaskov Mikhail Date: Fri, 11 Jul 2025 18:37:11 +0300 Subject: [PATCH 268/268] Optimized capture variables in lambda Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICLYBA Signed-off-by: Kaskov Mikhail --- ets2panda/checker/ETSchecker.cpp | 35 ++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/ets2panda/checker/ETSchecker.cpp b/ets2panda/checker/ETSchecker.cpp index d63dcd1f11..f65ec3e537 100644 --- a/ets2panda/checker/ETSchecker.cpp +++ b/ets2panda/checker/ETSchecker.cpp @@ -677,29 +677,34 @@ ETSObjectType *ETSChecker::GlobalBuiltinDynamicType(Language lang) const ETSObjectType *ETSChecker::GlobalBuiltinBoxType(Type *contents) { - switch (TypeKind(contents)) { - case TypeFlag::ETS_BOOLEAN: + ES2PANDA_ASSERT(contents->IsETSReferenceType()); + if (!contents->IsETSUnboxableObject()) { + auto *base = AsETSObjectType(&GlobalTypesHolder::GlobalBoxBuiltinType); + auto substitution = Substitution {}; + ES2PANDA_ASSERT(base != nullptr); + substitution.emplace(base->TypeArguments()[0]->AsETSTypeParameter(), contents); + return base->Substitute(Relation(), &substitution); + } + + switch (contents->AsETSObjectType()->UnboxableKind()) { + case ETSObjectFlags::BUILTIN_BOOLEAN: return AsETSObjectType(&GlobalTypesHolder::GlobalBooleanBoxBuiltinType); - case TypeFlag::BYTE: + case ETSObjectFlags::BUILTIN_BYTE: return AsETSObjectType(&GlobalTypesHolder::GlobalByteBoxBuiltinType); - case TypeFlag::CHAR: - return AsETSObjectType(&GlobalTypesHolder::GlobalCharBoxBuiltinType); - case TypeFlag::SHORT: + case ETSObjectFlags::BUILTIN_SHORT: return AsETSObjectType(&GlobalTypesHolder::GlobalShortBoxBuiltinType); - case TypeFlag::INT: + case ETSObjectFlags::BUILTIN_CHAR: + return AsETSObjectType(&GlobalTypesHolder::GlobalCharBoxBuiltinType); + case ETSObjectFlags::BUILTIN_INT: return AsETSObjectType(&GlobalTypesHolder::GlobalIntBoxBuiltinType); - case TypeFlag::LONG: + case ETSObjectFlags::BUILTIN_LONG: return AsETSObjectType(&GlobalTypesHolder::GlobalLongBoxBuiltinType); - case TypeFlag::FLOAT: + case ETSObjectFlags::BUILTIN_FLOAT: return AsETSObjectType(&GlobalTypesHolder::GlobalFloatBoxBuiltinType); - case TypeFlag::DOUBLE: + case ETSObjectFlags::BUILTIN_DOUBLE: return AsETSObjectType(&GlobalTypesHolder::GlobalDoubleBoxBuiltinType); default: { - auto *base = AsETSObjectType(&GlobalTypesHolder::GlobalBoxBuiltinType); - auto substitution = Substitution {}; - ES2PANDA_ASSERT(base != nullptr); - substitution.emplace(base->TypeArguments()[0]->AsETSTypeParameter(), contents); - return base->Substitute(Relation(), &substitution); + ES2PANDA_UNREACHABLE(); } } } -- Gitee